fork(14) download
  1. # include <bits/stdc++.h>
  2. using namespace std;
  3. # define fi cin
  4. # define fo cout
  5. string s[512];
  6. int dp[512][512];
  7. int main(void)
  8. {
  9. int n;
  10. fi>>n;
  11. for (int i = 1;i <= n;++i)
  12. fi>>s[i];
  13. int k = s[1].length();
  14. for (int i = 1;i <= n;++i)
  15. for (int j = 0;j < k;++j)
  16. dp[i][j] = 1e9;
  17. for (int i = 1;i <= n;++i)
  18. s[i] = s[i] + s[i];
  19. for (int i = 0;i < k;++i)
  20. dp[1][i] = i;
  21. for (int i = 2;i <= n;++i)
  22. {
  23. for (int j = 0;j < k;++j)
  24. for (int prev = 0;prev < k;++prev)
  25. if (s[i].substr(j,k) == s[i-1].substr(prev,k))
  26. dp[i][j] = min(dp[i][j],dp[i-1][prev] + j);
  27. }
  28. int ans = 1e9;
  29. for (int i = 0;i < k;++i)
  30. ans = min(ans,dp[n][i]);
  31. if (ans == 1e9)
  32. puts("-1");
  33. else
  34. fo << ans << '\n';
  35. return 0;
  36. }
  37.  
  38.  
  39.  
Runtime error #stdin #stdout 0s 17104KB
stdin
Standard input is empty
stdout
Standard output is empty