SPFA + 树形DP:The Ghost Blows Light

本文深入探讨了游戏开发领域的关键技术,包括游戏引擎、编程语言、硬件优化等,同时着重介绍了AI音视频处理的应用场景和实现方法,如语义识别、语音变声等,为开发者提供全面的技术指南。

The Ghost Blows Light

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1017    Accepted Submission(s): 303


Problem Description

My name is Hu Bayi, robing an ancient tomb in Tibet. The tomb consists of N rooms (numbered from 1 to N) which are connected by some roads (pass each road should cost some time). There is exactly one route between any two rooms, and each room contains some treasures. Now I am located at the 1st room and the exit is located at the Nth room.
Suddenly, alert occurred! The tomb will topple down in T minutes, and I should reach exit room in T minutes. Human beings die in pursuit of wealth, and birds die in pursuit of food! Although it is life-threatening time, I also want to get treasure out as much as possible. Now I wonder the maximum number of treasures I can take out in T minutes.
 

Input
There are multiple test cases.
The first line contains two integer N and T. (1 <= n <= 100, 0 <= T <= 500)
Each of the next N - 1 lines contains three integers a, b, and t indicating there is a road between a and b which costs t minutes. (1<=a<=n, 1<=b<=n, a!=b, 0 <= t <= 100)
The last line contains N integers, which Ai indicating the number of treasure in the ith room. (0 <= Ai <= 100)
 

Output
For each test case, output an integer indicating the maximum number of treasures I can take out in T minutes; if I cannot get out of the tomb, please output "Human beings die in pursuit of wealth, and birds die in pursuit of food!".
 

Sample Input
  
5 10 1 2 2 2 3 2 2 5 3 3 4 3 1 2 3 4 5
 

Sample Output
  
11
 

Source
2012 ACM/ICPC Asia Regional Changchun Online

题意:一张无向图,每条边走过去要花一定时间,每个节点上有一定数量的宝藏,在规定时间必须由起点走到终点,并尽可能多拿宝藏

分析:此题分两步做,首先求最短路,然后把这条路上的所有边的花费时间,再把总的时间减去上述时间
这样做的原因是最短路方法求出来的路是必经之路
然后做树形DP,以DFS的方法从起始点开始深搜,每搜到一个点x就更新一次所有dp[x][i](指到x点时还剩i时间,这时最多能已经拿到多少宝藏,i从m到2倍到下个点的时间)

#include <cstdio>
#include <iostream>
#include <cstring>
#include <cmath>
#include <string>
#include <algorithm>
#include <vector>
#include <queue>
#include <map>

using namespace std;

int n, m;
const int INF = 1 << 31 - 1;

struct node{
    int to;
    int next;
    int weight;
}e[201];

int w[210];
int lastshow[210];
int dp[210][510]; //dp[x][i]表示从x出发时间还剩m的时候最多拿多少宝藏
bool inqueue[2010];
queue<int>q;
long long d[210];
int cnt = -1;
int used[210];
int path[210];

void insert(int a, int b, int w){
    e[++cnt].to = b;         //插入边,起始编号为0
    e[cnt].weight = w;
    e[cnt].next = lastshow[a];
    lastshow[a] = cnt;
}

bool spfa(){
    q.push(1);
    int qq[2005];
    while(!q.empty()){
        int x = q.front();
        q.pop();
        inqueue[x] = false;
        int id = lastshow[x];
        while(id != -1){
            if(d[x] < INF && d[e[id].to] > e[id].weight + d[x]){
                d[e[id].to] = e[id].weight + d[x];
                path[e[id].to] = x;           //记录一路上经过的点
                qq[e[id].to] = id;            //记录以上述点为终点的边
                if(!inqueue[e[id].to]){
                    inqueue[e[id].to] = true;
                    q.push(e[id].to);
                }
            }
            id = e[id].next;
        }
    }
    int i;
    for(i = n; path[i] != -1; i = path[i]){   //特别注意此处判断循环停止的条件是path[i]!=-1,若是i!=-1,会强制删除边0
        e[qq[i]].weight = 0;
    }
    return false;
}

void init(){
    int i;
    memset(used, 0, sizeof(used));
    memset(path, -1, sizeof(path));
    memset(dp, 0, sizeof(dp));
    memset(lastshow, -1, sizeof(lastshow));
    for(i = 1; i <= n; i ++){
        inqueue[i] = false;
    }
    for(i = 1; i <= n; ++ i)
        d[i]=INF;
    d[1]=0;
    cnt=-1;
    while(!q.empty()){
        q.pop();
    }
}

void dfs(int x){//树形dp
    used[x] = 1;
    for(int k = lastshow[x]; k!= -1; k = e[k].next){
        int y = e[k].to;
        if(used[y])
            continue;
        dfs(y); //每到一个新的点就深度遍历此点
        int tmp = e[k].weight * 2;
        for(int i = m; i >= tmp; i --){
            for(int j = i - tmp; j >= 0; j --){
                dp[x][i] = max(dp[x][i], dp[x][j] + dp[y][i - tmp - j]);
            }
        }
    }
    for(int i = 0; i <= m; i ++){
        dp[x][i] += w[x];//更新所有以x为起始的情况下能获得的宝藏数
    }
}

