Problem:


Score : 400 points

Problem Statement

Fennec and Snuke are playing a board game.

On the board, there are N cells numbered 1 through N, and N-1 roads, each connecting two cells. Cell a_i is adjacent to Cell b_i through the i-th road. Every cell can be reached from every other cell by repeatedly traveling to an adjacent cell. In terms of graph theory, the graph formed by the cells and the roads is a tree.

Initially, Cell 1 is painted black, and Cell N is painted white. The other cells are not yet colored.
Fennec (who goes first) and Snuke (who goes second) alternately paint an uncolored cell.
More specifically, each player performs the following action in her/his turn:

Fennec: selects an uncolored cell that is adjacent to a black cell, and paints it black.

Snuke: selects an uncolored cell that is adjacent to a white cell, and paints it white.

A player loses when she/he cannot paint a cell. Determine the winner of the game when Fennec and Snuke play optimally.

Constraints

2 \leq N \leq 10^5

1 \leq a_i, b_i \leq N

The given graph is a tree.

Input

Input is given from Standard Input in the following format:

N
a_1 b_1
:
a_{N-1} b_{N-1}

Output

If Fennec wins, print Fennec; if Snuke wins, print Snuke.

Sample Input 1

7
3 6
1 2
3 1
7 4
5 7
1 4

Sample Output 1

Fennec

For example, if Fennec first paints Cell 2 black, she will win regardless of Snuke's moves.

Sample Input 2

4
1 4
4 2
2 3

Sample Output 2

Snuke



Sample input:
7
3 6
1 2
3 1
7 4
5 7
1 4


Sample output:
Fennec

Submission status: Accepted

Solution code:
import heapq
import sys

input = sys.stdin.readline

def dijlstra_heap(N,s,edge):
    d = [float('inf')] * N
    used = [True] * N
    d[s] = 0
    edgelist = []
    for a, b in edge[s]:
        heapq.heappush(edgelist, a*(10**6)+b)
    while len(edgelist):
        minedge = heapq.heappop(edgelist)
        if not used[minedge%(10**6)]:
            continue
        v = minedge % (10 ** 6)
        d[v] = minedge // (10 ** 6)
        used[v] = False
        for e in edge[v]:
            if used[e[1]]:
                heapq.heappush(edgelist,(e[0]+d[v])*(10**6)+e[1])
    return d

def main():
    N = int(input())
    edge = [[] for i in range(N)]
    for i in range(N-1):
        a, b = map(int, input().split())
        a -= 1
        b -= 1
        edge[a].append([1,b])
        edge[b].append([1,a])
    d0 = dijlstra_heap(N,0,edge)
    dn = dijlstra_heap(N,N-1,edge)

    f_cnt = 0
    s_cnt = 0
    for i in range(N):
        if d0[i] <= dn[i]:
            f_cnt += 1
        else:
            s_cnt += 1

    if f_cnt > s_cnt:
        print('Fennec')
    else:
        print('Snuke')


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
N = int(input())
tree = [[] for i in range(N+1)]

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

dist_fennec = [100001] * (N+1)
dist_snuke = [100001] * (N+1)
q = [1]
dist_fennec[1] = 0
while q:
    now = q.pop()
    for next in tree[now]:
        if dist_fennec[next] == 100001:
            dist_fennec[next] = dist_fennec[now] + 1
            q.append(next)

q = [N]
dist_snuke[N] = 0
while q:
    now = q.pop()
    for next in tree[now]:
        if dist_snuke[next] == 100001:
            dist_snuke[next] = dist_snuke[now] + 1
            q.append(next)

fennec, snuke = 0, 0
for i in range(1, N+1):
    if dist_snuke[i] >= dist_fennec[i]:
        fennec += 1
    else:
        snuke += 1

if fennec > snuke:
    print("Fennec")
else:
    print("Snuke")

Submission status: Accepted

Solution code:
from sys import setrecursionlimit
setrecursionlimit(10000000)

