A permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array. An inversion in a permutation p is a pair of indices (i, j) such that i > j and a_i < a_j. For example, a permutation [4, 1, 3, 2] contains 4 inversions: (2, 1), (3, 1), (4, 1), (4, 3).
You are given a permutation p of size n. However, the numbers on some positions are replaced by -1. Let the valid permutation be such a replacement of -1 in this sequence back to numbers from 1 to n in such a way that the resulting sequence is a permutation of size n.
The given sequence was turned into a valid permutation randomly with the equal probability of getting each valid permutation.
Calculate the expected total number of inversions in the resulting valid permutation.
It can be shown that it is in the form of P/Q where P and Q are non-negative integers and Q ≠ 0. Report the value of P ⋅ Q^{-1} \pmod {998244353}.
Input
The first line contains a single integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of the sequence.
The second line contains n integers p_1, p_2, ..., p_n (-1 ≤ p_i ≤ n, p_i ≠ 0) — the initial sequence.
It is guaranteed that all elements not equal to -1 are pairwise distinct.
Output
Print a single integer — the expected total number of inversions in the resulting valid permutation.
It can be shown that it is in the form of P/Q where P and Q are non-negative integers and Q ≠ 0. Report the value of P ⋅ Q^{-1} \pmod {998244353}.
Examples
Input
3
3 -1 -1
Output
499122179
Input
2
1 2
Output
0
Input
2
-1 -1
Output
499122177
Note
In the first example two resulting valid permutations are possible:
[3, 1, 2] — 2 inversions;
[3, 2, 1] — 3 inversions.
The expected value is (2 ⋅ 1 + 3 ⋅ 1)/(2) = 2.5.
In the second example no -1 are present, thus the only valid permutation is possible — the given one. It has 0 inversions.
In the third example there are two resulting valid permutations — one with 0 inversions and one with 1 inversion.
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 expected number of inversions over all completions of a partially specified permutation (with -1's replaced by numbers from 1..n to make a full permutation, all completions equally likely). n up to 2e5. Need modulo 998244353.
We need to compute E[total inversions] = sum over all pairs (i,j) with i>j of P(a_i > a_j). Because inversion is i>j and a_i < a_j (but note typical definition: inversion when i a_j, but problem statement says (i, j) with i > j and a_i < a_j, that's same as ia_j if we swap roles. Typically we consider pair (i,j) with i a_j. Let's be consistent. The definition: i>j and a_i < a_j. So for ordered pair (i, j) with i > j, condition is a_i < a_j. This is equivalent to for i<j, condition a_i > a_j. But it's easier to consider unordered pair i<j, and indicator that a_i > a_j. Because the total number of inversions = number of pairs (i,j) with i a_j. So we'll adopt that: for i<j, if a_i > a_j then inversion. So expected total = sum over i<j of Pr(a_i > a_j).
Thus we need for each pair (i,j) with i<j, the probability that in a random completion, the value at i is greater than the value at j.
We have fixed known numbers in some positions, and unknown positions that get a random permutation of the missing numbers.
We need to compute expected inversions efficiently.
We can treat missing numbers as random permutation uniformly over all permutations of the set M (the numbers not appearing in known positions). Let m = number of missing positions (number of -1's). Let known positions K.
Thus total number of completions = m! (since we assign the missing numbers in some order to the missing positions). And all are equally likely.
We need expected inversions.
We can break down contributions:
Inversions between two known positions: these are deterministic, because values are fixed. So contribution = sum_{i<j, both known} [p_i > p_j].
Inversions between known and unknown positions: for each pair (i known, j unknown) with ij, but since we consider i<j, we need to consider ordering. We'll compute for each known position and each missing position, probability that the known value > the unknown value (if i<j) or known < unknown if i>j? Actually for i<j, condition for inversion is a_i > a_j. So if i is known and j is unknown, we need Pr(p_i > a_j) where a_j is the random value assigned to missing position j. Similarly if i is unknown and j is known, for i<j, we need Pr(a_i > p_j). So need to compute for each known-unknown pair.
Inversions between two unknown positions: For two missing positions i<j, we need Pr(a_i > a_j) where (a_i, a_j) are two distinct random values from the set of missing numbers, uniformly random over all assignments without replacement. Since all permutations equally likely, for any two distinct missing positions, the joint distribution of (a_i, a_j) is uniform over ordered pairs of distinct values from M. So Pr(a_i > a_j) = (# of ordered pairs (x,y) with x,y in M, x != y, x>y) / (m*(m-1)). That's essentially 1/2 (since symmetry) except if there are ties (no ties). Indeed, for distinct values, Pr(a_i > a_j) = 1/2 because for any unordered set {x,y}, exactly one of the two orders gives x>y and the other gives y>x, assuming x != y. Since values are distinct integers, it's exactly 1/2. So for any pair of unknown positions, the probability is 1/2, regardless of which numbers are missing. So contribution: number of pairs (i,j) with i<j, both unknown times 1/2.
Thus the main difficulty is computing expected contributions for known-unknown pairs.
We need to compute for each known position, and each missing position, the probability that the known value > the unknown value, given that the unknown value is drawn uniformly from the set of missing numbers (without replacement, but for a single position, marginal distribution is uniform over M). Actually careful: The values assigned to missing positions are not independent; they are a random permutation. However, for a single missing position, its marginal distribution is uniform over M. For a pair of missing positions, they are not independent but we already used the symmetry to get Pr(a_i > a_j) = 1/2. For a known-unknown pair, we only care about the value at the unknown position relative to the known value. Since the unknown position's value is uniformly random from M (marginal), regardless of other assignments, we have Pr(unknown value = v) = 1/m for each v in M. Thus for a known-unknown pair (i known, j unknown), Pr(p_i > a_j) = (number of missing numbers less than p_i) / m. Similarly, for (i unknown, j known) with i<j, Pr(a_i > p_j) = (number of missing numbers greater than p_j) / m.
But careful: Is the marginal truly uniform? Yes, because all assignments are permutations uniformly; the value at a particular missing position is equally likely to be any missing number. So that's fine.
Thus the expected inversions from known-unknown pairs is:
Sum over known positions k, for each missing position u with k < u: (cnt_less(p_k) / m) where cnt_less(x) = number of missing numbers < x.
Plus sum over known positions k, for each missing position u with u < k (i.e., missing before known): (cnt_greater(p_k) / m) where cnt_greater(x) = number of missing numbers > x.
But note: In the second case, we need Pr(a_u > p_k) for u<k, and that equals (number of missing numbers > p_k)/m. Yes.
Alternatively, we can combine: For each ordered pair (i,j) with i<j, if i known, j unknown -> contribute (num missing less than p_i)/m. If i unknown, j known -> contribute (num missing greater than p_j)/m.
We can precompute the set of missing numbers M (i.e., numbers from 1..n not present among known values). Let m = |M|. Let sorted missing numbers.
For each known value x, we can compute:
L(x) = count of missing numbers < x.
G(x) = count of missing numbers > x. Note L(x)+G(x) = m if x not in missing? But x is known, so x is not in M, thus all missing numbers are either less or greater, but could be equal? No, because x is not missing, so none equals x. So yes L+G=m.
Now contributions:
Let positions: we have indices 1..n. For each known position i with value p_i, consider all missing positions. Among missing positions, some are to the left of i (index less than i), some to the right (index greater than i). For left missing positions (j < i), the pair is (j,i) with j < i, and we need inversion if a_j > p_i. So contribution per such missing position = G(p_i)/m. For right missing positions (j > i), pair (i,j) with i<j, inversion if p_i > a_j, contribution per such missing = L(p_i)/m.
Thus sum over known positions i: (num_missing_left_of_i * G(p_i) + num_missing_right_of_i * L(p_i)) / m.
Now for known-known pairs: deterministic, sum over i<j, both known, 1 if p_i > p_j else 0.
For unknown-unknown pairs: count = C(m,2) (since number of pairs i<j both unknown) and each contributes 1/2. So contribution = C(m,2) / 2 = m*(m-1)/4. However careful: That is exactly the expectation. But we must check if there is any dependency? We used symmetry: for any two distinct unknown positions, (a_i, a_j) is equally likely to be any ordered pair of distinct missing numbers. So Pr(a_i > a_j) = 1/2. So yes.
Thus total expectation E = E_kk + (1/m) * sum_{known i} (left_i * G_i + right_i * L_i) + m*(m-1)/4.
But we must be careful: When m = 0, the division by m? Then the known-unknown term is zero anyway. But we have to handle separately. Also m can be 1, then unknown-unknown term is 0 because C(1,2)=0. Works.
Now we need to compute this expectation exactly as a rational, then output modulo MOD = 998244353. Since we need to output P * Q^{-1} mod MOD, effectively we compute E mod MOD as a fraction: E = P/Q, we compute P * Q^{-1} mod MOD. Since we have formulas with division by m and 4, we must handle modular inverses. Also note that m could be large, but mod is prime.
But careful: The expectation is a rational number that might not be integer. But we can compute it as modular rational by working in modulo arithmetic with inverses.
We need to compute:
E_kk: sum over known-known inversions. This is integer.
Sum_ku: S = sum_{known i} (left_i * G_i + right_i * L_i). Then contribution = S / m.
E_uu: m*(m-1)/4.
Thus E = E_kk + S/m + m*(m-1)/4.
But note: m*(m-1)/4 may be fractional if m*(m-1) not divisible by 4. But we work modulo MOD with inverse of 4.
So final answer = (E_kk + S * inv(m) + m*(m-1) * inv(4)) mod MOD.
But wait: Is there any other contribution? What about inversions involving pairs where both are unknown but also maybe there is dependency with known ones? Already covered.
Thus algorithm:
Read n, array p of length n.
Determine which numbers 1..n are present. Create a boolean array or set. Count missing: m = n - known_count.
Determine missing numbers list, maybe sorted, to compute for each known value the count of missing numbers less than it (L) and greater than it (G). Since n up to 2e5, we can precompute prefix counts or use Fenwick tree over values 1..n.
Simplify: We can compute an array present[1..n] = true if appears. Then we can build an array of missing numbers sorted (just iterate 1..n, collect those not present). Then for a given known value x, L = number of missing numbers less than x. Since missing numbers sorted, we can binary search (lower_bound) to get index = count less than x. That yields L, then G = m - L. So we can compute for each known position.
Alternatively, we can compute prefix sum of present to get number of numbers less than x that are present? But easier: missing numbers sorted.
For known-known inversions: We need to count number of pairs (i,j) with i<j, both known, and p_i > p_j. That's like counting inversions among the known values ignoring unknown positions. Since known values are a subset of permutation, we can compute this using Fenwick tree (BIT) over values. We'll iterate positions i from 1 to n; if p_i != -1, we query BIT for count of known values > p_i seen so far? Actually we need to count pairs where i p_j. Standard inversion counting: as we iterate left to right, maintain BIT over values to count occurrences of known values seen. For each known p_i, number of inversions where this p_i is the right element and left element > p_i is: query for sum over range (p_i+1, n) in BIT. Add to total. Then update BIT at p_i. This gives known-known inversion count.
But careful: Since unknown positions are skipped, they are not in BIT. That's correct.
Alternatively, we could compute via sorting, but BIT O(n log n) fine.
Compute left_i and right_i for each known position i: number of missing positions to the left and right of i. We need for each known index i, count of missing positions with index < i (left_i) and > i (right_i). We can precompute prefix counts of missing positions: an array is_missing[1..n] boolean indicating if p_i==-1. Then prefix_missing[i] = number of missing positions up to i. Then for a known position i, left_i = prefix_missing[i-1] (or prefix_missing[i]? Actually if i is known, missing positions with index < i = prefix_missing[i-1]). right_i = total_missing - prefix_missing[i] (since prefix_missing[i] includes missing up to i, but i is known so no missing at i, so it's same as prefix_missing[i] maybe but careful: If i is known, prefix_missing[i] counts missing at positions <= i. Since i is not missing, prefix_missing[i] = prefix_missing[i-1]. So right_i = total_missing - prefix_missing[i] = total_missing - prefix_missing[i-1]. Could compute either way. So we can get left_i and right_i in O(1) after precomputing prefix.
For each known position i with value x, compute L = count_missing_less_than(x), G = m - L. Then contribute to S: S += left_i * G + right_i * L.
But careful: left_i is count of missing positions to left (indices less than i). For these left missing positions, the pair is (j,i) with j missing, i known, and inversion condition: a_j > p_i, probability = G/m. So each such contributes G/m, so total from these left missing = left_i * (G/m). Similarly right missing = right_i * (L/m). So summing gives S/m.
So we compute S as sum_{known i} (left_i * G + right_i * L). S is integer (since left_i, right_i, G, L are integers).
Now we have all pieces.
Complexities: O(n log n) due to BIT and binary searches for L (but we can also compute L using BIT on missing numbers preprocessed, but binary search on sorted missing array O(log m) per known i is okay, total O(n log n). n=2e5 fine.
Edge Cases: m=0. Then S is sum over known i of left_i * G + right_i * L, but G and L are based on missing numbers. If m=0, there are no missing numbers, then L=0, G=0 for any known x? Actually missing set empty, so L(x)=0, G(x)=0. Then S = 0. And m*(m-1)/4 = 0. So E = E_kk. Good.
If m>0, S/m term is fine.
But note: For known-unknown pairs, we assumed that marginal distribution of a single unknown is uniform over missing set. That's correct because all completions are equally likely. However, we must be careful about conditional dependencies: The probability that a specific unknown position gets a value less than p_i is indeed L(p_i)/m, regardless of other assignments? Since the assignment is a random permutation, the marginal distribution of a single position is uniform over the set of missing numbers. Yes. So that's fine.
Thus we can compute answer.
Now, verify with examples:
Example 1:
n=3, p=[3,-1,-1]
known positions: index1 value3. missing positions: 2,3. m=2. missing numbers: which numbers are not present? known: 3, so missing: {1,2}. Sorted: [1,2].
Compute known-known inversions: only one known, so E_kk=0.
Compute left_i, right_i for known i=1: left_i = missing positions with index<1 =0. right_i = missing positions with index>1 =2 (positions 2,3). So left=0, right=2.
For known value x=3: L = count missing <3 = 2 (both 1 and 2 are <3). G = m - L = 0. So S = leftG + rightL = 00 + 22 =4.
S/m = 4/2=2.
E_uu = m*(m-1)/4 = 2*1/4 = 0.5.
Total E = 0 + 2 + 0.5 = 2.5. Good.
Example 2:
n=2, p=[1,2], known both, m=0. E_kk: count inversions: 1<2, so 0. So E=0. Output 0.
Total E=0.5. But example output is 499122177, which is 1/2 mod 998244353? Let's compute: MOD=998244353, inv(2)= (998244353+1)/2? Actually 499122177 is modular inverse of 2? Let's check: 2 * 499122177 mod 998244353 = 998244354 mod? 2*499122177=998244354, mod 998244353 =1. So yes it's 1/2. So 0.5 mod representation. So matches.
Thus formula works.
Now we need to implement efficiently.
We'll need modular inverses: inv(m) and inv(4) (which is 748683265? Actually inv(4) mod 998244353 is 748683265 because 4748683265=2994733060? Let's compute: 7486832654=2994733060, mod 998244353? 998244353*3=2994733059, remainder 1. So yes inv(4)=748683265. But we can compute using pow(x, MOD-2, MOD). Precompute or compute on the fly.
Better to compute inv(m) using pow(m, MOD-2) since m up to 2e5, but could compute all inverses up to n using linear method? Not necessary, pow is O(log MOD) per call, single call. But we also need inv(4). So we can compute directly.
Now implement steps:
Read n, array p.
Determine present values: create boolean present[n+1] all false. For each p_i != -1, set present[p_i]=true.
Count known_count = number of p_i != -1. m = n - known_count.
Build missing list: for v=1..n: if not present[v], append to missing list. This gives sorted list automatically because we iterate increasing. Let missing = list of ints. m = len(missing).
For known positions we need L(x) quickly. Since missing sorted, we can for each known value x compute L = lower_bound(missing, x) => index of first >= x, which equals count of missing < x. So L = that index (0-index). In Python we can use bisect_left.
Compute prefix_missing: an array pref of length n+1 (or simple list). pref[0]=0. For i from 1 to n: pref[i] = pref[i-1] + (1 if p[i-1]==-1 else 0). Use 1-indexed? Simpler: Use 0-index for positions but careful with left/right. I'll use 0-index for array indices but easier to compute left as number of missing before position i (i exclusive) and right as number missing after i. Let's use 0-index: positions 0..n-1. Create array is_missing[i] = (p[i]==-1). Then prefix_miss[i] = number of missing in [0..i] inclusive? We can compute prefix array of length n+1: prefix[0]=0; for i in range(n): prefix[i+1] = prefix[i] + (1 if p[i]==-1 else 0). Then total_missing = prefix[n]. For a known position at index i (0-index), left = prefix[i] (since prefix[i] counts missing in indices 0..i-1). right = total_missing - prefix[i+1] (since prefix[i+1] counts missing up to i, but i is not missing so same as total_missing - prefix[i]). Actually prefix[i+1] = prefix[i] + (p[i]==-1). Since p[i] is known, p[i]!=-1, so prefix[i+1]=prefix[i]. So right = total_missing - prefix[i+1] = total_missing - prefix[i]. But careful: prefix[i+1] includes missing up to i inclusive; but i is not missing so it's same. So both formulas are fine. I'll compute left = prefix[i]; right = total_missing - prefix[i+1] (since prefix[i+1] counts missing up to i, and i not missing, it's equal to prefix[i]; but using prefix[i+1] is safe because if i were missing, we wouldn't be in known case). Since we only compute for known i, we can use left = prefix[i]; right = total_missing - prefix[i+1].
Now compute known-known inversions using BIT (Fenwick tree) over values 1..n.
Approach for BIT: size n. Iterate positions i from 0 to n-1. If p[i] != -1: let val = p[i]. Then inversions contributed by this element as right element: query sum of values greater than val in BIT, i.e., total_seen - query(val). Since BIT stores frequencies. So we maintain total_known_seen count. Actually query(val) returns count of values <= val. So greater = total_seen - query(val). Add to E_kk. Then update BIT at val with +1.
Alternatively, we can implement BIT that supports prefix sum.
Now compute S.
Initialize S = 0 (as integer, possibly large up to about O(n^2) but n=2e5, left_i up to n, G up to m up to n, product up to 4e10, but Python int can handle. However we will eventually mod after multiplication by inv(m) and addition; we can keep S as Python int and take modulo after? Actually we need to compute (S * inv(m)) mod MOD. S may be up to ~ (n^3)? Let's estimate worst-case: For each known i, left_i could be up to n, right_i up to n, G and L up to m (n). So each term up to n^2; sum over up to n terms gives up to n^3 ~ 8e15, which fits in Python int (unbounded) but we may want to mod after each addition to avoid huge ints, but not necessary. Python int can handle 10^18 easily, but n=2e5 => n^3=8e15, okay. But if n=200k, n^3=8e15, still within 64-bit? 2^63-1 ~ 9.22e18, so it's fine. So we can compute S as Python int.
But note: left_i and right_i are up to n, G and L up to m (<=n), so each term max n * n = n^2 = 4e10; times n = 4e15. Yes safe.
Now we compute:
E_mod = (E_kk % MOD + S % MOD * inv_m % MOD + (m*(m-1) % MOD) * inv4 % MOD) % MOD.
But careful: When m=0, inv_m undefined. So we need to treat separately: if m==0, then S term is 0, E_uu term 0, so E_mod = E_kk % MOD.
Otherwise compute inv_m = pow(m, MOD-2, MOD).
Also inv4 = pow(4, MOD-2, MOD) (or constant).
Now check example 1:
n=3, m=2, E_kk=0, S=4, inv_m = inv(2)=499122177, Sinv_m mod = 4499122177 mod =? 4499122177=1996488708, mod 998244353 = 1996488708-9982443532=1996488708-1996488706=2. So that's 2. m*(m-1)=21=2, inv4=748683265, product=2748683265=1497366530 mod 998244353 = 1497366530-998244353=499122177? Actually 1497366530-998244353=499122177. So that's 0.5 in modular terms. Sum = 2 + 0.5 = 2.5 mod => (2+499122177) mod = 499122179? Wait 2 mod = 2, plus 499122177 = 499122179. That's output. Yes.
So algorithm seems correct.
Now, before coding, think about potential pitfalls:
Must ensure that known values are distinct and within 1..n, which is guaranteed.
For known-known inversion count, we only count pairs where both known and i<j. Our BIT method does exactly that.
For missing numbers set: Since known values are distinct, the missing set is indeed all numbers not present.
For computing L(x) = number of missing numbers less than x, we can use binary search on sorted missing list. Since missing list is sorted ascending, lower_bound(x) gives count of elements < x.
But note: x may be less than the smallest missing or greater than largest. That's fine.
left_i and right_i computed via prefix_missing.
Potential integer overflow in intermediate multiplication S * inv_m: we take mod after.
Now confirm with more test cases.
Test: n=1, p=[-1] => m=1, known-known=0, known-unknown? No known, so S=0. E_uu = 1*0/4 =0. So expected inversions =0. Output 0.
Test: n=1, p=[1] => m=0, E_kk=0. Output 0.
Test: n=2, p=[-1,2] => known: index2 value2 (assuming index2? Actually positions: 1-> -1, 2->2). m=1 missing number: {1}. Known-known=0. Compute left_i, right_i for known index2: left = missing positions to left: position1 is missing, so left=1, right=0. For known value 2: L = count missing less than 2 = 1 (since 1<2). G=0. So S = leftG + rightL = 10+01=0. So S/m=0. E_uu = m*(m-1)/4 = 0. So E=0. But let's think: Only possible completion: [1,2] has 0 inversions. So correct.
Test: n=2, p=[2,-1] => known index1 value2, m=1 missing {1}. left=0, right=1. For known value2: L=1 (1<2), G=0. S = 00 + 11 =1. S/m=1/1=1. E_uu=0. So E=1. Let's check: Completion: [2,1] has one inversion (2>1 at i=1,j=2). So expected=1. Good.
Missing positions: 1 and 3. For known position index2 (value2): left = missing to left: position1 missing => left=1. right = missing to right: position3 missing => right=1. L = missing less than 2: only 1 -> L=1. G = m-L =1 (3>2). So S = leftG + rightL = 11 + 11 =2. S/m = 2/2 =1. Known-known=0. E_uu = 2*1/4 = 0.5. So expected = 1.5.
Now enumerate completions: Missing numbers {1,3}, assign to positions 1 and 3 uniformly over 2 permutations.
Permutation1: [1,2,3] inversions: none? Check pairs: (1,2): 1<2 no, (1,3):1<3 no, (2,3):2<3 no => 0.
n=4, p=[3,-1,1,-1] => known values: index1=3, index3=1. Missing positions: 2,4. Missing numbers: which numbers not in {3,1}? 2 and 4 => {2,4}. m=2. Compute known-known inversions: pair (1,3) with i=1<j=3: p1=3 > p3=1 so inversion => 1. So E_kk=1.
Compute left_i, right_i:
Index1 (val=3): left=0, right: missing positions >1? positions 2 and 4 => right=2. L for 3: missing numbers less than 3: {2} => L=1, G=1. So term: 01 + 21 =2.
Index3 (val=1): left: missing positions <3: position2 is missing => left=1. right: missing >3: position4 missing => right=1. L for 1: missing numbers less than 1: none => L=0, G=2. Term: leftG + rightL = 12 + 10 =2.
Sum S=2+2=4. S/m=4/2=2.
E_uu = 2*1/4 = 0.5.
Total E = 1 + 2 + 0.5 = 3.5.
Now enumerate completions: missing numbers {2,4} assigned to positions 2,4.
pos2=4, pos4=2 => [3,4,1,2] inversions: (1,2):3<4 no; (1,3):3>1 yes; (1,4):3>2 yes; (2,3):4>1 yes; (2,4):4>2 yes; (3,4):1<2 no => total 4. So expected = (3+4)/2=3.5. Good.
Thus formula works.
Now implementation details:
We need to handle modular arithmetic carefully. Since we need final answer modulo MOD, we can compute each term mod MOD.
Let MOD = 998244353.
Compute:
E_kk_mod = E_kk % MOD.
S_mod = S % MOD.
inv_m = pow(m, MOD-2, MOD) if m>0 else 0 (but we won't use).
term2 = S_mod * inv_m % MOD if m>0 else 0.
term3 = (m*(m-1) % MOD) * inv4 % MOD.
Ans = (E_kk_mod + term2 + term3) % MOD.
Double-check when m>0: The term2 expects S/m as rational. But if we compute S_mod * inv_m, that's equivalent to (S mod MOD) * inv_m mod MOD. Since we are working modulo MOD, but careful: S might be huge and we take mod, then multiply by inv_m. This gives (S mod MOD) * inv(m) mod MOD, which equals (S * inv(m)) mod MOD because inv(m) is the modular inverse of m modulo MOD, and we are effectively computing S * m^{-1} mod MOD. However, is it correct to reduce S modulo MOD before multiplication? Yes, because (S mod MOD) * inv_m mod MOD = S * inv_m mod MOD, since multiplication modulo MOD is well-defined. So fine.
But there is subtlety: The rational S/m may not be integer; but we compute modular representation of that rational as S * inv(m) mod MOD. Since MOD is prime > n, and m < MOD (since n <= 2e5 < MOD), inv(m) exists. So it's correct.
Similarly term3: m*(m-1)/4 = (m*(m-1) * inv(4)) mod MOD.
Edge case m=0: term3 = 0; term2 = 0; ans = E_kk_mod.
Now compute known-known inversions E_kk. We can compute using BIT over values 1..n. We'll need BIT with size n. We'll query for count of known values greater than current value. Implementation: BIT supports add(idx, delta) and sum(idx) returns prefix sum up to idx.
Standard: For each known value val (1-indexed), greater count = total_seen - sum(val). Then add val.
Initialize total_seen = 0.
We'll iterate positions from i=0..n-1. If p[i] != -1: val = p[i]; greater = total_seen - bit.sum(val) (if bit.sum(val) returns sum up to val inclusive? Usually BIT sum returns sum of indices 1..idx. So count of <= val = bit.sum(val). So greater = total_seen - bit.sum(val). Add to E_kk. Then bit.add(val,1); total_seen +=1.
Alternatively, we could compute bit.sum(n) - bit.sum(val). But total_seen = bit.sum(n) after update? Better use total_seen variable.
Now O(n log n). Fine.
Now compute S.
We need for each known position i (0-index), with value x, left = prefix[i] (since prefix[i] = count missing before i). Actually as we defined prefix array of length n+1: prefix[0]=0; for i in range(n): prefix[i+1] = prefix[i] + (1 if p[i]==-1 else 0). So for known position i (0-index), left = prefix[i]; right = prefix[n] - prefix[i+1] because prefix[i+1] counts missing up to i inclusive, and i is known, so it's same as total_missing - prefix[i+1].
So compute prefix as list of length n+1.
Then S = 0.
For each i where p[i] != -1:
left = prefix[i]
right = total_missing - prefix[i+1]
x = p[i]
L = number of missing numbers less than x. We'll get via binary search: import bisect; L = bisect.bisect_left(missing, x) # returns count of missing < x.
G = m - L
S += left * G + right * L
Now careful: L is count of missing numbers < x. Since x is known and not missing, indeed x is not in missing set, so L is correct. G = m - L.
Now done.
Now handle m=0 separately to avoid binary search on empty list (though bisect on empty works? It returns 0. But left and right would be 0 anyway, and G = m - L = 0-0=0, so S=0, but we also need to avoid division by zero. So we can either compute S anyway but then skip term2 if m==0. However, if m=0, missing list empty, bisect_left returns 0, L=0, G=0, S=0. So okay. But term2 would require inv(m). So we need to conditionally compute term2 only if m>0. So better to check m>0 before term2 and term3? Actually term3 also zero if m=0? m*(m-1) = 0, so term3 = 0 anyway. But we can compute term3 always as (m*(m-1) % MOD) * inv4 % MOD; for m=0, 0*inv4=0. So fine. But term2 must be conditional to avoid dividing by zero. So:
if m > 0:
term2 = (S % MOD) * pow(m, MOD-2, MOD) % MOD
else:
term2 = 0
But we also need S computation: we can compute S even if m=0, as described. Then term2=0.
Now we need to compute E_kk, S, and then answer.
Complexities: O(n log n) due to BIT and binary searches.
Now check for potential overflow: left_i and right_i up to n, L, G up to m (n), product up to 4e10, sum S up to ~4e15, still fits in Python int. But for large n=2e5, left_i could be n, G could be n, product n^2 = 4e10; sum over n known = up to 8e15. Actually worst case when all positions are known? Then m=0, left_i and right_i are 0 anyway. Actually for S to be large, we need many known positions with many missing on each side. The maximum S occurs maybe when half known, half missing, and values arranged such that L and G are about m/2. For each known, left_i and right_i roughly (n/2). So each term ~ (n/2)(m/2) + (n/2)(m/2) = nm/2. With n known about n/2, total S ~ (n/2) * (nm/2) = n^2 * m / 4. With m ~ n/2, S ~ n^3/8 = 1e15 for n=2e5: (2e5)^3/8 = 8e15/8 = 1e15. So still safe.
Now we need to verify that the probability for unknown-unknown pairs is indeed 1/2. This holds because the joint distribution of two distinct positions is uniform over all ordered pairs of distinct values from M. Since M has distinct integers, the number of ordered pairs with first > second equals number with first < second. So probability = 1/2. That is independent of the specific numbers? Yes, as long as they are distinct. So we don't need to know which numbers are missing for that term. Good.
Now we have answer.
But is there any nuance? Let's think about if the known values include numbers that are also part of missing? No, guaranteed distinct. So missing set is complement.
Now confirm with random tests via brute force for small n to ensure correctness.
Before coding, let's also think about alternative scenarios: Could the known-unknown probability be something else due to conditional dependencies? For a specific known-unknown pair, we might think that the unknown value distribution is uniform over M, but also the other unknown positions assignments affect the joint distribution; however, the marginal for a single unknown is uniform regardless. So probability that a_j > p_i is just proportion of missing numbers > p_i. So correct.
Now we must ensure that the counts left_i and right_i are correctly counted as number of missing positions on each side.
Now implement.
Implementation Steps:
Read n.
Read list p (size n).
MOD = 998244353.
Create present array of size n+1 (boolean) initialized False. Also count known_count.
For val in p: if val != -1: present[val] = True; known_count += 1.
m = n - known_count.
Build missing list: for v in range(1, n+1): if not present[v]: missing.append(v).
Compute prefix_missing: pref = [0]*(n+1); for i in range(n): pref[i+1] = pref[i] + (1 if p[i]==-1 else 0).
total_missing = pref[n].
Compute known-known inversions E_kk using BIT.
BIT implementation:
class BIT:
def init(self, n):
self.n = n
self.bit = [0]*(n+2)
def add(self, idx, val):
while idx <= self.n:
self.bit[idx] += val
idx += idx & -idx
def sum(self, idx):
res = 0
while idx > 0:
res += self.bit[idx]
idx -= idx & -idx
return res
Then:
E_kk = 0
bit = BIT(n)
seen = 0
for val in p:
if val != -1:
less_or_equal = bit.sum(val)
greater = seen - less_or_equal
E_kk += greater
bit.add(val, 1)
seen += 1
E_kk_mod = E_kk % MOD
Compute S.
Import bisect.
S = 0
for i in range(n):
if p[i] != -1:
left = pref[i]
right = total_missing - pref[i+1] # pref[i+1] includes missing up to i; i known so it's pref[i]
x = p[i]
L = bisect.bisect_left(missing, x) # count missing < x
G = m - L
S += left * G + right * L
(Even if m=0, missing empty, bisect_left returns 0, G = 0; S += left0 + right0 = 0.)
Compute term2:
if m > 0:
inv_m = pow(m, MOD-2, MOD)
term2 = (S % MOD) * inv_m % MOD
else:
term2 = 0
Now test: n=3, p=[-1,2,-1] -> earlier we computed E=1.5.
n=3, known_count=1, m=2 missing=[1,3]? Wait known is 2, numbers from 1..3 missing: {1,3}. Actually present[2]=true, missing = [1,3]. But note missing numbers are 1 and 3? However 3 is also missing. Yes.
pref: i0=-1 -> pref1=1; i1=2 -> pref2=1; i2=-1 -> pref3=2; total=2.
i1 known: left=pref1=1; right=total - pref2 = 2-1=1; x=2, L = bisect_left([1,3],2) = 1 (since 1<2, next 3>2) => L=1, G=1; S = 11 + 11 =2.
term2 = 2 * inv2 = 1.
term3 = 21 * inv4 = 2inv4 = 499122177.
ans = 0 + 1 + 499122177 = 499122178? Wait 1 + 499122177 = 499122178. But we expected 1.5. 1.5 mod corresponds to 1 + 0.5 = 1 + 499122177 = 499122178. That's correct? Let's compute: 0.5 mod is 499122177, plus 1 = 499122178. But earlier we said expected 1.5, so that matches.
But check manually: For n=3, p=[-1,2,-1], earlier we computed E=1.5. So output should be 499122178. Not given, but it's consistent.
Now test with multiple known: n=4, p=[3,-1,1,-1] -> expected 3.5 = 3 + 0.5 -> mod: 3 + 499122177 = 499122180? Wait 3+499122177=499122180. Let's compute: 499122177+3=499122180. So answer would be 499122180. But earlier we computed E=3.5. So check with our formula: m=2, E_kk=1, S=4, term2=4/2=2, term3=0.5, total=3.5 -> 1+2+0.5=3.5 -> modular: 1 + 2 + 499122177 = 499122180? Actually 1+2=3, +499122177=499122180. Good.
Now verify BIT code for known-known inversions: For p=[3,-1,1,-1], known positions: index0=3, index2=1. Process order: i0 val3: seen=0, greater=0, add. i1 skip, i2 val1: less_or_equal = bit.sum(1) =? BIT after first: added 3 at index3. bit.sum(1) = 0 (since no 1). less_or_equal=0, greater = seen(1) - 0 =1. So E_kk=1. Correct.
All good.
Now final check: Could there be any subtlety about the probability of known-unknown pairs when the unknown position's value is not independent of other unknowns? But we use marginal, so it's fine.
Thus solution works.
Now we should also confirm that the inversion count for known-known pairs counts only when i<j. Our BIT does that.
Now consider if there is any situation where p_i = -1 and we need to treat differently? No.
Now complexity: O(n log n). With n=2e5, it's fine.
Now we must implement BIT efficiently. Python might be fine with 2e5 operations with log factor.
Potential optimization: Use array and loops.
Now think about using Fenwick with 1-indexed values.
Now code.
But before finalizing, let's think about if there is any alternative nuance: The problem statement uses "i > j and a_i < a_j". We used the equivalent i a_j. So our counting of known-known inversions with i a_j is correct. Also for known-unknown pairs we considered i a_j. But note that if i known and j unknown, we considered case i<j (known left, unknown right) with condition a_i > a_j, probability L/m. And i unknown, j known (unknown left, known right) with condition a_i > a_j, probability G/m. That's consistent. So all good.
Now we should verify that for a known-unknown pair with i<j (known left, unknown right), the condition for inversion is a_i > a_j. So indeed we need probability that known > unknown. So using L/m.
For i<j (unknown left, known right), condition a_i > a_j -> unknown > known, probability = G/m.
Now confirm with example: p=[2,-1] (i=1 known=2, i=2 unknown). i=1<j=2, known left, unknown right -> probability known>unknown = proportion of missing numbers less than 2 = 1/1 =1, so inversion always. That's correct.
Now p=[-1,2]: i=1 unknown, i=2 known, condition unknown > known, probability = proportion of missing numbers greater than 2 = 0 (since missing number is 1) -> 0. So no inversion. That's correct.
Now we need to be careful about integer division when m=0. Already handled.
Now about modular arithmetic: inv4 = pow(4, MOD-2, MOD) = 748683265.
Now we can compute term3 as (m * (m-1) % MOD) * inv4 % MOD.
But note that m*(m-1) may be large but < MOD^2? m up to 2e5, product up to 4e10, still fit in Python int, but we take mod anyway.
Now answer computed.
Potential pitfalls: Use of bisect on missing list when m=0: bisect_left([], x) returns 0. That's fine.
But also note: If known value x is less than all missing numbers, L=0; if greater than all, L=m; G accordingly.
Now all set.
Now I'll implement.
But before that, I'd like to double-check if there is any contribution from known-unknown pairs when m=0? Already none.
Now think about a scenario where there are duplicates? Not possible because given permutation with -1 replacements, known numbers are distinct.
Now confirm large n: BIT with size n (200k) operations 200k log2(200k) ~ 200k*18 = 3.6M, fine.
Now about memory: present array of size n+1 bool (could use list of bool or bytearray). Missing list up to n.
Now final code.
But wait: There's another nuance: In the formula for known-unknown pairs, we used probability = L(p_i)/m for known left and unknown right. But is that exactly the marginal probability? Let's derive carefully: For a specific known position i (value x) and a specific missing position j (with j > i), we want Pr(x > a_j). Since a_j is uniformly distributed over M, indeed Pr(x > a_j) = |{v in M : v < x}| / m = L/m. However, is the uniform distribution over M correct for a_j? Yes, because all completions are equally likely, and the value at position j is equally likely to be any missing number (by symmetry). So that's correct.
Now for unknown left and known right: Pr(a_i > y) = |{v in M : v > y}| / m = G/m.
Thus correct.
Now about unknown-unknown pairs: For two distinct missing positions i<j, we need Pr(a_i > a_j). Since (a_i, a_j) is a uniformly random ordered pair of distinct elements from M, number of ordered pairs = m*(m-1). Among them, number with a_i > a_j = number of unordered pairs {x,y} with x≠y, and for each unordered pair there is exactly one order where first > second if we compare values. So count = number of unordered pairs = C(m,2). So probability = C(m,2) / (m*(m-1)) = 1/2. So correct.
Thus final answer.
Now implement.
Testing with random small n to ensure correctness: I'll simulate mental or maybe later.
Now there is also possibility of using linear-time method for known-known inversion using BIT or merge sort; but BIT fine.
Now, could we optimize computing S by precomputing for each known value the L and G and then combining with left_i, right_i? Already fine.
Now consider large n with many known values, bisect_left per known may be O(log m) but m could be up to n. Total O(n log n). Acceptable.
Alternatively we could precompute an array L_for_val for each possible value (1..n) representing number of missing numbers less than that value. Since we have missing list sorted, we can compute for each value quickly using a pointer? But not needed.
But we could also compute using a BIT over values that marks missing numbers and then prefix sum queries. But binary search is simpler.
Now we must ensure we import bisect.
Now code:
code
import sys
import bisect
MOD = 998244353
INV4 = pow(4, MOD-2, MOD)
def main():
input = sys.stdin.readline
n = int(input())
p = list(map(int, input().split()))
present = [False]*(n+1)
known_count = 0
for val in p:
if val != -1:
present[val] = True
known_count += 1
m = n - known_count
missing = []
for v in range(1, n+1):
if not present[v]:
missing.append(v)
# prefix missing count
pref = [0]*(n+1)
for i in range(n):
pref[i+1] = pref[i] + (1 if p[i] == -1 else 0)
total_missing = pref[n]
# known-known inversions
class BIT:
__slots__ = ('n', 'bit')
def __init__(self, n):
self.n = n
self.bit = [0]*(n+2)
def add(self, idx, delta):
while idx <= self.n:
self.bit[idx] += delta
idx += idx & -idx
def sum(self, idx):
s = 0
while idx > 0:
s += self.bit[idx]
idx -= idx & -idx
return s
bit = BIT(n)
seen = 0
E_kk = 0
for val in p:
if val != -1:
less_eq = bit.sum(val)
greater = seen - less_eq
E_kk += greater
bit.add(val, 1)
seen += 1
E_kk_mod = E_kk % MOD
# compute S
S = 0
for i in range(n):
if p[i] != -1:
left = pref[i]
right = total_missing - pref[i+1]
x = p[i]
L = bisect.bisect_left(missing, x)
G = m - L
S += left * G + right * L
if m > 0:
inv_m = pow(m, MOD-2, MOD)
term2 = (S % MOD) * inv_m % MOD
else:
term2 = 0
term3 = (m * (m-1) % MOD) * INV4 % MOD
ans = (E_kk_mod + term2 + term3) % MOD
print(ans)
if __name__ == "__main__":
main()
That should solve.
Now double-check BIT: sum(val) returns sum over indices 1..val inclusive. Since val is between 1 and n, works. For val=0? Not possible.
Now check if any off-by-one: prefix pref[i] gives missing count before index i (0-index). For i=0, pref[0]=0, correct left. For i known, right = total_missing - pref[i+1]. Since pref[i+1] counts missing up to index i inclusive; but i is known, so pref[i+1] = pref[i]. So right = total_missing - pref[i] = total_missing - left. Indeed left+right = total_missing. That's correct. But careful: total_missing = pref[n]. So for known i, left = number of missing positions with index < i, right = number with index > i. So left+right = total_missing. That's consistent. So fine.
Now test with random small n via brute force to ensure correctness. I'll simulate mentally for a few:
n=3, all possible patterns? Let's test p=[1, -1, -1]. known=1, m=2 missing={2,3}. pref: [0,0,1,2]? Actually compute: i0=1 not missing -> pref1=0; i1=-1 -> pref2=1; i2=-1 -> pref3=2; total=2. known i0: left=0, right=2, x=1, L = bisect_left([2,3],1)=0, G=2. So S = 02 + 20 =0. term2=0. term3 = 2*1/4=0.5. E_kk=0. So expected=0.5. Now possible completions: assign {2,3} to positions1,2: [1,2,3] inversions=0; [1,3,2] inversions=1 (since (2,3):3>2). Expected=0.5. Good.
Now p=[-1,1,-1]: known index1=1, missing={2,3}. left=pref[1]=? pref: i0:-1 -> pref1=1; i1:1 -> pref2=1; i2:-1 -> pref3=2. left for i1 = pref[1]=1, right = total - pref[2] = 2-1=1. x=1, L = bisect_left([2,3],1)=0, G=2. S = 12 + 10 =2; term2=1; term3=0.5; E_kk=0; total=1.5. Expected? Completions: positions 0 and 2 get {2,3}. Cases: [2,1,3]: pairs: (0,1):2>1 yes; (0,2):2<3 no; (1,2):1<3 no -> total=1. [3,1,2]: (0,1):3>1 yes; (0,2):3>2 yes; (1,2):1<2 no -> total=2. Expected=1.5. Good.
Now p=[-1,2,1]? But known two? Actually p=[-1,2,1] known positions index1=2, index2=1, m=1 missing={3}. pref: i0:-1 -> pref1=1; i1:2 -> pref2=1; i2:1 -> pref3=1. total=1. E_kk: known-known: process i1 val2: seen0 -> greater0; add; seen1. i2 val1: less_eq = bit.sum(1)=0? Wait BIT has 2 at index2. bit.sum(1)=0; greater=seen(1)-0=1; so E_kk=1. That's correct: pair (2,1) i=1<j=2? Actually indices: i=1 (val2) and j=2 (val1) with i<j? Yes i=1<j=2, and 2>1 so inversion. So E_kk=1. Now S: For known i1 (index1): left = pref[1] = pref1? Actually i=1: left = pref[1] (since i is 1, pref[1] is missing count up to index0? Wait careful: using 0-index: indices: 0:-1, 1:2, 2:1. For i=1 (known), left = pref[1] = number of missing in [0..0] = pref[1]=1 (since index0 missing). right = total - pref[2] = 1 - pref[2]; pref[2] = pref[1] + (p[1]==-1?) p[1]=2 not missing, so pref[2]=1. So right=0. x=2, L = bisect_left([3],2)=0, G=1. S contribution = 11 + 00 =1. For i=2 (known): left = pref[2] = 1, right = total - pref[3] = 1 - 1 =0; x=1, L = bisect_left([3],1)=0, G=1; contribution = 11 + 00 =1. So S=2. m=1, term2 = 2 * inv1 = 2. term3=0. So total E = 1 + 2 = 3. Let's check manually: Only missing number is 3, assign to position0. So only completion: [3,2,1]. Inversions: pairs (0,1):3>2 yes; (0,2):3>1 yes; (1,2):2>1 yes -> total=3. So expectation=3. Good.
Now test case with both known and unknown and known-known inversions: p=[2, -1, 1] we just did? Actually that's similar. So it's consistent.
Now test case where missing numbers include some values that are less and greater than known values. Already covered.
Thus solution seems correct.
Now we should think about potential integer division rounding: We are using modular arithmetic for rational numbers; it's fine.
Now we can finalize.
But there is a nuance: For known-unknown pairs, we assumed marginal uniform distribution. But is there any effect due to the fact that the assignment of missing numbers to missing positions is a random permutation, but we are conditioning on the rest? No, because for a particular known-unknown pair, the distribution of the unknown value is uniform over M, independent of the known values? Actually, it is independent of the known values? Not exactly independent but marginal is uniform. So probability is L/m.
Thus no problem.
Now verify correctness with another random test: n=4, p = [ -1, 3, -1, 2 ]? Let's compute both ways.
Known values: 3 at index1, 2 at index3. Missing numbers: which numbers from 1..4 not in {3,2}? {1,4}. m=2.
Compute manually expected inversions.
First compute known-known inversion: indices: known at 1 (val3) and 3 (val2) with i=1<j=3? Actually positions: 0-index: indices: 0: -1, 1:3, 2: -1, 3:2. So known indices 1 and 3, i<j? 1<3, and 3>2 so inversion -> E_kk=1.
pos0=4, pos2=1 => [4,3,1,2]. Inversions: (0,1):4>3 yes; (0,2):4>1 yes; (0,3):4>2 yes; (1,2):3>1 yes; (1,3):3>2 yes; (2,3):1<2 no => total 5. So expected = (2+5)/2=3.5. Good.
Now test p=[-1,-1,3,2,1] maybe? But not necessary.
Thus solution holds.
Now we can proceed.
Now let's consider potential pitfalls: The BIT for known-known inversion uses values from 1..n, but if we use n as size, fine. However, we should ensure that BIT sum returns correct for val = n.
Now I'll think about alternative simpler method: Since known values are distinct, we could compute known-known inversions by counting inversions in the known subsequence ignoring unknown positions. That's what BIT does.
Now we also need to consider large m (like 200000) and we compute term3 = m*(m-1)/4 mod. m*(m-1) might be even, but we use modular inverse of 4.
Now everything set.
But before finalizing, I'll check if there is any misinterpretation: The definition says i > j and a_i < a_j. If we adopt i a_j, it's same. Good.
Now think about if there is any effect from the condition that the permutation is uniformly random among valid permutations. This includes the fact that known positions are fixed; we are only randomizing unknown positions. Our approach considered that.
Now I'll implement final code.
But wait: There might be an issue with the computation of S: left = pref[i] and right = total_missing - pref[i+1]. However, careful: pref[i+1] = number of missing positions with index <= i. Since i is known, pref[i+1] = pref[i] (since no missing at i). So right = total_missing - pref[i]. That's same as total_missing - left. But our formula using pref[i+1] works. However, if we incorrectly treat i unknown? But we only compute for known i, so fine.
Double-check with example where i is known but there is a missing at same index? Not possible.
Now about BIT: we need to ensure that we add value after query. That's correct.
Now about potential performance: Python loops might be borderline but for 2e5 it's fine. Use sys.stdin.read for faster input? Not necessary.
Now verify for maximum input: n=200000, all positions known? Then m=0, we compute BIT for 200k, that's fine. If all positions unknown? Then m=n, no known positions, so we skip BIT and S loops. BIT operations none. Then term3 computed as n*(n-1)/4 mod. That's fine. For n=200k, term3 computed quickly.
If mixed, loops over all n for computing prefix and then for S we loop again and do bisect per known. At most 200k bisect operations, each O(log n) ~ 18. So fine.
Now note that missing list can be up to 200k, and bisect uses binary search on list, which is O(log m). Good.
Thus code should pass.
Now test with n=200000 all -1, answer should be n*(n-1)/4 mod. That is huge but compute mod.
Now test with n=1, all known. Already.
Now about negative values: p_i can be -1 only. So fine.
Now output as integer.
Now confirm that we included INV4 correctly.
Now I think solution is ready.
But perhaps there is a more clever way to compute S without bisect for each known? We could precompute an array cnt_less for each value. Since missing numbers are known, we could create an array less_count of size n+1 where less_count[v] = number of missing numbers < v. This can be computed by scanning v from 1 to n: maintain pointer to missing list. For v in 1..n, if missing[ptr] < v then increment count, else less_count[v] = count. But that would require O(n) time, which is maybe beneficial but not necessary. However, bisect per known might be slightly slower but still okay.
But let's consider worst-case: known_count ~ n/2 ~ 100k, each bisect O(log 100k) ~ 17, so 1.7 million operations, fine. Python's bisect is implemented in C, so it's fast.
Thus fine.
Now consider edge case: missing numbers list is empty, bisect_left([], x) returns 0, L=0, G=0, S=0. Works.
Now what about computing term2 if m > 0 but S could be 0? Works.
Now we should also consider the possibility of overflow in S * inv_m if S not reduced mod? Actually we compute S % MOD first, then multiply by inv_m, then mod. That's correct.
But we must ensure that S is not too huge for Python to compute % MOD quickly. Python's large integer modulo is fine.
Now final code.
Let's test quickly with some random small n using brute-force to double-check. Since I'm not executing, but we can mentally test few.
Now let's do a random n=4 with some pattern: p = [ -1, 4, -1, 2 ]? Already did similar.
Now test p = [1, -1, 2, -1] -> known: 1 at idx0, 2 at idx2; missing numbers: which? {3,4}. m=2.
Now test with known-known inversion: p = [2,1,-1] -> known: 2,1; missing: {3}. m=1. E_kk: process: i0=2 -> greater=0; add; i1=1 -> less_eq=0? BIT has 2 at idx2, bit.sum(1)=0, greater=1-0=1; so E_kk=1. prefix: i0:2 -> pref1=0; i1:1 -> pref2=0; i2:-1 -> pref3=1; total=1. S: i0: left=0, right=total - pref[1]=1-0=1? pref[1]=0 -> right=1. x=2, L = bisect_left([3],2)=0, G=1 => contribution =01+10=0. i1: left=pref[1]=0, right=total - pref[2]=1-0=1? pref[2]=0 -> right=1. x=1, L=0, G=1 => contribution =01+10=0. S=0. term2=0. term3=1*0/4=0. total E=1. Only completion: [2,1,3] has inversions: (1,2):2>1 yes, (1,3):2<3 no, (2,3):1<3 no -> total 1. Good.
Now test where known values and missing numbers have distribution leading to non-integer contributions, fine.
Thus solution appears correct.
Now we can consider if there is any need to compute modular inverses for large numbers but we only need pow(m, MOD-2) and inv4.
Now just code.
But wait, there is an alternative approach: the expected total number of inversions can be computed as sum over all pairs (i,j) of Pr(inversion). We derived that. So it's correct.
Now we might want to optimize BIT to use list of int and while loops; but it's fine.
Potential micro-optimizations: Use local variables inside loops for speed. But it's okay.
Now let's also think about if there is any issue with using BIT and integer addition; we use Python ints; fine.
Now consider scenario where known count is 0 and m is large: Then term3 = m*(m-1)/4. For n=200k, this is about 10^10, and mod operation yields a number. That's fine.
Now I'll produce final answer.
But wait: The problem statement says: "It can be shown that it is in the form of P/Q where P and Q are non-negative integers and Q ≠ 0. Report the value of P ⋅ Q^{-1} \pmod {998244353}." So we are doing exactly that.
Now some additional checks: The expected number could be rational, and we output its representation modulo MOD.
Now we have solved.
Now I'll produce final code with comments.
One more nuance: The BIT sum method can be made faster by using bit = [0]*(n+1) and while loops. Already.
Now I'll rewrite BIT more compactly maybe as functions.
Alternatively, we could use Python's built-in sorted list? No, BIT better.
Now produce final code.
I'll also consider using sys.setrecursionlimit but not needed.
Now final code.
After writing, test with given examples:
Example 1:
Input:
3
3 -1 -1
Our code: prints 499122179.
Example 2:
2
1 2 -> 0.
Example 3:
2
-1 -1 -> 499122177.
All good.
Now I'm confident.
But before finalizing, think about the possibility of integer division rounding errors in our calculation of S? S is integer sum, so no rounding.
Now final.
Now I'll provide the solution explanation as well, but the answer is just code.
However, the problem might be from Codeforces Round, and typical solutions use similar reasoning.
One more nuance: The known-known inversion counting via BIT counts all pairs i<j with both known. That's fine.
Now I'll implement.
But I think there is a potential subtle bug: When we compute left and right, we used pref[i] and total_missing - pref[i+1]. However, we need to ensure that i is known. In our loop, we only consider known positions, so fine.
But consider a known position at index 0: left = pref[0] = 0, correct. right = total_missing - pref[1]. Since pref[1] is missing count up to index 0 inclusive; if p[0] known, pref[1]=pref[0]=0, right = total_missing. So correct.
Now for known at last index n-1: left = pref[n-1] (count missing before last), right = total_missing - pref[n] (since pref[n] = total_missing), so right = 0. Correct.
Now we're done.
Now I'll produce final answer. ```python
import sys
import bisect
MOD = 998244353
INV4 = pow(4, MOD - 2, MOD) # modular inverse of 4
def main():
input = sys.stdin.readline
n = int(input())
p = list(map(int, input().split()))
code
# ----- find missing numbers -----
present = [False] * (n + 1)
known_cnt = 0
for val in p:
if val != -1:
present[val] = True
known_cnt += 1
m = n - known_cnt # number of missing positions
missing = []
for v in range(1, n + 1):
if not present[v]:
missing.append(v) # already sorted
# ----- prefix count of missing positions -----
pref = [0] * (n + 1) # pref[i] = number of -1 in p[0..i-1]
for i in range(n):
pref[i + 1] = pref[i] + (1 if p[i] == -1 else 0)
total_missing = pref[n]
# ----- known-known inversions (BIT) -----
class BIT:
__slots__ = ('n', 'bit')
def __init__(self, n):
self.n = n
self.bit = [0] * (n + 2)
def add(self, idx, delta):
while idx <= self.n:
self.bit[idx] += delta
idx += idx & -idx
def sum(self, idx):
s = 0
while idx:
s += self.bit[idx]
idx -= idx & -idx
return s
bit = BIT(n)
seen = 0
E_kk = 0
for val in p:
if val != -1:
less_eq = bit.sum(val)
greater = seen - less_eq # numbers already seen and larger than val
E_kk += greater
bit.add(val, 1)
seen += 1
E_kk_mod = E_kk % MOD
# ----- sum for known-unknown pairs -----
S = 0
for i in range(n):
if p[i] != -1:
left = pref[i] # missing positions to the left of i
# missing positions to the right of i
right = total_missing - pref[i + 1]
x = p[i]
L = bisect.bisect_left(missing, x) # count of missing numbers < x
G = m - L
S += left * G + right * L
if m > 0:
inv_m = pow(m, MOD - 2, MOD)
term2 = (S % MOD) * inv_m % MOD
else:
term2 = 0
term3 = (m * (m - 1) % MOD) * INV4 % MOD
ans = (E_kk_mod + term2 + term3) % MOD
print(ans)