zoukankan      html  css  js  c++  java
  • HDU1518 Square(DFS,剪枝是关键呀)

    Square

    Time Limit : 10000/5000ms (Java/Other)   Memory Limit : 65536/32768K (Java/Other)
    Total Submission(s) : 9   Accepted Submission(s) : 4
    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
     
    Source

    University of Waterloo Local Contest 2002.09.21

    题意:根据已知边的长度,问能否构成一个正方形.

    解决超时是关键!

    AC代码:

    #include<iostream>
    #include<cstring>
    #include<algorithm>
    using namespace std;
    int a[25];
    bool vis[25];
    int n,ave;
    bool flag;
    void dfs(int num,int len,int start)
    {
        if(flag)
        return;
        if(num==4)
        {
            flag=true;
            return;
        }
        if(len==ave)
        {
            dfs(num+1,0,0);
            if(flag)
                return;
        }
        for(int i=start;i<n;i++)
        {
            if(!vis[i]&&len+a[i]<=ave)
            {
                vis[i]=true;
                dfs(num,len+a[i],i+1);
                vis[i]=false;
                if(flag)
                    return;
            }
        }
    }
    int main()
    {
        int t;
        cin>>t;
        while(t--)
        {
            cin>>n;
            int sum=0,maxlen=0;
            for(int i=0;i<n;i++)
            {
                cin>>a[i];
                sum+=a[i];
                if(a[i]>maxlen)
                    maxlen=a[i];
            }
            ave=sum/4;
            if(sum%4!=0||maxlen>ave)
            {
                cout<<"no"<<endl;
                continue;
            }
            sort(a,a+n);
            memset(vis,0,sizeof(vis));
            flag=false;
            dfs(0,0,0);
            if(flag)
                cout<<"yes"<<endl;
            else
                cout<<"no"<<endl;
        }
    }
     
  • 相关阅读:
    Linux下搭建DNS服务器
    Linux下安装Oracle客户端
    CentOS下配置LVM和RAID
    Linux下配置MySQL主从复制
    Linux下二进制文件安装MySQL
    不偏移的天地图地图服务
    Lucene
    Arcpy处理修改shapefile FeatureClass 线要素坐标
    使用ArcGIS实现WGS84经纬度坐标到北京54高斯投影坐标的转换
    ArcGIS自定义坐标变换中的方法说明
  • 原文地址:https://www.cnblogs.com/wangmenghan/p/5683823.html
Copyright © 2011-2022 走看看