AtCoder备赛冲刺必刷题(C++) | 洛谷 AT_abc396_a Triple Four

本文分享的必刷题目是从蓝桥云课洛谷AcWing等知名刷题平台精心挑选而来,并结合各平台提供的算法标签和难度等级进行了系统分类。题目涵盖了从基础到进阶的多种算法和数据结构,旨在为不同阶段的编程学习者提供一条清晰、平稳的学习提升路径。

欢迎大家订阅我的专栏:算法题解:C++与Python实现!

附上汇总贴:算法竞赛备考冲刺必刷题(C++) | 汇总


【题目来源】

洛谷:AT_abc396_a [ABC396A] Triple Four - 洛谷

【题目描述】

You are given an integer sequence of length N : A = ( A 1 , A 2 , … , A N ) N: A=(A_1,A_2,…,A_N) N:A=(A1,A2,,AN).
给定一个长度为 N 的整数序列: N : A = ( A 1 , A 2 , … , A N ) N: A=(A_1,A_2,…,A_N) N:A=(A1,A2,,AN)

Determine whether there is a place in A A A where the same element appears three or more times in a row.
判断 A A A 中是否存在某个位置,使得相同的元素连续出现三次或更多次。

More formally, determine whether there exists an integer i i i with 1 ≤ i ≤ N − 2 1≤i≤N−2 1iN2 such that A i = A i + 1 = A i + 2 A_i=A_{i+1}=A_{i+2} Ai=Ai+1=Ai+2.
更正式地说,判断是否存在一个整数 i ( 1 ≤ i ≤ N − 2 ) i(1≤i≤N−2) i(1iN2),使得 A i = A i + 1 = A i + 2 A_i=A_{i+1}=A_{i+2} Ai=Ai+1=Ai+2

【输入】

The input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

【输出】

If there is a place in A A A where the same element appears three or more times in a row, print Yes. Otherwise, print No.

【输入样例】

5
1 4 4 4 2

【输出样例】

Yes

【算法标签】

《洛谷 AT_abc396_a [ABC396A] Triple Four》 #模拟#

【代码详解】

#include 
using namespace std;

const int N = 105;  // 定义常量 N,表示数组的最大长度
int n;              // 定义变量 n,表示数组的长度
int a[N];           // 定义数组 a,用于存储输入的元素

int main()
{
    cin >> n;  // 输入数组的长度 n
    for (int i = 1; i <= n; i++)
        cin >> a[i];  // 输入数组 a 的元素

    // 遍历数组,检查是否存在连续的三个相等元素
    for (int i = 1; i <= n - 2; i++)  // 注意循环范围是 1 到 n-2,避免越界
    {
        // 检查当前元素、下一个元素和下下个元素是否相等
        if (a[i] == a[i + 1] && a[i + 1] == a[i + 2])
        {
            cout << "Yes" << endl;  // 如果存在连续的三个相等元素,输出 "Yes"
            return 0;               // 直接结束程序
        }
    }

    // 如果遍历完数组都没有找到连续的三个相等元素,输出 "No"
    cout << "No" << endl;
    return 0;
}

【运行结果】

5
1 4 4 4 2
Yes

你可能感兴趣的:(c++,算法,开发语言)