Codeforces Round #464 (Div. 2) A. Love Triangle[判断是否存在三角恋]
1 second
256 megabytes
standard input
standard output
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.
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 «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.
5
2 4 5 1 3
YES
5
5 5 5 5 1
NO
In first example plane 2 likes plane 4, plane 4 likes plane 1, plane 1 likes plane 2 and that is a love triangle.
In second example there are no love triangles.
[题意]:判断是否存在A喜欢B,B喜欢C,C喜欢A.(即三角恋)
[分析]:a[a[a[i]]]==i可以判断存在三角恋
[代码]:
#include<bits/stdc++.h> using namespace std;
const int maxn = +; int main()
{
int n,a[maxn],ans,j,k;
while(cin>>n)
{
ans=;
for(int i=;i<=n;i++)
{
cin>>a[i];
} for(int i=;i<=n;i++)
{
j=a[i];
k=a[j];
if(a[k]==i && i!=j && j!=k && i!=k) ans++;
}
printf("%s\n",ans?"YES":"NO");
}
}
交换变量法
#include<bits/stdc++.h> using namespace std;
const int maxn = +; int main()
{
int n,a[maxn],f,ans;
while(cin>>n)
{
for(int i=;i<=n;i++)
cin>>a[i];
f=;
for(int i=;i<=n;i++)
{
if(a[a[a[i]]]==i) f=;
}
printf("%s\n",f?"YES":"NO");
}
}
数组嵌套法
最新文章
- Coursera台大机器学习课程笔记7 -- Noise and Error
- Android--Retrofit的简单使用(一)
- iOS中的多线程及GCD
- 函数xdes_find_bit
- bzoj1231: [Usaco2008 Nov]mixup2 混乱的奶牛
- Python爬虫实战(1):爬取Drupal论坛帖子列表
- nginx-gridfs 的安装配置和使用
- 《探索未知种族之osg类生物》目录
- 小问题填坑,关于obj.x和obj[";x";]
- WPA简介
- UUChart的使用
- mongodb批量操作, bulk_write,
- 【PyQt5-Qt Designer】按钮系列
- Java IO中转换流的作用
- Swift语言精要 - 属性
- The YubiKey NEO
- Maximum Likelihood Method最大似然法
- PyalgoTrade 打印收盘价(二)
- Js里头的对象字面量
- ***七牛跨域上传图片JS SDK