Hdu 1518 (dfs), hdu1518dfs
Reference page:
Http://www.yuanjiaocheng.net/CSharp/Csharp-keys.html
Http://www.yuanjiaocheng.net/CSharp/csharp-interface.html
Http://www.yuanjiaocheng.net/CSharp/Csharp-operators.html
Http://www.yuanjiaocheng.net/CSharp/Csharp-if-else.html
Http://www.yuanjiaocheng.net/CSharp/Csharp-ternary-operator.html
Question link: http://acm.hdu.edu.cn/showproblem.php? Pid = 1, 1518
Square Problem DescriptionGiven a set of sticks of various lengths, is it possible to join them end-to-end to form a square?
InputThe 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.
OutputFor each case, output a line containing "yes" if is possible to form a square; otherwise output "no ".
Sample Input3 4 1 1 1 1 5 10 20 30 40 50 8 1 7 2 6 4 3 5
Sample Outputyes no yes: give you n sides to use these sides to form a square (not many but only n ). Analysis: Mainly timeout issues. Pay attention to optimization.
1 # include <cstdio> 2 # include <cstring> 3 # include <algorithm> 4 using namespace std; 5 6 int a [22], vis [22]; 7 int n, m, length; // length indicates the side length of the square to be composed of 8 int ans, flag; 9 10 void dfs (int cnt, int sum, int k) // cnt record edge number, sum record current edge length, k record Location 11 {12 if (cnt = 3) // if three sides meet the requirements, then the fourth edge must meet the requirements of 13 {14 flag = 1; 15 return; 16} 17 if (sum = length) // find the edge that meets the requirements, and add one edge number, initialize 18 {19 cnt ++; 20 k = 0; 21 sum = 0; 22} 23 for (int I = k; I <M; I ++) 24 {25 if (! Vis [I] & sum + a [I] <= length) 26 {27 vis [I] = 1; 28 dfs (cnt, sum + a [I], I + 1); 29 if (flag) // optimization time, (returns after all edges are found, and you do not need to run the subsequent code again) 30 {31 return; 32} 33 vis [I] = 0; 34} 35} 36} 37 38 int main () 39 {40 scanf ("% d ", & n); 41 while (n --) 42 {43 ans = 0; 44 scanf ("% d", & m); 45 for (int I = 0; I <m; I ++) 46 {47 scanf ("% d", & a [I]); 48 ans + = a [I]; 49} 50 if (ans % 4) // if all edges are not multiples of 4, they cannot form a square 51 {52 printf ("no \ n"); 53 continue; 54} 55 memset (vis, 0, sizeof (vis); 56 flag = 0; 57 length = ans/4; // record square side length 58 dfs (0, 0, 0); 59 if (flag) 60 printf ("yes \ n"); 61 else62 printf ("no \ n"); 63} 64 return 0; 65}
View Code