无向图中的广度优先生成森林

来源:互联网 发布:linux trace 命令 编辑:程序博客网 时间:2024/04/28 12:57
广度优先生成森林的思路和深度优先生成森林的思路相同,在此不再复述,请看上一篇。
#include<iostream>#include<fstream>#include<vector>#include<time.h>#include<algorithm>#include<queue>using namespace std;struct CSTree{int data;CSTree * lchild;CSTree * nextsibling;};void BFSTree(int v,CSTree *&p);void BFSForest(CSTree *&root);CSTree *root = NULL;//生成森林bool *visited;vector<vector<int>> mGraph;//图结构int nodeNum;//图中顶点数int edgeNum;//图中边数void readGraph(){fstream fin("E:\\myData\\facebook_combined.txt");//打开文件fin>>nodeNum>>edgeNum;//读取顶点数和边数mGraph.resize(nodeNum);//设置图的大小visited = new bool[nodeNum];for(int i = 0; i < nodeNum; ++i){visited[i] = false;}int num1, num2;while(fin>>num1>>num2)//读取每一条边{mGraph[num1].push_back(num2);//存储边的信息mGraph[num2].push_back(num1);}fin.close();//关闭文件for(int i = 0; i < nodeNum; ++i){sort(mGraph[i].begin(),mGraph[i].end());//图中节点的邻接点排序}}//广度优先生成森林void BFSForest(CSTree *&root){CSTree *q = NULL;//指向当前生成树的树根for(int i = 0; i < nodeNum; ++i){if(!visited[i])//从顶点i开始生成广度优先生成树{CSTree *p = new CSTree;//设置树中的节点p->data = i;p->lchild = NULL;p->nextsibling = NULL;if(root == NULL)//如果是第一棵生成树的树根{root = p;}else//是其他生成树的树根{q->nextsibling = p;}q = p;//q指向当前生成树的树根BFSTree(i,p);//建立以p为树根的的生成树}}}//从节点v开始,生成一棵以root为根的树void BFSTree(int v,CSTree *&root){queue<CSTree *> qu;//定义一的储存CSTree指针的队列qu.push(root);//根指针入队列while(!qu.empty())//判断队列是否为空{bool first = true;//判断是当前节点的第一个孩子CSTree *q = qu.front();//指向当前根节点CSTree *tmp = NULL;int val = q->data;visited[val] = true;int count = mGraph[val].size();for(int i = 0; i < count; ++i)//val顶点的邻接点{int node = mGraph[val][i];if(!visited[node])//当前节点是否被访问过{visited[node] = true;tmp = new CSTree;tmp->data = node;tmp->lchild = NULL;tmp->nextsibling = NULL;qu.push(tmp);if(first)//如果是第一个孩子{q->lchild = tmp;first = false;}else//如果不是第一个孩子{q->nextsibling = tmp;}q = tmp;}}qu.pop();}}//以前序遍历的方式输出森林void show(CSTree *root){if(root != NULL){cout<<root->data<<" ";show(root->lchild);show(root->nextsibling);}}int main(void){readGraph();cout<<"无向图中顶点的个数:"<<nodeNum<<endl;cout<<"无向图中边的条数:"<<edgeNum<<endl;clock_t start,end;start = clock();BFSForest(root);end = clock();cout<<"生成森林时间:"<<float(end - start)/CLOCKS_PER_SEC*1000<<endl;system("pause");return 0;}
实验结果:单位(ms)
数据集为soc-Epinions
无向图中顶点的个数:75888
无向图中边的条数:508837
生成森林时间:87
数据集为facebook_combined
无向图中顶点的个数:4039
无向图中边的条数:88234
生成森林时间:4
广度优先生成森林和深度优先生成森林的时间基本相同,因为两者的时间复杂度一样。
0 0
原创粉丝点击