章鱼图的判断 dfs搜环大小 bfs搜去枝
作者:
徐枭翔
,
2024-08-02 17:10:39
,
所有人可见
,
阅读 3
https://pintia.cn/problem-sets/1813039306479005696/exam/problems/type/7?problemSetProblemId=1813039385617129475&page=0
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll, ll> PII;
typedef vector<long long> VI;
#define int long long
#define INF 0x3f3f3f3f
#define endl '\n'
#define N 200010
const int mod = 1e9 + 7;
ll lowbit(ll x) {
return -x & x;
}
int p[N], si[N];
int find(int x) {
if (x == p[x])return p[x];
p[x] = find(p[x]);
return p[x];
}
//size[find(b)] += size[find(a)];
//p[find(a)] = find(b)
int n, m, cnt, ans, d[N];
vector<int> g[N];
void dfs(int x) { //遍历搜环的大小
d[x] = 0;
for (auto t : g[x]) {
if (d[t]) {
cnt ++;
dfs(t);
}
}
}
void bfs() { // 无向图去枝,只保留环
queue<int> q;
for (int i = 1; i <= n; i++) {
if (d[i] == 1)q.push(i);
}
while (q.size()) {
auto t = q.front();
q.pop();
d[t] --;
for (auto now : g[t]) {
d[now] --;
if (d[now] == 1) {
q.push(now);
}
}
}
}
void solve() {
cin >> n >> m;
for (int i = 1; i <= n; i++) {
g[i].clear();
d[i] = 0;
}
for (int i = 1; i <= m; i++) {
int u, v;
cin >> u >> v;
g[u].push_back(v);
g[v].push_back(u);
d[u] ++;
d[v] ++;
}
bfs();
//如图有个环,直接跑一遍dfs清度数
for (int i = 1; i <= n; i++) {
if (d[i] > 2)dfs(i);
}
ans = cnt = 0;
for (int i = 1; i <= n; i++) {
if (d[i] == 2) {
ans ++;
cnt = 1;
dfs(i);
}
}
if(ans == 1)cout << "Yes " << cnt << endl;
else cout << "No " << ans << endl;
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
int T = 1;
cin >> T;
while (T --)
solve();
return 0;
}