📜  河内基于成本的塔

📅  最后修改于: 2021-04-27 05:26:05             🧑  作者: Mango

这里解释了标准的河内塔问题。在标准问题中,所有光盘事务都被认为是相同的。给定一个3×3的矩阵cost [] [],其中包含在杆之间进行圆盘转移的成本,其中cost [i] [j]存储将圆盘从杆i转移到杆j的成本。同一杆之间的转移成本为0 。因此,成本矩阵的对角元素均为0 。任务是打印所有N个圆盘从杆1转移到杆3的最低成本。

例子:

方法:想法是使用自上而下的动态编程。
假设mincost(idx,src,dest)是将索引idxN的光盘从src转移到rod dest的最低成本。第三个杆既不是源杆,也不是目标杆,其值rem = 6 –(i + j),因为杆号分别为1、2和3,它们的总和为6。目的地,则辅助杆的编号将为6 –(1 + 3)= 2。
现在将问题分为以下子问题:

  • 情况1:首先将索引为(idx +1)的所有光盘转移到N到其余杆。现在将最大的圆盘转移到目标杆。再次将所有光盘从剩余的杆传送到目标杆。此过程将花费为。
  • 情况2:首先将索引为(idx +1)的所有光盘转移到N到目标杆。现在将最大的圆盘转移到剩余的杆上。再次将所有光盘从目标杆传输到源杆。现在,将最大的圆盘从其余的杆转移到目标杆。再次将光盘从源杆传输到目标杆。此过程的成本为:
  • 答案将等于上述两种情况中的最小值。

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
#define RODS 3
#define N 3
int dp[N + 1][RODS + 1][RODS + 1];
  
// Function to initialize the dp table
void initialize()
{
  
    // Initialize with maximum value
    for (int i = 0; i <= N; i += 1) {
        for (int j = 1; j <= RODS; j++) {
            for (int k = 1; k <= RODS; k += 1) {
                dp[i][j][k] = INT_MAX;
            }
        }
    }
}
// Function to return the minimum cost
int mincost(int idx, int src, int dest,
            int costs[RODS][RODS])
{
  
    // Base case
    if (idx > N)
        return 0;
  
    // If problem is already solved,
    // return the pre-calculated answer
    if (dp[idx][src][dest] != INT_MAX)
        return dp[idx][src][dest];
  
    // Number of the auxiliary disk
    int rem = 6 - (src + dest);
  
    // Initialize the minimum cost as Infinity
    int ans = INT_MAX;
  
    // Calculationg the cost for first case
    int case1 = costs[src - 1][dest - 1]
                + mincost(idx + 1, src, rem, costs)
                + mincost(idx + 1, rem, dest, costs);
  
    // Calculating the cost for second case
    int case2 = costs[src - 1][rem - 1]
                + mincost(idx + 1, src, dest, costs)
                + mincost(idx + 1, dest, src, costs)
                + costs[rem - 1][dest - 1]
                + mincost(idx + 1, src, dest, costs);
  
    // Minimum of both the above cases
    ans = min(case1, case2);
  
    // Store it in the dp table
    dp[idx][src][dest] = ans;
  
    // Return the minimum cost
    return ans;
}
  
// Driver code
int main()
{
    int costs[RODS][RODS] = { { 0, 1, 2 },
                              { 2, 0, 1 },
                              { 3, 2, 0 } };
    initialize();
    cout << mincost(1, 1, 3, costs);
  
    return 0;
}


Java
// Java implementation of the approach
import java.io.*;
  
class GFG
{
      
static int RODS = 3;
static int N = 3;
static int [][][]dp=new int[N + 1][RODS + 1][RODS + 1];
  
// Function to initialize the dp table
static void initialize()
{
  
    // Initialize with maximum value
    for (int i = 0; i <= N; i += 1)
    {
        for (int j = 1; j <= RODS; j++)
        {
            for (int k = 1; k <= RODS; k += 1) 
            {
                dp[i][j][k] = Integer.MAX_VALUE;
            }
        }
    }
}
  
// Function to return the minimum cost
static int mincost(int idx, int src, int dest,int costs[][])
{
  
    // Base case
    if (idx > N)
        return 0;
  
    // If problem is already solved,
    // return the pre-calculated answer
    if (dp[idx][src][dest] != Integer.MAX_VALUE)
        return dp[idx][src][dest];
  
    // Number of the auxiliary disk
    int rem = 6 - (src + dest);
  
    // Initialize the minimum cost as Infinity
    int ans = Integer.MAX_VALUE;
  
    // Calculationg the cost for first case
    int case1 = costs[src - 1][dest - 1]
                + mincost(idx + 1, src, rem, costs)
                + mincost(idx + 1, rem, dest, costs);
  
    // Calculating the cost for second case
    int case2 = costs[src - 1][rem - 1]
                + mincost(idx + 1, src, dest, costs)
                + mincost(idx + 1, dest, src, costs)
                + costs[rem - 1][dest - 1]
                + mincost(idx + 1, src, dest, costs);
  
    // Minimum of both the above cases
    ans = Math.min(case1, case2);
  
    // Store it in the dp table
    dp[idx][src][dest] = ans;
  
    // Return the minimum cost
    return ans;
}
  
// Driver code
public static void main (String[] args) 
{
          
    int [][]costs = { { 0, 1, 2 },
                            { 2, 0, 1 },
                            { 3, 2, 0 } };
    initialize();
        System.out.print (mincost(1, 1, 3, costs));
          
}
}
  
