UVa1587--Box--盒子(代码超简洁)

题目链接https://vjudge.net/problem/UVA-1587

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


这道题不能想的太简单了,但是也不要想得太复杂。之前自己写的太复杂了,后来在网上看了一个答案,感觉写的非常好。

1、不要写成死循环。要能退出。

2、sort函数和swap函数都需要头文件支持

#include<algorithm>
using namespace std;

swap(box[i].first,box[i].second);//可以交换各类型数据,字符串等

sort(box,box+6);//对数组、结构体等进行排序

3、swap函数

直接交换数字:

int a=2,b=3;
swap(a,b);
printf("%d %d\n",a,b);

交换字符串:

char *a="hello",*b="world";
swap(a,b);
printf("%s %s\n",a,b);

关于自定义swap函数:更多自定义swap点击这里http://blog.chinaunix.net/uid-20769502-id-3436523.html

#include<stdio.h>
myswap(int *a,int *b){    //注意②
    int c;    //注意③
    c=*a;
    *a=*b;
    *b=c;
}
int main(){
    int a,b;
    scanf("%d%d",&a,&b);
    myswap(&a,&b);    //注意①
    printf("%d %d",a,b);
}


4、sort函数

去重排序:

sort(box,box+6);
new_len=sort(box,box+6)-box;

自定义排序规则:

typedef struct {
    int x;
    int y;
}mybox;
int cmp(mybox a,mybox b){
    if(a.x!=b.x) return a.x<b.x;
    else return a.y<b.y;
}
sort(box,box+6,cmp);

下面是这一题的代码:

#include<stdio.h>
#include<algorithm>
using namespace std;
pair <int,int> box[6];//注意书写方式
int i;
int main(){
    while(1){
        for(i=0;i<6;i++){
            if(scanf("%d%d",&box[i].first,&box[i].second)!=2) return 0;
            if(box[i].first>box[i].second)
                swap(box[i].first,box[i].second);
        }
        sort(box,box+6);//我试了一下,此处排序是按照先first递增,其次second递增排序
        puts(box[0].first==box[1].first&&box[1].first==box[2].first&&box[2].first==box[3].first&&
             box[0].second==box[1].second&&box[1].second==box[4].first&&box[4].first==box[5].first&&
             box[2].second==box[3].second&&box[3].second==box[4].second&&box[4].second==box[5].second?
             "POSSIBLE":"IMPOSSIBLE");
    }
}


  • 6
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值