Codeforces 977D Divide by three, multiply by two 题解

Codeforces 977D Divide by three, multiply by two 题解

题目在这里我就不贴出来了,大家可以去Codeforces官网查看,在洛谷上也有翻译过的题解。

这题我的思路比较简单:

主要用到了搜索

C++可以使用STL里的 binary_search()

Python可以使用 in 来判断

既然题目要求生成一个新排列,且存在一定规则。那么我们就先找出这个新排列的第一个数作为start。

start应当满足以下要求:

1、如果这个数是偶数,那么原数列中应当不存在 start/2 , 和 start*3

2、如果是奇数, 原数列中应当不存在 start*3

举个例子:

原数列 : 4 8 6 3 12 9

满足条件的只有9, 所以 start=9

好了,既然新排列的头找到了,后面按照题目的规则生成就行了

生成思路如下:

1、如果start为偶数, 分两种情况:

  1.如果 start%3==0 并且 start/3 存在于原数列,输出start/3。 更新start/=3, continue

  2.如果start*2存在于原数列,输出start*2。 更新start*=2, continue
  
2、如果start为奇数, 同上:

  1. 如果start*2存在于原数列,输出start*2。 更新start*=2, continue

  2.如果start/3 存在于原数列,输出start/3。 更新start/=3, continue

还是上述的例子: start=9

start下一个数满足条件的只有3, 更新start=3, 再去查找

3之后应该是 6 , 6之后应该是 12 , 12之后是4, 4之后是8

Python代码如下:

n=eval(input())
a=input().split()
length=n
start=0
for i in a:
    if int(i)%2 ==0:
        if not (str(eval(i)*3) in a) and not (str(eval(i)//2) in a):
            start=eval(i)
            break
    else:
        if not str(eval(i)*3) in a:
            start=eval(i)
            break
print(start, end=" ")
while length:
    length-=1
    if start%2==0:
        if start%3==0:
            x=start//3
            if(str(x) in a):
                start=x
                print(start,end=" ")
                continue
        x=start*2
        if(str(x) in a):
            print(x, end=" ")
            start=x
    else:
        x=start*2
        if str(x) in a:
            print(x, end=" ")
            start=x
            continue
        y=start//3
        if str(y) in a:
            print(y,end=" ")
            start=y
发布了17 篇原创文章 · 获赞 24 · 访问量 1933

猜你喜欢

转载自blog.csdn.net/qq_45271256/article/details/101052533