Showing posts with label connected component. Show all posts
Showing posts with label connected component. Show all posts

Thursday, March 1, 2018

Monk and Graph Problem

# Python Solution
 
import resource
import sys
sys.setrecursionlimit(0x100000)
#if you don't write this line you got runtime error ,coz python recursionlimit is soo poor , so you need upgrade recursionlimit
# Will segfault without this line.
#resource.setrlimit(resource.RLIMIT_STACK, [0x10000000, resource.RLIM_INFINITY])

def find_component(u):
    global ans
    if component[u] != -1:
        return
       
    component[u] = 0
       
    for i in range(0,len(adj[u])):
        ans += 1
        find_component(adj[u][i])
           
           
n,m = map(int,input().split())
adj = []
component = [-1]*(100001)
for i in range(n+1): adj.append([])
for i in range(m):
    x,y = map(int,input().split())
    adj[x].append(y)
    adj[y].append(x)
res = 0
for i in range(1,n+1):
    ans = 0
    if (component[i] == -1):
        find_component(i)
        res = max(res,ans//2)
           
print(res)


#C++ Solution

#include< bits/stdc++.h >
using namespace std;
vector< int >adj[100001];
vector< int >component(100001,-1);
int n,ans = 0;
void find_component(int u)
{

    if (component[u] == 0) {
        return ;
    }
    component[u] = 0;

    for(int i = 0; i < adj[u].size() ; i++){
        ans++;
        find_component(adj[u][i]);
    }

}

int main()
{
    int m,x,y;
    cin >> n >> m;
    for(int i = 0; i < m; i++){
        cin >> x >> y;
        adj[x].push_back(y);
        adj[y].push_back(x);
    }
    int components = 0,res = 0;
    for(int i = 1; i <= n; i++){
        ans = 0;
        if(component[i] == -1){
            find_component(i);
            // component++ if need how many component graph are present
        res = max(res,ans/2);
        }
    }
    cout << res << endl;
    return 0;
}