0

I was trying to make a bfs problem for an hour it always jump on time, getting me 2.2 sec on every method I used.

When I watched on the official source he used scanf and printf, so I changed fin and fout with scanf and printf and the time goes around 1.3 sec. After that I changed just fin with scanf( using scanf to read and fout to print) and the time surprisingly goes at 1.1.

So, I wonder which is the best in which situation, reading and printing.

Code:

#include <iostream>
#include <cstdio>
#include <vector>
#include <queue>
#include <fstream>

#define nMax 100003

using namespace std;

ifstream fin("bfs.in");
ofstream fout("bfs.out");

int main(){
    freopen("bfs.in", "r", stdin);
    freopen("bfs.out", "w", stdout);
    int n, m, start, now, x, y, cost[nMax];
    vector < int > v[nMax];
    queue < int > q;
    scanf("%d %d %d ", &n, &m, &start);
 //   fin>>n>>m>>start;
    for(int i = 1; i <= m; i++){
        scanf("%d %d ", &x, &y);
//        fin>>x>>y;
        v[x].push_back(y);
    }
    for(int i = 1; i <= n; i++){
        cost[i] = -1;
    }
    cost[start] = 0;
    q.push(start);
    while(!q.empty()){
        now = q.front();
        for(auto x : v[now]){
            if(cost[x] == -1){
                q.push(x);
                cost[x] = cost[now] + 1;
            }
        }
        q.pop();
    }
    for(int i = 1; i <=n ; i++){
        printf("%d ", cost[i]);
//        fout<<cost[i]<<" ";
    }
    fin.close();
    fout.close();
    return 0;
}

input for this: Input

Jason Aller
  • 3,391
  • 28
  • 37
  • 36
  • Very related, possibly a duplicate: https://stackoverflow.com/q/18688763/1896169 – Justin Jun 03 '17 at 19:12
  • 1
    Please only tag with either C or C++. They're quite different languages these days. – tambre Jun 03 '17 at 19:13
  • What is the size of your input? Post an example input file. – n. 'pronouns' m. Jun 03 '17 at 19:25
  • THis is system and library dependent. On windows the stream inserters and extractors are slower than their FILE* counterpart. On Linux, the figures are almost the same. – Christophe Jun 03 '17 at 20:53
  • Use binary mode to get better speed. – zdf Jun 03 '17 at 21:45
  • See this [link](https://stackoverflow.com/questions/34745078/improve-performance-of-accessing-elements-in-a-map-and-writing-to-a-file). – zdf Jun 03 '17 at 21:52
  • Your program segfaults on startup on my system.because of stack overflow in `main`. When I move `vector < int > v[nMax];` out of main, the iostreams version is actually faster than the stdio version (about 0.77 and 0.97 seconds respectively). Make sure you are compiling in release mode. – n. 'pronouns' m. Jun 04 '17 at 07:08
  • The above results are for the gcc compiler; Visual C++ produces much slower code. You should complain to Microsoft. – n. 'pronouns' m. Jun 04 '17 at 07:14

0 Answers0