Dijkstra nlogn版
#include <bits/stdc++.h> #define maxn 5000005 using namespace std; struct edge { int u=0; int v=0; int w=0; int next=0; }edge[2*maxn]; int head[maxn]; int cnt=0; int n; void addedge(int u,int v,int w) { edge[cnt].u=u; edge[cnt].v=v; edge[cnt].w=w; edge[cnt].next=head[u]; head[u]=cnt++; } int dist[maxn]; priority_queue < pair<int,int>,vector < pair<int,int> >,greater<pair<int,int> > >q; void dijkstra(int s,int t) { int i,now; for(i=1;i<=n;i++) { dist[i]=0x7fffffff; } dist[s]=0; q.push(make_pair(0,s)); while(!q.empty()) { now=q.top().second; q.pop(); for(i=head[now];i!=-1;i=edge[i].next) { if(dist[now]+edge[i].w<dist[edge[i].v]) { dist[edge[i].v]=dist[now]+edge[i].w; q.push(make_pair(dist[edge[i].v],edge[i].v)); } } } } int main() { int m,t,i; scanf("%d%d%d",&n,&m,&t); memset(head,-1,sizeof(head)); for(i=0;i<m;i++) { int u,v,w; scanf("%d%d%d",&u,&v,&w); addedge(u,v,w); addedge(v,u,w); } dijkstra(1,t); cout<<dist[t]<<endl; return 0; }
#include <bits/stdc++.h> #define maxn 5000005 using namespace std; struct edge { int u; int v; int w; int next; }edge[2*maxn]; int head[maxn]; int cnt=0; int n; void addedge(int u,int v,int w) { edge[cnt].u=u; edge[cnt].v=v; edge[cnt].w=w; edge[cnt].next=head[u]; head[u]=cnt++; } int dist[maxn]; priority_queue < pair<int,int>,vector < pair<int,int> >,greater<pair<int,int> > >q; bool vis[maxn]; void dijkstra(int s) { int i,now; memset(vis,false, sizeof(vis)); memset(dist,-1, sizeof(dist)); dist[s]=0; q.push(make_pair(0,s)); while(!q.empty()) { now=q.top().second; q.pop(); if(vis[now]) continue; vis[now]=true; for(i=head[now];i!=-1;i=edge[i].next) { if((dist[now]+edge[i].w<dist[edge[i].v]||dist[edge[i].v]==-1)&&!vis[edge[i].v]) { dist[edge[i].v]=dist[now]+edge[i].w; q.push(make_pair(dist[edge[i].v],edge[i].v)); } } } } int main() { int m,t,i; //freopen("in.txt","r",stdin); scanf("%d%d%d",&n,&m,&t); memset(head,-1,sizeof(head)); for(i=0;i<m;i++) { int u,v,w; scanf("%d%d%d",&u,&v,&w); addedge(u,v,w); //addedge(v,u,w); } dijkstra(t); for(int i=1;i<=n;i++) { if(i!=1) printf(" "); if(dist[i]==-1) printf("2147483647"); else printf("%d",dist[i]); } printf("\n"); return 0; }