Showing posts with label Disjoint Set. Show all posts
Showing posts with label Disjoint Set. Show all posts

Thursday, March 1, 2018

Feasible relations

--------------------------------------------------------------------------------------------------------
                                                #Python Solution
--------------------------------------------------------------------------------------------------------

import resource
import sys
resource.setrlimit(resource.RLIMIT_STACK, [0x10000000, resource.RLIM_INFINITY])
sys.setrecursionlimit(0x10000001)

def find(i):
    if(subset[i] != i):
        subset[i] = find(subset[i])
    return subset[i]

def UnionSet(x,y):
    xroot = find(x)
    yroot = find(y)
    subset[xroot] = yroot
   
t = int(input())
for _ in range(t):
    n,m = map(int,input().split())
    subset = [0]*(n+1)
    for i in range(n):
        subset[i] = i
   
    ans = 0
    for i in range(m):
        x,op,y = input().split(' ')
        x = int(x) - 1
        y = int(y) - 1
        if op == "=":
            UnionSet(x,y)
        elif find(x) == find(y):
            ans = 1
    print('YES' if not ans else 'NO')
           
 
--------------------------------------------------------------------------------------------------------
                                                # C++ Solution
--------------------------------------------------------------------------------------------------------

#include< bits/stdc++.h >
using namespace std;

struct subset{
    int parent ,rank ;
};

int find(struct subset subsets[],int i){
    if(subsets[i].parent != i) subsets[i].parent = find(subsets,subsets[i].parent);
    return subsets[i].parent;
}

void UnioSet(struct subset subsets[], int x, int y)
{
    int xroot = find(subsets,x);
    int yroot = find(subsets,y);

    if(subsets[xroot].rank < subsets[yroot].rank)subsets[xroot].parent = yroot;
    else if(subsets[xroot].rank > subsets[yroot].rank) subsets[yroot].parent = xroot;
    else{
        subsets[yroot].parent = xroot;
        subsets[xroot].rank++;
    }
}

int main()
{
    int t,n,m;
    cin >> t;
    while(t--){
            int x,y;
            string op ;
        cin >> n >> m;
        struct subset* subsets = (struct subset*) malloc((n+1)* sizeof(struct subset));
        for(int i = 0; i < n ; i++){
            subsets[i].parent = i;
            subsets[i].rank = 0;
        }
        int ans = 0;
        for(int i = 0; i < m; i++){
            cin >> x >>  op >> y;
            if(op == "=")
                UnioSet(subsets,x,y);
            else if(find(subsets,x) == find(subsets,y)) ans = 1;
        }


      cout << ((ans == 1)? "NO\n" : "YES\n");
    }
    return 0;
}