I. Painting a Square
outputstandard output
There is a square of size a×a. In its top left corner there is a square brush of size b×b. You should use this brush to paint a square (you can assume that the top left corner of size b×b is already painted). It is allowed to move a brush only in parallel to the square's sides. What is the minimal distance the center of the brush should pass to make the whole square painted?
Input
The input contains two integers a and b (1≤b≤a≤106) — the sides of the square and the brush, correspondingly.
Output
Output a single integer — the minimal distance that should be passed by the center of the brush. It is guaranteed that the answer is an integer.
Examples
inputCopy
4 2
outputCopy
6
inputCopy
4 3
outputCopy
3
inputCopy
9 3
outputCopy
24
inputCopy
1000000 1
outputCopy
999999999999
题目描述:
a*a的正方体左上角有一个b*b的正方体刷子,问刷子刷完整个a*a正方体要移动多少步。
分析:
可以先考虑先把边缘都刷完,里面的还没刷的正方体就变成(a-2b)*(a-2b)的正方体。
就是下面的dfs代码:
void dfs(int x)//这里面的x一开始就是a { if(x<=b) { ans+=(x-b); return; } if(x<=2*b) { ans+=3*(x-b); return; } else { ans+=4*(x-b); dfs(x-2*b); } }
因为数据比较大,把dfs计算的式子展开,若最后x<=b,可以得到4*(x-b+x-3b+x-5b+....)+(x-b),若最后x<=2*b,可以得到4*(x-b+x-3b+x-5b+....)+3*(x-b)。
再用一下等差数列求和公式,得到直接计算的代码:
#include<iostream> #include<algorithm> #include<cstring> #include<cstdio> #include<sstream> #include<vector> #include<stack> #include<deque> #include<cmath> #include<map> #define lson i<<1,l,mid #define rson i<<1|1,mid+1,r using namespace std; typedef long long ll; const int maxn=1e6+6; ll a,b; ll ans=0; int main() { cin>>a>>b; ll d=a/(2*b); ll mo=a%(2*b); if(a%(2*b)==0) mo=2*b,d--; ll ans; if(mo<=b) ans=(a-2*b*d-b); else ans=3*(a-2*b*d-b); ans+=4*(d*a-(1+2*(d-1)+1)*d/2*b); cout<<ans<<endl; return 0; }