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,475
  • 28
  • 40
  • 37

0 Answers0