2改爲-1計算,an[]存前綴和,將位置存入map,再遍歷n到2n,an[i]-an[2*n]表示1到最後之間的差值的相反數,在map中找到這個值,更新答案。
我這渣渣語文表述,詳見代碼:
#include <iostream>
#include <map>
#include <algorithm>
using namespace std;
const int maxn = 2e5 + 5;
const int inf = 0x3f3f3f3f;
typedef map<int, int> ::iterator iter;
int an[maxn];
int main(void)
{
ios::sync_with_stdio(false);
int t;
cin >> t;
while (t--) {
map<int, int> mp;
mp[0] = 0;
int n;
cin >> n;
for (int i = 1; i <= 2 * n; i++) {
int x;
cin >> x;
if (x == 2) x = -1;
an[i] = an[i - 1] + x;
if (i <= n) mp[an[i]] = i; //將位置存入map
}
int ans = inf;
for (int i = n; i <= 2 * n; i++) {
iter it = mp.find(an[i] - an[2 * n]);
if (it != mp.end()) ans = min(ans, i - it->second);
}
cout << ans << endl;
}
return 0;
}