#include <iostream> #include <vector> #include <algorithm> using namespace std; pair<int, string> generateSmallestBigger(string & a, string & b){ if(b.size() > a.size()){ return {0, b}; } bool prefBigger = false; auto lastSmallerThan9 = -1; int digitAdded = 0; string res = b; for(int i =0; i < b.size(); i++){ if(b[i] > a[i]){ prefBigger = true; break; }else if(b[i] < a[i]){ for(int i=b.size(); i<=a.size(); i++){ digitAdded++; res+='0'; } return {digitAdded, res}; } } for(int i = b.size(); i < a.size(); i++){ if(prefBigger){ res+='0'; }else{ res+=a[i]; if(a[i] < '9'){ lastSmallerThan9 = i; } } digitAdded++; } if(!prefBigger){ if(lastSmallerThan9 == -1){ res+='0'; for(int i=b.size(); i < a.size(); ++i){ res[i] = '0'; } digitAdded++; }else{ res[lastSmallerThan9++]+=1; for(int i=lastSmallerThan9; i <a.size(); i++){ res[i]='0'; } } } return {digitAdded, res}; } int main(){ int n; cin >> n; string prev; cin >> prev; int digitNeeded = 0; for(int i=1; i<n; i++){ //cout << prev << endl; string a; cin >> a; auto resPair = generateSmallestBigger(prev, a); prev = resPair.second; digitNeeded+=resPair.first; } // cout << prev << endl; cout << digitNeeded << endl; return 0; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 | #include <iostream> #include <vector> #include <algorithm> using namespace std; pair<int, string> generateSmallestBigger(string & a, string & b){ if(b.size() > a.size()){ return {0, b}; } bool prefBigger = false; auto lastSmallerThan9 = -1; int digitAdded = 0; string res = b; for(int i =0; i < b.size(); i++){ if(b[i] > a[i]){ prefBigger = true; break; }else if(b[i] < a[i]){ for(int i=b.size(); i<=a.size(); i++){ digitAdded++; res+='0'; } return {digitAdded, res}; } } for(int i = b.size(); i < a.size(); i++){ if(prefBigger){ res+='0'; }else{ res+=a[i]; if(a[i] < '9'){ lastSmallerThan9 = i; } } digitAdded++; } if(!prefBigger){ if(lastSmallerThan9 == -1){ res+='0'; for(int i=b.size(); i < a.size(); ++i){ res[i] = '0'; } digitAdded++; }else{ res[lastSmallerThan9++]+=1; for(int i=lastSmallerThan9; i <a.size(); i++){ res[i]='0'; } } } return {digitAdded, res}; } int main(){ int n; cin >> n; string prev; cin >> prev; int digitNeeded = 0; for(int i=1; i<n; i++){ //cout << prev << endl; string a; cin >> a; auto resPair = generateSmallestBigger(prev, a); prev = resPair.second; digitNeeded+=resPair.first; } // cout << prev << endl; cout << digitNeeded << endl; return 0; } |