#include #include #include #include using namespace std; int main(){ int N; cin >> N; vector S(N); vector begin(N, 100), end(N, 100); for(int i = 0; i < N; i++){ cin >> S[i]; string T = S[i]; sort(T.begin(), T.end()); if(T != S[i]) continue; begin[i] = S[i][0] - 'a'; int sz = S[i].size(); end[i] = S[i][sz - 1] - 'a'; } vector ind(N); for(int i = 0; i < N; i++) ind[i] = i; sort(ind.begin(), ind.end(), [&](int x, int y){ if(begin[x] != begin[y]) return begin[x] < begin[y]; return end[x] < end[y]; }); vector len(26); for(int i = 0; i < N; i++){ if(begin[ind[i]] == 100) break; int temp = 0; for(int j = 0; j <= begin[ind[i]]; j++) temp = max(temp, len[j]); len[end[ind[i]]] = max(len[end[ind[i]]], temp + (int)S[ind[i]].size()); } cout << *max_element(len.begin(), len.end()) << endl; }