本题基于最长递增子序列,使用二分查找使时间复杂度降为O(nlogn)。
#include <iostream>
using namespace std;
const int N = 500010;
int sub[N]; //存放rich的最长递增子序列
int poor[N]; //存放poor对应的rich
int binarySearch(int ans, int len) //二分查找rich在目前子序列中的位置
{
int left = 1, right = len;
int mid;
while (left <= right)
{
mid = (left + right) / 2;
if (sub[mid] == ans)
return mid;
else if (sub[mid] < ans)
left = mid + 1;
else
right = mid - 1;
}
return left;
}
int main()
{
int group = 0; //组号
int n, p, r;
while (cin >> n)
{
for (int i = 1; i <= n; i++)
{
cin >> p >> r;
poor[p] = r;
}
memset(sub, 0, sizeof(sub)); //初始化sub数组
int len = 1; //最长递增子序列长度
int location;
sub[1] = poor[1];
for (int j = 2; j <= n; j++)
{
location = binarySearch(poor[j], len); //查找poor[j]在子序列中的位置
sub[location] = poor[j];
if (location > len) //如果poor[j]在子序列的最后一位,则子序列长度加1,更新len
len = location;
}
if (len > 1)
{
cout << "Case " << ++group << ":" << endl;
cout << "My king, at most " << len << " roads can be built." << endl;
cout << endl;
}
else
{
cout << "Case " << ++group << ":" << endl;
cout << "My king, at most 1 road can be built." << endl;
cout << endl;
}
}
return 0;
}