求助帖,召唤神犇(from一个将快读搞成慢读的人的求助)

P2249 【深基13.例1】查找

Megumimwf @ 2023-01-16 09:50:18

#include<bits/stdc++.h>
using namespace std;
int n, m, a[1000086], q, l, r, mid, ans;
int read() {
    int x=0, f=1;
    char ch=getchar();
    while(ch<'0' || ch >'9') {
        if(ch == '-') {
            f = -1;
            ch = getchar();
        }
    }
    while(ch >= '0' && ch <= '9') {
        x = x * 10 + ch - 48;
        ch = getchar();
    }
    return x * f;
}
int main() {
    n = read();
    m = read();
    for(int i=1; i<=n; ++i) {
        a[i] = read();
    }
    while(m--) {
        q = read();
        l=1;
        r=n;
        ans = -1;
        while(l<r) {
            mid = (l + r)>>1;
            if(q > a[mid]) {
                l = mid + 1;
            } else {
                r = mid;
            }
        }
        if(a[l] == q) {
            ans = l;
        }
        printf("%d ", ans);
    }
    return 0;
}

一整个TLE住了,感觉代码没多大问题,求助帮忙debug一下


by AndyPomeloMars @ 2023-01-16 10:00:37

@LYH6123 你的ch=getchar放错位置了


by 初雪_matt @ 2023-01-16 10:00:57

@LYH6123

if(ch == '-') {
    f = -1;
    ch = getchar();
}

改成

if(ch == '-') {
    f = -1;
}
ch = getchar();

by AndyPomeloMars @ 2023-01-16 10:01:16

@LYH6123 应该这样:

#include<bits/stdc++.h>
using namespace std;
int n, m, a[1000086], q, l, r, mid, ans;
int read() {
    int x=0, f=1;
    char ch=getchar();
    while(ch<'0' || ch >'9') {
        if(ch == '-') {
            f = -1;
        }
        ch = getchar();
    }
    while(ch >= '0' && ch <= '9') {
        x = x * 10 + ch - 48;
        ch = getchar();
    }
    return x * f;
}
int main() {
    n = read();
    m = read();
    for(int i=1; i<=n; ++i) {
        a[i] = read();
    }
    while(m--) {
        q = read();
        l=1;
        r=n;
        ans = -1;
        while(l<r) {
            mid = (l + r)>>1;
            if(q > a[mid]) {
                l = mid + 1;
            } else {
                r = mid;
            }
        }
        if(a[l] == q) {
            ans = l;
        }
        printf("%d ", ans);
    }
    return 0;
}

by Megumimwf @ 2023-01-16 10:26:25

谢谢神犇们


|