This program's goal is to simulate the toggling of N lights and report the number of lights switched on in any given interval. Since N will not exceed 500 and the number of toggling/reporting operations will not exceed 2,000, even a relatively complex inner loop will be executed only a million times. Thus, this is a straightforward brute-force solution whose goal is to produce the correct answer the first time.
The program is simple: it reads the input line and, depending on the value of the command token, either sums and prints the number of lights that are on or toggles lights in some interval. The only unusual part of the program is the statement lights[j] ^= 1 which is equivalent to lights[j] = lights[j] ^ 1 where '^' is the 'exclusive or' operator with this truth table:
xor | 0 | 1 |
0 | 0 | 1 |
1 | 1 | 0 |
'Exclusive or' means "one or the other of the two inputs is true". x=x^1 toggles the 0/1 value of x.
Below is a simple rendering of the solution:
#include <stdio.h> #include <stdlib.h> int lights[500+1]; /* lights numbered 1..500 */ main () { FILE *fin = fopen ("switch.in", "r"); FILE *fout = fopen ("switch.out", "w"); int n, m, i, a, b, command, sum, j; fscanf (fin, "%d %d", &n, &m); for (i = 0; i < m; i++) { fscanf (fin, "%d %d %d", &command, &a, &b); if (command == 1) { /* print */ sum = 0; for (j = a; j <= b; j++) sum += lights[j]; fprintf (fout, "%d\n", sum); } else { for (j = a; j <= b; j++) lights[j] ^= 1; } } exit (0); }