C-dijkstra

package Week2;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
//5 5
//1 2 20
//2 3 30
//3 4 20
//4 5 20
//1 5 100
//求N点返回到1点的距离 迪杰斯特拉
public class C_Dijkstra {
   static int T,N;
   static int dis[];
   static boolean visited[];
   static List<NodeA>[] adjList=null;
   static int ans;
   static PriorityQueue<NodeA> pq = null;
   
   public static void main(String[] args) throws Exception{
      System.setIn(new FileInputStream("Solution.txt"));
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      StringTokenizer st = new StringTokenizer(br.readLine());
      T = Integer.parseInt(st.nextToken());
      N = Integer.parseInt(st.nextToken());
      dis = new int[N+1];
      visited = new boolean[N+1];
      adjList = new List[N+1];
      Arrays.fill(dis, Integer.MAX_VALUE/2);
      for (int i = 0; i <= N; i++) {
        adjList[i]=new ArrayList<NodeA>();
      }
      pq = new PriorityQueue<NodeA>(com);
      ans = 0;
      for (int i = 1; i <= T; i++) {
        st = new StringTokenizer(br.readLine());
        int s = Integer.parseInt(st.nextToken());
        int e = Integer.parseInt(st.nextToken());
        int len = Integer.parseInt(st.nextToken());
        adjList[s].add(new NodeA(e,len));
        adjList[e].add(new NodeA(s,len));
      }
      
      pq.add(new NodeA(1,0));
      dis[1]=0;
      dijkstra();
      ans = dis[N];
      System.out.println(ans);
   }

   private static void dijkstra() {
       while(!pq.isEmpty()) {
           NodeA curr = pq.poll();
           if(!visited[curr.pos]) {
               visited[curr.pos]=true;
               for (int i = 0; i < adjList[curr.pos].size(); i++) {
                   NodeA next = adjList[curr.pos].get(i);
                  if(next.len+curr.len < dis[next.pos]) {
                      dis[next.pos] = next.len+curr.len ;
                      pq.add(new NodeA(next.pos,dis[next.pos]));
                  }
               }
           }
       }
    
   }
   
   static PriorityQueue<NodeA> com = new PriorityQueue<NodeA>(11,new Comparator<NodeA>() {
        @Override
        public int compare(NodeA o1, NodeA o2) {
            return o1.len-o2.len;
        }
        
       });
}

class NodeA {
    int pos;
    int len;
    public NodeA(int pos,int len) {
        this.pos = pos;
        this.len = len;
    }
}
View Code

 

posted @ 2021-08-01 18:36  没带壳的蜗牛  阅读(32)  评论(0)    收藏  举报