We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
parent={}no_of_friends={}deffindparent(x):ifparent[x]==x:returnxparent[x]=findparent(parent[x])returnparent[x]defvalue(n):t1=n*(n+1)*(2*n+1)t1/=6t2=n*(n+1)t2/=2returnt1-t2defvalueOfFriendsship(n,m,friendships):# Write your code heretotal,current,ans=0,0,0foriinrange(1,n+1):parent[i]=ino_of_friends[i]=1foriinrange(m):u,v=friendships[i][0],friendships[i][1]pu,pv=findparent(u),findparent(v)ifpu!=pv:parent[pv]=puno_of_friends[pu]+=no_of_friends[pv]p=[]foriinrange(1,n+1):if(parent[i]==i):p.append(no_of_friends[i])p.sort(reverse=True)foriinrange(len(p)):current+=(p[i]-1)ans+=value(p[i])+total*(p[i]-1)total+=(p[i]*(p[i]-1))ans+=((m-current)*total)returnint(ans)
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
The Value of Friendship
You are viewing a single comment's thread. Return to all comments →
jt_112's solution in Python3