#include<iostream> #include<sstream> using namespace std; string numberToString(int number){ ostringstream ss; ss << number; return ss.str(); } string stringNumPlusOne(string s, int pos){ bool added = false; s = s.substr(pos); for(int i=s.size()-1; i>=0; i--){ if(s[i] != '9'){ s[i] = char(s[i] + 1); added = true; break; } else{ s[i] = '0'; } } if(!added){ s += '0'; } return s; } int main(){ int n, a; cin >> n; n--; cin >> a; long long changes = 0; string last_number = numberToString(a); while(n--){ int a; cin >> a; string current_number = numberToString(a); int cns = current_number.size(), lns = last_number.size(); if(cns == lns){ if(current_number <= last_number){ last_number = current_number + '0'; changes += 1; } else { last_number = current_number; } } else if(cns < lns) { int string_compare = last_number.compare(0, cns, current_number); if(string_compare == 0){ last_number = current_number + stringNumPlusOne(last_number, cns); changes += last_number.size() - cns; } else if(string_compare > 0){ changes += lns - cns + 1; current_number.append(lns-cns+1, '0'); last_number = current_number; } else { changes += lns - cns; current_number.append(lns-cns, '0'); last_number = current_number; } } else{ last_number = current_number; } } cout << changes; }
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 | #include<iostream> #include<sstream> using namespace std; string numberToString(int number){ ostringstream ss; ss << number; return ss.str(); } string stringNumPlusOne(string s, int pos){ bool added = false; s = s.substr(pos); for(int i=s.size()-1; i>=0; i--){ if(s[i] != '9'){ s[i] = char(s[i] + 1); added = true; break; } else{ s[i] = '0'; } } if(!added){ s += '0'; } return s; } int main(){ int n, a; cin >> n; n--; cin >> a; long long changes = 0; string last_number = numberToString(a); while(n--){ int a; cin >> a; string current_number = numberToString(a); int cns = current_number.size(), lns = last_number.size(); if(cns == lns){ if(current_number <= last_number){ last_number = current_number + '0'; changes += 1; } else { last_number = current_number; } } else if(cns < lns) { int string_compare = last_number.compare(0, cns, current_number); if(string_compare == 0){ last_number = current_number + stringNumPlusOne(last_number, cns); changes += last_number.size() - cns; } else if(string_compare > 0){ changes += lns - cns + 1; current_number.append(lns-cns+1, '0'); last_number = current_number; } else { changes += lns - cns; current_number.append(lns-cns, '0'); last_number = current_number; } } else{ last_number = current_number; } } cout << changes; } |