第一次提交超时了。
借鉴了一下别人的代码,发现dp的思路都错了。。。
而且还得用到二分法来减小时间复杂度。
dp+二分法。好题呀。
#include<iostream>
using namespace std;
int p[500005],dp[500005];
int search(int num,int low,int high)
{
int mid;
while (low <= high)
{
mid = (low + high) / 2;
if (num >= dp[mid]) low = mid + 1;
else high = mid - 1;
}
return low;
}
int main()
{
int len,pos,k=1;
int n,i,a,b,max;
while(cin>>n)
{
max=0;len=1;
memset(p,0,n+5);
memset(dp,0,n+5);
for( i=1;i<=n;i++)
{
cin>>a>>b;
p[a]=b;
}
dp[1]=p[1];
for(i=2;i<=n;i++)
{
if(p[i]>dp[len])
{
dp[++len]=p[i];
}
else{
pos=search(p[i],1,len);dp[pos]=p[i];
}
}
if(len==1)
cout<<"Case "<<k<<":"<<endl<<"My king, at most 1 road can be built."<<endl;
else
cout<<"Case "<<k<<":"<<endl<<"My king, at most "<<len<<" road can be built."<<endl;
k++;
}
return 0;
}