Problem:
 Score : 800 points    Problem Statement Takahashi and Aoki will play a game on a tree.
The tree has N vertices numbered 1 to N , and the i -th of the N-1 edges connects Vertex a_i and Vertex b_i .  At the beginning of the game, each vertex contains a coin.
Starting from Takahashi, he and Aoki will alternately perform the following operation:   Choose a vertex v that contains one or more coins, and remove all the coins from v .  Then, move each coin remaining on the tree to the vertex that is nearest to v among the adjacent vertices of the coin's current vertex.   The player who becomes unable to play, loses the game.
That is, the player who takes his turn when there is no coin remaining on the tree, loses the game.
Determine the winner of the game when both players play optimally.      Constraints  1 \leq N \leq 2 \times 10^5  1 \leq a_i, b_i \leq N  a_i \neq b_i  The graph given as input is a tree.         Input Input is given from Standard Input in the following format:  N  a_1  b_1  a_2  b_2  :  a_{N-1}  b_{N-1}       Output Print First if Takahashi will win, and print Second if Aoki will win.        Sample Input 1 3
1 2
2 3      Sample Output 1 First  Here is one possible progress of the game:   Takahashi removes the coin from Vertex 1 . Now, Vertex 1 and Vertex 2 contain one coin each.  Aoki removes the coin from Vertex 2 . Now, Vertex 2 contains one coin.  Takahashi removes the coin from Vertex 2 . Now, there is no coin remaining on the tree.  Aoki takes his turn when there is no coin on the tree and loses.        Sample Input 2 6
1 2
2 3
2 4
4 6
5 6      Sample Output 2 Second       Sample Input 3 7
1 7
7 4
3 4
7 5
6 3
2 1      Sample Output 3 First

Solution (Python):
import sys
input = sys.stdin.readline

n = int(input())
T = [[] for _ in range(n+1)]
for _ in range(n-1):
  a, b = map(int, input().split())
  T[a].append(b)
  T[b].append(a)
def dfs(v):
  dist = [-1]*(n+1)
  dist[v] = 0
  stack = [v]
  depth = 0
  while stack:
    nv = stack.pop()
    for i in T[nv]:
      if dist[i] != -1:
        continue
      dist[i] = dist[nv] + 1
      stack.append(i)
  return dist

D = dfs(1)
m = D.index(max(D))
dia = max(dfs(m))
if dia%3 == 1:
  print("Second")
else:
  print("First")

Solution (Python):
import sys
input = sys.stdin.readline

n = int(input())
T = [[] for _ in range(n+1)]
for _ in range(n-1):
  a, b = map(int, input().split())
  T[a].append(b)
  T[b].append(a)
def dfs(v):
  dist = [-1]*(n+1)
  dist[v] = 0
  stack = [v]
  depth = 0
  while stack:
    nv = stack.pop()
    for i in T[nv]:
      if dist[i] != -1:
        continue
      dist[i] = dist[nv] + 1
      stack.append(i)
  return dist

D = dfs(1)
m = D.index(max(D))
dia = max(dfs(m))
if dia%3 == 1:
  print("Second")
else:
  print("First")

Solution (Python):
from collections import deque
N, *L = map(int, open(0).read().split())
dic = [[] for i in range(N+1)]
for a,b in zip(*[iter(L)]*2):
  dic[a] += [b]
  dic[b] += [a]
q = deque([1])
  
dist = [-1]*(N+1)
while q:
  v = q.popleft()
  for u in dic[v]:
    if dist[u]==-1:
      dist[u] = dist[v]+1
      q.append(u)
p = max(range(1,N+1),key=lambda x:dist[x])
dist = [-1]*(N+1)
dist[p] = 0
q = deque([p])
while q:
  v = q.popleft()
  for u in dic[v]:
    if dist[u]==-1:
      dist[u] = dist[v]+1
      q.append(u)
M = max(dist)
if M%3==1:
  print('Second')
else:
  print('First')

