点击打开题目链接
本题目是考察 最长递增子序列的 有n^2 n(logn) n^2 会超时的
下面两个方法的代码 思路 可以百度LIS LCS
dp里面存子序列
n(logn) 代码
<span style="font-size:18px;">#include<iostream> #include<stdio.h> #include<string.h> #include<algorithm> #include<stdlib.h> #define N 500000 using namespace std; int road[N],dp[N],n,len; int two_part(int *a,int L,int R, int aim) //二分法找更新的位置 { int zz; if(len==1&&dp[1]==0) return 1; while(L<=R) { int mid=(L+R)/2; if(aim>a[mid]&&aim<a[mid+1]) return mid+1; else if(aim>a[mid]) L=mid+1; else if(aim<a[mid]) R=mid-1; } if(aim<=dp[1]) return 1; //目标数字比第一个数小则更新dp[1] return ++len; //找不到则在末尾更新 } int ans() { int i; for(i=1; i<=n; i++) //把每个数字在dp数组中更新 { int wz=two_part(dp,1,len,road[i]); dp[wz]=road[i]; // print(); } return len; } int main() { int t=1; while(scanf("%d",&n)!=EOF) { int i; len=1; memset(road,0,sizeof(road)); memset(dp,0,sizeof(dp)); for(i=1; i<=n; i++) { int ra,rb; scanf("%d%d",&ra,&rb); road[ra]=rb; } int answer=ans(); // printf("%d\n",ans()); printf("Case %d:\n",t++); if(answer==1) printf("My king, at most %d road can be built.\n\n",answer); else printf("My king, at most %d roads can be built.\n\n",answer); } return 0; }</span>
<span style="font-size:18px;"> </span>
n^2代码
#include<iostream> #include<stdio.h> #include<string.h> #include<algorithm> #include<stdlib.h> #define N 500000 using namespace std; int road[N],dp[N],n; //int two_part(int *a,int L,int R, int aim) //{ // while(L<=R) // { // int mid=(L+R)/2; // if(aim==a[mid]) return mid; // else if(aim>mid) // { // L=mid+1; // } // else // { // R=mid-1; // } // } // return -1; //} int ans() { int sum=0; int i,j; for(i=0;i<n;i++) { j=0; while(1) { if(road[i]<dp[j]||!dp[j]) { dp[j]=road[i]; break; } j++; } } for(i=0;i<n;i++) if(dp[i]) sum++; return sum; } int main() { while(scanf("%d",&n)!=EOF) { int i; memset(road,0,sizeof(road)); memset(dp,0,sizeof(dp)); for(i=0;i<n;i++) { int ra,rb; scanf("%d%d",&ra,&rb); road[ra]=rb; } int answer=ans(); // printf("%d\n",ans()); if(answer==1) printf("My king, at most %d road can be built.\n\n",answer); else printf("My king, at most %d roads can be built.\n\n",answer); } return 0; }