修改代码 #include <stdio.h> #include <stdlib.h> typedef struct Event { int begin; int end; } Event; int cmp(const void *a, const void *b) { Event *e1 = (Event *)a; Event *e2 = (Event *)b; return e1->end - e2->end; } int main() { int n; scanf("%d", &n); Event *events = (Event *)malloc(n * sizeof(Event)); for (int i = 0; i < n; i++) { scanf("%d %d", &events[i].begin, &events[i].end); } qsort(events, n, sizeof(Event), cmp); int max_len = 0; int last_end = 0; int *seq = (int *)malloc(n * sizeof(int)); int seq_len = 0; for (int i = 0; i < n; i++) { if (events[i].begin >= last_end) { seq[seq_len++] = i; last_end = events[i].end; if (seq_len > max_len) { max_len = seq_len; } } } printf("{"); for (int i = 0; i < max_len; i++) { printf("%d", events[seq[i]].begin); if (i < max_len - 1) { printf(","); } } printf("}\n"); free(events); free(seq); return 0; }使输出为采用线段所在位置
时间: 2024-03-22 22:42:59 浏览: 61
SeqList.h #include <stdio.h> //包含标准输入输出流的头文件 #include <assert.h
可以在主函数中对最长不相交子序列的位置进行记录,然后在输出时输出对应位置的线段所在位置即可。修改后的代码如下:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct Event {
int begin;
int end;
} Event;
int cmp(const void *a, const void *b) {
Event *e1 = (Event *)a;
Event *e2 = (Event *)b;
return e1->end - e2->end;
}
int main() {
int n;
scanf("%d", &n);
Event *events = (Event *)malloc(n * sizeof(Event));
for (int i = 0; i < n; i++) {
scanf("%d %d", &events[i].begin, &events[i].end);
}
qsort(events, n, sizeof(Event), cmp);
int max_len = 0;
int last_end = 0;
int *seq = (int *)malloc(n * sizeof(int));
int seq_len = 0;
int *positions = (int *)malloc(n * sizeof(int)); // 记录线段所在位置
int pos_len = 0;
for (int i = 0; i < n; i++) {
if (events[i].begin >= last_end) {
seq[seq_len++] = i;
positions[pos_len++] = events[i].begin; // 记录线段所在位置
last_end = events[i].end;
if (seq_len > max_len) {
max_len = seq_len;
}
}
}
printf("{");
for (int i = 0; i < max_len; i++) {
printf("%d", positions[seq[i]]); // 输出对应位置的线段所在位置
if (i < max_len - 1) {
printf(",");
}
}
printf("}\n");
free(events);
free(seq);
free(positions); // 释放内存
return 0;
}
```
阅读全文