区间问题选择不相交区间
https://blog.youkuaiyun.com/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.youkuaiyun.com/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
博客内容涉及两种不同的不相交区间选择算法的C++实现。第一种按左端点从大到小排序,然后根据右端点更新不相交区间计数;第二种则按右端点从小到大排序,同样更新不相交区间计数。两种方法都通过交换确保输入区间正确排序,并使用`sort`函数进行区间排序。
1156

被折叠的 条评论
为什么被折叠?



