zoukankan      html  css  js  c++  java
  • 开灯问题

    题目:

    有n盏灯,编号为1~n。第1个人把所有灯打开,第2个人按下所有编号为2的倍数的开关,第3个人按下所有编号为2倍数的开关
    (其中关掉的被打开,开着灯的将会被关掉),以此类推。一共K个人,最后有哪些灯是开着的?

    输入样例1:

    7 3
    

    输出样例1:

    1 5 6 7 
    

    输入样例2:

    40 10
    

    输出样例2:

    1 4 9 11 12 13 14 15 17 18 19 20 21 23 27 29 31 35 37 
    

    代码示例:

    #include <iostream>
    #include <cstdio>
    
    using namespace std;
    const int SIZE = 10001;
    
    int main()
    {
    	int pLight[SIZE] = { 0 };
    	int light = 0, people = 0;							// light:灯的个数; people:人的个数;
    	
    	for (int i = 0; i < SIZE; i++)						// 完成第一个人需要完成的任务,将所有的灯泡打开,记为1
    		pLight[i] = 1;
    
    	cin >> light >> people;
    
    	int i, j;
    	for (i = 2; i <= people; i++)						// 由于前面完成了第一个人的任务,所以从第二个人开始计数
    	{
    		for (j = 2; j <= light; j++)					// 由于完成了第一个人的任务,所以第一盏灯始终是亮的,从第二盏开始反转
    		{
    			if (j%i == 0)								// 要求是如果能被该人编号除尽的灯号,就反转打开或者灭掉
    				pLight[j-1] = -pLight[j - 1];
    		}
    	}
    
    	for (int i = 0; i < light; i++)
    	{
    		if (pLight[i] != -1)							// 判断哪些是亮的灯
    		{
    			pLight[i] = i + 1;							// 将这些灯重新赋值于它本身的编号
    			cout << pLight[i] << " ";
    		}
    	}
        
    	return 0;
    }
  • 相关阅读:
    Generate Parentheses
    Length of Last Word
    Maximum Subarray
    Count and Say
    二分搜索算法
    Search Insert Position
    Implement strStr()
    Remove Element
    Remove Duplicates from Sorted Array
    Remove Nth Node From End of List
  • 原文地址:https://www.cnblogs.com/JingWenxing/p/9935604.html
Copyright © 2011-2022 走看看