图结构练习——最短路径
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
Hint
Source
赵利强
#include <bits/stdc++.h>
using namespace std;
#define INF INT_MAX
int n, m;
int gra[111][111], cat[111], dist[111];
void Dijkstra(int k)
{
for (int i = 1; i <= n; i++) // dist数组初始化
dist[i] = gra[k][i];
dist[k] = 0; // 初始化起点
cat[k] = 1;
for (int q = 1; q <= n; q++)
{
int min = INF;
int index = k; // 记录下一个确定点的序号
for (int j = 1; j <= n; j++)
{
if (!cat[j] && dist[j] < min)
{
min = dist[j];
index = j;
}
}
cat[index] = 1;
for (int i = 1; i <= n; i++)
{
if (!cat[i] && gra[index][i] < INF && dist[i] > dist[index] + gra[index][i])
dist[i] = dist[index] + gra[index][i];
}
}
}
int main()
{
while (cin >> n >> m)
{
memset(cat, 0, sizeof(cat));
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
if (i == j)
gra[i][j] = 0;
else
gra[i][j] = INF;
}
}
int a, b, c;
for (int i = 0; i < m; i++)
{
cin >> a >> b >> c;
if (gra[a][b] > c) // 少了会wa
gra[a][b] = gra[b][a] = c;
}
if (m == 0)
cout << "0" << endl;
else
{
Dijkstra(1);
cout << dist[n] << endl;
}
}
return 0;
}
/***************************************************
User name: jk180602
Result: Accepted
Take time: 44ms
Take Memory: 260KB
Submit time: 2019-01-13 23:32:35
****************************************************/
Floyed:
#include <bits/stdc++.h>
#define INF INT_MAX
using namespace std;
int gra[105][105];
int cat[105];
int n, m;
void Floyed()
{
for (int k = 1; k <= n; k++)
{
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
if (gra[i][j] > gra[i][k] + gra[k][j])
gra[i][j] = gra[i][k] + gra[k][j];
}
}
}
}
int main()
{
while (cin >> n >> m)
{
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
if (i == j)
gra[i][j] = 0;
else
gra[i][j] = INF;
}
}
int a, b, c;
while (m--)
{
cin >> a >> b >> c;
if (gra[a][b] > c)
gra[a][b] = gra[b][a] = c;
}
Floyed();
cout << gra[1][n] << endl;
}
return 0;
}
/***************************************************
User name: jk180602
Result: Accepted
Take time: 48ms
Take Memory: 288KB
Submit time: 2019-01-18 11:34:59
****************************************************/