poj1724(dfs)

#include<iostream>
#include<vector>
#include<cstring>
#include<algorithm>
using namespace std;
struct road
{
    int d;
    int L;
    int t;
};
vector< vector<road> >F(110);
int totalcost=0;
const int inf = 1 << 30;
int minlen = 1<< 30;
int totalen=0;
int visited[300];
int x[110][10010];    //花费一定时候走的最长的路
int K, N, R;
void dfs(int k)
{
    if (k == N){
        if (totalen < minlen)                     //更新minlen                        
        {
            minlen = totalen;
            return;
        }
    }
    visited[k] = 1;
    for (size_t i = 0; i<F[k].size(); i++)
    {
        road r=F[k][i];
        if (totalcost + r.t>K)           //钱不够的话
            continue;
        if (totalen+r.L>=x[r.d][totalcost+r.t])         //花费一定的时候到达r.d路径最短
            continue;
        x[r.d][totalcost + r.t] = totalen + r.L;
        if (totalen + r.L > minlen)
            continue;
        if (!visited[r.d])
        {
            visited[r.d] = 1;
            totalen += r.L;
            totalcost += r.t;
            dfs(r.d);
            visited[r.d] = 0;
            totalen -= r.L;
            totalcost -= r.t;

        }
    }
}
int main()
{

    cin >> K >> N >> R;     
    for (int i = 0; i < R; i++)
    {
        
            int s;
            road r;
            cin >> s >> r.d >> r.L >> r.t;
            if (s != r.d){
                F[s].push_back(r);
            }
            
    }
    memset(visited,0,sizeof(visited));
    visited[1] = 1;
    fill(x[0], x[0] + 110 * 10010, inf);
    dfs(1);
    if (minlen < (1 << 30))
        cout << minlen;
    else
        cout << "-1";
    return 0;

}

ps:这道题考察了DFS的应用以及剪枝算法减少运行时间,其中第一次是oj出毛病了,一直compile error心碎一地,第二次超时。。。。。不过最后还是ac

猜你喜欢

转载自blog.csdn.net/luoshiyong123/article/details/80767988