F题
先说几个小结论
对于数 a,b(b>a)b/a后向上(下)取整,再乘以a即可得到大(小)于b的最小(大)的能整除a的值。
向上取整的两种代码
//向上取整
ll getceil(ll a,ll b)
{
return a/b+(a%b?1:0);
}
ll getceil(ll a,ll b)
{
return (a+b-1)/b;
}
整除分块
整除分块枚举的是被除数,n%i的结果相同的数(也就是i)会被分为一块,每一块只枚举一次,这种方法可以大大减少枚举次数。
根据上图我们枚举i过程只会枚举1,2,3,4,5,6,7,11。
整除分块代码的模板
//整除分块
for(int l=1,r;l<=n;l=r+1)
{
r=n/(n/l);//后边(n/l)一定要加括号,是先向下取整后再被n除
//执行一些操作
}
补充了这两个知识点这题就可以完成了
#include <bits/stdc++.h>
#include<math.h>
#define TLE std::ios::sync_with_stdio(false)
using namespace std;
typedef long long ll;
const int INF = 0x3f3f3f3f;
const int N = 1e5 + 10;
int a[N];
ll getceil(ll a, ll b)
{
return a / b + (a % b ? 1 : 0);
}
int main()
{
int _;
cin >> _;
while (_--)
{
int a, b;
cin >> a >> b;
if (a > b)cout << a - b << endl;
else if (a == b)cout << 0 << endl;
else
{
ll ans = INF;
for (ll l = 1, r; l <= a; l = r + 1)//枚举b的整除块(也就是a变化后的值)
{
r = (b-1) / ((b-1) / l);//我们要找到b-1的整除块,加1后就是b的整除块
ans = min(ans, getceil(b, l) * l - b + a - l);
}
cout << ans << endl;
}
}
return 0;
}
另外附上比赛是想到的bfs暴力搜索的方法,虽然超时了但能得出几个答案还是很兴奋的
#include<iostream>
#include<algorithm>
#include<math.h>
#include<cstring>
#include<queue>
#include<unordered_map>
#include<map>
#define TLE ios::sync_with_stdio(false);
using namespace std;
const int INF = 0x3f3f3f3f;
const int N = 1e3 + 10;
const int M = 5e6 + 10;
int a, b;
typedef long long LL;
typedef pair<LL, LL> PII;
int n, m;
LL bfs(LL a,LL b)
{
queue<PII>q;
map<PII, LL> dist;
LL dx[2] = {-1,0}, dy[2] = { 0,1 };
dist[{a,b}] = 0;
q.push({ a,b });
while (q.size())
{
PII t = q.front();
q.pop();
LL x = t.first, y = t.second;
if (y % x == 0)return dist[{x, y}];
LL distance = dist[t];
for (int i = 0; i < 2; i++)
{
LL s = x + dx[i], p = y + dy[i];
if (s != 0 && !dist.count({ s,p }))
{
q.push({ s,p });
dist[{s, p}] = distance + 1;
}
}
}
}
int main()
{
cin >> n;
for(LL i=1;i<=n;i++)
{
cin >> a >> b;
cout<<bfs(a,b)<<endl;
}
return 0;
}