Created
June 25, 2021 06:47
-
-
Save Avdesh02/98f9765d9adffdeb6e56713572f9e102 to your computer and use it in GitHub Desktop.
My code runs fine while testing 1 Test case but fails while submit code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
This is the problem: | |
Given an undirected and connected graph of N vertices and N-1 edges. | |
The number written on the ith vertex is val[i]. The task is to count | |
the number of pairs(x,y) such that the following conditions are satisfied: | |
0 ≤ x < y ≤ N-1 | |
The GCD of the numbers written on the vertices on the simple path in the given graph from x to y should be divisible by K. | |
For Example: | |
Input: | |
N = 4, K = 2 | |
Edges[] = {{0, 1}, {0, 2}, {2, 3}} | |
Val[] = {2, 6, 4, 3} | |
Output: | |
3 | |
Explanation: | |
0 - 1 | |
| | |
2 - 3 | |
There are three pairs - (0,1), (1,2) and | |
(0,2) which satisify both the conditions. | |
''' | |
# my solution: | |
import math | |
class Solution: | |
def countPair(self, N, Edges, Val, K): | |
count = 0 | |
for i in range(len(Val)): | |
for j in range(len(Val) - 1, i, -1): | |
if math.gcd(Val[i], Val[j]) % K == 0: | |
count += 1 | |
return count | |
if name == ‘main’: | |
t = int(input()) | |
for _ in range(t): | |
n,k = map(int, input().strip().split()) | |
val = [int(x) for x in input().strip().split()] | |
edges = [] | |
for i in range(n-1): | |
x,y = map(int, input().strip().split()) | |
edges.append([x,y]) | |
ob = Solution() | |
ans = ob.countPair(n,edges,val,k) | |
print(ans) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment