还可以效率更好点:有时间修改(晚上写注释)
package com.bluebridge.org;
public class CoordinateValue {
public CoordinateValue(int location,int value)
{
this.location=location;
this.value=value;
}
int location;
int value;
}
package com.bluebridge.org;
import java.util.Comparator;
public class CustomComparatpr implements Comparator {
@Override
public int compare(CoordinateValue o1, CoordinateValue o2) {
// TODO Auto-generated method stub
//if(o1.location==o2.location)
//return 0;
if(o1.value
return -1;
else return 1;
}
}
package com.bluebridge.org;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Scanner;
import java.util.TreeSet;
public class ShortestPath {
static int n;
public static void main(String[] args)
{
Scanner scan=new Scanner(System.in);
int value;
n=scan.nextInt();
TreeSet set[]=new TreeSet[n+1];
int map[][]=new int[n+1][n+1];
for(int i=1;i<=n;i++)
Arrays.fill(map[i], -1);
do
{
int i=scan.nextInt();
int j=scan.nextInt();
value=scan.nextInt();
if(value>0)
{
if(set[i]==null)
set[i]=new TreeSet();
set[i].add(j);
map[i][j]=value;
}
}while(value>0);
System.out.println(Dijkstra(map,set));
}
private static int Dijkstra(int map[][],TreeSet set[])
{
boolean ans[]=new boolean[n+1];
TreeSet comSet=new TreeSet(new CustomComparatpr());
ArrayList list=new ArrayList();
for(int i=1;i<=n;i++)
{
CoordinateValue value=new CoordinateValue(i,Integer.MAX_VALUE);
comSet.add(value);
list.add(value);
}
list.get(0).value=0;
comSet.clear();
comSet.addAll(list);
Arrays.fill(ans,false);
for(int i=1;i
{
CoordinateValue value=null;;
Iterator it=comSet.iterator();
while(it.hasNext())
{
value=it.next();
if(value.location!=n&&!ans[value.location]&&set[value.location]!=null)
{
break;
}
}
ans[value.location]=true;
Iterator its=set[value.location].iterator();
while(its.hasNext())
{
int location=its.next();
CoordinateValue values=list.get(location-1);
if(value.value+map[value.location][location]
{
values.value=value.value+map[value.location][location];
comSet.clear();
comSet.addAll(list);
}
}
}
return list.get(n-1).value;
}
}