跳到正文

题解

题解:P11310 无穷的迭代器

pengyirui约 5 分钟
原文
文章信息与版本

文章信息

发布
2025年1月16日
收录
2025年12月12日
更新
2026年9月12日
篇幅
约 5 分钟
题目
P11310

版本

  1. v1当前

思路

暴力

直接模拟

方法:方如其名,直接模拟,期望得分——1515。
评测记录。

暴力代码
C++
#include<bits/stdc++.h> 
#define int long long
using namespace std;
int T,k;
signed main()
{
	cin>>T;
	while(T--)
	{
		cin>>k;
		if(k==0)
		{
			cout<<"NO!";
			break;
		}
		double r=k+0.5;
		int ans=0;
		while((int)r!=r)
		{
			ans++;
			r*=double((int)r+1);
		}
		cout<<ans<<endl;
	}
	return 0;
}
超时分析

样例较大,1818 至 2222 行的数据转化耗费了过多时间。

优化

每乘一次相当于将原数字减少一个因数——22。

以上结论的证明

在输入转浮点数首次操作时,有两种情况,在此分类讨论。

情况 1:

r mod 2=1r \bmod 2=1 ,设 ⌊r÷2⌋=n\lfloor r\div 2 \rfloor =n ,转化后为 (2×n+32)×(2×n+2)=4×n×n+4×n+3×n+3(2\times n+\frac{3}{2})\times (2\times n+2)=4\times n \times n+4\times n+3\times n+3 ,可以证明以上为整数,程序结束。

情况 2:

r mod 2=0r \bmod 2=0,设 r÷b=nr\div b=n,转化后为 (2×n+12)×(2×n+1)=4×n×n+3×n+12(2\times n+\frac{1}{2})\times (2\times n+1)=4\times n\times n+3\times n+ \frac{1}{2},可以得出以上式子除以 22 等于 11(假设 nn 是奇数),而原来的 rr 是偶数,所以减少了一个因数 22,程序继续执行以上逻辑,依旧是两种情况,直到变成情况 11,结束程序。

代码(AC记录)
C++
#include<bits/stdc++.h> 
#define int long long
using namespace std;
int T,k;
signed main()
{
	cin>>T;
	while(T--)
	{
		cin>>k;
		if(k==0)
		{
			cout<<"NO!";
			continue;
		}
		int ans=1;
		while(k%2==0)
		{
			ans++;
			k/=2;
		}
		cout<<ans<<endl;
	}
	return 0;
}

找规律

暴力不好过,打表找规律。
通过打表,可得: 如果 ss 为 kk 二进制中 00 的个数,那么次数就是 s+1s+1。k=0k=0 时应特判输出 NO。

AC代码

C++
#include<bits/stdc++.h> 
#define int long long
#define lowbit(x) (x)&(-(x))
using namespace std;
int T,k;
signed main()
{
	cin>>T;
	while(T--)
	{
		cin>>k;
		if(k==0)
		{
			cout<<"NO!";
			break;
		}
		cout<<log2(lowbit(k))+1<<endl;
	}
	return 0;
}

代码合集

所以本题共有 22 种方法可以 AC 。

方法 2

C++
#include<bits/stdc++.h> 
#define int long long
using namespace std;
int T,k;
signed main()
{
	cin>>T;
	while(T--)
	{
		cin>>k;
		if(k==0)
		{
			cout<<"NO!";
			continue;
		}
		int ans=1;
		while(k%2==0)
		{
			ans++;
			k/=2;
		}
		cout<<ans<<endl;
	}
	return 0;
}

方法 3

C++
#include<bits/stdc++.h> 
#define int long long
#define lowbit(x) (x)&(-(x))
using namespace std;
int T,k;
signed main()
{
	cin>>T;
	while(T--)
	{
		cin>>k;
		if(k==0)
		{
			cout<<"NO!";
			break;
		}
		cout<<log2(lowbit(k))+1<<endl;
	}
	return 0;
}
原文