Link to the problem: SPOJ.com - Problem ADACYCLE
My code:
#include <bits/stdc++.h>
using namespace std;
#define FASTIO ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
const int MAXN = 2005;
int n;
vector<vector<int>> adj(MAXN);
vector<int> len(MAXN,MAXN);
int main()
{
FASTIO
cin >> n;
int x;
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
cin >> x;
if(x) adj[i].push_back(j);
}
}
for(int i=0; i<n; i++)
{
vector<bool> color(n,0);
vector<int> dist(n,0);
queue<int> q;
q.push(i);
color[i] = 1;
while(!q.empty())
{
int u = q.front();
q.pop();
for(int v : adj[u])
{
if(color[v] == 2) continue;
if(color[v] == 1 && v == i) len[i] = min(len[i], dist[u]-dist[v]+1);
if(color[v] == 0)
{
color[v] = 1;
dist[v] = 1+dist[u];
q.push(v);
}
}
color[u] = 2;
}
}
for(int i=0; i<n; i++) cout << ((len[i] != 2005) ? to_string(len[i])+"\n" : "NO WAY\n");
cout << "\n";
return 0;
}
The time complexity of the above code is O(V x (V+E)) which in the worst case becomes O(V^3), but I really don’t know about any optimizations that I can apply here to get rid of that TLE. Can anyone please help me with this?