[CodeForces 118D]Caesar's Legions[DP]

题目链接: [CodeForces 118D]Caesar's Legions[DP]

题意分析:

凯撒有n1个步兵和n2个骑兵,现在将他们排成一列,问总共有多少种不同的排列情况?(步兵不能连着超过k1个,骑兵不能连着超过k2个)

解题思路:

首先倒着考虑状态看看行不行,比如已经放置了n1个步兵和n2个骑兵的方法总数,那么这个状态的上一个状态应该考虑到当前状态中,最后一个兵种是什么,然后考虑来的状态有多少个,发现这样考虑蛮复杂的。那么试试正着考虑:正着考虑,先想到从第i个位置出发,有多少种方法,发现这样的话,有三个东西不知道:当前的排头兵是什么兵种,这个兵种连续了几个,用了多少个这种兵种。那么悉数补上,就有dp[i][j][s][k]表示从第i个位置开始,步兵使用了j个,当前兵种为s(0:步兵,1:骑兵),连续了k个,然后就能转移了。

个人感受:

第二次做了。昨天还没思路= =,今天发现可以正着推,23333

具体代码如下:

#include<algorithm>
#include<cctype>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<iomanip>
#include<iostream>
#include<map>
#include<queue>
#include<set>
#include<sstream>
#include<stack>
#include<string>
#define lowbit(x) (x & (-x))
#define root 1, n, 1
#define lson l, m, rt << 1
#define rson m + 1, r, rt << 1  1
#define ll long long
#define pr(x) cout << #x << " = " << (x) << '\n';
using namespace std;

const int MOD = 1e8;

int n1, n2, k1, k2;
int dp[300][111][2][20];

int dfs(int n, int num, int sta, int len) {
    //cout << n << '-' << num << '-' << sta << '-' << len << '\n';
    int &x = dp[n][num][sta][len];
    if (x != -1) return x;
    x = 0;
    if (n > n1 + n2) return 0;
    if (n == n1 + n2 && num == n1) return x = 1;

    if (sta == 0) {
        if (num + 1 <= n1 && len + 1 <= k1)
            x += dfs(n + 1, num + 1, 0, len + 1);
        if (n + 1 - num <= n2)
            x += dfs(n + 1, num, 1, 1);
    }
    else {
        if (num + 1 <= n1)
            x += dfs(n + 1, num + 1, 0, 1);
        if (len + 1 <= k2 && n + 1 - num <= n2)
            x += dfs(n + 1, num, 1, len + 1);
    }
    return x % MOD;
}

int main()
{
    cin >> n1 >> n2 >> k1 >> k2;
    memset(dp, -1, sizeof dp);
    cout << dfs(0, 0, 0, 0) << '\n';
    return 0;
}


### 关于 Codeforces 上 'Neo's Escape' 的解决方案 在解决 Codeforces 平台上的 `'Neo's Escape'` 问题时,通常需要考虑图论中的最短路径算法以及动态规划的应用。以下是对此类问题可能涉及的核心概念技术的分析: #### 图论与最短路径 该问题可以被建模为在一个加权有向图中寻找从起点到终点的最优路径。Dijkstra 算法是一种常用的方法来计算单源最短路径[^1]。如果边权重均为正数,则 Dijkstra 是一种高效的选择。 ```python import heapq def dijkstra(graph, start): distances = {node: float('inf') for node in graph} distances[start] = 0 priority_queue = [(0, start)] while priority_queue: current_distance, current_node = heapq.heappop(priority_queue) if current_distance > distances[current_node]: continue for neighbor, weight in graph[current_node].items(): distance = current_distance + weight if distance < distances[neighbor]: distances[neighbor] = distance heapq.heappush(priority_queue, (distance, neighbor)) return distances ``` #### 动态规划优化 对于某些变体问题,除了简单的最短路径外,还需要引入状态转移方程来进行进一步优化。例如,在存在多种属性约束的情况下(如时间、能量),可以通过定义多维数组 `dp[i][j]` 来表示到达节点 i 使用 j 单位资源所需的最小代价[^2]。 #### 讨论与实现细节 社区内的讨论往往围绕如何处理特殊边界条件展开,比如是否存在负环路或者超大数据集下的性能调优等问题。此外,部分参赛者会分享他们关于数据结构选取的经验教训,例如优先队列 vs. 堆栈的不同适用场景[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值