判断一个给定字符序列在可以由该序列字符组成的所有序列里按Lexical

题目:

Given a permutation which may contain repeated numbers, find its index in all the permutations of these numbers, which are ordered in lexicographical order. The index begins at 1.

Example

Given the permutation [1, 4, 2, 2], return 3.

注意index可能会超过int的表示范围。

def get_ranks(words):
    cc = {}
    def inv(a, n):
        t, nt = 0, 1
        r, nr = n, a
        while nr != 0:
            q = r / nr
            t, nt = nt, t - q * nt
            r, nr = nr, r - q * nr
        if t < 0: t += n
        return t

    def fact(n, M):
        if n == 1: return 1
        if n not in cc:
            cc[n] = (fact(n - 1, M) * n) % M
        return cc[n]

    def perm(w):
        M = int(1e9+7)
        n = len(w)
        w = sorted(w)
        x = fact(n, M)
        y = 1
        xs = [0] + filter(lambda i:w[i] != w[i - 1], range(1, n)) + [n]
        for i in xrange(1, len(xs)):
            y = (y * fact(xs[i] - xs[i - 1], M)) % M
        return (x * inv(y, M)) % M

    def cnt(w):
        t = 0
        x, rest = w[0], w[1:]
        v = set()
        for i in xrange(len(rest)):
            c = rest[i]
            if c < x and not c in v:
                v.add(c)
                t = (t + perm(rest[:i] + x + rest[i+1:])) % int(1e9+7)
        return t

    ret = []
    for word in words:
        c = 0
        n = len(word)
        for i in xrange(n - 1):
            c = (c + cnt(word[i:])) % int(1e9+7)
        ret.append(c)

    return ret

def get_rank(words):
    ret = []
    for i in range(len(words)):
        cur = words[i]
        hashmap = {}
        index, fact, divident = 0, 1, 1
        for j in range(len(cur) - 1, -1, -1):
            if cur[j] in hashmap:
                hashmap[cur[j]] += 1
                divident = (divident * hashmap[cur[j]])
            else:
                hashmap[cur[j]] = 1
            rank = 0
            for k in range(j + 1, len(cur)):
                if ord(cur[j]) > ord(cur[k]):
                    rank += 1
            #index += (rank * fact % int(1e9+7) / divident)
            index += (rank * fact / divident)
            fact *= len(cur) - j
        ret.append(index % int(1e9+7))
    return ret

def main():
    #f = open(os.environ['OUTPUT_PATH'], 'w')

    _words_cnt = int(raw_input())
    _words_i = 0
    _words = []

    while _words_i < _words_cnt:
        _words_item = raw_input()
        _words.append(_words_item)
        _words_i += 1

    res = get_ranks(_words)
    print res

    res2 = get_rank(_words)
    print res2


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值