HZ偶爾會拿些專業問題來忽悠那些非計算機專業的同窗。今天JOBDU測試組開完會後,他又發話了:在古老的一維模式識別中,經常須要計算連續子向量的最大和,當向量全爲正數的時候,問題很好解決。可是,若是向量中包含負數,是否應該包含某個負數,並指望旁邊的正數會彌補它呢?例如:{6,-3,-2,7,-15,1,2,2},連續子向量的最大和爲8(從第0個開始,到第3個爲止)。你會不會被他忽悠住?算法
輸入有多組數據,每組測試數據包括兩行。測試
第一行爲一個整數n(0<=n<=100000),當n=0時,輸入結束。接下去的一行包含n個整數(咱們保證全部整數屬於[-1000,1000])。spa
對應每一個測試案例,須要輸出3個整數單獨一行,分別表示連續子向量的最大和、該子向量的第一個元素的下標和最後一個元素的下標。如果存在多個子向量,則輸出起始元素下標最小的那個。code
3 -1 -3 -2 5 -8 3 2 0 5 8 6 -3 -2 7 -15 1 2 2 0
-1 0 0 10 1 4 8 0 3
算法思路,大概是:blog
咱們記錄當前掃描的最大和,與記錄中的最大和。若是當前的和超過了最大和,就替換,而且記錄兩端座標。不然就繼續掃描。io
while(i<n){ if(newMax < 0){ newMax = gArr[i]; newBegin = i; newEnd = i; }else{ newMax += gArr[i]; newEnd = i; } if(newMax > realMax){ realMax = newMax; realBegin = newBegin; realEnd = newEnd; flag = 1; } i++; }
可是,這個題目的測試用例很奇怪,它僅支持前向的最大子段,而不是後向的最大字段。舉個例子:class
咱們輸入-1 0 5 0 0 獲得的應該是5 1 2 而不是5 1 4,也就是說,它向前知足最大子段,可是不保證向後知足,可是也多是沒有這種用例,個人代碼恰好踩中了空擋區。至少個人經過用例是這樣證實的。若是理解不對,還請改正。第二個測試用例很奇怪。im
#include <stdio.h> #include <stdlib.h> #define MAXSIZE 100000 int gArr[MAXSIZE] = {0}; int main(){ int n,i; int realMax,realBegin,realEnd; int newMax,newBegin,newEnd; int flag; while(scanf("%d",&n)!=EOF && n>0 && n <= 100000){ for(i=0;i<n;i++){ scanf("%d",&gArr[i]); } realMax=-1001,realBegin=0,realEnd=0; newMax=-1001,newBegin=0,newEnd=0; flag = 0; i=0; while(i<n){ if(newMax < 0){ newMax = gArr[i]; newBegin = i; newEnd = i; }else{ newMax += gArr[i]; newEnd = i; } if(newMax > realMax){ realMax = newMax; realBegin = newBegin; realEnd = newEnd; flag = 1; } i++; } if(flag) printf("%d %d %d\n",realMax,realBegin,realEnd); else printf("%d %d %d\n",-1,0,0); } return 0; } /************************************************************** Problem: 1372 User: xhalo Language: C Result: Accepted Time:450 ms Memory:1304 kb ****************************************************************/