题目链接:http://acm.hdu.edu.cn/contests/contest_showproblem.php?pid=1009&cid=885
Problem Description
Notice:Don’t output extra spaces at the end of one line.
Given n,x,y, please construct a permutation of length n, satisfying that:
- The length of LIS(Longest Increasing Subsequence) is equal to x.
- The length of LDS(Longest Decreasing Subsequence) is equal to y.
If there are multiple possible permutations satisfying all the conditions, print the lexicographically minimum one.
Input
The first line contains an integer T(1≤T≤100), indicating the number of test cases.
Each test case contains one line, which contains three integers n,x,y(1≤n≤105,1≤x,y≤n).
Output
For each test case, the first line contains YES '' or
NO’’, indicating if the answer exists. If the answer exists, output another line which contains n integers, indicating the permutation.
翻译:
输入n,x,y三个数,能否构造一个长度为n的全排列,使得最长上升子序列的长度为x,最长下降子序列的长度为y。若能构造,输出YES和这个序列。不能,则输出NO。
分析:
- 特殊的情况先处理掉:
if(x+y>n+1)
{
printf("NO\n");
continue;
}
if(n>=3)
{
if(x+y<4)
{
printf("NO\n");
continue;
}
}
if(x==1&&y!=n||x!=n&&y==1)
{
printf("NO\n");
continue;
}
if(x==1&&y==1)
{
if(n!=1)
{
printf("NO\n");
continue;
}
}
- 先从后向前输出y个逆序,输出完后,还剩n-y个数。此时y的逆序,对x个升序已经贡献了1,这n-y个数还需要构造x-1个升序。
完整代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=1e5+10;
int n,x,y;
int a[N];
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d%d",&n,&x,&y);
int cnt=n;
if(x+y>n+1)
{
printf("NO\n");
continue;
}
if(n>=3)
{
if(x+y<4)
{
printf("NO\n");
continue;
}
}
if(x==1&&y!=n||x!=n&&y==1)
{
printf("NO\n");
continue;
}
if(x==1&&y==1)
{
if(n!=1)
{
printf("NO\n");
continue;
}
}
printf("YES\n");
memset(a,0,sizeof(a));
int res=n;
for(int i=y; i>=1; i--)
a[res--]=n-i+1;///先处理y个逆序
n-=y;
int sub=x-1;///y的逆序对x个正序已经贡献了1,还需要在剩余的n-y个数中构造sub个正序
while(n>=sub)
{
if(n==sub)
{
for(int i=1; i<=n; i++)
a[i]=i;
break;
}
if(n>sub)
{
if(n-sub>y-1)
{
sub--;
for(int i=y; i>=1; i--)///最大构造一个长度为y的逆序,对x的升序贡献1,这个逆序不能超过y
a[res--]=n-i+1;
n-=y;
}
else
{
sub--;
for(int i=1; i<=sub; i++)
a[i]=i;
for(int i=n-sub; i>=1; i--)
a[res--]=n-i+1;
break;
}
}
}
for(int i=1; i<cnt; i++)
printf("%d ",a[i]);
printf("%d\n",a[cnt]);
}
return 0;
}