zoukankan      html  css  js  c++  java
  • POJ 2387 Til the Cows Come Home

    思路:Dijkstra, bellman-ford和spfa,但是用dijkstra要考虑重边

     1 #include <iostream>
     2 #include <cstring>
     3 #include <algorithm>
     4 #include <stack>
     5 #include <cstdio>
     6 #include <queue>
     7 #define MAXVERTEXNUM 1010
     8 #define INF 99999999
     9 #define ERROR -1
    10 using namespace std;
    11 
    12 int MGraph[MAXVERTEXNUM][MAXVERTEXNUM];
    13 int dist[MAXVERTEXNUM];
    14 int Nv, Ne;
    15 int collected[MAXVERTEXNUM];
    16 
    17 int FindMinDist()
    18 {
    19     int MinDist = INF;
    20     int MinV;
    21     for (int i = 1; i < Nv; ++i)
    22     {
    23         if (!collected[i] && dist[i] < MinDist)
    24         {
    25             MinDist = dist[i];
    26             MinV = i;
    27         }
    28     }
    29     if (MinDist != INF)
    30         return MinV;
    31     return ERROR;
    32 }
    33 
    34 void Dijkstra()
    35 {
    36     memset(collected, 0, sizeof(collected));
    37 
    38     int start = Nv;
    39     //init start
    40     dist[start] = 0;
    41     collected[start] = 1;
    42     for (int i = 1; i < Nv; ++i)//start did not need to involve
    43     {
    44         dist[i] = MGraph[i][start];
    45     }
    46 
    47     while (true)
    48     {
    49         int V = FindMinDist();
    50         if (V == ERROR)
    51             break;
    52         collected[V] = 1;
    53         for (int i = 1; i < Nv; ++i)
    54         {
    55             if (!collected[i] && dist[V] + MGraph[V][i] < dist[i])//&& MGraph[V][i] != INF
    56                     dist[i] = dist[V] + MGraph[V][i];
    57         }
    58     }
    59 }
    60 
    61 int main()
    62 {
    63     ios::sync_with_stdio(false);
    64     cin >> Ne >> Nv;
    65 
    66     //init
    67     for (int i = 1; i <= Nv; ++i)
    68     {
    69         for (int j = 1; j <= Nv; ++j)
    70         {
    71             MGraph[i][j] = INF;
    72         }
    73     }
    74 
    75 
    76     for (int i = 0; i < Ne; ++i)
    77     {
    78         int V1, V2, E;
    79         cin >> V1 >> V2 >> E;
    80         if (MGraph[V1][V2] > E)
    81         {
    82             MGraph[V1][V2] = E;
    83             MGraph[V2][V1] = E;
    84         }
    85     }
    86 
    87     Dijkstra();
    88     cout << dist[1] << endl;
    89 
    90     return 0;
    91 }
  • 相关阅读:
    8.2.8 A Simple Game
    8.2.7 Be the Winner
    8.2.6 John
    8.2.5 kiki's game
    8.2.2 Good Luck in CET-4 Everybody!
    8.2.4 悼念512汶川大地震遇难同胞——选拔志愿者
    8.1.8 Team Queue
    8.2.1 Brave Game
    8.1.7 愚人节的礼物
    8.1.6 Windows Message Queue
  • 原文地址:https://www.cnblogs.com/ducklu/p/9175601.html
Copyright © 2011-2022 走看看