output_description stringlengths 15 956 | submission_id stringlengths 10 10 | status stringclasses 3 values | problem_id stringlengths 6 6 | input_description stringlengths 9 2.55k | attempt stringlengths 1 13.7k | problem_description stringlengths 7 5.24k | samples stringlengths 2 2.72k |
|---|---|---|---|---|---|---|---|
Print the string putting a single space between the first 4 letters and last 8
letters in the string s. Put a line break at the end.
* * * | s470332704 | Accepted | p03992 | The input is given from Standard Input in the following format:
s | hoge = input()
print(hoge[0:4], hoge[4:])
| Statement
This contest is `CODE FESTIVAL`. However, Mr. Takahashi always writes it
`CODEFESTIVAL`, omitting the single space between `CODE` and `FESTIVAL`.
So he has decided to make a program that puts the single space he omitted.
You are given a string s with 12 letters. Output the string putting a single
space between the first 4 letters and last 8 letters in the string s. | [{"input": "CODEFESTIVAL", "output": "CODE FESTIVAL\n \n\nPutting a single space between the first 4 letters and last 8 letters in\n`CODEFESTIVAL` makes it `CODE FESTIVAL`.\n\n* * *"}, {"input": "POSTGRADUATE", "output": "POST GRADUATE\n \n\n* * *"}, {"input": "ABCDEFGHIJKL", "output": "ABCD EFGHIJKL"}] |
Print the string putting a single space between the first 4 letters and last 8
letters in the string s. Put a line break at the end.
* * * | s272586094 | Accepted | p03992 | The input is given from Standard Input in the following format:
s | # A-Codefestival 2016
str = input()
str1 = str[:4] + " " + str[4:]
print(str1)
| Statement
This contest is `CODE FESTIVAL`. However, Mr. Takahashi always writes it
`CODEFESTIVAL`, omitting the single space between `CODE` and `FESTIVAL`.
So he has decided to make a program that puts the single space he omitted.
You are given a string s with 12 letters. Output the string putting a single
space between the first 4 letters and last 8 letters in the string s. | [{"input": "CODEFESTIVAL", "output": "CODE FESTIVAL\n \n\nPutting a single space between the first 4 letters and last 8 letters in\n`CODEFESTIVAL` makes it `CODE FESTIVAL`.\n\n* * *"}, {"input": "POSTGRADUATE", "output": "POST GRADUATE\n \n\n* * *"}, {"input": "ABCDEFGHIJKL", "output": "ABCD EFGHIJKL"}] |
Print the string putting a single space between the first 4 letters and last 8
letters in the string s. Put a line break at the end.
* * * | s345973278 | Accepted | p03992 | The input is given from Standard Input in the following format:
s | l = input().strip()
print(l[:4] + " " + l[4:])
| Statement
This contest is `CODE FESTIVAL`. However, Mr. Takahashi always writes it
`CODEFESTIVAL`, omitting the single space between `CODE` and `FESTIVAL`.
So he has decided to make a program that puts the single space he omitted.
You are given a string s with 12 letters. Output the string putting a single
space between the first 4 letters and last 8 letters in the string s. | [{"input": "CODEFESTIVAL", "output": "CODE FESTIVAL\n \n\nPutting a single space between the first 4 letters and last 8 letters in\n`CODEFESTIVAL` makes it `CODE FESTIVAL`.\n\n* * *"}, {"input": "POSTGRADUATE", "output": "POST GRADUATE\n \n\n* * *"}, {"input": "ABCDEFGHIJKL", "output": "ABCD EFGHIJKL"}] |
Print the string putting a single space between the first 4 letters and last 8
letters in the string s. Put a line break at the end.
* * * | s870642135 | Runtime Error | p03992 | The input is given from Standard Input in the following format:
s | s = input()
sega = s[0:4]
segb = s[4:12]
print(sega + “ “ + segb) | Statement
This contest is `CODE FESTIVAL`. However, Mr. Takahashi always writes it
`CODEFESTIVAL`, omitting the single space between `CODE` and `FESTIVAL`.
So he has decided to make a program that puts the single space he omitted.
You are given a string s with 12 letters. Output the string putting a single
space between the first 4 letters and last 8 letters in the string s. | [{"input": "CODEFESTIVAL", "output": "CODE FESTIVAL\n \n\nPutting a single space between the first 4 letters and last 8 letters in\n`CODEFESTIVAL` makes it `CODE FESTIVAL`.\n\n* * *"}, {"input": "POSTGRADUATE", "output": "POST GRADUATE\n \n\n* * *"}, {"input": "ABCDEFGHIJKL", "output": "ABCD EFGHIJKL"}] |
Print the string putting a single space between the first 4 letters and last 8
letters in the string s. Put a line break at the end.
* * * | s882128022 | Runtime Error | p03992 | The input is given from Standard Input in the following format:
s | s = input
ss = s[0:3] + " " + s[4:]
print(ss)
| Statement
This contest is `CODE FESTIVAL`. However, Mr. Takahashi always writes it
`CODEFESTIVAL`, omitting the single space between `CODE` and `FESTIVAL`.
So he has decided to make a program that puts the single space he omitted.
You are given a string s with 12 letters. Output the string putting a single
space between the first 4 letters and last 8 letters in the string s. | [{"input": "CODEFESTIVAL", "output": "CODE FESTIVAL\n \n\nPutting a single space between the first 4 letters and last 8 letters in\n`CODEFESTIVAL` makes it `CODE FESTIVAL`.\n\n* * *"}, {"input": "POSTGRADUATE", "output": "POST GRADUATE\n \n\n* * *"}, {"input": "ABCDEFGHIJKL", "output": "ABCD EFGHIJKL"}] |
Print the string putting a single space between the first 4 letters and last 8
letters in the string s. Put a line break at the end.
* * * | s473919987 | Accepted | p03992 | The input is given from Standard Input in the following format:
s | in_str = input()
out_str = []
k = 0
for c in in_str:
if k == 4:
out_str.append(" ")
out_str.append(c)
k += 1
print("".join(out_str))
| Statement
This contest is `CODE FESTIVAL`. However, Mr. Takahashi always writes it
`CODEFESTIVAL`, omitting the single space between `CODE` and `FESTIVAL`.
So he has decided to make a program that puts the single space he omitted.
You are given a string s with 12 letters. Output the string putting a single
space between the first 4 letters and last 8 letters in the string s. | [{"input": "CODEFESTIVAL", "output": "CODE FESTIVAL\n \n\nPutting a single space between the first 4 letters and last 8 letters in\n`CODEFESTIVAL` makes it `CODE FESTIVAL`.\n\n* * *"}, {"input": "POSTGRADUATE", "output": "POST GRADUATE\n \n\n* * *"}, {"input": "ABCDEFGHIJKL", "output": "ABCD EFGHIJKL"}] |
Print the string putting a single space between the first 4 letters and last 8
letters in the string s. Put a line break at the end.
* * * | s241998460 | Accepted | p03992 | The input is given from Standard Input in the following format:
s | line = list(input())
line.insert(4, " ")
final = "".join(line)
print(final)
| Statement
This contest is `CODE FESTIVAL`. However, Mr. Takahashi always writes it
`CODEFESTIVAL`, omitting the single space between `CODE` and `FESTIVAL`.
So he has decided to make a program that puts the single space he omitted.
You are given a string s with 12 letters. Output the string putting a single
space between the first 4 letters and last 8 letters in the string s. | [{"input": "CODEFESTIVAL", "output": "CODE FESTIVAL\n \n\nPutting a single space between the first 4 letters and last 8 letters in\n`CODEFESTIVAL` makes it `CODE FESTIVAL`.\n\n* * *"}, {"input": "POSTGRADUATE", "output": "POST GRADUATE\n \n\n* * *"}, {"input": "ABCDEFGHIJKL", "output": "ABCD EFGHIJKL"}] |
Print the string putting a single space between the first 4 letters and last 8
letters in the string s. Put a line break at the end.
* * * | s361706323 | Runtime Error | p03992 | The input is given from Standard Input in the following format:
s | size = int(input())
rabbit_list = input().split()
rabbits = [int(x) for x in rabbit_list]
count = 0
for i in range(size):
if (rabbits[i] - 1) > i and (rabbits[rabbits[i] - 1] - 1) == i:
count += 1
if count > 0:
print(count)
| Statement
This contest is `CODE FESTIVAL`. However, Mr. Takahashi always writes it
`CODEFESTIVAL`, omitting the single space between `CODE` and `FESTIVAL`.
So he has decided to make a program that puts the single space he omitted.
You are given a string s with 12 letters. Output the string putting a single
space between the first 4 letters and last 8 letters in the string s. | [{"input": "CODEFESTIVAL", "output": "CODE FESTIVAL\n \n\nPutting a single space between the first 4 letters and last 8 letters in\n`CODEFESTIVAL` makes it `CODE FESTIVAL`.\n\n* * *"}, {"input": "POSTGRADUATE", "output": "POST GRADUATE\n \n\n* * *"}, {"input": "ABCDEFGHIJKL", "output": "ABCD EFGHIJKL"}] |
Print the string putting a single space between the first 4 letters and last 8
letters in the string s. Put a line break at the end.
* * * | s316313504 | Runtime Error | p03992 | The input is given from Standard Input in the following format:
s | if __name__ == "__main__":
S="CODEFESTIVAL"
print (S[:4].upper() + " " + S[4:].upper())
S="POSTGRADUATE"
print (S[:4].upper() + " " + S[4:].upper())
S="ABCDEFGHIJKL"
print (S[:4].upper() + " " + S[4:].upper())
| Statement
This contest is `CODE FESTIVAL`. However, Mr. Takahashi always writes it
`CODEFESTIVAL`, omitting the single space between `CODE` and `FESTIVAL`.
So he has decided to make a program that puts the single space he omitted.
You are given a string s with 12 letters. Output the string putting a single
space between the first 4 letters and last 8 letters in the string s. | [{"input": "CODEFESTIVAL", "output": "CODE FESTIVAL\n \n\nPutting a single space between the first 4 letters and last 8 letters in\n`CODEFESTIVAL` makes it `CODE FESTIVAL`.\n\n* * *"}, {"input": "POSTGRADUATE", "output": "POST GRADUATE\n \n\n* * *"}, {"input": "ABCDEFGHIJKL", "output": "ABCD EFGHIJKL"}] |
Print the string putting a single space between the first 4 letters and last 8
letters in the string s. Put a line break at the end.
* * * | s579129116 | Runtime Error | p03992 | The input is given from Standard Input in the following format:
s | n = int(input())
a = input().split(" ")
t = 0
for o in range(n):
i = o + 1
b = int(a[o]) - i
if i == int(a[o + b]):
t += 1
print(int(t / 2))
| Statement
This contest is `CODE FESTIVAL`. However, Mr. Takahashi always writes it
`CODEFESTIVAL`, omitting the single space between `CODE` and `FESTIVAL`.
So he has decided to make a program that puts the single space he omitted.
You are given a string s with 12 letters. Output the string putting a single
space between the first 4 letters and last 8 letters in the string s. | [{"input": "CODEFESTIVAL", "output": "CODE FESTIVAL\n \n\nPutting a single space between the first 4 letters and last 8 letters in\n`CODEFESTIVAL` makes it `CODE FESTIVAL`.\n\n* * *"}, {"input": "POSTGRADUATE", "output": "POST GRADUATE\n \n\n* * *"}, {"input": "ABCDEFGHIJKL", "output": "ABCD EFGHIJKL"}] |
Print the string putting a single space between the first 4 letters and last 8
letters in the string s. Put a line break at the end.
* * * | s020576327 | Runtime Error | p03992 | The input is given from Standard Input in the following format:
s | s = input()
print("{} {}".format(s[:4], s[4:]) | Statement
This contest is `CODE FESTIVAL`. However, Mr. Takahashi always writes it
`CODEFESTIVAL`, omitting the single space between `CODE` and `FESTIVAL`.
So he has decided to make a program that puts the single space he omitted.
You are given a string s with 12 letters. Output the string putting a single
space between the first 4 letters and last 8 letters in the string s. | [{"input": "CODEFESTIVAL", "output": "CODE FESTIVAL\n \n\nPutting a single space between the first 4 letters and last 8 letters in\n`CODEFESTIVAL` makes it `CODE FESTIVAL`.\n\n* * *"}, {"input": "POSTGRADUATE", "output": "POST GRADUATE\n \n\n* * *"}, {"input": "ABCDEFGHIJKL", "output": "ABCD EFGHIJKL"}] |
Print the string putting a single space between the first 4 letters and last 8
letters in the string s. Put a line break at the end.
* * * | s527972624 | Runtime Error | p03992 | The input is given from Standard Input in the following format:
s | `r`````````````````. ````````@|@|@|@|@|@|@|@|@|@|@|@|i | Statement
This contest is `CODE FESTIVAL`. However, Mr. Takahashi always writes it
`CODEFESTIVAL`, omitting the single space between `CODE` and `FESTIVAL`.
So he has decided to make a program that puts the single space he omitted.
You are given a string s with 12 letters. Output the string putting a single
space between the first 4 letters and last 8 letters in the string s. | [{"input": "CODEFESTIVAL", "output": "CODE FESTIVAL\n \n\nPutting a single space between the first 4 letters and last 8 letters in\n`CODEFESTIVAL` makes it `CODE FESTIVAL`.\n\n* * *"}, {"input": "POSTGRADUATE", "output": "POST GRADUATE\n \n\n* * *"}, {"input": "ABCDEFGHIJKL", "output": "ABCD EFGHIJKL"}] |
Print the string putting a single space between the first 4 letters and last 8
letters in the string s. Put a line break at the end.
* * * | s903709071 | Runtime Error | p03992 | The input is given from Standard Input in the following format:
s | s = list(input())
print("".join(s[:4] + [" "] + s[4:]) | Statement
This contest is `CODE FESTIVAL`. However, Mr. Takahashi always writes it
`CODEFESTIVAL`, omitting the single space between `CODE` and `FESTIVAL`.
So he has decided to make a program that puts the single space he omitted.
You are given a string s with 12 letters. Output the string putting a single
space between the first 4 letters and last 8 letters in the string s. | [{"input": "CODEFESTIVAL", "output": "CODE FESTIVAL\n \n\nPutting a single space between the first 4 letters and last 8 letters in\n`CODEFESTIVAL` makes it `CODE FESTIVAL`.\n\n* * *"}, {"input": "POSTGRADUATE", "output": "POST GRADUATE\n \n\n* * *"}, {"input": "ABCDEFGHIJKL", "output": "ABCD EFGHIJKL"}] |
Print the string putting a single space between the first 4 letters and last 8
letters in the string s. Put a line break at the end.
* * * | s826224940 | Accepted | p03992 | The input is given from Standard Input in the following format:
s | #!/usr/bin/env python3
from collections import defaultdict, deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI():
return list(map(int, input().split()))
def LF():
return list(map(float, input().split()))
def LI_():
return list(map(lambda x: int(x) - 1, input().split()))
def II():
return int(input())
def IF():
return float(input())
def S():
return input().rstrip()
def LS():
return S().split()
def IR(n):
return [II() for _ in range(n)]
def LIR(n):
return [LI() for _ in range(n)]
def FR(n):
return [IF() for _ in range(n)]
def LFR(n):
return [LI() for _ in range(n)]
def LIR_(n):
return [LI_() for _ in range(n)]
def SR(n):
return [S() for _ in range(n)]
def LSR(n):
return [LS() for _ in range(n)]
mod = 1000000007
inf = 1e10
# solve
def solve():
s = S()
print(s[:4], s[4:])
return
# main
if __name__ == "__main__":
solve()
| Statement
This contest is `CODE FESTIVAL`. However, Mr. Takahashi always writes it
`CODEFESTIVAL`, omitting the single space between `CODE` and `FESTIVAL`.
So he has decided to make a program that puts the single space he omitted.
You are given a string s with 12 letters. Output the string putting a single
space between the first 4 letters and last 8 letters in the string s. | [{"input": "CODEFESTIVAL", "output": "CODE FESTIVAL\n \n\nPutting a single space between the first 4 letters and last 8 letters in\n`CODEFESTIVAL` makes it `CODE FESTIVAL`.\n\n* * *"}, {"input": "POSTGRADUATE", "output": "POST GRADUATE\n \n\n* * *"}, {"input": "ABCDEFGHIJKL", "output": "ABCD EFGHIJKL"}] |
Print the string putting a single space between the first 4 letters and last 8
letters in the string s. Put a line break at the end.
* * * | s849759065 | Accepted | p03992 | The input is given from Standard Input in the following format:
s | import sys, math, collections
from collections import defaultdict
# from itertools import permutations,combinations
def file():
sys.stdin = open("input.py", "r")
sys.stdout = open("output.py", "w")
def get_array():
l = list(map(int, input().split()))
return l
def get_ints():
return map(int, input().split())
# return a,b
def get_3_ints():
a, b, c = map(int, input().split())
return a, b, c
def sod(n):
n, c = str(n), 0
for i in n:
c += int(i)
return c
def isPrime(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i = i + 6
return True
def getFloor(A, x):
(left, right) = (0, len(A) - 1)
floor = -1
while left <= right:
mid = (left + right) // 2
if A[mid] == x:
return A[mid]
elif x < A[mid]:
right = mid - 1
else:
floor = A[mid]
left = mid + 1
return floor
def chk(aa, bb):
f = 0
for i in aa:
for j in bb:
if j[0] >= i[0] and j[1] <= i[1]:
f += 1
elif j[0] <= i[0] and j[1] >= i[1]:
f += 1
elif i[0] == j[1] or i[1] == j[0]:
f += 1
else:
continue
return f
# file()
def main():
s = input()
print(s[:4] + " " + s[4:])
if __name__ == "__main__":
main()
| Statement
This contest is `CODE FESTIVAL`. However, Mr. Takahashi always writes it
`CODEFESTIVAL`, omitting the single space between `CODE` and `FESTIVAL`.
So he has decided to make a program that puts the single space he omitted.
You are given a string s with 12 letters. Output the string putting a single
space between the first 4 letters and last 8 letters in the string s. | [{"input": "CODEFESTIVAL", "output": "CODE FESTIVAL\n \n\nPutting a single space between the first 4 letters and last 8 letters in\n`CODEFESTIVAL` makes it `CODE FESTIVAL`.\n\n* * *"}, {"input": "POSTGRADUATE", "output": "POST GRADUATE\n \n\n* * *"}, {"input": "ABCDEFGHIJKL", "output": "ABCD EFGHIJKL"}] |
Print the string putting a single space between the first 4 letters and last 8
letters in the string s. Put a line break at the end.
* * * | s866285269 | Accepted | p03992 | The input is given from Standard Input in the following format:
s | import math
import queue
import bisect
import heapq
import time
import itertools
mod = int(1e9 + 7)
def swap(a, b):
return (b, a)
def my_round(a, dig=0):
p = 10**dig
return (a * p * 2 + 1) // 2 / p
def gcd(a, b): # 最大公約数
if a < b:
a, b = swap(a, b)
if b == 0:
return a
else:
return gcd(b, a % b)
def lcm(a, b): # 最小公倍数
return a / gcd(a, b) * b
def divisors(a): # 約数列挙
divisors = []
for i in range(1, int(a**0.5) + 1):
if a % i == 0:
divisors.append(i)
if i != a // i:
divisors.append(a // i)
return divisors
def is_prime(a): # 素数判定
if a < 2:
return False
elif a == 2:
return True
elif a % 2 == 0:
return False
sqrt_num = int(a**0.5)
for i in range(3, sqrt_num + 1, 2):
if a % i == 0:
return False
return True
def prime_num(a): # 素数列挙
pn = [2]
for i in range(3, int(a**0.5), 2):
prime = True
for j in pn:
if i % j == 0:
prime = False
break
if prime:
pn.append(i)
return pn
def prime_fact(a): # 素因数分解
sqrt = math.sqrt(a)
res = []
i = 2
if is_prime(a):
res.append(a)
else:
while a != 1:
while a % i == 0:
res.append(i)
a //= i
i += 1
return res
def main():
s = input()
ans = []
ans.append(s[0:4])
ans.append(" ")
ans.append(s[4:12])
print("".join(ans))
return
if __name__ == "__main__":
main()
| Statement
This contest is `CODE FESTIVAL`. However, Mr. Takahashi always writes it
`CODEFESTIVAL`, omitting the single space between `CODE` and `FESTIVAL`.
So he has decided to make a program that puts the single space he omitted.
You are given a string s with 12 letters. Output the string putting a single
space between the first 4 letters and last 8 letters in the string s. | [{"input": "CODEFESTIVAL", "output": "CODE FESTIVAL\n \n\nPutting a single space between the first 4 letters and last 8 letters in\n`CODEFESTIVAL` makes it `CODE FESTIVAL`.\n\n* * *"}, {"input": "POSTGRADUATE", "output": "POST GRADUATE\n \n\n* * *"}, {"input": "ABCDEFGHIJKL", "output": "ABCD EFGHIJKL"}] |
Print the string putting a single space between the first 4 letters and last 8
letters in the string s. Put a line break at the end.
* * * | s183485351 | Wrong Answer | p03992 | The input is given from Standard Input in the following format:
s | # -*- coding: utf-8 -*-
# !/usr/bin/env python
# vim: set fileencoding=utf-8 :
"""
#
# Author: Noname
# URL: https://github.com/pettan0818
# License: MIT License
# Created: 2016-09-28
#
# Usage
#
"""
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
def input_process():
"""Receive Inputs."""
return input()
def insert_space(target_str: str) -> str:
"""
>>> insert_space("codefestival")
code festival
"""
return target_str[0:3] + " " + target_str[3:]
if __name__ == "__main__":
target = input()
print(insert_space(target))
| Statement
This contest is `CODE FESTIVAL`. However, Mr. Takahashi always writes it
`CODEFESTIVAL`, omitting the single space between `CODE` and `FESTIVAL`.
So he has decided to make a program that puts the single space he omitted.
You are given a string s with 12 letters. Output the string putting a single
space between the first 4 letters and last 8 letters in the string s. | [{"input": "CODEFESTIVAL", "output": "CODE FESTIVAL\n \n\nPutting a single space between the first 4 letters and last 8 letters in\n`CODEFESTIVAL` makes it `CODE FESTIVAL`.\n\n* * *"}, {"input": "POSTGRADUATE", "output": "POST GRADUATE\n \n\n* * *"}, {"input": "ABCDEFGHIJKL", "output": "ABCD EFGHIJKL"}] |
Print the string putting a single space between the first 4 letters and last 8
letters in the string s. Put a line break at the end.
* * * | s605202397 | Accepted | p03992 | The input is given from Standard Input in the following format:
s | s = [i for i in input()]
print("".join(s[:4]) + " " + "".join(s[4:]))
| Statement
This contest is `CODE FESTIVAL`. However, Mr. Takahashi always writes it
`CODEFESTIVAL`, omitting the single space between `CODE` and `FESTIVAL`.
So he has decided to make a program that puts the single space he omitted.
You are given a string s with 12 letters. Output the string putting a single
space between the first 4 letters and last 8 letters in the string s. | [{"input": "CODEFESTIVAL", "output": "CODE FESTIVAL\n \n\nPutting a single space between the first 4 letters and last 8 letters in\n`CODEFESTIVAL` makes it `CODE FESTIVAL`.\n\n* * *"}, {"input": "POSTGRADUATE", "output": "POST GRADUATE\n \n\n* * *"}, {"input": "ABCDEFGHIJKL", "output": "ABCD EFGHIJKL"}] |
Print the string putting a single space between the first 4 letters and last 8
letters in the string s. Put a line break at the end.
* * * | s199415118 | Wrong Answer | p03992 | The input is given from Standard Input in the following format:
s | text = input()
text2 = text[:4] + " " + "text[4:]"
print(text2)
| Statement
This contest is `CODE FESTIVAL`. However, Mr. Takahashi always writes it
`CODEFESTIVAL`, omitting the single space between `CODE` and `FESTIVAL`.
So he has decided to make a program that puts the single space he omitted.
You are given a string s with 12 letters. Output the string putting a single
space between the first 4 letters and last 8 letters in the string s. | [{"input": "CODEFESTIVAL", "output": "CODE FESTIVAL\n \n\nPutting a single space between the first 4 letters and last 8 letters in\n`CODEFESTIVAL` makes it `CODE FESTIVAL`.\n\n* * *"}, {"input": "POSTGRADUATE", "output": "POST GRADUATE\n \n\n* * *"}, {"input": "ABCDEFGHIJKL", "output": "ABCD EFGHIJKL"}] |
Print the string putting a single space between the first 4 letters and last 8
letters in the string s. Put a line break at the end.
* * * | s160708745 | Runtime Error | p03992 | The input is given from Standard Input in the following format:
s | s=list(input())
print(''.join(s[0:4]+' '+''.join(s[4:]) | Statement
This contest is `CODE FESTIVAL`. However, Mr. Takahashi always writes it
`CODEFESTIVAL`, omitting the single space between `CODE` and `FESTIVAL`.
So he has decided to make a program that puts the single space he omitted.
You are given a string s with 12 letters. Output the string putting a single
space between the first 4 letters and last 8 letters in the string s. | [{"input": "CODEFESTIVAL", "output": "CODE FESTIVAL\n \n\nPutting a single space between the first 4 letters and last 8 letters in\n`CODEFESTIVAL` makes it `CODE FESTIVAL`.\n\n* * *"}, {"input": "POSTGRADUATE", "output": "POST GRADUATE\n \n\n* * *"}, {"input": "ABCDEFGHIJKL", "output": "ABCD EFGHIJKL"}] |
Print the string putting a single space between the first 4 letters and last 8
letters in the string s. Put a line break at the end.
* * * | s071520502 | Accepted | p03992 | The input is given from Standard Input in the following format:
s | N = input()
print(N[0:4] + " " + N[4:16])
| Statement
This contest is `CODE FESTIVAL`. However, Mr. Takahashi always writes it
`CODEFESTIVAL`, omitting the single space between `CODE` and `FESTIVAL`.
So he has decided to make a program that puts the single space he omitted.
You are given a string s with 12 letters. Output the string putting a single
space between the first 4 letters and last 8 letters in the string s. | [{"input": "CODEFESTIVAL", "output": "CODE FESTIVAL\n \n\nPutting a single space between the first 4 letters and last 8 letters in\n`CODEFESTIVAL` makes it `CODE FESTIVAL`.\n\n* * *"}, {"input": "POSTGRADUATE", "output": "POST GRADUATE\n \n\n* * *"}, {"input": "ABCDEFGHIJKL", "output": "ABCD EFGHIJKL"}] |
Print the string putting a single space between the first 4 letters and last 8
letters in the string s. Put a line break at the end.
* * * | s030212913 | Runtime Error | p03992 | The input is given from Standard Input in the following format:
s | s=gets.chomp
puts s[0,4]+' '+s[4,8] | Statement
This contest is `CODE FESTIVAL`. However, Mr. Takahashi always writes it
`CODEFESTIVAL`, omitting the single space between `CODE` and `FESTIVAL`.
So he has decided to make a program that puts the single space he omitted.
You are given a string s with 12 letters. Output the string putting a single
space between the first 4 letters and last 8 letters in the string s. | [{"input": "CODEFESTIVAL", "output": "CODE FESTIVAL\n \n\nPutting a single space between the first 4 letters and last 8 letters in\n`CODEFESTIVAL` makes it `CODE FESTIVAL`.\n\n* * *"}, {"input": "POSTGRADUATE", "output": "POST GRADUATE\n \n\n* * *"}, {"input": "ABCDEFGHIJKL", "output": "ABCD EFGHIJKL"}] |
Print the string putting a single space between the first 4 letters and last 8
letters in the string s. Put a line break at the end.
* * * | s481054465 | Runtime Error | p03992 | The input is given from Standard Input in the following format:
s | s = input()
print(s[:4]+' '+s[4:] | Statement
This contest is `CODE FESTIVAL`. However, Mr. Takahashi always writes it
`CODEFESTIVAL`, omitting the single space between `CODE` and `FESTIVAL`.
So he has decided to make a program that puts the single space he omitted.
You are given a string s with 12 letters. Output the string putting a single
space between the first 4 letters and last 8 letters in the string s. | [{"input": "CODEFESTIVAL", "output": "CODE FESTIVAL\n \n\nPutting a single space between the first 4 letters and last 8 letters in\n`CODEFESTIVAL` makes it `CODE FESTIVAL`.\n\n* * *"}, {"input": "POSTGRADUATE", "output": "POST GRADUATE\n \n\n* * *"}, {"input": "ABCDEFGHIJKL", "output": "ABCD EFGHIJKL"}] |
Print the string putting a single space between the first 4 letters and last 8
letters in the string s. Put a line break at the end.
* * * | s660315587 | Accepted | p03992 | The input is given from Standard Input in the following format:
s | import math
import sys
def getinputdata():
# 配列初期化
array_result = []
data = input()
array_result.append(data.split(" "))
flg = 1
try:
while flg:
data = input()
array_temp = []
if data != "":
array_result.append(data.split(" "))
flg = 1
else:
flg = 0
finally:
return array_result
arr_data = getinputdata()
s = arr_data[0][0]
print(s[0:4] + " " + s[4:])
| Statement
This contest is `CODE FESTIVAL`. However, Mr. Takahashi always writes it
`CODEFESTIVAL`, omitting the single space between `CODE` and `FESTIVAL`.
So he has decided to make a program that puts the single space he omitted.
You are given a string s with 12 letters. Output the string putting a single
space between the first 4 letters and last 8 letters in the string s. | [{"input": "CODEFESTIVAL", "output": "CODE FESTIVAL\n \n\nPutting a single space between the first 4 letters and last 8 letters in\n`CODEFESTIVAL` makes it `CODE FESTIVAL`.\n\n* * *"}, {"input": "POSTGRADUATE", "output": "POST GRADUATE\n \n\n* * *"}, {"input": "ABCDEFGHIJKL", "output": "ABCD EFGHIJKL"}] |
If the area of the region the cow can reach is infinite, print `INF`;
otherwise, print an integer representing the area in \mathrm{cm^2}.
(Under the constraints, it can be proved that the area of the region is always
an integer if it is not infinite.)
* * * | s341076610 | Accepted | p02680 | Input is given from Standard Input in the following format:
N M
A_1 B_1 C_1
:
A_N B_N C_N
D_1 E_1 F_1
:
D_M E_M F_M | import sys
# from itertools import chain, accumulate
n, m, *abcdef = map(int, sys.stdin.buffer.read().split())
ver_lines = []
hor_lines = []
x_list = set()
y_list = set()
n3 = n * 3
for a, b, c in zip(abcdef[0:n3:3], abcdef[1:n3:3], abcdef[2:n3:3]):
y_list.add(a)
y_list.add(b)
x_list.add(c)
ver_lines.append((a, b, c))
for d, e, f in zip(abcdef[n3 + 0 :: 3], abcdef[n3 + 1 :: 3], abcdef[n3 + 2 :: 3]):
y_list.add(d)
x_list.add(e)
x_list.add(f)
hor_lines.append((d, e, f))
x_list.add(0)
y_list.add(0)
x_list = sorted(x_list)
y_list = sorted(y_list)
x_dict = {x: i for i, x in enumerate(x_list, start=1)}
y_dict = {y: i for i, y in enumerate(y_list, start=1)}
row_real = len(x_list)
col_real = len(y_list)
row = row_real + 2
col = col_real + 2
banned_up_ij = [[0] * row for _ in range(col)]
banned_down_ij = [[0] * row for _ in range(col)]
banned_left_ij = [[0] * col for _ in range(row)]
banned_right_ij = [[0] * col for _ in range(row)]
for a, b, c in ver_lines:
if a > b:
a, b = b, a
ai = y_dict[a]
bi = y_dict[b]
j = x_dict[c]
banned_left_ij[j][ai] += 1
banned_left_ij[j][bi] -= 1
banned_right_ij[j - 1][ai] += 1
banned_right_ij[j - 1][bi] -= 1
for d, e, f in hor_lines:
if e > f:
e, f = f, e
i = y_dict[d]
ej = x_dict[e]
fj = x_dict[f]
banned_up_ij[i][ej] += 1
banned_up_ij[i][fj] -= 1
banned_down_ij[i - 1][ej] += 1
banned_down_ij[i - 1][fj] -= 1
banned_up = [0] * (row * col)
banned_down = [0] * (row * col)
banned_left = [0] * (row * col)
banned_right = [0] * (row * col)
for i in range(col):
ru = banned_up_ij[i]
rd = banned_down_ij[i]
ri = row * i
banned_up[ri] = ru[0]
banned_down[ri] = rd[0]
for j in range(1, row):
banned_up[ri + j] = banned_up[ri + j - 1] + ru[j]
banned_down[ri + j] = banned_down[ri + j - 1] + rd[j]
for j in range(row):
rl = banned_left_ij[j]
rr = banned_right_ij[j]
banned_left[j] = rl[0]
banned_right[j] = rr[0]
for i in range(1, col):
ri0 = (i - 1) * row
ri1 = i * row
banned_left[ri1 + j] = banned_left[ri0 + j] + rl[i]
banned_right[ri1 + j] = banned_right[ri0 + j] + rr[i]
# banned_up = list(chain.from_iterable(map(accumulate, banned_up_ij)))
# banned_down = list(chain.from_iterable(map(accumulate, banned_down_ij)))
# banned_left = list(chain.from_iterable(zip(*map(accumulate, banned_left_ij))))
# banned_right = list(chain.from_iterable(zip(*map(accumulate, banned_right_ij))))
# for i in range(col):
# print(walls[i * row:(i + 1) * row])
s = row * y_dict[0] + x_dict[0]
enable = [-1] * row + ([-1] + [0] * (row - 2) + [-1]) * (col - 2) + [-1] * row
# for i in range(col):
# print(enable[i * row:(i + 1) * row])
q = [s]
moves = [(-row, banned_up), (-1, banned_left), (1, banned_right), (row, banned_down)]
while q:
c = q.pop()
if enable[c] == 1:
continue
elif enable[c] == -1:
print("INF")
exit()
enable[c] = 1
for dc, banned in moves:
if banned[c]:
continue
nc = c + dc
if enable[nc] == 1:
continue
q.append(nc)
# for i in range(col):
# print(enable[i * row:(i + 1) * row])
ans = 0
for i in range(col):
ri = i * row
for j in range(row):
if enable[ri + j] != 1:
continue
t = y_list[i - 1]
b = y_list[i]
l = x_list[j - 1]
r = x_list[j]
ans += (b - t) * (r - l)
print(ans)
| Statement
There is a grass field that stretches infinitely.
In this field, there is a negligibly small cow. Let (x, y) denote the point
that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the
cow stands now. The cow itself is standing at (0, 0).
There are also N north-south lines and M east-west lines drawn on the field.
The i-th north-south line is the segment connecting the points (A_i, C_i) and
(B_i, C_i), and the j-th east-west line is the segment connecting the points
(D_j, E_j) and (D_j, F_j).
What is the area of the region the cow can reach when it can move around as
long as it does not cross the segments (including the endpoints)? If this area
is infinite, print `INF` instead. | [{"input": "5 6\n 1 2 0\n 0 1 1\n 0 2 2\n -3 4 -1\n -2 6 3\n 1 0 1\n 0 1 2\n 2 0 2\n -1 -4 5\n 3 -2 4\n 1 2 4", "output": "13\n \n\nThe area of the region the cow can reach is 13\\ \\mathrm{cm^2}.\n\n\n\n* * *"}, {"input": "6 1\n -3 -1 -2\n -3 -1 1\n -2 -1 2\n 1 4 -2\n 1 4 -1\n 1 4 1\n 3 1 4", "output": "INF\n \n\nThe area of the region the cow can reach is infinite."}] |
If the area of the region the cow can reach is infinite, print `INF`;
otherwise, print an integer representing the area in \mathrm{cm^2}.
(Under the constraints, it can be proved that the area of the region is always
an integer if it is not infinite.)
* * * | s697383636 | Wrong Answer | p02680 | Input is given from Standard Input in the following format:
N M
A_1 B_1 C_1
:
A_N B_N C_N
D_1 E_1 F_1
:
D_M E_M F_M | import bisect
import os
import sys
if os.getenv("LOCAL"):
sys.stdin = open("_in.txt", "r")
sys.setrecursionlimit(10**9)
INF = float("inf")
IINF = 10**18
MOD = 10**9 + 7
# MOD = 998244353
N, M = list(map(int, sys.stdin.buffer.readline().split()))
ABX = [list(map(int, sys.stdin.buffer.readline().split())) for _ in range(N)]
YEF = [list(map(int, sys.stdin.buffer.readline().split())) for _ in range(M)]
# X, Y を列挙して四角をいっぱい作る
X = []
Y = []
for a, b, x in ABX:
X.append(x)
Y.append(a)
Y.append(b)
for y, e, f in YEF:
X.append(e)
X.append(f)
Y.append(y)
X = [-INF] + list(sorted(set(X))) + [INF, INF]
Y = [-INF] + list(sorted(set(Y))) + [INF, INF]
lines = []
for a, b, x in ABX:
l = bisect.bisect_left(Y, min(a, b))
r = bisect.bisect_left(Y, max(a, b))
xi = bisect.bisect_left(X, x)
for yi in range(l, r):
lines.append((xi, xi, yi, yi + 1))
for y, e, f in YEF:
l = bisect.bisect_left(X, min(e, f))
r = bisect.bisect_left(X, max(e, f))
yi = bisect.bisect_left(Y, y)
for xi in range(l, r):
lines.append((xi, xi + 1, yi, yi))
lines = set(lines)
# (0, 0) を含む場所を適当に選ぶ
xi = bisect.bisect_left(X, 0)
yi = bisect.bisect_left(Y, 0)
s = 0
seen = {(xi, yi)}
stack = [(xi, yi)]
while stack and s < INF:
xi, yi = stack.pop()
s += (X[xi + 1] - X[xi]) * (Y[yi + 1] - Y[yi])
# print(X[xi], X[xi + 1], Y[yi], Y[yi + 1], (X[xi + 1] - X[xi]) * (Y[yi + 1] - Y[yi]))
for dx, dy in ((0, 1), (1, 0), (0, -1), (-1, 0)):
xj, yj = xi + dx, yi + dy
if (xj, yj) in seen:
continue
if dx == 1:
key = (xi + 1, xi + 1, yi, yi + 1)
blocked = key in lines
elif dx == -1:
key = (xi, xi, yi, yi + 1)
blocked = key in lines
elif dy == 1:
key = (xi, xi + 1, yi + 1, yi + 1)
blocked = key in lines
elif dy == -1:
key = (xi, xi + 1, yi, yi)
blocked = key in lines
if blocked:
continue
seen.add((xj, yj))
stack.append((xj, yj))
if s < INF:
print(s)
else:
print("INF")
| Statement
There is a grass field that stretches infinitely.
In this field, there is a negligibly small cow. Let (x, y) denote the point
that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the
cow stands now. The cow itself is standing at (0, 0).
There are also N north-south lines and M east-west lines drawn on the field.
The i-th north-south line is the segment connecting the points (A_i, C_i) and
(B_i, C_i), and the j-th east-west line is the segment connecting the points
(D_j, E_j) and (D_j, F_j).
What is the area of the region the cow can reach when it can move around as
long as it does not cross the segments (including the endpoints)? If this area
is infinite, print `INF` instead. | [{"input": "5 6\n 1 2 0\n 0 1 1\n 0 2 2\n -3 4 -1\n -2 6 3\n 1 0 1\n 0 1 2\n 2 0 2\n -1 -4 5\n 3 -2 4\n 1 2 4", "output": "13\n \n\nThe area of the region the cow can reach is 13\\ \\mathrm{cm^2}.\n\n\n\n* * *"}, {"input": "6 1\n -3 -1 -2\n -3 -1 1\n -2 -1 2\n 1 4 -2\n 1 4 -1\n 1 4 1\n 3 1 4", "output": "INF\n \n\nThe area of the region the cow can reach is infinite."}] |
If the area of the region the cow can reach is infinite, print `INF`;
otherwise, print an integer representing the area in \mathrm{cm^2}.
(Under the constraints, it can be proved that the area of the region is always
an integer if it is not infinite.)
* * * | s109004345 | Wrong Answer | p02680 | Input is given from Standard Input in the following format:
N M
A_1 B_1 C_1
:
A_N B_N C_N
D_1 E_1 F_1
:
D_M E_M F_M | from bisect import bisect_left, bisect_right
from collections import defaultdict, deque
inpl = lambda: list(map(int, input().split()))
N, M = inpl()
hlines_orig = []
Xgrid = set()
vlines_orig = []
Ygrid = set()
for _ in range(N):
A, B, C = inpl()
hlines_orig.append((A, B, C))
Ygrid.add(C)
for _ in range(M):
D, E, F = inpl()
vlines_orig.append((D, E, F))
Xgrid.add(D)
Xgrid = sorted(list(Xgrid))
Ygrid = sorted(list(Ygrid))
W = len(Xgrid)
H = len(Ygrid)
areas = [
[(Xgrid[w + 1] - Xgrid[w]) * (Ygrid[h + 1] - Ygrid[h]) for h in range(H - 1)]
for w in range(W - 1)
]
walled = defaultdict(bool)
dirs = {(0, 1), (1, 0), (-1, 0), (0, -1)}
for A, B, C in hlines_orig:
a = bisect_left(Xgrid, A)
b = bisect_right(Xgrid, B) - 1
c = bisect_left(Ygrid, C)
for i in range(a, b):
if c < H - 1:
walled[((i, c), (0, -1))] = True
if c > 0:
walled[((i, c - 1), (0, 1))] = True
for D, E, F in vlines_orig:
d = bisect_left(Xgrid, D)
e = bisect_left(Ygrid, E)
f = bisect_right(Ygrid, F) - 1
for i in range(e, f):
if d < W - 1:
walled[((d, i), (-1, 0))] = True
if d > 0:
walled[((d - 1, i), (1, 0))] = True
x, y = bisect_right(Xgrid, 0) - 1, bisect_right(Ygrid, 0) - 1
if x <= 0 or y <= 0 or x >= W - 1 or y >= H - 1:
print("INF")
exit()
visited = [[False for _ in range(H - 1)] for _ in range(W - 1)]
visited[x][y] = True
pool = deque([(x, y)])
ans = 0
while pool:
x, y = pool.popleft()
ans += areas[x][y]
for d in dirs:
if not walled[((x, y), d)]:
cx, cy = x + d[0], y + d[1]
if cx < 0 or cx >= W - 1 or cy < 0 or cy >= H - 1:
print("INF")
exit()
elif not visited[cx][cy]:
visited[cx][cy] = True
pool.append((cx, cy))
print(ans)
| Statement
There is a grass field that stretches infinitely.
In this field, there is a negligibly small cow. Let (x, y) denote the point
that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the
cow stands now. The cow itself is standing at (0, 0).
There are also N north-south lines and M east-west lines drawn on the field.
The i-th north-south line is the segment connecting the points (A_i, C_i) and
(B_i, C_i), and the j-th east-west line is the segment connecting the points
(D_j, E_j) and (D_j, F_j).
What is the area of the region the cow can reach when it can move around as
long as it does not cross the segments (including the endpoints)? If this area
is infinite, print `INF` instead. | [{"input": "5 6\n 1 2 0\n 0 1 1\n 0 2 2\n -3 4 -1\n -2 6 3\n 1 0 1\n 0 1 2\n 2 0 2\n -1 -4 5\n 3 -2 4\n 1 2 4", "output": "13\n \n\nThe area of the region the cow can reach is 13\\ \\mathrm{cm^2}.\n\n\n\n* * *"}, {"input": "6 1\n -3 -1 -2\n -3 -1 1\n -2 -1 2\n 1 4 -2\n 1 4 -1\n 1 4 1\n 3 1 4", "output": "INF\n \n\nThe area of the region the cow can reach is infinite."}] |
If the area of the region the cow can reach is infinite, print `INF`;
otherwise, print an integer representing the area in \mathrm{cm^2}.
(Under the constraints, it can be proved that the area of the region is always
an integer if it is not infinite.)
* * * | s292174019 | Runtime Error | p02680 | Input is given from Standard Input in the following format:
N M
A_1 B_1 C_1
:
A_N B_N C_N
D_1 E_1 F_1
:
D_M E_M F_M | from collections import deque
n, m = list(map(int, input().split()))
c_ab = []
d_ef = []
ab = deque([])
ef = deque([])
for i in range(n):
A, B, C = list(map(int, input().split()))
if A > B:
t = A
A = B
B = t
c_ab.append([C, A, B])
for i in range(m):
D, E, F = list(map(int, input().split()))
if E > F:
t = E
E = F
F = t
d_ef.append([D, E, F])
c_ab.sort(key=lambda x: abs(x[0]))
d_ef.sort(key=lambda x: abs(x[0]))
wl = 0
wh = 0
for C, A, B in c_ab:
wl = min(wl, C)
wh = max(wh, C)
hl = 0
hh = 0
for D, E, F in d_ef:
hl = min(hl, D)
hh = max(hh, D)
hd = hl
wd = wl
wl = (wl - wd) * 2
wh = (wh - wd) * 2
hl = (hl - hd) * 2
hh = (hh - hd) * 2
start = [-wd * 2, -hd * 2]
map = [[0] * (hh + 1) for _ in range(wh + 1)]
for C, A, B in c_ab:
C = (C - wd) * 2
A = (A - hd) * 2
B = (B - hd) * 2
if A < hl:
A = hl
if B > hh:
B = hh
for y in range(A, B + 1):
map[C][y] = 1
for D, E, F in d_ef:
D = (D - hd) * 2
E = (E - wd) * 2
F = (F - wd) * 2
if E < wl:
E = wl
if F > wh:
F = wh
for x in range(E, F + 1):
map[x][D] = 1
dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]
que = deque([start])
cnt = 0
while que:
x, y = que.popleft()
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if (nx == 0 or nx == wh or ny == 0 or ny == hh) and map[nx][ny] == 0:
exit(print("INF"))
if 0 <= nx and nx <= wh and 0 <= ny and ny <= hh and map[nx][ny] == 0:
cnt += 1
map[nx][ny] = 1
que.append([nx, ny])
print(cnt // 2)
| Statement
There is a grass field that stretches infinitely.
In this field, there is a negligibly small cow. Let (x, y) denote the point
that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the
cow stands now. The cow itself is standing at (0, 0).
There are also N north-south lines and M east-west lines drawn on the field.
The i-th north-south line is the segment connecting the points (A_i, C_i) and
(B_i, C_i), and the j-th east-west line is the segment connecting the points
(D_j, E_j) and (D_j, F_j).
What is the area of the region the cow can reach when it can move around as
long as it does not cross the segments (including the endpoints)? If this area
is infinite, print `INF` instead. | [{"input": "5 6\n 1 2 0\n 0 1 1\n 0 2 2\n -3 4 -1\n -2 6 3\n 1 0 1\n 0 1 2\n 2 0 2\n -1 -4 5\n 3 -2 4\n 1 2 4", "output": "13\n \n\nThe area of the region the cow can reach is 13\\ \\mathrm{cm^2}.\n\n\n\n* * *"}, {"input": "6 1\n -3 -1 -2\n -3 -1 1\n -2 -1 2\n 1 4 -2\n 1 4 -1\n 1 4 1\n 3 1 4", "output": "INF\n \n\nThe area of the region the cow can reach is infinite."}] |
If the area of the region the cow can reach is infinite, print `INF`;
otherwise, print an integer representing the area in \mathrm{cm^2}.
(Under the constraints, it can be proved that the area of the region is always
an integer if it is not infinite.)
* * * | s584477108 | Wrong Answer | p02680 | Input is given from Standard Input in the following format:
N M
A_1 B_1 C_1
:
A_N B_N C_N
D_1 E_1 F_1
:
D_M E_M F_M | # coding: utf-8
import sys
# from operator import itemgetter
sysread = sys.stdin.readline
read = sys.stdin.read
from heapq import heappop, heappush
# from collections import defaultdict
sys.setrecursionlimit(10**7)
# import math
# from itertools import product#accumulate, combinations, product
# import bisect# lower_bound etc
# import numpy as np
# from copy import deepcopy
# from collections import deque
def run():
N, M = map(int, sysread().split())
verticals = []
for i in range(N):
verticals.append(list(map(int, sysread().split())))
horizontals = []
for i in range(M):
horizontals.append(list(map(int, sysread().split())))
verticals.sort(key=lambda x: x[2])
horizontals.sort(key=lambda x: x[0])
to = [[] for _ in range(N * M)]
for xi, (a, b, c) in enumerate(verticals):
pre = None
for yi, (d, e, f) in enumerate(horizontals):
if a <= d and d <= b and e <= c and c <= f:
cur = [xi * M + yi, d] # (id, d)
if pre == None:
pre = cur[:]
continue
to[pre[0]].append((cur[0], cur[1] - pre[1], c)) # Use Green's
to[cur[0]].append((pre[0], -cur[1] + pre[1], c))
pre = cur[:]
for yi, (d, e, f) in enumerate(horizontals):
pre = None
for xi, (a, b, c) in enumerate(verticals):
if a <= d and d <= b and e <= c and c <= f:
cur = [xi * M + yi, c] # (id, c)
if pre == None:
pre = cur[:]
continue
to[pre[0]].append((cur[0], 0, c))
to[cur[0]].append((pre[0], 0, c))
pre = cur[:]
seen = [False] * (N * M)
INF = float("inf")
min_sq = INF
for i in range(N * M):
stack = []
goal = -1
if not seen[i] and len(to[i]) > 0:
heappush(stack, (0, i)) # (sq, node)
while stack:
sq, current = heappop(stack)
seen[current] = True
for next, dist, y in to[current]:
if next == i:
goal = 1
sq += dist * y
break
if not seen[next]:
heappush(stack, (sq + dist * y, next))
if goal == 1:
min_sq = min(min_sq, sq)
if min_sq == INF:
print("INF")
else:
print(min_sq)
if __name__ == "__main__":
run()
| Statement
There is a grass field that stretches infinitely.
In this field, there is a negligibly small cow. Let (x, y) denote the point
that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the
cow stands now. The cow itself is standing at (0, 0).
There are also N north-south lines and M east-west lines drawn on the field.
The i-th north-south line is the segment connecting the points (A_i, C_i) and
(B_i, C_i), and the j-th east-west line is the segment connecting the points
(D_j, E_j) and (D_j, F_j).
What is the area of the region the cow can reach when it can move around as
long as it does not cross the segments (including the endpoints)? If this area
is infinite, print `INF` instead. | [{"input": "5 6\n 1 2 0\n 0 1 1\n 0 2 2\n -3 4 -1\n -2 6 3\n 1 0 1\n 0 1 2\n 2 0 2\n -1 -4 5\n 3 -2 4\n 1 2 4", "output": "13\n \n\nThe area of the region the cow can reach is 13\\ \\mathrm{cm^2}.\n\n\n\n* * *"}, {"input": "6 1\n -3 -1 -2\n -3 -1 1\n -2 -1 2\n 1 4 -2\n 1 4 -1\n 1 4 1\n 3 1 4", "output": "INF\n \n\nThe area of the region the cow can reach is infinite."}] |
If the area of the region the cow can reach is infinite, print `INF`;
otherwise, print an integer representing the area in \mathrm{cm^2}.
(Under the constraints, it can be proved that the area of the region is always
an integer if it is not infinite.)
* * * | s037722154 | Wrong Answer | p02680 | Input is given from Standard Input in the following format:
N M
A_1 B_1 C_1
:
A_N B_N C_N
D_1 E_1 F_1
:
D_M E_M F_M | import numpy as np
N, M = map(int, input().split())
ABC = np.zeros((N, 3))
for i in range(N):
ABC[i][0], ABC[i][1], ABC[i][2] = map(int, input().split())
DEF = np.zeros((M, 3))
for i in range(M):
DEF[i][0], DEF[i][1], DEF[i][2] = map(int, input().split())
# 座標圧縮
x_co = {-(10**9) - 1, 10**9 + 1}
y_co = {-(10**9) - 1, 10**9 + 1}
for i in range(N):
x_co.add(ABC[i][0])
x_co.add(ABC[i][1])
y_co.add(ABC[i][2])
for i in range(M):
x_co.add(DEF[i][0])
y_co.add(DEF[i][1])
y_co.add(DEF[i][2])
x_co = np.array(sorted(list(x_co)))
y_co = np.array(sorted(list(y_co)))
xL = len(x_co) - 1
yL = len(y_co) - 1
x_co_d = {x_co[i]: i for i in range(xL + 1)}
y_co_d = {y_co[i]: i for i in range(yL + 1)}
# 柵の存在
s_ex_tate = np.zeros((yL + 1, xL))
s_ex_yoko = np.zeros((xL + 1, yL))
for i in range(N):
a = x_co_d[ABC[i][0]]
b = x_co_d[ABC[i][1]]
c = y_co_d[ABC[i][2]]
s_ex_tate[c][a:b] = 1
for i in range(M):
d = x_co_d[DEF[i][0]]
e = y_co_d[DEF[i][1]]
f = y_co_d[DEF[i][2]]
s_ex_yoko[d][e:f] = 1
# 初期位置
for i in range(xL):
if x_co[i + 1] > 0:
xf = [i]
break
if x_co[i + 1] == 0:
xf = [i, i + 1]
break
for i in range(yL):
if y_co[i + 1] > 0:
yf = [i]
break
if y_co[i + 1] == 0:
yf = [i, i + 1]
break
def sq(x, y):
return int((x_co[x + 1] - x_co[x]) * (y_co[y + 1] - y_co[y]))
# 探索
Q = []
# houmon = [[False] * yL for _ in range(xL)]
houmon = np.zeros((xL, yL))
ans = 0
is_inf = False
for x in xf:
for y in yf:
houmon[x][y] = 1
Q.append((x, y))
while Q:
x, y = Q.pop()
if x in [0, xL - 1] or y in [0, yL - 1]:
is_inf = True
break
ans += sq(x, y)
if (not houmon[x - 1][y]) and (not s_ex_yoko[x][y]):
houmon[x - 1][y] = True
Q.append((x - 1, y))
if (not houmon[x][y - 1]) and (not s_ex_tate[y][x]):
houmon[x][y - 1] = True
Q.append((x, y - 1))
if (not houmon[x + 1][y]) and (not s_ex_yoko[x + 1][y]):
houmon[x + 1][y] = True
Q.append((x + 1, y))
if (not houmon[x][y + 1]) and (not s_ex_tate[y + 1][x]):
houmon[x][y + 1] = True
Q.append((x, y + 1))
if is_inf:
print("INF")
else:
print(ans)
| Statement
There is a grass field that stretches infinitely.
In this field, there is a negligibly small cow. Let (x, y) denote the point
that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the
cow stands now. The cow itself is standing at (0, 0).
There are also N north-south lines and M east-west lines drawn on the field.
The i-th north-south line is the segment connecting the points (A_i, C_i) and
(B_i, C_i), and the j-th east-west line is the segment connecting the points
(D_j, E_j) and (D_j, F_j).
What is the area of the region the cow can reach when it can move around as
long as it does not cross the segments (including the endpoints)? If this area
is infinite, print `INF` instead. | [{"input": "5 6\n 1 2 0\n 0 1 1\n 0 2 2\n -3 4 -1\n -2 6 3\n 1 0 1\n 0 1 2\n 2 0 2\n -1 -4 5\n 3 -2 4\n 1 2 4", "output": "13\n \n\nThe area of the region the cow can reach is 13\\ \\mathrm{cm^2}.\n\n\n\n* * *"}, {"input": "6 1\n -3 -1 -2\n -3 -1 1\n -2 -1 2\n 1 4 -2\n 1 4 -1\n 1 4 1\n 3 1 4", "output": "INF\n \n\nThe area of the region the cow can reach is infinite."}] |
If the area of the region the cow can reach is infinite, print `INF`;
otherwise, print an integer representing the area in \mathrm{cm^2}.
(Under the constraints, it can be proved that the area of the region is always
an integer if it is not infinite.)
* * * | s948886374 | Accepted | p02680 | Input is given from Standard Input in the following format:
N M
A_1 B_1 C_1
:
A_N B_N C_N
D_1 E_1 F_1
:
D_M E_M F_M | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import bisect
import collections
class VBoarder(object):
def __init__(self, x1, x2, y):
self.x1 = x1
self.x2 = x2
self.y = y
class HBoarder(object):
def __init__(self, x, y1, y2):
self.x = x
self.y1 = y1
self.y2 = y2
class Cell(object):
def __init__(self, x1, y1, x2, y2):
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
self.up = True
self.down = True
self.left = True
self.right = True
self.checked = False
def area(self):
return (self.x2 - self.x1) * (self.y2 - self.y1)
def __str__(self):
return "(({:2d},{:2d}),({:2d},{:2d})){}{}{}{}".format(
self.x1,
self.y1,
self.x2,
self.y2,
"Uu"[int(self.up)],
"Dd"[int(self.down)],
"Ll"[int(self.left)],
"Rr"[int(self.right)],
)
def main():
N, M = map(int, input().split())
vborders = [VBoarder(*map(int, input().split())) for _ in range(N)]
hborders = [HBoarder(*map(int, input().split())) for _ in range(M)]
y_axis = list(set([b.y for b in vborders]))
y_axis.sort()
y_axis = [y_axis[0] - 1] + y_axis + [y_axis[-1] + 1]
x_axis = list(set([b.x for b in hborders]))
x_axis.sort()
x_axis = [x_axis[0] - 1] + x_axis + [x_axis[-1] + 1]
cells = [
[Cell(x1, y1, x2, y2) for x1, x2 in zip(x_axis[:-1], x_axis[1:])]
for y1, y2 in zip(y_axis[:-1], y_axis[1:])
]
for b in vborders:
y_idx = bisect.bisect_left(y_axis, b.y)
x_idx1 = bisect.bisect_left(x_axis, b.x1)
x_idx2 = bisect.bisect_right(x_axis, b.x2) - 1
for x_idx in range(x_idx1, x_idx2):
cells[y_idx - 1][x_idx].down = False
cells[y_idx][x_idx].up = False
for b in hborders:
x_idx = bisect.bisect_left(x_axis, b.x)
y_idx1 = bisect.bisect_left(y_axis, b.y1)
y_idx2 = bisect.bisect_right(y_axis, b.y2) - 1
for y_idx in range(y_idx1, y_idx2):
cells[y_idx][x_idx - 1].right = False
cells[y_idx][x_idx].left = False
queue = collections.deque()
area = 0
x = bisect.bisect_right(x_axis, 0.5) - 1
y = bisect.bisect_right(y_axis, 0.2) - 1
queue.append((x, y))
while len(queue) != 0:
x, y = queue.popleft()
if x == 0 or x == len(x_axis) - 1 or y == 0 or y == len(y_axis) - 1:
print("INF")
return
c = cells[y][x]
if c.checked:
continue
area += c.area()
c.checked = True
if c.up:
queue.append((x, y - 1))
if c.down:
queue.append((x, y + 1))
if c.left:
queue.append((x - 1, y))
if c.right:
queue.append((x + 1, y))
print(area)
if __name__ == "__main__":
main()
| Statement
There is a grass field that stretches infinitely.
In this field, there is a negligibly small cow. Let (x, y) denote the point
that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the
cow stands now. The cow itself is standing at (0, 0).
There are also N north-south lines and M east-west lines drawn on the field.
The i-th north-south line is the segment connecting the points (A_i, C_i) and
(B_i, C_i), and the j-th east-west line is the segment connecting the points
(D_j, E_j) and (D_j, F_j).
What is the area of the region the cow can reach when it can move around as
long as it does not cross the segments (including the endpoints)? If this area
is infinite, print `INF` instead. | [{"input": "5 6\n 1 2 0\n 0 1 1\n 0 2 2\n -3 4 -1\n -2 6 3\n 1 0 1\n 0 1 2\n 2 0 2\n -1 -4 5\n 3 -2 4\n 1 2 4", "output": "13\n \n\nThe area of the region the cow can reach is 13\\ \\mathrm{cm^2}.\n\n\n\n* * *"}, {"input": "6 1\n -3 -1 -2\n -3 -1 1\n -2 -1 2\n 1 4 -2\n 1 4 -1\n 1 4 1\n 3 1 4", "output": "INF\n \n\nThe area of the region the cow can reach is infinite."}] |
If the area of the region the cow can reach is infinite, print `INF`;
otherwise, print an integer representing the area in \mathrm{cm^2}.
(Under the constraints, it can be proved that the area of the region is always
an integer if it is not infinite.)
* * * | s313387825 | Runtime Error | p02680 | Input is given from Standard Input in the following format:
N M
A_1 B_1 C_1
:
A_N B_N C_N
D_1 E_1 F_1
:
D_M E_M F_M | N, M = map(int, input().split())
h_lines = {}
v_lines = {}
for _ in range(N):
a, b, c = map(int, input().split())
if c in v_lines:
v_lines[c].append((a, b))
else:
v_lines[c] = [(a, b)]
for _ in range(M):
d, e, f = map(int, input().split())
if d in h_lines:
h_lines[d].append((e, f))
else:
h_lines[d] = [(e, f)]
h_lines = list(h_lines.items())
v_lines = list(v_lines.items())
h_lines.sort()
v_lines.sort()
rows = len(v_lines) - 1
cols = len(h_lines) - 1
h_walls = [[False] * rows for _ in range(cols + 1)]
v_walls = [[False] * (rows + 1) for _ in range(cols)]
for i, (y, l) in enumerate(h_lines):
for x1, x2 in l:
j = 0
while j < rows:
if x1 <= v_lines[j][0]:
break
j += 1
while j < rows:
if x2 < v_lines[j + 1][0]:
break
h_walls[i][j] = True
j += 1
for j, (x, l) in enumerate(v_lines):
for y1, y2 in l:
i = 0
while i < cols:
if y1 <= h_lines[i][0]:
break
i += 1
while i < cols:
if y2 < h_lines[i + 1][0]:
break
v_walls[i][j] = True
i += 1
# for i in range(cols + 1):
# print("+" + "+".join("--" if f else " " for f in h_walls[i]) + "+")
# if i < cols:
# print(" ".join("|" if f else " " for f in v_walls[i]))
def find_initial_pos():
for i in range(cols):
if h_lines[i][0] <= 0 and 0 <= h_lines[i + 1][0]:
for j in range(rows):
if v_lines[j][0] <= 0 and 0 <= v_lines[j + 1][0]:
return (i, j)
return None
def calc_area():
cur = find_initial_pos()
if cur == None:
return "INF"
stack = [cur]
area = 0
visited = [[False] * rows for _ in range(cols)]
visited[cur[0]][cur[1]] = True
search = (
(1, 0, lambda y, x: not h_walls[y + 1][x]),
(-1, 0, lambda y, x: not h_walls[y][x]),
(0, 1, lambda y, x: not v_walls[y][x + 1]),
(0, -1, lambda y, x: not v_walls[y][x]),
)
while stack:
y, x = stack.pop()
area += (h_lines[y + 1][0] - h_lines[y][0]) * (
v_lines[x + 1][0] - v_lines[x][0]
)
# print(area, y, x)
for dy, dx, check in search:
if check(y, x):
ny = y + dy
nx = x + dx
# print(">", ny, nx)
if not visited[ny][nx]:
if nx < 0 or nx >= rows or ny < 0 or ny >= cols:
return "INF"
stack.append((ny, nx))
visited[ny][nx] = True
return str(area)
print(calc_area())
| Statement
There is a grass field that stretches infinitely.
In this field, there is a negligibly small cow. Let (x, y) denote the point
that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the
cow stands now. The cow itself is standing at (0, 0).
There are also N north-south lines and M east-west lines drawn on the field.
The i-th north-south line is the segment connecting the points (A_i, C_i) and
(B_i, C_i), and the j-th east-west line is the segment connecting the points
(D_j, E_j) and (D_j, F_j).
What is the area of the region the cow can reach when it can move around as
long as it does not cross the segments (including the endpoints)? If this area
is infinite, print `INF` instead. | [{"input": "5 6\n 1 2 0\n 0 1 1\n 0 2 2\n -3 4 -1\n -2 6 3\n 1 0 1\n 0 1 2\n 2 0 2\n -1 -4 5\n 3 -2 4\n 1 2 4", "output": "13\n \n\nThe area of the region the cow can reach is 13\\ \\mathrm{cm^2}.\n\n\n\n* * *"}, {"input": "6 1\n -3 -1 -2\n -3 -1 1\n -2 -1 2\n 1 4 -2\n 1 4 -1\n 1 4 1\n 3 1 4", "output": "INF\n \n\nThe area of the region the cow can reach is infinite."}] |
If the area of the region the cow can reach is infinite, print `INF`;
otherwise, print an integer representing the area in \mathrm{cm^2}.
(Under the constraints, it can be proved that the area of the region is always
an integer if it is not infinite.)
* * * | s066991863 | Accepted | p02680 | Input is given from Standard Input in the following format:
N M
A_1 B_1 C_1
:
A_N B_N C_N
D_1 E_1 F_1
:
D_M E_M F_M | import bisect
import sys
lower_bound = bisect.bisect_left
upper_bound = bisect.bisect_right
INF = 0x3FFFFFFF
n, m = map(int, input().split())
a = [list(map(int, input().split())) for i in range(n)]
b = [list(map(int, input().split())) for i in range(m)]
X = {-INF, INF}
Y = {-INF, INF}
for i in a:
Y.add(i[2])
for i in b:
X.add(i[0])
X = list(sorted(X))
Y = list(sorted(Y))
n = len(X) - 1
m = len(Y) - 1
wallx = [[False] * m for i in range(n)]
wally = [[False] * m for i in range(n)]
for x1, x2, y1 in a:
x1 = lower_bound(X, x1)
y1 = lower_bound(Y, y1)
x2 = upper_bound(X, x2) - 1
for i in range(x1, x2):
wally[i][y1] = True
for x1, y1, y2 in b:
x1 = lower_bound(X, x1)
y1 = lower_bound(Y, y1)
y2 = upper_bound(Y, y2) - 1
for i in range(y1, y2):
wallx[x1][i] = True
cow = [[False] * m for i in range(n)]
cx = upper_bound(X, 0) - 1
cy = upper_bound(Y, 0) - 1
cow[cx][cy] = True
q = [(cx, cy)]
ans = 0
while q:
x, y = q.pop()
if not x or not y:
print("INF")
sys.exit()
ans += (X[x + 1] - X[x]) * (Y[y + 1] - Y[y])
if x and not wallx[x][y] and not cow[x - 1][y]:
cow[x - 1][y] = True
q.append((x - 1, y))
if y and not wally[x][y] and not cow[x][y - 1]:
cow[x][y - 1] = True
q.append((x, y - 1))
if x + 1 < n and not wallx[x + 1][y] and not cow[x + 1][y]:
cow[x + 1][y] = True
q.append((x + 1, y))
if y + 1 < m and not wally[x][y + 1] and not cow[x][y + 1]:
cow[x][y + 1] = True
q.append((x, y + 1))
print(ans)
| Statement
There is a grass field that stretches infinitely.
In this field, there is a negligibly small cow. Let (x, y) denote the point
that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the
cow stands now. The cow itself is standing at (0, 0).
There are also N north-south lines and M east-west lines drawn on the field.
The i-th north-south line is the segment connecting the points (A_i, C_i) and
(B_i, C_i), and the j-th east-west line is the segment connecting the points
(D_j, E_j) and (D_j, F_j).
What is the area of the region the cow can reach when it can move around as
long as it does not cross the segments (including the endpoints)? If this area
is infinite, print `INF` instead. | [{"input": "5 6\n 1 2 0\n 0 1 1\n 0 2 2\n -3 4 -1\n -2 6 3\n 1 0 1\n 0 1 2\n 2 0 2\n -1 -4 5\n 3 -2 4\n 1 2 4", "output": "13\n \n\nThe area of the region the cow can reach is 13\\ \\mathrm{cm^2}.\n\n\n\n* * *"}, {"input": "6 1\n -3 -1 -2\n -3 -1 1\n -2 -1 2\n 1 4 -2\n 1 4 -1\n 1 4 1\n 3 1 4", "output": "INF\n \n\nThe area of the region the cow can reach is infinite."}] |
If the area of the region the cow can reach is infinite, print `INF`;
otherwise, print an integer representing the area in \mathrm{cm^2}.
(Under the constraints, it can be proved that the area of the region is always
an integer if it is not infinite.)
* * * | s186875120 | Wrong Answer | p02680 | Input is given from Standard Input in the following format:
N M
A_1 B_1 C_1
:
A_N B_N C_N
D_1 E_1 F_1
:
D_M E_M F_M | print("INF")
| Statement
There is a grass field that stretches infinitely.
In this field, there is a negligibly small cow. Let (x, y) denote the point
that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the
cow stands now. The cow itself is standing at (0, 0).
There are also N north-south lines and M east-west lines drawn on the field.
The i-th north-south line is the segment connecting the points (A_i, C_i) and
(B_i, C_i), and the j-th east-west line is the segment connecting the points
(D_j, E_j) and (D_j, F_j).
What is the area of the region the cow can reach when it can move around as
long as it does not cross the segments (including the endpoints)? If this area
is infinite, print `INF` instead. | [{"input": "5 6\n 1 2 0\n 0 1 1\n 0 2 2\n -3 4 -1\n -2 6 3\n 1 0 1\n 0 1 2\n 2 0 2\n -1 -4 5\n 3 -2 4\n 1 2 4", "output": "13\n \n\nThe area of the region the cow can reach is 13\\ \\mathrm{cm^2}.\n\n\n\n* * *"}, {"input": "6 1\n -3 -1 -2\n -3 -1 1\n -2 -1 2\n 1 4 -2\n 1 4 -1\n 1 4 1\n 3 1 4", "output": "INF\n \n\nThe area of the region the cow can reach is infinite."}] |
If the area of the region the cow can reach is infinite, print `INF`;
otherwise, print an integer representing the area in \mathrm{cm^2}.
(Under the constraints, it can be proved that the area of the region is always
an integer if it is not infinite.)
* * * | s135560648 | Wrong Answer | p02680 | Input is given from Standard Input in the following format:
N M
A_1 B_1 C_1
:
A_N B_N C_N
D_1 E_1 F_1
:
D_M E_M F_M | print(0)
| Statement
There is a grass field that stretches infinitely.
In this field, there is a negligibly small cow. Let (x, y) denote the point
that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the
cow stands now. The cow itself is standing at (0, 0).
There are also N north-south lines and M east-west lines drawn on the field.
The i-th north-south line is the segment connecting the points (A_i, C_i) and
(B_i, C_i), and the j-th east-west line is the segment connecting the points
(D_j, E_j) and (D_j, F_j).
What is the area of the region the cow can reach when it can move around as
long as it does not cross the segments (including the endpoints)? If this area
is infinite, print `INF` instead. | [{"input": "5 6\n 1 2 0\n 0 1 1\n 0 2 2\n -3 4 -1\n -2 6 3\n 1 0 1\n 0 1 2\n 2 0 2\n -1 -4 5\n 3 -2 4\n 1 2 4", "output": "13\n \n\nThe area of the region the cow can reach is 13\\ \\mathrm{cm^2}.\n\n\n\n* * *"}, {"input": "6 1\n -3 -1 -2\n -3 -1 1\n -2 -1 2\n 1 4 -2\n 1 4 -1\n 1 4 1\n 3 1 4", "output": "INF\n \n\nThe area of the region the cow can reach is infinite."}] |
If the area of the region the cow can reach is infinite, print `INF`;
otherwise, print an integer representing the area in \mathrm{cm^2}.
(Under the constraints, it can be proved that the area of the region is always
an integer if it is not infinite.)
* * * | s091591484 | Accepted | p02680 | Input is given from Standard Input in the following format:
N M
A_1 B_1 C_1
:
A_N B_N C_N
D_1 E_1 F_1
:
D_M E_M F_M | def numba_compile(numba_config):
import os, sys
if sys.argv[-1] == "ONLINE_JUDGE":
from numba import njit
from numba.pycc import CC
cc = CC("my_module")
for func, signature in numba_config:
globals()[func.__name__] = njit(signature)(func)
cc.export(func.__name__, signature)(func)
cc.compile()
exit()
elif os.name == "posix":
exec(
f"from my_module import {','.join(func.__name__ for func, _ in numba_config)}"
)
for func, _ in numba_config:
globals()[func.__name__] = vars()[func.__name__]
else:
from numba import njit
for func, signature in numba_config:
globals()[func.__name__] = njit(signature, cache=True)(func)
print("compiled!", file=sys.stderr)
import sys
import numpy as np
def solve(N, M, ABCDEF):
L, R, U, D = 0, 1, 2, 3
Dy = [0, 0, -1, 1]
Dx = [-1, 1, 0, 0]
mapping_inv_x = [0]
mapping_inv_y = [0]
for i in range(N):
y1, y2, x = ABCDEF[i]
mapping_inv_x.append(x)
mapping_inv_y.append(y1)
mapping_inv_y.append(y2)
for i in range(N, N + M):
y, x1, x2 = ABCDEF[i]
mapping_inv_x.append(x1)
mapping_inv_x.append(x2)
mapping_inv_y.append(y)
mapping_inv_y = sorted(set(mapping_inv_y))
mapping_inv_x = sorted(set(mapping_inv_x))
H = len(mapping_inv_y) + 1
W = len(mapping_inv_x) + 1
E = np.ones((H, W, 4), dtype=np.int8)
# mapping_y = {v: i for i, v in enumerate(mapping_inv_y, 1)}
# mapping_x = {v: i for i, v in enumerate(mapping_inv_x, 1)}
mapping_y = {}
for i, v in enumerate(mapping_inv_y, 1):
mapping_y[v] = i
mapping_x = {}
for i, v in enumerate(mapping_inv_x, 1):
mapping_x[v] = i
for i in range(N):
y1, y2, x = ABCDEF[i]
y1 = mapping_y[y1]
y2 = mapping_y[y2]
x = mapping_x[x]
for y in range(y1, y2):
E[y, x, L] = 0
E[y, x - 1, R] = 0
for i in range(N, N + M):
y, x1, x2 = ABCDEF[i]
y = mapping_y[y]
x1 = mapping_x[x1]
x2 = mapping_x[x2]
for x in range(x1, x2):
E[y, x, U] = 0
E[y - 1, x, D] = 0
Diff_x = np.diff(np.array(mapping_inv_x))
Diff_y = np.diff(np.array(mapping_inv_y))
Area = np.empty((H, W), dtype=np.int64)
Area[1:-1, 1:-1] = Diff_y.reshape(-1, 1) * Diff_x
Closed = np.zeros((H, W), dtype=np.int8)
y, x = mapping_y[0], mapping_x[0]
Closed[y, x] = 1
ans = 0
stack = [(y, x)]
while stack:
vy, vx = stack.pop()
if vy == 0 or vy == H - 1 or vx == 0 or vx == W - 1:
print("INF")
return
ans += Area[vy, vx]
for direction in [L, R, U, D]:
if E[vy, vx, direction]:
uy, ux = vy + Dy[direction], vx + Dx[direction]
if not Closed[uy, ux]:
stack.append((uy, ux))
Closed[uy, ux] = 1
print(ans)
numba_compile(
[
[solve, "(i8,i8,i8[:,:])"],
]
)
def main():
N, M = map(int, sys.stdin.buffer.readline().split())
ABCDEF = np.array(sys.stdin.buffer.read().split(), dtype=np.int64).reshape(-1, 3)
solve(N, M, ABCDEF)
main()
| Statement
There is a grass field that stretches infinitely.
In this field, there is a negligibly small cow. Let (x, y) denote the point
that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the
cow stands now. The cow itself is standing at (0, 0).
There are also N north-south lines and M east-west lines drawn on the field.
The i-th north-south line is the segment connecting the points (A_i, C_i) and
(B_i, C_i), and the j-th east-west line is the segment connecting the points
(D_j, E_j) and (D_j, F_j).
What is the area of the region the cow can reach when it can move around as
long as it does not cross the segments (including the endpoints)? If this area
is infinite, print `INF` instead. | [{"input": "5 6\n 1 2 0\n 0 1 1\n 0 2 2\n -3 4 -1\n -2 6 3\n 1 0 1\n 0 1 2\n 2 0 2\n -1 -4 5\n 3 -2 4\n 1 2 4", "output": "13\n \n\nThe area of the region the cow can reach is 13\\ \\mathrm{cm^2}.\n\n\n\n* * *"}, {"input": "6 1\n -3 -1 -2\n -3 -1 1\n -2 -1 2\n 1 4 -2\n 1 4 -1\n 1 4 1\n 3 1 4", "output": "INF\n \n\nThe area of the region the cow can reach is infinite."}] |
If the area of the region the cow can reach is infinite, print `INF`;
otherwise, print an integer representing the area in \mathrm{cm^2}.
(Under the constraints, it can be proved that the area of the region is always
an integer if it is not infinite.)
* * * | s981024027 | Accepted | p02680 | Input is given from Standard Input in the following format:
N M
A_1 B_1 C_1
:
A_N B_N C_N
D_1 E_1 F_1
:
D_M E_M F_M | N, M = map(int, input().split())
ts = {}
tlis = []
for i in range(N):
B, C, A = map(int, input().split())
if A not in ts:
tlis.append(A)
ts[A] = []
ts[A].append([B, C])
ys = {}
ylis = []
for i in range(M):
A, B, C = map(int, input().split())
if A not in ys:
ylis.append(A)
ys[A] = []
ys[A].append([B, C])
tlis.sort()
ylis.sort()
import bisect
nowi = bisect.bisect_right(tlis, 0) - 1
nowj = bisect.bisect_right(ylis, 0) - 1
# print (tlis,ylis,nowi,nowj)
for i in ts:
ts[i].sort()
new = []
lastl = None
lastr = None
for tmp in ts[i]:
nl, nr = tmp
if lastl == None:
lastl = nl
lastr = nr
elif lastr < nl:
new.append([lastl, lastr])
lastl = nl
lastr = nr
else:
lastr = nr
new.append([lastl, lastr])
ts[i] = new
for i in ys:
ys[i].sort()
new = []
lastl = None
lastr = None
for tmp in ys[i]:
nl, nr = tmp
if lastl == None:
lastl = nl
lastr = nr
elif lastr < nl:
new.append([lastl, lastr])
lastl = nl
lastr = nr
else:
lastr = nr
new.append([lastl, lastr])
ys[i] = new
from collections import deque
q = deque([[nowi, nowj]])
import sys
ans = 0
end = {}
end[(nowi, nowj)] = 1
if len(tlis) < 2 or len(ylis) < 2:
print("INF")
sys.exit()
while len(q) > 0:
ni, nj = q.popleft()
if ni == -1 or nj == -1 or ni == len(tlis) - 1 or nj == len(ylis) - 1:
print("INF")
sys.exit()
up = ylis[nj]
do = ylis[nj + 1]
le = tlis[ni]
ri = tlis[ni + 1]
# print (ni,nj,up,do,le,ri)
ans += (do - up) * (ri - le)
# up
flag = True
nex = (ni, nj - 1)
if nex not in end:
for tmp in ys[up]:
L, R = tmp
if L <= le and ri <= R:
flag = False
break
if flag:
end[nex] = 1
q.append([nex[0], nex[1]])
nex = (ni, nj + 1)
flag = True
if nex not in end:
for tmp in ys[do]:
L, R = tmp
if L <= le and ri <= R:
flag = False
break
if flag:
end[nex] = 1
q.append([nex[0], nex[1]])
nex = (ni - 1, nj)
flag = True
if nex not in end:
for tmp in ts[le]:
L, R = tmp
if L <= up and do <= R:
flag = False
break
if flag:
end[nex] = 1
q.append([nex[0], nex[1]])
nex = (ni + 1, nj)
flag = True
if nex not in end:
for tmp in ts[ri]:
L, R = tmp
if L <= up and do <= R:
flag = False
break
if flag:
end[nex] = 1
q.append([nex[0], nex[1]])
print(ans)
| Statement
There is a grass field that stretches infinitely.
In this field, there is a negligibly small cow. Let (x, y) denote the point
that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the
cow stands now. The cow itself is standing at (0, 0).
There are also N north-south lines and M east-west lines drawn on the field.
The i-th north-south line is the segment connecting the points (A_i, C_i) and
(B_i, C_i), and the j-th east-west line is the segment connecting the points
(D_j, E_j) and (D_j, F_j).
What is the area of the region the cow can reach when it can move around as
long as it does not cross the segments (including the endpoints)? If this area
is infinite, print `INF` instead. | [{"input": "5 6\n 1 2 0\n 0 1 1\n 0 2 2\n -3 4 -1\n -2 6 3\n 1 0 1\n 0 1 2\n 2 0 2\n -1 -4 5\n 3 -2 4\n 1 2 4", "output": "13\n \n\nThe area of the region the cow can reach is 13\\ \\mathrm{cm^2}.\n\n\n\n* * *"}, {"input": "6 1\n -3 -1 -2\n -3 -1 1\n -2 -1 2\n 1 4 -2\n 1 4 -1\n 1 4 1\n 3 1 4", "output": "INF\n \n\nThe area of the region the cow can reach is infinite."}] |
Print the lexicographically largest string that satisfies the condition.
* * * | s952823835 | Runtime Error | p03300 | Input is given from Standard Input in the following format:
N
S | n = int(input())
s = input()
ab_index = {"a": 0, "b": 0}
ab_dic = {}
i = 0
while i < (2 * n):
ab_dic[i] = (s[i], ab_index[s[i]])
ab_index[s[i]] += 1
i += 1
import copy
class Info:
def __init__(self, string, includeds, excludeds):
self.string = string
self.includeds = includeds
self.excludeds = excludeds
def include(self, s, i):
dic = copy.copy(self.includeds)
dic[(s, i)] = True
return Info(self.string + s, dic, self.excludeds)
def exclude(self, s, i):
dic = copy.copy(self.excludeds)
dic[(s, i)] = True
return Info(self.string, self.includeds, dic)
def __repr__(self):
return "({0}, {1}, {2})".format(self.string, self.includeds, self.excludeds)
dp: [[Info]] = [[None for _ in range(len(s) + 1)] for _ in range(len(s) + 1)]
dp[0][0] = Info("", {}, {})
for i in range(len(s)):
ab, abi = ab_dic[i]
for j in range(i + 1):
inf = dp[i][j]
if inf is None:
continue
if ab == "a":
if inf.includeds.get(("b", abi)):
dp[i + 1][j + 1] = inf.include("a", abi)
elif inf.excludeds.get(("b", abi)):
candidate = inf.exclude("a", abi)
if dp[i + 1][j] is None:
dp[i + 1][j] = candidate
else:
if dp[i + 1][j].string <= candidate.string:
dp[i + 1][j] = candidate
else:
pass
else:
dp[i + 1][j + 1] = inf.include("a", abi)
candidate = inf.exclude("a", abi)
if dp[i + 1][j] is None:
dp[i + 1][j] = candidate
else:
if dp[i + 1][j].string <= candidate.string:
dp[i + 1][j] = candidate
else:
pass
if ab == "b":
if inf.includeds.get(("a", abi)):
dp[i + 1][j + 1] = inf.include("b", abi)
elif inf.excludeds.get(("a", abi)):
candidate = inf.exclude("b", abi)
if dp[i + 1][j] is None:
dp[i + 1][j] = candidate
else:
if dp[i + 1][j].string < candidate.string:
dp[i + 1][j] = candidate
else:
pass
else:
dp[i + 1][j + 1] = inf.include("b", abi)
candidate = inf.exclude("b", abi)
if dp[i + 1][j] is None:
dp[i + 1][j] = candidate
else:
if dp[i + 1][j].string < candidate.string:
dp[i + 1][j] = candidate
else:
pass
print(sorted(map(lambda x: x.string, filter(lambda x: x is not None, dp[-1])))[-1])
| Statement
You are given a string S of length 2N, containing N occurrences of `a` and N
occurrences of `b`.
You will choose some of the characters in S. Here, for each i = 1,2,...,N, it
is not allowed to choose exactly one of the following two: the i-th occurrence
of `a` and the i-th occurrence of `b`. (That is, you can only choose both or
neither.) Then, you will concatenate the chosen characters (without changing
the order).
Find the lexicographically largest string that can be obtained in this way. | [{"input": "3\n aababb", "output": "abab\n \n\nA subsequence of T obtained from taking the first, third, fourth and sixth\ncharacters in S, satisfies the condition.\n\n* * *"}, {"input": "3\n bbabaa", "output": "bbabaa\n \n\nYou can choose all the characters.\n\n* * *"}, {"input": "6\n bbbaabbabaaa", "output": "bbbabaaa\n \n\n* * *"}, {"input": "9\n abbbaababaababbaba", "output": "bbaababababa"}] |
If there are values that could be X, the price of the apple pie before tax,
print any one of them.
If there are multiple such values, printing any one of them will be accepted.
If no value could be X, print `:(`.
* * * | s990186584 | Wrong Answer | p02842 | Input is given from Standard Input in the following format:
N | a = input()
import math
for i in range(1, 50000):
z = i * 1.08
if (z - math.floor(z)) > (math.ceil(z) - z):
if math.ceil(z) == a:
print(i)
elif (z - math.floor(z)) < (math.ceil(z) - z):
if math.floor(z) == a:
print(i)
elif (z - math.floor(z)) == (math.ceil(z) - z):
if math.floor(z) == a or math.ceil(z) == a:
print(i)
else:
print(":(")
| Statement
Takahashi bought a piece of apple pie at ABC Confiserie. According to his
memory, he paid N yen (the currency of Japan) for it.
The consumption tax rate for foods in this shop is 8 percent. That is, to buy
an apple pie priced at X yen before tax, you have to pay X \times 1.08 yen
(rounded down to the nearest integer).
Takahashi forgot the price of his apple pie before tax, X, and wants to know
it again. Write a program that takes N as input and finds X. We assume X is an
integer.
If there are multiple possible values for X, find any one of them. Also,
Takahashi's memory of N, the amount he paid, may be incorrect. If no value
could be X, report that fact. | [{"input": "432", "output": "400\n \n\nIf the apple pie is priced at 400 yen before tax, you have to pay 400 \\times\n1.08 = 432 yen to buy one. \nOtherwise, the amount you have to pay will not be 432 yen.\n\n* * *"}, {"input": "1079", "output": ":(\n \n\nThere is no possible price before tax for which you have to pay 1079 yen with\ntax.\n\n* * *"}, {"input": "1001", "output": "927\n \n\nIf the apple pie is priced 927 yen before tax, by rounding down 927 \\times\n1.08 = 1001.16, you have to pay 1001 yen."}] |
If there are values that could be X, the price of the apple pie before tax,
print any one of them.
If there are multiple such values, printing any one of them will be accepted.
If no value could be X, print `:(`.
* * * | s097089451 | Wrong Answer | p02842 | Input is given from Standard Input in the following format:
N | n1 = int(input())
n2_1 = float(n1 + 0.999999)
n2_2 = float(n1)
n3 = int(n2_1 / 1.08)
n4 = int(n2_2 / 1.08)
n3n = int(n3)
n4n = int(n4)
if n3 != n4 or int(n1) == int(n2_1):
print(n3)
else:
print(":(")
| Statement
Takahashi bought a piece of apple pie at ABC Confiserie. According to his
memory, he paid N yen (the currency of Japan) for it.
The consumption tax rate for foods in this shop is 8 percent. That is, to buy
an apple pie priced at X yen before tax, you have to pay X \times 1.08 yen
(rounded down to the nearest integer).
Takahashi forgot the price of his apple pie before tax, X, and wants to know
it again. Write a program that takes N as input and finds X. We assume X is an
integer.
If there are multiple possible values for X, find any one of them. Also,
Takahashi's memory of N, the amount he paid, may be incorrect. If no value
could be X, report that fact. | [{"input": "432", "output": "400\n \n\nIf the apple pie is priced at 400 yen before tax, you have to pay 400 \\times\n1.08 = 432 yen to buy one. \nOtherwise, the amount you have to pay will not be 432 yen.\n\n* * *"}, {"input": "1079", "output": ":(\n \n\nThere is no possible price before tax for which you have to pay 1079 yen with\ntax.\n\n* * *"}, {"input": "1001", "output": "927\n \n\nIf the apple pie is priced 927 yen before tax, by rounding down 927 \\times\n1.08 = 1001.16, you have to pay 1001 yen."}] |
If there are values that could be X, the price of the apple pie before tax,
print any one of them.
If there are multiple such values, printing any one of them will be accepted.
If no value could be X, print `:(`.
* * * | s928277283 | Accepted | p02842 | Input is given from Standard Input in the following format:
N | print(
(lambda a, x: a.index(x) if a.count(x) else ":(")(
[i * 108 // 100 for i in range(50505)], int(input())
)
)
| Statement
Takahashi bought a piece of apple pie at ABC Confiserie. According to his
memory, he paid N yen (the currency of Japan) for it.
The consumption tax rate for foods in this shop is 8 percent. That is, to buy
an apple pie priced at X yen before tax, you have to pay X \times 1.08 yen
(rounded down to the nearest integer).
Takahashi forgot the price of his apple pie before tax, X, and wants to know
it again. Write a program that takes N as input and finds X. We assume X is an
integer.
If there are multiple possible values for X, find any one of them. Also,
Takahashi's memory of N, the amount he paid, may be incorrect. If no value
could be X, report that fact. | [{"input": "432", "output": "400\n \n\nIf the apple pie is priced at 400 yen before tax, you have to pay 400 \\times\n1.08 = 432 yen to buy one. \nOtherwise, the amount you have to pay will not be 432 yen.\n\n* * *"}, {"input": "1079", "output": ":(\n \n\nThere is no possible price before tax for which you have to pay 1079 yen with\ntax.\n\n* * *"}, {"input": "1001", "output": "927\n \n\nIf the apple pie is priced 927 yen before tax, by rounding down 927 \\times\n1.08 = 1001.16, you have to pay 1001 yen."}] |
If there are values that could be X, the price of the apple pie before tax,
print any one of them.
If there are multiple such values, printing any one of them will be accepted.
If no value could be X, print `:(`.
* * * | s645252480 | Accepted | p02842 | Input is given from Standard Input in the following format:
N | # -*- coding: utf-8 -*-
import sys
def input():
return sys.stdin.readline().strip()
def list2d(a, b, c):
return [[c] * b for i in range(a)]
def list3d(a, b, c, d):
return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e):
return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1):
return int(-(-x // y))
def INT():
return int(input())
def MAP():
return map(int, input().split())
def LIST(N=None):
return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes():
print("Yes")
def No():
print("No")
def YES():
print("YES")
def NO():
print("NO")
sys.setrecursionlimit(10**9)
INF = 10**18
MOD = 10**9 + 7
N = INT()
x = N / 1.08
if int(int(x) * 1.08) == N:
print(int(x))
elif int(ceil(x) * 1.08) == N:
print(ceil(x))
else:
print(":(")
| Statement
Takahashi bought a piece of apple pie at ABC Confiserie. According to his
memory, he paid N yen (the currency of Japan) for it.
The consumption tax rate for foods in this shop is 8 percent. That is, to buy
an apple pie priced at X yen before tax, you have to pay X \times 1.08 yen
(rounded down to the nearest integer).
Takahashi forgot the price of his apple pie before tax, X, and wants to know
it again. Write a program that takes N as input and finds X. We assume X is an
integer.
If there are multiple possible values for X, find any one of them. Also,
Takahashi's memory of N, the amount he paid, may be incorrect. If no value
could be X, report that fact. | [{"input": "432", "output": "400\n \n\nIf the apple pie is priced at 400 yen before tax, you have to pay 400 \\times\n1.08 = 432 yen to buy one. \nOtherwise, the amount you have to pay will not be 432 yen.\n\n* * *"}, {"input": "1079", "output": ":(\n \n\nThere is no possible price before tax for which you have to pay 1079 yen with\ntax.\n\n* * *"}, {"input": "1001", "output": "927\n \n\nIf the apple pie is priced 927 yen before tax, by rounding down 927 \\times\n1.08 = 1001.16, you have to pay 1001 yen."}] |
If there are values that could be X, the price of the apple pie before tax,
print any one of them.
If there are multiple such values, printing any one of them will be accepted.
If no value could be X, print `:(`.
* * * | s204777320 | Wrong Answer | p02842 | Input is given from Standard Input in the following format:
N | X = int(input())
mod = X % 100
q = int(X // 100)
sum = 0
ans = 0
if q >= 100:
ans = 1
else:
for i in range(0, q + 1):
for j in range(0, q + 1 - i):
for k in range(0, q + 1 - i - j):
for l in range(0, q + 1 - i - k - j):
for m in range(0, q + 1 - i - j - k - l):
sum = i + (2 * j) + (3 * k) + (4 * l) + (5 * m)
if sum == mod:
ans = 1
print(ans)
| Statement
Takahashi bought a piece of apple pie at ABC Confiserie. According to his
memory, he paid N yen (the currency of Japan) for it.
The consumption tax rate for foods in this shop is 8 percent. That is, to buy
an apple pie priced at X yen before tax, you have to pay X \times 1.08 yen
(rounded down to the nearest integer).
Takahashi forgot the price of his apple pie before tax, X, and wants to know
it again. Write a program that takes N as input and finds X. We assume X is an
integer.
If there are multiple possible values for X, find any one of them. Also,
Takahashi's memory of N, the amount he paid, may be incorrect. If no value
could be X, report that fact. | [{"input": "432", "output": "400\n \n\nIf the apple pie is priced at 400 yen before tax, you have to pay 400 \\times\n1.08 = 432 yen to buy one. \nOtherwise, the amount you have to pay will not be 432 yen.\n\n* * *"}, {"input": "1079", "output": ":(\n \n\nThere is no possible price before tax for which you have to pay 1079 yen with\ntax.\n\n* * *"}, {"input": "1001", "output": "927\n \n\nIf the apple pie is priced 927 yen before tax, by rounding down 927 \\times\n1.08 = 1001.16, you have to pay 1001 yen."}] |
For each query, print the pari of the lower bound $l$ ($l = 0, 1, ..., n$) and
upper bound $r$ ($r = 0, 1, ..., n$) separated by a space character in a line. | s116515819 | Accepted | p02454 | The input is given in the following format.
$n$
$a_0 \; a_1 \; ,..., \; a_{n-1}$
$q$
$k_1$
$k_2$
:
$k_q$
The number of elements $n$ and each element $a_i$ are given in the first line
and the second line respectively. In the third line, the number of queries $q$
is given and the following $q$ lines, $q$ integers $k_i$ are given as queries. | # -*- coding: utf-8 -*-
"""
Binary Search - Equal Range
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP2_6_D&lang=jp
"""
from bisect import bisect_left, bisect_right
n = int(input())
A = [int(a) for a in input().split()]
for _ in range(int(input())):
k = int(input())
print(bisect_left(A, k), bisect_right(A, k))
| Equal Range
For a given sequence $A = \\{a_0, a_1, ..., a_{n-1}\\}$ which is sorted by
ascending order, print a pair of the lower bound and the upper bound for a
specific value $k$ given as a query.
* lower bound: the place pointing to the first element greater than or equal to a specific value, or $n$ if there is no such element.
* upper bound: the place pointing to the first element greater than a specific value, or $n$ if there is no such element. | [{"input": "4\n 1 2 2 4\n 3\n 2\n 3\n 5", "output": "1 3\n 3 3\n 4 4"}] |
If the condition can be satisfied, follow the following format. If the
condition cannot be satisfied, print `-1`.
m
d_1 d_2 ... d_m
w_1
w_2
:
w_N
m and d_i are the configurations of the robot arm. Refer to the problem
statement for what each of them means. Here, 1 \leq m \leq 40 and 1 \leq d_i
\leq 10^{12} must hold. Also, m and d_i must all be integers.
w_j is a string of length m that represents the way to bring Joint m of the
robot arm to point (X_j, Y_j). The i-th character of w_j should be one of the
letters `L`, `R`, `D` and `U`, representing the mode of Section i.
* * * | s726843084 | Accepted | p03245 | Input is given from Standard Input in the following format:
N
X_1 Y_1
X_2 Y_2
:
X_N Y_N | ###############################################################################
from sys import stdout
from bisect import bisect_left as binl
from copy import copy, deepcopy
def intin():
input_tuple = input().split()
if len(input_tuple) <= 1:
return int(input_tuple[0])
return tuple(map(int, input_tuple))
def intina():
return [int(i) for i in input().split()]
def intinl(count):
return [intin() for _ in range(count)]
def modadd(x, y):
global mod
return (x + y) % mod
def modmlt(x, y):
global mod
return (x * y) % mod
def lcm(x, y):
while y != 0:
z = x % y
x = y
y = z
return x
def get_divisors(x):
retlist = []
for i in range(1, int(x**0.5) + 3):
if x % i == 0:
retlist.append(i)
retlist.append(x // i)
return retlist
def make_linklist(xylist):
linklist = {}
for a, b in xylist:
linklist.setdefault(a, [])
linklist.setdefault(b, [])
linklist[a].append(b)
linklist[b].append(a)
return linklist
def calc_longest_distance(linklist, v=1):
distance_list = {}
distance_count = 0
distance = 0
vlist_previous = []
vlist = [v]
nodecount = len(linklist)
while distance_count < nodecount:
vlist_next = []
for v in vlist:
distance_list[v] = distance
distance_count += 1
vlist_next.extend(linklist[v])
distance += 1
vlist_to_del = vlist_previous
vlist_previous = vlist
vlist = list(set(vlist_next) - set(vlist_to_del))
max_distance = -1
max_v = None
for v, distance in distance_list.items():
if distance > max_distance:
max_distance = distance
max_v = v
return (max_distance, max_v)
def calc_tree_diameter(linklist, v=1):
_, u = calc_longest_distance(linklist, v)
distance, _ = calc_longest_distance(linklist, u)
return distance
###############################################################################
def main():
n = intin()
xylist = intinl(n)
even_odd = None
uvlist = []
for x, y in xylist:
tmp_even_odd = (x + y) % 2
if even_odd is None:
even_odd = tmp_even_odd
if even_odd != tmp_even_odd:
print(-1)
return
uvlist.append((x + y, x - y))
m = 33 if even_odd else 34
print(m)
dlist = [str(2**i) for i in reversed(list(range(0, 33)))]
if not even_odd:
dlist.append("1")
print(" ".join(dlist))
for u, v in uvlist:
if not even_odd:
u += 1
v += 1
line = ""
if u >= 0 and v >= 0:
line += "R"
if u >= 0 and v < 0:
line += "U"
if u < 0 and v >= 0:
line += "D"
if u < 0 and v < 0:
line += "L"
for i in reversed(list(range(1, 33))):
u_bit = (u >> i) & 1
v_bit = (v >> i) & 1
if u_bit and v_bit:
line += "R"
if u_bit and not v_bit:
line += "U"
if not u_bit and v_bit:
line += "D"
if not u_bit and not v_bit:
line += "L"
if not even_odd:
line += "L"
print(line)
if __name__ == "__main__":
main()
| Statement
Snuke is introducing a **robot arm** with the following properties to his
factory:
* The robot arm consists of m **sections** and m+1 **joints**. The sections are numbered 1, 2, ..., m, and the joints are numbered 0, 1, ..., m. Section i connects Joint i-1 and Joint i. The length of Section i is d_i.
* For each section, its **mode** can be specified individually. There are four modes: `L`, `R`, `D` and `U`. The mode of a section decides the direction of that section. If we consider the factory as a coordinate plane, the position of Joint i will be determined as follows (we denote its coordinates as (x_i, y_i)):
* (x_0, y_0) = (0, 0).
* If the mode of Section i is `L`, (x_{i}, y_{i}) = (x_{i-1} - d_{i}, y_{i-1}).
* If the mode of Section i is `R`, (x_{i}, y_{i}) = (x_{i-1} + d_{i}, y_{i-1}).
* If the mode of Section i is `D`, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} - d_{i}).
* If the mode of Section i is `U`, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} + d_{i}).
Snuke would like to introduce a robot arm so that the position of Joint m can
be matched with all of the N points (X_1, Y_1), (X_2, Y_2), ..., (X_N, Y_N) by
properly specifying the modes of the sections. Is this possible? If so, find
such a robot arm and how to bring Joint m to each point (X_j, Y_j). | [{"input": "3\n -1 0\n 0 3\n 2 -1", "output": "2\n 1 2\n RL\n UU\n DR\n \n\nIn the given way to bring Joint m of the robot arm to each (X_j, Y_j), the\npositions of the joints will be as follows:\n\n * To (X_1, Y_1) = (-1, 0): First, the position of Joint 0 is (x_0, y_0) = (0, 0). As the mode of Section 1 is `R`, the position of Joint 1 is (x_1, y_1) = (1, 0). Then, as the mode of Section 2 is `L`, the position of Joint 2 is (x_2, y_2) = (-1, 0).\n * To (X_2, Y_2) = (0, 3): (x_0, y_0) = (0, 0), (x_1, y_1) = (0, 1), (x_2, y_2) = (0, 3).\n * To (X_3, Y_3) = (2, -1): (x_0, y_0) = (0, 0), (x_1, y_1) = (0, -1), (x_2, y_2) = (2, -1).\n\n* * *"}, {"input": "5\n 0 0\n 1 0\n 2 0\n 3 0\n 4 0", "output": "-1\n \n\n* * *"}, {"input": "2\n 1 1\n 1 1", "output": "2\n 1 1\n RU\n UR\n \n\nThere may be duplicated points among (X_j, Y_j).\n\n* * *"}, {"input": "3\n -7 -3\n 7 3\n -3 -7", "output": "5\n 3 1 4 1 5\n LRDUL\n RDULR\n DULRD"}] |
If the condition can be satisfied, follow the following format. If the
condition cannot be satisfied, print `-1`.
m
d_1 d_2 ... d_m
w_1
w_2
:
w_N
m and d_i are the configurations of the robot arm. Refer to the problem
statement for what each of them means. Here, 1 \leq m \leq 40 and 1 \leq d_i
\leq 10^{12} must hold. Also, m and d_i must all be integers.
w_j is a string of length m that represents the way to bring Joint m of the
robot arm to point (X_j, Y_j). The i-th character of w_j should be one of the
letters `L`, `R`, `D` and `U`, representing the mode of Section i.
* * * | s937282355 | Accepted | p03245 | Input is given from Standard Input in the following format:
N
X_1 Y_1
X_2 Y_2
:
X_N Y_N | import os
import sys
import numpy as np
if os.getenv("LOCAL"):
sys.stdin = open("_in.txt", "r")
sys.setrecursionlimit(10**9)
INF = float("inf")
IINF = 10**18
MOD = 10**9 + 7
# MOD = 998244353
N = int(sys.stdin.buffer.readline())
XY = [list(map(int, sys.stdin.buffer.readline().split())) for _ in range(N)]
# マンハッタン距離の偶奇は全部同じじゃないとだめ
x, y = XY[0]
odd = (abs(x) + abs(y)) % 2
ok = True
for x, y in XY:
ok &= (abs(x) + abs(y)) % 2 == odd
if not ok:
print(-1)
exit()
def solve(x):
# a + b = 2^39 - 1
# a - b = x
# とおいて a を求める
# 2a = 2^39 - 1 + x
n = int((2**39 - 1 + x) // 2)
ret = []
for _ in range(39):
if n & 1:
ret.append(1)
else:
ret.append(-1)
n >>= 1
ret = np.array(ret, dtype=int)
return ret
P = [complex(x, y) for x, y in XY]
P = np.array(P)
# マンハッタン距離を奇数にする
# 原点を (-1, 0) だけずらす
if not odd:
P -= 1
# 45度回転してみる
# アームの長さが決まってるとき、xとyについて独立にプラスマイナスを決められるようになる
P *= 1 + 1j
D = (2 ** np.arange(39, dtype=int)).tolist()
ans = []
for p in P:
xd = solve(p.real)
yd = solve(p.imag)
W = np.empty_like(D, dtype="U1")
W[(xd > 0) & (yd > 0)] = "R"
W[(xd > 0) & (yd < 0)] = "D"
W[(xd < 0) & (yd > 0)] = "U"
W[(xd < 0) & (yd < 0)] = "L"
ans.append("".join(W))
if not odd:
D.append(1)
for i in range(len(ans)):
ans[i] += "R"
print(len(D))
print(*D)
print(*ans, sep="\n")
| Statement
Snuke is introducing a **robot arm** with the following properties to his
factory:
* The robot arm consists of m **sections** and m+1 **joints**. The sections are numbered 1, 2, ..., m, and the joints are numbered 0, 1, ..., m. Section i connects Joint i-1 and Joint i. The length of Section i is d_i.
* For each section, its **mode** can be specified individually. There are four modes: `L`, `R`, `D` and `U`. The mode of a section decides the direction of that section. If we consider the factory as a coordinate plane, the position of Joint i will be determined as follows (we denote its coordinates as (x_i, y_i)):
* (x_0, y_0) = (0, 0).
* If the mode of Section i is `L`, (x_{i}, y_{i}) = (x_{i-1} - d_{i}, y_{i-1}).
* If the mode of Section i is `R`, (x_{i}, y_{i}) = (x_{i-1} + d_{i}, y_{i-1}).
* If the mode of Section i is `D`, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} - d_{i}).
* If the mode of Section i is `U`, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} + d_{i}).
Snuke would like to introduce a robot arm so that the position of Joint m can
be matched with all of the N points (X_1, Y_1), (X_2, Y_2), ..., (X_N, Y_N) by
properly specifying the modes of the sections. Is this possible? If so, find
such a robot arm and how to bring Joint m to each point (X_j, Y_j). | [{"input": "3\n -1 0\n 0 3\n 2 -1", "output": "2\n 1 2\n RL\n UU\n DR\n \n\nIn the given way to bring Joint m of the robot arm to each (X_j, Y_j), the\npositions of the joints will be as follows:\n\n * To (X_1, Y_1) = (-1, 0): First, the position of Joint 0 is (x_0, y_0) = (0, 0). As the mode of Section 1 is `R`, the position of Joint 1 is (x_1, y_1) = (1, 0). Then, as the mode of Section 2 is `L`, the position of Joint 2 is (x_2, y_2) = (-1, 0).\n * To (X_2, Y_2) = (0, 3): (x_0, y_0) = (0, 0), (x_1, y_1) = (0, 1), (x_2, y_2) = (0, 3).\n * To (X_3, Y_3) = (2, -1): (x_0, y_0) = (0, 0), (x_1, y_1) = (0, -1), (x_2, y_2) = (2, -1).\n\n* * *"}, {"input": "5\n 0 0\n 1 0\n 2 0\n 3 0\n 4 0", "output": "-1\n \n\n* * *"}, {"input": "2\n 1 1\n 1 1", "output": "2\n 1 1\n RU\n UR\n \n\nThere may be duplicated points among (X_j, Y_j).\n\n* * *"}, {"input": "3\n -7 -3\n 7 3\n -3 -7", "output": "5\n 3 1 4 1 5\n LRDUL\n RDULR\n DULRD"}] |
If the condition can be satisfied, follow the following format. If the
condition cannot be satisfied, print `-1`.
m
d_1 d_2 ... d_m
w_1
w_2
:
w_N
m and d_i are the configurations of the robot arm. Refer to the problem
statement for what each of them means. Here, 1 \leq m \leq 40 and 1 \leq d_i
\leq 10^{12} must hold. Also, m and d_i must all be integers.
w_j is a string of length m that represents the way to bring Joint m of the
robot arm to point (X_j, Y_j). The i-th character of w_j should be one of the
letters `L`, `R`, `D` and `U`, representing the mode of Section i.
* * * | s302901199 | Runtime Error | p03245 | Input is given from Standard Input in the following format:
N
X_1 Y_1
X_2 Y_2
:
X_N Y_N | def main():
n = int(input())
px, py = [0] * n, [0] * n
for i in range(n):
px[i], py[i] = map(int, input().split())
for i in range(1, n):
if (px[0] + py[0]) % 2 != (px[i] + py[i]) % 2:
print(-1)
exit()
print(40)
arms = ["1"] * 40
if (px[0] + py[0]) % 2:
arms[39] = "2"
print(" ".join(arms))
for i, j in zip(px, py):
order, idx = [""] * 40, 0
for k in range(abs(i)):
if 0 <= i:
order[idx] = "R"
else:
order[idx] = "L"
idx += 1
for k in range(abs(j)):
if 0 <= j:
order[idx] = "U"
else:
order[idx] = "D"
idx += 1
cnt = 40 - abs(i) - abs(j)
for k in range((cnt + 1) // 2):
order[idx] = "U"
idx += 1
for k in range(cnt // 2):
order[idx] = "D"
idx += 1
print("".join(order))
if __name__ == "__main__":
main()
| Statement
Snuke is introducing a **robot arm** with the following properties to his
factory:
* The robot arm consists of m **sections** and m+1 **joints**. The sections are numbered 1, 2, ..., m, and the joints are numbered 0, 1, ..., m. Section i connects Joint i-1 and Joint i. The length of Section i is d_i.
* For each section, its **mode** can be specified individually. There are four modes: `L`, `R`, `D` and `U`. The mode of a section decides the direction of that section. If we consider the factory as a coordinate plane, the position of Joint i will be determined as follows (we denote its coordinates as (x_i, y_i)):
* (x_0, y_0) = (0, 0).
* If the mode of Section i is `L`, (x_{i}, y_{i}) = (x_{i-1} - d_{i}, y_{i-1}).
* If the mode of Section i is `R`, (x_{i}, y_{i}) = (x_{i-1} + d_{i}, y_{i-1}).
* If the mode of Section i is `D`, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} - d_{i}).
* If the mode of Section i is `U`, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} + d_{i}).
Snuke would like to introduce a robot arm so that the position of Joint m can
be matched with all of the N points (X_1, Y_1), (X_2, Y_2), ..., (X_N, Y_N) by
properly specifying the modes of the sections. Is this possible? If so, find
such a robot arm and how to bring Joint m to each point (X_j, Y_j). | [{"input": "3\n -1 0\n 0 3\n 2 -1", "output": "2\n 1 2\n RL\n UU\n DR\n \n\nIn the given way to bring Joint m of the robot arm to each (X_j, Y_j), the\npositions of the joints will be as follows:\n\n * To (X_1, Y_1) = (-1, 0): First, the position of Joint 0 is (x_0, y_0) = (0, 0). As the mode of Section 1 is `R`, the position of Joint 1 is (x_1, y_1) = (1, 0). Then, as the mode of Section 2 is `L`, the position of Joint 2 is (x_2, y_2) = (-1, 0).\n * To (X_2, Y_2) = (0, 3): (x_0, y_0) = (0, 0), (x_1, y_1) = (0, 1), (x_2, y_2) = (0, 3).\n * To (X_3, Y_3) = (2, -1): (x_0, y_0) = (0, 0), (x_1, y_1) = (0, -1), (x_2, y_2) = (2, -1).\n\n* * *"}, {"input": "5\n 0 0\n 1 0\n 2 0\n 3 0\n 4 0", "output": "-1\n \n\n* * *"}, {"input": "2\n 1 1\n 1 1", "output": "2\n 1 1\n RU\n UR\n \n\nThere may be duplicated points among (X_j, Y_j).\n\n* * *"}, {"input": "3\n -7 -3\n 7 3\n -3 -7", "output": "5\n 3 1 4 1 5\n LRDUL\n RDULR\n DULRD"}] |
If the condition can be satisfied, follow the following format. If the
condition cannot be satisfied, print `-1`.
m
d_1 d_2 ... d_m
w_1
w_2
:
w_N
m and d_i are the configurations of the robot arm. Refer to the problem
statement for what each of them means. Here, 1 \leq m \leq 40 and 1 \leq d_i
\leq 10^{12} must hold. Also, m and d_i must all be integers.
w_j is a string of length m that represents the way to bring Joint m of the
robot arm to point (X_j, Y_j). The i-th character of w_j should be one of the
letters `L`, `R`, `D` and `U`, representing the mode of Section i.
* * * | s295786921 | Wrong Answer | p03245 | Input is given from Standard Input in the following format:
N
X_1 Y_1
X_2 Y_2
:
X_N Y_N | print(-1)
| Statement
Snuke is introducing a **robot arm** with the following properties to his
factory:
* The robot arm consists of m **sections** and m+1 **joints**. The sections are numbered 1, 2, ..., m, and the joints are numbered 0, 1, ..., m. Section i connects Joint i-1 and Joint i. The length of Section i is d_i.
* For each section, its **mode** can be specified individually. There are four modes: `L`, `R`, `D` and `U`. The mode of a section decides the direction of that section. If we consider the factory as a coordinate plane, the position of Joint i will be determined as follows (we denote its coordinates as (x_i, y_i)):
* (x_0, y_0) = (0, 0).
* If the mode of Section i is `L`, (x_{i}, y_{i}) = (x_{i-1} - d_{i}, y_{i-1}).
* If the mode of Section i is `R`, (x_{i}, y_{i}) = (x_{i-1} + d_{i}, y_{i-1}).
* If the mode of Section i is `D`, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} - d_{i}).
* If the mode of Section i is `U`, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} + d_{i}).
Snuke would like to introduce a robot arm so that the position of Joint m can
be matched with all of the N points (X_1, Y_1), (X_2, Y_2), ..., (X_N, Y_N) by
properly specifying the modes of the sections. Is this possible? If so, find
such a robot arm and how to bring Joint m to each point (X_j, Y_j). | [{"input": "3\n -1 0\n 0 3\n 2 -1", "output": "2\n 1 2\n RL\n UU\n DR\n \n\nIn the given way to bring Joint m of the robot arm to each (X_j, Y_j), the\npositions of the joints will be as follows:\n\n * To (X_1, Y_1) = (-1, 0): First, the position of Joint 0 is (x_0, y_0) = (0, 0). As the mode of Section 1 is `R`, the position of Joint 1 is (x_1, y_1) = (1, 0). Then, as the mode of Section 2 is `L`, the position of Joint 2 is (x_2, y_2) = (-1, 0).\n * To (X_2, Y_2) = (0, 3): (x_0, y_0) = (0, 0), (x_1, y_1) = (0, 1), (x_2, y_2) = (0, 3).\n * To (X_3, Y_3) = (2, -1): (x_0, y_0) = (0, 0), (x_1, y_1) = (0, -1), (x_2, y_2) = (2, -1).\n\n* * *"}, {"input": "5\n 0 0\n 1 0\n 2 0\n 3 0\n 4 0", "output": "-1\n \n\n* * *"}, {"input": "2\n 1 1\n 1 1", "output": "2\n 1 1\n RU\n UR\n \n\nThere may be duplicated points among (X_j, Y_j).\n\n* * *"}, {"input": "3\n -7 -3\n 7 3\n -3 -7", "output": "5\n 3 1 4 1 5\n LRDUL\n RDULR\n DULRD"}] |
If the condition can be satisfied, follow the following format. If the
condition cannot be satisfied, print `-1`.
m
d_1 d_2 ... d_m
w_1
w_2
:
w_N
m and d_i are the configurations of the robot arm. Refer to the problem
statement for what each of them means. Here, 1 \leq m \leq 40 and 1 \leq d_i
\leq 10^{12} must hold. Also, m and d_i must all be integers.
w_j is a string of length m that represents the way to bring Joint m of the
robot arm to point (X_j, Y_j). The i-th character of w_j should be one of the
letters `L`, `R`, `D` and `U`, representing the mode of Section i.
* * * | s818779760 | Runtime Error | p03245 | Input is given from Standard Input in the following format:
N
X_1 Y_1
X_2 Y_2
:
X_N Y_N | N = int(input())
XY = [[int(x) for x in input().split()] for _ in range(N)]
def f():
ms = 0
oe = 0
for x, y in XY:
s = abs(x) + abs(y)
a = s % 2
if ms != 0 and oe != a:
print(-1)
return
ms = max(ms, s)
oe = a
if ms == 0:
ms = 2
print(ms)
print("1 " * ms)
for x, y in XY:
s = ""
o = "R" if 0 < x else "L"
s += o * abs(x)
o = "U" if 0 < y else "D"
s += o * abs(y)
s += "UD" * ((ms - abs(x) - abs(y)) // 2)
print(s)
f()
| Statement
Snuke is introducing a **robot arm** with the following properties to his
factory:
* The robot arm consists of m **sections** and m+1 **joints**. The sections are numbered 1, 2, ..., m, and the joints are numbered 0, 1, ..., m. Section i connects Joint i-1 and Joint i. The length of Section i is d_i.
* For each section, its **mode** can be specified individually. There are four modes: `L`, `R`, `D` and `U`. The mode of a section decides the direction of that section. If we consider the factory as a coordinate plane, the position of Joint i will be determined as follows (we denote its coordinates as (x_i, y_i)):
* (x_0, y_0) = (0, 0).
* If the mode of Section i is `L`, (x_{i}, y_{i}) = (x_{i-1} - d_{i}, y_{i-1}).
* If the mode of Section i is `R`, (x_{i}, y_{i}) = (x_{i-1} + d_{i}, y_{i-1}).
* If the mode of Section i is `D`, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} - d_{i}).
* If the mode of Section i is `U`, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} + d_{i}).
Snuke would like to introduce a robot arm so that the position of Joint m can
be matched with all of the N points (X_1, Y_1), (X_2, Y_2), ..., (X_N, Y_N) by
properly specifying the modes of the sections. Is this possible? If so, find
such a robot arm and how to bring Joint m to each point (X_j, Y_j). | [{"input": "3\n -1 0\n 0 3\n 2 -1", "output": "2\n 1 2\n RL\n UU\n DR\n \n\nIn the given way to bring Joint m of the robot arm to each (X_j, Y_j), the\npositions of the joints will be as follows:\n\n * To (X_1, Y_1) = (-1, 0): First, the position of Joint 0 is (x_0, y_0) = (0, 0). As the mode of Section 1 is `R`, the position of Joint 1 is (x_1, y_1) = (1, 0). Then, as the mode of Section 2 is `L`, the position of Joint 2 is (x_2, y_2) = (-1, 0).\n * To (X_2, Y_2) = (0, 3): (x_0, y_0) = (0, 0), (x_1, y_1) = (0, 1), (x_2, y_2) = (0, 3).\n * To (X_3, Y_3) = (2, -1): (x_0, y_0) = (0, 0), (x_1, y_1) = (0, -1), (x_2, y_2) = (2, -1).\n\n* * *"}, {"input": "5\n 0 0\n 1 0\n 2 0\n 3 0\n 4 0", "output": "-1\n \n\n* * *"}, {"input": "2\n 1 1\n 1 1", "output": "2\n 1 1\n RU\n UR\n \n\nThere may be duplicated points among (X_j, Y_j).\n\n* * *"}, {"input": "3\n -7 -3\n 7 3\n -3 -7", "output": "5\n 3 1 4 1 5\n LRDUL\n RDULR\n DULRD"}] |
If the condition can be satisfied, follow the following format. If the
condition cannot be satisfied, print `-1`.
m
d_1 d_2 ... d_m
w_1
w_2
:
w_N
m and d_i are the configurations of the robot arm. Refer to the problem
statement for what each of them means. Here, 1 \leq m \leq 40 and 1 \leq d_i
\leq 10^{12} must hold. Also, m and d_i must all be integers.
w_j is a string of length m that represents the way to bring Joint m of the
robot arm to point (X_j, Y_j). The i-th character of w_j should be one of the
letters `L`, `R`, `D` and `U`, representing the mode of Section i.
* * * | s946487922 | Wrong Answer | p03245 | Input is given from Standard Input in the following format:
N
X_1 Y_1
X_2 Y_2
:
X_N Y_N | """
# keywords
Counter
# impression
Counterを使わない場合、処理を間違えずに書くのに以外と苦労
"""
import sys
IS = lambda: sys.stdin.readline().rstrip()
II = lambda: int(IS())
MII = lambda: list(map(int, IS().split()))
from collections import Counter
def main():
n = II()
vv = MII()
ee = Counter(vv[0::2])
oo = Counter(vv[1::2])
minv = 10**5
ee1 = ee.most_common()[0]
oo1 = oo.most_common()[0]
if ee1[0] != oo1[0]:
minv = min(minv, n - (ee1[1] + oo1[1]))
else:
ee2 = ee.most_common()[1] if len(ee) > 1 else (0, 0)
oo2 = oo.most_common()[1] if len(oo) > 1 else (0, 0)
minv = min(minv, n - (ee1[1] + oo2[1]))
minv = min(minv, n - (ee2[1] + oo1[1]))
print(minv)
if __name__ == "__main__":
main()
| Statement
Snuke is introducing a **robot arm** with the following properties to his
factory:
* The robot arm consists of m **sections** and m+1 **joints**. The sections are numbered 1, 2, ..., m, and the joints are numbered 0, 1, ..., m. Section i connects Joint i-1 and Joint i. The length of Section i is d_i.
* For each section, its **mode** can be specified individually. There are four modes: `L`, `R`, `D` and `U`. The mode of a section decides the direction of that section. If we consider the factory as a coordinate plane, the position of Joint i will be determined as follows (we denote its coordinates as (x_i, y_i)):
* (x_0, y_0) = (0, 0).
* If the mode of Section i is `L`, (x_{i}, y_{i}) = (x_{i-1} - d_{i}, y_{i-1}).
* If the mode of Section i is `R`, (x_{i}, y_{i}) = (x_{i-1} + d_{i}, y_{i-1}).
* If the mode of Section i is `D`, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} - d_{i}).
* If the mode of Section i is `U`, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} + d_{i}).
Snuke would like to introduce a robot arm so that the position of Joint m can
be matched with all of the N points (X_1, Y_1), (X_2, Y_2), ..., (X_N, Y_N) by
properly specifying the modes of the sections. Is this possible? If so, find
such a robot arm and how to bring Joint m to each point (X_j, Y_j). | [{"input": "3\n -1 0\n 0 3\n 2 -1", "output": "2\n 1 2\n RL\n UU\n DR\n \n\nIn the given way to bring Joint m of the robot arm to each (X_j, Y_j), the\npositions of the joints will be as follows:\n\n * To (X_1, Y_1) = (-1, 0): First, the position of Joint 0 is (x_0, y_0) = (0, 0). As the mode of Section 1 is `R`, the position of Joint 1 is (x_1, y_1) = (1, 0). Then, as the mode of Section 2 is `L`, the position of Joint 2 is (x_2, y_2) = (-1, 0).\n * To (X_2, Y_2) = (0, 3): (x_0, y_0) = (0, 0), (x_1, y_1) = (0, 1), (x_2, y_2) = (0, 3).\n * To (X_3, Y_3) = (2, -1): (x_0, y_0) = (0, 0), (x_1, y_1) = (0, -1), (x_2, y_2) = (2, -1).\n\n* * *"}, {"input": "5\n 0 0\n 1 0\n 2 0\n 3 0\n 4 0", "output": "-1\n \n\n* * *"}, {"input": "2\n 1 1\n 1 1", "output": "2\n 1 1\n RU\n UR\n \n\nThere may be duplicated points among (X_j, Y_j).\n\n* * *"}, {"input": "3\n -7 -3\n 7 3\n -3 -7", "output": "5\n 3 1 4 1 5\n LRDUL\n RDULR\n DULRD"}] |
Print the sum of all the scores modulo 998244353.
* * * | s268324206 | Accepted | p03615 | The input is given from Standard Input in the following format:
N
x_1 y_1
x_2 y_2
:
x_N y_N | from fractions import Fraction
from collections import defaultdict
from itertools import combinations
class Combination:
"""
O(n)の前計算を1回行うことで,O(1)でnCr mod mを求められる
n_max = 10**6のとき前処理は約950ms (PyPyなら約340ms, 10**7で約1800ms)
使用例:
comb = Combination(1000000)
print(comb(5, 3)) # 10
"""
def __init__(self, n_max, mod=10**9 + 7):
self.mod = mod
self.modinv = self.make_modinv_list(n_max)
self.fac, self.facinv = self.make_factorial_list(n_max)
def __call__(self, n, r):
return self.fac[n] * self.facinv[r] % self.mod * self.facinv[n - r] % self.mod
def make_factorial_list(self, n):
# 階乗のリストと階乗のmod逆元のリストを返す O(n)
# self.make_modinv_list()が先に実行されている必要がある
fac = [1]
facinv = [1]
for i in range(1, n + 1):
fac.append(fac[i - 1] * i % self.mod)
facinv.append(facinv[i - 1] * self.modinv[i] % self.mod)
return fac, facinv
def make_modinv_list(self, n):
# 0からnまでのmod逆元のリストを返す O(n)
modinv = [0] * (n + 1)
modinv[1] = 1
for i in range(2, n + 1):
modinv[i] = self.mod - self.mod // i * modinv[self.mod % i] % self.mod
return modinv
N = int(input())
XY = [list(map(int, input().split())) for i in range(N)]
D = defaultdict(int)
for (x1, y1), (x2, y2) in combinations(XY, 2):
if x1 != x2:
a = Fraction(y2 - y1, x2 - x1)
b = Fraction(y1) - a * Fraction(x1)
D[(a, b)] += 1
else:
D[(None, x1)] += 1
mod = 998244353
comb = Combination(N + 1, mod)
A = [0] * (N + 1)
coA = [0] * (N + 1)
ans = 0
for i in range(3, N + 1):
ans += comb(N, i)
ans %= mod
for i in range(3, N + 1):
for j in range(i - 2):
A[i] += (i - 2 - j) * (1 << j)
coA[i] = coA[i - 1] + A[i]
for (a, b), n in D.items():
if n == 1:
continue
n = int((n << 1) ** 0.5) + 1
ans -= coA[n]
ans %= mod
print(ans)
| Statement
You are given N points (x_i,y_i) located on a two-dimensional plane. Consider
a subset S of the N points that forms a convex polygon. Here, we say a set of
points S _forms a convex polygon_ when there exists a convex polygon with a
positive area that has the same set of vertices as S. All the interior angles
of the polygon must be strictly less than 180°.

