Codeforces 1283D Christmas Trees(BFS)

题目链接:

Codeforces 1283D Christmas Trees

思路:

直接BFS即可,先将距离圣诞树为1的点都加进队列,在pop距离为1的点时又可以加入距离为2的点…依次操作直到找到m个点;
用map来存储某个点是否被占用、以及离树的最短距离;
不要使用unordered_map,虽然u_map一般情况效率很高,但是遇到一些特殊情况效率反而比map低很多,具体原因参考这篇blog:https://www.cnblogs.com/tldr/p/11364781.html

代码:

#include<bits/stdc++.h>
using namespace std;
typedef pair<int,int> P;
typedef long long ll;
#define fi first
#define sc second
#define pb(a) push_back(a)
#define mp(a,b) make_pair(a,b)
#define pt(a) cerr<<a<<"---
"
#define rp(i,n) for(int i=0;i<n;i++)
#define rpn(i,n) for(int i=1;i<=n;i++)
const int maxn=2e5+5;
int x[maxn];
int main(){
	ios::sync_with_stdio(false); cin.tie(nullptr);
	int n,m; cin>>n>>m;
	map<int,ll> ln;
	rp(i,n){cin>>x[i]; ln[x[i]]=1;}
	queue<int> que;
	rp(i,n){
		if(!ln[x[i]-1]||!ln[x[i]+1]) que.push(x[i]);
	}
	ll ans=0; 
	vector<int> rs;
	while(!que.empty()){
		int now=que.front(); que.pop();
		if(ln[now-1]==0){
			ln[now-1]=ln[now]+1;ans+=ln[now];
			if(ln[now-2]==0) que.push(now-1);
			rs.pb(now-1); --m;
		}
		if(!m) break;
		if(ln[now+1]==0){
			ln[now+1]=ln[now]+1; ans+=ln[now];
			if(ln[now+2]==0) que.push(now+1);
			rs.pb(now+1); --m;
		}
		if(!m) break;
	}
	cout<<ans<<'
';
	for(int& x:rs) cout<<x<<' ';
	return 0;
}
原文地址:https://www.cnblogs.com/yuhan-blog/p/12308711.html