首页 > 代码库 > HDU-2850-Load Balancing(贪心)

HDU-2850-Load Balancing(贪心)

Problem Description
In the Wide Web World, Which web server was popular in web site? Apache, nginx, lighttpd? Baidu.com use Apache, and many web sites like 163.com use nginx. Why? Its configuration is very simple, and it has very powerful load balancing features.

How does load balancing work? Load balancing is a technique to spread work between two or more computers in order to get optimal resource utilization, maximize throughput, and minimize response time. Wiskey very curious about this technology and he wants to build a simple load balancing model.

He define the web site has M servers, and N jobs need be done. Each job has a processing time T; we seek to assign each job to one of the servers so that the loads placed on all servers are as "balanced" as possible. The "balanced" mean the Minimize it (max {TMi} - min {TMj}). TMi is the server i total time cost.

But, as Wiskey Know, this scheduling problem of finding an assignment of minimum gap is NP-hard.

Can you write a better load balancing than Wiskey? Challenge it~!
 

Input
The first integer C represents the number of cases, And C cases followed.

Each test case contains a single integer N (1<=N<=100000) and M (1<=M<=100). The next N line contains integers, meaning the time of job T1, T2Tn. (1<=Ti<=1000000)
 

Output
For each test case, first output the N, and follows N numbers mean the job i assign to which server. The servers number count from 0.
 

Sample Input
2 6 3 2 3 4 6 2 2 6 3 6 4 3 2 2 2
 

Sample Output
6 0 1 2 0 1 2 6 0 1 1 2 2 2


题意:把n个任务分给m个主机,输出每个主机的处理时间的最大值和最小值的差最小的方案。


思路:想多了,原来就一道水题,比赛的时候没敢敲。。。先把任务排下序,每一次都取总时间最小的主机分配剩下的时间最大的任务。


#include <cstdio>
#include <algorithm>
using namespace std;

struct S{
int val,index,ans;
}s[100001];

int sum[101];

bool cmp(struct S a,struct S b)
{
    return a.val<b.val;
}

bool cmpid(struct S a,struct S b)
{
    return a.index<b.index;
}

int main()
{
    int T,n,m,i,j,mn,mi;

    scanf("%d",&T);

    while(T--)
    {
        scanf("%d%d",&n,&m);

        for(i=0;i<n;i++)
        {
            scanf("%d",&s[i].val);
            s[i].index=i;
        }

        sort(s,s+n,cmp);

        for(i=0;i<m;i++) sum[i]=0;

        for(i=n-1;i>=0;i--)
        {
            mn=sum[0];
            mi=0;
            for(j=1;j<m;j++)
            {
                if(sum[j]<mn)
                {
                    mn=sum[j];
                    mi=j;
                }
            }

            s[i].ans=mi;
            sum[mi]+=s[i].val;
        }

        sort(s,s+n,cmpid);

        printf("%d\n",n);

        for(i=0;i<n;i++)
        {
            if(i) printf(" ");
            printf("%d",s[i].ans);
        }
        printf("\n");
    }
}