【发布时间】:2016-08-14 08:09:30
【问题描述】:
一个问题涉及在有向图中进行深度优先搜索,以查找可以从特定节点到达的所有节点。下面给出的解决方案在 codechef 上给出了错误的结果。但是我找不到任何可能产生与通常的 DFS 算法不同的结果的测试用例。
我知道我可以直接实现正确的算法以获得正确的结果,但我想了解为什么我的解决方案不正确,以便以后不再重复。请帮助我确定此解决方案有什么问题。代码被注释以解释我的方法
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
typedef long long int lli;
vector <lli> g[1000+5]; // the adjacency list 1 indexed
void dfs(lli j, lli i);
int main(){
lli n, m, k, a, b;
// n = number of nodes
// m = number of relations
// k = multiplication factor
cin >> n >> m >> k;
while(m--){
// a,b means a is dependent upon b (directed graph)
cin >> a >> b;
g[a].push_back(b);
}
for(lli j = 1; j <= n; j++)
for(lli i = 0; i < g[j].size(); i++){
dfs(j, g[j][i]); // adds dependencies of g[j][i]
// to adjacency list of j
}
// ans is the minimum no of nodes dependent on a particular node
lli ans = g[1].size();
for(lli i = 1; i <= n; i++){
if(g[i].size() < ans)
ans = g[i].size();
}
cout << (ans+1)*k <<"\n";
}
void dfs(lli j, lli i){
// adding dependencies of a node to itself
// would result in an infinite loop?
if(i != j){
for(lli k = 0; k < g[i].size(); k++){
// a node is not dependent on itself
if(g[i][k]!=j && find(g[j].begin(), g[j].end(), g[i][k])==g[j].end()){
g[j].push_back(g[i][k]);
dfs(j, g[i][k]);
}
}
}
}`
问题链接:problem
正确解决方案的链接:correct solution
【问题讨论】:
-
同意。这属于代码审查。
-
只有在代码真正正常工作时才属于CodeReview。
-
您是否收到裁判的“错误结果”或“超出时间限制”?
-
请将带有硬编码输入的代码发布到您的程序中。看到所有这些“在线法官”帖子会很累,并且发布的代码包含像这样的
cin语句(cin >> n >> m >> k;)。只需将 n、m 和 k 初始化为重现错误的值。