bfs understand --hdu6386 good questions

A queue maintenance, dfs performed for each color of the same side and connected to the recording

Note that this problem vis use to mark the edge, not markers

Because the depth of the points can be updated at any time (such an approach does not satisfy the greedy conditions)

#include<bits/stdc++.h>
using namespace std;
#define maxn 200005
#define INF 0x3f3f3f3f
struct Edge{
    int to,nxt,w,flag;
}edge[maxn<<1];
int head[maxn],tot,n,m;
void init(){memset(head,-1,sizeof head);tot=0;}
void add(int u,int v,int w){
    edge[tot].to=v;edge[tot].w=w;edge[tot].nxt=head[u];head[u]=tot++;
    edge[tot].flag=0;
}

queue<int>q;
int d[maxn];
        
void dfs(int u,int c,int deep){
    if(d[u]>deep){
        d[u]=deep;
        q.push(u);
    }    
    for(int i=head[u];i!=-1;i=edge[i].nxt){
        if(edge[i].flag)continue;
        if(edge[i].w==c){
            edge[i].flag=1;
            dfs(edge[i].to,c,deep);
        }
    }    
}        
void bfs(){
    while(q.size())q.pop();
    memset(d,0x3f,sizeof d);
    q.push(1);
    d[1]=0;
    while(q.size()){
        int u=q.front();q.pop();
        for(int i=head[u];i!=-1;i=edge[i].nxt){
            if(edge[i].flag)continue;
            int v=edge[i].to;
            edge[i].flag=1;
            dfs(v,edge[i].w,d[u]+1);
        }
    }
}



int main(){
    while(cin>>n>>m){
        memset(edge,0,sizeof edge);
        init();
        for(int i=1;i<=m;i++){
            int u,v,w;
            scanf("%d%d%d",&u,&v,&w);
            add(u,v,w);add(v,u,w);
        }
        bfs();
        if(d[n]==INF)puts("-1");
        else cout<<d[n]<<"\n";        
    }    
}

 

Guess you like

Origin www.cnblogs.com/zsben991126/p/10960509.html