In Touch(思维+dij+优先队列)

该问题要求找到从第1个点到第n个点的最小花费路径,其中每个点能到达一定范围内的其他点,并且有各自的费用。由于数据规模大,直接建图不合适。解决方案是结合Dijkstra算法和并查集,用优先队列维护最小距离,已更新的点不再更新,更新过的点归并。也可以使用线段树来解决。

In Touch

Time Limit: 8000/4000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 3217    Accepted Submission(s): 827


 

Problem Description

There are n soda living in a straight line. soda are numbered by 1,2,…,n from left to right. The distance between two adjacent soda is 1 meter. Every soda has a teleporter. The teleporter of i-th soda can teleport to the soda whose distance between i-th soda is no less than li and no larger than ri. The cost to use i-th soda's teleporter is ci.

The 1-st soda is their leader and he wants to know the minimum cost needed to reach i-th soda (1≤in).

 

 

Input

There are multiple test cases. The first line of input contains an integer T, indicating the number of test cases. For each test case:

The first line contains an integer n (1≤n≤2×105), the number of soda.
The second line contains n integers l1,l2,…,ln. The third line contains n integers r1,r2,…,rn. The fourth line contains n integers c1,c2,…,cn. (0≤lirin,1≤ci≤109)

 

 

Output

For each case, output n integers where i-th integer denotes the minimum cost needed to reach i-th soda. If 1-st soda cannot reach i-the soda, you should just output -1.

 

 

Sample Input

 

1 5 2 0 0 0 1 3 1 1 0 5 1 1 1 1 1

 

 

Sample Output

 

0 2 1 1 -1

Hint

If you need a larger stack size, please use #pragma comment(linker, "/STACK:102400000,102400000") and submit your solution using C++.

 

 

Author

zimpha@zju

 

 

Source

2015 Multi-University Training Contest 6

 

 

Recommend

wange2014   |   We have carefully selected several similar problems for you:  6343 6342 6341 6340 6339 

题意:题意是从给出n个点,第一行是l[i],第二行是r[i],意思是i点可以到达  距i点的距离在【l,r】以内的所有点,第三行是c[i],意思是到达i点需要花费c。问从第一个点到1—n的点,分别求一下最短路径。

由数据范围如此庞大可以知道,直接建图不是好方法。

然后我们就去利用dij算法,和并查集,那么dist[i]表示从1到 i 的花费再加上点 i 的花费,这样每个点就只会被更新一次,更新后在以后就不会再次被更新了,这里用到并查集把已经更新的点得father指向还没被更新的点。简单地说,就是从第一个点开始更新, 更新过的点缩成一个点, 因为在Dijkstra里 每次取出的都是最小的distance,(用优先队列维护) 所以更新过的点 后面肯定不需要再次更新。更新一个点后加入堆中, 因为通过这个点可能更新别的点。

ps:这道题自己还没敲,但是觉得思想很好,应该记住并且灵活运用!!

参考博客:

https://blog.youkuaiyun.com/u014422052/article/details/47376273

也可以用线段树做:

https://blog.youkuaiyun.com/hnust_derker/article/details/79343341

代码:

#include<bits/stdc++.h>
typedef __int64 ll;
using namespace std;

const ll INF = 1LL << 60;   //要大点
#define mod 1000000009
const int maxn = 200010;
const int MAXN = 2005;
const int MAXM = 200010;
const int N = 1005;

typedef pair<ll,int>Pir;
ll L[maxn],R[maxn],C[maxn],dist[maxn];
int n,father[maxn];

void init()
{
    for (int i=0;i<=n+5;i++)
    {
        father[i]=i;
        dist[i]=INF;
    }
}

int find_father(int x)
{
    if (x!=father[x])
        father[x]=find_father(father[x]);
    return father[x];
}

void solve()
{
    dist[1]=C[1];
    priority_queue<Pir,vector<Pir>,greater<Pir> >Q;
    Q.push(make_pair(dist[1],1));
    while (!Q.empty())
    {
        Pir st=Q.top(); Q.pop();
        int u=st.second;
      ///  cout<<u<<"&&&"<<endl;
        for (int i=-1;i<=1;i+=2)
        {
            int l=u+i*L[u];
            int r=u+i*R[u];
            if (l>r) swap(l,r);
            l=max(1,l);
            l=min(l,n+1);
            if (l>r) continue;
            for (int v=l;;v++)
            {
                v=find_father(v);
                if (v<=0||v>n||v>r) break;
                if (dist[v]>dist[u]+C[v])
                {
                    dist[v]=dist[u]+C[v];
                    Q.push(make_pair(dist[v],v));
                }
                father[find_father(v)]=find_father(v+1);
            }
        }
    }
    printf("0");
    for (int i=2;i<=n;i++)
    {
        if (dist[i]>=INF)
            printf(" -1");
        else
            printf(" %I64d",dist[i]-C[i]);
    }
    printf("\n");
}

int main()
{
    int i,j,t;
    scanf("%d",&t);
    while (t--)
    {
        scanf("%d",&n);
        for (i=1;i<=n;i++)
            scanf("%I64d",&L[i]);
        for (i=1;i<=n;i++)
            scanf("%I64d",&R[i]);
        for (i=1;i<=n;i++)
            scanf("%I64d",&C[i]);
        init();
        solve();
    }
    return 0;
}

 

