POJ1724最短路

n个点,拥有总的价值money
m条边(u,v,len ,cost),长度len,代价cost
求不超过money的代价条件下最短路。


public class Main {
	public static void main(String[] args) {
		new Task().solve();
	}
}

class Task {
	InputReader in = new InputReader(System.in);
	PrintWriter out = new PrintWriter(System.out);
	
	class Edge implements Comparable<Edge>{
		int v , cost , len ;
		Edge(int v , int len , int cost) {
			this.v = v ;
			this.len = len ;
			this.cost = cost ;
		}
		@Override
		public int compareTo(Edge o) {
			if(len == o.len) 
				return (cost < o.cost) ? -1 : ((cost == o.cost) ? 0 : 1) ;
			return (len < o.len) ? -1 : ((len == o.len) ? 0 : 1) ;
		}
	}
	
	List<Edge>[] adj  ;
	
	int bfs(int start , int end , int money){
		Queue<Edge> q = new PriorityQueue<Edge>() ;
		q.add(new Edge(start , 0 , 0)) ;
		while(! q.isEmpty()){
			Edge now = q.poll() ;
			if(now.v == end) return now.cost <= money ? now.len : -1 ;
			for(Edge next : adj[now.v]){
				if(now.cost + next.cost <= money)
					q.add(new Edge(next.v , now.len+next.len , now.cost + next.cost)) ;
			}
		}
		return -1 ;
	}

	void solve() {
		int cost = in.nextInt() ;
		int n = in.nextInt() ;
		int m = in.nextInt() ;
	    adj = new List[n+1] ;
	    for(int i = 1 ; i <= n ; i++) 
	    	adj[i] = new ArrayList<Edge>() ;
		while(m-- > 0){
	    	adj[in.nextInt()].add(new Edge(in.nextInt() , in.nextInt() , in.nextInt())) ;
	    }
        out.println(bfs(1 , n , cost)) ;
		out.flush();

	}

}

class InputReader {
	public BufferedReader reader;
	public StringTokenizer tokenizer;

	public InputReader(InputStream stream) {
		reader = new BufferedReader(new InputStreamReader(stream), 32768);
		tokenizer = new StringTokenizer("");
	}

	private void eat(String s) {
		tokenizer = new StringTokenizer(s);
	}

	public String nextLine() {
		try {
			return reader.readLine();
		} catch (Exception e) {
			return null;
		}
	}

	public boolean hasNext() {
		while (!tokenizer.hasMoreTokens()) {
			String s = nextLine();
			if (s == null)
				return false;
			eat(s);
		}
		return true;
	}

	public String next() {
		hasNext();
		return tokenizer.nextToken();
	}

	public int nextInt() {
		return Integer.parseInt(next());
	}

	public long nextLong() {
		return Long.parseLong(next());
	}

	public double nextDouble() {
		return Double.parseDouble(next());
	}

	public BigInteger nextBigInteger() {
		return new BigInteger(next());
	}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值