【NOIP2013提高组day1】货车运输

前奏

这题涉及的知识点如下,转载了几篇比较好的博客,建议学习。


链式前向星
最小生成树
倍增法求LCA

题面

Description

A 国有 n 座城市,编号从 1 到 n,城市之间有 m 条双向道路。每一条道路对车辆都有重量限制,简称限重。现在有 q 辆货车在运输货物,司机们想知道每辆车在不超过车辆限重的情况下,最多能运多重的货物。

Input

第一行有两个用一个空格隔开的整数 n,m,表示 A 国有 n 座城市和 m 条道路。
接下来 m 行每行 3 个整数 x、y、z,每两个整数之间用一个空格隔开,表示从 x 号城市到 y 号城市有一条限重为 z 的道路。注意:x 不等于 y,两座城市之间可能有多条道路。
接下来一行有一个整数 q,表示有 q 辆货车需要运货。
接下来 q 行,每行两个整数 x、y,之间用一个空格隔开,表示一辆货车需要从 x 城市运输货物到 y 城市,注意:x 不等于 y。

Output

输出共有 q 行,每行一个整数,表示对于每一辆货车,它的最大载重是多少。如果货车不能到达目的地,输出-1。

Sample Input

4 3
1 2 4
2 3 3
3 1 1
3
1 3
1 4
1 3

Sample Output

3
-1
3

Data Constraint

对于 30%的数据,0 < n < 1,000,0 < m < 10,000,0 < q < 1,000;
对于 60%的数据,0 < n < 1,000,0 < m < 50,000,0 < q < 1,000;
对于 100%的数据,0 < n < 10,000,0 < m < 50,000,0 < q < 30,000,0 ≤ z ≤ 100,000。

思路

首先构造一颗最大生成树,用链式前向星连边。接着求出两个点的LCA,顺带求路径上的最小值。

扫描二维码关注公众号,回复: 12478420 查看本文章

Code

#include<cstdio>
#include<iostream>
#include<cmath>
using namespace std;
struct data
{
    
    
	int to,from,ds;
}a[50005];
int n,m,q,fa[10005],tot,dep[10005],dis[50005];
int next[50005],head[50005],road[50005],f[10005][30],g[10005][30];
void add(int u,int v,int dv)
{
    
    
	tot++;
	next[tot]=head[u];
	head[u]=tot;
	dis[tot]=dv;
	road[tot]=v;
}
void qsort(int l,int r)
{
    
    
	int i=l,j=r,mid=a[l+r>>1].ds;
	while(i<=j)
	{
    
    
		while(a[i].ds>mid) i++;
		while(a[j].ds<mid) j--;
		if(i<=j)
		{
    
    
			swap(a[i],a[j]);
			i++,j--;
		}
	}
	if(l<j) qsort(l,j);
	if(i<r) qsort(i,r);
}
int find(int x)
{
    
    
	if(x!=fa[x]) return fa[x]=find(fa[x]);
	else return x;
}
void ready(int now,int come)
{
    
    
	dep[now]=dep[come]+1;
	for(int i=1;i<=20;i++)
	{
    
    
		f[now][i]=f[f[now][i-1]][i-1];
		g[now][i]=min(g[now][i-1],g[f[now][i-1]][i-1]);
	}
	for(int i=head[now];i;i=next[i])
	{
    
    
		int v=road[i];
		if(v==come) continue;
		f[v][0]=now;
		g[v][0]=dis[i];
		ready(v,now);
	}
}
int lca(int x,int y)
{
    
    
	if(dep[y]>=dep[x]) swap(x,y);
	int minx=999999999;
	for(int i=20;i>=0;i--)
	{
    
    
		if(dep[f[x][i]]>=dep[y])
		{
    
    
			minx=min(minx,g[x][i]);
			x=f[x][i];
		}
		if(x==y) return minx;
	}
	for(int i=20;i>=0;i--)
		if(f[x][i]!=f[y][i])
		{
    
    
			minx=min(minx,min(g[x][i],g[y][i]));
			x=f[x][i];
			y=f[y][i];
		}
	minx=min(minx,min(g[x][0],g[y][0]));
	return minx;
}
int main()
{
    
    
	scanf("%d%d",&n,&m);
	for(int i=1;i<=m;i++)
	{
    
    
		scanf("%d%d%d",&a[i].to,&a[i].from,&a[i].ds);
	}
	for(int i=1;i<=n;i++)
		fa[i]=i;
	qsort(1,m);
	for(int i=1;i<=m;i++)
		if(find(a[i].to)!=find(a[i].from))
		{
    
    
			fa[find(a[i].to)]=find(a[i].from);
			add(a[i].to,a[i].from,a[i].ds);
			add(a[i].from,a[i].to,a[i].ds);
		}
	ready(1,0);
	scanf("%d",&q);
	for(int i=1;i<=q;i++)
	{
    
    
		int x,y;
		scanf("%d%d",&x,&y);
		if(find(x)!=find(y)) printf("-1\n");
		else printf("%d\n",lca(x,y));
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_46830417/article/details/112763523