hdu4725(SPFA+建图技巧)

反思:巧妙的构图方式
hdu4725(SPFA+建图技巧)_第1张图片
再加上点与点之间的路径,最后再SPFA跑一下就可以了

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

using namespace std;

const int INF = 0x3f3f3f3f;
const int maxn = 300005;
const int maxm = 600010;

struct Edge
{
    int v, w, next;
    Edge(){}
    Edge(int vv, int ww, int nn) {
        v = vv;
        w = ww;
        next = nn;
    }
};

int head[maxn];
Edge e[maxm];
int dis[maxn];
int vis[maxn];
int flag[maxn];
int Level[maxn];
int m, n;
int cnt;

void Init()
{
    cnt = 1;
    memset (head, -1, sizeof(head));
    memset (vis, 0, sizeof(vis));
    memset (dis, 0x3f, sizeof(dis));
    memset (Level, 0, sizeof(Level));
    memset (flag, 0, sizeof(flag));
}

void Add(int u, int v, int w)
{
    e[cnt] = Edge(v, w, head[u]);
    head[u] = cnt++;
}

int SPFA(int u, int v)
{
    queue<int> q;
    q.push(u);
    vis[u] = 1;
    dis[u] = 0;
    while (!q.empty()) {
        int t = q.front();
        q.pop();
        vis[t] = 0;
        for (int i = head[t]; i != -1; i = e[i].next) {
            int tmp = e[i].v;
            if (dis[t] + e[i].w < dis[tmp]) {
                dis[tmp] = dis[t] + e[i].w;
                if (vis[tmp] == 0) {
                    q.push(tmp);
                    vis[tmp] = 1;
                }
            }
        }
    }
    return dis[v];
}

int main()
{
    #ifndef ONLINE_JUDGE
    freopen("in.txt", "r", stdin);
    //freopen("out.txt", "w", stdout);
    #endif // ONLINE_JUDGE
    int t;
    scanf ("%d", &t);
    for (int kase = 1; kase <= t; kase++) {
        int c;
        scanf ("%d%d%d", &n, &m, &c);
        Init ();
        for (int i = 1; i <= n; i++) {
            int l;
            scanf ("%d", &l);
            Level[i] = l;
            flag[l] = 1;
        }
        for (int i = 1; i < n; i++) {
            if (flag[i] && flag[i + 1]) {
                Add (n + i, n + i + 1, c);
                Add (n + i + 1, n + i, c);
            }
        }
        for (int i = 1; i <= n; i++) {
            int l = Level[i];
            Add (n + l, i, 0);
            if (l - 1 >= 1 && flag[l - 1]) {
                Add (i, n + l - 1, c);
            }
            if (l + 1 <= n && flag[l + 1]) {
                Add (i, n + l + 1, c);
            }
        }
        for (int i = 0; i < m; i++) {
            int u, v, w;
            scanf ("%d%d%d", &u, &v, &w);
            Add (u, v, w);
            Add (v, u, w);
        }
        int path = SPFA (1, n);
        if (path == INF) {
            path = -1;
        }
        printf ("Case #%d: %d\n", kase, path);
    }
    return 0;
}

你可能感兴趣的:(acm水题)