hdu1518

来源:互联网 发布:一键配置java环境 编辑:程序博客网 时间:2024/06/05 19:43

Square

Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 15091    Accepted Submission(s): 4749


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
34 1 1 1 15 10 20 30 40 508 1 7 2 6 4 4 3 5
 

Sample Output
yesnoyes
 

Source
University of Waterloo Local Contest 2002.09.21
 

Recommend

LL   |   We have carefully selected several similar problems for you:  1732 1401 1043 1226 1016 

思路:这个题目爆搜会超时,两个剪枝条件,第一个 sum%4==0,第二个其中有一个数大于sum/4,然后 还得选择最优的,就是例如 6 1 2 4.。。。。。。。假设这里sum/4=8;

从6开始循环 6不能选择1,应该要直接去选择2;这里也可以缩短时间。

然后用一个变量记录k  组合到了哪条边,下一次就直接找k后面的边就行了。因为要是前面的可以的话就已经成功了,不需要来找后面的了,所以前面就不需要了。

代码:

#include<stdio.h>#include<stdlib.h>#include<string.h>using namespace std;int m,sum,sum1,sum2;int a[30];int vis[30];int cmp(const void *a, const void *b){   //return *(int*)a  -  *(int*)b; //由小到大排序    return *(int*)b -*(int*)a ;  //由大到小排序}int dfs(int sum,int count,int k){  if(sum==sum1) {count++;sum=0;k=1;}  if(count==3) return 1;  for(int i=1;i<=m;i++)  {      if(a[i]>sum1) return 0;  }  for(int i=k;i<=m;i++)  {      if(sum+a[i]==sum1&&!vis[i]) {            vis[i]=1;            if(dfs(sum+a[i],count,i+1)) return 1;             vis[i]=0;            return 0;      }  }  for(int i=k;i<=m;i++)  {      if(sum+a[i]<=sum1&&!vis[i])      {          vis[i]=1;          if(dfs(sum+a[i],count,i+1)) return 1;          vis[i]=0;         // while(i<=m&&a[i]==a[i+1]) i++;      }  }  return 0;}int main(){    int t;    scanf("%d",&t);    while(t--)    {        scanf("%d",&m);        sum=0;        for(int i=1;i<=m;i++)            {scanf("%d",&a[i]);              sum+=a[i];            }        if(sum%4!=0) {printf("no\n");continue;}       // qsort(&a[1],m,sizeof(int),cmp);        /*for(int i=1;i<=m;i++)            printf("%d ",a[i]);        printf("%d",sum);*/        sum1=sum/4;        memset(vis,0,sizeof(vis));      if(dfs(0,0,1)) printf("yes\n");      else printf("no\n");    }}


原创粉丝点击