BZOJ 2152 聪聪可可

点分治
统计子树模\(3\)各长度个数
拼一拼

\(d\)\((3-d)\)配对是错误的:\(0\)\(0\)配对

#include <iostream>

using namespace std;

const int MAXN=200111;

int N;
long long l;

struct Vert{
	int FE;
	int Size, Val;
	bool Vis;
	int Dis;
} V[MAXN];

struct Edge{
	int x, y, l, next;
} E[MAXN<<1];

int Ecnt=0;

void addE(int a, int b, int c){
	++Ecnt;
	E[Ecnt].x=a;E[Ecnt].y=b;E[Ecnt].l=c;E[Ecnt].next=V[a].FE;V[a].FE=Ecnt;
}

void getSize(int at, int f=0){
	V[at].Size=1;
	for(int k=V[at].FE, to;k>0;k=E[k].next){
		to=E[k].y;
		if(to==f || V[to].Vis)	continue;
		getSize(to, at);
		V[at].Size+=V[to].Size;
	}
}

int AllSize;

void getVal(int at, int f=0){
	V[at].Val=AllSize-V[at].Size;
	for(int k=V[at].FE, to;k>0;k=E[k].next){
		to=E[k].y;
		if(to==f || V[to].Vis)	continue;
		getVal(to, at);
		V[at].Val=max(V[at].Val, V[to].Size);
	}
}

int getG(int at, int f=0){
	int ret=at;
	for(int k=V[at].FE, to;k>0;k=E[k].next){
		to=E[k].y;
		if(to==f || V[to].Vis)	continue;
		to=getG(to, at);
		if(V[ret].Val>V[to].Val)	ret=to;
	}
	return ret;
}

void getDis(int at, int f=0){
	for(int k=V[at].FE, to;k>0;k=E[k].next){
		to=E[k].y;
		if(to==f || V[to].Vis)	continue;
		V[to].Dis=V[at].Dis+E[k].l;
		getDis(to, at);
	}
}

int Tot[3], Now[3];
long long ANS=0LL;

void getCnt(int at, int f=0){
	++Now[V[at].Dis%3];
	for(int k=V[at].FE, to;k>0;k=E[k].next){
		to=E[k].y;
		if(to==f || V[to].Vis)	continue;
		getCnt(to, at);
	}
}

int inv(int a){
	if(a==0)	a=3;
	return (3-a);
}

void Div(int at){
	getSize(at);AllSize=V[at].Size;
	getVal(at);at=getG(at);
	V[at].Vis=true;
	V[at].Dis=0;
	getDis(at);
	Tot[0]=1;Tot[1]=0;Tot[2]=0;
	for(int k=V[at].FE, to;k>0;k=E[k].next){
		to=E[k].y;
		if(V[to].Vis)	continue;
		Now[0]=0;Now[1]=0;Now[2]=0;
		getCnt(to, at);
		for(int d=0;d<3;++d)	ANS+=(long long)(Now[d]*Tot[inv(d)]);
		for(int d=0;d<3;++d)	Tot[d]+=Now[d];
	}
	//cout << at << " " << ANS << endl;
	for(int k=V[at].FE, to;k>0;k=E[k].next){
		to=E[k].y;
		if(V[to].Vis)	continue;
		Div(to);
	}
}

int gcd(int a, int b){
	return (b==0)?a:gcd(b, a%b);
}

int main(){
	ios_base::sync_with_stdio(false);
	
	cin >> N;
	for(int i=1, a, b;i<N;++i){
		cin >> a >> b >> l;l%=3LL;
		addE(a, b, (int)(l));
		addE(b, a, (int)(l));
	}
	
	Div(1);
	
	//cout << ANS << endl;
	ANS=(ANS<<1)+N;
	N*=N;
	int G=gcd(ANS, N);
	ANS/=G;N/=G;
	cout << ANS << "/" << N << endl;
	
	return 0;
}

/*
5
1 2 1
1 3 2
1 4 1
2 5 3

13/25

*/

/*
7
1 2 2
2 3 0
2 4 1
1 5 0
5 6 2
6 7 2

19/49

*/
posted @ 2018-05-10 20:25  Pickupwin  阅读(104)  评论(0编辑  收藏  举报