F. Fair Distribution time limit per test1 second memory limit per test512 megabytes inputstandard input outputstandard output There are n robots and m energy bars in the Dream Kingdom. DreamGrid, the king, is trying to make a fair distribution of the energy bars. A fair distribution exists if and only if the number of the energy bars is a multiple of the number of robots. The only tool DreamGrid has is a powerful laser gun. Every time he turns on the laser gun, he can do exactly one of the two things: Create a new energy bar. Destroy a robot. To avoid the extinction of robots, it's forbidden to destroy all the n robots. It takes one dollar to turn on the laser gun once. You are asked to find the minimum cost of making a fair distribution. Input There are multiple test cases. The first line of the input contains an integer T (1≤T≤1000), indicating the number of test cases. For each test case: The only line contains two integers n and m (1≤n,m≤108), indicating the initial number of robots and energy bars. Output For each test case output one line containing an integer, indicating the minimum cost to get a fair distribution. Example inputCopy 3 3 12 10 6 8 20 outputCopy 0 4 2 Note For the third sample, the best way is to destroy a robot and create an energy bar. After that, we have 7 robots and 21 energy bars, which leads to a fair distribution.
#include <bits/stdc++.h> using namespace std; #define ri register int #define M 10005 template <class G> void read(G &x) { x=0;int f=0;char ch=getchar(); while(ch<'0'||ch>'9'){f|=ch=='-';ch=getchar();} while(ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+(ch^48);ch=getchar();} x=f?-x:x; return ; } int T,n,m; int main(){ read(T); while(T--) { read(n);read(m); if(n>=m) { printf("%d\n",n-m); continue; } if(m%n==0) { printf("0\n"); continue; } int l=1;int ans=1e8; int aa=1e8; while(l<=n) { int r=((m-1)/((m-1)/l)); int tmp=l*((m-1)/l); ans=min(ans,tmp); l=r+1; } ans=n-m+ans; printf("%d\n",ans); } }
思路: 更具题目 题目数学式子的提取,%的除法转化和%的取余数的应用
主题在求余数时,有整除可以特判的情况,就利用 这个m-1%x+1 来做就行了 X- 这个东西,不会影响结果的。
%可以用除法来代替,同时有除法就有分块除法来节省时间。