题解:P14039 [PAIO 2025] Cake
题目传送门
题目大意:
有一个大小为
法一(暴力枚举)
我们拿到题目首先想到的是这种方法:
直接去模拟且正方形过程,写一个 while 即可,算完即可退出程序,返回计算结果。
我们可以“轻松”写出以下代码:
#include <bits/stdc++.h>
using namespace std;
int count_square_cakes(int N,int M) {
int cnt=0;
while(1){
cnt++;
if(N>M) N-=M;
else if(M>N) M-=N;
else break;
}
return cnt;
}
那么这个代码有什么问题呢?
如果细心的读者测试即可发现,第一个测试点会 TLE。
怎么办呢?很简单,只需特判
#include <bits/stdc++.h>
using namespace std;
int count_square_cakes(int N,int M) {
int cnt=0;
if(M==1) return N;
while(1){
cnt++;
if(N>M) N-=M;
else if(M>N) M-=N;
else break;
}
return cnt;
}
以上即为法一的解法,但是,只能写出 82 分,但是已经够发题解了。
法二(优化,100 分!)
我们想一下有什么可以优化的呢?
很明显,我们可以预判 TA 切正方形,只需要模一下就好了(注意,要保证
#include <bits/stdc++.h>
using namespace std;
int count_square_cakes(int N,int M) {
int cnt=0;
if(N==M) return 1;
if(N%M==0) return N/M;
if(M%N==0) return M/N;
while(1){
if(M>N) swap(M,N);
cnt+=N/M;
N%=M;
if(N==0) return cnt;
}
}
PS:创作不易,麻烦点一个正着的小拇指谢谢!
在这里鸣谢 @jiu_wei 大佬提供的输出帮助!
这是评测记录