For example, in the figure above, {A,C,E} and {B,D,E} form convex polygons;
{A,C,D,E}, {A,B,C,E}, {A,B,C}, {D,E} and {} do not.
For a given set S, let n be the number of the points among the N points that
are inside the convex hull of S (including the boundary and vertices). Then,
we will define the _score_ of S as 2^{n-|S|}.
Compute the scores of all possible sets S that form convex polygons, and find
the sum of all those scores.
However, since the sum can be extremely large, print the sum modulo 998244353. | [{"input": "4\n 0 0\n 0 1\n 1 0\n 1 1", "output": "5\n \n\nWe have five possible sets as S, four sets that form triangles and one set\nthat forms a square. Each of them has a score of 2^0=1, so the answer is 5.\n\n* * *"}, {"input": "5\n 0 0\n 0 1\n 0 2\n 0 3\n 1 1", "output": "11\n \n\nWe have three \"triangles\" with a score of 1 each, two \"triangles\" with a score\nof 2 each, and one \"triangle\" with a score of 4. Thus, the answer is 11.\n\n* * *"}, {"input": "1\n 3141 2718", "output": "0\n \n\nThere are no possible set as S, so the answer is 0."}] |
Print the sum of all the scores modulo 998244353.
* * * | s300815550 | Runtime Error | p03615 | The input is given from Standard Input in the following format:
N
x_1 y_1
x_2 y_2
:
x_N y_N | import math
import itertools
def read_data():
try:
LOCAL_FLAG
import codecs
import os
lines = []
file_path = os.path.join(os.path.dirname(__file__), "arc082-e.dat")
with codecs.open(file_path, "r", "utf-8") as f:
lines.append(f.readline().rstrip("\r\n"))
N = int(lines[0])
for i in range(N):
lines.append(f.readline().rstrip("\r\n"))
except NameError:
lines = []
lines.append(input())
N = int(lines[0])
for i in range(N):
lines.append(input())
return lines
def isIncluded(ref_points, ref):
min_y = ref_points[0]["y"]
min_index = 0
for i in range(1, len(ref_points)):
if min_y > ref_points[i]["y"]:
min_y = ref_points[i]["y"]
min_index = i
points = []
p = {}
for i in range(len(ref_points)):
data = {}
data["x"] = ref_points[i]["x"] - ref_points[min_index]["x"]
data["y"] = ref_points[i]["y"] - ref_points[min_index]["y"]
data["rad"] = math.atan2(data["y"], data["x"])
points.append(data)
p["x"] = ref["x"] - ref_points[min_index]["x"]
p["y"] = ref["y"] - ref_points[min_index]["y"]
points = sorted(points, key=lambda x: x["rad"])
lines = []
v1 = {}
v2 = {}
Included = True
lines = ((0, 1), (1, 2), (2, 0))
for n in range(3):
v1["x"] = points[lines[n][1]]["x"] - points[lines[n][0]]["x"]
v1["y"] = points[lines[n][1]]["y"] - points[lines[n][0]]["y"]
v2["x"] = p["x"] - points[lines[n][1]]["x"]
v2["y"] = p["y"] - points[lines[n][1]]["y"]
cross = v1["x"] * v2["y"] - v2["x"] * v1["y"]
# print(v1, v2)
# print(cross)
if cross < 0:
return False
if Included:
return True
else:
return False
def isConvex(xy, points):
lines = []
v1 = {}
v2 = {}
N = len(points)
for n in range(N - 1):
lines.append((points[n], points[n + 1]))
lines.append((points[n + 1], points[0]))
lines.append(lines[0])
for n in range(N):
v1["x"] = xy[lines[n][1]]["x"] - xy[lines[n][0]]["x"]
v1["y"] = xy[lines[n][1]]["y"] - xy[lines[n][0]]["y"]
v2["x"] = xy[lines[n + 1][1]]["x"] - xy[lines[n + 1][0]]["x"]
v2["y"] = xy[lines[n + 1][1]]["y"] - xy[lines[n + 1][0]]["y"]
cross = v1["x"] * v2["y"] - v2["x"] * v1["y"]
if cross <= 0:
return False
return True
def sort_by_rad(xy, points):
min_y = xy[points[0]]["y"]
min_index = 0
for i in range(1, len(points)):
if min_y > xy[points[i]]["y"]:
min_y = xy[points[i]]["y"]
min_index = i
new_points = []
for i in range(len(points)):
data = {}
data["x"] = xy[points[i]]["x"] - xy[points[min_index]]["x"]
data["y"] = xy[points[i]]["y"] - xy[points[min_index]]["y"]
data["rad"] = math.atan2(data["y"], data["x"])
data["index"] = points[i]
new_points.append(data)
sort_points = sorted(new_points, key=lambda x: x["rad"])
results = []
for i in range(len(points)):
results.append(sort_points[i]["index"])
return results
def E_ConvexScore():
raw_data = read_data()
xy = []
N = int(raw_data[0])
key_list = ["x", "y"]
min_xy = dict(zip(key_list, list(map(int, raw_data[1].split()))))
max_xy = dict(zip(key_list, list(map(int, raw_data[1].split()))))
index_min = 0
for i in range(N):
xy.append(dict(zip(key_list, list(map(int, raw_data[i + 1].split())))))
xy[i]["rad"] = math.atan2(xy[i]["y"], xy[i]["x"])
xy[i]["d"] = xy[i]["y"] + xy[i]["x"]
xy_d = sorted(xy, key=lambda x: x["d"])
xy_rad = sorted(xy_d, key=lambda x: x["rad"])
xy = xy_rad
included = {}
total_rank = 0
for points in itertools.combinations(range(N), 3):
new_points = sort_by_rad(xy, points)
# print(new_points)
if not isConvex(xy, new_points):
included[points] = set([])
continue
count = 0
index_included = []
for i in range(points[0] + 1, points[2]):
if i in points:
continue
elif isIncluded(list([xy[points[0]], xy[points[1]], xy[points[2]]]), xy[i]):
count += 1
index_included.append(i)
included[points] = set(index_included)
# print(count)
total_rank += pow(2, count)
# print(included)
for i in range(4, N + 1):
for points in itertools.combinations(range(N), i):
new_points = sort_by_rad(xy, points)
if not isConvex(xy, new_points):
continue
# print(new_points)
count_set = set([])
for j in range(i - 2):
triangle = (new_points[0], new_points[j + 1], new_points[j + 2])
count_set = count_set ^ included[triangle]
# print(count_set)
total_rank += pow(2, len(count_set))
print(total_rank)
E_ConvexScore()
| Statement
You are given N points (x_i,y_i) located on a two-dimensional plane. Consider
a subset S of the N points that forms a convex polygon. Here, we say a set of
points S _forms a convex polygon_ when there exists a convex polygon with a
positive area that has the same set of vertices as S. All the interior angles
of the polygon must be strictly less than 180°.

