1. 程式人生 > >P3040 [USACO12JAN]貝爾分享Bale Share

P3040 [USACO12JAN]貝爾分享Bale Share

turn cin cas cst iostream read sse ++ 貝爾

想了一個二分 + 狀壓的思路, 嫌太麻煩了, 直接一個dfs + 最優性剪枝水了過去.
貌似比某些dp還快?

#include <cstdio>
#include <cstring>
#include <cassert>
#include <iostream>
#include <algorithm>
using namespace std;
const int MAXN = 20 + 2;
inline int read(){
    char ch = getchar(); int x = 0;
    while(!isdigit(ch)) ch = getchar();
    while(isdigit(ch)) x = x * 10 + ch - '0', ch = getchar();
    return x;
}

int N;
int s[MAXN], sum;

int ans = (1 << 30);
void dfs(int u, int suma, int sumb, int sumc) {
    if(u == N + 1) return ans = min(ans, max(suma, max(sumb, sumc))), void();
    if(suma + s[u] < ans) dfs(u + 1, suma + s[u], sumb, sumc);
    if(sumb + s[u] < ans) dfs(u + 1, suma, sumb + s[u], sumc);
    if(sumc + s[u] < ans) dfs(u + 1, suma, sumb, sumc + s[u]);
    return ;
}

int main(){
    cin>>N;
    for(int i = 1; i <= N; i++) sum += (s[i] = read());
    sort(s + 1, s + N + 1, greater<int>());
    dfs(1, 0, 0, 0);
    printf("%d\n", ans);
    return 0;
}

P3040 [USACO12JAN]貝爾分享Bale Share