题解:P11310 无穷的迭代器
pengyirui
·
·
题解
思路
暴力
直接模拟
方法:方如其名,直接模拟,期望得分——15。
评测记录。
暴力代码
#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;
}
超时分析
样例较大,18 至 22 行的数据转化耗费了过多时间。
优化
每乘一次相当于将原数字减少一个因数——2。
以上结论的证明
在输入转浮点数首次操作时,有两种情况,在此分类讨论。
情况 1:
##### 情况 2:
$$r \bmod 2=0$$,设 $$r\div b=n$$,转化后为 $$(2\times n+\frac{1}{2})\times (2\times n+1)=4\times n\times n+3\times n+
\frac{1}{2}$$,可以得出以上式子除以 $$2$$ 等于 $$1$$(假设 $$n$$ 是奇数),而原来的 $$r$$ 是偶数,所以减少了一个因数 $$2$$,程序继续执行以上逻辑,依旧是两种情况,直到变成情况 $$1$$,结束程序。
#### 代码([AC记录](https://www.luogu.com.cn/record/198520663))
```cpp
#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;
}
```
## 找规律
暴力不好过,打表找规律。
通过打表,可得:
如果 $$s$$ 为 $$k$$ 二进制中 $$0$$ 的个数,那么次数就是 $$s+1$$。$$k=0$$ 时应特判输出 ```NO```。
### AC代码
```cpp
#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;
}
```
# 代码合集
所以本题共有 $$2$$ 种方法可以 AC 。
### 方法 2
```cpp
#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
```cpp
#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;
}
```