[ACM]环形

来源:互联网 发布:serv u软件下载 编辑:程序博客网 时间:2024/04/28 00:45

Problem Description

有一个n*m的矩阵,对于每次询问,要求求出指定环形区域(大矩形扣去小矩形)的所有数字的和,并输出。

Input

输入的第一行为一个整数T,表示共有T组数据。
对于每一组数据,第一行输入两个整数n,m,表示矩阵的大小
接下来n行每行输入m个整数a,表示整个矩阵。
下面一行输入一个整数q,表示询问的组数
接下来q行,每行输入8个整数x1,y1,x2,y2,x3,y3,x4,y4。x1,y1和x4,y4是环形外圈矩形左上角和右下角的顶点坐标,x2,y2和x3,y3
是环形内圈小矩形的左上角和右下角的顶点坐标,详细情况参考样例。
1<=x1<=x2<x3<=x4<=n,1<=y1<=y2<y3<=y4<=m,1<n,m,q<=1000,0<=a<=10^9

Output

对于每组样例的每个询问输出指定的环形区域的数字的和,每个和占一行

Sample Input

14 41 1 1 11 1 1 11 1 1 11 1 1 121 1 2 2 3 3 4 41 1 1 1 4 4 4 4

Sample Output

16

12

//方法一:大矩形减去小矩形#include<iostream>using namespace std;int main(){int t;cin >> t;while (t--){int n,m;cin >> n>>m;int **a;                              //new二维数组a = new int *[n];for (int i = 0; i < n; i++)a[i] = new int[m];for (int i = 0; i < n; i++)//输入for (int j = 0; j < m; j++){cin >> a[i][j];}int q;cin >> q;while (q--){int x1, y1, x2, y2, x3, y3, x4, y4;cin >> x1 >> y1 >> x2 >> y2 >> x3 >> y3 >> x4 >> y4;x1 -= 1; x2 -= 1; x3 -= 1; x4 -= 1;y1 -= 1; y2 -= 1; y3 -= 1; y4 -= 1;int deleteSum = 0;int allSum = 0;for (int i = x1; i <= x4; i++){for (int j = y1; j <=y4; j++){allSum += a[i][j];}}for (int i = x2+1; i < x3; i++){for (int j = y2+1; j < y3; j++){deleteSum += a[i][j];}}cout << allSum-deleteSum << endl;}for (int i = 0; i < n; i++)delete[] a[i];delete[] a;}}
//方法二:按行输入#include<iostream>using namespace std;int main(){int t;cin >> t;while (t--){int n,m;cin >> n>>m;int **a;                              //new二维数组a = new int *[n];for (int i = 0; i < n; i++)a[i] = new int[m];for (int i = 0; i < n; i++)//输入for (int j = 0; j < m; j++)cin >> a[i][j];int q;cin >> q;while (q--){int x1, y1, x2, y2, x3, y3, x4, y4;cin >> x1 >> y1 >> x2 >> y2 >> x3 >> y3 >> x4 >> y4;x1 -= 1; x2 -= 1; x3 -= 1; x4 -= 1;y1 -= 1; y2 -= 1; y3 -= 1; y4 -= 1;int sum = 0;for (int i = 0; i < n; i++){if (i<=x2&&i>=x1|| i >= x3&&i <= x4)for (int j = y1; j <= y4; j++)sum += a[i][j];else if (i>x2&&i<x3){for (int j = y1; j <= y2; j++)sum += a[i][j];for (int j = y3; j <= y4; j++)sum += a[i][j];}}cout << sum << endl;}for (int i = 0; i < n; i++)delete[] a[i];delete[] a;}}



0 0
原创粉丝点击