ACM_08
来源:互联网 发布:java伪代码怎么写 编辑:程序博客网 时间:2024/06/06 04:03
描述
现在有很多长方形,每一个长方形都有一个编号,这个编号可以重复;还知道这个长方形的宽和长,编号、长、宽都是整数;现在要求按照一下方式排序(默认排序规则都是从小到大);
1.按照编号从小到大排序
2.对于编号相等的长方形,按照长方形的长排序;
3.如果编号和长都相同,按照长方形的宽排序;
4.如果编号、长、宽都相同,就只保留一个长方形用于排序,删除多余的长方形;最后排好序按照指定格式显示所有的长方形;
输入
第一行有一个整数 0 < n <10000,表示接下来有n组测试数据;每一组第一行有一个整数 0 < m < 1000,表示有m个长方形;接下来的m行,每一行有三个数
,第一个数表示长方形的编号,第二个和第三个数值大的表示长,数值小的表示宽,相等说明这是一个正方形(数据约定长宽与编号都小于10000);
输出
顺序输出每组数据的所有符合条件的长方形的”编号 长 宽”。
#include <iostream>#include <algorithm>#include <map>using namespace std;struct Items { int nLength; int nWeight; int nNo; Items() { Init(); } void Init() { nNo = 0; nLength = 0; nWeight = 0; } bool operator==(const Items& temp) { return (nNo == temp.nNo)&&(nLength == temp.nLength) && (nWeight == temp.nWeight); } bool operator<(const Items& temp)const{ if (nNo == temp.nNo) { if (nLength == temp.nLength) return nWeight < temp.nWeight; else return nLength < temp.nLength; } else return nNo < temp.nNo; }};int main(int argc, char** argv) { int nTimes = 0; cin >> nTimes; int nNums = 0; int nNo = 0, nLength = 0, nWeight = 0; std::map<struct Items, int> mapData; std::map<struct Items,int>::iterator iter; while (nTimes--) { cin >> nNums; for (int i = 0; i < nNums; ++i) { cin >> nNo >> nLength >> nWeight; if (nLength < nWeight) { nLength = nLength^nWeight; nWeight = nLength ^ nWeight; nLength = nLength^nWeight; } struct Items stuTemp; stuTemp.nNo = nNo; stuTemp.nLength = nLength; stuTemp.nWeight = nWeight; if (mapData.find(stuTemp) == mapData.end()) { mapData.insert(std::make_pair(stuTemp,nNo)); } } //输出 for (iter = mapData.begin(); iter != mapData.end(); ++iter) { cout << iter->first.nNo <<' '<< iter->first.nLength << ' ' << iter->first.nWeight << std::endl; } mapData.clear(); } return 0;}
标程还重载了输入,更加简洁了。其他set与map都是二叉树查找,区别不大。都是根据less缺省准则,以operator<对元素进行比较,完成排序的。
#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")); }}
我还查看了排名第一的代码,利用字节进行排序,占用内存低。耗时差不多。代码不易读,不太提倡。
#include<iostream>#include<algorithm>using namespace std;typedef long long l;int main(){ l n,m,a,b,c,x,y,t,i; cin>>n; while(n--){ cin>>m; l p[10000]; i=0; while(i<m){ cin>>a>>b>>c; if(b<c)t=b,b=c,c=t; p[i++]=a<<32|b<<16|c; } sort(p,p+m); i=y=0; while(i<m){ x=p[i++]; if(x!=y) y=x,cout<<short(x>>32)<<" "<<short(x>>16)<<" "<<short(x)<<endl; } }}