简体   繁体   English

返回的次数是state的灯泡变了?

[英]return the number of times is state of bulb changed?

Today in an exam I faced a problem which is Toggled Switches(Hacker Earth) as it is an exam question So, I am unable to send the question or its link (exactly).今天在考试中,我遇到了一个问题,即 Toggled Switches(Hacker Earth),因为它是一道考试题,所以,我无法(确切地)发送问题或其链接。

Problem: we have to print a number representing the number of times do bulb changed its state.问题:我们必须打印一个数字,代表灯泡更换其 state 的次数。 The bulb is attached to the "n" number of switches.灯泡连接到“n”个开关。 So the bulb will be in the "on" state only when half or more than half of the given n of switches to be "on".因此,只有当给定 n 个开关的一半或一半以上时,灯泡才会处于“开启”状态。

1 represents on state 1 代表 state

0 for off respectively. 0 分别表示关闭。

There is also a query that will be given to represent which switch has to be toggled ( change from on to off or vice-versa 1 ->0 or 0->1).还会给出一个查询来表示必须切换哪个开关(从打开更改为关闭,反之亦然 1 -> 0 或 0->1)。 So, by toggling may or may not the bulb state change.因此,通过切换灯泡 state 可能会或可能不会改变。 so we have to return the number of times it changed its state.所以我们必须返回它改变 state 的次数。

input:输入:

1 - number of test case 1 - 测试用例数

3 - number of switches (n) 3 - 开关数量 (n)

1 1 0 - initial all n switches states 1 1 0 - 初始所有 n 个开关状态

3 - number of switches to be toggled 3 - 要切换的开关数量

3 2 1 -> (3 represents third switch ie as index wise second in switches array.) switches that have to be toggled. 3 2 1 ->(3 代表第三个开关,即开关阵列中的第二个索引。)必须切换的开关。

output: output:

1 - number of times the bulb changed its state. 1 - 灯泡更换其 state 的次数。

explanation : initial array or switches state [1, 1, 0] as half or more than half switches are in on.解释:初始阵列或开关 state [1, 1, 0] 因为一半或一半以上的开关处于打开状态。 hence bulb is in on state.因此灯泡在 state 上。 as per queries [3,2,1]根据查询 [3,2,1]

we have to toggle the 3 rd switch.我们必须切换第三个开关。 As initially third is in off [1,1,0] after toggling it changes to on [1,1,1] present switches state.由于最初第三个是关闭 [1,1,0] 后切换到打开 [1,1,1] 存在开关 state。 as all are in on position bulb is on.因为所有的都在 position 灯泡上。 ( no changes in the state of the bulb) (灯泡的state没有变化)

Now, have to toggle 2 nd switch so [1,1,1] changes to [1,0,1] switches states as half switches are on the bulb is on.现在,必须切换第二个开关,以便 [1,1,1] 更改为 [1,0,1] 开关状态,因为半个开关打开,灯泡打开。 ( no changes in the state of the bulb) (灯泡的state没有变化)

Now, 1 st switch to be toggled.现在,要切换第一个开关。 Hence [1,0,1] changes to [0,0,1].因此 [1,0,1] 变为 [0,0,1]。 as not equal or more than half switches are in on states hence bulb is going to be off.由于不等于或超过一半的开关处于开启状态,因此灯泡将关闭。 ( now bulb state is changed) (现在灯泡 state 已更改)

Hence the output is one.因此 output 是一个。

I wrote the answer to this I am only able to solve the sample test case.我写了这个答案我只能解决示例测试用例。 No hidden test case is got the right answer and some got time exceeds error.没有隐藏的测试用例得到正确的答案,有些得到的时间超过了错误。 so totally 0 marks.所以完全是0分。

I am a beginner so please explain vividly where I am wrong what is wrong?我是初学者,所以请生动地解释我错在哪里,哪里错了? how it can be efficient?.它如何有效?

