卡常小祭巧
zhanghuanwen · · 个人记录
此文为
接上回,本文介绍如何卡常。
快速读入
以 P10815 为例。
一看题,水题啊!于是打出了代码:
#include <bits/stdc++.h>
using namespace std;
int main() {
int ans = 0;
int n, a;
cin >> n;
while (n--) cin >> a, ans += a;
cout << ans << '\n';
return 0;
}
TLE 了。考虑优化。
我们注意到 cin 是很慢的读入方式,所以使用 ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); 优化(TLE)或使用 scanf 和 printf(TLE)。注意千万不可以混用,会有一些玄学的错误(不兼容)。
这时候还是 TLE,我们尝试写快读提升速度。
int readint(){
int f = 1, ans = 0;
char ch = getchar();
while (!isdigit(ch)){
if (ch == '-') f = -1;
ch = getchar();
}
while (isdigit(ch)){
ans = (ans << 3) + (ans << 1) + (ch ^ 48);
ch = getchar();
}
return ans * f;
}
但是依然 TLE。
有一个小优化:在 Linux 评测机上使用 getchar_unlocked() 而不是 getchar()(在 Windows 上可以使用 _getchar_nolock()),可以快不少。这样可以 AC 2.18s。
既然要卡常就要卡到底,我们做这道题是为了学习卡常技巧的。
我们来学习一下 fread() 函数。它的语法是这样的:
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
函数 fread 会从 stream 流中读取 nmemb 个长度为 size 字节大小的数据,并将它们存储在 ptr 给定的位置,返回读取的字节数。
那么,我们可以写出另一个快读:
char buf[1 << 20], *p1, *p2;
char Getc() {
if (p1 == p2) {
p1 = buf;
p2 = buf + fread(buf, sizeof (char), sizeof (buf) / sizeof (char), stdin);
// 也可以写成:
// p2 = buf + fread(buf, 1, 1 << 20, stdin);
if (p1 == p2) return EOF;
}
return *p1++;
}
int readint(){
int f = 1, ans = 0;
char ch = Getc();
while (!isdigit(ch)){
if (ch == '-') f = -1;
ch = Getc();
}
while (isdigit(ch)){
ans = (ans << 3) + (ans << 1) + (ch ^ 48);
ch = Getc();
}
return ans * f;
}
当然,这样函数开销太大了,会 TLE。所以我们使用宏定义的方法:
char buf[1 << 20], *p1, *p2;
#define Getc() (p1 == p2 && (p2 = (p1 = buf) + fread(buf, sizeof (char), sizeof (buf) / sizeof (char), stdin)), *p1++)
int readint(){
int f = 1, ans = 0;
char ch = Getc();
while (!isdigit(ch)){
if (ch == '-') f = -1;
ch = Getc();
}
while (isdigit(ch)){
ans = (ans << 3) + (ans << 1) + (ch ^ 48);
ch = Getc();
}
return ans * f;
}
AC 1.62s。
mmap 不讲。