dfs and similar graphs greedy *2000

Please click on ads to support us..

C++ Code:

#include<bits/stdc++.h>
#include<unordered_map>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define Analog ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define ll long long
#define endl "\n"
#define fix(a,k) ((a%k)+k)%k
using namespace __gnu_pbds;

#define ordered_set tree<int, null_type,less_equal<int>, rb_tree_tag,tree_order_statistics_node_update>

using namespace std;
void File()
{
#ifndef ONLINE_JUDGE
    freopen("file.txt", "r", stdin);
    freopen("o.txt", "w", stdout);
#endif
}
ll gcd(ll a, ll b)
{
    return b == 0 ? a : gcd(b, a % b);
}
struct edge
{
    ll node, mn, cost;
};
struct cmp
{
    bool operator()(edge a, edge b)
    {
        return a.cost > b.cost;
    }
};
vector<int>adj[5001];
int vis[5001];
vector<int>topo;
void dfs(int node)
{
    vis[node]=1;
    for(auto&ch:adj[node])
    {
        if (!vis[ch])
            dfs(ch);
    }
    topo.push_back(node);
}
int ans=0;
set<int>notvisited;
bool sony=0;
void dfs2(int node)
{
    vis[node]=1;
    if (notvisited.find(node)!=notvisited.end() and !sony)
        ans++,sony=1;
    for(auto&i:adj[node])
    {
        if (!vis[i])
        {
            dfs2(i);
        }
    }
}
int main()
{
    Analog
    File();
    int t = 1;
    //cin >> t;
    int tst=1;
    while(t--)
    {
        int n,m,s;
        cin>>n>>m>>s;
        for(int i=1; i<=m; i++)
        {
            int u,v;
            cin>>u>>v;
            adj[u].push_back(v);
        }
        dfs(s);
        for(int i=1;i<=n;i++)
        {
            if (!vis[i])
            {
                notvisited.insert(i);
            }
        }
        memset(vis,0,sizeof vis);
        for(int i=1;i<=n;i++)
        {
            if (!vis[i])
                dfs(i);
        }
        reverse(topo.begin(),topo.end());
        memset(vis,0,sizeof vis);
        for(int i=0;i<topo.size();i++)
        {
            if (!vis[topo[i]])
            {
                sony=0;
                dfs2(topo[i]);
            }
        }
        cout<<ans;


    }
}

     				 		 	 				    		 		  	


Comments

Submit
0 Comments
More Questions

Book of Potion making
Duration
Birthday Party
e-maze-in
Bricks Game
Char Sum
Two Strings
Anagrams
Prime Number
Lexical Sorting Reloaded
1514A - Perfectly Imperfect Array
580A- Kefa and First Steps
1472B- Fair Division
996A - Hit the Lottery
MSNSADM1 Football
MATCHES Playing with Matches
HRDSEQ Hard Sequence
DRCHEF Doctor Chef
559. Maximum Depth of N-ary Tree
821. Shortest Distance to a Character
1441. Build an Array With Stack Operations
1356. Sort Integers by The Number of 1 Bits
922. Sort Array By Parity II
344. Reverse String
1047. Remove All Adjacent Duplicates In String
977. Squares of a Sorted Array
852. Peak Index in a Mountain Array
461. Hamming Distance
1748. Sum of Unique Elements
897. Increasing Order Search Tree