and my code is我的代码是

    import java.util.*;
    public class Main{
        static Scanner scan = new Scanner(System.in);
        public static void main(String[] args) {
        int test_cases = scan.nextInt();
    while(test_cases>0){
        //number of switches
        int n  = scan.nextInt();
        // contains on / off positions of switches
        int [] switches = new int[n];
        for(int i =0;i<n;i++)
        switches[i]=scan.nextInt();
        //number of queries 
        int q = scan.nextInt();
        //  starts at 1 i.e queries[0]=1 but represents switch index 1(queries representing switch position and tha position starts from 1)
        int [] queries  = new int[q];
        for(int i =0;i<q;i++)
        queries[i]=scan.nextInt();
        int result  = toggled(n,switches,q,queries);
        System.out.println(result);
        test_cases--;
    }
    }
    static int toggled(int n,int switches[],int q,int queries[]){
        if(n==1)
        return q;
        int result =0;
        //giving switch state on or off
        boolean initial = on(switches);
        //System.out.println("initial is "+initial);
        //to represent on or off for all toggle including initial
        boolean [] states = new boolean[q+1];
        states[0] = initial;
        int count  = 0;
        //to represent index of states
        int state_count =1;
        while(count<q){
            if((switches[queries[count]-1] & 1 )== 1)
            switches[queries[count]-1] = 0;
            else
            switches[queries[count]-1] = 1;
     
     states[state_count++]=on(switches);
     count++;
        }
       //System.out.println("state_count is "+state_count);
       for(int i =1;i<state_count;i++){
           if(initial ^ states[i] )
           {
               result+=1;
               initial = states[i];
           }
       }
       return result;
    }
    //method to evaluate whether to consider on or off ( to on(bulb) have to on atleast half of the switches)
    static boolean on(int arr[]){
        int sum = 0;
        for(int i =0;i<arr.length;i++)
            sum+=arr[i];
        
        if(sum>=arr.length/2.0)
            return true;
            else 
            return false;
            
        
    }
}

It seems like your on() function is taking n (linear) time where n is the number of switches.您的on() function 似乎需要n (线性)时间,其中n是开关的数量。 Total time complexity would be O(n*q) q is a number of queries.总时间复杂度为O(n*q) q 是查询的数量。 You can bring it down to O(n+q) .您可以将其降低到O(n+q)

I am not familiar with Java therefore Python我不熟悉 Java 因此 Python

Text after # denotes a comment in Python # 后面的文字表示 Python 中的注释

def on(number_of_on, n) : # //takes O(1)
    '''// Returns 1 if more than half or half of the switches are ON else returns 0'''
    if (number_of_on >= n/2) :
        return 1 #// ON STATE
    else :
        return 0 #// OFF state

for t in range(int(input())) : #// test cases (1)
    n = int(input()) #// number of switches (3)
    switches = list(map(int, input().split())) #// initial state of switches(1 1 0)
    q = int(input()) #// number of queries (3)
    queries = list(map(int, input().split())) #// toggle sequence (3 2 1)

    number_of_on = 0 #// denote number of bulbs which are ON
    count = 0 #// number of changes (ANSWER)
    
    for i in range(n) : #// O(n)
        if switches[i] == 1 :
            number_of_on += 1
          
    current = on(number_of_on, n) #// FUNCTION CALL
          
    for i in range(q) : #// ITERATING IN QUERIES
        if switches[queries[i]-1] == 1 : #//  IF switch at 'q' is 1 (ON)  
            switches[queries[i]-1] = 0 #// TURNING it OFF
            number_of_on -= 1 #// number of OFF will be (-1)
            if on(number_of_on, n) == False and current == 1 : #// if on() returns False/0 (OFF) AND current is ON/1
                current = 0 #// change current state
                count += 1 #// count++ (change in state)
        else :
            switches[queries[i]-1] = 1 
            number_of_on += 1
            if on(number_of_on, n) == True and current == 0 : #// if on() returns TRUE/1 (ON) AND current is OFF/0
                current = 1 #// change current state
                count += 1 #// count++ (change in state)
    print(count) #// ANSWER

