题目链接
对于每一个联通块, 如果有一个强连通分量, 那么这个联通块对答案的贡献就是0。 否则对答案贡献是1.
#include <iostream>
#include <vector>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <complex>
#include <cmath>
#include <map>
#include <set>
#include <string>
#include <queue>
#include <stack>
#include <bitset>
using namespace std;
#define pb(x) push_back(x)
#define ll long long
#define mk(x, y) make_pair(x, y)
#define lson l, m, rt<<1
#define mem(a) memset(a, 0, sizeof(a))
#define rson m+1, r, rt<<1|1
#define mem1(a) memset(a, -1, sizeof(a))
#define mem2(a) memset(a, 0x3f, sizeof(a))
#define rep(i, n, a) for(int i = a; i<n; i++)
#define fi first
#define se second
typedef complex <double> cmx;
typedef pair<int, int> pll;
const double PI = acos(-1.0);
const double eps = 1e-8;
const int mod = 1e9+7;
const int inf = 1061109567;
const int dir[][2] = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };
const int maxn = 1e5+5;
int num, head[maxn], s[maxn], ok[maxn], dfn[maxn], low[maxn];
int instack[maxn], st[maxn], vis[maxn], deep, cnt, top;
struct node
{
int to, nextt;
}e[maxn*2];
void add(int u, int v) {
e[num].to = v, e[num].nextt = head[u], head[u] = num++;
}
void tarjan(int u, int fa) {
dfn[u] = low[u] = ++deep;
st[++top] = u;
instack[u] = 1;
for(int i = head[u]; ~i; i = e[i].nextt) {
int v = e[i].to;
if(v == fa)
continue;
if(!dfn[v]) {
tarjan(v, u);
low[u] = min(low[u], low[v]);
} else if(instack[v]) {
low[u] = min(low[u], dfn[v]);
}
}
if(dfn[u] == low[u]) {
++cnt;
int v;
do {
v = st[top--];
instack[v] = 0;
s[v] = cnt;
} while(u != v);
}
}
int bfs(int u) {
queue <int> q;
q.push(u);
vis[u] = 1;
int flag = 0;
while(!q.empty()) {
u = q.front(); q.pop();
if(ok[u])
flag = 1;
for(int i = head[u]; ~i ; i = e[i].nextt) {
int v = e[i].to;
if(vis[v])
continue;
q.push(v);
vis[v] = 1;
}
}
return !flag;
}
pll ed[maxn];
int main()
{
int n, m;
cin>>n>>m;
mem1(head);
for(int i = 0; i < m; i++) {
scanf("%d%d", &ed[i].fi, &ed[i].se);
add(ed[i].fi, ed[i].se);
add(ed[i].se, ed[i].fi);
}
for(int i = 1; i <= n; i++)
if(!dfn[i])
tarjan(i, 0);
num = 0;
mem1(head);
for(int i = 0; i < m; i++) {
int u = s[ed[i].fi], v = s[ed[i].se];
if(u == v) {
ok[u] = 1;
continue;
}
add(u, v);
add(v, u);
}
int ans = 0;
for(int i = 1; i <= cnt; i++) {
if(!vis[i]) {
ans += bfs(i);
}
}
cout<<ans<<endl;
return 0;
}