概述
D.0-1 MST
Ujan has a lot of useless stuff in his drawers, a considerable part of which are his math notebooks: it is time to sort them out. This time he found an old dusty graph theory notebook with a description of a graph.
It is an undirected weighted graph on n vertices. It is a complete graph: each pair of vertices is connected by an edge. The weight of each edge is either 0 or 1; exactly m edges have weight 1, and all others have weight 0.
Since Ujan doesn’t really want to organize his notes, he decided to find the weight of the minimum spanning tree of the graph. (The weight of a spanning tree is the sum of all its edges.) Can you find the answer for Ujan so he stops procrastinating?
Input
The first line of the input contains two integers n and m (1≤n≤105, 0≤m≤min(n(n−1)2,105)), the number of vertices and the number of edges of weight 1 in the graph.
The i-th of the next m lines contains two integers ai and bi (1≤ai,bi≤n, ai≠bi), the endpoints of the i-th edge of weight 1.
It is guaranteed that no edge appears twice in the input.
Output
Output a single integer, the weight of the minimum spanning tree of the graph.
Examples
Input
6 11
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
Output
2
Input
3 0
Output
0
Note
The graph from the first sample is shown below. Dashed edges have weight 0, other edges have weight 1. One of the minimum spanning trees is highlighted in orange and has total weight 2.
In the second sample, all edges have weight 0 so any spanning tree has total weight 0.
思路:
答案是补图连通块的个数-1
bfs+set
set有好多细节,删除的时候迭代器会炸,所以要先指向下一个,然后再删
也是因为删除,所以这题如果用dfs的话应该不是很好写
code:
//别人那学来的代码
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <set>
#include <queue>
using namespace std;
const int maxm=1e5+5;
set<int>s;
set<int>g[maxm];
int mark[maxm];
int n,m;
void bfs(int st){
queue<int>q;
q.push(st);
s.erase(st);
while(!q.empty()){
int x=q.front();
q.pop();
if(mark[x])continue;
mark[x]=1;
set<int>::iterator it;
for(it=s.begin();it!=s.end();){
int v=*it;
it++;//it++必须放在这里,因为下面如果erase(v),it就炸了
if(g[x].find(v)==g[x].end()){
q.push(v);
s.erase(v);
}
}
}
}
signed main(){
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++){
s.insert(i);
}
for(int i=1;i<=m;i++){
int a,b;
scanf("%d%d",&a,&b);
g[a].insert(b);
g[b].insert(a);
}
int ans=0;
for(int i=1;i<=n;i++){
if(!mark[i]){
ans++;
bfs(i);
}
}
cout<<ans-1<<endl;
return 0;
}
最后
以上就是坚定手链为你收集整理的CodeForces1243 D.0-1 MST (补图的连通块数量,set+bfs)的全部内容,希望文章能够帮你解决CodeForces1243 D.0-1 MST (补图的连通块数量,set+bfs)所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复