题意:有n个富国和n个穷国,他们分别该在两条直线上,从编号从小到大,线上位置从左到右排列。每个穷国当且仅当有一个富国与之相连,且富国当且仅当有一个穷国与之相连。现在删除部分线,使得所有连线不相交,问最大剩余连线数是多少?
题解:
对输入,先根据穷国编号从小到大排序,得到一个富国的序列。我们发现对于任意富国ai和aj(i<j),只有ai<aj时才不相交,从而将题目转换为,求最长上升子序列。
这题的n可以达到500000,所以必须用nlogn的算法。
dp[i]=max(dp[k])+1;(0<=k<i,a[i]>a[k])
多加一个数组c[i],用于记录最长上升子序列长为i的序列中,最小的最后一个数字。这样查找max(dp[k])时只用找c[i]数组了,而c[i]数组递增,可以用二分查找查询,找到最接近且比a[i]小的值。若k为这个值,那么c[k+1]=min(c[k+1],a[i]);
由于c数组的长度t相当于记录了最长上升子序列,所以可以省略掉dp数组。
注意:输出的时候只有一条线时是road,多条线时是roads,被坑了。。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <algorithm>
#include <cmath>
#include <queue>
#include <vector>
using namespace std;
const int maxn=5e5+10;
struct node{
int x,y;
}e[maxn];
int c[maxn],dp[maxn],t;
int cmp(node a,node b)
{
return a.x<b.x;
}
void LongestIncreasingSubsequence(int n,int tt)
{
int i,j,k;
c[1]=e[0].y;
t=1;
for(i=1;i<n;i++)
{
if(e[i].y<c[1])c[1]=e[i].y;
else if(e[i].y>c[t])c[++t]=e[i].y;
else
{
k=lower_bound(c+1,c+t+1,e[i].y)-c;
c[k]=min(c[k],e[i].y);
}
}
if(t==1)printf("Case %d:\nMy king, at most %d road can be built.\n\n",tt,t);
else printf("Case %d:\nMy king, at most %d roads can be built.\n\n",tt,t);
}
int main()
{
int n,tt=0;
while(scanf("%d",&n)!=EOF)
{
int i,j,k;
for(i=0;i<n;i++)
scanf("%d%d",&e[i].x,&e[i].y);
sort(e,e+n,cmp);
LongestIncreasingSubsequence(n,++tt);
}
return 0;
}