描述
现在有很多长方形,每一个长方形都有一个编号,这个编号可以重复;还知道这个长方形的宽和长,编号、长、宽都是整数;现在要求按照一下方式排序(默认排序规则都是从小到大);
1.按照编号从小到大排序
2.对于编号相等的长方形,按照长方形的长排序;
3.如果编号和长都相同,按照长方形的宽排序;
4.如果编号、长、宽都相同,就只保留一个长方形用于排序,删除多余的长方形;最后排好序按照指定格式显示所有的长方形;
输入
第一行有一个整数 0<n<10000,表示接下来有n组测试数据;
每一组第一行有一个整数 0<m<1000,表示有m个长方形;
接下来的m行,每一行有三个数 ,第一个数表示长方形的编号,
第二个和第三个数值大的表示长,数值小的表示宽,相等
说明这是一个正方形(数据约定长宽与编号都小于10000);
输出
顺序输出每组数据的所有符合条件的长方形的 编号 长 宽
样例输入
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
分析
- 此题显然是排序题,利用struct类型和qsort()就好了。
- 但是注意当编号,长宽都相同时的特殊情况。
- 但是我们注意到在排序完成后,编号长宽都相同的会出现在相邻位置。这样我们边输出边检查是否重复就好了。
mycode
#include <stdio.h>
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <functional>
#include <stdlib.h>
using namespace std;
typedef struct retangle{
int num;
int len;
int width;
}tang;
int cmp(const void * a, const void * b){
tang *p = (tang *)a;
tang *q = (tang *)b;
if((*p).num >(*q).num){
return 1;
}else if((*p).num < (*q).num){
return -1;
}if((*p).len > (*q).len){
return 1;
}else if((*p).len < (*q).len){
return -1;
}else if((*p).width > (*q).width){
return 1;
}else if((*p).width < (*q).width){
return -1;
}else{
return 0;
}
}
void print(tang * a,int m){
int num = -1;
int len = -1;
int width = -1;
for(int i = 0;i < m; ++i){
if(num==a[i].num&&len==a[i].len&&width==a[i].width){
continue;
}
cout << a[i].num << " " << a[i].len << " " << a[i].width << endl;
num = a[i].num;
len = a[i].len;
width = a[i].width;
}
}
int main() {
//freopen("C:\\Users\\creator\\Desktop\\input.txt","r",stdin);
int n;
cin >> n;
while(n--){
tang group[1000];
int m;
cin >> m;
for(int i = 0; i < m; ++i){
cin >> group[i].num >> group[i].len >> group[i].width;
if(group[i].len < group[i].width){
int c;
c = group[i].width;
group[i].width = group[i].len;
group[i].len = c;
}
}
qsort(group,m,sizeof(group[0]),cmp);
print(group,m);
}
}
优秀代码(人家的代码)
#include<iostream>
#include<set>//人家用了集合类,我需要学习集合类的使用
#include<iterator>//迭代器,我也应该学习
using namespace std;
struct Rect
{
int num,length,width;
};
bool operator<(const Rect& r1,const Rect& r2)//<算符从载,我没有理解为什么只是从载小于号就好了
{
return r1.num<r2.num || r1.num==r2.num && r1.length<r2.length ||r1.num==r2.num&&r1.length==r2.length &&r1.width<r2.width;
}
istream& operator>>(istream& in,Rect& r)//从载
{
in>>r.num;
int a,b;
cin>>a>>b;
r.length=max(a,b);//没有想到,这两个函数在哪个头文件里面
r.width=min(a,b);
return in;
}
ostream& operator<<(ostream& out,const Rect& r)
{
return out<<r.num<<" "<<r.length<<" "<<r.width;
}
int main()
{
int num;
cin>>num;
while(num--)
{
set<Rect> rs;
Rect r;
int n;
cin>>n;
while(n--)
{
cin>>r;
rs.insert(r);//集合类的使用。
}
copy(rs.begin(),rs.end(),ostream_iterator<Rect>(cout,"\n"));//这句话很精简啊。
}
}