[51NOD1007] 正整数分组(DP,记忆化搜索)

时间:2024-12-17 18:07:33

题目链接:http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1007

dp(id, s)表示第id个数之前,其中一个集合和为s的差,按照取和不取dfs就行。

 #include <bits/stdc++.h>
using namespace std; const int maxn = ;
const int maxm = ;
const int inf = ;
int n;
int a[maxn], sum;
int dp[maxn][maxm]; int dfs(int id, int s) {
if(id == n+) return abs(s-(sum-s));
if(~dp[id][s]) return dp[id][s];
return dp[id][s] = min(dfs(id+, s), dfs(id+, s+a[id]));
} int main() {
// freopen("in", "r", stdin);
while(~scanf("%d", &n)) {
memset(dp, -, sizeof(dp));
sum = ;
for(int i = ; i <= n; i++) {
scanf("%d", &a[i]);
sum += a[i];
}
printf("%d\n", dfs(, ));
}
return ;
}