Solution (Python):
n,*L=map(int,open(0).read().split())
con=[[]for _ in range(n)]
for a,b in zip(*[iter(L)]*2):
	con[a-1].append(b-1)
	con[b-1].append(a-1)
dist=[-1]*n
dist[0]=0
farthest=0
q=[0]
while q:
	cur=q.pop()
	for nxt in con[cur]:
		if dist[nxt]<0:
			dist[nxt]=dist[cur]+1
			if dist[farthest]<dist[nxt]:
				farthest=nxt
			q.append(nxt)
dist=[-1]*n
dist[farthest]=0
diameter=0
q=[farthest]
while q:
	cur=q.pop()
	for nxt in con[cur]:
		if dist[nxt]<0:
			dist[nxt]=dist[cur]+1
			diameter=max(diameter,dist[nxt])
			q.append(nxt)
print("Second" if diameter%3==1 else "First")

Solution (Python):
import sys
input = sys.stdin.buffer.readline
from collections import deque

def main():
    N = int(input())
    if N == 1:
        print("First")
        exit()
    edge = [[] for _ in range(N)]
    
    for _ in range(N-1):
        a,b = map(int,input().split())
        edge[a-1].append(b-1)
        edge[b-1].append(a-1)
        
    dep = [-1 for _ in range(N)]
    dep[0] = 0
    q = deque([0])
    while q:
        now = q.popleft()
        for fol in edge[now]:
            if dep[fol] == -1:
                dep[fol] = dep[now]+1
                q.append(fol)
    
    st = dep.index(max(dep))
    dep = [-1 for _ in range(N)]
    dep[st] = 0
    q = deque([st])
    while q:
        now = q.popleft()
        for fol in edge[now]:
            if dep[fol] == -1:
                dep[fol] = dep[now]+1
                q.append(fol)
                
    if max(dep)%3 == 1:
        print("Second")
    else:
        print("First")

if __name__ == "__main__":
    main()

Solution (Python):
import sys
from collections import defaultdict as dd
input = sys.stdin.readline
N = int(input())
e = dd(list)
if N == 1:
  print("First")
  exit(0)
for _ in range(N - 1):
  u, v = map(int, input().split())
  e[u].append((v, 1))
  e[v].append((u, 1))
import heapq
class dijkstra:
  def __init__(self, n, e):
    self.e = e
    self.n = n
  def path(self, s, t):
    d = [float("inf")] * (self.n + 1)
    vis = set()
    d[s] = 0
    h = [s]
    while not t in vis and len(h):
      v = heapq.heappop(h)
      v1 = v % (10 ** 6)
      v0 = v // (10 ** 6)
      if v1 in vis: continue
      vis.add(v1)
      for p in self.e[v1]:
        d[p[0]] = min(d[p[0]], d[v1] + p[1])
        if p[0] in vis: continue
        heapq.heappush(h, d[p[0]] * (10 ** 6) + p[0])
    return d
dij = dijkstra(N, e)
s = 0
d = 0
p = dij.path(1, 0)
for i in range(1, N + 1):
  if p[i] > d:
    s = i
    d = p[i]
p = dij.path(s, 0)
mx = max(p[1: ])
if mx % 3 == 1: print("Second")
else: print("First")

Solution (Python):
def examA():
    N = I()
    ans = 0
    print(ans)
    return


def examB_maspy():
    H, W, N = LI()
    sr, sc = LI()
    S = SI()
    T = SI()
    sr = H + 1 - sr

    
    L, R = 1, W
    D, U = 1, H
    for s, t in zip(S[::-1], T[::-1]):
        if t == 'L':
            R += 1
        elif t == 'D':
            U += 1
        elif t == 'R':
            L -= 1
        elif t == 'U':
            D -= 1

        if L == 0: L = 1
        if D == 0: D = 1
        if R > W: R = W
        if U > H: U = H

        if s == 'L':
            L += 1
        elif s == 'R':
            R -= 1
        elif s == 'D':
            D += 1
        elif s == 'U':
            U -= 1

        if L > R or D > U:
            
            break

    bl = (L <= sc <= R) and (D <= sr <= U)
    answer = 'YES' if bl else 'NO'
    print(answer)
    return


