SSl 2404 上学#线性动态规划#

题目

某人至少要花多少钱才能到达学校。


分析

spfa后,听取WA声一片,所以看了解题报告后发现是dp
(而且比深搜慢)
状态转移方程: f [ t + 1 ] [ n ] = m i n ( f [ i ] [ j ] + m o n e y [ i ] )


dp代码

#include <cstdio>
#include <cctype>
#include <cstring>
using namespace std;
int n,t,m,x[51],y[51],l[51],r[51],w[51],f[100001][51];
int in(){
    int ans=0; char c=getchar();
    while (!isdigit(c)) c=getchar();
    while (isdigit(c)) ans=ans*10+c-48,c=getchar();
    return ans;
}
int main(){
    freopen("shaxu.in","r",stdin);
    freopen("shaxu.out","w",stdout);
    n=in(); t=in(); m=in(); memset(f,127/3,sizeof(f)); f[0][1]=0;
    for (int i=1;i<=m;i++) x[i]=1+in(),y[i]=1+in(),l[i]=in(),r[i]=l[i]+1+in(),w[i]=in();
    for (int i=0;i<=t;i++)
    for (int j=1;j<=n;j++){
        if (f[i][j]==707406378) continue;
        for (int k=1;k<=m;k++)
        if (x[k]==j&&l[k]==i&&r[k]<=t+1)
        if (f[i][j]+w[k]<f[r[k]][y[k]]) f[r[k]][y[k]]=f[i][j]+w[k];
        if (f[i+1][j]>f[i][j]) f[i+1][j]=f[i][j];
    }
    if (f[t+1][n]==707406378) return !puts("-1"); else return !printf("%d",f[t+1][n]);
}

深搜代码

#include <cstdio>
#include <cctype>
#include <algorithm>
using namespace std;
unsigned short n,m,ls[51]; int mint=2147483647,t; bool v[51];
struct node{int x,y,must,last,w,next;}e[51];
int in(){
    int ans=0; char c=getchar();
    while (!isdigit(c)) c=getchar();
    while (isdigit(c)) ans=ans*10+c-48,c=getchar();
    return ans;
}
void dfs(int x,int cost,int now){
    if (x==n&&now<=t) {mint=min(mint,cost); return;}
    v[x]=1; int p=ls[x];
    while (p){
        if (!v[e[p].y]&&now<e[p].must)
        dfs(e[p].y,cost+e[p].w,e[p].must+e[p].last);
        p=e[p].next;
    }
    v[x]=0;
}
int main(){
    freopen("shaxu.in","r",stdin);
    freopen("shaxu.out","w",stdout);
    n=in(); t=in(); m=in();
    for (int i=1;i<=m;i++){
        e[i].x=in()+1; e[i].y=in()+1; e[i].must=in(); e[i].last=in();
        e[i].w=in(); e[i].next=ls[e[i].x]; ls[e[i].x]=i;
        if (e[i].x==1&&e[i].must==0) e[i].must++; 
    }
    dfs(1,0,0);
    if (mint==2147483647) return !puts("-1");
    return !printf("%d",mint);
}

猜你喜欢

转载自blog.csdn.net/sugar_free_mint/article/details/80029503
今日推荐