CCF 回收站選址 201912-2 100分 15ms

點擊前往試題目錄: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_mapunordered_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
*/
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章