(SCC基于深度优先搜索DFS的强连通分量检索 C++实现) Coursera 斯坦福大学 算法课程 Programming Assignment #5

该博客讲述了如何使用深度优先搜索算法解决斯坦福大学算法课程中关于强连通分量(SCC)的问题。作者通过分析SCC.txt文件中的有向图,编写程序来计算最大的五个SCC的大小,并给出输出格式要求。文章提到了在实现过程中遇到的挑战,如递归可能导致的栈溢出、数据读取效率以及避免使用平方时间复杂度的算法。最后,作者建议使用链表作为可能更优的数据结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Divide and Conquer, Sorting and Searching, and Randomized Algorithms

题目

第 1 个问题

Download the following text file:
SCC.txt

The file contains the edges of a directed graph. Vertices are labeled as positive integers from 1 to 875714. Every row indicates an edge, the vertex label in first column is the tail and the vertex label in second column is the head (recall the graph is directed, and the edges are directed from the first column vertex to the second column vertex). So for example, the 11th11^{th}11th row looks liks : “2 47646”. This just means that the vertex with label 2 has an outgoing edge to the vertex with label 47646

Your task is to code up the algorithm from the video lectures for computing strongly connected components (SCCs), and to run this algorithm on the given graph.

Output Format: You should output the sizes of the 5 largest SCCs in the given graph, in decreasing order of sizes, separated by commas (avoid any spaces). So if your algorithm computes the sizes of the five largest SCCs to be 500, 400, 300, 200 and 100, then your answer should be “500,400,300,200,100” (without the quotes). If your algorithm finds less than 5 SCCs, then write 0 for the remaining terms. Thus, if your algorithm computes only 3 SCCs whose sizes are 400, 300, and 100, then your answer should be “400,300,100,0,0” (without the quotes). (Note also that your answer should not have any spaces in it.)

WARNING: This is the most challenging programming assignment of the course. Because of the size of the graph you may have to manage memory carefully. The best way to do this depends on your programming language and environment, and we strongly suggest that you exchange tips for doing this on the discussion forums.

程序

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <regex>

using namespace std;
class vertex{
   
   
private:
public:
    int leader;
    bool visited;
    int vertexName;
    int finishTime;
    vector<int> edges;
    void push_back(int i){
   
   
        edges.push_back(i);
    }
};

vector<int> finishList;

void readTxt(string file, vector<vertex>& fwdGraph, vector<vertex>& revGraph)
{
   
   
    vector<int> temp_line;
    string line;
    ifstream in(file);
    regex pat_regex("[[:digit:]]+");
    int count = 0;
    while(getline(in
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值