一個分糖果遊戲的解法

來源:互聯網
上載者:User
 所有學生以圓形圍著老師,每個學生開始時均有偶數塊糖果,老師每吹一次哨子,每位學生拿出手中一半糖果給右側的同學,對任何一個學生,吹哨後,當手中的糖果數為奇數塊時,由老師補一塊給他(她),這樣下去,當每個學生手中的糖果數相同時,遊戲結束.
輸入要求:遊戲測試不止一個,對於每個遊戲測試,輸入學生人數N,開始時每個學生手中的糖果數分別為多少(EVEN),輸入學生人數為"0"時,測試結束.
輸出要求:對每個遊戲測試,輸出老師吹了幾次哨後,學生手中的糖果數相同,並且在同一行輸出學生手中相同的糖果數是多少.
標準輸入:6
     36
     2
     2
     2
     2
     2
     4
     2
     4
     6
     8
標準輸出:15 14
     4   8

    所解輸出和執行個體輸出有所不同,主要是老師吹哨次數的不同:

#include <iostream>
using namespace std ;

void arun(int *a, int nlen, int *n, int * how)
{
    int j , t1, t2;
    int i = 0;
    while(1)
    {
        i++;
        t2 = a[nlen -1] /2 ;
        for ( j = 0 ; j < nlen ; j ++)
        {
            t1 = a[j] /2 ;
            a[j] = t1 + t2;
            t2 = t1;        
        }
        for (j = 1; j < nlen ; j ++)
        {
            if(a[0] != a[j] )
                break;
        }
        if(j == nlen) {
            *n = i;
            *how = a[0];
            return ;
        }
        for(j = 0 ; j < nlen ; j ++)
        {
            if(a[j] % 2 == 1) a[j] ++;
        }
    }
}

int main()
{
    int n,how;
    while(1)
    {
        if(cin >> n )
        {
            if(n <= 0) break;
            int * a = (int *) new int[n];
            for(int i = 0 ; i < n ; i ++)
            {
                cin >> a[i] ;
            }
            arun(a,n,&n, &how);
            delete [] a;
            cout << n <<"  " << how <<endl;
        }
        else break;
    }
    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.