zoj 1151 Word Reversal-------------输入输出超时

来源:互联网 发布:网络暴力 编辑:程序博客网 时间:2024/06/04 19:13

程序意思不难,不过就是对于输入输出的问题。

一开始时候,使用的是cin cout,但是,注意超时!

 

================================引用说明分割线============================================

“超时有很多原因,有的是算法的问题,但是你的程序没算法问题。所以只能是另外的一种可能,就是输入输出的问题。

你使用的c++标准输入输出cin cout 还有标准字符串类string,这些都是c++的对象或类,在使用的时候都要建立对象,使用起来速度很慢。在对小规模的acm问题时不影响,但是对输入量非常大的时候,使用cin cout明显比scanf和printf要慢的多。
string也是比vector<char>慢,而vector<char>又比char[]慢。。。 ” 

================================引用说明分割线============================================

所以,什么直接把cin cout 改成scanf printf,超时问题就解决了...

另外值得注意的,还有对stack,string等的应用。好用,但也要注意超时的问题。

下面附上自己的代码以及网上找来的代码,人家用到了诸如char[],putchar getchar等...惭愧..

 

==================================又是我,华丽分割线======================================

#include <iostream>
#include <stack>
#include<stdio.h>
using namespace std;

int main()
{
 int n,m;
 char wordchar;
 stack<char> word;
 
 
 scanf("%d",&n);
 scanf("%c",&wordchar);
 for(int i=0;i<n;i++)
 {
  scanf("%c",&wordchar);
  scanf("%d",&m);
  scanf("%c",&wordchar);
  for(int j=0;j<m;j++) 
  {
   scanf("%c",&wordchar);
   while(wordchar!='\n')
   {
    if(wordchar!=' ') word.push(wordchar);
    else
    {
     while(!word.empty())
     {
      printf("%c",word.top());
      word.pop();
     }
     printf(" ");
    }
    scanf("%c",&wordchar);
   }
   while(!word.empty())
   {
    printf("%c",word.top());
    word.pop();
   }
   printf("\n");
  }
  if(i!=n-1) printf("\n");
 }
 return 0;
}

 

网上找来的代码:

  1. #include <stdio.h>   
  2. #include <string.h>   
  3. int i, lines;   
  4. int total, now;   
  5. char s[250];                   //用数组来代替!!我用stack,大工程!!
  6. char c;   
  7.   
  8. int main()   
  9. {   
  10. #ifdef ONLINE_JUDGE   
  11. #else   
  12.     freopen("1151.txt""r"stdin);   
  13. #endif   
  14.     scanf("%d"&total);   
  15.     for (now 0; now total; now++)   
  16.     {   
  17.         scanf("%d\n"&lines);//IMPORTANT plus \n   //这个要注意!!
  18.         while (lines-- >= 0)   
  19.         {   
  20.             0;   
  21.             while ((c getchar()) != EOF)            //getchar putchar等的应用
  22.             {   
  23.                 if (c == ' || == '\n')   
  24.                 {   
  25.                     while (i-- 0)   
  26.                         putchar(s[i]);   
  27.                     putchar(c);   
  28.                     if (c == '\n')   
  29.                         break;   
  30.                     0;   
  31.                 }   
  32.                 else  
  33.                 {   
  34.                     s[i++] c;   
  35.                 }   
  36.             }   
  37.         }   
  38.     }   
  39. #ifdef ONLINE_JUDGE   
  40. #else   
  41.     fclose(stdin);   
  42. #endif   
  43.     return 0;   
  44.  
原创粉丝点击