用C ++实现无向图算法中的循环

时间:2016-01-22 04:26:38

标签: c++ algorithm graph

所以基本上我想在C ++中实现这个Finding all cycles in undirected graphs(唯一的区别是图表是加权的),但是现在这不是我的问题,因为我可以稍后处理它。

我尝试将C#代码重写为C ++,但我对C ++中的OOP仍然没有信心,而且我不太明白我做错了什么。我使用调试器,我的程序甚至没有进入findNewCycles函数,我也很确定有更多问题,但目前我想知道如何开始。我的Path类的构造函数有问题(至少调试器建议我这个),但我不明白为什么。你能帮我么?这是我的代码:

#include <iostream>
#include <utility>
#include <vector>
#include <algorithm>

using namespace std;

class Graph {
        struct Edge {
                int vert[2];
                double value;
            public:
                Edge(int vec1, int vec2, double w) {
                    vert[0] = vec1;
                    vert[1] = vec2;
                    value = w;
                };
        };

        struct Path {
                vector<int> vertices;
                double totalValue;
            public:
                Path() : totalValue(0) {};
                Path(vector<int> v, double tv) : vertices(v), totalValue(tv) {};
                Path(const Path &a) {
                    totalValue = a.totalValue;
                    vertices = a.vertices;
                }
        };

        int vortexCount, edgeCount, cycleCount;
        vector<Path> cycles;
        vector<Edge> edges;

        void findNewCycles(Path a) {
            int n = a.vertices[0];
            int x;
            Path sub(a);

            for(int i = 0; i < edgeCount; i++) {
                for(int j = 0; j <=1; j++) {
                    if (edges[i].vert[j] == n) {
                        x = edges[i].vert[(j+1)%2];

                        if (!visited(x, a)) {
                            sub.totalValue += edges[i].value;
                            sub.vertices.insert(sub.vertices.begin(), x);
                            findNewCycles(sub);
                        }
                        else if ((a.vertices.size() > 2) && (x == a.vertices[a.vertices.size() - 1])) {
                            Path normal = normalize(a);
                            Path inv = invert(normal);
                            if(isNew(normal) && isNew(inv)) cycles.push_back(normal);
                        }
                    }
                }
            }
        }

        bool equals(Path a, Path b) {
            if((a.vertices.size() == b.vertices.size()) && (a.totalValue == b.totalValue)) {
                for (unsigned i=0; i < a.vertices.size(); i++) {
                    if(a.vertices[i] != b.vertices[i]) return false;
                }
                return true;
            }
            else return false;
        }

        Path invert(Path a) {
            Path inverted(a);
            reverse(inverted.vertices.begin(), inverted.vertices.end());
            return normalize(inverted);
        }

        Path normalize(Path a) {
            Path normalized(a);
            vector<int>::iterator smallest = min_element(normalized.vertices.begin(), normalized.vertices.end());
            std::rotate(normalized.vertices.begin(), smallest, normalized.vertices.end());
            return normalized;
        }

        bool isNew(Path a) {
            for(int i=0; i<cycleCount; i++) {
                if(equals(cycles[i], a)) {
                    return false;
                }
            }
            return true;
        }

        bool visited(int n, Path a) {
            for (unsigned i=0; i < a.vertices.size(); i++) {
                if(a.vertices[i] == n) return true;
            }
            return false;
        }

    public:
        Graph(int size) : vortexCount(size), edgeCount(0), cycleCount(0) {};
        ~Graph() {};

        vector<Edge>::iterator findEdge(int v1, int v2) {
            if(v1 == v2 || v1 > vortexCount || v2 > vortexCount) return edges.end();
            vector<Edge>::iterator iter;

            for(iter = edges.begin(); iter != edges.end(); ++iter) {
                if(iter->vert[0] == v1 && iter->vert[1] == v2) return iter;
                if(iter->vert[1] == v1 && iter->vert[0] == v2) return iter;
            }
            return edges.end();
        }

        bool addEdge(int v1, int v2, double value) {
            if(v1 == v2 || v1 > vortexCount || v2 > vortexCount) return false;

            vector<Edge>::iterator p = findEdge(v1, v2);

            if(p != edges.end()) {
                p->value = value;
            }
            else {
                Edge edge(v1, v2, value);
                edges.push_back(edge);
                edgeCount++;
            }
            return true;
        }

        void runCycleSearch() {
            for (int i = 0; i < edgeCount; i++) {
                for (int j = 0; j < 2; j++) {
                    cout << i << " " << j;
                    Path searchPath;
                    searchPath.vertices.push_back(edges[i].vert[j]);
                    findNewCycles(searchPath);
                }
            }

            for(int i=0; i<cycleCount; i++) {
                for(unsigned j=0; j<cycles[i].vertices.size(); j++) {
                    cout << cycles[i].vertices[j] << " ";
                }
                cout << cycles[i].totalValue;
            }
        }

};

int main() {
    int n, v1, v2;
    double val;
    bool control = true;

    cin >> n;
    Graph graph(n);

    while(control) {
        cin >> v1;
        if(v1 == -1) break;
        cin >> v2 >> val;

        control = graph.addEdge(v1, v2, val);
    }

    graph.runCycleSearch();
}

2 个答案:

答案 0 :(得分:0)

你确定你已经离开了while循环吗?

尝试在阅读输入后添加此行:

cout << "v1=" << v1 << ", v2=" << v2 << " val=" << val << endl;

并将while (control)更改为

for (int i=0; i < n; i++)

答案 1 :(得分:0)

我发现了第一个错误。找到循环时,您没有更新cycleCount变量。即

                    else if ((a.vertices.size() > 2) && (x == a.vertices[a.vertices.size() - 1])) {
                        Path normal = normalize(a);
                        Path inv = invert(normal);
                        if(isNew(normal) && isNew(inv)) cycles.push_back(normal);
                    }

替换为

                    else if ((a.vertices.size() > 2) && (x == a.vertices[a.vertices.size() - 1])) {
                        Path normal = normalize(a);
                        Path inv = invert(normal);
                        if (isNew(normal) && isNew(inv)) {
                            cycleCount++;
                            cycles.push_back(normal);
                        }

                    }

我的建议仅针对此错误:完全删除edgeCountcycleCount,您可以使用cycles.size()edges.size()

来计算这些错误

此外,我将打印更改为cout:

in void runCycleSearch() function:

    cout << "Cycles:\n";
    for (int i = 0; i<cycleCount; i++) {
        for (unsigned j = 0; j<cycles[i].vertices.size(); j++) {
            cout << cycles[i].vertices[j] << " ";
        }
        cout << cycles[i].totalValue;
        cout << "\n";
    }

但是这段代码非常粗心并且充满了错误。例如,案例

4
1 2 0
2 3 0
3 4 0
1 4 0

返回

Cycles:
1 2 4 0
1 3 2 0
2 4 3 0
1 4 3 0

我可以继续更正此代码,但对我来说,从头开始重写更容易:)有很多问题:

  1. 图表示为边缘列表,因此查找特定边缘需要O(E)时间。这是非常低效的,用邻接列表替换它
  2. 尽量避免复制对象,每个向量都在复制,例如isNew(Path a)您需要将其替换为可能的引用。
  3. 以线性时间检查路径中的顶点的存在。为此目的使用全局集或无序集。您也可以使用全局路径变量,并且不需要在每次递归调用时复制它。