Codeforces 1283D Christmas Trees(BFS)

编程入门 行业动态 更新时间:2024-10-06 23:29:53

<a href=https://www.elefans.com/category/jswz/34/1770097.html style=Codeforces 1283D Christmas Trees(BFS)"/>

Codeforces 1283D Christmas Trees(BFS)

题目链接:

Codeforces 1283D Christmas Trees

思路:

直接BFS即可,先将距离圣诞树为1的点都加进队列,在pop距离为1的点时又可以加入距离为2的点…依次操作直到找到m个点;
用map来存储某个点是否被占用、以及离树的最短距离;
不要使用unordered_map,虽然u_map一般情况效率很高,但是遇到一些特殊情况效率反而比map低很多,具体原因参考这篇blog:.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<<"---\n"
#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<<'\n';for(int& x:rs) cout<<x<<' ';return 0;
}

更多推荐

Codeforces 1283D Christmas Trees(BFS)

本文发布于:2024-02-06 05:34:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1746466.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Codeforces   Christmas   BFS   Trees

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!