没有STL实现图形的最佳方法?

时间:2013-07-15 20:31:36

标签: data-structures tree graph-theory minimum-spanning-tree

我被分配了一个项目,我必须接受一堆节点,以及某些节点之间有权重的边。

然后,我必须使用此信息为图形的每个连接组件查找最小生成树(因此,如果图形具有两个连接组件,则需要创建两个生成树)

问题是我不能使用任何STL库,除了。

我知道我需要创建自己的数据结构,但我不知道我需要哪些数据结构。我想最小的堆对于找到要使用的最低权重边缘是有用的,但我将如何为每个连接的组件创建最小堆?

我认为我需要实现union-find才能组织连接组件集。

我需要为此实现哪些其他数据结构?

2 个答案:

答案 0 :(得分:1)

对于union-find,你需要实现DISJOINT SET。

这里是使用简单数组的简单实现..看看

// Disjoint Set implementation
// Shashank Jain

#include<iostream>
#define LL long long int
#define LIM 100005
using namespace std;
int p[LIM],n; // p is for parent
int rank[LIM];
void create_set()
{
    for(int i=1;i<=n;i++)
    {
        p[i]=i;
        rank[i]=0;
    }
}
int find_set(int x)
{
    if(x==p[x])
        return x;
    else    
    {
        p[x]=find_set(p[x]);
        return p[x];
    }           
}
void merge_sets(int x,int y)
{
    int px,py;
    px=find_set(x);
    py=find_set(y);
    if(rank[px]>rank[py])
        p[py]=px;
    else
    if(rank[py]>rank[px])
        p[px]=py;
    else
    if(rank[px]==rank[py])
    {
        p[px]=py;
        rank[py]++;
    }               
}
int main()
{
    cin>>n; // no: of vertex , considering that vertex are numbered from 1 to n
    create_set();
    int a,b,q,i;
    cin>>q; // queries
    while(q--)
    {
        cin>>a>>b;
        merge_sets(a,b);
    }
    for(i=1;i<=n;i++)
    {
        cout<<find_set(i)<<endl; // vertex having same value of find_set i.e same representative of set are in same subset  
    }
    return 0;
}

答案 1 :(得分:0)

我将假设你可以选择你的MST算法并且输出是一个边缘列表。 Borůvka's algorithm易于实现,除了图形和不相交的集合结构之外,不需要任何数据结构。相比之下,Prim的算法需要一个优先级队列和一些逻辑来处理断开连接的图形,而Kruskal的算法需要一个不相交的集合结构一个排序算法。我会像这样设置数据结构。每个事件顶点边对都有一个邻接记录。

struct Adjacency;

struct Edge {
    int weight;
};

struct Vertex {
    struct Adjacency *listhead;  // singly-linked list of adjacencies
    struct Vertex *parent;  // union-find parent
};

struct Adjacency {
    struct Adjacency *listnext;
    struct Edge *edge;
    struct Vertex *endpoint;  // the "other" endpoint
};
相关问题