hdu 1025(最长非递减子序列的n*log(n)求法)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1025
经典题。。。最长非递减序列的n*log(n)求法。。。orz...
View Code
1 #include<iostream> 2 const int N=500007; 3 using namespace std; 4 int city[N]; 5 int dp[N];//dp[i]保存的是长度为i的最长不降子序列的最小尾元素 6 7 //二分查找返回num在dp中的位置 8 int Search(int dp[],int len,int num){ 9 int low=1,high=len; 10 while(low<=high){ 11 int mid=(low+high)/2; 12 if(num==dp[mid])return mid; 13 else if(num<dp[mid])high=mid-1; 14 else if(num>dp[mid])low=mid+1; 15 } 16 return low; 17 } 18 19 int main(){ 20 int n,_case=1; 21 while(~scanf("%d",&n)){ 22 int a,b; 23 for(int i=1;i<=n;i++){ 24 scanf("%d%d",&a,&b); 25 city[a]=b; 26 } 27 dp[0]=-1,dp[1]=city[1]; 28 int len=1; 29 //n*log(n)求最长单调非递减序列 30 for(int i=1;i<=n;i++){ 31 int j=Search(dp,len,city[i]); 32 dp[j]=city[i];//每次都要更新dp 33 if(j>len)len++; 34 } 35 printf("Case %d:\n",_case++); 36 if(len==1){ 37 printf("My king, at most %d road can be built.\n\n",len); 38 }else 39 printf("My king, at most %d roads can be built.\n\n",len); 40 } 41 return 0; 42 } 43 44 45