Cowntagion#10367

Cowntagion (Editorial)

To infect all the farms, two types of actions must be performed:

Note that doublings and movements can occur at different locations of the tree after an infection.

Suppose one infected cow arrives at farm . If farm has children in the tree, it needs to send infected cows to neighbors, so it must have at least cows.

Initially, farm has cow. We perform doublings: 1 \to 2 \to 4 \to 8 ... . The minimum number of doublings required to reach at least cows is ⌈log_2 x⌉.

Thus, the minimum number of days needed to spread the disease to all farms is

(n - 1) + ∑_{v = 1}^n ⌈log_2~number~of~children~of~vertex~v⌉

According to the problem statement, it is sufficient that at some point in time at least one infected cow visits each farm. The statement does not require that after all farms are infected, each farm must still have at least one infected cow.

Algorithm implementation

The tree is stored as an adjacency list .

vector<vector<int>> g;

The dfs function performs a depth-first search starting from vertex and returns the number of days required to double the infected cows in all vertices of the subtree rooted at . The parent of vertex is .

int dfs(int v, int par = 0)
{
  int ans = 0;
  for (int to : g[v])
    if (to != par)
      ans += dfs(to, v);
  return ans + ceill(log2(g[v].size()));
}

The main part of the program. Read the input data. Build the graph.

scanf("%d", &n);
g.resize(n + 1);
for (i = 0; i < n - 1; i++)
{
  scanf("%d %d", &a, &b);
  g[a].push_back(b);
  g[b].push_back(a);
}

Run a depth-first search starting from vertex and compute the minimum number of days required to infect all farms. The result is stored in the variable .

res = dfs(1) + n - 1;

Print the answer.

printf("%d\n", res);