bzoj2152(树分治)

2152: 聪聪可可

Time Limit: 3 Sec   Memory Limit: 259 MB
Submit: 1284   Solved: 655
[ Submit][ Status][ Discuss]

Description

聪聪和可可是兄弟俩,他们俩经常为了一些琐事打起来,例如家中只剩下最后一根冰棍而两人都想吃、两个人都想玩儿电脑(可是他们家只有一台电脑)……遇到这种问题,一般情况下石头剪刀布就好了,可是他们已经玩儿腻了这种低智商的游戏。他们的爸爸快被他们的争吵烦死了,所以他发明了一个新游戏:由爸爸在纸上画n个“点”,并用n-1条“边”把这n个“点”恰好连通(其实这就是一棵树)。并且每条“边”上都有一个数。接下来由聪聪和可可分别随即选一个点(当然他们选点时是看不到这棵树的),如果两个点之间所有边上数的和加起来恰好是3的倍数,则判聪聪赢,否则可可赢。聪聪非常爱思考问题,在每次游戏后都会仔细研究这棵树,希望知道对于这张图自己的获胜概率是多少。现请你帮忙求出这个值以验证聪聪的答案是否正确。

Input

输入的第1行包含1个正整数n。后面n-1行,每行3个整数x、y、w,表示x号点和y号点之间有一条边,上面的数是w。

Output

以即约分数形式输出这个概率(即“a/b”的形式,其中a和b必须互质。如果概率为1,输出“1/1”)。

Sample Input

5
1 2 1
1 3 2
1 4 1
2 5 3

Sample Output

13/25
【样例说明】
13组点对分别是(1,1) (2,2) (2,3) (2,5) (3,2) (3,3) (3,4) (3,5) (4,3) (4,4) (5,2) (5,3) (5,5)。

【数据规模】

对于100%的数据,n<=20000。


解题思路:

解法同poj 1741 tree.


#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
using namespace std;
int n,opp,ma,root;
long long sug,sum;
int len=0;
struct data
 {
  int to,zhi,next;
 }e[40000];
int h[40000];
int son[40000];
bool vis[40000];
int t[5];


long long gcd(long long a,long long b)
 {
  if (b==0) return a;else
  return gcd(b,a%b);
 }


void insert(int x,int y,int w){++len; e[len].to=y; e[len].zhi=w; e[len].next=h[x]; h[x]=len;}


int getroot(int o,int fa)
 {
  son[o]=1;
  int u=h[o];
  while (u!=0)
  {
  if (vis[e[u].to] && e[u].to!=fa)
  {
  son[o]+=getroot(e[u].to,o);
  }
u=e[u].next;
 }
int zan=max(son[o]-1,opp-son[o]);
if (zan<ma) {ma=zan; root=o;}
return son[o];
 }


void getdeep(int o,int leng,int fa)
 {
  t[leng]++;
  int u=h[o];
  while (u!=0)
  {
  if (vis[e[u].to] && fa!=e[u].to) 
  {
  getdeep(e[u].to,(leng+e[u].zhi)%3,o);
 }
u=e[u].next;
}
 }


int cal(int now,int x0)
 {
  t[0]=0; t[1]=0; t[2]=0;
  getdeep(now,x0%3,0);
  return t[1]*t[2]*2+t[0]*t[0];
 }


void work(int ro)
 {
  sum+=cal(ro,0);
  vis[ro]=false;
  int u=h[ro];
  while (u!=0)
  {
  if (vis[e[u].to])
  {
  sum-=cal(e[u].to,e[u].zhi);
  opp=son[e[u].to];
  ma=0x7fffffff; root=0;
  getroot(e[u].to,0);
  work(root);
}
u=e[u].next;
 }
 }


int main()
 {
  scanf("%d",&n);
  for (int i=1;i<=n-1;++i)
  {
  int x,y,w;
  scanf("%d %d %d",&x,&y,&w);
  insert(x,y,w); insert(y,x,w);
 }
sug=n*n;
sum=0;
memset(vis,true,sizeof(vis));
ma=0x7fffffff; root=0; opp=n;
getroot(1,0);
work(root); long long h1=gcd(sug,sum);
while (h1!=1)
 {
  sug/=h1; sum/=h1;
  h1=gcd(sug,sum);
 }
printf("%lld/%lld",sum,sug);
 }

你可能感兴趣的:(bzoj2152(树分治))