road repair hackerrank problem solving solution github code example
Example: road repair hackerrank problem solving solution github
#include <algorithm>
#include <cstdio>
#include <deque>
#include <utility>
#include <vector>
using namespace std;
typedef pair<int, int> pii;
#define REP(i, n) for (int i = 0; i < (n); i++)
#define fi first
#define mp make_pair
#define pb push_back
#define se second
int ri()
{
int x;
scanf("%d", &x);
return x;
}
const int N = 100000;
vector<int> e[N];
pair<bool, pii> dfs(int v, int p)
{
deque<pii> c;
int t = -1;
bool has = false;
for (auto u: e[v])
if (u != p) {
auto r = dfs(u, v);
if (! r.fi)
has = true;
if (r.se.fi == r.se.se)
c.push_front(r.se);
else
c.pb(r.se);
t = u;
}
if (c.empty())
return {false, pii{0, 1}};
bool cover = false;
int f = 0, g = 0, i = 0;
for (; i+1 < c.size() && c[i+1].fi == c[i+1].se; i += 2)
f += c[i].se+c[i+1].se-1, cover = true;
if (i < c.size()) {
g = f+c[i].se;
if (c[i].fi == c[i].se)
cover = true;
f += ! cover && has ? cover = true, c[i].se : c[i].fi;
while (++i < c.size())
f += c[i].fi, g += c[i].fi;
} else
g = f+1;
return {cover, {f, g}};
}
int main()
{
for (int cc = ri(); cc--; ) {
int n = ri();
REP(i, n)
e[i].clear();
REP(i, n-1) {
int u = ri(), v = ri();
e[u].pb(v);
e[v].pb(u);
}
printf("%d\n", dfs(0, -1).se.fi);
}
}