标签:
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3115 Accepted Submission(s): 737
#include <iostream> #include <algorithm> #include <cstdio> #include <cmath> #include <cstring> #include <vector> using namespace std ; typedef long long LL ; const double inf = 1e9+7; const int N = 1010; const int M = 40010; struct edge { int u , v ; LL w; }e[M]; int n , m , ans2 ; int pre[N] , id[N] , vis[N] ; LL in[N] ; LL zhuliu( int root , int n , int m ) { LL res = 0 ; int u , v ; while(1) { for( int i = 0 ; i < n ; ++i ) in[i] = inf ; for( int i = 0 ; i < m ; ++i ) if( e[i].u != e[i].v && e[i].w < in[e[i].v] ) { pre[e[i].v] = e[i].u; if( e[i].u == root ) ans2 = i ; in[e[i].v] = e[i].w; } for( int i = 0 ; i < n ; ++i ) if( i != root && in[i] == inf ) return -1 ; int tn = 0 ; memset( id , -1 , sizeof id ); memset( vis , -1 , sizeof vis ); in[root] = 0 ; for( int i = 0 ; i < n ; ++i ) { res += in[i]; v = i ; while( vis[v] != i && id[v] == -1 && v != root ) { vis[v] = i ; v = pre[v] ; } if( v != root && id[v] == -1 ) { for( int u = pre[v] ; u != v ; u = pre[u] ) id[u] = tn ; id[v] = tn++ ; } } if( tn == 0 ) break ; // no circle for( int i = 0 ; i < n ; ++i ) if( id[i] == -1 ) { id[i] = tn++ ; } for( int i = 0 ; i < m ; ++i ){ v = e[i].v; e[i].u = id[e[i].u]; e[i].v = id[e[i].v]; if( e[i].u != e[i].v ) e[i].w -= in[v]; } n = tn ; root = id[root]; } return res ; } int main () { // freopen("in.txt","r",stdin); int _ , cas = 1 ; while( ~scanf("%d%d",&n,&m) ) { LL sum = 1 ; for( int i = 0 ; i < m ; ++i ) { scanf("%d%d%I64d",&e[i].u,&e[i].v,&e[i].w); sum += e[i].w; } int L = m ; for( int i = 0 ; i < n ; ++i ) { e[L].u = n , e[L].v = i , e[L++].w = sum ; } LL ans = zhuliu( n , n + 1 , L ); if( ans == -1 || ans >= 2 * sum ) puts("impossible"); else { ans -= sum ; printf("%I64d %d\n",ans,ans2 - m); } puts(""); } }
HDU 2121 Ice_cream’s world II(无定根最小树形图)
标签:
原文地址:http://www.cnblogs.com/hlmark/p/4292829.html