You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
# include <bits/stdc++.h>
using namespace std ;
const int N = 30010 ;
int m ;
int p [ N ] , sz [ N ] , d [ N ] ;
int find ( int x ) {
if ( p [ x ] ! = x ) {
int px = find ( p [ x ] ) ;
d [ x ] + = d [ p [ x ] ] ; // 距离
p [ x ] = px ;
}
return p [ x ] ;
}
int main ( ) {
scanf ( " %d " , & m ) ;
for ( int i = 1 ; i < N ; i + + ) p [ i ] = i , sz [ i ] = 1 ;
while ( m - - ) {
char op [ 2 ] ; // 读入一个操作符的办法: 读入一个字符串, 只用op[0]
scanf ( " %s " , op ) ;
int a , b ;
scanf ( " %d %d " , & a , & b ) ;
if ( op [ 0 ] = = ' M ' ) {
int pa = find ( a ) , pb = find ( b ) ;
if ( pa ! = pb ) { // 如果a,b不在同一个集合中, 需要合并集合
d [ pa ] = sz [ pb ] ; // 需要在它家族人数未修改前, 记录下pa前面的船的数量, 否则, 修改完就没机会了
sz [ pb ] + = sz [ pa ] ; // 维护pb家族人员数量
p [ pa ] = pb ; // 将pa加入pb家族
}
} else {
int pa = find ( a ) , pb = find ( b ) ;
if ( pa ! = pb ) // 不在一起
puts ( " -1 " ) ;
else
// 注意: 题目C操作问的是间隔多少条船, 若a != b,
// 则间隔abs(d[a] - d[b]) - 1条船, 若a == b, 则间隔0条船
cout < < max ( 0 , abs ( d [ a ] - d [ b ] ) - 1 ) < < endl ;
}
}
return 0 ;
}