POJ-1724 ROADS

Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 12451   Accepted: 4597

Description

N cities named with numbers 1 ... N are connected with one-way roads. Each road has two parameters associated with it : the road length and the toll that needs to be paid for the road (expressed in the number of coins). 
Bob and Alice used to live in the city 1. After noticing that Alice was cheating in the card game they liked to play, Bob broke up with her and decided to move away - to the city N. He wants to get there as quickly as possible, but he is short on cash. 

We want to help Bob to find  the shortest path from the city 1 to the city N  that he can afford with the amount of money he has. 

Input

The first line of the input contains the integer K, 0 <= K <= 10000, maximum number of coins that Bob can spend on his way. 
The second line contains the integer N, 2 <= N <= 100, the total number of cities. 

The third line contains the integer R, 1 <= R <= 10000, the total number of roads. 

Each of the following R lines describes one road by specifying integers S, D, L and T separated by single blank characters : 
  • S is the source city, 1 <= S <= N 
  • D is the destination city, 1 <= D <= N 
  • L is the road length, 1 <= L <= 100 
  • T is the toll (expressed in the number of coins), 0 <= T <=100

Notice that different roads may have the same source and destination cities.

Output

The first and the only line of the output should contain the total length of the shortest path from the city 1 to the city N whose total toll is less than or equal K coins. 
If such path does not exist, only number -1 should be written to the output. 

Sample Input

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

Sample Output

11

Source

CEOI 1998


之前一直T。。然后改了一下搜索时对边的遍历顺序,然后就A了。。好神奇,而且换成我自己造的随机数据也快了很多,一个程序的命运啊,当然要靠算法的奋斗,但也要考虑到遍历的进程。

#include <cstdio>
#include <cstring>
#include <vector>
#include <iostream>
#define MAXN 2147483647
using namespace std;
int n,k,ans,r,s,d[10001],l[10001],t[10001],f[101],v[101];
bool jud[101];
vector <int> a[101];
void dfs(int now,int dis,int k)
{
	if(k < 0) return;
	if(dis >= ans) return;
	if(f[now] <= dis && v[now] >= k) return;
	if(dis <= f[now] && k >= v[now])
	{
		f[now]=dis;
		v[now]=k;
	}
	if(now == n)
	{
		ans=dis;
		return ;
	}
	int length=a[now].size();
	if(length) 
	 for(int i = length-1;i >= 0;i--)
	 {
	 	 int u=a[now][i];
		 if(!jud[d[u]])
		 {
	 		 jud[d[u]]=true;
			 dfs(d[u],dis+l[u],k-t[u]);
			 jud[d[u]]=false;	
		 }
	 }  
}
int main()
{
	freopen("text.txt","r",stdin);
	memset(f,3,sizeof(f));
	memset(jud,0,sizeof(jud));
	f[1]=0;
	scanf("%d%d%d%",&k,&n,&r);
	for(int i = 1;i <= r;i++)
	{
		scanf("%d%d%d%d%",&s,&d[i],&l[i],&t[i]);
		a[s].push_back(i);
	} 
	ans=MAXN; 
	jud[1]=true;
	dfs(1,0,k);
	if(ans == MAXN) ans=-1;
	cout<<ans<<endl;
} 



你可能感兴趣的:(搜索,ACM)