给定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;
}
相关推荐
倒头就睡的小比特3 天前
算法竞赛C++常用的STL
c++·算法
小羊没烦恼!3 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
猎头南楼3 天前
知识社区推荐系统实践:新用户冷启动与长短期兴趣建模的挑战 资深推荐算法工程师
人工智能·深度学习·算法·机器学习
旖旎夜光3 天前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
wzdark3 天前
大规模并行计算中的负载均衡算法研究4
算法
Because_of_Her13 天前
并查集-听课笔记
笔记·算法·并查集
码流子3 天前
高速公路安全监测实践:碰撞监测预警+物联网底座,从感知到处置的闭环
大数据·人工智能·物联网·算法·架构
another heaven3 天前
【算法/C++ MD5算法能否逆解码?原理、C++实现与同类哈希算法对比】
c++·算法·哈希算法
wzdark3 天前
从算法设计模式看编程思维的抽象能力4
算法
2601_962218613 天前
万象生鲜系统称重自动多退少补算法解决生鲜非标品痛点
大数据·数据库·人工智能·python·算法