TLE in #374 Div2 C -- Journey

Revision en1, by clanmasr2, 2016-10-02 13:04:22

I tried to solve it using DP which has parameter (current vertex (s) — No. of vertices that I've passed by (cnt) ) and it equals to minimum time takes to dp[s][cnt] but I get TLE in test case #33 ... I've read the editorial and I think I'm following the same approach .

#include<bits/stdc++.h>
using namespace std;
pair <int, int> arr[5001][1001];
vector <int> res2;
vector <int> res3;
int n, maxi = 0, T;
int dp[5001][5001], sz[5001];

int fun(int s, int cnt, int time)
{
    int &ret = dp[s][cnt];
        if(ret!=-1 && ret < time){res2.pop_back();return ret;}
    ret = 2e9;
    if(time > T)
    {
        res2.pop_back();
        return 2e9;
    }

    if(s == n)
    {
        if(maxi < cnt)
        {
            maxi = cnt;
            res3 = res2;
        }
        ret = time;
        res2.pop_back();
        return 0;
    }

    for(int i=0; i<sz[s];i++)
    {
        ret = time;
        res2.push_back(arr[s][i].first);
        fun(arr[s][i].first, cnt+1, time+arr[s][i].second);
    }
res2.pop_back();
return ret;
}
int main()
{
    memset(dp, -1, sizeof(dp));
    int m, f, t, v, mm;
    scanf("%d%d%d", &n, &m, &T);mm=m;
    arr[0][0] = make_pair(1, 0);sz[0]=1;
    while(m--)
    {
        scanf("%d%d%d", &f, &t, &v);
        arr[f][sz[f]] = (make_pair(t, v));sz[f]++;
    }
    fun(0, 0, 0);
    printf("%d\n", maxi);
    for(int i=0; i<res3.size(); i++)
        printf("%d ",res3[i]);
    cout<<endl;
return 0;
}

I've found a comment saying that it can be solved using Bellman Ford Algorithm but I still don't know how it can be used ?

Thanks in advance

Tags 374, journey, 2d-dp, bellman-ford

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en1 English clanmasr2 2016-10-02 13:04:22 1691 Initial revision (published)