修改该代码,使其输出最后一个作业后面无空格:#include <stdio.h> #include <stdlib.h> #define MAX_N 200 typedef struct job { int deadline; int profit; int id; } Job; int cmp(const void *a, const void *b) { return ((Job *)b)->profit - ((Job *)a)->profit; } int main() { int n, i, j, k, max_profit = 0; Job jobs[MAX_N]; int selected[MAX_N] = {0};//已选的任务 scanf("%d", &n); for (i = 0; i < n; i++) { scanf("%d%d", &jobs[i].deadline, &jobs[i].profit); jobs[i].id = i + 1; } qsort(jobs, n, sizeof(Job), cmp);//将效益值从大到小排列 for (i = 0; i < n; i++) { for (j = jobs[i].deadline - 1; j >= 0; j--) { if (!selected[j]) { selected[j] = jobs[i].id; max_profit += jobs[i].profit; break; } } } printf("%d\n", max_profit); for (i = 0; i < n; i++) { if (selected[i]) { printf("%d ", selected[i]); } } printf("\n"); return 0; }
时间: 2024-02-14 10:08:53 浏览: 48
编译原理词法分析程序,按照老师要求编写的
5星 · 资源好评率100%
请将最后一个printf语句修改为如下代码,即可实现输出最后一个作业后面无空格:
```
for (i = 0; i < n; i++) {
if (selected[i]) {
printf("%d", selected[i]);
if (i != n-1) {
printf(" ");
}
}
}
printf("\n");
```
修改后的完整代码如下:
```
#include <stdio.h>
#include <stdlib.h>
#define MAX_N 200
typedef struct job {
int deadline;
int profit;
int id;
} Job;
int cmp(const void *a, const void *b) {
return ((Job *)b)->profit - ((Job *)a)->profit;
}
int main() {
int n, i, j, k, max_profit = 0;
Job jobs[MAX_N];
int selected[MAX_N] = {0};//已选的任务
scanf("%d", &n);
for (i = 0; i < n; i++) {
scanf("%d%d", &jobs[i].deadline, &jobs[i].profit);
jobs[i].id = i + 1;
}
qsort(jobs, n, sizeof(Job), cmp);//将效益值从大到小排列
for (i = 0; i < n; i++) {
for (j = jobs[i].deadline - 1; j >= 0; j--) {
if (!selected[j]) {
selected[j] = jobs[i].id;
max_profit += jobs[i].profit;
break;
}
}
}
printf("%d\n", max_profit);
for (i = 0; i < n; i++) {
if (selected[i]) {
printf("%d", selected[i]);
if (i != n-1) {
printf(" ");
}
}
}
printf("\n");
return 0;
}
```
阅读全文