def examB():
    H, W, N = LI()
    start = LI()
    S = SI();
    T = SI()
    for t, a in [["U", "D"], ["R", "L"]]:
        if t == "U":
            n = H
        else:
            n = W
        
        l = 1;
        r = n
        if S[-1] == t:
            r -= 1
        elif S[-1] == a:
            l += 1
        for i in range(N - 2, -1, -1):
            if T[i] == t and l > 1:
                l -= 1
            elif T[i] == a and r < n:
                r += 1
            if S[i] == t:
                r -= 1
            elif S[i] == a:
                l += 1
            
            if l > r:
                print("NO")
                return
            if t == "U" and (r == 0 or l == n):
                print("NO")
                return
            if t == "R" and (r == 0 or l == n):
                print("NO")
                return

        if t == "U" and (not l <= H + 1 - start[0] <= r):
            print("NO")
            return
        elif t == "R" and (not l <= start[1] <= r):
            print("NO")
            return
    print("YES")
    return

def examC():
    def bfs(n, e, fordfs):
        
        W = [-1] * n
        
        W[e] = 0
        que = deque()
        que.append(e)
        while que:
            now = que.popleft()
            nowW = W[now]
            for ne in fordfs[now]:
                if W[ne] == -1:
                    W[ne] = nowW + 1
                    que.append(ne)
        return W
    N = I()
    V = [[]for _ in range(N)]
    for _ in range(N-1):
        a, b = LI()
        a -=1; b -=1
        V[a].append(b)
        V[b].append(a)
    L = bfs(N,0,V)
    D = max(bfs(N,L.index(max(L)),V))

    if D%3==1:
        print("Second")
    else:
        print("First")
    return

def examD():
    ans = 0
    print(ans)
    return

import sys,copy,bisect,itertools,heapq,math
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18
alphabet = [chr(ord('a') + i) for i in range(26)]

if __name__ == '__main__':
    examC()

"""

"""

Solution (Python):


import sys

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 19
MOD = 10 ** 9 + 7

def dfs(N, nodes, src):
    """ DFS(木、スタック、重みなし) """

    stack = [(src, -1, 0)]
    dist = [INF] * N
    while stack:
        u, prev, c = stack.pop()
        dist[u] = c
        for v in nodes[u]:
            if v != prev:
                stack.append((v, u, c+1))
    return dist

N = INT()
nodes = [[] for i in range(N)]
for _ in range(N-1):
    a, b = MAP()
    a -= 1; b -= 1
    nodes[a].append(b)
    nodes[b].append(a)


dist1 = dfs(N, nodes, 0)
u = dist1.index(max(dist1))
dist2 = dfs(N, nodes, u)
L = max(dist2)

if L % 3 != 1:
    print('First')
else:
    print('Second')

Solution (Python):


import sys

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 19
MOD = 10 ** 9 + 7

def dfs(N, nodes, src):
    """ DFS(木、スタック、重みなし) """

    stack = [(src, -1, 0)]
    dist = [INF] * N
    while stack:
        u, prev, c = stack.pop()
        dist[u] = c
        for v in nodes[u]:
            if v != prev:
                stack.append((v, u, c+1))
    return dist

N = INT()
nodes = [[] for i in range(N)]
for _ in range(N-1):
    a, b = MAP()
    a -= 1; b -= 1
    nodes[a].append(b)
    nodes[b].append(a)


dist1 = dfs(N, nodes, 0)
u = dist1.index(max(dist1))
dist2 = dfs(N, nodes, u)
L = max(dist2)

if L % 3 != 1:
    print('First')
else:
    print('Second')

Solution (Python):

import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline
INF = 2**62-1


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, AB):
    g = defaultdict(set)

    for a, b in AB:
        g[a].add(b)
        g[b].add(a)

    def dfs(s):
        stack = [s]
        done = {s: 0}

        while stack:
            u = stack.pop()
            for v in g[u]:
                if v not in done:
                    done[v] = done[u] + 1
                    stack.append(v)
        l = (-0, 0)
        for k, v in done.items():
            if l[1] < v:
                l = (k, v)
        return l

    v, _ = dfs(1)
    _, l = dfs(v)
    return 'First' if l % 3 != 1 else 'Second'


def main():
    N = read_int()
    AB = [read_int_n() for _ in range(N-1)]
    print(slv(N, AB))


if __name__ == '__main__':
    main()

Solution (Python):

import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline
INF = 2**62-1


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, AB):
    g = defaultdict(set)

    for a, b in AB:
        g[a].add(b)
        g[b].add(a)

    def dfs(s):
        stack = [s]
        done = {s: 0}

        while stack:
            u = stack.pop()
            for v in g[u]:
                if v not in done:
                    done[v] = done[u] + 1
                    stack.append(v)
        l = (-0, 0)
        for k, v in done.items():
            if l[1] < v:
                l = (k, v)
        return l

    v, _ = dfs(1)
    _, l = dfs(v)
    return 'First' if l % 3 != 1 else 'Second'


def main():
    N = read_int()
    AB = [read_int_n() for _ in range(N-1)]
    print(slv(N, AB))


if __name__ == '__main__':
    main()

Solution (Python):
import sys
from collections import deque

def ni():
    return int(sys.stdin.readline())


def nia():
    data = sys.stdin.readline().split(' ')
    return [int(g) for g in data]

n = ni()
graph = []
for i in range(0, n):
    graph.append([])

for i in range(1, n):
    a, b = nia()
    a = a - 1
    b = b - 1

    graph[a].append(b)
    graph[b].append(a)


q = deque()
q.append(0)
visited = set()
visited.add(0)
last = 0
while q:
    n = q.popleft()
    last = n
    for nb in graph[n]:
        if nb not in visited:
            visited.add(nb)
            q.append(nb)

diam = 0
visited = set()
next = [(last, 0)]
while next:
    ind, x = next.pop()
    diam = max(diam, x)
    for nb in graph[ind]:
        if nb not in visited:
            visited.add(nb)
            next.append((nb, x + 1))

if (diam + 1) % 3 == 2:
    print 'Second'
else:
    print 'First'

Solution (Python):
N=int(input())
ab=[list(map(int,input().split())) for i in range(N-1)]
data=[[] for i in range(N+1)]
for a,b in ab:
    data[a].append(b)
    data[b].append(a)
flag=[-1]*(N+1)
flag[1]=0
que=[1]
l=1
while que:
    h=[]
    for u in que:
        for v in data[u]:
            if flag[v]==-1:
                flag[v]=l
                h.append(v)
    l+=1
    que=h
ind=0
num=0
for i in range(1,N+1):
    if num<flag[i]:
        num=flag[i]
        ind=i
flag=[-1]*(N+1)
flag[ind]=0
que=[ind]
l=1
while que:
    h=[]
    for u in que:
        for v in data[u]:
            if flag[v]==-1:
                flag[v]=l
                h.append(v)
    l+=1
    que=h
num=max(flag)+1
if num%3==2:
    print("Second")
else:
    print("First")

Solution (Python):
N = int(input())
vec = [[] for _ in range(N)]
for _ in range(N - 1) :
  a, b = map(int, input().split())
  vec[a-1].append(b-1)
  vec[b-1].append(a-1)

que = [(0, -1, 0)]
Mi, Mv = 0, 0
while que :
  cur, pre, dist = que.pop()
  if dist > Mv :
    Mi, Mv = cur, dist
  for nex in vec[cur] :
    if nex == pre :
      continue
    que.append((nex, cur, dist + 1))

que = [(Mi, -1, 1)]
Mi, Mv = 0, 0
while que :
  cur, pre, dist = que.pop()
  if dist > Mv :
    Mi, Mv = cur, dist
  for nex in vec[cur] :
    if nex == pre :
      continue
    que.append((nex, cur, dist + 1))

if Mv % 3 != 2 :
  print('First')
else :
  print('Second')

Solution (Python):
n = int(input())
l = [list() for _ in range(n)]
for _ in range(n-1):
  a,b = map(int,input().split())
  l[a-1].append(b-1)
  l[b-1].append(a-1)

def dfs(p):
  dep = [None]*n
  dep[p] = 0
  q = [p]
  while q:
    v = q.pop()
    for x in l[v]:
      if dep[x] is None:
        dep[x] = dep[v] + 1
        q.append(x)
  return dep
      
dep = dfs(0)
p = dep.index(max(dep))
dep = dfs(p)
q = max(dep)-1
print("First" if q%3 else "Second")

Solution (Python):
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda:sys.stdin.readline().rstrip()
from collections import deque
def resolve():
    n=int(input())
    E=[[] for _ in range(n)]
    for i in range(n-1):
        a,b=map(int,input().split())
        a-=1; b-=1
        E[a].append(b)
        E[b].append(a)

    
    dist=[INF]*n
    dist[0]=0
    Q=deque([0])
    while(Q):
        v=Q.popleft()
        for nv in E[v]:
            if(dist[nv]!=INF): continue
            dist[nv]=dist[v]+1
            Q.append(nv)

    v=max((dist[v],v) for v in range(n))[1]
    dist=[INF]*n
    dist[v]=0
    Q=deque([v])
    while(Q):
        v=Q.popleft()
        for nv in E[v]:
            if(dist[nv]!=INF): continue
            dist[nv]=dist[v]+1
            Q.append(nv)

    dia=max(dist)
    print("Second" if(dia%3==1) else "First")
resolve()

Solution (Python):
import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline

n = int(input())
G = [[] for i in range(n)]
for i in range(n-1):
    a,b = map(int, input().split())
    a,b = a-1,b-1
    G[a].append(b)
    G[b].append(a)

def dfs(cur, cost):
    dist[cur] = cost
    for to in G[cur]:
        if dist[to] == -1:
            dfs(to, cost+1)
dist = [-1]*n
dfs(0, 0)
m = max(dist)
for i in range(n):
    if dist[i] == m:
        start = i
        break
dist = [-1]*n
dfs(start, 0)
m = max(dist)

if m%3==1:
    print("Second")
else:
    print("First")

Solution (Python):
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
from bisect import bisect_left, bisect_right
import random
from itertools import permutations, accumulate, combinations
import sys
import string



INF = 10 ** 13
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return sys.stdin.readline().strip()
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 10 ** 9 + 7



n = I()
G = [[] for _ in range(n)]
for k in range(n - 1):
    a, b = LI()
    G[a - 1] += [b - 1]
    G[b - 1] += [a - 1]


def bfs(root):
    que = deque([root])
    dist = [INF] * n
    dist[root] = 0
    while que:
        u = que.popleft()
        for v in G[u]:
            if dist[u] + 1 < dist[v]:
                dist[v] = dist[u] + 1
                que += [v]
    return dist



def double_sweep():
    dist = bfs(0)
    ret = -1
    for u in range(n):
        if dist[u] > ret:
            ret = dist[u]
            v = u
    return max(bfs(v))



if (double_sweep() + 1) % 3 == 2:
    print('Second')
else:
    print('First')

Solution (Python):
N = int(input())
graph = [[] for _ in range(N)]
for _ in range(N-1):
    a, b = map(int, input().split())
    graph[a-1].append(b-1)
    graph[b-1].append(a-1)

def bfs(start):
    checked = [False]*N
    q = [start]
    c = -1
    while q:
        qq = []
        c += 1
        for p in q:
            for np in graph[p]:
                if not checked[np]:
                    checked[np] = True
                    qq.append(np)
        if not qq:
            break
        q = qq
    return c, q

_, q = bfs(0)
d, _ = bfs(q[0])
if d%3 == 1:
    print('Second')
else:
    print("First")

Solution (Python):
from collections import deque
import sys

N = int(input())

if N == 1:
    print ("First")
    sys.exit()


dic = {}

for  i in range(N-1):

    a,b = map(int,input().split())
    a-=1
    b-=1

    if a not in dic:
        dic[a] = []
    if b not in dic:
        dic[b] = []

    dic[a].append(b)
    dic[b].append(a)

for xxx in range(1):

    lis = [float("inf")] * N
    lis[0] = 0
    maxind = 0
    q = deque([0])

    while len(q) > 0:

        now = q.popleft()

        for nex in dic[now]:

            if lis[nex] > lis[now] + 1:
                lis[nex] = lis[now] + 1
                q.append(nex)
                maxind = nex

    lis = [float("inf")] * N
    lis[maxind] = 1
    q = deque([maxind])
    L = 0

    while len(q) > 0:

        now = q.popleft()

        for nex in dic[now]:

            if lis[nex] > lis[now] + 1:
                lis[nex] = lis[now] + 1
                q.append(nex)
                L = lis[nex]

    
    

    if L == 1 or L % 3 != 2:

        print ("First")

    else:

        print ("Second")

Solution (Python):
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
from bisect import bisect_left, bisect_right
import random
from itertools import permutations, accumulate, combinations
import sys
import string



INF = float('inf')
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return sys.stdin.readline().strip()
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 10 ** 9 + 7



n = I()
graph = [[] for _ in range(n)]
for k in range(n - 1):
    a, b = LI()
    graph[a - 1] += [b - 1]
    graph[b - 1] += [a - 1]


def bfs(v):
    que = deque([v])
    dist = [INF] * n
    dist[v] = 0
    while que:
        cur = que.popleft()
        for nxt in graph[cur]:
            if dist[cur] + 1 < dist[nxt]:
                dist[nxt] = dist[cur] + 1
                que += [nxt]
    return dist



def double_sweep():
    dist = bfs(0)
    ret = -1
    for i in range(n):
        if dist[i] > ret:
            ret = dist[i]
            u = i
    return max(bfs(u))



if (double_sweep() + 1) % 3 == 2:
    print('Second')
else:
    print('First')

Solution (Python):
n = int(input())
g = [[] for _ in range(n)]
for i in range(n - 1):
    a, b = map(int, input().split())
    g[a - 1].append(b - 1)
    g[b - 1].append(a - 1)
s = [0]
d = [-1] * n
d[0] = 0
while s:
    p = s.pop()
    for node in g[p]:
        if d[node] == -1:
            s.append(node)
            d[node] = d[p] + 1
idx = 0
for i in range(n):
    if d[i] > d[idx]:
        idx = i
s = [idx]
d = [-1] * n
d[idx] = 0
while s:
    p = s.pop()
    for node in g[p]:
        if d[node] == -1:
            s.append(node)
            d[node] = d[p] + 1
m = 0
for i in range(n):
    if d[i] > m:
        m = d[i]
if m % 3 == 1:
    print('Second')
else:
    print('First')

Solution (Python):

import sys
from collections import deque, defaultdict
import copy
import bisect
sys.setrecursionlimit(10 ** 9)
import math
import heapq
from itertools import product, permutations,combinations
import fractions
from operator import itemgetter

import sys
def input():
	return sys.stdin.readline().strip()

N = int(input())
tree = [[] for _ in range(N)]
for _ in range(N - 1):
	a, b = list(map(int, input().split()))
	a -= 1
	b -= 1
	tree[a].append(b)
	tree[b].append(a)

que = deque()
que.append(0)
max_length = 0
max_loc = 0
length_list = [100000000]*N
length_list[0] = 0
while len(que) > 0:
	node = que.popleft()
	for node_next in tree[node]:
		if length_list[node_next] > length_list[node]:
			length_list[node_next] = length_list[node] + 1
			if max_length < length_list[node_next]:
				max_length = length_list[node_next]
				max_loc =node_next
			que.append(node_next)

que = deque()
que.append(max_loc)
max_length = 0
length_list = [100000000]*N
length_list[max_loc] = 0
while len(que) > 0:
	node = que.popleft()
	for node_next in tree[node]:
		if length_list[node_next] > length_list[node]:
			length_list[node_next] = length_list[node] + 1
			max_length = max(max_length, length_list[node_next])
			que.append(node_next)
max_length += 1

if max_length % 3 == 2:
	print("Second")
else:
	print("First")

Solution (Python):
def bfs(v):
  distance=[-1]*n
  distance[v]=0
  next=connection[v]
  next2=set()
  visited=[-1]*n
  visited[v]=1
  visitct=1
  ct=0
  while visitct!=n:
    ct+=1
    for i in range(len(next)):
      distance[next[i]]=ct
      visited[next[i]]=1
      visitct+=1
      for j in range(len(connection[next[i]])):
        if visited[connection[next[i]][j]]==-1:
          next2.add(connection[next[i]][j])
    next=list(next2)
    next2=set()
    
  return distance

n=int(input())
l=[list(map(int,input().split())) for i in range(n-1)]
connection=[[] for i in range(n)]
for i in range(n-1):
  connection[l[i][0]-1].append(l[i][1]-1)
  connection[l[i][1]-1].append(l[i][0]-1)
 
if max(bfs(bfs(0).index(max(bfs(0)))))%3==1:
  print('Second')
else:
  print('First')

Solution (Python):
def bfs(v):
  distance=[-1]*n
  distance[v]=0
  next=connection[v]
  next2=set()
  visited=[-1]*n
  visited[v]=1
  visitct=1
  ct=0
  while visitct!=n:
    ct+=1
    for i in range(len(next)):
      if visited[next[i]]==-1:
        distance[next[i]]=ct
        visited[next[i]]=1
        visitct+=1
        for j in range(len(connection[next[i]])):
          if visited[connection[next[i]][j]]==-1:
            next2.add(connection[next[i]][j])
    next=list(next2)
    next2=set()
    
  return distance
 
n=int(input())
l=[list(map(int,input().split())) for i in range(n-1)]
connection=[[] for i in range(n)]
for i in range(n-1):
  connection[l[i][0]-1].append(l[i][1]-1)
  connection[l[i][1]-1].append(l[i][0]-1)
 
if max(bfs(bfs(0).index(max(bfs(0)))))%3==1:
  print('Second')
else:
  print('First')

Solution (Python):
def main():
  def bfs(v):
    distance=[-1]*n
    distance[v]=0
    next=connection[v]
    next2=set()
    visited=[-1]*n
    visited[v]=1
    visitct=1
    ct=0
    while len(next)!=0 and visitct!=n:
      ct+=1
      for i in range(len(next)):
        if visited[next[i]]==-1:
          distance[next[i]]=ct
          visited[next[i]]=1
          visitct+=1
          for j in range(len(connection[next[i]])):
            if visited[connection[next[i]][j]]==-1:
              next2.add(connection[next[i]][j])
      next=list(next2)
      next2=set()
      
    return distance

  n=int(input())
  l=[list(map(int,input().split())) for i in range(n-1)]
  connection=[[] for i in range(n)]
  for i in range(n-1):
    connection[l[i][0]-1].append(l[i][1]-1)
    connection[l[i][1]-1].append(l[i][0]-1)

  if max(bfs(bfs(0).index(max(bfs(0)))))%3==1:
    print('Second')
  else:
    print('First')
if __name__ == '__main__':
    main()

Solution (Python):
def bfs(v):
  distance=[-1]*n
  distance[v]=0
  next=connection[v]
  next2=set()
  visited=[-1]*n
  visited[v]=1
  visitct=1
  ct=0
  while len(next)!=0 and visitct!=n:
    ct+=1
    for i in range(len(next)):
      if visited[next[i]]==-1:
        distance[next[i]]=ct
        visited[next[i]]=1
        visitct+=1
        for j in range(len(connection[next[i]])):
          if visited[connection[next[i]][j]]==-1:
            next2.add(connection[next[i]][j])
    next=list(next2)
    next2=set()
    
  return distance

n=int(input())
l=[list(map(int,input().split())) for i in range(n-1)]
connection=[[] for i in range(n)]
for i in range(n-1):
  connection[l[i][0]-1].append(l[i][1]-1)
  connection[l[i][1]-1].append(l[i][0]-1)

if max(bfs(bfs(0).index(max(bfs(0)))))%3==1:
  print('Second')
else:
  print('First')

Solution (Python):
def bfs(v):
  distance=[-1]*n
  distance[v]=0
  next=connection[v]
  next2=[]
  visited=[-1]*n
  visited[v]=1
  visitct=1
  ct=0
  while len(next)!=0 and visitct!=n:
    ct+=1
    for i in range(len(next)):
      if visited[next[i]]==-1:
        distance[next[i]]=ct
        visited[next[i]]=1
        visitct+=1
        for j in range(len(connection[next[i]])):
          if visited[connection[next[i]][j]]==-1:
            next2.append(connection[next[i]][j])
    next=next2
    next2=[]
    
  return distance

n=int(input())
l=[list(map(int,input().split())) for i in range(n-1)]
connection=[[] for i in range(n)]
for i in range(n-1):
  connection[l[i][0]-1].append(l[i][1]-1)
  connection[l[i][1]-1].append(l[i][0]-1)

if max(bfs(bfs(0).index(max(bfs(0)))))%3==1:
  print('Second')
else:
  print('First')

Solution (Python):
from collections import deque
N = int(input())
edges = [[] for _ in range(N)]
for _ in range(N-1):
    a, b = map(int, input().split())
    edges[a-1].append(b-1)
    edges[b-1].append(a-1)

def bfs(v0):
    dist = [-1]*N
    que = deque([v0])
    dist[v0] = 0
    while que:
        v = que.pop()
        d = dist[v]
        for nv in edges[v]:
            if dist[nv] < 0:
                que.append(nv)
                dist[nv] = d+1
    m = max(dist)
    v = dist.index(m)
    return v, m
u, _ = bfs(0)
_, dia = bfs(u)
if N == 1:
    print('First')
elif (dia+1-2)%3 == 0:
    print('Second')
else:
    print('First')

Solution (Python):
from heapq import heappush, heappop
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations,combinations
import sys
import bisect
import string



def I():
    return int(input())
def MI():
    return map(int,input().split())
def LI():
    return [int(i) for i in input().split()]
def LI_():
    return [int(i)-1 for i in input().split()]
def StoI():
    return [ord(i)-97 for i in input()]
def show(*inp,end='\n'):
    if show_flg:
        print(*inp,end=end)
YN=['Yes','No']
mo=10**9+7



show_flg=False


n=I()


g=[[] for i in range(1+n)]
v=[-1]*(1+n)

for i in range(n-1):
    a,b=LI_()
    g[a].append(b)
    g[b].append(a)

def dfs(cur,dep):
    mdep=0
    end=cur
    
    q=[]
    q.append((cur,dep))

    while q:
        cur,dep=q.pop()
        v[cur]=dep
        if dep>mdep:
            mdep=dep
            end=cur

        for nb in g[cur]:
            if v[nb]==-1:
                q.append((nb,dep+1))
    return mdep,end
    
dist,end=dfs(0,0)
v=[-1]*(1+n)
diam,beg=dfs(end,0)
show(end,beg,diam)
print(['First','Second'][diam%3==1])