题目如下
A. Love Triangle
time limit per test1 second
memory limit per test256 megabytes
As you could know there are no male planes nor female planes. However, each plane on Earth likes some other plane. There are n planes on Earth, numbered from 1 to n, and the plane with number i likes the plane with number fi, where 1 ≤ fi ≤ n and fi ≠ i.
We call a love triangle a situation in which plane A likes plane B, plane B likes plane C and plane C likes plane A. Find out if there is any love triangle on Earth.
Input
The first line contains a single integer n (2 ≤ n ≤ 5000) — the number of planes.
The second line contains n integers f1, f2, ..., fn (1 ≤ fi ≤ n, fi ≠ i), meaning that the i-th plane likes the fi-th.
Output
Output «YES» if there is a love triangle consisting of planes on Earth. Otherwise, output «NO».
You can output any letter in lower case or in upper case.
题目大意
现有n个飞机,编号从1到n,数组元素的值代表了每个飞机喜欢的飞机编号,如果A->B,B->C, C->A,那么称之为三角恋,请问上述飞机中是否存在这种情况。
题目分析
嵌套即可,确认B喜欢的飞机C喜欢的飞机是不是A即可。
点击查看代码
#include <iostream>
using namespace std;int main(){int n;cin >> n;int like[5005];for(int i = 1; i <= n; i++){cin >> like[i];}bool tri = false;for(int i = 1; i < n; i++){if(like[like[like[i]]] == i){tri = true;break;}}if(tri){printf("YES\n");}else{printf("NO\n");}return 0;
}