Question:
For an undirected graph, each vertex has an attribute that supports A or B (the attribute of point 1 is always a, and the attribute of point 2 is always B), and the shortest path of point 1 to 2 is obtained, the requested shortest path must meet the requirements: the vertices on both sides of the path have different attributes at most.
Analysis:
Use spfa for the shortest path ~~ D [v] [0] indicates that the attribute from the starting point to the V point has not changed. d [v] [1] indicates that the attribute from the starting point to the V point has changed, the final answer is Min (d [2] [0]. d [2] [1]);
Code:
//poj 3767//sep9#include <iostream>#include <queue>using namespace std;const int maxN=698;const int maxM=20024;struct Edge{int v,w,next;}edge[maxM];struct Node{int u,s;};int n,e;int head[maxN];int camp[maxN],inq[maxN][2],d[maxN][2];void addedge(int u,int v, int w){ edge[e].v=v;edge[e].w=w,edge[e].next=head[u];head[u]=e++;}void spfa(){queue<Node> Q;int i;memset(inq,0,sizeof(inq));for(i=1;i<=n;++i) d[i][0]=d[i][1]=INT_MAX; d[1][0]=0;inq[1][0]=1;Node x;x.u=1,x.s=0;Q.push(x);while(!Q.empty()){Node x=Q.front();Q.pop();int u=x.u,s=x.s;inq[u][s]=0;for(i=head[u];i!=-1;i=edge[i].next){int v=edge[i].v,w=edge[i].w;if(camp[u]==camp[v]){if(d[v][s]>d[u][s]+w){d[v][s]=d[u][s]+w;if(!inq[v][s]){Node x;x.u=v,x.s=s;inq[v][s]=1;Q.push(x);}}}else{if(s==0&&d[v][1]>d[u][0]+w){d[v][1]=d[u][0]+w;if(!inq[v][1]){Node x;x.u=v,x.s=1;inq[v][1]=1;Q.push(x);}}}}}} int main(){while(scanf("%d",&n)==1&&n){e=0;memset(head,-1,sizeof(head));int i,m;scanf("%d",&m);while(m--){int u,v,w;scanf("%d%d%d",&u,&v,&w);addedge(u,v,w);addedge(v,u,w);}for(i=1;i<=n;++i)scanf("%d",&camp[i]);int ans;spfa();ans=min(d[2][0],d[2][1]);if(ans==INT_MAX)printf("-1\n");elseprintf("%d\n",ans);}return 0;}
Poj 3767 I wanna go home shortest spfa