#include<algorithm>
#include<cstring>
#include<vector>
#include<map>
#include<cmath>
#include<cstdio>
#include<queue>
#include<iostream>
typedef long long ll;
const int mod = 1e9+7;
const int maxn = 1000000;
const int inf = 0x3f3f3f3f;
using namespace std;
/*dij堆优化*/
struct edge
{
int to, dis, next;
};
edge e[maxn];
int head[maxn], dis[maxn], cnt;
bool vis[maxn];
int n, m, s;
inline void add_edge( int u, int v, int d )
{
cnt++;
e[cnt].dis = d;
e[cnt].to = v;
e[cnt].next = head[u];
head[u] = cnt;
}
struct node
{
int dis;
int pos;
bool operator <( const node &x )const
{
return x.dis < dis;
}
};
priority_queue<node> q;
inline void dijkstra(int start)
{
dis[s] = 0;
q.push( ( node ){0, s} );
while( !q.empty() )
{
node tmp = q.top();
q.pop();
int x = tmp.pos ;
if( vis[x] )
continue;
vis[x] = 1;
for( int i = head[x]; i; i = e[i].next )
{
int y = e[i].to;
if( dis[y] > dis[x] + e[i].dis )
{
dis[y] = dis[x] + e[i].dis;
if( !vis[y] )
{
q.push( ( node ){dis[y], y} );
}
}
}
}
}
int main()
{
cin>>n>>m>>s;
for(int i = 1; i <= n; ++i)dis[i] = inf;
for( register int i = 0; i < m; ++i )
{
register int u, v, d;
cin>>u>>v>>d; // u起点 v终点 d权重
add_edge( u, v, d );
}
dijkstra(s); //s为起点,dis[i]为 从起点到 i的最短路
for( int i = 1; i <= n; i++ )
cout<<dis[i]<<" ";
cout<<endl;
return 0;
}
多组输入的初始化问题
HDU 1874
#include<algorithm>
#include<cstring>
#include<vector>
#include<map>
#include<cmath>
#include<cstdio>
#include<queue>
#include<iostream>
typedef long long ll;
const int mod = 1e9+7;
const int maxn = 1000000;
const int inf = 0x3f3f3f3f;
using namespace std;
/*dij堆优化*/
struct edge
{
int to, dis, next;
};
edge e[maxn] = {0,0,0};
int head[maxn], dis[maxn], cnt;
bool vis[maxn];
int n, m, s;
inline void add_edge( int u, int v, int d )
{
cnt++;
e[cnt].dis = d;
e[cnt].to = v;
e[cnt].next = head[u];
head[u] = cnt;
}
struct node
{
int dis;
int pos;
bool operator < ( const node &x )const
{
return x.dis < dis;
}
};
priority_queue<node> q;
void init()
{
cnt = 0;
memset(head,0,sizeof(head));
memset(vis,0,sizeof(vis));
memset(dis,inf,sizeof(dis));
memset(e,0,sizeof(e));
}
inline void dijkstra(int start)
{
dis[start] = 0;
q.push( ( node ){0, start} );
while( !q.empty() )
{
node tmp = q.top();
q.pop();
int x = tmp.pos ;
if( vis[x] )
continue;
vis[x] = 1;
for( int i = head[x]; i; i = e[i].next )
{
int y = e[i].to;
if( dis[y] > dis[x] + e[i].dis )
{
dis[y] = dis[x] + e[i].dis;
if( !vis[y] )
{
q.push( ( node ){dis[y], y} );
}
}
}
}
}
int main()
{
while(scanf("%d %d",&n,&m)!=EOF)
{
init();
int S,T;
for(int i = 0; i <= n; ++i)dis[i] = inf;//初始化从0开始
for( register int i = 0; i < m; ++i )
{
register int u, v, d;
cin>>u>>v>>d; // u起点 v终点 d权重
add_edge( u, v, d );
add_edge( v, u, d );
}
cin>>S>>T;
dijkstra(S);
if(dis[T]!=inf)
cout<<dis[T]<<endl;
else
cout<<-1<<endl;
}
return 0;
}