标签:
最朴素的做法o(n^2)
#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
#include<string>
#include<string.h>
const int MAX = 2002;
int n;
int graph[MAX][MAX];
int dis[MAX];
bool vis[MAX];
const int INF = 0X7FFFFFFF;
int dijkstra()
{
memset(vis, false, sizeof(vis));
vis[1] = true;
for (int i = 1; i <= n; i++)
dis[i] =INF;
dis[1] = 0;
for (int i = 1; i <= n; i++)
{
if (graph[i][1] != 0)
dis[i] = graph[i][1];
}
for (int i = 0; i < n-1; i++)
{
int minn = INF, position = 1;
for (int i = 1; i <= n; i++)
{
if (!vis[i] && minn>dis[i])
{
minn = dis[i];
position = i;
}
}
vis[position] = true;
for (int i = 1; i <= n; i++)
{
if (!vis[i] &&graph[i][position]!=0&&dis[i] > (dis[position] + graph[i][position]))
dis[i] = dis[position] + graph[i][position];
}
}
return dis[n];
}
int main()
{
int t;
cin >> t>> n;
memset(graph, 0, sizeof(graph));
for (int i = 0; i < t; i++)
{
int x1, y1, val;
cin >> x1 >> y1 >> val;
if (graph[x1][y1])
{
if (graph[x1][y1]>val)
graph[x1][y1] = graph[y1][x1] = val;
}
else
{
graph[x1][y1] = graph[y1][x1] = val;
}
}
cout << dijkstra() << endl;
return 0;
}
/*
5 5
1 2 20
2 3 30
3 4 20
4 5 20
1 5 100
*/
标签:
原文地址:http://www.cnblogs.com/wuxiangli/p/5625225.html