题解 P4381 【[IOI2008] Island】
可到我的博客食用
这道题确实非常简单... 只是没有看懂其他题解为什么要用单调队列,明明记两个最大值就可以解决?
题目大意是给出一个基环树森林(每一个点有一条无向边),让你求出所有基环树的直径(即一条不经过重复点的基环树上的最长路径)之和。
我们考虑不使用邻接表,而是只记录一个点的边的目标位置(
我们发现对于一个在环上的点
下面,对于基环树环上的每个点
这里的 1、2、3 都是环上的点。那么 1 的外环树就是
我们记一个点
我们发现,一个基环树的直径要不是一个外环树的直径,要不就是
第二种情况可能不太好理解。以上图为例,
那么接下来就简单了。我们只需要用拓扑序处理出每一个环上的点的
我们发现
那么最后的答案就是(
对于每一个环扫一遍即可。
小优化:
-
我们再遍历完一个环之前并没法拿到这个环的长度
len ,因此我们更新ret2 时不加上len ,最后遍历完后再给ret2 加上len 即可。 -
我们可以把
g_i 顺便统计到ret1 里面,并没有什么用。
代码(494ms / 30.84MB,目前洛谷2nd最优解):
mivik.h
// Mivik 2020.8.22
#include <mivik.h>
#include <algorithm>
#include <climits>
#ifdef MIVIK
MI cin(popen("xsel -ob", "r"));
#else
MI cin;
#endif
typedef long long qe;
const int nmax = 1000005;
template<typename T> inline bool getmax(T &a, const T &b) { return a<b && (a = b, true); }
int n;
int tar[nmax], wei[nmax];
// deg -> degree 度数
int deg[nmax];
qe f[nmax], g[nmax];
inline qe loop(int x) {
const int beg = x;
qe m1 = f[x], m2 = f[x];
qe pre = wei[x];
qe ret1 = g[x];
x = tar[x];
qe ret2 = LLONG_MIN;
while (x!=beg) {
deg[x] = 0;
getmax(ret1, f[x]+pre+m1);
getmax(ret2, f[x]-pre+m2);
getmax(ret1, g[x]);
getmax(m1, f[x]-pre);
getmax(m2, f[x]+pre);
pre += wei[x];
x = tar[x];
}
return std::max(ret1, ret2+pre);
}
int main() {
int i;
cin>n;
for (i=1;i<=n;i++) {
cin>tar[i]>wei[i];
++deg[tar[i]];
}
static int q[nmax];
int head = 1, tail = 0;
for (i=1;i<=n;i++) if (!deg[i]) q[++tail] = i;
// 计算出环上每个点的 f[i] 和 g[i]
while (head<=tail) {
const int x = q[head++];
const qe cc = f[x]+wei[x];
getmax(g[tar[x]], f[tar[x]]+cc);
getmax(g[tar[x]], g[x]);
getmax(f[tar[x]], cc);
if (!(--deg[tar[x]])) q[++tail] = tar[x];
}
qe ans = 0;
for (i=1;i<=n;i++) // 如果 deg[i] 不为 0 代表 i 是在环上
if (deg[i]) ans += loop(i);
cout<ans<endl;
return 0;
}