题解:P1161 开灯

· · 题解

题解:P1161 开灯

思路

注意到数据量不大,故按照题意模拟即可。

这里给出两种模拟方式:

  1. 开一个数组记录每一盏灯的状态。每次操作时,将对应灯的状态取反。最后遍历数组,将开着的灯输出即可。
  2. 开一个数组,统计每一盏灯被操作的次数。最后遍历数组,如果该灯被操作的次数为奇数,由于初始状态为关,则此时该灯的状态为开。输出其编号即可。

那么思路就分析完了。两种模拟方式的实现可以参考代码。

代码

#include <bits/stdc++.h>
using namespace std;
#define N 2000001
bool f[N]; // 第二种:int f[N];
#define sw(x) ((x) = (x) ? 0 : 1)
signed main() {
    cin.tie(0), cout.tie(0) -> sync_with_stdio(0);
    int n; cin >> n;
    while(n--) {
        double a; int t; cin >> a >> t;
        for(int i = 1; i <= t; ++i)
            sw(f[(int)(a * i)]); // 第二种:++f[(int)(a * i)];
    }
    for(int i = 1; i < N; ++i)
        if(f[i]) // 第二种:if(f[i] & 1)
        { cout << i; return 0; }
    return 0;
}