7_4_O题 Heavy Transportation 题解[POJ 1797](Dijkstra变形)

题目链接

题意

1到n之间有一些通路,这些通路有承载力的上限,不能超过,问从1到n最多能运多重的货物。

思路

和最短路类似,只不过对Dijkstra算法进行一点小小的修改,把顶点的更新条件改为如果访问到该点了,且该点的权值小于这条路的承载力和上个点的权值中的较小值,则更新他为该值;其他不做改变,直接跑就行了。

代码

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#define INF 0x3f3f3f3f

using namespace std;
typedef long long ll;
const int maxn = 1e3+5;
const int mod = 1e9+13;

struct edge{
    int v,to,cost;
    edge(int t,int c):to(t),cost(c){};
    edge(int v, int t,int c):v(v),to(t),cost(c){};
    bool operator < (const edge & a) const{
        return cost < a.cost;
    }
};

vector  G_a[maxn];
bool vis[maxn];

void addedge(int from, int to, int cost){
    G_a[from].push_back(edge(to, cost));
    G_a[to].push_back(edge(from, cost));
}
int dis_a[maxn];

void Dijkstra(int s, int dis[]){
    for(int i = 0 ; i < s ; i ++)
        dis[i] = 0;
    dis[s] = INF;
    priority_queue Q;
    Q.push(edge(s,dis[s]));
    while(!Q.empty()){
        edge tmp = Q.top();Q.pop();
        vis[tmp.to] = 1;
        int limt = G_a[tmp.to].size();
        for(int i = 0 ; i < limt; i ++){
            edge& next = G_a[tmp.to][i];
            if(!vis[next.to] && dis[next.to] < min(tmp.cost, next.cost)){
                dis[next.to] = min(tmp.cost, next.cost);
                Q.push(edge(next.to,dis[next.to]));
            }
        }
    }
}

int main(){
    int T;
    scanf("%d", &T);
    int kas = 1;
    while(T--){
        int n,m;
        scanf("%d %d",&n,&m);
        int from, to, cos;
        memset(vis, 0 , sizeof vis);
        for(int i = 1 ; i <= n ; i ++)
            G_a[i].clear();
        for (int i = 0 ; i < m ; i ++){
            scanf("%d %d %d",&from,&to,&cos);
            addedge(from,to,cos);
        }
        Dijkstra(n,dis_a);
        printf("Scenario #%d:\n%d\n\n",kas++,dis_a[1]);
    }
    return 0;
}

你可能感兴趣的:(题解)