1381: City Road (Dijkstra)
Time limit: 1000 ms Memory limit: 65536 KB
Number of submissions: 2710 Number of passes: 772
[Title description]
Teacher Luo was invited to a dance party, in city n, and the city where Luo is currently located is 1, and there are many nearby Cities 2~n-1, some cities do not have a directly connected road, and some cities have a directly connected road. These roads are two-way, of course there may be multiple roads.
Now given the road length of the directly adjacent cities, Mr. Luo wants to know the shortest distance from city 1 to city n.
[Input]
Input n, m, which means n cities and m roads;
The next m lines, each line abc, means that there is a road of length c between city a and city b.
[Output]
Output the shortest path from 1 to n. If 1 cannot reach n, -1 is output.
[Input sample]
5 5
1 2 20
2 3 30
3 4 20
4 5 20
1 5 100
[Output sample]
90
[Prompt]
[Data scale and convention]
1≤n≤2000
1≤m≤10000
0≤c≤10000
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
long long g[2501][2501];
long long d[2501];
bool v[2501];
int main()
{
long long n,m;
cin>>n>>m;
fill_n(d,2502,999999);
memset(g,0x7f,sizeof(g));
for(long long i=1;i<=m;i++)
{
long long x,y,z;
cin>>x>>y>>z;
g[x][y]=g[y][x]=min(z,g[x][y]);
}
d[1]=0;
for(long long i=1;i<=n;i++)
{
long long x,minn=999999;
for(long long j=1;j<=n;j++)
if(minn>=d[j]&&!v[j])
{
minn=d[j];
x=j;
}
v[x]=true;
for(long long j=1;j<=n;j++)
d[j]=min(d[j],d[x]+g[x][j]);
}
if(d[n]==999999)
cout<<-1;
else
cout<<d[n];
return 0;
}