J - FatMouse's Speed

  p的思路不一定要到最后去找到ans;也可以设置成在中间找到ans;比如J - FatMouse's Speed 这个题,如果要是让dp[n]成为最终答案的话,即到了i,最差的情况也是dp[i-1],就很难去保存路径,但是如果换一个思路,让dp[i]必须去参与,如果无法与前面的结合,那么就新开一个。

  最后路径是保存的逆序的,那么开一个stack就可以解决。

 

 1 //显然这个题是要维护两个变量的最长上升子序列 
 2 #include <iostream>
 3 #include <fstream>
 4 #include <algorithm>
 5 #include <cstring>
 6 #include <fstream>
 7 #include <stack>
 8 
 9 using namespace std;
10 //ifstream fin("a.txt");
11 struct node{
12     int weight,speed,num;
13 }a[10005];
14 bool cmp(node a,node b)
15 {
16     if(a.weight==b.weight)
17         return a.speed>b.speed;
18     else return a.weight<b.weight;
19 }
20 struct Node{
21     int cnt,now,pre;
22 }dp[10005];
23 int pre[10005];
24 int main()
25 {
26     int x,y;int i=1;
27     while(cin>>x>>y)
28     {
29         a[i].weight=x;a[i].speed=y,a[i].num=i;i++; 
30     }
31         sort(a+1,a+i,cmp);
32         dp[1].cnt=1;
33         for(int j=2;j<=i-1;j++)
34         {
35             dp[j].cnt=1; 
36             for(int k=j-1;k>=1;k--)
37             {
38                 if(a[j].speed<a[k].speed&&a[j].weight>a[k].weight)
39                     {
40                         if(dp[j].cnt<dp[k].cnt+1)
41                         {
42                             dp[j].cnt=dp[k].cnt+1;
43                             dp[j].pre=k;
44                             dp[j].now=a[j].speed;
45                         }
46                     }
47             }
48         }
49         int ans=0;
50         int m=i-1;
51         for(int j=1;j<=i-1;j++)
52         {
53             if(ans<dp[j].cnt)
54                 {
55                     ans=dp[j].cnt;
56                     m=j;
57                 }
58         }
59         
60         cout <<ans<<endl;
61         
62         stack <int> s;
63         s.push(a[m].num);ans--;
64         while(ans--)
65         {
66             s.push(a[dp[m].pre].num);
67             m=dp[m].pre;
68         }
69         while(!s.empty())
70         {
71             cout << s.top()<<endl;
72             s.pop();
73         }
74     return 0;
75  } 

 

posted @ 2019-02-01 14:45  Chuhanjing  阅读(150)  评论(0编辑  收藏  举报