zoukankan      html  css  js  c++  java
  • Just for funzjfc 并查集操作

    题目描述

    When I boring , I'm crazy...So I design a BT game just for fun...It's easy...

    输入描述

        First line is a interger T <=20 ;
    T case follow ,each case begin with the interger N(N<=100000) , as the max number I will give .
    Then the interger M(M<=10000) ,as the M lines follow:
    One type of format as "A B" is the only instruction I did,it means let A and B in the same set.
    All the interger not less than 0.

    输出描述

        if they are already in the same set puts "nop",else printf the min number in this set.

    样例输入

    1
    10
    5
    1 3
    1 2
    5 4
    5 3
    5 3

    样例输出

    1
    1
    4
    1
    nop
    使用并查集,
    做每次归并操作的时候,取2个集合中的最小根结点作为新集合的根节点,并输出该
    结点的值。同时可以做路径压缩操作。
    代码如下:
    #include<stdio.h>
    int set[100002],n,m,a,b,t;
    void init()
    {
        int i;
        for(i=1;i<=n;i++){
            set[i]=i;
        }
    }
    int find2(int x)
    {
        int r=x,temp;
        while(set[x]!=x)
            x=set[x];
    while(r!=x)
    temp=set[r],set[r]=x,r=temp;
        return x;
    }
    void merge2(int a,int b)
    {
    int ra=find2(a);
    int rb=find2(b);
    if(ra==rb)
    printf("nop\n");
        else if(ra<rb){
            set[rb]=ra;
    printf("%d\n",ra);
    }
        else{
            set[ra]=rb;
    printf("%d\n",rb);}
    }
    int main()
    {
        scanf("%d",&t);
        while(t--){
    scanf("%d",&n);
            init();
    scanf("%d",&m);
            while(m--){
                scanf("%d %d",&a,&b);
                merge2(a,b);
            }   
        }
        return 0;
    }
  • 相关阅读:
    DHCP Option 60 的理解
    程序中的魔鬼数字
    开源GUI-Microwindows之程序入口分析
    http报错之return error code:401 unauthorized
    内存泄漏以及常见的解决方法
    怎样对ListView的项进行排序
    getline函数
    JavaFx初探
    ListBox控件的操作与实现
    SQLite的SQL语法
  • 原文地址:https://www.cnblogs.com/pandy/p/1447647.html
Copyright © 2011-2022 走看看