计蒜客 网页跳转解决cincout超时问题

mac2025-12-15  7

在刷题的时候,经常会遇到超时的问题。算法没问题,将cin cout 换成 scanf printf 便AC了, 

那 cin cout 与scanf printf 到底熟快熟慢??

我看了这篇文章后豁然开朗,推荐:C++的输入输出 cin/cout和scanf/printf谁比较快?

cin/cout 速度超越scanf/printf的方法:

大家习惯了C++ cin/cout 输入输出风格的,再换成C风格的输入输出比较烦,而且C中没有string类,对字符串的处理也很不友好。那怎么办呢??

方法来了!!

只需要在main函数的开始加上以下两行代码,即可实现提高输入输出的速度:(具体原理见上面的链接 )

      ios::sync_with_studio(0);

      cin.tie(0);

     2.所有的换行操作cout<<endl;统统换为'\n'   (大大的节约时间 haha)

 

 

注意点:

在加上ios::sync_with_studio(0);cin.tie(0);两行代码后,输入输出仅用cin/cout即可,不要一会cin一会scanf,如果再混用c风格的输入输出(scanf printf)会出错。

 

AC代码:

#include <iostream> #include<stack> #include<cstring> #include<bits/stdc++.h> using namespace std; stack<string> back; stack<string> go; int main() { ios::sync_with_stdio(false);//避免输入输出超时 cin.tie(0); int n; cin>>n; string str1,str2; for(int i=0;i<n;i++){ cin>>str1; if(str1=="VISIT"){ cin>>str2; back.push(str2); cout<<back.top()<<'\n'; while(!go.empty()){//每次打开新页面 清空 go go.pop(); } } if(str1=="BACK"){ if(back.empty()){ cout<<"Ignore\n"; } else{ go.push(back.top()); back.pop(); if(back.empty()){ cout<<"Ignore\n"; back.push(go.top()); go.pop(); } else{ cout<<back.top()<<'\n'; } } } if(str1=="FORWARD"){ if(go.empty()){ cout<<"Ignore\n"; } else{ cout<<go.top()<<'\n'; back.push(go.top()); go.pop(); } } } return 0; }

 

最新回复(0)