From:http://www.cnblogs.com/killerlegend/p/3918452.html
Author:KillerLegend
Date:2014.8.17
杭电OJ之3233很简单的一个问题,谁知道一直提示我超时,超时,最后都快哭了,C++代码如下:
#include <iostream> #include <iomanip> using namespace std; int main() { int t,tmp,band,index=0; while(cin>>t>>tmp>>band) { if(t==0||tmp==0||band==0) break; double a,b,sum=0.0; for(int i=0;i<t;++i) { cin>>a>>b; sum+=a*(100-b)*0.01; } cout<<"Case "<<++index<<": "<<fixed<<setprecision(2)<<sum/band<<endl<<endl; } return 0; }
#include <cstdio> int main() { int t,tmp,band,index=0; while(scanf("%d%d%d",&t,&tmp,&band)) { if(t==0||tmp==0||band==0) break; double a,b,sum=0.0; for(int i=0;i<t;++i) { scanf("%lf%lf",&a,&b); sum+=a*(100-b)*0.01; } printf("Case %d: %.2f ",++index,sum/band); } return 0; }
cout测试:
#include <iostream> #include <cstdio> #include <time.h> using namespace std; int main() { freopen("in.conf","r",stdin); freopen("out.conf","w",stdout); clock_t t1,t2,t3,t4; t1 = clock(); for(int i=0;i<10000000;++i)cout<<i<<" "; t2 = clock(); cout<<"cin-time:"<<(double)(t2-t1)/CLOCKS_PER_SEC<<endl; return 0; }
printf测试:
#include <iostream> #include <cstdio> #include <time.h> using namespace std; int main() { freopen("in.conf","r",stdin); freopen("out.conf","w",stdout); clock_t t1,t2,t3,t4; t1 = clock(); for(int i=0;i<10000000;++i)printf("%d ",i); t2 = clock(); cout<<"cin-time:"<<(double)(t2-t1)/CLOCKS_PER_SEC<<endl; return 0; }
我们使用上面循环1千万次所产生的数据(78.89MB),用于下面读入时的测试数据:
使用cin读入:
#include <iostream> #include <cstdio> #include <time.h> using namespace std; int main() { freopen("out.conf","r",stdin); freopen("in.conf","w",stdout); clock_t t1,t2,t3,t4; t1 = clock(); int k; for(int i=0;i<10000000;++i)cin>>k; t2 = clock(); cout<<"cin-time:"<<(double)(t2-t1)/CLOCKS_PER_SEC<<endl; return 0; }
使用scanf读入:
#include <iostream> #include <cstdio> #include <time.h> using namespace std; int main() { freopen("out.conf","r",stdin); freopen("in.conf","w",stdout); clock_t t1,t2,t3,t4; t1 = clock(); int k; for(int i=0;i<10000000;++i)scanf("%d",&k); t2 = clock(); cout<<"cin-time:"<<(double)(t2-t1)/CLOCKS_PER_SEC<<endl; return 0; }
结果一览表:
结论:输出时尽量使用cout,输入时尽量使用scanf.