社区讨论

快读引发超时,求解释

学术版参与者 3已保存回复 7

讨论操作

快速查看讨论及其快照的属性,并进行相关操作。

当前回复
7 条
当前快照
1 份
快照标识符
@lo3ivtde
此快照首次捕获于
2023/10/24 07:22
2 年前
此快照最后确认于
2023/10/24 07:22
2 年前
查看原帖
这是P3383的代码,尝试努力优化所以用了快读。
快读改了几次,之前能A,从stdin换成cin的时候就变成TLE了。
CPP
#include<iostream>
#include<vector>
const int maxn = (int)1e8 + 1;
int ip, p[(int)5e7];
bool np[maxn];
using std::cin;
using std::cout;
using std::endl;
namespace SpeedUp {
    const int MS = 1 << 20;
    static char inbuf[MS], outbuf[MS];
    static char *ipos, *itail, *opos = outbuf, *otail = outbuf + MS;
    static std::streambuf *_ibuf(std::cin.rdbuf()),*_obuf(std::cout.rdbuf());
    #define gc() (ipos == itail && (itail = (ipos = inbuf) + _ibuf -> sgetn(inbuf,MS), ipos==itail)? EOF : *ipos++)
    #define isd(C) ((C & 48) == 48)
    #define isnd(C) ((C & 48) != 48)
    // 注意:48~63 都是0x3?,此函数仅过滤空格或换行
    
    inline int rd() {
        static int x;
        static bool neg;
        static char c;
        x = 0, neg = false;
        c = ' ';
        while (isnd(c)) if ((c = gc()) == '-') neg = true;
        while (isd(c)) x = (x << 3) + (x << 1) + (c ^ 48), c = gc();
        return neg?-x:x;
    }
    
    inline void flush(){_obuf->sputn(outbuf, otail - outbuf);}
    
    inline void push(const char &c) {
        opos == otail?_obuf->sputn(opos=outbuf,MS),*opos++=c:*opos++=c;
        // if (opos - outbuf == MS) flush();
        // *opos++ = c;
    }

    inline void write(int x) {
        static int sta[35];
        int top = 0;
        if(x<0){
            push('-');   
            x = -x;
        }
        do {
          sta[top++] = (x % 10) | 48, x /= 10;
        } while (x);
        while (top) push(sta[--top]);
    }
    
    class Starduster{
    public:
        Starduster(){}
        ~Starduster(){flush();}
    };
    Starduster starduster;
}

using SpeedUp::rd, SpeedUp::flush, SpeedUp::write, SpeedUp::push;
void calcP(){
    register int num = 2;
    int mh = maxn >> 1;
    int mul = 0, kp = 0, k = 0;
    for (num = 2; num < mh; num++){
        if (!np[num]) p[ip++] = num;
        for (k = 0; k < ip; k++){
            kp = p[k];
            mul = num * kp;
            if (mul < maxn) np[mul] = true;
            else break;
            if (num % kp == 0) break;
        }
    }
    for(; num < maxn; num++){
        if (!np[num]) p[ip++] = num;
    }
}
int main(){
    std::ios::sync_with_stdio(0);
    calcP();
    int n, q, l;
    n = rd(), q = rd();
    while (q--){
        l = rd();
        write(p[l - 1]);
        push('\n');
    }
    return 0;
}

回复

7 条回复,欢迎继续交流。

正在加载回复...