交互题
题意:猜一个排列 a [ 1... n ] a[1...n] a[1...n] 。通过 “ ? i j ? \ i \ j ? i j” 的方式提问 a [ i ] % a [ j ] a[i] \% a[j] a[i]%a[j] 的答案是多少,最多提问 2 n 2n 2n次。输出“!”,然后输出排列。
思路:因为是排列,没有重复数字,所以a[i] 和 a[j]一定有大有小。我们通过提问 a [ i ] % a [ j ] a[i] \% a[j] a[i]%a[j] 和 a [ j ] % a [ i ] a[j] \% a[i] a[j]%a[i] 可以得到较小的数字(大的模数也就是较小的数字)。2n次提问的机会一定能得到最终排列。
#include <bits/stdc++.h>
using namespace std;
typedef long long ll ;
const int maxN = 10004;
int read() {
int x = 0, f = 1; char ch = getchar();
while(ch < '0' || ch > '9') {
if(ch == '-') f = -f; ch = getchar(); }
while(ch >= '0' && ch <= '9') {
x = x * 10 + ch - '0'; ch = getchar(); }
return x * f;
}
int n, ans[maxN], id[maxN], cnt;
bool vis[maxN];
void init() {
for(int i = 0; i <= n; ++ i ) {
ans[i] = -1;
vis[i] = false;
}
}
void update() {
cnt = 0;
for(int i = 1; i <= n; ++i ) {
if(ans[i] == -1) {
id[cnt ++ ] = i;
}
}
}
int main() {
n = read(); init(); update();
while(cnt > 1) {
for(int i = 0; i + 1 < cnt; i += 2 ) {
//cnt次
int x, y;
cout << "? " << id[i] << ' ' << id[i + 1] << endl;
fflush(stdout);
cin >> x; //a[id[i]] % a[id[i + 1]]
cout << "? " << id[i + 1] << ' ' << id[i] << endl;
fflush(stdout);
cin >> y; //a[id[i + 1]] % a[id[i]]
if(x > y) {
//a[id[i]]小
ans[id[i]] = x;
vis[x] = true;
} else {
ans[id[i + 1]] = y;
vis[y] = true;
}
}
update();
}
int lst = 0;
for(int i = 1; i <=n; ++ i) {
if(!vis[i]) lst = i;
}
cout << "! ";
for(int i = 1; i <= n; ++ i ) {
cout << (ans[i] == -1 ? lst : ans[i]) << ' ';
}
cout << endl;
return 0;
}