一看数据量就知道要 O(nlogn) 的 LIS
于是上网学了下。。
DP方程仍然是 dp[i] = max(dp[j]+1) (a[j] < a[i])
不过这次用 f[i] 表示所有长度为 i 的上升子序列中结尾最小的那个子序列的结尾。(有点绕嘴。。)
这样就免去了求 max 的过程。
维护 f 数组,每当读入一个 a[i] 时,如果它比 f 中最后一个元素还大,则将 f 数组的长度增加1,并把 a[i] 赋给 f 的结尾。
否则找到 f 中第一个比 a[i] 大的数,将其替换为 a[i] 。
很不严谨的证明:假设要找结尾最小的那个 LIS ,那么我们如果保证在遍历 a 数组时,遍历到该 LIS 的最后一项之前,我们已经得到了 a 数组在这一项之前的所有元素中长度为 LIS 长度减1的结尾最小的子序列,显然问题可解。同理,LIS 长度减1的子问题又可以由 LIS 长度减2的得出。故问题得解。
查找过程可以二分,故时间复杂度被优化到了 O(nlogn)。
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 501000;
int p[maxn], r[maxn], r1[maxn], od[maxn];
int que[maxn], cnt;
bool cmp(int a, int b)
{
return p[a] < p[b];
}
int findr(int x)
{
int lf = 0, rt = cnt;
while(lf <= rt) {
int md = (lf + rt) / 2;
if(que[md] <= x && que[md+1] > x)
return md + 1;
else if(que[md] > x)
rt = md - 1;
else
lf = md + 1;
}
}
int main()
{
int n, ca = 1;
while(~scanf("%d", &n)) {
for(int i = 0; i < n; i++) {
scanf("%d%d", &p[i], &r1[i]);
od[i] = i;
}
sort(od, od+n, cmp);
for(int i = 0; i < n; i++)
r[i] = r1[od[i]];
cnt = 0;
que[0] = r[0];
for(int i = 1; i < n; i++) {
if(r[i] > que[cnt]) {
cnt++;
que[cnt] = r[i];
}
else que[findr(r[i])] = r[i];
}
printf("Case %d:\nMy king, at most %d ", ca++, cnt+1);
if(cnt == 0) printf("road ");
else printf("roads ");
printf("can be built.\n\n");
}
return 0;
}
PS:此题有一坑,输出时要注意单复数。。。