公式
B - Find Permutation 2 解説 by en_translator
This problem can be solved by an exhaustive search of permutations.
There are \(N!\) candidates of \(P\), which are permutations of \((1,2,\ldots,N)\). We inspect each of them to check if it satisfies the second condition.
Once you find a conforming \(P\), print it immediately and terminate the program; if you do not find one after scanning all, print No
.
The proposition “if \(A_i \neq -1\), then \(P_i=A_i\)” is equivalent to “\(A_i=-1\) or \(A_i=P_i\).” The latter form is convenient for the implementation.
from itertools import permutations
n = int(input())
a = list(map(int, input().split()))
for p in permutations([i + 1 for i in range(n)]):
ok = True
for i in range(n):
ok &= a[i] == -1 or p[i] == a[i]
if ok:
print("Yes")
print(*p)
break
else:
print("No")
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> a(n);
for (int &i : a)
cin >> i;
vector<int> p(n);
iota(p.begin(), p.end(), 1);
do {
bool ok = true;
for (int i = 0; i < n; i++) {
ok &= a[i] == -1 || p[i] == a[i];
}
if (ok) {
cout << "Yes" << endl;
for (int i = 0; i < n; i++) {
cout << p[i] << " \n"[i + 1 == n];
}
return 0;
}
} while (next_permutation(p.begin(), p.end()));
cout << "No" << endl;
return 0;
}
投稿日時:
最終更新: