标签:dfs
A 2 3 6 3 3 8 8
Yes No
题意。。。。
就是模板
代码:
#include <iostream> #include <cstdio> #include <cstring> const int M = 50; int num[M]; bool vis[M]; int dfs(int n, int top){ if(n == 1){ if(24 == num[top-1]) return 1; return 0; } for(int i = 0; i < top; ++ i){ if(!vis[i]){ vis[i] = 1; for(int j = i+1; j < top; ++ j){ if(!vis[j]){ vis[j] = 1; num[top] = num[i]+num[j]; if(dfs(n-1, top+1)) return 1; num[top] = num[i]-num[j]; if(dfs(n-1, top+1)) return 1; num[top] = num[j]-num[i]; if(dfs(n-1, top+1)) return 1; num[top] = num[i]*num[j]; if(dfs(n-1, top+1)) return 1; if(num[j]&&num[i]%num[j] == 0){ num[top] = num[i]/num[j]; if(dfs(n-1, top+1)) return 1; } if(num[i]&&num[j]%num[i] == 0){ num[top] = num[j]/num[i]; if(dfs(n-1, top+1)) return 1; } vis[j] = 0; } } vis[i] = 0; } } return 0; } int main(){ int i = 0; char s[2]; while(scanf("%s", s) == 1){ if(s[0] >= '2'&&s[0] <= '9'){ num[i++] = s[0]-'0'; } else if(s[0] == 'A') num[i++] = 1; else if(s[0] == 'J') num[i++] = 11; else if(s[0] == 'Q') num[i++] = 12; else if(s[0] == '1') num[i++] = 10; else num[i++] = 13; int t = 3; while(t --){ scanf("%s", s); if(s[0] >= '2'&&s[0] <= '9'){ num[i++] = s[0]-'0'; } else if(s[0] == 'A') num[i++] = 1; else if(s[0] == 'J') num[i++] = 11; else if(s[0] == 'Q') num[i++] = 12; else if(s[0] == '1') num[i++] = 10; else num[i++] = 13; } memset(vis, 0, sizeof(vis)); if(dfs(4, 4)) puts("Yes"); else puts("No"); i = 0; } return 0; }
标签:dfs
原文地址:http://blog.csdn.net/shengweisong/article/details/45256807