JGShining王国由2n个坐落在平行线上的城市组成,其中n个城市富有,另外n个城市贫穷,而正好n个富有城市可以为n个贫穷的城市提供资源,而且必须是一对一的,因为每个富有的城市所提供的资源各不相同,而每个贫穷的城市所需要的资源也各不相同。
Input
Each test case will begin with a line containing an integer n(1 ≤ n ≤ 500,000). Then n lines follow. Each line contains two integers p and r which represents that Poor City p needs to import resources from Rich City r. Process to the end of file.
Output
For each test case, output the result in the form of sample.
You should tell JGShining what's the maximal number of road(s) can be built.
Sample Input
2
1 2
2 1
3
1 2
2 3
3 1
Sample Output
Case 1:
My king, at most 1 road can be built.
Case 2:
My king, at most 2 roads can be built.
做题思路:
对每一行进行排序,而排序的基准是第一列,因此p[a] = b,其中a代表第一列,而b代表第二列,从而转换为求解p数列的最长子序列问题。
最长子序列问题详解
代码如下:
Input
Each test case will begin with a line containing an integer n(1 ≤ n ≤ 500,000). Then n lines follow. Each line contains two integers p and r which represents that Poor City p needs to import resources from Rich City r. Process to the end of file.
Output
For each test case, output the result in the form of sample.
You should tell JGShining what's the maximal number of road(s) can be built.
Sample Input
2
1 2
2 1
3
1 2
2 3
3 1
Sample Output
Case 1:
My king, at most 1 road can be built.
Case 2:
My king, at most 2 roads can be built.
做题思路:
对每一行进行排序,而排序的基准是第一列,因此p[a] = b,其中a代表第一列,而b代表第二列,从而转换为求解p数列的最长子序列问题。
最长子序列问题详解
代码如下:
#include <iostream>
using namespace std;
int p[500005], b[500005];
int n;
int bSearch(int num, int k)
{
int low=1, high=k;
while(low<=high)
{
int mid=(low+high)/2;
if(num>=b[mid])
low=mid+1;
else
high=mid-1;
}
return low;
}
int LIS()
{
int low = 1, high = n;
int k = 1;
b[1] = p[1];
for(int i=2; i<=n; ++i)
{
if(p[i]>=b[k])
b[++k] = p[i];
else
{
int pos = bSearch(p[i], k);
b[pos] = p[i];
}
}
return k;
}
int main()
{
int a, b;
int nCases = 1;
while(scanf("%d", &n) != EOF)
{
for(int i=1; i<=n; ++i)
{
scanf("%d %d", &a, &b);
p[a] = b;
}
int ans = LIS();
printf("Case %d:\nMy king, at most %d road", nCases++, ans);
if(ans != 1) printf("s");
printf(" can be built.\n\n");
}
return 0;
}