백준17228 아름다운 만영로

문제 링크

  • http://icpc.me/17228

사용 알고리즘

  • Hashing
  • DFS

시간복잡도

  • $O(N)$

풀이

DFS를 돌면서, 해시 값을 스택을 이용해 관리하면 됩니다.

전체 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/******************************
Author: jhnah917(Justice_Hui)
g++ -std=c++17 -DLOCAL
******************************/

#include <bits/stdc++.h>
#define x first
#define y second
#define all(v) v.begin(), v.end()
#define compress(v) sort(all(v)), v.erase(unique(all(v)), v.end())
#define IDX(v, x) lower_bound(all(v), x) - v.begin()
using namespace std;

using uint = unsigned;
using ll = long long;
using ull = unsigned long long;
using Edge = pair<int, char>;

constexpr ll p1 = 917, m1 = 998244353;

int N, ans;
vector<Edge> G[505050];
string P; ll ph, pw = 1;

vector<ll> stk;

void DFS(int v){
    if(stk.size() > P.size()){
        ll now = stk.back() - stk[stk.size()-P.size()-1] * pw;
        now %= m1; if(now < 0) now += m1;
        if(ph == now) ans++;
    }
    for(const auto &i : G[v]){
        stk.push_back((stk.back() * p1 + i.y) % m1);
        DFS(i.x);
        stk.pop_back();
    }
}

int main(){
    ios_base::sync_with_stdio(false); cin.tie(nullptr);
    cin >> N;
    for(int i=1; i<N; i++){
        int s, e; char x; cin >> s >> e >> x;
        G[s].emplace_back(e, x);
    }
    cin >> P;
    for(const auto &c : P){
        ph = (ph * p1 + c) % m1;
        pw = pw * p1 % m1;
    }
    stk.push_back(0);
    DFS(1);
    cout << ans;
}