点击前往试题目录:https://blog.csdn.net/best335/article/details/99550556
题目描述
题目分析
仔细阅读后我们发现,这道题主要考察STL容器的熟练使用以及数据结构基础构造能力。
我们明确以下两部分:
-
回收站定义: 某个点有垃圾 且 其上下左右都有垃圾
-
得分定义: 必须是回收站,得分为该垃圾站左上角,右上角,左下角,右下角的垃圾点个数,故得分可为0,1,2,3,4;否则不计入得分,并且不计入0分。
注意:
- 5号测试点以后的x,y值属于在int范围内的大数量级,故不可使用for循环顺序遍历。
- 10号测试点: |x|,|y|<=109,注意负数的处理。
故我们选用:unordered_map 和 unordered_set 快速遍历求解。
汇总成以下解题代码:
#include<iostream>
#include<unordered_map>
#include<unordered_set>
using namespace std;
int main(){
unordered_map<int,unordered_set<int> > g;//存放所有垃圾的容器 <x,y>
unordered_map<int,unordered_set<int> >::iterator it;//查询垃圾的迭代器
int n,x,y;
//输入
cin>>n;
for(int i=0;i<n;++i){
cin>>x>>y;
//在x坐标插入垃圾容器并记录所有的y
if((it=g.find(x))==g.end()){
unordered_set<int> s;
s.insert(y);
g.insert(pair<int,unordered_set<int> >(x,s));
}
else{
it->second.insert(y);
}
}
int scores[5]{0,0,0,0,0};//得分分别为0,1,2,3,4回收站个数
int top_x,bottom_x,left_x,right_x,left_top_x,right_top_x,left_bottom_x,right_bottom_x;
int top_y,bottom_y,left_y,right_y,left_top_y,right_top_y,left_bottom_y,right_bottom_y;
unordered_map<int,unordered_set<int> >::iterator it_finder;
for(it = g.begin();it!=g.end();++it){//遍历所有的x坐标
x = it->first;
unordered_set<int> s = it->second;
for(unordered_set<int>::iterator its = s.begin();its!=s.end();++its){
y = *its;
//以下部分判断是否为合法的回收站
top_x = x,top_y = y+1;
bottom_x = x,bottom_y = y-1;
if((it_finder = g.find(x))==g.end()) continue;//上下两点至少有一处没有垃圾
if(it_finder->second.find(top_y)==it_finder->second.end()) continue;//上边没有垃圾
if(it_finder->second.find(bottom_y)==it_finder->second.end()) continue;//下边没有垃圾
left_x = x-1,left_y = y;
right_x = x+1,right_y = y;
if((it_finder = g.find(left_x))==g.end()) continue;//左边没有垃圾
if(it_finder->second.find(left_y)==it_finder->second.end()) continue;//左边没有垃圾
if((it_finder = g.find(right_x))==g.end()) continue;//右边没有垃圾
if(it_finder->second.find(right_y)==it_finder->second.end()) continue;//右边没有垃圾
//以下开始计算得分
int score = 0;
left_top_x = x-1,left_top_y = y+1;
left_bottom_x = x-1, left_bottom_y = y-1;
if((it_finder = g.find(left_top_x))!=g.end()){
if(it_finder->second.find(left_top_y)!=it_finder->second.end()) ++score;//左上角有垃圾
if(it_finder->second.find(left_bottom_y)!=it_finder->second.end()) ++score;//左下角有垃圾
}
right_top_x = x+1,right_top_y = y+1;
right_bottom_x = x+1,right_bottom_y = y-1;
if((it_finder = g.find(right_top_x))!=g.end()){
if(it_finder->second.find(right_top_y)!=it_finder->second.end()) ++score;//右上角有垃圾
if(it_finder->second.find(right_bottom_y)!=it_finder->second.end()) ++score;//右下角有垃圾
}
++scores[score];//更新该点得分情况
}
}
for(int i=0;i<5;++i) cout<<scores[i]<<endl;//输出得分情况
return 0;
}
/*
7
1 2
2 1
0 0
1 1
1 0
2 0
0 1
2
0 0
-100000 10
11
9 10
10 10
11 10
12 10
13 10
11 9
11 8
12 9
10 9
10 11
12 11
*/