Problem Description
Problem Analysis
Used the most basic version of Dijkstra’s algorithm
Still pretty rusty with it…
A very simple Shortest Path problem
All that background the statement gives…
is really just the weight of each road
and then find the Shortest Path from 1 to N
Note that there can be duplicate edges, so add a check to keep the smallest weight
Multiple test cases…
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
| #include<stdio.h>
int e[1200][1200],dis[1200];
int main() {
int inf=999999;
int T,n;
while(scanf("%d %d",&T,&n)!=EOF) {
for(int i=1; i<=n; i++) {
for(int j=1; j<=n; j++) {
if(i==j)
e[i][j]=0;
else
e[i][j]=inf;
}
}
while(T--) {
int x,y,t;
scanf("%d %d %d",&x,&y,&t);
if(e[x][y]>t)
e[x][y]=e[y][x]=t;
}
for(int i=1; i<=n; i++)
dis[i]=e[1][i];
bool flag[1200];
for(int i=2; i<=n; i++)
flag[i]=false;
flag[1]=true;
for(int i=1; i<=n; i++) {
int min=inf,tj;
for(int j=1; j<=n; j++) {
if(!flag[j]&&dis[j]<min) {
min=dis[j];
tj=j;
}
}
flag[tj]=true;
for(int k=1; k<=n; k++) {
if(e[tj][k]<inf) {
if(dis[k]>dis[tj]+e[tj][k])
dis[k]=dis[tj]+e[tj][k];
}
}
}
printf("%d\n",dis[n]);
}
return 0;
}
|
Problem address: 【POJ】Til the Cows Come Home