1 Star 1 Fork 0

bensonrachel/Atcoder_algorithm

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
TPM(step2)G. Coprime Segment(单调栈).py 2.00 KB
一键复制 编辑 原始数据 按行查看 历史
bensonrachel 提交于 2021-09-06 14:54 +08:00 . G. Coprime Segment(单调栈的做法)
# -*- coding: utf-8 -*-
# @project : 《Atcoder》
# @Author : created by bensonrachel on 2021/9/6
# @File : TPM(step2)G. Coprime Segment(单调栈).py
from collections import deque
from math import gcd
import sys
MAX_INT = sys.maxsize
class stk:
def __init__(self):
"""
Initialize your data structure here.
"""
self.que = deque()
self.gcd_dp = deque()
self.gcd_dp.append(0)
def push(self, x: int) -> None:
"""
Push element x to the back of queue.
每次做一次GCD即可
"""
self.que.append(x)
temp = self.gcd_dp[-1]
self.gcd_dp.append(gcd(temp,x))
def pop(self) -> None:
"""
Removes the element from in front of queue and returns that element.
"""
tmp = self.que.pop()
tmp2 = self.gcd_dp.pop()
def peek(self) -> int:
"""
Get the front element.
"""
return self.que[-1]
def empty(self) -> bool:
"""
Returns whether the queue is empty.
"""
return not self.que
def get(self) -> int:
"""
"""
return self.gcd_dp[-1]
def query(s1,s2):
"""
:param s1:
:param s2:
:return: 一个区间的gcd等于这个区间分成前后两部分的gcd的结果再做一次gcd
"""
dp1 = s1.get()
dp2 = s2.get()
return gcd(dp1,dp2) == 1
def remove(s1,s2):
if(s1.empty()):
while(not s2.empty()):
s1.push(s2.peek())
s2.pop()
s1.pop()
def TPM():
s1 = stk()
s2 = stk()
l = 0
res = MAX_INT
for r in range(n):
s2.push(a[r])
while(l <= r and query(s1,s2)):#这里也while(query(l,r)>k):,l=r时有可能这个数就是1,不同于st表的方法。
res = min(res,r-l+1)
remove(s1,s2)
l += 1
if(res > n):
res = -1
return res
if __name__ == '__main__':
n = int(input())
a = [int(i) for i in input().split()]
ans = TPM()
print(ans)
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/bensonrachel/atcoder_algorithm.git
git@gitee.com:bensonrachel/atcoder_algorithm.git
bensonrachel
atcoder_algorithm
Atcoder_algorithm
master

搜索帮助