以下代码使用Xcode 100%工作,但是当我使用Autograder运行代码时,我收到了以下错误Time out error, probably infinite loop C++
,如下图所示。
这是否意味着我的阵列太小了?
输入:
4 6
女性保守派新保守派退伍军人
特朗普女士1
特朗普保守党1
特朗普新保守派5
女性Neocons 1
Neocons Veterans 5
保守派退伍军人1
输出:
8
这是我的代码:
#include <iostream>
#include <algorithm>
#include <string>
#include <stdlib.h>
#include <vector>
#include <ctime>
#include <map>
using namespace std;
/*map Group Name to a Integer
useful for representation of graph
*/
map <string, int> nameToNumber;
/*
adjacency matrix to represent graph
this will work since number of nodes is less
*/
int graph[301][301];
/*
recursion to find if target is reachable from src in graph
par == parent of src.. useful to keep track of visited nodes
*/
bool reachable(int src, int target, int par = -1)
{
if (src == target) return true;
bool isReachable = false;
for (int i = 0; i < 100; ++i)
{
if (i != par && graph[src][i] != 0 && reachable(i, target, src))
{
isReachable = true;
}
}
return isReachable;
}
int main()
{
int n, m;
cin >> n >> m;
// add names to map
for (int i = 0; i < n; ++i) {
string name;
cin >> name;
nameToNumber[name] = i;
}
vector <pair<int, pair<int, int>>> edges;
// input edges
for (int i = 0; i < m; ++i)
{
string u, v; int w;
cin >> u >> v >> w;
edges.push_back(make_pair(w, make_pair(nameToNumber[v], nameToNumber[u])));
}
// sort edges based in increasing weights
sort(edges.begin(), edges.end());
int cost = 0;
for (int i = 0; i < edges.size(); ++i) {
int u = edges[i].second.first;
int v = edges[i].second.second;
int w = edges[i].first;
// check if u-v edge causes cycle
if (!reachable(u, v)) {
graph[u][v] = 1;
cost += w;
}
}
cout << cost ;
return 0;
}
每次我使用Autograder运行我的代码时都会收到以下错误Time out error, probably infinite loop
。