最大連續和

14 views
Skip to first unread message

正捷 林

unread,
Apr 24, 2011, 12:06:00 AM4/24/11
to itrs
我寫完後 一直跑不出我要的值 我打的是9 -11 4 3 2 拜託誰可以幫幫我
#include <stdio.h>
#include <stdlib.h>

int main(){
int i,j,k;
int n,t,a[100];
int best;
scanf("%d",&n);
for(t=0;t<n;t++){
scanf("%d",&a[t]);
}
best=a[0];
for(i=1;i<=n;i++)
for(j=i;j<=n;j++){
int sum=0;
for(k=i;k<=j;k++){
sum+=a[k];
}
if(sum>best)
best=sum;
}
printf("%d",best);
system("PAUSE");
return 0;
}

大兔子

unread,
Apr 24, 2011, 7:56:08 AM4/24/11
to itrs
你一開始讀 0 base
後面寫 1 base
然後你排版有點......嗯哼嗯哼

正捷 林

unread,
Apr 24, 2011, 11:29:12 AM4/24/11
to itrs
把i的起始值改成0也是不行耶!
順便問一下 如果有個式子叫best>?=a[i] 是指當best>a[i]時 才執行後面的式子嗎?
#include <stdio.h>
#include <stdlib.h>

int main(){
int i,j,k;
int n,t,a[100];
int best;
scanf("%d",&n);
for(t=0;t<n;t++){
scanf("%d",&a[t]);
}
best=a[0];
for(i=0;i<=n;i++){

大兔子

unread,
Apr 24, 2011, 11:49:34 AM4/24/11
to itrs
for (i = 0; i <= n; i++)
你的陣列a[n] 明明是存你不知道的東西

kunghua

unread,
Apr 24, 2011, 9:22:52 PM4/24/11
to itrs
第一個問題是你不能用 a[n] 。C 式陣列是從 0 開始的 所以要用 a[0] ~ a[n-1].
要將迴圈改成 for(i=0;i<n;i++)

第二個問題是演算法太慢
最大連續和當你的 sum 變成負數的時候還要繼續加下去嗎? 一個迴圈應該就可以了...O(n).

林正捷

unread,
Apr 25, 2011, 12:20:48 PM4/25/11
to it...@googlegroups.com
我後來改成這樣  似乎就成功了   可是best>?=a[i]的問題還是沒有解決
for(i=0;i<n;i++){
                     for(j=i;j<n;j++){
                                       int sum=0;
                                       for(k=i;k<j;k++){

kunghua

unread,
Apr 25, 2011, 6:12:55 PM4/25/11
to itrs
"best>?=a[i]的問題" <= 我不太清楚這問題是在問什麼? 可不可以詳細解釋一下?

林正捷

unread,
Apr 26, 2011, 9:40:11 AM4/26/11
to it...@googlegroups.com
就是有一個迴圈
for(i=1;i<n;i++){
                      best>?=a[i];  
                      }
意思是說  當best>a[i]時  就不把a[i]的值宣告給best嗎

kunghua

unread,
Apr 26, 2011, 4:32:30 PM4/26/11
to itrs
我寫了一個測試程式跑了一下

#include <stdio.h>
#include <stdlib.h>

int main()
{
int i;
int a[14] = {1,2,3,4,5,1,2,3,4,1,2,3,4,0};
int best=0;

for(i=0;i<14;i++)
{
best>?=a[i];
}

printf("Best = %d\n",best);

return 0;
}

Best = 5

所以學弟說的對.... If best > a[i], do nothing.

莊典融(Tien-Jung Chuang)

unread,
Apr 26, 2011, 10:55:58 PM4/26/11
to it...@googlegroups.com
可以請問一下 >?= 這東西是定義在哪嗎?

2011/4/27 kunghua <kun...@gmail.com>
--
You are subscribed to the "itrs" group, see: http://groups.google.com/group/itrs

Tien-Ren Chen

unread,
Apr 26, 2011, 10:57:16 PM4/26/11
to it...@googlegroups.com
gcc extension

2011/4/26 莊典融(Tien-Jung Chuang) <tien...@gmail.com>:

Will Wang

unread,
Apr 26, 2011, 11:18:34 PM4/26/11
to it...@googlegroups.com
<?= 我一直認為這個東東很像是某種紋章
<@=

不過gcc會希望你不要用這個東西。

其他有趣且有用的extention還有case range, 還有designated init

case 'A'...'Z':

char A[256] = {[0 ... 9] = 1, 2, 3, [20 ... 45] = 2};


2011/4/27 Tien-Ren Chen <trche...@gmail.com>
Reply all
Reply to author
Forward
0 new messages