๋ณธ๋ฌธ์œผ๋กœ ๋ฐ”๋กœ๊ฐ€๊ธฐ
728x90
๐Ÿ”—๋ฌธ์ œ ๋ณด๋Ÿฌ๊ฐ€๊ธฐ
 

11660๋ฒˆ: ๊ตฌ๊ฐ„ ํ•ฉ ๊ตฌํ•˜๊ธฐ 5

์ฒซ์งธ ์ค„์— ํ‘œ์˜ ํฌ๊ธฐ N๊ณผ ํ•ฉ์„ ๊ตฌํ•ด์•ผ ํ•˜๋Š” ํšŸ์ˆ˜ M์ด ์ฃผ์–ด์ง„๋‹ค. (1 ≤ N ≤ 1024, 1 ≤ M ≤ 100,000) ๋‘˜์งธ ์ค„๋ถ€ํ„ฐ N๊ฐœ์˜ ์ค„์—๋Š” ํ‘œ์— ์ฑ„์›Œ์ ธ ์žˆ๋Š” ์ˆ˜๊ฐ€ 1ํ–‰๋ถ€ํ„ฐ ์ฐจ๋ก€๋Œ€๋กœ ์ฃผ์–ด์ง„๋‹ค. ๋‹ค์Œ M๊ฐœ์˜ ์ค„์—๋Š” ๋„ค

www.acmicpc.net

 

๐Ÿง‘‍๐Ÿ’ปํ’€์ด ๊ณผ์ •

  1. ์ดˆ๊ธฐ๊ฐ’์œผ๋กœ, 1ํ–‰๊ณผ 1์—ด ๊ฐ๊ฐ์˜ ๋ฐฐ์—ด ์›์†Œ์— ๋ˆ„์ ํ•ฉ์„ ์ €์žฅํ•ฉ๋‹ˆ๋‹ค.
  2. 2ํ–‰ 2์—ด ~ Nํ–‰ N์—ด๊นŒ์ง€ ๋‹ค์Œ ๊ณผ์ •์„ ๋ฐ˜๋ณตํ•ฉ๋‹ˆ๋‹ค.
    •  \( N \times N \) ๋ฐฐ์—ด์„ arr์ด๋ผ๊ณ  ํ•œ๋‹ค๋ฉด,
    • arr[row][col] += arr[row - 1][col] + arr[row][col - 1] - arr[row - 1][col - 1]
      • arr[row - 1][col]์—๋Š” (row - 1 ) * col ์‚ฌ๊ฐํ˜• ํฌ๊ธฐ๋งŒํผ์˜ ๋ˆ„์ ํ•ฉ์ด ์ €์žฅ๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค.
      • arr[row][col - 1]์—๋Š” row * (col - 1) ์‚ฌ๊ฐํ˜• ํฌ๊ธฐ๋งŒํผ์˜ ๋ˆ„์ ํ•ฉ์ด ์ €์žฅ๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค.
      • ์ฆ‰, arr[row - 1][col] + arr[row][col - 1]์„ ํ•˜๊ฒŒ ๋˜๋ฉด, arr[row - 1][col - 1]๋ถ€๋ถ„์ด ๊ฒน์น˜๊ฒŒ ๋ฉ๋‹ˆ๋‹ค.
      • ๋”ฐ๋ผ์„œ, arr[row - 1][col - 1]์„ ๋นผ์ค˜์•ผ row * col ์‚ฌ๊ฐํ˜•์˜ ๋ˆ„์ ํ•ฉ์ด ์ €์žฅ๋˜๊ฒŒ ๋ฉ๋‹ˆ๋‹ค.
      • ๊ทธ๋ฆผ์œผ๋กœ ํ‘œํ˜„ํ•˜์—ฌ ๋ณด๋Š” ๊ฒƒ์ด ๋” ์ดํ•ด๊ฐ€ ๋น ๋ฅผ ๊ฒ๋‹ˆ๋‹ค.

 

3. (x1, y1)๋ถ€ํ„ฐ (x2, y2)๊นŒ์ง€์˜ ์‚ฌ๊ฐํ˜• ํฌ๊ธฐ ํ•ฉ๊ณ„๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์ด ๊ตฌํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

  • (x1, y1)๋ถ€ํ„ฐ (x2, y2)์˜ ํ•ฉ๊ณ„ = arr[x2][y2] - arr[x2][y1 - 1] - arr[x1 - 1][y2] + arr[x1 - 1][y1 - 1]

 

โœ๏ธ์†Œ์Šค ์ฝ”๋“œ ๋ฐ ๊ฒฐ๊ณผ

#include <iostream>
#include <vector>
#define FAST_IO cout.tie(NULL); cin.tie(NULL); ios::sync_with_stdio(false);
using namespace std;

int main()
{
	FAST_IO;

	int N, M;
	cin >> N >> M;

	vector<vector<int>> field(N + 1, vector<int>(N + 1));
	for (int row = 1; row <= N; row++)
	{
		for (int col = 1; col <= N; col++)
		{
			// 1. 0ํ–‰ 0์—ด ๊ฐ’์€ ๊ทธ๋ƒฅ ์ €์žฅํ•˜๊ธฐ
			if (row == 1 and col == 1)
			{
				cin >> field[row][col];
				continue;
			}

			int data;
			cin >> data;

			// 2. 0๋ฒˆ์งธ ํ–‰์€ col - 1๋ฒˆ์งธ ๊ฐ’์—๋‹ค ์ƒˆ๋กœ์šด ๋ฐ์ดํ„ฐ๋ฅผ ๋”ํ•ด ๋ˆ„์ ํ•˜์—ฌ ์ €์žฅํ•˜๊ธฐ
			if (row == 1 and col > 1)
			{
				field[row][col] = field[row][col - 1] + data;
				continue;
			}

			// 3. 0๋ฒˆ์งธ ์—ด์€ row - 1๋ฒˆ์งธ ๊ฐ’์—๋‹ค ์ƒˆ๋กœ์šด ๋ฐ์ดํ„ฐ๋ฅผ ๋”ํ•ด ๋ˆ„์ ํ•˜์—ฌ ์ €์žฅํ•˜๊ธฐ
			if (col == 1 and row > 1)
			{
				field[row][col] = field[row - 1][col] + data;
				continue;
			}

			// 4. field[row][col] = [row - 1][col] + [row][col - 1] - [row - 1][col - 1] + data
			field[row][col] = field[row - 1][col] + field[row][col - 1] - field[row - 1][col - 1] + data;
		}
	}


	for (int i = 0; i < M; i++)
	{
		int x1, y1, x2, y2;
		cin >> x1 >> y1 >> x2 >> y2;

		// [x2, y2] ๋ฉด์  - ([x1 - 1, y2] ๊นŒ์ง€์˜ ๋ฉด์ ) - ([x2, y1 - 1] ๊นŒ์ง€์˜ ์—ด ๋ฉด์ ) + (์•ž์—์„œ ๋‘ ๋ฒˆ ๋นผ์„œ ๊ฒน์น˜๋Š” ๋ถ€๋ถ„)
		int answer = field[x2][y2] - field[x1 - 1][y2] - field[x2][y1 - 1] + field[x1 - 1][y1 - 1];
		cout << answer << "\n";
	}


	return 0;
}

 

728x90
๋ฐ˜์‘ํ˜•