图结构练习——最短路径
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
给定一个带权无向图,求节点1到节点n的最短路径。
Input
输入包含多组数据,格式如下。
第一行包括两个整数n m,代表节点个数和边的个数。(n<=100)
剩下m行每行3个正整数a b c,代表节点a和节点b之间有一条边,权值为c。
Output
每组输出占一行,仅输出从1到n的最短路径权值。(保证最短路径存在)
Sample Input
3 2
1 2 1
1 3 1
1 0
Sample Output
1
0
Floyd算法:
#include<bits/stdc++.h>
#define Maxn 0x3f3f3f3f
using namespace std;
int Map[201][201], vis[201];
int n, m;
void Floyd()
{
for(int k = 1; k <= n; k++)
{
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= n; j++)
{
if(Map[i][j] > (Map[i][k] + Map[k][j]))
Map[i][j] = Map[i][k] + Map[k][j];
}
}
}
}
int main()
{
while(cin >> n >> m)
{
int a, b, c;
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= n; j++)
{
if(i == j)
Map[i][j] = 0;
else
Map[i][j] = Maxn;
}
}
for(int i = 0; i < m; i++)
{
cin >> a >> b >> c;
if(Map[a][b] > c)
{
Map[a][b] = Map[b][a] = c;
}
}
Floyd();
cout << Map[1][n] << endl;
}
return 0;
}
Dijkstra算法:
#include <iostream>
#include <queue>
#define INF 999999
#define ERROR -1
using namespace std;
int n, m, s, d;
int Map[1001][1001];
int Min, i, j;
int V, W;
bool collected[1001];
int dist[1001];
int FindMinDist( )
{
Min = INF;
for(i=1; i<=n; i++)
if( !collected[i] && dist[i] < Min )
{
Min = dist[i];
V = i;
}
if( Min == INF )
V = ERROR;
return V;
}
void Dijkstra( int s )
{
dist[s] = 0;
while(1)
{
V = FindMinDist( );
if( V == ERROR )
break;
collected[V] = true;
for( W=1; W<=n; W++ )
if( collected[W] == false && Map[V][W] < INF )
{
if( dist[V] + Map[V][W] < dist[W] )
{
dist[W] = dist[V] + Map[V][W];
}
}
}
}
int main()
{
while(cin >> n >> m)
{
int a, b, c;
for( i = 1; i <= n; i++)
{
for( j = 1; j <= n; j++)
{
if(i == j)
Map[i][j] = 0;
else
Map[i][j] = INF;
}
}
for(i=1; i<=n; i++)
{
dist[i] = INF;
collected[i] = false;
}
for( i = 1; i <= m; i++ )
{
cin >> a >> b >> c;
if(Map[a][b] > c)
{
Map[a][b] = Map[b][a] = c;
}
}
Dijkstra(1);
cout << dist[n] << endl;
}
return 0;
}
关于这两种算法:最短路径 Dijkstra算法 AND Floyd算法