一個遞迴實現的取數遊戲

來源:互聯網
上載者:User

//還沒有最佳化,歡迎各位提出最佳化意見^.^

題目:

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;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.