zoukankan      html  css  js  c++  java
  • 洛谷 1196 银河英雄传说

    传送门

    写题一时WA了时间不多了计划还没完成先放下去写道水题好像是正确的选择。

    对每个点记录它到当前代表元的距离,初始都为0(到自己)。

    合并时之前代表元的距离就等于它要合并的那个集合的size。路径压缩时先加上父亲到代表元的距离,再把父亲换成代表元。

    //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
    ");
    	    	else {
    			    printf("%d
    ",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;
    }
    

      

  • 相关阅读:
    jQuery遍历之siblings()
    命名空间
    AnsiString
    《linux内核完全注释》读书笔记 2
    mciSendString
    PeekMessage, GetMessage, PostMessage, SendMessage
    c/c++中运行外部程序或打开文件(转)
    定义基类和派生类
    复制构造函数
    让StringGrid控件显示下拉菜单
  • 原文地址:https://www.cnblogs.com/Achenchen/p/7726111.html
Copyright © 2011-2022 走看看