본문 바로가기

PS/BOJ

[C++] BOJ (백준) 15829 : Hashing

문제

15829번: Hashing (acmicpc.net)

 

15829번: Hashing

APC에 온 것을 환영한다. 만약 여러분이 학교에서 자료구조를 수강했다면 해시 함수에 대해 배웠을 것이다. 해시 함수란 임의의 길이의 입력을 받아서 고정된 길이의 출력을 내보내는 함수로 정

www.acmicpc.net

코드
#include <iostream>

#define R 31
#define M 1234567891

using namespace std;
typedef long long int lld;

lld R_pow(int n) {
  lld res = 1;
  for (int i = 0; i < n; i++) {
    res *= R;
    res %= M;
  }
  return res;
}

lld hashing(int l, const string &s) {
  lld res = 0;
  for (int i = 0; i < l; i++) {
    res += (s[i] - 'a' + 1) * R_pow(i);
    res %= M;
  }
  return res;
}

int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);

  int l;
  string s;
  cin >> l >> s;
  cout << hashing(l, s);
  return 0;
}
설명

mod(%) 연산에 대해 다음이 성립한다.
(a + b) mod n = (a mod n + b mod n) mod n

(a * b) mod n = (a mod n * b mod n)

오버플로우가 일어날 수 있기 때문에 모든 자료형은 long long int로 바꾸고,
계산 중간과정에서 계속 % 연산을 해준다.