20132014-acmicpc-brazil-subregional-programming-contest Problem J Trucks


题解:
把没用的边删掉,剩下一棵最大生成树,
倍增求公共祖先即可。
代码:
#include<bits/stdc++.h>
using namespace std;
const int maxn=2e4+7;
struct node
{
    int from,to,cost;
}c[5*maxn];
vector<node>G[maxn];
bool vis[5*maxn];
int lg[maxn],dp[maxn][20],f[maxn][20];
int dep[maxn];
bool cmp(const node &a,const node &b)
{
    return a.cost>b.cost;
}
int par[maxn];
int find(int x)
{
    if(x==par[x])return x;
    return par[x]=find(par[x]);
}
void unite(int x,int y)
{
    x=find(x);y=find(y);
    if(x!=y)
        par[x]=y;
}
void dfs(int u,int fa,int k)
{
    dep[u]=dep[fa]+1;
    f[u][0]=fa;
    if(fa!=0)dp[u][0]=G[fa][k].cost;
    for(int i=1;(1<<i)<=dep[u];i++)
    {
        f[u][i]=f[f[u][i-1]][i-1];
        dp[u][i]=min(dp[u][i-1],dp[f[u][i-1]][i-1]);
    }
    for(int i=0;i<G[u].size();i++)
    {
        node e=G[u][i];
        if(e.to==fa)continue;
        dfs(e.to,u,i);
    }
}
int lca(int x,int y)
{
    int mi=1e9;
    if(dep[x]<dep[y])swap(x,y);
    while(dep[x]>dep[y])
    {
        int h=lg[dep[x]-dep[y]];
        mi=min(mi,dp[x][h]);
        x=f[x][h];
    }
    if(x==y)return mi;
    for(int i=lg[dep[x]];i>=0;i--)
    {
        if(f[x][i]!=f[y][i])
        {
            mi=min(mi,min(dp[x][i],dp[y][i]));
            x=f[x][i];y=f[y][i];
        }
    }
    return min(mi,min(dp[x][0],dp[y][0]));
}
int main()
{
    for(int i=0;i<maxn;i++)
        par[i]=i;
    for(int i=2;i<maxn;i++)
        lg[i]=lg[i-1]+(1<<lg[i-1]+1==i);
    int n,m,Q;
    scanf("%d%d%d",&n,&m,&Q);
    for(int i=0;i<m;i++)
    scanf("%d%d%d",&c[i].from,&c[i].to,&c[i].cost);
    sort(c,c+m,cmp);
    for(int i=0;i<m;i++)
    {
        node e=c[i];
        if(find(e.from)!=find(e.to))
        {
            G[e.from].push_back((node){0,e.to,e.cost});
            G[e.to].push_back((node){0,e.from,e.cost});
            unite(e.from,e.to);
        }
    }
    dfs(1,0,0);
    while(Q--)
    {
        int x,y;
        scanf("%d%d",&x,&y);
        printf("%d\n",lca(x,y));
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值