【动态规划】 流水调度问题

319 阅读1分钟

#include<stdio.h>

typedef struct
{
    int index;//任务的给定序号
    int a;//印刷时间
    int b;//装订时间
}job;

void Johnson(job* m,int n);
void swap(job*a,job*b);
int min(int a,int b){
    return a>b?b:a;
}

int main(){
    job m[7];
    int a[7] = {5,3,6,4,8,9,6};//6项任务依次需要 印刷时间
    int b[7] = {2,4,7,2,9,7,3};//6项任务依次需要 装订时间
    int i = 0;
    printf("ss");
    for(;i<7;i++){//赋值到结构体内
        m[i].index = i;
        m[i].a = a[i];
        m[i].b = b[i];
    }
    
    Johnson(m,7);//对结构体数组进行重新排序 使其符合 johnson 法则
    printf("最优调度为:");
    for(i=0;i<7;i++){
        printf("%d ",m[i].index+1);
    }
    return 0;
}

void Johnson(job* m,int n){
    /*
    * 对 job 中 a<b 数据的 按照 a的非降序排列 放在数组的前面 对 a>=b 的数据 按照 b的非升序排列
    */
    int i=0,j=n-1;
    int p;
    if(n==1) return;
    while(i!=j){//将 a<b的数据全部放在左边
        while(m[j].a>=m[j].b&&i<j){
            j--;
        }
        while(m[i].a<m[i].b&&i<j){
            i++;
        }
        if(i<j){
            swap(m+i,m+j);
        }
    }
    p = i;
    for(i=1;i<=p;i++){//对左边的数据进行插入排序
        job temp = m[i];
        j = i-1;
        while(j >= 0&&temp.a<m[j].a){
            m[j+1] = m[j];
            j--;
        }
        m[j+1] = temp;
    }
    for(i=n-2;i>p;i--){//对右边的数据进行插入排序
        job temp = m[i];
        j = i+1;
        while(j<n&&temp.b<m[j].b){//对于插入排序来说从右向左插入 应该按照非降序排列
            m[j-1]=m[j];
            j++;
        }
        m[j-1] = temp;
    }

}

void swap(job* x,job* y){
    job temp = *x;
    *x = *y;
    *y = temp;
}