题解:AtCoder AT_awc0002_a Organizing the Bookshelf
本文分享的必刷题目是从蓝桥云课、洛谷、AcWing等知名刷题平台精心挑选而来,并结合各平台提供的算法标签和难度等级进行了系统分类。题目涵盖了从基础到进阶的多种算法和数据结构,旨在为不同阶段的编程学习者提供一条清晰、平稳的学习提升路径。
欢迎大家订阅我的专栏:算法题解:C++与Python实现!
附上汇总贴:算法竞赛备考冲刺必刷题(C++) | 汇总
【题目来源】
AtCoder:A - Organizing the Bookshelf (atcoder.jp)
【题目描述】
Takahashi works at a library. On a bookshelf in the library,N NNbooks are lined up in a row, and each book has a catalog number assigned to it. The catalog number of thei ii-th book from the left (1 ≤ i ≤ N 1≤i≤N1≤i≤N) isA i A_iAi. Note that different books may have the same catalog number.
高桥在图书馆工作。图书馆的书架上有一排N NN本书,每本书都分配有一个书目编号。从左数第i ii本书(1 ≤ i ≤ N 1 ≤ i ≤ N1≤i≤N)的书目编号为A i A_iAi。注意,不同的书可能具有相同的书目编号。
Aoki asks, “I’m looking for the book with catalog numberK KK. Where is it?”
青木问道:“我正在寻找书目编号为K KK的书。它在哪里?”
Among theN NNbooks on the bookshelf, find the book whose catalog number is exactlyK KK. If a book with catalog numberK KKexists, output the smallest position of such a book (counted from the left, 1-indexed). If no such book exists, output−1.
在书架上的N NN本书中,找到书目编号恰好为K KK的书。如果存在书目编号为K KK的书,输出这类书中位置最靠左的书的位置(从左计数,从1 11开始编号)。如果不存在这样的书,输出-1。
【输入】
N NNK KK
A 1 A 2 … A N A_1\ A_2\dots A_NA1A2…AN
- The first line contains an integerN NNrepresenting the number of books and an integerK KKrepresenting the catalog number being searched for, separated by a space.
- The second line contains integersA 1 , A 2 , … , A N A_1,A_2,…,A_NA1,A2,…,ANrepresenting the catalog numbers of the books, separated by spaces.
【输出】
If a book with catalog number exactlyK KKexists, output on a single line the smallest position of such a book (counted from the left, 1-indexed). If no such book exists, output−1.
【输入样例】
5 3 1 4 3 2 3【输出样例】
3【算法标签】
#模拟#
【解题思路】
【代码详解】
#include<bits/stdc++.h>usingnamespacestd;intn,k;// n: 序列长度,k: 要查找的数intmain(){cin>>n>>k;// 读入序列长度和要查找的数intpos=1;// 当前位置,从1开始计数for(inti=1;i<=n;i++){intx;cin>>x;// 读入当前数if(x==k)// 如果找到目标数{cout<<pos<<endl;// 输出当前位置return0;// 结束程序}pos++;// 当前位置加1}// 如果循环结束后仍然没有找到if(pos==n+1)// 等价于 i==n+1{cout<<-1<<endl;// 输出-1表示未找到}return0;}【运行结果】
5 3 1 4 3 2 3 3