一种排序

本文介绍了一种对长方形集合进行排序的方法,首先按照长方形的编号排序,若编号相同则按长度排序,长度也相同则按宽度排序,并且在排序过程中去重。使用C++实现并展示了完整的代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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"));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值