20241002

libohan0518發表於2024-10-03

跳蚤os

我們可以考慮使用線段樹

#include <bits/stdc++.h>

using namespace std;

const int N = 1e6 + 5;

struct node {
  int son[27];
} trie[500005];

struct F {
  int x;
  string s;
};

int n, m, cnt = 1, arr[N];

string mp[N];

int c(char a) {
  if (a == '/') {
    return 26;
  }
  return a - 'a';
}

F insert(string s) {
  int u = 1;
  string sum = "";
  for (int i = 0; i < s.size(); i++) {
    char cur = s[i];
    if (!trie[u].son[c(cur)]) {
      trie[u].son[c(cur)] = ++cnt;
    }
    u = trie[u].son[c(cur)];
    sum += cur;
    if (arr[u] && (i == s.size() - 1 || s[i + 1] == '/')) {
      sum = mp[u];
      u = arr[u];
      if (u == 2) {
        u = 1;
        sum = "";
      }
    }
  }
  return {u, sum};
}

string query(string s) {
  int u = 1;
  string sum = "";
  for (int i = 0; i < s.size(); i++) {
    char cur = s[i];
    if (!trie[u].son[c(cur)]) {
      trie[u].son[c(cur)] = ++cnt;
    }
    u = trie[u].son[c(cur)];
    sum += cur;
    if (arr[u] && (i == s.size() - 1 || s[i + 1] == '/')) {
      sum = mp[u];
      u = arr[u];
      if (u == 2) {
        u = 1;
        sum = "";
      }
    }
  }
  if (sum == "") {
    return "/";
  }
  return sum;
}

int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cin >> n >> m;
  for (int i = 1; i <= n; i++) {
    string s, t;
    cin >> s >> t;
    F tmp1 = insert(s), tmp2 = insert(t);
    arr[tmp1.x] = tmp2.x;
    mp[tmp1.x] = tmp2.s;
    //cout << tmp1.x << " " << tmp2.x << "\n";
  }
  for (int i = 1; i <= m; i++) {
    string s;
    cin >> s;
    cout << query(s) << "\n";
  }
  return 0;
}

T2

我們可以使用線段樹來維護,然後我們就可以