开灯问题

来源:互联网 发布:手机淘宝注册会员名 编辑:程序博客网 时间:2024/05/29 09:21

开灯问题

时间限制:3000 ms  |  内存限制:65535 KB
难度:1
描述

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

输入
输入一组数据:n和k
输出
输出开着的灯编号
样例输入
7 3
样例输出
1 5 6 7
来源
经典算法
上传者

首席执行官

问题链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=77

问题分析:模拟开关灯的过程。

代码:

#include <iostream>#include <stdio.h> #include <string.h>#include <math.h>#include <vector>#include <queue>#include <stack>#include <map>#include <string>#include <algorithm>#define MAX 1001using namespace std; /* run this program using the console pauser or add your own getch, system("pause") or input loop */bool light[MAX];int main(int argc, char** argv) {int n,k;scanf("%d%d",&n,&k);//第一个人把所有灯全开 memset(light,true,sizeof(light));for(int i=2;i<=k;i++){//开始模拟第2个人之后的开关灯 for(int j=i;j<=n;j+=i){light[j]=light[j]==true?false:true;}}for(int i=1;i<n;i++){if(light[i] == true){printf("%d ",i);}}if(light[n] == true){printf("%d",n);}return 0;}


原创粉丝点击