最短路模板

for(register int k=1;k<=n;k++)//Floyd for(register int i=1;i<=n;i++) for(register int j=1;j<=n;j++) dis[i][j] = min(dis[i][k]+dis[k][j] ,dis[i][j]); 
//spfa inline void add(int from,int to,int dis){ edge[++cnt].nxt=head[from]; edge[cnt].to=to; edge[cnt].dis=dis; head[from]=cnt; return ; } inline void Spfa(){ queue<int>q; for(register int i=1;i<=n;i++) dis[i]=0x7fffffff,vis[i]=0; q.push(s); dis[s]=0; vis[s]=1; while(!q.empty()){ int u=q.front(); q.pop(); vis[u]=0; for(register int i=head[u];i;i=edge[i].nxt){ int v=edge[i].to; if(dis[v]>dis[u]+edge[i].dis){ dis[v]=dis[u]+edge[i].dis; if(!vis[v]) vis[v]=1,q.push(v); } } } }
//dijkstra
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; } }; std::priority_queue<node> q; inline void dijkstra() { dis[s] = 0; q.push( ( node ) { 0, s } ); while( !q.empty() ) { node tmp = q.top(); q.pop(); int x = tmp.pos, d = tmp.dis; 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 } ); } } } } }

最短路的題目html

相關文章
相關標籤/搜索