zoukankan      html  css  js  c++  java
  • hdu 1258

    Problem : http://acm.hdu.edu.cn/showproblem.php?pid=1258

    dfs简单搜索

    题再简单不过了,只是关键的是同样的求和序列只能算一次

    感觉要来做判重处理会很难过...超无聊的人才会去判重

    因为1<=n<=12,最坏的情况也才2^12,果断直接dfs随便搞一搞

    感觉考验的就只有输出格式了

    只是代码会不会有点长

    #include<cstdio>
    #include<algorithm>
    using namespace std;
    int t,n,k,ans,cou[20];
    struct Num{
        int v,c;//v存数列中某个数的数值,c存该数的个数
    }a[20];
    bool cmp(Num x,Num y){
        return x.v>y.v;
    }
    void put(){
        int sum=0;
        for(int i=0;i<k;i++)sum+=cou[i]*a[i].v;
        if(sum==t){//输出,相信你懂
            ans++;
            int e=0;//e存这个满足条件数列的个数
            for(int i=0;i<k;i++){
                int w=cou[i];
                while(w){
                    if(e)printf("+");
                    printf("%d",a[i].v);
                    w--;
                    e++;
                }
            }
            printf("
    ");
        }
    }
    void dfs(int dex){
        if(dex==k){
            put();
            return;
        }
        for(int i=a[dex].c;i>=0;i--){
            cou[dex]=i;//第dex数选i个,依次减少,保证无重复
            dfs(dex+1);
        }
    }
    void init(){
        k=0;//用来存数列中有多少个相异的数
        for(int i=0;i<n;i++){
            scanf("%d",&a[k].v);
            int j;
            for(j=0;j<k;j++)
                if(a[j].v==a[k].v){
                    a[j].c++;
                    break;
                }
            if(j==k)a[k++].c=1;
        }
    }
    int main()
    {
        while(scanf("%d%d",&t,&n),n){
            init();
            sort(a,a+k,cmp);//按从大到小排列
            printf("Sums of %d:
    ",t);
            ans=0;
            dfs(0);//从最大元素开始搜
            if(ans==0)printf("NONE
    ");
        }
        return 0;
    }
    View Code

    这份代码还可以剪枝优化,数据太弱懒得搞了

  • 相关阅读:
    UVALive 4660 A+B
    UVALive 4660 A+B
    UVA10474 Where is the Marble?
    UVA10474 Where is the Marble?
    UVA1339 UVALive3213 POJ2159 ZOJ2658 Ancient Cipher【密码】
    hdu_1108 最小公倍数
    hdu_1106 排序
    hdu_1205 吃糖果
    hdu_1201 18岁生日
    hdu_1005 Number Sequence
  • 原文地址:https://www.cnblogs.com/cshhr/p/3540992.html
Copyright © 2011-2022 走看看