程序設計與算法(三)期末考試之015:編程填空:矩形排序

總時間限制: 

1000ms

 

內存限制: 

1024kB

// 在此處補充你的代碼

描述

給定一系列邊長已知的矩形,輸出對矩形進行兩種排序的結果。

在第一種排序中,先按矩形的面積從大到小排序;若兩個矩形的面積相同,則周長大的排在前。

在第二種排序中,先按矩形的周長從小到大排序;若兩個矩形的周長相同,則面積小的排在前。

 

#include <iostream>
#include <set>
using namespace std;
int main() {
    multiset<Rectangle> m1;
    multiset<Rectangle, Comp> m2;
    int n, a, b;
    cin >> n;
    for (int i = 0; i < n; i++) {
        cin >> a >> b;
        m1.insert(Rectangle(a, b));
        m2.insert(Rectangle(a, b));
    }
    for (multiset<Rectangle>::iterator it = m1.begin(); it != m1.end(); it++) {
        cout << *it << endl;
    }
    cout << endl;
    for (multiset<Rectangle>::iterator it = m2.begin(); it != m2.end(); it++) {
        cout << *it << endl;
    }
	return 0;
}

輸入

第一行是一個整數n,表示輸入的矩形個數。
接下來n行表示了n個矩形。每行有兩個整數a與b,表示該矩形的長與寬。

輸出

先用n行輸出第一種排序的結果。每行兩個整數,依次表示該矩形的面積與周長。
再輸出一個空行。
最後用n行輸出第二種排序的結果。每行兩個整數,依次表示該矩形的面積與周長。

樣例輸入

6
3 8
4 6
10 2
6 6
4 8
3 6

樣例輸出

36 24
32 24
24 22
24 20
20 24
18 18

18 18
24 20
24 22
20 24
32 24
36 24
// 在此處補充你的代碼
class Rectangle
{
public:
    int a,b,area,premiere;
    Rectangle(int c,int d)
    {
        a = c;
        b = d;
        area = a*b;
        premiere = (a+b)*2;
    }
    friend bool operator < (const Rectangle& a1, const Rectangle& a2)
    {
        if(a1.area>a2.area)
            return true;
        else if(a1.area == a2.area)
        {
            if(a1.premiere>a2.premiere)
                return true;
            else
                return false;
        }
        else
            return false;
    }
    friend class Comp;
    friend ostream & operator<<(ostream &o, const Rectangle& a1)
    {
        o << a1.area << " "<<a1.premiere;
        return o;
    }
};
struct Comp{
    bool operator()(const Rectangle& a1, const Rectangle& a2)
    {
        if(a1.premiere<a2.premiere)
            return true;
        else if(a1.premiere == a2.premiere)
        {
            if(a1.area < a2.area)
                return true;
            else
                return false;
        }
        else
            return false;
    }
};
//

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章