美图欣赏 | 设为首页 | 加入收藏 | 网站地图

当前位置:电脑中国 > 编程 > C++ >

C++之开灯问题(链表)

2019-10-18 14:29|来源:未知 |作者:dnzg |点击:

有n盏灯,编号为1~n。第1个人把所有灯打开,第2个人按下所有编号为2的倍数开关(这些灯将被关掉),第3个人按下所有编号为3的倍数的开关,以此类推。一共有k个人,问最后有哪些灯开着?输入n和k,输出开着的灯的编号。k<=n<=100

 

样例输入    7  3

样例输出    1  5   6   7

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

typedef struct light{
    int state;  // state 为 0 时代表灯是关着的,为 1 时代表灯是亮着的 
    struct light *next;
};

int main(void)
{
    int num, k, i, j;
    light *light_state = NULL;
    light *head = NULL, *temp = NULL;
    
    printf("请输入灯的数量n,人的数量k:");
    scanf("%d %d", &num, &k);

    for(i = 0; i < num; i++)   // 创建长度为 num 的链表 
    {
        light_state = (light*)malloc(sizeof(light));
        if (head == NULL)
            head = light_state;
        else
            temp->next = light_state;
        light_state->next = NULL;
        light_state->state = 0;
        temp = light_state;
    }

    for(j = 0; j < k; j++)
    {
        light_state = head;
        for(i = 0; i < num; i++)
        {
            if((i + 1) % (j + 1) == 0)  // 灯的编号符合需要对应的人按开关时 
                if(light_state->state == 0)
                {
                    light_state->state = 1;
                }
                else if(light_state->state == 1)
                {
                    light_state->state = 0;
                }
            light_state = light_state->next;
        }
    }
        
    printf("开着的灯的编号为:");
    light_state = head;
    for(i = 0; i < num; i++)
    {
        if(light_state->state == 1)
        {
            printf("%d ", i+1);
        }
        light_state = light_state->next;
    }
    
    printf("\n");
    system("pause");
}
(责任编辑:dnzg)