Don’t Really Like How The Story Ends---图的dfs

任意门
There are n planets in the galaxy, and many undirected warp tunnels connecting them. 6000 years ago,
Spinel performed a depth-first search on the planets, visited all of them, and labeled them from 1 to n in
the order of discovery.
Many warp tunnels have broken down since, and only m of them are still working. Spinel wants to know
how many new warp tunnels have to be built so that it is possible to perform a depth-first search, where
the order of discovery is exactly as labeled 6000 years ago.
Recall that the depth-first search (DFS) algorithm inputs a graph G and a vertex v of G, and labels all
vertices reachable from v as discovered.
Here is the pseudocode of a recursive implementation of DFS:
在这里插入图片描述
在这里插入图片描述
目标是希望能够建立一个能够从1-n的图,就是他能从1到每一个点。

#include<iostream>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
 
#define endl "\n"
 
const int maxn = 100100;
int t;
int n, m;
int ans;
int cnt;
vector<int> v[maxn];
 
void dfs(int x){
    if(x == n + 1) return;
    for(auto y : v[x]){
        if(y < cnt) continue;
        while(y >= cnt){
            if(y > cnt) ans++;//说明断层,断层加边
            dfs(cnt++);
        }
    }
}
 
int main(){
    ios::sync_with_stdio(false);cin.tie(0),cout.tie(0);
    //多组输入
    cin >> t;
    while(t--){
        cin >> n >> m;
        int x, y;
        for(int i = 1; i <= n; i++) v[i].clear();
        for(int i = 1; i <= m; i++){
            cin >> x >> y;
            v[x].push_back(y);//建立图
            v[y].push_back(x);
        }
        v[1].push_back(n + 1);
        for(int i = 1; i <= n; i++) sort(v[i].begin(), v[i].end());//将每一组从小到大排序
        ans = 0;//答案
        cnt = 2;//记录应该遍历哪个点,记录断层点
        dfs(1);
        cout << ans << endl;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值