洛谷 1196 银河英雄传说
写题一时WA了时间不多了计划还没完成先放下去写道水题好像是正确的选择。
对每个点记录它到当前代表元的距离,初始都为0(到自己)。
合并时之前代表元的距离就等于它要合并的那个集合的size。路径压缩时先加上父亲到代表元的距离,再把父亲换成代表元。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | //Twenty #include<algorithm> #include<iostream> #include<cstdlib> #include<cstring> #include<cstdio> #include<cmath> #include<ctime> #include<queue> const int maxn=30005; using namespace std; typedef long long LL; int n,fa[maxn],d[maxn],sz[maxn],x,y,u,v,top; char op[5]; void read( int &ret) { int f=1; ret=0; char ch=getchar(); while (ch!= '-' &&(ch< '0' ||ch> '9' )) ch=getchar(); if (ch== '-' ) f=-1,ch=getchar(); for (;ch>= '0' &&ch<= '9' ;ch=getchar()) ret=ret*10+ch- '0' ; ret*=f; } int find( int x) { if (x==fa[x]) { return top=x;} else { find(fa[x]); d[x]+=d[fa[x]]; fa[x]=top; return top; } } void init() { read(n); for ( int i=1;i<maxn;i++) fa[i]=i,sz[i]=1,d[i]=0; for ( int i=1;i<=n;i++) { scanf( "%s" ,op); read(x); read(y); top=0; u=find(x); top=0; v=find(y); if (op[0]== 'C' ) { if (u!=v) printf( "-1\n" ); else { printf( "%d\n" ,abs(d[x]-d[y])-1); } } else { if (u==v) continue ; d[u]=sz[v]; sz[v]+=sz[u]; fa[u]=v; } } } int main() { init(); return 0; } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步