zoukankan      html  css  js  c++  java
  • poj3767

    最短路

    View Code
    #include <iostream>
    #include <cstdlib>
    #include <cstring>
    #include <cstdio>
    using namespace std;

    #define maxn 605
    #define maxm 10005
    #define inf 0x3f3f3f3f

    struct Edge
    {
    int v, next, w;
    }edge[maxm * 2];

    int n, m;
    int id[maxn];
    int ecount, head[maxn];
    int lowcost[maxn];
    bool vis[maxn];

    void addedge(int a, int b, int w)
    {
    edge[ecount].v = b;
    edge[ecount].next = head[a];
    edge[ecount].w = w;
    head[a] = ecount++;
    }

    void input()
    {
    scanf("%d", &m);
    ecount = 0;
    memset(head, -1, sizeof(head));
    for (int i = 0; i < m; i++)
    {
    int a, b, w;
    scanf("%d%d%d", &a, &b, &w);
    a--;
    b--;
    addedge(a, b, w);
    addedge(b, a, w);
    }
    for (int i = 0; i < n; i++)
    scanf("%d", &id[i]);
    }

    void dijkstra()
    {
    memset(vis, 0, sizeof(vis));
    for (int i = 0; i < n; i++)
    lowcost[i] = inf;
    vis[0] = true;
    lowcost[0] = 0;
    int u = 0;
    while (~u)
    {
    for (int i = head[u]; ~i; i = edge[i].next)
    {
    int v = edge[i].v;
    if (vis[v])
    continue;
    if (id[u] != id[0] && id[v] == id[0])
    continue;
    lowcost[v] = min(lowcost[v], lowcost[u] + edge[i].w);
    }
    u = -1;
    int low = inf;
    for (int i = 0; i < n; i++)
    if (!vis[i] && lowcost[i] < low)
    {
    low = lowcost[i];
    u = i;
    }
    vis[u] = true;
    }
    }

    int main()
    {
    //freopen("t.txt", "r", stdin);
    while (scanf("%d", &n), n)
    {
    input();
    dijkstra();
    if (lowcost[1] == inf)
    printf("-1\n");
    else
    printf("%d\n", lowcost[1]);
    }
    return 0;
    }

  • 相关阅读:
    CF1070F Debate
    P3502 [POI2010]CHO-Hamsters
    CF1421A XORwice
    P2073 送花
    树链剖分边权转化为点权
    球——数学分析,模型构建
    数位dp的模版
    不要62
    智慧题——规律题
    CF551C GukiZ hates Boxes——模拟加二分
  • 原文地址:https://www.cnblogs.com/rainydays/p/2207707.html
Copyright © 2011-2022 走看看