AcWing 3215. 网络延时(高性能,拓扑解法,15ms AC)
原题链接
中等
作者:
南川
,
2021-02-20 14:19:00
,
所有人可见
,
阅读 789
代码
#include "cstdio"
using namespace std;
#define Max(a, b) (a) = (b) > (a) ? (b) : (a)
const int N = 10000;
int degOut[N+1];
int father[N+1];
int height[N+1];
int n, m, v, k, ans;
bool topo(int i)
{
--degOut[i]; // lock
--degOut[father[i]]; // topologic
Max(ans, height[i] + height[father[i]] + 1);
Max(height[father[i]], height[i]+1);
if(--k == 1) return printf("%d", ans) && 0;
if(!degOut[father[i]]) return topo(father[i]);
}
int main()
{
scanf("%d %d", &n, &m);
for(int i=2; i<=n; ++i) scanf("%d", &father[i]), ++degOut[father[i]];
// ++degOut[v], // the deg of PCs should be excluded
for(int i=1; i<=m; ++i) scanf("%d", &v), height[v] = 1;
k = n;
for(int i=1; i<=n; ++i)
if(!degOut[i])
topo(i);
}
void print(int i, int k)
{
printf(">>> i: %d, k: %d->%d", i, k, k-1);
printf("\nheights: ");
for(int i=1; i<=n; ++i) printf("%2d ", height[i]);
printf("\ndegOuts: ");
for(int i=1; i<=n; ++i) printf("%2d ", degOut[i]);
printf("\n\n");
}
orz