标签:des style blog http io ar os sp for
Problem 2178 礼物分配
题目链接: Click Here~
Problem Description
#include <iostream> #include <algorithm> #include <vector> #include <cstdio> #include <cstring> using namespace std; typedef __int64 LL; const int INF = 1 << 30; const int MAXN = 40; vector<int> num[MAXN]; int vi[MAXN],wi[MAXN]; int main() { int n,T; scanf("%d",&T); while(T--) { scanf("%d",&n); for(int i = 0;i < n;++i) { scanf("%d",&vi[i]); } for(int i = 0;i < n;++i) { scanf("%d",&wi[i]); } for(int i = 0;i <= n;++i) num[i].clear(); int n2 = n/2; int cnt,sum1 ,sum2,sum; for(int S = 0;S < 1 << n2; ++S) { cnt = 0,sum1 = 0,sum2 = 0; for(int i = 0;i < n2;++i) { if(S >> i & 1) { sum1 += vi[i]; cnt++; } else { sum2 += wi[i]; } } num[cnt].push_back(sum1 - sum2); } for(int i = 0;i < n2;++i) { sort(num[i].begin(),num[i].end()); num[i].erase(unique(num[i].begin(),num[i].end()),num[i].end()); } int ans = INF; for(int S = 0;S < 1 << (n-n2);++S) { sum,cnt = 0,sum1 = 0,sum2 = 0; for(int i = 0;i < (n-n2);++i) { if(S >> i & 1) { sum1 += vi[i+n2]; cnt++; } else { sum2 += wi[i+n2]; } } int t = n - n2 - cnt; sum = sum1 - sum2; vector<int>::iterator iter; iter = lower_bound(num[t].begin(),num[t].end(),-sum); if(iter != num[t].end() && abs(*iter + sum) < ans) ans = abs(*iter + sum); if(iter != num[t].begin()) { --iter; if(abs(*iter + sum) < ans) ans = abs(*iter + sum); } } printf("%d\n",ans); } return 0; } /* 3 1 2 3 4 2 1 5 1 2 3 5 4 1 1 1 1 5 6 1 2 3 4 5 5 1 1 1 1 1 8 */
标签:des style blog http io ar os sp for
原文地址:http://blog.csdn.net/zhongshijunacm/article/details/41215179