栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

zoj 3195 Design the city

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

zoj 3195 Design the city

#include <cmath>#include <cstdio>#include <cstring>#include <iostream>#include <vector>#include <algorithm>using namespace std ;#define MAXNODE 50050#define vi vector<int>#define vvi vector< vi >#define imax 1023456789vvi costs ; int heights[ MAXNODE + 10 ] ; int P[ MAXNODE + 10 ] ;int cost[ MAXNODE + 10 ] ;int parent[ MAXNODE + 10 ] ;vvi edges ; int mxHeight = 0 ; int nr ;int getParent( int x , int y ) { while( P[ x ] != P[ y ] ) { if( heights[ x ] > heights[ y ] ) { x = P[ x ] ; } else { y = P[ y ] ; } } while( x != y ) { if( heights[ x ] > heights[ y ] ) { x = parent[ x ] ; } else { y = parent[ y ] ; } } return x ;}void depth( int cur , int height , int curCost ) { heights[ cur ] = height ; cost[ cur ] = curCost ; mxHeight = max( height , mxHeight ) ; for( int i = 0 ; i < edges[ cur ].size() ; i ++ ) { int nxt = edges[ cur ][ i ] ; if( heights[ nxt ] == -1 ) { parent[ nxt ] = cur ; int nxtCost = curCost + costs[ cur ][ i ] ; depth( nxt , height + 1 , nxtCost ) ; } }}void dfs( int cur ) { if( heights[ cur ] < nr ) { P[ cur ] = 0 ; } else if( ( heights[ cur ] % nr == 0 ) ) { P[ cur ] = parent[ cur ] ; } else { P[ cur ] = P[ parent[ cur ] ] ; } for( int i = 0 ; i < edges[ cur ].size() ; i ++ ) { int nxt = edges[ cur ][ i ] ; if( P[ nxt ] != -1 ) continue ; dfs( nxt ) ; }}int solve( int x , int y , int z ) { int ret = imax ; vector<int> v ; v.push_back( x ) ; v.push_back( y ) ; v.push_back( z ) ; sort( v.begin() , v.end() ) ; do { int pa = getParent( v[ 0 ] , v[ 1 ] ) ; int curTot = 0 ; curTot = cost[ v[ 0 ] ] - cost[ pa ] ; curTot += cost[ v[ 1 ] ] - cost[ pa ] ; int pb = getParent( pa , v[ 2 ] ) ; curTot += cost[ pa ] - cost[ pb ] ; curTot += cost[ v[ 2 ] ] - cost[ pb ]; ret = min( ret , curTot ) ; }while( next_permutation( v.begin() , v.end() )); return ret ;}int main() { int N ; int cnt = 0 ; while( cin >> N ) { cnt ++ ; int u , v , c; edges = vvi ( N ) ; costs = vvi ( N ) ; memset( heights , -1 , sizeof( heights ) ) ; memset( P , -1 , sizeof( P ) ) ; mxHeight = 0 ; for( int i = 0 ; i < ( N - 1 ) ; i ++ ) { scanf("%d %d %d",&u,&v,&c) ; edges[ u ].push_back( v ) ; edges[ v ].push_back( u ) ; costs[ u ].push_back( c ) ; costs[ v ].push_back( c ) ; } parent[ 0 ] = 0 ; depth( 0 , 0 , 0 ) ; int lim = sqrt( mxHeight ) ; nr = lim + 1 ; dfs( 0 ) ; int Q ; cin >> Q ; int x , y , z ; if( cnt != 1 ) { cout << "n" ; } for( int i = 0 ; i < Q ; i ++ ) { scanf("%d %d %d",&x,&y,&z) ; int res = solve( x , y , z ) ; cout << res << "n" ; } } return 0 ;}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/368436.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号