long time no write solutions.
题面大意
两个长度都为 的字符串 ,给定 次查询,每次交换字符串 上第 到第 的字符,求操作完成后字符串 的最终状态。
思路
很容易发现性质:对于任意一个一个字母,交换偶数次后,他仍然在原来的字符串上。也就是说,交换偶数次,对于这个字母是没有任何作用的。
利用这个性质,我们很容易地联想到我们需要统计 上每个字母的交换次数,操作完成后遍历,当该字母交换次数为奇数时,直接交换,否则啥都不干。最后直接输出即可。
那么,如何统计交换次数呢?显然是不能 到 暴力 枚举的。但是,我们发现,每次交换增加的次数都是 ,没有其他修改动作,且只有最后才用统计答案,于是我们想到使用差分来统计交换次数,每次将 到 区间加一即可,这样我们就可以将时间复杂度降为 ,总时间复杂度为 。
Code
#include <bits/stdc++.h>
#define ll long long
#define endl '\n'
#define PII pair<ll, ll>
#define x first
#define y second
using namespace std;
const int E = 1e6 + 5;
ll n, m;
string s, t;
ll sum[E];
int main()
{
cin >> n >> m;
cin >> s >> t;
while (m--)
{
ll l, r;
cin >> l >> r;
sum[l]++;
sum[r + 1]--;
}
for (int i = 1; i <= n; i++)
sum[i] += sum[i - 1];
for (int i = 1; i <= n; i++)
if (sum[i] % 2 == 1)
swap(s[i - 1], t[i - 1]);
for (int i = 0; i < n; i++)
cout << s[i];
return 0;
}