求hack
查看原帖
求hack
571841
ZVitality楼主2023/9/6 13:55

rt,或者帮忙看看哪里出了问题,感谢。

#include<bits/stdc++.h>
using namespace std;

const int _ = 1e5 + 5;

int n , m , q;

struct Edge { int v , w , nxt ; } e[_*2];
int head[_] , ecnt;
void Add( int u , int v , int w = 1 ) { e[ ++ecnt ] = Edge{ v , w , head[ u ] } ; head[ u ] = ecnt ; }

template< int Maxx >
struct DSU {
  int a[ Maxx ] , fa[ Maxx ];
  void Init( int n ) { for( int i = 1 ; i <= n ; i++ ) fa[ i ] = i ; }
  void Union( int x , int y ) { fa[ y ] = x ; }
  int Find( int x ) { return fa[ x ] == x ? x : fa[ x ] = Find( fa[ x ] ) ; }
};

DSU<_> dsu;

struct Node {
  int x , y , w;
  bool operator<( const Node &a ) const { return w < a.w ; }
};

priority_queue< Node > Q;

void Kruskal() {
  dsu.Init( n );
  while( !Q.empty() ) {
    Node p = Q.top();
    Q.pop();
    int X = dsu.Find( p.x ) , Y = dsu.Find( p.y );
    if( X == Y ) continue;
    dsu.Union( X , Y );
    Add( X , Y , p.w );
    Add( Y , X , p.w );
  }
}

int fa[_][ 30 ] , dep[_] , w[_][ 30 ] , lg[_] , vis[_];

void DFS( int x , int father ) {
  fa[ x ][ 0 ] = father;
  w[ x ][ 0 ] = e[ x ].w;
  vis[ x ] = 1;
  dep[ x ] = dep[ father ] + 1;
  for( int i = 1 ; i <= lg[ dep[ x ] ] + 1 ; i++ ) {
    fa[ x ][ i ] = fa[ fa[ x ][ i - 1 ] ][ i - 1 ];
    w[ x ][ i ] = min( w[ x ][ i - 1 ] , w[ fa[ x ][ i - 1 ] ][ i - 1 ] );
  }
  for( int i = head[ x ] ; i ; i = e[ i ].nxt ) {
    if( e[ i ].v != father ) {
      DFS( e[ i ].v , x );
    }
  }
}

int Get( int x , int y ) {
  if( dsu.Find( x ) != dsu.Find( y ) ) return -1;
  int ans = INT_MAX;
  if( dep[ x ] > dep[ y ] ) {
  	swap( x , y );
  }
  while( dep[ x ] < dep[ y ] ) {
  	ans = min( ans , w[ y ][ lg[ dep[ y ] - dep[ x ] ] ] );
  	y = fa[ y ][ lg[ dep[ y ] - dep[ x ] ] ];
  }
  if( x == y ) return ans;
  for( int i = lg[ dep[ x ] ] ; i >= 0 ; i-- ) {
  	if( fa[ x ][ i ] != fa[ x ][ i ] ) {
  	  ans = min( ans , min( w[ x ][ i ] , w[ y ][ i ] ) );
  	  x = fa[ x ][ i ];
  	  y = fa[ y ][ i ];
  	}
  }
  return min( ans , min( w[ x ][ 0 ] , w[ y ][ 0 ] ) );
}

int main() {
  cin >> n >> m;
  for( int i = 1 , x , y , z ; i <= m ; i++ ) {
  	cin >> x >> y >> z;
  	Q.push( Node{ x , y , z } );
  }
  Kruskal();
  for( int i = 2 ; i <= n ; i++ ) lg[ i ] = lg[ i / 2 ] + 1;
  for( int i = 1 ; i <= n ; i++ ) {
    if( !vis[ i ] ) {
      DFS( i , 0 );
    }
  }
  cin >> q;
  while( q-- ) {
  	int x , y;
  	cin >> x >> y;
  	cout << Get( x , y ) << '\n';
  }
  return 0;
}
2023/9/6 13:55
加载中...