For example, in the figure above, {A,C,E} and {B,D,E} form convex polygons;
{A,C,D,E}, {A,B,C,E}, {A,B,C}, {D,E} and {} do not.
For a given set S, let n be the number of the points among the N points that
are inside the convex hull of S (including the boundary and vertices). Then,
we will define the _score_ of S as 2^{n-|S|}.
Compute the scores of all possible sets S that form convex polygons, and find
the sum of all those scores.
However, since the sum can be extremely large, print the sum modulo 998244353. | [{"input": "4\n 0 0\n 0 1\n 1 0\n 1 1", "output": "5\n \n\nWe have five possible sets as S, four sets that form triangles and one set\nthat forms a square. Each of them has a score of 2^0=1, so the answer is 5.\n\n* * *"}, {"input": "5\n 0 0\n 0 1\n 0 2\n 0 3\n 1 1", "output": "11\n \n\nWe have three \"triangles\" with a score of 1 each, two \"triangles\" with a score\nof 2 each, and one \"triangle\" with a score of 4. Thus, the answer is 11.\n\n* * *"}, {"input": "1\n 3141 2718", "output": "0\n \n\nThere are no possible set as S, so the answer is 0."}] |
Print the sum of all the scores modulo 998244353.
* * * | s589195155 | Runtime Error | p03615 | The input is given from Standard Input in the following format:
N
x_1 y_1
x_2 y_2
:
x_N y_N | 4
0 0
0 1
1 0
1 1
| Statement
You are given N points (x_i,y_i) located on a two-dimensional plane. Consider
a subset S of the N points that forms a convex polygon. Here, we say a set of
points S _forms a convex polygon_ when there exists a convex polygon with a
positive area that has the same set of vertices as S. All the interior angles
of the polygon must be strictly less than 180°.

