12.7总结

· · 个人记录

P7158 「dWoi R1」Password of Shady

题意

需要构造一个 n 位数,满足:

思路

使用动态规:

解题步骤

  1. 初始化:

    • dp1[1] = 1$:第一位是 $k
  2. 状态转移:

    • 从 dp[i-1] 转移:前面有偶数个 k,当前位不是 k(8 种选择)或当前位是 k(1 种选择)
    • 从 dp1[i-1] 转移:前面有奇数个 k,当前位不是 k(8 种选择)或当前位是 k(1 种选择)
  3. 最终答案:dp[n]

    时间复杂度

    1e5 + 1e6 = 1100000

    Code

    
    #include <iostream>
    #define int long long
    using namespace std;

const int MOD = 998244353; const int N = 100010; int dp[N], dp1[N];

signed main() { ios::sync_with_stdio(false); cin.tie(0), cout.tie(0);

// 预处理
dp[1] = 8;
dp1[1] = 1;
for (int i = 2; i <= 100000; i++) {
    dp[i] = (dp[i - 1] * 9 + dp1[i - 1]) % MOD;
    dp1[i] = (dp1[i - 1] * 9 + dp[i - 1]) % MOD;
}

int t;
cin >> t;
while (t--) {
    int n, k;
    cin >> n >> k;

    if (n == 1) {
        cout << 9 << "\n";
    } else {
        cout << dp[n] << "\n";
    }
}

return 0;

}

# P2196 [NOIP 1996 提高组] 挖地雷

## 题意
有 $N$ 个地窖,每个地窖有不同数量的地雷,地窖之间有单向连接。只能从编号小的地窖移动到编号大的地窖。要求找到一条路径,使得挖到的地雷总数最多,并输出这条路径和最大地雷数。

## 思路
使用动态规划求解。$dp[i]$ 表示以第 $i$ 个地窖为终点时能挖到的最大地雷数。转移时,枚举所有能到达 $i$ 的地窖 $j$,如果 $g[j][i]=1$,则 $dp[i] = \max(dp[i], dp[j] + a[i])$。同时记录前驱节点以便输出路径。

## 解题步骤
1. 读入地雷数量和连接关系
2. 初始化 $dp[i] = a[i]$,$pre[i] = 0$
3. 对于每个地窖 $i$,枚举所有 $j < i$,如果有连接则尝试更新 $dp[i]$
4. 找到最大的 $dp[i]$ 和对应的终点
5. 通过前驱数组回溯得到路径
6. 输出路径和最大地雷数

## Code
```cpp
#include <bits/stdc++.h>
using namespace std;

int g[25][25], dp[25], a[25], pre[25];

int main() {
    int n;
    cin >> n;
    for (int i = 1; i <= n; i++) {
        cin >> a[i];
    }
    for (int i = 1; i < n; i++) {
        for (int j = i + 1; j <= n; j++) {
            cin >> g[i][j];
        }
    }

    for (int i = 1; i <= n; i++) {
        dp[i] = a[i];
        pre[i] = 0;
        for (int j = 1; j < i; j++) {
            if (g[j][i]) {
                if (dp[j] + a[i] > dp[i]) {
                    dp[i] = dp[j] + a[i];
                    pre[i] = j;
                }
            }
        }
    }

    stack<int> st;
    int pos = 0, ans = 0;
    for (int i = 1; i <= n; i++) {
        if (dp[i] > ans) {
            ans = dp[i];
            pos = i;
        }
    }

    while (pos) {
        st.push(pos);
        pos = pre[pos];
    }

    while (!st.empty()) {
        cout << st.top();
        st.pop();
        if (!st.empty()) {
            cout << ' ';
        }
    }
    cout << endl << ans << endl;

    return 0;
}

时间复杂度

20+400+400+20+20+20 = 880