### lalit.n.chandora's blog

By lalit.n.chandora, history, 10 months ago,

So there's this question 939A - Love Triangle which has a tag of "graph" and I can't seem to find a solution for it. :( Although, the solution for this problem is available but it does not use graphs. I really wanted to know a solution which uses graph since it has a tag of "graph". Here's my approach for it 77461286

Here it checks for the number of vertices which has more than or equal to 3 occurences, if they are more than or equal to 3 then it prints YES. But, it fails on test 4. Please help.

• -8

 » 10 months ago, # |   0 First of all, your approach is wrong when the graph is like a square. I suggest thinking that f(x) shows the special case of a directed graph. f(x) is the only one direct successor of x.
•  » » 10 months ago, # ^ |   0 Oh, I was taking it as an undirected graph. Thanks a lot for pointing it out. :)
 » 10 months ago, # | ← Rev. 2 →   0 You can model almost any problem into a graph. This problem has the tag "Graph" which means it is solvable using graphs, but not necessarily that it is solvable only using graphs. Even problems that don't have the tag can probably be solved by modelling into a graph. The main idea required to solve a problem using graphs is to think "How can I model this into a graph". This problem being relatively simple, you can just check for a cycle using the code below. Codeint main () { ios::sync_with_stdio (false); cin.tie (nullptr); cout.precision (10); cout << fixed << boolalpha; int N; cin >> N; vector A (N); for (int& i : A) cin >> i; bool Cycle = false; for (int i = 0; i < Nodes; i++) { if (A [A [A [i] - 1] - 1] - 1 == i) { Cycle = true; break; } } cout << (Cycle ? "YES" : "NO"); return 0; } If you want to go all in, you can model the graph and then run a cycle detection algorithm for unweighted graphs.
•  » » 10 months ago, # ^ |   0 Oh I see, I am new in my journey. Thanks a lot. I will try it out.
 » 5 weeks ago, # |   0 here is my approach using graphs — #include #include #define usi unsigned short int #define ui unsigned int #define ulli unsigned long long int using namespace std; int main() { //ios_base::sync_with_stdio(false); //cin.tie(NULL); //cout.tie(NULL); usi n; cin>>n; usi a[n]; for(usi i=0;i>a[i]; for(usi i=0;i