def solve():
    N = int(input())
    adj = [list() 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)

    # path
    goal = N-1
    path = [0]
    candidates = [adj[0][:]]
    while path[-1] != goal:
        while not candidates[-1]:
            candidates.pop()
            path.pop()
        u = candidates[-1].pop()
        candidates.append([n for n in adj[u] if n != path[-1]])
        path.append(u)

    black = path[(len(path)-1)//2]
    white = path[(len(path)-1)//2+1]

    # count
    path = [black]
    candidates = [[n for n in adj[black] if n != white]]
    cnt = 0
    try:
        while True:
            while not candidates[-1]:
                cnt += 1
                candidates.pop()
                path.pop()
            u = candidates[-1].pop()
            candidates.append([n for n in adj[u] if n != path[-1]])
            path.append(u)
    except IndexError:
        pass
    bscore = cnt
    print('Fennec' if bscore*2 > N else 'Snuke')


if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:

import math
import sys
sys.setrecursionlimit(1000000)
N = int(input())
graph = {}
SCORE = 0
def dfs(visted,v,depth):
    visted[v] = depth
    for next_v in graph[v]:
        if  visted[next_v]  == -1 :
            dfs(visted,next_v,depth + 1)




for _ in range(N-1):
    a,b = map(int,input().split(" "))
    if a not in graph:
        graph[a] = [b]
    else:
        graph[a].append(b)

    if b not in graph:
        graph[b] = [a]
    else:
        graph[b].append(a)

vF = [-1] * (N + 1)
vF[1] = 0
dfs(vF,1,0)
# print(vF)

vS = [-1] * (N + 1)
vS[N] = 0

dfs(vS,N,0)
# print(vS)

fc = 0
sc = 0

for f,s in zip(vF[1:N + 1],vS[1:N + 1]):
    if f <= s:
        fc += 1
    else:
        sc += 1

# print(fc,sc)
if fc > sc:
    print("Fennec")
else:
    print("Snuke")

Submission status: Accepted

Solution code:
class UnionFind:
    def __init__(self, n):
        self.par = [-1 for i in range(n+1)]
        self.rank = [0] * (n+1)

    # 検索
    def find(self, x):
        if self.par[x] < 0:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    # 併合
    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if not x==y: # 根が同じでない場合のみ併合する
            if self.rank[x] < self.rank[y]:
                self.par[y] += self.par[x] # 要素数を併合
                self.par[x] = y # 根を付け替えている
            else:
                self.par[x] += self.par[y]
                self.par[y] = x
                if self.rank[x] == self.rank[y]:
                    self.rank[x] += 1
        
    # 同じ集合に属するか判定
    def same_check(self, x, y):
        return self.find(x) == self.find(y) 

def main():
    import sys
    input = sys.stdin.readline
    
    N = int(input())
    from collections import defaultdict,deque
    G = defaultdict(list)
    D = []
    for i in range(N-1):
        a, b = map(int,input().split())
        D.append([a,b])
        G[a].append(b)
        G[b].append(a)
    
    que = deque()
    que.append(1)
    visited = {}
    oya = [-1]*(10**5+1)
    while que != deque():
        v = que.pop()
        visited[v] = 1
        if v == N:
            break
        else:
            for i in G[v]:
                if not i in visited:
                    oya[i] = v
                    que.append(i)
    now = N
    path = []
    while now != -1:
        path.append(now)
        now = oya[now]
    path = path[::-1]
    #print(path)
    L = len(path)
    if L%2==0:
        d1,d2 = path[L//2-1],path[L//2]
    else:
        d1,d2 = path[L//2],path[L//2+1]
    G2 = UnionFind(N)
    
    for i in D:
        a,b = i
        if not {a,b} == {d1,d2}:
            G2.union(a,b)
    one = -G2.par[G2.find(1)]
    enu = -G2.par[G2.find(N)]
    
    if one>enu:
        print("Fennec")
    else:
        print("Snuke")
    

main()

Submission status: Accepted

Solution code:
from heapq import heappush, heappop
from collections import defaultdict

def dijkstra(V, E, s):
    '''
    Input:
        V = list(range(N))
        E = defaultdict(dict)
        s (in V) : start vertex
    Output:
        dist: the list of the minimum cost from s to arbitrary vertex v in the given graph
    '''
    INF = float('inf')
    dist = {v: INF for v in V}
    heap = []
    dist[s] = 0; rem = len(V);
    heappush(heap, (0, s))
    while heap and rem:
        d, v = heappop(heap)
        # don't need to check when the stored value is greater than provisional distance
        if d > dist[v]: continue
        rem -= 1;
        for u, c in E[v].items():
            temp = d + c
            if temp < dist[u]:
                dist[u] = temp
                heappush(heap, (temp, u))
    return dist

N = int(input())
V = list(range(1, N+1))
E = defaultdict(dict)
for _ in range(N-1):
    a, b = map(int, input().split())
    E[a][b] = 1
    E[b][a] = 1
fen = dijkstra(V, E, 1)
sun = dijkstra(V, E, N)
black, white = 0, 0
for v in V:
    if fen[v] <= sun[v]: black += 1
    else: white += 1
print('Fennec' if black > white else 'Snuke')

Submission status: Accepted

Solution code:
N = int(input())
import sys

sys.setrecursionlimit(N+10)
ab = [[] for _ in range(N)]

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

dF = [0] * N
dS = [0] * N
def dfs(now, d, dlist, visited):
    
    if visited[now] == False:
        dlist[now] = d
        visited[now] = True

        for next in ab[now]:
            dfs(next, d+1, dlist, visited)


vF = [False] * N
dfs(0,0,dF, vF)
vS = [False] * N
dfs(N-1, 0, dS, vS)

cnt_F = 0
cnt_S = 0
for i in range(N):
    if dF[i] <= dS[i]:
        cnt_F += 1
    else:
        cnt_S += 1

#print(dF, dS)
if cnt_F > cnt_S:
    print("Fennec")
else:
    print("Snuke")

Submission status: Accepted

Solution code:
# ARC078D - Fennec VS. Snuke (ABC067D)
from collections import deque


def bfs(s: int, d: "List[int]") -> None:
    q = deque([s])
    while q:
        v = q.popleft()
        for u in G[v]:
            if not d[u]:
                q.append(u)
                d[u] = d[v] + 1


def main():
    global G, DB, DW
    N, *E = map(int, open(0).read().split())
    G = [[] for _ in range(N + 1)]
    for i in range(0, (N - 1) * 2, 2):
        v, u = E[i : i + 2]
        G[v] += [u]
        G[u] += [v]
    DB, DW = [0] * (N + 1), [0] * (N + 1)
    bfs(1, DB), bfs(N, DW)
    b, w = 0, 0
    for i, j in zip(DB[1:], DW[1:]):
        if i <= j:
            b += 1
        else:
            w += 1
    flg = b > w
    print("Fennec" if flg else "Snuke")


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import heapq
# v:頂点数, s:始点, path[i]:[[cost,to]...] i=fromの隣接リスト
def dijkstra(v,s,path):
    inf = float('inf')

    # 距離をinfで初期化
    d = [inf for i in range(v)]
    d[s] = 0

    # sへの距離は0
    q = [[0,s]]
    heapq.heapify(q)

    # 距離が最小の頂点から更新していけば
    # p[1]から行ける
    while q:
        p = heapq.heappop(q)

        # 頂点p[1]までの距離がheapないのp[1]までの距離より小さい場合、continue
        if d[p[1]]<p[0]:
            continue

        # 頂点p[1]から伸びる、全ての辺の距離を確認
        for i in range(len(path[p[1]])):
            # 頂点p[1]から行ける頂点の距離がp[1]までの距離とp[1]からの距離の和より小さい場合 -> 距離を更新し、heapに追加
            if d[path[p[1]][i][1]] > d[p[1]] + path[p[1]][i][0]:
                d[path[p[1]][i][1]] = d[p[1]]+path[p[1]][i][0]
                heapq.heappush(q,[d[path[p[1]][i][1]], path[p[1]][i][1]])
    return d

n = int(input())

l = [[] for i in range(n)]
for i in range(n-1):
    a,b = map(int, input().split())
    # dijkstraのlibraryに合わせるため、距離1を追加
    l[a-1].append([1,b-1])
    l[b-1].append([1,a-1])

d1 = dijkstra(n,0,l)
d2 = dijkstra(n,n-1,l)

a = 0
for i in range(n):
    if d1[i]<=d2[i]:
        a+=1
    else:
        a-=1
print('Fennec' if a>0 else 'Snuke')

Submission status: Accepted

Solution code:
import heapq
# v:頂点数, s:始点, path[i]:[[cost,to]...] i=fromの隣接リスト
def dijkstra(v,s,path):
    inf = float('inf')

    # 距離をinfで初期化
    d = [inf for i in range(v)]
    d[s] = 0

    # sへの距離は0
    q = [[0,s]]
    heapq.heapify(q)

    # 距離が最小の頂点から更新していけば
    # p[1]から行ける
    while q:
        p = heapq.heappop(q)

        # 頂点p[1]までの距離がheapないのp[1]までの距離より小さい場合、continue
        if d[p[1]]<p[0]:
            continue

        # 頂点p[1]から伸びる、全ての辺の距離を確認
        for i in range(len(path[p[1]])):
            # 頂点p[1]から行ける頂点の距離がp[1]までの距離とp[1]からの距離の和より小さい場合 -> 距離を更新し、heapに追加
            if d[path[p[1]][i][1]] > d[p[1]] + path[p[1]][i][0]:
                d[path[p[1]][i][1]] = d[p[1]]+path[p[1]][i][0]
                heapq.heappush(q,[d[path[p[1]][i][1]], path[p[1]][i][1]])
    return d

def path_recovery(e,d,path):
    # 経路
    route = [e]
    # 残りの距離
    a = d[e]
    while a!=0:
        for i in range(len(path[e])):
            if d[path[e][i][1]]+path[e][i][0]==a:
                route.append(path[e][i][1])
                a -= path[e][i][0]
                e = path[e][i][1]
                break
    route.reverse()
    return route

class UnionFind:
    # 初期化
    def __init__(self, n):
        # 根なら-size, 子なら親の頂点
        self.par = [-1] * n
        # 木の高さ
        self.rank = [0] * n

    # 検索
    def find(self, x):
        if self.par[x] < 0:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    # 併合
    def unite(self, x, y):
        x = self.find(x)
        y = self.find(y)
        # 異なる集合に属する場合のみ併合
        if x != y:
            # 高い方をxとする。
            if self.rank[x] < self.rank[y]:
                x,y = y,x
            # 同じ高さの時は高さ+1
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1
            # yの親をxとし、xのサイズにyのサイズを加える
            self.par[x] += self.par[y]
            self.par[y] = x

    # 同集合判定
    def same(self, x, y):
        return self.find(x) == self.find(y)

    # 集合の大きさ
    def size(self, x):
        return -self.par[self.find(x)]

n = int(input())

l = [[] for i in range(n)]
for i in range(n-1):
    a,b = map(int, input().split())
    # dijkstraのlibraryに合わせるため、距離1を追加
    l[a-1].append([1,b-1])
    l[b-1].append([1,a-1])

d = dijkstra(n,0,l)

p = path_recovery(n-1,d,l)

x = p[(len(p)-1)//2]
y = p[(len(p)-1)//2+1]

for i in range(len(l[x])):
    if l[x][i][1]==y:
        l[x].pop(i)
        break
for i in range(len(l[y])):
    if l[y][i][1]==x:
        l[y].pop(i)
        break

u = UnionFind(n)

for i in range(len(l)):
    for j in range(len(l[i])):
        u.unite(i,l[i][j][1])


if u.size(0)>u.size(n-1):
    print('Fennec')
else:
    print('Snuke')

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
from collections import deque


inf = float('inf')

def solve(N: int, a: "List[int]", b: "List[int]"):
    adj = [set() for _ in range(N)]
    for u, v in zip(a, b):
        adj[u].add(v)
        adj[v].add(u)
    
    dist_F = [inf for _ in range(N)]
    dist_F[0] = 0
    dist_S = [inf for _ in range(N)]
    dist_S[N-1] = 0

    Q = deque([(0, 0)], N)
    while len(Q) > 0:
        du, u = Q.pop()
        for v in adj[u]:
            if dist_F[v] < inf:
                continue
            dist_F[v] = du + 1
            Q.append((du+1, v))
    

    Q = deque([(0, N-1)], N)
    while len(Q) > 0:
        du, u = Q.pop()
        for v in adj[u]:
            if dist_S[v] < inf:
                continue
            dist_S[v] = du + 1
            Q.append((du+1, v))

    c_S = 0
    c_F = 0

    for df, ds in zip(dist_F, dist_S):
        if df <= ds:
            c_F += 1
        else:
            c_S += 1

    if c_F <= c_S:
        print('Snuke')
    else:
        print('Fennec')    

    return


# Generated by 1.1.4 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
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)) - 1
        b[i] = int(next(tokens)) - 1
    solve(N, a, b)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import deque

def dfs(graph, start):
    stack = deque()
    costs = [0] * (N+1)
    stack.append([start,0])
    costs[start] = -1
    while stack:
        a, cost = stack.popleft()
        for b in graph[a].keys():
            if not costs[b]:
                stack.append([b,cost+1])
                costs[b] = cost+1
    return costs

N = int(input())
graph = {}
for i in range(N-1):
    a,b = map(int, input().split())
    if a not in graph:
        graph[a] = {}
    if b not in graph:
        graph[b] = {}
    graph[a][b] = graph[b][a] = 1
f_costs = dfs(graph,1)
s_costs = dfs(graph,N)
f_cnt = 1
for i in range(2,N):
    if f_costs[i] <= s_costs[i]:
        f_cnt += 1
# print(f_costs, s_costs, f_cnt)
print('Fennec' if f_cnt > N - f_cnt else 'Snuke')

Submission status: Accepted

Solution code:

#
#フェネックとすぬけさんが最短でお互いのマスへ向かう時の、ぶつかる点を求めて
#木を分割する。分割した二つのマスを数えて比較し、大きい方が勝利

import sys
sys.setrecursionlimit(1000000)

N = int(input())
e = [ [] for i 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)

#二人がぶつかる点を求める（木を分割する点を求める）
col = [ -1 for i in range(N)]
col[0] = 0
p = []
path = [ 0 for i in range(10**5+1)]
def dfs(n,c):
    global p
    if n == N - 1:
        p = path
    path[c] = n
    for v in e[n]:
        if col[v] == -1:
            col[v] = c + 1
            dfs(v,c+1)
            if p:
                return
dfs(0,0)

t = col[N-1] + 1
if t % 2 ==0:
    sn = p[t//2]
else:
    sn = p[t//2+1]


#フェネック側の木のマス数を数える
colfn = [ -1 for i in range(N)]
colfn[0] = 0
def dfs2(n,c):

    for v in e[n]:
        if v == sn:
            continue
        elif colfn[v] == -1:
            colfn[v] = c + 1
            dfs2(v,c+1)

dfs2(0,0)

fennec = -1
for i in range(N):
    if colfn[i] != -1:
        fennec += 1


#すぬけさん側は全マス数からフェネックのマスを引けば良い
snuke = N - fennec - 2

if fennec > snuke:
    print("Fennec")
else:
    print("Snuke")

Submission status: Accepted

Solution code:

import sys
sys.setrecursionlimit(1000000)

N = int(input())

e = [ [] for i 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)

col = [ -1 for i in range(N)]
col[0] = 0

p = []
path = [ 0 for i in range(10**5+1)]
def dfs(n,c):
    global p
    if n == N - 1:
        p = path
    path[c] = n
    for v in e[n]:
        if col[v] == -1:
            col[v] = c + 1
            dfs(v,c+1)
            if p:
                return
dfs(0,0)

t = col[N-1] + 1
if t % 2 ==0:
    sn = p[t//2]
else:
    sn = p[t//2+1]


colfn = [ -1 for i in range(N)]
colfn[0] = 0
def dfs2(n,c):

    for v in e[n]:
        if v == sn:
            continue
        elif colfn[v] == -1:
            colfn[v] = c + 1
            dfs2(v,c+1)

dfs2(0,0)

fennec = -1
for i in range(N):
    if colfn[i] != -1:
        fennec += 1

snuke = N - fennec - 2
if fennec > snuke:
    print("Fennec")
else:
    print("Snuke")

Submission status: Accepted

Solution code:

import sys

p = []
path = [ 0 for i in range(10**5+1)]
def main():

    sys.setrecursionlimit(1000000)

    N = int(input())

    e = [ [] for i 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)

    col = [ -1 for i in range(N)]
    col[0] = 0
    
    def dfs(n,c):
        global p
        if n == N - 1:
            p = path
        path[c] = n
        for v in e[n]:
            if col[v] == -1:
                col[v] = c + 1
                dfs(v,c+1)
                if p:
                    return
    dfs(0,0)

    t = col[N-1] + 1
    if t % 2 ==0:
        sn = p[t//2]
    else:
        sn = p[t//2+1]


    colfn = [ -1 for i in range(N)]
    colfn[0] = 0
    def dfs2(n,c):

        for v in e[n]:
            if v == sn:
                continue
            elif colfn[v] == -1:
                colfn[v] = c + 1
                dfs2(v,c+1)

    dfs2(0,0)

    fennec = -1
    for i in range(N):
        if colfn[i] != -1:
            fennec += 1

    snuke = N - fennec - 2
    if fennec > snuke:
        print("Fennec")
    else:
        print("Snuke")



if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys

p = []
path = [ 0 for i in range(10**5+1)]
def main():

    sys.setrecursionlimit(1000000)

    N = int(input())

    e = [ [] for i 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)

    col = [ -1 for i in range(N)]
    col[0] = 0
    
    #def dfs(n,c,path):
    def dfs(n,c):
        global p
        #path =  path  + [n]
        #path.append(n)
        #print(path)
        if n == N - 1:
            p = path
        path[c] = n
        for v in e[n]:
            if col[v] == -1:
                col[v] = c + 1
                dfs(v,c+1)
                #dfs(v,c+1,path)
                if p:
                    return
    dfs(0,0)
    #print(p[:N+10])
    #dfs(0,0,[])

    t = col[N-1] + 1
    if t % 2 ==0:
        sn = p[t//2]
    else:
        sn = p[t//2+1]


    colfn = [ -1 for i in range(N)]
    colfn[0] = 0
    def dfs2(n,c):

        for v in e[n]:
            if v == sn:
                continue
            elif colfn[v] == -1:
                colfn[v] = c + 1
                dfs2(v,c+1)

    dfs2(0,0)

    fennec = -1
    for i in range(N):
        if colfn[i] != -1:
            fennec += 1

    snuke = N - fennec - 2
    if fennec > snuke:
        print("Fennec")
    else:
        print("Snuke")



if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import deque

def dfs(graph, start, goal):
    s_stack = deque()
    g_stack = deque()
    visited = [0 for i in range(N+1)]
    s_stack.append([start,0])
    g_stack.append([goal, 0])
    visited[start] = 1 
    visited[goal] = 1 
    s_cnt = 1
    g_cnt = 1
    round = 0
    while s_stack or g_stack:
        while s_stack:
            a,cost = s_stack.popleft()
            if cost > round:
                s_stack.appendleft([a,cost])
                break
            for b in graph[a].keys():
                if not visited[b]:
                    s_stack.append([b,cost+1])
                    visited[b] += 1 
                    s_cnt += 1
        while g_stack:
            a, cost = g_stack.popleft()
            if cost > round:
                g_stack.appendleft([a,cost])
                break
            for b in graph[a].keys():
                if not visited[b]:
                    g_stack.append([b,cost+1])
                    visited[b] += 1 
                    g_cnt += 1
        round += 1
    # print(s_cnt, g_cnt)
    return s_cnt > g_cnt

N = int(input())
graph = {}
for i in range(N-1):
    a,b = map(int, input().split())
    if a not in graph:
        graph[a] = {}
    if b not in graph:
        graph[b] = {}
    graph[a][b] = graph[b][a] = 1
print('Fennec' if dfs(graph,1,N) else 'Snuke')

Submission status: Accepted

Solution code:
N=int(input())
edge=[list(map(int,input().split())) for i in range(N-1)]
inf=10**20
c=[[] for i in range(N)]
for i,j in edge:
    c[i-1].append(j-1)
    c[j-1].append(i-1)
d=[0]+[inf]*(N-1)
v=[0]*N
import sys
sys.setrecursionlimit(10**6)
def dfs(p,v,d):
    for n in c[p]:
        if v[n]==0:
            d[n]=min(d[n],d[p]+1)
            v[n]=1
            dfs(n,v,d)
dfs(0,v,d)
d2=[inf]*(N-1)+[0]
v=[0]*N
dfs(N-1,v,d2)
c=0
for i,j in zip(d,d2):
    c=c+1 if i<=j else c-1
print(['Snuke','Fennec'][c>0])

Submission status: Accepted

Solution code:
import sys
stdin = sys.stdin

sys.setrecursionlimit(10 ** 7)

def li(): return map(int, stdin.readline().split())
def li_(): return map(lambda x: int(x) - 1, stdin.readline().split())
def lf(): return map(float, stdin.readline().split())
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())

from collections import deque

def bfs(graph: list, start: int):
    n = len(graph)
    dist = [-1]*n

    que = deque([(start, 0)])

    while que:
        cur_node, cur_dist = que.popleft()
        dist[cur_node] = cur_dist

        for nex in graph[cur_node]:
            if dist[nex] < 0:
                dist[nex] = cur_dist + 1
                que.append((nex, cur_dist+1))

    return dist

n = ni()

graph = [[] for _ in range(n)]
for _ in range(n-1):
    x, y = li_()
    graph[x].append(y)
    graph[y].append(x)

fenec = bfs(graph, 0)
snuke = bfs(graph, n-1)

fenec_saki = 0
for d1, d2 in zip(fenec, snuke):
    if d1 <= d2:
        fenec_saki += 1
    elif d1 > d2:
        fenec_saki -= 1

if fenec_saki == 0:
    if n%2:
        print("Fennec")
    else:
        print("Snuke")

elif fenec_saki > 0:
    print("Fennec")

else:
    print("Snuke")

Submission status: Accepted

Solution code:

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

vi = 0 #時と場合によってここを変える
from collections import deque
Q = deque([vi])
checked_list = [False for i in range(N)]
checked_list[vi]=True
prev_list = [-1 for i in range(N)]
min_path_list = [10**27 for i in range(N)] #問題によりここを変える
min_path_list[vi] = 0
while len(Q)>0:
    v = Q.pop()
    for v1 in e_list[v]:
        if not checked_list[v1]:
            checked_list[v1]=True
            Q.appendleft(v1)
            prev_list[v1]=v
            min_path_list[v1]=min(min_path_list[v1],min_path_list[v]+1) #問題によりここを変える

path = [N-1]
v=N-1
while prev_list[v]!=-1:
    path.append(prev_list[v])
    v=prev_list[v]

a=path[(min_path_list[N-1]-1)//2]
b=path[(min_path_list[N-1]-1)//2+1]
for i in range(len(e_list[a])):
    if e_list[a][i]==b:
        break
del e_list[a][i]

for i in range(len(e_list[b])):
    if e_list[b][i]==a:
        break
del e_list[b][i]

vi = 0 #時と場合によってここを変える

Q = deque([vi])
checked_list = [False for i in range(N)]
checked_list[vi]=True
count = 1
while len(Q)>0:
    v = Q.pop()
    for v1 in e_list[v]:
        if not checked_list[v1]:
            checked_list[v1]=True
            Q.appendleft(v1)
            count+=1

if count>N-count:
    print("Fennec")
else:
    print("Snuke")

Submission status: Accepted

Solution code:
###template###
import sys
def input(): return sys.stdin.readline().rstrip()
def mi(): return map(int, input().split())
###template###

N = int(input())

#neighbor
#0~N-1でアクセス
ngb = [[] for _ in range(N)]

#入力
#すべて-1ベースに
for _ in range(N-1):
  a,b = mi()
  a -= 1
  b -= 1
  ngb[a].append(b)
  ngb[b].append(a)

start = 0
goal = N-1

#nodes[番号][0]には探索済みならstartからの距離、未探索なら-1を格納
#nodes[番号][1]には（探索済みなら）「何番のノードから来たか(0~N-1)」を格納
nodes = [[-1, -1] for _ in range(N)]

#nodesにスタート地点を入れ、stackを初期化
nodes[start][0] = 0
nodes[start][1] = -1
stack = []
for eachngb in ngb[start]:
  stack.append(eachngb)
  nodes[eachngb][0] = 1
  nodes[eachngb][1] = start

#phase1 start->goalの最短距離を探索
while 1:
  try:
    nownode = stack.pop()
  except:
    break

  if nownode == goal:
    break

  #現在のノードとエッジで繋がるノードのうち、未探索のものをスタックに入れる
  #スタックに入れたらもう探索済みとする
  #木なので、ngb[]が空になっていることはありえない
  for eachngb in ngb[nownode]:
    if nodes[eachngb][0] == -1:
      stack.append(eachngb)
      #距離を+1して入れ、今のノード番号（どこから来たか、となる）を入れる
      nodes[eachngb][0] = nodes[nownode][0]+1
      nodes[eachngb][1] = nownode

#phase2 B, Wの根を見つける
length = nodes[goal][0] #スタートからゴールへの距離
FenRootPos = length // 2 #Fenの根がある距離
SnRootPos = FenRootPos + 1 #Snukeの根がある距離
FenRoot = -1 #Fenの根ノード番号
SnRoot = -1 #Snukeの根ノード番号

#ゴールからフェネックの根がある場所まで、順に逆走していく
nextnode = goal
#このループ内において、iは今見ているノードのスタートからの距離を表す
for i in range(length, FenRootPos-1, -1):
  nownode = nextnode
  if i == SnRootPos:
    SnRoot = nownode
  elif i == FenRootPos:
    FenRoot = nownode
  nextnode = nodes[nownode][1]

#phase3 B, Wそれぞれの根から、その木のノード数を数える
#お互いの根は探索済み(0)とすることで、重複を避ける

#まずはFen
#探索済みかどうか
ndsFen = [-1] * N
ndsFen[SnRoot] = 0
ndsFen[FenRoot] = 0
stkFen = []
stkFen.append(FenRoot)
FenCnt = 0
while 1:
  try:
    nownode = stkFen.pop()
  except:
    break

  #現在のノードとエッジで繋がるノードのうち、未探索のものをスタックに入れる
  #スタックに入れたらもう探索済みとする
  #木なので、ngb[]が空になっていることはありえない
  for eachngb in ngb[nownode]:
    if ndsFen[eachngb] == -1:
      stkFen.append(eachngb)
      #今回は距離は関係無いので、0を入れるだけでいい
      ndsFen[eachngb] = 1
      FenCnt += 1

#次はSnuke
#探索済みかどうか
ndsSn = [-1] * N
ndsSn[FenRoot] = 0
ndsSn[SnRoot] = 0
stkSn = []
stkSn.append(SnRoot)
SnCnt = 0
while 1:
  try:
    nownode = stkSn.pop()
  except:
    break

  #現在のノードとエッジで繋がるノードのうち、未探索のものをスタックに入れる
  #スタックに入れたらもう探索済みとする
  #木なので、ngb[]が空になっていることはありえない
  for eachngb in ngb[nownode]:
    if ndsSn[eachngb] == -1:
      stkSn.append(eachngb)
      #今回は距離は関係無いので、0を入れるだけでいい
      ndsSn[eachngb] = 1
      SnCnt += 1

print('Fennec' if FenCnt > SnCnt else 'Snuke')

Submission status: Accepted

Solution code:
from collections import defaultdict
from heapq import heappop, heappush


class Graph(object):
    """
    隣接リストによる有向グラフ
    """

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

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

    def add_edge(self, src, dst, weight=1):
        self.graph[src].append((dst, weight))

    def get_nodes(self):
        return self.graph.keys()


class Dijkstra(object):
    """
    ダイクストラ法（二分ヒープ）による最短経路探索
    計算量: O((E+V)logV)
    """

    def __init__(self, graph, start):
        self.g = graph.graph

        # startノードからの最短距離
        # startノードは0, それ以外は無限大で初期化
        self.dist = defaultdict(lambda: float('inf'))
        self.dist[start] = 0

        # 最短経路での1つ前のノード
        self.prev = defaultdict(lambda: None)

        # startノードをキューに入れる
        self.Q = []
        heappush(self.Q, (self.dist[start], start))

        while self.Q:
            # 優先度（距離）が最小であるキューを取り出す
            dist_u, u = heappop(self.Q)
            if self.dist[u] < dist_u:
                continue
            for v, weight in self.g[u]:
                alt = dist_u + weight
                if self.dist[v] > alt:
                    self.dist[v] = alt
                    self.prev[v] = u
                    heappush(self.Q, (alt, v))

    def shortest_distance(self, goal):
        """
        startノードからgoalノードまでの最短距離
        """
        return self.dist[goal]

    def shortest_path(self, goal):
        """
        startノードからgoalノードまでの最短経路
        """
        path = []
        node = goal
        while node is not None:
            path.append(node)
            node = self.prev[node]
        return path[::-1]


g = Graph()
#N, M = [int(i) for i in input().split()]
N = int(input())

for i in range(N-1):
    u, v = [int(i) for i in input().split()]
    g.add_edge(u-1, v-1, 1)
    g.add_edge(v-1, u-1, 1)

d1 = Dijkstra(g, 0)
d2 = Dijkstra(g, N-1)

ans = 0

#print(d1.dist)
#print(d2.dist)

for i in range(N):
    if d1.dist[i] <= d2.dist[i]:
        ans += 1

if ans > N - ans:
    print("Fennec")
else:
    print("Snuke")