hdu 1025 Constructing Roads In JGShining's Kingdom

本题明白题意以后,就可以看出是让求最长上升子序列,但是不知道最长上升子序列的算法,用了很多YY的方法去做,最后还是超时,

因为普通算法时间复杂度为O(n*2),去搜了题解,学习了一下,感觉不错,拿出来分享一下。

 1 #include <stdio.h>
 2 #include <string.h>
 3 
 4 #define N 500005
 5 int map[N], dp[N];
 6 
 7 int main ()
 8 {
 9     int x, y, n, i, j = 0;
10     
11     while (scanf ("%d", &n) != EOF)
12     {
13         for (i=0; i<n; i++)
14         {
15             scanf ("%d %d", &x, &y);
16             map[x] = y;
17         }
18         
19         memset (dp, 0, sizeof(dp));
20         
21         dp[1] = map[1];
22         
23         int low, up, mid, len = 1;
24         for (i=2; i<=n; i++)
25         {
26             low = 1;
27             up = len;
28             
29             while (low <= up)
30             {
31                 mid = (low + up) / 2;
32                 if (dp[mid] > map[i])
33                     up = mid - 1;
34                 else
35                     low = mid + 1;
36             }
37             
38             dp[low] = map[i];
39             if (low > len)
40                 len ++;
41         }
42         if (len == 1)
43             printf ("Case %d:\nMy king, at most 1 road can be built.\n\n", ++j);
44         else
45             printf ("Case %d:\nMy king, at most %d roads can be built.\n\n", ++j, len);
46     }
47     
48     return 0;
49 }
View Code

 

posted @ 2014-11-12 13:24  罗茜  阅读(259)  评论(3编辑  收藏  举报