码迷,mamicode.com
首页 > 其他好文 > 详细

多源bfs

时间:2020-01-28 14:09:52      阅读:60      评论:0      收藏:0      [点我收藏+]

标签:scanf   cout   type   tor   eof   define   string   space   解法   

https://codeforces.com/contest/1283/problem/D

题意:在一条无限长的坐标轴上,给你n颗树,m个人。求所有人到树的最短距离的总和和坐标。

解法:多源bfs,map标记。

//#include <bits/stdc++.h>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <iostream>
#include <cstdio>
#include <string>
#include <stdio.h>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <string.h>
#include <vector>
#define ME(x , y) memset(x , y , sizeof(x))
#define SF(n) scanf("%d" , &n)
#define rep(i , n) for(int i = 0 ; i < n ; i ++)
#define INF  0x3f3f3f3f
#define mod 1000000007
#define PI acos(-1)
using namespace std;
typedef long long ll ;
map<int , int>ma;

struct node{
    int x , st ;
    node(int x , int st):x(x),st(st){}
};

int main()
{
    queue<node>q;
    int n , m ;
    scanf("%d%d" , &n , &m);
    for(int i = 0 ; i < n ; i++)
    {
        int x ;
        scanf("%d" , &x);
        q.push(node(x , 0));
        ma[x] = 1;
    }
    int ans = 0 ;
    ll sum = 0 ;
    vector<int>v;
    while(!q.empty())
    {
        node a = q.front();
        q.pop();
        if(ma[a.x + 1] != 1)
        {
            ans++;
            q.push(node(a.x + 1 , a.st+1));
            sum += a.st + 1 ;
            v.push_back(a.x + 1);
            ma[a.x+1] = 1 ;
        }
        if(ans == m) break ;
        if(ma[a.x - 1] != 1)
        {
            ans++;
            q.push(node(a.x - 1 , a.st+1));
            sum += a.st + 1 ;
            v.push_back(a.x - 1);
            ma[a.x-1] = 1 ;
        }
        if(ans == m) break ;
    }
    cout << sum << endl ;
    for(auto i : v)
    {
        cout << i << " " ;
    }
    cout << endl ;




    return 0 ;
}

 

多源bfs

标签:scanf   cout   type   tor   eof   define   string   space   解法   

原文地址:https://www.cnblogs.com/nonames/p/12237908.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!