现在有 n 条线段,线段的左端坐标为 L ,右端坐标为 R(保证 L<R)。需要对这些线段排
序,具体要求如下:
l
在左端坐标不一样的时候,按照左端坐标从小到大排序;
l
在左端坐标相等的时候,按照右端坐标从小到大排序。
输入要求:
输入共 n+1 行;
第一行为一个整数 n (1≤n≤1000),表示一共有 n 条需要排序的线段;
接下来 n 行,每行两个整数 L,R (0≤L,R≤100),表示每条线段的左端和右端坐标。
需要注意的是,可能会出现一模一样的线段,请将他们全部输出。
输出要求:
一共输出 n 行,为 n 条线段从小到大排序之后的结果;
每一行两个整数,为每条线段的左端和右端坐标,以一个空格分隔。
输入样例:
3
2 3
1 4
1 2
输出样例:
1 2
1 4
2 3
#include<iostream>
#include<algorithm>
using namespace std;
struct P
{
int left;
int right;
};
bool cmp(P& p1, P& p2)
{
if (p1.left == p2.left)
{
return p1.right < p2.right;
}
return p1.left < p2.left;
}
int main()
{
int n;
cin >> n;
P* arr = new P[n];
for (int i = 0; i < n; i++)
{
int a, b;
cin >> a >> b;
arr[i] = { a,b };
}
//sort(arr, arr + n, cmp);
//冒泡排序
bool adjust = true; //标识符,如果一次循环没有做交换则说明数据有序
for (int i = 0; i < n-1&&adjust; i++)
{
adjust = false;
for (int j = i + 1; j < n; j++)
{
//arr[j-1]比arr[j]相比,cmp返回false时交换
if (!cmp(arr[j-1], arr[j]))
{
P temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
adjust = true; //做交换后更改标识
}
}
}
for (int i = 0; i < n; i++)
{
cout << arr[i].left << ' ' << arr[i].right << endl;
}
}
#include<bits/stdc++.h>
using namespace std;
struct Line{
int l,r;//左端点和右端点
bool operator<(const Line&a) const{//重载<,就是重定义Line类型变量比较大小的方法
if(l<a.l)return 1;//左端点<另一个的左端点,返回小于
if(l>a.l)return 0;//左端点>另一个的左端点,返回不小于
//此时l=a.l
if(r<a.r)return 1; //右端点<另一个的右端点,返回小于
return 0;//此时右端点>另一个的右端点,返回大于
}
};
Line a[1009];
int main() {
int n;
cin>>n;
for(int i=1;i<=n;i++)cin>>a[i].l>>a[i].r;
sort(a+1,a+1+n);
for(int i=1;i<=n;i++)cout<<a[i].l<<" "<<a[i].r<<endl;
return 0;
}
算法的长河永无止境,继续加油!
望采纳,谢谢