>贪心算法

来源:互联网 发布:mysql 查看事件 编辑:程序博客网 时间:2024/04/28 14:53

贪心算法的多机调度问题

//Job Node (greedy)#include <stdio.h>void JobNode( int job[] , int machine[] , int n , int m ){    int i , j , t , flag = 0 , max , min ,k = 1;    for( i = 1 ; i < n ; i++ )          //little to big sort        for( j = i+1 ; j <= n ; j++ )            if( job[i] > job[j] )            {                t = job[i] ;                job[i] = job[j] ;                job[j] = t ;            }    for( i = 1 ; i <= m ; i++ )        machine[i] = 0;    if( m < n )     //machine is not enough need attemper    {        for( i =1 ; i <= m ; i++ )            machine[i] = job[i] ;        for( i = m+1 ; i <= n ; i++ )        {            min = machine[1] ;            for( j = 2 ; j <= m ; j++ )                if( machine[j] < min )      //chose the min time to add the job time                {                    min  = machine[j] ;                    k = j;                }            machine[k] = machine[k] + job[i] ;  //make the job in the number k  machine        }        max = machine[1] ;        for( i = 2 ; i <= m ; i++ )     //when the job finashed,choose the max time,that is all job working time            if( machine[i] > max )                max = machine[i] ;    }       else        //machine is enough    {        for( i = 1 ; i <= n ; i++ )            machine[i] = job[i] ;        max  = job[n] ;     //choose the after sort's job time    }    printf( "the machine's working time is:\n" ) ;    for( i = 1 ; i <= m ; i++ )        printf( "%d ",machine[i] );    printf( "\nthe time is : %d\n",job[n] ) ;}int main(void){    int n , m , i ;    printf( "please input the number of job n and the number of machine m:\n" ) ;    scanf( "%d %d",&n,&m ) ;    int job[n+1] , machine[m+1] ;    printf( "please input job's time\n" ) ;    for(i = 1;i <= n;i++)        scanf( "%d",&job[i] ) ;    JobNode(job,machine,n,m) ;      return 0;}

贪心算法一般需要先进行排序,本题中需要先将每个作业的工作时间进行由小大大排序。

1 0