My solution for ADACYCLE was correct, but it gave me TLE when I submit it. I’m not sure how to optimise my solution. I read this hint: “consider those edges that the current node stems to. You should know this before or preprocess it.”, I’m not sure what it means, I need some hints.
code:
#include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> vertex;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int N;
unordered_map<int, vector<int>> adj;
cin >> N;
for (int i = 1; i <= N; ++i)
{
vector<int> v;
int on;
for (int j = 1; j <= N; ++j)
{
cin >> on;
if (on)
v.push_back(j);
}
adj[i] = v;
}
for (int i = 1; i <= N; ++i)
{
unordered_map<int, int> m;
queue<vertex> q;
vertex start = make_pair(i, 0);
bool flag = false;
int shortest = INT_MAX;
m[i] = 1;
q.push(start);
while (!q.empty())
{
vertex v = q.front();
q.pop();
if (v.first == i && v.second != 0)
{
if (!flag) flag = true;
shortest = min(shortest, v.second);
continue;
}
for (int n : adj.at(v.first))
{
vertex s = make_pair(n, v.second + 1);
if (m.find(s.first) == m.end() || s.first == i)
{
m[s.first] = 1;
q.push(s);
}
}
}
if (flag)
cout << shortest << "\n";
else
cout << "NO WAY\n";
}
return 0;
}