求单源点最短路径,用Dijkstra求解,390MS。
需要注意的是,问题涉及到的最大数达到了2^501,所以要使用BigInteger。其他就是常规的Dijkstra解法,不算复杂。
代码:
package Test1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import java.math.BigInteger;
public class Test14_1100 {
/**
* by qr jobdu 1100 2014-8-12 dijkstra
*
* @throws IOException
*
* Accepted 390MS
*/
public static void main(String[] args) throws IOException {
StreamTokenizer st = new StreamTokenizer(new BufferedReader(
new InputStreamReader(System.in)));
while (st.nextToken() != StreamTokenizer.TT_EOF) {
int n = (int) st.nval;
st.nextToken();
int m = (int) st.nval;
BigInteger road[][] = new BigInteger[n][n]; // n citys 0-->n-1 DS:邻接链表
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
road[i][j] = new BigInteger("2").pow(m); // 最初都为最大数
BigInteger weight = BigInteger.ONE; // 2^0 道路的长度
for (int i = 0; i < m; i++) {
st.nextToken();
int num1 = (int) st.nval;
st.nextToken();
int num2 = (int) st.nval;
road[num1][num2] = weight;
road[num2][num1] = weight;
weight = weight.multiply(new BigInteger("2")); //存储长度的时候不能模,所以采用BigInteger
}
BigInteger max=weight; //最大数
//可把Dijkstra写成一个方法便于重用
int min=0;//具有最小minLen的城市编号
BigInteger minLen[] = new BigInteger[n]; // 0号城市到其他城市的最短路 DS:两个数组,一个存储距离,一个标记城市是否在S中
boolean joinS[] = new boolean[n]; // 标记该城市是否已经在S集合中
for (int i = 0; i < n; i++) {
minLen[i] = road[0][i];
joinS[i] = false;
if( minLen[i].compareTo(minLen[min])<0){ // <
min=i;
}
}
joinS[0] = true;
for(int t=0;t<n-2;t++){ //共有n-1个城市加入S,但最后一个不用管
joinS[min]=true;
for (int i = 1; i < n; i++) { //城市加入S之后,修改与其邻接的城市的值
if (road[min][i].compareTo(max)!=0 && minLen[i].compareTo(minLen[min].add(road[min][i]))>0 && !joinS[i]) {
minLen[i]=minLen[min].add(road[min][i]); //这里不应该取模
}
}
//再找到minLen最小的城市号
min=0;
for(int i=1;i<n;i++){
if(minLen[i].compareTo(minLen[min])<0 && !joinS[i]){
min=i;
}
}
}
for(int i=1;i<n;i++){
if(minLen[i].compareTo(max)!=0){
System.out.println((minLen[i]).mod(new BigInteger("100000"))); //只在这里取模
}else{
System.out.println("-1");
}
}
}
}
}