In this HackerEarth Candy Game problem solution There are N candies in a room labelled from 1 to N and there are N - 1 directed path between these candies such that every candy has at least 1 path leading to the candy or away from it.

K and L want to eat all the candies in the room but they don't know where to start.

If K starts with the candy labelled c (1 <= c <= N), then he can eat all the candies which can be reached from the position of the candy c. Similarly, if L starts with the candy labelled d (1 <= d <= N), then he can eat all the candies which can be reached from the position of the candy d. Note that both, K and L, can start from the same candy position.

Now, they will be able to eat all the candies in the room if there exist candy positions c and d such that any other candy in the room can be eaten by at least one of them. In order to make this possible, they want to change the direction of some number of paths. You have to calculate the minimum number of paths that need to be changed so that K and L can eat all the candies.


HackerEarth Candy Game problem solution


HackerEarth Candy Game problem solution.

#include <iostream>
#include <sstream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <string>
#include <map>
#include <set>
#include <stack>
#include <vector>
#include <queue>

using namespace std;

#define SI ({int x;scanf("%d",&x);x;})
#define MP make_pair
#define PB push_back
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define getSize(x) ((int) (x).size())
const int INF = (1000000007);
typedef pair<int,int> PII;
typedef long long LL;
const int MAXN=5000;
vector<pair<int,int> > E[MAXN];
int ans=(~0U>>1),u[MAXN],d[MAXN][3],n;

void dfs(int v)
{
int nv,tp,d1=0,d2=0; d[v][0]=0; u[v]=1;
for(int i=0;i<(int)E[v].size();i++)
{
nv=E[v][i].first, tp=E[v][i].second;
if(u[nv])
continue;
else
dfs(nv);
d[v][0]+=tp+d[nv][0];
d1=min(d1,d[nv][1]+1-tp-d[nv][0]-tp);
d2=min(d2,min((d[nv][2]+tp)-(d[nv][0]+tp),d[nv][1]-(d[nv][0]+tp)));
}
d[v][1]=d[v][0]+d1, d[v][2]=d[v][0]+d2;
}
int main()
{
int x,y;
cin>>n;
if(n==1)
{
cout<<0<<endl;
return 0;
}
for(int i=0;i<n-1;i++)
{
cin>>x>>y;
x--; y--;
E[x].PB(MP(y,0));
E[y].PB(MP(x,1));
}
for(int i=0;i<n;i++)
{
memset(u,0,sizeof u);
dfs(i);
ans=min(ans,min(d[i][0],min(d[i][1],d[i][2])));
}
cout<<ans<<endl;
}