1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
| #include<iostream> #include <algorithm> #include<ctime> #define n 6 using namespace std; typedef struct { int id; int d; int w; }tesk;
bool cmpW(tesk t1, tesk t2) { return t1.w>t2.w; } bool cmpD(tesk t1, tesk t2) { return t1.d<t2.d; } void InitNum(tesk t[]) { srand((unsigned)time(NULL)); for (int i = 0; i < n; i++) { t[i].id = i + 1; t[i].d = rand() % n + 1; t[i].w = rand() % 30; } }
void copy(tesk &t1, tesk &t2) { t1.id = t2.id; t1.d = t2.d; t1.w = t2.w; }
int greedy(tesk a[], tesk ta[], int &ans) { int num = 0, i, j; sort(ta, ta + n, cmpW); int fla[9999]; memset(fla, 0, sizeof(fla)); for (i = 0; i<n; i++) { for (j = ta[i].d; j>0; j--) { if (fla[j] == 0) { fla[j] = 1; break; } } if (j>0) { copy(a[num++], ta[i]); ans -= ta[i].w; } } return num; }
int main() { tesk ta[n], a[n], tb[n], b[n]; printf("%s", "正在生成随机数据\n"); InitNum(ta); for (int i = 0; i < n; i++) { copy(tb[i], ta[i]); } printf("%s", "生成的数据为\n"); int max_w = -1, sum_w = 0; for (int i = 0; i < n; i++) { printf("ID: %d,任务的期限: %d,任务的惩罚:%d\n", ta[i].id, ta[i].d, ta[i].w); sum_w += ta[i].w; if (max_w < ta[i].w) { max_w = ta[i].w; } } int k = greedy(a, ta, sum_w); printf("任务惩罚为:%d\n", sum_w); sort(a, a + k, cmpD); printf("将完成执行的任务按照时间递增顺序排列输出:\n"); for (int i = 0; i<k; i++) { printf("ID:%d,期限:%d,惩罚:%d\n", a[i].id, a[i].d, a[i].w); } sort(a, a + k, cmpW); printf("将完成的任务按惩罚排序;\n"); for (int i = 0; i<k; i++) { printf("ID:%d,期限:%d,惩罚:%d\n", a[i].id, a[i].d, a[i].w); }
printf("若将每个wi替换为max{m1,m2...mn}—wi,新的数据为\n"); for (int i = 0; i<n; i++) { tb[i].w = max_w - tb[i].w; printf("ID:%d,期限:%d,惩罚:%d\n", tb[i].id, tb[i].d, tb[i].w); sum_w += tb[i].w; } k = greedy(b, tb, sum_w); printf("任务惩罚为:%d\n", sum_w); sort(b, b + k, cmpD); printf("将完成执行的任务按照时间递增顺序排列输出:\n"); for (int i = 0; i<k; i++) { printf("ID:%d,期限:%d,惩罚:%d\n", b[i].id, b[i].d, b[i].w); } sort(b, b + k, cmpW); printf("将完成的任务按惩罚排序;\n"); for (int i = 0; i<k; i++) { printf("ID:%d,期限:%d,惩罚:%d\n", b[i].id, b[i].d, b[i].w); }
}
|