約瑟夫環問題變形——循環數到的數中,若某一位是給定數D,則踢出此人。

這是湘大2012年6月18日程序設計實踐考試的一個題目。

——————————————————————

題目描述:

Cycle

Description

題目描述

N個人按順時鐘圍成一個圈,標號爲1到N,然後從1號人從1開始按順時鐘數數。如果數到數字中含有數碼D,那麼這個人就退出圈子,下個人繼續數下一個數,直到剩下一個人爲止。

輸入

第一行是一個整數K,表示樣例的個數。
每個樣例佔一行,爲兩個整數N (1 ≤ N ≤ 1000), D (0 ≤ D ≤ 9);

輸出

每行輸出一個樣例的結果,即最後剩下的那個人的標號。

樣例輸入

3
5 0
5 1
5 2

樣例輸出

4
5
5

Sample Input


Sample Output

——————————————————————————————————————————
很可惜,當時沒做出來。
下午敲了下,覺得應該是這樣的,也不知道如果提交上去,會不會ac。
代碼:
————————————————————————————————————————

#include <stdio.h>
#include <malloc.h>
struct data
{
    int v;
    struct data *next;
};//定義一個結構體,存儲“人”的編號,和下個“人”的地址。


int f(int m, int a)
{
while (m)
{
if (m % 10 == a)
return 1;
m = (m - m % 10) /10;
}
return 0;
}
//判斷當數到某數字m時,數字m的各個數位中,是否有數字a(0=<a<=9)。



int main()
{
    int t, n, d;
    int j, x;
    struct data * head ,*p, *q;
    scanf("%d", &t);
    head = (struct data*)malloc(sizeof (struct data));
head->v = -99999;
    while(t--)
    {
        p = q = head;
        scanf("%d%d", &n, &d);
        {
            for (j = 0; j < n; j++)
            {
                q = (struct data*)malloc(sizeof (struct data));
                q->v = j + 1;
                p ->next = q;
p = q;
            }
            q->next = head->next;
        }
//初始數數字的環。





q = head ->next;
j = 1;
x = 1;
while (j < n)
        {
            if (f(x, d))
            {
                p ->next = q->next;
                free(q);
                q = p;
                j++;


            }
else
{
            p = q;


}
q = q->next;
x++;


        }
//數數過程。

printf("%d\n\n",p->v );
    }


    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章