[AGC074B] Swap if Equal Length and Sum
Genius_Star · · 题解
或许更好的阅读体验。
很神秘的构造,感觉完全想不到。
思路:
首先注意一下不变量,显然
根据不变量可以轻松判定无解情况;我们需要证明满足不变量的都有解,可以给出一种构造:
-
我们钦定
A 中第i 个1 要去匹配B 中第i 个1 。 -
然后将所有的
1 分为两个部分L, R ,表示要往走匹配的集合和往右匹配的集合。 -
那么每次操作时,拿出
L 中最左边的元素和R 中最右边的元素,显然它们到目标之间应该全是0 不存在其它1 ,不然会与已有条件矛盾。 -
然后我们显然可以
0 \cdots 01 和10 \cdots 0 操作,其中0 的个数是取出的两个元素到目标的距离的较小值,这样就可以至少把其中一个1 匹配上。
于是最多操作
时间复杂度为
完整代码:
#include<bits/stdc++.h>
#define ls(k) k << 1
#define rs(k) k << 1 | 1
#define fi first
#define se second
#define popcnt(x) __builtin_popcount(x)
#define open(s1, s2) freopen(s1, "r", stdin), freopen(s2, "w", stdout);
using namespace std;
typedef __int128 __;
typedef long double lb;
typedef double db;
typedef unsigned long long ull;
typedef long long ll;
const int N = 2.5e5 + 10;
inline ll read(){
ll x = 0, f = 1;
char c = getchar();
while(c < '0' || c > '9'){
if(c == '-')
f = -1;
c = getchar();
}
while(c >= '0' && c <= '9'){
x = (x << 1) + (x << 3) + (c ^ 48);
c = getchar();
}
return x * f;
}
inline void write(ll x){
if(x < 0){
putchar('-');
x = -x;
}
if(x > 9)
write(x / 10);
putchar(x % 10 + '0');
}
int T, n, ca, cb;
int a[N], b[N], ida[N], idb[N];
vector<int> VL, VR;
inline void solve(){
ll s1 = 0, s2 = 0;
n = read();
for(int i = 1; i <= n; ++i)
a[i] = read(), s1 += a[i] * i;
for(int i = 1; i <= n; ++i)
b[i] = read(), s2 += b[i] * i;
if(s1 != s2){
puts("No");
return ;
}
s1 = s2 = 0;
for(int i = 1; i <= n; ++i)
s1 += a[i], s2 += b[i];
if(s1 != s2){
puts("No");
return ;
}
if(s1 > (n >> 1)){
for(int i = 1; i <= n; ++i)
a[i] ^= 1, b[i] ^= 1;
s1 = n - s1;
}
ca = cb = 0;
for(int i = 1; i <= n; ++i){
if(a[i])
ida[++ca] = i;
if(b[i])
idb[++cb] = i;
}
VL.clear(), VR.clear();
for(int i = 1; i <= s1; ++i){
// cerr << ida[i] << " to " << idb[i] << '\n';
if(ida[i] > idb[i])
VL.push_back(i);
else if(ida[i] < idb[i])
VR.push_back(i);
}
reverse(VR.begin(), VR.end());
vector<pair<pair<int, int>, pair<int, int>>> ans;
int h1 = 0, h2 = 0;
while(h1 < (int)VL.size() && h2 < (int)VR.size()){
int x = VL[h1], y = VR[h2];
if(ida[x] - idb[x] > idb[y] - ida[y]){
// cerr << "???1\n";
// cerr << x << ' ' << y << '\n';
ans.push_back({{ida[x] - (idb[y] - ida[y]), ida[x]}, {ida[y], idb[y]}});
++h2;
ida[x] -= (idb[y] - ida[y]);
}
else if(ida[x] - idb[x] < idb[y] - ida[y]){
// cerr << "???2\n";
ans.push_back({{idb[x], ida[x]}, {ida[y], ida[y] + (ida[x] - idb[x])}});
++h1;
ida[y] += (ida[x] - idb[x]);
}
else{
// cerr << "???3\n";
ans.push_back({{idb[x], ida[x]}, {ida[y], idb[y]}});
++h1, ++h2;
}
}
assert(h1 == (int)VL.size() && h2 == (int)VR.size());
puts("Yes");
write(ans.size());
putchar('\n');
for(auto t : ans){
if(t.fi.fi > t.se.fi)
swap(t.fi, t.se);
write(t.fi.fi);
putchar(' ');
write(t.fi.se);
putchar(' ');
write(t.se.fi);
putchar(' ');
write(t.se.se);
putchar('\n');
}
}
int main(){
T = read();
while(T--)
solve();
return 0;
}