zoukankan      html  css  js  c++  java
  • 并查集(路径更新) LA 3027 Corporative Network

    题目传送门

    题意:训练指南P192

    分析:主要就是一个在路径压缩的过程中,更新点i到根的距离

    #include <bits/stdc++.h>
    using namespace std;
    
    const int N = 2e4 + 5;
    struct DSU	{
    	int rt[N], d[N];
    	void init(void)	{
    		memset (rt, -1, sizeof (rt));
    		memset (d, 0, sizeof (d));
    	}
    	int Find(int x)	{
    		if (rt[x] != -1)	{
    			int root = Find (rt[x]);	//先找到根
    			d[x] += d[rt[x]];			//回溯的过程把距离更新
    			return rt[x] = root;		//路径压缩
    		}
    		else	return x;
    	}
    	void Union(int x, int y)	{
    		if (x == y)	{
    			d[x] = 0;	return ;
    		}
    		else	{
    			rt[x] = y;
    			d[x] = abs (x - y) % 1000;
    		}
    	}
    	bool same(int x, int y)	{
    		return Find (x) == Find (y);
    	}
    }dsu;
    
    int main(void)	{
    	int T;	scanf ("%d", &T);
    	while (T--)	{
    		int n;	scanf ("%d", &n);
    		char str[3];	dsu.init ();
    		int x, y;
    		while (scanf ("%s", str) == 1)	{
    			if (str[0] == 'O')	break;
    			if (str[0] == 'E')	{
    				scanf ("%d", &x);
    				dsu.Find (x);
    				printf ("%d
    ", dsu.d[x]);
    			}
    			else	{
    				scanf ("%d%d", &x, &y);
    				dsu.Union (x, y);			//初始就是到fa的距离
    			}
    		}
    	}
    
    	return 0;
    }
    

      

    编译人生,运行世界!
  • 相关阅读:
    java集合
    struts2的OGNL表达式
    struts2 result type
    struts2在Action中访问WEB资源
    03异或^
    02自加自减运算机制
    原码,补码,反码
    Java基础50题test10—自由落体
    Java基础50题test9—求完数
    Java基础50题test8—输入数字求和
  • 原文地址:https://www.cnblogs.com/Running-Time/p/5027140.html
Copyright © 2011-2022 走看看