99. 激光炸弹
题意
给定一个5000x5000的地图 随机在该地图上放置物品,物品具有价值,且不同物品可以放置在同一位置 有一个炸弹的爆炸范围为RxR的正方形 问该炸弹在地图上爆炸一次,最多能摧毁的物品价值为多少
思路
枚举该正方形在地图中所有可能出现的位置 利用二维前缀和计算在正方形范围内物品的价值和 找出最大的那一个价值和
class Main {
BufferedReader reader = new BufferedReader ( new InputStreamReader ( System. in) ) ;
String[ ] split;
int n, r;
int x, y, w;
int [ ] [ ] map = new int [ 5010 ] [ 5010 ] ;
int [ ] [ ] S = new int [ 5010 ] [ 5010 ] ;
void run ( ) throws Exception {
split = reader. readLine ( ) . split ( " " ) ;
n = Integer. parseInt ( split[ 0 ] ) ;
r = Integer. parseInt ( split[ 1 ] ) ;
while ( n-- > 0 ) {
split = reader. readLine ( ) . split ( " " ) ;
x = Integer. parseInt ( split[ 0 ] ) ;
y = Integer. parseInt ( split[ 1 ] ) ;
w = Integer. parseInt ( split[ 2 ] ) ;
map[ x + 1 ] [ y + 1 ] += w;
}
for ( int i = 1 ; i <= 5001 ; i++ ) {
for ( int j = 1 ; j <= 5001 ; j++ ) {
S[ i] [ j] = S[ i - 1 ] [ j] + S[ i] [ j - 1 ] - S[ i - 1 ] [ j - 1 ] + map[ i] [ j] ;
}
}
int res = - Integer. MAX_VALUE;
for ( int i = 1 ; i <= 5001 ; i++ ) {
if ( i + r - 1 > 5001 ) break ;
for ( int j = 1 ; j <= 5001 ; j++ ) {
if ( j + r - 1 > 5001 ) break ;
int x1 = i, y1 = j;
int x2 = i + r - 1 , y2 = j + r - 1 ;
int sum = S[ x2] [ y2] - S[ x1 - 1 ] [ y2] - S[ x2] [ y1 - 1 ] + S[ x1 - 1 ] [ y1 - 1 ] ;
res = Math. max ( sum, res) ;
}
}
System. out. println ( res) ;
}
public static void main ( String[ ] args) throws Exception { new Main ( ) . run ( ) ; }
}