您的位置:首页 > 其它

fzu 2038

2012-03-30 19:58 295 查看
#include<iostream>
#include<vector>
#include<algorithm>
#include<cstdio>
#include<queue>
#include<stack>
#include<string>
#include<map>
#include<set>
#include<cmath>
#include<cassert>
#include<cstring>
#include<iomanip>
using namespace std;

#ifdef _WIN32
#define i64 __int64
#define out64 %I64d
#define in64 "%I64d"
#else
#define i64 long long
#define out64 %lld
#define in64 "%lld"
#endif

#define FOR(i,a,b)      for( int i = (a) ; i <= (b) ; i ++)
#define FF(i,a)         for( int i = 0 ; i < (a) ; i ++)
#define FFD(i,a)        for( int i = (a)-1 ; i >= 0 ; i --)
#define S64(a)          scanf(in64,&a)
#define SS(a)           scanf("%d",&a)
#define LL(a)           ((a)<<1)
#define RR(a)           (((a)<<1)+1)
#define SZ(a)           ((int)a.size())
#define PP(n,m,a)       puts("---");FF(i,n){FF(j,m)cout << a[i][j] << ' ';puts("");}
#define pb              push_back
#define CL(Q)           while(!Q.empty())Q.pop()
#define MM(name,what)   memset(name,what,sizeof(name))
#define read            freopen("in.txt","r",stdin)
#define write           freopen("out.txt","w",stdout)

const int inf = 0x3f3f3f3f;
const i64 inf64 = 0x3f3f3f3f3f3f3f3fLL;
const double oo = 10e9;
const double eps = 10e-10;
const double pi = acos(-1.0);

const int maxn = 100011;

struct zz
{
    int from;
    int to;
    i64 cost;
}zx;

int T;
int n;
int dp[maxn];
int f[maxn];
bool vis[maxn];
vector<zz>g[maxn];

int dfs(int now=0)
{

    int to;
    int temp=0;
    vis[now] = true;
    for(int i=0;i<g[now].size();i++)
    {
        to = g[now][i].to;
        if(!vis[to])
        {
            f[to] = g[now][i].cost;
            temp += dfs(to);
        }
    }
    temp ++;
    dp[now] = temp;
    return temp;
}

i64 dpstart()
{
    MM(dp,0);
    MM(vis,false);
    MM(f,0);
    dfs();
    i64 ans=0;
    i64 now;
    int to;
    for(int i=1;i<n;i++)
    {
        now = dp[i];
        to = n-dp[i];
        ans += 2*now*to*f[i];
    }
    return ans;
}

int main()
{
    cin>>T;
    for(int tt=1;tt<=T;tt++)
    {
        cin>>n;
        FF(i,n) g[i].clear();
        for(int i=1;i<=n-1;i++)
        {
            SS(zx.from);
            SS(zx.to);
            SS(zx.cost);
            g[zx.from].pb(zx);
            swap(zx.from,zx.to);
            g[zx.from].pb(zx);
        }
        cout<<"Case "<<tt<<": ";
        cout<<dpstart()<<endl;
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: