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



Sample input:
3
1 2
2 3


Sample output:
First

Submission status: Accepted

Solution code:
from collections import deque
def dia(i):
	lst = [-1]*N
	lst[i] = 0
	q = deque([i])
	while q:
		c = q.popleft()
		l = lst[c]
		for i in A[c]:
			if lst[i] != -1:
				continue
			else:
				lst[i] = l+1
				q.append(i)
	return lst.index(max(lst))
def dia2(i):
	lst = [-1]*N
	lst[i] = 0
	q = deque([i])
	while q:
		c = q.popleft()
		l = lst[c]
		for i in A[c]:
			if lst[i] != -1:
				continue
			else:
				lst[i] = l+1
				q.append(i)
	return max(lst)+1
N = input()
A = [[] for i in range(N)]
for i in range(N-1):
	a2,b2 = map(int, raw_input().split())
	A[a2-1].append(b2-1)
	A[b2-1].append(a2-1)
if((dia2(dia(0))) % 3 == 2):
	print("Second")
else:
	print("First")

Submission status: Accepted

Solution code:
from collections import deque
import sys
readline = sys.stdin.readline
N = int(readline())
G = [[] for i in range(N)]
for i in range(N-1):
    a, b = map(int, readline().split())
    G[a-1].append(b-1)
    G[b-1].append(a-1)
def bfs(s):
    dist = [None]*N
    que = deque([s])
    dist[s] = 0
    while que:
        v = que.popleft()
        d = dist[v]
        for w in G[v]:
            if dist[w] is not None:
                continue
            dist[w] = d + 1
            que.append(w)
    d = max(dist)
    return dist.index(d), d
u, _ = bfs(0)
v, d = bfs(u)
print("Second" if d % 3 == 1 else "First")

Submission status: Accepted

Solution code:
from collections import defaultdict
from collections import deque

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

class Graph(object):

    def __init__(self):
        self.graph = defaultdict(list)

    def __len__(self):
        return len(self.graph)

    def add_edge(self, a, b):
        self.graph[a].append(b)


class breadth(object):
    def __init__(self, graph, s):
        self.g = graph.graph
        self.dist = defaultdict(lambda: float('inf'))
        self.dist[s] = 0
        self.visit = ["no" for i in range(len(graph) + 1)]
        self.visit[s] = "yes"

        self.Q = deque()
        self.Q.append([self.dist[s], s])

        while self.Q:
            dist_u, u = self.Q.popleft()
            for v in self.g[u]:
                if self.visit[v] == "yes":
                    continue
                else:
                    self.dist[v] = dist_u + 1
                    self.visit[v] = "yes"
                    self.Q.append([self.dist[v], v])


N = int(input())
if N == 1:
	print("First")
else:
	g_a = Graph()
	for i in range(N - 1):
		a, b = getlist()
		g_a.add_edge(a, b)
		g_a.add_edge(b, a)
	
	s = 1
	E = breadth(g_a, s)
	x = 0
	for i in E.dist:
		if E.dist[i] > x:
			x = E.dist[i]
			y = i
	F = breadth(g_a, y)
	x = 0
	for i in F.dist:
		if F.dist[i] > x:
			x = F.dist[i]
			y = i

	if x % 3 == 0 or x % 3 == 2:
		print("First")
	else:
		print("Second")

Submission status: Accepted

Solution code:
import sys
range = xrange

inp = [int(x) for x in sys.stdin.read().split()]
ii = 0

n = inp[ii]
ii += 1

coupl = [[] for _ in range(n)]
for _ in range(n-1):
    u,v = inp[ii]-1, inp[ii+1]-1
    ii += 2
    
    coupl[u].append(v)
    coupl[v].append(u)

root = 0
for _ in range(2):
    depth = [-1]*n
    depth[root] = 1
    Q = [root]
    for node in Q:
        d = depth[node]
        for nei in coupl[node]:
            if depth[nei]==-1:
                depth[nei] = d+1
                Q.append(nei)

    root = max(range(n), key = lambda i:depth[i])
dia = depth[root]
if dia%3!=2:
    print 'First'
else:
    print 'Second'

Submission status: Accepted

Solution code:
import sys
range = xrange
input = sys.stdin.readline

n = int(input())
coupl = [[] for _ in range(n)]
for _ in range(n-1):
    u,v = [int(x)-1 for x in input().split()]
    
    coupl[u].append(v)
    coupl[v].append(u)

root = 0
for _ in range(2):
    depth = [-1]*n
    depth[root] = 1
    Q = [root]
    for node in Q:
        d = depth[node]
        for nei in coupl[node]:
            if depth[nei]==-1:
                depth[nei] = d+1
                Q.append(nei)

    root = max(range(n), key = lambda i:depth[i])
dia = depth[root]
if dia%3!=2:
    print 'First'
else:
    print 'Second'

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**7)
input = sys.stdin.readline

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


def dfs(v, dist, memo):
    memo[v] = dist
    for nv in graph[v]:
        if memo[nv] >= 0:
            continue
        dfs(nv, dist+1, memo)

memo = [-1] * n
dfs(0, 0, memo)

node = 0
dist = 0
for i in range(n):
    if memo[i] > dist:
        dist = memo[i]
        node = i

memo = [-1] * n
dfs(node, 0, memo)

dist = max(memo)
count = dist + 1

dp = [0] * (count + 10)
dp[0] = 0
dp[1] = 1
dp[2] = 0
dp[3] = 1
dp[4] = 1


if count >= 5:
    for i in range(5, count+1):
        if dp[i-2] == 1 and dp[i-1] == 1:
            dp[i] = 0
        else:
            dp[i] = 1

if dp[count]:
    print("First")
else:
    print("Second")

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(300000)

def dfs(idx, con, visited):
    visited[idx] = True
    max_depth = 0
    max_len = 0
    depths = []
    if idx >= len(con):
        return max_depth, max_len
    for v in con[idx]:
        if v < len(visited) and not visited[v]:
            max_d, max_l = dfs(v, con, visited)
            max_len = max(max_len, max_l)
            depths.append(max_d + 1)
    if len(depths) > 0:
        depths.sort(reverse=True)
        max_depth = depths[0]
        if len(depths) > 1:
            max_len = max(max_len, depths[0] + depths[1])
        else:
            max_len = max(max_len, depths[0])
    visited[idx] = False
    return max_depth, max_len


def solve(N: int, A: "List[int]", B: "List[int]"):
    con = [[] for _ in range(N)]
    for i in range(len(A)):
        a = A[i] - 1
        b = B[i] - 1
        con[a].append(b)
        con[b].append(a)
    #print(con)
    visited = [False] * N
    max_depth, max_len = dfs(0, con, visited)
    #print(max_len)
    if (max_len + 1) % 3 == 2:
        ret = 'Second'
    else:
        ret = 'First'
    print(ret)
    return


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    a = [int()] * (N-1)  # type: "List[int]" 
    b = [int()] * (N-1)  # type: "List[int]" 
    for i in range(N-1):
        a[i] = int(next(tokens))
        b[i] = int(next(tokens))
    solve(N, a, b)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N = int(input())
if N == 1:
  print("First")
  exit()
ab = [list(map(int, input().split())) for _ in range(N - 1)]

R = {}
for a, b in ab:
  if a - 1 in R:
    R[a - 1].append(b - 1)
  else:
    R[a - 1] = [b - 1]
  if b - 1 in R:
    R[b - 1].append(a - 1)
  else:
    R[b - 1] = [a - 1]

L = [0] * N
L[0] = 1
F = []
RL = {}
RL[1] = [0]
RL[2] = []
for i in R[0]:
  F.append(i)
  L[i] = 2
  RL[2].append(i)

k = 2
while F != []:
  k += 1
  Ft = []
  RL[k] = []
  for i in F:
    for j in R[i]:
      if L[j] == 0:
        L[j] = k
        Ft.append(j)
        RL[k].append(j)
  F = Ft

d = 0
D = [0] * N
for i in range(k - 1, 0, -1):
  for j in RL[i]:
    for k in R[j]:
      if L[k] == i - 1:
        if D[k] == 0:
          D[k] = D[j] + 1
          d = max(d, D[j] + 1)
        else:
          d = max(d, D[j] + D[k] + 1)
          D[k] = max(D[k], D[j] + 1)

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

Submission status: Accepted

Solution code:
N = int(input())
Edge = [[] for _ in range(N+1)]
for _ in range(N-1):
    a, b = map(int, input().split())
    Edge[a].append(b)
    Edge[b].append(a)
