HDU 1258 Sum It Up (dfs)

 

 

#include<cstdio>

#include<cstring>

#include<iostream>

#include<algorithm>

using namespace std;

int a[20];

int ans[20];

int num[200];

struct Mark

{

    int shu,rt;

};

Mark mark[20];

int ok;

int n,t;

int cnt;

int cmp(int x,int y)

{

    return x>y;

}

void dfs(int rt,int i,int j,int sum)

{

       if(sum>t) return ;

       int k,l;

       mark[rt].shu=a[i];

       mark[rt].rt=j;

       //printf("%d...\n",sum);

       if(sum==t)

       {

           ok=1; //printf("%d\n",rt);



           int coun=0;

           /*if(t==5&&rt==3)

           {

               printf("%d %d %d %d\n",rt,i,j,sum);

           }*/

           for(k=1;k<=rt;k++)

           {

              for(l=1;l<=mark[k].rt;l++)

              {

                  ans[coun++]=mark[k].shu;

              }

           }

           for(k=0;k<coun;k++)

           {

               if(k!=0) printf("+");

               printf("%d",ans[k]);

           }

           printf("\n");

           return ;

       }

       if(i<cnt-1)

       {

           for(k=num[a[i+1]];k>=0;k--)

           {

               dfs(rt+1,i+1,k,sum+a[i+1]*k);

           }

       }

}

int main()

{

    int i,j,k;

    int temp;

    //int cnt;

    while(scanf("%d%d",&t,&n)!=EOF)

    {

        if(t==0&&n==0) break;

        ok=0; cnt=0;

        memset(ans,0,sizeof(ans));

        memset(num,0,sizeof(num));

        memset(mark,0,sizeof(mark));



        for(i=0;i<n;i++)

        {

            scanf("%d",&temp);

            if(num[temp]==0)

            {

                a[cnt++]=temp;

            }

            num[temp]++;

        }

        //printf("%d..\n",cnt);

        sort(a,a+cnt,cmp);

        /*for(i=0;i<cnt;i++)

        {

            printf("%d %d..\n",a[i],num[a[i]]);

        }*/

        printf("Sums of %d:\n",t);



            for(i=num[a[0]];i>=0;i--)

            {

                dfs(1,0,i,a[0]*i);

            }



        if(ok==0)

            printf("NONE\n");

    }

    return 0;

}

 

你可能感兴趣的:(HDU)