给定n个结点m条边的简单无向图,判断该图是否存在鱼形状的子图:有一个环,其中有一个结点有另外两条边,连向不在环内的两个结点。若有,输出子图的连边

题目

思路:

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define pb push_back
#define fi first
#define se second
#define lson p << 1
#define rson p << 1 | 1
const int maxn = 1e6 + 5, inf = 1e18 * 3, maxm = 4e4 + 5, mod = 1e9 + 7;
int a[maxn], b[maxn];
int n, m;
string s;
bool vis[maxn];
vector<int> G[maxn];
int from, to;
vector<int> tmp, vec;
int deg[maxn];

void dfs(int u, int p){
	if(u == to && p == from) return;
	if(vis[u]) return;
	vis[u] = 1;
	tmp.pb(u);
	if(u == to){
		vec = tmp;
		return;
	}
	for(auto v : G[u]){
		dfs(v, u);
	}
	tmp.pop_back();
}
void solve(){
    int res = 0;
    int k, x, q;
	cin >> n >> m;
	for(int i = 1; i <= n; i++){
		G[i].clear();
		deg[i] = 0;
	}
	for(int i = 1; i <= m; i++){
		int u, v;
		cin >> u >> v;
		G[u].pb(v);
		G[v].pb(u);
		deg[u]++;
		deg[v]++;
	}
	for(int u = 1; u <= n; u++){
		if(deg[u] < 4) continue;
		for(auto v : G[u]){
			for(int i = 1; i <= n; i++){
				vis[i] = 0;
			}
			from = u;
			to = v;
			vec.clear();
			tmp.clear();
			dfs(u, u);
			if(vec.empty()) continue;
			vector<int> extra;
			tmp.clear();
			for(auto x : G[u]){
				if(x == vec.back() || x == *(vec.begin() + 1)) continue;
				if(find(vec.begin(), vec.end(), x) == vec.end()){//不在环内
					extra.pb(x);
					if(extra.size() == 2) break;
				}
				else{
					tmp.pb(x);//在环内,且与u相连
				}
			}
			vector<int> vt;
			if(extra.size() < 2){
				for(auto x : vec){
					vt.pb(x);
					if(find(tmp.begin(), tmp.end(), x) != tmp.end()){//在tmp内
						break;
					}
				}
				
				extra.pb(vec.back());
				for(int i = vec.size() - 1; i >= 0; i--){
					int x = vec[i];
					if(find(tmp.begin(), tmp.end(), x) != tmp.end()){
						extra.pb(x);
						break;
					}
				}
				// extra.pb(vec.end() - 2) 不能这样写,因为这个结点不一定与u相连
				// extra.pb(tmp.back()); 不能这样写,因为tmp的顺序跟环的结点顺序不一致

				extra.resize(2);
				vec = vt;
			}
			cout << "Yes\n";
			cout << vec.size() + 2 << '\n';
			int m = vec.size();
			for(int i = 0; i < vec.size(); i++){
				cout << vec[i] << ' ' << vec[(i + 1) % m] << '\n';
			}
			cout << u << ' ' << extra[0] << '\n';
			cout << u << ' ' << extra[1] << '\n';
			return;
		}
		
	}
	cout << "No\n";
}
    
signed main(){
    ios::sync_with_stdio(0);
    cin.tie(0);
    int T = 1;
    cin >> T;
    while (T--)
    {
        solve();
    }
    return 0;
}
相关推荐
yagamiraito_2 小时前
757. 设置交集大小至少为2 (leetcode每日一题)
算法·leetcode·go
星释2 小时前
Rust 练习册 57:阿特巴什密码与字符映射技术
服务器·算法·rust
无敌最俊朗@2 小时前
力扣hot100-141.环形链表
算法·leetcode·链表
WWZZ20254 小时前
快速上手大模型:深度学习10(卷积神经网络2、模型训练实践、批量归一化)
人工智能·深度学习·神经网络·算法·机器人·大模型·具身智能
sali-tec5 小时前
C# 基于halcon的视觉工作流-章62 点云采样
开发语言·图像处理·人工智能·算法·计算机视觉
fashion 道格5 小时前
用 C 语言玩转归并排序:递归实现的深度解析
数据结构·算法·排序算法
九年义务漏网鲨鱼7 小时前
蓝桥杯算法——状态压缩DP
算法·职场和发展·蓝桥杯
CappuccinoRose7 小时前
MATLAB学习文档(二十八)
开发语言·学习·算法·matlab
Freedom_my7 小时前
插入排序算法
数据结构·算法·排序算法
952367 小时前
排序-算法
数据结构·算法·排序算法