用于竞争编程的快速I/O

在竞争性编程中,尽可能快地读取输入非常重要,这样可以节省宝贵的时间。

null

你一定见过各种各样的问题陈述: 警告: 大型I/O数据,使用某些语言时要小心(尽管如果算法设计良好,大多数语言应该是可以的)” .解决此类问题的关键是使用更快的I/O技术。

通常建议使用scanf/printf而不是cin/cout来快速输入和输出。但是,通过在main()函数中包含以下两行,您仍然可以使用cin/cout,并实现与scanf/printf相同的速度:

    ios_base::sync_with_stdio(false);

如果程序执行第一次输入或输出操作之前调用它,则它会切换或关闭所有C++标准流的同步与相应的标准C流。添加ios_base::sync_with_stdio(false);(默认情况下为true)在任何I/O操作避免此同步之前。它是std::ios_base函数的静态成员。

    cin.tie(NULL);

tie()是一种方法,它只保证在std::cin接受输入之前刷新std::cout。这对于需要不断更新控制台的交互式控制台程序非常有用,但对于大型I/O,这也会降低程序的速度。空部分只返回空指针。

此外,您还可以将标准模板库(STL)包含在一个包含中:

    #include <bits/stdc++.h>

因此,竞争性编程的模板可以如下所示:

#include <bits/stdc++.h>using namespace std;int main(){    ios_base::sync_with_stdio(false);    cin.tie(NULL);    return 0;}

建议使用cout< 这 详细信息)。(比如说,如果你在写一个交互式进度条,就需要刷新,但在写一百万行数据时就不需要刷新。)写下而不是endl。

我们可以在这个问题上测试我们的输入和输出方法 INTEST–对SPOJ的大量输入测试。 在进一步阅读之前,我建议你先解决这个问题。 C++ 4.92中的解决方案

正常I/O: 下面的代码使用cin和cout。该解决方案的运行时间为2.17秒。

C++

// A normal IO example code
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n, k, t;
int cnt = 0;
cin >> n >> k;
for ( int i=0; i<n; i++)
{
cin >> t;
if (t % k == 0)
cnt++;
}
cout << cnt << "" ;
return 0;
}


快速I/O 然而,通过添加两行代码,我们可以做得更好,并大大减少运行时间。下面的程序以0.41秒的运行时间被接受。

C++

// A fast IO program
#include <bits/stdc++.h>
using namespace std;
int main()
{
// added the two lines below
ios_base::sync_with_stdio( false );
cin.tie(NULL);
int n, k, t;
int cnt = 0;
cin >> n >> k;
for ( int i=0; i<n; i++)
{
cin >> t;
if (t % k == 0)
cnt++;
}
cout << cnt << "" ;
return 0;
}


现在,说到竞争性比赛,比如ACM ICPC、Google CodeJam、TopCoder Open,这里有一个以最快的方式读取整数的专用代码。

C++

void fastscan( int &number)
{
//variable to indicate sign of input number
bool negative = false ;
register int c;
number = 0;
// extract current character from buffer
c = getchar ();
if (c== '-' )
{
// number is negative
negative = true ;
// extract the next character from the buffer
c = getchar ();
}
// Keep on extracting characters if they are integers
// i.e ASCII Value lies from '0'(48) to '9' (57)
for (; (c>47 && c<58); c= getchar ())
number = number *10 + c - 48;
// if scanned input has a negative sign, negate the
// value of the input number
if (negative)
number *= -1;
}
// Function Call
int main()
{
int number;
fastscan(number);
cout << number << "" ;
return 0;
}


getchar_unlocked()在C语言中提供更快的输入,从而实现竞争性编程

本文由 维尼·加格。 如果你喜欢GeekSforgeks,并且想贡献自己的力量,你也可以写一篇文章,然后把你的文章邮寄给评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写评论

© 版权声明
THE END
喜欢就支持一下吧
点赞9 分享