#include <stdio.h> #include <stdlib.h> struct Segment { int left; int right; }; // 比较函数,排序用 int cmp(const void* a, const void* b) { struct Segment* seg1 = (struct Segment*)a; struct Segment* seg2 = (struct Segment*)b; if (seg1->left == seg2->left) { return seg1->right - seg2->right; } return seg1->left - seg2->left; } int main() { int n, m; scanf("%d%d", &n, &m); struct Segment* segments = (struct Segment*)malloc(n * sizeof(struct Segment)); for (int i = 0; i < n; i++) { scanf("%d%d", &(segments[i].left), &(segments[i].right)); } // 按照左端点排序,如果左端点相同,按照右端点从小到大排序 qsort(segments, n, sizeof(struct Segment), cmp); int ans = 0; int curRight = 0; int i = 0; while (i < n && curRight < m) { int maxRight = -1; int maxIndex = -1; while (i < n && segments[i].left <= curRight) { if (segments[i].right > maxRight) { maxRight = segments[i].right; maxIndex = i; } i++; } if (maxIndex == -1) { printf("wrong!\n"); return 0; } curRight = maxRight; ans++; } printf("the answer is %d\n", ans); free(segments); return 0; }修改一下代码使该代码可以多次输入
时间: 2024-03-22 11:37:27 浏览: 48
可以使用一个while循环来实现多次输入,每次输入前先清空上一次输入的segments数组。以下是修改后的代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct Segment {
int left;
int right;
};
// 比较函数,排序用
int cmp(const void* a, const void* b) {
struct Segment* seg1 = (struct Segment*)a;
struct Segment* seg2 = (struct Segment*)b;
if (seg1->left == seg2->left) {
return seg1->right - seg2->right;
}
return seg1->left - seg2->left;
}
int main() {
int n, m;
while (scanf("%d%d", &n, &m) != EOF) {
struct Segment* segments = (struct Segment*)malloc(n * sizeof(struct Segment));
for (int i = 0; i < n; i++) {
scanf("%d%d", &(segments[i].left), &(segments[i].right));
}
// 按照左端点排序,如果左端点相同,按照右端点从小到大排序
qsort(segments, n, sizeof(struct Segment), cmp);
int ans = 0;
int curRight = 0;
int i = 0;
while (i < n && curRight < m) {
int maxRight = -1;
int maxIndex = -1;
while (i < n && segments[i].left <= curRight) {
if (segments[i].right > maxRight) {
maxRight = segments[i].right;
maxIndex = i;
}
i++;
}
if (maxIndex == -1) {
printf("wrong!\n");
return 0;
}
curRight = maxRight;
ans++;
}
printf("the answer is %d\n", ans);
free(segments);
}
return 0;
}
```
阅读全文