题目链接: Partition
题意
将一个长度为 n n 的序列 中的每个数字,分到两个序列 B B 和 中,一个数字只能被分到一个序列,要求序列 B B 中所有数字的和减去序列 中所有数字的和的差最大,问最大的差是多少。
输入
第一行为一个整数 n (1≤n≤100) n ( 1 ≤ n ≤ 100 ) ,第二行为 n n 个整数 。
输出
输出序列 B B 中所有数字的和减去序列 中所有数字的和的差的最大值。
样例
输入 |
---|
3 1 -2 0 |
输出 |
3 |
提示 |
我们可以令 B={1,0},C={−2} B = { 1 , 0 } , C = { − 2 } 于是 sumB=1,sumC=−2,sumB−sumC=3 s u m B = 1 , s u m C = − 2 , s u m B − s u m C = 3 。 |
输入 |
---|
6 16 23 16 15 42 8 |
输出 |
120 |
提示 |
令 B={16,23,16,15,42,8},C={} B = { 16 , 23 , 16 , 15 , 42 , 8 } , C = { } ,那么 sumB=120,sumC=0,B−C=120 s u m B = 120 , s u m C = 0 , B − C = 120 。 |
题解
把所有正数都放到 B B 序列,所有负数都放到 序列,最后的结果等于 A A <script type="math/tex" id="MathJax-Element-46">A</script> 序列中所有数字绝对值的和。
过题代码
#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;
}