[csp ccf]201912-2回收站选址

解题思路:

        本题题目看似清爽,实则脑袋疼,因为题目要求的是坐标图含有负坐标,普通的二维数组只包括第一象限,因此我们得寻找其他的解题思路。

        我的想法是,定义一个结构体,包括x和y,然后用map容器存储。

        值得注意的是,如果用map来解题,本题是一个极佳的训练map容器使用的题目,(让我对map有了更进一步的理解)

        1.用map存储结构体,需要运算符重载,以完成排序,由于结构体包括x和y,因此先判断x,再判断y即可。

        2.map的find函数返回值是迭代器,因此判断find存不存在需使用 != _map.end(). ,其中.end()表示尾后,即最后一个元素的后面,若迭代到此,说明find未找到。

代码如下:

        

#include <cstdio>
#include <map>
using namespace std;
struct node{//存储节点
    int x;
    int y;
    bool operator < (const node& other) const{
        if(x > other.x){
            return true;
        }else if(x == other.x){
            return y > other.y;
        }else{
            return false;
        }
    }
};
int main(){
    int n ;
    scanf("%d",&n);//读取n
    map<node,int> myMap; //存储坐标
    int score[5] = {0}; //存储分数
    for(int i = 0 ; i < n ; i++){//读取每个坐标
        node temp;//当前节点
        scanf("%d%d",&temp.x,&temp.y);
        myMap.insert(map<node,int>::value_type(temp,1));//插入map
    }
    map<node,int>::iterator it = myMap.begin(); //遍历myMap

    for(it; it != myMap.end(); it++){//对每个节点判断是否上下左右有垃圾
        int x = it->first.x;
        int y = it->first.y; //取出xy
        node up,down,left,right; //生成左右节点
        up.x = x;
        up.y = y+1;
        down.x = x;
        down.y = y-1;
        left.x = x-1;
        left.y = y;
        right.x =x+1;
        right.y = y; //完成这些节点的初始化,进行判断
        if(myMap.find(up) != myMap.end() &&
        myMap.find(down) != myMap.end() &&
        myMap.find(left) != myMap.end()
        &&myMap.find(right) != myMap.end()){ //若四周存在垃圾,进行计算分数
            int mark = 0;
            node upLeft,upRight,downLeft,downRight;
            upLeft.x = x - 1;
            upLeft.y = y + 1;
            upRight.x = x + 1;
            upRight.y = y + 1;
            downLeft.x = x - 1;
            downLeft.y = y - 1;
            downRight.x = x + 1;
            downRight.y = y - 1;
            if(myMap.find(upLeft) != myMap.end()){
                mark++;
            }
            if(myMap.find(upRight) != myMap.end()){
                mark++;
            }
            if(myMap.find(downLeft) != myMap.end()){
                mark++;
            }
            if(myMap.find(downRight) != myMap.end()){
                mark++;
            }//计算分数
            score[mark]++;//记录到数组中
        }
    }
    //判断完毕,进行输出
    for(int i = 0 ; i < 5 ; i++){
        printf("%d\n",score[i]);
    }
}

  • 9
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值