最長同號連續段 |
Time Limit: 1 Seconds Memory Limit: 32768 K Total Submit:447 Accepted:179 |
Description 給出一個由非0整數組成的序列a1,a2,…,an, 設計遞歸算法求其中由同號整數組成的最長連續段(稱爲最長同號連續段)的長度。例如,序列2,3,-1,6,-1,-5,-2,2的最長同號連續段爲-1,-5,-2,其長度爲3。 Input 輸入的第一行是一個正整數k,表示測試例個數。接下來幾行是k個測試例的數據,每個測試例的數據由兩行組成,其中第一行爲一個正整數n (n<=1000),表示整數序列的長度,第二行給出整數序列,整數之間用一個空格隔開。 Output 對於每個測試例輸出一行,含一個整數,表示相應序列的最長同號連續段的長度。 Sample Input 2 8 2 3 -1 6 -1 -5 -2 2 10 -1 -1 1 1 1 1 -1 -1 -1 -1
Sample Output 3 4 |
Source: #include<iostream.h> int count(int a[],int n) { if(n==1) return 1; else { int i=n-1,j;j=1; while(i>=1&&a[n]*a[i]>0) { j++; i--; } if(j>=count(a,n-1)) return j; else return count(a,n-1); } } int main() { int a[1001],i,j,n; cin>>j; while(j--) { cin>>n; for(i=1;i<=n;i++) cin>>a[i]; cout<<count(a,n)<<endl; } return 0; }
|