【动态规划】【图论】【C++算法】1575统计所有可行路径

简介: 【动态规划】【图论】【C++算法】1575统计所有可行路径

作者推荐

【动态规划】【字符串】【行程码】1531. 压缩字符串

本文涉及知识点

动态规划汇总

图论

LeetCode1575统计所有可行路径

给你一个 互不相同 的整数数组,其中 locations[i] 表示第 i 个城市的位置。同时给你 start,finish 和 fuel 分别表示出发城市、目的地城市和你初始拥有的汽油总量每一步中,如果你在城市 i ,你可以选择任意一个城市 j ,满足 j != i 且 0 <= j < locations.length ,并移动到城市 j 。从城市 i 移动到 j 消耗的汽油量为 |locations[i] - locations[j]|,|x| 表示 x 的绝对值。

请注意, fuel 任何时刻都 不能 为负,且你 可以 经过任意城市超过一次(包括 start 和 finish )。

请你返回从 start 到 finish 所有可能路径的数目。

由于答案可能很大, 请将它对 10^9 + 7 取余后返回。

示例 1:

输入:locations = [2,3,6,8,4], start = 1, finish = 3, fuel = 5

输出:4

解释:以下为所有可能路径,每一条都用了 5 单位的汽油:

1 -> 3

1 -> 2 -> 3

1 -> 4 -> 3

1 -> 4 -> 2 -> 3

示例 2:

输入:locations = [4,3,1], start = 1, finish = 0, fuel = 6

输出:5

解释:以下为所有可能的路径:

1 -> 0,使用汽油量为 fuel = 1

1 -> 2 -> 0,使用汽油量为 fuel = 5

1 -> 2 -> 1 -> 0,使用汽油量为 fuel = 5

1 -> 0 -> 1 -> 0,使用汽油量为 fuel = 3

1 -> 0 -> 1 -> 0 -> 1 -> 0,使用汽油量为 fuel = 5

示例 3:

输入:locations = [5,2,1], start = 0, finish = 2, fuel = 3

输出:0

解释:没有办法只用 3 单位的汽油从 0 到达 2 。因为最短路径需要 4 单位的汽油。

提示:

2 <= locations.length <= 100

1 <= locations[i] <= 109

所有 locations 中的整数 互不相同 。

0 <= start, finish < locations.length

1 <= fuel <= 200

动态规划

令n = locations.length

动态规划的状态表示

dp[l][f] 表示 使用f单位的汽油,终点是l的可行路径数。状态数共:nm,故空间复杂度:O(nm)。

动态规划的转移方程

通过前置条件转移后置条件。

枚举符合以下条件的l1:

l1!=l

f1 = |loc[l1]-[l]| + f <= fuel。

