【开源社区openEuler实践】 E. Binary Search

这篇文章描述了一个使用C++编写的程序,解决了一个涉及二分查找的题目,当给定数组中存在目标值x时,可能需要交换x与其他元素的位置,以优化某种条件。提供了两种可能的解决方案。

题目

#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;
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

__night_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值