#include #include #include #include using namespace std; struct tup{ int s; int e; int len; tup(int s, int e, int len): s(s), e(e), len(len){} bool operator<(const tup &other) const { if(this->e != other.e) return this->e < other.e; else return this->s < other.s; }; }; int main(){ int n; cin >> n; vector s(n); for(auto &p: s) cin >> p; vector t; for(auto &it: s){ bool isgood = true; for(int i = 1; i < it.size(); i++){ if(it[i-1] > it[i]) isgood = false; } if(isgood) t.emplace_back(it[0]-'a', it.back()-'a', it.size()); } sort(t.begin(), t.end()); vector> dp(t.size()+1, vector(26, -(1 << 30))); for(int i = 0; i < t.size(); i++){ dp[i][t[i].e] = max(dp[i][t[i].e], t[i].len); if(i > 0){ for(int j = 0; j <= t[i].s; j++) dp[i][t[i].e] = max(dp[i][t[i].e], dp[i-1][j]+t[i].len); } for(int j = 0; j < 26; j++){ dp[i+1][j] = max(dp[i+1][j], dp[i][j]); } } int ans = 0; for(int i = 0; i < 26; i++) ans = max(ans, dp[t.size()][i]); cout << ans << endl; return 0; }