Tug of War
A tug of war is to be arranged at the local office picnic. For the tug of war, the picnickers must be divided into two teams. Each person must be on one team or the other; the number of people on the two teams must not differ by more than 1; the total weight of the people on each team should be as nearly equal as possible.
Input
The first line of input contains n the number of people at the picnic. n lines follow. The first line gives the weight of person 1; the second the weight of person 2; and so on. Each weight is an integer between 1 and 450. There are at most 100 people at the picnic.
Output
Your output will be a single line containing 2 numbers: the total weight of the people on one team, and the total weight of the people on the other team. If these numbers differ, give the lesser first.
Sample Input
3
100
90
200
Sample Output
190 200
Source
题目类型:二维01背包
算法分析:每一个人都可以看做是一个物品,然后对于每一个物品,有一个重量的限制(总重量的一半)和一个人数的限制(总人数的一半),可以直接使用二维01背包求解
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
#include <set> #include <bitset> #include <list> #include <map> #include <stack> #include <queue> #include <deque> #include <string> #include <vector> #include <ios> #include <iostream> #include <fstream> #include <sstream> #include <iomanip> #include <algorithm> #include <utility> #include <complex> #include <numeric> #include <functional> #include <cmath> #include <ctime> #include <climits> #include <cstdarg> #include <cstdio> #include <cstdlib> #include <cstring> #include <cctype> #include <cassert> using namespace std; const int INF = 0x7FFFFFFF; const int MOD = 1000000000 + 7; const double EPS = 1e-10; const double PI = 2 * acos (0.0); const int maxn = 1000 + 66; int dp[166][466*100]; int ans[maxn]; int main() { // ifstream cin ("aaa.txt"); int n; while (cin >> n) { memset (dp, 0, sizeof (dp)); int all = 0; for (int i = 0;i < n;i++) { cin >> ans[i]; all += ans[i]; } int num = n, w = all / 2; if (n % 2 == 0) n /= 2; else n = n / 2 + 1; for (int i = 0; i < num; i++) { for (int u = n; u >= 1; u--) { for (int v = w; v >= ans[i]; v--) dp[u][v] = max (dp[u][v], dp[u-1][v-ans[i]] + ans[i]); } } int tempa = dp[n][w], tempb = all - dp[n][w]; if (tempa > tempb) swap (tempa, tempb); cout << tempa << " " << tempb << endl; } return 0; } |
- « 上一篇:poj2570
- poj2585:下一篇 »