[BOJ] 16139λ² | μΈκ°-μ»΄ν¨ν° μνΈμμ© (C++)
2023. 8. 27. 17:46γCoding Test/BOJ
πλ¬Έμ 보λ¬κ°κΈ°
π§π»νμ΄ κ³Όμ
λμ λ©μ²ν μ€μ
μ΄μ λ¬Έμ μμ λμ ν©μ μ ꡬν΄λκ³ , μ¬κΈ°μμλ μ μ μ©μ λͺ»νλ μΆμ΅λλ€..
μ²μμλ DP[26][S.length()] λ°°μ΄μ μ μΈνμ¬, κ° μνλ²³λ§λ€ λ±μ₯ν νμλ₯Ό λμ νμ¬ μ μ₯νλ λ°©μμΌλ‘ μ κ·Όνμμ΅λλ€.
const int ALPHABET_COUNT = 26;
const int LOWER_A_ASCII = 97;
string S;
vector<vector<int>> DP(ALPHABET_COUNT, vector<int>(S.length()));
for (int i = 0; i < S.length(); i++)
{
// i-1λ² μ΄μ λμ κ°μλ€ κ·Έλλ‘ κ°μ Έμ€κΈ°
for (int j = 0; (i != 0) and (j < ALPHABET_COUNT); j++)
if (DP[j][i-1] != 0)
DP[j][i] = DP[j][i-1];
// S[i]μ ν΄λΉνλ μνλ²³ κ°μ μΆκ°
int index = S[i] - LOWER_A_ASCII;
DP[index][i]++;
}
μ΄λ κ² μ ꡬν΄λκ³ , μ μ§λ¬Έμμ DP[alphabet][r] - DP[alphabet][l - 1]μ μκ° λͺ» νλ μΆλ€μ...
μ무νΌ, μ μμ μκ° λͺ»νλ λ°λμ μ΄μ§ νμ(Binary Search)λ‘ νμ΄ λ°©ν₯μ λ°κΎΈμμ΅λλ€..
μ΄μ§ νμ λ°©μ μ κ·Ό
- μ£Όμ΄μ§ S λ¬Έμμ΄μμ, κ°κ°μ μνλ²³λ€μ΄ λ±μ₯νλ μΈλ±μ€ μμΉλ€μ λ°°μ΄λ‘ λ΄μμ΅λλ€.
- for λ¬ΈμΌλ‘ μμ°¨ νμν κ±°λΌ, μλμΌλ‘ μ€λ¦μ°¨μ μ λ ¬μ΄ λμ΄ μμ΅λλ€.
- λ¬Έμ μμ μ£Όμ΄μ§ l, rμ λνμ¬, lμλ lower_bound(), rμλ upper_bound()λ₯Ό μ μ©ν©λλ€.
- lower_bound()μ upper_bound() κ²°κ³Ό κ°κ°μ vector.begin()μ λΉΌλ©΄ μΈλ±μ€ λ²νΈκ° λμ΅λλ€.
- 2λ²μμ ꡬν μΈλ±μ€ λ²νΈ μ°¨μ΄κ° μ λ΅μ λλ€.
βοΈμμ€ μ½λ λ° κ²°κ³Ό
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
const int ALPHABET_COUNT = 26;
const int LOWER_A_ASCII = 97;
int main()
{
ios::sync_with_stdio(false);
cout.tie(NULL); cin.tie(NULL);
int quesitionCount;
string sequence;
cin >> sequence >> quesitionCount;
// 1. κ° μνλ²³λ§λ€, λμ€λ μμΉλ€μ μ μ₯
vector<vector<int>> alphabetPositions(ALPHABET_COUNT);
for (int i = 0; i < sequence.length(); i++)
{
int index = sequence[i] - LOWER_A_ASCII;
alphabetPositions[index].emplace_back(i);
}
// 2. μ΄μ§ νμμ μ΄μ©νμ¬, μΈλ±μ€ μ°¨μ΄λ₯Ό κ³μ° ν μΆλ ₯
for (int i = 0; i < quesitionCount; i++)
{
char find;
int l, r;
cin >> find >> l >> r;
int index = find - LOWER_A_ASCII;
int start = lower_bound(alphabetPositions[index].begin(), alphabetPositions[index].end(), l) - alphabetPositions[index].begin();
int last = upper_bound(alphabetPositions[index].begin(), alphabetPositions[index].end(), r) - alphabetPositions[index].begin();
cout << last - start << "\n";
}
return 0;
}
728x90
λ°μν
'Coding Test > BOJ' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
[BOJ] 11660λ² | κ΅¬κ° ν© κ΅¬νκΈ° 5 (C++) (0) | 2023.08.29 |
---|---|
[BOJ] 2559λ² | μμ΄ (C++) (0) | 2023.08.27 |
[BOJ] 11659λ² | κ΅¬κ° ν© κ΅¬νκΈ° 4 (C++) (0) | 2023.08.27 |
[BOJ] 10844λ² | μ¬μ΄ κ³λ¨ μ (C++) (0) | 2023.08.26 |
[BOJ] 3190λ² | λ± (C++) (1) | 2023.08.26 |