很简单的一道题,就是给出k种不同的组合就可以了,比赛的时候没有注意到k的范围,直接dfs,果断超时,k只有(n+1)n/2种,所以可以直接枚举即可……
以后要看好范围再写
dfs代码(修改后)
/*
author:jxy
lang:C/C++
university:China,Xidian University
**If you need to reprint,please indicate the source**
*/
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <map>
#define INF 1E9
using namespace std;
int s[50];
int A[51],n,k;
map<int,bool> vis;
int dfs(int remind,int i,int ans)
{
int r;
if(remind==0)
{
if(vis[ans])return 0;
vis[ans]=1;
return ans;
}
if(remind>=2)
{
A[remind]=--i;
return dfs(remind-1,i,ans+s[i]);
}
for(i--;i>=0;i--)
{
A[remind]=i;
r=dfs(remind-1,i,ans+s[i]);
if(r!=0)return r;
}
return 0;
}
int main()
{
int i,j;
scanf("%d%d",&n,&k);
for(i=0;i<n;i++)
scanf("%d",&s[i]);
sort(s,s+n);
int ans;
i=1;
while(k--)
{
ans=dfs(i,n,0);
if(ans==0){i++;k++;continue;}
printf("%d",i);
for(j=i;j>0;j--)
printf(" %d",s[A[j]]);
puts("");
}
}
枚举代码:
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
int a[51];
int n,k,s=0,j=0,i,p;
cin>>n>>k;
for(i=0;i<n;i++)cin>>a[i];
sort(a,a+n);
for(i=0;i<k;i++)
{
cout<<s+1<<" ";
for(p=0;p<s;p++)cout<<a[n-1-p]<<" ";
cout<<a[j++]<<endl;
if(j==n-s){s++;j=0;}
}
return 0;
}