hdu4370-Java-spfa

这个题容易错,第一点是考虑两种情况,1-n的最短路 对比 1自环和n自环的和,较小的那个就是结果的值。第二点是,求自环的时候,一定要初始化dis[1]为inf,(之前改了很多没用的
东西),第三点,java要使用读入挂, 否则tle


import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import java.util.StringTokenizer;


public class Main{
	
	static int[] dis,vis,L,head;
	static int con,uu,s,e,inf=0x3f3f3f3f,n,m;
	static int [][] map;

static class InputReader
{
    BufferedReader buf;
    StringTokenizer tok;
    InputReader()
    {
        buf = new BufferedReader(new InputStreamReader(System.in));
    }
    boolean hasNext()
    {
        while(tok == null || !tok.hasMoreElements()) 
        {
            try
            {
                tok = new StringTokenizer(buf.readLine());
            } 
            catch(Exception e) 
            {
                return false;
            }
        }
        return true;
    }
    String next()
    {
        if(hasNext()) return tok.nextToken();
        return null;
    }
    int nextInt()
    {
        return Integer.parseInt(next());
    }
    long nextLong()
    {
        return Long.parseLong(next());
    }
    double nextDouble()
    {
        return Double.parseDouble(next());
    }
    BigInteger nextBigInteger()
    {
        return new BigInteger(next());
    }
    BigDecimal nextBigDecimal()
    {
        return new BigDecimal(next());
    }
}

	static void djk(int s) {
		Queue <Integer>q=new LinkedList<Integer>();
		vis=new int[5000];
		for(int i=1;i<=n;i++) {
			if(i!=s) {
				q.add(i);
				dis[i]=map[s][i];
				vis[i]=0;
			}
		}
		dis[s]=inf;
		while(!q.isEmpty()) {
			int top = q.poll();
			vis[top]=1;
			for(int i=1;i<=n;i++) {
				if(i==top) continue;
				if(dis[i]>dis[top]+map[top][i]) {
					dis[i]=dis[top]+map[top][i];
					if(vis[i]==1) {
						vis[i]=0;
						q.add(i);
					}
				}
			}
		}
	}
	public static void main(String[] args) {
		InputReader sc  = new InputReader();
		map=new int [500][500];
		dis=new int[500];
		
		while(sc.hasNext()) {
			n=sc.nextInt();
			for(int i=1;i<=n;i++){
				for(int j=1;j<=n;j++) {
					map[i][j]=sc.nextInt();
				}
			}
			djk(1);
			int res1= dis[n]; 
			int res2=dis[1];//1自环
			djk(n);
			int res3=dis[n];//n自环
			System.out.println(Math.min(res1,res2+res3));
		}
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值