PAT 天梯赛 L3-001. 凑零钱 【DP】【DFS】

本文介绍了一种使用动态规划解决背包问题的方法,并提供了一个具体的实现案例。通过将物品按价值从大到小排序并利用二维DP数组记录状态,最终找到满足条件的最小价值序列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接

https://www.patest.cn/contests/gplt/L3-001

思路
DP【I】【J】 I 表示第几个物品 J 表示多少钱
dp[i][j] 为 bool 值 表示 当前状态是否能满足
对于一个物品 有两个选择
一个是选 当 arr[i] < j 的时候 dp[i - 1][j - arr[i]] == 1 就可以选
一个是不选 就是 更新为 dp[i - 1][j] 的答案

然后最后找 满足条件的最小序列
在刚开始选的时候 将数组 按 从大到小 排列
然后最后找的时候 从小的开始搜 往大的地方搜
因为 当一个数尽量小 那么这个可解序列 的字典序 就小

AC代码

#include <cstdio>
#include <cstring>
#include <ctype.h>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <ctime>
#include <iostream>
#include <algorithm>
#include <deque>
#include <vector>
#include <queue>
#include <string>
#include <map>
#include <stack>
#include <set>
#include <numeric>
#include <sstream>
#include <iomanip>
#include <limits>

#define CLR(a) memset(a, 0, sizeof(a))

using namespace std;
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
typedef pair <int, int> pii;
typedef pair <ll, ll> pll;

const double PI  = 3.14159265358979323846264338327;
const double E   = exp(1);
const double eps = 1e-6;

const int INF  = 0x3f3f3f3f;
const int maxn = 1e4 + 5;
const int MOD  = 1e9 + 7;

int arr[maxn], dp[maxn][105];
int  n, m;

vector <int> v;

bool comp(int x, int y)
{
    return x > y;
}

bool in_range(int x, int y)
{
    if (x >= 0 && x < n && y > 0 && y <= m)
        return true;
    return false;
}

void dfs(int x, int y)
{
    if (in_range(x, y))
    {
        if (x == 0 && y == arr[x])
        {
            v.push_back(arr[x]);
            return;
        }
        if (dp[x - 1][y - arr[x]])
        {
            v.push_back(arr[x]);
            dfs(x - 1, y - arr[x]); 
        }
        else
            dfs(x - 1, y);
    }
    else
        return;
}

int main()
{
    scanf("%d%d", &n, &m);
    for (int i = 0; i < n; i++)
        scanf("%d", &arr[i]);
    sort(arr, arr + n, comp);
    memset(dp, 0, sizeof(dp));
    if (arr[0] <= m)
        dp[0][arr[0]] = 1;
    for (int i = 0; i < n; i++)
        dp[i][0] = 1;
    for (int i = 1; i < n; i++)
    {
        for (int j = 1; j <= m; j++)
        {
            if (arr[i] > j)
                dp[i][j] = dp[i - 1][j];
            else
                dp[i][j] = (dp[i - 1][j] || dp[i - 1][j - arr[i]]);
        }
    }
    if (dp[n - 1][m])
    {
        v.clear();
        dfs(n - 1, m);
        sort (v.begin(), v.end());
        vector <int>::iterator it;
        for (it = v.begin(); it != v.end(); it++)
        {
            if (it != v.begin())
                printf(" ");
            cout << (*it);
        }
        cout << endl;
    }
    else
        printf("No Solution\n");
}
### 关于 PAT 天梯赛 L2-001 紧急救援 的分析 题目描述通常涉及在一个加权图中找到从起点到终点的最短路径,同时满足某些条件(如最大权重边最小)。此类问题可以通过 **Dijkstra算法** 和 **优先队列优化** 来解决。 #### 图论基础回顾 在图论中,单源最短路径问题是经典的算法问题之一。对于带正权值的有向无环图 (Directed Acyclic Graph, DAG),或者一般的加权图,Dijkstra 是一种高效的解决方案[^1]。该算法通过维护一个优先队列来动态更新节点的距离,并逐步扩展已知最优路径至目标节点。 针对本题的具体需求——不仅需要求出最短路径长度,还需要记录路径上的最大权重以及可能的不同路径数量,以下是详细的解答思路: --- #### 数据结构设计 为了高效处理输入数据并支持后续查询操作,需定义如下辅助类或变量: 1. 使用邻接表存储图的信息。 2. 定义三个数组分别保存当前顶点的状态: - `dist[v]` 表示从起始点到达 v 的最短距离; - `max_edge[v]` 记录从起点到 v 路径上遇到的最大边权值; - `path_count[v]` 统计有多少条不同的路径能够达到相同的 `(dist[v], max_edge[v])` 值组合。 初始化时设所有顶点不可达 (`inf`) 并设置起点状态为零。 --- #### 主要逻辑流程 采用 Dijkstra 算法的核心思想,结合优先队列实现多维度比较功能。具体步骤如下所示: 1. 初始化优先队列 PQ,按照三元组 `(distance, maximum edge weight, node)` 排序,其中 distance 应作为主要关键字升序排列,maximum edge weight 则次之降序排列。 2. 将初始结点加入队列,其对应的距离和最大边权均置为 0;路径数记作 1。 3. 循环提取队首元素 u 进行松弛操作:遍历与 u 相连的所有邻居 w,尝试更新它们的相关属性。如果发现更优解,则同步调整 dist[w], max_edge[w] 及 path_count[w] 的取值;当新旧两方案具有相同效果时累加路径数目即可。 4. 结束循环直至访问完全图中的每一个可触及位置为止。 最终输出结果应包括总耗时、途中经历过的最高危险等级数值以及符合条件的有效路线总数模去某个固定常量后的余数形式呈现出来。 --- #### 实现代码样例 下面是基于 Python 编写的完整程序版本: ```python import heapq def dijkstra(n, start, end, graph): INF = float(&#39;inf&#39;) # Initialize arrays to store distances, max edges and counts. dist = [INF]*n max_edge = [-1]*n count = [0]*n pq = [(0, 0, start)] # Priority queue with tuple of (current_distance, current_max_edge, vertex). dist[start] = 0 max_edge[start] = 0 count[start] = 1 while pq: d_u, m_e_u, u = heapq.heappop(pq) if u == end: break for v, cost in graph[u]: alt_dist = d_u + cost # Compute the new potential &#39;max edge&#39; value along this route. candidate_me_v = max(m_e_u, cost) if alt_dist < dist[v]: dist[v] = alt_dist max_edge[v] = candidate_me_v count[v] = count[u] # Push updated state into priority queue. heapq.heappush(pq, (alt_dist, candidate_me_v, v)) elif alt_dist == dist[v] and candidate_me_v < max_edge[v]: max_edge[v] = candidate_me_v count[v] += count[u] return dist[end], max_edge[end], count[end]%int(1e9+7) if __name__ == "__main__": n_vertices, n_edges, src, dst = map(int, input().split()) g = [[]for _ in range(n_vertices)] for i in range(n_edges): a,b,cost=map(int,input().strip().split()) g[a].append((b,cost)) res=dijkstra(n_vertices,src,dst,g) print(*res) ``` 上述脚本实现了完整的读入解析过程并通过标准输入获取必要的参数配置信息之后调用了核心函数完成任务执行最后按指定格式打印答案内容. --- #### 时间复杂度分析 由于采用了二叉堆作为底层支撑的数据结构,在每次迭代过程中最多只需要 O(log E) 的时间成本来进行插入/删除动作,因此整体运行效率大致维持在线性对数级别范围内即 O(E log V)。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值