POJ.3172 Scales (DFS)

POJ.3172 Scales (DFS)

题意分析

一开始没看数据范围,上来直接01背包写的。RE后看数据范围吓死了。然后写了个2^1000的DFS,妥妥的T。 后来想到了预处理前缀和的方法。细节以注释的方式给出。

代码总览

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <sstream>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <cmath>
#define INF 0x3f3f3f3f
#define nmax 1005
#define MEM(x) memset(x,0,sizeof(x))
using namespace std;
long long a[nmax];
long long sum[nmax];
long long n,M,ans;
void dfs(int depth,long long num )
{
    if(num > ans) ans = num;
    if(depth < 1) return;
    for(int i = depth;i>=1;--i){
        if(a[i] + num> M) continue;//如果当前位置的值加上num 超过了M 不合适,继续向小的方向找
        if(sum[i] + num <= ans) break;// 当前位置的前缀和加上num 比ans还小,那么解不会更优, 况且前面的前缀和只会更小,直接break.
        dfs(i-1,num+a[i]);// 若不满足上述条件,继续向前搜索。
    }
}
int main()
{
    //freopen("in.txt","r",stdin);
    while(scanf("%I64d %I64d",&n,&M)!= EOF){
        ans = 0;
        sum[0] = 0;
        for(int i = 1; i<=n;++i){
            scanf("%I64d",&a[i]);
            sum[i] = sum[i-1] + a[i];
        }
        dfs(n,0);
        printf("%I64d
",ans);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/pengwill/p/7367093.html