更快的输入和输出 [英] Faster input and output

查看:92
本文介绍了更快的输入和输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<iostream>
using namespace std;
int main(){
    int i,x,max=0;
    cin>>x;
    int a[x];
    for(i=0;i<x;i++){
        cin>>a[i];
        if(max<a[i]){
            max=a[i];}                 
        }
        int b[max+1];
        for(i=0;i<max+1;i++){
            b[i]=-1;
        }
        for(i=0;i<x;i++){
            if(b[a[i]]==-1){
            b[a[i]]=1;
        }
        else{
            b[a[i]]++;
        }
    }
    i=0;
    while(i<=max){
        while(b[i]>0&&b[i]!=-1){
            cout<<i<<endl;
            b[i]--;
        }
        i++;
    }
    return 0;
}

我试过索引方法排序和codechef显示tle ..问题不是o(n),但更接近...问题的时间限制为5秒,源限制为50000字节..

Guys I tried indexing method for sorting and codechef shows tle .. complexity of this problem is not o(n) but closer to it ... the question has a time limit of 5 sec and source limit is 50000 bytes..

任何帮助通过更快的i / o或代码计算来提高性能...

Any help on how to improve the performance either by faster i/o or code computations ...

推荐答案

我很确定你的代码有问题因为你使用 cout<< x < endl; 在一个循环中,将打印大量的行。

I'm pretty certain your code is problematic because you are using cout << x << endl; in a loop that will print a huge number of lines.

我会在几分钟后回到差异化。

I will be back with "difference" in a few minutes.

编辑:不确定我可以做出很多不同的方式。显然,根据编译器,它可能有很大的变化,但是对于我的g ++ -O2和100000输入数字,需要0.16 - 0.18s使用 endl; 和0.06 - 0.07s

Not sure I can make much of a difference either way. Obviously, depending on compiler, it may vary greatly, but with my g++ -O2 and 100000 input numbers, it takes 0.16 - 0.18s to use endl; and 0.06 - 0.07s to use '\n' for the output.

使用 printf 不比 cout 快,但 scanf cin (0.04s +/- 0.05)。

Using printf isn't faster than cout, but scanf is a little faster than cin (0.04s +/- 0.05).

但是,这真的与 sync_with_stdio 有关。如果我们使用 cin.sync_with_stdio(false); ,则结果与 scanf cin

However, that is really related to sync_with_stdio. If we use cin.sync_with_stdio(false); then the results are the same for scanf and cin.

所有测量都是以文件作为输入,文件作为输出 - 但是这是因为它滚动100k行的文本超过我。

All measurements are made with a file as input and a file as output - it takes much longer to write to the shell, but that's because it's scrolling 100k lines of text past me.

(您的程序将与eithr大输入或大量输入一起崩溃 - 如果 max 超过大约1百万,代码将崩溃由于堆栈 - 在许多系统,这可能发生较低的值太)。

(Your program will crash with eithr "large" inputs or with large number of inputs - if max is greater than about 1 million, the code will crash due to out of stack - on many systems, that may happen for lower values too)

这篇关于更快的输入和输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