Official

C - Between P and Q Editorial by en_translator


There are \(N!\) permutations of \((1,2,\ldots,N)\). Under \(N\le 10\), this is at most \(3628800\), so we may inspect all of them and check if the condition is satisfied.

The permutations of \((1,2,\ldots,N)\) can be enumerated exhaustively without duplicates using, for example, next_permutation in C++.

Sample code (C++)

#include <bits/stdc++.h>
using namespace std;
int main() {
	int n;
	cin >> n;
	vector<int> p(n), q(n);
	for (int &v : p) cin >> v;
	for (int &v : q) cin >> v;
	vector<int> a(n);
	iota(a.begin(), a.end(), 1);
	int ans = 0;
	do {
		if (p < a && a < q) ans++;
	} while (next_permutation(a.begin(), a.end()));
	cout << ans << endl;
}

Sample code (Python)

from itertools import permutations

n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
ans = 0
for a in permutations([i + 1 for i in range(n)]):
    ans += p < list(a) < q
print(ans)

Bonus: find the answer modulo \(998244353\) under \(N\le 10^5\).

posted:
last update: