嗨,我是c ++的新手,正在尝试为最小割实现随机图收缩算法。该图表示为向量(数据)的向量,其中每个向量的第一个条目表示一个顶点,其余条目是与其相连的顶点。 这是随机收缩的功能:
std::vector<std::vector<int> > contraction (std::vector<std::vector<int> > data)
{
srand (time(NULL));
//choose a random vertex
int randNum = rand()%(data.size());
//choose a random vertex connected to the first
int randNum2 = rand()%(data[randNum].size()-1) +1;
//loop through all vertices
for (int i = 0; i < data.size(); i++)
{
//find the entry corresponding to the second vertex
if (data[i][0] == data[randNum][randNum2])
{
for (int j =1; j <data[i].size(); j++)
{
//no self loop
if (data[i][j] !=data[randNum][0])
//add the vertex connection from the second vertex to the first one
data[randNum].push_back(data[i][j]);
}
//remove the entry for the second vertex
data.erase (data.begin()+i-1);
}
}
for (int i = 0; i < data.size(); i++)
{
//all vertices connected to the second vertex are to be connected to the first
for (int j =1; j <data[i].size(); j++)
{
if (data[i][j] == data[randNum][randNum2])
data[i][j] = data[randNum][0];
}
}
//now the graph has one less vertex
return data;
}
此函数在主体中被迭代调用:
while (data.size() > 2)
{
data = contraction (data);
}
图形永远不会缩小到两个顶点。该程序在几次迭代后终止,没有任何错误。它经历的迭代次数是可变的,通常为20-30。我不知道为什么它会过早终止,我们将不胜感激。