本文主要是介绍【BZOJ】2152: 聪聪可可 点分治,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
传送门:【BZOJ】2152: 聪聪可可
题目分析:记录权值和%3的路径的个数。。。然后去重。。没了。。
代码如下:
#include <vector>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std ;typedef long long LL ;#define rep( i , a , b ) for ( int i = ( a ) ; i < ( b ) ; ++ i )
#define For( i , a , b ) for ( int i = ( a ) ; i <= ( b ) ; ++ i )
#define rev( i , a , b ) for ( int i = ( a ) ; i >= ( b ) ; -- i )
#define clr( a , x ) memset ( a , x , sizeof a )const int MAXN = 100005 ;
const int MAXE = 200005 ;struct Edge {int v , c , n ;Edge () {}Edge ( int v , int c , int n ) : v ( v ) , c ( c ) , n ( n ) {}
} ;Edge E[MAXE] ;
int H[MAXN] , cntE ;
int dis[MAXN] ;
int vis[MAXN] , Time ;
int pre[MAXN] ;
int siz[MAXN] ;
int dp[MAXN] ;
int d[3] ;
int Q[MAXN] , head , tail ;
int ans ;
int n ;void clear () {cntE = 0 ;clr ( H , -1 ) ;Time ++ ;ans = 0 ;
}void addedge ( int u , int v , int c ) {E[cntE] = Edge ( v , c , H[u] ) ;H[u] = cntE ++ ;
}int gcd ( int a , int b ) {return b ? gcd ( b , a % b ) : a ;
}int get_root ( int s ) {head = tail = 0 ;Q[tail ++] = s ;pre[s] = 0 ;while ( head != tail ) {int u = Q[head ++] ;for ( int i = H[u] ; ~i ; i = E[i].n ) {int v = E[i].v ;if ( v != pre[u] && vis[v] != Time ) {pre[v] = u ;Q[tail ++] = v ;}}}int tot_size = tail ;int root = s , max_size = tail ;while ( tail ) {int u = Q[-- tail] ;siz[u] = 1 ;int cnt = 0 ;for ( int i = H[u] ; ~i ; i = E[i].n ) {int v = E[i].v ;if ( v != pre[u] && vis[v] != Time ) {siz[u] += siz[v] ;cnt = max ( cnt , siz[v] ) ;}}cnt = max ( cnt , tot_size - siz[u] ) ;if ( cnt < max_size ) {max_size = cnt ;root = u ;}}return root ;
}int get_ans ( int s , int init_dis ) {head = tail = 0 ;Q[tail ++] = s ;pre[s] = 0 ;dis[s] = init_dis % 3 ;d[0] = d[1] = d[2] = 0 ;while ( head != tail ) {int u = Q[head ++] ;d[dis[u]] ++ ;for ( int i = H[u] ; ~i ; i = E[i].n ) {int v = E[i].v ;if ( v != pre[u] && vis[v] != Time ) {pre[v] = u ;Q[tail ++] = v ;dis[v] = ( dis[u] + E[i].c ) % 3 ;}}}return d[1] * d[2] * 2 + d[0] * d[0] ;
}void divide ( int u ) {int root = get_root ( u ) ;vis[root] = Time ;ans += get_ans ( root , 0 ) ;for ( int i = H[root] ; ~i ; i = E[i].n ) {int v = E[i].v ;if ( vis[v] != Time ) {ans -= get_ans ( v , E[i].c ) ;divide ( v ) ;}}vis[root] = 0 ;
}void scanf ( int& x , char c = 0 ) {while ( ( c = getchar () ) < '0' || c > '9' ) ;x = c - '0' ;while ( ( c = getchar () ) >= '0' && c <= '9' ) x = x * 10 + c - '0' ;
}void solve () {int u , v , c ;clear () ;rep ( i , 1 , n ) {scanf ( u ) ;scanf ( v ) ;scanf ( c ) ;addedge ( u , v , c % 3 ) ;addedge ( v , u , c % 3 ) ;}divide ( 1 ) ;//printf ( "%lld %lld\n" , ans , ( LL ) n * n ) ;int __gcd = gcd ( n * n , ans ) ;printf ( "%d/%d\n" , ans / __gcd , n * n / __gcd ) ;
}int main () {clr ( vis , 0 ) ;Time = 0 ;while ( ~scanf ( "%d" , &n ) ) solve () ;return 0 ;
}
这篇关于【BZOJ】2152: 聪聪可可 点分治的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!