其他分享
首页 > 其他分享> > Fair Distribution

Fair Distribution

作者:互联网

Fair Distribution


前置知识点

向上取整

ll getceil(ll a, ll b)
{
    return a / b + (a % b ? 1 : 0);
}
ll getceil(ll a, ll b)
{
    return (a + b - 1) / b;
}

思路

这道题一开始想的是用的dfs, 但是第三个测试点始终是过不了的,下面附上错误代码

void dfs(int a, int b, int res)
{
    if(b % a == 0)
    {
        return res;
    }
    else
    {
        int x = a - 1, y = b + 1;
        if(x >= 1)
        {
            dfs(x, b, res++);
            dfs(a, y, res++);
        }
    }
}

分块

这道题需要用到分块知识来做

#include <iostream>
using namespace std;
typedef long long ll;
ll getceil(ll a, ll b)
{
    return a / b  + (a % b != 0 ? 1 : 0);
} // 向上取整

int main()
{
    ll n, m;
    int t;
    cin >> t;
    while(t--)
    {
        cin >> n >> m;

        if(m % n == 0) cout << 0 << endl;
        else if(n >= m) cout << n - m << endl;
        else
        {
            ll ans = 0x3f3f3f3f;
            for(ll l = 1, r;  l <= n; l = r + 1)
            {
                r = (m - 1) / ((m - 1) / l); //向下取整分块
                ans = min(ans, getceil(m, l) * l - m + n - l);
            }
            cout << ans << endl;
        }
    }
    return 0;
}

扩展

向下取整的分块

for (ll l = 1, r; l <= m; l = r + 1) {
    r = n / (n / l);  
}

向上取整的分块

for(ll l = 1 , r ; l <= a ; l = r + 1){ 
		r = (b - 1) / ((b  - 1) / l) ;//向下取整区间分块
	}

标签:return,Fair,int,res,ll,dfs,取整,Distribution
来源: https://www.cnblogs.com/Flying-bullet/p/16099547.html