codeforces 303 D. Ilya and Roads(动态规划)

多年没有写动态规划就是个悲剧啊!!省赛结束之后学习数据结构+动态规划..努力努力

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <cmath>
#include <stack>
#include <map>
#include <string>
#define LL long long
#define DB double
using namespace std;
const int N = 509;
const int M = 100009;
LL dp[N][N];
struct LT{
    int to,dis,nex;
} L[M];
int F[N],cnt =1 ;
void add(int f,int t,int d)
{
    L[cnt].dis = d; L[cnt].nex = F[f];
    L[cnt].to = t; F[f] = cnt++;
}
int n,m,k;
const int INF = 0x3f3f3f3f;
void solve()
{
    for(int i=0;i<=n+1;i++)
    {
        for(int j=1;j<=n+1;j++)
        dp[i][j] = 1ll*INF*INF;
    }
    for(int i=0;i<=n;i++)
    {
        for(int j=n;j>0;j--)
            dp[i][j] = min(dp[i][j],dp[i][j+1]);
        for(int j=0;j<=n;j++)
        {
            if(i-1>=0)
            dp[i][j] = min(dp[i-1][j],dp[i][j]);
            for(int k=F[i];k;k=L[k].nex)
            {
                int to = L[k].to;
                if(j+(to-i)<=n)
                {
                    dp[to][j+(to-i)] = min(dp[to][j+(to-i)],dp[i][j]+L[k].dis);
                }

            }
        }
    }

    LL ans = 1ll*INF*INF;
    for(int i=1;i<=n;i++)
    {
        for(int j=k;j<=n;j++)
        ans = min(dp[i][j],ans);
    }
    if(ans==1ll*INF*INF) cout<<"-1"<<endl;
    else cout<<ans<<endl;
}
int re[N][N];
int main()
{
    #ifndef ONLINE_JUDGE
    freopen("in.txt","r",stdin);
    #endif
    int a,b,c;
    scanf("%d%d%d",&n,&m,&k);
    cnt = 1;
    memset(re,0x7f,sizeof(re));
    for(int i=0;i<m;i++)
    {
        scanf("%d%d%d",&a,&b,&c);
        for(int j=a;j<=b;j++)
        re[j][b] = min(re[j][b],c);
    }
    for(int i=1;i<=n;i++)
    for(int j=i;j<=n;j++)
    if(re[i][j]!=0x7f7f7f7f)
    {
        add(i-1,j,re[i][j]);
    }
    solve();
    return 0;
}


你可能感兴趣的:(动态规划)