题目不难,深搜水题。
大致题意为:给定n个城市以及m条道路,道路描述如下:s,d,l,t分别表示起点,终点,长度,花费,为有向道路,现在某人有k钱币,问从1能否到达n,若能则输出在满足花费不超过k的情况下的最短路径长度。
题意很明确:从1到n,要求总花费<=k,并且路径最短
典型深搜题型,剪枝关键:总花费<=k,并且路径最短
另外要注意的就是:由于可能存在多条路径(两个顶点之间),故需要用邻接表存储边信息
直接上代码:552K+110MS
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <cmath>
#include <cstring>
#include <stack>
#include <queue>
#include <map>
#include <algorithm>
#define Lson(p) (p<<1)
#define Rson(p) (p<<1|1)
#define Min(a,b) ((a+b)>>1)
#define lowbit(x) (x&(-x))
#define PI acos(-1.0)
#define Max(a,b) (a)>(b)?(a):(b)
#define Minn(a,b) (a)<(b)?(a):(b)
#define Inf 100000010
#define Maxx 110
using namespace std;
typedef struct Point{
int index;
int len;
int cost;
struct Point *next;
}point,*ppoint;
struct Node{
ppoint first;
}node[Maxx];
bool vis[Maxx];
int k,n,r;
int s,d,l,t;
int ans;
void add_edge(){
for(int i=1;i<=n;i++)
node[i].first=NULL;
for(int i=0;i<r;i++){
scanf("%d%d%d%d",&s,&d,&l,&t);
ppoint temp=(ppoint)malloc(sizeof(point));
temp->index=d;
temp->len=l;
temp->cost=t;
temp->next=node[s].first;
node[s].first=temp;
}
}
void dfs(int index,int tlen,int tsum){
if(index==n){
ans=tlen;
return ;
}
ppoint temp=node[index].first;
while(temp){
if(!vis[temp->index] && temp->len+tlen<ans && temp->cost+tsum<=k){ //最优化剪枝+可行性剪枝
vis[temp->index]=true;
dfs(temp->index,temp->len+tlen,temp->cost+tsum);
vis[temp->index]=false; //回溯
}
temp=temp->next;
}
}
int main(){
scanf("%d%d%d",&k,&n,&r);
add_edge();
memset(vis,0,sizeof(vis));
vis[1]=true;
ans=Inf;
dfs(1,0,0);
if(ans==Inf) //若不能到达,则输出-1
printf("-1\n");
else //否则输出最短路径长度
printf("%d\n",ans);
return 0;
}