hdu Holiday's Accommodation dfs

来源:互联网 发布:手机通讯软件作用 编辑:程序博客网 时间:2024/06/04 18:11
#include <iostream>#include <cstdio>#include <cstring>#include <vector>#define ll long long#pragma comment(linker, "/STACK:1024000000,1024000000") using namespace std;const int maxn=1e5+9;vector < pair<int,int> > e[maxn];int n;int son[maxn];ll ans;void dfs(int t,int from){    for(vector < pair<int,int> > :: iterator k=e[t].begin();k!=e[t].end();k++)    if(k->first!=from)    {        dfs(k->first,t);        son[t]+=son[k->first];        ans+=(ll)min(son[k->first],n-son[k->first])*k->second;    }    son[t]++;}int main(){//    freopen("in.txt","r",stdin);    int T,cas=0;    scanf("%d",&T);    while(T--)    {        scanf("%d",&n);        for(int i=1;i<=n;i++) e[i].clear();        for(int i=1,from,to,w;i<n;i++)        {            scanf("%d%d%d",&from,&to,&w);            e[from].push_back((make_pair(to,w)));            e[to].push_back(make_pair(from,w));        }        memset(son,0,sizeof(son));        ans=0;        dfs(1,-1);        printf("Case #%d: %I64d\n",++cas,ans*2);    }    return 0;}

原创粉丝点击