欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

天上的星星

程序员文章站 2022-10-03 20:10:53
天上的星星在一个星光摧残的夜晚,蒜头君一颗一颗的数这天上的星星。蒜头君给在天上巧妙的画了一个直角坐标系,让所有的星星都分布在第一象。天上有 nnn 颗星星,他能知道每一颗星星的坐标和亮度。现在,蒜头君问自己 q 次,每次他问自己每个矩形区域的星星的亮度和是多少(包含边界上的星星)。样例输入55 0 67 9 78 6 139 7 13 0 1940......

天上的星星

在一个星光摧残的夜晚,蒜头君一颗一颗的数这天上的星星。

蒜头君给在天上巧妙的画了一个直角坐标系,让所有的星星都分布在第一象。天上有 nnn 颗星星,他能知道每一颗星星的坐标和亮度。

现在,蒜头君问自己 q 次,每次他问自己每个矩形区域的星星的亮度和是多少(包含边界上的星星)。

天上的星星

天上的星星

 

样例输入

5
5 0 6
7 9 7
8 6 13
9 7 1
3 0 19
4
0 8 7 9
0 0 7 10
2 7 10 9
5 4 7 5

样例输出

7
32
8
0

题目来源

2018 蓝桥杯省赛 A 组模拟赛(一)

思路

二维前缀和 + 容斥

import java.util.*;
import java.math.*;

public class Main {
	static int[][] step = new int[30][30];
	public static void main(String[] args) {
		Scanner cin = new Scanner(System.in);
		
		int n = cin.nextInt();
		
		int[][] arr = new int[2005][2005];
		for(int i=0; i<n; i++) {
			int a = cin.nextInt();
			int b = cin.nextInt();
			int c = cin.nextInt();
			arr[a+1][b+1] += c;
		}
		
		//二维前缀和
		int[][] sum = new int[2005][2005];
		for(int i=1; i<=2001; i++) {
			for(int j=1; j<=2001; j++) {
				sum[i][j] = (sum[i-1][j] + sum[i][j-1] - sum[i-1][j-1]) + arr[i][j];
			}
		}
		
		int m = cin.nextInt();
		for(int i=0; i<m; i++) {
			int a = cin.nextInt()+1;
			int b = cin.nextInt()+1;
			int c = cin.nextInt()+1;
			int d = cin.nextInt()+1;
			
			int ans = sum[c][d] - sum[c][b-1] - sum[a-1][d] + sum[a-1][b-1];
			
			System.out.println(ans);
		}
	}
	
}

 

本文地址:https://blog.csdn.net/qq_37194492/article/details/90413786

相关标签: 前缀和 容斥