ural 1005 dp dfs or 0 1背包

就是说不到20堆石头。分成2大堆。。让他们绝对值最小。。
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
int w[22],n,sum[22],ans,ave;
void dfs(int idx,int num)
{
    if(num>ave)return;
    if(idx<=0)return;
    if(sum[idx]+num<=ave)
    {
        if(sum[idx]+num>ans)ans=sum[idx]+num;
        return;
    }
    if(num>ans) ans=num;
    dfs(idx-1,num+w[idx]);
    dfs(idx-1,num);
}
int main()
{
    while(scanf("%d",&n)!=EOF)
    {
        int i,j;
        ans=0;
        for(i=1;i<=n;i++)scanf("%d",&w[i]),sum[i]=sum[i-1]+w[i];
        ave=sum[n]>>1;
        dfs(n,0);
        printf("%d",sum[n]-2*ans);
    }
    return 0;
}

你可能感兴趣的:(ural 1005 dp dfs or 0 1背包)