๐Ÿ˜Ž ๊ณต๋ถ€ํ•˜๋Š” ์ง•์ง•์•ŒํŒŒ์นด๋Š” ์ฒ˜์Œ์ด์ง€?

[์ด๊ฒƒ์ด ์ฝ”๋”ฉ ํ…Œ์ŠคํŠธ๋‹ค with Python]_40_๊ตฌ๊ฐ„ ํ•ฉ ๋น ๋ฅด๊ฒŒ ๊ณ„์‚ฐํ•˜๊ธฐ ๋ณธ๋ฌธ

๐Ÿฆฅ ์ฝ”ํ…Œ/์ด๊ฒƒ์ด ์ฝ”๋”ฉ ํ…Œ์ŠคํŠธ๋‹ค with python

[์ด๊ฒƒ์ด ์ฝ”๋”ฉ ํ…Œ์ŠคํŠธ๋‹ค with Python]_40_๊ตฌ๊ฐ„ ํ•ฉ ๋น ๋ฅด๊ฒŒ ๊ณ„์‚ฐํ•˜๊ธฐ

์ง•์ง•์•ŒํŒŒ์นด 2022. 2. 16. 00:30
728x90
๋ฐ˜์‘ํ˜•

220216 ์ž‘์„ฑ

<๋ณธ ๋ธ”๋กœ๊ทธ๋Š” ใ€Ž์ด๊ฒƒ์ด ์ทจ์—…์„ ์œ„ํ•œ ์ฝ”๋”ฉ ํ…Œ์ŠคํŠธ๋‹คใ€ ์˜ youtube๋ฅผ ์ฐธ๊ณ ํ•ด์„œ ๊ณต๋ถ€ํ•˜๋ฉฐ ์ž‘์„ฑํ•˜์˜€์Šต๋‹ˆ๋‹ค>

https://www.youtube.com/watch?v=kqyHnoriStk&list=PLVsNizTWUw7H9_of5YCB0FmsSc-K44y81&index=40 

 

 

 

 

 

 

 

1. ๊ตฌ๊ฐ„ ํ•ฉ (interval sum)

: ์—ฐ์†์ ์œผ๋กœ ๋‚˜์—ด๋œ N๊ฐœ์˜ ์ˆ˜๊ฐ€ ์žˆ์„ ๋•Œ, ํŠน์ • ๊ตฌ๊ฐ„์˜ ๋ชจ๋“  ์ˆ˜๋ฅผ ํ•ฉํ•œ ๊ฐ’์„ ๊ณ„์‚ฐํ•˜๋Š” ๋ฌธ์ œ

 

1) N๊ฐœ์˜ ์ •์ˆ˜๋กœ ๊ตฌ์—ด๋œ ์ˆ˜์—ด

2) M๊ฐœ์˜ ์ฟผ๋ฆฌ ์ •๋ณด ์ฃผ์–ด์ง

- ๊ฐ ์ฟผ๋ฆฌ๋Š” LEFT, RIGHT ์œผ๋กœ ๊ตฌ์„ฑ

- ๊ฐ ์ฟผ๋ฆฌ์— ๋Œ€ํ•˜์—ฌ [LEFT, RIGHT] ๊ตฌ๊ฐ„์— ํฌํ•จ๋œ ๋ฐ์ดํ„ฐ๋“ค์˜ ํ•ฉ ์ถœ๋ ฅ

3) O(N+M)

 

 

 

2. ์ ‘๋‘์‚ฌ ํ•ฉ (Prefix sum)

: ๋ฐฐ์—ด์˜ ๋งจ ์•ž๋ถ€ํ„ฐ ํŠน์ • ์œ„์น˜๊นŒ์ง€์˜ ํ•ฉ ๋ฏธ๋ฆฌ ๊ตฌํ•˜๊ธฐ

