CF EDU 103 C - Longest Simple Cycle
C - Longest Simple Cycle
dp
设 \(f[i]\) 为以第 \(i\) 个线段为环的右边界,环的最大长度
不妨令 \(l = min(a[i],b[i]),r =max(a[i],b[i])\)
-
\(l\neq r\)
- 第 \(i-1\) 条线段的 \([l,r]\) 这部分作为环的左边界,此时环的长度为 \(r-l+1+c[i]\)
- 不选第 \(i-1\) 条线段的 \([l,r]\) 这部分,与以第 $i-1 $ 条线段为右端点的环解上,此时环的长度为 \(f[i-1]-(r-l-1)+c[i]\)
-
\(l == r\)
只有策略 1 可以选,\(f[i]=c[i]+1\)
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <cmath>
using namespace std;
typedef long long ll;
const int N = 1e5 + 10;
int n;
ll c[N], a[N], b[N], f[N];
int main()
{
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
int T;
cin >> T;
while(T--)
{
cin >> n;
for (int i = 1; i <= n; i++)
cin >> c[i];
for (int i = 1; i <= n; i++)
cin >> a[i];
for (int i = 1; i <= n; i++)
cin >> b[i];
f[1] = 0;
for (int i = 2; i <= n; i++)
{
ll l = min(a[i], b[i]), r = max(a[i], b[i]);
if (l == r)
{
f[i] = c[i] + 1;
continue;
}
f[i] = max(r - l + 1, f[i-1] - (r - l - 1)) + c[i];
}
cout << *max_element(f + 1, f + n + 1) << endl;
}
return 0;
}