P1364 医院设置 - bfs

P1364 医院设置

https://www.luogu.com.cn/problem/P1364

题意

  • 一个树形村庄。一个节点内数字代表,村庄的人数。
  • 求把医院放到哪里。大家所走的距离最小

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lsXQsq72-1591145091454)(../图库/1590895408135.png)]

想法

  • BFS + 邻接表
  • 暴力枚举每一个点做为医院的,最小路径
// P1364 医院设置
// Created by majoe on 2020/5/31.
// https://www.luogu.com.cn/problem/P1364

#include <bits/stdc++.h>
using namespace std;
const int N = 2e2 +10;
int n,vis[N];
int ne[N],e[N],h[N],w[N],idx;
void add(int a,int b){ // a到b有边
    e[idx] = b;
    ne[idx] = h[a];
    h[a] = idx++;
}
struct node{
    int num, steps;
};

int bfs(int x){                    //bfs找当前点x为医院设置点时的总距离
    memset(vis,0,sizeof(vis));
    queue<node> q;
    vis[x]=1;
    q.push((node){x,0});
    int sum=0;
    while(!q.empty()){
        node now=q.front();
        q.pop();
        for (int i = h[now.num]; i != -1; i = ne[i]) {
            int t = e[i];
            if(!vis[t]){ // 如果t没被访问过
                sum += w[t] * (now.steps + 1);
                vis[t] = 1;
                q.push((node){t,now.steps+1});
            }
        }
    }
    return sum;
}
int main(){
    cin >> n;
    memset(h,-1,sizeof(h));
    for (int i = 1; i <= n; ++i) {
        int v , a , b;
        cin >> v >> a >> b;
        w[i] = v; //某点的人数
        if(a){
            add(i,a); add(a,i);
        }
        if(b) {
            add(i,b); add(b,i);
        }
    }

    int ans = 1e9;
    for (int i = 1; i <= n ; ++i) {
        ans = min(ans,bfs(i));
    }
    cout << ans;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值