Sequence one
Time Limit: 6000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 551 Accepted Submission(s): 203
Now give you a number sequence, include n (<=1000) integers, each integer not bigger than 2^31, you want to find the first P subsequences that is not decrease (if total subsequence W is smaller than P, than just give the first W subsequences). The order of subsequences is that: first order the length of the subsequence. Second order the sequence of each integer’s position in the initial sequence. For example initial sequence 1 3 2 the total legal subsequences is 5. According to order is {1}; {3}; {2}; {1,3}; {1,2}. {1,3} is first than {1,2} because the sequence of each integer’s position in the initial sequence are {1,2} and {1,3}. {1,2} is smaller than {1,3}. If you also can not understand , please see the sample carefully.
Each test case include, first two integers n, P. (1<n<=1000, 1<p<=10000).
3 5 1 3 2 3 6 1 3 2 4 100 1 2 3 2
1 3 2 1 3 1 2 1 3 2 1 3 1 2 1 2 3 1 2 1 3 2 3 2 2 1 2 3 1 2 2HintHint : You must make sure each subsequence in the subsequences is unique.
题目大意:给出n个数,最多需要p个序列、每个序列都要递增的,而且是独一无二的(意味着要去重)、而且如果子序列长度相同,位子靠前的先输出、
思路:dfs+剪枝、
直接dfs之后我们知道答案有重复的,而且这些个重复的都有一个特点,在慢慢摸索到这个特点之后,去重的问题就能够简单解决了:
问题1、去重问题:
直接dfs找第三组样例的答案是:
1
2
3
2
1 2
1 3
2 3
1 2
2 2
1 2 3
1 2 2
其中第四个明显重复,发现第一个特点:如果子序列长度为1,那么我们从原序列第一个元素开始一直扫到当前位子元素,如果有重复,那么就说明会重复、
其中第八个明显重复,发现第二个特点:如果子序列长度大于1,那么我们对应找到上一个子序列元素所在原序列的位子,然后一直扫到当前位子元素,如果有重复,那么就说明会重复,
第一个特点比较好理解,这里不多说,我们来强调一下第二个特点:
原序列 1 2 3 2
第八个子序列上一个元素对应1,在原序列位子是1,然后一直扫到当前位子4,其中两个2重复了,如果这个2符合序列条件(递增)、可想而知之前这个2是已经用过了的,所以这个序列是重复的、
去重问题处理之后,交了一发,TLE,剪枝:
1、如果当前原序列剩下的元素少于我们对目标长度序列需要的元素,return;
2、如果长度为3的目标子序列长度没有找到可行解,那么长度为4的目标子序列长度也不可能有可行解、
3、如果得到的目标子序列数目已经足够了,也要剪枝、
解决了两个主要问题,最后上AC代码:
#include<stdio.h>
#include<string.h>
using namespace std;
int n,m;
int ans[1005];
int a[1005];
int cont;
void dfs(int cur,int now,int len)
{
if(n-cur<len-now)return ;//
if(cont>=m)return ;
if(now==len)
{
cont++;
for(int i=0;i<len-1;i++)
{
printf("%d ",ans[i]);
}
printf("%d\n",ans[len-1]);
return ;
}
for(int i=cur+1;i<=n;i++)
{
if(now>0&&a[i]<ans[now-1])continue;
int pos=false;
for(int j=cur+1;j<i;j++)
{
if(a[j]==a[i])
{
pos=true;
break;
}
}
if(pos==true)continue;
ans[now]=a[i];
dfs(i,now+1,len);
if(cont==m)return ;
}
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
cont=0;
for(int i=1;i<n;i++)
{
int cnt=cont;
dfs(0,0,i);
if(cont==cnt||cont>=m)break;
}
printf("\n");
}
}
本文探讨了在限定条件下寻找不下降的子序列问题,通过DFS深度优先搜索结合剪枝策略实现有效求解,并附带AC代码。
356

被折叠的 条评论
为什么被折叠?



