hdu-5514 Frogs(容斥+数论)

题意:给出序号为[0, m -1]的石头,以及n个青蛙能每次跳的步长,可以在石头上循环跳,问所有青蛙能够到达的所有石头的序号相加。


题解:很容易发现每个青蛙的跳的石头为gcd(ai, m)的倍数(拓展欧几里得),求这些石头的编号和也是一个等差数列的求和公式(代码中的sum函数),然后发现很多石头会被多次跳到以及多次相加,因此我们要把多次跳的石头容斥掉,我处理了所有a和m的gcd后把互质的所有gcd(ai, m)放到一个数组中,计算sum(a[i]) (i = 1….n) - lcm(a[i], a[j])(i = 1…..n, j = i + 1……n),然后一直WA,去看了一下正解,分解出了m的因数(init函数),然后暴力查看一下这些青蛙可以跳到m的哪个因数,然后这些因数的倍数都可以跳到,然后容斥的时候减掉对应多跳的就可以了


AC代码:

#include 
using namespace std;
#define met(a, b) memset(a, b, sizeof(a))
#define rep(i, a, b) for(int i = a; i < b; i++)
#define per(i, a, b) for(int i = a; i >= b; i--)
#define fi first
#define se second
#define pb push_back
#define mp make_pair
typedef long long ll;
typedef unsigned long long ull;
ll gcd(ll a, ll b) {return b == 0 ? a : gcd(b, a % b);}
ll lcm(ll a, ll b) {return a / gcd(a, b) * b;}
ll qPow(ll base, ll n) {ll res = 1; while(n) {if(n & 1) res *= base; base *= base; n >>= 1;} return res;}
const int maxn = 1e4 + 10;
const ll inf = 0x3f3f3f3f;
ll n, m, T, a[maxn], d[maxn];
int vis[maxn];
vector fac;
ll sum(ll x) {
    if(x >= m) return 0;
    ll t = (m - 1) / x;
    return (t * x * (t + 1)) / 2;
}

void init(ll x) {
    fac.clear();
    fac.pb(1LL);
    ll limit = sqrt(x);
    for(ll i = 2; i < limit; i++) {
        if(x % i == 0) {
            fac.pb(i);
            fac.pb(x / i);
        }
    }
    if(limit * limit == x) fac.pb(limit);
    else if(x % limit == 0) fac.pb(x / limit), fac.pb(limit);
//    rep(i, 0, fac.size()) cout << fac[i] << endl;
}

int main() {
    init(12);
    int cas = 1;
    scanf("%lld", &T);
    while(T--) {
        scanf("%lld%lld", &n, &m);
        init(m);
        sort(fac.begin(), fac.end());
        rep(i, 0, n) scanf("%lld", &d[i]), d[i] = gcd(d[i], m);
//        sort(d, d + n);
//        n = unique(d, d + n) - d;
        met(vis, 0);
        int len = fac.size();
        rep(i, 0, n) rep(j, 0, len) {
            if(fac[j] % d[i] == 0) vis[j] = 1;
        }
        ll ans = 0;
        rep(i, 0, len) {
            if(vis[i] == 0) continue;
            ans += sum(fac[i]) * vis[i];
            rep(j, i + 1, len) if(fac[j] % fac[i] == 0) vis[j] -= vis[i];
        }

        printf("Case #%d: %lld\n", cas++, ans);
    }
    return 0;
}

你可能感兴趣的:(ICPC,数论基础)