[Usaco2009 Dec] 过路费

[题目链接]

        https://www.luogu.org/problemnew/show/P2966

[算法]

        SPFA最短路

        时间复杂度 : O(N ^ 2)

[代码]

        

#include<bits/stdc++.h>
using namespace std;
#define MAXN 510
#define MAXM 10010
typedef long long LL;
const int INF = 1e9;

struct edge
{
    int to , w , nxt;
} e[MAXM << 1];

int n , m , q , tot;
int a[MAXN] , head[MAXN];
LL dist[MAXN][MAXN];
bool inq[MAXN];

template <typename T> inline void chkmax(T &x,T y) { x = max(x,y); }
template <typename T> inline void chkmin(T &x,T y) { x = min(x,y); }
template <typename T> inline void read(T &x)
{
    T f = 1; x = 0;
    char c = getchar();
    for (; !isdigit(c); c = getchar()) if (c == '-') f = -f;
    for (; isdigit(c); c = getchar()) x = (x << 3) + (x << 1) + c - '0';
    x *= f;
}
inline void addedge(int u , int v , int w)
{
    ++tot;
    e[tot] = (edge){v , w , head[u]};
    head[u] = tot;
}
inline void spfa(int id , int s)
{
    queue< int > que;
    memset(inq , false , sizeof(inq)); 
    que.push(s);
    while (!que.empty())
    {
        int cur = que.front();
        que.pop();
        inq[cur] = false;
        for (int i = head[cur]; i; i = e[i].nxt)
        {
            int v = e[i].to , w = e[i].w;
            if (dist[id][cur] + w < dist[id][v] && a[v] <= a[id])
            {
                dist[id][v] = dist[id][cur] + w;
                if (!inq[v])
                {
                    inq[v] = true;
                    que.push(v);
                }
            }
        }
    }
}

int main()
{
    
    read(n); read(m); read(q);
    for (int i = 1; i <= n; i++) read(a[i]);
    for (int i = 1; i <= m; i++)
    {
        int u , v , w;
        read(u); read(v); read(w);
        addedge(u , v , w);
        addedge(v , u , w);    
    }
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= n; j++)
        {
            dist[i][j] = INF;    
        }    
    }
    for (int i = 1; i <= n; i++)
    {
        dist[i][i] = 0;
        spfa(i , i);    
    }
    while (q--)
    {
        int x , y;
        read(x); read(y);
        LL ans = INF;
        for (int i = 1; i <= n; i++) chkmin(ans , dist[i][x] + dist[i][y] + a[i]);
        printf("%lld
" , ans);    
    }
    
    return 0;
}
原文地址:https://www.cnblogs.com/evenbao/p/9870326.html