Square
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 8900 Accepted Submission(s): 2893
Problem Description
Given a set of sticks of various lengths, is it possible to join them end-to-end to form a square?
Input
The first line of input contains N, the number of test cases. Each test case begins with an integer 4 <= M <= 20, the number of sticks. M integers follow; each gives the length of a stick - an integer between 1 and 10,000.
Output
For each case, output a line containing "yes" if is is possible to form a square; otherwise output "no".
Sample Input
3 4 1 1 1 1 5 10 20 30 40 50 8 1 7 2 6 4 4 3 5
Sample Output
yes no yes
Source
University of Waterloo Local Contest 2002.09.21
#include <stdio.h> #include <string.h> #include <iostream> #include <algorithm> #define maxn 22 int L[maxn], n, tar, times; bool vis[maxn], ok; bool DFS(int k, int leftLen) { if(!leftLen) { if(++times == 4) return true; for(int i = 1; i < n; ++i) { if(!vis[i]) { vis[i] = 1; if(DFS(i + 1, tar - L[i])) return true; else { --times; vis[i] = 0; return false; } } } } int i; for(i = k; i < n; ++i) { if(!vis[i] && L[i] <= leftLen) { vis[i] = 1; if(L[i-1] == L[i] && !vis[i-1]) { vis[i] = 0; continue; } if(DFS(i+1, leftLen - L[i])) return true; vis[i] = 0; } } return false; } int main() { int t, i; scanf("%d", &t); while(t--) { scanf("%d", &n); tar = 0; for(i = 0; i < n; ++i) { scanf("%d", &L[i]); vis[i] = 0; tar += L[i]; } if(tar % 4) { printf("no\n"); continue; } tar /= 4; std::sort(L, L + n, std::greater<int>()); if(L[0] > tar) { printf("no\n"); continue; } times = 0; vis[0] = 1; DFS(1, tar - L[0]); printf(times == 4 ? "yes\n" : "no\n"); } return 0; }
时间: 2024-12-31 07:21:44