• 微信公众号:美女很有趣。 工作之余,放松一下,关注即送10G+美女照片!

P2387母牛回家

开发技术 开发技术 2周前 (04-30) 8次浏览

题目链接:送母牛回家

迪杰斯特拉算法的应用.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.Buffer;
import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        int T = Integer.parseInt(st.nextToken());
        int N = Integer.parseInt(st.nextToken());

        ArrayList<int[]>[] roadList = new ArrayList[N+1];
        for(int i = 0;i<T;i++){
            st = new StringTokenizer(br.readLine());
            int start = Integer.parseInt(st.nextToken());
            int end = Integer.parseInt(st.nextToken());
            int weight = Integer.parseInt(st.nextToken());
            if(roadList[start] == null){
                roadList[start] = new ArrayList<int[]>();
            }
            if(roadList[end] == null){
                roadList[end] = new ArrayList<int[]>();
            }
            roadList[start].add(new int[]{end,weight});
            roadList[end].add(new int[]{start,weight});
        }

        PriorityQueue<int[]> pq = new PriorityQueue<int[]>(new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[1]-o2[1];
            }
        });

        int[] visitDist = new int[N+1];
        Arrays.fill(visitDist,100000000);
        visitDist[N] = 0;

        pq.add(new int[]{N,0});
        int cost=0;
        while(!pq.isEmpty()){
            int[] visit = pq.poll();
            if(visit[0] == 1){
                cost = visit[1];
                break;
            }
            List<int[]> conn = roadList[visit[0]];
            for(int i =0;i<conn.size();i++){
                int[] nextPoint = conn.get(i).clone();
                nextPoint[1] = nextPoint[1]+visit[1];
                if(nextPoint[1]<visitDist[nextPoint[0]]){
                    visitDist[nextPoint[0]] = nextPoint[1];
                    pq.add(nextPoint);
                }
            }
        }
        System.out.println(cost);
    }
}

程序员灯塔
转载请注明原文链接:P2387母牛回家
喜欢 (0)