Video Solution
Note: The video solution might not be the same as other solutions. Code in C++.
Explanation
Let represent the number of neighboring farms without a infected cow a farm has.
We can notice that it takes superspreader events for that farm to collect enough infected cows to send a infected cow to each one of its uninfected adjacent farms.
Additionally, it takes an additional operations to send a cow to each one of those uninfected adjacent farms.
So, at each farm it takes operations to spread the infected cows.
Since the given graph is a tree, we can traverse through the tree, and at each farm, calculate the number of operations and add it to the answer.
Implementation 1 - BFS
Time Complexity:
C++
#include <bits/stdc++.h>using namespace std;int main() {int farm_num;cin >> farm_num;vector<vector<int>> neighbors(farm_num);// Creates a standard adjacency list
Java
import java.io.*;import java.util.*;public class Cowntagion {@SuppressWarnings("unchecked")// don't worry, i totally know what i'm doingpublic static void main(String[] args) throws IOException {BufferedReader read = new BufferedReader(new InputStreamReader(System.in));int farmNum = Integer.parseInt(read.readLine());List<Integer>[] neighbors = new ArrayList[farmNum];
Python
from collections import deque# straight from stackoverflowdef ceil_log_2(x): # returns the smallest n so that 2^n >= xreturn 1 if x == 0 else (x - 1).bit_length()num_farms = int(input())neighbors = [[] for _ in range(num_farms)]for _ in range(num_farms - 1):
Implementation 2 - DFS
Time Complexity:
C++
#include <bits/stdc++.h>using namespace std;#define maxn 100005int n;vector<int> adj[maxn];int dfs(int start, int parent) {
Java
import java.io.*;import java.util.*;public class Cowntagion {private static List<Integer>[] adj;private static int dfs(int start, int parent) {int ans = 0;int cows = adj[start].size();if (parent == -1) { cows++; }
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!