Description
小明有一台笔记本电脑,一台台式机电脑,两台电脑的性能相同,现在小明手里有N个等待运行的程序,每个程序运行所需的时间分别为n1,n2,n3,n4……,一台电脑同一时刻只能运行一个程序,一个程序只需要运行一次。两台电脑同时开始运行,请问小明该如何分配程序在这两台电脑上运行,使得最后结束运行的电脑的运行时间最短。
Input
输入不超过30组数据,每组数据第一行为N,代表有N个等待运行的程序,第二行为N个数字,代表每个程序的运行时间,1 <= N <= 1000 ,每个程序的运行时间均为正整数, 所有程序的运行时间之和不超过5000。
Output
输出最后结束运行的电脑的运行时间。
Sample Input
2 1 1 2 1 2 3 1 2 3
Sample Output
1 2 3
好吧,这是个背包问题。
OTZ,比赛的时候拿贪心做的,跪了。后来看数据的话,发现贪心实际上也差得不是很多,果然贪心是一个比较好的近似算法呀。
背包的思想就是如何选择一些物品使得最接近平均值,因为两台机器都是平均值肯定是最好的。
想通了之后,代码并不是很长,还是比较好写的。
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxm=5010;
bool dp[maxm];
int n,mid,arr[1010],sum,ans;
int main(){
ios_base::sync_with_stdio(0);
while(cin>>n){
if(n==1){
cin>>ans;
cout<<ans<<endl;
continue;
}
for(int i=0;i<n;++i)
cin>>arr[i],sum+=arr[i];
mid=(sum>>1);
memset(dp,0,sizeof dp);
dp[0]=true;
for(int i=0;i<n;++i)
if(arr[i]<=mid)
for(int j=mid;j>=arr[i];--j)
if(dp[j-arr[i]])
dp[j]=true;
for(int i=mid;i;--i)
if(dp[i])
ans=i,i=1;
cout<<sum-ans<<endl;
sum=0;
}
return 0;
}