We need to parse the problem. We have an array of n positive integers. There are m good pairs (i, j) such that i+j is odd and i<j. In each operation: choose a good pair (i,j) and an integer v>1 such that v divides both a[i] and a[j]; then divide both a[i] and a[j] by v. This operation reduces the values. The goal: maximum number of operations we can perform sequentially (i.e., repeatedly applying such operations) possibly reusing pairs. We want the maximum total number of operations possible (like the total number of times we can divide some numbers using these constraints). This is reminiscent of maximum matching or flow problems with capacities representing the amount of times we can divide by prime factors? Since operations involve dividing by any v > 1 that divides both numbers. Equivalent to we can pick any divisor >1 of both numbers; after dividing, the numbers are reduced. The operation consumes a factor from both numbers. Since v can be any divisor, effectively we can reduce the numbers by any common factor >1. But it's not necessary that v be prime; we could factor out composite numbers in one go, but that would count as one operation. So the total number of operations is limited by the total "common factor mass" we can extract from pairs.
We want to maximize the number of operations, not necessarily the total reduction. Since an operation requires dividing by v>1, if we divide by a composite number we reduce many prime factors at once, but that counts as one operation. So to maximize the number of operations, we would want to divide by the smallest possible v each time, i.e., v=2 if both are even, then maybe again, etc. In other words, each operation reduces the numbers by at least a factor of 2, but we can choose to do many small operations rather than one big operation. The maximum number of operations is essentially the maximum total number of times we can pick a pair and divide both by some integer >1, i.e., we can break down the prime factorizations into individual prime reductions as long as each operation corresponds to dividing by some prime (since dividing by composite could be simulated by multiple prime division operations). However, note that the operation must divide both numbers by the same v, and v can be prime or composite. If we want to maximize the count, we would always use v = some prime factor p that divides both numbers at that moment. Because if we use composite, we could instead do multiple operations each dividing by one prime factor, increasing the count. So the maximum number of operations equals the maximum total number of prime factor extractions we can do across all numbers, respecting that each operation extracts a common prime factor from the two numbers of the chosen pair. However, note that we might also extract a prime factor multiple times if it appears with multiplicity. So essentially, we have prime factors (with multiplicities) distributed among the numbers. Each operation selects a good pair (i,j) and a prime p that currently divides both a[i] and a[j] (i.e., both have at least one copy of p), and reduces the exponent of p by 1 in both numbers. That operation counts 1. We can also choose v = p^k (k>1) to reduce exponent by k in one operation, but that would be suboptimal for maximizing count. Since we are free to choose any v, to maximize operations we will always use v = a prime factor each time. So the problem reduces to: Given a bipartite graph? Good pairs connect indices i and j such that i+j odd => that implies i and j have opposite parity? Since i+j odd => one is even, other is odd. So the indices can be partitioned by parity: even index set and odd index set. Since i < j but i+j odd, it means i and j are of opposite parity. So the good pairs always connect an odd-indexed node to an even-indexed node. Actually, careful: i and j are indices. i+j odd => parity different. Since i < j, we could have i odd, j even; or i even, j odd. In either case, it's cross between parity sets. So the graph of allowed operations is bipartite between odd indices and even indices. And we have m edges.
We have numbers a[i]. Each a[i] can be factored into primes. But a[i] up to 1e9, so factorization possible by trial division up to sqrt? n up to 100, we can factor each a[i] individually using primes up to 31623; feasible. Then for each prime p, each index i has some exponent e_i(p) (nonnegative integer). An operation with p on edge (i,j) consumes 1 from e_i(p) and 1 from e_j(p). Each such operation reduces the exponents. We can do multiple operations across different primes independently? They are independent because operations on different primes are separate (since dividing by a prime p does not affect other primes). However, we cannot simultaneously use the same exponent for multiple operations; each unit of exponent can be used only once. So the maximum total number of operations is sum over primes of the maximum number of operations we can perform using prime p, where each operation consumes one unit of p from each endpoint of an edge. For a given prime p, we have a bipartite graph G = (U = odd indices, V = even indices) with capacities on nodes equal to the exponent of p at that node. Each operation corresponds to selecting an edge and subtracting 1 from both endpoint's capacities. We want to maximize the number of operations, i.e., the maximum number of unit matchings (each edge can be used multiple times up to min of capacities of its endpoints? Actually it's like: we have a bipartite graph with node capacities (supplies/demands?) and we want to maximize the number of matchings (assignments) such that each node i can be incident to at most e_i(p) selected edges (since each time we use an edge incident to i, we consume one unit of p from i). Edges can be used multiple times, but each use consumes one unit from each endpoint. This is exactly a classic maximum flow problem: create source connected to left partition nodes (say odd) with capacity e_i(p), and edges from left to right (if there is a good pair) with infinite (or high) capacity, and right nodes to sink with capacity e_j(p). The maximum flow from source to sink gives the maximum number of unit matchings (operations) for prime p. Because each unit of flow corresponds to one operation: one unit from left node goes through an edge to right node, then to sink, consuming one unit of capacity at both ends.
Thus the total answer is sum over all primes p of max flow on that network. Since exponents may be up to maybe 30 (since a[i] <= 1e9, max prime exponent sum per number is about log2(1e9) ~ 30). So total operations at most about 100*30=3000, manageable.
But we must consider that primes may be many (distinct primes up to 1e9). However, each a[i] factorization yields at most O(log a[i]) distinct primes, so total distinct primes across all numbers at most n * O(log a) = maybe 100 * 9 = 900? Actually worst-case a[i] could be product of many small primes; maximum number of distinct primes in a number ≤ 1e9 is around 9 (since product of first 9 primes: 23571113171923 ≈ 9.69e8, adding 29 would exceed). So at most 9 per number, but across 100 numbers could be up to 100*9=900 distinct primes, but many may overlap. So total distinct primes is bounded by maybe ~1000. That's fine. For each prime, we construct a flow network with up to n nodes on each side, and m edges. n ≤100, m ≤100. So we can run max flow per prime. Using Dinic or Edmonds-Karp. Since capacities are up to maybe 30, but number of primes up to 1000, total flow steps could be large but still fine. Let's compute worst-case: for each prime, maximum flow is at most total exponent sum across all nodes ~ 3000. In Dinic, complexity O(E sqrt(V)) for unit capacities? Not exactly; but we can use Dinic O(E V^2) worst-case but with small capacities it's fine. Since total sum of exponents over all primes is total sum of prime factor multiplicities across all numbers, which is at most 100 * 30 = 3000. So sum of all max flows across primes <= 3000. Actually each operation consumes one unit of exponent from two numbers, so total operations <= 3000/2? Let's think: total sum of exponents across all numbers is S = sum_i (total prime exponents in a[i]). Each operation reduces two numbers' exponents (each by 1) for a particular prime. So the total number of operations across all primes cannot exceed S/2? Actually each operation reduces two exponent counts, each from possibly different primes? But since each operation is on a specific prime p, it reduces exponents of p on two nodes. So overall total operations across all primes = sum over p of number of operations for p. And total sum of exponents across all nodes and primes is S. Each operation consumes 2 exponent units (one from each of two nodes). So sum over p (2 * ops_p) <= S => ops total <= floor(S/2). S is at most ~3000, so total ops <= 1500. So the flow across all primes will sum to at most 1500 augmentations, each of which is size 1? In flow, each augmenting path may carry flow of 1 if capacities are small. If we implement Dinic, it's efficient.
We can also combine all primes into a single flow network? But capacities depend on prime and we can't mix because operations must use same prime. So separate.
Thus solution: factor all a[i] into prime factors with exponents. Collect distinct primes. For each prime p:
- Build graph: source -> nodes in set A (choose one parity as left). Which parity is which? Since edges always connect odd and even indices, we can set left = indices with odd parity? But careful: good pairs given (i,j) with i<j and i+j odd. That means i and j have opposite parity. We can arbitrarily set U = indices with odd index numbers, V = even. But need to ensure i<j does not impose direction; our flow is undirected. So we just add directed edges from U to V if there is a good pair connecting an odd index u and even index v. However, pair could be (i,j) with i even, j odd? Since i<j, if i is even and j is odd, then even < odd? That can happen: e.g., i=2 (even), j=3 (odd) => 2+3=5 odd, okay. So edges connect odd and even irrespective of order. So we need to treat as undirected; but in flow we need directed edges from left partition to right partition. So we can assign left = odd, right = even (or vice versa). Then for each good pair (ik,jk), if ik is odd and jk even, add edge from ik (odd) to jk (even). If ik even and jk odd, add edge from jk? Actually we need to ensure direction from left to right. So if ik odd, jk even, then edge from ik (left) to jk (right). If ik even, jk odd, then we can add edge from jk (left, since jk odd) to ik (right). So we need to map correctly. Alternatively, we can build undirected bipartite graph and then for flow, add two directed edges? But that would allow flow both ways, but since we have source on left and sink on right, we only need capacity from left to right. But it's okay to add both directions? Actually in flow we want each operation to correspond to one unit flowing from left to right via an edge. If we add both directions, a flow could go from left to right using an edge oriented left->right, but also from right to left if we added reverse? But we shouldn't add both because then flow could go from left to right via some path that goes through a reverse edge? That might cause cycles but not necessarily harm if capacities are set properly? But typical bipartite flow: source->left nodes with capacities, left->right edges with infinite capacity (or 1? Actually each operation uses one edge; we can use same edge multiple times up to min of capacities of its endpoints. Since we are not limiting per-edge usage, we can set edge capacities to a large number (like INF). And then right nodes->sink with capacities. The flow from source to sink must go through exactly one edge from left to right. Adding reverse edges from right to left (except the residual reverse edges automatically added) would allow flow to go from left to right to left to right again? That's not needed; we want directed edges only from left to right. So we just add edges according to orientation.
Thus for each prime, we:
- Let left_indices = indices where index is odd (or even, but consistent). Actually parity: index i: i%2. Since i from 1 to n. Usually 1 odd, 2 even, etc. So left = odd indices, right = even indices.
- For each good pair (i,j):
if i%2==1 and j%2==0: add edge left i -> right j with high capacity (like INF or simply the sum of all capacities, maybe up to 30*100? Actually maximum flow through that edge is limited by the capacities of its endpoints, so we can set capacity = INF, e.g., large like sum of exponents from left or right). But to be safe, set capacity = min(total exponent left sum, total right sum) which at most 3000. So INF = 1e9.
else if i%2==0 and j%2==1: add edge left j -> right i with high capacity.
- Add source s -> each left node i with capacity = exponent_i(p) (the number of times p divides a[i] initially).
- Add each right node j -> sink t with capacity = exponent_j(p).
Then compute max flow from s to t. The flow value = maximum number of operations for prime p.
Sum over primes gives answer.
Edge cases: What if a[i] = 1? Then exponent zero for all primes, no contribution.
Also, note that after performing operations on one prime, we could later perform operations on another prime. They are independent because dividing by one prime does not affect exponents of other primes. So sum of max flows is indeed maximum total operations. However, we need to ensure that there is no interference: could the order of operations affect the total possible? Since operations on different primes are independent (the divisibility for a prime p only depends on the exponent of p), and we can always perform operations for each prime independently in any order. The maximum total is the sum of the maxima for each prime, as we can realize them simultaneously by performing all operations for each prime sequentially without conflict because they reduce different prime factors. So yes.
Thus answer is sum of max flows.
Now we need to factor numbers up to 1e9. Use trial division up to sqrt. Since n=100, we can precompute primes up to 31623 (sqrt(1e9) ≈ 31622.776). There are about 3400 primes less than 31623; that's fine to test each number by dividing by all primes up to sqrt. Or we can just do trial division by i from 2 to sqrt, but that would be about 31622 divisions per number, 100 numbers => 3.16 million, okay. But to speed up we can generate primes via sieve. We'll do that.
Implementation details:
- Read n,m.
- Read array a[1..n].
- Read m pairs, store them in list.
- Precompute primes up to 31623 using sieve.
- For each i, factor a[i] using these primes, and collect prime->exponent mapping per index. Since exponents per prime per index needed. We'll store a dictionary: for each prime p, an array of length n+1 with exponent. Or we can store map from p to list of exponents. Since we'll process each prime separately, we can extract all primes that appear in any a[i]. Let's use a global dictionary prime_to_exponents: for each prime p, a list exp[i] (i=1..n) default 0.
Factor each a[i]:
x = a[i]
for each prime p up to sqrt(x):
if p*p > x: break
cnt=0
while x%p==0:
x//=p; cnt+=1
if cnt>0: store exp[i] for p.
if x>1: then x is a prime (since sqrt leftover) or 1. If x>1, then it's a prime factor (maybe large prime <=1e9 but > sqrt) . So store exp for x (x itself is prime). Note: x could be 1 if fully factored.
After factoring all numbers, we have distinct primes.
Now for each prime p:
Build flow network with nodes:
source = 0
left nodes: indices i where i%2==1 (odd) and exp[i]>0 (we can include all, but capacity 0 if no exponent, but we can skip to reduce nodes)
right nodes: indices j where j%2==0 and exp[j]>0
sink = something.
We need to assign integer node IDs. Since n ≤100, we can just create a graph with total nodes = 2 + n? Actually we need to include all indices, even if capacity 0, but we can still include; flow will just be 0. Simpler: assign source = 0, sink = n+1. Use original indices for nodes 1..n? But we need to add edges from source to left (odd) and from right to sink. But we must ensure no edge from source to even or from odd to sink directly. So we can just build adjacency list with capacities for directed edges.
But we also need edges from left to right for good pairs.
We'll implement Dinic:
class Dinic:
def init(self, N):
self.N = N
self.adj = [[] for _ in range(N)]
def add_edge(self, u, v, cap):
self.adj[u].append([v, cap, len(self.adj[v])])
self.adj[v].append([u, 0, len(self.adj[u]) - 1])
But we need to handle multiple edges? For each good pair, we add one directed edge from left to right with INF capacity. However, there might be duplicate edges? The problem says good pairs are distinct, but there could be both (i,j) and (j,i) not possible since i<j. So each pair is unique and direction is determined by parity. So we can just add one directed edge for each pair. But could there be multiple edges connecting the same left and right nodes? Not if pairs distinct. So fine.
Capacities: source->left i: capacity = exp[i] (exponent of p at i). left->right edge: INF (we can set INF = sum_exponents_left maybe 3000). Right->sink: capacity = exp[j].
Then compute max flow.
Sum flows.
One nuance: The good pairs may be given such that both nodes belong to same parity? But condition ensures i+j odd, so they are opposite parity. So the bipartite property holds.
Now test on examples.
Example1:
n=3,m=2
a=[8,3,8]
Pairs: (1,2) -> 1+2=3 odd, good: 1 odd,2 even -> left1->right2.
(2,3) -> 2+3=5 odd, 2 even,3 odd -> left3->right2? Actually 3 odd,2 even, so left3->right2.
Now factor:
8=2^3, so exponents: index1: 2^3, index3:2^3. index2:3 prime 3^1.
Prime 2: exponents: i1=3,i2=0,i3=3. So left nodes: odd indices:1 and 3 (both odd). Right nodes: even index:2. Source->1 cap3, source->3 cap3. Right 2->sink cap0 (since exponent 0). So max flow from source to sink is 0. So sum=0.
Prime 3: exponents: i2=1 (even, right) cap=1; i1=0,i3=0. left nodes have cap0, so flow 0. Answer 0. matches.
Example2:
n=3,m=2
a=[8,12,8]
8=2^3, 12=2^2 *3, 8=2^3.
Prime 2: exponents: i1=3, i2=2, i3=3. odd indices: 1,3 (left) caps 3 and 3. even index:2 (right) cap 2. Edges: (1,2) from left1->right2; (2,3) from left3->right2. So network: source->1(3), source->3(3), 1->2 INF, 3->2 INF, 2->sink(2). Maximum flow: we can send up to 2 units from source to sink because right cap 2. So flow=2 (possible: 1 unit via 1->2, 1 unit via 3->2). So prime 2 gives 2 ops.
Prime 3: exponents: i2=1 (right) cap=1; i1=0,i3=0 left caps 0. So flow 0.
Total 2. matches output.
Thus solution works.
Now complexity: For each prime, run Dinic on graph with up to n+2 nodes, m edges plus source/sink edges (up to n). In worst case, each prime's capacities are small; total flow across all primes is O(total_exponents). Using Dinic, each augment is O(E) maybe, but we can also use scaling? But it's fine. Since total flow sum is at most 1500, even Edmonds-Karp O(VE^2) would be okay because V102, E202? Actually E = source edges (<=50? up to n) + m (<=100) + sink edges (<=n) ~ <=300. V~102. So EV small. For each prime (up to ~1000) 1000 * (small) might be up to 100010000? But wait, if we have 1000 primes, each we run Dinic from scratch, even if flow is 0 (capacities zero). That could be 1000 * (graph building + BFS/DFS). But 1000 is still okay for 2 secs? Probably yes, but we can optimize by skipping primes where total exponent sum on left or right is zero or flow potential zero. However, building the graph for each prime may be cheap. But we should be careful: the number of distinct primes might be up to about 1000 (if each number is product of distinct primes, but 1e9 limit restricts to max 9 per number, and 100 numbers could have 9100=900 distinct if all primes different. So about 900 primes. For each we run Dinic. Dinic on a graph with up to ~102 nodes and ~300 edges. The max flow per prime is at most min(total left cap, total right cap) ≤ maybe 30. So the number of augmentations (phases) in Dinic is O(sqrt(V)? Actually Dinic's complexity O(E * V^2) worst-case but with unit capacities? But here capacities are not large; number of augmenting phases is at most O(sqrt(E)?) Actually Dinic's number of BFS layers steps is O(V^2E) worst-case but typical is fast. Even if we run 900* small, it's fine. But we can also combine flow computations into a multi-commodity? No.
But we must consider that we have to factor numbers and handle large primes >31623. That's fine.
Implementation steps:
-
Read input.
-
Factor numbers:
- Precompute primes up to 31623 using simple sieve.
- For each a_i:
x = a_i
for p in primes:
if p*p > x: break
if x % p == 0:
cnt=0
while x%p==0:
x//=p; cnt+=1
store exp for i, p.
if x > 1:
store exp for i, x.
-
After factoring, we have a dict: prime -> list of exponents per index (maybe using array size n+1). Let's create a map: exponents_by_prime = {} where key = prime (int), value = list of length n+1 (index from 1 to n) with default 0. We'll fill while factoring.
Approach:
exponents_by_prime = {}
For each i in 1..n:
factorize a[i] as described; for each (p, cnt):
if p not in exponents_by_prime: exponents_by_prime[p] = [0](n+1) (or [0] (n+1) for index 0..n)
exponents_by_prime[p][i] = cnt
Since n up to 100, memory fine.
-
Determine parity: For each index i, odd = (i%2==1).
-
For each prime p in exponents_by_prime:
-
Get exp list e[1..n].
-
Compute total_left = sum(e[i] for i where i%2==1)
-
Compute total_right = sum(e[i] for i where i%2==0)
-
If total_left == 0 or total_right == 0, then flow = 0; skip to avoid building network (though would be 0 anyway).
-
Build flow network:
Node numbering: We can use original indices for simplicity? But need source and sink. Let's assign:
source = 0
nodes 1..n represent the original indices (so we don't need to remap)
sink = n+1
However, we need to add edges only from left (odd) to right (even) and also source->odd, even->sink. But we must ensure no other edges. That's fine.
So Dinic with N = n+2.
For each left node i (i odd):
if e[i] > 0: add_edge(source, i, e[i])
For each right node j (j even):
if e[j] > 0: add_edge(j, sink, e[j])
For each good pair (ik, jk):
Determine orientation:
if ik%2==1 and jk%2==0: add_edge(ik, jk, INF)
elif ik%2==0 and jk%2==1: add_edge(jk, ik, INF)
else: (shouldn't happen)
Note: We must ensure that we don't add duplicate edges if a good pair appears in both directions? It won't. But multiple pairs between same left and right? Possibly if there are two distinct pairs? But indices are distinct; there can be at most one edge between a specific left and right because pairs are unique and i<j, so (i,j) is unique. So fine.
-
INF can be set as sum of all capacities from source (or something) plus 1: e.g., INF = 10**9.
-
Compute max flow using Dinic. Add flow to answer.
-
Print answer.
Check: Are there any constraints that may require we consider composite v > 1 that is not prime? Since we want maximize operations, we will never use composite v if we can split into primes. However, is it always possible to split? Suppose we have only one operation possible because after one composite division, the numbers become coprime? But if we could do composite v, that would be one operation; if we split into prime steps, we would get multiple operations. But can we always perform the prime steps sequentially? Possibly there might be an order dependency: after dividing by p, the numbers might no longer have another common factor q that they originally had? But they originally had both p and q. After dividing by p, the numbers still have q (since dividing by p doesn't affect q). So they would still have q in common. So we can do p and q separately. So indeed splitting composite into primes yields at least as many operations, as long as the prime steps are feasible. However, what if the composite v is a power of a prime, like p^k? If both numbers have at least k copies of p, we could divide by p^k in one operation or do k operations each dividing by p. The latter gives more operations, so we would do that. So indeed maximum operations is sum over primes of the maximum number of times we can simultaneously divide that prime from pairs. So our flow approach yields maximum.
But is there any scenario where we cannot achieve the sum of per-prime maxima due to interference? Since operations on different primes are independent, we can schedule them arbitrarily. For each prime, the flow solution gives a set of operations (matching) that uses some edges. Could it be that for different primes, the same edge might be used beyond its 'capacity' in terms of node capacities? Node capacities are per prime, not shared. For prime p, node i can be used at most e_i(p) times. For prime q, node i can be used at most e_i(q) times. So they are independent; there is no conflict across primes. So we can simply sum.
Thus answer is sum.
Now verify more complex cases.
Consider n=2, m=1, a=[6,6], pair (1,2). 1 odd,2 even. a[1]=23, a[2]=23. exponents: 2: each 1; 3: each 1. For prime 2: left1 cap1, right2 cap1, edge 1->2 INF, flow=1. For prime 3: same, flow=1. total=2. Is that maximum? Possible operations: first divide by 2 (v=2): get [3,3]. Then divide by 3: get [1,1]. That's 2 operations. Could we do more? What about divide by 6 then nothing else? That's 1 operation. So max=2. OK.
Consider n=2, m=1, a=[4,4]. Both have 2^2. For prime 2: left cap=2, right cap=2, flow=2. So answer 2. Indeed we can divide by 2 twice: [4,4] -> [2,2] -> [1,1]. Could we do divide by 4 first? That's 1 operation; not max. So correct.
Consider n=4, m many edges. Let's test with overlapping.
Now we must consider that the graph might not be complete bipartite; we need matching that respects edges. The flow captures that.
Edge case: The good pairs may include indices that are both on left? No, condition prevents that.
Edge case: There might be multiple edges connecting the same left-right pair? Not if pairs distinct, but could there be (i,j) and (j,i)? Not allowed because i<j. So no.
Edge case: The same pair might be used multiple times; flow allows that.
Edge case: If there is a prime p where both sides have capacities, but the bipartite graph is disconnected, flow might be limited.
Now about INF: we need to set capacity of edges from left to right high enough not to limit flow. Since max possible flow through a specific edge is limited by min of the capacities of its endpoints (as those are the only sources). So INF = total sum of left capacities or right capacities, which is at most 3000. So we can set INF = 10**9.
Now implement Dinic:
class Dinic:
def init(self, N):
self.N = N
self.adj = [[] for _ in range(N)]
def add_edge(self, u, v, cap):
# forward edge index
self.adj[u].append([v, cap, len(self.adj[v])])
self.adj[v].append([u, 0, len(self.adj[u]) - 1])
def bfs(self, s, t):
self.level = [-1]*self.N
q = deque([s])
self.level[s] = 0
while q:
u = q.popleft()
for v, cap, rev in self.adj[u]:
if cap > 0 and self.level[v] == -1:
self.level[v] = self.level[u] + 1
q.append(v)
return self.level[t] != -1
def dfs(self, u, t, f):
if u == t:
return f
for i in range(self.it[u], len(self.adj[u])):
self.it[u] = i
v, cap, rev = self.adj[u][i]
if cap > 0 and self.level[v] == self.level[u] + 1:
ret = self.dfs(v, t, min(f, cap))
if ret > 0:
# reduce forward cap, increase reverse
self.adj[u][i][1] -= ret
self.adj[v][rev][1] += ret
return ret
return 0
def max_flow(self, s, t):
flow = 0
INF = 10**18
while self.bfs(s, t):
self.it = [0]*self.N
while True:
f = self.dfs(s, t, INF)
if f == 0:
break
flow += f
return flow
Be careful with recursion depth in dfs; we can implement iteratively or use recursion; depth at most V (100) so recursion ok.
Now about mapping: using original indices 1..n, source 0, sink n+1, N = n+2.
But we need to be careful: For right nodes (even) we add edge from node j to sink. That is fine.
One more nuance: When adding edges from source to left, we add for all left nodes regardless of capacity? If capacity 0, add_edge(source,i,0) does nothing, but we can skip to save time.
Similarly for right nodes.
Now for good pairs: need to add edges only if they connect left to right. Since condition ensures they do, but we still need to orient correctly.
Implementation steps:
-
After reading pairs, store them in list pairs.
-
For each prime:
dinic = Dinic(N)
for i in range(1,n+1):
if i%2==1 and e[i]>0:
dinic.add_edge(0, i, e[i])
elif i%2==0 and e[i]>0:
dinic.add_edge(i, n+1, e[i])
for (ik, jk) in pairs:
if ik%2==1 and jk%2==0:
# left ik, right jk
dinic.add_edge(ik, jk, INF)
elif ik%2==0 and jk%2==1:
dinic.add_edge(jk, ik, INF)
flow = dinic.max_flow(0, n+1)
ans += flow
But note: What about the case where a node is both left and right? impossible because parity is fixed.
Also, note that the graph might have edges that connect left to right but the left node might have 0 capacity; adding the edge is fine, but no flow will pass because left node has no outgoing capacity from source. Similarly, right node capacity 0 will block flow. So we could skip edges if either endpoint has 0 capacity? But not necessary.
Now need to consider that INF must be large enough. We'll set INF = 10**9.
Now what about large primes that appear many times? Each number's exponent for that prime is at most about 30, so fine.
Now testing with random small cases: We can brute force for small n and small numbers to confirm.
But we should also think about whether there is any subtlety: The operation v must divide both numbers a[ik] and a[jk] at that moment. Since we are only dividing by primes sequentially, and the flow model ensures that each node's usage does not exceed its exponent for that prime. However, does the order of operations across different primes affect ability to use the same edge for different primes? Not an issue.
But could there be a scenario where a prime p appears, but the flow solution might use an edge multiple times, but each time it consumes one from left and right. That's exactly operations. However, is it always possible to realize the flow as a sequence of operations? In flow, we get a set of paths (each is a direct edge from left to right). Each unit of flow corresponds to using a specific edge (i,j). So we have a multiset of edges. Since each edge can be used multiple times, we can just perform operations in any order, each time picking that edge and prime p. As long as we have enough exponent on both nodes for p, we can do it. So flow gives a feasible schedule. And since flow is maximum, it's optimal for that prime. So overall sum is maximum.
But we must ensure that the flow solution does not depend on the order; indeed flow decomposition yields a set of edge usages. We can execute them in any order.
Thus solution correct.
Now we need to implement factorization efficiently.
Sieve for primes up to 31623:
limit = int(sqrt(10**9)) + 1 = 31623 (maybe 31623). Actually sqrt(1e9)=31622.776... so 31623 is safe.
We can generate primes up to 31623 using simple sieve.
Implementation:
def sieve(limit):
is_prime = [True](limit+1)
is_prime[0]=is_prime[1]=False
primes=[]
for i in range(2, limit+1):
if is_prime[i]:
primes.append(i)
for j in range(ii, limit+1, i):
is_prime[j]=False
return primes
But careful: ii might overflow limit? Use range(i, limit+1, i) starting at i2? Simpler: for j in range(i*2, limit+1, i): is_prime[j]=False.
Complexity okay.
Now factorization:
def factorize(x, primes):
factors = {}
for p in primes:
if p*p > x:
break
if x % p == 0:
cnt = 0
while x % p == 0:
x //= p
cnt += 1
factors[p] = cnt
if x > 1:
factors[x] = 1
return factors
But we need to combine exponents across numbers.
We could do:
exp_by_prime = defaultdict(lambda: [0]*(n+1))
Then for each i, factors = factorize(a[i], primes). For p,cnt in factors.items(): exp_by_prime[p][i] = cnt.
But careful: Using defaultdict with lambda creates a new list each time accessed? Actually defaultdict(lambda: [0]*(n+1)) will call the lambda to generate default value when key missing. That lambda returns a new list of zeros of length n+1. So each prime gets its own list. That works.
But note: If we use [0]*(n+1) for each prime, it's okay.
Alternatively, we could store as dict of prime -> list, and after factoring all, we have list.
Now after building, iterate over items in exp_by_prime.
But we can further optimize: For each prime, we may compute total left and right sum quickly. If min(total_left, total_right)==0 then skip, flow=0.
Also, we might not need to build the flow for primes with very small capacities; but building is fine.
Now about INF: maybe we should set INF = sum(e[i] for i in left) or something but not necessary.
Now complexity: For each prime, we run Dinic. But the graph is built anew each time. That's fine.
Now potential pitfalls:
-
The problem might require to handle large exponent sums up to maybe 30 per node, but that's small.
-
There may be primes that are large (e.g., 999999937) and they appear only in one node; but flow will be 0 because only one side. So skip.
-
Need to handle that a[i] could be 1. Factorization yields empty.
-
Good pairs might have indices that have a[i] = 1; still edges exist, but capacities zero, so no flow.
Now test with a more complex example to ensure flow works.
Example: n=4, m=3
a = [2, 4, 8, 16] (but let's think) Actually we need to factor.
Let's make n=4, indices 1,2,3,4. Good pairs: (1,2), (1,4), (3,2) maybe? But need odd+even.
Indices: 1 odd,2 even,3 odd,4 even.
Pairs: (1,2) ok; (1,4) 1+4=5 odd ok; (3,2) 3+2=5 odd ok; (3,4) 3+4=7 odd ok but not needed.
Now a = [8, 12, 18, 6]? Let's compute.
Better test: prime 2 exponents:
i1=3 (8), i2=2 (12), i3=1? Actually 18=2*9 => 1, i4=1 (6). So left (odd) i1=3, i3=1; right (even) i2=2, i4=1. Edges: (1,2), (1,4), (3,2), (3,4) if all present. So bipartite graph complete between left {1,3} and right {2,4}. Capacities: source->1(3), ->3(1); right->sink: 2(2), 4(1). Maximum flow: We can send flow from left to right. This is a bipartite matching with capacities: we can send up to total left=4, total right=3, but limited by edges (which have INF). The max flow is min(total left, total right)=3? Actually total right=3, so at most 3. But can we achieve 3? Need to assign flows: left1 can send up to 3, left3 up to1. Right2 up to2, right4 up to1. With complete bipartite, we can send 2 from left1 to right2, 1 from left1 to right4? That would be left1 total 3, right2 2, right4 1, okay. So flow=3. But total exponent sum left=4, right=3, min=3, so flow=3. That uses edge (1,4) and (1,2) etc. So possible operations: 3 times divide by 2? But i3 has only exponent1, so only one operation from node3. But we used left1 for all 3? But then i3's exponent1 is unused. So we have 3 operations total. Could we get 4? No because right side only has total exponent 3. So maximum operations for prime2 is 3. Is that achievable? Yes: perform operation on (1,2) twice, (1,4) once? But after two operations on (1,2), i2 exponent becomes 0, but i2 had exponent2 initially, so okay. And i4 exponent1 used. So total 3 operations. Could we also use (3,2) to use i3's exponent? But we would exceed right2's capacity; if we did (3,2) once, then we would need to reduce one from (1,2) to keep within i2's capacity 2. That's also 3. So flow gives 3. Good.
Now overall answer sum across primes.
Now implement.
But there might be one more nuance: The operation v > 1 must be an integer divisor of both numbers. We assumed prime v is allowed. Yes, if v is prime and divides both numbers, that's valid.
Thus solution stands.
Now we should consider if we might need to account for the possibility that we can combine primes in a single operation to get more operations? That seems paradoxical: combining reduces operations. So to maximize, we split.
But is there any scenario where splitting is not possible because after performing some prime operations, the numbers might become such that another prime factor is no longer common? No, dividing by a prime p doesn't affect other prime factors. So they remain common as long as both originally had them. So splitting yields more operations.
Hence maximum is sum over primes of max matchings.
Now consider edge case: v can be 1? No, v > 1.
Now consider if a[i] = 0? No, positive integers.
Now we need to ensure that the flow model works even if the same edge is used for multiple operations but the capacities of nodes are per prime, so flow handles that via capacities on source/sink edges.
Now implement code.
Potential optimization: Instead of running Dinic for each prime separately, we could treat all primes together as a multi-commodity? Not needed.
Now final answer fits in int? Max ops <= 1500, but maybe with larger exponents? Actually a[i] up to 1e9, each a[i] max prime exponents sum could be up to floor(log2(1e9)) = 29. So total S <= 2900. So ops <= 1450. So int fine.
But wait: Could a[i] be 1e9 = 2^? Actually 2^30 is about 1e9 (2^30=1,073,741,824) but >1e9, so max exponent for 2 is 29. For 3, 3^18 > 1e9? 3^18 = 387M, 3^19=1.16B >1e9, so exponent up to 18. So sum exponents < 30. So total S <= 3000. So int fine.
Now implement.
One more thought: The flow network for each prime might have many nodes with zero capacity. But it's fine.
Now code structure:
import sys
from collections import defaultdict, deque
def sieve(limit):
is_prime = [True](limit+1)
is_prime[0] = is_prime[1] = False
primes = []
for i in range(2, limit+1):
if is_prime[i]:
primes.append(i)
for j in range(i2, limit+1, i):
is_prime[j] = False
return primes
class Dinic:
def init(self, N):
self.N = N
self.adj = [[] for _ in range(N)]
def add_edge(self, u, v, cap):
# forward: [v, cap, rev_index]
self.adj[u].append([v, cap, len(self.adj[v])])
self.adj[v].append([u, 0, len(self.adj[u])-1])
def bfs(self, s, t):
self.level = [-1]*self.N
q = deque([s])
self.level[s] = 0
while q:
u = q.popleft()
for v, cap, rev in self.adj[u]:
if cap > 0 and self.level[v] == -1:
self.level[v] = self.level[u] + 1
if v == t:
# we can continue to set levels for others? Not necessary, but we can break early? Not needed.
pass
q.append(v)
return self.level[t] != -1
def dfs(self, u, t, f):
if u == t:
return f
for i in range(self.it[u], len(self.adj[u])):
self.it[u] = i
v, cap, rev = self.adj[u][i]
if cap > 0 and self.level[v] == self.level[u] + 1:
ret = self.dfs(v, t, min(f, cap))
if ret:
self.adj[u][i][1] -= ret
self.adj[v][rev][1] += ret
return ret
return 0
def max_flow(self, s, t):
flow = 0
INF = 10**18
while self.bfs(s, t):
self.it = [0]*self.N
while True:
f = self.dfs(s, t, INF)
if f == 0:
break
flow += f
return flow
def main():
import sys
input = sys.stdin.readline
n, m = map(int, input().split())
a = list(map(int, input().split()))
# indices from 1, so a indexed 0..n-1; we'll use 1-indexed for convenience.
a = [0] + a # 1-indexed
pairs = []
for _ in range(m):
i, j = map(int, input().split())
pairs.append((i, j))
# Precompute primes up to sqrt(1e9)
limit = int(1e5) # wait sqrt(1e9)=31623, but to be safe, we can use 100000? Actually need up to 31623, but we can generate primes up to 40000.
# Let's compute max_a = max(a) maybe to limit sqrt? But a[i] up to 1e9, so sqrt = 31623. So we generate primes up to 31623.
max_val = max(a[1:])
sqrt_max = int(max_val**0.5) + 1
# Actually we need primes up to sqrt(max_val) for factorization. So compute sqrt_max = int(max_val**0.5)+1
sqrt_max = int(max_val**0.5) + 1
# Generate primes up to sqrt_max (max 31623)
primes_list = sieve(sqrt_max)
# Factorize each a[i] and accumulate exponents by prime.
from collections import defaultdict
exp_by_prime = defaultdict(lambda: [0]*(n+1))
for i in range(1, n+1):
x = a[i]
for p in primes_list:
if p*p > x:
break
if x % p == 0:
cnt = 0
while x % p == 0:
x //= p
cnt += 1
exp_by_prime[p][i] = cnt
if x > 1:
# x is prime
exp_by_prime[x][i] = 1
# Now for each prime, compute max flow.
INF = 10**9 # large enough
ans = 0
# Precompute parity for indices (odd/even) maybe boolean array.
odd = [False]*(n+1)
for i in range(1, n+1):
odd[i] = (i % 2 == 1)
for p, exp in exp_by_prime.items():
# total left (odd) and right (even) capacities
total_left = 0
total_right = 0
for i in range(1, n+1):
if exp[i] > 0:
if odd[i]:
total_left += exp[i]
else:
total_right += exp[i]
if total_left == 0 or total_right == 0:
continue
# Build Dinic
N = n + 2
source = 0
sink = n+1
dinic = Dinic(N)
# add source->left, right->sink
for i in range(1, n+1):
if odd[i] and exp[i] > 0:
dinic.add_edge(source, i, exp[i])
elif not odd[i] and exp[i] > 0:
dinic.add_edge(i, sink, exp[i])
# add edges for pairs
for (ik, jk) in pairs:
if odd[ik] and not odd[jk]:
# ik left, jk right
dinic.add_edge(ik, jk, INF)
elif not odd[ik] and odd[jk]:
# jk left, ik right
dinic.add_edge(jk, ik, INF)
flow = dinic.max_flow(source, sink)
ans += flow
print(ans)
if name == "main":
main()
Now test with provided examples.
Let's simulate manually.
Example1: as earlier gives 0.
Example2: gives 2.
Now consider another test: n=2,m=1,a=[6,6] -> 2. Our code: max_val=6, sqrt_max=3; primes up to 3: [2,3]. Factorization: a1=6: p=2 cnt1, p=3 cnt1; a2 similarly. exp_by_prime: 2: [0,1,1]; 3: [0,1,1]. odd: 1 True, 2 False. For prime2: total_left=1, total_right=1. Build graph: source->1 cap1; 2->sink cap1; edge (1,2) from pair? Pair (1,2): odd1, not odd2 => add_edge(1,2,INF). flow=1. prime3 similarly 1. total 2. OK.
Now test with n=4, m=4 (all cross pairs). a: [8,12,18,6] as earlier. Expected flow for prime2 = 3. Let's compute: exp for prime2: i1=3, i2=2, i3=1, i4=1. total_left = i1+i3=4, total_right = i2+i4=3. So flow=3. prime3: a: 12 has 3^1? Actually 12=2^23; 18=23^2; 6=23; 8 no. So exp3: i2=1, i3=2, i4=1. left: i3=2 (odd index3? 3 is odd => left) i1=0; right: i2=1, i4=1. total_left=2, total_right=2. Edges: (1,2), (1,4), (3,2), (3,4) all present. So flow for prime3 = 2? Possibly min(total_left, total_right)=2, but we need to check if the graph allows 2: left3 can send to right2 and right4, so yes. So prime3 flow=2. Sum = 5. But is that achievable? Let's simulate: Initially: a1=8 (2^3), a2=12 (2^23), a3=18 (23^2), a4=6 (23). Operations: We want max operations. For prime2: we can do 3 operations (as earlier). For prime3: we can do 2 operations. But are there dependencies? After performing prime2 operations, the numbers' exponents of 3 unchanged, so we can still do prime3 operations. However, careful: The same edge might be used for both primes, but that's fine because they are different operations at different times. So total 5. Could we do more? Possibly combine? No. So answer should be 5. Our flow sum gives 5. Let's try to construct: For prime2: use (1,2) twice and (1,4) once (or other). After those: a1: 8/2^3 =1, a2: 12/2^2=3, a4: 6/2=3? Wait: careful: a1 initially 8 =2^3, after two divides by 2 on edge (1,2) and one on (1,4): a1 divided by 2 three times -> becomes 1. a2 divided by 2 twice -> from 12 to 3 (since 12/4=3). a4 divided by 2 once -> from 6 to 3. a3 unchanged (18). Now numbers: a1=1, a2=3, a3=18 (2*3^2), a4=3. For prime3: exponents: a2=1, a3=2, a4=1. Edges: (1,2) but a1=1 no exponent; (1,4) a1=1; (3,2) (3,4) work. We can perform (3,2) and (3,4) each once: a3 divided by 3 twice? Actually we need two operations: (3,2) divides a3 and a2 by 3: a3 from 18 to 6, a2 from 3 to 1. (3,4) divides a3 and a4 by 3: a3 from 6 to 2, a4 from 3 to 1. That's two operations. So total 5. Good.
Thus flow approach works.
Now we need to ensure we handle primes > sqrt_max properly. Factorization: after dividing by small primes, if remaining x>1, it's prime (since we checked all primes up to sqrt(x) but note that if x is composite with two large prime factors > sqrt(original), but after division, x could be product of two primes? Actually when we loop over primes up to sqrt(original), after we've divided by all small primes, the remaining x may be 1 or a prime > sqrt(original) or a product of two primes both > sqrt(original). However, if x has two prime factors both > sqrt(original), their product would exceed original number (since each > sqrt(original), product > original). So that's impossible. Thus remaining x must be prime. Good.
Now the primes list we generate up to sqrt(max_val). However, if max_val is large, sqrt_max up to 31623. But after factorization, x could be a prime larger than sqrt_max; we store it as key. That's fine.
Now about INF: using 10**9 is okay. But in Dinic, we may have capacities as int, sum may be up to 3000. Using INF=1e9 is safe.
Now complexity: For each prime we run Dinic. In worst-case, number of primes maybe ~900. For each, BFS and DFS loops. With small capacities, it's fast. Should be okay.
Potential improvement: We could combine all primes into a single flow network with multiple source-sink? But not needed.
Now we need to be careful about recursion depth in DFS. Since we implement recursively, depth is at most number of nodes, about 102, safe. But Python recursion limit is typically 1000, okay.
Now one more nuance: In the Dinic implementation, we used list of lists with edges as [v, cap, rev]. However, we need to update the capacity of reverse edge when we augment. In our dfs, we used:
self.adj[u][i][1] -= ret
self.adj[v][rev][1] += ret
That modifies the second element (cap) of the forward edge and the reverse edge's cap. That works because we stored lists.
Alternatively, we could use classes, but list is fine.
Now we need to ensure we import deque.
Now test with a scenario where there are multiple edges between same left-right but with different orientation? Not possible.
Now test with n=100, m=100, all a[i]=2^29 (536870912) approx. Then each exponent 29. So total exponents S=100*29=2900. But total operations max = floor(S/2)=1450, but also limited by graph connectivity. The flow for prime2: left indices (odd) maybe ~50, each cap 29, total left ~1450, right ~1450. If graph is complete bipartite (all pairs between odd and even present), then max flow = min(total left, total right) = 1450. So answer would be 1450. But m=100 edges may not be complete; it's only 100 edges. So flow may be less. That's okay.
Now need to handle case where some indices have 0 exponent but we still add edges? Not a problem.
Now note: In our building, we add edges for all good pairs, even if capacities are zero. That's fine.
Now about memory: For each prime we rebuild Dinic; we can just create new object each time.
Now final check: Is there any possibility of integer overflow? No.
Now we should consider if the problem expects to count operations where v could be 1? No, v > 1.
Now we should test on random small cases via brute force to be extra sure. Since I'm ChatGPT, I can reason about correctness.
But let's do a small brute force mental check with n=2,m=1, a=[4,2]. 1 odd,2 even. Exponents: 2: i1=2, i2=1. Flow: source->1 cap2, 2->sink cap1, edge 1->2 INF. Max flow = 1 (limited by right cap). So answer=1. Is that maximum? Operations: we can divide by 2 once: [4,2] -> [2,1]. Then cannot divide further because a[1]=2, a[2]=1: no common divisor >1. Could we do more? If we first divide by 2? That's only one operation. Could we divide by 4? Not possible because a[2]=2 not divisible by 4. So max=1. Good.
Now test n=2,m=1, a=[2,4]. i1=2: exp i1=1, i2=2. flow = 1 (limited by left cap). Good.
Now test n=3,m=2, a=[4,4,4] pairs: (1,2) and (2,3). Exponents: prime2: i1=2, i2=2, i3=2. odd indices: 1 and 3 (if n=3: 1 odd,2 even,3 odd). left caps: 2,2; right cap: 2. Edges: (1,2): left1->right2; (2,3): left3->right2. So max flow: total right=2, left sum=4, but edges both go to same right node 2. So maximum flow cannot exceed capacity of right node 2 which is 2. So flow = 2. Is that maximum? Let's simulate: Initially [4,4,4]. We can perform two operations: using (1,2) twice? But after first operation, a1 becomes 2, a2 becomes 2. Then second operation? Could use (1,2) again? a1=2, a2=2, divide by 2 -> [1,1,4]. Now (2,3) maybe? a2=1, a3=4, no common divisor >1. Could we instead use (1,2) once and (2,3) once? After first (1,2): [2,2,4]; then (2,3): a2=2, a3=4, common divisor 2 -> [2,1,2]. That's 2 operations. Could we get 3? total exponent sum left 4, right 2 => impossible because each operation consumes one right exponent. So max 2. Good.
Now test where there are multiple right nodes, e.g., n=4, pairs complete cross. a as earlier gave 3. Good.
Now consider prime appears only on left side? flow 0. Good.
Now consider if there are multiple primes and the graph is sparse. The flow per prime is independent. So sum works.
Now potential nuance: In the operation, v must be an integer >1 dividing both numbers. If we try to use a prime p that appears only on one side, not allowed. So flow handles.
Now consider if we try to use an edge multiple times but the node capacities for that prime may be enough but the edge usage may need to be performed sequentially. That's fine.
Now everything seems consistent.
But let's read problem statement again: "In one operation you can perform a sequence of actions: * take one of the good pairs (ik, jk) and some integer v (v > 1), which divides both numbers a[ik] and a[jk]; * divide both numbers by v." It says "perform a sequence of actions" but the operation is basically as described. So it's exactly one pair and one divisor.
Now note: The problem says "Determine the maximum number of operations you can sequentially perform". So we can stop at any time; we want the maximum possible count.
Now, is there any scenario where using a composite v could enable more operations than sum of per-prime flows? That seems counterintuitive. Consider the following: Suppose we have two primes p and q, and the graph connectivity is such that using p on a certain edge might block using q on that edge later due to node capacities? But node capacities are separate for each prime; they don't interfere. So no.
But maybe there is a scenario where using a composite v could allow an operation that later enables more operations than the sum of per-prime flows? Let's think: Using composite v reduces both primes in one go, which reduces operation count by 1 compared to doing them separately. So it can't increase the count.
Thus our approach is correct.
Now confirm with more complex reasoning: The problem is essentially: We have a bipartite graph (odd vs even). Each vertex i has a multiset of prime factors. Each operation picks an edge (i,j) and a prime factor p that both currently have, and removes one copy of p from both. The goal is to maximize the number of removals. Since primes are independent, the maximum total removals is the sum over primes of the maximum number of disjoint (in the sense of vertex capacity) edge usages for that prime. That's exactly the max flow per prime.
Now prove: For each prime, the problem reduces to a bipartite "matching with capacities" where each vertex i can be incident to at most e_i(p) selected edges (edges are allowed to be used multiple times). This is equivalent to maximum b-matching in bipartite graph, which can be solved by flow. So correct.
Thus implementation is done.
Now just ensure we handle potential large prime keys in dict: we may store as int.
Now about sieve: we computed sqrt_max = int(max_val**0.5) + 1. But max_val up to 1e9, sqrt is 31622, so generating primes up to 31623 is fine. Use sieve up to 31623.
Alternatively, we could generate primes up to 31623 directly without computing max_val. But computing max_val and sqrt is fine.
Now test with random numbers.
I'll implement a small brute force for n=2,3 with small numbers to verify by mental.
For n=2,m=1,a=[6,10] = 23 and 25. Prime2: exponents 1 each, flow=1. Prime3: left exponent1, right0, so 0. Prime5: left0, right1, 0. Total=1. Can we do more than 1? Operation: divide by 2 -> [3,5], no common divisor >1. So max=1. Good.
Now a=[12,18] = 2^23 and 23^2. prime2: left exponent2, right1, flow=1. prime3: left1, right2, flow=1. total=2. Sequence: divide by 2: [6,9]; then divide by 3: [2,3]? Wait after first: 12/2=6,18/2=9 => [6,9]; common divisors: 3 divides both? 6 and 9 share 3. So second operation divide by 3: [2,3]; no more common >1. So 2 operations. Could we do 3? Not possible. So correct.
Now a=[36,54] = 2^23^2, 23^3. exponents: 2: left2, right1; 3: left2, right3. Flow: 2:1; 3: min(2,3)=2 but check connectivity: only one edge (1,2) so maximum flow for 3: left can send at most 2? But right capacity 3, left 2, edge unlimited, so flow=2. total=3. Sequence: divide by 2 once: [18,27]; then divide by 3 twice? After first 3: [18,27] divide by 3 -> [6,9]; still common 3? 6 and 9 share 3, divide by 3 -> [2,3]; total 3 operations. Could we do 4? initial exponents sum left=4 (2+2), right=4 (1+3) total S=8, max ops <= floor(8/2)=4. But is 4 possible? To achieve 4, we would need to use 4 units from left and 4 from right. But left has only 4, right 4. But prime2: left2, right1 => possible usage 1; prime3: left2, right3 => possible usage 2; total 3. So left leftover exponent? Actually left after using 1 of prime2 and 2 of prime3 = 3 used out of 4, one left exponent (which one?) left has prime2 exponent left 1 and prime3 exponent left 0? Wait left exponents: 2:2, 3:2 => after using 1 of 2 and 2 of 3, left still has one 2 left. But right: prime2 used 1 (right had 1), prime3 used 2 (right had 3, still has 1 left). So there is a leftover 2 on left and leftover 3 on right, but they are different primes, so cannot be used together. So total ops 3. So flow sum 3 matches maximum. Could we achieve 4 by using composite v? e.g., first divide by 6 (23): [6,9]; then divide by 2: [3,9]? Not common? 3 and 9 share 3, so divide by 3 -> [1,3]; total 2 operations. Or first divide by 9 (3^2)? Not possible because left has 3^2, right has 3^3 => both divisible by 9? 36 divisible by 9? 36/9=4, 54/9=6 -> yes both divisible by 9! Actually 36 divisible by 9? 94=36, yes. So we could do: operation 1: v=9 -> [4,6]; then operation 2: v=2 -> [2,3]; then operation 3: v? 2 and 3 no common divisor. So 2 ops. Worse. So can't exceed 3. So correct.
Now consider a scenario where the flow for a prime might be limited by edges not by node capacities. That's captured.
Now consider scenario where multiple primes share the same node, but the flow for each prime is computed independently, and we sum them. This is correct because each prime's operations are independent.
Now think about possibility of using v that is product of two primes simultaneously, and that might enable subsequent operations that wouldn't be possible if we did them separately? For instance, after dividing by p, maybe the numbers become coprime for q? But they initially had both p and q. Dividing by p does not remove q. So they still have q. So no. Could there be scenario where we need to preserve some factor to be able to use an edge later? Not relevant.
Thus solution stands.
Now I'll consider potential pitfalls:
-
The graph might be directed? In flow we added directed edges from left to right. But what if we have a pair (i,j) where i is even and j odd? We added edge from j (odd) to i (even). That's correct because left must be odd. However, we need to ensure that for that edge, the left node indeed belongs to left partition (odd) and right to even. In our assignment, left = odd. So (even, odd) => left = odd = j, right = even = i. So edge j->i. That's fine.
-
What about pair (i,j) where i odd, j even? We add edge i->j. Good.
-
What about pair where i odd, j odd? Not allowed.
-
What about pair where i even, j even? Not allowed.
Now, we have to confirm that all good pairs are distinct, but they could be like (1,2) and (2,1) not possible. So fine.
Now, we also need to consider that indices start at 1, and we have n up to 100, so we can precompute odd array.
Now, about the flow: When we add edge from source to left node, we use capacity = exp[i]. That's the exponent count. However, is it possible that after using that node in some operations for different primes, we exceed that node's total exponent? No, because each prime separate.
Now, about memory: The Dinic adjacency list stores edges as lists of 3 elements; we might modify them in dfs. That's fine.
Now, what about the initial factorization: For numbers like 1e9 = 1000000000 = 10^9 = 2^9 * 5^9? Actually 10^9 = (2*5)^9 = 2^9 *5^9. So exponents 9 and 9. So total exponent 18. So okay.
Now, we need to be careful about Python recursion? dfs recursion depth at most number of nodes, which is ≤ 102, safe.
Now, potential performance: In Dinic, we use BFS each time. For each prime, number of BFS layers steps is at most O(E * flow) maybe but flow small. So fine.
Now, there is also possibility of using a simpler algorithm like maximum bipartite matching with multiplicities (b-matching) by converting to flow, as we did.
Now, we must output answer as integer.
Now final code.
But before finalizing, let's think if there is any alternative interpretation: Could an operation be performed multiple times on the same pair with the same v? Yes, as long as after previous operations, both numbers are still divisible by v. Since we are dividing by v each time, if v>1 and divides both after previous divisions, we can do it again. That's equivalent to using that edge multiple times.
Now, one more nuance: In the problem statement, "take one of the good pairs (ik, jk) and some integer v (v > 1), which divides both numbers a[ik] and a[jk]; divide both numbers by v". It doesn't say that v must be prime. So our approach of splitting into prime steps is valid for maximizing count.
Now, confirm with another edge: Suppose a[ik] and a[jk] are both 4, v=4 divides both. If we take v=4 in one operation, we get 1 operation. If we take v=2 twice, we get 2 operations. So we would choose v=2 twice. So indeed max operations > 1.
Now, does there exist any constraint that v must be the same for both numbers? Yes, we divide both by the same v. So splitting into primes uses v=p each time. That's valid because p divides both at each step.
Now, all good.
Now let's test with an example where graph is not complete and the maximum per prime might require fractional assignment? But flow integrality theorem ensures integer flows.
Now, I think solution is correct.
Now we can proceed to write final answer.
But before final, consider that the exponents_by_prime might include primes that appear only in one parity side; we skip those.
Now we need to ensure that we use 1-indexed arrays consistently.
Now potential bug: In factorization, we loop over primes list, but primes list might be empty if max_val=1? But a[i] >=1, could be all ones. Then max_val=1, sqrt_max=2? Actually max_val=1, sqrt_max=int(1**0.5)+1 = 1+1=2. sieve(2) returns primes up to 2: [2]? Actually 2 is prime, but sqrt_max=2, so primes_list=[2]? In sieve(2), we generate primes: is_prime[0]=F, [1]=F, then i=2: is_prime[2] True -> add 2. That's fine. Then factorization for a[i]=1: x=1. Loop over primes: p=2, check pp > x? 22 >1 => break. So x>1? no. So no factors stored. So exp_by_prime remains empty. Then answer 0. Good.
But if max_val=0? Not possible.
Now check for a[i]=0? Not allowed.
Now one more nuance: In factorization, we used primes up to sqrt_max, but sqrt_max computed from max_val. For numbers like 10^9, sqrt_max=31623. But after division, the remaining x might be a prime >31623, which we add as a factor. So fine.
Now, about the time: Factorization for 100 numbers with primes up to 31623: about 3400 primes, but we break early when p*p > x. So for each number, we check only primes up to sqrt(x). So on average maybe 100-200 divisions. So total about 20k divisions, fine.
Now, is there any requirement to consider that the good pairs condition ik+jk odd ensures bipartite? Yes.
Now, think about potential alternative: Could we treat all primes together as a multi-commodity flow? But we already decided separate.
Now, final code: we'll implement everything as described.
We'll also include from collections import deque, defaultdict.
Now final answer.
But wait: The problem statement says "In one operation you can perform a sequence of actions: * take one of the good pairs (ik, jk) and some integer v (v > 1), which divides both numbers a[ik] and a[jk]; * divide both numbers by v, i. e. perform the assignments: a[ik] = a[ik] / v; a[jk] = a[jk] / v." So it's exactly one action per operation.
Now, we should output answer as integer.
Now I think we are done.
Now, I'll write final solution.
But there is a nuance: The flow network we construct uses directed edges from left to right with INF capacity. However, the operations are symmetric; we could also have flow from source to right and left to sink if we swapped partitions. But our orientation is fine. Because the flow must go from source (left) to sink (right). Since we assign left = odd, right = even. That's correct because edges are always from odd to even? Actually edges are undirected; we orient them from left to right. So if we had set left = even, right = odd, then we would need to add edges from even to odd. Both ways work as long as we are consistent. Our approach with condition ensures we add edges in direction from odd to even. So fine.
Now, what about the case where there is a good pair (i,j) with i even, j odd: we add edge from j (odd) to i (even). That is from odd to even. Good.
Now, check: In our code we have:
if odd[ik] and not odd[jk]:
dinic.add_edge(ik, jk, INF)
elif not odd[ik] and odd[jk]:
dinic.add_edge(jk, ik, INF)
Yes.
Now, we also need to ensure that we add edges only once. That's done.
Now, test with small example where n=2, (1,2) works.
Now, consider n=3, good pairs: (2,3) only. Then odd indices: 1,3; even:2. Pair (2,3): i=2 even, j=3 odd => we add edge from j=3 to i=2 (odd->even). So source->3 (if exp) and 2->sink. That's correct.
Now, consider n=3, pairs: (1,2) and (2,3). That's earlier.
Now, we need to verify that the flow can use both edges. Good.
Now, finalize.
But wait: There might be a scenario where using a composite v could be necessary to achieve the maximum count? That would be counterintuitive, but let's examine thoroughly.
Suppose we have three primes p,q,r and the graph is such that the maximum per-prime flows cannot be achieved simultaneously because they would conflict on edge usage? But earlier we argued they are independent because node capacities are per prime. However, edges are not limited in capacity, so they can be used arbitrarily many times across primes. So no conflict. So we can achieve each prime's max flow independently. Therefore, sum of maxima is achievable. So no need for composite.
What about a situation where you need to use a composite v to "preserve" some prime factor for later use? For example, if you divide by p, you might reduce a number's value such that it becomes odd (if p=2) and then you cannot use an edge that requires evenness? But that doesn't affect other primes. So no.
Thus it's safe.
Now, final answer.
Now, note: The problem constraints: n,m up to 100. a[i] up to 1e9. So we need to be careful with Python's recursion depth? Not a problem.
Now, I will write final solution code.
But let's also consider potential improvements: We can precompute the edges orientation once, storing for each pair the (left,right) ordered version. That may speed up building for each prime. But not necessary.
Implementation: before prime loop, compute list of oriented pairs: for each (ik,jk) compute (left,right) where left is odd index, right is even. So:
oriented_pairs = []
for (ik,jk) in pairs:
if odd[ik] and not odd[jk]:
oriented_pairs.append((ik, jk))
elif not odd[ik] and odd[jk]:
oriented_pairs.append((jk, ik))
else:
pass # shouldn't happen
Then for each prime, add all oriented_pairs with INF.
That reduces repeated condition checks. We'll implement that.
Also, we can compute list of left nodes and right nodes for each prime? But we already do loop.
Better: We'll compute left_indices and right_indices globally: left_idx = [i for i in range(1,n+1) if odd[i]]; right_idx similarly.
Then for each prime, we iterate through these lists to add source/sink edges if exp>0.
Now code:
def main():
import sys
from collections import defaultdict, deque
input = sys.stdin.readline
n, m = map(int, input().split())
a = [0] + list(map(int, input().split()))
pairs = [tuple(map(int, input().split())) for _ in range(m)]
# parity
odd = [False]*(n+1)
for i in range(1,n+1):
odd[i] = (i%2==1)
# precompute oriented pairs: (left,right) where left is odd, right even
oriented = []
for i,j in pairs:
if odd[i] and not odd[j]:
oriented.append((i,j))
elif not odd[i] and odd[j]:
oriented.append((j,i))
else:
# according to problem, shouldn't happen, but just in case skip
pass
# factorize
max_val = max(a[1:])
sqrt_max = int(max_val**0.5) + 1
primes_list = sieve(sqrt_max)
exp_by_prime = defaultdict(lambda: [0]*(n+1))
for idx in range(1, n+1):
x = a[idx]
for p in primes_list:
if p*p > x:
break
if x % p == 0:
cnt = 0
while x % p == 0:
x //= p
cnt += 1
exp_by_prime[p][idx] = cnt
if x > 1:
exp_by_prime[x][idx] = 1
INF = 10**9
source = 0
sink = n+1
ans = 0
# precompute left_indices and right_indices
left_indices = [i for i in range(1,n+1) if odd[i]]
right_indices = [i for i in range(1,n+1) if not odd[i]]
for p, exp in exp_by_prime.items():
total_left = 0
for i in left_indices:
total_left += exp[i]
total_right = 0
for j in right_indices:
total_right += exp[j]
if total_left == 0 or total_right == 0:
continue
dinic = Dinic(n+2)
# source to left
for i in left_indices:
cap = exp[i]
if cap > 0:
dinic.add_edge(source, i, cap)
# right to sink
for j in right_indices:
cap = exp[j]
if cap > 0:
dinic.add_edge(j, sink, cap)
# oriented edges
for u,v in oriented:
dinic.add_edge(u, v, INF)
flow = dinic.max_flow(source, sink)
ans += flow
print(ans)
Now we need to define sieve and Dinic class outside main.
We'll also ensure that INF is not too high to cause overflow in DFS? In DFS we use min(f, cap) and INF=10**18, so fine.
Now we also need to consider that for each prime, we create a new Dinic with N=n+2. That's fine.
Now test with the given examples:
Example1:
3 2
8 3 8
1 2
2 3
odd:1,3 odd;2 even.
oriented: (1,2) (since odd,even) -> (1,2); (2,3) -> (3,2) because 2 even,3 odd => (3,2). So oriented = [(1,2),(3,2)].
exp_by_prime: 2: [0,3,0,3] (indices 1..3), 3: [0,0,1,0]? Actually a[2]=3 gives exp3 at index2 =1. So for prime2: left indices: 1,3 caps 3,3; right indices: 2 cap 0. total_left=6? Actually a[1]=3? Wait a[1]=8 (exp2=3), a[2]=3 (exp2=0), a[3]=8 (exp2=3). So total_left=3+3=6, total_right=0 => skip. prime3: left caps: 1? left indices 1,3: exp3 at index1? a[1]=8 =>0; index3=8 =>0; so total_left=0; skip. ans=0. Good.
Example2:
3 2
8 12 8
exp2: i1=3,i2=2,i3=3. left caps: 3,3; right cap:2. total_left=6, total_right=2 >0. Build network: source->1(3),->3(3); 2->sink(2); edges (1,2),(3,2). Flow computed: max flow = 2. ans=2. Good.
Now consider test with prime > sqrt, e.g., n=2,m=1, a=[999999937, 9999999372? But 999999937 is a prime near 1e9. a[1]=999999937, a[2]=9999999372? But a[2] must be <=1e9, 9999999372 > 1e9, not allowed. So maybe a[1]=999999937, a[2]=999999937? That's 1e9? Actually 9999999371 = 999999937, both <=1e9. So a=[999999937, 999999937]. Factorization: after small primes, x remains 999999937, which > sqrt_max? sqrt(1e9)=31623, so 999999937 > 31623, so it will be treated as prime. So exp_by_prime[999999937] = [0,1,1]. left indices: 1 odd cap1, right indices:2 even cap1. total_left=1, total_right=1. Build network: source->1 cap1; 2->sink cap1; oriented: (1,2) from pair? Assume pair (1,2) provided. Then flow=1. ans=1. Good.
Now, one more nuance: The problem says "m good pairs of integers (i1, j1), (i2, j2), ..., (im, jm). Each good pair meets conditions: ik + jk is an odd number and 1 ≤ ik < jk ≤ n." It's guaranteed that all the good pairs are distinct. So we treat each as an edge.
Now, is there any scenario where the bipartite graph might be directed? No.
Now, final code.
Now we need to ensure we import sys, collections.
Now, also in sieve function, we should set limit properly. Using sqrt_max which is at most 31623. But if max_val=1, sqrt_max=2, we generate primes up to 2. That's fine.
But note: When max_val=1, sqrt_max=2, sieve returns [2]. That's okay. But if we have a number = 2, factorization works.
But there is a slight inefficiency: we generate primes up to sqrt_max which may be as low as 2. That's fine.
Now, I'll write final code.
But let's also think about the scenario where there are large numbers that are squares of primes just above sqrt_max? For example, if max_val = 31607^2 ≈ 999 million? Actually 31607^2 = 999,000,? Let's compute: 31607^2 = 998,? Anyway, sqrt_max = int(sqrt(max_val))+1. If max_val = 31607^2 (which is about 999,000,000), sqrt(max_val) ≈ 31607, so sqrt_max = 31608. That includes the prime 31607. Good. So factorization will catch that prime when we loop through primes up to sqrt_max. Since we generate primes up to sqrt_max, we will include that prime if it is prime. So fine.
Now, we must be careful about the case where a[i] contains a factor that is a square of a prime > sqrt_max? Not possible, because if prime > sqrt_max, its square > max_val, so it cannot appear with exponent >=2. So at most one factor > sqrt_max remains, which is prime.
Thus factorization is correct.
Now, final code.
But before finishing, I'll also consider if there is any possibility to use the same prime factor multiple times on different edges from the same node; flow handles that because node capacity limits total usage.
Now, we should consider the possibility of using a prime factor to divide a number more times than its exponent? Not allowed.
Now, final answer.
I think this is the intended solution.
Now, I'll produce the final answer in the required format.
But wait: I recall that there is a known Codeforces problem "Good Pairs" or something? Actually it's CF Round? Possibly problem "Maximum Number of Operations" from some contest. The solution described in editorial is exactly max flow per prime.
Thus correct.
Now, I'll output final code. ```python
import sys
from collections import defaultdict, deque
---------- Sieve of Eratosthenes ----------
def sieve(limit):
is_prime = [True] * (limit + 1)
is_prime[0] = is_prime[1] = False
primes = []
for i in range(2, limit + 1):
if is_prime[i]:
primes.append(i)
for j in range(i * 2, limit + 1, i):
is_prime[j] = False
return primes
---------- Dinic max flow ----------
class Dinic:
def init(self, n):
self.n = n
self.adj = [[] for _ in range(n)]
def add_edge(self, u, v, cap):
# forward edge
self.adj[u].append([v, cap, len(self.adj[v])])
# backward edge
self.adj[v].append([u, 0, len(self.adj[u]) - 1])
def bfs(self, s, t):
self.level = [-1] * self.n
q = deque([s])
self.level[s] = 0
while q:
u = q.popleft()
for v, cap, _ in self.adj[u]:
if cap > 0 and self.level[v] == -1:
self.level[v] = self.level[u] + 1
q.append(v)
return self.level[t] != -1
def dfs(self, u, t, f):
if u == t:
return f
for i in range(self.it[u], len(self.adj[u])):
self.it[u] = i
v, cap, rev = self.adj[u][i]
if cap > 0 and self.level[v] == self.level[u] + 1:
ret = self.dfs(v, t, min(f, cap))
if ret:
self.adj[u][i][1] -= ret
self.adj[v][rev][1] += ret
return ret
return 0
def max_flow(self, s, t):
flow = 0
INF = 10**18
while self.bfs(s, t):
self.it = [0] * self.n
while True:
pushed = self.dfs(s, t, INF)
if not pushed:
break
flow += pushed
return flow
---------- Main ----------
def main():
input = sys.stdin.readline
n, m = map(int, input().split())
a = [0] + list(map(int, input().split())) # 1‑indexed
pairs = [tuple(map(int, input().split())) for _ in range(m)]
# parity of indices
odd = [False] * (n + 1)
for i in range(1, n + 1):
odd[i] = (i % 2 == 1)
# reorient edges: from odd (left) to even (right)
oriented = []
for i, j in pairs:
if odd[i] and not odd[j]:
oriented.append((i, j))
elif not odd[i] and odd[j]:
oriented.append((j, i))
# the problem guarantees i+j odd, so no other case
# factorisation
max_val = max(a[1:])
sqrt_max = int(max_val**0.5) + 1
primes_list = sieve(sqrt_max)
# exponents[prime][index]
exp_by_prime = defaultdict(lambda: [0] * (n + 1))
for idx in range(1, n + 1):
x = a[idx]
for p in primes_list:
if p * p > x:
break
if x % p == 0:
cnt = 0
while x % p == 0:
x //= p
cnt += 1
exp_by_prime[p][idx] = cnt
if x > 1: # remaining prime factor
exp_by_prime[x][idx] = 1
# pre‑compute left / right node lists
left_nodes = [i for i in range(1, n + 1) if odd[i]]
right_nodes = [i for i in range(1, n + 1) if not odd[i]]
INF = 10**9
source = 0
sink = n + 1
answer = 0
for p, exp in exp_by_prime.items():
# total capacity on each side
total_left = sum(exp[i] for i in left_nodes)
total_right = sum(exp[i] for i in right_nodes)
if total_left == 0 or total_right == 0:
continue
dinic = Dinic(n + 2)
# source -> left
for i in left_nodes:
cap = exp[i]
if cap:
dinic.add_edge(source, i, cap)
# right -> sink
for j in right_nodes:
cap = exp[j]
if cap:
dinic.add_edge(j, sink, cap)
# oriented edges (odd -> even) with infinite capacity
for u, v in oriented:
dinic.add_edge(u, v, INF)
flow = dinic.max_flow(source, sink)
answer += flow
print(answer)
if name == "main":
main()