uva1587BOX

给定6个矩形的长和宽wi和hi(1≤wi,hi≤1000),判断它们能否构成长方体的6个面。

思路是首先排序,每个矩形都是x<y,就是短边x,长边y,然后对六个矩形进行二级排序,排序以后构成长方体的条件有两步,第一步,首先是三对相同的长和宽,排序之后是0和1,2和3,4和5,是相同的。

接下来第二步,根据0,2,4,这三对数来看,0.x必然等于2.x,0.y必然等4.x,2.y必然等于4.y;至于为什么,长方体有三种不同的边,我们记为abc,并且记a>b>c,则长方体的六个面必定是ab、ab、ac、ac、bc、bc(按照边的长度排序),符合这种形式的就是一个长方体。下面有两份代码,思路是一样的,实现方式不一样,

先看看我的代码,比较渣

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;

struct boxs
{
    int x, y;
}box[6];

bool cmp(boxs b1,boxs b2)
{
    if (b1.x < b2.x)//一级排序
        return true;
    else             // 二级排序
    {
        if (b1.x == b2.x)
        {
            if (b1.y < b2.y)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }
}
bool check()
{
    if ((!(box[0].x==box[1].x&&box[0].y==box[1].y)) || (!(box[2].x == box[3].x&&box[2].y == box[3].y)) || (!(box[4].x == box[5].x&&box[4].y == box[5].y)))return false;
    if (box[0].x != box[2].x || box[0].y != box[4].x || box[2].y != box[4].y) return false;
    return true;
}
int main()
{
    int a, b;
    while (cin>>a>>b) {
        if (a > b) {
            box[0].x = b;
            box[0].y = a;
        }
        else {
            box[0].x = a;
            box[0].y = b;
        }
        for (int i = 1;i < 6;i++) {
            cin >> a >> b;
            if (a > b) {
                box[i].x = b;
                box[i].y = a;
            }
            else {
                box[i].x = a;
                box[i].y = b;
            }
        }
        sort(box, box + 6, cmp);
        cout << (check() ? "POSSIBLE" : "IMPOSSIBLE" )<< endl;
    }
    return 0;
}

别人的代码

#include <bits/stdc++.h>  
using namespace std;  
  
struct face{  
    int x, y;  
}a[6];  
bool check()  
{  
    if(memcmp(a, a+1, sizeof(face)) || memcmp(a+2, a+3, sizeof(face)) || memcmp(a+4, a+5, sizeof(face))) return false;  
    if(a[0].x!=a[2].x || a[0].y!= a[4].x || a[2].y!=a[4].y) return false;  
    return true;  
}  
int main()  
{  
    while(cin >> a[0].x >> a[0].y >> a[1].x >> a[1].y >> a[2].x >> a[2].y >> a[3].x >> a[3].y >> a[4].x >> a[4].y >> a[5].x >> a[5].y){  
        for(int i = 0; i < 6; ++i)  
            if(a[i].x < a[i].y)  
                swap(a[i].x, a[i].y);  
        sort(a, a+6, [](const face a, const face b) {return a.x==b.x ? (a.y > b.y) : (a.x > b.x);});  
        printf("%s
", check() ? "POSSIBLE" : "IMPOSSIBLE");  
    }  
    return 0;  
}  
原文地址:https://www.cnblogs.com/ArvinShaffer/p/6160489.html