Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- #define pb push_back
- #define mp make_pair
- #define sz(x) (int)(x).size()
- #define li long long
- #define ld long double
- #define x first
- #define y second
- #define pt pair<int, int>
- #define pll pair<ll, ll>
- #define forn(i, t) for(int i = 0; i < (t); i++)
- #define fore(i, f, t) for(int i = (f); i < (t); i++)
- #define forr(i, f, t) for(int i = (f) - 1; i >= (t); i--)
- #define all(x) (x).begin(), (x).end()
- #define ins insert
- using namespace std;
- mt19937 myrand(time(NULL));
- const int INF = 2e9;
- const int MOD = 1000000007;
- const li INF64 = 9223372036854775807;
- const ld EPS = 1e-7;
- const int N = 300 * 1000 + 13;
- const int AL = 26;
- int n;
- int g[AL][N], h[N], s[N], z[N];
- vector<int> d[N];
- pair<pt, int> st[N];
- pt st1[N];
- int cnt, cnt1;
- bool read(){
- if(scanf("%d\n", &n) != 1)
- return 0;
- int f, t;
- char c;
- memset(g, 255, sizeof(g));
- forn(i, n - 1){
- scanf("%d %d %c\n", &f, &t, &c);
- --f, --t;
- g[c - 'a'][f] = t;
- }
- return 1;
- }
- int dfs(int v, int k){
- d[k].pb(v);
- int cur = 1, maxn = 0;
- forn(i, AL)
- if (g[i][v] != -1){
- int t = dfs(g[i][v], k + 1);
- cur += t;
- if (h[v] == -1 || maxn < t){
- h[v] = g[i][v];
- maxn = t;
- }
- }
- s[v] = cur;
- z[k] += cur;
- return cur;
- }
- void merge(int a, int b){
- if (a == b || b == -1)
- return;
- int siz = 1;
- forn(i, 26){
- if (g[i][a] != -1 && g[i][b] != -1)
- merge(g[i][a], g[i][b]);
- else if (g[i][a] == -1 && g[i][b] != -1){
- st[cnt++] = mp(mp(i, a), g[i][a]);
- g[i][a] = g[i][b];
- }
- siz += (g[i][a] == -1 ? 0 : s[g[i][a]]);
- }
- st1[cnt1++] = mp(a, s[a]);
- s[a] = siz;
- }
- void print(int v){
- forn(i, 26)
- if (g[i][v] != -1){
- printf("%d %d %c\n", v + 1, g[i][v] + 1, 'a' + i);
- print(g[i][v]);
- }
- }
- void solve(){
- memset(z, 0, sizeof(z));
- memset(h, 255, sizeof(h));
- forn(i, n)
- d[i] = vector<int>();
- dfs(0, 0);
- cnt = 0;
- cnt1 = 0;
- int ans = INF, res = 0;
- forn(i, n){
- int tmp = 0;
- for (auto v : d[i]){
- int bst = h[v];
- if (bst == -1)
- continue;
- forn(j, AL)
- merge(bst, g[j][v]);
- tmp += s[bst];
- #ifdef _DEBUG
- forn(j, n)
- forn(k, AL)
- if (g[k][j] == v){
- st[cnt++] = mp(mp(k, j), g[k][j]);
- g[k][j] = -1;
- forn(l, AL)
- if (g[l][v] == bst){
- st[cnt++] = mp(mp(l, j), g[l][j]);
- g[l][j] = bst;
- break;
- }
- break;
- }
- #endif
- }
- #ifdef _DEBUG
- printf("\n%d\n", i + 1);
- print(0);
- printf("\n");
- #endif
- if (z[0] - z[i] + tmp < ans){
- ans = z[0] - z[i] + tmp;
- res = i + 1;
- }
- forr(j, cnt, 0)
- g[st[j].x.x][st[j].x.y] = st[j].y;
- forr(j, cnt1, 0)
- s[st1[j].x] = st1[j].y;
- cnt = 0;
- cnt1 = 0;
- }
- printf("%d\n%d\n", ans, res);
- }
- int main(){
- #ifdef _DEBUG
- freopen("input.txt", "r", stdin);
- #endif
- while(read())
- solve();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement