Codeforces Round #611 (div. 3)D. Christmas Trees

D. Christmas Trees

在这里插入图片描述
在这里插入图片描述
题目大意:

给定一根无限长的坐标轴,在所给位置处有n课圣诞树的坐标,给定m个人,要求我们为他们安排位置,使得他们到圣诞树的位置距离的绝对值之和最小。

思路:
一开始还以为是思维题,想着怎么构造,实在想不出来,搜了一下题解发现竟然是个算法题。。。
宽搜一下,首先读入圣诞树点的坐标,并且打上标记,将它向左向右分别扩展利用bfs宽搜一遍即可。

#include<iostream>
#include<stack>
#include<algorithm>
#include<cstring>
#include<string>
#include<map>
#include<cmath>
#include<queue>
using namespace std;

typedef long long ll;
const int p = 1e9 + 7;
typedef pair<int, int> pii;
const int N = 1e6+10;
map<ll, bool>mp;
queue<pii>q;
vector<int>v;//答案可能很大,用vector存。
ll ans;
int n, m;
void bfs() {
	while (q.size()&&m)
	{
		auto t = q.front();
		q.pop();

		if (mp[t.second] == false) {//如果没有标记过我们就从这开始扩展

			ans += t.first;
			mp[t.second] = true;
			v.push_back(t.second);
			m--;//要满足m个人全部匹配。
			q.push({ t.first + 1, t.second + 1 });//扩展
		    q.push({ t.first + 1, t.second - 1 });

		}

		
	}
}
int main() {
	
	cin >> n >> m;
	for (int i = 1; i <= n; i++) {
		ll x;
		cin >> x;
		mp[x] = true;
		q.push({ 1, x + 1 });
		q.push({ 1, x - 1 });
	}
	bfs();
	cout << ans << endl;
	for (auto p : v) {
		cout << p << ' ';
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值