stack = [1]
dist = [0]*(N+1)
visited = set([1])
while stack:
    vs = stack.pop()
    for e in Edge[vs]:
        if e in visited:
            continue
        visited.add(e)
        dist[e] = 1 + dist[vs]
        stack.append(e)
s = dist.index(max(dist))
stack = [s]
dist = [0]*(N+1)
visited = set([s])
while stack:
    vs = stack.pop()
    for e in Edge[vs]:
        if e in visited:
            continue
        visited.add(e)
        dist[e] = 1 + dist[vs]
        stack.append(e)
dia = max(dist) + 1
f = 'First'
s = 'Second'
if dia == 0:
    print(s)
elif dia == 1:
    print(f)
elif dia == 2:
    print(s)
else:
    if dia % 3 == 2:
        print(s)
    else:
        print(f)

Submission status: Accepted

Solution code:
N = int(input())
ab = [list(map(int,input().split())) for _ in range(N-1)]

connect = [[] for _ in range(N)]
for a,b in ab:
    connect[a-1].append(b-1)
    connect[b-1].append(a-1)

q = [0]
k = 0
d = [-1] * N
d[0] = 1
while k < len(q):
    i = q[k]
    di = d[i]
    for j in connect[i]:
        if d[j] == -1:
            d[j] = di + 1
            q.append(j)
    k += 1
q = [d.index(max(d))]
k = 0
d = [-1] * N
d[q[0]] = 1
while k < len(q):
    i = q[k]
    di = d[i]
    for j in connect[i]:
        if d[j] == -1:
            d[j] = di + 1
            q.append(j)
    k += 1

size = max(d)
if size == 1:
    print("First")
elif size == 2:
    print("Second")
elif size%3 == 2:
    print("Second")
else:
    print("First")

Submission status: Accepted

Solution code:
# coding:utf-8

import sys
from collections import deque, defaultdict

INF = float('inf')
MOD = 10 ** 9 + 7
dy, dx = (0, -1, 0, 1), (1, 0, -1, 0)

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x) - 1 for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def II(): return int(sys.stdin.readline())
def SI(): return input()


def main():
    n = II()
    G = defaultdict(list)
    for _ in range(n - 1):
        a, b = LI_()
        G[a].append(b)
        G[b].append(a)

    def DFS(start):
        stack = deque([start])
        dist = [INF] * n
        dist[start] = 0
        max_dist = 0
        farthest_v = start
        while stack:
            curr = stack.pop()

            for next in G[curr]:
                if dist[next] != INF:
                    continue
                dist[next] = dist[curr] + 1
                stack.append(next)
                if dist[next] > max_dist:
                    max_dist = dist[next]
                    farthest_v = next

        return farthest_v, max_dist

    v, d = DFS(0)
    u, d = DFS(v)

    # print(v + 1, u + 1, d)
    if d == 1: d = 0
    print('First' if d % 3 != 1 else 'Second')
    # print('First' if d % 2 else 'Second')

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
input=sys.stdin.readline
from collections import deque
n=int(input())
Edges=[[] for _ in range(n)]
for _ in range(n-1):
    a,b=map(int,input().split())
    a-=1; b-=1
    Edges[a].append(b)
    Edges[b].append(a)

def bfs(v):
    Visited=[False]*n
    q=deque()
    q.append((v,0))
    Visited[v]=True
    ret=(v,0)
    while q:
        fr,dist=q.popleft()
        if ret[1]<dist:
            ret=(fr,dist)
        for to in Edges[fr]:
            if not Visited[to]:
                Visited[to]=True
                q.append((to,dist+1))
    return ret

(v,dist)=bfs(0)
#print(v,dist)
(v,dist)=bfs(v)
#print(v,dist)
print('Second' if dist%3==1 else 'First')

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

N=int(input())
EDGE=[list(map(int,input().split())) for i in range(N-1)]

EDGELIST=[[] for i in range(N+1)]

for x,y in EDGE:
    EDGELIST[x].append(y)
    EDGELIST[y].append(x)

from collections import deque
H=[-1]*(N+1)
H[1]=0

QUE=deque([1])

while QUE:
    x=QUE.pop()
    for to in EDGELIST[x]:
        if H[to]==-1:
            H[to]=H[x]+1
            QUE.append(to)


QUE=deque([H.index(max(H))])

H=[-1]*(N+1)
H[QUE[0]]=0