Function on(number_of_on, number_of_switches) // Returns 1 if more than half or half of the switches are ON else returns 0 Function on(number_of_on, number_of_switches) // Returns 1 if more than half or half of the switches are ON else returns 0

  • n // number of switches (3) - input n // number of switches (3) - 输入
  • switches // initial state of switches(1 1 0) - input switches // initial state of switches(1 1 0) - 输入
  • q // number of queries (3) - input q // number of queries (3) - 输入
  • queries // toggle sequence (3 2 1) - input queries // toggle sequence (3 2 1) - 输入
  • number_of_on = 0 // denote number of bulbs which are ON
  • count = 0 // number of changes (ANSWER)
  1. Firstly counting the number of switches that are ON and will store them in the variable number_of_on will take O(n) time.首先计算打开的开关数量并将它们存储在变量number_of_on中将花费O(n)时间。

  2. and see the current state of the bulb by calling a function on(number_of_on, number_of_switches) and assign value to the current variable.并通过调用 function on(number_of_on, number_of_switches)查看灯泡的当前 state 并将值分配给current变量。

  3. Then iterate over the queries (i - for loop variable)然后遍历查询(i - for 循环变量)

  • if the value at element at index queries[i]-1 is 1, means we will toggle OFF the switch and decrease the value of number_of_switches by 1. number_of_swiches -= 1;如果索引queries[i]-1处元素的值为 1,则意味着我们将关闭开关并将number_of_switches的值减少 1。 number_of_swiches -= 1; now we will call the function on(number_of_on, number_of_switches) and if the value return is 1 and the current was 0 means the bulb must have changed its state (from 0 -> 1).现在我们将调用 function on(number_of_on, number_of_switches)并且如果返回值是1并且current0意味着灯泡一定已经改变了它的 state(从 0 -> 1)。 SO count += 1所以count += 1

  • if the value at element at index queries[i]-1 is 0, means we will toggle ON the switch and increase the value of number_of_switches by 1. number_of_swiches += 1;如果索引queries[i]-1处元素的值为 0,则意味着我们将打开开关并将number_of_switches的值增加 1。 number_of_swiches += 1; now we will call the function on(number_of_on, number_of_switches) and if the value return is 0 and the current was 1 means the bulb must have changed it state (from 1 -> 0).现在我们将调用 function on(number_of_on, number_of_switches)如果返回值是0并且current1意味着灯泡必须改变它 state(从 1 -> 0)。 So count += 1 .所以count += 1

I tested your code.我测试了你的代码。 I found one logical error in the method I mention below.我在下面提到的方法中发现了一个逻辑错误。

static boolean on(int arr[])
{
     int sum = 0;
     
     for(int i = 0;i < arr.length;i++) sum+=arr[i];
   
     //The test expression should be sum >= arr.length/2.0
     if(sum > arr.length/2.0) return true;
     else return false;

You said in the problem statement:你在问题陈述中说:

So the bulb will be in the "on" state only when half or more than half of the given n of switches to be "on".因此,只有当给定 n 个开关的一半或一半以上时,灯泡才会处于“开启”状态。

To test this condition the test expression should be为了测试这个条件,测试表达式应该是

if (sum >= arr.length/2.0)

and not并不是

if (sum > arr.length/2.0)

Another improvement in your code is its time complexity .代码的另一个改进是它的time complexity Currently you are checking the state of the bulb by checking all the switches.目前,您正在通过检查所有开关来检查灯泡的 state。

There are n number of bulbs and q number of queries .n个灯泡q个查询 If you check the state of the bulb in this manner it will result in O(q*n) .如果您以这种方式检查灯泡的 state ,它将导致O(q*n)

It can be done in O(q + n) .它可以在O(q + n)中完成。

Logic in Brief:简要逻辑:

If you declare a variable to store the total number of switches on and update it after each query.如果您声明一个变量来存储打开的开关总数并在每次查询后更新它。 Then use this variable to check if there is a change in the state of the bulb, your code will be more efficient.然后用这个变量检查灯泡的state是否有变化,你的代码会更有效率。

I have provided a code below using this implementation.我在下面提供了使用此实现的代码。

BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));

    int testCases = Integer.parseInt(bufferedReader.readLine().trim());
    //To score output of all the testCases
    int[] result = new int[testCases];

    for (int i = 0;i < testCases;i++)
    {
        //number of bulbs
        int n = Integer.parseInt(bufferedReader.readLine().trim());
        //input in String array
        String[] in = bufferedReader.readLine().split(" ");
        //To count how many switches are in on state
        int countOn = 0;
        //To store if the bulb is currently on or not
        boolean isBulbOn;

        //Converting the input String array to number array
        int[] bulbState = new int[n];
        for(int j = 0;j < n;j++)
        {
            int x = Integer.parseInt(in[j]);
            bulbState[j] = x;

            if (x == 1) countOn++;
        }
        //Initializing isBulbOn to true if countOn >= n/2
        //Math.ceil() conversion is necessary since in case of odd number of bulbs n/2 will result in 1
        //and isBulbOn condition will be assigned an incorrect value
        //Here 2.0 is necessary since if it just to n/2 will result in integer not a double
        isBulbOn = countOn >= (int)Math.ceil(n/2.0);

        //Input number of queries and store it
        int q = Integer.parseInt(bufferedReader.readLine().trim());
        String[] toggleInput = bufferedReader.readLine().trim().split(" ");

        //To count number of times the state has changed
        int countStateChange = 0;

        for (int j = 0;j < q;j++)
        {
            int currentToggle = Integer.parseInt(toggleInput[j]);

            //If switch is on make it off else do the opposite
            if(bulbState[currentToggle-1] == 0)
            {
                bulbState[currentToggle-1] = 1;
                countOn++;
            }
            else
            {
                bulbState[currentToggle-1] = 0;
                countOn--;
            }

            //Check if bulb was previously on and the switch on is less than half of n
            //Register a state change
            if (isBulbOn && countOn < (int)Math.ceil(n/2.0))
            {
                isBulbOn = false;
                countStateChange++;
            }

            //Check if bulb was previously off and the switch on is more than or equal to half of n
            //Register a state change
            if (!isBulbOn && countOn >= (int)Math.ceil(n/2.0))
            {
                isBulbOn = true;
                countStateChange++;
            }
        }

        //store the result of current test case
        result[i] = countStateChange;
    }

    //Print all the results
    for (int x: result)
        System.out.println(x);
}

I hope I have helped you.我希望我对你有所帮助。 I did test my code against various inputs.我确实针对各种输入测试了我的代码。 Do comment if you find any problems or if any part of my code is hard to understand.如果您发现任何问题或我的代码的任何部分难以理解,请发表评论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 计算灯泡的state换了多少次? - to count the number of times do state of bulb changed? 返回hi出现的次数 - Return the number of times hi appears Function 在 TelephonyManager.ACTION_PHONE_STATE_CHANGED 中多次触发 - Function triggered multiple times in a TelephonyManager.ACTION_PHONE_STATE_CHANGED 返回字符在字符串中出现的次数 - Return the number of times a character shows up in a string 返回查询作为src的子字符串出现的次数 - Return the number of times query occurs as a substring of src 如何返回 Singleton 访问 getInstance() 的次数? - how to return the number of times Singleton accessed getInstance()? 计算一个单词输入次数的程序,然后按降序返回单词和使用次数 - Program to count the number of times a word is entered then return the word and number of times used in descending order 返回字符串“hi”出现在给定字符串中的任何位置的次数 - Return the number of times that the string “hi” appears anywhere in the given string 返回字符串“ hello”出现在给定字符串中任何位置的次数 - Return the number of times that the string “hello” appears anywhere in the given string 检查输入条目中的每个位置并返回出现字符的次数 - Check each position in the input entry and return the number of times a character occurs
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM