图论判环模板

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

using namespace std;
const int MAX = 1e5 + 5;
int n, m, flag;
vector v[MAX];
int vis[MAX];

inline void file()
{
    freopen("D:\\go.txt", "r", stdin);
    freopen("D:\\leave.txt", "w", stdout);
}

void dfs(int id, int fa)
{
    if (vis[id])
    {
        flag = 1;
        return ;
    }
    int lenth = v[id].size();
    vis[id] = 1;
    for (int i = 0; i < lenth; ++i)
    {
        if (v[id][i] == fa)
            continue;
        dfs(v[id][i], id);
    }
}

int main()
{
    //file();
    scanf("%d%d", &n, &m);
    int f, t;
    while (m--)
    {
        scanf("%d%d", &f, &t);
        v[f].push_back(t);
        v[t].push_back(f);
    }
    int res = 0;
    for (int i = 1; i <= n; ++i)
    {
        flag = 0;
        if (vis[i] == 0)
        {
            dfs(i, -1);
            if (!flag)
            res++;
        }

    }
    printf("%d\n", res);
    return 0;
}

你可能感兴趣的:(图论判环模板)