HDU - 6386 Age of Moyu (双端队列+bfs)
双端队列跑边,颜色相同的边之间的花费为0,放进队首;不同的花费为1,放进队尾。
用Dijkstra+常数优化也能过
1 #include<bits/stdc++.h> 2 using namespace std; 3 typedef long long ll; 4 const int N=4e5+10,mod=1e9+7; 5 int n,m,hd[N],ne,dp[N]; 6 struct E {int v,c,nxt;} e[N]; 7 void addedge(int u,int v,int c) {e[ne]= {v,c,hd[u]},hd[u]=ne++;} 8 deque<int> q; 9 int solve() { 10 q.clear(); 11 memset(dp,-1,sizeof dp); 12 q.push_back(ne-1),dp[ne-1]=0; 13 while(q.size()) { 14 int u=q.front(),now=dp[u],cu=e[u].c; 15 q.pop_front(); 16 if(e[u].v==n)return now; 17 for(int v=hd[e[u].v]; ~v; v=e[v].nxt) { 18 int cv=e[v].c; 19 if(!~dp[v]) { 20 if(cv==cu)dp[v]=now,q.push_front(v); 21 else dp[v]=now+1,q.push_back(v); 22 } 23 } 24 } 25 return -1; 26 } 27 int main() { 28 while(scanf("%d%d",&n,&m)==2) { 29 memset(hd,-1,sizeof hd),ne=0; 30 while(m--) { 31 int u,v,c; 32 scanf("%d%d%d",&u,&v,&c); 33 addedge(u,v,c); 34 addedge(v,u,c); 35 } 36 addedge(1,1,0); 37 printf("%d\n",solve()); 38 } 39 return 0; 40 }