使用iostream进行读取和打印时间翻倍

时间:2017-06-03 19:06:50

标签: c++

我想要在一小时内制作一个bfs问题,它总是按时跳起来,让我每次使用的方法都要2.2秒。 当我观察他的使用scanf和printf时,我用scanf和printf改变了fin和fout,时间大约是1.3秒。之后我用scanf改变了fin(使用scanf读取和fout打印),时间惊人的是1.1。 所以,我想知道这是最好的,阅读和印刷。

代码:

#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

0 个答案:

没有答案
相关问题