• hdu 1518(DFS+剪枝)


    Square

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


    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
     
    题意:问n根木棍能否组成一个正方形?
    题解:排序+暴力+剪枝。。那些15ms的大神是怎么做到的。。
    #include <cstdio>
    #include <cstring>
    #include <queue>
    #include <algorithm>
    #include <stdlib.h>
    using namespace std;
    
    int v[25];
    int n;
    int sum = 0;
    bool vis[25];
    bool flag;
    //cnt代表当前到第几根了,len代表当前木棍长度
    void dfs(int cnt,int len,int now){
        if(cnt==4){
            flag = true;
            return;
        }
        for(int i=now;i<n;i++){
            if(flag) return;
            if(vis[i]||sum<len+v[i]) continue;
            if(sum==len+v[i]){
                vis[i] = true;
                dfs(cnt+1,0,0);
                vis[i] = false;
            }else if(sum>len+v[i]){
                vis[i] = true;
                dfs(cnt,len+v[i],i+1);
                vis[i] = false;
            }
        }
    }
    int cmp(int a,int b){
        return a>b;
    }
    int main(){
        int tcase;
        scanf("%d",&tcase);
        while(tcase--){
            scanf("%d",&n);
            sum = 0;
            for(int i=0;i<n;i++){
                scanf("%d",&v[i]);
                sum+=v[i];
            }
            sort(v,v+n,cmp);
            if(sum%4!=0){
                printf("no
    ");
                continue;
            }
            sum/=4;
            if(v[0]>sum) {
                printf("no
    ");
                continue;
            }
            memset(vis,false,sizeof(vis));
            flag = false;
            dfs(0,0,0);
            if(flag) printf("yes
    ");
            else printf("no
    ");
        }
    }
  • 相关阅读:
    sdmenu js
    python 语言开发组合模块,为软件整合提供帮助
    星际二 地图制作过程
    mozilla
    虚拟机 装 ios
    jaxb之xjc编码问题
    抽象类注意事项(面试常常涉及)
    使用java6做webservice
    在linux上jaxb 工具的shell命令编写
    在Redhat 5.0 上安装Eclipse 3.6
  • 原文地址:https://www.cnblogs.com/liyinggang/p/5740427.html
Copyright © 2020-2023  润新知