P4046 [JSOI2010]快递服务

· · 题解

本题一眼看出是一道DP题,我们可以很容易得出状态和方程

好了我们就做完了,散了吧散了吧

上面这样显然是不行的,我们来想办法优化

可以通过大喊老司机带带我触发常数变0.00001特效,水过这个题

!!!Optimization:

Code:

#include<iostream>
#include<cstdio>
#include<queue>
#include<algorithm>
#include<cstring>
#define M(a) memset(a,0,sizeof(a))
#define inf (long long)1e18
using namespace std;

const int maxn=201;

typedef long long ll;

ll read(){
    char ch=getchar();int res=0,f=1;
    while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();} 
    while(isdigit(ch)){res=res*10+ch-'0';ch=getchar();}
    return res*f;
}

ll f[2][maxn][maxn];
int m,n,t;
ll ans;
ll c[maxn][maxn];
int pos[maxn*10];

int main(){
    scanf("%d",&n);
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            c[i][j]=read();
        }
    } 

    m=0;int p;
    while(cin>>p){
        pos[++m]=p;
    }
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            f[0][i][j]=f[1][i][j]=inf;
        }
    }
    int lst=0,now=1;
    f[lst][1][2]=0;
    pos[0]=3;
    for(int t=1;t<=m;t++){
        for(int i=1;i<=n;i++){
            for(int j=1;j<=n;j++){
                f[now][i][j]=inf;
            }
        }
        for(int i=1;i<=n;i++){
            for(int j=1;j<=n;j++)if(f[lst][i][j]!=inf&&i!=j&&i!=pos[t-1]&&j!=pos[t-1]){//三车位置:i,j,pos[t-1] 
                if(i!=pos[t]&&j!=pos[t])f[now][i][j]=min(f[now][i][j],f[lst][i][j]+c[pos[t-1]][pos[t]]);
                if(j!=pos[t])f[now][pos[t-1]][j]=min(f[now][pos[t-1]][j],f[lst][i][j]+c[i][pos[t]]);
                if(i!=pos[t])f[now][i][pos[t-1]]=min(f[now][i][pos[t-1]],f[lst][i][j]+c[j][pos[t]]);
            }
        }
        lst=1-lst,now=1-now;
    }
    ans=inf;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            ans=min(ans,f[lst][i][j]);
        }
    }
    printf("%lld\n",ans); 

}