JAVA CCF-201409-4 最优配餐

欢迎访问我的CCF认证解题目录

 

题目描述

 

思路过程

最短路径的变形题,有多个起始点,需要计算出距离最近的起始点,采用BFS遍历即可。

注意:多个起始点一起压入队列,否则可能会超时

 

代码

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;

public class Main {
	
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String[] line = br.readLine().split(" ");
		int n = Integer.parseInt(line[0]), m = Integer.parseInt(line[1]);
		int k = Integer.parseInt(line[2]), d = Integer.parseInt(line[3]);
		int[][] graph = new int[n+1][n+1];//到达每个点的最小花费
		int[][] way = {{0,1}, {1,0}, {0,-1}, {-1,0}};//方向
		int INF = Integer.MAX_VALUE;//未访问的初始值
		Node[] buys = new Node[k];//客户
		LinkedList<Node> q = new LinkedList<Node>();//队列
		
		//初始化图
		for ( int i = 1; i <= n; i++ ) {
			for ( int j = 1; j <= n; j++ ) {
				graph[i][j] = INF;
			}
		}
		
		//读入商店
		for ( int i = 0; i < m; i++ ) {
			line = br.readLine().split(" ");
			int x = Integer.parseInt(line[0]), y = Integer.parseInt(line[1]);
			q.add(new Node(x,y));
			graph[x][y] = 0;
		}
		
		//读入买家
		for ( int i = 0; i < buys.length; i++ ) {
			line = br.readLine().split(" ");
			buys[i] = new Node(Integer.parseInt(line[0]), Integer.parseInt(line[1]), Integer.parseInt(line[2]));
		}
		
		//标记不能访问的点
		for ( int i = 0; i < d; i++ ) {
			line = br.readLine().split(" ");
			graph[Integer.parseInt(line[0])][Integer.parseInt(line[1])] = -1;
		}
		
		//BFS
		while ( !q.isEmpty() ) {
			Node temp = q.remove(0);
			
			for ( int j = 0; j < way.length; j++ ) {
				int r = temp.r+way[j][0], c = temp.c+way[j][1];
				//不越界,能访问且能优化
				if ( r > 0 && r <= n && c > 0 && c <= n && graph[r][c] != -1 && graph[temp.r][temp.c]+1 < graph[r][c] ) {
					graph[r][c] = graph[temp.r][temp.c]+1;
					q.add(new Node(r, c));
				}
			}
		}
		
		long sum = 0;
		for ( int i = 0; i < k; i++ ) {
			sum += graph[buys[i].r][buys[i].c]*buys[i].cnt;
		}
		
		System.out.println(sum);
	}
	
}
class Node{
	int r, c, cnt;
	public Node(int r, int c) {
		this.r = r;
		this.c = c;
	}
	
	public Node(int r, int c, int cnt) {
		this.r = r;
		this.c = c;
		this.cnt = cnt;
	}
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值