分析:从头到尾将每个元素逐个考虑,从上一个元素截至得到的vector融入该元素,得到一个新的vector,直到vector个数等于k。vector用来保存,和互不相同的包含各状态信息的结构体。
#include<cstdio> #include<algorithm> #include<cmath> #include<cstring> #include<iostream> #include<vector> #include<set> using namespace std; typedef struct S { int sum; bool vis[52]; int cnt; } NODE; NODE node[1300]; int a[52], tot; vector<int> b; int main() { int n, k, i, j, m, end = 1; scanf("%d%d", &n, &k); for (i = 1; i <= n; ++i) scanf("%d", &a[i]); node[tot].sum = a[1]; b.push_back(a[1]); memset(node[tot].vis, 0, sizeof (node[tot].vis)); node[tot].vis[1] = 1; node[tot].cnt = 1; printf("%d", node[tot].cnt); for (j = 1; j <= 1; ++j) if (node[tot].vis[j]) printf(" %d", a[j]); printf("\n"); ++tot; if (tot == k) return 0; for (i = 2; i <= n; ++i) { node[tot].sum = a[i]; if (count(b.begin(), b.end(), node[tot].sum)) goto L; b.push_back(a[i]); memset(node[tot].vis, 0, sizeof (node[tot].vis)); node[tot].vis[i] = 1; node[tot].cnt = 1; printf("%d", node[tot].cnt); for (j = 1; j <= i; ++j) if (node[tot].vis[j]) printf(" %d", a[j]); printf("\n"); ++tot; if (tot == k) return 0; L: for (m = 0; m < end; ++m) { node[tot].sum = node[m].sum + a[i]; if (count(b.begin(), b.end(), node[tot].sum)) continue; b.push_back(node[tot].sum); for (j = 1; j < i; ++j) node[tot].vis[j] = node[m].vis[j]; node[tot].vis[i] = 1; node[tot].cnt = node[m].cnt + 1; printf("%d", node[tot].cnt); for (j = 1; j <= i; ++j) if (node[tot].vis[j]) printf(" %d", a[j]); printf("\n"); ++tot; if (tot == k) return 0; } end=tot; } return 0; }