fork(1) download
  1. n = int(input())
  2. s = [input().strip() for i in range(n)]
  3.  
  4. ss = [si+si for si in s] # save strings concatenated to themselves
  5. best = 10**9
  6. T = s[0] # initially target string is s[0]
  7. for i in range(len(T)):
  8. total_steps = 0
  9. for S in ss:
  10. steps = S.find(T) # finds occurence of T in S
  11. if steps==-1: # not found, hence impossible
  12. best = -1
  13. break
  14. total_steps += steps
  15. if best==-1: # impossible
  16. break
  17. best = min(total_steps, best)
  18. T = T[1:]+T[:1] # cyclic shift T to get next rotation
  19.  
  20. print(best)
Success #stdin #stdout 0.02s 27720KB
stdin
4
xzzwo
zwoxz
zzwox
xzzwo
stdout
5