For example, in the figure above, {A,C,E} and {B,D,E} form convex polygons;
{A,C,D,E}, {A,B,C,E}, {A,B,C}, {D,E} and {} do not.
For a given set S, let n be the number of the points among the N points that
are inside the convex hull of S (including the boundary and vertices). Then,
we will define the _score_ of S as 2^{n-|S|}.
Compute the scores of all possible sets S that form convex polygons, and find
the sum of all those scores.
However, since the sum can be extremely large, print the sum modulo 998244353. | [{"input": "4\n 0 0\n 0 1\n 1 0\n 1 1", "output": "5\n \n\nWe have five possible sets as S, four sets that form triangles and one set\nthat forms a square. Each of them has a score of 2^0=1, so the answer is 5.\n\n* * *"}, {"input": "5\n 0 0\n 0 1\n 0 2\n 0 3\n 1 1", "output": "11\n \n\nWe have three \"triangles\" with a score of 1 each, two \"triangles\" with a score\nof 2 each, and one \"triangle\" with a score of 4. Thus, the answer is 11.\n\n* * *"}, {"input": "1\n 3141 2718", "output": "0\n \n\nThere are no possible set as S, so the answer is 0."}] |
Print the properties of the binary heap in the above format from node $1$ to
$H$ in order. _Note that, the last character of each line is a single space
character._ | s845780693 | Accepted | p02287 | In the first line, an integer $H$, the size of the binary heap, is given. In
the second line, $H$ integers which correspond to values assigned to nodes of
the binary heap are given in order of node id (from $1$ to $H$). | H = int(input())
A = list(map(int, input().split()))
for i in range(H):
s = f"node {i + 1}: key = {A[i]}, "
if i != 0:
s += f"parent key = {A[(i - 1) // 2]}, "
if H > i * 2 + 1:
s += f"left key = {A[i * 2 + 1]}, "
if H > i * 2 + 2:
s += f"right key = {A[i * 2 + 2]}, "
print(s)
| Complete Binary Tree
A complete binary tree is a binary tree in which every internal node has two
children and all leaves have the same depth. A binary tree in which if last
level is not completely filled but all nodes (leaves) are pushed across to the
left, is also (nearly) a complete binary tree.
A binary heap data structure is an array that can be viewed as a nearly
complete binary tree as shown in the following figure.

