ZOJ
来源:互联网 发布:ubuntu打开共享文件夹 编辑:程序博客网 时间:2024/06/13 21:37
Farmer John is well known for his great cows. Recently, the cows have decided to participate in the Incredible Cows Puzzle Contest (ICPC).
Farmer John wants to divide the cows into two teams, and he wants to minimize the difference of Puzzle Solving Power of two teams.
Puzzle Solving Power of a team is sum of Puzzle Solving Power of cows forming that team.
Help F.J. to find the minimum difference!
The first line of input consists of a single integer T, the number of test-cases. Each test-case consists of a line containing n (2 <= n <= 34), number of cows. n lines follow. i-th line contains the Puzzle Solving Power of i-th cow. Puzzle Solving Power of a cow is a non-negative number less than 10,000,000. There is a blank line between two consecutive test-cases.
<b< dd="">
For each test-case, output a line containing the minimum difference which can be achieved.
<b< dd="">
2
3
12
6
6
10
123
455
1000
403
234
554
129
454
84
11
<b< dd="">
0
5
直接暴力搜索会超时,所以要进行优化。优化的方法是,将物品分成两堆。首先,记录下第一堆中物品价值累加可能出现的值,之后在对这个数组排序。之后,在对第二堆进行搜索。对于每种状态,在数组中找出一个值使得两个数值相加越接近sum。
#include <iostream>#include <algorithm>#include <cstdio>#include <cmath>#include <cstring>#include <string>#include <string.h>#include <map>#include <set>#include <queue>#include <deque>#include <list>#include <bitset>#include <stack>#include <stdlib.h>#define lowbit(x) (x&-x)#define e exp(1.0)//ios::sync_with_stdio(false);// auto start = clock();// cout << (clock() - start) / (double)CLOCKS_PER_SEC;typedef long long ll;typedef long long LL;using namespace std;const int maxn=1<<18;;int n,m1,m2,sum,half,ans,cnt,a[100],b[100];int vis[maxn];void pre(int now,int s){ if(now==m1) { vis[cnt++]=s; return ; } pre(now+1,s); pre(now+1,a[now]+s);}void dfs(int now,int s){ if(now==m2) { int k=lower_bound(vis,vis+cnt,half-s)-vis; if(k<cnt)ans=min(ans,abs(sum-s-vis[k]-s-vis[k])); return ; } dfs(now+1,s); dfs(now+1,b[now]+s);}int main(){ int T; cin>>T; while(T--) { cin>>n; m1=n/2;m2=n-m1; sum=0; for(int i=0;i<m1;i++)cin>>a[i],sum+=a[i]; for(int i=0;i<m2;i++)cin>>b[i],sum+=b[i]; half=sum/2;cnt=0;ans=sum; pre(0,0); sort(vis,vis+cnt); dfs(0,0); cout<<ans<<endl; } return 0;}
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- uva 11572 Unique Snowflakes (唯一的雪花)
- CSS 字体效果
- Tomcat启动提示(8080等)端口号被占用,(不重启电脑)解决办法
- 乐观锁、悲观锁
- mtk6570/6580/6737有关modem的总结
- ZOJ
- FZU 2229 Calculus Midterm
- Luogu 1169 棋盘制作:计数问题
- JS笔记
- 全局解释器锁(GIL)Cpython
- XListView+ViewPager
- UVa-11987 Almost union-find(带删除操作的并查集)
- 照片墙
- Elastic-Job 基础篇:基本信息及环境搭建