【题解】CF1283D Christmas Trees

Sol

首先,显然要先放距离为 1 的位置,再放 2 的,以此类推。
因为是最短距离,考虑 bfs。
一开始把圣诞树全部丢到队列里,然后用这些圣诞树来扩展距离为 1 的,再用距离为 1 的去扩展距离为 2 的。
然后开个 map 防止一个位置被多次扩展。
当扩展到的点的个数为 m 时停止扩展。
时间复杂度 O(n+m)

Code

//LYC_music yyds!
#include<bits/stdc++.h>
#define IOS ios::sync_with_stdio(0)
#define lowbit(x) (x&(-x))
#define int long long
using namespace std;
inline char gc()
{
	static char buf[1000000],*p1=buf,*p2=buf;
	return p1==p2&&(p2=(p1=buf)+fread(buf,1,1000000,stdin),p1==p2)?EOF:*p1++;
}
int read()
{
	int pos=1,num=0;
	char ch=getchar();
	while (!isdigit(ch))
	{
		if (ch=='-') pos=-1;
		ch=getchar();
	}
	while (isdigit(ch))
	{
		num=num*10+(int)(ch-'0');
		ch=getchar();
	}
	return pos*num;
}
void write(int x)
{
	if (x<0)
	{
		putchar('-');
		write(-x);
		return;
	}
	if (x>=10) write(x/10);
	putchar(x%10+'0');
}
void writesp(int x)
{
	write(x);
	putchar(' ');
}
void writeln(int x)
{
	write(x);
	putchar('\n');
}
const int N=2e5+10;
int n,m,sum;
const int dx[]={-1,1};
queue<int> q;
map<int,int> dis;
vector<int> ans;
void bfs()
{
	while (ans.size()<m)
	{
		int u=q.front(); q.pop();
		sum+=dis[u];
		if (dis[u]) ans.push_back(u);
		for (int i=0;i<2;i++)
		{
			int xx=u+dx[i];
			if (dis.count(xx)) continue;
			dis[xx]=dis[u]+1; q.push(xx);
		}
	}
}
signed main()
{
	n=read(); m=read();
	for (int i=1;i<=n;i++)
	{
		int x=read();
		q.push(x); dis[x]=0;
	}
	bfs();
	writeln(sum);
	for (auto x:ans)
		writesp(x);
}




posted @   dd_d  阅读(51)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
点击右上角即可分享
微信分享提示
主题色彩