classSolution{public:vector<int>countPairs(intn,vector<vector<int>>&edges,vector<int>&queries){vector<int>ans(queries.size());// count[i] := the number of edges of node ivector<int>count(n+1);// shared[i][j] := the number of edges incident to i or j, where i < jvector<unordered_map<int,int>>shared(n+1);for(constvector<int>&edge:edges){constintu=edge[0];constintv=edge[1];++count[u];++count[v];++shared[min(u,v)][max(u,v)];}vector<int>sortedCount(count);ranges::sort(sortedCount);intk=0;for(constintquery:queries){for(inti=1,j=n;i<j;)if(sortedCount[i]+sortedCount[j]>query)// sortedCount[i] + sortedCount[j] > query// sortedCount[i + 1] + sortedCount[j] > query// ...// sortedCount[j - 1] + sortedCount[j] > query// So, there are (j - 1) - i + 1 = j - i pairs > queryans[k]+=(j--)-i;else++i;for(inti=1;i<=n;++i)for(constauto&[j,sh]:shared[i])if(count[i]+count[j]>query&&count[i]+count[j]-sh<=query)--ans[k];++k;}returnans;}};
classSolution{publicint[]countPairs(intn,int[][]edges,int[]queries){int[]ans=newint[queries.length];// count[i] := the number of edges of node iint[]count=newint[n+1];// shared[i][j] := the number of edges incident to i or j, where i < jMap<Integer,Integer>[]shared=newMap[n+1];for(inti=1;i<=n;++i)shared[i]=newHashMap<>();for(int[]edge:edges){finalintu=edge[0];finalintv=edge[1];++count[u];++count[v];shared[Math.min(u,v)].merge(Math.max(u,v),1,Integer::sum);}int[]sortedCount=count.clone();Arrays.sort(sortedCount);intk=0;for(finalintquery:queries){for(inti=1,j=n;i<j;)if(sortedCount[i]+sortedCount[j]>query)// sortedCount[i] + sortedCount[j] > query// sortedCount[i + 1] + sortedCount[j] > query// ...// sortedCount[j - 1] + sortedCount[j] > query// So, there are (j - 1) - i + 1 = j - i pairs > queryans[k]+=(j--)-i;else++i;for(inti=1;i<=n;++i)for(Map.Entry<Integer,Integer>p:shared[i].entrySet()){finalintj=p.getKey();finalintsh=p.getValue();if(count[i]+count[j]>query&&count[i]+count[j]-sh<=query)--ans[k];}++k;}returnans;}}
classSolution:defcountPairs(self,n:int,edges:list[list[int]],queries:list[int],)->list[int]:ans=[0]*len(queries)# count[i] := the number of edges of node icount=[0]*(n+1)# shared[i][j] := the number of edges incident to i or j, where i < jshared=[collections.Counter()for_inrange(n+1)]foru,vinedges:count[u]+=1count[v]+=1shared[min(u,v)][max(u,v)]+=1sortedCount=sorted(count)fork,queryinenumerate(queries):i=1j=nwhilei<j:ifsortedCount[i]+sortedCount[j]>query:# sortedCount[i] + sortedCount[j] > query# sortedCount[i + 1] + sortedCount[j] > query# ...# sortedCount[j - 1] + sortedCount[j] > query# So, there are (j - 1) - i + 1 = j - i pairs > queryans[k]+=j-ij-=1else:i+=1foriinrange(1,n+1):forj,shinshared[i].items():ifcount[i]+count[j]>queryandcount[i]+count[j]-sh<=query:ans[k]-=1returnans
Thanks for stopping by! If you find this site helpful, consider buying me some protein powder to keep me fueled! 😄