1851E - Nastya and Potions - CodeForces Solution


dfs and similar dp graphs greedy shortest paths

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define pb push_back
#define s second
#define f first
#define fastio ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define endl '\n'
#define V vector<ll>
#define VV vector<vector<ll>>
vector<ll> adj[200005+2];
ll cost[200005+2],ans[200005];

void dfs(ll p)
{
    if(ans[p]!=-1)return ;
    ll sum=0;
    for (auto u : adj[p])
    {
        dfs(u);
        sum+=ans[u];
    }
    if(adj[p].empty())ans[p]=cost[p];
    else ans[p]=min(sum,cost[p]);

}
int main()
{
   ll t=1;
   cin>>t;
    while(t--){
     ll n,k;
     cin>>n>>k;

     for(int i=1;i<=n;i++){cin>>cost[i];adj[i].clear();ans[i]=-1;}
     for(int i=1;i<=k;i++){ll x; cin>>x; cost[x]=0;}
     for(int i=1;i<=n;i++)
     {
         ll num;
         cin>>num;
         while(num--)
         {
             ll x;
             cin>>x;
             adj[i].pb(x);
         }
     }
     for(int i=1;i<=n;i++)dfs(i);
     for(int i=1;i<=n;i++)cout<<ans[i]<<" ";
     cout<<endl;
}
    return 0;
}


Comments

Submit
0 Comments
More Questions

732A - Buy a Shovel
1220C - Substring Game in the Lesson
452A - Eevee
1647B - Madoka and the Elegant Gift
1408A - Circle Coloring
766B - Mahmoud and a Triangle
1618C - Paint the Array
469A - I Wanna Be the Guy
1294A - Collecting Coins
1227A - Math Problem
349A - Cinema Line
47A - Triangular numbers
1516B - AGAGA XOOORRR
1515A - Phoenix and Gold
1515B - Phoenix and Puzzle
155A - I_love_username
49A - Sleuth
1541A - Pretty Permutations
1632C - Strange Test
673A - Bear and Game
276A - Lunch Rush
1205A - Almost Equal
1020B - Badge
1353A - Most Unstable Array
770A - New Password
1646B - Quality vs Quantity
80A - Panoramix's Prediction
1354B - Ternary String
122B - Lucky Substring
266B - Queue at the School