题解:P16846 [GKS 2021 #C] Alien Generator
邵屹淇
·
·
题解
题解:P16846 [GKS 2021 #C] Alien Generator
本题看似是一道橙题,但是想做满分也属实不容易。
题意
- 第一天为一个正整数 K,第 i 天则为 K + i - 1。
- 累计总数一旦超过 G,机器就立刻损坏(当天的产出不算,累计数不计超过部分)。
- 目标是:最终累积总数恰好等于 G。
- 你需要求解出 K 的可能性总数。
解法
- 这道题先要用到等差数列求和的公式,将问题转化,然后再枚举求解。
- 给定 K,以及生成金条的天数 n,产生的金条总数就是。
- 金条求解方法为 \frac{(2K + n - 1)}{2}。
于是,作者便得出了以下代码。
#include<bits/stdc++.h>
#define For(i ,x ,y) for(ll i = x; i <= y; ++ i)
#define Dor(i ,x ,y) for(ll i = x; i >= y; -- i)
using namespace std;
typedef long long ll;
ll T,G,g,mid,ans;
int main(){
cin >> T;//T组数据
For(i1 ,1 ,T){
cin >> G;
ans = 0;
For(i ,1 ,G){
if(i > G) break;
mid = i;
g = G;
while(g >= mid) g -= mid,mid++;
if(g == 0) ans++;
}
cout << "Case #" << i1 << ": " << ans << "\n";//输出
}
}
结果,7 分 TLE。
思考一下,我们哪里会导致时间超限呢?
由此,作者想到了枚举 $\sqrt{2 * G}$ 这个区间。
于是,我的第二版代码出版了。
```
#include<bits/stdc++.h>
#define For(i ,x ,y) for(ll i = x; i <= y; ++ i)
#define Dor(i ,x ,y) for(ll i = x; i >= y; -- i)
using namespace std;
typedef long long ll;
ll T,G,g,mid,ans,m,d,K,b;
int main(){
cin >> T;//T组数据
For(i1 ,1 ,T){
cin >> G;
ans = 0;
for(int i = 1; i * i <= G * 2; ++ i){
if((2 * G) % i != 0) continue;
b = (2 * G) / i;
if((b - (i - 1)) % 2 == 0){
K = ((b - (i - 1)) / 2);
if(K > 0) ans++;
}
m = (2 * G) / i;
if(m != i){
d = (2 * G) / m;
if(d - (m - 1) % 2 == 0){
K = (d - (m - 1)) / 2;
if(K > 0) ans++;
}
}
}
cout << "Case #" << i1 << ": " << ans << "\n";//输出
}
}
```
但是,现实却如同一个响亮的耳光,狠狠劈在我的脸上,还是TLE。
就在我即将放弃之时,我发现了,$2.20$ 秒还是 TLE,说明循环次数虽然理论上是 $O (\sqrt{G})$,但常数太大了,而且每次循环里做了**两次**完整的因数判断和 $K$ 计算。
我决定进一步优化——同一个因数只判断一次,并且减少取模和除法次数。
终于,我 ${\color{green} AC}$ 了。
::::success[AC code]
```
#include<bits/stdc++.h>
#define For(i ,x ,y) for(ll i = x; i <= y; ++ i)
#define Dor(i ,x ,y) for(ll i = x; i >= y; -- i)
using namespace std;
typedef long long ll;
ll T, G, g, mid, ans, m, d, K, b;
int main(){
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);//快读快输
cin >> T;
//T组数据
For(i1, 1, T){
cin >> G;
ans = 0;
for (ll i = 1; i * i <= G * 2; ++ i){
if ((2 * G) % i != 0) continue;
b = (2 * G) / i;
if (((b - (i - 1)) & 1) == 0){
K = ((b - (i - 1)) >> 1);// >> 1 比 /2 更快
if (K > 0) ans++;
}
m = (2 * G) / i;
if (m != i){
d = (2 * G) / m;
if ((d - (m - 1) & 1) == 0){
K = (d - (m - 1)) >> 1;
if (K > 0) ans++;
}
}
}
cout << "Case #" << i1 << ": " << ans << "\n";
//输出
}
}
```
::::
制作不易,还是恳请管理员大大通过。