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;
    }

  • 相关阅读:
    030-PHP日期查询函数
    029-PHP取随机数
    028-PHP常用数学函数abs和acos和asin
    027-PHP编码和解码函数base64
    026-PHP常用字符串函数(三)
    025-PHP常用字符串函数(二)
    024-PHP常用字符串函数(一)
    023-PHP常用数组函数
    022-PHP数组排序asort
    021-PHP常用的数值类型判断函数
  • 原文地址:https://www.cnblogs.com/rainydays/p/2207707.html
Copyright © 2011-2022 走看看