p1364医院设置题解

· · 题解

既然关乎全村人民

那我得认真一点

很容易我们能发现,我们只要把所有节点都看一遍,找路程最短的那个即可。

既然如此,话不多说,上代码

#include<bits/stdc++.h>
using namespace std;
int n,ans=1000000000,vis[110];//好大的ans啊,这可是要比所以路程都大呢
struct node{
    int l,r,fa,val;//左子结点,右子节点,父结点(老爹),权值
}t[110];
int tree(int x,int d){
    if(!x||vis[x])//x==0或vis[x]==1
        return 0;
    vis[x]=1;//已经遍历过了
    return tree(t[x].l,d+1)+tree(t[x].r,d+1)+tree(t[x].fa,d+1)+t[x].val*d;
 /* d:已经多深了;
   tree(t[x].l,d+1):左子树再深一层;
   tree(t[x].r,d+1):右子树再深一层;
   tree(t[x].fa,d+1):老爹再深一层;
   t[x].val*d:都我的地盘了直接清算,看看走了几段*/
}
int main(){
    cin>>n;
    for(int i=1;i<=n;i++)
        cin>>t[i].val>>t[i].l>>t[i].r;
    for(int i=1;i<=n;i++){
        t[t[i].l].fa=i;//你的左儿子叫你爸爸
        t[t[i].r].fa=i;//你的右儿子叫你爸爸
    }
    for(int i=1;i<=n;i++){
        memset(vis,0,sizeof(vis));//重新清算
        ans=min(ans,tree(i,0));//我懒,要最短的那个
    }
    cout<<ans;//通知全村人民
    return 0;
}

小学生的第一篇题解求过QwQ