把n个数分成k份,使其尽量平均
2012-09-03 15:03:17 来源:WEB开发网 #include<stdio.h>
#include<vector>
#include<algorithm>
#include<iostream>
using namespace std;
typedef vector<int> IntVector;
typedef vector<IntVector> IntMat;
void DeuceNumber(const IntVector &SourceVecNum,
const int nShare,
IntMat &OutVecVecNum)
{
IntVector copySourceNum = SourceVecNum;
sort(copySourceNum.begin(), copySourceNum.end(), greater<int>());
IntVector sum(nShare);
OutVecVecNum.resize(nShare);
int len=copySourceNum.size();
for (int i = 0; i < len ; i++)
{
const int nMinSumPos = min_element(sum.begin(), sum.end()) - sum.begin();
OutVecVecNum[nMinSumPos].push_back(copySourceNum[i]);
sum[nMinSumPos] += copySourceNum[i];
}
}
int main(){
int a[]={8,26,10,19,10,24,11,18,11,21,12,12,17,13,16,14,15,12,16};
int n=3;
IntVector v;
IntMat v2;
v.insert(v.begin(),a,a+18);
DeuceNumber(v,n,v2);
IntVector::iterator it;
IntMat::iterator iit;
iit=v2.begin();
int sum,total=0;
while(iit!=v2.end()){
it=iit->begin();
sum=0;
while(it!=iit->end()){
printf("%d ",*it);
sum+=*it;
it++;
}
total+=sum;
printf(" sum=%d\n",sum);
iit++;
}
printf("%d",total);
return 0;
}
更多精彩
赞助商链接