本文主要是介绍div3 E. Binary Search,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define pb push_back
#define fi first
#define se second
#define lson p << 1
#define rson p << 1 | 1
const int maxn = 2e5 + 5, inf = 1e18, maxm = 4e4 + 5, base = 397;
const int mod = 1e9 + 7;
// const int mod = 998244353;
// const __int128 mod = 212370440130137957LL;
const int N = 1e5;
// int a[1005][1005];
int a[maxn], b[maxn];
bool vis[maxn];
int n, m;
string s;struct Node{// int val, id;// bool operator<(const Node &u)const{// return val < u.val;// }
}c[maxn];void solve(){int res = 0;int q;int x;// cin >> n;cin >> n >> x;int pos;for(int i = 1; i <= n; i++){vis[i] = 0;}for(int i = 1; i <= n; i++){cin >> a[i];if(a[i] == x){pos = i;}}int l = 1, r = n + 1;while(r - l > 1){int mid = (l + r) >> 1;vis[mid] = 1;if(a[mid] <= x){l = mid;}else{r = mid;}}if(a[l] == x){//正常二分,最好恰好找到x,就不用交换cout << 0 << '\n';return;}if(!vis[pos]){//二分过程没有访问到x,直接把x与最后的找到的元素a[l]交换,交换后二分过程访问的元素除了最后找到的元素,其他不会变cout << 1 << '\n';cout << pos << ' ' << l << '\n';}else{// cout << 2 << '\n';vector<pair<int, int>> ans;ans.pb({pos, l});//先把x与a[l]交换,如果a[l] <= x,那么二分过程不变,只交换一次,否则:法一:找到一个未被访问的小于等于x的元素//法二:如果再进行一次二分,再把x与最后的找到的元素a[l]交换(这次二分肯定不会访问到x)if(a[l] > x){for(int i = 1; i <= n; i++){if(!vis[i] && a[i] <= x){ans.pb({i, l});break;}}}cout << ans.size() << '\n';for(auto [x, y] : ans){cout << x << ' ' << y << '\n';}}
} signed main(){ios::sync_with_stdio(0);cin.tie(0);int T = 1;cin >> T;while (T--){solve();}return 0;
}
这篇关于div3 E. Binary Search的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!