poj 2387 简单的dijkstra运用
2013-12-14 20:05
387 查看
题意: 给出n 个农场 , 和t条双向路径 , 求从农场1 到 你的最短距离?
出题人有意思 , 输入时 ,题目先输入 t , 再输入 n
#include
#include
#include
#include
using namespace std;
#define max(u , v) (u)>(v)?(u):(v)
#define min(u , v)
(u)<(v)?(u):(v)
const int INF = 0xfffffff;
const int maxn = 2010;
int grap[maxn][maxn] , dist[maxn] , pre[maxn];
int n , m ;
void init()
{
int i ,
j;
for(i = 1; i
<= n; i++)
for(j = 1; j
<= n; j++)
grap[i][j] =
INF;
memset(pre ,
0 , sizeof(pre));
}
void dijkstra()
{
int i ,
j;
for(i = 1; i
<= n; i++)
dist[i] =
grap[1][i];
pre[1] =
1;
int x =
1;
for(j = 1; j
< n; j++)
{
int maxs
=INF;
for(i = 1; i
<= n; i++)
if(!pre[i]
&& maxs > dist[i])
{
maxs =
dist[i];
x = i;
}
pre[x] =
1;
//
cout<<dist
<<endl;
for(i = 1; i
<= n; i++)
if(!pre[i]
&& (grap[x][i]+dist[x]) < dist[i] )
dist[i] =
grap[x][i] + dist[x];
}
}
int main()
{
while(scanf("%d %d" , &m , &n) != EOF)
{
init();
int i , x ,
y , z;
for(i = 0; i
< m; i++)
{
scanf("%d %d
%d" , &x , &y , &z);
if(grap[x][y] > z)
grap[x][y] =
grap[y][x] = z;
}
dijkstra();
cout<<dist
<<endl;
}
return
0;
}
出题人有意思 , 输入时 ,题目先输入 t , 再输入 n
#include
#include
#include
#include
using namespace std;
#define max(u , v) (u)>(v)?(u):(v)
#define min(u , v)
(u)<(v)?(u):(v)
const int INF = 0xfffffff;
const int maxn = 2010;
int grap[maxn][maxn] , dist[maxn] , pre[maxn];
int n , m ;
void init()
{
int i ,
j;
for(i = 1; i
<= n; i++)
for(j = 1; j
<= n; j++)
grap[i][j] =
INF;
memset(pre ,
0 , sizeof(pre));
}
void dijkstra()
{
int i ,
j;
for(i = 1; i
<= n; i++)
dist[i] =
grap[1][i];
pre[1] =
1;
int x =
1;
for(j = 1; j
< n; j++)
{
int maxs
=INF;
for(i = 1; i
<= n; i++)
if(!pre[i]
&& maxs > dist[i])
{
maxs =
dist[i];
x = i;
}
pre[x] =
1;
//
cout<<dist
<<endl;
for(i = 1; i
<= n; i++)
if(!pre[i]
&& (grap[x][i]+dist[x]) < dist[i] )
dist[i] =
grap[x][i] + dist[x];
}
}
int main()
{
while(scanf("%d %d" , &m , &n) != EOF)
{
init();
int i , x ,
y , z;
for(i = 0; i
< m; i++)
{
scanf("%d %d
%d" , &x , &y , &z);
if(grap[x][y] > z)
grap[x][y] =
grap[y][x] = z;
}
dijkstra();
cout<<dist
<<endl;
}
return
0;
}
相关文章推荐
- poj 1135 有点弯的最短路运用
- poj 1079 判断最…
- poj 1258 简单的prim算法运用
- poj 2031 简单的kruskal算法运用
- poj1823,3667
- poj 1465 一题非常经典的bfs题
- hdu 1026 简单的bfs
- hdu1728 很有难度的bfs…
- poj 1733 并查集+偏移向…
- poj 1182 并查集经典题…
- poj 1611 并查集训练
- poj 1703 并查集的拓展
- HDU 4277 USACO ORZ
- poj 1836 最长增长序列的变形
- 集合中子集的生成算法
- poj 1742
- LA 4726 Average
- 动态规划求 最长递增子序列
- 01背包和完全背包比较容易忽略的地…
- Distant Galaxy poj 3141