第一次提交,判我超時Out of Contest Time

題目:http://acm.zju.edu.cn/contests/show_problem.php?cid=154&pid=1003

被判超時的代碼:

#include<iostream>
#include<string> 
using namespace std;
int main()
{
 int count,i = 0,len,j;
 string S;
 cin>>S;
 count = S.length();

 for(len = count;i < len;i++)
 {
  j=1;
  while(S[i-j] == S[i+j] && S[i-j] != NULL && S[i+j] != NULL)
  {
   ++count;
   ++j;
  }
  j=1;   
  while(S[i-j+1] == S[i+j]&& S[i-j+1] != NULL && S[i+j] != NULL )
  {
   ++count;
   ++j;
  }
 }
 cout<<count;

 return 0;

反正都已經超時了,再修改代碼也不錯了的,呵呵,下面是部分優化過的代碼,還是沒有註釋,主要是對程序性能上的優化,在算法上還是老樣子,不過優化過的代碼通過彙編之後會少段尋找數組地址的代碼,在測試string非常大的情況下。能明顯使運行時間縮短

#include<iostream>
#include<string> 
using namespace std;
int main()
{
 int count,i = 0,len,j;
 string S;
 cin>>S;
 count = S.length();
 for(len = count;i < len;i++)
 {
  j=1;
  while(S[i-j] == S[i+j] && !(i-j <0 && i+j > len))      //被優化的地方
  {
   ++count;
   ++j;
  }
  j=1;
  while(S[i-j+1] == S[i+j] && !(i-j < -1 && i+j > len ))  //被優化的地方
  {
   ++count;
   ++j;
  }
 }
 cout<<count-1<<endl;
 system("pause");
 return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章