原先有一个图,dfs序是1,2,...,n, 但是其中一些边被破坏,给定被破坏边后的图,求最少要加几条边,可以使图的dfs序为1,2,...,n
发布时间:2024年01月15日
题目
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define pb push_back
const int maxn = 2e5 + 5, maxm = 2e3 + 5;
int a[maxn];
int nxt;//下一个应该遍历的结点
int res = 0;
int n, m;
vector<int> G[maxn];
void dfs(int u){
if(u == nxt) nxt++;
for(int i = 0; i < G[u].size();){//这里不写i++
int v = G[u][i];
if(v < nxt){//之前遍历过的结点,跳过
i++;
continue;
}
if(v > nxt){
res++;
dfs(nxt);//这里不i++, 等把nxt~v-1的结点遍历完再dfs(v)
/*
1
4 1
1 3
*/
}
else{
dfs(v);
i++;
}
}
}
void solve(){
cin >> n >> m;
for(int i = 1; i <= n; i++){
G[i].clear();
}
res = 0;
for(int i = 1; i <= m; i++){
int u, v;
cin >> u >> v;
// if(u == v) continue;
// if(u > v) swap(u, v);
G[u].push_back(v);
G[v].push_back(u);
}
for(int i = 1; i <= n; i++){
sort(G[i].begin(), G[i].end());//按顺序来
}
nxt = 1;
while(nxt <= n){
res++;//向nxt连一条边
dfs(nxt);
}
cout << res - 1 << '\n';//减去向1连的一条边
}
signed main(){
ios::sync_with_stdio(0);
cin.tie(0);
int T;
cin >> T;
while(T--){
solve();
}
}
文章来源:https://blog.csdn.net/way_back__/article/details/135611096
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:chenni525@qq.com进行投诉反馈,一经查实,立即删除!