Codeforces 758D:Ability To Convert(思维+模拟)

http://codeforces.com/problemset/problem/758/D

题意:给出一个进制数n,还有一个数k表示在n进制下的值,求将这个数转为十进制最小可以是多少。

思路:模拟着做,有点像two-pointer的做法。正着扫这个字符串,如果找到一个符合题意的即比n小的数,那么这个数是合法的,可以加上,接下来下标就移动到扫到的位置-1。主要难点我觉得在于0的时候的情况,如果当前的下标指的位置是0的话,无疑这个0是对当前的数是没有贡献的,那么这一位0应该不算上去,指针应该向后找非0的直到边界。

 1 #include <cstdio>
 2 #include <algorithm>
 3 #include <iostream>
 4 #include <cstring>
 5 #include <string>
 6 #include <cmath>
 7 #include <queue>
 8 #include <vector>
 9 #include <map>
10 #include <set>
11 #include <stack>
12 using namespace std;
13 #define INF 0x3f3f3f3f
14 #define N 100010
15 typedef long long LL;
16 char s[100];
17 
18 int main() {
19     LL base;
20     cin >> base >> s;
21     int len = strlen(s);
22     LL ans = 0, mul = 1, tmp;
23     int st, ed = len - 1;
24     while(ed >= 0) {
25         st = 0;
26         for(int i = 0; i <= ed; i++) {
27             if(ed - i > 15) continue; // 如果太大会爆LL
28             tmp = 0;
29             for(int j = i; j <= ed; j++)
30                 tmp = tmp * 10 + s[j] - '0';
31             if(tmp < base) { st = i; break; } // 找到合适的数
32         }
33         while(st < ed && s[st] == '0') st++;
34         ans = ans + mul * tmp;  mul = mul * base; ed = st - 1;
35     }
36     cout << ans << endl;
37     return 0;
38 }
39 /*
40 17
41 202016
42 */
原文地址:https://www.cnblogs.com/fightfordream/p/6322636.html