活跃农民
- 积分
- 401
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2011-11-13
- 最后登录
- 1970-1-1
|
托了两周才把week 4的编程题补上。。。完全按照video上的算法写的,为了图省事用了三个graph,空间复杂度太大,不过不会出现爆栈的情况,而且计算速度比较快。
- #include <iostream>
- #include <stdio.h>
- #include <vector>
- #include <stack>
- #include <algorithm>
- using namespace std;
- #define SIZE 875714
- struct Node{
- size_t finishTime; // finishing time
- size_t leader; // leader node of inclosed SCC
- bool ifExplored; // flag for DFS exploration
- vector<size_t> tailList; // list of tail nodes
- };
- Node graph[SIZE],revGraph[SIZE],copyGraph[SIZE];
- size_t countFinishTime; //count for finishing time
- size_t leaderNode; // index of leader node in a strongly connected component
- void DFS(Node testGraph[],int headNode){
- testGraph[headNode-1].ifExplored = true; // mark head node as explored
- testGraph[headNode-1].leader = leaderNode; // mark leader node
- for (vector<size_t>::size_type i=0;i!=testGraph[headNode-1].tailList.size();i++) // traverse all arcs from source node
- {
- int tail = testGraph[headNode-1].tailList[i];
- if (!testGraph[tail-1].ifExplored) // if the tail is unexplored
- DFS(testGraph,tail);
- }
- testGraph[headNode-1].finishTime = ++countFinishTime; //mark finishing time
- }
- void DFSLoop(Node testGraph[]){
- countFinishTime =0;
- leaderNode = 0;
- for (size_t i=SIZE;i>0;i--){ //traverse nodes in descending order
- if (!testGraph[i-1].ifExplored){ //if the node unexplored
- leaderNode = i; //mark as leader node
- DFS(testGraph,i);
- }
- }
- }
- void CountSCCs(Node testGraph[]){
- size_t SCCList[SIZE] ={0}; //array of leader in SCCs
- for (size_t i=0;i<SIZE;i++) // counting size of SCC
- SCCList[testGraph[i].leader-1] ++;
-
- sort(SCCList,SCCList+SIZE); // sort the sizes in ascending order
- for( int i=SIZE;i>SIZE-5;i--) // print the largest 5 sizes
- cout<<SCCList[i-1]<<" ";
- }
- void KosarajusAlgorithm(){
- DFSLoop(revGraph); //run DFSLoop on reversed graph
-
- size_t tempFinishTime;
- size_t tempTailNode;
- vector<size_t> tempList;
- for (size_t i=0;i<SIZE;i++){ // replace node index with node finishing time
- tempList.clear();
- tempFinishTime = revGraph[i].finishTime;
- for (vector<size_t>::size_type j=0;j<copyGraph[i].tailList.size();j++){
- tempTailNode = copyGraph[i].tailList.at(j);
- tempList.push_back(revGraph[tempTailNode-1].finishTime);
- }
- graph[tempFinishTime-1].tailList = tempList;
- }
- DFSLoop(graph); // run DFSLoop on forward-order graph
- CountSCCs(graph); // Count the 5 largest SCCs
- }
- int main()
- {
- FILE *pFile;
- size_t headNode,tailNode;
- pFile = fopen("SCC.txt","r");
- if (pFile ==NULL) perror("Error openning file.");
- else{
- rewind(pFile);
- while (!feof(pFile)){
- fscanf_s(pFile,"%d",&headNode);
- fscanf_s(pFile,"%d",&tailNode);
- copyGraph[headNode-1].tailList.push_back(tailNode);
- revGraph[tailNode-1].tailList.push_back(headNode);
- }
- }
- fclose(pFile);
- KosarajusAlgorithm();
- return 0;
- }
复制代码
|
|