using static System.Math; using System.Collections.Generic; using System.Linq; using System; public class P { public int start { get; set; } public int end { get; set; } public int L { get; set; } } public class Hello { static void Main() { var n = int.Parse(Console.ReadLine().Trim()); var ps = new List
(); for (int i = 0; i < n; i++) { var s = Console.ReadLine().Trim(); var w = getP(s); if (w.start != -1) ps.Add(w); } getAns(ps); } static void getAns(List
ps) { var n = ps.Count(); if (n == 0) { Console.WriteLine(0); return; } ps = ps.OrderBy(x => x.end).ThenBy(x => x.start).ToList(); var dp = new int[n, 27]; for (int i = 0; i < n; i++) for (int j = 1; j <= 26; j++) dp[i, j] = -1; var w = ps[0]; dp[0, 0] = 0; dp[0, w.end] = w.L; for (int i = 0; i < n - 1; i++) for (int j = 0; j <= 26; j++) { var ww = dp[i, j]; if (ww != -1) { dp[i + 1, j] = Max(dp[i + 1, j], ww); if (ps[i + 1].start >= j) { var nextend = ps[i + 1].end; dp[i + 1, nextend] = Max(dp[i + 1, nextend], ww + ps[i + 1].L); } } } var ans = 0; for (int i = 1; i <= 26; i++) { if (dp[n - 1, i] != -1) ans = Max(ans, dp[n - 1, i]); } Console.WriteLine(ans); } static P getP(string s) { var sL = s.Length; var ss = s.ToCharArray(); Array.Sort(ss); if (new string(ss) == s) return new P { start = s[0] - 'a' + 1, end = s[sL - 1] - 'a' + 1, L = sL }; else return new P { start = -1 }; } }