题解:AtCoder AT_awc0046_b Organizing the Locker
2026/5/6 6:16:36 网站建设 项目流程

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

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

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


【题目来源】

AtCoder:B - Organizing the Locker

【题目描述】

Takahashi is in charge of managingN NNlockers in the school gymnasium. The lockers are numbered from1 11toN NN. Initially, all lockers are closed.
高桥负责管理学校体育馆的N NN个储物柜。储物柜编号从1 11N NN。初始时,所有储物柜都是关闭的。

Takahashi will performN NNoperations. In thei ii-th operation (i = 1 , 2 , … , N i = 1, 2, \ldots, Ni=1,2,,N), for every locker whose number is a multiple ofi ii(including locker numberi iiitself), he toggles its state: if it is open, he closes it, and if it is closed, he opens it.
高桥将执行N NN次操作。在第i ii次操作中(i = 1 , 2 , … , N i = 1, 2, \ldots, Ni=1,2,,N),对于每个编号是i ii的倍数的储物柜(包括编号为i ii的储物柜本身),他会切换其状态:如果它是打开的,则关闭它;如果它是关闭的,则打开它。

For example, in the 1st operation, he toggles the state of all lockers whose numbers are multiples of1 11, namely lockers1 , 2 , … , N 1, 2, \ldots, N1,2,,N. In the 2nd operation, he toggles the state of lockers whose numbers are multiples of2 22and at mostN NN, namely lockers2 , 4 , 6 , … 2, 4, 6, \ldots2,4,6,. In the 3rd operation, he toggles the state of lockers whose numbers are multiples of3 33and at mostN NN, namely lockers3 , 6 , 9 , … 3, 6, 9, \ldots3,6,9,.
例如,在第 1 次操作中,他会切换所有编号是1 11的倍数的储物柜的状态,即储物柜1 , 2 , … , N 1, 2, \ldots, N1,2,,N。在第 2 次操作中,他会切换编号是2 22的倍数且不超过N NN的储物柜的状态,即储物柜2 , 4 , 6 , … 2, 4, 6, \ldots2,4,6,。在第 3 次操作中,他会切换编号是3 33的倍数且不超过N NN的储物柜的状态,即储物柜3 , 6 , 9 , … 3, 6, 9, \ldots3,6,9,

After all operations are completed, find the number of lockers that are open.
所有操作完成后,求处于打开状态的储物柜数量。

【输入】

N NN

An integerN NNrepresenting the number of lockers is given on a single line.

【输出】

Print the number of lockers that are open after all operations are completed, as an integer on a single line.

【输入样例】

10

【输出样例】

3

【算法标签】

#整数二分#

【代码详解】

#include<bits/stdc++.h>usingnamespacestd;#defineintlonglongintn;signedmain(){cin>>n;// 输入n// 二分查找:寻找最大的整数x,使得x² ≤ nintl=1,r=1e9;// 二分查找的左右边界// 二分查找模板while(l<r){intmid=(l+r+1)/2;// 上取整,避免死循环if(mid*mid<=n)// 如果mid的平方小于等于nl=mid;// 说明mid可能太小,向右缩小范围elser=mid-1;// 否则mid太大,向左缩小范围}cout<<l<<endl;// 输出结果:⌊√n⌋return0;}

【运行结果】

10 3

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询