algorithm - 在特定成本内找到路径

标签 algorithm graph routes dijkstra

有许多算法或策略可用于寻找成本最低或最高的路径。但是,很难找到一种方法可以在所需成本 (RC)(或以下)找到路径,即这样的 RC 不是最小值或最大值,实际成本应该小于这样的 RC。

我正在寻找一种可行的算法来找到满足两个约束的路径:

  1. 这样一条路径的成本应该低于所需的成本。
  2. 从源到目的地的路径应包含尽可能多的跃点。

一个例子如下, 例如,

源是节点A,目的是节点B;所需成本为10。从A到B可以找到3条路径:

 1. A --> C --> B;               cost is 5
 2. A --> C --> D --> B;         cost is 8
 3. A --> C --> D --> E --> B;   cost is 12

根据上面提到的两个约束,路径 2 (A --> C --> D --> B; cost is 8) 是最好的,因为成本是 8 小于所需成本为 10,路径 2 比路径 1 长。

希望我能清楚地解释我的问题。 有没有发布的算法或方法来解决这个问题?

提前谢谢你。

最佳答案

我认为这个问题没有众所周知的算法。

让我给你看我的片段。

#include <iostream>
#include <algorithm>
#include <queue>
#include <vector>
using namespace std;

class info
{
    public:
        int hopcount;
    vector<int> path;
    int cost;
};

int main()
{
    int n;
    int s, e;
    vector<vector < int>> arr;
    cin >> n;
    arr.resize(n + 1);
    for (int i = 1; i <= n; i++)
    {
        arr[i].resize(n + 1);
    }
    cin >> s >> e;
    int pc;
    cin >> pc;
    for (int i = 0; i < pc; i++)
    {
        int source, def, cost;
        cin >> source >> def >> cost;
        arr[source][def] = cost;
    }
    int maxcost;
    cin >> maxcost;
    queue<info> q;
    q.push({1, {s}, 0 });
    int maxhopcount = -1;
    vector<int> hoppath;
    while (!q.empty())
    {
        auto qel = q.front();
        q.pop();
        int currentN = qel.path[qel.path.size() - 1];
        if (currentN == e)
        {
            if (qel.hopcount > maxhopcount)
            {
                maxhopcount = qel.hopcount;
                hoppath = qel.path;
            }
        }
        for (int i = 1; i <= n; i++)
        {
            int sign = 0;
            for (auto c: qel.path)
            {
                if (c == i)
                {
                    sign = 1;
                    break;
                }
            }
            if (sign == 1) continue;
            if (arr[currentN][i] > 0)
            {
                info ni = qel;
                ni.path.push_back(i);
                ni.hopcount += 1;
                ni.cost += arr[currentN][i];
                if (ni.cost <= maxcost)
                {
                    q.push(ni);
                }
            }
        }
    }
    cout << maxhopcount << endl;
    for (auto c: hoppath)
    {
        cout << c << " ";
    }
    return 0;
}
/*
testcases
5
1 2
6
1 3 2
3 2 3
3 4 3
4 2 3
4 5 4
5 2 3
10

1 3 4 2
4
*/

我用简单的 bfs 方法写了一个代码。

写下每一步的信息就可以解决这个问题。

如果有任何极端情况,请告诉我。

关于algorithm - 在特定成本内找到路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63609925/

相关文章:

c++ - 将网格内的数字转换为其对应的 x,y 坐标

apache-spark - 合并 Spark 数据框中的两列以形成单列

重定向到 Razor 页面中带有 ID 的页面

php - 在 Laravel 中添加 Sitemap 文件和路由

algorithm - 实时趋势算法

algorithm - 在汉诺塔算法中,辅助是什么?

arrays - 数组数组中的所有组合

r - 为什么networkd3 R中的forceNetwork显示不在边缘列表中的所有节点?

graph - 在 javafx 2.2 散点图中隐藏轴

java - Swagger UI 和 Play 路由 *path