{每日一题}Google Code Jam 2012 Qualification Round - Problem C解答(python版)

Problem C: recycled numbers (官方解答戳这里)

题目背景:电视台播放节目时经常循环播放,数字对也会出现类似的情况。例如(12345, 34512)就是一对循环对,可以通过把位于‘12345’末尾的‘345’移到最前端就可以得到‘34512’. 当可以通过吧n最末尾的几位数字移到n的最前端,同时不改变数字的相对次序,从而得到m时,(n, m)为循环对。

输入文件将给出循环对搜索范围AB,找到[A, B]范围内不重复的循环对个数

解题思路:我采用的是将数字转为字符串,对字符串进行移位操作得到movedNum,然后查看movedNum是否在[A, B]的范围之内的方法,很暴力很低效的一种方法。能够通过small dataset的测试,但是效率过低,无法通过large dataset的时间要求。

def recycledPair(A, B):
    result = 0
    if B<10:
        return result
    else:
        # cat = {}
        for i in range(A, B+1):
            digits = str(i)
            movStr = digits[0]
            while(len(movStr)<len(digits)):
                movedNum = (int)(digits[len(movStr):]+movStr)
                if i == movedNum:
                    break
                if i < movedNum and movedNum>=A and movedNum<=B:
                    print(digits, movedNum)
                    result = result + 1
                movStr = movStr+digits[len(movStr)]
        return result

if __name__=="__main__":
    iFile = open("G:/usaco/C-small-practice.in", 'r')
    oFile = open("G:/usaco/C-small.out", 'w')
    caseNum = (int)(iFile.readline())
    print(caseNum)
    for i in range(0, caseNum):
        result = 0
        out = "Case #"+str(i+1)+": "
        text = iFile.readline().strip('\n').strip('\r')
        text = text.split(" ")
        A = (int)(text[0])
        B = (int)(text[1])
        # print(A, B)
        # find the number of pairs (n, m)
        result = recycledPair(A, B)
        out = out+str(result)+'\n'
        print(out)
        oFile.write(out)
    iFile.close()
    oFile.close()

官网的solution给出了通过计算而非字符串操作得到经过shift后的数字的版本(c/c++)

int solve(int A, int B) {
    int power = 1, temp = A;
    while (temp >= 10) {
        power *= 10;
        temp /= 10;
    }
  // power 为A的数量级
int ret = 0; for (int n = A; n <= B; ++n) { temp = n; while (true) { temp = (temp / 10) + ((temp % 10) * power); // 得到移位后的值 if (temp == n) // 移位有循环性 break; if (temp > n && temp >= A && temp <= B) ret++; } } return ret; }

附Problem C原题描述:

Do you ever become frustrated with television because you keep seeing the same things, recycled over and over again? Well I personally don't care about television, but I do sometimes feel that way about numbers.

Let's say a pair of distinct positive integers (n, m) is recycled if you can obtain m by moving some digits from the back of n to the front without changing their order. For example, (12345, 34512) is a recycled pair since you can obtain 34512 by moving 345 from the end of 12345 to the front. Note that n and m must have the same number of digits in order to be a recycled pair. Neither n nor m can have leading zeros.

Given integers A and B with the same number of digits and no leading zeros, how many distinct recycled pairs (n, m) are there with An < mB?

posted @ 2012-04-15 12:14  Apprentice.Z  阅读(502)  评论(0编辑  收藏  举报