题目链接: Partition
题意
将一个长度为 的序列 中的每个数字,分到两个序列 和 中,一个数字只能被分到一个序列,要求序列 中所有数字的和减去序列 中所有数字的和的差最大,问最大的差是多少。
输入
第一行为一个整数 ,第二行为 个整数 。
输出
输出序列 中所有数字的和减去序列 中所有数字的和的差的最大值。
样例
输入 |
---|
3 1 -2 0 |
输出 |
3 |
提示 |
我们可以令 于是 。 |
输入 |
---|
6 16 23 16 15 42 8 |
输出 |
120 |
提示 |
令 ,那么 。 |
题解
把所有正数都放到 序列,所有负数都放到 序列,最后的结果等于 序列中所有数字绝对值的和。
过题代码
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cstring>
#include <string>
#include <vector>
#include <list>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <bitset>
#include <algorithm>
#include <functional>
#include <iomanip>
using namespace std;
#define LL long long
const int maxn = 200;
int n, num;
int main() {
#ifdef LOCAL
freopen("test.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
#endif // LOCAL
ios::sync_with_stdio(false);
while(scanf("%d", &n) != EOF) {
int ans = 0;
for(int i = 0; i < n; ++i) {
scanf("%d", &num);
ans += abs(num);
}
printf("%d\n", ans);
}
return 0;
}