zoukankan      html  css  js  c++  java
  • 319. Bulb Switcher

    There are n bulbs that are initially off. You first turn on all the bulbs. Then, you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the ith round, you toggle every i bulb. For the nth round, you only toggle the last bulb. Find how many bulbs are on after n rounds.

    Example:

    Given n = 3. 
    At first, the three bulbs are [off, off, off]. After first round, the three bulbs are [on, on, on]. After second round, the three bulbs are [on, off, on]. After third round, the three bulbs are [on, off, off].
    So you should return 1, because there is only one bulb is on.


    用DP非常直观的解法如下,但是超时了。
    public int BulbSwitch(int n) {
            var dp = new bool[n+1];
            for(int i=1;i<=n;i++)
            {
                int j = 1;
                while(i*j<=n)
                {
                    dp[i*j] = !dp[i*j];
                    j++;
                }
            }
            int res=0;
            for(int i =1;i<=n;i++)
            {
                if(dp[i] == true) res++;
            }
            return res;
        }

    仔细分析,以6,16为例,6可以分解为[1,6],[2,3],[3,2],[6,1],也就是说,反复了四次,on/off不变,所以是off。只要能分解为偶数对个两个数的相乘,就是off。那什么情况下会有奇数个分解呢?只要在恰好是平方差数的时候,那么问题化简为求1-n这些数里哪些是平方差数。代码如下:

    public int BulbSwitch(int n) {
            int res=0;
            for(int i=1;i<=Math.Sqrt(n);i++)  if(i*i<=n) res++;
            return res;
        }

    更为简单的方法是只需要知道sqrt就好了。。

    public int BulbSwitch(int n) {
            return  (int)Math.Sqrt(n);
        }
  • 相关阅读:
    添加GDataXMLNODE.h和.m的方法
    NSPredicate的用法
    oc正则表达式基本语法(二)
    洛谷3931 [洛谷八连测] 一道难题
    洛谷2024 食物链 并查集
    洛谷1005 【NOIP2007】矩阵取数游戏
    洛谷3927 [洛谷八连测] 一道中档题
    洛谷1113 杂务
    洛谷1019 单词接龙 字符串dfs
    洛谷1414 又是毕业季II
  • 原文地址:https://www.cnblogs.com/renyualbert/p/5902465.html
Copyright © 2011-2022 走看看