Guest User

The Space War Solution

a guest
Jan 7th, 2020
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.44 KB | None | 0 0
  1. from collections import defaultdict
  2. class Graph:
  3.     def __init__(self):
  4.         self.graph = defaultdict(list)
  5.     def addEdge(self,u,v):
  6.         self.graph[u].append(v)
  7.     def BFS(self, s):
  8.         path=[]
  9.         d2={}
  10.         queue = []
  11.         queue.append(s)
  12.         d2[s]=1
  13.  
  14.         while queue:
  15.             s = queue.pop(0)
  16.             path.append(s)
  17.             for i in self.graph[s]:
  18.                 if i not in d2:
  19.                     queue.append(i)
  20.                     d2[i]=1
  21.         return path
  22.     def DIAMETER(self,s):
  23.         path=[]
  24.         d2={}
  25.         dist={}
  26.         queue=[]
  27.         queue.append(s)
  28.         d2[s]=1
  29.         dist[s]=0
  30.         d=0
  31.         while queue:
  32.             s= queue.pop()
  33.             for i in self.graph[s]:
  34.                 if i not in d2:
  35.                     queue.append(i)
  36.                     dist[i]=dist[s]+1
  37.                     d=max(dist[i],d)
  38.                     d2[i]=1
  39.         return d
  40.        
  41. g=Graph()
  42. n,m=map(int,input().split())
  43. d1={}
  44. l1=list(range(1,n+1))
  45. for item in l1:
  46.     d1[item]=1
  47. for i in range(0,m):
  48.     x,y=map(int,input().split())
  49.     g.addEdge(x,y)
  50.     g.addEdge(y,x)
  51. ans=0
  52. for item in l1:
  53.     if len(d1)==0:
  54.         break
  55.     else :
  56.         if item in d1:
  57.        
  58.             path=g.BFS(item)
  59.             d=g.DIAMETER(path[-1])
  60.             ans=max(ans,(d+1)//2)
  61.             for x in path:
  62.                del d1[x]
  63. print(ans)
Add Comment
Please, Sign In to add comment