标签:
Description
Input
Output
Sample Input
Sample Output
题目要求的就是四个数全排列从小到大输出。
由于考虑到需要排序,而且要去重,所以直接使用了set容器。
全排列用dfs生成。
代码:
#include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <set> #define LL long long using namespace std; int a[5]; bool vis[5]; set <int> ans; void dfs(int now, int val) { if (now == 4) { if (val >= 1000) ans.insert(val); return; } for (int i = 0; i < 4; ++i) { if (vis[i]) continue; vis[i] = true; dfs(now+1, val*10+a[i]); vis[i] = false; } } void Work() { ans.clear(); memset(vis, 0, sizeof(vis)); dfs(0, 0); set <int>::iterator it; int high = -1; bool flag = false; for (it = ans.begin(); it != ans.end(); ++it) { if (high == -1) high = *it/1000; if (high != -1 && *it/1000 != high) { printf("\n"); high = *it/1000; flag = false; } if (flag) printf(" "); printf("%d", *it); flag = true; } printf("\n"); } int main() { //freopen("test.in", "r", stdin); bool flag = false; while (scanf("%d%d%d%d", &a[0], &a[1], &a[2], &a[3]) != EOF && (a[0]+a[1]+a[2]+a[3])) { if (flag) printf("\n"); Work(); flag = true; } return 0; }
ACM学习历程—HDU1716 排列2(dfs && set容器)
标签:
原文地址:http://www.cnblogs.com/andyqsmart/p/4526513.html