HAOI2007 上升序列

[HAOI2007]上升序列

Description

  对于一个给定的S={a1,a2,a3,…,an},若有P={ax1,ax2,ax3,…,axm},满足(x1 < x2 < … < xm)且( ax1 < ax
2 < … < axm)。那么就称P为S的一个上升序列。如果有多个P满足条件,那么我们想求字典序最小的那个。任务给
出S序列,给出若干询问。对于第i个询问,求出长度为Li的上升序列,如有多个,求出字典序最小的那个(即首先
x1最小,如果不唯一,再看x2最小……),如果不存在长度为Li的上升序列,则打印Impossible.

Input

  第一行一个N,表示序列一共有N个元素第二行N个数,为a1,a2,…,an 第三行一个M,表示询问次数。下面接M
行每行一个数L,表示要询问长度为L的上升序列。N<=10000,M<=1000

Output

  对于每个询问,如果对应的序列存在,则输出,否则打印Impossible.

Sample Input

6
3 4 1 2 3 6
3
6
4
5

Sample Output

Impossible
1 2 3 6
Impossible

Solution

这道题有个非常巧妙地想法。

因为要求字典序最小的上升子序列,那么我们从n1求出最长下降子序列,然后再从1n找 (f[i])大于要求值的就行了。

Code

//Writer : Hsz %WJMZBMR%tourist%hzwer
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <vector>
#include <cstdlib>
#include <algorithm>
#define LL long long
using namespace std;
int read() {
	int x=0,f=1;
	char ch=getchar();
	while(ch<'0'||ch>'9') {
		if(ch=='-')f=-1;
		ch=getchar();
	}
	while(ch>='0'&&ch<='9') x=(x<<3)+(x<<1)+ch-'0',ch=getchar();
	return x*f;
}
const int inf=0x3fffffff;
int n,a[10005*32],m;
int f[10005*32],t[10005*32],ans;
int find(int x) {
	int l=1,r=ans;
	int res=0;
	while(l<=r) {
		int mid=(l+r)>>1;
		if(t[mid]>x) res=mid,l=mid+1;
		else r=mid-1;
	}
	return res;
}
void dp() {
	for(int i=n; i; i--) {
		int tt=find(a[i]);
		f[i]=tt+1;ans=max(ans,tt+1);
		if(t[tt+1]<a[i]) t[tt+1]=a[i];
	}
}
int main() {
	n=read();
	for(int i=1; i<=n; i++) a[i]=read();
	dp();//二分nlogn找最长下降子序列
	m=read();
	int opt;
	for(int i=1; i<=m; i++) {
		opt=read();
		if(opt>ans) {
			puts("Impossible");
			continue;
		}
		int last=0;
		for(int i=1; i<=n; i++) {
			if(f[i]>=opt&&a[i]>last) {//如果它是那个lis的一部分
				printf("%d ",a[i]);
				last=a[i];
				opt--;
				if(!opt) break;
			}
		}
		printf("
");
	}
	return 0;
}
我是咸鱼。转载博客请征得博主同意Orz
原文地址:https://www.cnblogs.com/sdfzhsz/p/9145546.html