1. 程式人生 > >PAT-B-1040

PAT-B-1040

-- art ase base mat scripts bottom 循環 nbsp

1040 有幾個PAT(25 分)

字符串 APPAPT 中包含了兩個單詞 PAT,其中第一個 PAT 是第 2 位(P),第 4 位(A),第 6 位(T);第二個 PAT 是第 3 位(P),第 4 位(A),第 6 位(T)。

現給定字符串,問一共可以形成多少個 PAT

輸入格式:

輸入只有一行,包含一個字符串,長度不超過10?5??,只包含 PAT 三種字母。

輸出格式:

在一行中輸出給定字符串中包含多少個 PAT。由於結果可能比較大,只輸出對 1000000007 取余數的結果。

輸入樣例:

APPAPT

輸出樣例:

2

思路:

首先暴力破解沒錯,但O(n^3)的時間復雜度不能接受。

求PAT個數,可以分析為找A的位置,找到A之後看A前面有幾個P(count_P),再看A後面有幾個T(count_T),該位置的A參與的有效“PAT”個數即:count_P * count_T,循環找A,並計算結果,最後求余。

可以先使用循環計算從0到當前位置有多少P,從len-1到當前位置有多少T,然後在找A的循環找就可以在O(1)下得到當前位置之前的P的個數、之後T的個數。

時間復雜度:O(3N),空間復雜度O(3N)。

卡在測試項4沒能過,問題見36行備註。

 1 #include <stdio.h>
 2 #include <string.h>
 3 
 4 #define MAXSIZE 1000000007
 5 
 6 typedef long ElementType;
 7 
 8 int main(void){
 9   int i, A_Index=0;
10   ElementType count=0
; 11 char str[100001]; 12 13 gets(str); 14 int len = strlen(str); 15 int Count_T[len], Count_P[len], A_Pos[len]; 16 17 Count_P[0] = str[0] == P? 1 : 0; 18 Count_T[len-1] = str[len-1] == T? 1 : 0; 19 for( i=1; i<len; i++) 20 if( str[i] == P ) 21 Count_P[i] = Count_P[i-1
]+1; 22 else{ 23 Count_P[i] = Count_P[i-1]; 24 if( str[i] == A ) 25 A_Pos[A_Index++] = i; 26 } 27 28 for( i=len-2; i>=0; i--) 29 if( str[i] == T ) 30 Count_T[i] = Count_T[i+1]+1; 31 else 32 Count_T[i] = Count_T[i+1]; 33 34 for( i=0; i<A_Index; i++){ 35 count += Count_P[A_Pos[i]] * Count_T[A_Pos[i]]; 36 count %= MAXSIZE; //這裏有個坑:對n取余不等於 減去k個n 37 } 38 39 printf("%ld", count); 40 41 return 0; 42 }

看到一個更加簡明的方法,整體復雜度還是O(2n), 大約少了一個O(N)的時間, 且代碼更短,占用空間O(1)。參考出處

 1 #include <stdio.h>
 2 #include <string.h>
 3 
 4 #define MAXSIZE 1000000007
 5 
 6 typedef long ElementType;
 7 
 8 int main(void){
 9   int i, count_P=0, count_A=0, count_T=0;
10   ElementType count=0;
11   char str[100001];
12   
13   gets(str);
14   
15   for( i=0; str[i]; ++i)
16     if( str[i] == T )
17       count_T++;
18   
19   for( i=0; str[i]; ++i){
20     if( str[i] == P )
21       count_P++;
22     else if( str[i] == T)
23       count_T--;
24     else if( str[i] == A )
25       count = ( count+ (count_P*count_T) % MAXSIZE ) % MAXSIZE;
26   }
27   
28   printf("%ld", count);
29   
30   return 0;
31 }

PAT-B-1040