In Bubble Cup 14, I used std::cin
on problem G. Shortest Path and got TLE. See my submission 131334076. Note that I used std::ios_base::sync_with_stdio(false)
and std::cin.tie(nullptr)
to accelerate it, but it still got TLE. However, I simply changed it to std::scanf
and got AC, with an execution time of 342ms. See my submission 131336297.
I tested the efficiency on my computer, but it only took me around 200ms to read $$$10^6$$$ double variables. My computer is Intel i7 8565U. My compiler is gcc version 9.3.0 (Ubuntu 9.3.0-17ubuntu1~20.04) with -O2
. I will show my code and generator below.
My Code:
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
template <typename T>
void checkmax(T &x, T y) {
if (x < y) x = y;
}
template <typename T>
void checkmin(T &x, T y) {
if (x > y) x = y;
}
int n;
double a[1000001];
int main(int argc, char const *argv[]) {
std::ios_base::sync_with_stdio(false);
std::cin.tie(nullptr), std::cout.tie(nullptr);
std::cin >> n;
for (int i = 1; i <= n; i++) std::cin >> a[i];
// std::scanf("%d", &n);
// for (int i = 1; i <= n; i++) std::scanf("%lf", &a[i]);
return 0;
}
My generator:
#include <bits/stdc++.h>
std::mt19937 rng(
std::chrono::_V2::steady_clock::now().time_since_epoch().count());
template <typename T>
T Rand(T l, T r) {
return std::uniform_real_distribution<T>(l, r)(rng);
}
int n = 1000000;
int main(int argc, char const *argv[]) {
std::ofstream fout("data.in");
fout.precision(6);
fout << n << '\n';
fout << std::fixed;
for (int i = 1; i <= n; i++) fout << Rand(-1e6, 1e6) << " \n"[i == n];
return 0;
}
Can anyone explain it?
stod might help?
It works, thanks!!
Actually reading string and using
std::stod
is much faster thanstd::scanf
. But I still wanna know why usingstd::cin
to process float points is slow... Could anyone explain it?Can I ask Mike here?