邻接表存图,输出连通分量里顶点的下标:
#include <bits/stdc++.h>
using namespace std;
struct Edge{
int to;
Edge* next;
};
struct Vex{
int id;
Edge* first;
}vex[100];
struct Tree{
int id;
Tree *child,*sibling;
};
void AddEdge(int u,int v){
if(!vex[u].first){
vex[u].first=new Edge;
vex[u].first->to=v;
vex[u].first->next=NULL;
return;
}
Edge *p=new Edge;
p->next=vex[u].first;
p->to=v;
vex[u].first=p;
}
int n;
void CreatGraph(){
int u,v;
cin>>n;
for(int i=0;i<n;i++) vex[i].id=i;
while(cin>>u>>v){
AddEdge(u,v);
AddEdge(v,u);
}
}
bool vis[100];
void DFSTree(int v){
for(Edge *e=vex[v].first;e;e=e->next){
int w=e->to;
if(!vis[w]){
cout<<w<<' ';
vis[w]=1;
DFSTree(w);
}
}
}
int dfs(){
int res=0;
for(int i=0;i<n;i++) vis[i]=0;
for(int v=0;v<n;v++){
if(!vis[v]){
vis[v]=1;
res++;
cout<<v<<' ';
DFSTree(v);
cout<<endl;
}
}
return res;
}
int main(){
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
CreatGraph();
cout<<dfs();
return 0;
}