题目链接:U364050 路灯全同(Street Lights Identical)
解题思路
如果采用暴力解法,每次操作后都逐一比较两条路上路灯的状态是否一致,那么这样的算法时间复杂度为 ,运行时间会超限,无法通过本题。
为了降低程序运行时间,我们引入一个辅助变量 ,表示两条路上同一位置路灯状态不同的个数(即,多少个 使得第一条路上第 个路灯的状态与第二条路上第 个路灯的状态不同)。
首先,我们用一个数组 来记录两条路上某一位置路灯状态是否相同。数组中每个元素都为 或 。如果第一条路上第 ()个路灯的状态与第二条路上第 个路灯的状态不同,则 ;否则,。(建议用布尔数组实现。)
然后,统计数组 中 的个数,记录到变量 中。
随后,判断 是否为 。当 时,意味着数组 中全是 ,即两条路上路灯的状态完全一致,因此输出 ;否则,输出 。
在第 次操作中,小蓝按下了第 条路上的第 个路灯的开关。不论 等于 还是 ,这一操作的作用都相当于反转 的值(即,如果 原先是 ,则变为 ;如果 原先是 ,则变为 )。这是因为,如果第一条路上第 个路灯的状态与第二条路上第 个路灯的状态原先相同,则操作后必将变为不同;如果原先不同,则操作后必将变为相同。
如果小蓝进行的操作使 由 变成 ,则令 减去 ;如果小蓝进行的操作使 由 变成 ,则令 加上 。这一操作的目的是保证 永远等于数组 中 的个数。
接下来,再次判断 是否为 。当 时,输出 ;否则,输出 。
对于每次操作,都进行同样的处理。
时间复杂度为 ,可以通过本题。
在实际做题过程中,发现有选手利用硬件的加持通过了本题(如利用 C++ 的
std::vector或std::string的等号运算符直接比较,效率出奇地高)。这一点出题人也很困惑。
AC 代码
C++
#include <iostream>
using namespace std;
const int N = 100'000;
bool x[N];
int main()
{
int n = 0, m = 0, d = 0;
char c = '\0';
cin >> n >> m;
for (int i = 0; i < n; ++i)
{
cin >> c;
x[i] = (c == '1'); // if c == '1' then x[i] = true else x[i] = false
}
for (int i = 0; i < n; ++i)
{
cin >> c;
x[i] = (x[i] != (c == '1')); // if c_1 != c_2 then x[i] = true else x[i] = false
}
for (int i = 0; i < n; ++i)
if (x[i])
++d;
cout << (d == 0); // if d == 0 then output 1 else output 0
for (int i = 0; i < m; ++i)
{
int s = 0, l = 0;
cin >> s >> l;
--l;
if (x[l])
--d;
else
++d;
x[l] = !x[l];
cout << (d == 0);
}
cout << '\n';
return 0;
}Java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(), m = sc.nextInt(), d = 0;
String str = sc.next();
boolean[] x = new boolean[n];
for (int i = 0; i < n; ++i)
x[i] = (str.charAt(i) == '1'); // if str[i] == '1' then x[i] = true else x[i] = false
str = sc.next();
for (int i = 0; i < n; ++i)
x[i] = (x[i] != (str.charAt(i) == '1')); // if str_1[i] != str_2[i] then x[i] = true else x[i] = false
for (int i = 0; i < n; ++i)
if (x[i])
++d;
System.out.print(d == 0 ? '1' : '0');
for (int i = 0; i < m; ++i) {
int l = 0;
sc.nextInt();
l = sc.nextInt() - 1;
if (x[l])
--d;
else
++d;
x[l] = !x[l];
System.out.print(d == 0 ? '1' : '0');
}
System.out.println();
}
}Python
n, m = map(int, input().split())
x = list(map(lambda a, b: a != b, list(input()), list(input()))) # if a != b then x = True else x = False
d = x.count(True)
print(int(d == 0), end = '') # if d == 0 then output 1 else output 0
for i in range(m):
l = list(map(int, input().split()))[1] - 1
if x[l]:
d -= 1
else:
d += 1
x[l] = not x[l]
print(int(d == 0), end = '')
print()