POJ - 3159Candies差分約束+spfa

During the kindergarten days, flymouse was the monitor of his class. Occasionally the head-teacher brought the kids of flymouse’s class a large bag of candies and had flymouse distribute them. All the kids loved candies very much and often compared the numbers of candies they got with others. A kid A could had the idea that though it might be the case that another kid B was better than him in some aspect and therefore had a reason for deserving more candies than he did, he should never get a certain number of candies fewer than B did no matter how many candies he actually got, otherwise he would feel dissatisfied and go to the head-teacher to complain about flymouse’s biased distribution.
求編號1與編號n的最大差是多少。
數據量較大,直接用隊列會TLE,可以採用數組模擬隊列。
用鄰接表。

#include<queue>
#include<stdio.h>
#include<string>
#include<iostream>
#include<map>
#include<limits>
#include<math.h>

using namespace std;
#define N 150000+2
#define LL long long int
#define pow(a) ((a)*(a))
#define INF 0x3f3f3f3f
#define mem(arr,a) memset(arr,a,sizeof(arr))
struct edge{
    int to, cost, next;
};
edge es[N];
int headlist[N];
int d[N];
int vis[N];
int n, m;
int Q[N];
void spfa(){
    for (int i = 1; i <= n; i++){
        d[i] = INF;
        vis[i] = 0;
    }
    mem(Q, -1);
    int top = 0;
    d[1] = 0;
    Q[top] = 1;
    while (top >= 0){
        int u = Q[top]; top--; vis[u] = 0;
        for (int i = headlist[u]; i != -1; i = es[i].next){
            if (d[es[i].to] > d[u] + es[i].cost){
                d[es[i].to] = d[u] + es[i].cost;
                if (!vis[es[i].to]){
                    Q[++top] = es[i].to;
                    vis[es[i].to] = 1;
                }
            }
        }
    }
}
int main(){
    cin >> n >> m;
    mem(headlist, -1);
    for (int i = 0; i < m; i++){
        int a, b, c;
        scanf("%d%d%d", &a, &b, &c);
        es[i].to = b;
        es[i].cost = c;
        es[i].next = headlist[a];
        headlist[a] = i;
    }
    spfa();
    cout << d[n] << endl;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章