题目链接:UVALive 6948 Jokewithpermutation
题意:给一串数字序列,没有空格,拆成从1到N的连续数列。
dfs.
可以计算出N的值,也可以直接检验当前数组是否合法。
#include <stdio.h> #include <iostream> #include <string.h> #define maxn 100 using namespace std; char str[maxn]; int num[maxn]; bool vis[maxn]; int cnt; int len; int N; bool ok = false; bool dfs(int id, int pos) { if (ok) return false; if (pos == len && id == N) { cnt = id; ok = true; return true; } if (pos >= len) return false; num[id] = str[pos] - ‘0‘; if (num[id] >= 1 && num[id] <= N && !vis[num[id]]) { vis[num[id]] = 1; if (dfs(id+1, pos+1)) return true; //dfs(id+1, pos+1); vis[num[id]] = 0; } num[id] = (str[pos]-‘0‘)*10 + str[pos+1]-‘0‘; if (num[id] >= 1 && num[id] <= N && !vis[num[id]]) { vis[num[id]] = 1; if (dfs(id+1, pos+2)) return true; //dfs(id+1, pos+2); vis[num[id]] = 0; } return false; } int main() { //freopen("in.cpp", "r", stdin); while(~scanf("%s", str)) { ok = false; len = strlen(str); cnt = 0; N = (len>9?9:len)+(len>9?(len-9)/2:0); memset(vis, 0, sizeof(vis)); dfs(0, 0); for (int i=0; i<cnt; ++i) { if (i == 0) printf("%d", num[i]); else printf(" %d", num[i]); } printf("\n"); } return 0; }
dfs要优雅...
时间: 2024-10-10 08:58:56