P10035题解

· · 题解

瞎写个暴力能拿一半分?

50pts

对于这道题,我们可以先试一下一下思路。
已知:

则 A 是以 01 重复的字符串,B 是以 10 重复的字符串,C 的第 I 个字符为 V_3(I) \bmod 2,因此我们构造这三个长度为 3^N 的字符串后,去匹配一下,求出 \min\{\operatorname{mc}(A,C),\operatorname{mc}(B,C)\} 即可。

代码:

#include <iostream>
#include <string>
#define int long long
const int mod = 1e9 + 7;
using namespace std;
int mceq(string a, string b) {
    int ans = 0;
    for (int i = 0; i < a.size(); i++) {
        if (a[i] == b[i]) ans++;
    }
    return ans;
}
int ksm(int a, int b) {
    int ans = 1;
    while (b) {
        if (b & 1) ans = ans * a % mod;
        a = a * a % mod, b >>= 1;
    }
    return ans;
}
int V3(int x) {
    int ans = 0;
    while (x % 3 == 0) ans++, x /= 3;
    return ans;
}
signed main() {
    int t;
    cin >> t;
    while (t--) {
        int x;
        cin >> x;
        string a, b, c;
        for (int i = 1; i <= ksm(3, x); i++) {
            a += ((i % 2 == 1) ? '1' : '0'), b += ((i % 2 == 0) ? '1' : '0'), c += to_string(V3(i) % 2);
        }
        cout << min(mceq(a, c), mceq(b, c)) % mod << endl;
    }
}

100pts

测试点 2 没过?那么还要找一下规律。
在原程序里测试一下 1~10 的情况,得 N 分别等于 1,4,13,40,121\ldots。
分析发现:

得

\sum_{i = 0}^{N - 1} 3^i

变形,得 \frac{3 ^ N - 1}{2}。
所以我们只要输出 \frac{3 ^ N - 1}{2} 即可。(注意,不要直接除以 2 而是要乘上 2 的逆元,因为这个我卡了好久)

代码如下:

#include <iostream>
#define int long long
const int mod = 1000000007;
using namespace std;
int ksm(int a, int b) {
    int ans = 1;
    a %= mod;
    while (b) {
        if (b & 1) ans = ans * a % mod;
        a = a * a % mod, b >>= 1;
    }
    return ans;
}
inline void read(int& v) {
    char ch = getchar(); int x = 0, f = 1;
    while (!isdigit(ch)) {
        if (ch == '-') f = -1; ch = getchar();
    }
    while (isdigit(ch)) {
        x = x * 10 + ch - '0'; ch = getchar();
    }
    v = (f == 1) ? x : -x;
}
inline void print(int x) {
    if (x < 0)
        putchar('-'), x = -x;
    if (x > 9)
        print(x / 10);
    putchar(x % 10 + '0');
}
signed main() {
    int t;
    read(t);
    while (t--) {
        int x;
        read(x);
        print(((ksm(3, x) % mod - 1) % mod * (ksm(2, mod - 2)) % mod));

        putchar('\n');
    }
}