题目链接
The kingdom of Z is fighting against desertification these years since there are plenty of deserts in its wide and huge territory. The deserts are too arid to have rainfall or human habitation, and the only creatures that can live inside the deserts are the cactuses. In this problem, a cactus in desert can be represented by a cactus in graph theory. In graph theory, a cactus is a connected undirected graph with no self-loops and no multi-edges, and each edge can only be in at most one simple cycle. While a tree in graph theory is a connected undirected acyclic graph. So here comes the idea: just remove some edges in these cactuses so that the remaining connected components all become trees. After that, the deserts will become forests, which can halt desertification fundamentally. Now given an undirected graph with n vertices and m edges satisfying that all connected components are cactuses, you should determine the number of schemes to remove edges in the graph so that the remaining connected components are all trees. Print the answer modulo 998244353. Two schemes are considered to be different if and only if the sets of removed edges in two schemes are different.
The first line contains two non-negative integers n,m (1≤n≤300000,0≤m≤500000), denoting the number of vertices and the number of edges in the given graph. Next m lines each contains two positive integers u,v (1≤u,v≤n,u≠v), denoting that vertices u and v are connected by an undirected edge. It is guaranteed that each connected component in input graph is a cactus.
Output a single line containing a non-negative integer, denoting the answer modulo 998244353.
题意比较简单,就是删去任意数量的边使得图变成森林~ 对一个长为 n n n 的环,我们可以删任意的边,答案就是 C n 1 + C n 2 + ⋯ + C n n = 2 n − 1 C_n^1+C_n^2+\cdots +C_n^n=2^n-1 Cn1+Cn2+⋯+Cnn=2n−1 对于除环外的边数 k k k,我们可以任选,答案就是 2 k 2^k 2k 题目的难点就在于求环长,我们可以在 DFS 的过程中加入深度,当出现比当前结点深度更小的结点时(不是前驱结点),那么就一定出现了环,环的长度也即深度之差,AC代码如下:
#include<bits/stdc++.h> using namespace std; typedef long long ll; const int N=3e5+5; const ll mod=998244353; vector<ll>G[N]; int n,m,u,v,vis[N]; ll depth[N],pow2[N],ans=1; void init(){ pow2[0]=1; for(int i=1;i<N;i++) pow2[i]=(pow2[i-1]<<1)%mod; } void dfs(int u){ vis[u]=1; for(auto v:G[u]){ if(depth[v]&&depth[v]==depth[u]-1) continue; if(!depth[v]){ depth[v]=depth[u]+1; dfs(v); continue; } if(depth[u]>=depth[v]){ ans=ans*(pow2[depth[u]-depth[v]+1]-1)%mod; if(ans<0) ans=(mod+(-ans)%mod)%mod; m-=(depth[u]-depth[v]+1); } } } int main(){ init(); scanf("%d%d",&n,&m); for(int i=0;i<m;i++){ scanf("%d%d",&u,&v); G[u].push_back(v); G[v].push_back(u); } for(int i=1;i<=n;i++){ if(!vis[i]){ depth[i]=1; dfs(i); } } printf("%lld",ans*pow2[m]%mod); return 0; }