题目链接: vjudge
题意
就是最短路hhh
输入
第一行两个数字,分别表示边数量和点数量
后面每一行都是source targe cost。
输入样例
5 5
1 2 20
2 3 30
3 4 20
4 5 20
1 5 100
输出样例
90
解题思路
就以后写迪杰斯特拉记得要考虑重边
题解
#include <cstdio>
#include <cstring>
#include <limits>
#define Max __INT_MAX__
int dist[2000], map[2000][2000];
bool vis[2000];
int dijikstra(int n)
{
vis[1] = true;
int min, k;
for (int i = 1; i < n; i++)
{
min = Max;
for (int j = 1; j <= n; j++)
{
if (vis[j] == false && dist[j] < min)
{
min = dist[j];
k = j;
}
}
vis[k] = true;
for (int j = 1; j <= n; j++)
{
if (vis[j] == false && dist[j] > dist[k] + map[k][j] && dist[k] + map[k][j] > 0)
dist[j] = dist[k] + map[k][j];
}
}
return dist[n];
}
int main()
{
int t, n, from, to, cost;
scanf("%d %d", &t, &n);
memset(dist, 0, sizeof dist);
memset(vis, false, sizeof vis);
for (int i = 1; i <= n; i++)
{
map[i][i] = 0;
// 一次初始化两个,所以j<i
for (int j = 1; j < i; j++)
{
map[i][j] = map[j][i] = Max;
}
}
while (t--)
{
scanf("%d %d %d", &from, &to, &cost);
//重边真狠啊
if (map[from][to] > cost)
map[from][to] = map[to][from] = cost;
}
for (int i = 1; i <= n; i++)
{
dist[i] = map[1][i];
}
printf("%d", dijikstra(n));
return 0;
}