• Dijkstra算法示例程序_1


    好几天不写程序的结果就是以前的东西都忘得差不多了……o(╯□╰)o

     1 #include <iostream>
     2 #include <cstdio>
     3 #include <cstdlib>
     4 #include <cstring>
     5 #include <cctype>
     6 #include <stack>
     7 #include <queue>
     8 #include <map>
     9 #include <set>
    10 #include <vector>
    11 #include <cmath>
    12 #include <algorithm>
    13 #define lson l, m, rt<<1
    14 #define rson m+1, r, rt<<1|1
    15 using namespace std;
    16 typedef long long int LL;
    17 const int MAXN =  0x7fffffff;
    18 const int  MINN =  -0x7fffffff;
    19 const double eps = 1e-9;
    20 const int dir[8][2] = {{0,1},{1,0},{0,-1},{-1,0},{-1,1},
    21   {1,1},{1,-1},{-1,-1}};
    22 const int MAX = 20;
    23 int S[MAX], dist[MAX], path[MAX], edge[MAX][MAX];
    24 int n;
    25 void Dijkstra(int v0) {
    26   int i, j, k;
    27   for (i = 0; i <n ; ++i) {
    28     dist[i] = edge[v0][i]; S[i] = 0;
    29     if (i != v0 && edge[v0][i] != MAXN) path[i] = v0;
    30     else path[i] = -1;
    31   }
    32   S[v0] = 1; dist[v0] = 0;
    33   for (i = 0; i < n - 1; ++i) {
    34     int Min = MAXN, u = v0;
    35     for (j = 0; j < n; ++j) {
    36       if (dist[j] < Min && S[j] == 0) {
    37         Min = dist[j]; u = j;
    38       }
    39     }
    40     S[u] = 1;
    41     for (j = 0; j < n; ++j) {
    42       if (S[j] == 0 && edge[u][j] != MAXN) {
    43         int tmp = edge[u][j] + dist[u];
    44         if (tmp < dist[j]) {
    45           dist[j] = tmp; path[j] = u;
    46         }
    47       }
    48     }
    49   }
    50 }
    51 int main(void){
    52 #ifndef ONLINE_JUDGE
    53   freopen("dijkstra.in", "r", stdin);
    54 #endif
    55   scanf("%d", &n);
    56   int u, v, w, i, j, k;
    57   memset(edge, 0, sizeof(edge));
    58   while (1) {
    59     scanf("%d%d%d", &u, &v, &w);
    60     if (u == -1 && v == -1 && w == -1) break;
    61     edge[u][v] = w;
    62   }
    63   for (i = 0; i < n; ++i) {
    64     for (j = 0; j < n; ++j) {
    65       if (i == j) edge[i][j] = 0;
    66       else if (edge[i][j] == 0) edge[i][j] = MAXN;
    67     }
    68   }
    69   Dijkstra(0);
    70   for (i = 1; i < n; ++i) {
    71     printf("%d\t", dist[i]);
    72     int Shortest[MAX]; k = 0;
    73     Shortest[k] = i; int po = path[i];
    74     while (po != -1) {
    75       Shortest[++k] = po; po = path[po];
    76     }
    77     for (j = k; j > 0; --j) {
    78       printf("%d->", Shortest[j]);
    79     }
    80     printf("%d\n", Shortest[0]);
    81   }
    82 
    83   return 0;
    84 }

    这次遇到的问题就是edge的初始化位置写错了,调好久。。

  • 相关阅读:
    memcache
    memcache 杂记
    mysql_函数
    MySQL_存储过程
    MySQL_视图
    mysql _触发器
    MySQL_优化
    mysql_索引
    R语言编程艺术_第六章_因子和表
    Bioinfo:学习Python,做生信PartII 学习笔记
  • 原文地址:https://www.cnblogs.com/liuxueyang/p/3072477.html
Copyright © 2020-2023  润新知