【题解】CF1283D Christmas Trees
Sol
首先,显然要先放距离为
因为是最短距离,考虑 bfs。
一开始把圣诞树全部丢到队列里,然后用这些圣诞树来扩展距离为
然后开个 map 防止一个位置被多次扩展。
当扩展到的点的个数为
时间复杂度
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);
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探