Each node of a nearly complete binary tree corresponds to an element of the
array that stores the value in the node. An array $A$ that represents a binary
heap has the heap size $H$, the number of elements in the heap, and each
element of the binary heap is stored into $A[1...H]$ respectively. The root of
the tree is $A[1]$, and given the index $i$ of a node, the indices of its
parent $parent(i)$, left child $left(i)$, right child $right(i)$ can be
computed simply by $\lfloor i / 2 \rfloor$, $2 \times i$ and $2 \times i + 1$
respectively.
Write a program which reads a binary heap represented by a nearly complete
binary tree, and prints properties of nodes of the binary heap in the
following format:
node $id$: key = $k$, parent key = $pk$, left key = $lk$, right key = $rk$,
$id$, $k$, $pk$, $lk$ and $rk$ represent id (index) of the node, value of the
node, value of its parent, value of its left child and value of its right
child respectively. Print these properties in this order. If there are no
appropriate nodes, print nothing. | [{"input": "5\n 7 8 1 2 3", "output": "node 1: key = 7, left key = 8, right key = 1, \n node 2: key = 8, parent key = 7, left key = 2, right key = 3, \n node 3: key = 1, parent key = 7, \n node 4: key = 2, parent key = 8, \n node 5: key = 3, parent key = 8,"}] |
Print the properties of the binary heap in the above format from node $1$ to
$H$ in order. _Note that, the last character of each line is a single space
character._ | s281146087 | Accepted | p02287 | In the first line, an integer $H$, the size of the binary heap, is given. In
the second line, $H$ integers which correspond to values assigned to nodes of
the binary heap are given in order of node id (from $1$ to $H$). | h = int(input())
a = list(map(lambda x: int(x), input().split()))
for i in range(1, h + 1):
key = a[i - 1]
print("node {0}: key = {1}, ".format(i, key), end="")
if i != 1:
parentindex = i // 2
parentkey = a[parentindex - 1]
print("parent key = {0}, ".format(parentkey), end="")
leftindex = 2 * i
if leftindex <= h:
leftkey = a[leftindex - 1]
print("left key = {0}, ".format(leftkey), end="")
rightindex = 2 * i + 1
if rightindex <= h:
rightkey = a[rightindex - 1]
print("right key = {0}, ".format(rightkey), end="")
print()
| Complete Binary Tree
A complete binary tree is a binary tree in which every internal node has two
children and all leaves have the same depth. A binary tree in which if last
level is not completely filled but all nodes (leaves) are pushed across to the
left, is also (nearly) a complete binary tree.
A binary heap data structure is an array that can be viewed as a nearly
complete binary tree as shown in the following figure.

