一种排序
时间限制:3000 ms | 内存限制:65535 KB
难度:3
描述
现在有很多长方形,每一个长方形都有一个编号,这个编号可以重复;还知道这个长方形的宽和长,编号、长、宽都是整数;现在要求按照一下方式排序(默认排序规则都是从小到大);
1.按照编号从小到大排序
2.对于编号相等的长方形,按照长方形的长排序;
3.如果编号和长都相同,按照长方形的宽排序;
4.如果编号、长、宽都相同,就只保留一个长方形用于排序,删除多余的长方形;最后排好序按照指定格式显示所有的长方形;
输入
第一行有一个整数 0
输出
顺序输出每组数据的所有符合条件的长方形的 编号 长 宽
样例输入
1
8
1 1 1
1 1 1
1 1 2
1 2 1
1 2 2
2 1 1
2 1 2
2 2 1
样例输出
1 1 1
1 2 1
1 2 2
2 1 1
2 2 1
来源
经典题目
上传者
iphxer
题解
sort函数自定义cmp,实现多关键字排序
代码
1 #include<iostream>
2 #include<cstdio>
3 #include<cstdlib>
4 #include<cstring>
5 #include<algorithm>
6 using namespace std;
7
8 const int M=1000;
9 struct node{
10 int h,w,i;
11 }rectan[M];
12
13 bool cmp(struct node x,struct node y)
14 {
15 if(x.i!=y.i)
16 return x.i<y.i;
17 else
18 {
19 if(x.h!=y.h)
20 return x.h<y.h;
21 else
22 return x.w<x.w;
23 }
24 }
25
26 int main()
27 {
28 int n,m;
29 scanf("%d",&n);
30 while(n--)
31 {
32 scanf("%d",&m);
33 for(int j=0;j<m;j++)
34 {
35 int a,b,c;
36 scanf("%d %d %d",&a,&b,&c);
37 rectan[j].i=a;
38 if(b>c)
39 rectan[j].h=b,rectan[j].w=c;
40 else
41 rectan[j].h=c,rectan[j].w=b;
42
43 }
44 sort(rectan,rectan+m,cmp);46 printf("%d %d %d\n",rectan[0].i,rectan[0].h,rectan[0].w);
47 for(int j=1;j<m;j++)
48 {
49 if(!(rectan[j].i==rectan[j-1].i&&rectan[j].h==rectan[j-1].h&&rectan[j].w==rectan[j-1].w))
50 printf("%d %d %d\n",rectan[j].i,rectan[j].h,rectan[j].w);
51 }
52
53 }
54 return 0;
55 }