地址
点击打开链接
哇,这两个题,写的我头皮发麻。这个和上一个的区别就是这个要求输出按字典序,也就是1 3 2 在上题目中是1 3 和 1 2而这一题输出顺序为1 2 和 1 3.
理论上这个题比上一个题目要简单。这个题的限制其实就两个,一个是排完序后,你需要记录原来的位置,不但要数值上不递减,还要求index索引上递增。因此只有当前索引大于上一索引时,才可以通过。
另一个限制,就是比如 2 3 3 5 6 当你走完第一次,开头2的情况就都用了(注意这里指的纵向的,也就是深度优先),下一次开始3开头,但是再往后访问,又发现一个3,这个时候就不允许了。因此要把这个3跳过去。也就是需要记录一下上一轮循环的起始位置。如果这次与上次相等,那么就直接continue,否则就更新上一个数值的记录。
附代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string.h>
#include<cmath>
#include<algorithm>
using namespace std;
#define MAXN 1010
struct Node{
int num,pos;
}nodes[MAXN];
int num[MAXN];
int n,p,_count,len;
bool flag;
bool cmp(Node a , Node b)
{
if(a.num==b.num)
return a.pos<b.pos;
return a.num<b.num;
}
void dfs(int l,int pos,int rePos){
if(_count==p)
{
return ;
}
// cout << l <<" "<< len<<endl;
if(l==len)
{
_count ++;
for(int i = 0 ; i<l-1 ; i ++)
{
cout << num[i]<<" ";
}
cout << num[l-1]<<endl;
return ;
}
int preNum;
int flag =0 ;
for(int i = pos ;i<n;i++ )
{
if(nodes[i].pos>rePos)
{
if(flag==0)
{
flag++;
preNum = nodes[i].num;
}
else {
if(preNum==nodes[i].num)
{
continue ;
}
}
preNum = nodes[i].num;
num[l] = nodes[i].num;
dfs(l+1,i+1,nodes[i].pos);
}
}
}
int main(){
while (cin>>n>>p )
{
for(int i = 0 ; i <n ;i++)
{
cin>>nodes[i].num;
nodes[i].pos = i ;
}
sort(nodes,nodes+n,cmp);
_count =0 ;
for(int i = 1 ; i < n ; i++)
{
len = i ;
dfs(0,0,-1);
if(_count>=p) break ;
}
cout <<endl;
}
}