CF392BTower of Hanoi (memory search)

CF392B


Jisouhaoti


Pretreatment

Consideration is given to a subject is moved from disk x y (code for a [] []), as we know it is not optimal

Like floyd shortest relaxation operation as pretreatment to give an optimum value b between two column [] []

for(int i=1;i<=3;i++)
    for(int j=1;j<=3;j++)
        scanf("%lld",&a[i][j]),b[i][j]=a[i][j];
for(int i=1;i<=3;i++)
    for(int j=1;j<=3;j++) if(i!=j)
        for(int k=1;k<=3;k++) if(k!=i&&k!=j)
            b[i][j]=min(b[i][j],b[i][k]+b[k][j]);

Hutchison found the body

Cool analysis, each transfer n disks has two transport methods:

  1. method one
  2. Method Two

We know that every time the maximum cost of the disk is directly a [] [], and the remainder of n-1 is obtained by a recursive search remember

When a disk recursively to just simply use the pre-optimal solution out of the B [] [] to

int dfs(int l,int r,int n){
    if(f[l][r][n]) return f[l][r][n]; //已经走过,直接返回
    if(n==1) return b[l][r]; //递归边界,只剩一个盘
    int x=6-l-r; //表示中介盘,因为三个盘编号之和为6
    int an1=dfs(l,x,n-1)+dfs(x,r,n-1)+a[l][r]; //方法一
    int an2=(dfs(l,r,n-1)<<1)+dfs(r,l,n-1)+a[l][x]+a[x][r]; //方法二
    return f[l][r][n]=min(an1,an2); //取个最优值
}

dfs (l, r, n) represents the number of disks is moved from the n-l r solution

So the answer is,dfs(1,3,n)


Note that this problem will explode int

AC Code:

#include <bits/stdc++.h>
#define int long long
using namespace std;
int n,a[5][5],b[5][5],f[5][5][50];
int dfs(int l,int r,int n){
    if(f[l][r][n]) return f[l][r][n];
    if(n==1) return b[l][r];
    int x=6-l-r;
    int an1=dfs(l,x,n-1)+dfs(x,r,n-1)+a[l][r];
    int an2=(dfs(l,r,n-1)<<1)+dfs(r,l,n-1)+a[l][x]+a[x][r];
    return f[l][r][n]=min(an1,an2);
}
signed main(){
    for(int i=1;i<=3;i++)
        for(int j=1;j<=3;j++)
            scanf("%lld",&a[i][j]),b[i][j]=a[i][j];
    for(int i=1;i<=3;i++)
        for(int j=1;j<=3;j++) if(i!=j)
            for(int k=1;k<=3;k++) if(k!=i&&k!=j)
                b[i][j]=min(b[i][j],b[i][k]+b[k][j]);
    scanf("%lld",&n);
    printf("%lld",dfs(1,3,n));
}

Guess you like

Origin www.cnblogs.com/think-twice/p/11237621.html