dp[l1][[f1] += dp[l][f]

时间复杂度: O(nnm)

动态规划的填表顺序

f从小到大,确保动态规划的无后效性。

动态规划的初始状态

dp[start][0] =1 ,其它全部为0。

动态规划的返回值

dp[finish]之和

代码

核心代码

template<int MOD = 1000000007>
class C1097Int
{
public:
  C1097Int(long long llData = 0) :m_iData(llData% MOD)
  {
  }
  C1097Int  operator+(const C1097Int& o)const
  {
    return C1097Int(((long long)m_iData + o.m_iData) % MOD);
  }
  C1097Int& operator+=(const C1097Int& o)
  {
    m_iData = ((long long)m_iData + o.m_iData) % MOD;
    return *this;
  }
  C1097Int& operator-=(const C1097Int& o)
  {
    m_iData = (m_iData + MOD - o.m_iData) % MOD;
    return *this;
  }
  C1097Int  operator-(const C1097Int& o)
  {
    return C1097Int((m_iData + MOD - o.m_iData) % MOD);
  }
  C1097Int  operator*(const C1097Int& o)const
  {
    return((long long)m_iData * o.m_iData) % MOD;
  }
  C1097Int& operator*=(const C1097Int& o)
  {
    m_iData = ((long long)m_iData * o.m_iData) % MOD;
    return *this;
  }
  bool operator<(const C1097Int& o)const
  {
    return m_iData < o.m_iData;
  }
  C1097Int pow(long long n)const
  {
    C1097Int iRet = 1, iCur = *this;
    while (n)
    {
      if (n & 1)
      {
        iRet *= iCur;
      }
      iCur *= iCur;
      n >>= 1;
    }
    return iRet;
  }
  C1097Int PowNegative1()const
  {
    return pow(MOD - 2);
  }
  int ToInt()const
  {
    return m_iData;
  }
private:
  int m_iData = 0;;
};
class Solution {
public:
  int countRoutes(vector<int>& locations, int start, int finish, int fuel) {
    const int n = locations.size();
    vector<vector<C1097Int<> >> dp(n, vector<C1097Int<>>(fuel + 1));
    dp[start][0] = 1;
    for (int f = 0; f < fuel; f++)
    {
      for (int l = 0; l < n; l++)
      {
        for (int l1 = 0; l1 < n; l1++)
        {
          if (l1 == l)
          {
            continue;
          }
          int f1 = f + abs(locations[l1] - locations[l]);
          if (f1 <= fuel)
          {
            dp[l1][f1] += dp[l][f];
          }
        }
      }
    }
    return std::accumulate(dp[finish].begin(), dp[finish].end(), C1097Int()).ToInt();
  }
};

测试用例

template<class T>
void Assert(const T& t1, const T& t2)
{
  assert(t1 == t2);
}
template<class T>
void Assert(const vector<T>& v1, const vector<T>& v2)
{
  if (v1.size() != v2.size())
  {
    assert(false);
    return;
  }
  for (int i = 0; i < v1.size(); i++)
  {
    Assert(v1[i], v2[i]);
  }
}
int main()
{ 
  vector<int> locations;
  int start,  finish,  fuel;
  {
    Solution sln;
    locations = { 2, 3, 6, 8, 4 }, start = 1, finish = 3, fuel = 5;
    auto res = sln.countRoutes(locations, start, finish, fuel);
    Assert(4, res);
  }
  {
    Solution sln;
    locations = { 4, 3, 1 }, start = 1, finish = 0, fuel = 6;
    auto res = sln.countRoutes(locations, start, finish, fuel);
    Assert(5, res);
  }
  {
    Solution sln;
    locations = { 5, 2, 1 }, start = 0, finish = 2, fuel = 3;
    auto res = sln.countRoutes(locations, start, finish, fuel);
    Assert(0, res);
  }
}

小幅优化

排序后,向右(左)第一个油量不够的城市就停止。

class Solution {
public:
  int countRoutes(vector<int>& locations, int start, int finish, int fuel) {
    const int n = locations.size();
    const int startLoc = locations[start];
    const int finishLoc = locations[finish];
    sort(locations.begin(), locations.end());
    start = std::find(locations.begin(), locations.end(), startLoc)- locations.begin();
    finish = std::find(locations.begin(), locations.end(), finishLoc) - locations.begin();
    vector<vector<C1097Int<> >> dp(n, vector<C1097Int<>>(fuel + 1));
    dp[start][0] = 1;
    for (int f = 0; f < fuel; f++)
    {
      for (int l = 0; l < n; l++)
      {
        int use = 0;
        for (int l1 = l+1 ;(l1 < n )&&( f + (use = locations[l1] - locations[l]) <= fuel); l1++)
        {
          dp[l1][f+use] += dp[l][f];          
        }
        for (int l1 = l - 1; (l1 >= 0 ) && (f + (use = locations[l] - locations[l1]) <= fuel); l1--)
        {
          dp[l1][f + use] += dp[l][f];
        }
      }
    }
    return std::accumulate(dp[finish].begin(), dp[finish].end(), C1097Int()).ToInt();
  }
};

再次优化

填表顺序,还是从使用汽油少的到使用汽油多的。

前一个位置可能在当前位置的左边,也可能是右边。不失一般性,只讨论从左边过来。

假定当前使用汽油是f,位置是l。前一站使用的汽油是f1,位置是l1。则

行驶的路径等于消耗的汽油 → \rightarrow f-f1= l - l1 → \rightarrow f-l = f1-l1 性质一

符合性质一的状态分以下三类:

一,使用汽油比当前使用的汽油少。此状态就是本状态的前置状态。

二,使用汽油和当前状态使用的汽油一样,就是本状态。

三,使用汽油比当前汽油多,还没有更新。

结论: 符合性质一的状态路径和,就是本状态的路径和。

从右边来,类似:

f-f1=l1-l → \rightarrow f+l==f1+l1 性质二

m1,记录性质一;m2 记录性质二。

时间复杂度:将为O(nfuel)。

class Solution {
public:
  int countRoutes(vector<int>& locations, int start, int finish, int fuel) {
    const int n = locations.size();
    vector<vector<C1097Int<> >> dp(n, vector<C1097Int<>>(fuel + 1));
    unordered_map<int, C1097Int<>> m1,m2;
    dp[start][0] = 1;
    m1[0 - locations[start]] +=1 ;
    m2[0 + locations[start]] += 1;
    for (int f = 1; f <= fuel; f++)
    {
      for (int l = 0; l < n; l++)
      {
        dp[l][f] = m1[f- locations[l]]+ m2[f + locations[l]];
        m1[f - locations[l]] += dp[l][f];
        m2[f + locations[l]] += dp[l][f];
      }
    }
    return std::accumulate(dp[finish].begin(), dp[finish].end(), C1097Int()).ToInt();
  }
};

2023年2月第一版

class C1097Int

{

public:

C1097Int(int iData = 0) :m_iData(iData)

{

}

C1097Int operator+(const C1097Int& o)const

{

return C1097Int((m_iData + o.m_iData) % s_iMod);

}

C1097Int& operator+=(const C1097Int& o)

{

m_iData = (m_iData + o.m_iData) % s_iMod;

return this;
}
C1097Int operator
(const C1097Int& o)const

{

return((long long)m_iData o.m_iData) % s_iMod;
}
C1097Int& operator
=(const C1097Int& o)

{

m_iData =((long long)m_iData *o.m_iData) % s_iMod;

return *this;

}

int ToInt()const

{

return m_iData;

}

private:

int m_iData = 0;;

static const int s_iMod = 1000000007;

};

int operator+(int iData, const C1097Int& int1097)

{

int iRet = int1097.operator+(C1097Int(iData)).ToInt();

return iRet;

}

int& operator+=(int& iData, const C1097Int& int1097)

{

iData = int1097.operator+(C1097Int(iData)).ToInt();

return iData;

}

class Solution {

public:

int countRoutes(vector& locations, int start, int finish, int fuel) {

m_c = locations.size();

vector<vector> vFuelPos(fuel + 1, vector(m_c));

vFuelPos[fuel][start] = 1;

for (int iCurFuel = fuel-1; iCurFuel >= 0; iCurFuel–)

{

for (int iPos = 0; iPos < m_c; iPos++)

{

for (int iPrePos = 0; iPrePos < m_c; iPrePos++)

{

if (iPrePos == iPos)

{

continue;

}

const int iNeedFuel = iCurFuel + abs(locations[iPos] - locations[iPrePos]);

if (iNeedFuel <= fuel)

{

vFuelPos[iCurFuel][iPos] += vFuelPos[iNeedFuel][iPrePos];

}

}

}

}

C1097Int iNum = 0;

for (int iCurFuel = fuel ; iCurFuel >= 0; iCurFuel–)

{

iNum += vFuelPos[iCurFuel][finish];

}

return iNum.ToInt();

}

int m_c;

};

2023年9月版

class Solution {

public:

int countRoutes(vector& locations, int start, int finish, int fuel) {

m_c = locations.size();

int startValue = locations[start], finishValue = locations[finish];

std::sort(locations.begin(), locations.end());

start = std::lower_bound(locations.begin(), locations.end(), startValue) - locations.begin();

finish = std::lower_bound(locations.begin(), locations.end(), finishValue) - locations.begin();

m_vLeft.assign(m_c, vector<C1097Int<>>(fuel + 1));

m_vRight = m_vLeft;

int iRemain;

if ((start+1 < m_c)&&(( iRemain = fuel - locations[start+1]+ locations[start ]) >=0 ))

{

m_vRight[start+1][iRemain] = 1;

}

if ((start > 0) && ((iRemain = fuel - locations[start] + locations[start - 1]) >= 0))

{

m_vLeft[start-1][iRemain] = 1;

}

for (int iFuel = fuel-1; iFuel > 0; iFuel–)

{

for (int city = 0; city < m_c; city++)

{

RightMoveRight(iFuel, city, locations);

RightMoveLeft(iFuel, city, locations);

LeftMoveRight(iFuel, city, locations);

LeftMoveLeft(iFuel, city, locations);

}

}

C1097Int<> biRet = 0;

for (int iFuel = fuel; iFuel >= 0; iFuel–)

{

biRet += m_vLeft[finish][iFuel];

biRet += m_vRight[finish][iFuel];

}

if (start == finish)

{

biRet += 1;

}

return biRet.ToInt();

}

void RightMoveRight(int iFuel, int city, const vector& loc)

{

if (city + 1 >= m_c)

{

return;

}

const int iNeedFuel = loc[city + 1] - loc[city];

if (iNeedFuel > iFuel)

{

return;

}

m_vRight[city + 1][iFuel - iNeedFuel] += m_vRight[city][iFuel] * 2;

}

void RightMoveLeft(int iFuel, int city, const vector& loc)

{

if (0 == city)

{

return;

}

const int iNeedFuel = loc[city] - loc[city - 1];

if (iNeedFuel > iFuel)

{

return;

}

m_vLeft[city - 1][iFuel - iNeedFuel] += m_vRight[city][iFuel];

}

void LeftMoveRight(int iFuel, int city, const vector& loc)

{

if (city + 1 >= m_c)

{

return;

}

const int iNeedFuel = loc[city + 1] - loc[city];

if (iNeedFuel > iFuel)

{

return;

}

m_vRight[city + 1][iFuel - iNeedFuel] += m_vLeft[city][iFuel];

}

void LeftMoveLeft(int iFuel, int city, const vector& loc)

{

if (0 == city)

{

return;

}

const int iNeedFuel = loc[city] - loc[city - 1];

if (iNeedFuel > iFuel)

{

return;

}

m_vLeft[city - 1][iFuel - iNeedFuel] += m_vLeft[city][iFuel] * 2;

}

vector<vector<C1097Int<>>> m_vLeft, m_vRight;

int m_c;

};


相关文章
|
5月前
|
机器学习/深度学习 存储 算法
动态规划算法深度解析:0-1背包问题
0-1背包问题是经典的组合优化问题,目标是在给定物品重量和价值及背包容量限制下,选取物品使得总价值最大化且每个物品仅能被选一次。该问题通常采用动态规划方法解决,通过构建二维状态表dp[i][j]记录前i个物品在容量j时的最大价值,利用状态转移方程避免重复计算子问题,从而高效求解最优解。
672 1
|
9月前
|
存储 监控 算法
基于 C++ 哈希表算法实现局域网监控电脑屏幕的数据加速机制研究
企业网络安全与办公管理需求日益复杂的学术语境下,局域网监控电脑屏幕作为保障信息安全、规范员工操作的重要手段,已然成为网络安全领域的关键研究对象。其作用类似网络空间中的 “电子眼”,实时捕获每台电脑屏幕上的操作动态。然而,面对海量监控数据,实现高效数据存储与快速检索,已成为提升监控系统性能的核心挑战。本文聚焦于 C++ 语言中的哈希表算法,深入探究其如何成为局域网监控电脑屏幕数据处理的 “加速引擎”,并通过详尽的代码示例,展现其强大功能与应用价值。
206 2
|
9月前
|
监控 算法 数据处理
基于 C++ 的 KD 树算法在监控局域网屏幕中的理论剖析与工程实践研究
本文探讨了KD树在局域网屏幕监控中的应用,通过C++实现其构建与查询功能,显著提升多维数据处理效率。KD树作为一种二叉空间划分结构,适用于屏幕图像特征匹配、异常画面检测及数据压缩传输优化等场景。相比传统方法,基于KD树的方案检索效率提升2-3个数量级,但高维数据退化和动态更新等问题仍需进一步研究。未来可通过融合其他数据结构、引入深度学习及开发增量式更新算法等方式优化性能。
238 17
|
8月前
|
存储 机器学习/深度学习 算法
基于 C++ 的局域网访问控制列表(ACL)实现及局域网限制上网软件算法研究
本文探讨局域网限制上网软件中访问控制列表(ACL)的应用,分析其通过规则匹配管理网络资源访问的核心机制。基于C++实现ACL算法原型,展示其灵活性与安全性。文中强调ACL在企业与教育场景下的重要作用,并提出性能优化及结合机器学习等未来研究方向。
228 4
|
7月前
|
存储 监控 算法
基于跳表数据结构的企业局域网监控异常连接实时检测 C++ 算法研究
跳表(Skip List)是一种基于概率的数据结构,适用于企业局域网监控中海量连接记录的高效处理。其通过多层索引机制实现快速查找、插入和删除操作,时间复杂度为 $O(\log n)$,优于链表和平衡树。跳表在异常连接识别、黑名单管理和历史记录溯源等场景中表现出色,具备实现简单、支持范围查询等优势,是企业网络监控中动态数据管理的理想选择。
206 0
|
8月前
|
机器学习/深度学习 存储 算法
基于 C++ 布隆过滤器算法的局域网上网行为控制:URL 访问过滤的高效实现研究
本文探讨了一种基于布隆过滤器的局域网上网行为控制方法,旨在解决传统黑白名单机制在处理海量URL数据时存储与查询效率低的问题。通过C++实现URL访问过滤功能,实验表明该方法可将内存占用降至传统方案的八分之一,查询速度提升约40%,假阳性率可控。研究为优化企业网络管理提供了新思路,并提出结合机器学习、改进哈希函数及分布式协同等未来优化方向。
255 0
|
编译器 C++ 开发者
【C++篇】深度解析类与对象(下)
在上一篇博客中,我们学习了C++的基础类与对象概念,包括类的定义、对象的使用和构造函数的作用。在这一篇,我们将深入探讨C++类的一些重要特性,如构造函数的高级用法、类型转换、static成员、友元、内部类、匿名对象,以及对象拷贝优化等。这些内容可以帮助你更好地理解和应用面向对象编程的核心理念,提升代码的健壮性、灵活性和可维护性。
|
10月前
|
编译器 C++ 容器
【c++11】c++11新特性(上)(列表初始化、右值引用和移动语义、类的新默认成员函数、lambda表达式)
C++11为C++带来了革命性变化,引入了列表初始化、右值引用、移动语义、类的新默认成员函数和lambda表达式等特性。列表初始化统一了对象初始化方式,initializer_list简化了容器多元素初始化;右值引用和移动语义优化了资源管理,减少拷贝开销;类新增移动构造和移动赋值函数提升性能;lambda表达式提供匿名函数对象,增强代码简洁性和灵活性。这些特性共同推动了现代C++编程的发展,提升了开发效率与程序性能。
414 12
|
8月前
|
人工智能 机器人 编译器
c++模板初阶----函数模板与类模板
class 类模板名private://类内成员声明class Apublic:A(T val):a(val){}private:T a;return 0;运行结果:注意:类模板中的成员函数若是放在类外定义时,需要加模板参数列表。return 0;
220 0
|
8月前
|
存储 编译器 程序员
c++的类(附含explicit关键字,友元,内部类)
本文介绍了C++中类的核心概念与用法,涵盖封装、继承、多态三大特性。重点讲解了类的定义(`class`与`struct`)、访问限定符(`private`、`public`、`protected`)、类的作用域及成员函数的声明与定义分离。同时深入探讨了类的大小计算、`this`指针、默认成员函数(构造函数、析构函数、拷贝构造、赋值重载)以及运算符重载等内容。 文章还详细分析了`explicit`关键字的作用、静态成员(变量与函数)、友元(友元函数与友元类)的概念及其使用场景,并简要介绍了内部类的特性。
353 0

热门文章

最新文章