ROADS(POJ) 剪枝+搜索

题目描述

N个城市,编号1到N。城市间有R条单向道路。
每条道路连接两个城市,有长度和过路费两个属性。
Bob只有K块钱,他想从城市1走到城市N。问最短共需要走多长的路。如果到不了N,输出-1
2<=N<=100
0<=K<=10000
1<=R<=10000
每条路的长度 L, 1 <= L <= 100
每条路的过路费T , 0 <= T <= 100

输入

输入的第一行包含整数K,0 <= K <= 10000,Bob可以在途中花费的最大硬币数。
第二行包含整数N,2 <= N <= 100,即城市总数。

第三行包含整数R,1 <= R <= 10000,道路总数。

以下R行中的每一行通过指定由单个空白字符分隔的整数S,D,L和T来描述一条道路:

S是源城市,1 <= S <= N.
D是目的地城市,1 <= D <= N.
L是道路长度,1 <= L <= 100
T是收费(以硬币数表示),0 <= T <= 100

请注意,不同的道路可能具有相同的源和目的地城市。

输出

输出的第一行和唯一一行应包含从城市1到城市N的最短路径的总长度,其总收费小于或等于K个硬币。
如果此路径不存在,则只应将数字-1写入输出。

输入样例

5  
6  
7  
1 2 2 3  
2 4 3 3  
3 4 2 4  
1 3 4 1  
4 6 2 1  
3 5 2 0  
5 4 3 2

输出样例

11

思路

DFS加剪枝

代码

#include<iostream>
#include<vector>
#include<cstring>
using namespace std;

int K,N,R;
struct Road
{
    int d,L,t; //终点为d,长度为L,过路费为t
};
vector<vector<Road> > cityMap(110); //邻接表

int minLen = 1<<30; //目前的最优路径
int totalLen; //正在走的路径的长度
int totalCost; //正在走的路径的花销
int visited[110];
int minL[110][10100]; //minL[i][j]表示从1到i点,花销为j的最短路的长度

void Dfs(int s)
{
    if(s == N) //边界条件
    {
        minLen = min(minLen,totalLen);
        return;
    }
    for(int i=0;i<cityMap[s].size();++i)
    {
        //逐个考察s右路连到的点
        int d=cityMap[s][i].d;
        if(!visited[d])
        {
            int cost=totalCost+cityMap[s][i].t;
            if(cost>K) continue;
            if(totalLen+cityMap[s][i].L>=minLen||
               totalLen+cityMap[s][i].L>=minL[d][cost]) continue;
            totalLen+=cityMap[s][i].L;
            totalCost+=cityMap[s][i].t;
            minL[d][cost]=totalLen;
            visited[d]=1;
            Dfs(d);
            visited[d]=0;
            totalCost-=cityMap[s][i].t;
            totalLen-=cityMap[s][i].L;
        }
    }
}

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)
            cityMap[s].push_back(r);
    }
    for(int i = 0;i<110;i++)
    {
        for(int j=0;j<10100;j++)
        {
            minL[i][j]=1<<30;
        }
    }
    memset(visited,0,sizeof(visited));
    totalLen = 0;
    totalCost = 0;
    visited[1]=1;
    minLen=1<<30;
    Dfs(1);
    if(minLen<1<<30)
        cout<<minLen<<endl;
    
    else
    {
        cout<<"-1"<<endl;
    }
    return 0;
    
}
print_r('1024节日快乐!')var_dump('1024节日快乐!')NSLog(@"1024节日快乐!")
System.out.println("1024节日快乐!");
console.log("1024节日快乐!);
print("1024节日快乐!");
printf("1024节日快乐!n");
cout << "1024节日快乐!" << endl;
Console.WriteLine("1024节日快乐!");
fmt.Println("1024节日快乐!")
Response.Write("1024节日快乐!");
alert(’1024节日快乐!’)

猜你喜欢

转载自blog.csdn.net/qq_41822647/article/details/83351508