- N๊ฐœ์˜ ์ˆ˜ ์œ„์น˜ ๊ฐ๊ฐ์— ๋Œ€ํ•˜์—ฌ ์ ‘๋‘์‚ฌ ํ•ฉ์„ ๊ณ„์‚ฐํ•˜์—ฌ P์— ์ €์žฅ

- ๋งค M๊ฐœ์˜ ์ฟผ๋ฆฌ ์ •๋ณด๋ฅผ ํ™•์ธํ•  ๋•Œ ๊ตฌ๊ฐ„ ํ•ฉ์€ P[RIGHT] - P[LEFT - 1]

 

 

 

 

 

 

 

  • python
# ๋ฐ์ดํ„ฐ์˜ ๊ฐœ์ˆ˜ N๊ณผ ์ „์ฒด ๋ฐ์ดํ„ฐ ์„ ์–ธ
n = 5
data = [10, 20, 30, 40, 50]

# ์ ‘๋‘์‚ฌ ํ•ฉ(Prefix Sum) ๋ฐฐ์—ด ๊ณ„์‚ฐ
sum_value = 0
prefix_sum = [0]
for i in data:
    sum_value += i
    prefix_sum.append(sum_value)

# ๊ตฌ๊ฐ„ ํ•ฉ ๊ณ„์‚ฐ (์„ธ ๋ฒˆ์งธ ์ˆ˜๋ถ€ํ„ฐ ๋„ค ๋ฒˆ์งธ ์ˆ˜๊นŒ์ง€)
left = 3
right = 4
print(prefix_sum[right] - prefix_sum[left - 1])

3, 4 ๋ฒˆ์งธ ํ•ฉ

  • c++
#include <bits/stdc++.h>

using namespace std;

int n = 5; // ๋ฐ์ดํ„ฐ์˜ ๊ฐœ์ˆ˜ N๊ณผ ๋ฐ์ดํ„ฐ ์ž…๋ ฅ๋ฐ›๊ธฐ
int arr[] = {10, 20, 30, 40, 50};
int prefixSum[6];

int main() {
    // ์ ‘๋‘์‚ฌ ํ•ฉ(Prefix Sum) ๋ฐฐ์—ด ๊ณ„์‚ฐ
    int sumValue = 0;

    for (int i = 0; i < n; i++) {
        sumValue += arr[i];
        prefixSum[i + 1] = sumValue;
    }

    // ๊ตฌ๊ฐ„ ํ•ฉ ๊ณ„์‚ฐ(์„ธ ๋ฒˆ์งธ ์ˆ˜๋ถ€ํ„ฐ ๋„ค ๋ฒˆ์งธ ์ˆ˜๊นŒ์ง€)
    int left = 3;
    int right = 4;
    cout << prefixSum[right] - prefixSum[left - 1] << '\n';
}
  • java
import java.util.*;

class Main {
    public static int n = 5; // ๋ฐ์ดํ„ฐ์˜ ๊ฐœ์ˆ˜ N๊ณผ ๋ฐ์ดํ„ฐ ์ž…๋ ฅ๋ฐ›๊ธฐ
    public static int arr[] = {10, 20, 30, 40, 50};
    public static int[] prefixSum = new int[6];

    public static void main(String[] args) {
        // ์ ‘๋‘์‚ฌ ํ•ฉ(Prefix Sum) ๋ฐฐ์—ด ๊ณ„์‚ฐ
        int sumValue = 0;

        for (int i = 0; i < n; i++) {
            sumValue += arr[i];
            prefixSum[i + 1] = sumValue;
        }

        // ๊ตฌ๊ฐ„ ํ•ฉ ๊ณ„์‚ฐ(์„ธ ๋ฒˆ์งธ ์ˆ˜๋ถ€ํ„ฐ ๋„ค ๋ฒˆ์งธ ์ˆ˜๊นŒ์ง€)
        int left = 3;
        int right = 4;
        System.out.println(prefixSum[right] - prefixSum[left - 1]);
    }
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

728x90
๋ฐ˜์‘ํ˜•
Comments