其他分享
首页 > 其他分享> > 多源bfs

多源bfs

作者:互联网

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 ;
}

 

标签:node,int,st,bfs,ans,include,多源,define
来源: https://www.cnblogs.com/nonames/p/12237908.html