You have two binary strings � a and � b of length � n. You would like to make all the elements of both strings equal to 0 0. Unfortunately, you can modify the contents of these strings using only the following operation: You choose two indices � l and � r ( 1 ≤ � ≤ � ≤ � 1≤l≤r≤n); For every � i that respects � ≤ � ≤ � l≤i≤r, change � � a i to the opposite. That is, � � : = 1 − � � a i :=1−a i ; For every � i that respects either 1 ≤ � < � 1≤i<l or � < � ≤ � r<i≤n, change � � b i to the opposite. That is, � � : = 1 − � � b i :=1−b i . Your task is to determine if this is possible, and if it is, to find such an appropriate chain of operations. The number of operations should not exceed � + 5 n+5. It can be proven that if such chain of operations exists, one exists with at most � + 5 n+5 operations. Input Each test consists of multiple test cases. The first line contains a single integer � t ( 1 ≤ � ≤ 1 0 5 1≤t≤10 5 ) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer � n ( 2 ≤ � ≤ 2 ⋅ 1 0 5 2≤n≤2⋅10 5 ) — the length of the strings. The second line of each test case contains a binary string � a, consisting only of characters 0 and 1, of length � n. The third line of each test case contains a binary string � b, consisting only of characters 0 and 1, of length � n. It is guaranteed that sum of � n over all test cases doesn't exceed 2 ⋅ 1 0 5 2⋅10 5 . Output For each testcase, print first "YES" if it's possible to make all the elements of both strings equal to 0 0. Otherwise, print "NO". If the answer is "YES", on the next line print a single integer � k ( 0 ≤ � ≤ � + 5 0≤k≤n+5) — the number of operations. Then � k lines follows, each contains two integers � l and � r ( 1 ≤ � ≤ � ≤ � 1≤l≤r≤n) — the description of the operation. If there are several correct answers, print any of them.
时间: 2024-02-14 09:21:07 浏览: 179
这道题目的意思是给定两个长度为n的01字符串a和b,每次操作可以选择一个区间[l, r],将a中该区间内的元素取反,将b中该区间外的元素取反,问是否能通过有限次操作将a和b都变成全0。
思路:首先考虑每次操作对a和b的影响,发现每次操作不会改变a和b的异同性质,即a和b中相同位置的元素要么都取反,要么都不变。因此我们可以将a和b的不同位置分别记录下来,然后将它们的异同性质分开考虑。对于a和b中相同位置的元素,如果它们不同,那么无论怎么操作都不可能使它们都变成0;如果它们相同,那么我们只需要将它们都变成0即可。对于a和b中不同位置的元素,我们可以将它们分别记录下来,然后我们需要将它们都变成0,那么考虑对于每一个不同位置,我们需要将它所在的位置变成0,同时我们需要保证其他不同位置元素不受影响,因此我们可以将每个不同位置拆分成两个区间[l, r],分别表示需要将a中[l, r]变成0和需要将b中[l, r]变成0。
具体实现时,我们可以先将a和b中不同的位置分别记录下来,然后对于a和b中相同位置的元素,如果它们都是1,那么我们需要将它们变成0,此时操作数加1;对于a和b中不同位置的元素,我们可以先将每个不同位置拆分成两个区间[l, r],分别表示需要将a中[l, r]变成0和需要将b中[l, r]变成0。然后我们可以通过贪心的思想,将所有需要变成0的区间按照左端点排序,然后依次进行操作,直到把所有的区间变成0。具体实现时,我们可以将需要变成0的区间看成点,如果两个区间有重叠,那么它们之间就有一条边,我们只需要求出这个图的一个完美匹配即可。
时间复杂度为O(nlogn+n),其中n为字符串长度。
阅读全文