Forest Program
[Link](Problem - F - Codeforces)
题意
给你一个图,你可以砍点一些边,问你有多少种砍法使得这个图变成一个森林。
题解
因为最后要变成一个森林才合法,所以就等价于最后变成一个无环的图,就是说环一定要至少砍掉其中一条边,对于不在环上的边砍或不砍都可以。环上的每一个边都有砍与不砍两种情况,一个环有n条边则一共有 2 n 2^n 2n种砍法,去掉都不砍的情况一共有 2 n − 1 2^n - 1 2n−1中砍法,非环上的边假设有m条则一共有 2 m 2^m 2m种砍法,答案符合乘法原理。
我们可以用dfs找环,每个点只被遍历一次,当二次搜到这个点的时候就证明一定是个环,然后给每个点赋一个时间戳,第二次 - 第一个次的时间戳就可以算出这个环的长度。为了防止死循环,遍历过的边打个标记保证只被遍历一次。
Code
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <set>
#include <queue>
#include <vector>
#include <map>
#include <bitset>
#include <unordered_map>
#include <cmath>
#include <stack>
#include <iomanip>
#include <deque>
#include <sstream>
#define x first
#define y second
using namespace std;
typedef long double ld;
typedef long long LL;
typedef pair<int, int> PII;
typedef pair<double, double> PDD;
typedef unsigned long long ULL;
const int N = 3e5 + 10, M = 1e6 + 10, INF = 0x3f3f3f3f, mod = 998244353;
const double eps = 1e-8;
int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};
int h[N], e[M], ne[M], w[M], idx;
void add(int a, int b, int v = 0) {
e[idx] = b, w[idx] = v, ne[idx] = h[a], h[a] = idx ++;
}
int n, m, k;
LL res = 1;
bool st[N], ok[M];
int dfn[N];
int sum, p;
LL qmi(LL a, LL b, LL p) {
LL res = 1;
while (b) {
if (b & 1) res = res * a % p;
a = a * a % p;
b >>= 1;
}
return res;
}
void dfs(int u, int fa, int dep) {
st[u] = true, dfn[u] = dep;
for (int i = h[u]; ~i; i = ne[i]) {
int j = e[i];
if (ok[i] || j == fa) continue;
sum ++;
ok[i] = ok[i ^ 1] = true;
if (st[j] && dep > dfn[j]) {
res = res * (qmi(2, dep - dfn[j] + 1, mod) - 1) % mod;
p += dep - dfn[j] + 1;
}
if (!st[j]) dfs(j, u, dep + 1);
}
}
int main() {
ios::sync_with_stdio(false), cin.tie(0);
memset(h, -1, sizeof h);
cin >> n >> m;
while (m --) {
int a, b;
cin >> a >> b;
add(a, b), add(b, a);
}
for (int i = 1; i <= n; i ++ )
if (!st[i]) dfs(i, -1, 1);
res = res * qmi(2, sum - p, mod) % mod;
cout << res << endl;
return 0;
}