这是一个非常有趣且富有哲思的问题:“能否用 Floyd、Dijkstra 或 SPFA 这些**最短路算法**来实现 A+B?” 从实际计算的角度来看,A+B 是一个简单的算术运算,而 Floyd、Dijkstra 和 SPFA 是用于求解图中**顶点之间最短路径**的算法。它们本不适用于加法操作。但如果我们跳出常规思维,借助“建模”和“映射”的思想,**在特定抽象意义下**,我们确实可以“用最短路算法来做 A+B”。 下面我将详细解释每种方式是否可行、如何构造模型,并给出可运行的 C++ 代码示例。 --- ### ✅ 总体结论: > ❌ **不能直接用这些算法做 A+B 的数值计算**(毫无必要且效率极低) > ✅ **但可以通过构造特殊图模型,使最短路径的结果等于 A+B** —— 属于“算法思想的泛化应用”或“教学演示”。 --- ## 1. 能否用 Dijkstra 求 A+B? ### ✔️ 可以!通过构造一条“加法路径” 我们将问题转化为: > 构造一个图,使得从起点到终点的最短路径长度恰好为 `A + B`。 #### 建模思路: - 创建三个节点:`0 -> 1 -> 2` - 边 `0→1` 的权值为 A - 边 `1→2` 的权值为 B - 则从 `0` 到 `2` 的最短路径就是 A+B ```cpp #include <iostream> #include <vector> #include <queue> #include <climits> using namespace std; const int N = 3; vector<pair<int, int>> graph[N]; // 邻接表:to, weight int dist[N]; void dijkstra(int start) { for (int i = 0; i < N; ++i) dist[i] = INT_MAX; dist[start] = 0; priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> pq; pq.push({0, start}); while (!pq.empty()) { auto [d, u] = pq.top(); pq.pop(); if (d > dist[u]) continue; for (auto &[v, w] : graph[u]) { if (dist[u] + w < dist[v]) { dist[v] = dist[u] + w; pq.push({dist[v], v}); } } } } int main() { int A, B; cin >> A >> B; // 构造图:0 --A--> 1 --B--> 2 graph[0].push_back({1, A}); graph[1].push_back({2, B}); dijkstra(0); cout << dist[2] << endl; // 输出 A+B return 0; } ``` ✅ **解释**:这不是真正的“计算加法”,而是把加法嵌入图结构中,让 Dijkstra “走一遍”得到结果。虽然极度低效(O(n log n) vs O(1)),但它体现了 **图论对计算的表达能力**。 --- ## 2. 能否用 SPFA 求 A+B? SPFA 是 Bellman-Ford 的队列优化版,也能处理负权边。 同样的建模方式适用。 ```cpp #include <iostream> #include <vector> #include <queue> #include <climits> using namespace std; const int N = 3; vector<pair<int, int>> graph[N]; int dist[N], inq[N]; void spfa(int start) { for (int i = 0; i < N; ++i) dist[i] = INT_MAX; queue<int> q; dist[start] = 0; q.push(start); inq[start] = true; while (!q.empty()) { int u = q.front(); q.pop(); inq[u] = false; for (auto &[v, w] : graph[u]) { if (dist[u] + w < dist[v]) { dist[v] = dist[u] + w; if (!inq[v]) { q.push(v); inq[v] = true; } } } } } int main() { int A, B; cin >> A >> B; graph[0].push_back({1, A}); graph[1].push_back({2, B}); spfa(0); cout << dist[2] << endl; // A+B return 0; } ``` ✅ **解释**:即使 A 或 B 为负数也成立(Dijkstra 不支持负权,但 SPFA 支持)。这说明 SPFA 更通用,但仍只是“模拟”加法。 --- ## 3. 能否用 Floyd 求 A+B? Floyd 算法用于求**所有点对之间的最短路径**,基于动态规划: ```cpp dp[k][i][j] = min(dp[k-1][i][j], dp[k-1][i][k] + dp[k-1][k][j]) ``` 我们可以构造三元图,然后运行 Floyd,最后取 `dist[0][2]`。 ```cpp #include <iostream> #include <climits> using namespace std; const int N = 3; int dist[N][N]; void floyd() { for (int k = 0; k < N; ++k) for (int i = 0; i < N; ++i) for (int j = 0; j < N; ++j) if (dist[i][k] != INT_MAX && dist[k][j] != INT_MAX) dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]); } int main() { int A, B; cin >> A >> B; // 初始化距离矩阵 for (int i = 0; i < N; ++i) for (int j = 0; j < N; ++j) dist[i][j] = (i == j ? 0 : INT_MAX); dist[0][1] = A; dist[1][2] = B; floyd(); cout << dist[0][2] << endl; // 应该是 A+B return 0; } ``` ✅ **解释**:Floyd 完全可以“算出” A+B,尽管它的时间复杂度是 O() = O(1)(因为 n=3 固定),但这只是为了形式上的完整性。 --- ### 🔚 总结与哲学思考 | 算法 | 是否可用于 A+B | 说明 | |----------|----------------|------| | Dijkstra | ✅ 可以(正权) | 构造路径,跑一遍最短路 | | SPFA | ✅ 可以(含负权) | 支持 A/B 为负数的情况 | | Floyd | ✅ 可以(全源) | 把加法嵌入图中进行松弛 | > 💡 这些方法都不是“真正计算 A+B”,而是 **将加法编码为图问题**,再用最短路算法解码出来。 > 它们的价值在于:展示**算法的统一性与建模能力** —— 即便最简单的运算,也可以被复杂的算法框架所容纳。 --- ### 🧠 类比理解: 就像你可以用一台超级计算机模拟整个宇宙,只为算出 `1+1=2` —— 虽然荒谬,但逻辑上成立。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值