Xenia is an amateur programmer. Today on the IT lesson she learned about the Hamming distance.
The Hamming distance between two strings s = s1s2... sn and t = t1t2... tn of equal length n is value . Record [si ≠ ti] is the Iverson notation and represents the following: if si ≠ ti, it is one, otherwise — zero.
Now Xenia wants to calculate the Hamming distance between two long strings a and b. The first string a is the concatenation of n copies of string x, that is, . The second string b is the concatenation of m copies of string y.
Help Xenia, calculate the required Hamming distance, given n, x, m, y.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 1012). The second line contains a non-empty string x. The third line contains a non-empty string y. Both strings consist of at most 106 lowercase English letters.
It is guaranteed that strings a and b that you obtain from the input have the same length.
Output
Print a single integer — the required Hamming distance.
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
100 10
a
aaaaaaaaaa
Output
0
Input
1 1
abacaba
abzczzz
Output
4
Input
2 3
rzr
az
Output
5
Note
In the first test case string a is the same as string b and equals 100 letters a. As both strings are equal, the Hamming distance between them is zero.
In the second test case strings a and b differ in their 3-rd, 5-th, 6-th and 7-th characters. Thus, the Hamming distance equals 4.
In the third test case string a is rzrrzr and string b is azazaz. The strings differ in all characters apart for the second one, the Hamming distance between them equals 5.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
We need to compute Hamming distance between a and b where a = x repeated n times, b = y repeated m times, and the total lengths are equal: |a| = n * |x|, |b| = m * |y|, and they are equal. So we have n*|x| = m*|y| = L.
We need Hamming distance = sum_{i=0}^{L-1} [a[i] != b[i]].
We have two periodic strings: a repeats pattern x of length lenX, b repeats pattern y of length lenY.
We need to compute mismatches over the whole length L = LCM(nlenX? Actually L = nlenX = m*lenY). But note n and m are huge (up to 1e12), and lenX, lenY up to 1e6. So L could be up to 10^12 * 10^6 = 10^18? But we are given that the total length L is the same; but n and m can be large and the strings lengths can also be large, but it's guaranteed that total length L is the same and presumably fits within 64-bit? Actually constraints: n,m ≤ 10^12, |x|,|y| ≤ 10^6, so L can be as large as 10^18, which fits in 64-bit (2^63 ~9e18). So we need to compute Hamming distance without iterating over each character.
We have two periodic sequences with periods lenX and lenY respectively. The combined period of both (the lcm of the periods) is the length after which the alignment of positions modulo lenX and modulo lenY repeats. Actually consider index i from 0 to L-1. a[i] = x[i mod lenX], b[i] = y[i mod lenY]. So Hamming distance = sum_{i=0}^{L-1} f(i mod lenX, i mod lenY) where f(p,q) = [x[p] != y[q]].
We can group positions i by the pair (i mod lenX, i mod lenY). The pattern of pairs repeats every T = lcm(lenX, lenY). Because after T steps, both mod cycles align. However, note L may not be a multiple of T? Since L = nlenX = mlenY, is L a multiple of T? Let's check: L is a common multiple of lenX and lenY? L = nlenX is a multiple of lenX; L = mlenY is a multiple of lenY. So L is a common multiple of lenX and lenY, so it is a multiple of lcm(lenX, lenY) (since lcm is the least common multiple, any common multiple is a multiple of lcm). Yes, L is a multiple of T because L is a common multiple of lenX and lenY. So L = k * T for some integer k.
Thus we can compute Hamming distance = k * (sum over all positions in one period T of mismatches) plus possible leftover? Since L is multiple of T, no leftover.
But careful: L may be huge and T may also be huge? lenX and lenY up to 10^6, so T = lcm(lenX, lenY) could be up to about 10^12 (if they are coprime and each 10^6). Actually product of two numbers up to 1e6 is 1e12, so lcm could be up to about 1e12. That's still manageable in terms of memory? We cannot allocate array of size up to 1e12. But we don't need to iterate over each position in T if T is large. However, we need to compute sum of mismatches over the period efficiently, maybe using number theory.
We need to compute total mismatches over the whole L. The period T = lcm(lenX, lenY). Let lenX = A, lenY = B. Then T = L0 = lcm(A,B). Then L = nA = mB = some common multiple. Let k = L / T.
We need to compute the number of positions i in [0, T-1] such that x[i mod A] != y[i mod B].
But we cannot iterate over T if T is up to 1e12. However, we can think of using the structure: we need to count mismatches for pairs (p,q) that occur as positions i such that i mod A = p, i mod B = q. For a given pair (p,q), when does such i exist in a period? The Chinese remainder theorem says that there is either 0 or T/A? Actually we need to consider the frequency of each pair (p,q) within one period T. For each p in [0,A-1], q in [0,B-1], the condition i ≡ p mod A, i ≡ q mod B has a solution iff p ≡ q (mod g) where g = gcd(A,B). If solution exists, then within [0,T-1] there are exactly g solutions? Wait, careful: For given p and q, the set of integers i satisfying i ≡ p (mod A) and i ≡ q (mod B) is either empty or an arithmetic progression with difference LCM(A,B)=T. Actually if there is a solution i0, then all solutions are i = i0 + tT, t integer. So within a complete period of length T, there is exactly one solution (i0 modulo T) if solution exists. Since we are considering i from 0 to T-1, each such pair (p,q) that is compatible appears exactly once. Because T is the least common multiple, the mapping from i in [0,T-1] to (i mod A, i mod B) is a bijection onto the set of compatible pairs? Let's examine: There are T numbers i in [0,T-1]. The total number of compatible pairs (p,q) such that p ≡ q mod g is exactly T. Since A * B / g = lcm(A,B) * g? Actually, the number of pairs (p,q) with 0≤p<A, 0≤q<B and p≡q mod g is exactly AB/g? Let's compute: For each p, q must be in set {p, p+g, p+2g,...} mod B. There are B/g such q that are congruent to p mod g? Actually q must satisfy q ≡ p (mod g). Since q ∈ [0,B-1], the number of solutions for q given p is exactly B/g (because residues mod B that are ≡ p mod g are spaced by g, and there are B/g such residues). So total pairs = A * (B/g) = AB/g. But T = AB / g. So indeed A*B/g = T. So there are exactly T compatible pairs. And each i in [0,T-1] yields a distinct pair (i mod A, i mod B), and all such pairs are compatible. Therefore mapping i -> (i mod A, i mod B) is a bijection from [0,T-1] to the set of compatible pairs. So indeed in one period, each compatible pair occurs exactly once.
Thus sum over i in [0,T-1] of mismatches = number of compatible pairs (p,q) such that x[p] != y[q].
So total Hamming distance = k * M, where M = number of pairs (p,q) with p∈[0,A-1], q∈[0,B-1], p≡q (mod g) and x[p] != y[q].
So we need to compute M efficiently without iterating over all T (which could be up to 1e12) but we can perhaps iterate over one of the strings and compute counts per residue class modulo g.
Observe condition p ≡ q (mod g). Let g = gcd(A,B). Write A = g * a, B = g * b, with gcd(a,b)=1. Then p and q can be represented as p = p_group * g + r? Actually residues modulo g: Let r = p mod g, which is same as q mod g. Since p and q range 0..A-1 and 0..B-1 respectively, we can group by r = 0..g-1. For each fixed residue r, the positions p in x with p ≡ r (mod g) and similarly q in y with q ≡ r (mod g). Then the condition p≡q mod g is exactly that r matches. For each r, we have a set of indices in x: indices = { r, r+g, r+2g, ..., up to < A } - there are a indices (since A = g*a). Similarly in y: b indices.
Now for each r, the mapping between p and q in the period T? For the period, the compatible pairs (p,q) with given r are all pairs (p,q) where p from the set X_r (size a) and q from Y_r (size b). But note: in the period, we have exactly one occurrence for each compatible pair? Let's check: Total pairs across all r: sum over r of ab = g * a * b = AB/g = T. Indeed, for each r, there are ab compatible pairs. But do all such pairs actually occur in the period? According to the bijection argument, yes, all compatible pairs occur exactly once. So for each residue r, we need to count over all (p in X_r, q in Y_r) whether x[p] != y[q]. Then M = sum_{r=0}^{g-1} count_mismatch(X_r, Y_r). So we need to compute for each r: given two strings: the characters of x at indices congruent to r mod g (which we'll denote x_r of length a) and characters of y at indices congruent to r mod g (denoted y_r of length b). And we need to count the number of pairs (i in [0,a-1], j in [0,b-1]) such that x_r[i] != y_r[j]. That total number of pairs is ab, and the mismatches count = a*b - matches, where matches = number of pairs with equal characters. So for each r, we need to compute the number of equal pairs between multiset of characters in x_r and y_r.
Thus matches for residue r = sum_{c in alphabet} count_x_r[c] * count_y_r[c]. Because each pair (i,j) where x_r[i]=c and y_r[j]=c contributes one match.
Thus total matches across all residues = sum_{r} sum_c cnt_x[r][c] * cnt_y[r][c].
Total number of positions L = nA = mB. But careful: Our M is computed over one period T, which includes all compatible pairs. And total Hamming distance = k * M, where k = L/T = (nA) / (AB/g) = n * g / B? Let's compute: L = nA = n * g * a. T = AB/g = ga * gb / g = gab. So k = L/T = nga / (gab) = n/b. But also L = mB = mgb, so k = mgb/(gab) = m/a. So k = n/b = m/a. Since L is common multiple, n/b and m/a must be integers. Indeed, given the constraint that L is equal, we have nA = mB => n * ga = m * gb => na = m*b. Since a and b are coprime (since we divided by gcd), it follows that n is multiple of b and m is multiple of a. So k = n/b = m/a is integer. Good.
Thus total Hamming distance = k * M = (n/b) * M.
Alternatively, we can compute directly as L - total matches over whole length. But careful: The total matches over whole length is k * (sum_r matches_r) because the pattern repeats k times. But we need to ensure that the period indeed repeats exactly k times. Since L = k*T, yes.
Thus the problem reduces to: given A, B, strings x (length A), y (length B), g = gcd(A,B), a = A/g, b = B/g. Compute for each residue class r from 0 to g-1, the count vectors of characters from x and y for indices ≡ r mod g. Then compute matches_r = sum_c cnt_x_r[c] * cnt_y_r[c]. Then M = sum_r (ab - matches_r) = gab - sum_r matches_r. But ga*b = T, which is the period length. So M = T - total_matches_per_period.
Then answer = k * M = (n/b) * (T - total_matches) = L - k * total_matches.
But note total matches over whole string = k * total_matches_per_period. So answer = L - total_matches.
So we could also compute total matches directly: For each r, matches from that residue class over the whole length? Actually each residue class repeats? Let's think: The whole string of length L can be seen as k repetitions of the period. In each period, for each r, we have a*b pairs, but they are not directly matches between characters? Wait, careful: The matches we computed per period M matches is the number of positions i in [0,T-1] where x[i mod A] == y[i mod B]. So total matches over entire length = k * matches_per_period. So total mismatches = L - total_matches.
Thus answer = L - total_matches.
Thus the core is to compute total_matches = k * sum_r (sum_c cnt_x_r[c] * cnt_y_r[c]).
But we need to compute sum_r cnt_x_r[c] * cnt_y_r[c] efficiently. Since g could be up to 10^6 (since A,B up to 10^6, g ≤ min(A,B) ≤ 10^6). That's okay to loop over r from 0 to g-1, but for each r we need to compute character counts. However, A and B may be up to 10^6 each, so iterating over all characters to build counts per residue is feasible: we can iterate over indices of x and add to count[r][char] for r = index % g. But note that g could be up to 10^6 and characters 26, so a 2D array of size g26 (max 26e6) is okay in memory? 26 million integers (4 bytes each = 104 MB) might be borderline but acceptable? However we need two such arrays for x and y. That's ~200 MB, maybe too high. But we can use one array for counts per residue: we need cnt_x[r][c] and cnt_y[r][c]. Could store as two separate arrays or combined. 26e6 64-bit ints would be 208 MB; with 32-bit ints (since counts per residue for a single string per residue: the count of a character in that residue class cannot exceed a = A/g ≤ A ≤ 1e6? Actually the number of indices in x with a given residue r is either floor((A-1 - r)/g)+1 = a (since A = ga, exactly a indices per residue). So count per char ≤ a ≤ 1e6. So 32-bit int is enough. But 2 arrays of 26e6 ints: 2 * 26e6 * 4 = 208 MB. That's too high for typical contest memory limits (usually 256 MB maybe but borderline). However, we might be able to compute matches without storing full 2D arrays. For each residue r, we need to compute dot product of count vectors. We could iterate over x and y and for each pair of positions? That would be too many.
Alternative: Since the alphabet is small (26), we can for each residue r compute the counts on the fly by scanning x and y and accumulating counts in arrays of size 26 per residue? But that still requires storing counts for each residue. However, we can compute matches by iterating over one of the strings and for each index, we can compute contributions to matches based on counts from the other string? Let's think.
We have total matches = sum_{i=0}^{L-1} [x[i mod A] == y[i mod B]]. But we cannot iterate L.
We have derived total_matches = k * sum_{r=0}^{g-1} sum_c cnt_x_r[c] * cnt_y_r[c].
So we need to compute S = sum_{r=0}^{g-1} sum_c cnt_x_r[c] * cnt_y_r[c].
We can compute cnt_x_r[c] and cnt_y_r[c] by iterating over x and y once: for each position p in x, compute r = p % g, increment cnt_x[r][char]; similarly for y. So we need to store cnt_x and cnt_y as 2D arrays. But we can reduce memory by storing only one of them and compute S on the fly? For example, we can compute cnt_x first, then iterate over y and for each position compute its residue r and char, and then we need to add cnt_x[r][char] to some accumulator? But careful: S = sum_r sum_c cnt_x_r[c] * cnt_y_r[c]. If we have cnt_x precomputed, then while iterating y we can accumulate for each position: for each y position q with residue r and char c, we want to add cnt_x_r[c] multiplied by the number of times that char appears at residue r in y. But each occurrence in y will contribute cnt_x_r[c] to the product, but the product is count_x * count_y, not sum over occurrences. So if we process y, we could maintain cnt_y per residue and then after full counting, compute dot products. But that still requires storing cnt_y per residue to compute dot product with cnt_x. But we can compute dot product on the fly if we iterate over y and for each occurrence, we add cnt_x_r[c] to a total sum, but that would give sum_r sum_c cnt_x_r[c] * (number of occurrences of c in y at residue r?) Actually if we do: for each occurrence in y of (r,c), we add cnt_x_r[c]. Then after processing all y, the sum would be sum_{r,c} cnt_x_r[c] * cnt_y_r[c] because each occurrence contributes cnt_x_r[c], and there are cnt_y_r[c] occurrences. Yes! That works. So we don't need to store cnt_y at all. We just need cnt_x[r][c] for all residues and chars. Then we iterate over y, for each index q, compute r = q % g, char = y[q], and add cnt_x[r][char] to S. That yields S exactly. Because S = sum_{r,c} cnt_x_r[c] * cnt_y_r[c] = sum_{r,c} cnt_x_r[c] * (number of times char c appears in y at residue r) = sum over each occurrence in y of cnt_x_r[c].
So algorithm:
Compute A = len(x), B = len(y). g = gcd(A,B). a = A/g, b = B/g.
Compute L = n * A (or m * B) as 64-bit (but careful with overflow? up to 1e18 fits in 64-bit). Actually we can compute L = n * A (since n up to 1e12, A up to 1e6 => product up to 1e18, fits in unsigned 64-bit. In C++ with signed 64-bit it's okay as 1e18 < 9.22e18).
Compute k = n / b = m / a (but we don't necessarily need k if we compute total matches directly as k * S? Wait we need total matches = k * S? Because S = sum_r matches_per_period? Let's check: S = sum_r sum_c cnt_x_r[c] * cnt_y_r[c] = matches_per_period? Actually earlier we defined matches_per_period = sum_r matches_r, where matches_r = sum_c cnt_x_r[c] * cnt_y_r[c] because per residue the number of matches contributed by that residue within one period equals that dot product. Let's verify:
In one period, for a fixed residue r, we have a indices from x (actually positions i in x_r) and b indices from y (y_r). For each pair (p in X_r, q in Y_r), we have a distinct i in the period? Actually in the period mapping i -> (p,q) is bijective, so the number of i such that i mod A = p and i mod B = q is exactly 1 for each compatible pair. So the total number of positions i in the period where x[p] == y[q] is exactly the number of compatible pairs (p,q) with equality. That can be computed as: for each r, for each char c, count_x_r[c] * count_y_r[c] because each such pair (p with char c, q with char c) yields equality. So matches_per_period = sum_r sum_c cnt_x_r[c] * cnt_y_r[c]. Yes.
Thus S = matches_per_period.
Now total matches over whole length = k * S, where k = L / T.
But we computed S using cnt_x only, and we want total matches = k * S.
However we can compute total matches directly as: For each occurrence in y (of which there are total mB = L), we consider its contribution? Wait, if we iterate over y and add cnt_x[r][char] for each occurrence, we get sum_{occurrence in y} cnt_x[r][char]. But each occurrence in y corresponds to a specific index in b. However, total matches is not simply that sum. Let's analyze: total matches = number of positions i in [0,L-1] where a[i] == b[i]. We derived it equals k * sum_r sum_c cnt_x_r[c] * cnt_y_r[c]. How can we compute it directly from cnt_x and scanning y? The sum over y occurrences of cnt_x[r][char] gives sum_r cnt_y_r[c] * cnt_x_r[c] = S. That's matches per period, not total matches. So we need to multiply by k. But note that when we scan y, we are scanning the whole string b? Actually y is repeated m times to form b. The total length of b is L. So if we scan the pattern y (length B) and consider its occurrences repeated m times, we might need to account for the repetitions? The count vector cnt_y_r we computed from the pattern y (single copy) corresponds to counts per residue over one copy of y. But the total occurrences in b of a given residue r and character c is m * cnt_y_r[c] (since each copy of y contributes same counts). Indeed, total counts over b: cnt_total_y[r][c] = m * cnt_y_r[c]. And similarly for x pattern, total counts over a: cnt_total_x[r][c] = n * cnt_x_r[c]. But careful: In the whole strings a and b, each position i corresponds to some residue r = i mod g (since g divides both A and B? Actually i mod g: if we compute r = i mod g, does it align with p mod g? Since A and B are multiples of g, i mod A gives p, and i mod B gives q, and we have p ≡ i mod g, q ≡ i mod g, so indeed r = i mod g is the residue class. So we could think of grouping positions in the whole strings by residue r. Then total number of positions with residue r in a is n * a (since per copy of x we have a indices per residue) = n * a. Similarly in b: m * b. But the matches per residue across the whole strings would be something like? We could compute total matches = sum_r sum_c cnt_total_x[r][c] * cnt_total_y[r][c]? Not exactly, because not every pair of positions from a and b with same residue r are aligned; the alignment is more specific: each position i in the combined string pairs a[i] and b[i]; the i's residue r determines which positions from a and b are paired: for each i, the character from a is from some p in x (with residue r) and from b is from some q in y (with residue r). But the pairing between specific p and q is determined by the index i. However, if we think of the whole string as k repetitions of the period, within each period, the pairing between the a positions (the x indices) and b positions (the y indices) is a bijection between the a indices of residue r (there are a of them) and b indices of residue r (b of them) but not all pairs: it's a specific pairing (a permutation). Actually in the period, each residue r contributes exactly ab positions, each corresponding to a unique pair (p,q). So the matches in that period for residue r are exactly the number of pairs (p,q) that match, i.e., dot product of counts. So total matches across whole string = k * dot product of counts from one copy of x and one copy of y (since counts per copy are the same). So indeed total matches = k * S, with S = sum_r cnt_x_r * cnt_y_r.
Thus, after computing S via scanning y and using cnt_x, we need k = L / T. Alternatively, we can compute total matches directly as: total matches = sum_{i=0}^{L-1} [a[i]==b[i]] = k * S. Since L = kT, T = AB/g.
So answer = L - k*S.
We can compute k = L / T. But we may avoid computing T explicitly to prevent overflow? But we can compute k as n / b (or m / a). Since we have n, b = B/g. b up to 1e6, n up to 1e12, division yields integer. Or m / a. That is safe.
Thus algorithm steps:
Read n, m as long long.
Read strings x and y.
Compute A = x.length(), B = y.length().
Compute g = gcd(A, B). (using built-in __gcd or manual).
Compute a = A / g, b = B / g.
Compute L = n * A (since given that lengths match, L = n * A = m * B, we can compute as n * A using 128-bit? but in C++ 64-bit multiply may overflow if both up to 1e12 and 1e6 => 1e18, which fits in unsigned 64-bit but signed 64-bit max is 9.22e18, so safe. However, to be safe use unsigned long long or __int128 if needed; but typical 64-bit signed can hold up to 9.22e18, so 1e18 is fine.
Compute k = n / b. Since b = B/g, and B ≤ 1e6, g ≥1, so b ≤ 1e6. n up to 1e12, k up to 1e12? Actually L = nA, T = AB/g = Ab. So k = L/T = nA / (A*b) = n/b, so k = n/b. Since n up to 1e12, b up to 1e6, k up to 1e12. That's fine in 64-bit.
Now we need to compute S = matches_per_period = sum_{r=0}^{g-1} sum_c cnt_x_r[c] * cnt_y_r[c].
Approach: allocate an array cnt_x of size g x 26 (or maybe a 2D vector). g up to 1e6, 26 columns => 26e6 entries. That's large but maybe okay if we use short ints? But counts per residue for x: each residue class has exactly a indices, a = A/g, which can be up to 1e6 (if g=1). So count can be up to 1e6, fits in 32-bit int. But memory: 26e6 * 4 bytes = 104 MB. That's okay? Many contests allow 256 MB. But we also have other variables. However we might also need to store y? we can process y without storing its count, just scanning. So total memory: cnt_x (104 MB) + maybe a few other arrays. Could be acceptable. But we also might need to store x and y strings themselves: each up to 1e6 characters => about 1 MB each. So total ~106 MB. That's fine. But we need to ensure that the 2D array is accessed efficiently and doesn't cause too much overhead. We can use vector<vector> of size g, each inner vector of size 26. The overhead of vector of vectors is significant (each inner vector has its own pointer, size, capacity). That could add memory: each inner vector ~24 bytes overhead, times g up to 1e6 => 24 MB extra, plus the actual data. Total maybe ~130 MB, still okay. But may be close to memory limit (maybe 256 MB). However some judges limit to 256 MB, it should be okay. But we can optimize memory by using a single contiguous array: int cnt_x[g][26]? But g is not compile-time constant. We can allocate a 1D array of size g26 and access as cnt_x[r26 + c]. That reduces overhead significantly. Use a vector of size g*26, initialized to 0. That's 26e6 ints => 104 MB. That's good.
But we need to fill counts for x. For each index i from 0 to A-1, r = i % g, c = x[i] - 'a', increment cnt_x[r*26 + c]. That's O(A). A ≤ 1e6, fine.
Then compute S = 0. Iterate over y: for each index j from 0 to B-1, r = j % g, c = y[j] - 'a', add cnt_x[r*26 + c] to S. But careful: The counts we have are from one copy of x. That yields S = sum_r sum_c cnt_x_r[c] * cnt_y_r[c] as desired. Because for each occurrence in y, we add the count of that character in x for the same residue r. So after scanning y, S is computed.
But we must ensure that the result S may be up to T? Since each cnt_x_r[c] ≤ a, and there are b occurrences per residue in y, so S ≤ abg = T. S fits in up to 1e12? T can be up to 1e12. So S can be up to 1e12. That's within 64-bit.
Then compute total_matches = k * S. k up to 1e12, S up to 1e12 => product up to 1e24, which exceeds 64-bit (2^64 ~1.84e19). Oops! That's a problem! Because L is up to 1e18, but k * S could be as large as? Let's examine: total_matches = k * S, and L = k * T, and S ≤ T, so total_matches ≤ L ≤ 1e18. Actually L = n * A = up to 1e12 * 1e6 = 1e18. Since total_matches cannot exceed L, product k * S must be ≤ L. But if we compute k and S separately, their product might exceed 64-bit range before we compare to L? Let's check the actual magnitudes: k = n/b, S ≤ ab? Wait S = matches_per_period ≤ T = abg. But T can be up to 1e12? Actually T = lcm(A,B) up to 1e12, so S ≤ 1e12. k = n/b, with n up to 1e12, b up to 1 (if g = B) but b can be as low as 1 if B divides A? Actually b = B/g. Since B ≤ 1e6, g can be as large as B, so b can be as low as 1. So k can be as high as 1e12. Then kS could be as high as 1e12 * 1e12 = 1e24, which is larger than L. However, we must recall that S is not independent; S is matches_per_period, and k = n/b. But there is relation: L = k * T, and T = abg. And S ≤ T. So kS ≤ kT = L. So mathematically, kS ≤ L ≤ 1e18. But if we compute k and S as 64-bit numbers, their product may overflow 64-bit even though the true product fits within L (≤1e18). For example, if n = 1e12, b = 1, then k = 1e12. If S = 1e12 (but then T must be at least 1e12, and L = kT would be 1e121e12 = 1e24, which exceeds 1e18. So such scenario cannot happen because L would be too large. Wait, constraints: n ≤ 1e12, A ≤ 1e6, so L = nA ≤ 1e18. So L is capped at 1e18. Therefore, any scenario where kS would exceed 1e18 is impossible because that would imply L ≥ kS > 1e18. Let's check: L = k * T, and T >= S, so L >= kS. So if kS > 1e18, then L > 1e18, contradicting L ≤ 1e18. So indeed, kS is always ≤ 1e18. However, computing k and S individually might yield numbers that when multiplied in 64-bit could overflow, because the product of two numbers each up to 1e12 is up to 1e24, but the actual product is limited by L ≤ 1e18, but the intermediate product could overflow if we simply multiply them as 64-bit integers without checking. For example, suppose k = 1e12, S = 1e12, but then L would be at least 1e24, which violates L ≤ 1e18, so this combination cannot occur because S cannot be 1e12 when k=1e12 given L ≤ 1e18. Let's find maximum possible k and S given L ≤ 1e18. k = n/b, S ≤ T. Since L = nA = n * g * a = (n/b) * (b * g * a) = k * T. So T = L/k. And S ≤ T = L/k. So S ≤ L/k. Thus kS ≤ L. So if k is large, S must be small. For example, if k = 1e12, then S ≤ L/k ≤ 1e18/1e12 = 1e6. So S would be at most 1e6. So product kS ≤ 1e18. So in any actual case, k and S individually may be up to 1e12, but they cannot both be large simultaneously. However, if we compute them independently, we could still get an overflow if we naively multiply 64-bit ints: e.g., k = 1e12 (fits), S = 1e12 (fits), product = 1e24 > 2^63-1, causing overflow in signed 64-bit. But as argued, such combination cannot happen because L would exceed 1e18. But we can't guarantee that from the numbers: It is possible that A is 1e6, n = 1e12 => L=1e18. Then b = B/g. For k = n/b to be 1e12, we need b = 1. That means B = g, so B divides A? Actually b = B/g = 1 => B = g, so B divides A? g = gcd(A,B) = B, so B divides A. Then A = g * a = B * a. So a = A/B. T = lcm(A,B) = A (since B divides A). Then T = A = up to 1e6. Then S ≤ T = 1e6. So S is at most 1e6. So indeed S cannot be 1e12. Similarly, if S is large (say 1e12), then T must be at least 1e12. But T = lcm(A,B) ≤ AT must be ≤1e18 => k ≤ 1e6. So k is at most 1e6. So product k*S ≤ 1e6 * 1e12 = 1e18. So indeed the product fits in 64-bit.
Thus if we compute k and S as 64-bit, we can multiply them safely if we use 128-bit or do multiplication with overflow detection? But we can avoid the multiplication altogether by computing total matches directly as: total_matches = (n / b) * S. However, we could also compute total_matches by scanning y but weighting each occurrence by k? Actually, we could compute total matches as sum over occurrences in b (which is m copies of y) of cnt_x[r][char] but multiplied by? Wait, if we consider the whole string b (length L), the total matches = sum_{i=0}^{L-1} [a[i]==b[i]] = sum over each occurrence of y in b? Not directly.
We can compute total matches as: For each residue r, total matches = k * (cnt_x_r dot cnt_y_r). Since cnt_total_y[r][c] = m * cnt_y_r[c]. And cnt_total_x[r][c] = n * cnt_x_r[c]. But total matches is not dot product of total counts; it's something like a sum over i of pairing, which equals k times dot product of per-copy counts. So if we wanted to compute total matches without multiplying k and S, we might compute S from one copy and then multiply. But we can compute total matches by iterating over the pattern y but considering that each occurrence in the full b will have the same contribution from cnt_x? Actually, because the whole string a is n copies of x, the total count of character c at residue r in a is n * cnt_x_r[c]. For each occurrence in b (which are m copies of y) with residue r and char c, the number of matches contributed by that occurrence? Not directly, because each position i pairs one character from a with one from b. The number of matches contributed by a given occurrence in b (i.e., a specific index j in b) is not simply cnt_x_r[c]; it's whether the specific a character at that index i equals that b character. That depends on the mapping, not on aggregate counts. So we can't avoid multiplication.
But we can compute total matches using 128-bit integers to be safe. In C++, we can use __int128 (if available) for intermediate multiplication, then convert to 64-bit for output (since answer fits in 64-bit). Or we can compute answer as L - kS using either __int128 or careful multiplication with checking (but using __int128 is easier if allowed). But in many contests (Codeforces) __int128 is allowed? Usually yes in GNU C++17. However, they might not allow %lld but that's about output. We can store answer in unsigned long long and use multiplication that might overflow? Since product is guaranteed ≤ L ≤ 1e18, we could use unsigned long long for k and S, multiply, and it will be correct because unsigned overflow wraps around mod 2^64, which would give wrong result if product exceeds 2^64. But product ≤ 1e18 < 2^64 (2^64 ~1.84e19). So actually product ≤ 1e18 < 2^64, so even unsigned 64-bit multiplication won't overflow if we use unsigned long long? 1e18 is less than 2^64, so product fits within 64-bit unsigned. Wait, but we are using signed? Usually we use long long, which is signed 64-bit, max positive 9.22e18. 1e18 < 9.22e18, so product also fits in signed 64-bit if product ≤ 1e18. But if product could be up to 1e18, it's safe. However, earlier we thought product could be up to 1e18, but is that the maximum? L max = 1e12 * 1e6 = 1e18. So total_matches ≤ L ≤ 1e18. So total_matches fits in 64-bit signed. And k * S = total_matches. So product kS ≤ 1e18. Therefore, we can safely multiply 64-bit (signed) as long as we ensure no intermediate overflow beyond 64-bit? But the multiplication of two 64-bit numbers yields a product that may exceed 2^63-1, but if the true product is ≤ 1e18, then both k and S individually are ≤ 1e18, but the product of two numbers each up to 1e12 could exceed 1e18? Actually if k = 1e12 and S = 1e12, product = 1e24 > 1e18. But as argued, such combination cannot happen because then L would be at least kT and T≥S => L ≥ 1e24 > 1e18, impossible. So for all valid inputs, the actual product kS will be ≤ 1e18. However, when we compute k and S from the input, they are numbers that are derived; their values are such that product ≤ L ≤ 1e18. So if we multiply them as 64-bit, we might get overflow if the product in the computer's arithmetic exceeds 2^63-1, because signed overflow is undefined behavior. But if we cast to unsigned long long, the product will be computed modulo 2^64, which could yield an incorrect value if the product exceeds 2^64, but since product ≤ 1e18 < 2^64, it won't exceed 2^64. However, if product exceeds 2^63-1 but is less than 2^64, using signed multiplication might overflow (undefined) but if we use unsigned multiplication, it's well-defined. So we can store k and S as unsigned long long and multiply to get unsigned long long product, which will be correct as long as product < 2^64. And 1e18 < 2^64, so it's safe. So we can just use unsigned long long for all large integers.
But careful: n and m are given as up to 1e12, A and B up to 1e6, L = n * A may be up to 1e18, which fits in unsigned 64-bit. So we can use unsigned long long.
Thus plan: Use unsigned long long for n, m, A, B, etc. But note that A and B are ints (≤1e6) so we can keep them as int. But multiplication n * A should be done with unsigned long long.
Implementation steps:
Read n, m as long long (or unsigned long long).
Read strings x, y.
Compute A = x.size(), B = y.size().
Compute g = gcd(A, B). Use int.
Compute a = A / g, b = B / g. (as int)
Compute k = n / b. Since n is unsigned long long and b is int, division yields unsigned long long.
Compute L = n * (unsigned long long)A. (L = n * A)
Now compute cnt_x: vector cnt(g * 26, 0). We'll use unsigned int (32-bit) to save memory (since counts per residue for x ≤ a ≤ 1e6). Actually a can be up to 1e6, so count fits in 32-bit. However, we'll also accumulate S which may be up to 1e12, so we need 64-bit for S. When we add cnt_x values to S, we need to convert to 64-bit.
For i=0 to A-1: r = i % g; c = x[i]-'a'; cnt[r*26 + c]++.
Initialize unsigned long long S = 0.
For j=0 to B-1: r = j % g; c = y[j]-'a'; S += cnt[r*26 + c].
Now total_matches = k * S. (both unsigned long long)
Answer = L - total_matches.
Print answer.
But we must be cautious: L = n * A. Since n and A are both ≤ 1e12 and 1e6, product ≤ 1e18 fits. n is unsigned long long, A is int cast to unsigned long long.
Double-check with examples.
Example 1:
n=100, m=10, x="a", y="aaaaaaaaaa". A=1, B=10. g = gcd(1,10)=1. a=1, b=10. k = n / b = 100/10=10. L = 1001=100.
cnt_x: r=0 only, cnt[026 + 'a'] = 1.
Scan y: each of 10 positions, r=j%1=0, char 'a', cnt[0,0]=1, so S = 10.
total_matches = 10*10=100. Answer = 100-100=0. Correct.
Example 2:
n=1, m=1, x="abacaba" (len=7), y="abzczzz" (len=7). A=7, B=7, g=gcd(7,7)=7, a=1, b=1. k = n/b =1/1=1. L=1*7=7.
cnt_x: for i=0..6, r=i%7 (so each r unique), counts per r: each has count 1 for respective char.
Scan y: for j=0..6, r=j%7, add cnt for that r and char. This essentially compares each position directly: S = number of positions where chars equal (since each r unique). x: a b a c a b a, y: a b z c z z z -> matches at indices 0,1,3? Actually positions: 0: a==a -> match; 1: b==b -> match; 2: a vs z -> no; 3: c==c -> match; 4: a vs z -> no; 5: b vs z -> no; 6: a vs z -> no. So S=3. total_matches=3. Answer=7-3=4. Correct.
Example 3:
n=2, m=3, x="rzr" (len=3), y="az" (len=2). A=3, B=2, g=gcd(3,2)=1, a=3, b=2. k = n/b =2/2=1? Wait b = B/g = 2/1 =2, n=2, so k=1. L = nA = 23=6. (Also mB=32=6). Good.
cnt_x: g=1, so r=0 only. Count characters in x: r:0, c1: 'r' (cnt=2? Actually "rzr": characters: r, z, r -> counts: r:2, z:1). So cnt[0][r]=2, cnt[0][z]=1.
Scan y: y="az": characters: a, z. For each: r=0, add cnt[0][char]. For 'a': cnt[0][a]=0; for 'z': cnt[0][z]=1. So S = 0+1=1.
total_matches = kS =11=1. Answer =6-1=5. matches example says distance 5, so correct.
All good.
Now consider edge cases.
Very large g (e.g., A=B=10^6, g=10^6). Then a=1, b=1. cnt_x size = g26 = 26e6, each int 4 bytes => 104 MB. That's acceptable. But we need to ensure that memory allocation works. Using vector of that size (104 million ints) may be okay but watch out for stack vs heap. We'll allocate on heap via vector. In C++, vector cnt(g26) will allocate contiguous memory. With 104 MB, it's okay. Some judges might have memory limit of 256 MB, so 104 MB is fine. Plus overhead for strings (2 MB) and other variables, total < 120 MB. So fine.
Cases where g is small but a and b large. Then cnt_x size is small, but we still need to compute S by scanning y. Works.
Cases where A and B are large and coprime (g=1). Then cnt_x size = 126 = 26, trivial. However, T = AB may be up to 1e12, but we don't iterate over T. S = dot product of full character counts of x and y. Indeed, when g=1, each residue r=0 only, cnt_x counts all chars in x, cnt_y counts all chars in y. S = sum_c cnt_x[c] * cnt_y[c]. That's consistent. And k = n/b = n / B? Actually b = B/g = B, so k = n / B. Since n is multiple of B? Because nA = mB, with coprime A and B, we have B divides n. So k = n/B. So total matches = (n/B) * (counts dot product). That makes sense: For each alignment period? Actually the period T = A*B. Since g=1, the mapping i -> (i mod A, i mod B) is a bijection from 0..AB-1 to all pairs. So each pair of characters from x and y occurs exactly once in one period. So total matches = number of periods * matches per period. Matches per period = sum over all pairs (i,j) of [x_i == y_j] = dot product of counts. So that's correct.
Now verify that our method works when g>1. Yes.
Now potential issues: When computing cnt_x, we use r = i % g. Since g may be up to 1e6, that's fine. However, for each i we compute modulo; that's cheap.
Now we need to ensure that k = n / b is integer. According to problem guarantee, it is, but we can compute as n / b using integer division; since we use unsigned, it's fine.
Now answer is L - total_matches, which is non-negative and ≤ L.
Now check overflow: L = n * A. n up to 1e12, A up to 1e6 => product up to 1e18. n is unsigned long long, A is int, so we cast to unsigned long long. That's fine.
total_matches = k * S. Both are ≤ L (since k = n/b, S ≤ T, product ≤ L). So total_matches ≤ 1e18. So answer fits in 64-bit.
Now we just need to be careful with data types: Use uint64_t from to be explicit.
Now implement:
#include <bits/stdc++.h>
using namespace std;
using ull = unsigned long long;
int main() {
ull n, m;
cin >> n >> m;
string x, y;
cin >> x >> y;
int A = x.size();
int B = y.size();
code
int g = gcd(A, B);
int a = A / g;
int b = B / g;
ull L = n * A; // total length
ull k = n / b; // since n divisible by b
// allocate cnt_x: g rows, 26 columns
vector<int> cnt(g * 26, 0); // int is fine (counts up to a <= 1e6)
for (int i = 0; i < A; ++i) {
int r = i % g;
int c = x[i] - 'a';
cnt[r * 26 + c]++;
}
ull S = 0;
for (int j = 0; j < B; ++j) {
int r = j % g;
int c = y[j] - 'a';
S += cnt[r * 26 + c]; // cnt is int, promote to ull automatically
}
ull total_matches = k * S;
ull ans = L - total_matches;
cout << ans << endl;
return 0;
}
Test with examples.
Edge test: n=1e12, m such that L=1e18. For A=1e6, B=1e6, g may vary. If A and B are both 1e6, g = 1e6, a=1, b=1. Then L = 1e12 * 1e6 = 1e18. k = n / b = 1e12. cnt_x size = g26 = 26e6, that's 104 MB, okay. For each i in x (1e6) we update cnt. That's fine. For each j in y (1e6) we update S. Then S = sum over counts? Since a=1, each residue r has exactly one character in x. cnt[r][c] is either 1 or 0. So S = number of residues where x's char equals y's char? Actually S = sum over j of cnt[r][y_j] = number of positions j where y_j equals the character of x at that residue (since each residue appears exactly once in x). That's essentially the number of matches if we align by residue, but that's correct for period matches? Let's compute: Since g = 1e6, a=b=1, T = ga*b = 1e6. The period consists of each i from 0 to 999999, mapping to (p=i mod A, q=i mod B). Since A=B=1e6, p=i, q=i. So period is just the pair of same index. So matches per period = number of i in [0, 999999] where x[i]==y[i]. That's exactly S computed as: for each j in y (0..999999), we add cnt[ r=j ][ y_j ] where cnt[r][c] is 1 if x[r]==c else 0. So S = count of indices i where x[i]==y[i]. So matches per period = common positions count. Then total matches = k * S = 1e12 * common_count. That could be up to 1e12 * 1e6 = 1e18. That fits. Our code: cnt array is int, but each entry is either 0 or 1. S computed as sum of those ints, S up to 1e6 fits in 32-bit? Actually up to 1e6, but we store S in ull, fine. k=1e12, product 1e18, fine. L=1e18. So answer = L - total_matches. Works.
Now check when g=1. Then cnt size = 26. That's trivial.
Now verify the condition that n/b is integer. Since input guarantees total lengths equal, it should hold. But if there is any weird input, we could compute k = L / T maybe safer? But we can compute k = n / b because we derived from L = nA = mB and A = ga, B = gb, so L = nga. Also T = gab. So k = L/T = nga/(gab) = n/b. Since L is integer, n/b should be integer. We'll trust.
Now complexity: O(A + B + g*26) memory, O(A + B) time. A and B up to 1e6, so fine.
Now potential pitfalls: The strings may contain uppercase? Problem says lowercase English letters. Good.
Now confirm that we need to output a single integer.
Now consider if g is large (1e6) and we allocate vector(g26). That's fine. However, we must be careful that the vector constructor with that many elements zero-initializes them, which may take some time but still manageable (26 million zeros initialization is fine: it's O(g26) ~ 26 million, which is okay.
But we can perhaps reduce initialization cost by using vector and resize with default 0; it will be zero-initialized anyway.
Alternatively, we could use a map but not needed.
Now we must ensure that we use 'gcd' from or . In C++17, #include provides std::gcd.
Now think about potential integer division: n/b where b is int. Since n is ull, b is int, it's okay.
Now test with another scenario: Suppose A=6, B=4. g=gcd=2, a=3, b=2. Then T = lcm = 12. Let n=5, then L = nA = 30. Since L = mB, m = L/B = 30/4 = 7.5 not integer? But problem guarantees that strings a and b have same length, so such n,m combination must satisfy nA = mB. So we cannot choose arbitrary n,m. So given input, it's guaranteed that nA = mB. So n/b integer.
Now test with random to ensure.
Edge case: x and y length 1, but different characters? Example: n=1e12, m=1e12? Actually need L equal: n1 = m1 => n=m. So n=m up to 1e12. x="a", y="b". Then g=1, a=1,b=1. cnt_x[0][0]=1. S = sum over y (only one char 'b') cnt = 0. So total_matches = k * 0 = 0, L = n. Answer = n. So distance = n, which is correct: all positions differ. n up to 1e12, answer fits.
Now check when g is moderate.
Now confirm that we didn't forget to handle case where g=0? Not possible.
Now think about alternative approach: Use number theory for each character, but our approach is straightforward.
Now we must be mindful that the product k * S might be computed as unsigned long long, but if we used int for cnt, S might be computed as int sum? We'll store S as ull.
Now potential overflow in S accumulation: cnt entries are int up to 1e6, and we add up to B (1e6) times, so S ≤ A*B? Actually max S is T, which ≤ 1e12. That's within 64-bit. So we need S as ull.
Now we need to compute L = n * A. Since n and A are within range, product may be up to 1e18. Use ull.
Now output: cout << ans << endl; Since ans is ull, that's fine.
Now check memory: vector cnt(g*26). If g=10^6, then 26e6 ints. int is typically 4 bytes, so 104 MB. In some environments, int is 4 bytes. Good. Could we use short (2 bytes) to reduce? Counts up to a ≤ 1e6, which needs at least 20 bits, so short (max 32767) insufficient. Could use unsigned short if a ≤ 65535? Not guaranteed; a can be up to 1e6. So need 32-bit. So int is fine.
But we could reduce memory by using vector<array<int,26>> but that would be similar but with overhead. The contiguous array is best.
Now alternative: Instead of storing all residues, we could process residues one by one: For each residue r, compute counts for x and y on the fly. Since we have to scan x and y anyway, we could accumulate counts per residue in separate arrays and then compute dot product. But that still needs storing cnt_x for all residues because we need to match with y's counts. However, we could compute cnt_x and cnt_y separately and then dot product. But storing both cnt_x and cnt_y would double memory. Our approach stores only cnt_x and uses y scanning to accumulate S, which is efficient.
Thus final solution is ready.
But we need to ensure that the modulo operation i % g is computed correctly for large i? i is int index within string length (<=1e6), so fine.
Now test with maximum input: A=1e6, B=1e6, g could be 1e6 or something. Let's simulate memory: vector cnt(1e6 * 26 = 26e6). That's 104 MB. plus strings: 1e6 each -> 2 MB. Plus other overhead maybe few MB. Total ~110 MB. Under 256 MB, okay.
Now time: initializing cnt to zero: 26e6 assignments, that's fine (takes maybe 0.1 sec). Then scanning x (1e6) and y (1e6), each doing modulo and array access. Modulo operation might be a bit heavy but okay.
Now potential improvements: Precompute residues for x and y? Not needed.
Now we should double-check the reasoning for S = sum over y of cnt_x[r][c]. Because that computes sum_{r,c} cnt_x_r[c] * cnt_y_r[c] exactly? Let's derive formally.
Let for each residue r (0 ≤ r < g), define X_r(c) = number of indices i in [0,A-1] with i ≡ r (mod g) and x[i]=c. Similarly Y_r(c) from y.
Then S = sum_{r,c} X_r(c) * Y_r(c).
Now, if we iterate over y: for each j in [0,B-1], let r = j mod g, c = y[j]. Then we increment S by X_r(c). So after processing all y, we have added X_r(c) for each occurrence of (r,c) in y. The number of occurrences of (r,c) in y is Y_r(c). So total added = sum_{r,c} X_r(c) * Y_r(c). So correct.
Thus algorithm is correct.
Now consider if we had used cnt_x of type vector, and S as ull, the addition of int to ull is fine.
Now check potential issue: k = n / b. But b is int, n is ull. That's fine.
Now compute answer: L - k*S. Since L and total_matches are both ≤ L, ans is non-negative.
Now confirm with example where g=0? Not possible.
Now handle case where g=1 but a and b large? Already covered.
Now what about when x or y length is 0? Problem says non-empty strings.
Now we should also note that the input guarantees strings a and b have same length, so nlenX = mlenY. That's used to ensure integer divisions.
Now double-check the derivation of k: Since L = nA = mB, and T = AB/g, then k = L / T = (nA) / (AB/g) = ng/B = n / b. Indeed b = B/g, so n*g/B = n/(B/g) = n/b. So ok.
Now we might need to use 64-bit for a and b as well? a = A/g, A ≤ 1e6, so a ≤ 1e6, fits in int.
Now all good.
Now let's think about potential pitfalls with large g and the vector allocation. We need to be careful that g could be 0? No. Also, we need to ensure that we compute g = gcd(A, B) correctly using ints.
Now implement with standard includes.
Now let's test with a custom case to ensure correctness manually.
Case: n=3, m=2, x="ab", y="aba"? Wait lengths: A=2, B=3, L must be equal: nA=6, mB=6 => m=2, n=3 works. So x repeats 3 times: "ababab". y repeats 2 times: "abaaba". Let's compute Hamming distance manually.
x pattern: indices: 0:a,1:b.
y pattern: 0:a,1:b,2:a.
Total length 6: positions:
i=0: a (x[0]) vs a (y[0]) -> match
i=1: b (x[1]) vs b (y[1]) -> match
i=2: a (x[0]) vs a (y[2]) -> match? Actually x[0]=a, y[2]=a -> match
i=3: b (x[1]) vs a (y[0]) -> mismatch
i=4: a (x[0]) vs b (y[1]) -> mismatch
i=5: b (x[1]) vs a (y[2]) -> mismatch
Matches: 3, mismatches: 3. So distance = 3.
Now our algorithm: A=2, B=3, g=gcd(2,3)=1, a=2, b=3. k = n / b = 3/3=1. L = 32=6. cnt_x: g=1, counts: a:1? Wait x="ab": counts: a:1, b:1. So cnt[0]['a']=1, cnt[0]['b']=1. Scan y="aba": chars: a,b,a. S = cnt['a'] + cnt['b'] + cnt['a'] = 1+1+1=3. total_matches = 13=3, ans = 6-3=3. Correct.
Case with g>1: n=4, m=6, x="abc", y="ab"? Lengths: A=3, B=2, L=12? nA=12, mB=12 => works. g=gcd(3,2)=1. So similar.
Now case with g=2: x="abab", y="ab". A=4, B=2, n=?, m=? Need L equal: say n=1, m=2? Then L=4, mB=4 => m=2. So n=1,m=2. x="abab", y repeated 2 -> "abab". Both same, distance 0. Our algorithm: g=gcd(4,2)=2, a=A/g=2, b=B/g=1. k = n/b = 1/1=1. L=4. cnt_x: residues r=0,1. For x indices: i=0(a) r=0; i=1(b) r=1; i=2(a) r=0; i=3(b) r=1. So cnt_x: r0: a:2, b:0; r1: a:0, b:2. Scan y: y="ab", indices: j=0(a) r=0; j=1(b) r=1. S = cnt[0][a] + cnt[1][b] = 2 + 2 = 4. total_matches = 14=4, ans=4-4=0. correct.
Now case where they are not fully matching: n=2, m=3, x="abab", y="ac". A=4, B=2. L=8? nA=8, mB=6? Not equal. Need to pick such that L equal. Let's choose n=1, m=2 => L=4, m*B=4 => m=2. So n=1, m=2. x="abab", y="acac"? Actually y="ac", repeated twice => "acac". Compare: a b a b vs a c a c: mismatches at positions 1 and 3 => distance 2. Let's compute: A=4,B=2,g=gcd=2, a=2,b=1. k=n/b=1/1=1. L=4. cnt_x: as before r0: a:2,b:0; r1: a:0,b:2. y="ac": indices: j=0('a') r=0; j=1('c') r=1. S = cnt[0]['a'] + cnt[1]['c'] = 2 + 0 = 2. total_matches=2, ans=2. correct? Wait distance = 2, total matches = 2, length 4, so yes.
Now case where g large: x length 1000000, y length 999999 (coprime). Then g=1, trivial.
Now we should also consider scenario where x and y have length up to 10^6 and g=10^6, that is A and B both multiples of 10^6? But max length is 10^6, so if g=10^6, then A=B=10^6, as earlier.
Thus implementation is fine.
Now finalize.
Potential issues: Input reading: strings may contain spaces? No, they are on separate lines, just words.
Now ensure to include <bits/stdc++.h> or necessary headers.
Now check for speed: vector initialization of size 26e6 might be a bit slow but acceptable in 2 seconds? Usually allocating and zero-initializing 100 MB takes some time (~0.1-0.2 sec). The loops over A and B are 1e6 each, fast. So overall should be okay.
Alternative: Instead of initializing full cnt array to zero, we could use vector cnt; cnt.assign(g*26, 0); same.
But we could also avoid initialization by using a map and only storing non-zero entries? But with g up to 1e6 and 26 letters, most entries might be zero? Actually for each residue, there are at most a characters from x. Since a = A/g, on average each residue gets a characters. If g is large (close to A), then a is small (maybe 1). So many residues will have only 1 character, others may have 0? Actually if A = ga, then each residue has exactly a characters (since A divisible by g). So for each r, there are exactly a positions in x. So cnt[r][c] may be zero for many c, but each r has at most a non-zero entries. However, total non-zero entries across all r is A (since each index contributes to exactly one (r,c)). So there are at most A non-zero entries, which is ≤ 1e6. So we could store cnt as a sparse structure: for each residue, a map of char to count. But then when scanning y, we would need to lookup cnt[r][c]; using map per residue would be slower but maybe okay if g is large and a is small. However, memory wise, storing vector of size g26 might be large but still okay. The tradeoff: using contiguous array is faster for random access. Since g up to 1e6, 26e6 entries, and we only access it A + B times (2e6), that's fine. Memory is okay. So I'll stick with contiguous array.
Now check potential integer overflow in indexing: r26 + c, where r up to 1e6, 261e6=26e6, which fits in 32-bit signed int (max 2^31-1 ~2.14e9). So using int for index is fine.
Now final code.
But also note: In C++, vector cnt(g26) requires g26 to fit in size_t (unsigned). 1e6*26 = 26e6, fine.
Now we might want to use std::gcd from . So include .
Now output as long long? But we are using unsigned long long; output works.
Now finalize.
But we must check that n and m are given as up to 10^12, but they could be 64-bit. Use unsigned long long.
Now test with random small cases to ensure consistency. We can do mental small cases.
Edge: n=0? Not allowed because n,m ≥1.
Now confirm that string lengths are up to 10^6 but maybe x and y lengths after input could be large. But reading with cin >> string should be fine.
Now final code:
#include
#include
#include
#include // for gcd
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
code
unsigned long long n, m;
cin >> n >> m;
string x, y;
cin >> x >> y;
int A = (int)x.size();
int B = (int)y.size();
int g = gcd(A, B);
int a = A / g;
int b = B / g;
unsigned long long L = n * A; // total length
unsigned long long k = n / b; // integer division
// allocate cnt_x for each residue class and character
vector<int> cnt(g * 26, 0);
for (int i = 0; i < A; ++i) {
int r = i % g;
int c = x[i] - 'a';
cnt[r * 26 + c]++;
}
unsigned long long S = 0;
for (int j = 0; j < B; ++j) {
int r = j % g;
int c = y[j] - 'a';
S += cnt[r * 26 + c];
}
unsigned long long total_matches = k * S;
unsigned long long ans = L - total_matches;
cout << ans << '\n';
return 0;
}
Now double-check the use of gcd: In C++17, std::gcd is in . Works.
Now note: In some environments, gcd might be in as well. But safe.
Now try to test with large values for correctness: Suppose A=1000000, B=1000000, g=1000000, a=1, b=1. Then cnt size = 26e6. n = 10^12, m = 10^12? But need L = nA = 10^12 * 10^6 = 10^18, and also mB = 10^12 * 10^6 = 10^18. So m = 10^12 works. Then k = n / b = 10^12. S is at most 10^6. total_matches up to 10^18. That's okay. Our algorithm will allocate 104 MB. The loops of 1e6 each. Works.
Now what about time to initialize cnt of 26e6 zeros: O(26e6) which is fine. Could we avoid initialization by using vector and relying on default zero? Yes that's initialization.
Now consider that the problem statement says not to use %lld in C++, but we are using cin/cout with unsigned long long, which is fine.
Now we might want to use 'auto' for convenience.
Now also check if there is any risk of integer overflow when computing L = n * A. If n=10^12 and A=10^6, product is 10^18, fits in unsigned long long (max 1.84e19). So safe.
Now all set.
But wait: In our derivation, we assumed that total matches = k * S, where S = sum_r sum_c cnt_x_r[c] * cnt_y_r[c]. This S is computed based on one copy of x and one copy of y. But we must ensure that the residue classes align correctly across copies. Since a is n copies of x and b is m copies of y, and we have already accounted for the period repetition via k, it should be fine.
Let's double-check the reasoning with a more rigorous approach: The total length L = nA = mB. Define g = gcd(A, B). Write A = ga, B = gb with gcd(a,b)=1. Then L = nga = mgb. Since a and b are coprime, n must be multiple of b, m multiple of a. Let k = n/b = m/a. Then L = k * (gab). Indeed L = k * T where T = lcm(A,B) = gab.
Now for any integer i in [0, L-1], we can write i = q * T + r, where 0 ≤ q < k and 0 ≤ r < T. Since T is the period, we have a[i] = a[r] (because x repeats every A, and A divides T? Actually A divides T, yes because T = lcm(A,B) is multiple of A. Similarly B divides T. So a[i] = x[r mod A] and b[i] = y[r mod B]. So a[r] and b[r] are periodic with period T. Therefore, the Hamming distance over L is k times the Hamming distance over one period of length T. So it's correct that total matches = k * (matches in one period).
Now matches in one period = number of r in [0,T-1] with x[r mod A] == y[r mod B]. As argued, mapping r -> (p = r mod A, q = r mod B) is bijection onto compatible pairs (p,q) with p ≡ q (mod g). Therefore, matches_per_period = |{(p,q): 0≤p<A, 0≤q<B, p≡q mod g, x[p]==y[q]}| = sum_{r=0}^{g-1} sum_c X_r(c) * Y_r(c). So our S is that.
Thus all good.
Now we should also handle cases where g=0? No.
Now final code.
But wait: We used n/b to compute k. However, b = B/g could be up to 1e6, so division is fine. But what if n/b is not integer? The problem guarantees that the lengths match, but if we compute n/b using integer division, we might get truncated value if not divisible. However, due to guarantee, it should be divisible exactly. So we can assert.
Now we might compute k also as L / T, but T might be large (up to 1e12) and we need to compute T = (A/g) * B? Actually T = (A/g) * B? Wait T = A * (B/g) = (A/g) * B. Both are safe? A up to 1e6, B/g up to 1e6, product up to 1e12, safe. But L/T might be safer because L is already computed and T might be computed as (A/g) * B (or A * (B/g)). But we need to be careful about overflow when computing T as product of two numbers up to 1e6 and 1e6 = 1e12, which fits in 64-bit. So we could compute T = (A / g) * B; (since A/g is integer up to 1e6, B up to 1e6, product up to 1e12). But we have to ensure we cast to unsigned long long to avoid overflow of int (since A/g and B are ints up to 1e6, product up to 1e12 which exceeds 32-bit). So better to cast: (unsigned long long)(A/g) * B. Or just compute k = n / (B/g). That's simpler.
Now check if there is any scenario where B/g doesn't fit in int? B ≤ 1e6, g≥1, so B/g ≤ 1e6, fits in int. So b is int. n / b is unsigned long long division.
Now all good.
Now finalize the answer.
But before finalizing, consider alternative viewpoint: Could we compute answer directly as L - k*S, but if we compute S as described, it's fine.
Now let's test with the given examples programmatically (simulate in mind). Already did.
Now edge case: When x and y consist of different characters only? Already covered.
Now might there be any off-by-one in indexing? We used 0-based indices, fine.
Now about modulo: i % g for i up to 1e6, g up to 1e6, fine.
Now ensure that we include for gcd.
Now final code.
Potential improvement: Use unsigned int for cnt to reduce memory? unsigned int is also 4 bytes on most platforms. int is fine.
Now compile and test.
Now final answer.
But we must also consider that n and m are given as up to 10^12, but they can be read as unsigned long long. Input spec: "two integers n and m (1 ≤ n, m ≤ 10^12)". So they fit in 64-bit.
Now output: "Print a single integer — the required Hamming distance." So it's integer up to 1e18, fits in 64-bit.
Now final solution is ready.
But there is a nuance: The problem statement says "strings a and b that you obtain from the input have the same length." So it's guaranteed. However, we didn't explicitly verify that nA == mB. But we rely on it for correctness of k. If the input violates this, our program might produce wrong answer, but it's guaranteed.
Now consider possibility that g*26 is zero? Not.
Now done.
Now write final answer. ```cpp
#include
#include
#include
#include // for std::gcd
using namespace std;
using ull = unsigned long long;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
code
ull n, m;
cin >> n >> m;
string x, y;
cin >> x >> y;
int A = (int)x.size();
int B = (int)y.size();
int g = gcd(A, B); // greatest common divisor of lengths
int a = A / g; // number of blocks in x per residue
int b = B / g; // number of blocks in y per residue
ull L = n * A; // total length of the constructed strings
ull k = n / b; // number of full periods (k = L / lcm(A,B))
// cnt[r*26 + c] = how many times character c appears in x at indices i with i%g = r
vector<int> cnt(g * 26, 0);
for (int i = 0; i < A; ++i) {
int r = i % g;
int c = x[i] - 'a';
++cnt[r * 26 + c];
}
// S = matches per period = Σ_r Σ_c cntX[r][c] * cntY[r][c]
ull S = 0;
for (int j = 0; j < B; ++j) {
int r = j % g;
int c = y[j] - 'a';
S += cnt[r * 26 + c];
}
ull matches = k * S; // total matches over the whole strings
ull ans = L - matches; // Hamming distance
cout << ans << '\n';
return 0;