HDU-1160.FatMouse'sSpeed.(LIS变形 + 路径打印)

  本题大意:给定一定数量的数对,每个数保存着一只老鼠的质量和速度,让你求出一个最长序列,这个序列按照质量严格递增,速度严格递减排列,让你输出这个序列的最长长度,并且输出组成这个最长长度的序列的对应的老鼠的编号...

  本题思路:看到最长序列,可以想到是LIS的变形,然后需要打印路径,那我们只需要回溯思想数组保存即可。很基础的一道题目......记得找到最后的那只老鼠...

  参考代码:

 1 #include <iostream>
 2 #include <cstring>
 3 #include <algorithm>
 4 #include <stack>
 5 using namespace std;
 6 
 7 const int maxn = 1e3 + 5;
 8 struct node {
 9     int m, s, pre, ind;
10 } a[maxn];
11 
12 bool cmp(const node a, const node b) {
13     if(a.m == b.m) return a.s > b.s;
14     return a.m < b.m;
15 }
16 
17 bool check(int i, int j) {
18     return a[i].m > a[j].m && a[i].s < a[j].s;
19 }
20 
21 int main () {
22     int num = 0, c1, c2, cnt = 0, ans = 0, preidx = 0, dp[maxn];
23     memset(dp, 0, sizeof dp);
24     while(cin >> c1 >> c2) {
25         a[++ num].m = c1;
26         a[num].s = c2;
27         a[num].ind = num;
28         a[num].pre = -1;
29     }
30     sort(a + 1, a + num + 1, cmp);
31     for(int i = 1; i <= num; i ++) {
32         dp[i] = 1;
33         for(int j = 1; j < i; j ++) {
34             if(check(i, j) && dp[i] < dp[j] + 1) {
35                 dp[i] = dp[j] + 1;
36                 a[i].pre = j;
37             }
38             if(dp[i] > ans) {
39                 preidx = i;
40                 ans = dp[i];
41             }
42         }
43     }
44     cout << ans << endl;
45     stack <int >P;
46     while(preidx != - 1) {
47         P.push(a[preidx].ind);
48         preidx = a[preidx].pre;
49     }
50     while(!P.empty()) {
51         cout << P.top() << endl;
52         P.pop();
53     }
54     return 0;  
55 }
View Code

 

  

posted @ 2019-04-02 23:34  Cruel_King  阅读(193)  评论(0编辑  收藏  举报