Hdu1518 Square


Square

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


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


題意:輸入m個數據,判斷m根木棒能否能構成一個正方形,可以的話輸出yes,否則輸出no.


關鍵:深搜,有可能會超時,所以首先要剪枝,排除一部分情況,每次深搜都要把前一根木棒的下標記錄下來,從後面開始搜,避免重複搜索,搜到一根木棒,則從最開始重新搜索。如果發現能夠構成正方形,直接退出,通過flag的狀態來判斷。


代碼:

#include<iostream>
#include<cstring>
using namespace std;
int m;
int a[100000];
int len;
bool flag;
bool vis[100000];
void dfs(int parent,int cnt,int num);
int main(void)
{
    int n;
    cin>>n;
    while(n--)
    {
        cin>>m;
        int sum=0;
        int max=-1;
        for(int i=0;i<m;i++)
        {
            cin>>a[i];
            sum+=a[i];
            max= max>a[i]?max:a[i];
        }

        if(sum%4!=0 || sum/4<max)  //剪枝如果邊長不爲整數或邊長爲整數但是最長的邊大於邊長,則直接輸出no
        {
            cout<<"no"<<endl;
            continue;
        }
        len=sum/4;

        memset(vis,0,sizeof(vis));

        flag=false;
        vis[0]=true;
        dfs(0,1,0);

        if(flag)
        cout<<"yes"<<endl;
        else
        cout<<"no"<<endl;
    }
    return 0;
}
void dfs(int parent,int cnt,int num)
{
    if(cnt==4)
    {
        flag=true;
        return ;
    }

    if(num==len)
    {
        dfs(0,cnt+1,0);
        return ;
    }

    for(int i=parent;i<m;i++)
    {
        int fnum=num+a[i];
        if(fnum<=len && !vis[i])
        {   vis[i]=true;
            dfs(i,cnt,fnum);
            if(flag)   //找到以後直接退出來
            return ;
            vis[i]=false;
        }
    }

}





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章