不敢死隊問題 (sdut oj)


不敢死隊問題

Time Limit: 1000MS Memory Limit: 65536KB

Problem Description

說到“敢死隊”,大家不要以爲我來介紹電影了,因爲數據結構裏真有這麼道程序設計題目,原題如下:

有M個敢死隊員要炸掉敵人的一個碉堡,誰都不想去,排長決定用輪迴數數的辦法來決定哪個戰士去執行任務。如果前一個戰士沒完成任務,則要再派一個戰士上去。現給每個戰士編一個號,大家圍坐成一圈,隨便從某一個戰士開始計數,當數到5時,對應的戰士就去執行任務,且此戰士不再參加下一輪計數。如果此戰士沒完成任務,再從下一個戰士開始數數,被數到第5時,此戰士接着去執行任務。以此類推,直到任務完成爲止。

這題本來就叫“敢死隊”。“誰都不想去”,就這一句我覺得這個問題也只能叫“不敢死隊問題”。今天大家就要完成這道不敢死隊問題。我們假設排長是1號,按照上面介紹,從一號開始數,數到5的那名戰士去執行任務,那麼排長是第幾個去執行任務的?

Input

輸入包括多試數據,每行一個整數M(0<=M<=10000)(敢死隊人數),若M==0,輸入結束,不做處理。

Output

輸出一個整數n,代表排長是第n個去執行任務。


Example Input

9
6
223
0

Example Output

2
6
132

Hint


Author






參考代碼



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

struct node
{
    int data;
    struct node *next;
};

int main()
{
    int n;
    struct node *head,*p,*tail,*q;
    head = (struct node *)malloc(sizeof(struct node));
    while(~scanf("%d",&n) && n )
    {
        head->next = NULL;
        tail = head;
        while(n--)
        {
            p = (struct node *)malloc(sizeof(struct node));
            p->next = tail->next;
            tail->next = p;
            tail = p;
        }
        tail->next = head->next;
        p = head->next;
        q = tail;
        n = 0;
        int i = 1;
        while( p )
        {
            if( i == 6 )
                i = 1;
            p->data = i;
            if( head->next->data == 5 )
            {
                printf("%d\n",n+1);
                break;
            }
            if( p->data == 5 )
            {
                q->next = p->next;
                free(p);
                p = q->next;
                n++;
            }
            else
            {
                q = p;
                p = p->next;
            }
            i++;
        }

    }

    return 0;
}



發佈了189 篇原創文章 · 獲贊 60 · 訪問量 17萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章