Brain Network (medium) (Codeforces 690C2)
Tags: Others, trees

Further research on zombie thought processes yielded interesting results. As we know from the previous problem, the nervous system of a zombie consists of n brains and m brain connectors joining some pairs of brains together. It was observed that the intellectual abilities of a zombie depend mainly on the topology of its nervous system. More precisely, we define the distance between two brains u and v (1 ≤ u, v ≤ n) as the minimum number of brain connectors used when transmitting a thought between these two brains. The brain latency of a zombie is defined to be the maximum distance between any two of its brains. Researchers conjecture that the brain latency is the crucial parameter which determines how smart a given zombie is. Help them test this conjecture by writing a program to compute brain latencies of nervous systems.In this problem you may assume that any nervous system given in the input is valid, i.e., it satisfies conditions (1) and (2) from the easy version.

Input: The first line of the input contains two space-separated integers n and m (1 ≤ n, m ≤ 100000) denoting the number of brains (which are conveniently numbered from 1 to n) and the number of brain connectors in the nervous system, respectively. In the next m lines, descriptions of brain connectors follow. Every connector is given as a pair of brains a b it connects (1 ≤ a, b ≤ n and a ≠ b).

Output: Print one number – the brain latency.


Sample Inputs:
4 3
1 2
1 3
1 4

5 4
1 2
2 3
3 4
3 5

Sample Outputs:
2

3

Solution (Python):
import sys

def read_graph():
    graph = {}
    (n, m) = map(int, sys.stdin.readline().split(' '))
    for _ in range(m):
        (a, b) = map(int, sys.stdin.readline().split(' '))
        graph.setdefault(a, set()).add(b)
        graph.setdefault(b, set()).add(a)
    return graph

def build_degree_dict(graph):
    degree = {}
    for (node, neighbors) in graph.items():
        degree.setdefault(len(neighbors), set()).add(node)
    return degree

def main():
    graph = read_graph()
    degree = build_degree_dict(graph)
    latency = 0
    while len(graph.keys()) > 2:
        latency += 2
        leaves = degree[1].copy()
        degree.pop(1, None)
        if leaves == {}:
            print('We probably did something wrong...')
        for leaf in leaves:
            neighbors = graph[leaf]
            graph.pop(leaf, None)
            for neighbor in neighbors:
                neighbor_degree = len(graph[neighbor])
                graph[neighbor].remove(leaf)
                degree[neighbor_degree].remove(neighbor)
                degree.setdefault(neighbor_degree - 1, set()).add(neighbor)
    if len(graph.keys()) == 2:
        latency += 1
    print(latency)
if __name__ == '__main__':
    main()

Solution (Python):
def solution(idx):
    visited = [False] * n
    max_distance = (0, idx)
    stack = [max_distance]
    while stack:
        (distance, idx) = stack.pop()
        visited[idx] = True
        if distance > max_distance[0]:
            max_distance = (distance, idx)
        stack += [(distance + 1, j) for j in links[idx] if not visited[j]]
    return max_distance
if __name__ == '__main__':
    (n, m) = map(int, input().split())
    links = [[] for i in range(n)]
    for j in range(m):
        (a, b) = map(int, input().split())
        links[a - 1].append(b - 1)
        links[b - 1].append(a - 1)
    print(solution(solution(0)[1])[0])

Solution (Python):
from sys import *
from collections import defaultdict
import threading
setrecursionlimit(10 ** 9)
threading.stack_size(10 ** 8)

def solve():

    def dfs_plz_chal_ja(u, vis, d, ans):
        vis[u] = True
        x = []
        if len(d[u]) == 1 and u != 0:
            ans[0] = max(ans[0], 1)
            return 1
        for neighbor in d[u]:
            if vis[neighbor] == False:
                x.append(dfs_plz_chal_ja(neighbor, vis, d, ans))
        x.sort(reverse=True)
        if len(x) == 1:
            ans[0] = max(ans[0], x[0])
            return x[0] + 1
        ans[0] = max(ans[0], x[0] + x[1])
        return x[0] + 1
    (n, m) = map(int, stdin.readline().split())
    d = defaultdict(list)
    for i in range(m):
        (u, v) = map(int, stdin.readline().split())
        u -= 1
        v -= 1
        d[u].append(v)
        d[v].append(u)
    vis = [False] * n
    ans = [0]
    dfs_plz_chal_ja(0, vis, d, ans)
    stdout.write(str(ans[0]))
threading.Thread(target=solve).start()