Codeforces 997 C

C - Sky Full of Stars

思路:

容斥原理

题解:http://codeforces.com/blog/entry/60357

注意当i > 1 且 j > 1,是同一种颜色

代码:

#include<iostream>
#include<cstdio>
#include<queue>
#include<deque>
#include<set>
#include<cstring>
using namespace std;
#define fi first
#define se second
#define pi acos(-1.0)
#define LL long long
#define mp make_pair
#define pb push_back
#define ls rt<<1, l, m
#define rs rt<<1|1, m+1, r
#define ULL unsigned LL
#define pll pair<LL, LL>
#define pii pair<int, int>
#define mem(a, b) memset(a, b, sizeof(a))
#define fio ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define fopen freopen("in.txt", "r", stdin);freopen("out.txt", "w", stout);
//head

const int MOD = 998244353;

LL q_pow(LL n, LL k) {
    LL ans = 1;
    while(k) {
        if(k&1) ans = (ans * n) % MOD;
        n = (n*n) % MOD;
        k >>= 1;
    }
    return ans;
}
int main() {
    int n;
    scanf("%d", &n);
    LL res = 0, t = 1, sign = -1;
    for (int i = 1; i <= n; i++) {
        t = (t * (n-i+1)) % MOD;
        t = (t * q_pow(i, MOD - 2)) % MOD;
        sign = -sign;
        LL tt = q_pow(3, 1LL*n*(n-i)+i);
        res = (res + tt*t*sign) % MOD;
    }
    res = (res * 2) % MOD;
    res = (res + MOD) % MOD;
    LL ans = 0;
    t = 1, sign = -1;
    for (int i = 0; i < n; i++) {
        LL tt = q_pow( 1 - q_pow(3, i), n);
        tt = (tt - q_pow( - q_pow(3, i), n)) % MOD;
        ans = (ans + tt*t*sign) % MOD;
        t = (t * (n-i)) % MOD;
        t = (t * q_pow(i+1, MOD-2)) % MOD;
        sign = -sign;
    }
    ans = (ans * 3) % MOD;
    ans = (ans + MOD) % MOD;
    printf("%lld
", (res + ans) % MOD);
    return 0;
}
原文地址:https://www.cnblogs.com/widsom/p/9306316.html