标签:col mes std 建图 return bool ons queue print
题意:给出一张有向图,求原点到所有点的最短路和所有点到原点的最短路的距离之和
解法:反向建图+spfa
#include<iostream> #include<cstdio> #include<cstring> #include<queue> using namespace std; const int MAXP=1000005,MAXQ=1000005; struct Edge{int next,to,dis;}edge[MAXQ][2]; int n,p,q,head[MAXP][2],n_e[2],dis[MAXP][2]; bool vis[MAXP][2]; void spfa(int bgn,int x); void init(); void addedge(int from,int to,int dis,int x); int main() { scanf("%d",&n); for(int k=1;k<=n;k++) { int ans=0,u,v,w; init(); scanf("%d%d",&p,&q); for(int i=1;i<=q;i++) { scanf("%d%d%d",&u,&v,&w); addedge(u,v,w,1); addedge(v,u,w,0); } spfa(1,1); spfa(1,0); for(int i=2;i<=p;i++) ans+=dis[i][1]+dis[i][0]; printf("%d\n",ans); } return 0; } void addedge(int from,int to,int dis,int x) { edge[++n_e[x]][x].next=head[from][x]; edge[n_e[x]][x].to=to; edge[n_e[x]][x].dis=dis; head[from][x]=n_e[x]; } void init() { memset(vis,0,sizeof(vis)); memset(head,0,sizeof(head)); memset(edge,0,sizeof(edge)); memset(dis,0x7f,sizeof(dis)); } void spfa(int bgn,int x) { int u,v; queue<int> q; q.push(bgn); dis[bgn][x]=0; vis[bgn][x]=1; while(!q.empty()) { u=q.front(); q.pop(); vis[u][x]=0; for(int i=head[u][x];i;i=edge[i][x].next) { v=edge[i][x].to; if(dis[v][x]>dis[u][x]+edge[i][x].dis) { dis[v][x]=dis[u][x]+edge[i][x].dis; if(!vis[v][x]) { vis[v][x]!=vis[v][x]; q.push(v); } } } } }
标签:col mes std 建图 return bool ons queue print
原文地址:https://www.cnblogs.com/nenT/p/11621566.html