在Python中打印大字符串会花费太多时间

时间:2018-09-22 01:03:03

标签: python string python-3.x algorithm

我在Codeforce上尝试了一个问题,并在打印解决方案时陷入困境。问题链接为:-{Problem Link

Igor has fallen in love with Tanya. 
Now Igor wants to show his feelings and write a number on the fence opposite to Tanya's house. 
Igor thinks that the larger the number is, the more chance to win Tanya's heart he has.

Unfortunately, Igor could only get v liters of paint. 
He did the math and concluded that digit d requires ad liters of paint. 
Besides, Igor heard that Tanya doesn't like zeroes. That's why Igor won't use them in his number.

Help Igor find the maximum number he can write on the fence.

Input:-The first line contains a positive integer v (0 ≤ v ≤ 106). 
The second line contains nine positive integers a1, a2, ..., a9 (1 ≤ ai ≤ 105).

Output:-Print the maximum number Igor can write on the fence. 
If he has too little paint for any digit (so, he cannot write anything), print -1.

简而言之,问题是希望我们使用v作为最大成本来形成尽可能大的数字,并给我们每个数字的成本。

我的代码超出其时间限制的输入是:-

1000000
1 1 1 1 1 1 1 1 1

我的代码:-

import sys
from sys import stdin,stdout
def findbestwithin(re):
    global cost
    s=-1;m1=re
    for i in range(len(cost)):
        if cost[i]<=m1 and i>s:
            s=i
    return s

def findminnumber():
    global cost
    s=-1;m1=sys.maxsize;co=cost
    for i in range(len(co)):
        if co[i]<m1 or(co[i]==m1 and i>s):
            s=i;m1=co[i]
    return s

m=int(input())
cost=list(map(int,input().split(' ')))


if min(cost)>m:
    print(-1)
else:
    d={}#Dictionary to store count of each digit
    t1=findminnumber()#Returns the minimum number in the List.
    t2=m//cost[t1]
    t3=m%cost[t1]#Money Left
    d[t1+1]=t2
    if t3==0:#If no money is left simply print.
        for i in d:
            for j in range(d[i]):
                stdout.write(str(i))
    else:#Try to greedily maximize each digit
        getbest=findbestwithin(cost[t1]+t3)#returns the greatest posssible number that can be selected within a given value. If none can be selected returns -1.
        while getbest!=-1:
            if getbest>t1:
                t3=t3+cost[t1]-cost[getbest]
                if getbest+1 in d:
                    d[getbest+1]+=1
                else:
                    d[getbest+1]=1
                d[t1+1]-=1
            if getbest==t1:
                break
            getbest=findbestwithin(cost[t1]+t3)

        t4=list(d.keys());t4.sort();t4.reverse();
        for i in t4:
            for j in range(d[i]):
                stdout.write(str(i))

我的解决方法:-

Algorithm(Greedy??):-
(1)Select the cheapest digit and select as many copies of 
    it as possible(money//cost[cheapest_digit]).
    This will maximize number of digits.
(2)Iteratively maximize each of the digits from most 
    significant to least significant using the money left at repective steps.

失败的TestCase基本上需要打印10次“ 9” 9。

使用print()需要0.8秒。

使用stdout.write()需要0.3秒。

但是,它似乎永远无法在代码内部运行。

我没有主意,如果有人可以指出一些东西,我会很高兴。

Submission Link

0 个答案:

没有答案