Cup Blue Bridge - found ring (disjoint-set + DFS)

topic:

Here Insert Picture Description

input Output:

Here Insert Picture Description

analysis:

According to a topic can be seen only extra edge, then the only possible one ring, use and check whether the judge set two points have the same ancestor whenever two input points, and if not, will merge the two points, if two points have a common ancestor, indicating that at this time this edge constitutes a ring, then the time can these two points as the start and end of the loop, using DFS search this path, through which the point is on the ring point.

Code:

#include <iostream>
#include <cstring>
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;

const int MAXN = 100005;
int root[MAXN],rnk[MAXN],num[MAXN];
bool vis[MAXN],found;
vector<int> vec[MAXN];
int n,ind;

int Getr(int x)
{
    if(root[x] == x) return x;
    else return root[x] = Getr(root[x]);
}

void Union(int x,int y)
{
    if(rnk[x] > rnk[y])
        root[y] = x;
    else
    {
        root[x] = y;
        if(rnk[x] == rnk[y])
            rnk[y]++;
    }
}

void Dfs(int now,int fn)
{
    if(found) return;
    if(now == fn)
    {
        found = true;
        sort(num+1,num+ind+1);
        for(int i=1;i<ind;++i)
            printf("%d ",num[i]);
        printf("%d\n",num[ind]);
        return;
    }
    for(int i=0;i<vec[now].size();++i)
        if(!vis[vec[now][i]])
        {
            vis[vec[now][i]] = true;
            num[++ind] = vec[now][i];
            Dfs(vec[now][i],fn);
            ind--;
            vis[vec[now][i]] = false;
        }
}

int main()
{
    int x,y,st,fn;
    int fx,fy;
    scanf("%d",&n);
    for(int i=1;i<=n;++i)
        root[i] = i,rnk[i]=0;
    for(int i=1;i<=n;++i)
    {
        scanf("%d%d",&x,&y);
        vec[x].push_back(y);
        vec[y].push_back(x);
        fx = Getr(x);
        fy = Getr(y);
        if(fx != fy)
            Union(fx,fy);
        else
        {
            st = x;
            fn = y;
        }
    }
    vis[st] = true;
    num[++ind] = st;
    Dfs(st,fn);
    return 0;
}

Published 61 original articles · won praise 7 · views 3632

Guess you like

Origin blog.csdn.net/weixin_42469716/article/details/104678951