这是一道可癌的思维题目。
感谢 Na1L0n9 提供了 ,虽然其他题解中有,但是还是感谢他的思路。
前置知识
思路
考虑令 表示 到 的答案, 为排列,那么 。为什么呢?因为 就是 到 中有多少比 大的数,加上 ,那么还剩下 没有加上。
我们整理一下式子,变成 ,因为 肯定等于 或 ,所以对 取余没有影响。
我们令 表示 对 取模后的答案,也就是可以向交互库询问的东西,那么式子就变成了 。
所以我们就可以快速确定两个式子大小关系了,那么我们不妨将每个数都二分加入 vector 中,那么这个 vector 就表示每个 代表的 从小到大排序后的结果。
因为每次确定大小需要 次,而每次插入需要 的比较,所以询问次数是 的,因为 ,所以大概是 ,刚好通过。
Code
#include<bits/stdc++.h>
#define N 1005
using namespace std;
int n = 1000,ans[N];
vector<int> v;
bool check(int i,int j){
if(i + 1 == j){
int f;
cout << "? " << i << " " << j << endl;
cin >> f;
return f == 1;
}
int f1,f2,f3,f4;
cout << "? " << i << " " << j << endl;
cin >> f1;
cout << "? " << i << " " << j - 1 << endl;
cin >> f2;
cout << "? " << i + 1 << " " << j << endl;
cin >> f3;
cout << "? " << i + 1 << " " << j - 1 << endl;
cin >> f4;
return (f1 - f2 - f3 + f4 + 2) & 1;
}
int main(){
v.push_back(1);
for(int i = 2;i <= n;i ++){
int l = 0,r = i - 2,mid,ans = -1;
while(l <= r){
mid = (l + r) >> 1;
if(check(v[mid],i) == true){
r = mid - 1;
}else{
ans = mid;
l = mid + 1;
}
}
v.insert(v.begin() + (ans + 1),i);
}
for(int i = 0;i < n;i ++){
ans[v[i]] = i + 1;
}
cout << "! ";
for(int i = 1;i <= n;i ++){
cout << ans[i] << " ";
}
cout << endl;
return 0;
}