一种排序

来源:互联网 发布:无缝丝袜淘宝贴吧 编辑:程序博客网 时间:2024/05/20 13:17

描述
现在有很多长方形,每一个长方形都有一个编号,这个编号可以重复;还知道这个长方形的宽和长,编号、长、宽都是整数;现在要求按照一下方式排序(默认排序规则都是从小到大);

1.按照编号从小到大排序

2.对于编号相等的长方形,按照长方形的长排序;

3.如果编号和长都相同,按照长方形的宽排序;

4.如果编号、长、宽都相同,就只保留一个长方形用于排序,删除多余的长方形;最后排好序按照指定格式显示所有的长方形;
输入
第一行有一个整数 0

#include<bits/stdc++.h>using namespace std;class Orthogon{    public:        int m_serial;        int m_long;        int m_wide;    bool operator < (const Orthogon & A) const    {        if(m_serial == A.m_serial)        {            if(m_long == A.m_long)            {                return m_wide < A.m_wide;            }           return m_long < A.m_long;        }        return m_serial < A.m_serial;    }};Orthogon my_orthogon[1000];set<Orthogon> m_sort[10000];int main(){    int n,m;    cin >> n;    for(int i = 0; i < n; i++)    {        cin >> m;        for(int j = 0 ; j < m; j++)        {            cin >> my_orthogon[j].m_serial;            cin >> my_orthogon[j].m_long;            cin >> my_orthogon[j].m_wide;            if(my_orthogon[j].m_long < my_orthogon[j].m_wide)            {                my_orthogon[j].m_long = my_orthogon[j].m_long + my_orthogon[j].m_wide;                my_orthogon[j].m_wide =  my_orthogon[j].m_long - my_orthogon[j].m_wide;                my_orthogon[j].m_long = my_orthogon[j].m_long - my_orthogon[j].m_wide;            }            m_sort[i].insert(my_orthogon[j]);        }    }    set<Orthogon>::iterator it;    for(int i = 0 ; i < n ; i++)    {        it = m_sort[i].begin();        while(it != m_sort[i].end())        {            cout << (*it).m_serial << " "<< (*it).m_long << " "<< (*it).m_wide << " " << endl;            it++;        }    }}

代码优化:

#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"));    }}
0 0
原创粉丝点击