while QUE:
    x=QUE.pop()
    for to in EDGELIST[x]:
        if H[to]==-1:
            H[to]=H[x]+1
            QUE.append(to)

HEIGHT=max(H)

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

Submission status: Accepted

Solution code:
from collections import deque

# input
N = int(input())
G = dict()
for i in range(N):
    G[i] = dict()

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

# find diameter of the tree
# 2 times dijkstra
queue1 = deque([0])
d1 = [1000000] * N
d1[0] = 0

while len(queue1) > 0:
    p = queue1.popleft()
    for q in G[p].keys():
        if d1[q] > d1[p] + 1:
            d1[q] = d1[p] + 1
            queue1.append(q)
# find farthest
far = 0
dd = 0
for i in range(N):
    if d1[i] > dd:
        far = i
        dd = d1[i]

queue2 = deque([far])
d2 = [1000000] * N
d2[far] = 0

while len(queue2) > 0:
    p = queue2.popleft()
    for q in G[p].keys():
        if d2[q] > d2[p] + 1:
            d2[q] = d2[p] + 1
            queue2.append(q)
diam = max(d2)
# print(diam)
if diam % 3 == 1:
    print("Second")
else:
    print("First")

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(300000)
def input():
	return sys.stdin.readline()[:-1]

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

vis = [-1 for _ in range(n)]
def dfs(start):
	s = [start]
	while s:
		l = s.pop()
		for c in adj[l]:
			if vis[c] < 0:
				s.append(c)
				vis[c] = vis[l] + 1
	return

vis[0] = 0
dfs(0)

dia = -1
dia_ind = -1
for i in range(n):
	if vis[i] > dia:
		dia = vis[i]
		dia_ind = i

vis = [-1 for _ in range(n)]
vis[dia_ind] = 0
dfs(dia_ind)

dia = -1
dia_ind = -1
for i in range(n):
	if vis[i] > dia:
		dia = vis[i]
		dia_ind = i

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

Submission status: Accepted

Solution code:
#!usr/bin/env python3
from collections import defaultdict
from collections import deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS():return list(map(list, sys.stdin.readline().split()))
def S(): return list(sys.stdin.readline())[:-1]
def IR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = I()
    return l
def LIR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = LI()
    return l
def SR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = S()
    return l
def LSR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = LS()
    return l
sys.setrecursionlimit(1000000)
mod = 1000000007

#A
def A():
    h,w = LI()
    a = [sys.stdin.readline() for i in range(h)]
    s = 0
    p = [None for i in range(w*h)]
    q = [None for j in range(w*h)]
    l = 0
    for i in range(h):
        for j in range(w):
            if a[i][j] == "#":
                p[s] = (i,j)
                s += 1
            else:
                q[l] = (i,j)
                l += 1
    if s == h*w:
        print(0)
        quit()
    ans = 0
    M = w*h
    for i,j in q[:h*w-s]:
        m = M
        for x,y in p[:s]:
            if abs(i-x)+abs(j-y) < m:
                m = abs(i-x)+abs(j-y)
        if m > ans:
            ans = m
    print(ans)
    return

#B
def B():
    h,w,n = LI()
    sy,sx = LI()
    sy -= 1
    sx -= 1
    s = S()
    t = S()
    ks = list("LRUD")
    kt = list("RLDU")
    ds = [[0,-1],[0,1],[-1,0],[1,0]]
    dt = [[0,1],[0,-1],[1,0],[-1,0]]
    for i in range(4):
        y,x = [sy,sx]
        for j in range(n):
            if s[j] == ks[i]:
                y+=ds[i][0]
                x+=ds[i][1]
                if y < 0 or y >= h or x < 0 or x >= w:
                    print("NO")
                    quit()
            if t[j] == kt[i]:
                y += dt[i][0]
                x += dt[i][1]
                if y < 0:y = 0
                elif y >= h:y = h-1
                elif x < 0:x=0
                elif x >= w:x=w-1
    print("YES")
    return

