CodeForces 721C Journey

$dp$,拓扑排序。

记$dp[i][j]$表示走到节点$i$,走过了$j$个点的最小时间,然后就可以递推了。要注意的是节点$1$的入度一开始不一定等于$0$。

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<vector>
#include<map>
#include<set>
#include<queue>
#include<stack>
#include<iostream>
using namespace std;
typedef long long LL;
const double pi=acos(-1.0),eps=1e-6;
void File()
{
    freopen("D:\in.txt","r",stdin);
    freopen("D:\out.txt","w",stdout);
}
template <class T>
inline void read(T &x)
{
    char c = getchar();
    x = 0;
    while(!isdigit(c)) c = getchar();
    while(isdigit(c)) { x = x * 10 + c - '0'; c = getchar(); }
}

const int INF=0x7fffffff;
const int maxn=5010;
int dp[maxn][maxn];
struct Edge
{
    int v,nx; int w;
}e[maxn];
int h[maxn],sz,r[maxn];
int n,m,T;
queue<int>Q;
int pre[maxn][maxn];

void add(int u,int v,LL w)
{
    e[sz].v=v; e[sz].w=w;
    e[sz].nx=h[u]; h[u]=sz++;
}

int main()
{
    scanf("%d%d%d",&n,&m,&T);

    for(int i=0;i<=n;i++)
    {
        h[i]=-1;
        for(int j=0;j<=n;j++)
        {
            dp[i][j]=INF;
            pre[i][j]=-1;
        }
    }

    for(int i=1;i<=m;i++)
    {
        int u,v; LL w; scanf("%d%d%d",&u,&v,&w);
        add(u,v,w); r[v]++;
    }

    dp[1][1]=0;
    for(int i=1;i<=n;i++) if(r[i]==0) Q.push(i);
    bool flag=0;
    while(!Q.empty())
    {
        int top=Q.front(); Q.pop();
        if(top==1) flag=1;
        if(flag==0)
        {
            for(int i=h[top];i!=-1;i=e[i].nx)
            {
                int to=e[i].v;
                r[to]--;
                if(r[to]==0) Q.push(to);
            }
            continue;
        }
        for(int i=h[top];i!=-1;i=e[i].nx)
        {
            int to=e[i].v;
            for(int j=1;j<=n;j++)
            {
                if(dp[top][j-1]==INF) continue;
                if(dp[top][j-1]+e[i].w>T) continue;
                if(dp[top][j-1]+e[i].w>=dp[to][j]) continue;

                pre[to][j]=(top-1)*n+j-1-1;
                dp[to][j]=dp[top][j-1]+e[i].w;
            }
            r[to]--;
            if(r[to]==0) Q.push(to);
        }
    }

    int sum;
    for(int i=1;i<=n;i++) if(dp[n][i]<=T) sum=i;

    cout<<sum<<endl;
    int nowx=n,nowy=sum; stack<int>S;
    while(1)
    {
        S.push(nowx);
        int tx,ty;
        tx=pre[nowx][nowy]/n; tx++;
        ty=pre[nowx][nowy]%n; ty++;
        if(pre[nowx][nowy]==-1) break;
        nowx=tx; nowy=ty;
    }
    while(!S.empty())
    {
        cout<<S.top()<<" "; S.pop();
    }

    return 0;
}
原文地址:https://www.cnblogs.com/zufezzt/p/5925437.html