fork(1) download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define inf 99999999999999
  4. int main() {
  5. ios_base::sync_with_stdio(false);
  6. cin.tie(NULL);
  7. int n,i;
  8. cin>>n;
  9. int cost[n];
  10. string a[n],b[n];
  11. for(i=0;i<n;i++)cin>>cost[i];
  12. for(i=0;i<n;i++){
  13. cin>>a[i];
  14. b[i]=a[i];
  15. reverse(b[i].begin(),b[i].end());
  16. }
  17. int ans=0;
  18. for(i=0;i<n-1;i++){
  19. if(a[i+1]<a[i]){
  20. long long c1=-99,c2=-99,c3=-99;
  21. if(b[i]<a[i+1])c1=cost[i];else c1=inf;
  22. if(b[i+1]>a[i])c2=cost[i+1];else c2=inf;
  23. if(b[i]<b[i+1])c3=cost[i]+cost[i+1];else c3=inf;
  24. if(c1 <= c2 && c1 <=c3 && c1!=inf){ans+=c1;if(c1==c2)a[i+1]=min(a[i+1],b[i+1]);}
  25. else if(c2<=c1 && c2 <=c3 && c2!=inf){ans+=c2;a[i+1]=min(a[i+1],b[i+1]);}
  26. else if(c3<=c1 && c3 <=c2 && c3!=inf){ans+=c3;a[i+1]=min(b[i+1],a[i+1]);}
  27. else {cout<<-1;return 0;}
  28. }
  29. }
  30. cout<<ans;
  31.  
  32. return 0;
  33. }
Success #stdin #stdout 0s 3468KB
stdin
3
1 3 1
aa
ba
ac
stdout
1