J - FatMouse's Speed

  p的思路不必定要到最後去找到ans;也能夠設置成在中間找到ans;好比J - FatMouse's Speed 這個題,若是要是讓dp[n]成爲最終答案的話,即到了i,最差的狀況也是dp[i-1],就很難去保存路徑,可是若是換一個思路,讓dp[i]必須去參與,若是沒法與前面的結合,那麼就新開一個。node

  最後路徑是保存的逆序的,那麼開一個stack就能夠解決。ios

 

 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  } 
相關文章
相關標籤/搜索