int main(){
    int i, j, k;
    while(~scanf("%d %d", &n, &m)){
        int a, b, c;
        init();
        for(i = 0; i < n - 1; i ++){
            scanf("%d %d %d", &a, &b, &c);
            insert(a, b, c);
            insert(b, a, c);
        }
        for(i = 1; i <= n; i ++){
            scanf("%d", &w[i]);
        }
        spfa();      //找出最短路,并把路上要花费的时间置为零,因为它是必经之路
        //cout << d[n] << endl;
        if(d[n] > m){
            printf("Human beings die in pursuit of wealth, and birds die in pursuit of food!\n");
        }
        else{
            m -= d[n]; //更新还剩的时间
            dfs(1); 
            printf("%d\n", dp[1][m]);
        }
    }
    return 0;
}



**SPFA + 堆优化通常没有实际好处,反而可能更慢或出错**。下面我们详细解释为什么。 --- ### 一、SPFA 本身是什么? SPFA(Shortest Path Faster Algorithm)是 **Bellman-Ford 算法的队列优化版本**,核心思想是: - 只有当某个节点的最短距离被更新了,才用它去松弛其邻接点。 - 使用一个普通队列(FIFO)来维护待处理的节点。 ```python from collections import deque def spfa(n, graph, start): dist = [float('inf')] * n in_queue = [False] * n dist[start] = 0 in_queue[start] = True q = deque([start]) while q: u = q.popleft() in_queue[u] = False for v, w in graph[u]: if dist[u] + w < dist[v]: dist[v] = dist[u] + w if not in_queue[v]: q.append(v) in_queue[v] = True return dist ``` ✅ SPFA 的优点: - 能处理负权边 - 平均性能较好(尤其稀疏图) - 实现简单 --- ### 二、能不能加“堆优化”?比如用优先队列代替普通队列? 你可能会想:“Dijkstra 用堆优化更快,那 SPFA 也用堆试试?” 即:把 `deque` 换成 `heapq`,每次取出当前 `dist` 最小的节点来松弛 —— 这听起来像 Dijkstra! 但问题来了: > ❌ **一旦你用堆来取最小距离节点,你就不再是 SPFA,也不再是正确的负权最短路算法!** --- ### 三、为什么 SPFA 不适合堆优化? #### ✅ 正确性问题:堆优化版 SPFA 实际上退化为 Dijkstra - Dijkstra 使用堆的前提是:**边权非负** - 如果你在存在负权边的情况下使用堆,会出现: - 某个节点虽然当前 `dist` 小,但它之后可能通过负权边变得更小 - 但堆结构会优先处理“当前小”的点,并可能提前将其弹出,不再更新 - 导致无法正确传播后续的更优路径 → **结果错误** #### ⚠️ 示例说明: ``` A --1--> B --(-2)--> C \ / \--3------------>/ ``` 从 A 出发: - 初始:dist[A]=0, dist[B]=1, dist[C]=3 - 若使用堆,先处理 B(dist=1),然后更新 C:1 + (-2) = -1 → 更好 - 再处理 C(现在 dist[C]=-1) - 但如果图中有环或更多节点,堆可能已经忽略了某些本该再次更新的节点 但更大的问题是:**堆中元素一旦被取出,就不再重新考虑其更优值的可能性**(除非重新入堆),而频繁入堆会导致复杂度失控。 --- ### 四、性能分析:堆优化对 SPFA 没有收益 | 版本 | 数据结构 | 时间复杂度(平均) | 是否支持负权 | 稳定性 | |------|----------|---------------------|---------------|--------| | SPFA | 队列(deque) | O(kE),k 很小 | ✅ 支持 | 较好 | | SPFA + 堆 | 优先队列(heapq) | 接近 O(E log V) | ❌ 在负权下易错 | 差 | | Dijkstra + 堆 | 优先队列 | O((V+E) log V) | ❌ 不支持负权 | 稳定 | 👉 结论: - 堆优化并不能提升 SPFA 的效率 - 反而破坏了 SPFA “允许反复更新”的机制 - 在负权图中可能导致遗漏更优路径 --- ### 五、有没有“带堆的正确算法”能处理负权? 目前主流算法中: - **没有基于堆的通用负权最短路算法** - Johnson 算法会在预处理时重赋权,然后用 Dijkstra 多次求解,其中用了堆,但前提是先消除负权 - 所以堆的作用是在**非负权子问题**中加速 --- ### 六、总结 ❌ **不要给 SPFA 加堆优化!** - ✅ SPFA 应该用普通队列(或双端队列) - ❌ 堆优化不仅不能提高性能,还可能导致错误结果 - 🚫 它违背了 SPFA 的设计初衷:动态更新和多次入队 - 🔁 SPFA 的优势就在于灵活地处理负权边,而堆会限制这种灵活性 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值