首页 > 代码库 > HDU 1258 Sum It Up (POJ 1564)

HDU 1258 Sum It Up (POJ 1564)

以前做过,碰巧看到了。我去复制了一下。很奇怪……交POJ的程序交HDU 就WA。

然后重写,交HDU的程序AC后再去交 POJ 居然TLE。简直……


简单DFS,判重就好了。


HDU :

#include<cstdio>
#include<cstring>
#include<string>
#include<queue>
#include<algorithm>
#include<map>
#include<stack>
#include<iostream>
#include<list>
#include<set>
#include<vector>
#include<cmath>

#define INF 0x7fffffff
#define eps 1e-8
#define LL long long
#define PI 3.141592654
#define CLR(a,b) memset(a,b,sizeof(a))
#define FOR(i,a,b) for(int i=a;i<b;i++)
#define FOR_(i,a,b) for(int i=a;i>=b;i--)
#define rep(i,a,b) for(int i=a ; b>a?i<b:i>=b ; b>a? i++:i--)
#define pb push_back
#define mp make_pair
#define ft first
#define sd second
#define sf scanf
#define pf printf
#define sz(v) ((int)(v).size())
#define all(v) (v).begin(),(v).end()
#define acfun std::ios::sync_with_stdio(false)

#define SIZE 100000000 +1
using namespace std;

int n,m,a[12],b[12];
bool vis[12];
bool cmp(int a,int b){return a>b;}
vector<string>ha;
void dfs(int deep,int sum)
{
    if(sum>m)return;
    if(sum==m)
    {
        //pf("(%d==%d   %d)\n",sum,m,deep);
        int out[12];
        memcpy(out,b,sizeof(b));
        sort(out,out+deep,cmp);
        string ch;
        ch.clear();
        FOR(i,0,deep)
        {
            char tmp[11];
            sprintf(tmp,"%d",out[i]);
            ch.append(tmp);
        }
        FOR(i,0,sz(ha))
            if(ha[i]==ch)return;
        ha.pb(ch);
        FOR(i,0,deep-1)
        pf("%d+",out[i]);
        pf("%d\n",out[deep-1]);
    }
    FOR(i,0,n)
    {
        if(vis[i])continue;
        vis[i]=1;
        b[deep]=a[i];
        dfs(deep+1,sum+a[i]);
        vis[i]=0;
    }
}

int main()
{
    while(~sf("%d%d",&m,&n),n||m)
    {
        FOR(i,0,n)
        sf("%d",&a[i]);
        CLR(vis,0);
        ha.clear();
        pf("Sums of %d:\n",m);
        dfs(0,0);
        if(ha.empty())
            puts("NONE");
    }
}

POJ 。以前撸的。


#include<cstdio>
#include<cstring>
int sum,n,a[10001];
int vis[10001],ok;
int ck[10001],top=0;
int check(int ans)
{
    int i;
    for(i=0;i<top;i++)
    if(ck[i]==ans)return 0;
    ck[top++]=ans;return 1;
}
void dfs(int s,int j)
{
    int i;
    if(s==sum)
    {
        int o=0;ok=1;
        int num=0,j=1;
        for(i=0;i<n;i++)
        {
            if(vis[i])
            num=num+a[i]*j,j++;
        }
        if(!check(num))return ;
        for(i=0;i<n;i++)
        {
            if(vis[i]&&!o)printf("%d",a[i]),o=1;
            else if(vis[i])printf("+%d",a[i]);
        }
        printf("\n");
    }
    else
    {
        for(i=j;i<n;i++)
        if(s+a[i]<=sum&&!vis[i])
        vis[i]=1,dfs(s+a[i],i+1),vis[i]=0;
    }
}
int main()
{
    int i;
    while(scanf("%d%d",&sum,&n),sum!=0,n!=0)
    {
        memset(vis,0,sizeof(vis));
        for(i=0;i<n;i++)
        scanf("%d",&a[i]);
        printf("Sums of %d:\n",sum);
        ok=0;top=0;dfs(0,0);
        if(!ok)printf("NONE\n");
    }
}



HDU 1258 Sum It Up (POJ 1564)