#C
def C():
    def dijkstra(s):
        d = [float("inf") for i in range(n)]
        d[s] = 0
        q=[[0,s]]
        while q:
            dx,x = heappop(q)
            for y in v[x]:
                if dx+1 < d[y]:
                    d[y] = dx+1
                    heappush(q,[d[y],y])
        return d
    n = I()
    v = [[] for i in range(n)]
    for i in range(n-1):
        a,b = LI()
        a -= 1
        b -= 1
        v[a].append(b)
        v[b].append(a)
    d = dijkstra(0)
    l = d.index(max(d))
    d = dijkstra(l)
    m = max(d)+1
    if m%3 == 2:
        print("Second")
    else:
        print("First")
    return

#D
def D():
    n = I()
    return

#E
def E():
    n = I()
    return

#F
def F():
    n = I()
    return

#Solve
if __name__ == "__main__":
    C()

Submission status: Accepted

Solution code:
from collections import deque
import sys
sys.setrecursionlimit(10**6)
readline = sys.stdin.readline
N = int(readline())
if N == 1:
    print("First")
    exit(0)
G = [[] for i in range(N)]
for i in range(N-1):
    a, b = map(int, readline().split())
    G[a-1].append(b-1)
    G[b-1].append(a-1)
def bfs(s):
    dist = [None]*N
    que = deque([s])
    dist[s] = 0
    while que:
        v = que.popleft()
        d = dist[v]
        for w in G[v]:
            if dist[w] is not None:
                continue
            dist[w] = d + 1
            que.append(w)
    d = max(dist)
    return dist.index(d), d
u, _ = bfs(0)
v, d = bfs(u)

memo = [-1]*(d+2)
memo[0] = 0
memo[1] = 1
memo[2] = 0
for i in range(3, d+2):
    if memo[i-1] == 0 or memo[i-2] == 0:
        memo[i] = 1
    else:
        memo[i] = 0
print("First" if memo[d+1] else "Second")

Submission status: Accepted

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

from collections import deque
def bfs(s):
    dist = [None]*N
    que = deque([s])
    dist[s] = 0
    while que:
        v = que.popleft()
        d = dist[v]
        for w in E[v]:
            if dist[w] is not None:
                continue
            dist[w] = d + 1
            que.append(w)
    d = max(dist)
    return dist.index(d), d
u, _ = bfs(0)
v, d = bfs(u)
#print(d)
if d%3==1:
    print("Second")
else:
    print("First")

Submission status: Accepted

Solution code:
from sys import stdin
def main():
    n = int(stdin.readline())
    e = [[] for _ in xrange(n)]
    for line in stdin:
        x, y = map(int, line.split())
        x -= 1
        y -= 1
        e[x].append(y)
        e[y].append(x)
    d = [None] * n
    st = []
    pu = st.append
    po = st.pop
    pu(0)
    d[0] = 0
    while st:
        x = po()
        for y in e[x]:
            if d[y] is None:
                d[y] = d[x] + 1
                pu(y)
    y = -1
    for i, x in enumerate(d):
        if y < x:
            y = x
            j = i
    d = [None] * n
    pu(j)
    d[j] = 0
    while st:
        x = po()
        for y in e[x]:
            if d[y] is None:
                d[y] = d[x] + 1
                pu(y)
    x = max(d)
    print 'Second' if x % 3 == 1 else 'First'
main()

Submission status: Accepted

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools
import random

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def pe(s): return print(str(s), file=sys.stderr)

def main():
    n = I()
    aa = LLI()
    e = collections.defaultdict(set)
    for a,b in aa:
        e[a].add(b)
        e[b].add(a)


    def search(s):
        d = collections.defaultdict(lambda: inf)
        d[s] = 0
        q = []
        heapq.heappush(q, (0, s))
        v = collections.defaultdict(bool)
        while len(q):
            k, u = heapq.heappop(q)
            if v[u]:
                continue
            v[u] = True

            for uv in e[u]:
                if v[uv]:
                    continue
                vd = k + 1
                if d[uv] > vd:
                    d[uv] = vd
                    heapq.heappush(q, (vd, uv))

        return d

    d1 = search(1)
    mv = -1
    mk = 1
    for k,v in d1.items():
        if mv < v:
            mv = v
            mk = k
    d2 = search(mk)
    mv = max(d2.values())

    if (mv + 1) % 3 == 2:
        return 'Second'

    return 'First'


print(main())

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(2 * 10 ** 5 + 5)


def dfs(v, p, links):
    farthest_d = 0
    farthest_v = v

    for u in links[v]:
        if u == p:
            continue
        res_d, res_v = dfs(u, v, links)
        if res_d > farthest_d:
            farthest_d = res_d
            farthest_v = res_v
    return farthest_d + 1, farthest_v


