1850H - The Third Letter - CodeForces Solution


dfs and similar graphs greedy implementation

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
ll powi(ll a, ll b)
{
    if (b == 0)
        return 1;
    if (b % 2 == 0)
    {
        ll k = powi(a, b / 2);
        return k * k;
    }
    else
    {
        ll k = powi(a, b / 2);
        return a * k * k;
    }
}

ll maxl(ll a, ll b)
{
    if (a > b)
    {
        return a;
    }
    return b;
}

ll minl(ll a, ll b)
{
    if (a < b)
    {
        return a;
    }
    return b;
}
void dfs(vector<pair<ll, ll>> adj[],vector<ll>&vis,vector<ll>&dis,int i,ll dip){
    vis[i]=1;
    dis[i]=dip;
    for(auto it:adj[i]){
        int node=it.first;
        int tmdis=it.second;
        if (vis[node]==0)
        {
            dfs(adj,vis,dis,node,dip+tmdis);
        }
        else if (dis[node]!=dip+tmdis )
        {
            dis[node]=LLONG_MAX;
        }
    }
}
int main()
{
    int t;
    cin >> t;
    while (t--)
    {
        int n, m;
        cin >> n >> m;
        int a, b, d;
        vector<pair<ll, ll>> adj[n + 1];
        for (int i = 0; i < m; i++)
        {
            cin >> a >> b >> d;

            adj[a].push_back({b, d});

            adj[b].push_back({a, -1*d});
        }
        vector<ll>vis(n+1,0);
        vector<ll>dis(n+1,LLONG_MIN);
        for (int i = 1; i < n+1 ; i++)
        {
            if (vis[i]==0)
            {
                dfs(adj,vis,dis,i,0);
            }
            
        }
        // for (auto it:dis)
        // {
        //     cout<<it<<" ";
        // }cout<<endl;
        int chk=0;
        for (auto it:dis)
        {
            if (it==LLONG_MAX )
            {
                chk=1;
                break;
            }
            
        }
        if (chk )
        {
            cout<<"NO"<<endl;
        }
        else{
            cout<<"YES"<<endl;
        }
        
        
    }

    return 0;
}


Comments

Submit
0 Comments
More Questions

1468C - Berpizza
1546B - AquaMoon and Stolen String
1353C - Board Moves
902A - Visiting a Friend
299B - Ksusha the Squirrel
1647D - Madoka and the Best School in Russia
1208A - XORinacci
1539B - Love Song
22B - Bargaining Table
1490B - Balanced Remainders
264A - Escape from Stones
1506A - Strange Table
456A - Laptops
855B - Marvolo Gaunt's Ring
1454A - Special Permutation
1359A - Berland Poker
459A - Pashmak and Garden
1327B - Princesses and Princes
1450F - The Struggling Contestant
1399B - Gifts Fixing
1138A - Sushi for Two
982C - Cut 'em all
931A - Friends Meeting
1594A - Consecutive Sum Riddle
1466A - Bovine Dilemma
454A - Little Pony and Crystal Mine
2A - Winner
1622B - Berland Music
1139B - Chocolates
1371A - Magical Sticks