c_cpp HR-ComponentsInAGraph
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp HR-ComponentsInAGraph相关的知识,希望对你有一定的参考价值。
#include <bits/stdc++.h>
using namespace std;
vector<vector<int> >g; // define graph globally
void DFS(int s, vector<bool> &visited,int &count,vector<int> &group){
visited[s]=true;
count++;
group.push_back(s);
for(int i=0;i<g[s].size();i++){
if(!visited[g[s][i]]){
DFS(g[s][i],visited,count,group);
}
}
}
vector<int> componentsInGraph(vector<vector<int>> gb) {
//vector<vector<int> >g;
for(int i=0;i<gb.size();i++){
if(g.size()<=max(gb[i][0],gb[i][1])){
g.resize(max(gb[i][0],gb[i][1])+1); // 1 indexed
}
g[gb[i][0]].push_back(gb[i][1]);
g[gb[i][1]].push_back(gb[i][0]);
}
cout<<"Graph"<<endl;
for(int i=1;i<g.size();i++){
cout<<i<<"->";
for(int j=0;j<g[i].size();j++){
cout<<g[i][j]<<" ";
}
cout<<endl;
}
vector<bool> visited(g.size(),false);
int minComp=INT_MAX,maxComp=INT_MIN;
for(int i=1;i<g.size();i++){ // 1 indexed
if(!visited[i] && g[i].size()>=1){ // IMP: check if vertex is a part of given graph
int count=0;
vector<int> group;
DFS(i,visited,count,group);
if(count>maxComp){
maxComp=count;
}
if(count<minComp){
minComp=count;
}
cout<<"Group"<<endl;
for(auto i: group){
cout<<i<<" ";
}
cout<<endl;
}
}
cout<<minComp<<" "<<maxComp<<endl;
vector<int> ans={minComp,maxComp};
return ans;
}
int main(){
//freopen("ip.txt","r",stdin);
int e;
cin>>e;
vector<vector<int>> gb(e,vector<int>(2));
for(int i=0;i<e;i++){
cin>>gb[i][0]>>gb[i][1];
}
cout<<"Edges"<<endl;
for(int i=0;i<e;i++){
cout<<gb[i][0]<<" "<<gb[i][1];
cout<<endl;
}
cout<<endl;
vector<int> ans=componentsInGraph(gb);
cout<<ans[0]<<" "<<ans[1]<<endl;
}
以上是关于c_cpp HR-ComponentsInAGraph的主要内容,如果未能解决你的问题,请参考以下文章
c_cpp 127.单词阶梯
c_cpp MOFSET
c_cpp MOFSET
c_cpp 31.下一个排列
c_cpp string→char *
c_cpp 54.螺旋矩阵