def solve(n, links):
    if n == 1:
        return True

    d, v = dfs(0, -1, links)
    d, v = dfs(v, -1, links)
    if (d + 1) % 3 == 0:
        return False
    return True


n = int(input())
links = [set() for _ in [0] * n]
for line in sys.stdin:
    a, b = map(int, line.split())
    a -= 1
    b -= 1
    links[a].add(b)
    links[b].add(a)
print('First' if solve(n, links) else 'Second')

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline
from collections import *

def bfs(s):
    dist = [-1]*N
    dist[s] = 0
    q = deque([s])
    
    while q:
        v = q.popleft()
        
        for nv in G[v]:
            if dist[nv]==-1:
                dist[nv] = dist[v]+1
                q.append(nv)
    
    return dist

N = int(input())
G = [[] for _ in range(N)]

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

dist = bfs(0)
M = 0

for i in range(N):
    if dist[i]>M:
        M = dist[i]
        s = i

d = max(bfs(s))+1
dp = [False]*(d+1)
dp[1] = True

for i in range(3, d+1):
    dp[i] |= not dp[i-1]
    dp[i] |= not dp[i-2]

if dp[d]:
    print('First')
else:
    print('Second')

Submission status: Runtime Error

Solution code:
from collections import deque
printn = lambda x: print(x,end='')
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split())
ins = lambda : input().strip()
DBG = True # and False
BIG = 10**18
R = 10**9 + 7

def ddprint(x):
  if DBG:
    print(x)

n = inn()
dst = [{} for i in range(n+1)]
for i in range(n-1):
    u,v = inm()
    dst[u][v] = dst[v][u] = 1
s = 1
d1 = [-1]*(n+1)
d1[s] = 0
q = deque([s])
while len(q)>0:
    x = q.popleft()
    d = d1[x]
    for u in dst[x]:
        if d1[u]<0:
            d1[u] = d+1
            q.append(u)
mx = 0
for i in range(1,n+1):
    if d1[i]>mx:
        mx = d1[i]
        mxi = i

s = mxi
d1 = [-1]*(n+1)
d1[s] = 0
q = deque([s])
while len(q)>0:
    x = q.popleft()
    d = d1[x]
    for u in dst[x]:
        if d1[u]<0:
            d1[u] = d+1
            q.append(u)
if max(d1)%3==1:
    print('Second')
else:
    print('First')

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline


def dfs(V, start):
    q = [(start, 0)]
    used = [False] * (n+1)
    farthest = 0
    pos = 0

    while q:
        s, cost = q.pop()
        if farthest < cost:
            pos = s
            farthest = cost
        used[s] = True
        for t, c in V[s].items():
            if used[t]:
                continue
            q.append((t, cost + c))
    
    return farthest, pos


if __name__ == "__main__":
    n = int(input())
    V = {i:dict() for i in range(1, n+1)}

    for _ in range(n - 1):
        s, t = map(int, input().split())
        V[s][t] = 1
        V[t][s] = 1

    d = dfs(V, dfs(V, 1)[1])[0]
    if d==0:
        print("First")
    elif d==1:
        print("Second")
    elif d==2:
        print("First")
    elif (d-1)%3==0:
        print("Second")
    else:
        print("First")

Submission status: Runtime Error

Solution code:
# AGC033C

import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


from collections import defaultdict
n = int(input())
ns = defaultdict(set)
for _ in range(n-1):
    u,v = map(int, input().split())
    ns[u-1].add(v-1)
    ns[v-1].add(u-1)

def bfs(start):
    from queue import deque
    q = deque([start])
    seen = [None] * n
    seen[start] = 0
    dd = 0
    target = None
    while q:
        u = q.pop()
        d = seen[u]
        if d>dd:
            dd = d
            target = u
        for v in ns[u]:
            if seen[v] is None:
                seen[v] = d + 1
                q.appendleft(v)
    return target, dd
target, tmp = bfs(0)
_, d = bfs(target)
if (d-1)%3!=0:
    print("First")
else:
    print("Second")

Submission status: Runtime Error

Solution code:
from sys import stdin, stdout

def main():
    N = (int)(stdin.readline())
    graph = dict()

    for i in range(N-1):
        edge = stdin.readline().split()
        ai = (int)(edge[0])
        bi = (int)(edge[1])

        if ai in graph.keys():
            graph[ai].append(bi)
        else:
            graph[ai] = [bi]
        
        if bi in graph.keys():
            graph[bi].append(ai)
        else:
            graph[bi] = [ai]

    mid_node = bfs(graph, 1)[0]
    
    longest_path = bfs(graph, mid_node)[1]
    
    if longest_path % 3 == 1:
        print("second")
    else:
        print("first")

def bfs(graph, node):

    result = -1
    last_level = set()
    visited = set()

    last_level.add(node)
    visited.add(node)

    length = 0

    while len(last_level) > 0:
        
        new_level = set()

        length += 1

        for last_node in last_level:
            result = last_node
            for neighbor in graph[last_node]:
                if neighbor not in visited:
                    new_level.add(neighbor)
                    visited.add(neighbor)
        last_level = new_level
    
    return result, length - 1

if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
from collections import deque
import sys
input = sys.stdin.buffer.readline

N = int(input())
edges = [[] for _ in range(N)]

for _ in range(N - 1):
    fr, to = map(lambda a: int(a) - 1, input().split())
    edges[fr].append(to)
    edges[to].append(fr)

def calcDist(fr):
    minDist = [10**18] * N
    que = deque([(fr, 0)])

    while que:
        now, dist = que.pop()

        if minDist[now] < dist:
            continue
        minDist[now] = dist

        for to in edges[now]:
            if minDist[to] > dist + 1:
                minDist[to] = dist + 1
                que.append((to, dist + 1))

    return minDist

D0 = calcDist(0)
R = max(calcDist(D0.index(max(D0)))) + 1

canFirstWin = [False] * (R + 1)
canFirstWin[1] = True
canFirstWin[2] = False

for i in range(3, R + 1):
    canFirstWin[i] = not(canFirstWin[i - 1] and canFirstWin[i - 2])

print('First' if canFirstWin[R] else 'Second')

Submission status: Runtime Error

Solution code:
H,W,T = list(map(int,input().split()))

mod = 10**9

S = [input() for i in range(H)]
e_list = [[] for i in range(H*W)]
def z(i,j):
    return i*W + j
N = H*W
for i in range(H):
    for j in range(W):
        if i!=H-1:
            if S[i+1][j]=='.' or S[i+1][j]=="S" or S[i+1][j]=="G":
                e_list[z(i,j)].append((z(i+1,j),1))
            else:
                e_list[z(i,j)].append((z(i+1,j),mod))
        if j!=W-1:
            if S[i][j+1]=='.' or S[i][j+1]=="S" or S[i][j+1]=="G":
                e_list[z(i,j)].append((z(i,j+1),1))
            else:
                e_list[z(i,j)].append((z(i,j+1),mod))
        if i!=0:
            if S[i-1][j]=='.' or S[i-1][j]=="S" or S[i-1][j]=="G":
                e_list[z(i,j)].append((z(i-1,j),1))
            else:
                e_list[z(i,j)].append((z(i-1,j),mod))
        if j!=0:
            if S[i][j-1]=='.' or S[i][j-1]=="S" or S[i][j-1]=="G":
                e_list[z(i,j)].append((z(i,j-1),1))
            else:
                e_list[z(i,j)].append((z(i,j-1),mod))
#dijkstra
#you need to prepare e_list = [(orient,dist)]

import heapq

vi = 0
INF = float('inf')
min_d_list = [INF]*N
min_d_list[vi] = 0
prev_list = [-1]*N
q = []
for i in range(N):
    heapq.heappush(q,(min_d_list[i],i))

while len(q)>0:
    d,v = heapq.heappop(q)
    for e in e_list[v]:
        v1,d1 = e
        if min_d_list[v1] > d+d1:
            min_d_list[v1] = d+d1
            prev_list[v1] = v
            heapq.heappush(q,(d+d1,v1))

x = min_d_list[H*W-1]%mod
y = min_d_list[H*W-1]//mod

print((T-x)//y)

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.buffer.readline
from collections import deque

def main():
    N = int(input())
    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)
        
    for i in range(N):
        if len(edge[i]) == 1:
            st = i
            break
    dep = [-1 for _ in range(N)]
    dep[st] = 0
    
    q = deque([st])
    while q:
        now = q.pop()
        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()