Given a set of sticks of various lengths, is it possible to join them end-to-end to form a square? 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. 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 Output for Sample Input yes no yes
#include <stdio.h> #include <stdlib.h> #include <ctime> //计时用的头文件 #include <iostream> using namespace std; #define size 20 int test_num;//TEST数目 int data[size]={}; bool findsquare = false; int l1,l2,l3,l4; int a[size]={}; int sum; int TimeStart; int TimeEnd; int TimeUsed; void handle(){ //for(int i=0;i<data[0];i++){ // if(a[i]==1) {l1+=data[i+1];} // if(a[i]==2) {l2+=data[i+1];} // if(a[i]==3) {l3+=data[i+1];} // if(a[i]==4) {l4+=data[i+1];} //} if(l1==l2&&l2==l3&&l3==l4) findsquare = true; } void dfs(int step){ if(step ==data[0]+1){ handle(); return; } if(step ==0){ for(int i=1;i<data[0]+1;i++){ sum +=data[i]; } if(sum%4!=0){ return; } } if(l1>sum/4||l2>sum/4||l3>sum/4||l4>sum/4){return;} if(l1==sum/4&&l2==sum/4&&l3==sum/4){findsquare=true;return;} a[step] = 1; l1 +=data[step+1]; dfs(step+1); l1 -=data[step+1]; a[step] = 2; l2 +=data[step+1]; dfs(step+1); l2 -=data[step+1]; a[step] = 3; l3 +=data[step+1]; dfs(step+1); l3 -=data[step+1]; a[step] = 4; l4 +=data[step+1]; dfs(step+1); l4 -=data[step+1]; } int main(){ // time_t start,end,time; /*注意计时所用的变量名称*/ //start=clock(); int count=0; int data_num=0; //freopen("input.txt","r",stdin); scanf("%d",&test_num); for(int i=test_num;i>0;i--){ scanf("%d ",&data[count]); count++; for(int j=data[0];j>0;j--){ scanf("%d ",&data[count]); count++; } data_num = count; count =0; dfs(0); sum =0; if(findsquare == true){ printf("yes "); findsquare = false; } else{ printf("no "); } }//一个case的结束 //end=clock(); // time=end-start;//这里的时间是计算机内部时间 // cout<<"time:"<<time<<endl; // system("pause"); }