Codeforces Round 901 (Div. 2) C. Jellyfish and Green Apple (思维)

题目链接

代码 (判空):

#include<bits/stdc++.h>
using namespace std;
#define endl "\n"
typedef long long ll;
typedef pair<int, int> PII;
typedef pair<PII, int> PIII;
const int inf = 0x3f3f3f3f;
const ll infinf = 0x3f3f3f3f3f3f3f3f;

//const int N = 

void solve() {
    int n, m; cin >> n >> m;

    if (n % m == 0) cout << 0 << endl;
    else {
        n %= m;    // 先分整个的
        int d = __gcd(n, m);  // 求剩下的苹果和人数的最大公约数d, 分d组, 一组n/d个人, m/d个苹果
        int tmp = m;
        tmp /= d;
        while (tmp % 2 == 0) tmp /= 2; // 如果每一组的人数是2的幂, 则可以平均分

        if (tmp != 1) cout << -1 << endl;   // 有不是2的质因子, 则不能平均分
        else {
            ll ans = 0;
            while (n) {  // 每次把剩下的块全部劈成两半,统计刀数,直到块数足够分给m个人。
                ans += n;  // 分给那些人后,让块数减去m, 在重复这个过程, 直到最后只剩0块。
                n *= 2;
                if (n >= m) n -= m;
            }
            cout << ans << endl;
        }
    }
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);

    int t; cin >> t;
    while (t --) solve();

    return 0;
}

代码(暴力玄学):

#include<bits/stdc++.h>
using namespace std;
#define endl "\n"
typedef long long ll;
typedef pair<int, int> PII;
typedef pair<PII, int> PIII;
const int inf = 0x3f3f3f3f;
const ll infinf = 0x3f3f3f3f3f3f3f3f;
 
//const int N = 
 
void solve() {
    int n, m; cin >> n >> m;
 
    if (n % m == 0) cout << 0 << endl;
    else {
        n %= m;
 
        ll ans = 0, cnt = 1;
        while (n && cnt <= 10000) {    // cnt判断能否在10000次内分完, 若不能, 即无法平均分
            ans += n;
            n *= 2;
            if (n >= m) n -= m;
            cnt ++;
        }
        if (n == 0) cout << ans << endl;
        else cout << -1 << endl;
    }
}
 
int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
 
    int t; cin >> t;
    while (t --) solve();
 
    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值