给定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;
}
相关推荐
Sw1zzle2 小时前
算法入门(四):二叉树 - 递归遍历三件套
算法·leetcode
万法若空3 小时前
【算法-查找】查找算法
java·数据结构·算法
海石3 小时前
子树怎么找?树的3种遍历方式来帮忙!
算法·leetcode
海石3 小时前
难度分 1588:思路 + 技巧 = AC
算法·leetcode
珠海西格电力6 小时前
云边端协同架构:零碳园区管理系统的技术底座
大数据·运维·人工智能·算法·架构·能源
还有多久拿退休金8 小时前
让飞书知识库跟着 commit 自己长:一套自动化知识库的真实实现
前端·算法·架构
KaMeidebaby9 小时前
卡梅德生物技术快报|小 RNA 适配体合成 + 多方法亲和力表征全流程标准化操作手册
前端·网络·数据库·人工智能·算法
是Dream呀9 小时前
基于深度学习的人类行为识别算法研究
人工智能·深度学习·算法
happyprince10 小时前
03_NVIDIA_ModelOpt-量化算法深入
人工智能·深度学习·算法
大鱼>10 小时前
AI+货物追踪:智能快递柜追踪系统
人工智能·深度学习·算法·机器学习