zoukankan      html  css  js  c++  java
  • 和小哥哥一起刷洛谷(5) 图论之深度优先搜索DFS

    关于dfs

    dfs伪代码:

    void dfs(s){
        for(int i=0;i<s的出度;i++){
            if(used[i]为真) continue;
            used[i]=1;
            dfs(i);
        }
        return;
    }
    

    统计无向图的连通分量

    显然,你在洛谷上是搜不到这题的,因为这是我们学校团队的题。所以还是找个小板凳专心听我讲吧。

    题目描述:

    给定无向图G(V,E),请统计G中连通分量的数量。

    • 连通分量:结点V的一个子集V',保证V'中任意两点间都有路径
    • 需要在主循环中进行多次dfs

    输入输出格式:

    输入格式:

    第一行包含两个整数N、M,表示该图共有N个结点和M条无向边(N<= 5000,M<=200000);

    接下来M行,每行包含2个整数{u,v},表示有一条无向边(u,v)。

    输出格式:

    一个整数,代表图G连通分量的数量

    样例:

    输入:

    5 4
    1 5
    2 3
    3 4
    4 2
    

    输出:

    2
    

    代码:

    #include<cstdio>
    #include<cstdlib>
    #include<cstring>
    #include<cmath>
    #include<algorithm>
    #include<string>
    #include<iostream>
    #include<queue>
    #include<vector>
    using namespace std;
    const int NR=5005;
    bool color[NR];//used数组
    int cnt=0,n,m;
    vector<int> link[NR];
    void dfs(int a){//dfs函数
        int sz=link[a].size();
        for(int i=0;i<sz;i++){
            int nx=link[a][i];
            if(color[nx]==false){
                color[nx]=true;
                dfs(nx); 
            }
        }
        return;
    } 
    int main(){
        scanf("%d%d",&n,&m);
        for(int i=0;i<m;i++){
            int st,en;
            scanf("%d%d",&st,&en);
            link[st].push_back(en);
            link[en].push_back(st);
        }
        for(int i=1;i<=n;i++){//对于每个没有去过的点,将其所有可以到达的点标为true,计数加一,重复
            if(color[i])continue;
            color[i]=true;
            dfs(i);
            cnt++;
        }
        cout<<cnt;
        return 0;
    }
    
  • 相关阅读:
    Excel长数字防止转换为科学计数法
    SVN迁移部署
    且行且珍惜
    功能的权衡——推荐功能做不做?
    渗透小白如何学编程
    Metasploit log命令技巧
    Metasploit 使用msfconsole帮助功能技巧
    Metasploit resource命令技巧
    Metasploit makerc命令技巧
    Metasploit irb命令使用技巧
  • 原文地址:https://www.cnblogs.com/BlogE/p/luogu_day5.html
Copyright © 2011-2022 走看看