// This code is contributed by ajit..23@


Python3
# Python3 implementation of the approach 
import numpy as np
import sys
  
RODS = 3 
N = 3 
dp = np.zeros((N + 1,RODS + 1,RODS + 1)); 
  
# Function to initialize the dp table 
def initialize() :
  
    # Initialize with maximum value 
    for i in range(N + 1) :
        for j in range(1, RODS + 1) :
            for k in range(1, RODS + 1) :
                dp[i][j][k] = sys.maxsize; 
              
  
# Function to return the minimum cost 
def mincost(idx, src, dest, costs) :
  
    # Base case 
    if (idx > N) :
        return 0; 
  
    # If problem is already solved, 
    # return the pre-calculated answer 
    if (dp[idx][src][dest] != sys.maxsize) :
        return dp[idx][src][dest]; 
  
    # Number of the auxiliary disk 
    rem = 6 - (src + dest); 
  
    # Initialize the minimum cost as Infinity 
    ans = sys.maxsize; 
  
    # Calculationg the cost for first case 
    case1 = costs[src - 1][dest - 1] + mincost(idx + 1, src, rem, costs) + mincost(idx + 1, rem, dest, costs); 
  
    # Calculating the cost for second case 
    case2 = (costs[src - 1][rem - 1] + mincost(idx + 1, src, dest, costs) + mincost(idx + 1, dest, src, costs) + costs[rem - 1][dest - 1] + mincost(idx + 1, src, dest, costs)); 
  
    # Minimum of both the above cases 
    ans = min(case1, case2); 
  
    # Store it in the dp table 
    dp[idx][src][dest] = ans; 
  
    # Return the minimum cost 
    return ans; 
  
  
# Driver code 
if __name__ == "__main__" : 
  
    costs = [ [ 0, 1, 2 ], 
            [ 2, 0, 1 ], 
            [ 3, 2, 0 ] ]; 
    initialize(); 
    print(mincost(1, 1, 3, costs)); 
  
    # This code is contributed by AnkitRai01


C#
// C# implementation of the approach
using System; 
      
class GFG
{
      
static int RODS = 3;
static int N = 3;
static int [,,]dp=new int[N + 1,RODS + 1,RODS + 1];
  
// Function to initialize the dp table
static void initialize()
{
  
    // Initialize with maximum value
    for (int i = 0; i <= N; i += 1)
    {
        for (int j = 1; j <= RODS; j++)
        {
            for (int k = 1; k <= RODS; k += 1) 
            {
                dp[i,j,k] = int.MaxValue;
            }
        }
    }
}
  
// Function to return the minimum cost
static int mincost(int idx, int src, int dest,int [,]costs)
{
  
    // Base case
    if (idx > N)
        return 0;
  
    // If problem is already solved,
    // return the pre-calculated answer
    if (dp[idx,src,dest] != int.MaxValue)
        return dp[idx,src,dest];
  
    // Number of the auxiliary disk
    int rem = 6 - (src + dest);
  
    // Initialize the minimum cost as Infinity
    int ans = int.MaxValue;
  
    // Calculationg the cost for first case
    int case1 = costs[src - 1,dest - 1]
                + mincost(idx + 1, src, rem, costs)
                + mincost(idx + 1, rem, dest, costs);
  
    // Calculating the cost for second case
    int case2 = costs[src - 1,rem - 1]
                + mincost(idx + 1, src, dest, costs)
                + mincost(idx + 1, dest, src, costs)
                + costs[rem - 1,dest - 1]
                + mincost(idx + 1, src, dest, costs);
  
    // Minimum of both the above cases
    ans = Math.Min(case1, case2);
  
    // Store it in the dp table
    dp[idx,src,dest] = ans;
  
    // Return the minimum cost
    return ans;
}
  
// Driver code
public static void Main (String[] args) 
{
          
    int [,]costs = { { 0, 1, 2 },
                            { 2, 0, 1 },
                            { 3, 2, 0 } };
    initialize();
        Console.WriteLine(mincost(1, 1, 3, costs));
          
}
}
  
/* This code is contributed by PrinciRaj1992 */


输出:
12

时间复杂度: O(N),其中N是给定杆中圆盘的数量。