https://codeforces.com/contest/1243/problem/D
总结 :题目求的就是补图的连通块-1。首先可以把1~n个点都存放到set的s中。当某个点没有被访问过的时候,就调用bfs函数,从s中删除,因为这个点已经访问了,并且加入到队列中。
寻找在补图中和这个点相连的,遍历s,如果找到一个v和k并没有相连,就说明它们是补图中相连的。就从s中删除,加入队列,并且做上标记。
1 /*求补图的连通块*/ 2 #include <bits/stdc++.h> 3 #define ll long long 4 using namespace std; 5 const int N = 1e5+5; 6 7 set<int>G[N]; 8 int n,m; 9 set<int>s; 10 int vis[N]; 11 set<int>::iterator it; 12 13 void bfs(int x){ 14 queue<int>q; 15 s.erase(x);//将在s中的x删掉 16 q.push(x);//需要连接与x相连的 17 vis[x] = 1;//表示这个点已经访问过了 18 while(!q.empty()){ 19 int k = q.front(); 20 q.pop(); 21 for(it = s.begin();it != s.end();){ 22 int v = *it++;//这儿因为下面可能要把这个地址删除,所以先增加。这样删除就不影响了 23 if(G[v].count(k) == 0){//表示和k相连的并没有v,所以就是补图中的一个 24 s.erase(v);//因为已经访问过了,以后不需要访问了,所以可以删掉 25 q.push(v); 26 vis[v] = 1; 27 } 28 } 29 } 30 } 31 int main(){ 32 cin >> n >> m; 33 for(int i = 1;i <= n;i++){ 34 s.insert(i); 35 } 36 while(m--){ 37 int x,y; 38 cin >> x >> y; 39 G[x].insert(y); 40 G[y].insert(x);//代表这个点是原来的图里有了多少的点 41 } 42 int cnt = 0; 43 for(int i = 1;i <= n;i++){ 44 if(!vis[i]){ 45 cnt++; 46 bfs(i); 47 } 48 } 49 cout<<cnt-1<<endl; 50 return 0; 51 }