题解:UVA11488 Hyper Prefix Sets

· · 题解

UVA11488 Hyper Prefix Sets 题解

0x01 题意

给出 n 字符串,要你选出几个串使得最长公共前缀的长度与串的个数之积最大。

0x02 思路

可以为所有字符串维护一个字典树,然后用搜索依次遍历字典树的每个节点,要记录深度,最后统计答案。

0x03 代码

#include<bits/stdc++.h>
using namespace std;

const int N = 1e7 + 5;
int t, n, m, a[N][3], f[N], cnt = 1, ans;
string s;

inline void insert(const string &s){
  int u = 1;
  for(auto i : s){
    if(!a[u][i - '0']){
      a[u][i - '0'] = ++cnt;
    }
    u = a[u][i - '0'];
    f[u]++;
  }
}

inline int query(const string &s){
  int u = 1;
  for(auto i : s){
    u = a[u][i - '0'];
    if(!u){
      break;
    }
  }
  return f[u];
}

inline void init(){
  for(int i = 1; i <= cnt; i++){
    for(int j = 0; j <= 2; j++){
      a[i][j] = 0;
    }
    f[i] = 0;
  }
  cnt = 1;
  ans = 0;
}

void dfs(int u, int dep){
  if(u == 0) return;
  ans = max(ans, f[u] * dep);
  for(int i = 0; i < 2; i++){
    dfs(a[u][i], dep + 1);
  }
}

int main(){
  ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  cin >> t;
  while(t--){
    cin >> n;
    init();
    for(int i = 1; i <= n; i++){
      cin >> s;
      insert(s);
    }
    dfs(1, 0);
    cout << ans << "\n";
  }
  return 0;
}