659E - New Reform - CodeForces Solution


data structures dfs and similar dsu graphs greedy *1600

Please click on ads to support us..

Python Code:

def dfs(node, prev_node):
    global flag
    if node not in visited:
        if flag:
            visited.add(node)
        else:
            flag = True
        ret = True
        for n in arcs[node]:
            if prev_node != n:
                ret = ret and dfs(n,node)
        return ret

cities, roads = list(map(int,input().split()))
arcs = {k+1: [] for k in range(cities)}
flag = False
visited = set()
min = 0


for _ in range(roads):
    a,b = list(map(int,input().split()))
    arcs[a].append(b)
    arcs[b].append(a)

for n in range(1,cities+1):
    if n not in visited:
        if(dfs(n,0)):
            min +=1
print(min)

C++ Code:

#include <bits/stdc++.h>
#define rep(i,n) for (long long i=0; i<n; ++i)
#define isodd %2==1
#define iseven %2==0
#define ll long long
#define ld long double
#define pb push_back
#define mp make_pair
#define all(v) v.begin(),v.end()
#define back(v) v.rbegin(),v.rend()
#define vi vector<ll>
#define vb vector<bool>
#define IOS ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0)
using namespace std;
bool dfs(ll node,vb &vis,vector<vi> &adj,ll parent){
    vis[node]= true;
    bool ans = false;
    for(auto it:adj[node]){
        if(!vis[it]){
            if(dfs(it,vis,adj,node)) {
                    ans= true;
            } 
        }
        else if(it!=parent) {
            ans= true;
        };
    }
    return ans;
}
void sol(){
    ll n,m;
    cin>>n>>m;
    vector<vi> adj(n+1);
    for (ll i = 0; i < m; i++)
    {
        ll x,y;cin>>x>>y;
        adj[x].push_back(y);
        adj[y].push_back(x);
    }
    ll cnt=0;
    vb vis(n+1,0);
    for (ll i = 1; i <= n; i++)
    {
        if(!vis[i]){
            if(!dfs(i,vis,adj,-1)){
                cnt++;
            }
        }
    }
    cout<<cnt<<'\n';
    
    
}
int main()
{IOS;

    sol();

    
    return 0;
}


Comments

Submit
0 Comments
More Questions

961A - Tetris
1635B - Avoid Local Maximums
20A - BerOS file system
1637A - Sorting Parts
509A - Maximum in Table
1647C - Madoka and Childish Pranks
689B - Mike and Shortcuts
379B - New Year Present
1498A - GCD Sum
1277C - As Simple as One and Two
1301A - Three Strings
460A - Vasya and Socks
1624C - Division by Two and Permutation
1288A - Deadline
1617A - Forbidden Subsequence
914A - Perfect Squares
873D - Merge Sort
1251A - Broken Keyboard
463B - Caisa and Pylons
584A - Olesya and Rodion
799A - Carrot Cakes
1569B - Chess Tournament
1047B - Cover Points
1381B - Unmerge
1256A - Payment Without Change
908B - New Year and Buggy Bot
979A - Pizza Pizza Pizza
731A - Night at the Museum
742A - Arpa’s hard exam and Mehrdad’s naive cheat
1492A - Three swimmers