Codeforces 659E New Reform【DFS】

题目链接:

http://codeforces.com/problemset/problem/659/E

题意:

给定n个点和m条双向边,将双向边改为单向边,问无法到达的顶点最少有多少个?

分析:

无法到达的话即入度为0。
DFS判断每一个连通块中是否存在环,如果存在环,就能保证环中每个点的入度都大于等于1。否则,有头有尾,头的入度为0。

代码:

#include<cstdio>
#include<queue>
#include<cstring>
#include<iostream>
#include<vector>
using namespace std;
const int maxn = 1e5 + 5;
vector<int>v[maxn];
int vis[maxn];
int ans;
void dfs(int now, int pre)
{
    if(vis[now]) {ans = 0;return;}
    vis[now] = 1;
    for(int i = 0; i < v[now].size(); i++){
        if(v[now][i] != pre)
             dfs(v[now][i], now);
    }
}
int main (void)
{
    int n, m;scanf("%d%d", &n,&m);
    int a, b;
    for(int i = 0; i < m; i++){
        scanf("%d%d", &a, &b);
        v[a].push_back(b);
        v[b].push_back(a);
   }
   memset(vis, 0, sizeof(vis));
   int res = 0;
   for(int i = 1; i <= n; i++){
       if(vis[i]) continue;
       ans = 1;
       dfs(i, 0);
       res += ans;
   }
   printf("%d
", res);
   return 0;
}
原文地址:https://www.cnblogs.com/Tuesdayzz/p/5758682.html