Each node of a nearly complete binary tree corresponds to an element of the
array that stores the value in the node. An array $A$ that represents a binary
heap has the heap size $H$, the number of elements in the heap, and each
element of the binary heap is stored into $A[1...H]$ respectively. The root of
the tree is $A[1]$, and given the index $i$ of a node, the indices of its
parent $parent(i)$, left child $left(i)$, right child $right(i)$ can be
computed simply by $\lfloor i / 2 \rfloor$, $2 \times i$ and $2 \times i + 1$
respectively.
Write a program which reads a binary heap represented by a nearly complete
binary tree, and prints properties of nodes of the binary heap in the
following format:
node $id$: key = $k$, parent key = $pk$, left key = $lk$, right key = $rk$,
$id$, $k$, $pk$, $lk$ and $rk$ represent id (index) of the node, value of the
node, value of its parent, value of its left child and value of its right
child respectively. Print these properties in this order. If there are no
appropriate nodes, print nothing. | [{"input": "5\n 7 8 1 2 3", "output": "node 1: key = 7, left key = 8, right key = 1, \n node 2: key = 8, parent key = 7, left key = 2, right key = 3, \n node 3: key = 1, parent key = 7, \n node 4: key = 2, parent key = 8, \n node 5: key = 3, parent key = 8,"}] |
Print the properties of the binary heap in the above format from node $1$ to
$H$ in order. _Note that, the last character of each line is a single space
character._ | s780727589 | Accepted | p02287 | In the first line, an integer $H$, the size of the binary heap, is given. In
the second line, $H$ integers which correspond to values assigned to nodes of
the binary heap are given in order of node id (from $1$ to $H$). | n = int(input())
A = [""]
A += [int(i) for i in input().split()]
# print(A)
for i in range(1, len(A)):
print("node {}: key = {},".format(i, A[i]), end=" ")
if i != 1:
print("parent key = {},".format(A[i // 2]), end=" ")
if 2 * i + 1 < len(A):
print("left key = {}, right key = {},".format(A[2 * i], A[2 * i + 1]), end=" ")
elif 2 * i + 1 == len(A):
print("left key = {},".format(A[2 * i]), end=" ")
print("")
"""
5
7 8 1 2 3
"""
| Complete Binary Tree
A complete binary tree is a binary tree in which every internal node has two
children and all leaves have the same depth. A binary tree in which if last
level is not completely filled but all nodes (leaves) are pushed across to the
left, is also (nearly) a complete binary tree.
A binary heap data structure is an array that can be viewed as a nearly
complete binary tree as shown in the following figure.

Each node of a nearly complete binary tree corresponds to an element of the
array that stores the value in the node. An array $A$ that represents a binary
heap has the heap size $H$, the number of elements in the heap, and each
element of the binary heap is stored into $A[1...H]$ respectively. The root of
the tree is $A[1]$, and given the index $i$ of a node, the indices of its
parent $parent(i)$, left child $left(i)$, right child $right(i)$ can be
computed simply by $\lfloor i / 2 \rfloor$, $2 \times i$ and $2 \times i + 1$
respectively.
Write a program which reads a binary heap represented by a nearly complete
binary tree, and prints properties of nodes of the binary heap in the
following format:
node $id$: key = $k$, parent key = $pk$, left key = $lk$, right key = $rk$,
$id$, $k$, $pk$, $lk$ and $rk$ represent id (index) of the node, value of the
node, value of its parent, value of its left child and value of its right
child respectively. Print these properties in this order. If there are no
appropriate nodes, print nothing. | [{"input": "5\n 7 8 1 2 3", "output": "node 1: key = 7, left key = 8, right key = 1, \n node 2: key = 8, parent key = 7, left key = 2, right key = 3, \n node 3: key = 1, parent key = 7, \n node 4: key = 2, parent key = 8, \n node 5: key = 3, parent key = 8,"}] |
Print the properties of the binary heap in the above format from node $1$ to
$H$ in order. _Note that, the last character of each line is a single space
character._ | s819495479 | Accepted | p02287 | In the first line, an integer $H$, the size of the binary heap, is given. In
the second line, $H$ integers which correspond to values assigned to nodes of
the binary heap are given in order of node id (from $1$ to $H$). | class Node:
def __init__(self):
self.left = None
self.right = None
self.key = None
self.parent = None
def setkeys(T):
length = len(T)
ls = [Node() for i in range(length)]
for i in range(length):
ls[i].key = T[i]
if i + 1 != 1:
ls[i].parent = T[(i + 1) // 2 - 1]
if length >= 2 * (i + 1):
ls[i].left = T[2 * i + 1]
if length >= 2 * (i + 1) + 1:
ls[i].right = T[2 * i + 2]
return ls
h = int(input())
nodes = [int(i) for i in input().split()]
ls = setkeys(nodes)
j = 0
for i in ls:
j += 1
if i.parent and i.left and i.right:
print(
"node "
+ str(j)
+ ": key = "
+ str(i.key)
+ ", parent key = "
+ str(i.parent)
+ ", left key = "
+ str(i.left)
+ ", right key = "
+ str(i.right)
+ ", "
)
elif i.left and i.right:
print(
"node "
+ str(j)
+ ": key = "
+ str(i.key)
+ ", left key = "
+ str(i.left)
+ ", right key = "
+ str(i.right)
+ ", "
)
elif i.parent and i.left:
print(
"node "
+ str(j)
+ ": key = "
+ str(i.key)
+ ", parent key = "
+ str(i.parent)
+ ", left key = "
+ str(i.left)
+ ", "
)
elif i.left:
print(
"node "
+ str(j)
+ ": key = "
+ str(i.key)
+ ", left key = "
+ str(i.left)
+ ", "
)
else:
print(
"node "
+ str(j)
+ ": key = "
+ str(i.key)
+ ", parent key = "
+ str(i.parent)
+ ", "
)
| Complete Binary Tree
A complete binary tree is a binary tree in which every internal node has two
children and all leaves have the same depth. A binary tree in which if last
level is not completely filled but all nodes (leaves) are pushed across to the
left, is also (nearly) a complete binary tree.
A binary heap data structure is an array that can be viewed as a nearly
complete binary tree as shown in the following figure.

Each node of a nearly complete binary tree corresponds to an element of the
array that stores the value in the node. An array $A$ that represents a binary
heap has the heap size $H$, the number of elements in the heap, and each
element of the binary heap is stored into $A[1...H]$ respectively. The root of
the tree is $A[1]$, and given the index $i$ of a node, the indices of its
parent $parent(i)$, left child $left(i)$, right child $right(i)$ can be
computed simply by $\lfloor i / 2 \rfloor$, $2 \times i$ and $2 \times i + 1$
respectively.
Write a program which reads a binary heap represented by a nearly complete
binary tree, and prints properties of nodes of the binary heap in the
following format:
node $id$: key = $k$, parent key = $pk$, left key = $lk$, right key = $rk$,
$id$, $k$, $pk$, $lk$ and $rk$ represent id (index) of the node, value of the
node, value of its parent, value of its left child and value of its right
child respectively. Print these properties in this order. If there are no
appropriate nodes, print nothing. | [{"input": "5\n 7 8 1 2 3", "output": "node 1: key = 7, left key = 8, right key = 1, \n node 2: key = 8, parent key = 7, left key = 2, right key = 3, \n node 3: key = 1, parent key = 7, \n node 4: key = 2, parent key = 8, \n node 5: key = 3, parent key = 8,"}] |
Print the properties of the binary heap in the above format from node $1$ to
$H$ in order. _Note that, the last character of each line is a single space
character._ | s630213814 | Accepted | p02287 | In the first line, an integer $H$, the size of the binary heap, is given. In
the second line, $H$ integers which correspond to values assigned to nodes of
the binary heap are given in order of node id (from $1$ to $H$). | h = int(input())
t = input().split()
for i in range(h):
ans = f"node {i+1}: key = {t[i]}, "
p = (i + 1) // 2 - 1
if p >= 0:
ans += f"parent key = {t[min([p,h])]}, "
l, r = (i + 1) * 2 - 1, (i + 1) * 2
if l < h:
ans += f"left key = {t[l]}, "
if r < h:
ans += f"right key = {t[r]}, "
print(ans)
| Complete Binary Tree
A complete binary tree is a binary tree in which every internal node has two
children and all leaves have the same depth. A binary tree in which if last
level is not completely filled but all nodes (leaves) are pushed across to the
left, is also (nearly) a complete binary tree.
A binary heap data structure is an array that can be viewed as a nearly
complete binary tree as shown in the following figure.

Each node of a nearly complete binary tree corresponds to an element of the
array that stores the value in the node. An array $A$ that represents a binary
heap has the heap size $H$, the number of elements in the heap, and each
element of the binary heap is stored into $A[1...H]$ respectively. The root of
the tree is $A[1]$, and given the index $i$ of a node, the indices of its
parent $parent(i)$, left child $left(i)$, right child $right(i)$ can be
computed simply by $\lfloor i / 2 \rfloor$, $2 \times i$ and $2 \times i + 1$
respectively.
Write a program which reads a binary heap represented by a nearly complete
binary tree, and prints properties of nodes of the binary heap in the
following format:
node $id$: key = $k$, parent key = $pk$, left key = $lk$, right key = $rk$,
$id$, $k$, $pk$, $lk$ and $rk$ represent id (index) of the node, value of the
node, value of its parent, value of its left child and value of its right
child respectively. Print these properties in this order. If there are no
appropriate nodes, print nothing. | [{"input": "5\n 7 8 1 2 3", "output": "node 1: key = 7, left key = 8, right key = 1, \n node 2: key = 8, parent key = 7, left key = 2, right key = 3, \n node 3: key = 1, parent key = 7, \n node 4: key = 2, parent key = 8, \n node 5: key = 3, parent key = 8,"}] |
Print the properties of the binary heap in the above format from node $1$ to
$H$ in order. _Note that, the last character of each line is a single space
character._ | s051251748 | Accepted | p02287 | In the first line, an integer $H$, the size of the binary heap, is given. In
the second line, $H$ integers which correspond to values assigned to nodes of
the binary heap are given in order of node id (from $1$ to $H$). | n = int(input())
li = list(map(int, input().split()))
class Node:
def __init__(self, data):
self.data = data
self.parent = None
self.left, self.right = None, None
def all_print(node, key, parent, left, right):
if node:
print("node {}: ".format(node), end="")
if key:
print("key = {}, ".format(key), end="")
if parent:
print("parent key = {}, ".format(parent), end="")
if left:
print("left key = {}, ".format(left), end="")
if right:
print("right key = {}, ".format(right), end="")
print("")
result = []
for i in range(n):
x = Node(li[i])
result.append(x)
for i in range(n):
x = result[i]
if 2 * (i + 1) <= n:
x.left = result[2 * (i + 1) - 1]
if 2 * (i + 1) + 1 <= n:
x.right = result[2 * (i + 1)]
if i >= 1:
x.parent = result[int((i + 1) / 2) - 1]
result.append(x)
for i in range(n):
node = i + 1
key = result[i].data
if node != 1:
parent = result[i].parent.data
else:
parent = None
if result[i].left:
left = result[i].left.data
else:
left = None
if result[i].right:
right = result[i].right.data
else:
right = None
all_print(node, key, parent, left, right)
| Complete Binary Tree
A complete binary tree is a binary tree in which every internal node has two
children and all leaves have the same depth. A binary tree in which if last
level is not completely filled but all nodes (leaves) are pushed across to the
left, is also (nearly) a complete binary tree.
A binary heap data structure is an array that can be viewed as a nearly
complete binary tree as shown in the following figure.

Each node of a nearly complete binary tree corresponds to an element of the
array that stores the value in the node. An array $A$ that represents a binary
heap has the heap size $H$, the number of elements in the heap, and each
element of the binary heap is stored into $A[1...H]$ respectively. The root of
the tree is $A[1]$, and given the index $i$ of a node, the indices of its
parent $parent(i)$, left child $left(i)$, right child $right(i)$ can be
computed simply by $\lfloor i / 2 \rfloor$, $2 \times i$ and $2 \times i + 1$
respectively.
Write a program which reads a binary heap represented by a nearly complete
binary tree, and prints properties of nodes of the binary heap in the
following format:
node $id$: key = $k$, parent key = $pk$, left key = $lk$, right key = $rk$,
$id$, $k$, $pk$, $lk$ and $rk$ represent id (index) of the node, value of the
node, value of its parent, value of its left child and value of its right
child respectively. Print these properties in this order. If there are no
appropriate nodes, print nothing. | [{"input": "5\n 7 8 1 2 3", "output": "node 1: key = 7, left key = 8, right key = 1, \n node 2: key = 8, parent key = 7, left key = 2, right key = 3, \n node 3: key = 1, parent key = 7, \n node 4: key = 2, parent key = 8, \n node 5: key = 3, parent key = 8,"}] |
Print the properties of the binary heap in the above format from node $1$ to
$H$ in order. _Note that, the last character of each line is a single space
character._ | s344331054 | Accepted | p02287 | In the first line, an integer $H$, the size of the binary heap, is given. In
the second line, $H$ integers which correspond to values assigned to nodes of
the binary heap are given in order of node id (from $1$ to $H$). | index = int(input())
nodes = [int(n) for n in input().split(" ")]
for i in range(index):
i += 1
print("node " + str(i) + ": key = " + str(nodes[i - 1]) + ", ", end="")
if i // 2 > 0:
print("parent key = " + str(nodes[i // 2 - 1]) + ", ", end="")
if i * 2 < index + 1:
print("left key = " + str(nodes[i * 2 - 1]) + ", ", end="")
if i * 2 + 1 < index + 1:
print("right key = " + str(nodes[i * 2]) + ", ", end="")
print("")
| Complete Binary Tree
A complete binary tree is a binary tree in which every internal node has two
children and all leaves have the same depth. A binary tree in which if last
level is not completely filled but all nodes (leaves) are pushed across to the
left, is also (nearly) a complete binary tree.
A binary heap data structure is an array that can be viewed as a nearly
complete binary tree as shown in the following figure.

Each node of a nearly complete binary tree corresponds to an element of the
array that stores the value in the node. An array $A$ that represents a binary
heap has the heap size $H$, the number of elements in the heap, and each
element of the binary heap is stored into $A[1...H]$ respectively. The root of
the tree is $A[1]$, and given the index $i$ of a node, the indices of its
parent $parent(i)$, left child $left(i)$, right child $right(i)$ can be
computed simply by $\lfloor i / 2 \rfloor$, $2 \times i$ and $2 \times i + 1$
respectively.
Write a program which reads a binary heap represented by a nearly complete
binary tree, and prints properties of nodes of the binary heap in the
following format:
node $id$: key = $k$, parent key = $pk$, left key = $lk$, right key = $rk$,
$id$, $k$, $pk$, $lk$ and $rk$ represent id (index) of the node, value of the
node, value of its parent, value of its left child and value of its right
child respectively. Print these properties in this order. If there are no
appropriate nodes, print nothing. | [{"input": "5\n 7 8 1 2 3", "output": "node 1: key = 7, left key = 8, right key = 1, \n node 2: key = 8, parent key = 7, left key = 2, right key = 3, \n node 3: key = 1, parent key = 7, \n node 4: key = 2, parent key = 8, \n node 5: key = 3, parent key = 8,"}] |
Print the properties of the binary heap in the above format from node $1$ to
$H$ in order. _Note that, the last character of each line is a single space
character._ | s026556472 | Accepted | p02287 | In the first line, an integer $H$, the size of the binary heap, is given. In
the second line, $H$ integers which correspond to values assigned to nodes of
the binary heap are given in order of node id (from $1$ to $H$). | # coding:UTF-8
class Node:
def __init__(self, point):
self.n = point
self.p = None
self.left = None
self.right = None
def CBT(A, n):
nlist = []
for i in range(n + 1):
if i == 0:
nlist.append(Node(0))
else:
nlist.append(Node(A[i - 1]))
for i in range(n + 1):
if i == 0:
continue
if i / 2 >= 1:
nlist[i].p = nlist[int(i / 2)].n
if 2 * i <= n:
nlist[i].left = nlist[2 * i].n
if 2 * i + 1 <= n:
nlist[i].right = nlist[2 * i + 1].n
for i in range(n + 1):
if i == 0:
continue
ans = "node " + str(i) + ": key = " + nlist[i].n + ", "
if i != 1:
ans += "parent key = " + nlist[i].p + ", "
if nlist[i].left != None:
ans += "left key = " + nlist[i].left + ", "
if nlist[i].right != None:
ans += "right key = " + nlist[i].right + ", "
print(ans)
if __name__ == "__main__":
n = int(input())
A = input().split(" ")
CBT(A, n)
| Complete Binary Tree
A complete binary tree is a binary tree in which every internal node has two
children and all leaves have the same depth. A binary tree in which if last
level is not completely filled but all nodes (leaves) are pushed across to the
left, is also (nearly) a complete binary tree.
A binary heap data structure is an array that can be viewed as a nearly
complete binary tree as shown in the following figure.

Each node of a nearly complete binary tree corresponds to an element of the
array that stores the value in the node. An array $A$ that represents a binary
heap has the heap size $H$, the number of elements in the heap, and each
element of the binary heap is stored into $A[1...H]$ respectively. The root of
the tree is $A[1]$, and given the index $i$ of a node, the indices of its
parent $parent(i)$, left child $left(i)$, right child $right(i)$ can be
computed simply by $\lfloor i / 2 \rfloor$, $2 \times i$ and $2 \times i + 1$
respectively.
Write a program which reads a binary heap represented by a nearly complete
binary tree, and prints properties of nodes of the binary heap in the
following format:
node $id$: key = $k$, parent key = $pk$, left key = $lk$, right key = $rk$,
$id$, $k$, $pk$, $lk$ and $rk$ represent id (index) of the node, value of the
node, value of its parent, value of its left child and value of its right
child respectively. Print these properties in this order. If there are no
appropriate nodes, print nothing. | [{"input": "5\n 7 8 1 2 3", "output": "node 1: key = 7, left key = 8, right key = 1, \n node 2: key = 8, parent key = 7, left key = 2, right key = 3, \n node 3: key = 1, parent key = 7, \n node 4: key = 2, parent key = 8, \n node 5: key = 3, parent key = 8,"}] |
Print the properties of the binary heap in the above format from node $1$ to
$H$ in order. _Note that, the last character of each line is a single space
character._ | s033518117 | Accepted | p02287 | In the first line, an integer $H$, the size of the binary heap, is given. In
the second line, $H$ integers which correspond to values assigned to nodes of
the binary heap are given in order of node id (from $1$ to $H$). | H = int(input())
heap = list(map(int, input().split()))
for i, h in enumerate(heap):
index = i + 1
print("node {}: key = {}, ".format(index, h), end="")
if index // 2:
print("parent key = {}, ".format(heap[index // 2 - 1]), end="")
if index * 2 <= H:
print("left key = {}, ".format(heap[index * 2 - 1]), end="")
if index * 2 < H:
print("right key = {}, ".format(heap[index * 2]), end="")
print()
| Complete Binary Tree
A complete binary tree is a binary tree in which every internal node has two
children and all leaves have the same depth. A binary tree in which if last
level is not completely filled but all nodes (leaves) are pushed across to the
left, is also (nearly) a complete binary tree.
A binary heap data structure is an array that can be viewed as a nearly
complete binary tree as shown in the following figure.

Each node of a nearly complete binary tree corresponds to an element of the
array that stores the value in the node. An array $A$ that represents a binary
heap has the heap size $H$, the number of elements in the heap, and each
element of the binary heap is stored into $A[1...H]$ respectively. The root of
the tree is $A[1]$, and given the index $i$ of a node, the indices of its
parent $parent(i)$, left child $left(i)$, right child $right(i)$ can be
computed simply by $\lfloor i / 2 \rfloor$, $2 \times i$ and $2 \times i + 1$
respectively.
Write a program which reads a binary heap represented by a nearly complete
binary tree, and prints properties of nodes of the binary heap in the
following format:
node $id$: key = $k$, parent key = $pk$, left key = $lk$, right key = $rk$,
$id$, $k$, $pk$, $lk$ and $rk$ represent id (index) of the node, value of the
node, value of its parent, value of its left child and value of its right
child respectively. Print these properties in this order. If there are no
appropriate nodes, print nothing. | [{"input": "5\n 7 8 1 2 3", "output": "node 1: key = 7, left key = 8, right key = 1, \n node 2: key = 8, parent key = 7, left key = 2, right key = 3, \n node 3: key = 1, parent key = 7, \n node 4: key = 2, parent key = 8, \n node 5: key = 3, parent key = 8,"}] |
Let m be the number of operations in your solution. In the first line, print
m. In the i-th of the subsequent m lines, print the numbers x and y chosen in
the i-th operation, with a space in between. The output will be considered
correct if m is between 0 and 2N (inclusive) and a satisfies the condition
after the m operations.
* * * | s480694688 | Accepted | p03496 | Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_{N} | # -*- coding: utf-8 -*-
#############
# Libraries #
#############
import sys
input = sys.stdin.readline
import math
# from math import gcd
import bisect
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache
#############
# Constants #
#############
MOD = 10**9 + 7
INF = float("inf")
AZ = "abcdefghijklmnopqrstuvwxyz"
#############
# Functions #
#############
######INPUT######
def I():
return int(input().strip())
def S():
return input().strip()
def IL():
return list(map(int, input().split()))
def SL():
return list(map(str, input().split()))
def ILs(n):
return list(int(input()) for _ in range(n))
def SLs(n):
return list(input().strip() for _ in range(n))
def ILL(n):
return [list(map(int, input().split())) for _ in range(n)]
def SLL(n):
return [list(map(str, input().split())) for _ in range(n)]
######OUTPUT######
def P(arg):
print(arg)
return
def Y():
print("Yes")
return
def N():
print("No")
return
def E():
exit()
def PE(arg):
print(arg)
exit()
def YE():
print("Yes")
exit()
def NE():
print("No")
exit()
#####Shorten#####
def DD(arg):
return defaultdict(arg)
#####Inverse#####
def inv(n):
return pow(n, MOD - 2, MOD)
######Combination######
kaijo_memo = []
def kaijo(n):
if len(kaijo_memo) > n:
return kaijo_memo[n]
if len(kaijo_memo) == 0:
kaijo_memo.append(1)
while len(kaijo_memo) <= n:
kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
return kaijo_memo[n]
gyaku_kaijo_memo = []
def gyaku_kaijo(n):
if len(gyaku_kaijo_memo) > n:
return gyaku_kaijo_memo[n]
if len(gyaku_kaijo_memo) == 0:
gyaku_kaijo_memo.append(1)
while len(gyaku_kaijo_memo) <= n:
gyaku_kaijo_memo.append(
gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo), MOD - 2, MOD) % MOD
)
return gyaku_kaijo_memo[n]
def nCr(n, r):
if n == r:
return 1
if n < r or r < 0:
return 0
ret = 1
ret = ret * kaijo(n) % MOD
ret = ret * gyaku_kaijo(r) % MOD
ret = ret * gyaku_kaijo(n - r) % MOD
return ret
######Factorization######
def factorization(n):
arr = []
temp = n
for i in range(2, int(-(-(n**0.5) // 1)) + 1):
if temp % i == 0:
cnt = 0
while temp % i == 0:
cnt += 1
temp //= i
arr.append([i, cnt])
if temp != 1:
arr.append([temp, 1])
if arr == []:
arr.append([n, 1])
return arr
#####MakeDivisors######
def make_divisors(n):
divisors = []
for i in range(1, int(n**0.5) + 1):
if n % i == 0:
divisors.append(i)
if i != n // i:
divisors.append(n // i)
return divisors
#####MakePrimes######
def make_primes(N):
max = int(math.sqrt(N))
seachList = [i for i in range(2, N + 1)]
primeNum = []
while seachList[0] <= max:
primeNum.append(seachList[0])
tmp = seachList[0]
seachList = [i for i in seachList if i % tmp != 0]
primeNum.extend(seachList)
return primeNum
#####GCD#####
def gcd(a, b):
while b:
a, b = b, a % b
return a
#####LCM#####
def lcm(a, b):
return a * b // gcd(a, b)
#####BitCount#####
def count_bit(n):
count = 0
while n:
n &= n - 1
count += 1
return count
#####ChangeBase#####
def base_10_to_n(X, n):
if X // n:
return base_10_to_n(X // n, n) + [X % n]
return [X % n]
def base_n_to_10(X, n):
return sum(int(str(X)[-i - 1]) * n**i for i in range(len(str(X))))
def base_10_to_n_without_0(X, n):
X -= 1
if X // n:
return base_10_to_n_without_0(X // n, n) + [X % n]
return [X % n]
#####IntLog#####
def int_log(n, a):
count = 0
while n >= a:
n //= a
count += 1
return count
#############
# Main Code #
#############
N = I()
A = IL()
MAX = max(A)
MIN = min(A)
ma = A.index(MAX)
mi = A.index(MIN)
print(2 * N - 1)
if MAX + MIN >= 0:
for i in range(N):
print(ma + 1, i + 1)
for i in range(N - 1):
print(i + 1, i + 2)
else:
for i in range(N):
print(mi + 1, i + 1)
for i in range(N - 1)[::-1]:
print(i + 2, i + 1)
| Statement
Snuke has an integer sequence, a, of length N. The i-th element of a
(1-indexed) is a_{i}.
He can perform the following operation any number of times:
* Operation: Choose integers x and y between 1 and N (inclusive), and add a_x to a_y.
He would like to perform this operation between 0 and 2N times (inclusive) so
that a satisfies the condition below. Show one such sequence of operations. It
can be proved that such a sequence of operations always exists under the
constraints in this problem.
* Condition: a_1 \leq a_2 \leq ... \leq a_{N} | [{"input": "3\n -2 5 -1", "output": "2\n 2 3\n 3 3\n \n\n * After the first operation, a = (-2,5,4).\n * After the second operation, a = (-2,5,8), and the condition is now satisfied.\n\n* * *"}, {"input": "2\n -1 -3", "output": "1\n 2 1\n \n\n * After the first operation, a = (-4,-3) and the condition is now satisfied.\n\n* * *"}, {"input": "5\n 0 0 0 0 0", "output": "0\n \n\n * The condition is satisfied already in the beginning."}] |
Let m be the number of operations in your solution. In the first line, print
m. In the i-th of the subsequent m lines, print the numbers x and y chosen in
the i-th operation, with a space in between. The output will be considered
correct if m is between 0 and 2N (inclusive) and a satisfies the condition
after the m operations.
* * * | s970147958 | Wrong Answer | p03496 | Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_{N} | # 一番絶対値大きいところから
# 正なら右側に2回足すを繰り返す
# 負なら左側に2回足すを繰り返す
# これを行った領域を切り捨てて領域がなくなるまで
N = int(input())
a = [0] + list(map(int, input().split()))
l = 1
r = N
ans = []
while l < r:
# 正で一番大きいところ取得
inde = l
maxm = a[l]
for i in range(l, r + 1, 1):
if a[i] > maxm:
inde = i
maxm = a[i]
# 負で一番大きいところ取得
inde_hu = l
minim = a[l]
for i in range(l, r + 1, 1):
if a[i] <= minim:
inde_hu = i
minim = a[i]
if abs(maxm) >= abs(minim):
tmp = inde
else:
tmp = inde_hu
if a[tmp] > 0:
for i in range(tmp, r, 1):
ans.append([i, i + 1])
ans.append([i, i + 1])
r = tmp - 1
else:
for i in range(tmp, l, -1):
ans.append([i, i - 1])
ans.append([i, i - 1])
l = tmp + 1
print(len(ans))
for i in range(len(ans)):
print(ans[i][0], ans[i][1])
| Statement
Snuke has an integer sequence, a, of length N. The i-th element of a
(1-indexed) is a_{i}.
He can perform the following operation any number of times:
* Operation: Choose integers x and y between 1 and N (inclusive), and add a_x to a_y.
He would like to perform this operation between 0 and 2N times (inclusive) so
that a satisfies the condition below. Show one such sequence of operations. It
can be proved that such a sequence of operations always exists under the
constraints in this problem.
* Condition: a_1 \leq a_2 \leq ... \leq a_{N} | [{"input": "3\n -2 5 -1", "output": "2\n 2 3\n 3 3\n \n\n * After the first operation, a = (-2,5,4).\n * After the second operation, a = (-2,5,8), and the condition is now satisfied.\n\n* * *"}, {"input": "2\n -1 -3", "output": "1\n 2 1\n \n\n * After the first operation, a = (-4,-3) and the condition is now satisfied.\n\n* * *"}, {"input": "5\n 0 0 0 0 0", "output": "0\n \n\n * The condition is satisfied already in the beginning."}] |
Let m be the number of operations in your solution. In the first line, print
m. In the i-th of the subsequent m lines, print the numbers x and y chosen in
the i-th operation, with a space in between. The output will be considered
correct if m is between 0 and 2N (inclusive) and a satisfies the condition
after the m operations.
* * * | s215674097 | Accepted | p03496 | Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_{N} | # -*- coding: utf-8 -*-
import io
import sys
import math
def format_multi_answer(lst):
ans = ""
ans += f"{len(lst)}\n"
for y in lst:
ans += f"{y[0]} {y[1]}\n"
return ans
def is_condition_ok(lst):
for i in range(len(lst) - 1):
if lst[i] > lst[i + 1]:
return False
return True
def solve(n, a_lst):
"""
D_2: 記述軽く、アルゴリズムやや悪い?バージョン
"""
# implement process
if is_condition_ok(a_lst):
return 0
# get max / min value and index
i_max, a_max = -1, -1
i_min, a_min = +1, +1
for i in range(len(a_lst)):
if a_max < a_lst[i]:
a_max = a_lst[i]
i_max = i
if a_min > a_lst[i]:
a_min = a_lst[i]
i_min = i
ans_lst = []
if a_max >= 0 and a_max >= abs(a_min):
# 全ての負の値にmax値を足し込み正の値にする。次に、plus時の処理を行う。
if _DEB:
logd(f"plus")
for i in range(len(a_lst)):
if a_lst[i] < 0:
ans_lst.append([i_max + 1, i + 1])
ans_lst.append([i_max + 1, 1])
for i in range(len(a_lst) - 1):
ans_lst.append([i + 1, i + 2])
else:
# 全ての正の値を負の値にし、minus時の処理を行う。
if _DEB:
logd(f"minus")
for i in range(len(a_lst)):
if a_lst[i] >= 0:
ans_lst.append([i_min + 1, i + 1])
ans_lst.append([i_min + 1, len(a_lst)])
for i in range(len(a_lst) - 1, 0, -1):
ans_lst.append([i + 1, i])
return format_multi_answer(ans_lst)
def main():
# input
n = int(input())
a_lst = list(map(int, input().split()))
# process
ans = str(solve(n, a_lst)).strip()
# output
print(ans)
return ans
### DEBUG I/O ###
_DEB = 0 # 1:ON / 0:OFF
_INPUT = """\
2
-1 -3
"""
_EXPECTED = """\
2
2 3
3 3
"""
def logd(str):
"""usage:
if _DEB: logd(f"{str}")
"""
if _DEB:
print(f"[deb] {str}")
### MAIN ###
if __name__ == "__main__":
if _DEB:
sys.stdin = io.StringIO(_INPUT)
print("!! Debug Mode !!")
ans = main()
if _DEB:
print()
if _EXPECTED.strip() == ans.strip():
print("!! Success !!")
else:
print(f"!! Failed... !!\nANSWER: {ans}\nExpected: {_EXPECTED}")
| Statement
Snuke has an integer sequence, a, of length N. The i-th element of a
(1-indexed) is a_{i}.
He can perform the following operation any number of times:
* Operation: Choose integers x and y between 1 and N (inclusive), and add a_x to a_y.
He would like to perform this operation between 0 and 2N times (inclusive) so
that a satisfies the condition below. Show one such sequence of operations. It
can be proved that such a sequence of operations always exists under the
constraints in this problem.
* Condition: a_1 \leq a_2 \leq ... \leq a_{N} | [{"input": "3\n -2 5 -1", "output": "2\n 2 3\n 3 3\n \n\n * After the first operation, a = (-2,5,4).\n * After the second operation, a = (-2,5,8), and the condition is now satisfied.\n\n* * *"}, {"input": "2\n -1 -3", "output": "1\n 2 1\n \n\n * After the first operation, a = (-4,-3) and the condition is now satisfied.\n\n* * *"}, {"input": "5\n 0 0 0 0 0", "output": "0\n \n\n * The condition is satisfied already in the beginning."}] |
Let m be the number of operations in your solution. In the first line, print
m. In the i-th of the subsequent m lines, print the numbers x and y chosen in
the i-th operation, with a space in between. The output will be considered
correct if m is between 0 and 2N (inclusive) and a satisfies the condition
after the m operations.
* * * | s992035617 | Wrong Answer | p03496 | Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_{N} | #!/usr/bin/env python3
import sys
# import time
# import math
# import numpy as np
# import scipy.sparse.csgraph as cs # csgraph_from_dense(ndarray, null_value=inf), bellman_ford(G, return_predecessors=True), dijkstra, floyd_warshall
# import random # random, uniform, randint, randrange, shuffle, sample
# import string # ascii_lowercase, ascii_uppercase, ascii_letters, digits, hexdigits
# import re # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from collections import deque # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict # subclass of dict. defaultdict(facroty)
# from collections import Counter # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from datetime import date, datetime # date.today(), date(year,month,day) => date obj; datetime.now(), datetime(year,month,day,hour,second,microsecond) => datetime obj; subtraction => timedelta obj
# from datetime.datetime import strptime # strptime('2019/01/01 10:05:20', '%Y/%m/%d/ %H:%M:%S') returns datetime obj
# from datetime import timedelta # td.days, td.seconds, td.microseconds, td.total_seconds(). abs function is also available.
# from copy import copy, deepcopy # use deepcopy to copy multi-dimentional matrix without reference
# from functools import reduce # reduce(f, iter[, init])
# from functools import lru_cache # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
# from itertools import accumulate # accumulate(iter[, f])
# from operator import itemgetter # itemgetter(1), itemgetter('key')
# from fractions import gcd # for Python 3.4 (previous contest @AtCoder)
def main():
mod = 1000000007 # 10^9+7
inf = float("inf") # sys.float_info.max = 1.79...e+308
# inf = 2 ** 64 - 1 # (for fast JIT compile in PyPy) 1.84...e+19
sys.setrecursionlimit(10**6) # 1000 -> 1000000
def input():
return sys.stdin.readline().rstrip()
def ii():
return int(input())
def mi():
return map(int, input().split())
def mi_0():
return map(lambda x: int(x) - 1, input().split())
def lmi():
return list(map(int, input().split()))
def lmi_0():
return list(map(lambda x: int(x) - 1, input().split()))
def li():
return list(input())
def change_to_all_pos_or_all_neg(L):
n = len(L)
M = max(L)
M_ind = L.index(M)
m = min(L)
m_ind = L.index(m)
assert M > 0 and m < 0
if M >= abs(m):
for i in range(n):
L[i] += M
command = [[M_ind + 1, i + 1] for i in range(n)]
else:
for i in range(n):
L[i] += m
command = [[m_ind + 1, i + 1] for i in range(n)]
return command
def change_to_non_increasing(L):
pivot = max(L) if all(map(lambda x: x >= 0, L)) else min(L)
pivot_ind = L.index(pivot)
command = [[pivot_ind + 1, 1]] + [[i, i + 1] for i in range(1, n)]
return command
n = ii()
L = lmi()
command = []
if all(map(lambda x: x >= 0, L)):
cnt = n
command += change_to_non_increasing(L)
elif all(map(lambda x: x <= 0, L)):
cnt = n
command += change_to_non_increasing(L)
else:
cnt = 2 * n
command += change_to_all_pos_or_all_neg(L)
command += change_to_non_increasing(L)
print(cnt)
for a, b in command:
print("{} {}".format(a, b))
if __name__ == "__main__":
main()
| Statement
Snuke has an integer sequence, a, of length N. The i-th element of a
(1-indexed) is a_{i}.
He can perform the following operation any number of times:
* Operation: Choose integers x and y between 1 and N (inclusive), and add a_x to a_y.
He would like to perform this operation between 0 and 2N times (inclusive) so
that a satisfies the condition below. Show one such sequence of operations. It
can be proved that such a sequence of operations always exists under the
constraints in this problem.
* Condition: a_1 \leq a_2 \leq ... \leq a_{N} | [{"input": "3\n -2 5 -1", "output": "2\n 2 3\n 3 3\n \n\n * After the first operation, a = (-2,5,4).\n * After the second operation, a = (-2,5,8), and the condition is now satisfied.\n\n* * *"}, {"input": "2\n -1 -3", "output": "1\n 2 1\n \n\n * After the first operation, a = (-4,-3) and the condition is now satisfied.\n\n* * *"}, {"input": "5\n 0 0 0 0 0", "output": "0\n \n\n * The condition is satisfied already in the beginning."}] |
Let m be the number of operations in your solution. In the first line, print
m. In the i-th of the subsequent m lines, print the numbers x and y chosen in
the i-th operation, with a space in between. The output will be considered
correct if m is between 0 and 2N (inclusive) and a satisfies the condition
after the m operations.
* * * | s948020974 | Wrong Answer | p03496 | Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_{N} | def get_min_idx_val(A, N):
min_val = A[0]
min_idx = 0
for i in range(N):
if min_val > A[i]:
min_val = A[i]
min_idx = i
return min_idx, min_val
def get_max_idx_val(A, N):
max_val = A[0]
max_idx = 0
for i in range(N):
if max_val < A[i]:
max_val = A[i]
max_idx = i
return max_idx, max_val
def solve():
N = int(input())
A = list(map(int, input().split()))
min_idx, min_A = get_min_idx_val(A, N)
max_idx, max_A = get_max_idx_val(A, N)
sign = 0
if abs(min_A) <= abs(max_A):
sign = 1
else:
sign = -1
ret = 0
query = []
# print('sign:',sign)
additive_idx = max_idx if sign > 0 else min_idx
additive_val = max_A if sign > 0 else min_A
# print(min_idx, max_idx, additive_idx, additive_val)
for i in range(N):
if A[i] * sign < 0:
ret += 1
query.append("{0} {1}".format(additive_idx + 1, i + 1))
A[i] += additive_val
if sign > 0:
for i in range(1, N):
first = i - 1
second = i
if A[first] > A[second]:
# if A[second] >= 0:
ret += 1
query.append("{0} {1}".format(first + 1, second + 1))
A[first] += A[second]
elif sign < 0:
for i in range(0, N - 1)[::-1]:
first = i
second = i + 1
# print(first, second, A[first], A[second])
if A[first] > A[second]:
# if A[first] <= 0:
ret += 1
query.append("{0} {1}".format(second + 1, first + 1))
A[first] += A[second]
# print(A)
output = """{0}
{1}""".format(
ret, "\n".join(query)
)
print(output)
solve()
| Statement
Snuke has an integer sequence, a, of length N. The i-th element of a
(1-indexed) is a_{i}.
He can perform the following operation any number of times:
* Operation: Choose integers x and y between 1 and N (inclusive), and add a_x to a_y.
He would like to perform this operation between 0 and 2N times (inclusive) so
that a satisfies the condition below. Show one such sequence of operations. It
can be proved that such a sequence of operations always exists under the
constraints in this problem.
* Condition: a_1 \leq a_2 \leq ... \leq a_{N} | [{"input": "3\n -2 5 -1", "output": "2\n 2 3\n 3 3\n \n\n * After the first operation, a = (-2,5,4).\n * After the second operation, a = (-2,5,8), and the condition is now satisfied.\n\n* * *"}, {"input": "2\n -1 -3", "output": "1\n 2 1\n \n\n * After the first operation, a = (-4,-3) and the condition is now satisfied.\n\n* * *"}, {"input": "5\n 0 0 0 0 0", "output": "0\n \n\n * The condition is satisfied already in the beginning."}] |
Let m be the number of operations in your solution. In the first line, print
m. In the i-th of the subsequent m lines, print the numbers x and y chosen in
the i-th operation, with a space in between. The output will be considered
correct if m is between 0 and 2N (inclusive) and a satisfies the condition
after the m operations.
* * * | s822458889 | Accepted | p03496 | Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_{N} | def getN():
return int(input())
def getMN():
a = input().split()
b = [int(i) for i in a]
return b[0], b[1]
def getlist():
a = input().split()
b = [int(i) for i in a]
return b
n = getN()
nums = getlist()
ln = len(nums)
maxn, minn = max(nums), min(nums)
already = False
if minn >= 0:
plus = True
if maxn < 0:
plus = False
if maxn >= 0 and minn < 0:
print(ln * 2 - 1)
already = True
if abs(maxn) > abs(minn):
source = nums.index(maxn)
plus = True
else:
source = nums.index(minn)
plus = False
for i in range(len(nums)):
print(source + 1, i + 1)
if not already:
print(ln - 1)
if plus:
for i in range(ln - 1):
print(i + 1, i + 2)
else:
for i in range(ln - 1):
print(ln - i, ln - i - 1)
| Statement
Snuke has an integer sequence, a, of length N. The i-th element of a
(1-indexed) is a_{i}.
He can perform the following operation any number of times:
* Operation: Choose integers x and y between 1 and N (inclusive), and add a_x to a_y.
He would like to perform this operation between 0 and 2N times (inclusive) so
that a satisfies the condition below. Show one such sequence of operations. It
can be proved that such a sequence of operations always exists under the
constraints in this problem.
* Condition: a_1 \leq a_2 \leq ... \leq a_{N} | [{"input": "3\n -2 5 -1", "output": "2\n 2 3\n 3 3\n \n\n * After the first operation, a = (-2,5,4).\n * After the second operation, a = (-2,5,8), and the condition is now satisfied.\n\n* * *"}, {"input": "2\n -1 -3", "output": "1\n 2 1\n \n\n * After the first operation, a = (-4,-3) and the condition is now satisfied.\n\n* * *"}, {"input": "5\n 0 0 0 0 0", "output": "0\n \n\n * The condition is satisfied already in the beginning."}] |
Let m be the number of operations in your solution. In the first line, print
m. In the i-th of the subsequent m lines, print the numbers x and y chosen in
the i-th operation, with a space in between. The output will be considered
correct if m is between 0 and 2N (inclusive) and a satisfies the condition
after the m operations.
* * * | s415610694 | Wrong Answer | p03496 | Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_{N} | N = int(input())
inl = list(map(int, input().split()))
max_v = -100000000
max_i = -1
min_v = 100000000
min_i = -1
for i, num in enumerate(inl):
if max_v < num:
max_v = num
max_i = i
if min_v > num:
min_v = num
min_i = i
outl = []
if abs(min_v) > abs(max_v):
for i in range(N):
if inl[i] > min_v:
inl[i] += min_v
outl.append((min_i, i))
for i in range(1, N):
if inl[i - 1] > inl[i]:
inl[i - 1] += inl[i]
outl.append((i, i - 1))
else:
for i in range(N):
if inl[i] < max_v:
inl[i] += max_v
outl.append((max_i, i))
for i in range(1, N):
if inl[i - 1] > inl[i]:
inl[i] += inl[i - 1]
outl.append((i - 1, i))
print(inl)
print(len(outl))
for i, j in outl:
print(i + 1, j + 1)
| Statement
Snuke has an integer sequence, a, of length N. The i-th element of a
(1-indexed) is a_{i}.
He can perform the following operation any number of times:
* Operation: Choose integers x and y between 1 and N (inclusive), and add a_x to a_y.
He would like to perform this operation between 0 and 2N times (inclusive) so
that a satisfies the condition below. Show one such sequence of operations. It
can be proved that such a sequence of operations always exists under the
constraints in this problem.
* Condition: a_1 \leq a_2 \leq ... \leq a_{N} | [{"input": "3\n -2 5 -1", "output": "2\n 2 3\n 3 3\n \n\n * After the first operation, a = (-2,5,4).\n * After the second operation, a = (-2,5,8), and the condition is now satisfied.\n\n* * *"}, {"input": "2\n -1 -3", "output": "1\n 2 1\n \n\n * After the first operation, a = (-4,-3) and the condition is now satisfied.\n\n* * *"}, {"input": "5\n 0 0 0 0 0", "output": "0\n \n\n * The condition is satisfied already in the beginning."}] |
Let m be the number of operations in your solution. In the first line, print
m. In the i-th of the subsequent m lines, print the numbers x and y chosen in
the i-th operation, with a space in between. The output will be considered
correct if m is between 0 and 2N (inclusive) and a satisfies the condition
after the m operations.
* * * | s049464583 | Runtime Error | p03496 | Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_{N} | = int(input())
a = list(map(int, input().split()))
end = False
def check(a_, count, ans):
global end
#print(a_)
if(end):
return False
#print(a_)
if(count > 2 * n):
return False
ac = True
prev = a_[0]
for i in range(n):
if(a_[i] < prev):
for j in range(n):
#print(a_[i] + a_[j], prev)
#print(a_[i - 1] + a_[j], a[i])
if(a_[i] + a_[j] >= prev or abs(a_[i] + a_[j] - prev) < abs(a_[i] - prev)):
a_[i] += a_[j]#print(str(j + 1) + " " + str(i + 1))
count += 1
tmp = ans + str(j + 1) + " " + str(i + 1) + "\n"
if(check(a_, count, tmp) == True):
print(count)
print(ans + str(j + 1) + " " + str(i + 1))
end = True
return False
elif(a_[i - 1] + a_[j] < a[i] or abs(a_[i - 1] + a_[j] - a[i]) < abs(a_[i - 1] - a[i])):
a_[i - 1] += a_[j]#print(str(j + 1) + " " + str(i + 1))
count += 1
tmp = ans + str(j + 1) + " " + str(i) + "\n"
if(check(a_, count, tmp) == True):
print(count)
print(ans + str(j + 1) + " " + str(i))
end = True
return False
ac = False
if(ac == False):
break
prev = a_[i]
return ac
z = 0
prev = a[0]
for i in range(n):
if(a[i] < prev):
z = 1
prev = a[i]
if(z == 0):
print(z)
else:
check(a, 0, "") | Statement
Snuke has an integer sequence, a, of length N. The i-th element of a
(1-indexed) is a_{i}.
He can perform the following operation any number of times:
* Operation: Choose integers x and y between 1 and N (inclusive), and add a_x to a_y.
He would like to perform this operation between 0 and 2N times (inclusive) so
that a satisfies the condition below. Show one such sequence of operations. It
can be proved that such a sequence of operations always exists under the
constraints in this problem.
* Condition: a_1 \leq a_2 \leq ... \leq a_{N} | [{"input": "3\n -2 5 -1", "output": "2\n 2 3\n 3 3\n \n\n * After the first operation, a = (-2,5,4).\n * After the second operation, a = (-2,5,8), and the condition is now satisfied.\n\n* * *"}, {"input": "2\n -1 -3", "output": "1\n 2 1\n \n\n * After the first operation, a = (-4,-3) and the condition is now satisfied.\n\n* * *"}, {"input": "5\n 0 0 0 0 0", "output": "0\n \n\n * The condition is satisfied already in the beginning."}] |
Let m be the number of operations in your solution. In the first line, print
m. In the i-th of the subsequent m lines, print the numbers x and y chosen in
the i-th operation, with a space in between. The output will be considered
correct if m is between 0 and 2N (inclusive) and a satisfies the condition
after the m operations.
* * * | s168541929 | Runtime Error | p03496 | Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_{N} | N = int(input())
series = list(map(int,input().split()))
series_sorted = series[:]
series_sorted.sort()
def make_no_decrease(condition, series):
if condition == 0:#正の整数列
for i in range(1,N):
print(i, i+1)
elif condition == 1:#負の整数列
for i in range(1,N):
print(N-i+1, N-i)
if series_sorted[0] >= 0: #正の時
print(len(series)-1)
make_no_decrease(0, series)
elif series_sorted[-1] < 0: #負の時
print(len(series)-1)
make_no_decrease(1, series)
else:
if abs(series_sorted[-1]) <= abs(series_sorted[0]): #負の値のほうが大きい時
print(2*len(series)-1)
min = series.index(series_sorted[0])
for i in range(len(series)):
print(min+1, i)
make_no_decrease(1, series)
else abs(series_sorted[0]) < abs(series_sorted[-1]): #正の値のほうが大きい時
print(2*len(series)-1)
max = series.index(series_sorted[-1])
for i in range(len(series)):
print(max+1, i+1)
make_no_decrease(0, series) | Statement
Snuke has an integer sequence, a, of length N. The i-th element of a
(1-indexed) is a_{i}.
He can perform the following operation any number of times:
* Operation: Choose integers x and y between 1 and N (inclusive), and add a_x to a_y.
He would like to perform this operation between 0 and 2N times (inclusive) so
that a satisfies the condition below. Show one such sequence of operations. It
can be proved that such a sequence of operations always exists under the
constraints in this problem.
* Condition: a_1 \leq a_2 \leq ... \leq a_{N} | [{"input": "3\n -2 5 -1", "output": "2\n 2 3\n 3 3\n \n\n * After the first operation, a = (-2,5,4).\n * After the second operation, a = (-2,5,8), and the condition is now satisfied.\n\n* * *"}, {"input": "2\n -1 -3", "output": "1\n 2 1\n \n\n * After the first operation, a = (-4,-3) and the condition is now satisfied.\n\n* * *"}, {"input": "5\n 0 0 0 0 0", "output": "0\n \n\n * The condition is satisfied already in the beginning."}] |
Let m be the number of operations in your solution. In the first line, print
m. In the i-th of the subsequent m lines, print the numbers x and y chosen in
the i-th operation, with a space in between. The output will be considered
correct if m is between 0 and 2N (inclusive) and a satisfies the condition
after the m operations.
* * * | s385454631 | Runtime Error | p03496 | Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_{N} | N=int(input())
a=list(map(int,input().split()))
print(2*N-2)
if max(a)>=-min(a):
for i in range(0,N):
N[i]+=max(a)
for i in range(0,N-1):
print(i+1)
print(' ')
print(i+2)
a[i+1]+=a[i]
elif max(a)<-min(a):
for i in range(0,N):
N[i]+=min(a)
for i in range(N-1,0,-1):
print(i)
print(' ')
print(i+1)
a[i-1]+=a[i] | Statement
Snuke has an integer sequence, a, of length N. The i-th element of a
(1-indexed) is a_{i}.
He can perform the following operation any number of times:
* Operation: Choose integers x and y between 1 and N (inclusive), and add a_x to a_y.
He would like to perform this operation between 0 and 2N times (inclusive) so
that a satisfies the condition below. Show one such sequence of operations. It
can be proved that such a sequence of operations always exists under the
constraints in this problem.
* Condition: a_1 \leq a_2 \leq ... \leq a_{N} | [{"input": "3\n -2 5 -1", "output": "2\n 2 3\n 3 3\n \n\n * After the first operation, a = (-2,5,4).\n * After the second operation, a = (-2,5,8), and the condition is now satisfied.\n\n* * *"}, {"input": "2\n -1 -3", "output": "1\n 2 1\n \n\n * After the first operation, a = (-4,-3) and the condition is now satisfied.\n\n* * *"}, {"input": "5\n 0 0 0 0 0", "output": "0\n \n\n * The condition is satisfied already in the beginning."}] |
Let m be the number of operations in your solution. In the first line, print
m. In the i-th of the subsequent m lines, print the numbers x and y chosen in
the i-th operation, with a space in between. The output will be considered
correct if m is between 0 and 2N (inclusive) and a satisfies the condition
after the m operations.
* * * | s650820739 | Wrong Answer | p03496 | Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_{N} | N = int(input())
As = list(map(int, input().split()))
rs = []
a = 0
b = N
while a < b:
n = max(range(a, b), key=lambda i: abs(As[i]))
if As[n] > 0:
for i in range(n + 1, b):
rs.append((i - 1, i))
rs.append((i - 1, i))
b = n
if As[n] < 0:
for i in reversed(range(a, n)):
rs.append((i + 1, i))
rs.append((i + 1, i))
a = n + 1
if As[n] == 0:
break
# print(rs)
print(len(rs))
for x, y in rs:
print(x + 1, y + 1)
| Statement
Snuke has an integer sequence, a, of length N. The i-th element of a
(1-indexed) is a_{i}.
He can perform the following operation any number of times:
* Operation: Choose integers x and y between 1 and N (inclusive), and add a_x to a_y.
He would like to perform this operation between 0 and 2N times (inclusive) so
that a satisfies the condition below. Show one such sequence of operations. It
can be proved that such a sequence of operations always exists under the
constraints in this problem.
* Condition: a_1 \leq a_2 \leq ... \leq a_{N} | [{"input": "3\n -2 5 -1", "output": "2\n 2 3\n 3 3\n \n\n * After the first operation, a = (-2,5,4).\n * After the second operation, a = (-2,5,8), and the condition is now satisfied.\n\n* * *"}, {"input": "2\n -1 -3", "output": "1\n 2 1\n \n\n * After the first operation, a = (-4,-3) and the condition is now satisfied.\n\n* * *"}, {"input": "5\n 0 0 0 0 0", "output": "0\n \n\n * The condition is satisfied already in the beginning."}] |
Let m be the number of operations in your solution. In the first line, print
m. In the i-th of the subsequent m lines, print the numbers x and y chosen in
the i-th operation, with a space in between. The output will be considered
correct if m is between 0 and 2N (inclusive) and a satisfies the condition
after the m operations.
* * * | s825628206 | Wrong Answer | p03496 | Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_{N} | n = int(input())
as_ = list(int(i) for i in input().split())
def output_history(history):
print(len(history))
for h in history:
print("{0} {1}".format(h[0], h[1]))
def distribute(list_, hstr, x, y):
list_[y] += list_[x]
hstr.append((x, y))
return list_, hstr
history = []
# 正負どちらかに寄せる
# MaxMin大きく外れている方に寄せる
if abs(max(as_)) > abs(min(as_)):
# 正に寄せる
# 正のMaxを負の要素に繰り返し分配
x = as_.index(max(as_))
while not all([a >= 0 for a in as_]):
for y, a in enumerate(as_):
if a < 0:
as_, history = distribute(as_, history, x, y)
# 正のMaxを探しそれより後ろの要素に繰り返し分配
while not as_.index(max(as_)) == len(as_) - 1:
x = as_.index(max(as_))
for y, a in enumerate(as_):
if y > x:
as_, history = distribute(as_, history, x, y)
else:
# 負に寄せる
# 負のMaxを正の要素に繰り返し分配
x = as_.index(min(as_))
while not all([a <= 0 for a in as_]):
for y, a in enumerate(as_):
if a > 0:
as_, history = distribute(as_, history, x, y)
# 正のMaxを探しそれより後ろの要素に繰り返し分配
while not as_.index(min(as_)) == 0:
x = as_.index(min(as_))
for y, a in enumerate(as_):
if y < x:
as_, history = distribute(as_, history, x, y)
output_history(history)
| Statement
Snuke has an integer sequence, a, of length N. The i-th element of a
(1-indexed) is a_{i}.
He can perform the following operation any number of times:
* Operation: Choose integers x and y between 1 and N (inclusive), and add a_x to a_y.
He would like to perform this operation between 0 and 2N times (inclusive) so
that a satisfies the condition below. Show one such sequence of operations. It
can be proved that such a sequence of operations always exists under the
constraints in this problem.
* Condition: a_1 \leq a_2 \leq ... \leq a_{N} | [{"input": "3\n -2 5 -1", "output": "2\n 2 3\n 3 3\n \n\n * After the first operation, a = (-2,5,4).\n * After the second operation, a = (-2,5,8), and the condition is now satisfied.\n\n* * *"}, {"input": "2\n -1 -3", "output": "1\n 2 1\n \n\n * After the first operation, a = (-4,-3) and the condition is now satisfied.\n\n* * *"}, {"input": "5\n 0 0 0 0 0", "output": "0\n \n\n * The condition is satisfied already in the beginning."}] |
Print the maximum possible sum of the values of the blocks contained in the
tower.
* * * | s852386876 | Accepted | p03183 | Input is given from Standard Input in the following format:
N
w_1 s_1 v_1
w_2 s_2 v_2
:
w_N s_N v_N | # -*- coding: utf-8 -*-
#############
# Libraries #
#############
import sys
input = sys.stdin.readline
import math
# from math import gcd
import bisect
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache
#############
# Constants #
#############
MOD = 10**9 + 7
INF = float("inf")
AZ = "abcdefghijklmnopqrstuvwxyz"
#############
# Functions #
#############
######INPUT######
def I():
return int(input().strip())
def S():
return input().strip()
def IL():
return list(map(int, input().split()))
def SL():
return list(map(str, input().split()))
def ILs(n):
return list(int(input()) for _ in range(n))
def SLs(n):
return list(input().strip() for _ in range(n))
def ILL(n):
return [list(map(int, input().split())) for _ in range(n)]
def SLL(n):
return [list(map(str, input().split())) for _ in range(n)]
#####Shorten#####
def DD(arg):
return defaultdict(arg)
#####Inverse#####
def inv(n):
return pow(n, MOD - 2, MOD)
######Combination######
kaijo_memo = []
def kaijo(n):
if len(kaijo_memo) > n:
return kaijo_memo[n]
if len(kaijo_memo) == 0:
kaijo_memo.append(1)
while len(kaijo_memo) <= n:
kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
return kaijo_memo[n]
gyaku_kaijo_memo = []
def gyaku_kaijo(n):
if len(gyaku_kaijo_memo) > n:
return gyaku_kaijo_memo[n]
if len(gyaku_kaijo_memo) == 0:
gyaku_kaijo_memo.append(1)
while len(gyaku_kaijo_memo) <= n:
gyaku_kaijo_memo.append(
gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo), MOD - 2, MOD) % MOD
)
return gyaku_kaijo_memo[n]
def nCr(n, r):
if n == r:
return 1
if n < r or r < 0:
return 0
ret = 1
ret = ret * kaijo(n) % MOD
ret = ret * gyaku_kaijo(r) % MOD
ret = ret * gyaku_kaijo(n - r) % MOD
return ret
######Factorization######
def factorization(n):
arr = []
temp = n
for i in range(2, int(-(-(n**0.5) // 1)) + 1):
if temp % i == 0:
cnt = 0
while temp % i == 0:
cnt += 1
temp //= i
arr.append([i, cnt])
if temp != 1:
arr.append([temp, 1])
if arr == []:
arr.append([n, 1])
return arr
#####MakeDivisors######
def make_divisors(n):
divisors = []
for i in range(1, int(n**0.5) + 1):
if n % i == 0:
divisors.append(i)
if i != n // i:
divisors.append(n // i)
return divisors
#####MakePrimes######
def make_primes(N):
max = int(math.sqrt(N))
seachList = [i for i in range(2, N + 1)]
primeNum = []
while seachList[0] <= max:
primeNum.append(seachList[0])
tmp = seachList[0]
seachList = [i for i in seachList if i % tmp != 0]
primeNum.extend(seachList)
return primeNum
#####GCD#####
def gcd(a, b):
while b:
a, b = b, a % b
return a
#####LCM#####
def lcm(a, b):
return a * b // gcd(a, b)
#####BitCount#####
def count_bit(n):
count = 0
while n:
n &= n - 1
count += 1
return count
#####ChangeBase#####
def base_10_to_n(X, n):
if X // n:
return base_10_to_n(X // n, n) + [X % n]
return [X % n]
def base_n_to_10(X, n):
return sum(int(str(X)[-i - 1]) * n**i for i in range(len(str(X))))
def base_10_to_n_without_0(X, n):
X -= 1
if X // n:
return base_10_to_n_without_0(X // n, n) + [X % n]
return [X % n]
#####IntLog#####
def int_log(n, a):
count = 0
while n >= a:
n //= a
count += 1
return count
#############
# Main Code #
#############
N = I()
data = ILL(N)
data.sort(lambda x: x[0] + x[1])
wmax = 22000
dp = [0 for w in range(wmax)]
for i in range(N):
w, s, v = data[i]
for j in range(s + 1)[::-1]:
dp[j + w] = max(dp[j + w], dp[j] + v)
print(max(dp))
| Statement
There are N blocks, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N),
Block i has a weight of w_i, a solidness of s_i and a value of v_i.
Taro has decided to build a tower by choosing some of the N blocks and
stacking them vertically in some order. Here, the tower must satisfy the
following condition:
* For each Block i contained in the tower, the sum of the weights of the blocks stacked above it is not greater than s_i.
Find the maximum possible sum of the values of the blocks contained in the
tower. | [{"input": "3\n 2 2 20\n 2 1 30\n 3 1 40", "output": "50\n \n\nIf Blocks 2, 1 are stacked in this order from top to bottom, this tower will\nsatisfy the condition, with the total value of 30 + 20 = 50.\n\n* * *"}, {"input": "4\n 1 2 10\n 3 1 10\n 2 4 10\n 1 6 10", "output": "40\n \n\nBlocks 1, 2, 3, 4 should be stacked in this order from top to bottom.\n\n* * *"}, {"input": "5\n 1 10000 1000000000\n 1 10000 1000000000\n 1 10000 1000000000\n 1 10000 1000000000\n 1 10000 1000000000", "output": "5000000000\n \n\nThe answer may not fit into a 32-bit integer type.\n\n* * *"}, {"input": "8\n 9 5 7\n 6 2 7\n 5 7 3\n 7 8 8\n 1 9 6\n 3 3 3\n 4 1 7\n 4 5 5", "output": "22\n \n\nWe should, for example, stack Blocks 5, 6, 8, 4 in this order from top to\nbottom."}] |
Print the maximum possible sum of the values of the blocks contained in the
tower.
* * * | s245428440 | Accepted | p03183 | Input is given from Standard Input in the following format:
N
w_1 s_1 v_1
w_2 s_2 v_2
:
w_N s_N v_N | import sys
sys.setrecursionlimit(2147483647)
INF = 1 << 60
MOD = 10**9 + 7 # 998244353
input = lambda: sys.stdin.readline().rstrip()
def resolve():
n = int(input())
WSV = [tuple(map(int, input().split())) for _ in range(n)]
WSV.sort(key=lambda tup: tup[0] + tup[1])
# dp[i][w] : i 番目まで見て、total weight が w のときの max value
# solid_max <= 10^4 なので、total weight > 10^4 は考えなくて良い
res = 0
solid_max = 10**4
dp = [-1] * (solid_max + 1)
dp[0] = 0
for w0, s0, v in WSV:
for w in range(solid_max, -1, -1):
if dp[w] == -1:
continue
if w > s0: # w <= s0
continue
if w + w0 > solid_max:
res = max(res, dp[w] + v)
else:
dp[w + w0] = max(dp[w + w0], dp[w] + v)
res = max(res, max(dp))
print(res)
resolve()
| Statement
There are N blocks, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N),
Block i has a weight of w_i, a solidness of s_i and a value of v_i.
Taro has decided to build a tower by choosing some of the N blocks and
stacking them vertically in some order. Here, the tower must satisfy the
following condition:
* For each Block i contained in the tower, the sum of the weights of the blocks stacked above it is not greater than s_i.
Find the maximum possible sum of the values of the blocks contained in the
tower. | [{"input": "3\n 2 2 20\n 2 1 30\n 3 1 40", "output": "50\n \n\nIf Blocks 2, 1 are stacked in this order from top to bottom, this tower will\nsatisfy the condition, with the total value of 30 + 20 = 50.\n\n* * *"}, {"input": "4\n 1 2 10\n 3 1 10\n 2 4 10\n 1 6 10", "output": "40\n \n\nBlocks 1, 2, 3, 4 should be stacked in this order from top to bottom.\n\n* * *"}, {"input": "5\n 1 10000 1000000000\n 1 10000 1000000000\n 1 10000 1000000000\n 1 10000 1000000000\n 1 10000 1000000000", "output": "5000000000\n \n\nThe answer may not fit into a 32-bit integer type.\n\n* * *"}, {"input": "8\n 9 5 7\n 6 2 7\n 5 7 3\n 7 8 8\n 1 9 6\n 3 3 3\n 4 1 7\n 4 5 5", "output": "22\n \n\nWe should, for example, stack Blocks 5, 6, 8, 4 in this order from top to\nbottom."}] |
Print the maximum possible sum of the values of the blocks contained in the
tower.
* * * | s284748005 | Runtime Error | p03183 | Input is given from Standard Input in the following format:
N
w_1 s_1 v_1
w_2 s_2 v_2
:
w_N s_N v_N | import sys
input = sys.stdin.readline
N, M = map(int, input().split())
N0 = 2 ** ((N + 1).bit_length())
INF = 10**18
data = [0] * (2 * N0)
lazy = [0] * (2 * N0)
def gindex(l, r):
L = l + N0
R = r + N0
lm = (L // (L & -L)) >> 1
rm = (R // (R & -R)) >> 1
while L < R:
if R <= rm:
yield R
if L <= lm:
yield L
L >>= 1
R >>= 1
while L:
yield L
L >>= 1
def propagates(*ids):
for i in reversed(ids):
v = lazy[i - 1]
if not v:
continue
lazy[2 * i - 1] += v
lazy[2 * i] += v
data[2 * i - 1] += v
data[2 * i] += v
lazy[i - 1] = 0
def update(l, r, x):
L = N0 + l
R = N0 + r
while L < R:
if R & 1:
R -= 1
lazy[R - 1] += x
data[R - 1] += x
if L & 1:
lazy[L - 1] += x
data[L - 1] += x
L += 1
L >>= 1
R >>= 1
for i in gindex(l, r):
data[i - 1] = max(data[2 * i - 1], data[2 * i]) + lazy[i - 1]
def update2(k, x):
k += N0 - 1
data[k] = x
while k >= 0:
k = (k - 1) // 2
data[k] = max(data[2 * k + 1], data[2 * k + 2])
def query(l, r):
propagates(*gindex(l, r))
L = N0 + l
R = N0 + r
s = -INF
while L < R:
if R & 1:
R -= 1
s = max(s, data[R - 1])
if L & 1:
s = max(s, data[L - 1])
L += 1
L >>= 1
R >>= 1
return s
xs = [0] * (N + 1)
ys = [[] for _ in range(N + 1)]
for _ in range(M):
l, r, a = map(int, input().split())
xs[l] += a
ys[r].append((l, a))
for i in range(1, N + 1):
update(0, i, xs[i])
update2(i, query(0, i))
for l, a in ys[i]:
update(0, l, -a)
print(query(0, N + 1))
| Statement
There are N blocks, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N),
Block i has a weight of w_i, a solidness of s_i and a value of v_i.
Taro has decided to build a tower by choosing some of the N blocks and
stacking them vertically in some order. Here, the tower must satisfy the
following condition:
* For each Block i contained in the tower, the sum of the weights of the blocks stacked above it is not greater than s_i.
Find the maximum possible sum of the values of the blocks contained in the
tower. | [{"input": "3\n 2 2 20\n 2 1 30\n 3 1 40", "output": "50\n \n\nIf Blocks 2, 1 are stacked in this order from top to bottom, this tower will\nsatisfy the condition, with the total value of 30 + 20 = 50.\n\n* * *"}, {"input": "4\n 1 2 10\n 3 1 10\n 2 4 10\n 1 6 10", "output": "40\n \n\nBlocks 1, 2, 3, 4 should be stacked in this order from top to bottom.\n\n* * *"}, {"input": "5\n 1 10000 1000000000\n 1 10000 1000000000\n 1 10000 1000000000\n 1 10000 1000000000\n 1 10000 1000000000", "output": "5000000000\n \n\nThe answer may not fit into a 32-bit integer type.\n\n* * *"}, {"input": "8\n 9 5 7\n 6 2 7\n 5 7 3\n 7 8 8\n 1 9 6\n 3 3 3\n 4 1 7\n 4 5 5", "output": "22\n \n\nWe should, for example, stack Blocks 5, 6, 8, 4 in this order from top to\nbottom."}] |
Print the maximum possible sum of the values of the blocks contained in the
tower.
* * * | s020927571 | Wrong Answer | p03183 | Input is given from Standard Input in the following format:
N
w_1 s_1 v_1
w_2 s_2 v_2
:
w_N s_N v_N | n = int(input())
ans = 0
p = [0] * 22222
for w, s, v in sorted(
[list(map(int, input().split())) for _ in [0] * n], key=lambda a: a[0] + a[1]
):
for j in range(s + 1):
p[j + w] = max(p[j + w], p[j] + v)
ans = max(ans, p[j + w])
print(ans)
| Statement
There are N blocks, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N),
Block i has a weight of w_i, a solidness of s_i and a value of v_i.
Taro has decided to build a tower by choosing some of the N blocks and
stacking them vertically in some order. Here, the tower must satisfy the
following condition:
* For each Block i contained in the tower, the sum of the weights of the blocks stacked above it is not greater than s_i.
Find the maximum possible sum of the values of the blocks contained in the
tower. | [{"input": "3\n 2 2 20\n 2 1 30\n 3 1 40", "output": "50\n \n\nIf Blocks 2, 1 are stacked in this order from top to bottom, this tower will\nsatisfy the condition, with the total value of 30 + 20 = 50.\n\n* * *"}, {"input": "4\n 1 2 10\n 3 1 10\n 2 4 10\n 1 6 10", "output": "40\n \n\nBlocks 1, 2, 3, 4 should be stacked in this order from top to bottom.\n\n* * *"}, {"input": "5\n 1 10000 1000000000\n 1 10000 1000000000\n 1 10000 1000000000\n 1 10000 1000000000\n 1 10000 1000000000", "output": "5000000000\n \n\nThe answer may not fit into a 32-bit integer type.\n\n* * *"}, {"input": "8\n 9 5 7\n 6 2 7\n 5 7 3\n 7 8 8\n 1 9 6\n 3 3 3\n 4 1 7\n 4 5 5", "output": "22\n \n\nWe should, for example, stack Blocks 5, 6, 8, 4 in this order from top to\nbottom."}] |
Print the maximum possible sum of the values of the blocks contained in the
tower.
* * * | s056367462 | Wrong Answer | p03183 | Input is given from Standard Input in the following format:
N
w_1 s_1 v_1
w_2 s_2 v_2
:
w_N s_N v_N | n = int(input())
wsv = [list(map(int, input().split())) for i in range(n)]
wsv.sort(key=lambda x: x[0] + x[1], reverse=True)
smx = max(list(zip(*wsv))[1])
dp = [[0 for i in range(smx + 1)] for j in range(n + 1)]
for i in range(1, n + 1):
dp[i] = dp[i - 1][:]
w, s, v = wsv[i - 1]
dp[i][s] = max(dp[i - 1][s], v)
for ss in range(smx + 1)[::-1]:
sn = min(ss - w, s)
if sn >= 0:
dp[i][sn] = max(dp[i - 1][sn], dp[i - 1][ss] + v)
print(max(dp[-1]))
| Statement
There are N blocks, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N),
Block i has a weight of w_i, a solidness of s_i and a value of v_i.
Taro has decided to build a tower by choosing some of the N blocks and
stacking them vertically in some order. Here, the tower must satisfy the
following condition:
* For each Block i contained in the tower, the sum of the weights of the blocks stacked above it is not greater than s_i.
Find the maximum possible sum of the values of the blocks contained in the
tower. | [{"input": "3\n 2 2 20\n 2 1 30\n 3 1 40", "output": "50\n \n\nIf Blocks 2, 1 are stacked in this order from top to bottom, this tower will\nsatisfy the condition, with the total value of 30 + 20 = 50.\n\n* * *"}, {"input": "4\n 1 2 10\n 3 1 10\n 2 4 10\n 1 6 10", "output": "40\n \n\nBlocks 1, 2, 3, 4 should be stacked in this order from top to bottom.\n\n* * *"}, {"input": "5\n 1 10000 1000000000\n 1 10000 1000000000\n 1 10000 1000000000\n 1 10000 1000000000\n 1 10000 1000000000", "output": "5000000000\n \n\nThe answer may not fit into a 32-bit integer type.\n\n* * *"}, {"input": "8\n 9 5 7\n 6 2 7\n 5 7 3\n 7 8 8\n 1 9 6\n 3 3 3\n 4 1 7\n 4 5 5", "output": "22\n \n\nWe should, for example, stack Blocks 5, 6, 8, 4 in this order from top to\nbottom."}] |
Print the maximum possible length of the sequence.
* * * | s587934918 | Runtime Error | p03479 | Input is given from Standard Input in the following format:
X Y | X, Y = map(int, input().split())
count = 0
while True:
count++
X = X * 2
if X > Y:
break
print(count) | Statement
As a token of his gratitude, Takahashi has decided to give his mother an
integer sequence. The sequence A needs to satisfy the conditions below:
* A consists of integers between X and Y (inclusive).
* For each 1\leq i \leq |A|-1, A_{i+1} is a multiple of A_i and strictly greater than A_i.
Find the maximum possible length of the sequence. | [{"input": "3 20", "output": "3\n \n\nThe sequence 3,6,18 satisfies the conditions.\n\n* * *"}, {"input": "25 100", "output": "3\n \n\n* * *"}, {"input": "314159265 358979323846264338", "output": "31"}] |
Print the maximum possible length of the sequence.
* * * | s120063021 | Wrong Answer | p03479 | Input is given from Standard Input in the following format:
X Y | X, Y = map(int, input().split())
maxstack = []
stack = []
for i in range(X, Y + 1):
j = i
# print("j",j)
while j <= Y + 1:
# print("loopj",j)
stack.append(j)
j *= 2
# print(stack, len(stack))
if len(maxstack) < len(stack):
maxstack.clear()
maxstack.extend(stack)
# print(maxstack)
stack.clear()
print(len(maxstack))
| Statement
As a token of his gratitude, Takahashi has decided to give his mother an
integer sequence. The sequence A needs to satisfy the conditions below:
* A consists of integers between X and Y (inclusive).
* For each 1\leq i \leq |A|-1, A_{i+1} is a multiple of A_i and strictly greater than A_i.
Find the maximum possible length of the sequence. | [{"input": "3 20", "output": "3\n \n\nThe sequence 3,6,18 satisfies the conditions.\n\n* * *"}, {"input": "25 100", "output": "3\n \n\n* * *"}, {"input": "314159265 358979323846264338", "output": "31"}] |
Print the maximum possible length of the sequence.
* * * | s779105423 | Runtime Error | p03479 | Input is given from Standard Input in the following format:
X Y | import math
x, y =map(int, input().split())
print(int(math.log2(y / x) + 1 ) | Statement
As a token of his gratitude, Takahashi has decided to give his mother an
integer sequence. The sequence A needs to satisfy the conditions below:
* A consists of integers between X and Y (inclusive).
* For each 1\leq i \leq |A|-1, A_{i+1} is a multiple of A_i and strictly greater than A_i.
Find the maximum possible length of the sequence. | [{"input": "3 20", "output": "3\n \n\nThe sequence 3,6,18 satisfies the conditions.\n\n* * *"}, {"input": "25 100", "output": "3\n \n\n* * *"}, {"input": "314159265 358979323846264338", "output": "31"}] |
Print the maximum possible length of the sequence.
* * * | s901335969 | Runtime Error | p03479 | Input is given from Standard Input in the following format:
X Y | x, y = map(int, input().split())
count = 1
while x <= y:
x *= 2
count += 1
print(count-1 | Statement
As a token of his gratitude, Takahashi has decided to give his mother an
integer sequence. The sequence A needs to satisfy the conditions below:
* A consists of integers between X and Y (inclusive).
* For each 1\leq i \leq |A|-1, A_{i+1} is a multiple of A_i and strictly greater than A_i.
Find the maximum possible length of the sequence. | [{"input": "3 20", "output": "3\n \n\nThe sequence 3,6,18 satisfies the conditions.\n\n* * *"}, {"input": "25 100", "output": "3\n \n\n* * *"}, {"input": "314159265 358979323846264338", "output": "31"}] |
Print the maximum possible length of the sequence.
* * * | s844931473 | Runtime Error | p03479 | Input is given from Standard Input in the following format:
X Y | x, y = map(in
t, input().split())
ans = 0 if x>y else 1
while x*2<=y:
ans+=1
x=x*2
print(ans) | Statement
As a token of his gratitude, Takahashi has decided to give his mother an
integer sequence. The sequence A needs to satisfy the conditions below:
* A consists of integers between X and Y (inclusive).
* For each 1\leq i \leq |A|-1, A_{i+1} is a multiple of A_i and strictly greater than A_i.
Find the maximum possible length of the sequence. | [{"input": "3 20", "output": "3\n \n\nThe sequence 3,6,18 satisfies the conditions.\n\n* * *"}, {"input": "25 100", "output": "3\n \n\n* * *"}, {"input": "314159265 358979323846264338", "output": "31"}] |
Print the maximum possible length of the sequence.
* * * | s471977362 | Accepted | p03479 | Input is given from Standard Input in the following format:
X Y | x, y = [int(x) for x in input().split()]
ans = [x]
while ans[-1] * 2 <= y:
ans.append(ans[-1] * 2)
# print(ans)
print(len(ans))
| Statement
As a token of his gratitude, Takahashi has decided to give his mother an
integer sequence. The sequence A needs to satisfy the conditions below:
* A consists of integers between X and Y (inclusive).
* For each 1\leq i \leq |A|-1, A_{i+1} is a multiple of A_i and strictly greater than A_i.
Find the maximum possible length of the sequence. | [{"input": "3 20", "output": "3\n \n\nThe sequence 3,6,18 satisfies the conditions.\n\n* * *"}, {"input": "25 100", "output": "3\n \n\n* * *"}, {"input": "314159265 358979323846264338", "output": "31"}] |
Print the maximum possible length of the sequence.
* * * | s565653277 | Runtime Error | p03479 | Input is given from Standard Input in the following format:
X Y | x, y = map(int, input().split())
c = 2
z = 1
if(x > 1):
c = x;
while(c*2 <= y):
c *= 2;
z += 1;
print(z) | Statement
As a token of his gratitude, Takahashi has decided to give his mother an
integer sequence. The sequence A needs to satisfy the conditions below:
* A consists of integers between X and Y (inclusive).
* For each 1\leq i \leq |A|-1, A_{i+1} is a multiple of A_i and strictly greater than A_i.
Find the maximum possible length of the sequence. | [{"input": "3 20", "output": "3\n \n\nThe sequence 3,6,18 satisfies the conditions.\n\n* * *"}, {"input": "25 100", "output": "3\n \n\n* * *"}, {"input": "314159265 358979323846264338", "output": "31"}] |
Print the maximum possible length of the sequence.
* * * | s648754349 | Runtime Error | p03479 | Input is given from Standard Input in the following format:
X Y | imput_list = list(map(int, input().split()))
a = imput_list[1] / imput_list[0]
print(math.floor(math.log2(a)) + 1)
| Statement
As a token of his gratitude, Takahashi has decided to give his mother an
integer sequence. The sequence A needs to satisfy the conditions below:
* A consists of integers between X and Y (inclusive).
* For each 1\leq i \leq |A|-1, A_{i+1} is a multiple of A_i and strictly greater than A_i.
Find the maximum possible length of the sequence. | [{"input": "3 20", "output": "3\n \n\nThe sequence 3,6,18 satisfies the conditions.\n\n* * *"}, {"input": "25 100", "output": "3\n \n\n* * *"}, {"input": "314159265 358979323846264338", "output": "31"}] |
Print the maximum possible length of the sequence.
* * * | s738254107 | Accepted | p03479 | Input is given from Standard Input in the following format:
X Y | x, y = map(int, input().split())
l = []
flag = True
left = x
l.append(left)
l_max = y
mul = 2
current_value = left
while flag:
a = current_value * mul
if l_max < a:
flag = False
break
l.append(a)
current_value = a
print(len(l))
| Statement
As a token of his gratitude, Takahashi has decided to give his mother an
integer sequence. The sequence A needs to satisfy the conditions below:
* A consists of integers between X and Y (inclusive).
* For each 1\leq i \leq |A|-1, A_{i+1} is a multiple of A_i and strictly greater than A_i.
Find the maximum possible length of the sequence. | [{"input": "3 20", "output": "3\n \n\nThe sequence 3,6,18 satisfies the conditions.\n\n* * *"}, {"input": "25 100", "output": "3\n \n\n* * *"}, {"input": "314159265 358979323846264338", "output": "31"}] |
Print the maximum possible length of the sequence.
* * * | s103782510 | Accepted | p03479 | Input is given from Standard Input in the following format:
X Y | #!/usr/bin/env python3
import sys
def solve(X: int, Y: int):
ans = []
cur = X
while cur <= Y:
ans.append(cur)
cur *= 2
print(len(ans))
return
# Generated by 1.1.4 https://github.com/kyuridenamida/atcoder-tools (tips: You use the default template now. You can remove this line by using your custom template)
def main():
def iterate_tokens():
for line in sys.stdin:
for word in line.split():
yield word
tokens = iterate_tokens()
X = int(next(tokens)) # type: int
Y = int(next(tokens)) # type: int
solve(X, Y)
if __name__ == "__main__":
main()
| Statement
As a token of his gratitude, Takahashi has decided to give his mother an
integer sequence. The sequence A needs to satisfy the conditions below:
* A consists of integers between X and Y (inclusive).
* For each 1\leq i \leq |A|-1, A_{i+1} is a multiple of A_i and strictly greater than A_i.
Find the maximum possible length of the sequence. | [{"input": "3 20", "output": "3\n \n\nThe sequence 3,6,18 satisfies the conditions.\n\n* * *"}, {"input": "25 100", "output": "3\n \n\n* * *"}, {"input": "314159265 358979323846264338", "output": "31"}] |
Print the maximum possible length of the sequence.
* * * | s869106491 | Runtime Error | p03479 | Input is given from Standard Input in the following format:
X Y | X,Y=map(int,input().split())
d=Y-X
k= Y // X
if k <= 1:
print(1)
exit(0)
count=0
while(1):
if <= 2**count:
break
else:
count+=1
print(count+1)
| Statement
As a token of his gratitude, Takahashi has decided to give his mother an
integer sequence. The sequence A needs to satisfy the conditions below:
* A consists of integers between X and Y (inclusive).
* For each 1\leq i \leq |A|-1, A_{i+1} is a multiple of A_i and strictly greater than A_i.
Find the maximum possible length of the sequence. | [{"input": "3 20", "output": "3\n \n\nThe sequence 3,6,18 satisfies the conditions.\n\n* * *"}, {"input": "25 100", "output": "3\n \n\n* * *"}, {"input": "314159265 358979323846264338", "output": "31"}] |
Print the maximum possible length of the sequence.
* * * | s079382769 | Wrong Answer | p03479 | Input is given from Standard Input in the following format:
X Y | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on 2019/3/16
Solved on 2019/3/
@author: shinjisu
"""
# ABC 083 C Multiple Gift
import math
# import numpy as np
def getInt():
return int(input())
def getIntList():
return [int(x) for x in input().split()]
# def getIntList(): return np.array(input().split(), dtype=np.longlong)
def zeros(n):
return [0] * n
# def zeros(n): return np.zeros(n, dtype=np.longlong)
def getIntLines(n):
return [int(input()) for i in range(n)]
"""
def getIntLines(n):
data = zeros(n)
for i in range(n):
data[i] = getInt()
return data
"""
def zeros2(n, m):
return [zeros(m) for i in range(n)] # obsoleted zeros((n, m))で代替
def getIntMat(n, m): # n行に渡って、1行にm個の整数
# mat = zeros((n, m))
mat = zeros2(n, m)
for i in range(n):
mat[i] = getIntList()
return mat
ALPHABET = [chr(i + ord("a")) for i in range(26)]
DIGIT = [chr(i + ord("0")) for i in range(10)]
N1097 = 10**9 + 7
INF = 10**18
class Debug:
def __init__(self):
self.debug = True
def off(self):
self.debug = False
def dmp(self, x, cmt=""):
if self.debug:
if cmt != "":
print(cmt, ": ", end="")
print(x)
return x
def prob():
d = Debug()
d.off()
X, Y = getIntList()
d.dmp((X, Y), "X, Y")
return int(math.log2(Y / X)) + 1
ans = prob()
if ans is None:
pass
elif type(ans) == tuple and ans[0] == 1: # 1,ans
for elm in ans[1]:
print(elm)
else:
print(ans)
| Statement
As a token of his gratitude, Takahashi has decided to give his mother an
integer sequence. The sequence A needs to satisfy the conditions below:
* A consists of integers between X and Y (inclusive).
* For each 1\leq i \leq |A|-1, A_{i+1} is a multiple of A_i and strictly greater than A_i.
Find the maximum possible length of the sequence. | [{"input": "3 20", "output": "3\n \n\nThe sequence 3,6,18 satisfies the conditions.\n\n* * *"}, {"input": "25 100", "output": "3\n \n\n* * *"}, {"input": "314159265 358979323846264338", "output": "31"}] |
Print the maximum possible length of the sequence.
* * * | s389169670 | Runtime Error | p03479 | Input is given from Standard Input in the following format:
X Y | import math
import itertools
import heapq
from sys import stdin, stdout, setrecursionlimit
from bisect import bisect, bisect_left, bisect_right
from collections import defaultdict, deque
# d = defaultdict(lambda: 0)
# setrecursionlimit(10**7)
# inf = float("inf")
##### stdin ####
def LM(t, r): return list(map(t, r))
def R(): return stdin.readline()
def RS(): return R().split()
def I(): return int(R())
def F(): return float(R())
def LI(): return LM(int,RS())
def LF(): return LM(float,RS())
def ONE_SL(): return list(input())
def ONE_IL(): return LM(int, ONE_SL())
def ALL_I(): return map(int, stdin)
def ALL_IL(): return LM(int,stdin)
##### tools #####
def ap(f): return f.append
def pll(li): print('\n'.join(LM(str,li)))
def pljoin(li, s): print(s.join(li))
##### main #####
def main():
x,y = LI()
ans=
while x<=y:
x*=2
ans+=1
print(ans)
if __name__ == '__main__':
main() | Statement
As a token of his gratitude, Takahashi has decided to give his mother an
integer sequence. The sequence A needs to satisfy the conditions below:
* A consists of integers between X and Y (inclusive).
* For each 1\leq i \leq |A|-1, A_{i+1} is a multiple of A_i and strictly greater than A_i.
Find the maximum possible length of the sequence. | [{"input": "3 20", "output": "3\n \n\nThe sequence 3,6,18 satisfies the conditions.\n\n* * *"}, {"input": "25 100", "output": "3\n \n\n* * *"}, {"input": "314159265 358979323846264338", "output": "31"}] |
Print the maximum number of apple pies we can make with what we have.
* * * | s933593154 | Wrong Answer | p03029 | Input is given from Standard Input in the following format:
A P | n = list(map(int, input().split()))
print((n[0] * 3 + n[1]) / 2)
| Statement
We have A apples and P pieces of apple.
We can cut an apple into three pieces of apple, and make one apple pie by
simmering two pieces of apple in a pan.
Find the maximum number of apple pies we can make with what we have now. | [{"input": "1 3", "output": "3\n \n\nWe can first make one apple pie by simmering two of the three pieces of apple.\nThen, we can make two more by simmering the remaining piece and three more\npieces obtained by cutting the whole apple.\n\n* * *"}, {"input": "0 1", "output": "0\n \n\nWe cannot make an apple pie in this case, unfortunately.\n\n* * *"}, {"input": "32 21", "output": "58"}] |
Print the maximum number of apple pies we can make with what we have.
* * * | s839565439 | Runtime Error | p03029 | Input is given from Standard Input in the following format:
A P | a, p = map(int, inputy().split())
a = 3 * p
print((a + p) // 2)
| Statement
We have A apples and P pieces of apple.
We can cut an apple into three pieces of apple, and make one apple pie by
simmering two pieces of apple in a pan.
Find the maximum number of apple pies we can make with what we have now. | [{"input": "1 3", "output": "3\n \n\nWe can first make one apple pie by simmering two of the three pieces of apple.\nThen, we can make two more by simmering the remaining piece and three more\npieces obtained by cutting the whole apple.\n\n* * *"}, {"input": "0 1", "output": "0\n \n\nWe cannot make an apple pie in this case, unfortunately.\n\n* * *"}, {"input": "32 21", "output": "58"}] |
Print the maximum number of apple pies we can make with what we have.
* * * | s493939672 | Accepted | p03029 | Input is given from Standard Input in the following format:
A P | a = input().rstrip().split(" ")
b = int(a[0])
c = int(a[1])
c = b * 3 + c
print(int(c / 2))
| Statement
We have A apples and P pieces of apple.
We can cut an apple into three pieces of apple, and make one apple pie by
simmering two pieces of apple in a pan.
Find the maximum number of apple pies we can make with what we have now. | [{"input": "1 3", "output": "3\n \n\nWe can first make one apple pie by simmering two of the three pieces of apple.\nThen, we can make two more by simmering the remaining piece and three more\npieces obtained by cutting the whole apple.\n\n* * *"}, {"input": "0 1", "output": "0\n \n\nWe cannot make an apple pie in this case, unfortunately.\n\n* * *"}, {"input": "32 21", "output": "58"}] |
Print the maximum number of apple pies we can make with what we have.
* * * | s045192464 | Runtime Error | p03029 | Input is given from Standard Input in the following format:
A P | import copy
class MyClass:
maxSum = 0
def do(self, baseList, _temochi, leftIndex, rightIndex, nokoriSousaCount):
if nokoriSousaCount < 0:
return
sum = 0
for each in _temochi:
sum += each
if self.maxSum < sum:
self.maxSum = sum
if leftIndex <= rightIndex:
temochi = copy.copy(_temochi)
temochi.append(baseList[leftIndex])
self.do(baseList, temochi, leftIndex + 1, rightIndex, nokoriSousaCount - 1)
temochi = copy.copy(_temochi)
temochi.append(baseList[rightIndex])
self.do(baseList, temochi, leftIndex, rightIndex - 1, nokoriSousaCount - 1)
self.removeMin(_temochi, leftIndex, rightIndex, nokoriSousaCount - 1)
def removeMin(self, _temochi, leftIndex, rightIndex, nokoriSousaCount):
if len(_temochi) > 0 and nokoriSousaCount > 0:
minNum = min(_temochi)
if minNum < 0:
temochi = copy.copy(_temochi)
temochi.remove(minNum)
self.do(baseList, temochi, leftIndex, rightIndex, nokoriSousaCount)
count, opeCount = map(int, input().split())
baseList = list(map(int, input().split()))
doClass = MyClass()
doClass.do(baseList, [], 0, count - 1, opeCount)
print(doClass.maxSum)
| Statement
We have A apples and P pieces of apple.
We can cut an apple into three pieces of apple, and make one apple pie by
simmering two pieces of apple in a pan.
Find the maximum number of apple pies we can make with what we have now. | [{"input": "1 3", "output": "3\n \n\nWe can first make one apple pie by simmering two of the three pieces of apple.\nThen, we can make two more by simmering the remaining piece and three more\npieces obtained by cutting the whole apple.\n\n* * *"}, {"input": "0 1", "output": "0\n \n\nWe cannot make an apple pie in this case, unfortunately.\n\n* * *"}, {"input": "32 21", "output": "58"}] |
Print the maximum number of apple pies we can make with what we have.
* * * | s543933612 | Wrong Answer | p03029 | Input is given from Standard Input in the following format:
A P | import sys
from bisect import bisect_left
n, q = map(int, input().split())
lines = sys.stdin.readlines()
c = []
for line in lines[:n]:
s, t, x = map(int, line.split())
c.append((x, s, t))
c.sort()
d = list(map(int, lines[n:]))
ans = [-1] * q
skip = [-1] * q
for x, s, t in c:
ss = bisect_left(d, s - x)
tt = bisect_left(d, t - x)
while ss < tt:
if skip[ss] == -1:
ans[ss] = x
skip[ss] = tt
ss += 1
else:
ss = skip[ss]
print(*ans, sep="\n")
| Statement
We have A apples and P pieces of apple.
We can cut an apple into three pieces of apple, and make one apple pie by
simmering two pieces of apple in a pan.
Find the maximum number of apple pies we can make with what we have now. | [{"input": "1 3", "output": "3\n \n\nWe can first make one apple pie by simmering two of the three pieces of apple.\nThen, we can make two more by simmering the remaining piece and three more\npieces obtained by cutting the whole apple.\n\n* * *"}, {"input": "0 1", "output": "0\n \n\nWe cannot make an apple pie in this case, unfortunately.\n\n* * *"}, {"input": "32 21", "output": "58"}] |
Print the maximum number of apple pies we can make with what we have.
* * * | s116485168 | Runtime Error | p03029 | Input is given from Standard Input in the following format:
A P | import itertools
n, m = map(int, input().split())
ks = [list(map(int, input().split())) for _ in range(m)]
p = list(map(int, input().split()))
# %%
cnt = 0
for bits in itertools.product([0, 1], repeat=n):
# ライトの配列の初期化
lights = [0] * m
# 電球ごとのONになってるスイッチの数をカウント
# スイッチのindexでループを回す
for i in range(n):
if bits[i] == 1: # スイッチがONのとき
sw = i + 1 # スイッチの番号
for j in range(len(ks)): # 全部のlight-switchの配線を確認
if sw in ks[j][1:]: # 配線がつながってるとき
lights[j] += 1 # そのlightに1を加算
# カウント終了後条件判別
# 一つもスイッチがONになってないとライトが付きもしない
# if 0 not in lights:
# 2で割ったあまり
m_lights = [l % 2 for l in lights]
if m_lights == p:
cnt += 1
print(cnt)
| Statement
We have A apples and P pieces of apple.
We can cut an apple into three pieces of apple, and make one apple pie by
simmering two pieces of apple in a pan.
Find the maximum number of apple pies we can make with what we have now. | [{"input": "1 3", "output": "3\n \n\nWe can first make one apple pie by simmering two of the three pieces of apple.\nThen, we can make two more by simmering the remaining piece and three more\npieces obtained by cutting the whole apple.\n\n* * *"}, {"input": "0 1", "output": "0\n \n\nWe cannot make an apple pie in this case, unfortunately.\n\n* * *"}, {"input": "32 21", "output": "58"}] |
Print the maximum number of apple pies we can make with what we have.
* * * | s152059383 | Wrong Answer | p03029 | Input is given from Standard Input in the following format:
A P | import random
random.seed(1)
Apple = random.randint(0, 101)
Piece = random.randint(0, 101)
Pie = 0
def BreakApple():
global Apple
while Apple >= 1:
Apple -= 1
global Piece
Piece += 3
def MakePie():
global Piece
while Piece >= 3:
Piece -= 2
global Pie
Pie += 1
BreakApple()
MakePie()
print(Pie)
| Statement
We have A apples and P pieces of apple.
We can cut an apple into three pieces of apple, and make one apple pie by
simmering two pieces of apple in a pan.
Find the maximum number of apple pies we can make with what we have now. | [{"input": "1 3", "output": "3\n \n\nWe can first make one apple pie by simmering two of the three pieces of apple.\nThen, we can make two more by simmering the remaining piece and three more\npieces obtained by cutting the whole apple.\n\n* * *"}, {"input": "0 1", "output": "0\n \n\nWe cannot make an apple pie in this case, unfortunately.\n\n* * *"}, {"input": "32 21", "output": "58"}] |
Print the maximum number of apple pies we can make with what we have.
* * * | s887788134 | Runtime Error | p03029 | Input is given from Standard Input in the following format:
A P | number = input().split(" ")
A = int(number[0])
P = int(number[1])
apple = (A * 3) + P
print(math.floor(apple / 2))
| Statement
We have A apples and P pieces of apple.
We can cut an apple into three pieces of apple, and make one apple pie by
simmering two pieces of apple in a pan.
Find the maximum number of apple pies we can make with what we have now. | [{"input": "1 3", "output": "3\n \n\nWe can first make one apple pie by simmering two of the three pieces of apple.\nThen, we can make two more by simmering the remaining piece and three more\npieces obtained by cutting the whole apple.\n\n* * *"}, {"input": "0 1", "output": "0\n \n\nWe cannot make an apple pie in this case, unfortunately.\n\n* * *"}, {"input": "32 21", "output": "58"}] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.