//還沒有最佳化,歡迎各位提出最佳化意見^.^
題目:
Program國度的人,喜歡玩這樣一個遊戲,在一塊板上寫著一行數,共n個。兩個遊戲者,輪流從最右或最左取一個數。剛開始,每個遊戲者的得分均為零。如果一個遊戲者取下一個數,則將該數的值加到該遊戲者的得分上,最後誰的得分最高誰就贏了遊戲。給出這n個數( 從左往右), 假設遊戲者都是非常聰明的,問最後兩個人的得分(假設第一個人首先取數).
輸入格式:第一行為n(2<=n<=100),第二行為n個數,每個數字之間均用空格隔開。輸出為兩個遊戲者的得分.第一個數表示第一個遊戲者的得分,第二個數為第二個遊戲者的得分,兩個數字之間用空格隔開。
如輸入
6
4 7 2 9 5 2
輸出
18 11
==================code===============
/*Copyright (c) aprin at Xiamen University
*2005-04
*/
#include <stdio.h>
#define MAXN 100
int sum(int data[], int head, int tail);
int best(int data[], int head, int tail) {
int temp1, temp2;
if(head==tail)
return head;
temp1= *(data+head)+sum(data, head+1, tail);
temp2= *(data+tail)+sum(data, head, tail-1);
return (temp1>temp2)?head:tail;/*返回指標*/
}
int sum(int data[], int head, int tail) {
int temp;
if(head==tail)
return 0;/*有0個資料*/
if(tail== head+1)
return (*(data+head)<*(data+tail))?head:tail;/*取小的那一個*/
if(best(data, head, tail)==head)/*改變工作指標,讓對方選一個最好值*/
head++;
else tail--;
temp= best(data, head, tail);
if(temp==head)
return *(data+temp)+sum(data, head+1, tail);
else
return *(data+temp)+sum(data, head, tail-1);
}
int main(void) {
int data[MAXN], head, tail, n, i, total1, total2, temp;
scanf("%d", &n);
while((n<2)||(n>100)) {
printf("N is wrong! Please input n(2<=n<=100) again!/n");
scanf("%d", &n);
}
for(i=0; i<n; i++)
scanf("%d", data+i);
total1= total2= 0;
head=0;
tail= n-1;
for(i=0; i<n; i++) {
temp= best(data, head, tail);
if((i+1)%2!=0)
total1= total1+*(data+temp);
else
total2= total2+*(data+temp);
if(temp==head)
head= head+1;
else
tail= tail-1;
}
printf("%d %d/n", total1, total2);
getch();
return 0;
}