【动态规划】【图论】【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;

};


相关文章
|
1月前
|
编译器 C++
VS Code设置C++编译器路径
VS Code设置C++编译器路径
30 0
|
1月前
|
算法 C++ 容器
【C++算法】双指针
【C++算法】双指针
|
1月前
|
存储 算法 Java
LeetCode初级算法题:反转链表+统计N以内的素数+删除排序数组中的重复项Java详解
LeetCode初级算法题:反转链表+统计N以内的素数+删除排序数组中的重复项Java详解
20 0
|
2月前
|
存储 算法 搜索推荐
|
3月前
|
算法 数据中心 C++
基于C++雪花算法工具类Snowflake -来自chatGPT
基于C++雪花算法工具类Snowflake -来自chatGPT
|
3月前
|
算法 数据处理 C++
C++一分钟之-迭代器与算法
【6月更文挑战第21天】C++ STL的迭代器统一了容器元素访问,分为多种类型,如输入、输出、前向、双向和随机访问。迭代器使用时需留意失效和类型匹配。STL算法如查找、排序、复制要求特定类型的迭代器,注意容器兼容性和返回值处理。适配器和算法组合增强灵活性,但过度使用可能降低代码可读性。掌握迭代器和算法能提升编程效率和代码质量。
46 3
|
3月前
|
算法 搜索推荐 C++
C++之STL常用算法(遍历、查找、排序、拷贝、替换、算数生成、集合)
C++之STL常用算法(遍历、查找、排序、拷贝、替换、算数生成、集合)
|
10天前
|
编译器 C++
C++ 类构造函数初始化列表
构造函数初始化列表以一个冒号开始,接着是以逗号分隔的数据成员列表,每个数据成员后面跟一个放在括号中的初始化式。
56 30
|
24天前
|
存储 编译器 C++
C ++初阶:类和对象(中)
C ++初阶:类和对象(中)
|
1月前
|
存储 安全 编译器
【C++】类和对象(下)
【C++】类和对象(下)
【C++】类和对象(下)