zoukankan      html  css  js  c++  java
  • 图的遍历 | 1076 bfs

    bfs踩了很多坑才写完。注意:出队时不做是否vis判断,但是要加上vis[出队顶点]=1 。入队时进行判断,并且也要 vis[入队顶点]=1

    #include <stdio.h>
    #include <memory.h>
    #include <math.h>
    #include <string>
    #include <vector>
    #include <set>
    #include <stack>
    #include <queue>
    #include <algorithm>
    #include <map>
    
    #define I scanf
    #define OL puts
    #define O printf
    #define F(a,b,c) for(a=b;a<c;a++)
    #define FF(a,b) for(a=0;a<b;a++)
    #define FG(a,b) for(a=b-1;a>=0;a--)
    #define LEN 1010
    #define MAX 0x06FFFFFF
    #define V vector<int>
    
    using namespace std;
    
    vector<int> g[LEN];
    int vis[LEN];
    
    int main(){
    //    freopen("D:\CbWorkspace\PAT\图的遍历\1076.txt","r",stdin);
        int n,l,i,j,m,a,b,t,k;
        I("%d%d",&n,&l) ;
        F(i,1,n+1){
            I("%d",&m);
            FF(j,m){
                I("%d",&t);
                g[t].push_back(i);
            }
        }
        I("%d",&k);
        FF(i,k){
            I("%d",&t);
            memset(vis,0,sizeof vis);
            queue<int> q;
            q.push(t);
            int level=0;
            int cnt=0;
            while(!q.empty()){
                int sz=q.size();
                while(sz-->0){    //每一层bfs 
                    int tmp=q.front();
                    q.pop();
    //                if(vis[tmp]) continue;    //出队防止遍历已知点 
                    vis[tmp]=1;
                    FF(j,g[tmp].size()){    //遍历后继 
                        int o=g[tmp][j];
                        if(vis[o]==0){        //入队防止遍历已知点
                            vis[o]=1;
                            q.push(o);
                            cnt++;
                        }
                    }
                }
                level++;
                if(level>=l) break;
            }
            printf("%d
    ",cnt) ;
        }
        return 0;
    }
  • 相关阅读:
    hdu 4508
    hdu 4506
    hdu 4505
    hdu 1525
    hdu 2212
    (贪心)删数问题
    (最短路 Dijkstra) hdu 1544
    (次小生成树) poj 1679
    (prim)hdu 1102
    (kruskal)hdu 1863
  • 原文地址:https://www.cnblogs.com/TQCAI/p/8513881.html
Copyright © 2011-2022 走看看