[JOI 2013 Final]彩燈

maniubi發表於2024-10-10

[JOI 2013 Final]彩燈

題意

給出一個 \(01\) 序列,可以把一段區間反轉。

求反轉後序列最長的交替子段,即 \(010101 \ldots\)\(101010 \ldots\)

思路

首先發現一個性質,反轉的一定是一段交替子段。

因為反轉不交替子段對答案的貢獻不優。

列舉反轉哪一段交替子段,統計左右兩邊的子段和它連起來的長度,取最大值即可。

具體實現時維護從某個數向前和向後的連續 \(0101\) 長度,連續 \(1010\) 長度。

程式碼

#include <bits/stdc++.h>
using namespace std;

const int N = 1e5 + 5;

int n, a[N], ans;
int p0[N], p1[N], s0[N], s1[N];

int main() {
	freopen("deng.in", "r", stdin);
	freopen("deng.out", "w", stdout);
	
	cin >> n;
	for (int i = 1; i <= n; i ++)
		cin >> a[i];
	
	for (int i = 1; i <= n; i ++) {
		if (a[i] != a[i - 1]) {
			p0[i] = p0[i - 1] + 1;
			p1[i] = p1[i - 1] + 1;
		}	else {
			p0[i] = 1;
			p1[i] = 1;
		}
	}
	for (int i = 1; i <= n; i ++) {
		if (a[i] == 1) p0[i] = 0;
		else p1[i] = 0;
	}
	
	for (int i = n; i >= 1; i --) {
		if (a[i] != a[i + 1]) {
			s0[i] = s0[i + 1] + 1;
			s1[i] = s1[i + 1] + 1;
		} else {
 			s0[i] = 1;
			s1[i] = 1;	
		}
	}
	for (int i = 1; i <= n; i ++) {
		if (a[i] == 1) s0[i] = 0;
		else s1[i] = 0;
	}
	
	for (int i = 1; i <= n; i ++) {
		if (i + s0[i + 1] <= n && a[i + s0[i + 1]] == 0) 
			ans = max(ans, p0[i] + s0[i + 1] + s0[i + s0[i + 1] + 1]);
		if (i + s0[i + 1] <= n && a[i + s0[i + 1]] == 1)
			ans = max(ans, p0[i] + s0[i + 1] + s1[i + s0[i + 1] + 1]);
		if (i + s1[i + 1] <= n && a[i + s1[i + 1]] == 0)
			ans = max(ans, p1[i] + s1[i + 1] + s0[i + s1[i + 1] + 1]);
		if (i + s1[i + 1] <= n && a[i + s1[i + 1]] == 1)
			ans = max(ans, p1[i] + s1[i + 1] + s1[i + s1[i + 1] + 1]);
		ans = max(ans, p0[i] + s1[i + 1]);
		ans = max(ans, p1[i] + s0[i + 1]);
	}
	
	cout << ans << "\n";
	return 0;
}

相關文章