1126

题目链接:http://ifrog.cc/acm/problem/1126

两种思路:

  • 1.用kruskal求这个图的最小生成树,由于kruskal算法先添加边权小的边,然后添加边权大的边。由这个性质可以知道,每添加完边r,如果s,t由不在一个树上两个点变为在同一个树上的两个点,那么这个边就是s,t路径上的最大值。即为答案。
  • 2.用dijkstra算法求两点间的最短路。更新方式换一下就好了。

kruskal算法

#include<bits/stdc++.h>
using namespace std;

const int INF = 0x3f3f3f3f;

struct edge
{
    int u, v, cost;
    edge(){}
    edge(int x, int y, int z)
    {
        u = x, v = y, cost = z;
    }
};

bool comp(const edge &e1, const edge &e2)
{
    return e1.cost < e2.cost;
}

edge arr[500007];
int par[100005], Rank[100005];
int n, V;

void init()
{
    for(int i=0; i<=n; ++ i)
        par[i] = i, Rank[i] = 0;
}

int Find(int x)
{
    while(x != par[x])
        x = par[x];
    return x;
}

void unite(int x, int y)
{
    x = Find(x), y = Find(y);
    if(x == y)
        return ;

    if(Rank[x] > Rank[y])
        par[y] = x;
    else
    {
        par[x] = y;
        if(Rank[x] == Rank[y])
            Rank[y] ++;
    }
}

bool same(int x, int y)
{
    return Find(x) == Find(y);
}

int kruskal(int s, int t)
{
    sort(arr, arr+V, comp);
    init();

    if(same(s, t))
        return 0;

    for(int i=0; i<V; ++ i)
    {
        edge e = arr[i];
        if(!same(e.u, e.v))
            unite(e.u, e.v);
        if(same(s, t))
            return e.cost;
    }
    return -1;
}

int main()
{
    while(scanf("%d%d", &n, &V) != EOF)
    {
        for(int i=0, u, v, c; i < V; ++ i)
        {
            scanf("%d%d%d", &u, &v, &c);
            arr[i] = edge(u, v, c);
        }
        int s, t;
        scanf("%d%d", &s, &t);
        printf("%d
", kruskal(s, t));
    }
    return 0;
}

Dijkstra算法

#include<bits/stdc++.h>
using namespace std;

const int INF = 0x3f3f3f3f;

struct edge
{
    int to, cost;
    edge(int x, int y)
    {
        to = x, cost = y;
    }
};

typedef pair<int, int> P;

vector<edge> G[500007];
int d[500007];
int n, V;

void dijkstra(int s)
{
    priority_queue<P, vector<P>, greater<P> > que;
    fill(d, d+n+5, INF);
    d[s] = 0;
    que.push(P(0, s));
    while(!que.empty())
    {
        P p = que.top();
        que.pop();

        int v = p.second;
        for(int i=0; i<G[v].size(); ++ i)
        {
            edge e = G[v][i];
            if(d[e.to] > max(d[v], e.cost))
            {
                d[e.to] = max(d[v], e.cost);
                que.push(P(d[e.to], e.to));
            }
        }
    }
}

int main()
{
    while(scanf("%d%d", &n, &V) != EOF)
    {
        for(int i=0, u, v, c; i<V; ++ i)
        {
            scanf("%d%d%d", &u, &v, &c);
            G[u].push_back(edge(v, c));
            G[v].push_back(edge(u, c));
        }
        int s, t;
        scanf("%d%d", &s, &t);
        dijkstra(s);
        if(d[t] == INF)
            printf("%d
", -1);
        else
            printf("%d
", d[t]);
    }
    return 0;
}

原文地址:https://www.cnblogs.com/aiterator/p/6944494.html