区间问题选择不相交区间

    科技2025-01-05  17

    区间问题选择不相交区间

    https://blog.csdn.net/qq_40073459/article/details/86636963?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-2.channel_param&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-2.channel_param

    此处存在输入数据没有交换的问题:

    #include<cstdio> #include<algorithm> using namespace std; const int maxn = 110; struct Inteval { int x, y; }I[maxn]; bool cmp(Inteval a, Inteval b) { if (a.x != b.x) return a.x > b.x;//按左端点从大到小排序 else return a.y < b.y;//左端点相同时按右端点从小到大排序 } int main() { int n; while (scanf_s("%d", &n), n != 0) { for (int i = 0; i < n; i++) { scanf_s("%d%d", &I[i].x, &I[i].y); if (I[i].x > I[i].y) {//记得交换输入数据的位置 int temp = I[i].x; I[i].x = I[i].y; I[i].y = temp; } } sort(I, I + n, cmp);//把区间排序 int ans = 1, lastX = I[0].x; for (int i = 1; i < n; i++) { if (I[i].y <= lastX) {//如果该区间右端点在lastX左侧 lastX = I[i].x;//以I[i]作为新选中的区间 ans++;//不相交区间加1 } } printf("%d\n", ans); } return 0; } #include<cstdio> #include<algorithm> using namespace std; const int maxn = 110; struct Inteval { int x, y; }I[maxn]; bool cmp(Inteval a, Inteval b) { if (a.y != b.y) return a.y < b.y;//按右端点从小到大排序 else return a.x > b.x; } int main() { int n; while (scanf("%d", &n), n != 0) { for (int i = 0; i < n; i++) { scanf("%d%d", &I[i].x, &I[i].y); if (I[i].x > I[i].y) {//记得交换输入数据的位置 int temp = I[i].x; I[i].x = I[i].y; I[i].y = temp; } } sort(I, I + n, cmp); int ans = 1, lastY = I[0].y; for (int i = 1; i < n; i++) { if (I[i].x >= lastY) { lastY = I[i].y; ans++; } } printf("%d\n", ans); } return 0; }

    https://blog.csdn.net/liusuangeng/article/details/38519403?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.channel_param&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.channel_param

    Processed: 0.009, SQL: 8