hdu 1518

来源:互联网 发布:湖州丝绸外汇数据 编辑:程序博客网 时间:2024/05/22 04:56


Square

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


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

一道简单的dfs题,我已开始以为题意为可以不全部使用木棍,原来是,要全用上的.如果补全用上则需要每次去除若干个,然后就和木棍全部使用一样了.

Accepted1518828MS316K

#include <iostream>using namespace std;bool visit[1200];int val[1200];int total;bool dfs(int index ,int n,int sum,int depth){    if (depth ==3)        return true;    if ( sum==total )       return dfs(0,n,0,depth+1);    for ( int i=index;i<n; ++i ){        if ( visit[i] || val[i]+sum>total )            continue;        visit[i]=true;        if ( dfs(i+1,n,val[i]+sum,depth) )            return true;        visit[i]=false;    }    return false;}int main(){    int testnum ;    int valnum;        cin>>testnum;    while ( testnum-- ){        total = 0;        memset(visit,0,sizeof(visit));        cin>>valnum;        for ( int i=0;i<valnum;++i ){            cin>>val[i];            total+=val[i];        }        if ( total%4!=0 || valnum<4){            cout<<"no"<<endl;            continue;        }        total/=4;        if ( dfs(0,valnum,0,0) ){            cout<<"yes"<<endl;        }else {            cout<<"no"<<endl;        }     }    return 0;}

用sort排序后:

Accepted1518515MS320K1166 BC++

#include <iostream>#include <algorithm> using namespace std;bool visit[1200];int val[1200];int total;bool dfs(int index ,int n,int sum,int depth){    if (depth ==3)        return true;    if ( sum==total )       return dfs(0,n,0,depth+1);    for ( int i=index;i<n; ++i ){               if ( visit[i]   )            continue;        if ( val[i]+sum>total )            return false;        visit[i]=true;        if ( dfs(i+1,n,val[i]+sum,depth) )            return true;        visit[i]=false;    }    return false;}int main(){    int testnum ;    int valnum;        cin>>testnum;    while ( testnum-- ){        total = 0;        memset(visit,0,sizeof(visit));        cin>>valnum;        for ( int i=0;i<valnum;++i ){            cin>>val[i];            total+=val[i];        }        if ( total%4!=0 || valnum<4){            cout<<"no"<<endl;            continue;        }        total/=4;        sort(val,val+valnum);        if ( dfs(0,valnum,0,0) ){            cout<<"yes"<<endl;        }else {            cout<<"no"<<endl;        }     }    return 0;}


0 0