题目大意:
题意就是输入棍子的数量和每根棍子的长度,看能不能拼成正方形。
#include <stdio.h> #include <string.h> #include <iostream> #include <algorithm> using namespace std; int n, m, ans,cur,sum,cor; int vis[25],str[25]; void dfs(int der,int res,int start) //这三个变量分别是指,成功条数、目前长度、当前位置 { int i, j; if (der == 4) { cor = 1; return; } if (res == cur) { dfs(der + 1, 0, 0); } for (i = start; i < m; i++) { if (!vis[i] && res + str[i] <= cur) { vis[i] = 1; dfs(der, res + str[i], i + 1); //放或者不放 vis[i] = 0; if (cor)return; //注意不加上这一条就会超时,这个剪枝很关键! } } } int main() { int i, j; scanf("%d", &n); while (n--) { memset(vis, 0, sizeof(vis)); sum = 0; scanf("%d", &m); for (i = 0; i < m; i++) { scanf("%d", &str[i]); sum += str[i]; } cur = sum / 4; sort(str, str + m); if (sum % 4 != 0||cur<str[m-1])printf("no\n"); else { ans = 1; cor = 0; dfs(0, 0, 0); if (cor)printf("yes\n"); else printf("no\n"); } } return 0; }
2018-03-31