ZZUOJ-10452 "分"数

这道题在常规下要开个三维dp数组dp(i)(j)(k), dp(i)(j)(k) |= dp(i-1)(j-1)(k-num[i]);不过可以用滚动数组

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <vector>
#include <climits>
#include <set>
#include <cstdlib>

using namespace std;
#define INF 1e8
int num[55];
bool dp[55][5050];
int main(){

// freopen("in.txt", "r", stdin);
    int n;

    while(cin >> n){

        int sum = 0;
        memset(dp, 0, sizeof(dp));
        for(int i = 0; i < n; i++){

            scanf("%d", num+i);
            sum += num[i];
        }
        dp[0][0] = true;
        for(int i = 0; i < n; i++)
          for(int j = i+1; j >= 1; j--)
            for(int h = sum; h >= num[i]; h--)
             dp[j][h] |= dp[j-1][h-num[i]]; 

        int m = n / 2;
        int mins = INF, ans;

        for(int h = 0; h <= sum; h++)
            if(dp[m][h]){

            int d = abs(h - sum/2);
            if(mins > d){   
              mins = d;
              ans = h;
            }
           }
        printf("%d %d\n", min(ans, sum-ans), max(ans, sum-ans));
    }

    return 0;
}

你可能感兴趣的:(ZZUOJ-10452 "分"数)