DOJ logoDOJ
Problems
Recently added problemsSaved problemsWorkbooks
CategoriesDLCContestsGroupsTeamsBoard
Ranking
Solved Problem RankingStreak rankingDOJ Power ranking
Status
Call for TasksLoginRegister
DOJ logoDOJ

Community online judge with OI-style subtask scoring, Elo ratings, and Discord-backed certification.

Problems
ProblemsCategories
Community
ContestsRankingBoardNoticesHost an external contestGuide
Account
LoginRegisterJudge Status
Policy
Terms of ServiceDLC RulesPrivacyAPI documentationLanguage runtimesContest rank rewardsRating and performance
© 2026 DOJ
All rights reserved
Editorial

Common Ground

Back to problem

Editorial

Find connected components using the distinct prime factors of each integer.

Every pair of vertices divisible by the same prime ppp is connected by an edge. Thus, it is enough to remember one representative vertex for each prime ppp and merge every subsequent vertex divisible by ppp with that representative.

Precompute the smallest prime factor of every integer using a sieve. Factorize each AiA_iAi​ into distinct prime factors. For every such factor ppp, merge vertex iii with the recorded representative of ppp using a disjoint-set union structure. The number 111 has no prime factors and is not merged with any other vertex.

Every edge (i,j)(i,j)(i,j) has a prime dividing both AiA_iAi​ and AjA_jAj​, so its endpoints are merged. Conversely, each merge is between vertices sharing a prime factor, so these vertices are adjacent in the original graph. Therefore the resulting disjoint sets are exactly the connected components of the graph.

Answer each query by checking whether its endpoints have the same DSU representative. This also handles u=vu=vu=v.

Let M=max⁡AiM=\max A_iM=maxAi​. The time complexity is O(Mlog⁡log⁡M+Nlog⁡M+Qα(N))O(M\log\log M + N\log M + Q\alpha(N))O(MloglogM, and the space complexity is .

Solution written by GPT6

+
NlogM+
Qα(N))
O(M+N)O(M+N)O(M+N)