U364050 路灯全同(Street Lights Identical)题解
题目链接: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()