跳到正文

算法·理论

《卡常》

用户 739299约 2 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 2 分钟
获赞
2

版本

  1. v1当前

总所周知,一个卡过常的程序首先需要优化读入输出:

C++
inline int read()
{
	register char in = getchar(),f = 0; register int t = 0;
	for(;in < '0' || in > '9';in = getchar())if(!(in ^ 45))f = 1;
	for(;in >= '0' && in <= '9';in = getchar())
	 t = (t << 1) + (t << 3) + (in ^ 48);
	return f ? -t : t;
}
inline void write(register int x)
{
	static int t[99];register int tp = 0;
	if(x == 0) return (void) (fputs("0\n",stdout));
	else if(x < 0) putchar('-'),x = -x;
	while(x) t[tp++] = x % 10,x /= 10;
	while(tp--) putchar(t[tp] + 48);
	fputs("\n",stdout);//fputs会更快一些
}

当然,也可以这样

C++
setvbuf(stdin,(char*)calloc(1 << 20,sizeof(char)),_IOFBF,1 << 20);
setvbuf(stdout,(char*)calloc(1 << 20,sizeof(char)),_IOFBF,1 << 20);

位运算也是必不可少的,所以你可以把amod  ba\mod b换成a & (b - 1),把a×2a\times 2换成a<<1a << 1等。
还有就是对ifif的优化:

1

用switch判断操作之类的。

C++
switch (o)
{
	case 1 : { write(find(read(),read())); break; }
	case 2 : { amend(read(),read()); break; }
	case 3 : { change(read(),read()); break; }
}

2

用三目运算符。

C++
return f ? -t : t;

还有,少用STL!!!尽量手写(加油吧年轻人)。 最后,还是多写正解少卡常吧。。。毕竟可能卡不过QwQ。

原文