任意门
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;
}
}