题目思路
1、算法基础课里的模板多源bfs
2、数据量输入较大,需要使用快读的方式,否则会TLE
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main
{
private static int N=1010;
private static int n,m,k,d;
private static int[][] map=new int[N][N];//map[i][j]>0,表示此位置是客户
private static boolean[][] st=new boolean[N][N];
private static Queue<Node> queue=new LinkedList<>();
private static long ans=0;
public static void main(String[] args) throws IOException
{
Scanner scan=new Scanner(System.in);
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
String str1 = read.readLine();
String[] split1 = str1.split("\\s+");
n=Integer.valueOf(split1[0]);
m=Integer.valueOf(split1[1]);
k=Integer.valueOf(split1[2]);
d=Integer.valueOf(split1[3]);
//店家
for(int i=0;i<m;i++)
{
String str = read.readLine();
String[] split = str.split("\\s+");
int x=Integer.valueOf(split[0]);
int y=Integer.valueOf(split[1]);
queue.offer(new Node(x,y,0));
st[x][y]=true;
//System.out.println(x+" "+y);
}
//买家
int cnt=0;
for(int i=0;i<k;i++)
{
String str = read.readLine();
String[] split = str.split("\\s+");
int x=Integer.valueOf(split[0]);
int y=Integer.valueOf(split[1]);
int c=Integer.valueOf(split[2]);
//System.out.println(x+" "+y+" "+c);
if(map[x][y]==0)
{
map[x][y]+=c;
}
else
{
cnt++;
map[x][y]+=c;
}
}
k-=cnt;//表示只要送到k个位置即可
//不能走的位置
for(int i=0;i<d;i++)
{
String str = read.readLine();
String[] split = str.split("\\s+");
int x=Integer.valueOf(split[0]);
int y=Integer.valueOf(split[1]);
st[x][y]=true;
//System.out.println(x+" "+y);
}
bfs();
System.out.println(ans);
scan.close();
}
private static void bfs()
{
int[] dx= {-1,0,1,0};
int[] dy= {0,1,0,-1};
Node t=null;
while(!queue.isEmpty())
{
t=queue.poll();
//买家位置
if(map[t.x][t.y]!=0)
{
k--;
ans+=(map[t.x][t.y]*t.step);
}
//送完了
if(k==0)
break;
for(int i=0;i<4;i++)
{
int tx=t.x+dx[i];
int ty=t.y+dy[i];
if(tx>=1&&tx<=n&&ty>=1&&ty<=n&&!st[tx][ty])
{
st[tx][ty]=true;
queue.offer(new Node(tx,ty,t.step+1));
}
}
}
}
private static class Node
{
private int x;
private int y;
private int step;
public Node(int x,int y,int step)
{
this.x=x;
this.y=y;
this.step=step;
}
}
}