poj1986tarjan离线LCA模板

#include<bits/stdc++.h>
using namespace std;
#define ll long long;
struct edge
{
	int u;
	int v;
	int w;
	int next;
}e[400009],e1[400009];
int head[400009], head1[400009];
int fa[400009];
int dis[400009];
int vis[400009];
int tot, tot1;
void add(int u, int v, int w)
{
	e[++tot].u = u;
	e[tot].v = v;
	e[tot].w = w;
	e[tot].next = head[u];
	head[u] = tot;
}
void add1(int u, int v)
{
	e1[++tot1].u = u;
	e1[tot1].v = v;
	e1[tot1].next = head1[u];
	head1[u] = tot1;
}
int find(int x) { return x == fa[x] ? x : find(fa[x]); }
void lca(int root)
{
	fa[root] = root;
	vis[root] = 1;
	for (int i = head[root]; i;i=e[i].next)
	{
		if (vis[e[i].v] == 0)
		{
			dis[e[i].v] = dis[root] + e[i].w;
			lca(e[i].v);
			fa[e[i].v] = root;
		}
	}
	for (int i = head1[root]; i; i = e1[i].next)
	{
		if (vis[e1[i].v])
		{
			e1[i].w = dis[root] + dis[e1[i].v] - 2 * dis[find(e1[i].v)];
		}
	}
}
int main()
{
	int m, n, cost, x, y;
	char c;
	while (cin >> x >> y)
	{
		memset(dis, 0, sizeof(dis));
		memset(vis, 0, sizeof(vis));
		memset(head, 0, sizeof(head));
		memset(head1, 0, sizeof(head1));
		tot = tot1 = 0;
		for (int i = 0; i < y; i++)
		{
			scanf("%d%d%d %c", &m, &n, &cost, &c);
			add(m, n, cost);
			add(n, m, cost);
		}
		scanf("%d", &m);
		while (m--)
		{
			scanf("%d%d", &x, &y);
			add1(x, y);
			add1(y, x);
		}
		lca(1);
		for (int i = 1; i <= tot1; i +=2)
			printf("%d\n",max(e1[i].w,e1[i+1].w));
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_37765455/article/details/82813283
今日推荐