快读

· · 算法·理论

事实 1: 基于下面代码的普通快读在 P10815 中获得了超时的好成绩。

inline 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-'0',ch=getchar();
    return x*f;
}

事实 2: 将上述代码中的 getchar 改为 getchar_unlocked,在 P10815 中获得了 1.93s 的好成绩。

事实 3: 下列代码中的 getline 读入 string 的快读获得了 2.29s 的好成绩。缺点是占用空间较大,使用了 1GB 空间。

int n;
string s;
int pos;
inline int read(){
    int x=0,f=1; char ch = s[pos++];
    while(ch<'0' || ch>'9')if(ch=='-')f=-1,ch=s[pos++];
    while(ch>='0' && ch<='9')x=x*10+ch-'0',ch=s[pos++];
    return x*f;
}
int main(){
    F_sync;
    cin>>n;
    getline(cin,s);
    getline(cin,s);
    s+=" ";
    int ret = 0;
    while(n--)ret+=read();
    cout<<ret;
    return 0;
}

总结:在行数极少的情况下,使用 getline 实现快读,比 getchar 快。

用处: