【发布时间】:2017-03-28 18:12:29
【问题描述】:
int main()
{
char line[100];
int N = 5;
vector<int>adj[N];
FILE *in = fopen("test.txt", "r");
for (int i = 1; i <= N; i++) // Accepting the graph from file
{
fgets(line, 100, in);
char *pch = strtok(line, "\t \n");
int u = atoi(pch);
pch = strtok(NULL, "\t \n");
while (pch != NULL)
{
int v = atoi(pch);
adj[u-1].push_back(v);
pch = strtok(NULL, "\t \n");
}
}
for( int i = 0; i < 5; i++ ) // printing the graph
{
for( int p = 0 ; p < adj[i].size(); p++ )
{
cout<< i+1 << " , "<< adj[i][p]<<endl;
}
}
if (isCycle(adj))
cout << endl << "graph contains cycle" ;
else
cout << endl << "graph does not contain cycle" ;
return 0;
}
int isCycle( vector<int> adj[] )
{
// Allocate memory for creating V subsets
int *parent = (int*) malloc( 5 * sizeof(int) );
// Initialize all subsets as single element sets
memset(parent, -1, sizeof(int) * 5);
for(int i = 0; i < 5; i++)
{
for( int p = 0 ; p < adj[i].size(); p++ )
{
int x = find(parent,i);
int y = find(parent, adj[i][p]-1); // I think problem is here
if (x == y)
return 1;
Union(parent, x, y);
}
}
return 0;
}
// A utility function to find the subset of an element i
int find(int parent[], int i)
{
if (parent[i] == -1)
return i;
return find(parent, parent[i]);
}
// A utility function to do union of two subsets
void Union(int parent[], int x, int y)
{
int xset = find(parent, x);
int yset = find(parent, y);
parent[xset] = yset;
}
test.txt 文件包含以下输入:
1 2 3
2 1 4 5
3 1
4 2
5 2
第一列包含顶点 (1 - 5)
1 2 3
上排(第一行)表示,Node 1 连接到Node 2 和Node 3
2 1 4 5
上排(第 2 排)表示,Node 2 连接到 Node 1、Node 4 和 Node 5
现在的问题是,接受它总是说的任何输入:图形包含循环。(虽然图形不包含循环) 现在在上面的输入图中不包含循环,但说图包含循环。 我哪里错了??谁能帮我 ??
【问题讨论】:
-
vector<int>adj[N];是一个可变长度数组,不是 C++ 标准的一部分。避开他们 -
我在这里也看到了很多 C。这段代码可以受益于更现代的 C++
-
@AndyG 是的,它混合了 C 和 C++。我没有得到 C++ 代码来读取图形文件,所以我使用了我知道的 C 代码。我应该使用“new”而不是“malloc”对不起,但现在我的目标不是纯 C++ 代码。
-
@AndyG 你能检查一下我的 isCycle() 函数,这似乎是错误的。 union() 和 find() 以及接受图,打印图都经过测试。
-
你有
malloc,没有free。您使用 1 和 0 代替true和false。您使用文件句柄而不是文件流。有可变长度数组。你有一个 c 风格的向量数组。您正在使用字符缓冲区而不是 std::string。考虑到所有这些事情,难怪你没有时间专注于逻辑错误。请稍等,我会为您更新。
标签: c++ algorithm graph union-find