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

  • 相关阅读:
    异常:java.io.IOException: Too many open files:
    转载 Servlet3.0中使用注解配置Servle
    Spring 源码从github导入源码到idea2016
    git 命令
    常用linux命令
    mysql优化常用语句
    mysql中in、not in、exists和not exists的区别
    mysql优化
    php常用的数据结构算法
    算法(一)
  • 原文地址:https://www.cnblogs.com/rainydays/p/2207707.html
Copyright © 2011-2022 走看看