#include #include #include #include using namespace std; vector> goodstring(26, vector(26, 0)); vector> dp(27, vector(27, -1)); int f(int i, int j){ if(dp[i][j] != -1) return dp[i][j]; dp[i][j] = goodstring[i][j]; for(int k = i; k <= j; k++){ for(int kk = k; kk <= j; kk++){ if(f(i, k) > 0 && f(kk, j) > 0){ if((i == k && k == kk)) dp[i][j] = max(dp[i][j], max(f(i, k), f(kk, j))); else if((j == kk && k == kk)) dp[i][j] = max(dp[i][j], max(f(i, k), f(kk, j))); else dp[i][j] = max(dp[i][j], f(i, k) + f(kk, j)); } } } //cerr << i << " " << j << " = " << dp[i][j] << endl; return dp[i][j]; } int main(){ int n; cin >> n; vector s(n); for(auto &p: s) cin >> p; for(int ii = 0; ii < n; ii++){ auto &p = s[ii]; bool isgood = true; for(int i = 1; i < p.length(); i++){ if(p[i-1] > p[i]) isgood = false; } if(isgood){ int start = *p.begin()-'a'; int end = *p.rbegin()-'a'; if(start == end) goodstring[start][end] += p.length(); if(start != end) goodstring[start][end] = max(goodstring[start][end], (int)p.length()); } } for(int i = 0; i < 26; i++){ dp[i][i] = goodstring[i][i]; for(int j = i+1; j < 26; j++){ if(goodstring[i][j]) goodstring[i][j] += goodstring[i][i]; } for(int j = i-1; j >= 0; j--){ if(goodstring[j][i]) goodstring[j][i] += goodstring[i][i]; } } int ans = 0; for(int i = 0; i < 26; i++){ for(int j = 0; j < 26; j++){ ans = max(ans, f(i, j)); //cerr << f(i, j) << " "; } //cerr << endl; } cout << ans << endl; return 0; }