ZOJ-1177-K-Magic Number

就是分别以1到9作为开头构造结果,取最小答案。看了参考书之后才做出来,对参考书上的代码进行了一些改进

Accepted 1177 C++11 0 408
#include "bits/stdc++.h"
using namespace std;
// 参考书上说经在线测试ans的位数最高在15000以内,所以MAXL定为15000
const int MAXL = 15000;
int num[MAXL], ans[MAXL], ansLen;
void saveSmaller(int len) {
    for (int i = len; i > 0; i--) {
        ans[i] = num[i];
    }
    ansLen = len;
}
void build(int k) {
    int carry = 0, pos = 0;
    // 进入循环我们要构造第pos + 1位,当pos + 1 == ansLen的时候num[pos] 一定大于 ans[pos]就算构造成功也会比ans大 
    while (pos < ansLen - 1) {
        carry += num[pos] * k;
        num[++pos] = carry % 10;
        carry /= 10;
        // 当构造成功并且num的长度小于ans的时候说明num < ans,更新ans 
        if (carry == 0 && num[pos] == num[0]) {
            saveSmaller(pos);
            return;
        }
    }
}
int main() {
    int t, n;
    scanf("%d", &t);
    while (t--) {
        scanf("%d", &n);
        ansLen = MAXL;
        // 一个数开头不能是0,所以从1到9构造结果,并选取最小的作为答案 
        for (int i = 1; i <= 9; i++) {
            num[0] = i;
            build(n);
        }
        for (int i = ansLen; i; i--) {
            printf("%d", ans[i]);
        }
        puts(""); 
        if (t != 0) {
            puts("");
        }
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/Angel-Demon/p/10339785.html