POJ 1847 Tram Dijkstra模板
[题目内容]
Tram network in Zagreb consists of a number of intersections and rails connecting some of them. In every intersection there is a switch pointing to the one of the rails going out of the intersection. When the tram enters the intersection it can leave only in the direction the switch is pointing. If the driver wants to go some other way, he/she has to manually change the switch.
When a driver has do drive from intersection A to the intersection B he/she tries to choose the route that will minimize the number of times he/she will have to change the switches manually.
Write a program that will calculate the minimal number of switch changes necessary to travel from intersection A to intersection B.
[输入]
The first line of the input contains integers N, A and B, separated by a single blank character, 2 <= N <= 100, 1 <= A, B <= N, N is the number of intersections in the network, and intersections are numbered from 1 to N.
Each of the following N lines contain a sequence of integers separated by a single blank character. First number in the i-th line, Ki (0 <= Ki <= N-1), represents the number of rails going out of the i-th intersection. Next Ki numbers represents the intersections directly connected to the i-th intersection.Switch in the i-th intersection is initially pointing in the direction of the first intersection listed.
[输出]
The first and only line of the output should contain the target minimal number. If there is no route from A to B the line should contain the integer “-1”.
[样例输入]
3 2 1
2 2 3
2 3 1
2 1 2
[样例输出]
0
AC代码:
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
#define inf 99999999
using namespace std;
int n,a,b,vis[105],dis[105],map[105][105];
void dijkstra(int x)
{
memset(vis,0,sizeof(vis));
for(int i=1;i<=n;i++)
dis[i]=map[x][i];//以x为原点
for(int i=1;i<=n;i++)
{
int k=0,minn=inf;
for(int j=1;j<=n;j++)
if(vis[j]==0&&dis[j]<minn)
{
minn=dis[j];
k=j;
}
if(k==0) break;//此句很重要,因为本题可能走不通
vis[k]=1;
for(int j=1;j<=n;j++)
if(vis[j]==0&&dis[j]>dis[k]+map[k][j])
dis[j]=dis[k]+map[k][j];
}
}//最短路径问题,dijkstra算法
int main()
{
int a,b,num,t;
scanf("%d%d%d",&n,&a,&b);
for(int i=0;i<=n;i++)
for(int j=0;j<=n;j++)//这题因为有可能走不通,所以最好从0开始初始化
{
if(i==j)
map[i][j]=0;
else
map[i][j]=inf;
}//图的初始化
for(int i=1;i<=n;i++)
{
scanf("%d",&num);
for(int j=1;j<=num;j++)
{
scanf("%d",&t);
if(j==1)
map[i][t]=0;
else
map[i][t]=1;
}
}
dijkstra(a);//从a点出发
if(dis[b]>=inf)//有可能没法达到b点
printf("-1\n");
else
printf("%d\n",dis[b]);
return 0;
}
这道题因为有可能走不通(输出答案为-1),因此要注意细节否则就会导致出错。周赛的时候WA了5发也没发现问题,以后还是要更加细心。