D. Unmerge
题目描述
Example
input
6
2
2 3 1 4
2
3 1 2 4
4
3 2 6 1 5 7 8 4
3
1 2 3 4 5 6
4
6 1 3 7 4 5 8 2
6
4 3 2 5 1 11 9 12 8 6 10 7
output
YES
NO
YES
YES
NO
NO
**题意思路:**给一个长度为2×n长的数组,问是否可有两个长度为n的数组合并而成,合并规则如下:a数组的数组头小于b的数组头就放入合成字符串中,删去这个被拿走的,补位,继续比较,知道全部数都放入到2×n的合成字符串。
看了好多方的题解、代码,应该是这样的吧。
分析:如果合成字符串中一个数已经判断完了原先是那个字符串的,那么接着他的下一个字符串,如果比他小,则一定是跟上一个同一个字符串(两个字符串头比较取小的),所以可以推出,2×n长的字符串中,下降子序列一定是一个字符串的,记在一起,一起活动。之后问是否能组成两个长度为n的字符串,使用dp来(01背包)选择或者不选总共统计下来的几个长度(下降子序列),dp[n]是否等于n即可。
dp
代码
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
int t,n,a[4005],top;
int f[4005]= {0};
int main()
{
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
top=0;
int v=0,cur=0;
for(int i=1; i<=2*n; i++)
{
int x;
scanf("%d",&x);
//!统计每次降序的个数
if(v<x)
{
if(cur)
a[++top]=cur;
v=x;
cur=1;
}
else
cur++;
}
for(int i=0; i<=2*n; i++)
f[i]=0;
for(int i=1; i<=top; i++)
{
for(int j=n; j>=a[i]; j--)
f[j]=max(f[j],f[j-a[i]]+a[i]);
}
if(f[n]==n)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}