并查集求解

银河英雄传说

https://ac.nowcoder.com/acm/problem/16889

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

const int N=30005;
int T;
int fa[N], sz[N], d[N]; // sz维护队列长度, d维护到队首的距离

inline int find(int x){
    if(x!=fa[x]){
        int root=find(fa[x]); // 递归查找根节点
        d[x]+=d[fa[x]];
        fa[x]=root;
    }
    return fa[x];
}

int main(){
    memset(d, 0x00, sizeof d);
    cin>>T;
    for(int i=1; i<N; ++i) {fa[i]=i; sz[i]=1;}
    while(T--){
        char ch;
        int x, y;
        cin>>ch>>x>>y;
        if(ch=='M'){ // 合并舰队
            int fx=find(x);
            int fy=find(y);
            d[fx]=sz[fy];
            sz[fy]+=sz[fx];
            fa[fx]=fy;
        }
        else if(ch=='C'){ // 查询舰队
            int fx=find(x);
            int fy=find(y);
            if(fx!=fy) cout<<-1<<endl;
            else cout<<max(0, abs(d[x]-d[y])-1)<<endl;
        }
    }

    return 0;
}
全部评论

相关推荐

写不来代码的小黑:这么小的城市能有做it的公司也不容易
点赞 评论 收藏
分享
zzzzhz:兄弟你先猛猛投简历至少三百家,能约到面试就去面。最近可以速成智能小车,智慧家居烂大街的项目,不需要自己写,只需要把里面的代码讲解看明白就行。把其中涉及到的八股文都拿出来单独背一下,我去年找工作就一个智能小车智慧家居找了10k差不多。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务