,可能是最简单的问题。输入由一系列≤ 2^32 的无符号整数对组成(因此要求使用 64 位整数……)对于每一对,任务是打印出较大整数和较小整数之间的差异。
根据,最快的解决方案运行时间低于 0.01 秒。然而,我解决这个问题的所有尝试通常都在 0.02 秒内完成,随机偏差可能为 ± 0.01 秒。
I tried:
#include <cstdint>
#include <iostream>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
uint_fast64_t i, j;
while(cin >> i >> j) {
if(i > j)
cout << i-j << '\n';
else
cout << j-i << '\n';
}
}
并且:
#include <cstdlib>
#include <cstdint>
#include <iostream>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int_fast64_t i, j;
while(cin >> i >> j) {
cout << abs(i-j) << '\n';
}
}
并且:
#include <algorithm>
#include <cstdint>
#include <iostream>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
uint_fast64_t i, j;
while(cin >> i >> j) {
cout << max(i,j)-min(i,j) << '\n';
}
}
全部结果相同。
我也尝试过使用printf()
/scanf()
代替cin/cout
,仍然具有相同的结果(此外,我的基准测试表明cin/cout
之前是cin.tie(nullptr)
甚至可以比printf()/scanf()
– 至少除非有一些方法来优化性能cstdio
我不知道)。
有什么方法可以将其优化到 0.01 秒以下,或者我应该假设这次实现的人要么非常幸运,要么作弊者打印出针对法官输入的预先计算的答案?
这些程序是用C++11 5.3.0 - GNU C++ Compiler with options: -lm -lcrypt -O2 -std=c++11 -pipe -DONLINE_JUDGE
.
编辑:这是我尝试结合@Sorin 和@MSalters 的建议:
#include <stdio.h>
#include <stdint.h>
unsigned long long divisors[] = {
1000000000,
1000000000,
1000000000,
1000000000,
100000000,
100000000,
100000000,
10000000,
10000000,
10000000,
1000000,
1000000,
1000000,
1000000,
100000,
100000,
100000,
10000,
10000,
10000,
1000,
1000,
1000,
1000,
100,
100,
100,
10,
10,
10,
1,
1,
1
};
int main()
{
unsigned long long int i, j, res;
unsigned char inbuff[2500000]; /* To be certain there's no overflow here */
unsigned char *in = inbuff;
char outbuff[2500000]; /* To be certain there's no overflow here */
char *out = outbuff;
int c = 0;
while(1) {
i = j = 0;
inbuff[fread(inbuff, 1, 2500000, stdin)] = '\0';
/* Skip whitespace before first number and check if end of input */
do {
c = *(in++);
} while(c != '\0' && !(c >= '0' && c <= '9'));
/* If end of input, print answer and return */
if(c == '\0') {
*(--out) = '\0';
puts(outbuff);
return 0;
}
/* Read first integer */
do {
i = 10 * i + (c - '0');
c = *(in++);
} while(c >= '0' && c <= '9');
/* Skip whitespace between first and second integer */
do {
c = *(in++);
} while(!(c >= '0' && c <= '9'));
/* Read second integer */
do {
j = 10 * j + (c - '0');
c = *(in++);
} while(c >= '0' && c <= '9');
if(i > j)
res = i-j;
else
res = j-i;
/* Buffer answer */
if(res == 0) {
*(out++) = '0';
} else {
unsigned long long divisor = divisors[__builtin_clzll(res)-31];
/* Skip trailing 0 */
if(res < divisor) {
divisor /= 10;
}
/* Buffer digits */
while(divisor != 0) {
unsigned long long digit = res / divisor;
*(out++) = digit + '0';
res -= divisor * digit;
divisor /= 10;
}
}
*(out++) = '\n';
}
}
还有0.02秒。