Thursday, March 1, 2018

Happy Vertices (Python3)

def dfs(u):
    global ans
    for i in range(len(adj[u])):
        v = adj[u][i]
        if not visited[v]:
            visited[v] = len(adj[v])-1
            if visited[v] > visited[u]:
                ans += 1
            dfs(v)



n,m = map(int,input().split())
ans = 0
adj = []
for i in range(n+1): adj.append([])
for i in range(m):
    x,y = map(int,input().split())
    adj[x].append(y)
    adj[y].append(x)

visited = [0]*(n+1)
for i in range(1,n+1):
    if not visited[i]:
        visited[i] = len(adj[i])
        dfs(i)
print(ans)

No comments: