text
stringlengths
198
433k
conversation_id
int64
0
109k
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two rectangles on a plane. The centers of both rectangles are located in the origin of coordinates (meaning the center of the rectangle's symmetry). The first rectangle's sides are parallel to the coordinate axes: the length of the side that is parallel to the Ox axis, equals w, the length of the side that is parallel to the Oy axis, equals h. The second rectangle can be obtained by rotating the first rectangle relative to the origin of coordinates by angle Ξ±. <image> Your task is to find the area of the region which belongs to both given rectangles. This region is shaded in the picture. Input The first line contains three integers w, h, Ξ± (1 ≀ w, h ≀ 106; 0 ≀ Ξ± ≀ 180). Angle Ξ± is given in degrees. Output In a single line print a real number β€” the area of the region which belongs to both given rectangles. The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 6. Examples Input 1 1 45 Output 0.828427125 Input 6 4 30 Output 19.668384925 Note The second sample has been drawn on the picture above. Submitted Solution: ``` import math def rot_by_a(p, a): return (p[0] * math.cos(a) - p[1] * math.sin(a), p[0] * math.sin(a) + p[1] * math.cos(a)) h, w, alpha = map(int, input().split()) if h > w: h, w = w, h if alpha > 90: alpha = 180 - alpha ang = math.radians(alpha) b = math.tan(h / w) # why not * 2 ? if alpha == 0: print(h * w) elif alpha == 90: print(h * h) elif ang > b: side = h / math.sin(ang) print(side * h) else: left_top = (w / 2, h / 2) rot_left_top = rot_by_a(left_top, ang) tri_h = rot_left_top[1] - left_top[1] tri_base = tri_h * math.tan(ang) + tri_h / math.tan(math.pi / 2 - ang) longer_cathetus = tri_base * math.cos(ang) smaller_tri_smaller_cathetus = w - tri_base - longer_cathetus smaller_tri_longer_cathetus = smaller_tri_smaller_cathetus / math.tan(ang) print(w * h - tri_base * tri_h - smaller_tri_smaller_cathetus * smaller_tri_longer_cathetus) ``` No
6,100
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two rectangles on a plane. The centers of both rectangles are located in the origin of coordinates (meaning the center of the rectangle's symmetry). The first rectangle's sides are parallel to the coordinate axes: the length of the side that is parallel to the Ox axis, equals w, the length of the side that is parallel to the Oy axis, equals h. The second rectangle can be obtained by rotating the first rectangle relative to the origin of coordinates by angle Ξ±. <image> Your task is to find the area of the region which belongs to both given rectangles. This region is shaded in the picture. Input The first line contains three integers w, h, Ξ± (1 ≀ w, h ≀ 106; 0 ≀ Ξ± ≀ 180). Angle Ξ± is given in degrees. Output In a single line print a real number β€” the area of the region which belongs to both given rectangles. The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 6. Examples Input 1 1 45 Output 0.828427125 Input 6 4 30 Output 19.668384925 Note The second sample has been drawn on the picture above. Submitted Solution: ``` import math def rot_by_a(p, a): return (p[0] * math.cos(a) - p[1] * math.sin(a), p[0] * math.sin(a) + p[1] * math.cos(a)) h, w, alpha = map(int, input().split()) if h > w: h, w = w, h if alpha > 90: alpha = 180 - alpha ang = math.radians(alpha) b = math.tan(h / w) # why not * 2 ? if alpha == 0: print(h * w) elif alpha == 90: print(float(h * h)) elif ang > b: side = h / math.sin(ang) print(side * h) else: left_top = (w / 2, h / 2) rot_left_top = rot_by_a(left_top, ang) tri_h = rot_left_top[1] - left_top[1] tri_base = tri_h * math.tan(ang) + tri_h / math.tan(math.pi / 2 - ang) longer_cathetus = tri_base * math.cos(ang) smaller_tri_smaller_cathetus = w - tri_base - longer_cathetus smaller_tri_longer_cathetus = smaller_tri_smaller_cathetus / math.tan(ang) print(w * h - tri_base * tri_h - smaller_tri_smaller_cathetus * smaller_tri_longer_cathetus) ``` No
6,101
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two rectangles on a plane. The centers of both rectangles are located in the origin of coordinates (meaning the center of the rectangle's symmetry). The first rectangle's sides are parallel to the coordinate axes: the length of the side that is parallel to the Ox axis, equals w, the length of the side that is parallel to the Oy axis, equals h. The second rectangle can be obtained by rotating the first rectangle relative to the origin of coordinates by angle Ξ±. <image> Your task is to find the area of the region which belongs to both given rectangles. This region is shaded in the picture. Input The first line contains three integers w, h, Ξ± (1 ≀ w, h ≀ 106; 0 ≀ Ξ± ≀ 180). Angle Ξ± is given in degrees. Output In a single line print a real number β€” the area of the region which belongs to both given rectangles. The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 6. Examples Input 1 1 45 Output 0.828427125 Input 6 4 30 Output 19.668384925 Note The second sample has been drawn on the picture above. Submitted Solution: ``` import math def rot_by_a(p, a): return (p[0] * math.cos(a) - p[1] * math.sin(a), p[0] * math.sin(a) + p[1] * math.cos(a)) h, w, alpha = map(int, input().split()) if h > w: h, w = w, h if alpha > 90: alpha = 180 - alpha ang = math.radians(alpha) b = math.tan(h / w) # why not * 2 ? if alpha == 0: print(h * w) elif ang > b: side = h / math.sin(ang) print(side * h) else: left_top = (w / 2, h / 2) rot_left_top = rot_by_a(left_top, ang) tri_h = rot_left_top[1] - left_top[1] tri_base = tri_h / math.tan(ang) + tri_h / math.tan(math.pi / 2 - ang) longer_cathetus = tri_base * math.cos(ang) smaller_tri_smaller_cathetus = w - tri_base - longer_cathetus smaller_tri_longer_cathetus = smaller_tri_smaller_cathetus / math.tan(ang) print(w * h - tri_base * tri_h - smaller_tri_smaller_cathetus * smaller_tri_longer_cathetus) ``` No
6,102
Provide tags and a correct Python 3 solution for this coding contest problem. Calendars in widespread use today include the Gregorian calendar, which is the de facto international standard, and is used almost everywhere in the world for civil purposes. The Gregorian reform modified the Julian calendar's scheme of leap years as follows: Every year that is exactly divisible by four is a leap year, except for years that are exactly divisible by 100; the centurial years that are exactly divisible by 400 are still leap years. For example, the year 1900 is not a leap year; the year 2000 is a leap year. <image> In this problem, you have been given two dates and your task is to calculate how many days are between them. Note, that leap years have unusual number of days in February. Look at the sample to understand what borders are included in the aswer. Input The first two lines contain two dates, each date is in the format yyyy:mm:dd (1900 ≀ yyyy ≀ 2038 and yyyy:mm:dd is a legal date). Output Print a single integer β€” the answer to the problem. Examples Input 1900:01:01 2038:12:31 Output 50768 Input 1996:03:09 1991:11:12 Output 1579 Tags: brute force, implementation Correct Solution: ``` from datetime import date d = [0] * 2 for i in range(0, 2): a = list(map(int, input().split(':'))) d[i] = date(a[0], a[1], a[2]) r = (d[0] - d[1]).days print(r if r >= 0 else -r) ```
6,103
Provide tags and a correct Python 3 solution for this coding contest problem. Calendars in widespread use today include the Gregorian calendar, which is the de facto international standard, and is used almost everywhere in the world for civil purposes. The Gregorian reform modified the Julian calendar's scheme of leap years as follows: Every year that is exactly divisible by four is a leap year, except for years that are exactly divisible by 100; the centurial years that are exactly divisible by 400 are still leap years. For example, the year 1900 is not a leap year; the year 2000 is a leap year. <image> In this problem, you have been given two dates and your task is to calculate how many days are between them. Note, that leap years have unusual number of days in February. Look at the sample to understand what borders are included in the aswer. Input The first two lines contain two dates, each date is in the format yyyy:mm:dd (1900 ≀ yyyy ≀ 2038 and yyyy:mm:dd is a legal date). Output Print a single integer β€” the answer to the problem. Examples Input 1900:01:01 2038:12:31 Output 50768 Input 1996:03:09 1991:11:12 Output 1579 Tags: brute force, implementation Correct Solution: ``` import datetime t1 = datetime.datetime.strptime(input(),"%Y:%m:%d") t2 = datetime.datetime.strptime(input(),"%Y:%m:%d") print(abs((t2-t1).days)) ```
6,104
Provide tags and a correct Python 3 solution for this coding contest problem. Calendars in widespread use today include the Gregorian calendar, which is the de facto international standard, and is used almost everywhere in the world for civil purposes. The Gregorian reform modified the Julian calendar's scheme of leap years as follows: Every year that is exactly divisible by four is a leap year, except for years that are exactly divisible by 100; the centurial years that are exactly divisible by 400 are still leap years. For example, the year 1900 is not a leap year; the year 2000 is a leap year. <image> In this problem, you have been given two dates and your task is to calculate how many days are between them. Note, that leap years have unusual number of days in February. Look at the sample to understand what borders are included in the aswer. Input The first two lines contain two dates, each date is in the format yyyy:mm:dd (1900 ≀ yyyy ≀ 2038 and yyyy:mm:dd is a legal date). Output Print a single integer β€” the answer to the problem. Examples Input 1900:01:01 2038:12:31 Output 50768 Input 1996:03:09 1991:11:12 Output 1579 Tags: brute force, implementation Correct Solution: ``` from datetime import date a1 = [int(i) for i in input().split(':')] a2 = [int(i) for i in input().split(':')] print(abs((date(a1[0], a1[1], a1[2]) - date(a2[0], a2[1], a2[2])).days)) ```
6,105
Provide tags and a correct Python 3 solution for this coding contest problem. Calendars in widespread use today include the Gregorian calendar, which is the de facto international standard, and is used almost everywhere in the world for civil purposes. The Gregorian reform modified the Julian calendar's scheme of leap years as follows: Every year that is exactly divisible by four is a leap year, except for years that are exactly divisible by 100; the centurial years that are exactly divisible by 400 are still leap years. For example, the year 1900 is not a leap year; the year 2000 is a leap year. <image> In this problem, you have been given two dates and your task is to calculate how many days are between them. Note, that leap years have unusual number of days in February. Look at the sample to understand what borders are included in the aswer. Input The first two lines contain two dates, each date is in the format yyyy:mm:dd (1900 ≀ yyyy ≀ 2038 and yyyy:mm:dd is a legal date). Output Print a single integer β€” the answer to the problem. Examples Input 1900:01:01 2038:12:31 Output 50768 Input 1996:03:09 1991:11:12 Output 1579 Tags: brute force, implementation Correct Solution: ``` from datetime import * R = lambda: datetime(*map(int, input().split(':'))) date1 = R() date2 = R() print(abs(date2 - date1).days) ```
6,106
Provide tags and a correct Python 3 solution for this coding contest problem. Calendars in widespread use today include the Gregorian calendar, which is the de facto international standard, and is used almost everywhere in the world for civil purposes. The Gregorian reform modified the Julian calendar's scheme of leap years as follows: Every year that is exactly divisible by four is a leap year, except for years that are exactly divisible by 100; the centurial years that are exactly divisible by 400 are still leap years. For example, the year 1900 is not a leap year; the year 2000 is a leap year. <image> In this problem, you have been given two dates and your task is to calculate how many days are between them. Note, that leap years have unusual number of days in February. Look at the sample to understand what borders are included in the aswer. Input The first two lines contain two dates, each date is in the format yyyy:mm:dd (1900 ≀ yyyy ≀ 2038 and yyyy:mm:dd is a legal date). Output Print a single integer β€” the answer to the problem. Examples Input 1900:01:01 2038:12:31 Output 50768 Input 1996:03:09 1991:11:12 Output 1579 Tags: brute force, implementation Correct Solution: ``` from collections import Counter import string import math dicti={'1':31,'2':28,'3':31,'4':30,'5':31,'6':30,'7':31,'8':31 ,'9':30,'10':31,'11':30,'12':31} def array_int(): return [int(i) for i in input().split()] def vary(number_of_variables): if number_of_variables==1: return int(input()) if number_of_variables>=2: return map(int,input().split()) def makedict(var): return dict(Counter(var)) mod=1000000007 from datetime import date print(abs((date(*map(int,input().split(':')))-date(*map(int,input().split(':')))).days)) ```
6,107
Provide tags and a correct Python 3 solution for this coding contest problem. Calendars in widespread use today include the Gregorian calendar, which is the de facto international standard, and is used almost everywhere in the world for civil purposes. The Gregorian reform modified the Julian calendar's scheme of leap years as follows: Every year that is exactly divisible by four is a leap year, except for years that are exactly divisible by 100; the centurial years that are exactly divisible by 400 are still leap years. For example, the year 1900 is not a leap year; the year 2000 is a leap year. <image> In this problem, you have been given two dates and your task is to calculate how many days are between them. Note, that leap years have unusual number of days in February. Look at the sample to understand what borders are included in the aswer. Input The first two lines contain two dates, each date is in the format yyyy:mm:dd (1900 ≀ yyyy ≀ 2038 and yyyy:mm:dd is a legal date). Output Print a single integer β€” the answer to the problem. Examples Input 1900:01:01 2038:12:31 Output 50768 Input 1996:03:09 1991:11:12 Output 1579 Tags: brute force, implementation Correct Solution: ``` import datetime y1, m1, d1 = map(int, input().split(':')) y2, m2, d2 = map(int, input().split(':')) print(abs(datetime.date(y1, m1, d1) - datetime.date(y2, m2, d2)).days) ```
6,108
Provide tags and a correct Python 3 solution for this coding contest problem. Calendars in widespread use today include the Gregorian calendar, which is the de facto international standard, and is used almost everywhere in the world for civil purposes. The Gregorian reform modified the Julian calendar's scheme of leap years as follows: Every year that is exactly divisible by four is a leap year, except for years that are exactly divisible by 100; the centurial years that are exactly divisible by 400 are still leap years. For example, the year 1900 is not a leap year; the year 2000 is a leap year. <image> In this problem, you have been given two dates and your task is to calculate how many days are between them. Note, that leap years have unusual number of days in February. Look at the sample to understand what borders are included in the aswer. Input The first two lines contain two dates, each date is in the format yyyy:mm:dd (1900 ≀ yyyy ≀ 2038 and yyyy:mm:dd is a legal date). Output Print a single integer β€” the answer to the problem. Examples Input 1900:01:01 2038:12:31 Output 50768 Input 1996:03:09 1991:11:12 Output 1579 Tags: brute force, implementation Correct Solution: ``` from datetime import * t1 = datetime.strptime(input(), "%Y:%m:%d") t2 = datetime.strptime(input(), "%Y:%m:%d") print(abs((t2-t1).days)) ```
6,109
Provide tags and a correct Python 3 solution for this coding contest problem. Calendars in widespread use today include the Gregorian calendar, which is the de facto international standard, and is used almost everywhere in the world for civil purposes. The Gregorian reform modified the Julian calendar's scheme of leap years as follows: Every year that is exactly divisible by four is a leap year, except for years that are exactly divisible by 100; the centurial years that are exactly divisible by 400 are still leap years. For example, the year 1900 is not a leap year; the year 2000 is a leap year. <image> In this problem, you have been given two dates and your task is to calculate how many days are between them. Note, that leap years have unusual number of days in February. Look at the sample to understand what borders are included in the aswer. Input The first two lines contain two dates, each date is in the format yyyy:mm:dd (1900 ≀ yyyy ≀ 2038 and yyyy:mm:dd is a legal date). Output Print a single integer β€” the answer to the problem. Examples Input 1900:01:01 2038:12:31 Output 50768 Input 1996:03:09 1991:11:12 Output 1579 Tags: brute force, implementation Correct Solution: ``` import datetime tA = datetime.datetime.strptime(input(),"%Y:%m:%d") tB = datetime.datetime.strptime(input(),"%Y:%m:%d") print(abs((tB-tA).days)) ```
6,110
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Calendars in widespread use today include the Gregorian calendar, which is the de facto international standard, and is used almost everywhere in the world for civil purposes. The Gregorian reform modified the Julian calendar's scheme of leap years as follows: Every year that is exactly divisible by four is a leap year, except for years that are exactly divisible by 100; the centurial years that are exactly divisible by 400 are still leap years. For example, the year 1900 is not a leap year; the year 2000 is a leap year. <image> In this problem, you have been given two dates and your task is to calculate how many days are between them. Note, that leap years have unusual number of days in February. Look at the sample to understand what borders are included in the aswer. Input The first two lines contain two dates, each date is in the format yyyy:mm:dd (1900 ≀ yyyy ≀ 2038 and yyyy:mm:dd is a legal date). Output Print a single integer β€” the answer to the problem. Examples Input 1900:01:01 2038:12:31 Output 50768 Input 1996:03:09 1991:11:12 Output 1579 Submitted Solution: ``` from datetime import date s1=list(map(int,input().split(':'))) s2=list(map(int,input().split(':'))) a = date(s1[0],s1[1],s1[2]) b = date(s2[0],s2[1],s2[2]) x=abs((a-b).days) print(x) ``` Yes
6,111
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Calendars in widespread use today include the Gregorian calendar, which is the de facto international standard, and is used almost everywhere in the world for civil purposes. The Gregorian reform modified the Julian calendar's scheme of leap years as follows: Every year that is exactly divisible by four is a leap year, except for years that are exactly divisible by 100; the centurial years that are exactly divisible by 400 are still leap years. For example, the year 1900 is not a leap year; the year 2000 is a leap year. <image> In this problem, you have been given two dates and your task is to calculate how many days are between them. Note, that leap years have unusual number of days in February. Look at the sample to understand what borders are included in the aswer. Input The first two lines contain two dates, each date is in the format yyyy:mm:dd (1900 ≀ yyyy ≀ 2038 and yyyy:mm:dd is a legal date). Output Print a single integer β€” the answer to the problem. Examples Input 1900:01:01 2038:12:31 Output 50768 Input 1996:03:09 1991:11:12 Output 1579 Submitted Solution: ``` def s(): import datetime dt = datetime.datetime print(abs((dt(*list(map(int,input().split(':'))))-dt(*list(map(int,input().split(':'))))).days)) s() ``` Yes
6,112
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Calendars in widespread use today include the Gregorian calendar, which is the de facto international standard, and is used almost everywhere in the world for civil purposes. The Gregorian reform modified the Julian calendar's scheme of leap years as follows: Every year that is exactly divisible by four is a leap year, except for years that are exactly divisible by 100; the centurial years that are exactly divisible by 400 are still leap years. For example, the year 1900 is not a leap year; the year 2000 is a leap year. <image> In this problem, you have been given two dates and your task is to calculate how many days are between them. Note, that leap years have unusual number of days in February. Look at the sample to understand what borders are included in the aswer. Input The first two lines contain two dates, each date is in the format yyyy:mm:dd (1900 ≀ yyyy ≀ 2038 and yyyy:mm:dd is a legal date). Output Print a single integer β€” the answer to the problem. Examples Input 1900:01:01 2038:12:31 Output 50768 Input 1996:03:09 1991:11:12 Output 1579 Submitted Solution: ``` import sys a = [int(x) for x in sys.stdin.readline().strip().split(":")] b = [int(x) for x in sys.stdin.readline().strip().split(":")] stuff = [a, b] stuff = sorted(stuff) begin = stuff[0] end = stuff[1] year1 = begin[0] if begin[1] <= 2 else begin[0] + 1 year2 = end[0] - 1 if end[1] <= 2 else end[0] leaps = 0 for i in range(year1, year2 + 1): if((i % 4 == 0 and i % 100 != 0) or i % 400 == 0): #print(i) leaps += 1 days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] sums = 0 b = 0 for i in range(begin[1], 12): b += days[i] b += (days[begin[1] - 1] - begin[2]) a = 0 for i in range(0, end[1] - 1): a += days[i] a += end[2] sums = sums + a + b sums += 365 * ((end[0]) - (begin[0] + 1)) sums += leaps print(sums) ``` Yes
6,113
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Calendars in widespread use today include the Gregorian calendar, which is the de facto international standard, and is used almost everywhere in the world for civil purposes. The Gregorian reform modified the Julian calendar's scheme of leap years as follows: Every year that is exactly divisible by four is a leap year, except for years that are exactly divisible by 100; the centurial years that are exactly divisible by 400 are still leap years. For example, the year 1900 is not a leap year; the year 2000 is a leap year. <image> In this problem, you have been given two dates and your task is to calculate how many days are between them. Note, that leap years have unusual number of days in February. Look at the sample to understand what borders are included in the aswer. Input The first two lines contain two dates, each date is in the format yyyy:mm:dd (1900 ≀ yyyy ≀ 2038 and yyyy:mm:dd is a legal date). Output Print a single integer β€” the answer to the problem. Examples Input 1900:01:01 2038:12:31 Output 50768 Input 1996:03:09 1991:11:12 Output 1579 Submitted Solution: ``` from datetime import date list1 = input().split(':') list2 = input().split(':') d0 = date(int(list1[0]),int(list1[1]),int(list1[2])) d1 = date(int(list2[0]),int(list2[1]),int(list2[2])) if d0<d1: delta = d1 - d0 else: delta = d0-d1 print(delta.days) ``` Yes
6,114
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Calendars in widespread use today include the Gregorian calendar, which is the de facto international standard, and is used almost everywhere in the world for civil purposes. The Gregorian reform modified the Julian calendar's scheme of leap years as follows: Every year that is exactly divisible by four is a leap year, except for years that are exactly divisible by 100; the centurial years that are exactly divisible by 400 are still leap years. For example, the year 1900 is not a leap year; the year 2000 is a leap year. <image> In this problem, you have been given two dates and your task is to calculate how many days are between them. Note, that leap years have unusual number of days in February. Look at the sample to understand what borders are included in the aswer. Input The first two lines contain two dates, each date is in the format yyyy:mm:dd (1900 ≀ yyyy ≀ 2038 and yyyy:mm:dd is a legal date). Output Print a single integer β€” the answer to the problem. Examples Input 1900:01:01 2038:12:31 Output 50768 Input 1996:03:09 1991:11:12 Output 1579 Submitted Solution: ``` def leapyear(a): if a%400 == 0: return True elif a%100 == 0: return False elif a%4==0: return True # ============================================================================= # a1 = '1949:07:09' # a2 = '1901:10:24' # ============================================================================= a1 = input() a2 = input() if int(a1[:4]) > int(a2[:4]): temp = a1 a1 = a2 a2 = temp y1,m1,d1 = a1.split(':') y2,m2,d2 = a2.split(':') y1=int(y1) d1=int(d1) y2=int(y2) d2=int(d2) months = {'01':31, '02':28, '03':31, '04':30, '05':31, '06':30, '07':31, '08':31, '09':30, '10':31, '11':30, '12':31} rem_months = {'01':334, '02':306, '03':275, '04':245, '05':214, '06':184, '07':153, '08':122, '09':92, '10':61, '11':31, '12':0} end_months = {'01':0, '02':31, '03':59, '04':90, '05':120, '06':151, '07':181, '08':212, '09':243, '10':273, '11':304, '12':334} res = 0 #checking whether first year is leap year if m1>02 if m1!='02' or m1!='01': res += (months[m1] - d1) res += (rem_months[m1]) else: if y1%4==0 and leapyear(y1)==True: if m1=='01': res += (months[str(m1)] - d1) res += 29 else: res += (29-d1) else: if m1=='01': res += (months[str(m1)] - d1) res += 28 else: res += (28-d1) res += (rem_months['03']) y1 += 1 while y1<y2: if leapyear(y1)==True: res += 366 else : res += 365 y1 += 1 if leapyear(y2)==True: res += end_months[m2] res += d2 if m2 !='02' and m1 != '01': res += 1 else: res += end_months[m2] res += d2 print(res) ``` No
6,115
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Calendars in widespread use today include the Gregorian calendar, which is the de facto international standard, and is used almost everywhere in the world for civil purposes. The Gregorian reform modified the Julian calendar's scheme of leap years as follows: Every year that is exactly divisible by four is a leap year, except for years that are exactly divisible by 100; the centurial years that are exactly divisible by 400 are still leap years. For example, the year 1900 is not a leap year; the year 2000 is a leap year. <image> In this problem, you have been given two dates and your task is to calculate how many days are between them. Note, that leap years have unusual number of days in February. Look at the sample to understand what borders are included in the aswer. Input The first two lines contain two dates, each date is in the format yyyy:mm:dd (1900 ≀ yyyy ≀ 2038 and yyyy:mm:dd is a legal date). Output Print a single integer β€” the answer to the problem. Examples Input 1900:01:01 2038:12:31 Output 50768 Input 1996:03:09 1991:11:12 Output 1579 Submitted Solution: ``` def leapyear(a): if a%400 == 0: return True elif a%100 == 0: return False elif a%4==0: return True a1 = input() a2 = input() if int(a1[:4]) > int(a2[:4]): temp = a1 a1 = a2 a2 = temp y1,m1,d1 = a1.split(':') y2,m2,d2 = a2.split(':') y1=int(y1) d1=int(d1) y2=int(y2) d2=int(d2) months = {'01':31, '02':28, '03':31, '04':30, '05':31, '06':30, '07':31, '08':31, '09':30, '10':31, '11':30, '12':31} rem_months = {'01':334, '02':306, '03':275, '04':245, '05':214, '06':184, '07':153, '08':123, '09':92, '10':62, '11':31, '12':0} end_months = {'01':0, '02':31, '03':59, '04':90, '05':120, '06':151, '07':181, '08':212, '09':243, '10':273, '11':304, '12':334} res = 0 #checking whether first year is leap year if m1>02 if m1!='02' or m1!='01': res += (months[m1] - d1) res += (rem_months[m1]) else: if y1%4==0 and leapyear(y1)==True: if m1=='01': res += (months[str(m1)] - d1) res += 29 else: res += (29-d1) else: if m1=='01': res += (months[str(m1)] - d1) res += 28 else: res += (28-d1) res += (rem_months['03']) y1 += 1 while y1<y2: if leapyear(y1)==True: res += 366 else : res += 365 y1 += 1 if leapyear(y2)==True: res += end_months[m2] res += d2 if m2 !='02' and m1 != '01': res += 1 else: res += end_months[m2] res += d2 print(res) ``` No
6,116
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Calendars in widespread use today include the Gregorian calendar, which is the de facto international standard, and is used almost everywhere in the world for civil purposes. The Gregorian reform modified the Julian calendar's scheme of leap years as follows: Every year that is exactly divisible by four is a leap year, except for years that are exactly divisible by 100; the centurial years that are exactly divisible by 400 are still leap years. For example, the year 1900 is not a leap year; the year 2000 is a leap year. <image> In this problem, you have been given two dates and your task is to calculate how many days are between them. Note, that leap years have unusual number of days in February. Look at the sample to understand what borders are included in the aswer. Input The first two lines contain two dates, each date is in the format yyyy:mm:dd (1900 ≀ yyyy ≀ 2038 and yyyy:mm:dd is a legal date). Output Print a single integer β€” the answer to the problem. Examples Input 1900:01:01 2038:12:31 Output 50768 Input 1996:03:09 1991:11:12 Output 1579 Submitted Solution: ``` from collections import Counter import string import math dicti={'1':31,'2':28,'3':31,'4':30,'5':31,'6':30,'7':31,'8':31 ,'9':30,'10':31,'11':30,'12':31} def array_int(): return [int(i) for i in input().split()] def vary(number_of_variables): if number_of_variables==1: return int(input()) if number_of_variables>=2: return map(int,input().split()) def makedict(var): return dict(Counter(var)) mod=1000000007 date1=input() date2=input() year1=int(date1[:4]) year2=int(date2[:4]) day1=int(date1[8:]) day2=int(date2[8:]) month1=int(date1[5:7]) month2=int(date2[5:7]) class Date: def __init__(self, d, m, y): self.d = d self.m = m self.y = y monthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ] def countLeapYears(d): years = d.y if (d.m <= 2): years-= 1 return int(years / 4 - years / 100 + years / 400 ) def getDifference(dt1, dt2) : n1 = dt1.y * 365 + dt1.d # Add days for months in given date for i in range(0, dt1.m - 1) : n1 += monthDays[i] # Since every leap year is of 366 days, # Add a day for every leap year n1 += countLeapYears(dt1) # SIMILARLY, COUNT TOTAL NUMBER OF DAYS BEFORE 'dt2' n2 = dt2.y * 365 + dt2.d for i in range(0, dt2.m - 1) : n2 += monthDays[i] n2 += countLeapYears(dt2) # return difference between two counts return (n2 - n1) # Driver program dt1 = Date(day1, month1, year1 ) dt2 = Date(day2, month2, year2 ) print(abs(getDifference(dt1, dt2))) ``` No
6,117
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Calendars in widespread use today include the Gregorian calendar, which is the de facto international standard, and is used almost everywhere in the world for civil purposes. The Gregorian reform modified the Julian calendar's scheme of leap years as follows: Every year that is exactly divisible by four is a leap year, except for years that are exactly divisible by 100; the centurial years that are exactly divisible by 400 are still leap years. For example, the year 1900 is not a leap year; the year 2000 is a leap year. <image> In this problem, you have been given two dates and your task is to calculate how many days are between them. Note, that leap years have unusual number of days in February. Look at the sample to understand what borders are included in the aswer. Input The first two lines contain two dates, each date is in the format yyyy:mm:dd (1900 ≀ yyyy ≀ 2038 and yyyy:mm:dd is a legal date). Output Print a single integer β€” the answer to the problem. Examples Input 1900:01:01 2038:12:31 Output 50768 Input 1996:03:09 1991:11:12 Output 1579 Submitted Solution: ``` def get(y, m, d): if(m < 3): --y m += 12 return 365 * y + y // 4 - y //100 + y//400 + (153*m-457)//5+d-306 a1 = input().split(':') a2 = input().split(':') print(abs(get(int(a1[0]),int(a1[1]),int(a1[2])) - get(int(a2[0]),int(a2[1]),int(a2[2])))) ``` No
6,118
Provide tags and a correct Python 3 solution for this coding contest problem. You are an adventurer currently journeying inside an evil temple. After defeating a couple of weak zombies, you arrived at a square room consisting of tiles forming an n Γ— n grid. The rows are numbered 1 through n from top to bottom, and the columns are numbered 1 through n from left to right. At the far side of the room lies a door locked with evil magical forces. The following inscriptions are written on the door: The cleaning of all evil will awaken the door! Being a very senior adventurer, you immediately realize what this means. You notice that every single cell in the grid are initially evil. You should purify all of these cells. The only method of tile purification known to you is by casting the "Purification" spell. You cast this spell on a single tile β€” then, all cells that are located in the same row and all cells that are located in the same column as the selected tile become purified (including the selected tile)! It is allowed to purify a cell more than once. You would like to purify all n Γ— n cells while minimizing the number of times you cast the "Purification" spell. This sounds very easy, but you just noticed that some tiles are particularly more evil than the other tiles. You cannot cast the "Purification" spell on those particularly more evil tiles, not even after they have been purified. They can still be purified if a cell sharing the same row or the same column gets selected by the "Purification" spell. Please find some way to purify all the cells with the minimum number of spells cast. Print -1 if there is no such way. Input The first line will contain a single integer n (1 ≀ n ≀ 100). Then, n lines follows, each contains n characters. The j-th character in the i-th row represents the cell located at row i and column j. It will be the character 'E' if it is a particularly more evil cell, and '.' otherwise. Output If there exists no way to purify all the cells, output -1. Otherwise, if your solution casts x "Purification" spells (where x is the minimum possible number of spells), output x lines. Each line should consist of two integers denoting the row and column numbers of the cell on which you should cast the "Purification" spell. Examples Input 3 .E. E.E .E. Output 1 1 2 2 3 3 Input 3 EEE E.. E.E Output -1 Input 5 EE.EE E.EE. E...E .EE.E EE.EE Output 3 3 1 3 2 2 4 4 5 3 Note The first example is illustrated as follows. Purple tiles are evil tiles that have not yet been purified. Red tile is the tile on which "Purification" is cast. Yellow tiles are the tiles being purified as a result of the current "Purification" spell. Green tiles are tiles that have been purified previously. <image> In the second example, it is impossible to purify the cell located at row 1 and column 1. For the third example: <image> Tags: constructive algorithms, greedy Correct Solution: ``` n = int(input()) a = [] for i in range(n): a.append(input()) if 'E' * n in a and ('E',) * n in zip(*a): print(-1) elif 'E' * n in a: for j, s in enumerate(map(lambda x: ''.join(x), zip(*a))): for i, c in enumerate(s): if c == '.': print(i + 1, j + 1) break else: for i, s in enumerate(a): for j, c in enumerate(s): if c == '.': print(i + 1, j + 1) break ```
6,119
Provide tags and a correct Python 3 solution for this coding contest problem. You are an adventurer currently journeying inside an evil temple. After defeating a couple of weak zombies, you arrived at a square room consisting of tiles forming an n Γ— n grid. The rows are numbered 1 through n from top to bottom, and the columns are numbered 1 through n from left to right. At the far side of the room lies a door locked with evil magical forces. The following inscriptions are written on the door: The cleaning of all evil will awaken the door! Being a very senior adventurer, you immediately realize what this means. You notice that every single cell in the grid are initially evil. You should purify all of these cells. The only method of tile purification known to you is by casting the "Purification" spell. You cast this spell on a single tile β€” then, all cells that are located in the same row and all cells that are located in the same column as the selected tile become purified (including the selected tile)! It is allowed to purify a cell more than once. You would like to purify all n Γ— n cells while minimizing the number of times you cast the "Purification" spell. This sounds very easy, but you just noticed that some tiles are particularly more evil than the other tiles. You cannot cast the "Purification" spell on those particularly more evil tiles, not even after they have been purified. They can still be purified if a cell sharing the same row or the same column gets selected by the "Purification" spell. Please find some way to purify all the cells with the minimum number of spells cast. Print -1 if there is no such way. Input The first line will contain a single integer n (1 ≀ n ≀ 100). Then, n lines follows, each contains n characters. The j-th character in the i-th row represents the cell located at row i and column j. It will be the character 'E' if it is a particularly more evil cell, and '.' otherwise. Output If there exists no way to purify all the cells, output -1. Otherwise, if your solution casts x "Purification" spells (where x is the minimum possible number of spells), output x lines. Each line should consist of two integers denoting the row and column numbers of the cell on which you should cast the "Purification" spell. Examples Input 3 .E. E.E .E. Output 1 1 2 2 3 3 Input 3 EEE E.. E.E Output -1 Input 5 EE.EE E.EE. E...E .EE.E EE.EE Output 3 3 1 3 2 2 4 4 5 3 Note The first example is illustrated as follows. Purple tiles are evil tiles that have not yet been purified. Red tile is the tile on which "Purification" is cast. Yellow tiles are the tiles being purified as a result of the current "Purification" spell. Green tiles are tiles that have been purified previously. <image> In the second example, it is impossible to purify the cell located at row 1 and column 1. For the third example: <image> Tags: constructive algorithms, greedy Correct Solution: ``` n = int(input()) c = [list(input()) for _ in range(n)] r = set() s = set() rows = set() cols = set() for i in range(n): for j in range(n): if c[i][j] == "." and (i not in rows): r.add((i+1, j+1)) rows.add(i) break for i in range(n): for j in range(n): if c[j][i] == "." and (i not in cols): s.add((j+1, i+1)) cols.add(i) break if not set(range(n)) - rows: print("\n".join(map(lambda x: str(x[0]) + " " + str(x[1]), r))) elif not set(range(n)) - cols: print("\n".join(map(lambda x: str(x[0]) + " " + str(x[1]), s))) else: print(-1) ```
6,120
Provide tags and a correct Python 3 solution for this coding contest problem. You are an adventurer currently journeying inside an evil temple. After defeating a couple of weak zombies, you arrived at a square room consisting of tiles forming an n Γ— n grid. The rows are numbered 1 through n from top to bottom, and the columns are numbered 1 through n from left to right. At the far side of the room lies a door locked with evil magical forces. The following inscriptions are written on the door: The cleaning of all evil will awaken the door! Being a very senior adventurer, you immediately realize what this means. You notice that every single cell in the grid are initially evil. You should purify all of these cells. The only method of tile purification known to you is by casting the "Purification" spell. You cast this spell on a single tile β€” then, all cells that are located in the same row and all cells that are located in the same column as the selected tile become purified (including the selected tile)! It is allowed to purify a cell more than once. You would like to purify all n Γ— n cells while minimizing the number of times you cast the "Purification" spell. This sounds very easy, but you just noticed that some tiles are particularly more evil than the other tiles. You cannot cast the "Purification" spell on those particularly more evil tiles, not even after they have been purified. They can still be purified if a cell sharing the same row or the same column gets selected by the "Purification" spell. Please find some way to purify all the cells with the minimum number of spells cast. Print -1 if there is no such way. Input The first line will contain a single integer n (1 ≀ n ≀ 100). Then, n lines follows, each contains n characters. The j-th character in the i-th row represents the cell located at row i and column j. It will be the character 'E' if it is a particularly more evil cell, and '.' otherwise. Output If there exists no way to purify all the cells, output -1. Otherwise, if your solution casts x "Purification" spells (where x is the minimum possible number of spells), output x lines. Each line should consist of two integers denoting the row and column numbers of the cell on which you should cast the "Purification" spell. Examples Input 3 .E. E.E .E. Output 1 1 2 2 3 3 Input 3 EEE E.. E.E Output -1 Input 5 EE.EE E.EE. E...E .EE.E EE.EE Output 3 3 1 3 2 2 4 4 5 3 Note The first example is illustrated as follows. Purple tiles are evil tiles that have not yet been purified. Red tile is the tile on which "Purification" is cast. Yellow tiles are the tiles being purified as a result of the current "Purification" spell. Green tiles are tiles that have been purified previously. <image> In the second example, it is impossible to purify the cell located at row 1 and column 1. For the third example: <image> Tags: constructive algorithms, greedy Correct Solution: ``` import sys from functools import lru_cache, cmp_to_key from heapq import merge, heapify, heappop, heappush from math import * from collections import defaultdict as dd, deque, Counter as C from itertools import combinations as comb, permutations as perm from bisect import bisect_left as bl, bisect_right as br, bisect from time import perf_counter from fractions import Fraction # sys.setrecursionlimit(int(pow(10, 6))) # sys.stdin = open("input.txt", "r") # sys.stdout = open("output.txt", "w") mod = int(pow(10, 9) + 7) mod2 = 998244353 def data(): return sys.stdin.readline().strip() def out(*var, end="\n"): sys.stdout.write(' '.join(map(str, var))+end) def l(): return list(sp()) def sl(): return list(ssp()) def sp(): return map(int, data().split()) def ssp(): return map(str, data().split()) def l1d(n, val=0): return [val for i in range(n)] def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)] # @lru_cache(None) n=int(input()) A=[list(input()) for _ in range(n)] r=c=0 for i in range(n): if(A[i].count(".")==0): r+=1 for i in range(n): x=[A[j][i] for j in range(n)] if(x.count(".")==0): c+=1 if(r>0 and c>0): print(-1) exit() if(c==0): for i in range(n): for j in range(n): if(A[j][i]=="."): print(j+1,i+1) break elif(r==0): for i in range(n): for j in range(n): if(A[i][j]=="."): print(i+1,j+1) break ```
6,121
Provide tags and a correct Python 3 solution for this coding contest problem. You are an adventurer currently journeying inside an evil temple. After defeating a couple of weak zombies, you arrived at a square room consisting of tiles forming an n Γ— n grid. The rows are numbered 1 through n from top to bottom, and the columns are numbered 1 through n from left to right. At the far side of the room lies a door locked with evil magical forces. The following inscriptions are written on the door: The cleaning of all evil will awaken the door! Being a very senior adventurer, you immediately realize what this means. You notice that every single cell in the grid are initially evil. You should purify all of these cells. The only method of tile purification known to you is by casting the "Purification" spell. You cast this spell on a single tile β€” then, all cells that are located in the same row and all cells that are located in the same column as the selected tile become purified (including the selected tile)! It is allowed to purify a cell more than once. You would like to purify all n Γ— n cells while minimizing the number of times you cast the "Purification" spell. This sounds very easy, but you just noticed that some tiles are particularly more evil than the other tiles. You cannot cast the "Purification" spell on those particularly more evil tiles, not even after they have been purified. They can still be purified if a cell sharing the same row or the same column gets selected by the "Purification" spell. Please find some way to purify all the cells with the minimum number of spells cast. Print -1 if there is no such way. Input The first line will contain a single integer n (1 ≀ n ≀ 100). Then, n lines follows, each contains n characters. The j-th character in the i-th row represents the cell located at row i and column j. It will be the character 'E' if it is a particularly more evil cell, and '.' otherwise. Output If there exists no way to purify all the cells, output -1. Otherwise, if your solution casts x "Purification" spells (where x is the minimum possible number of spells), output x lines. Each line should consist of two integers denoting the row and column numbers of the cell on which you should cast the "Purification" spell. Examples Input 3 .E. E.E .E. Output 1 1 2 2 3 3 Input 3 EEE E.. E.E Output -1 Input 5 EE.EE E.EE. E...E .EE.E EE.EE Output 3 3 1 3 2 2 4 4 5 3 Note The first example is illustrated as follows. Purple tiles are evil tiles that have not yet been purified. Red tile is the tile on which "Purification" is cast. Yellow tiles are the tiles being purified as a result of the current "Purification" spell. Green tiles are tiles that have been purified previously. <image> In the second example, it is impossible to purify the cell located at row 1 and column 1. For the third example: <image> Tags: constructive algorithms, greedy Correct Solution: ``` n = int(input()) a = [] for i in range(n): a.append(input()) if 'E' * n in a and ('E',) * n in zip(*a): print(-1) elif 'E' * n in a: for j, s in enumerate(map(lambda x: ''.join(x), zip(*a))): for i, c in enumerate(s): if c == '.': print(i + 1, j + 1) break else: for i, s in enumerate(a): for j, c in enumerate(s): if c == '.': print(i + 1, j + 1) break # Made By Mostafa_Khaled ```
6,122
Provide tags and a correct Python 3 solution for this coding contest problem. You are an adventurer currently journeying inside an evil temple. After defeating a couple of weak zombies, you arrived at a square room consisting of tiles forming an n Γ— n grid. The rows are numbered 1 through n from top to bottom, and the columns are numbered 1 through n from left to right. At the far side of the room lies a door locked with evil magical forces. The following inscriptions are written on the door: The cleaning of all evil will awaken the door! Being a very senior adventurer, you immediately realize what this means. You notice that every single cell in the grid are initially evil. You should purify all of these cells. The only method of tile purification known to you is by casting the "Purification" spell. You cast this spell on a single tile β€” then, all cells that are located in the same row and all cells that are located in the same column as the selected tile become purified (including the selected tile)! It is allowed to purify a cell more than once. You would like to purify all n Γ— n cells while minimizing the number of times you cast the "Purification" spell. This sounds very easy, but you just noticed that some tiles are particularly more evil than the other tiles. You cannot cast the "Purification" spell on those particularly more evil tiles, not even after they have been purified. They can still be purified if a cell sharing the same row or the same column gets selected by the "Purification" spell. Please find some way to purify all the cells with the minimum number of spells cast. Print -1 if there is no such way. Input The first line will contain a single integer n (1 ≀ n ≀ 100). Then, n lines follows, each contains n characters. The j-th character in the i-th row represents the cell located at row i and column j. It will be the character 'E' if it is a particularly more evil cell, and '.' otherwise. Output If there exists no way to purify all the cells, output -1. Otherwise, if your solution casts x "Purification" spells (where x is the minimum possible number of spells), output x lines. Each line should consist of two integers denoting the row and column numbers of the cell on which you should cast the "Purification" spell. Examples Input 3 .E. E.E .E. Output 1 1 2 2 3 3 Input 3 EEE E.. E.E Output -1 Input 5 EE.EE E.EE. E...E .EE.E EE.EE Output 3 3 1 3 2 2 4 4 5 3 Note The first example is illustrated as follows. Purple tiles are evil tiles that have not yet been purified. Red tile is the tile on which "Purification" is cast. Yellow tiles are the tiles being purified as a result of the current "Purification" spell. Green tiles are tiles that have been purified previously. <image> In the second example, it is impossible to purify the cell located at row 1 and column 1. For the third example: <image> Tags: constructive algorithms, greedy Correct Solution: ``` n = int(input()) maze = [input().strip() for _ in range(n)] def go(by_row): global maze maze = list(zip(*maze)) can = True for i in range(n): if '.' not in maze[i]: can = False if can: for i in range(n): for j in range(n): if maze[i][j] == '.': print(i + 1, j + 1) if by_row else print(j + 1, i + 1) break return can if not go(0) and not go(1): print(-1) ```
6,123
Provide tags and a correct Python 3 solution for this coding contest problem. You are an adventurer currently journeying inside an evil temple. After defeating a couple of weak zombies, you arrived at a square room consisting of tiles forming an n Γ— n grid. The rows are numbered 1 through n from top to bottom, and the columns are numbered 1 through n from left to right. At the far side of the room lies a door locked with evil magical forces. The following inscriptions are written on the door: The cleaning of all evil will awaken the door! Being a very senior adventurer, you immediately realize what this means. You notice that every single cell in the grid are initially evil. You should purify all of these cells. The only method of tile purification known to you is by casting the "Purification" spell. You cast this spell on a single tile β€” then, all cells that are located in the same row and all cells that are located in the same column as the selected tile become purified (including the selected tile)! It is allowed to purify a cell more than once. You would like to purify all n Γ— n cells while minimizing the number of times you cast the "Purification" spell. This sounds very easy, but you just noticed that some tiles are particularly more evil than the other tiles. You cannot cast the "Purification" spell on those particularly more evil tiles, not even after they have been purified. They can still be purified if a cell sharing the same row or the same column gets selected by the "Purification" spell. Please find some way to purify all the cells with the minimum number of spells cast. Print -1 if there is no such way. Input The first line will contain a single integer n (1 ≀ n ≀ 100). Then, n lines follows, each contains n characters. The j-th character in the i-th row represents the cell located at row i and column j. It will be the character 'E' if it is a particularly more evil cell, and '.' otherwise. Output If there exists no way to purify all the cells, output -1. Otherwise, if your solution casts x "Purification" spells (where x is the minimum possible number of spells), output x lines. Each line should consist of two integers denoting the row and column numbers of the cell on which you should cast the "Purification" spell. Examples Input 3 .E. E.E .E. Output 1 1 2 2 3 3 Input 3 EEE E.. E.E Output -1 Input 5 EE.EE E.EE. E...E .EE.E EE.EE Output 3 3 1 3 2 2 4 4 5 3 Note The first example is illustrated as follows. Purple tiles are evil tiles that have not yet been purified. Red tile is the tile on which "Purification" is cast. Yellow tiles are the tiles being purified as a result of the current "Purification" spell. Green tiles are tiles that have been purified previously. <image> In the second example, it is impossible to purify the cell located at row 1 and column 1. For the third example: <image> Tags: constructive algorithms, greedy Correct Solution: ``` #------------------------template--------------------------# import os import sys from math import * from collections import * from fractions import * from bisect import * from heapq import* from io import BytesIO, IOBase def vsInput(): sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") def value():return tuple(map(int,input().split())) def array():return [int(i) for i in input().split()] def Int():return int(input()) def Str():return input() def arrayS():return [i for i in input().split()] #-------------------------code---------------------------# #vsInput() n=Int() row=defaultdict(list) col=defaultdict(list) points=[] for i in range(n): s=input() for j in range(n): if(s[j]=='.'): row[i].append((i+1,j+1)) col[j].append((i+1,j+1)) points.append((i,j)) ok=[False,False] for i in range(n): if(len(row[i])==0): ok[0]=True if(len(col[i])==0): ok[1]=True if(ok[0] and ok[1]): print(-1) exit() if(ok[1]): for i in range(n): print(*row[i][0]) else: for i in range(n): print(*col[i][0]) ```
6,124
Provide tags and a correct Python 3 solution for this coding contest problem. You are an adventurer currently journeying inside an evil temple. After defeating a couple of weak zombies, you arrived at a square room consisting of tiles forming an n Γ— n grid. The rows are numbered 1 through n from top to bottom, and the columns are numbered 1 through n from left to right. At the far side of the room lies a door locked with evil magical forces. The following inscriptions are written on the door: The cleaning of all evil will awaken the door! Being a very senior adventurer, you immediately realize what this means. You notice that every single cell in the grid are initially evil. You should purify all of these cells. The only method of tile purification known to you is by casting the "Purification" spell. You cast this spell on a single tile β€” then, all cells that are located in the same row and all cells that are located in the same column as the selected tile become purified (including the selected tile)! It is allowed to purify a cell more than once. You would like to purify all n Γ— n cells while minimizing the number of times you cast the "Purification" spell. This sounds very easy, but you just noticed that some tiles are particularly more evil than the other tiles. You cannot cast the "Purification" spell on those particularly more evil tiles, not even after they have been purified. They can still be purified if a cell sharing the same row or the same column gets selected by the "Purification" spell. Please find some way to purify all the cells with the minimum number of spells cast. Print -1 if there is no such way. Input The first line will contain a single integer n (1 ≀ n ≀ 100). Then, n lines follows, each contains n characters. The j-th character in the i-th row represents the cell located at row i and column j. It will be the character 'E' if it is a particularly more evil cell, and '.' otherwise. Output If there exists no way to purify all the cells, output -1. Otherwise, if your solution casts x "Purification" spells (where x is the minimum possible number of spells), output x lines. Each line should consist of two integers denoting the row and column numbers of the cell on which you should cast the "Purification" spell. Examples Input 3 .E. E.E .E. Output 1 1 2 2 3 3 Input 3 EEE E.. E.E Output -1 Input 5 EE.EE E.EE. E...E .EE.E EE.EE Output 3 3 1 3 2 2 4 4 5 3 Note The first example is illustrated as follows. Purple tiles are evil tiles that have not yet been purified. Red tile is the tile on which "Purification" is cast. Yellow tiles are the tiles being purified as a result of the current "Purification" spell. Green tiles are tiles that have been purified previously. <image> In the second example, it is impossible to purify the cell located at row 1 and column 1. For the third example: <image> Tags: constructive algorithms, greedy Correct Solution: ``` n = int(input()) pl = [0] * 100 p = [[] for i in range(100)] s = [str() for i in range(100)] cp = [0] * 100 rp = [0] * 100 for i in range(n): s[i] = str(input()) for j in range(len(s[i])): if s[i][j] == '.': rp[i] += 1 cp[j] += 1 tag1 = 0 for i in range(n): if cp[i] == 0: tag1 = 1 break if tag1 == 0: for i in range(n): for j in range(n): if s[i][j] == '.': p[i].append(j) pl[i] += 1 for i in range(n): for j in range(pl[i]): cp[p[i][j]] -= 1 if cp[p[i][j]] == 0: print(i + 1, p[i][j] + 1) exit() for i in range(n): if rp[i] == 0: print('-1') exit() for i in range(n): for j in range(n): if s[j][i] == '.': p[i].append(j) pl[i] += 1 for i in range(n): for j in range(pl[i]): rp[p[i][j]] -= 1 if rp[p[i][j]] == 0: print(p[i][j] + 1, i + 1) ```
6,125
Provide tags and a correct Python 3 solution for this coding contest problem. You are an adventurer currently journeying inside an evil temple. After defeating a couple of weak zombies, you arrived at a square room consisting of tiles forming an n Γ— n grid. The rows are numbered 1 through n from top to bottom, and the columns are numbered 1 through n from left to right. At the far side of the room lies a door locked with evil magical forces. The following inscriptions are written on the door: The cleaning of all evil will awaken the door! Being a very senior adventurer, you immediately realize what this means. You notice that every single cell in the grid are initially evil. You should purify all of these cells. The only method of tile purification known to you is by casting the "Purification" spell. You cast this spell on a single tile β€” then, all cells that are located in the same row and all cells that are located in the same column as the selected tile become purified (including the selected tile)! It is allowed to purify a cell more than once. You would like to purify all n Γ— n cells while minimizing the number of times you cast the "Purification" spell. This sounds very easy, but you just noticed that some tiles are particularly more evil than the other tiles. You cannot cast the "Purification" spell on those particularly more evil tiles, not even after they have been purified. They can still be purified if a cell sharing the same row or the same column gets selected by the "Purification" spell. Please find some way to purify all the cells with the minimum number of spells cast. Print -1 if there is no such way. Input The first line will contain a single integer n (1 ≀ n ≀ 100). Then, n lines follows, each contains n characters. The j-th character in the i-th row represents the cell located at row i and column j. It will be the character 'E' if it is a particularly more evil cell, and '.' otherwise. Output If there exists no way to purify all the cells, output -1. Otherwise, if your solution casts x "Purification" spells (where x is the minimum possible number of spells), output x lines. Each line should consist of two integers denoting the row and column numbers of the cell on which you should cast the "Purification" spell. Examples Input 3 .E. E.E .E. Output 1 1 2 2 3 3 Input 3 EEE E.. E.E Output -1 Input 5 EE.EE E.EE. E...E .EE.E EE.EE Output 3 3 1 3 2 2 4 4 5 3 Note The first example is illustrated as follows. Purple tiles are evil tiles that have not yet been purified. Red tile is the tile on which "Purification" is cast. Yellow tiles are the tiles being purified as a result of the current "Purification" spell. Green tiles are tiles that have been purified previously. <image> In the second example, it is impossible to purify the cell located at row 1 and column 1. For the third example: <image> Tags: constructive algorithms, greedy Correct Solution: ``` n = int(input()) grid = [input() for line in range(n)] total = sum([ln.count('.') for ln in grid]) rowsWSpcN = len([True for ln in grid if '.' in ln]) colsWSpcN = len([True for col in range(n) if '.' in [ln[col] for ln in grid]]) rowsWSpc = [ln.count('.') for ln in grid] colsWSpc = [[ln[col] for ln in grid].count('.') for col in range(n)] #print(rowsWSpc,colsWSpc) used = 0 if 0 in rowsWSpc and 0 in colsWSpc: print(-1) elif 0 not in rowsWSpc: for row in range(n): print(row+1,grid[row].index('.')+1) else: for col in range(n): print([grid[row][col] for row in range(n)].index('.')+1,col+1) #assert total == used #print(used) #print('\n'.join(['%s %s'%(str(col+1),str(row+1)) for col,row in used])) ```
6,126
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are an adventurer currently journeying inside an evil temple. After defeating a couple of weak zombies, you arrived at a square room consisting of tiles forming an n Γ— n grid. The rows are numbered 1 through n from top to bottom, and the columns are numbered 1 through n from left to right. At the far side of the room lies a door locked with evil magical forces. The following inscriptions are written on the door: The cleaning of all evil will awaken the door! Being a very senior adventurer, you immediately realize what this means. You notice that every single cell in the grid are initially evil. You should purify all of these cells. The only method of tile purification known to you is by casting the "Purification" spell. You cast this spell on a single tile β€” then, all cells that are located in the same row and all cells that are located in the same column as the selected tile become purified (including the selected tile)! It is allowed to purify a cell more than once. You would like to purify all n Γ— n cells while minimizing the number of times you cast the "Purification" spell. This sounds very easy, but you just noticed that some tiles are particularly more evil than the other tiles. You cannot cast the "Purification" spell on those particularly more evil tiles, not even after they have been purified. They can still be purified if a cell sharing the same row or the same column gets selected by the "Purification" spell. Please find some way to purify all the cells with the minimum number of spells cast. Print -1 if there is no such way. Input The first line will contain a single integer n (1 ≀ n ≀ 100). Then, n lines follows, each contains n characters. The j-th character in the i-th row represents the cell located at row i and column j. It will be the character 'E' if it is a particularly more evil cell, and '.' otherwise. Output If there exists no way to purify all the cells, output -1. Otherwise, if your solution casts x "Purification" spells (where x is the minimum possible number of spells), output x lines. Each line should consist of two integers denoting the row and column numbers of the cell on which you should cast the "Purification" spell. Examples Input 3 .E. E.E .E. Output 1 1 2 2 3 3 Input 3 EEE E.. E.E Output -1 Input 5 EE.EE E.EE. E...E .EE.E EE.EE Output 3 3 1 3 2 2 4 4 5 3 Note The first example is illustrated as follows. Purple tiles are evil tiles that have not yet been purified. Red tile is the tile on which "Purification" is cast. Yellow tiles are the tiles being purified as a result of the current "Purification" spell. Green tiles are tiles that have been purified previously. <image> In the second example, it is impossible to purify the cell located at row 1 and column 1. For the third example: <image> Submitted Solution: ``` n = int(input()) maze = [input().strip() for _ in range(n)] def go(x): global maze maze = list(zip(*maze)) check = True for i in range(n): if '.' not in maze[i]: check = False if check: for i in range(n): for j in range(n): if maze[i][j] == '.': print(i + 1, j + 1) if x else print(j + 1, i + 1) break return check if not go(0) and not go(1): print(-1) ``` Yes
6,127
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are an adventurer currently journeying inside an evil temple. After defeating a couple of weak zombies, you arrived at a square room consisting of tiles forming an n Γ— n grid. The rows are numbered 1 through n from top to bottom, and the columns are numbered 1 through n from left to right. At the far side of the room lies a door locked with evil magical forces. The following inscriptions are written on the door: The cleaning of all evil will awaken the door! Being a very senior adventurer, you immediately realize what this means. You notice that every single cell in the grid are initially evil. You should purify all of these cells. The only method of tile purification known to you is by casting the "Purification" spell. You cast this spell on a single tile β€” then, all cells that are located in the same row and all cells that are located in the same column as the selected tile become purified (including the selected tile)! It is allowed to purify a cell more than once. You would like to purify all n Γ— n cells while minimizing the number of times you cast the "Purification" spell. This sounds very easy, but you just noticed that some tiles are particularly more evil than the other tiles. You cannot cast the "Purification" spell on those particularly more evil tiles, not even after they have been purified. They can still be purified if a cell sharing the same row or the same column gets selected by the "Purification" spell. Please find some way to purify all the cells with the minimum number of spells cast. Print -1 if there is no such way. Input The first line will contain a single integer n (1 ≀ n ≀ 100). Then, n lines follows, each contains n characters. The j-th character in the i-th row represents the cell located at row i and column j. It will be the character 'E' if it is a particularly more evil cell, and '.' otherwise. Output If there exists no way to purify all the cells, output -1. Otherwise, if your solution casts x "Purification" spells (where x is the minimum possible number of spells), output x lines. Each line should consist of two integers denoting the row and column numbers of the cell on which you should cast the "Purification" spell. Examples Input 3 .E. E.E .E. Output 1 1 2 2 3 3 Input 3 EEE E.. E.E Output -1 Input 5 EE.EE E.EE. E...E .EE.E EE.EE Output 3 3 1 3 2 2 4 4 5 3 Note The first example is illustrated as follows. Purple tiles are evil tiles that have not yet been purified. Red tile is the tile on which "Purification" is cast. Yellow tiles are the tiles being purified as a result of the current "Purification" spell. Green tiles are tiles that have been purified previously. <image> In the second example, it is impossible to purify the cell located at row 1 and column 1. For the third example: <image> Submitted Solution: ``` # Purification f = lambda: input() n = int(f()) m = [] for i in range(n): m.append(input()) fr = [] fc = [] fct = [False] *n for i in range(n): for j in range(n): if m[i][j] == '.': fr.append((i+1, j+1)) break for i in range(n): if len(fc) < n: for j in range(n): if len(fc) > n-1: break if m[i][j] == '.': if fct[j] == False: fct[j] = True fc.append((i+1, j+1)) #print(fr) #print(fc) if len(fr) == n: for i in range(n): print(fr[i][0], fr[i][1]) elif len(fc) == n: for i in range(n): print(fc[i][0], fc[i][1]) else: print(-1) ``` Yes
6,128
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are an adventurer currently journeying inside an evil temple. After defeating a couple of weak zombies, you arrived at a square room consisting of tiles forming an n Γ— n grid. The rows are numbered 1 through n from top to bottom, and the columns are numbered 1 through n from left to right. At the far side of the room lies a door locked with evil magical forces. The following inscriptions are written on the door: The cleaning of all evil will awaken the door! Being a very senior adventurer, you immediately realize what this means. You notice that every single cell in the grid are initially evil. You should purify all of these cells. The only method of tile purification known to you is by casting the "Purification" spell. You cast this spell on a single tile β€” then, all cells that are located in the same row and all cells that are located in the same column as the selected tile become purified (including the selected tile)! It is allowed to purify a cell more than once. You would like to purify all n Γ— n cells while minimizing the number of times you cast the "Purification" spell. This sounds very easy, but you just noticed that some tiles are particularly more evil than the other tiles. You cannot cast the "Purification" spell on those particularly more evil tiles, not even after they have been purified. They can still be purified if a cell sharing the same row or the same column gets selected by the "Purification" spell. Please find some way to purify all the cells with the minimum number of spells cast. Print -1 if there is no such way. Input The first line will contain a single integer n (1 ≀ n ≀ 100). Then, n lines follows, each contains n characters. The j-th character in the i-th row represents the cell located at row i and column j. It will be the character 'E' if it is a particularly more evil cell, and '.' otherwise. Output If there exists no way to purify all the cells, output -1. Otherwise, if your solution casts x "Purification" spells (where x is the minimum possible number of spells), output x lines. Each line should consist of two integers denoting the row and column numbers of the cell on which you should cast the "Purification" spell. Examples Input 3 .E. E.E .E. Output 1 1 2 2 3 3 Input 3 EEE E.. E.E Output -1 Input 5 EE.EE E.EE. E...E .EE.E EE.EE Output 3 3 1 3 2 2 4 4 5 3 Note The first example is illustrated as follows. Purple tiles are evil tiles that have not yet been purified. Red tile is the tile on which "Purification" is cast. Yellow tiles are the tiles being purified as a result of the current "Purification" spell. Green tiles are tiles that have been purified previously. <image> In the second example, it is impossible to purify the cell located at row 1 and column 1. For the third example: <image> Submitted Solution: ``` n = int(input()) s = [''] * n for i in range(n): s[i] = input() row, col = 0, 0 for i in range(n): for j in range(n): if s[i][j] == '.': break else: row = 1 break for i in range(n): for j in range(n): if s[j][i] == '.': break else: col = 1 break if row == col == 1: print(-1) exit() if row == 0: for i in range(n): for j in range(n): if s[i][j] == '.': print(i+1, j+1) break else: for i in range(n): for j in range(n): if s[j][i] == '.': print(j+1, i+1) break ``` Yes
6,129
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are an adventurer currently journeying inside an evil temple. After defeating a couple of weak zombies, you arrived at a square room consisting of tiles forming an n Γ— n grid. The rows are numbered 1 through n from top to bottom, and the columns are numbered 1 through n from left to right. At the far side of the room lies a door locked with evil magical forces. The following inscriptions are written on the door: The cleaning of all evil will awaken the door! Being a very senior adventurer, you immediately realize what this means. You notice that every single cell in the grid are initially evil. You should purify all of these cells. The only method of tile purification known to you is by casting the "Purification" spell. You cast this spell on a single tile β€” then, all cells that are located in the same row and all cells that are located in the same column as the selected tile become purified (including the selected tile)! It is allowed to purify a cell more than once. You would like to purify all n Γ— n cells while minimizing the number of times you cast the "Purification" spell. This sounds very easy, but you just noticed that some tiles are particularly more evil than the other tiles. You cannot cast the "Purification" spell on those particularly more evil tiles, not even after they have been purified. They can still be purified if a cell sharing the same row or the same column gets selected by the "Purification" spell. Please find some way to purify all the cells with the minimum number of spells cast. Print -1 if there is no such way. Input The first line will contain a single integer n (1 ≀ n ≀ 100). Then, n lines follows, each contains n characters. The j-th character in the i-th row represents the cell located at row i and column j. It will be the character 'E' if it is a particularly more evil cell, and '.' otherwise. Output If there exists no way to purify all the cells, output -1. Otherwise, if your solution casts x "Purification" spells (where x is the minimum possible number of spells), output x lines. Each line should consist of two integers denoting the row and column numbers of the cell on which you should cast the "Purification" spell. Examples Input 3 .E. E.E .E. Output 1 1 2 2 3 3 Input 3 EEE E.. E.E Output -1 Input 5 EE.EE E.EE. E...E .EE.E EE.EE Output 3 3 1 3 2 2 4 4 5 3 Note The first example is illustrated as follows. Purple tiles are evil tiles that have not yet been purified. Red tile is the tile on which "Purification" is cast. Yellow tiles are the tiles being purified as a result of the current "Purification" spell. Green tiles are tiles that have been purified previously. <image> In the second example, it is impossible to purify the cell located at row 1 and column 1. For the third example: <image> Submitted Solution: ``` import sys input = sys.stdin.readline I = lambda : list(map(int,input().split())) n,=I() l=[] an=[] for i in range(n): x=input().strip() l.append(x) if '.' in x: an.append([i+1,x.index('.')+1]) if len(an)==n: for i in an: print(*i) else: an=[] for i in range(n): for j in range(n): if l[j][i]=='.': an.append([j+1,i+1]) break if len(an)==n: for i in an: print(*i) else: print(-1) ``` Yes
6,130
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are an adventurer currently journeying inside an evil temple. After defeating a couple of weak zombies, you arrived at a square room consisting of tiles forming an n Γ— n grid. The rows are numbered 1 through n from top to bottom, and the columns are numbered 1 through n from left to right. At the far side of the room lies a door locked with evil magical forces. The following inscriptions are written on the door: The cleaning of all evil will awaken the door! Being a very senior adventurer, you immediately realize what this means. You notice that every single cell in the grid are initially evil. You should purify all of these cells. The only method of tile purification known to you is by casting the "Purification" spell. You cast this spell on a single tile β€” then, all cells that are located in the same row and all cells that are located in the same column as the selected tile become purified (including the selected tile)! It is allowed to purify a cell more than once. You would like to purify all n Γ— n cells while minimizing the number of times you cast the "Purification" spell. This sounds very easy, but you just noticed that some tiles are particularly more evil than the other tiles. You cannot cast the "Purification" spell on those particularly more evil tiles, not even after they have been purified. They can still be purified if a cell sharing the same row or the same column gets selected by the "Purification" spell. Please find some way to purify all the cells with the minimum number of spells cast. Print -1 if there is no such way. Input The first line will contain a single integer n (1 ≀ n ≀ 100). Then, n lines follows, each contains n characters. The j-th character in the i-th row represents the cell located at row i and column j. It will be the character 'E' if it is a particularly more evil cell, and '.' otherwise. Output If there exists no way to purify all the cells, output -1. Otherwise, if your solution casts x "Purification" spells (where x is the minimum possible number of spells), output x lines. Each line should consist of two integers denoting the row and column numbers of the cell on which you should cast the "Purification" spell. Examples Input 3 .E. E.E .E. Output 1 1 2 2 3 3 Input 3 EEE E.. E.E Output -1 Input 5 EE.EE E.EE. E...E .EE.E EE.EE Output 3 3 1 3 2 2 4 4 5 3 Note The first example is illustrated as follows. Purple tiles are evil tiles that have not yet been purified. Red tile is the tile on which "Purification" is cast. Yellow tiles are the tiles being purified as a result of the current "Purification" spell. Green tiles are tiles that have been purified previously. <image> In the second example, it is impossible to purify the cell located at row 1 and column 1. For the third example: <image> Submitted Solution: ``` n = int(input()) c = [list(input()) for _ in range(n)] r = [] rows = set() cols = set() for i in range(n): for j in range(n): if c[i][j] == "." and (i not in rows or j not in cols): r.append((i+1, j+1)) rows.add(i) cols.add(i) break if not set(range(n)) - rows and not set(range(n)) - cols: print("\n".join(map(lambda x: str(x[0]) + " " + str(x[1]), r))) else: print(-1) ``` No
6,131
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are an adventurer currently journeying inside an evil temple. After defeating a couple of weak zombies, you arrived at a square room consisting of tiles forming an n Γ— n grid. The rows are numbered 1 through n from top to bottom, and the columns are numbered 1 through n from left to right. At the far side of the room lies a door locked with evil magical forces. The following inscriptions are written on the door: The cleaning of all evil will awaken the door! Being a very senior adventurer, you immediately realize what this means. You notice that every single cell in the grid are initially evil. You should purify all of these cells. The only method of tile purification known to you is by casting the "Purification" spell. You cast this spell on a single tile β€” then, all cells that are located in the same row and all cells that are located in the same column as the selected tile become purified (including the selected tile)! It is allowed to purify a cell more than once. You would like to purify all n Γ— n cells while minimizing the number of times you cast the "Purification" spell. This sounds very easy, but you just noticed that some tiles are particularly more evil than the other tiles. You cannot cast the "Purification" spell on those particularly more evil tiles, not even after they have been purified. They can still be purified if a cell sharing the same row or the same column gets selected by the "Purification" spell. Please find some way to purify all the cells with the minimum number of spells cast. Print -1 if there is no such way. Input The first line will contain a single integer n (1 ≀ n ≀ 100). Then, n lines follows, each contains n characters. The j-th character in the i-th row represents the cell located at row i and column j. It will be the character 'E' if it is a particularly more evil cell, and '.' otherwise. Output If there exists no way to purify all the cells, output -1. Otherwise, if your solution casts x "Purification" spells (where x is the minimum possible number of spells), output x lines. Each line should consist of two integers denoting the row and column numbers of the cell on which you should cast the "Purification" spell. Examples Input 3 .E. E.E .E. Output 1 1 2 2 3 3 Input 3 EEE E.. E.E Output -1 Input 5 EE.EE E.EE. E...E .EE.E EE.EE Output 3 3 1 3 2 2 4 4 5 3 Note The first example is illustrated as follows. Purple tiles are evil tiles that have not yet been purified. Red tile is the tile on which "Purification" is cast. Yellow tiles are the tiles being purified as a result of the current "Purification" spell. Green tiles are tiles that have been purified previously. <image> In the second example, it is impossible to purify the cell located at row 1 and column 1. For the third example: <image> Submitted Solution: ``` #------------------------template--------------------------# import os import sys from math import * from collections import * from fractions import * from bisect import * from heapq import* from io import BytesIO, IOBase def vsInput(): sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") def value():return tuple(map(int,input().split())) def array():return [int(i) for i in input().split()] def Int():return int(input()) def Str():return input() def arrayS():return [i for i in input().split()] #-------------------------code---------------------------# #vsInput() def GetMax(): ele=(-1,-1) score[ele]=-1 for i in score: if(score[i]>score[ele]): ele=i x,y=ele score[ele]=0 if(x not in row_over): for i in row[x]: score[i]-=1 if(y not in col_over): for i in col[y]: score[i]-=1 return (x,y) n=Int() row=defaultdict(list) col=defaultdict(list) points=[] for i in range(n): s=input() for j in range(n): if(s[j]=='.'): row[i].append((i,j)) col[j].append((i,j)) points.append((i,j)) row_over=set() col_over=set() ans=set() ok=[False,False] for i in range(n): if(len(row[i])==1): r,c=row[i][0] row_over.add(r) col_over.add(c) ans.add((r+1,c+1)) if(len(col[i])==1): r,c=col[i][0] row_over.add(r) col_over.add(c) ans.add((r+1,c+1)) if(len(row[i])==0): ok[0]=True if(len(col[i])==0): ok[1]=True if(ok[0] and ok[1]): print(-1) exit() score=defaultdict(int) for i in points: r,c=i if(r not in row_over): score[i]+=1 if(c not in col_over): score[i]+=1 # print(ans) while(len(row_over)!=n and len(col_over)!=n): x,y=GetMax() row_over.add(x) col_over.add(y) ans.add((x+1,y+1)) for i in ans: print(*i) ``` No
6,132
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are an adventurer currently journeying inside an evil temple. After defeating a couple of weak zombies, you arrived at a square room consisting of tiles forming an n Γ— n grid. The rows are numbered 1 through n from top to bottom, and the columns are numbered 1 through n from left to right. At the far side of the room lies a door locked with evil magical forces. The following inscriptions are written on the door: The cleaning of all evil will awaken the door! Being a very senior adventurer, you immediately realize what this means. You notice that every single cell in the grid are initially evil. You should purify all of these cells. The only method of tile purification known to you is by casting the "Purification" spell. You cast this spell on a single tile β€” then, all cells that are located in the same row and all cells that are located in the same column as the selected tile become purified (including the selected tile)! It is allowed to purify a cell more than once. You would like to purify all n Γ— n cells while minimizing the number of times you cast the "Purification" spell. This sounds very easy, but you just noticed that some tiles are particularly more evil than the other tiles. You cannot cast the "Purification" spell on those particularly more evil tiles, not even after they have been purified. They can still be purified if a cell sharing the same row or the same column gets selected by the "Purification" spell. Please find some way to purify all the cells with the minimum number of spells cast. Print -1 if there is no such way. Input The first line will contain a single integer n (1 ≀ n ≀ 100). Then, n lines follows, each contains n characters. The j-th character in the i-th row represents the cell located at row i and column j. It will be the character 'E' if it is a particularly more evil cell, and '.' otherwise. Output If there exists no way to purify all the cells, output -1. Otherwise, if your solution casts x "Purification" spells (where x is the minimum possible number of spells), output x lines. Each line should consist of two integers denoting the row and column numbers of the cell on which you should cast the "Purification" spell. Examples Input 3 .E. E.E .E. Output 1 1 2 2 3 3 Input 3 EEE E.. E.E Output -1 Input 5 EE.EE E.EE. E...E .EE.E EE.EE Output 3 3 1 3 2 2 4 4 5 3 Note The first example is illustrated as follows. Purple tiles are evil tiles that have not yet been purified. Red tile is the tile on which "Purification" is cast. Yellow tiles are the tiles being purified as a result of the current "Purification" spell. Green tiles are tiles that have been purified previously. <image> In the second example, it is impossible to purify the cell located at row 1 and column 1. For the third example: <image> Submitted Solution: ``` n = int(input()) inp = [input() for i in range(n)] A = [[0 for j in range(n)] for i in range(n)] for i in range(n): for j in range(n): if inp[i][j] == 'E': A[i][j] = 1 k = 0 for i in A: if sum(i) == n: k += 1 c = 0 for j in range(n): s = 0 for i in range(n): s += A[i][j] if s == n: c += 1 if k > 0 and c > 0: print(-1) exit(0) if k > 0: for i in range(n): for j in range(n): if A[i][j] == 0: print(i + 1, j + 1) break else: for j in range(n): for i in range(n): if A[i][j] == 0: print(i + 1, j + 1) break ``` No
6,133
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are an adventurer currently journeying inside an evil temple. After defeating a couple of weak zombies, you arrived at a square room consisting of tiles forming an n Γ— n grid. The rows are numbered 1 through n from top to bottom, and the columns are numbered 1 through n from left to right. At the far side of the room lies a door locked with evil magical forces. The following inscriptions are written on the door: The cleaning of all evil will awaken the door! Being a very senior adventurer, you immediately realize what this means. You notice that every single cell in the grid are initially evil. You should purify all of these cells. The only method of tile purification known to you is by casting the "Purification" spell. You cast this spell on a single tile β€” then, all cells that are located in the same row and all cells that are located in the same column as the selected tile become purified (including the selected tile)! It is allowed to purify a cell more than once. You would like to purify all n Γ— n cells while minimizing the number of times you cast the "Purification" spell. This sounds very easy, but you just noticed that some tiles are particularly more evil than the other tiles. You cannot cast the "Purification" spell on those particularly more evil tiles, not even after they have been purified. They can still be purified if a cell sharing the same row or the same column gets selected by the "Purification" spell. Please find some way to purify all the cells with the minimum number of spells cast. Print -1 if there is no such way. Input The first line will contain a single integer n (1 ≀ n ≀ 100). Then, n lines follows, each contains n characters. The j-th character in the i-th row represents the cell located at row i and column j. It will be the character 'E' if it is a particularly more evil cell, and '.' otherwise. Output If there exists no way to purify all the cells, output -1. Otherwise, if your solution casts x "Purification" spells (where x is the minimum possible number of spells), output x lines. Each line should consist of two integers denoting the row and column numbers of the cell on which you should cast the "Purification" spell. Examples Input 3 .E. E.E .E. Output 1 1 2 2 3 3 Input 3 EEE E.. E.E Output -1 Input 5 EE.EE E.EE. E...E .EE.E EE.EE Output 3 3 1 3 2 2 4 4 5 3 Note The first example is illustrated as follows. Purple tiles are evil tiles that have not yet been purified. Red tile is the tile on which "Purification" is cast. Yellow tiles are the tiles being purified as a result of the current "Purification" spell. Green tiles are tiles that have been purified previously. <image> In the second example, it is impossible to purify the cell located at row 1 and column 1. For the third example: <image> Submitted Solution: ``` n = int(input()) c = [list(input()) for _ in range(n)] r = [] rows = set() cols = set() for i in range(n): for j in range(n): if c[i][j] == "." and i not in rows or j not in cols: r.append((i+1, j+1)) rows.add(i) cols.add(i) break if not set(range(n)) - rows and not set(range(n)) - cols: print("\n".join(map(lambda x: str(x[0]) + " " + str(x[1]), r))) else: print(-1) ``` No
6,134
Provide tags and a correct Python 3 solution for this coding contest problem. Jeff's got n cards, each card contains either digit 0, or digit 5. Jeff can choose several cards and put them in a line so that he gets some number. What is the largest possible number divisible by 90 Jeff can make from the cards he's got? Jeff must make the number without leading zero. At that, we assume that number 0 doesn't contain any leading zeroes. Jeff doesn't have to use all the cards. Input The first line contains integer n (1 ≀ n ≀ 103). The next line contains n integers a1, a2, ..., an (ai = 0 or ai = 5). Number ai represents the digit that is written on the i-th card. Output In a single line print the answer to the problem β€” the maximum number, divisible by 90. If you can't make any divisible by 90 number from the cards, print -1. Examples Input 4 5 0 5 0 Output 0 Input 11 5 5 5 5 5 5 5 5 0 5 5 Output 5555555550 Note In the first test you can make only one number that is a multiple of 90 β€” 0. In the second test you can make number 5555555550, it is a multiple of 90. Tags: brute force, implementation, math Correct Solution: ``` a = int(input()) r = input().split(' ') r = ''.join(r) m = 0 count = r.count('0') r = r.replace('0', '') z = '0'*count for i in range(1, len(r) + 1): if int(r[:i] + z)%90 == 0: m = int(r[:i] + z) if m != 0: exit if m == 0 and count == 0: print(-1) else: print(m) ```
6,135
Provide tags and a correct Python 3 solution for this coding contest problem. Jeff's got n cards, each card contains either digit 0, or digit 5. Jeff can choose several cards and put them in a line so that he gets some number. What is the largest possible number divisible by 90 Jeff can make from the cards he's got? Jeff must make the number without leading zero. At that, we assume that number 0 doesn't contain any leading zeroes. Jeff doesn't have to use all the cards. Input The first line contains integer n (1 ≀ n ≀ 103). The next line contains n integers a1, a2, ..., an (ai = 0 or ai = 5). Number ai represents the digit that is written on the i-th card. Output In a single line print the answer to the problem β€” the maximum number, divisible by 90. If you can't make any divisible by 90 number from the cards, print -1. Examples Input 4 5 0 5 0 Output 0 Input 11 5 5 5 5 5 5 5 5 0 5 5 Output 5555555550 Note In the first test you can make only one number that is a multiple of 90 β€” 0. In the second test you can make number 5555555550, it is a multiple of 90. Tags: brute force, implementation, math Correct Solution: ``` c = {0:0,5:0} n=int(input()) a=map(int,input().split()) s=0 for i in a: c[i]+=1 if c[0]==0: print(-1) elif c[5]<9: print(0) else: print('5'*(9*(c[5]//9)) + '0'*c[0]) ```
6,136
Provide tags and a correct Python 3 solution for this coding contest problem. Jeff's got n cards, each card contains either digit 0, or digit 5. Jeff can choose several cards and put them in a line so that he gets some number. What is the largest possible number divisible by 90 Jeff can make from the cards he's got? Jeff must make the number without leading zero. At that, we assume that number 0 doesn't contain any leading zeroes. Jeff doesn't have to use all the cards. Input The first line contains integer n (1 ≀ n ≀ 103). The next line contains n integers a1, a2, ..., an (ai = 0 or ai = 5). Number ai represents the digit that is written on the i-th card. Output In a single line print the answer to the problem β€” the maximum number, divisible by 90. If you can't make any divisible by 90 number from the cards, print -1. Examples Input 4 5 0 5 0 Output 0 Input 11 5 5 5 5 5 5 5 5 0 5 5 Output 5555555550 Note In the first test you can make only one number that is a multiple of 90 β€” 0. In the second test you can make number 5555555550, it is a multiple of 90. Tags: brute force, implementation, math Correct Solution: ``` n=int(input()) l=[int(i) for i in input().split()] if 0 in l: if l.count(5)%9==0: print(int(''.join(str(i) for i in sorted(l,reverse=True)))) else: print(int('5'*(l.count(5)//9*9)+'0'*l.count(0))) else: print(-1) ```
6,137
Provide tags and a correct Python 3 solution for this coding contest problem. Jeff's got n cards, each card contains either digit 0, or digit 5. Jeff can choose several cards and put them in a line so that he gets some number. What is the largest possible number divisible by 90 Jeff can make from the cards he's got? Jeff must make the number without leading zero. At that, we assume that number 0 doesn't contain any leading zeroes. Jeff doesn't have to use all the cards. Input The first line contains integer n (1 ≀ n ≀ 103). The next line contains n integers a1, a2, ..., an (ai = 0 or ai = 5). Number ai represents the digit that is written on the i-th card. Output In a single line print the answer to the problem β€” the maximum number, divisible by 90. If you can't make any divisible by 90 number from the cards, print -1. Examples Input 4 5 0 5 0 Output 0 Input 11 5 5 5 5 5 5 5 5 0 5 5 Output 5555555550 Note In the first test you can make only one number that is a multiple of 90 β€” 0. In the second test you can make number 5555555550, it is a multiple of 90. Tags: brute force, implementation, math Correct Solution: ``` input() dic = {0:0,5:0} for i in map(int,input().split()): dic[i] += 1 ans = dic[5]//9 if ans and dic[0]: print(int(('5'*ans*9)+('0'*dic[0]))) elif dic[0]==0: print(-1) else: print(0) ```
6,138
Provide tags and a correct Python 3 solution for this coding contest problem. Jeff's got n cards, each card contains either digit 0, or digit 5. Jeff can choose several cards and put them in a line so that he gets some number. What is the largest possible number divisible by 90 Jeff can make from the cards he's got? Jeff must make the number without leading zero. At that, we assume that number 0 doesn't contain any leading zeroes. Jeff doesn't have to use all the cards. Input The first line contains integer n (1 ≀ n ≀ 103). The next line contains n integers a1, a2, ..., an (ai = 0 or ai = 5). Number ai represents the digit that is written on the i-th card. Output In a single line print the answer to the problem β€” the maximum number, divisible by 90. If you can't make any divisible by 90 number from the cards, print -1. Examples Input 4 5 0 5 0 Output 0 Input 11 5 5 5 5 5 5 5 5 0 5 5 Output 5555555550 Note In the first test you can make only one number that is a multiple of 90 β€” 0. In the second test you can make number 5555555550, it is a multiple of 90. Tags: brute force, implementation, math Correct Solution: ``` n = int(input()) A = list(map(int, input().split())) cnt5 = sum(A) // 5 cnt0 = n - cnt5 if (cnt0 == 0): print(-1) else: ans = 0 for i in range(cnt5 - cnt5 % 9): ans = 10 * ans + 5; for i in range(cnt0): ans *= 10; print(ans) ```
6,139
Provide tags and a correct Python 3 solution for this coding contest problem. Jeff's got n cards, each card contains either digit 0, or digit 5. Jeff can choose several cards and put them in a line so that he gets some number. What is the largest possible number divisible by 90 Jeff can make from the cards he's got? Jeff must make the number without leading zero. At that, we assume that number 0 doesn't contain any leading zeroes. Jeff doesn't have to use all the cards. Input The first line contains integer n (1 ≀ n ≀ 103). The next line contains n integers a1, a2, ..., an (ai = 0 or ai = 5). Number ai represents the digit that is written on the i-th card. Output In a single line print the answer to the problem β€” the maximum number, divisible by 90. If you can't make any divisible by 90 number from the cards, print -1. Examples Input 4 5 0 5 0 Output 0 Input 11 5 5 5 5 5 5 5 5 0 5 5 Output 5555555550 Note In the first test you can make only one number that is a multiple of 90 β€” 0. In the second test you can make number 5555555550, it is a multiple of 90. Tags: brute force, implementation, math Correct Solution: ``` n=int(input()) if n==1: a=int(input()) if a%90==0: print(a) else: print(-1) exit() A=[int(x) for x in input().split()] A.sort(reverse=True) cnt0=A.count(0) cnt5=A.count(5) cnt5=9*(cnt5//9) C="" for i in range(cnt5): C+='5' for i in range(cnt0): C+='0' if cnt0: if C.count('0')==len(C): print(0) else: print(C) else: print(-1) ```
6,140
Provide tags and a correct Python 3 solution for this coding contest problem. Jeff's got n cards, each card contains either digit 0, or digit 5. Jeff can choose several cards and put them in a line so that he gets some number. What is the largest possible number divisible by 90 Jeff can make from the cards he's got? Jeff must make the number without leading zero. At that, we assume that number 0 doesn't contain any leading zeroes. Jeff doesn't have to use all the cards. Input The first line contains integer n (1 ≀ n ≀ 103). The next line contains n integers a1, a2, ..., an (ai = 0 or ai = 5). Number ai represents the digit that is written on the i-th card. Output In a single line print the answer to the problem β€” the maximum number, divisible by 90. If you can't make any divisible by 90 number from the cards, print -1. Examples Input 4 5 0 5 0 Output 0 Input 11 5 5 5 5 5 5 5 5 0 5 5 Output 5555555550 Note In the first test you can make only one number that is a multiple of 90 β€” 0. In the second test you can make number 5555555550, it is a multiple of 90. Tags: brute force, implementation, math Correct Solution: ``` a=int(input()) b=[int(s) for s in input().split()] c=b.count(5) cc=b.count(0) if c//9>0 and cc>0: print("5"*(c//9*9)+"0"*cc) elif cc>0: print(0) else: print(-1) ```
6,141
Provide tags and a correct Python 3 solution for this coding contest problem. Jeff's got n cards, each card contains either digit 0, or digit 5. Jeff can choose several cards and put them in a line so that he gets some number. What is the largest possible number divisible by 90 Jeff can make from the cards he's got? Jeff must make the number without leading zero. At that, we assume that number 0 doesn't contain any leading zeroes. Jeff doesn't have to use all the cards. Input The first line contains integer n (1 ≀ n ≀ 103). The next line contains n integers a1, a2, ..., an (ai = 0 or ai = 5). Number ai represents the digit that is written on the i-th card. Output In a single line print the answer to the problem β€” the maximum number, divisible by 90. If you can't make any divisible by 90 number from the cards, print -1. Examples Input 4 5 0 5 0 Output 0 Input 11 5 5 5 5 5 5 5 5 0 5 5 Output 5555555550 Note In the first test you can make only one number that is a multiple of 90 β€” 0. In the second test you can make number 5555555550, it is a multiple of 90. Tags: brute force, implementation, math Correct Solution: ``` a = int(input()) b = list(map(int,input().split())) z = b.count(5) if a-z>0: if z<9:print(0) else:print("5"*((z//9)*9)+"0"*b.count(0)) else:print(-1) ```
6,142
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Jeff's got n cards, each card contains either digit 0, or digit 5. Jeff can choose several cards and put them in a line so that he gets some number. What is the largest possible number divisible by 90 Jeff can make from the cards he's got? Jeff must make the number without leading zero. At that, we assume that number 0 doesn't contain any leading zeroes. Jeff doesn't have to use all the cards. Input The first line contains integer n (1 ≀ n ≀ 103). The next line contains n integers a1, a2, ..., an (ai = 0 or ai = 5). Number ai represents the digit that is written on the i-th card. Output In a single line print the answer to the problem β€” the maximum number, divisible by 90. If you can't make any divisible by 90 number from the cards, print -1. Examples Input 4 5 0 5 0 Output 0 Input 11 5 5 5 5 5 5 5 5 0 5 5 Output 5555555550 Note In the first test you can make only one number that is a multiple of 90 β€” 0. In the second test you can make number 5555555550, it is a multiple of 90. Submitted Solution: ``` n = int(input()) a = list(map(int, input().split())) if a.count(5) // 9 > 0 and a.count(0) > 0: print('5' * (a.count(5) // 9) * 9 + '0' * a.count(0)) elif a.count(0) != 0: print(0) else: print(-1) ``` Yes
6,143
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Jeff's got n cards, each card contains either digit 0, or digit 5. Jeff can choose several cards and put them in a line so that he gets some number. What is the largest possible number divisible by 90 Jeff can make from the cards he's got? Jeff must make the number without leading zero. At that, we assume that number 0 doesn't contain any leading zeroes. Jeff doesn't have to use all the cards. Input The first line contains integer n (1 ≀ n ≀ 103). The next line contains n integers a1, a2, ..., an (ai = 0 or ai = 5). Number ai represents the digit that is written on the i-th card. Output In a single line print the answer to the problem β€” the maximum number, divisible by 90. If you can't make any divisible by 90 number from the cards, print -1. Examples Input 4 5 0 5 0 Output 0 Input 11 5 5 5 5 5 5 5 5 0 5 5 Output 5555555550 Note In the first test you can make only one number that is a multiple of 90 β€” 0. In the second test you can make number 5555555550, it is a multiple of 90. Submitted Solution: ``` # cook your dish here from sys import stdin, stdout import math from itertools import permutations, combinations from collections import defaultdict from bisect import bisect_left def L(): return list(map(int, stdin.readline().split())) def In(): return map(int, stdin.readline().split()) def I(): return int(stdin.readline()) P = 1000000007 n = I() lis = L() a = lis.count(0) b = lis.count(5) if a == 0: print(-1) else: if b < 9: print(0) else: print(str("5"*(b//9)*9) + "0"*a) ``` Yes
6,144
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Jeff's got n cards, each card contains either digit 0, or digit 5. Jeff can choose several cards and put them in a line so that he gets some number. What is the largest possible number divisible by 90 Jeff can make from the cards he's got? Jeff must make the number without leading zero. At that, we assume that number 0 doesn't contain any leading zeroes. Jeff doesn't have to use all the cards. Input The first line contains integer n (1 ≀ n ≀ 103). The next line contains n integers a1, a2, ..., an (ai = 0 or ai = 5). Number ai represents the digit that is written on the i-th card. Output In a single line print the answer to the problem β€” the maximum number, divisible by 90. If you can't make any divisible by 90 number from the cards, print -1. Examples Input 4 5 0 5 0 Output 0 Input 11 5 5 5 5 5 5 5 5 0 5 5 Output 5555555550 Note In the first test you can make only one number that is a multiple of 90 β€” 0. In the second test you can make number 5555555550, it is a multiple of 90. Submitted Solution: ``` t=int(input()) l=[int(x) for x in input().split()] c=0 for i in l: if i==0: c=c+1 if(c!=0): f=0 for i in l: if(i==5): f=f+1 if(f<9): print(0) else: for i in range(f-f%9): print(5,end="") for i in range(c): print(0,end="") else: print("-1") ``` Yes
6,145
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Jeff's got n cards, each card contains either digit 0, or digit 5. Jeff can choose several cards and put them in a line so that he gets some number. What is the largest possible number divisible by 90 Jeff can make from the cards he's got? Jeff must make the number without leading zero. At that, we assume that number 0 doesn't contain any leading zeroes. Jeff doesn't have to use all the cards. Input The first line contains integer n (1 ≀ n ≀ 103). The next line contains n integers a1, a2, ..., an (ai = 0 or ai = 5). Number ai represents the digit that is written on the i-th card. Output In a single line print the answer to the problem β€” the maximum number, divisible by 90. If you can't make any divisible by 90 number from the cards, print -1. Examples Input 4 5 0 5 0 Output 0 Input 11 5 5 5 5 5 5 5 5 0 5 5 Output 5555555550 Note In the first test you can make only one number that is a multiple of 90 β€” 0. In the second test you can make number 5555555550, it is a multiple of 90. Submitted Solution: ``` n=int(input()) a=list(map(int,input().split())) if sum(a)<45 and 0 in a: print(0) elif sum(a)<45 and 0 not in a: print(-1) elif sum(a)>=45 and 0 in a: x=sum(a)//45 y=a.count(0) print('5'*(9*x)+'0'*y) else: print(-1) ``` Yes
6,146
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Jeff's got n cards, each card contains either digit 0, or digit 5. Jeff can choose several cards and put them in a line so that he gets some number. What is the largest possible number divisible by 90 Jeff can make from the cards he's got? Jeff must make the number without leading zero. At that, we assume that number 0 doesn't contain any leading zeroes. Jeff doesn't have to use all the cards. Input The first line contains integer n (1 ≀ n ≀ 103). The next line contains n integers a1, a2, ..., an (ai = 0 or ai = 5). Number ai represents the digit that is written on the i-th card. Output In a single line print the answer to the problem β€” the maximum number, divisible by 90. If you can't make any divisible by 90 number from the cards, print -1. Examples Input 4 5 0 5 0 Output 0 Input 11 5 5 5 5 5 5 5 5 0 5 5 Output 5555555550 Note In the first test you can make only one number that is a multiple of 90 β€” 0. In the second test you can make number 5555555550, it is a multiple of 90. Submitted Solution: ``` n = int(input()) arr = list(map(int, input().split())) srt = sorted(arr, reverse=True) ans = 0 srt = [str(i) for i in srt] while srt: if srt[0] != '0' and int(''.join(srt)) % 90 == 0: print(''.join(srt)) exit() else: check = srt.pop(0) if check == 0: print(0) exit() print(-1) ``` No
6,147
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Jeff's got n cards, each card contains either digit 0, or digit 5. Jeff can choose several cards and put them in a line so that he gets some number. What is the largest possible number divisible by 90 Jeff can make from the cards he's got? Jeff must make the number without leading zero. At that, we assume that number 0 doesn't contain any leading zeroes. Jeff doesn't have to use all the cards. Input The first line contains integer n (1 ≀ n ≀ 103). The next line contains n integers a1, a2, ..., an (ai = 0 or ai = 5). Number ai represents the digit that is written on the i-th card. Output In a single line print the answer to the problem β€” the maximum number, divisible by 90. If you can't make any divisible by 90 number from the cards, print -1. Examples Input 4 5 0 5 0 Output 0 Input 11 5 5 5 5 5 5 5 5 0 5 5 Output 5555555550 Note In the first test you can make only one number that is a multiple of 90 β€” 0. In the second test you can make number 5555555550, it is a multiple of 90. Submitted Solution: ``` l=input() s=input() k=list(map(int,s.split(" "))) x,y,flag=k.count(5),k.count(0),False for i in range(x): s="5"*(x-i) if(int(s)%9==0): break flag=True l=s for i in range(y): k="0"*(y-i) l+=k if(int(s)%90): print(l) flag=True if(not flag): print("0") ``` No
6,148
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Jeff's got n cards, each card contains either digit 0, or digit 5. Jeff can choose several cards and put them in a line so that he gets some number. What is the largest possible number divisible by 90 Jeff can make from the cards he's got? Jeff must make the number without leading zero. At that, we assume that number 0 doesn't contain any leading zeroes. Jeff doesn't have to use all the cards. Input The first line contains integer n (1 ≀ n ≀ 103). The next line contains n integers a1, a2, ..., an (ai = 0 or ai = 5). Number ai represents the digit that is written on the i-th card. Output In a single line print the answer to the problem β€” the maximum number, divisible by 90. If you can't make any divisible by 90 number from the cards, print -1. Examples Input 4 5 0 5 0 Output 0 Input 11 5 5 5 5 5 5 5 5 0 5 5 Output 5555555550 Note In the first test you can make only one number that is a multiple of 90 β€” 0. In the second test you can make number 5555555550, it is a multiple of 90. Submitted Solution: ``` #!/usr/bin/env python3 n = int(input()) numbers = input().split() fives=0 zeroes=0 for n in numbers: if n=='5': fives+=1 else: zeroes+=1 if(fives<9): if zeroes==0: print("-1") else: print('0') else: print('555555555'*int(fives/9)+'0'*zeroes) ``` No
6,149
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Jeff's got n cards, each card contains either digit 0, or digit 5. Jeff can choose several cards and put them in a line so that he gets some number. What is the largest possible number divisible by 90 Jeff can make from the cards he's got? Jeff must make the number without leading zero. At that, we assume that number 0 doesn't contain any leading zeroes. Jeff doesn't have to use all the cards. Input The first line contains integer n (1 ≀ n ≀ 103). The next line contains n integers a1, a2, ..., an (ai = 0 or ai = 5). Number ai represents the digit that is written on the i-th card. Output In a single line print the answer to the problem β€” the maximum number, divisible by 90. If you can't make any divisible by 90 number from the cards, print -1. Examples Input 4 5 0 5 0 Output 0 Input 11 5 5 5 5 5 5 5 5 0 5 5 Output 5555555550 Note In the first test you can make only one number that is a multiple of 90 β€” 0. In the second test you can make number 5555555550, it is a multiple of 90. Submitted Solution: ``` # https://codeforces.com/problemset/problem/352/A n = int(input()) fiveCount = 0 zeroCount = 0 for num in input().split(): if num == '5': fiveCount += 1 else: zeroCount += 1 while fiveCount>0: if (fiveCount*5) % 9 == 0: print('5'*fiveCount, sep='', end='') break else: fiveCount -= 1 if fiveCount==0: if zeroCount == 0: print(-1) else: print(0) else: print('o'*zeroCount) ``` No
6,150
Provide tags and a correct Python 3 solution for this coding contest problem. Imagine that there is a group of three friends: A, B and Π‘. A owes B 20 rubles and B owes C 20 rubles. The total sum of the debts is 40 rubles. You can see that the debts are not organized in a very optimal manner. Let's rearrange them like that: assume that A owes C 20 rubles and B doesn't owe anything to anybody. The debts still mean the same but the total sum of the debts now equals 20 rubles. This task is a generalisation of a described example. Imagine that your group of friends has n people and you know the debts between the people. Optimize the given debts without changing their meaning. In other words, finally for each friend the difference between the total money he should give and the total money he should take must be the same. Print the minimum sum of all debts in the optimal rearrangement of the debts. See the notes to the test samples to better understand the problem. Input The first line contains two integers n and m (1 ≀ n ≀ 100; 0 ≀ m ≀ 104). The next m lines contain the debts. The i-th line contains three integers ai, bi, ci (1 ≀ ai, bi ≀ n; ai β‰  bi; 1 ≀ ci ≀ 100), which mean that person ai owes person bi ci rubles. Assume that the people are numbered by integers from 1 to n. It is guaranteed that the same pair of people occurs at most once in the input. The input doesn't simultaneously contain pair of people (x, y) and pair of people (y, x). Output Print a single integer β€” the minimum sum of debts in the optimal rearrangement. Examples Input 5 3 1 2 10 2 3 1 2 4 1 Output 10 Input 3 0 Output 0 Input 4 3 1 2 1 2 3 1 3 1 1 Output 0 Note In the first sample, you can assume that person number 1 owes 8 rubles to person number 2, 1 ruble to person number 3 and 1 ruble to person number 4. He doesn't owe anybody else anything. In the end, the total debt equals 10. In the second sample, there are no debts. In the third sample, you can annul all the debts. Tags: implementation Correct Solution: ``` n,m = [int(x) for x in input().split()] listaDividas = [] for i in range(101): listaDividas.append([0,0]) for i in range(m): individado,agiota,quantidade = [int(x) for x in input().split()] listaDividas[individado][0] += quantidade listaDividas[agiota][1] += quantidade quantidadeTotal = 0 for i in range(101): quantidadeTotal += max(listaDividas[i][0]-listaDividas[i][1],0) print(quantidadeTotal) ```
6,151
Provide tags and a correct Python 3 solution for this coding contest problem. Imagine that there is a group of three friends: A, B and Π‘. A owes B 20 rubles and B owes C 20 rubles. The total sum of the debts is 40 rubles. You can see that the debts are not organized in a very optimal manner. Let's rearrange them like that: assume that A owes C 20 rubles and B doesn't owe anything to anybody. The debts still mean the same but the total sum of the debts now equals 20 rubles. This task is a generalisation of a described example. Imagine that your group of friends has n people and you know the debts between the people. Optimize the given debts without changing their meaning. In other words, finally for each friend the difference between the total money he should give and the total money he should take must be the same. Print the minimum sum of all debts in the optimal rearrangement of the debts. See the notes to the test samples to better understand the problem. Input The first line contains two integers n and m (1 ≀ n ≀ 100; 0 ≀ m ≀ 104). The next m lines contain the debts. The i-th line contains three integers ai, bi, ci (1 ≀ ai, bi ≀ n; ai β‰  bi; 1 ≀ ci ≀ 100), which mean that person ai owes person bi ci rubles. Assume that the people are numbered by integers from 1 to n. It is guaranteed that the same pair of people occurs at most once in the input. The input doesn't simultaneously contain pair of people (x, y) and pair of people (y, x). Output Print a single integer β€” the minimum sum of debts in the optimal rearrangement. Examples Input 5 3 1 2 10 2 3 1 2 4 1 Output 10 Input 3 0 Output 0 Input 4 3 1 2 1 2 3 1 3 1 1 Output 0 Note In the first sample, you can assume that person number 1 owes 8 rubles to person number 2, 1 ruble to person number 3 and 1 ruble to person number 4. He doesn't owe anybody else anything. In the end, the total debt equals 10. In the second sample, there are no debts. In the third sample, you can annul all the debts. Tags: implementation Correct Solution: ``` n,m=input().strip().split(" ") n,m=[int(n),int(m)] ag=[0 for _ in range(n)] for i in range(m): a,b,c=input().strip().split(" ") a,b,c=[int(a),int(b),int(c)] ag[a-1]+=c ag[b-1]-=c sum=0 for i in range(n): if ag[i]>0: sum+=ag[i] print(sum) ```
6,152
Provide tags and a correct Python 3 solution for this coding contest problem. Imagine that there is a group of three friends: A, B and Π‘. A owes B 20 rubles and B owes C 20 rubles. The total sum of the debts is 40 rubles. You can see that the debts are not organized in a very optimal manner. Let's rearrange them like that: assume that A owes C 20 rubles and B doesn't owe anything to anybody. The debts still mean the same but the total sum of the debts now equals 20 rubles. This task is a generalisation of a described example. Imagine that your group of friends has n people and you know the debts between the people. Optimize the given debts without changing their meaning. In other words, finally for each friend the difference between the total money he should give and the total money he should take must be the same. Print the minimum sum of all debts in the optimal rearrangement of the debts. See the notes to the test samples to better understand the problem. Input The first line contains two integers n and m (1 ≀ n ≀ 100; 0 ≀ m ≀ 104). The next m lines contain the debts. The i-th line contains three integers ai, bi, ci (1 ≀ ai, bi ≀ n; ai β‰  bi; 1 ≀ ci ≀ 100), which mean that person ai owes person bi ci rubles. Assume that the people are numbered by integers from 1 to n. It is guaranteed that the same pair of people occurs at most once in the input. The input doesn't simultaneously contain pair of people (x, y) and pair of people (y, x). Output Print a single integer β€” the minimum sum of debts in the optimal rearrangement. Examples Input 5 3 1 2 10 2 3 1 2 4 1 Output 10 Input 3 0 Output 0 Input 4 3 1 2 1 2 3 1 3 1 1 Output 0 Note In the first sample, you can assume that person number 1 owes 8 rubles to person number 2, 1 ruble to person number 3 and 1 ruble to person number 4. He doesn't owe anybody else anything. In the end, the total debt equals 10. In the second sample, there are no debts. In the third sample, you can annul all the debts. Tags: implementation Correct Solution: ``` n,m = map(int, input().split()) debt=[0]*(n+1) for i in range(m): a,b,c = map(int, input().split()) debt[a]-=c debt[b]+=c ans=0 for i in debt: if i>0: ans+=i print(ans) ```
6,153
Provide tags and a correct Python 3 solution for this coding contest problem. Imagine that there is a group of three friends: A, B and Π‘. A owes B 20 rubles and B owes C 20 rubles. The total sum of the debts is 40 rubles. You can see that the debts are not organized in a very optimal manner. Let's rearrange them like that: assume that A owes C 20 rubles and B doesn't owe anything to anybody. The debts still mean the same but the total sum of the debts now equals 20 rubles. This task is a generalisation of a described example. Imagine that your group of friends has n people and you know the debts between the people. Optimize the given debts without changing their meaning. In other words, finally for each friend the difference between the total money he should give and the total money he should take must be the same. Print the minimum sum of all debts in the optimal rearrangement of the debts. See the notes to the test samples to better understand the problem. Input The first line contains two integers n and m (1 ≀ n ≀ 100; 0 ≀ m ≀ 104). The next m lines contain the debts. The i-th line contains three integers ai, bi, ci (1 ≀ ai, bi ≀ n; ai β‰  bi; 1 ≀ ci ≀ 100), which mean that person ai owes person bi ci rubles. Assume that the people are numbered by integers from 1 to n. It is guaranteed that the same pair of people occurs at most once in the input. The input doesn't simultaneously contain pair of people (x, y) and pair of people (y, x). Output Print a single integer β€” the minimum sum of debts in the optimal rearrangement. Examples Input 5 3 1 2 10 2 3 1 2 4 1 Output 10 Input 3 0 Output 0 Input 4 3 1 2 1 2 3 1 3 1 1 Output 0 Note In the first sample, you can assume that person number 1 owes 8 rubles to person number 2, 1 ruble to person number 3 and 1 ruble to person number 4. He doesn't owe anybody else anything. In the end, the total debt equals 10. In the second sample, there are no debts. In the third sample, you can annul all the debts. Tags: implementation Correct Solution: ``` class CodeforcesTask376BSolution: def __init__(self): self.result = '' self.n_m = [] self.debts = [] def read_input(self): self.n_m = [int(x) for x in input().split(" ")] for x in range(self.n_m[1]): self.debts.append([int(y) for y in input().split(" ")]) def process_task(self): people_balance = [0] * self.n_m[0] for d in self.debts: people_balance[d[0] - 1] -= d[2] people_balance[d[1] - 1] += d[2] self.result = str(sum([abs(x) for x in people_balance]) // 2) def get_result(self): return self.result if __name__ == "__main__": Solution = CodeforcesTask376BSolution() Solution.read_input() Solution.process_task() print(Solution.get_result()) ```
6,154
Provide tags and a correct Python 3 solution for this coding contest problem. Imagine that there is a group of three friends: A, B and Π‘. A owes B 20 rubles and B owes C 20 rubles. The total sum of the debts is 40 rubles. You can see that the debts are not organized in a very optimal manner. Let's rearrange them like that: assume that A owes C 20 rubles and B doesn't owe anything to anybody. The debts still mean the same but the total sum of the debts now equals 20 rubles. This task is a generalisation of a described example. Imagine that your group of friends has n people and you know the debts between the people. Optimize the given debts without changing their meaning. In other words, finally for each friend the difference between the total money he should give and the total money he should take must be the same. Print the minimum sum of all debts in the optimal rearrangement of the debts. See the notes to the test samples to better understand the problem. Input The first line contains two integers n and m (1 ≀ n ≀ 100; 0 ≀ m ≀ 104). The next m lines contain the debts. The i-th line contains three integers ai, bi, ci (1 ≀ ai, bi ≀ n; ai β‰  bi; 1 ≀ ci ≀ 100), which mean that person ai owes person bi ci rubles. Assume that the people are numbered by integers from 1 to n. It is guaranteed that the same pair of people occurs at most once in the input. The input doesn't simultaneously contain pair of people (x, y) and pair of people (y, x). Output Print a single integer β€” the minimum sum of debts in the optimal rearrangement. Examples Input 5 3 1 2 10 2 3 1 2 4 1 Output 10 Input 3 0 Output 0 Input 4 3 1 2 1 2 3 1 3 1 1 Output 0 Note In the first sample, you can assume that person number 1 owes 8 rubles to person number 2, 1 ruble to person number 3 and 1 ruble to person number 4. He doesn't owe anybody else anything. In the end, the total debt equals 10. In the second sample, there are no debts. In the third sample, you can annul all the debts. Tags: implementation Correct Solution: ``` import sys def readInputs(): global n,m,lAdj, counts n,m = map(int,f.readline().split()) lAdj = [[] for _ in range(n)] counts = n*[0] for _ in range(m): (a,b,c) = map(int,f.readline().split()) lAdj[a-1] += [(b-1,c)] #print(lAdj) def solve(): if(m == 0): return 0 for i in range(n): for cple in lAdj[i]: succ = cple[0] debt = cple[1] counts[i] -= debt counts[succ] += debt sum = 0 for i in range(n): if(counts[i]<0): sum += abs(counts[i]) return sum def tests(): global f bFail = False for i in range(1,3): # inputs f = open("test"+str(i)+".txt") readInputs() # output expected lEx = list(map(int,f.readline().split())) lEx.sort() resExpect = str(lEx) # output res = str(solve()) if(res != resExpect): print("TEST",i,"FAILED !"+" Found :",res,", Expected :",resExpect) bFail = True else: print("TEST",i,"PASSED") if(not bFail): print("\n--- ALL OF THE "+str(i)+" TESTS HAVE SUCCEEDED ---") def main(): global f i = 2 if(i == 1): tests() return f = sys.stdin readInputs() print(solve()) main() ```
6,155
Provide tags and a correct Python 3 solution for this coding contest problem. Imagine that there is a group of three friends: A, B and Π‘. A owes B 20 rubles and B owes C 20 rubles. The total sum of the debts is 40 rubles. You can see that the debts are not organized in a very optimal manner. Let's rearrange them like that: assume that A owes C 20 rubles and B doesn't owe anything to anybody. The debts still mean the same but the total sum of the debts now equals 20 rubles. This task is a generalisation of a described example. Imagine that your group of friends has n people and you know the debts between the people. Optimize the given debts without changing their meaning. In other words, finally for each friend the difference between the total money he should give and the total money he should take must be the same. Print the minimum sum of all debts in the optimal rearrangement of the debts. See the notes to the test samples to better understand the problem. Input The first line contains two integers n and m (1 ≀ n ≀ 100; 0 ≀ m ≀ 104). The next m lines contain the debts. The i-th line contains three integers ai, bi, ci (1 ≀ ai, bi ≀ n; ai β‰  bi; 1 ≀ ci ≀ 100), which mean that person ai owes person bi ci rubles. Assume that the people are numbered by integers from 1 to n. It is guaranteed that the same pair of people occurs at most once in the input. The input doesn't simultaneously contain pair of people (x, y) and pair of people (y, x). Output Print a single integer β€” the minimum sum of debts in the optimal rearrangement. Examples Input 5 3 1 2 10 2 3 1 2 4 1 Output 10 Input 3 0 Output 0 Input 4 3 1 2 1 2 3 1 3 1 1 Output 0 Note In the first sample, you can assume that person number 1 owes 8 rubles to person number 2, 1 ruble to person number 3 and 1 ruble to person number 4. He doesn't owe anybody else anything. In the end, the total debt equals 10. In the second sample, there are no debts. In the third sample, you can annul all the debts. Tags: implementation Correct Solution: ``` def I(): return list(map(int, input().split())) n, m = I() list_of_persons = [0]*(n+1) sum = 0 for i in range(m): x, y, z = I() list_of_persons[x] += z list_of_persons[y] -= z for i in range(n+1): if list_of_persons[i] > 0: sum += list_of_persons[i] print(sum) ```
6,156
Provide tags and a correct Python 3 solution for this coding contest problem. Imagine that there is a group of three friends: A, B and Π‘. A owes B 20 rubles and B owes C 20 rubles. The total sum of the debts is 40 rubles. You can see that the debts are not organized in a very optimal manner. Let's rearrange them like that: assume that A owes C 20 rubles and B doesn't owe anything to anybody. The debts still mean the same but the total sum of the debts now equals 20 rubles. This task is a generalisation of a described example. Imagine that your group of friends has n people and you know the debts between the people. Optimize the given debts without changing their meaning. In other words, finally for each friend the difference between the total money he should give and the total money he should take must be the same. Print the minimum sum of all debts in the optimal rearrangement of the debts. See the notes to the test samples to better understand the problem. Input The first line contains two integers n and m (1 ≀ n ≀ 100; 0 ≀ m ≀ 104). The next m lines contain the debts. The i-th line contains three integers ai, bi, ci (1 ≀ ai, bi ≀ n; ai β‰  bi; 1 ≀ ci ≀ 100), which mean that person ai owes person bi ci rubles. Assume that the people are numbered by integers from 1 to n. It is guaranteed that the same pair of people occurs at most once in the input. The input doesn't simultaneously contain pair of people (x, y) and pair of people (y, x). Output Print a single integer β€” the minimum sum of debts in the optimal rearrangement. Examples Input 5 3 1 2 10 2 3 1 2 4 1 Output 10 Input 3 0 Output 0 Input 4 3 1 2 1 2 3 1 3 1 1 Output 0 Note In the first sample, you can assume that person number 1 owes 8 rubles to person number 2, 1 ruble to person number 3 and 1 ruble to person number 4. He doesn't owe anybody else anything. In the end, the total debt equals 10. In the second sample, there are no debts. In the third sample, you can annul all the debts. Tags: implementation Correct Solution: ``` n, m = map(int, input().split()) balance = [0] * (n+1) for i in range(m): a, b, c = map(int, input().split()) balance[a] -= c balance[b] += c debt = 0 for b in balance: if b < 0: debt += abs(b) print(debt) ```
6,157
Provide tags and a correct Python 3 solution for this coding contest problem. Imagine that there is a group of three friends: A, B and Π‘. A owes B 20 rubles and B owes C 20 rubles. The total sum of the debts is 40 rubles. You can see that the debts are not organized in a very optimal manner. Let's rearrange them like that: assume that A owes C 20 rubles and B doesn't owe anything to anybody. The debts still mean the same but the total sum of the debts now equals 20 rubles. This task is a generalisation of a described example. Imagine that your group of friends has n people and you know the debts between the people. Optimize the given debts without changing their meaning. In other words, finally for each friend the difference between the total money he should give and the total money he should take must be the same. Print the minimum sum of all debts in the optimal rearrangement of the debts. See the notes to the test samples to better understand the problem. Input The first line contains two integers n and m (1 ≀ n ≀ 100; 0 ≀ m ≀ 104). The next m lines contain the debts. The i-th line contains three integers ai, bi, ci (1 ≀ ai, bi ≀ n; ai β‰  bi; 1 ≀ ci ≀ 100), which mean that person ai owes person bi ci rubles. Assume that the people are numbered by integers from 1 to n. It is guaranteed that the same pair of people occurs at most once in the input. The input doesn't simultaneously contain pair of people (x, y) and pair of people (y, x). Output Print a single integer β€” the minimum sum of debts in the optimal rearrangement. Examples Input 5 3 1 2 10 2 3 1 2 4 1 Output 10 Input 3 0 Output 0 Input 4 3 1 2 1 2 3 1 3 1 1 Output 0 Note In the first sample, you can assume that person number 1 owes 8 rubles to person number 2, 1 ruble to person number 3 and 1 ruble to person number 4. He doesn't owe anybody else anything. In the end, the total debt equals 10. In the second sample, there are no debts. In the third sample, you can annul all the debts. Tags: implementation Correct Solution: ``` n,m=map(int,input().split()) d=[0]*n for i in range(m): a,b,c=map(int,input().split()) d[a-1]-=c d[b-1]+=c ans=0 for i in range(n): if d[i]>0: ans+=d[i] print(ans) ```
6,158
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Imagine that there is a group of three friends: A, B and Π‘. A owes B 20 rubles and B owes C 20 rubles. The total sum of the debts is 40 rubles. You can see that the debts are not organized in a very optimal manner. Let's rearrange them like that: assume that A owes C 20 rubles and B doesn't owe anything to anybody. The debts still mean the same but the total sum of the debts now equals 20 rubles. This task is a generalisation of a described example. Imagine that your group of friends has n people and you know the debts between the people. Optimize the given debts without changing their meaning. In other words, finally for each friend the difference between the total money he should give and the total money he should take must be the same. Print the minimum sum of all debts in the optimal rearrangement of the debts. See the notes to the test samples to better understand the problem. Input The first line contains two integers n and m (1 ≀ n ≀ 100; 0 ≀ m ≀ 104). The next m lines contain the debts. The i-th line contains three integers ai, bi, ci (1 ≀ ai, bi ≀ n; ai β‰  bi; 1 ≀ ci ≀ 100), which mean that person ai owes person bi ci rubles. Assume that the people are numbered by integers from 1 to n. It is guaranteed that the same pair of people occurs at most once in the input. The input doesn't simultaneously contain pair of people (x, y) and pair of people (y, x). Output Print a single integer β€” the minimum sum of debts in the optimal rearrangement. Examples Input 5 3 1 2 10 2 3 1 2 4 1 Output 10 Input 3 0 Output 0 Input 4 3 1 2 1 2 3 1 3 1 1 Output 0 Note In the first sample, you can assume that person number 1 owes 8 rubles to person number 2, 1 ruble to person number 3 and 1 ruble to person number 4. He doesn't owe anybody else anything. In the end, the total debt equals 10. In the second sample, there are no debts. In the third sample, you can annul all the debts. Submitted Solution: ``` n, m = [int(x) for x in input().split()] gives = [0 for i in range(n+1)] receives = [0 for i in range(n+1)] for i in range(m): a,b,c = [int(x) for x in input().split()] gives[a] += c receives[b] += c opt = 0 for i in range(n+1): diff = gives[i] - receives[i] if diff > 0: opt += diff print(opt) ``` Yes
6,159
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Imagine that there is a group of three friends: A, B and Π‘. A owes B 20 rubles and B owes C 20 rubles. The total sum of the debts is 40 rubles. You can see that the debts are not organized in a very optimal manner. Let's rearrange them like that: assume that A owes C 20 rubles and B doesn't owe anything to anybody. The debts still mean the same but the total sum of the debts now equals 20 rubles. This task is a generalisation of a described example. Imagine that your group of friends has n people and you know the debts between the people. Optimize the given debts without changing their meaning. In other words, finally for each friend the difference between the total money he should give and the total money he should take must be the same. Print the minimum sum of all debts in the optimal rearrangement of the debts. See the notes to the test samples to better understand the problem. Input The first line contains two integers n and m (1 ≀ n ≀ 100; 0 ≀ m ≀ 104). The next m lines contain the debts. The i-th line contains three integers ai, bi, ci (1 ≀ ai, bi ≀ n; ai β‰  bi; 1 ≀ ci ≀ 100), which mean that person ai owes person bi ci rubles. Assume that the people are numbered by integers from 1 to n. It is guaranteed that the same pair of people occurs at most once in the input. The input doesn't simultaneously contain pair of people (x, y) and pair of people (y, x). Output Print a single integer β€” the minimum sum of debts in the optimal rearrangement. Examples Input 5 3 1 2 10 2 3 1 2 4 1 Output 10 Input 3 0 Output 0 Input 4 3 1 2 1 2 3 1 3 1 1 Output 0 Note In the first sample, you can assume that person number 1 owes 8 rubles to person number 2, 1 ruble to person number 3 and 1 ruble to person number 4. He doesn't owe anybody else anything. In the end, the total debt equals 10. In the second sample, there are no debts. In the third sample, you can annul all the debts. Submitted Solution: ``` n,m = (map(int,input().split())) s = [0] * n for i in range(m): a,b,c = (map(int,input().split())) s[a-1] -= c s[b-1] += c print(sum(s[i] for i in range(n) if s[i] > 0)) ``` Yes
6,160
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Imagine that there is a group of three friends: A, B and Π‘. A owes B 20 rubles and B owes C 20 rubles. The total sum of the debts is 40 rubles. You can see that the debts are not organized in a very optimal manner. Let's rearrange them like that: assume that A owes C 20 rubles and B doesn't owe anything to anybody. The debts still mean the same but the total sum of the debts now equals 20 rubles. This task is a generalisation of a described example. Imagine that your group of friends has n people and you know the debts between the people. Optimize the given debts without changing their meaning. In other words, finally for each friend the difference between the total money he should give and the total money he should take must be the same. Print the minimum sum of all debts in the optimal rearrangement of the debts. See the notes to the test samples to better understand the problem. Input The first line contains two integers n and m (1 ≀ n ≀ 100; 0 ≀ m ≀ 104). The next m lines contain the debts. The i-th line contains three integers ai, bi, ci (1 ≀ ai, bi ≀ n; ai β‰  bi; 1 ≀ ci ≀ 100), which mean that person ai owes person bi ci rubles. Assume that the people are numbered by integers from 1 to n. It is guaranteed that the same pair of people occurs at most once in the input. The input doesn't simultaneously contain pair of people (x, y) and pair of people (y, x). Output Print a single integer β€” the minimum sum of debts in the optimal rearrangement. Examples Input 5 3 1 2 10 2 3 1 2 4 1 Output 10 Input 3 0 Output 0 Input 4 3 1 2 1 2 3 1 3 1 1 Output 0 Note In the first sample, you can assume that person number 1 owes 8 rubles to person number 2, 1 ruble to person number 3 and 1 ruble to person number 4. He doesn't owe anybody else anything. In the end, the total debt equals 10. In the second sample, there are no debts. In the third sample, you can annul all the debts. Submitted Solution: ``` n, m = map(int, input().split()) d = [0 for i in range(n)] for i in range(m): a, b, c = map(int, input().split()) d[a-1] -= c d[b-1] += c print(sum(i for i in d if i > 0)) ``` Yes
6,161
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Imagine that there is a group of three friends: A, B and Π‘. A owes B 20 rubles and B owes C 20 rubles. The total sum of the debts is 40 rubles. You can see that the debts are not organized in a very optimal manner. Let's rearrange them like that: assume that A owes C 20 rubles and B doesn't owe anything to anybody. The debts still mean the same but the total sum of the debts now equals 20 rubles. This task is a generalisation of a described example. Imagine that your group of friends has n people and you know the debts between the people. Optimize the given debts without changing their meaning. In other words, finally for each friend the difference between the total money he should give and the total money he should take must be the same. Print the minimum sum of all debts in the optimal rearrangement of the debts. See the notes to the test samples to better understand the problem. Input The first line contains two integers n and m (1 ≀ n ≀ 100; 0 ≀ m ≀ 104). The next m lines contain the debts. The i-th line contains three integers ai, bi, ci (1 ≀ ai, bi ≀ n; ai β‰  bi; 1 ≀ ci ≀ 100), which mean that person ai owes person bi ci rubles. Assume that the people are numbered by integers from 1 to n. It is guaranteed that the same pair of people occurs at most once in the input. The input doesn't simultaneously contain pair of people (x, y) and pair of people (y, x). Output Print a single integer β€” the minimum sum of debts in the optimal rearrangement. Examples Input 5 3 1 2 10 2 3 1 2 4 1 Output 10 Input 3 0 Output 0 Input 4 3 1 2 1 2 3 1 3 1 1 Output 0 Note In the first sample, you can assume that person number 1 owes 8 rubles to person number 2, 1 ruble to person number 3 and 1 ruble to person number 4. He doesn't owe anybody else anything. In the end, the total debt equals 10. In the second sample, there are no debts. In the third sample, you can annul all the debts. Submitted Solution: ``` __author__ = 'asmn' n, m = tuple(map(int, input().split())) l = [0] * n for i in range(m): a, b, c = tuple(map(int, input().split())) l[a - 1] += c l[b - 1] -= c print(sum(abs(x) for x in l)//2) ``` Yes
6,162
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Imagine that there is a group of three friends: A, B and Π‘. A owes B 20 rubles and B owes C 20 rubles. The total sum of the debts is 40 rubles. You can see that the debts are not organized in a very optimal manner. Let's rearrange them like that: assume that A owes C 20 rubles and B doesn't owe anything to anybody. The debts still mean the same but the total sum of the debts now equals 20 rubles. This task is a generalisation of a described example. Imagine that your group of friends has n people and you know the debts between the people. Optimize the given debts without changing their meaning. In other words, finally for each friend the difference between the total money he should give and the total money he should take must be the same. Print the minimum sum of all debts in the optimal rearrangement of the debts. See the notes to the test samples to better understand the problem. Input The first line contains two integers n and m (1 ≀ n ≀ 100; 0 ≀ m ≀ 104). The next m lines contain the debts. The i-th line contains three integers ai, bi, ci (1 ≀ ai, bi ≀ n; ai β‰  bi; 1 ≀ ci ≀ 100), which mean that person ai owes person bi ci rubles. Assume that the people are numbered by integers from 1 to n. It is guaranteed that the same pair of people occurs at most once in the input. The input doesn't simultaneously contain pair of people (x, y) and pair of people (y, x). Output Print a single integer β€” the minimum sum of debts in the optimal rearrangement. Examples Input 5 3 1 2 10 2 3 1 2 4 1 Output 10 Input 3 0 Output 0 Input 4 3 1 2 1 2 3 1 3 1 1 Output 0 Note In the first sample, you can assume that person number 1 owes 8 rubles to person number 2, 1 ruble to person number 3 and 1 ruble to person number 4. He doesn't owe anybody else anything. In the end, the total debt equals 10. In the second sample, there are no debts. In the third sample, you can annul all the debts. Submitted Solution: ``` from collections import defaultdict n, m = map(int, input().split()) s = defaultdict(lambda: 0) for i in range(m): a, b, c = map(int, input().split()) s[a]+=c s[b]-=c print(s) print(sum(i for i in s.values() if i>0)) ``` No
6,163
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Imagine that there is a group of three friends: A, B and Π‘. A owes B 20 rubles and B owes C 20 rubles. The total sum of the debts is 40 rubles. You can see that the debts are not organized in a very optimal manner. Let's rearrange them like that: assume that A owes C 20 rubles and B doesn't owe anything to anybody. The debts still mean the same but the total sum of the debts now equals 20 rubles. This task is a generalisation of a described example. Imagine that your group of friends has n people and you know the debts between the people. Optimize the given debts without changing their meaning. In other words, finally for each friend the difference between the total money he should give and the total money he should take must be the same. Print the minimum sum of all debts in the optimal rearrangement of the debts. See the notes to the test samples to better understand the problem. Input The first line contains two integers n and m (1 ≀ n ≀ 100; 0 ≀ m ≀ 104). The next m lines contain the debts. The i-th line contains three integers ai, bi, ci (1 ≀ ai, bi ≀ n; ai β‰  bi; 1 ≀ ci ≀ 100), which mean that person ai owes person bi ci rubles. Assume that the people are numbered by integers from 1 to n. It is guaranteed that the same pair of people occurs at most once in the input. The input doesn't simultaneously contain pair of people (x, y) and pair of people (y, x). Output Print a single integer β€” the minimum sum of debts in the optimal rearrangement. Examples Input 5 3 1 2 10 2 3 1 2 4 1 Output 10 Input 3 0 Output 0 Input 4 3 1 2 1 2 3 1 3 1 1 Output 0 Note In the first sample, you can assume that person number 1 owes 8 rubles to person number 2, 1 ruble to person number 3 and 1 ruble to person number 4. He doesn't owe anybody else anything. In the end, the total debt equals 10. In the second sample, there are no debts. In the third sample, you can annul all the debts. Submitted Solution: ``` from collections import defaultdict def debt(g): for i in g.keys(): l = len(g[i]) for k in range(l): t =g[i][k][1] u = g[i][k][0] if u in g.keys(): for j in g[u]: t -=j[1] g[i][k][1] = t return dict(g) n , m = map(int,input().split()) d = defaultdict(list) for _ in range(m): a,b,c = map(int,input().split()) d[a].append([b,c]) a = debt(d) s = 0 print(a) for i , j in a.items(): l = len(a[i]) for k in range(l): s+=j[k][1] print(s) ``` No
6,164
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Imagine that there is a group of three friends: A, B and Π‘. A owes B 20 rubles and B owes C 20 rubles. The total sum of the debts is 40 rubles. You can see that the debts are not organized in a very optimal manner. Let's rearrange them like that: assume that A owes C 20 rubles and B doesn't owe anything to anybody. The debts still mean the same but the total sum of the debts now equals 20 rubles. This task is a generalisation of a described example. Imagine that your group of friends has n people and you know the debts between the people. Optimize the given debts without changing their meaning. In other words, finally for each friend the difference between the total money he should give and the total money he should take must be the same. Print the minimum sum of all debts in the optimal rearrangement of the debts. See the notes to the test samples to better understand the problem. Input The first line contains two integers n and m (1 ≀ n ≀ 100; 0 ≀ m ≀ 104). The next m lines contain the debts. The i-th line contains three integers ai, bi, ci (1 ≀ ai, bi ≀ n; ai β‰  bi; 1 ≀ ci ≀ 100), which mean that person ai owes person bi ci rubles. Assume that the people are numbered by integers from 1 to n. It is guaranteed that the same pair of people occurs at most once in the input. The input doesn't simultaneously contain pair of people (x, y) and pair of people (y, x). Output Print a single integer β€” the minimum sum of debts in the optimal rearrangement. Examples Input 5 3 1 2 10 2 3 1 2 4 1 Output 10 Input 3 0 Output 0 Input 4 3 1 2 1 2 3 1 3 1 1 Output 0 Note In the first sample, you can assume that person number 1 owes 8 rubles to person number 2, 1 ruble to person number 3 and 1 ruble to person number 4. He doesn't owe anybody else anything. In the end, the total debt equals 10. In the second sample, there are no debts. In the third sample, you can annul all the debts. Submitted Solution: ``` import sys import math import collections import bisect from collections import deque as queue def get_ints(): return map(int, sys.stdin.readline().strip().split()) def get_list(): return list(map(int, sys.stdin.readline().strip().split())) def get_string(): return sys.stdin.readline().strip() for t in range(1): n,m=get_ints() counter=dict() for i in range(m): a,b,c=get_ints() if a in counter: counter[a]-=c elif b in counter: counter[b]+=c else: counter[a]=-c counter[b]=+c cost=0 for i in counter: val=counter[i] if val<=0: cost+=abs(val) print(cost) ``` No
6,165
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Imagine that there is a group of three friends: A, B and Π‘. A owes B 20 rubles and B owes C 20 rubles. The total sum of the debts is 40 rubles. You can see that the debts are not organized in a very optimal manner. Let's rearrange them like that: assume that A owes C 20 rubles and B doesn't owe anything to anybody. The debts still mean the same but the total sum of the debts now equals 20 rubles. This task is a generalisation of a described example. Imagine that your group of friends has n people and you know the debts between the people. Optimize the given debts without changing their meaning. In other words, finally for each friend the difference between the total money he should give and the total money he should take must be the same. Print the minimum sum of all debts in the optimal rearrangement of the debts. See the notes to the test samples to better understand the problem. Input The first line contains two integers n and m (1 ≀ n ≀ 100; 0 ≀ m ≀ 104). The next m lines contain the debts. The i-th line contains three integers ai, bi, ci (1 ≀ ai, bi ≀ n; ai β‰  bi; 1 ≀ ci ≀ 100), which mean that person ai owes person bi ci rubles. Assume that the people are numbered by integers from 1 to n. It is guaranteed that the same pair of people occurs at most once in the input. The input doesn't simultaneously contain pair of people (x, y) and pair of people (y, x). Output Print a single integer β€” the minimum sum of debts in the optimal rearrangement. Examples Input 5 3 1 2 10 2 3 1 2 4 1 Output 10 Input 3 0 Output 0 Input 4 3 1 2 1 2 3 1 3 1 1 Output 0 Note In the first sample, you can assume that person number 1 owes 8 rubles to person number 2, 1 ruble to person number 3 and 1 ruble to person number 4. He doesn't owe anybody else anything. In the end, the total debt equals 10. In the second sample, there are no debts. In the third sample, you can annul all the debts. Submitted Solution: ``` from collections import defaultdict as dd d=dd(lambda:0) from sys import stdin stdin.readline def mp(): return list(map(int, stdin.readline().strip().split())) def it():return int(stdin.readline().strip()) from math import pi,sqrt n,m=mp() try: for _ in range(m): a,b,deb=mp() d[a]+=deb d[b]-=deb print(max(d.values())) except: print(0) ``` No
6,166
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. User ainta decided to make a new instant messenger called "aintalk". With aintalk, each user can chat with other people. User ainta made the prototype of some functions to implement this thing. 1. login(u): User u logins into aintalk and becomes online. 2. logout(u): User u logouts and becomes offline. 3. add_friend(u, v): User u and user v become friends. It means, u and v can talk with each other. The friendship is bidirectional. 4. del_friend(u, v): Unfriend user u and user v. It means, u and v cannot talk with each other from then. 5. count_online_friends(u): The function returns the number of friends of user u who are online at the moment. Because the messenger is being tested by some users numbered from 1 to n, there is no register method. This means, at the beginning, some users may be online, and some users may have friends. User ainta is going to make these functions, but before making the messenger public, he wants to know whether he is correct. Help ainta verify his code. Input The first line contains three space-separated integers n, m and q (1 ≀ n ≀ 50000; 1 ≀ m ≀ 150000; 1 ≀ q ≀ 250000) β€” the number of users, the number of pairs of friends, and the number of queries. The second line contains an integer o (1 ≀ o ≀ n) β€” the number of online users at the beginning. The third line contains o space-separated integers x1, x2, ..., xo (1 ≀ xi ≀ n) β€” the ids of the online users. It is guaranteed that these values are distinct. Each of the next m lines contains two space-separated integers ai and bi (1 ≀ ai, bi ≀ n; ai β‰  bi) β€” the ids of two users who are friends at the beginning. It is guaranteed there are no multiple friendship given in the input. Note that the friendship is bidirectional. Next q lines describe the q queries in the format: * "O u" (1 ≀ u ≀ n) : Call online(u). It is guaranteed that user u was offline just before the function call. * "F u" (1 ≀ u ≀ n) : Call offline(u). It is guaranteed that user u was online just before the function call. * "A u v" (1 ≀ u, v ≀ n; u β‰  v) : Call add_friend(u, v). It is guaranteed that these two users weren't friends just before the function call. * "D u v" (1 ≀ u, v ≀ n; u β‰  v) : Call del_friend(u, v). It is guaranteed that these two users were friends just before the function call. * "C u" (1 ≀ u ≀ n) : Call count_online_friends(u) and print the result in a single line. Output For each count_online_friends(u) query, print the required answer in a single line. Examples Input 5 2 9 1 4 1 3 3 4 C 3 A 2 5 O 1 D 1 3 A 1 2 A 4 2 C 2 F 4 C 2 Output 1 2 1 Submitted Solution: ``` class User: def __init__(self, uid): self.uid = uid self.session = None self.friends = [] def addFriend(self, u): self.friends.append(u) u.friends.append(self) def removeFriend(self, u): self.friends.remove(u) u.friends.remove(self) def login(self): self.session = 1 def logout(self): self.session = None def onlineFriends(self): print(self.friends) return sum([1 for i in self.friends if i.session == 1]) n, m, q = list(map(int, input().split())) users_l = [None]*(n+1) for i in range(n+1): users_l[i] = User(i) o = int(input()) ou = list(map(int, input().split())) for i in range(o): users_l[i].login() for i in range(m): s = input().split() users_l[int(s[0])].addFriend(users_l[int(s[1])]) for i in range(q): s = input().split() if s[0] == 'O': users_l[int(s[1])].login() elif s[0] == 'F': users_l[int(s[1])].logout() elif s[0] == 'A': users_l[int(s[1])].addFriend(users_l[int(s[2])]) elif s[0] == 'D': users_l[int(s[1])].removeFriend(users_l[int(s[2])]) elif s[0] == 'C': print(users_l[int(s[1])].onlineFriends()) ``` No
6,167
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A coder cannot sit and code all day. Sometimes it is a good idea to rise from the desk, have a rest, have small talk with colleagues and even play. The coders of the F company have their favorite ball game. Let's imagine the game on the plane with a cartesian coordinate system. The point (0, 0) contains the player who chooses an arbitrary direction and throws a ball in that direction. The ball hits the plane at distance d from the player's original position and continues flying in the same direction. After the ball hits the plane for the first time, it flies on and hits the plane again at distance 2Β·d from the player's original position and so on (it continue flying in the chosen direction and hitting the plane after each d units). All coders in the F company are strong, so the ball flies infinitely far away. The plane has n circles painted on it. If a ball hits the plane and hits a circle that is painted on the plane (including its border), then the player gets one point. The ball can hit multiple circles at once and get one point for each of them (if the ball hits some circle x times during the move, the player also gets x points). Count the maximum number of points a player can get if he throws a ball in the arbitrary direction. Note that the direction may have real cooridinates. Input The first line contains two space-separated integers β€” n ΠΈ d (1 ≀ n ≀ 2Β·104; 5 ≀ d ≀ 10). Next n lines contain the circles' description. The i-th line contains three space-separated integers xi, yi, ri ( - 10000 ≀ xi, yi ≀ 10000; 1 ≀ r ≀ 50), where (xi, yi, ri) are the coordinates of the center and the radius of the circle, correspondingly. The point (0, 0) is not inside or on the border of some circle. Output Print a single integer β€” the maximum number of points you can get. Examples Input 2 5 1 1 1 5 0 1 Output 1 Input 2 5 4 0 3 5 3 1 Output 2 Input 1 10 20 0 10 Output 3 Submitted Solution: ``` import math class Point: def __init__(self, x1, y1): self.x = x1 self.y = y1 class Circle: def __init__(self, x1, y1, r1): self.A = Point(0, 0) self.B = Point(0, 0) self.x = float(x1) self.y = float(y1) self.r = float(r1) self.A.x = self.x - self.r #A is bottom left vertex self.A.y = self.y - self.r self.B.x = self.x + self.r #B is top right vertex self.B.y = self.y + self.r #special class that has 5 lists to store circles in class SpecialCircleList: def append(self, c): if(c.x >= 0): if(c.x - c.r <= 0): self.crosses_axis.append(c) return if(c.x <= 0): if(c.x + c.r >= 0): self.crosses_axis.append(c) return if(c.y >= 0): if(c.y - c.r <= 0): self.crosses_axis.append(c) return if(c.y <= 0): if(c.y + c.r >= 0): self.crosses_axis.append(c) return if(c.x > 0 and c.y > 0): self.first_quadrant.append(c) elif(c.x < 0 and c.y > 0): self.second_quadrant.append(c) elif(c.x < 0 and c.y < 0): self.thrid_quadrant.append(c) else: self.fourth_quadrant.append(c) #pass in a bounce point or unit vector, and i'll return a list of circles to check def getRelevantList(self, p): retList = list() retList.extend(self.crosses_axis) if(p.x >= 0 and p.y >= 0): retList.extend(self.first_quadrant) elif(p.x < 0 and p.y >= 0): retList.extend(self.second_quadrant) elif(p.x < 0 and p.y < 0): retList.extend(self.thrid_quadrant) else: retList.extend(self.fourth_quadrant) return(retList) def __init__(self): self.crosses_axis = list() #for any circle that even remotely crosses and axis self.first_quadrant = list() #for any circle that exclusively resides in quad self.second_quadrant = list() self.thrid_quadrant = list() self.fourth_quadrant = list() circle_list = SpecialCircleList() d = 0 bound_up = 0 bound_down = 0 bound_left = 0 bound_right = 0 max_score = 0 def main(): global circle_list global max_score global d global bound_up global bound_down global bound_left global bound_right line_in = input("") (n, d) = line_in.split() n = int(n) d = int(d) for i in range(n): line_in = input("") (x, y, r) = line_in.split() x = int(x) y = int(y) r = int(r) newCircle = Circle(x, y, r) circle_list.append(newCircle) #determine checking bounds if(y+r > bound_up): bound_up = y + r if(y-r < bound_down): bound_down = y - r if(x + r > bound_right): bound_right = x + r if(x - r < bound_left): bound_left = x - r #brute force for angles 0->360 for angle in range(0, 360, 5): #generate unit vector with direction unit_vector = Point(math.cos(angle*math.pi/180),math.sin(angle*math.pi/180)) #get a list of points where the ball will bounce for a given direction/line bounce_list = getBouncePoints(unit_vector, bound_up, bound_right,\ bound_down, bound_left) if(len(bounce_list) <= max_score): continue #no point doing this one if i've already got a higher score score_for_line = checkIfInAnyCircles(bounce_list, unit_vector) if(score_for_line > max_score): max_score = score_for_line print(max_score) #returns the score of a line/trajectory def checkIfInAnyCircles(bounce_list, unit_vector): global circle_list list_of_relavent_circles = circle_list.getRelevantList(unit_vector) score = 0 if(len(list_of_relavent_circles) == 0 or len(bounce_list) == 0): return(0) for b in bounce_list: for c in list_of_relavent_circles: if(b.x >= c.A.x and b.y >= c.A.y and b.x <= c.B.x and b.y <= c.B.y): if(thoroughCheck(b, c)): score += 1 return(score) #after passing a basic bounded box collision check, do a more thorough check with #floating point arithmatic to see if a bounce (b) lands within a given circle, (c) def thoroughCheck(b, c): distanceFromCircleCentre = (b.x - c.x)**2 + (b.y - c.y)**2 distanceFromCircleCentre = math.sqrt(distanceFromCircleCentre) if(distanceFromCircleCentre <= c.r): return(True) else: return(False) #returns a list of points which a ball will bounce at given a direction/trajectory #takes into consideration bounding box, so doens't calculate more than necessary def getBouncePoints(unit_vector, bound_up, bound_right, bound_down, bound_left ): global d bounce_list = list() bounce_vector = Point(unit_vector.x * d, unit_vector.y * d) newBounce = Point(0, 0) if(unit_vector.x >= 0 and unit_vector.y >= 0): #first quadrant while(newBounce.x <= bound_right and newBounce.y <= bound_up): newBounce = Point(newBounce.x +bounce_vector.x, newBounce.y +bounce_vector.y) bounce_list.append(newBounce) elif(unit_vector.x < 0 and unit_vector.y >= 0): #second quadrant while(newBounce.x >= bound_left and newBounce.y <= bound_up): newBounce = Point(newBounce.x +bounce_vector.x, newBounce.y +bounce_vector.y) bounce_list.append(newBounce) elif(unit_vector.x < 0 and unit_vector.y < 0): #thrid quadrant while(newBounce.x >= bound_left and newBounce.y >= bound_down): newBounce = Point(newBounce.x +bounce_vector.x, newBounce.y +bounce_vector.y) bounce_list.append(newBounce) else: #fourth quadrant while(newBounce.x <= bound_left and newBounce.y >= bound_down): newBounce = Point(newBounce.x +bounce_vector.x, newBounce.y +bounce_vector.y) bounce_list.append(newBounce) return(bounce_list) if __name__ == "__main__": main() ``` No
6,168
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A coder cannot sit and code all day. Sometimes it is a good idea to rise from the desk, have a rest, have small talk with colleagues and even play. The coders of the F company have their favorite ball game. Let's imagine the game on the plane with a cartesian coordinate system. The point (0, 0) contains the player who chooses an arbitrary direction and throws a ball in that direction. The ball hits the plane at distance d from the player's original position and continues flying in the same direction. After the ball hits the plane for the first time, it flies on and hits the plane again at distance 2Β·d from the player's original position and so on (it continue flying in the chosen direction and hitting the plane after each d units). All coders in the F company are strong, so the ball flies infinitely far away. The plane has n circles painted on it. If a ball hits the plane and hits a circle that is painted on the plane (including its border), then the player gets one point. The ball can hit multiple circles at once and get one point for each of them (if the ball hits some circle x times during the move, the player also gets x points). Count the maximum number of points a player can get if he throws a ball in the arbitrary direction. Note that the direction may have real cooridinates. Input The first line contains two space-separated integers β€” n ΠΈ d (1 ≀ n ≀ 2Β·104; 5 ≀ d ≀ 10). Next n lines contain the circles' description. The i-th line contains three space-separated integers xi, yi, ri ( - 10000 ≀ xi, yi ≀ 10000; 1 ≀ r ≀ 50), where (xi, yi, ri) are the coordinates of the center and the radius of the circle, correspondingly. The point (0, 0) is not inside or on the border of some circle. Output Print a single integer β€” the maximum number of points you can get. Examples Input 2 5 1 1 1 5 0 1 Output 1 Input 2 5 4 0 3 5 3 1 Output 2 Input 1 10 20 0 10 Output 3 Submitted Solution: ``` import math class Point: def __init__(self, x1, y1): self.x = x1 self.y = y1 class Circle: def __init__(self, x1, y1, r1): self.A = Point(0, 0) self.B = Point(0, 0) self.x = float(x1) self.y = float(y1) self.r = float(r1) self.A.x = self.x - self.r #A is bottom left vertex self.A.y = self.y - self.r self.B.x = self.x + self.r #B is top right vertex self.B.y = self.y + self.r self.angle = math.degrees(math.atan2(self.y, self.x)) #special class that has 5 lists to store circles in class SpecialCircleList: def append(self, c): if(c.x >= 0): if(c.x - c.r <= 0): self.crosses_axis.append(c) return if(c.x <= 0): if(c.x + c.r >= 0): self.crosses_axis.append(c) return if(c.y >= 0): if(c.y - c.r <= 0): self.crosses_axis.append(c) return if(c.y <= 0): if(c.y + c.r >= 0): self.crosses_axis.append(c) return if(c.x > 0 and c.y > 0): self.first_quadrant.append(c) elif(c.x < 0 and c.y > 0): self.second_quadrant.append(c) elif(c.x < 0 and c.y < 0): self.thrid_quadrant.append(c) else: self.fourth_quadrant.append(c) #pass in a bounce point or unit vector, and i'll return a list of circles to check def getRelevantList(self, p): acceptance_angle = 45 pangle = math.degrees(math.atan2(p.y, p.x)) retList = list() for c in self.crosses_axis: if((abs(pangle - c.angle) <acceptance_angle) or abs(c.x < 50) or abs(c.y<50)): retList.append(c) #retList.extend(self.crosses_axis) if(p.x >= 0 and p.y >= 0): #retList.extend(self.first_quadrant) for c in self.first_quadrant: if(abs(pangle - c.angle) < acceptance_angle): retList.append(c) elif(p.x < 0 and p.y >= 0): #retList.extend(self.second_quadrant) for c in self.second_quadrant: if(abs(pangle - c.angle) < acceptance_angle): retList.append(c) elif(p.x < 0 and p.y < 0): #retList.extend(self.thrid_quadrant) for c in self.thrid_quadrant: if(abs(pangle - c.angle) < acceptance_angle): retList.append(c) else: #retList.extend(self.fourth_quadrant) for c in self.fourth_quadrant: if(abs(pangle - c.angle) < acceptance_angle): retList.append(c) return(retList) def __init__(self): self.crosses_axis = list() #for any circle that even remotely crosses and axis self.first_quadrant = list() #for any circle that exclusively resides in quad self.second_quadrant = list() self.thrid_quadrant = list() self.fourth_quadrant = list() circle_list = SpecialCircleList() d = 0 bound_up = 0 bound_down = 0 bound_left = 0 bound_right = 0 max_score = 0 def main(): global circle_list global max_score global d global bound_up global bound_down global bound_left global bound_right line_in = input("") (n, d) = line_in.split() n = int(n) d = int(d) for i in range(n): line_in = input("") (x, y, r) = line_in.split() x = int(x) y = int(y) r = int(r) newCircle = Circle(x, y, r) circle_list.append(newCircle) #determine checking bounds if(y+r > bound_up): bound_up = y + r if(y-r < bound_down): bound_down = y - r if(x + r > bound_right): bound_right = x + r if(x - r < bound_left): bound_left = x - r #brute force for angles 0->360 for angle in range(0, 360, 3): #generate unit vector with direction unit_vector = Point(math.cos(angle*math.pi/180),math.sin(angle*math.pi/180)) #get a list of points where the ball will bounce for a given direction/line bounce_list = getBouncePoints(unit_vector, bound_up, bound_right,\ bound_down, bound_left) if(len(bounce_list) <= max_score): continue #no point doing this one if i've already got a higher score score_for_line = checkIfInAnyCircles(bounce_list, unit_vector) if(score_for_line > max_score): max_score = score_for_line print(max_score) #returns the score of a line/trajectory def checkIfInAnyCircles(bounce_list, unit_vector): global circle_list list_of_relavent_circles = circle_list.getRelevantList(unit_vector) score = 0 if(len(list_of_relavent_circles) == 0 or len(bounce_list) == 0): return(0) for b in bounce_list: for c in list_of_relavent_circles: if(b.x >= c.A.x and b.y >= c.A.y and b.x <= c.B.x and b.y <= c.B.y): if(thoroughCheck(b, c)): score += 1 return(score) #after passing a basic bounded box collision check, do a more thorough check with #floating point arithmatic to see if a bounce (b) lands within a given circle, (c) def thoroughCheck(b, c): distanceFromCircleCentre = (b.x - c.x)**2 + (b.y - c.y)**2 distanceFromCircleCentre = math.sqrt(distanceFromCircleCentre) if(distanceFromCircleCentre <= c.r): return(True) else: return(False) #returns a list of points which a ball will bounce at given a direction/trajectory #takes into consideration bounding box, so doens't calculate more than necessary def getBouncePoints(unit_vector, bound_up, bound_right, bound_down, bound_left ): global d bounce_list = list() bounce_vector = Point(unit_vector.x * d, unit_vector.y * d) newBounce = Point(0, 0) if(unit_vector.x >= 0 and unit_vector.y >= 0): #first quadrant while(newBounce.x <= bound_right and newBounce.y <= bound_up): newBounce = Point(newBounce.x +bounce_vector.x, newBounce.y +bounce_vector.y) bounce_list.append(newBounce) elif(unit_vector.x < 0 and unit_vector.y >= 0): #second quadrant while(newBounce.x >= bound_left and newBounce.y <= bound_up): newBounce = Point(newBounce.x +bounce_vector.x, newBounce.y +bounce_vector.y) bounce_list.append(newBounce) elif(unit_vector.x < 0 and unit_vector.y < 0): #thrid quadrant while(newBounce.x >= bound_left and newBounce.y >= bound_down): newBounce = Point(newBounce.x +bounce_vector.x, newBounce.y +bounce_vector.y) bounce_list.append(newBounce) else: #fourth quadrant while(newBounce.x <= bound_left and newBounce.y >= bound_down): newBounce = Point(newBounce.x +bounce_vector.x, newBounce.y +bounce_vector.y) bounce_list.append(newBounce) return(bounce_list) if __name__ == "__main__": main() ``` No
6,169
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A coder cannot sit and code all day. Sometimes it is a good idea to rise from the desk, have a rest, have small talk with colleagues and even play. The coders of the F company have their favorite ball game. Let's imagine the game on the plane with a cartesian coordinate system. The point (0, 0) contains the player who chooses an arbitrary direction and throws a ball in that direction. The ball hits the plane at distance d from the player's original position and continues flying in the same direction. After the ball hits the plane for the first time, it flies on and hits the plane again at distance 2Β·d from the player's original position and so on (it continue flying in the chosen direction and hitting the plane after each d units). All coders in the F company are strong, so the ball flies infinitely far away. The plane has n circles painted on it. If a ball hits the plane and hits a circle that is painted on the plane (including its border), then the player gets one point. The ball can hit multiple circles at once and get one point for each of them (if the ball hits some circle x times during the move, the player also gets x points). Count the maximum number of points a player can get if he throws a ball in the arbitrary direction. Note that the direction may have real cooridinates. Input The first line contains two space-separated integers β€” n ΠΈ d (1 ≀ n ≀ 2Β·104; 5 ≀ d ≀ 10). Next n lines contain the circles' description. The i-th line contains three space-separated integers xi, yi, ri ( - 10000 ≀ xi, yi ≀ 10000; 1 ≀ r ≀ 50), where (xi, yi, ri) are the coordinates of the center and the radius of the circle, correspondingly. The point (0, 0) is not inside or on the border of some circle. Output Print a single integer β€” the maximum number of points you can get. Examples Input 2 5 1 1 1 5 0 1 Output 1 Input 2 5 4 0 3 5 3 1 Output 2 Input 1 10 20 0 10 Output 3 Submitted Solution: ``` import math class Point: def __init__(self, x1, y1): self.x = x1 self.y = y1 class Circle: def __init__(self, x1, y1, r1): self.A = Point(0, 0) self.B = Point(0, 0) self.x = float(x1) self.y = float(y1) self.r = float(r1) self.A.x = self.x - self.r #A is bottom left vertex self.A.y = self.y - self.r self.B.x = self.x + self.r #B is top right vertex self.B.y = self.y + self.r self.angle = math.degrees(math.atan2(self.y, self.x)) self.d = math.hypot(self.x, self.y) #special class that has 5 lists to store circles in class SpecialCircleList: def append(self, c): if(c.x >= 0): if(c.x - c.r <= 0): self.crosses_axis.append(c) return if(c.x <= 0): if(c.x + c.r >= 0): self.crosses_axis.append(c) return if(c.y >= 0): if(c.y - c.r <= 0): self.crosses_axis.append(c) return if(c.y <= 0): if(c.y + c.r >= 0): self.crosses_axis.append(c) return if(c.x > 0 and c.y > 0): self.first_quadrant.append(c) elif(c.x < 0 and c.y > 0): self.second_quadrant.append(c) elif(c.x < 0 and c.y < 0): self.thrid_quadrant.append(c) else: self.fourth_quadrant.append(c) #pass in a bounce point or unit vector, and i'll return a list of circles to check def getRelevantList(self, p): acceptance_angle = 30 pangle = math.degrees(math.atan2(p.y, p.x)) retList = list() max_d = 0 for c in self.crosses_axis: if((abs(pangle - c.angle) <acceptance_angle) or abs(c.x < 50) or abs(c.y<50)): retList.append(c) if(c.d > max_d): max_d = c.d #retList.extend(self.crosses_axis) if(p.x >= 0 and p.y >= 0): #retList.extend(self.first_quadrant) for c in self.first_quadrant: if(abs(pangle - c.angle) < acceptance_angle): retList.append(c) if(c.d > max_d): max_d = c.d elif(p.x < 0 and p.y >= 0): #retList.extend(self.second_quadrant) for c in self.second_quadrant: if(abs(pangle - c.angle) < acceptance_angle): retList.append(c) if(c.d > max_d): max_d = c.d elif(p.x < 0 and p.y < 0): #retList.extend(self.thrid_quadrant) for c in self.thrid_quadrant: if(abs(pangle - c.angle) < acceptance_angle): retList.append(c) if(c.d > max_d): max_d = c.d else: #retList.extend(self.fourth_quadrant) for c in self.fourth_quadrant: if(abs(pangle - c.angle) < acceptance_angle): retList.append(c) if(c.d > max_d): max_d = c.d return(retList, max_d) def __init__(self): self.crosses_axis = list() #for any circle that even remotely crosses and axis self.first_quadrant = list() #for any circle that exclusively resides in quad self.second_quadrant = list() self.thrid_quadrant = list() self.fourth_quadrant = list() circle_list = SpecialCircleList() d = 0 bound_up = 0 bound_down = 0 bound_left = 0 bound_right = 0 max_score = 0 def main(): global circle_list global max_score global d global bound_up global bound_down global bound_left global bound_right line_in = input("") (n, d) = line_in.split() n = int(n) d = int(d) for i in range(n): line_in = input("") (x, y, r) = line_in.split() x = int(x) y = int(y) r = int(r) newCircle = Circle(x, y, r) circle_list.append(newCircle) #determine checking bounds if(y+r > bound_up): bound_up = y + r if(y-r < bound_down): bound_down = y - r if(x + r > bound_right): bound_right = x + r if(x - r < bound_left): bound_left = x - r #brute force for angles 0->360 for angle in range(0, 360, 2): #generate unit vector with direction unit_vector = Point(math.cos(angle*math.pi/180),math.sin(angle*math.pi/180)) #get a list of points where the ball will bounce for a given direction/line score_for_line = checkIfInAnyCircles(unit_vector) if(score_for_line > max_score): max_score = score_for_line print(max_score) #returns the score of a line/trajectory def checkIfInAnyCircles(unit_vector): global circle_list global d list_of_relavent_circles, max_d = circle_list.getRelevantList(unit_vector) #bounce_list = getBouncePoints(unit_vector, bound_up, bound_right,\ # bound_down, bound_left) score = 0 if(len(list_of_relavent_circles) < (max_score/2)): return(0) #largestX = 0 #largestY = 0 #for c in list_of_relavent_circles: # if(abs(c.x) > largestX): # largestX = abs(c.x) # if(abs(c.y) > largestY): # largestY = abs(c.y) bounce_vector = Point(unit_vector.x * d, unit_vector.y * d) b = Point(bounce_vector.x, bounce_vector.y) max_d = int((max_d + 50)/d) i = 0 while(i < max_d): #while((abs(b.x) <= largestX + 50) and (abs(b.y) <= largestY + 50)): #for b in bounce_list: for c in list_of_relavent_circles: if(b.x >= c.A.x and b.y >= c.A.y and b.x <= c.B.x and b.y <= c.B.y): if(thoroughCheck(b, c)): score += 1 b.x += bounce_vector.x b.y += bounce_vector.y i += 1 return(score) #after passing a basic bounded box collision check, do a more thorough check with #floating point arithmatic to see if a bounce (b) lands within a given circle, (c) def thoroughCheck(b, c): distanceFromCircleCentre = (b.x - c.x)**2 + (b.y - c.y)**2 distanceFromCircleCentre = math.sqrt(distanceFromCircleCentre) if(distanceFromCircleCentre <= c.r): return(True) else: return(False) #returns a list of points which a ball will bounce at given a direction/trajectory #takes into consideration bounding box, so doens't calculate more than necessary def getBouncePoints(unit_vector, bound_up, bound_right, bound_down, bound_left ): global d bounce_list = list() bounce_vector = Point(unit_vector.x * d, unit_vector.y * d) newBounce = Point(0, 0) if(unit_vector.x >= 0 and unit_vector.y >= 0): #first quadrant while(newBounce.x <= bound_right and newBounce.y <= bound_up): newBounce = Point(newBounce.x +bounce_vector.x, newBounce.y +bounce_vector.y) bounce_list.append(newBounce) elif(unit_vector.x < 0 and unit_vector.y >= 0): #second quadrant while(newBounce.x >= bound_left and newBounce.y <= bound_up): newBounce = Point(newBounce.x +bounce_vector.x, newBounce.y +bounce_vector.y) bounce_list.append(newBounce) elif(unit_vector.x < 0 and unit_vector.y < 0): #thrid quadrant while(newBounce.x >= bound_left and newBounce.y >= bound_down): newBounce = Point(newBounce.x +bounce_vector.x, newBounce.y +bounce_vector.y) bounce_list.append(newBounce) else: #fourth quadrant while(newBounce.x <= bound_left and newBounce.y >= bound_down): newBounce = Point(newBounce.x +bounce_vector.x, newBounce.y +bounce_vector.y) bounce_list.append(newBounce) return(bounce_list) if __name__ == "__main__": main() ``` No
6,170
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A coder cannot sit and code all day. Sometimes it is a good idea to rise from the desk, have a rest, have small talk with colleagues and even play. The coders of the F company have their favorite ball game. Let's imagine the game on the plane with a cartesian coordinate system. The point (0, 0) contains the player who chooses an arbitrary direction and throws a ball in that direction. The ball hits the plane at distance d from the player's original position and continues flying in the same direction. After the ball hits the plane for the first time, it flies on and hits the plane again at distance 2Β·d from the player's original position and so on (it continue flying in the chosen direction and hitting the plane after each d units). All coders in the F company are strong, so the ball flies infinitely far away. The plane has n circles painted on it. If a ball hits the plane and hits a circle that is painted on the plane (including its border), then the player gets one point. The ball can hit multiple circles at once and get one point for each of them (if the ball hits some circle x times during the move, the player also gets x points). Count the maximum number of points a player can get if he throws a ball in the arbitrary direction. Note that the direction may have real cooridinates. Input The first line contains two space-separated integers β€” n ΠΈ d (1 ≀ n ≀ 2Β·104; 5 ≀ d ≀ 10). Next n lines contain the circles' description. The i-th line contains three space-separated integers xi, yi, ri ( - 10000 ≀ xi, yi ≀ 10000; 1 ≀ r ≀ 50), where (xi, yi, ri) are the coordinates of the center and the radius of the circle, correspondingly. The point (0, 0) is not inside or on the border of some circle. Output Print a single integer β€” the maximum number of points you can get. Examples Input 2 5 1 1 1 5 0 1 Output 1 Input 2 5 4 0 3 5 3 1 Output 2 Input 1 10 20 0 10 Output 3 Submitted Solution: ``` import math class Point: def __init__(self, x1, y1): self.x = x1 self.y = y1 class Circle: def __init__(self, x1, y1, r1): self.A = Point(0, 0) self.B = Point(0, 0) self.x = float(x1) self.y = float(y1) self.r = float(r1) self.A.x = self.x - self.r #A is bottom left vertex self.A.y = self.y - self.r self.B.x = self.x + self.r #B is top right vertex self.B.y = self.y + self.r self.angle = math.degrees(math.atan2(self.y, self.x)) self.d = math.hypot(self.x, self.y) #special class that has 5 lists to store circles in class SpecialCircleList: def append(self, c): if(c.x >= 0): if(c.x - c.r <= 0): self.crosses_axis.append(c) return if(c.x <= 0): if(c.x + c.r >= 0): self.crosses_axis.append(c) return if(c.y >= 0): if(c.y - c.r <= 0): self.crosses_axis.append(c) return if(c.y <= 0): if(c.y + c.r >= 0): self.crosses_axis.append(c) return if(c.x > 0 and c.y > 0): self.first_quadrant.append(c) elif(c.x < 0 and c.y > 0): self.second_quadrant.append(c) elif(c.x < 0 and c.y < 0): self.thrid_quadrant.append(c) else: self.fourth_quadrant.append(c) #pass in a bounce point or unit vector, and i'll return a list of circles to check def getRelevantList(self, p): acceptance_angle = 5 pangle = math.degrees(math.atan2(p.y, p.x)) retList = list() max_d = 0 for c in self.crosses_axis: if((abs(pangle - c.angle) <acceptance_angle) or abs(c.x < 50) or abs(c.y<50)): retList.append(c) if(c.d > max_d): max_d = c.d #retList.extend(self.crosses_axis) if(p.x >= 0 and p.y >= 0): #retList.extend(self.first_quadrant) for c in self.first_quadrant: if(abs(pangle - c.angle) < acceptance_angle): retList.append(c) if(c.d > max_d): max_d = c.d elif(p.x < 0 and p.y >= 0): #retList.extend(self.second_quadrant) for c in self.second_quadrant: if(abs(pangle - c.angle) < acceptance_angle): retList.append(c) if(c.d > max_d): max_d = c.d elif(p.x < 0 and p.y < 0): #retList.extend(self.thrid_quadrant) for c in self.thrid_quadrant: if(abs(pangle - c.angle) < acceptance_angle): retList.append(c) if(c.d > max_d): max_d = c.d else: #retList.extend(self.fourth_quadrant) for c in self.fourth_quadrant: if(abs(pangle - c.angle) < acceptance_angle): retList.append(c) if(c.d > max_d): max_d = c.d return(retList, max_d) def __init__(self): self.crosses_axis = list() #for any circle that even remotely crosses and axis self.first_quadrant = list() #for any circle that exclusively resides in quad self.second_quadrant = list() self.thrid_quadrant = list() self.fourth_quadrant = list() self.frequency = [] circle_list = SpecialCircleList() d = 0 bound_up = 0 bound_down = 0 bound_left = 0 bound_right = 0 max_score = 0 def main(): global circle_list global max_score global d global bound_up global bound_down global bound_left global bound_right line_in = input("") (n, d) = line_in.split() n = int(n) d = int(d) for i in range(n): line_in = input("") (x, y, r) = line_in.split() x = int(x) y = int(y) r = int(r) newCircle = Circle(x, y, r) circle_list.append(newCircle) #determine checking bounds if(y+r > bound_up): bound_up = y + r if(y-r < bound_down): bound_down = y - r if(x + r > bound_right): bound_right = x + r if(x - r < bound_left): bound_left = x - r #brute force for angles 0->360 for angle in range(0, 360, 1): #generate unit vector with direction unit_vector = Point(math.cos(angle*math.pi/180),math.sin(angle*math.pi/180)) score_for_line = checkIfInAnyCircles(unit_vector) if(score_for_line > max_score): max_score = score_for_line print(max_score) #returns the score of a line/trajectory def checkIfInAnyCircles(unit_vector): global circle_list global d list_of_relavent_circles, max_d = circle_list.getRelevantList(unit_vector) score = 0 if(len(list_of_relavent_circles) < (max_score/2)): return(0) bounce_vector = Point(unit_vector.x * d, unit_vector.y * d) b = Point(bounce_vector.x, bounce_vector.y) max_d = int((max_d + 50)/d) i = 0 while(i < max_d): for c in list_of_relavent_circles: if(b.x >= c.A.x and b.y >= c.A.y and b.x <= c.B.x and b.y <= c.B.y): if(thoroughCheck(b, c)): score += 1 b.x += bounce_vector.x b.y += bounce_vector.y i += 1 return(score) #after passing a basic bounded box collision check, do a more thorough check with #floating point arithmatic to see if a bounce (b) lands within a given circle, (c) def thoroughCheck(b, c): distanceFromCircleCentre = (b.x - c.x)**2 + (b.y - c.y)**2 distanceFromCircleCentre = math.sqrt(distanceFromCircleCentre) if(distanceFromCircleCentre <= c.r): return(True) else: return(False) if __name__ == "__main__": main() ``` No
6,171
Provide tags and a correct Python 3 solution for this coding contest problem. DZY has a sequence a, consisting of n integers. We'll call a sequence ai, ai + 1, ..., aj (1 ≀ i ≀ j ≀ n) a subsegment of the sequence a. The value (j - i + 1) denotes the length of the subsegment. Your task is to find the longest subsegment of a, such that it is possible to change at most one number (change one number to any integer you want) from the subsegment to make the subsegment strictly increasing. You only need to output the length of the subsegment you find. Input The first line contains integer n (1 ≀ n ≀ 105). The next line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109). Output In a single line print the answer to the problem β€” the maximum length of the required subsegment. Examples Input 6 7 2 3 1 5 6 Output 5 Note You can choose subsegment a2, a3, a4, a5, a6 and change its 3rd element (that is a4) to 4. Tags: dp, implementation, two pointers Correct Solution: ``` import math; from math import log2,sqrt; import sys; sys.setrecursionlimit(pow(10,6)) import collections from collections import defaultdict from statistics import median inf = float("inf") mod=pow(10,9)+7 def gen_left(a): l=[0]*n; for i in range(1,len(l)): if a[i]>a[i-1]: l[i]=l[i-1]+1; return l; def gen_right(a): r=[0]*n; for i in reversed(range(len(l)-1)): if a[i]<a[i+1]: r[i]=r[i+1]+1 return r; def generate(a,l,r): ans=0 for i in range(n): if i==0: ans=max(ans,r[i+1]+1+1) elif i==n-1: ans=max(ans,l[n-2]+1+1) elif a[i-1]+1<a[i+1]: ans=max(ans,r[i+1]+1+l[i-1]+1+1) else: ans=max(ans,r[i+1]+1+1,l[i-1]+1+1) return ans; t=1; for i in range(t): n=int(input()) a = list(map(int, input().split())) if n==1: print(1) continue if n==2: print(2) continue l=gen_left(a) r=gen_right(a) ans=generate(a,l,r) print(ans) ```
6,172
Provide tags and a correct Python 3 solution for this coding contest problem. DZY has a sequence a, consisting of n integers. We'll call a sequence ai, ai + 1, ..., aj (1 ≀ i ≀ j ≀ n) a subsegment of the sequence a. The value (j - i + 1) denotes the length of the subsegment. Your task is to find the longest subsegment of a, such that it is possible to change at most one number (change one number to any integer you want) from the subsegment to make the subsegment strictly increasing. You only need to output the length of the subsegment you find. Input The first line contains integer n (1 ≀ n ≀ 105). The next line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109). Output In a single line print the answer to the problem β€” the maximum length of the required subsegment. Examples Input 6 7 2 3 1 5 6 Output 5 Note You can choose subsegment a2, a3, a4, a5, a6 and change its 3rd element (that is a4) to 4. Tags: dp, implementation, two pointers Correct Solution: ``` # import math n = int(input()) arr = [int(var) for var in input().split()] maxLeft = [1 for _ in range(n)] maxRight = [1 for _ in range(n)] ans = 1 # maxLeft[0], maxRight[-1] = 1, 1 for i in range(1, n): if arr[i] > arr[i-1]: maxLeft[i] = maxLeft[i-1]+1 for i in reversed(range(n-1)): if arr[i] < arr[i+1]: maxRight[i] = maxRight[i+1] + 1 # DEBUG # print(arr) # print(maxRight) # print(maxLeft) for i in range(n): prev, next = arr[i-1] if i-1 >= 0 else -float("inf"), arr[i+1] if i+1 < n else float("inf") leftSubArray = maxLeft[i-1] if i-1 >= 0 else 0 rightSubArray = maxRight[i+1] if i+1 < n else 0 if not(prev < arr[i] < next): if next - prev >= 2: ans = max(ans, rightSubArray+leftSubArray+1) else: ans = max(ans, leftSubArray+1, 1+rightSubArray) else: ans = max(ans, rightSubArray + leftSubArray + 1) print(ans) ```
6,173
Provide tags and a correct Python 3 solution for this coding contest problem. DZY has a sequence a, consisting of n integers. We'll call a sequence ai, ai + 1, ..., aj (1 ≀ i ≀ j ≀ n) a subsegment of the sequence a. The value (j - i + 1) denotes the length of the subsegment. Your task is to find the longest subsegment of a, such that it is possible to change at most one number (change one number to any integer you want) from the subsegment to make the subsegment strictly increasing. You only need to output the length of the subsegment you find. Input The first line contains integer n (1 ≀ n ≀ 105). The next line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109). Output In a single line print the answer to the problem β€” the maximum length of the required subsegment. Examples Input 6 7 2 3 1 5 6 Output 5 Note You can choose subsegment a2, a3, a4, a5, a6 and change its 3rd element (that is a4) to 4. Tags: dp, implementation, two pointers Correct Solution: ``` n=int(input()) l=list(map(int,input().split(" "))) a=[1]*n b=[1]*n for i in range(1,n): if l[i]>l[i-1]: a[i]=a[i-1]+1 i=n-2 while(i>=0): if l[i+1]>l[i]: b[i]=b[i+1]+1 i=i-1 total=max(a) if total<n: total=total+1 for i in range(1,n-1): if l[i-1]+1<l[i+1]: total=max(total,a[i-1]+1+b[i+1]) else: total=max(total,a[i-1]+1) print(total) # Made By Mostafa_Khaled ```
6,174
Provide tags and a correct Python 3 solution for this coding contest problem. DZY has a sequence a, consisting of n integers. We'll call a sequence ai, ai + 1, ..., aj (1 ≀ i ≀ j ≀ n) a subsegment of the sequence a. The value (j - i + 1) denotes the length of the subsegment. Your task is to find the longest subsegment of a, such that it is possible to change at most one number (change one number to any integer you want) from the subsegment to make the subsegment strictly increasing. You only need to output the length of the subsegment you find. Input The first line contains integer n (1 ≀ n ≀ 105). The next line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109). Output In a single line print the answer to the problem β€” the maximum length of the required subsegment. Examples Input 6 7 2 3 1 5 6 Output 5 Note You can choose subsegment a2, a3, a4, a5, a6 and change its 3rd element (that is a4) to 4. Tags: dp, implementation, two pointers Correct Solution: ``` import sys n = int(input()) s = list(map(int, input().split())) a = [0] * n b = [0] * n a[0] = 1 b[0] = 1 if n == 1: print(1) sys.exit() for i in range(1, n): if s[i] > s[i-1]: a[i] = a[i-1] + 1 else: a[i] = 1 s = s[::-1] for i in range(1, n): if s[i] < s[i-1]: b[i] = b[i-1] + 1 else: b[i] = 1 s = s[::-1] b = b[::-1] ans = b[1] + 1 for i in range(1, n - 1): if s[i-1] + 1 < s[i + 1]: ans = max(ans, a[i - 1] + 1 + b[i + 1]) else: ans = max(ans, a[i - 1] + 1, 1 + b[i + 1]) ans = max(ans, a[n - 2] + 1) print(ans) ```
6,175
Provide tags and a correct Python 3 solution for this coding contest problem. DZY has a sequence a, consisting of n integers. We'll call a sequence ai, ai + 1, ..., aj (1 ≀ i ≀ j ≀ n) a subsegment of the sequence a. The value (j - i + 1) denotes the length of the subsegment. Your task is to find the longest subsegment of a, such that it is possible to change at most one number (change one number to any integer you want) from the subsegment to make the subsegment strictly increasing. You only need to output the length of the subsegment you find. Input The first line contains integer n (1 ≀ n ≀ 105). The next line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109). Output In a single line print the answer to the problem β€” the maximum length of the required subsegment. Examples Input 6 7 2 3 1 5 6 Output 5 Note You can choose subsegment a2, a3, a4, a5, a6 and change its 3rd element (that is a4) to 4. Tags: dp, implementation, two pointers Correct Solution: ``` """ pppppppppppppppppppp ppppp ppppppppppppppppppp ppppppp ppppppppppppppppppppp pppppppp pppppppppppppppppppppp pppppppppppppppppppppppppppppppp pppppppppppppppppppppppp ppppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppp pppppppppppppppppppppppppppppppppppppppppppppppp ppppppppppppppppppppp ppppppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppppp ppppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppppppp pppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppppppppp ppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppppppppppp pppppppppppppppppppppppppppppppp pppppppppppppppppppppppppppppppp pppppppppppppppppppppppppppp pppppppppppppppppppppppppppppppppppppppppppppp ppppppppppppppppppppppppppp pppppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppppppp pppppppppppppppppppppppppppppppppppppppppppppppppp ppppppppppppppppppppppp ppppppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppppp ppppppppppppppppppppppppppppppppppppppppppppppp ppppppppppppppppppppp ppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppppppp pppppppppppppppppppppppppppppppp pppppppppppppppppppppp pppppppp ppppppppppppppppppppp ppppppp ppppppppppppppppppp ppppp pppppppppppppppppppp """ import sys from functools import lru_cache, cmp_to_key from heapq import merge, heapify, heappop, heappush, nsmallest from math import ceil, floor, gcd, fabs, factorial, fmod, sqrt, inf from collections import defaultdict as dd, deque, Counter as C from itertools import combinations as comb, permutations as perm from bisect import bisect_left as bl, bisect_right as br, bisect from time import perf_counter from fractions import Fraction from decimal import Decimal # sys.setrecursionlimit(pow(10, 6)) # sys.stdin = open("input.txt", "r") # sys.stdout = open("output.txt", "w") mod = pow(10, 9) + 7 mod2 = 998244353 def data(): return sys.stdin.readline().strip() def out(var): sys.stdout.write(str(var)) def outa(*var, end="\n"): sys.stdout.write(' '.join(map(str, var)) + end) def l(): return list(sp()) def sl(): return list(ssp()) def sp(): return map(int, data().split()) def ssp(): return map(str, data().split()) def l1d(n, val=0): return [val for i in range(n)] def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)] n = int(data()) arr = l() if len(arr) <= 2: out(n) exit() suf, pref = [1] * n, [1] * n for i in range(1, n): if arr[i] > arr[i-1]: suf[i] = suf[i-1] + 1 for i in range(n-2, -1, -1): if arr[i] < arr[i+1]: pref[i] = pref[i+1] + 1 answer = max(suf) if answer < n: answer += 1 for i in range(1, n-1): if arr[i-1] + 1 < arr[i+1]: answer = max(answer, suf[i-1] + 1 + pref[i+1]) out(answer) ```
6,176
Provide tags and a correct Python 3 solution for this coding contest problem. DZY has a sequence a, consisting of n integers. We'll call a sequence ai, ai + 1, ..., aj (1 ≀ i ≀ j ≀ n) a subsegment of the sequence a. The value (j - i + 1) denotes the length of the subsegment. Your task is to find the longest subsegment of a, such that it is possible to change at most one number (change one number to any integer you want) from the subsegment to make the subsegment strictly increasing. You only need to output the length of the subsegment you find. Input The first line contains integer n (1 ≀ n ≀ 105). The next line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109). Output In a single line print the answer to the problem β€” the maximum length of the required subsegment. Examples Input 6 7 2 3 1 5 6 Output 5 Note You can choose subsegment a2, a3, a4, a5, a6 and change its 3rd element (that is a4) to 4. Tags: dp, implementation, two pointers Correct Solution: ``` #!/usr/bin/env python # -*- coding: utf-8 -*- N = int(input()) A = list(map(int,input().split())) subseg = [] start = 0 for i in range(N-1): if A[i] >= A[i+1]: subseg.append((A[start],A[i],i-start,start,i)) start = i+1 else: if N-1 == 0: subseg.append((A[start],A[start],N-start-1,start,start)) else: subseg.append((A[start],A[i+1],N-start-1,start,i+1)) l = len(subseg) ans = max(subseg,key=lambda x:x[2])[2] + 1 for i in range(l): if i + 1 < l and subseg[i+1][2] == 0: if i+2 < l and subseg[i][1] + 2 <= subseg[i+2][0]: ans = max(ans,subseg[i][2] + subseg[i+2][2] + 3) if i + 1 < l and subseg[i+1][3] + 1 < N and subseg[i][1] + 1 < A[subseg[i+1][3]+1]: ans = max(ans,subseg[i][2] + subseg[i+1][2] + 2) if i + 1 < l and 0 <= subseg[i][4] - 1 and A[subseg[i][4]-1] + 1 < subseg[i+1][0]: ans = max(ans,subseg[i][2] + subseg[i+1][2] + 2) if i != 0 or i != l -1: ans = max(ans,subseg[i][2] + 2) else: ans = max(ans,subseg[i][2] + 1) print(ans) ```
6,177
Provide tags and a correct Python 3 solution for this coding contest problem. DZY has a sequence a, consisting of n integers. We'll call a sequence ai, ai + 1, ..., aj (1 ≀ i ≀ j ≀ n) a subsegment of the sequence a. The value (j - i + 1) denotes the length of the subsegment. Your task is to find the longest subsegment of a, such that it is possible to change at most one number (change one number to any integer you want) from the subsegment to make the subsegment strictly increasing. You only need to output the length of the subsegment you find. Input The first line contains integer n (1 ≀ n ≀ 105). The next line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109). Output In a single line print the answer to the problem β€” the maximum length of the required subsegment. Examples Input 6 7 2 3 1 5 6 Output 5 Note You can choose subsegment a2, a3, a4, a5, a6 and change its 3rd element (that is a4) to 4. Tags: dp, implementation, two pointers Correct Solution: ``` import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**10 mod = 998244353 dd = [(-1,0),(0,1),(1,0),(0,-1)] ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)] def LI(): return list(map(int, sys.stdin.readline().split())) def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines()] def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()] def LF(): return [float(x) for x in sys.stdin.readline().split()] def LS(): return sys.stdin.readline().split() def I(): return int(sys.stdin.readline()) def F(): return float(sys.stdin.readline()) def S(): return input() def pf(s): return print(s, flush=True) def pe(s): return print(str(s), file=sys.stderr) def JA(a, sep): return sep.join(map(str, a)) def JAA(a, s, t): return s.join(t.join(map(str, b)) for b in a) def main(): n = I() a = LI() if n < 3: return n b = [1] for i in range(1,n): if a[i-1] < a[i]: b.append(b[-1] + 1) else: b.append(1) c = [1] for i in range(n-2,-1,-1): if a[i+1] > a[i]: c.append(c[-1]+1) else: c.append(1) c = c[::-1] # print(b) # print(c) r = max(c[1], b[-2]) + 1 for i in range(1,n-1): if a[i+1] - a[i-1] > 1: t = b[i-1] + c[i+1] + 1 if r < t: r = t else: t = max(b[i-1], c[i+1]) + 1 if r < t: r = t return r print(main()) ```
6,178
Provide tags and a correct Python 3 solution for this coding contest problem. DZY has a sequence a, consisting of n integers. We'll call a sequence ai, ai + 1, ..., aj (1 ≀ i ≀ j ≀ n) a subsegment of the sequence a. The value (j - i + 1) denotes the length of the subsegment. Your task is to find the longest subsegment of a, such that it is possible to change at most one number (change one number to any integer you want) from the subsegment to make the subsegment strictly increasing. You only need to output the length of the subsegment you find. Input The first line contains integer n (1 ≀ n ≀ 105). The next line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109). Output In a single line print the answer to the problem β€” the maximum length of the required subsegment. Examples Input 6 7 2 3 1 5 6 Output 5 Note You can choose subsegment a2, a3, a4, a5, a6 and change its 3rd element (that is a4) to 4. Tags: dp, implementation, two pointers Correct Solution: ``` from heapq import heapify, heappush, heappop from collections import Counter, defaultdict, deque, OrderedDict from sys import setrecursionlimit, maxsize from bisect import bisect_left, bisect, insort_left, insort from math import ceil, log, factorial, hypot, pi from fractions import gcd from copy import deepcopy from functools import reduce from operator import mul from itertools import product, permutations, combinations, accumulate, cycle from string import ascii_uppercase, ascii_lowercase, ascii_letters, digits, hexdigits, octdigits prod = lambda l: reduce(mul, l) prodmod = lambda l, mod: reduce(lambda x, y: mul(x,y)%mod, l) def read_list(t): return [t(x) for x in input().split()] def read_line(t): return t(input()) def read_lines(t, N): return [t(input()) for _ in range(N)] N = read_line(int) array = read_list(int) i = 0 inc_subsegments = [] while i < N: start = i while i+1 < N and array[i] < array[i+1]: i += 1 if i != start: inc_subsegments.append((start, i)) i += 1 ans = max(min(2, N), max(min(end-start+1+1, N) for start, end in inc_subsegments) if inc_subsegments else 0) for i in range(len(inc_subsegments) - 1): i_last = inc_subsegments[i][1] i_next_first = inc_subsegments[i+1][0] if i_last + 1 == i_next_first and (array[i_next_first + 1] - array[i_last] > 1 or array[i_next_first] - array[i_last - 1] > 1): ans = max(ans, inc_subsegments[i+1][1] - inc_subsegments[i][0] + 1) print(ans) ```
6,179
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. DZY has a sequence a, consisting of n integers. We'll call a sequence ai, ai + 1, ..., aj (1 ≀ i ≀ j ≀ n) a subsegment of the sequence a. The value (j - i + 1) denotes the length of the subsegment. Your task is to find the longest subsegment of a, such that it is possible to change at most one number (change one number to any integer you want) from the subsegment to make the subsegment strictly increasing. You only need to output the length of the subsegment you find. Input The first line contains integer n (1 ≀ n ≀ 105). The next line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109). Output In a single line print the answer to the problem β€” the maximum length of the required subsegment. Examples Input 6 7 2 3 1 5 6 Output 5 Note You can choose subsegment a2, a3, a4, a5, a6 and change its 3rd element (that is a4) to 4. Submitted Solution: ``` n = int(input()) a = [int(x) for x in input().split()] res = [[0], []] cur = 1 for i in range(1, n): res[0].append(cur) if a[i-1] < a[i]: cur += 1 else: cur = 1 cur = 1 for i in range(n-2, -1, -1): res[1].append(cur) if a[i+1] > a[i]: cur += 1 else: cur = 1 res[1] = res[1][::-1] + [0] fin = max(max(res[1][0] + 1, res[0][-1] + 1), 2) #print(res) for i in range(1, n - 1): fin = max(fin, max(res[0][i] + 1, res[1][i] + 1)) if a[i - 1] + 1 < a[i + 1]: fin = max(fin, res[0][i] + res[1][i] + 1) print(min(n, fin)) ``` Yes
6,180
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. DZY has a sequence a, consisting of n integers. We'll call a sequence ai, ai + 1, ..., aj (1 ≀ i ≀ j ≀ n) a subsegment of the sequence a. The value (j - i + 1) denotes the length of the subsegment. Your task is to find the longest subsegment of a, such that it is possible to change at most one number (change one number to any integer you want) from the subsegment to make the subsegment strictly increasing. You only need to output the length of the subsegment you find. Input The first line contains integer n (1 ≀ n ≀ 105). The next line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109). Output In a single line print the answer to the problem β€” the maximum length of the required subsegment. Examples Input 6 7 2 3 1 5 6 Output 5 Note You can choose subsegment a2, a3, a4, a5, a6 and change its 3rd element (that is a4) to 4. Submitted Solution: ``` ###### ### ####### ####### ## # ##### ### ##### # # # # # # # # # # # # # ### # # # # # # # # # # # # # ### ###### ######### # # # # # # ######### # ###### ######### # # # # # # ######### # # # # # # # # # # # #### # # # # # # # # # # ## # # # # # ###### # # ####### ####### # # ##### # # # # from __future__ import print_function # for PyPy2 from collections import Counter, OrderedDict from itertools import permutations as perm from fractions import Fraction from collections import deque from sys import stdin from bisect import * from heapq import * # from math import * g = lambda : stdin.readline().strip() gl = lambda : g().split() gil = lambda : [int(var) for var in gl()] gfl = lambda : [float(var) for var in gl()] gcl = lambda : list(g()) gbs = lambda : [int(var) for var in g()] mod = int(1e9)+7 inf = float("inf") # range = xrange n, = gil() a = gil() ans = 1 l, r = [1]*n, [1]*n for i in range(1, n): if a[i] > a[i-1]: l[i] += l[i-1] ans = max(ans, l[i]+1) for i in reversed(range(n-1)): if a[i] < a[i+1]: r[i] += r[i+1] ans = max(ans, r[i]+1) ans = min(ans, n) # print(a) # print(l) for i in range(1, n-1): if a[i+1] - a[i-1] > 1: ans = max(ans, r[i+1] + l[i-1] + 1) print(ans) ``` Yes
6,181
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. DZY has a sequence a, consisting of n integers. We'll call a sequence ai, ai + 1, ..., aj (1 ≀ i ≀ j ≀ n) a subsegment of the sequence a. The value (j - i + 1) denotes the length of the subsegment. Your task is to find the longest subsegment of a, such that it is possible to change at most one number (change one number to any integer you want) from the subsegment to make the subsegment strictly increasing. You only need to output the length of the subsegment you find. Input The first line contains integer n (1 ≀ n ≀ 105). The next line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109). Output In a single line print the answer to the problem β€” the maximum length of the required subsegment. Examples Input 6 7 2 3 1 5 6 Output 5 Note You can choose subsegment a2, a3, a4, a5, a6 and change its 3rd element (that is a4) to 4. Submitted Solution: ``` import random n = int(input()) a = list(map(int, input().split())) ''' a = [] for i in range(10): a.append(random.randint(1, 10)) print(a) ''' inc = [] j = 0 for i in range(len(a)): if i != len(a)-1 and a[i] < a[i+1]: if j == 0: first = a[i] if j == 1: second = a[i] j += 1 else: if j == 1: second = a[i] if j == 0: inc.append((a[i], a[i], a[i], a[i], j+1)) else: inc.append((first, second, a[i-1], a[i], j+1)) j = 0 if(len(inc) == 1): print(inc[0][4]) exit() inc2 = [] for i in range(len(inc)-1): if inc[i][3] + 1 < inc[i+1][1]: inc2.append(inc[i][4] + inc[i+1][4]) if inc[i][2] + 1 < inc[i+1][0]: inc2.append(inc[i][4] + inc[i+1][4]) inc2.append(max(inc[i][4]+1, inc[i+1][4]+1)) print(max(inc2)) ``` Yes
6,182
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. DZY has a sequence a, consisting of n integers. We'll call a sequence ai, ai + 1, ..., aj (1 ≀ i ≀ j ≀ n) a subsegment of the sequence a. The value (j - i + 1) denotes the length of the subsegment. Your task is to find the longest subsegment of a, such that it is possible to change at most one number (change one number to any integer you want) from the subsegment to make the subsegment strictly increasing. You only need to output the length of the subsegment you find. Input The first line contains integer n (1 ≀ n ≀ 105). The next line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109). Output In a single line print the answer to the problem β€” the maximum length of the required subsegment. Examples Input 6 7 2 3 1 5 6 Output 5 Note You can choose subsegment a2, a3, a4, a5, a6 and change its 3rd element (that is a4) to 4. Submitted Solution: ``` import sys def inputArray(): tp=str(input()).split(); return list(map( int , tp)); if( __name__=="__main__"): n=int(input()); input=inputArray(); if(n==1): print("1"); sys.exit(); left=[1 for x in range(n)]; right=[1 for x in range(n) ]; for i in range(1,n,1): if( input[i-1] < input[i]): left[i]=left[i-1]+1; for i in range(n-2,-1,-1): if( input[i] < input[i+1]): right[i]=right[i+1]+1; ans=1; for i in range(n): if(i==0): #Make curr smaller than `right one ans=max(ans , right[i+1]+1); continue; if(i==n-1 ): ans=max(ans, left[i-1]+1); continue; ans=max(ans , right[i+1] +1 ); ans=max(ans ,left[i-1]+1); if( input[i+1]-input[i-1] >=2): ans=max(ans , left[i-1]+1+right[i+1]); print(ans); ``` Yes
6,183
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. DZY has a sequence a, consisting of n integers. We'll call a sequence ai, ai + 1, ..., aj (1 ≀ i ≀ j ≀ n) a subsegment of the sequence a. The value (j - i + 1) denotes the length of the subsegment. Your task is to find the longest subsegment of a, such that it is possible to change at most one number (change one number to any integer you want) from the subsegment to make the subsegment strictly increasing. You only need to output the length of the subsegment you find. Input The first line contains integer n (1 ≀ n ≀ 105). The next line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109). Output In a single line print the answer to the problem β€” the maximum length of the required subsegment. Examples Input 6 7 2 3 1 5 6 Output 5 Note You can choose subsegment a2, a3, a4, a5, a6 and change its 3rd element (that is a4) to 4. Submitted Solution: ``` n = int(input()) a = [int(x) for x in input().split()] res = [] cur = 1 for i in range(1, n): if a[i] > a[i-1]: cur += 1 elif cur != 1: res.append([i - cur, i - 1]) cur = 1 if cur != 1: res.append([n - cur, n - 1]) #print(res) if len(res) > 1: maxres = -1 for i in range(1, len(res)): if (res[i][0] - res[i-1][1] == 1) and (a[res[i-1][1]] + 1 < a[res[i][0] + 1]): maxres = max(maxres, res[i][1] - res[i-1][0] + 1) else: #print(a[res[i-1][1]], a[res[i][0] + 1]) maxres = max(maxres, max(res[i][1] - res[i][0] + 2, res[i-1][1] - res[i][0] + 2)) print(min(n, maxres)) elif len(res) == 1: print(min(res[0][1] - res[0][0] + 2, n)) else: print(min(n, 2)) ``` No
6,184
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. DZY has a sequence a, consisting of n integers. We'll call a sequence ai, ai + 1, ..., aj (1 ≀ i ≀ j ≀ n) a subsegment of the sequence a. The value (j - i + 1) denotes the length of the subsegment. Your task is to find the longest subsegment of a, such that it is possible to change at most one number (change one number to any integer you want) from the subsegment to make the subsegment strictly increasing. You only need to output the length of the subsegment you find. Input The first line contains integer n (1 ≀ n ≀ 105). The next line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109). Output In a single line print the answer to the problem β€” the maximum length of the required subsegment. Examples Input 6 7 2 3 1 5 6 Output 5 Note You can choose subsegment a2, a3, a4, a5, a6 and change its 3rd element (that is a4) to 4. Submitted Solution: ``` import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**10 mod = 998244353 dd = [(-1,0),(0,1),(1,0),(0,-1)] ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)] def LI(): return list(map(int, sys.stdin.readline().split())) def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines()] def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()] def LF(): return [float(x) for x in sys.stdin.readline().split()] def LS(): return sys.stdin.readline().split() def I(): return int(sys.stdin.readline()) def F(): return float(sys.stdin.readline()) def S(): return input() def pf(s): return print(s, flush=True) def pe(s): return print(str(s), file=sys.stderr) def JA(a, sep): return sep.join(map(str, a)) def JAA(a, s, t): return s.join(t.join(map(str, b)) for b in a) def main(): n = I() a = LI() b = [1] for i in range(1,n): if a[i-1] < a[i]: b.append(b[-1] + 1) else: b.append(1) c = [1] for i in range(n-2,-1,-1): if a[i+1] > a[i]: c.append(c[-1]+1) else: c.append(1) c = c[::-1] # print(b) # print(c) r = max(c[0], b[-1]) + 1 for i in range(1,n-1): if a[i+1] - a[i-1] > 1: t = b[i-1] + c[i+1] + 1 if r < t: r = t else: t = max(b[i-1], c[i+1]) + 1 if r < t: r = t return r print(main()) ``` No
6,185
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. DZY has a sequence a, consisting of n integers. We'll call a sequence ai, ai + 1, ..., aj (1 ≀ i ≀ j ≀ n) a subsegment of the sequence a. The value (j - i + 1) denotes the length of the subsegment. Your task is to find the longest subsegment of a, such that it is possible to change at most one number (change one number to any integer you want) from the subsegment to make the subsegment strictly increasing. You only need to output the length of the subsegment you find. Input The first line contains integer n (1 ≀ n ≀ 105). The next line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109). Output In a single line print the answer to the problem β€” the maximum length of the required subsegment. Examples Input 6 7 2 3 1 5 6 Output 5 Note You can choose subsegment a2, a3, a4, a5, a6 and change its 3rd element (that is a4) to 4. Submitted Solution: ``` n = int(input()) a = [int(x) for x in input().split()] res = [] cur = 1 for i in range(1, n): if a[i] > a[i-1]: cur += 1 elif cur != 1: res.append([i - cur, i - 1]) cur = 1 if cur != 1: res.append([n - cur, n - 1]) if len(res) > 1: maxres = -1 for i in range(1, len(res)): maxres = max(maxres, res[i][1] - res[i-1][0] + 1) print(maxres) elif len(res) == 1: print(min(res[0][1] - res[0][0] + 2, n)) else: print(min(n, 2)) ``` No
6,186
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. DZY has a sequence a, consisting of n integers. We'll call a sequence ai, ai + 1, ..., aj (1 ≀ i ≀ j ≀ n) a subsegment of the sequence a. The value (j - i + 1) denotes the length of the subsegment. Your task is to find the longest subsegment of a, such that it is possible to change at most one number (change one number to any integer you want) from the subsegment to make the subsegment strictly increasing. You only need to output the length of the subsegment you find. Input The first line contains integer n (1 ≀ n ≀ 105). The next line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109). Output In a single line print the answer to the problem β€” the maximum length of the required subsegment. Examples Input 6 7 2 3 1 5 6 Output 5 Note You can choose subsegment a2, a3, a4, a5, a6 and change its 3rd element (that is a4) to 4. Submitted Solution: ``` from heapq import heapify, heappush, heappop from collections import Counter, defaultdict, deque, OrderedDict from sys import setrecursionlimit, maxsize from bisect import bisect_left, bisect, insort_left, insort from math import ceil, log, factorial, hypot, pi from fractions import gcd from copy import deepcopy from functools import reduce from operator import mul from itertools import product, permutations, combinations, accumulate, cycle from string import ascii_uppercase, ascii_lowercase, ascii_letters, digits, hexdigits, octdigits prod = lambda l: reduce(mul, l) prodmod = lambda l, mod: reduce(lambda x, y: mul(x,y)%mod, l) def read_list(t): return [t(x) for x in input().split()] def read_line(t): return t(input()) def read_lines(t, N): return [t(input()) for _ in range(N)] N = read_line(int) array = read_list(int) i = 0 inc_subsegments = [] while i < N: start = i while i+1 < N and array[i] < array[i+1]: i += 1 if i != start: inc_subsegments.append((start, i)) i += 1 ans = max(min(2, N), max(min(end-start+1+1, N) for start, end in inc_subsegments) if inc_subsegments else 0) for i in range(len(inc_subsegments) - 1): i_last = inc_subsegments[i][1] i_next_first = inc_subsegments[i+1][0] if i_last + 1 == i_next_first and array[i_last] < array[i_next_first + 1]: ans = max(ans, inc_subsegments[i+1][1] - inc_subsegments[i][0] + 1) print(ans) ``` No
6,187
Provide tags and a correct Python 3 solution for this coding contest problem. Little X has n distinct integers: p1, p2, ..., pn. He wants to divide all of them into two sets A and B. The following two conditions must be satisfied: * If number x belongs to set A, then number a - x must also belong to set A. * If number x belongs to set B, then number b - x must also belong to set B. Help Little X divide the numbers into two sets or determine that it's impossible. Input The first line contains three space-separated integers n, a, b (1 ≀ n ≀ 105; 1 ≀ a, b ≀ 109). The next line contains n space-separated distinct integers p1, p2, ..., pn (1 ≀ pi ≀ 109). Output If there is a way to divide the numbers into two sets, then print "YES" in the first line. Then print n integers: b1, b2, ..., bn (bi equals either 0, or 1), describing the division. If bi equals to 0, then pi belongs to set A, otherwise it belongs to set B. If it's impossible, print "NO" (without the quotes). Examples Input 4 5 9 2 3 4 5 Output YES 0 0 1 1 Input 3 3 4 1 2 4 Output NO Note It's OK if all the numbers are in the same set, and the other one is empty. Tags: 2-sat, dfs and similar, dsu, graph matchings, greedy Correct Solution: ``` import sys from collections import defaultdict as dd input = sys.stdin.readline I = lambda : list(map(int,input().split())) n,a,b=I() l=I() dic=dd(int) for i in range(n): dic[l[i]]=1 bs=[] pa=dd(int) for i in range(n): if dic[a-l[i]]==0: bs.append(l[i]) else: pa[l[i]]=a-l[i] j=0 while j<len(bs): for i in range(j,len(bs)): cr=bs[i] dic[cr]=2 if dic[b-cr]==0: print("NO");exit() dic[b-cr]=2 if dic[a-b+cr]==1: dic[a-b+cr]=2 bs.append(a-b+cr) j+=1 #ct=0;vt=a-b+cr #while vt!=pa[pa[vt]]: # vt=pa[vt];dic[b-vt]=2 # dic[vt]=2 an=[0]*n for i in range(n): an[i]=dic[l[i]]-1 print("YES") print(*an) ```
6,188
Provide tags and a correct Python 3 solution for this coding contest problem. Little X has n distinct integers: p1, p2, ..., pn. He wants to divide all of them into two sets A and B. The following two conditions must be satisfied: * If number x belongs to set A, then number a - x must also belong to set A. * If number x belongs to set B, then number b - x must also belong to set B. Help Little X divide the numbers into two sets or determine that it's impossible. Input The first line contains three space-separated integers n, a, b (1 ≀ n ≀ 105; 1 ≀ a, b ≀ 109). The next line contains n space-separated distinct integers p1, p2, ..., pn (1 ≀ pi ≀ 109). Output If there is a way to divide the numbers into two sets, then print "YES" in the first line. Then print n integers: b1, b2, ..., bn (bi equals either 0, or 1), describing the division. If bi equals to 0, then pi belongs to set A, otherwise it belongs to set B. If it's impossible, print "NO" (without the quotes). Examples Input 4 5 9 2 3 4 5 Output YES 0 0 1 1 Input 3 3 4 1 2 4 Output NO Note It's OK if all the numbers are in the same set, and the other one is empty. Tags: 2-sat, dfs and similar, dsu, graph matchings, greedy Correct Solution: ``` class DisjointSet: def __init__(self, n): self._fa = list(range(n)) def union(self, x, y): x = self.get_father(x) y = self.get_father(y) self._fa[x] = y return y def get_father(self, x): y = self._fa[x] if self._fa[y] == y: return y else: z = self._fa[y] = self.get_father(y) return z def __repr__(self): return repr([self.get_father(i) for i in range(len(self._fa))]) def solve(n, a, b, xs): h = {x: i for i, x in enumerate(xs)} if a == b: if all(a - x in h for x in xs): return [0] * n return False g1 = n g2 = n + 1 ds = DisjointSet(n + 2) for i, x in enumerate(xs): for t in (a, b): if t - x in h: ds.union(i, h[t-x]) for i, x in enumerate(xs): b1 = (a - x) in h b2 = (b - x) in h if b1 + b2 == 0: return False if b1 + b2 == 1: if b1: ds.union(i, g1) else: ds.union(i, g2) if ds.get_father(g1) == ds.get_father(g2): return False group = [None] * n for i, x in enumerate(xs): f = ds.get_father(i) if f < n: return False group[i] = f - n return group n, a, b = map(int, input().split()) xs = list(map(int, input().split())) group = solve(n, a, b, xs) if isinstance(group, list): print('YES') print(' '.join(map(str, group))) else: print('NO') ```
6,189
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Little X has n distinct integers: p1, p2, ..., pn. He wants to divide all of them into two sets A and B. The following two conditions must be satisfied: * If number x belongs to set A, then number a - x must also belong to set A. * If number x belongs to set B, then number b - x must also belong to set B. Help Little X divide the numbers into two sets or determine that it's impossible. Input The first line contains three space-separated integers n, a, b (1 ≀ n ≀ 105; 1 ≀ a, b ≀ 109). The next line contains n space-separated distinct integers p1, p2, ..., pn (1 ≀ pi ≀ 109). Output If there is a way to divide the numbers into two sets, then print "YES" in the first line. Then print n integers: b1, b2, ..., bn (bi equals either 0, or 1), describing the division. If bi equals to 0, then pi belongs to set A, otherwise it belongs to set B. If it's impossible, print "NO" (without the quotes). Examples Input 4 5 9 2 3 4 5 Output YES 0 0 1 1 Input 3 3 4 1 2 4 Output NO Note It's OK if all the numbers are in the same set, and the other one is empty. Submitted Solution: ``` import sys input = sys.stdin.readline I = lambda : list(map(int,input().split())) n,a,b=I() l=I() st=set(l) an=[0]*n pos=1 for i in range(n): if (a-l[i]) in st: continue if (b-l[i]) in st: an[i]=1 continue pos=0;break if pos: print("YES") print(*an) else: print("NO") ``` No
6,190
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Little X has n distinct integers: p1, p2, ..., pn. He wants to divide all of them into two sets A and B. The following two conditions must be satisfied: * If number x belongs to set A, then number a - x must also belong to set A. * If number x belongs to set B, then number b - x must also belong to set B. Help Little X divide the numbers into two sets or determine that it's impossible. Input The first line contains three space-separated integers n, a, b (1 ≀ n ≀ 105; 1 ≀ a, b ≀ 109). The next line contains n space-separated distinct integers p1, p2, ..., pn (1 ≀ pi ≀ 109). Output If there is a way to divide the numbers into two sets, then print "YES" in the first line. Then print n integers: b1, b2, ..., bn (bi equals either 0, or 1), describing the division. If bi equals to 0, then pi belongs to set A, otherwise it belongs to set B. If it's impossible, print "NO" (without the quotes). Examples Input 4 5 9 2 3 4 5 Output YES 0 0 1 1 Input 3 3 4 1 2 4 Output NO Note It's OK if all the numbers are in the same set, and the other one is empty. Submitted Solution: ``` import sys input = sys.stdin.readline I = lambda : list(map(int,input().split())) n,a,b=I() l=I() st=set(l) an=[0]*n;ban=[1]*n pos=1 for i in range(n): pp=1 if (a-l[i]) in st: ban[i]=0 pp=0 if (b-l[i]) in st: an[i]=1 pp=0 if pp: pos=0;break if pos: dic={} for i in range(n): dic[l[i]]=i jk=0 for i in range(n): if an[i]==0 and an[dic[a-l[i]]]!=0: jk=1;break print("YES") if jk: print(*ban) else: print(*an) else: print("NO") ``` No
6,191
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Little X has n distinct integers: p1, p2, ..., pn. He wants to divide all of them into two sets A and B. The following two conditions must be satisfied: * If number x belongs to set A, then number a - x must also belong to set A. * If number x belongs to set B, then number b - x must also belong to set B. Help Little X divide the numbers into two sets or determine that it's impossible. Input The first line contains three space-separated integers n, a, b (1 ≀ n ≀ 105; 1 ≀ a, b ≀ 109). The next line contains n space-separated distinct integers p1, p2, ..., pn (1 ≀ pi ≀ 109). Output If there is a way to divide the numbers into two sets, then print "YES" in the first line. Then print n integers: b1, b2, ..., bn (bi equals either 0, or 1), describing the division. If bi equals to 0, then pi belongs to set A, otherwise it belongs to set B. If it's impossible, print "NO" (without the quotes). Examples Input 4 5 9 2 3 4 5 Output YES 0 0 1 1 Input 3 3 4 1 2 4 Output NO Note It's OK if all the numbers are in the same set, and the other one is empty. Submitted Solution: ``` import sys from collections import defaultdict as dd input = sys.stdin.readline I = lambda : list(map(int,input().split())) n,a,b=I() l=I() st=set(l) an=[0]*n pos=1;vis=dd(int) for i in range(n): if vis[l[i]]: an[i]=1;continue if (b-l[i]) in st: an[i]=1;vis[b-l[i]]=1 #print(l[i],b-l[i],l.index(b-l[i])) continue if (a-l[i]) in st: continue pos=0;break if pos: print("YES") print(*an) else: print("NO") ``` No
6,192
Provide tags and a correct Python 3 solution for this coding contest problem. Vova and Marina love offering puzzles to each other. Today Marina offered Vova to cope with the following task. Vova has a non-directed graph consisting of n vertices and m edges without loops and multiple edges. Let's define the operation of contraction two vertices a and b that are not connected by an edge. As a result of this operation vertices a and b are deleted and instead of them a new vertex x is added into the graph, and also edges are drawn from it to all vertices that were connected with a or with b (specifically, if the vertex was connected with both a and b, then also exactly one edge is added from x to it). Thus, as a result of contraction again a non-directed graph is formed, it contains no loops nor multiple edges, and it contains (n - 1) vertices. Vova must perform the contraction an arbitrary number of times to transform the given graph into a chain of the maximum length. A chain of length k (k β‰₯ 0) is a connected graph whose vertices can be numbered with integers from 1 to k + 1 so that the edges of the graph connect all pairs of vertices (i, i + 1) (1 ≀ i ≀ k) and only them. Specifically, the graph that consists of one vertex is a chain of length 0. The vertices that are formed as a result of the contraction are allowed to be used in the following operations of contraction. <image> The picture illustrates the contraction of two vertices marked by red. Help Vova cope with his girlfriend's task. Find the maximum length of the chain that can be obtained from the resulting graph or else determine that it is impossible to obtain the chain. Input The first line contains two integers n, m (1 ≀ n ≀ 1000, 0 ≀ m ≀ 100 000) β€” the number of vertices and the number of edges in the original graph. Next m lines contain the descriptions of edges in the format ai, bi (1 ≀ ai, bi ≀ n, ai β‰  bi), which means that there is an edge between vertices ai and bi. It is guaranteed that there is at most one edge between each pair of vertexes. Output If it is impossible to obtain a chain from the given graph, print - 1. Otherwise, print the maximum possible number of edges in the resulting chain. Examples Input 5 4 1 2 2 3 3 4 3 5 Output 3 Input 4 6 1 2 2 3 1 3 3 4 2 4 1 4 Output -1 Input 4 2 1 3 2 4 Output 2 Note In the first sample test you can contract vertices 4 and 5 and obtain a chain of length 3. In the second sample test it is initially impossible to contract any pair of vertexes, so it is impossible to achieve the desired result. In the third sample test you can contract vertices 1 and 2 and obtain a chain of length 2. Tags: graphs, shortest paths Correct Solution: ``` # lista doble enlazada o(1) operaciones en los bordes es mejor que si se implementa en el propio lenguaje from collections import deque def solve(): n, m = input().split() n = int(n) m = int(m) global maxValue maxValue = n*2 graph = [[] for _ in range(0, n)] edges = [] diameters = [] for _ in range(0, m): u, v = input().split() u = int(u)-1 v = int(v)-1 edges.append(v) graph[u].append(v) graph[v].append(u) distance = [maxValue]*n cc = [maxValue]*n for i in range(0, n): if distance[i] == maxValue: cc = bfs_2k(graph, i, distance) if(cc == None): print(-1) return diameters.append(distance[cc[-1]]) for v in range(1, len(cc)): newDistance = [maxValue]*n samecc = bfs_2k(graph, cc[v], newDistance) diameters[-1] = max(diameters[-1], newDistance[samecc[-1]]) print(sum(diameters)) def bfs_2k(graph, initVertex, dist): queue = [] qlen = 1 queue.append(initVertex) dist[initVertex] = 0 u = None i = 0 while qlen: u = queue[i] qlen-=1 for v in graph[u]: if(dist[v] == maxValue): dist[v] = dist[u] + 1 queue.append(v) qlen+=1 if (dist[u] - dist[v]) % 2 == 0: return None i+=1 return queue solve() ```
6,193
Provide tags and a correct Python 3 solution for this coding contest problem. Vova and Marina love offering puzzles to each other. Today Marina offered Vova to cope with the following task. Vova has a non-directed graph consisting of n vertices and m edges without loops and multiple edges. Let's define the operation of contraction two vertices a and b that are not connected by an edge. As a result of this operation vertices a and b are deleted and instead of them a new vertex x is added into the graph, and also edges are drawn from it to all vertices that were connected with a or with b (specifically, if the vertex was connected with both a and b, then also exactly one edge is added from x to it). Thus, as a result of contraction again a non-directed graph is formed, it contains no loops nor multiple edges, and it contains (n - 1) vertices. Vova must perform the contraction an arbitrary number of times to transform the given graph into a chain of the maximum length. A chain of length k (k β‰₯ 0) is a connected graph whose vertices can be numbered with integers from 1 to k + 1 so that the edges of the graph connect all pairs of vertices (i, i + 1) (1 ≀ i ≀ k) and only them. Specifically, the graph that consists of one vertex is a chain of length 0. The vertices that are formed as a result of the contraction are allowed to be used in the following operations of contraction. <image> The picture illustrates the contraction of two vertices marked by red. Help Vova cope with his girlfriend's task. Find the maximum length of the chain that can be obtained from the resulting graph or else determine that it is impossible to obtain the chain. Input The first line contains two integers n, m (1 ≀ n ≀ 1000, 0 ≀ m ≀ 100 000) β€” the number of vertices and the number of edges in the original graph. Next m lines contain the descriptions of edges in the format ai, bi (1 ≀ ai, bi ≀ n, ai β‰  bi), which means that there is an edge between vertices ai and bi. It is guaranteed that there is at most one edge between each pair of vertexes. Output If it is impossible to obtain a chain from the given graph, print - 1. Otherwise, print the maximum possible number of edges in the resulting chain. Examples Input 5 4 1 2 2 3 3 4 3 5 Output 3 Input 4 6 1 2 2 3 1 3 3 4 2 4 1 4 Output -1 Input 4 2 1 3 2 4 Output 2 Note In the first sample test you can contract vertices 4 and 5 and obtain a chain of length 3. In the second sample test it is initially impossible to contract any pair of vertexes, so it is impossible to achieve the desired result. In the third sample test you can contract vertices 1 and 2 and obtain a chain of length 2. Tags: graphs, shortest paths Correct Solution: ``` # lista doble enlazada o(1) operaciones en los bordes es mejor que si se implementa en el propio lenguaje from collections import deque def solve(): global n, m n, m = map(lambda x: int(x), input().split()) global maxVal maxVal = n**2 graph = [[] for _ in range(0, n)] for _ in range(0, m): u, v = map(lambda x: int(x)-1, input().split()) graph[u].append(v) graph[v].append(u) ccNum = 0 cc = [0]*n # pueden ser a lo sumo vertices aislados innrCc = [0]*n dmtrs = [0]*n distance = [maxVal]*n for i in range(0, n): if distance[i] == maxVal: ccLen = bfs_2k(graph, i, distance, cc) if(ccLen is None): print(-1) return dmtrs[ccNum] = distance[cc[ccLen-1]] for v in range(0, ccLen): innrDst = [maxVal]*n bfs_2k(graph, cc[v], innrDst, innrCc) dmtrs[ccNum] = max(dmtrs[ccNum], innrDst[innrCc[ccLen-1]]) ccNum += 1 print(sum(dmtrs)) def bfs_2k(graph, s, dist, cc): queue = deque() queue.append(s) dist[s] = 0 ccLen = 0 while queue: u = queue.popleft() for v in graph[u]: if(dist[v] == maxVal): dist[v] = dist[u] + 1 queue.append(v) cc[ccLen] = v ccLen += 1 elif (dist[u] - dist[v]) % 2 == 0: return None return ccLen solve() ```
6,194
Provide tags and a correct Python 3 solution for this coding contest problem. Vova and Marina love offering puzzles to each other. Today Marina offered Vova to cope with the following task. Vova has a non-directed graph consisting of n vertices and m edges without loops and multiple edges. Let's define the operation of contraction two vertices a and b that are not connected by an edge. As a result of this operation vertices a and b are deleted and instead of them a new vertex x is added into the graph, and also edges are drawn from it to all vertices that were connected with a or with b (specifically, if the vertex was connected with both a and b, then also exactly one edge is added from x to it). Thus, as a result of contraction again a non-directed graph is formed, it contains no loops nor multiple edges, and it contains (n - 1) vertices. Vova must perform the contraction an arbitrary number of times to transform the given graph into a chain of the maximum length. A chain of length k (k β‰₯ 0) is a connected graph whose vertices can be numbered with integers from 1 to k + 1 so that the edges of the graph connect all pairs of vertices (i, i + 1) (1 ≀ i ≀ k) and only them. Specifically, the graph that consists of one vertex is a chain of length 0. The vertices that are formed as a result of the contraction are allowed to be used in the following operations of contraction. <image> The picture illustrates the contraction of two vertices marked by red. Help Vova cope with his girlfriend's task. Find the maximum length of the chain that can be obtained from the resulting graph or else determine that it is impossible to obtain the chain. Input The first line contains two integers n, m (1 ≀ n ≀ 1000, 0 ≀ m ≀ 100 000) β€” the number of vertices and the number of edges in the original graph. Next m lines contain the descriptions of edges in the format ai, bi (1 ≀ ai, bi ≀ n, ai β‰  bi), which means that there is an edge between vertices ai and bi. It is guaranteed that there is at most one edge between each pair of vertexes. Output If it is impossible to obtain a chain from the given graph, print - 1. Otherwise, print the maximum possible number of edges in the resulting chain. Examples Input 5 4 1 2 2 3 3 4 3 5 Output 3 Input 4 6 1 2 2 3 1 3 3 4 2 4 1 4 Output -1 Input 4 2 1 3 2 4 Output 2 Note In the first sample test you can contract vertices 4 and 5 and obtain a chain of length 3. In the second sample test it is initially impossible to contract any pair of vertexes, so it is impossible to achieve the desired result. In the third sample test you can contract vertices 1 and 2 and obtain a chain of length 2. Tags: graphs, shortest paths Correct Solution: ``` def solve(): n, m = input().split() n = int(n) m = int(m) global maxValue maxValue = n*2 graph = [[] for _ in range(0, n)] edges = [] diameters = [] for _ in range(0, m): u, v = input().split() u = int(u)-1 v = int(v)-1 edges.append(v) graph[u].append(v) graph[v].append(u) distance = [maxValue]*n queueCc = [0]*n queue = [0]*n for i in range(0, n): if distance[i] == maxValue: qlen = bfs_2k(graph, i, distance, queueCc) if(qlen == None): print(-1) return diameters.append(distance[queueCc[qlen-1]] if qlen > 0 else 0) for v in range(1, qlen): newDistance = [maxValue]*n bfs_2k(graph, queueCc[v], newDistance, queue) diameters[-1] = max(diameters[-1], newDistance[queue[qlen-1]]) print(sum(diameters)) def bfs_2k(graph, initVertex, dist, queue): dist[initVertex] = 0 queue[0] = initVertex qlen = qcount = 1 i = 0 while qcount: u = queue[i] qcount -= 1 i += 1 for v in graph[u]: if(dist[v] == maxValue): dist[v] = dist[u] + 1 queue[qlen] = v qlen += 1 qcount+=1 if (dist[u] - dist[v]) % 2 == 0: return None return qlen solve() ```
6,195
Provide tags and a correct Python 3 solution for this coding contest problem. Vova and Marina love offering puzzles to each other. Today Marina offered Vova to cope with the following task. Vova has a non-directed graph consisting of n vertices and m edges without loops and multiple edges. Let's define the operation of contraction two vertices a and b that are not connected by an edge. As a result of this operation vertices a and b are deleted and instead of them a new vertex x is added into the graph, and also edges are drawn from it to all vertices that were connected with a or with b (specifically, if the vertex was connected with both a and b, then also exactly one edge is added from x to it). Thus, as a result of contraction again a non-directed graph is formed, it contains no loops nor multiple edges, and it contains (n - 1) vertices. Vova must perform the contraction an arbitrary number of times to transform the given graph into a chain of the maximum length. A chain of length k (k β‰₯ 0) is a connected graph whose vertices can be numbered with integers from 1 to k + 1 so that the edges of the graph connect all pairs of vertices (i, i + 1) (1 ≀ i ≀ k) and only them. Specifically, the graph that consists of one vertex is a chain of length 0. The vertices that are formed as a result of the contraction are allowed to be used in the following operations of contraction. <image> The picture illustrates the contraction of two vertices marked by red. Help Vova cope with his girlfriend's task. Find the maximum length of the chain that can be obtained from the resulting graph or else determine that it is impossible to obtain the chain. Input The first line contains two integers n, m (1 ≀ n ≀ 1000, 0 ≀ m ≀ 100 000) β€” the number of vertices and the number of edges in the original graph. Next m lines contain the descriptions of edges in the format ai, bi (1 ≀ ai, bi ≀ n, ai β‰  bi), which means that there is an edge between vertices ai and bi. It is guaranteed that there is at most one edge between each pair of vertexes. Output If it is impossible to obtain a chain from the given graph, print - 1. Otherwise, print the maximum possible number of edges in the resulting chain. Examples Input 5 4 1 2 2 3 3 4 3 5 Output 3 Input 4 6 1 2 2 3 1 3 3 4 2 4 1 4 Output -1 Input 4 2 1 3 2 4 Output 2 Note In the first sample test you can contract vertices 4 and 5 and obtain a chain of length 3. In the second sample test it is initially impossible to contract any pair of vertexes, so it is impossible to achieve the desired result. In the third sample test you can contract vertices 1 and 2 and obtain a chain of length 2. Tags: graphs, shortest paths Correct Solution: ``` n, m = map(int, input().split()) g = [[] for _ in range(n)] for i in range(m): p, q = map(int, input().split()) g[p - 1].append(q - 1) g[q - 1].append(p - 1) comp = [-1] * n def shortest(root): dist = [-1] * n q = [0] * n left, right = 0, 1 q[left] = root dist[root] = 0 good = True while left < right: x = q[left] left = left + 1 for i in g[x]: if dist[i] is -1: dist[i] = 1 + dist[x] q[right] = i right = right + 1 elif dist[i] == dist[x]: good = False far = 0 for i in dist: if far < i: far = i return good, far, dist arr = [0] * n good = True for i in range(n): _, opt, dist = shortest(i) if _ is False: good = False if comp[i] is -1: for j in range(n): if dist[j] is not -1: comp[j] = i if arr[comp[i]] < opt: arr[comp[i]] = opt if good is False: print('-1') else: print(sum(arr)) ```
6,196
Provide tags and a correct Python 3 solution for this coding contest problem. Vova and Marina love offering puzzles to each other. Today Marina offered Vova to cope with the following task. Vova has a non-directed graph consisting of n vertices and m edges without loops and multiple edges. Let's define the operation of contraction two vertices a and b that are not connected by an edge. As a result of this operation vertices a and b are deleted and instead of them a new vertex x is added into the graph, and also edges are drawn from it to all vertices that were connected with a or with b (specifically, if the vertex was connected with both a and b, then also exactly one edge is added from x to it). Thus, as a result of contraction again a non-directed graph is formed, it contains no loops nor multiple edges, and it contains (n - 1) vertices. Vova must perform the contraction an arbitrary number of times to transform the given graph into a chain of the maximum length. A chain of length k (k β‰₯ 0) is a connected graph whose vertices can be numbered with integers from 1 to k + 1 so that the edges of the graph connect all pairs of vertices (i, i + 1) (1 ≀ i ≀ k) and only them. Specifically, the graph that consists of one vertex is a chain of length 0. The vertices that are formed as a result of the contraction are allowed to be used in the following operations of contraction. <image> The picture illustrates the contraction of two vertices marked by red. Help Vova cope with his girlfriend's task. Find the maximum length of the chain that can be obtained from the resulting graph or else determine that it is impossible to obtain the chain. Input The first line contains two integers n, m (1 ≀ n ≀ 1000, 0 ≀ m ≀ 100 000) β€” the number of vertices and the number of edges in the original graph. Next m lines contain the descriptions of edges in the format ai, bi (1 ≀ ai, bi ≀ n, ai β‰  bi), which means that there is an edge between vertices ai and bi. It is guaranteed that there is at most one edge between each pair of vertexes. Output If it is impossible to obtain a chain from the given graph, print - 1. Otherwise, print the maximum possible number of edges in the resulting chain. Examples Input 5 4 1 2 2 3 3 4 3 5 Output 3 Input 4 6 1 2 2 3 1 3 3 4 2 4 1 4 Output -1 Input 4 2 1 3 2 4 Output 2 Note In the first sample test you can contract vertices 4 and 5 and obtain a chain of length 3. In the second sample test it is initially impossible to contract any pair of vertexes, so it is impossible to achieve the desired result. In the third sample test you can contract vertices 1 and 2 and obtain a chain of length 2. Tags: graphs, shortest paths Correct Solution: ``` # lista doble enlazada o(1) operaciones en los bordes es mejor que si se implementa en el propio lenguaje from collections import deque def solve(): n, m = input().split() n = int(n) m = int(m) global maxValue maxValue = n*2 graph = [[] for _ in range(0, n)] for _ in range(0, m): u, v = input().split() u = int(u)-1 v = int(v)-1 graph[u].append(v) graph[v].append(u) diameters = [0]*n ccNum =0 distance = [maxValue]*n cc = [0]*n # los a lo sumo n-1 vertices en la misma componente conexa de i # los a lo sumo n-1 vertices en la misma componente conexa de i en distinto orden innerCc = [0]*n for i in range(0, n): if distance[i] == maxValue: ccLen = bfs_2k(graph, i, distance, cc) if(ccLen == None): print(-1) return diameters[ccNum]=distance[cc[ccLen-1]] for v in range(0, ccLen): innerDist = [maxValue]*n bfs_2k(graph, cc[v], innerDist, innerCc) diameters[ccNum] = max(diameters[ccNum], innerDist[innerCc[ccLen-1]]) ccNum+=1 print(sum(diameters)) def bfs_2k(graph, initVertex, dist, cc): queue = deque() queue.append(initVertex) dist[initVertex] = 0 ccLen = 0 while queue: u = queue.popleft() for v in graph[u]: if(dist[v] == maxValue): dist[v] = dist[u] + 1 queue.append(v) cc[ccLen] = v ccLen += 1 if (dist[u] - dist[v]) % 2 == 0: return None return ccLen solve() ```
6,197
Provide tags and a correct Python 3 solution for this coding contest problem. Vova and Marina love offering puzzles to each other. Today Marina offered Vova to cope with the following task. Vova has a non-directed graph consisting of n vertices and m edges without loops and multiple edges. Let's define the operation of contraction two vertices a and b that are not connected by an edge. As a result of this operation vertices a and b are deleted and instead of them a new vertex x is added into the graph, and also edges are drawn from it to all vertices that were connected with a or with b (specifically, if the vertex was connected with both a and b, then also exactly one edge is added from x to it). Thus, as a result of contraction again a non-directed graph is formed, it contains no loops nor multiple edges, and it contains (n - 1) vertices. Vova must perform the contraction an arbitrary number of times to transform the given graph into a chain of the maximum length. A chain of length k (k β‰₯ 0) is a connected graph whose vertices can be numbered with integers from 1 to k + 1 so that the edges of the graph connect all pairs of vertices (i, i + 1) (1 ≀ i ≀ k) and only them. Specifically, the graph that consists of one vertex is a chain of length 0. The vertices that are formed as a result of the contraction are allowed to be used in the following operations of contraction. <image> The picture illustrates the contraction of two vertices marked by red. Help Vova cope with his girlfriend's task. Find the maximum length of the chain that can be obtained from the resulting graph or else determine that it is impossible to obtain the chain. Input The first line contains two integers n, m (1 ≀ n ≀ 1000, 0 ≀ m ≀ 100 000) β€” the number of vertices and the number of edges in the original graph. Next m lines contain the descriptions of edges in the format ai, bi (1 ≀ ai, bi ≀ n, ai β‰  bi), which means that there is an edge between vertices ai and bi. It is guaranteed that there is at most one edge between each pair of vertexes. Output If it is impossible to obtain a chain from the given graph, print - 1. Otherwise, print the maximum possible number of edges in the resulting chain. Examples Input 5 4 1 2 2 3 3 4 3 5 Output 3 Input 4 6 1 2 2 3 1 3 3 4 2 4 1 4 Output -1 Input 4 2 1 3 2 4 Output 2 Note In the first sample test you can contract vertices 4 and 5 and obtain a chain of length 3. In the second sample test it is initially impossible to contract any pair of vertexes, so it is impossible to achieve the desired result. In the third sample test you can contract vertices 1 and 2 and obtain a chain of length 2. Tags: graphs, shortest paths Correct Solution: ``` # lista doble enlazada o(1) operaciones en los bordes es mejor que si se implementa en el propio lenguaje from collections import deque def solve(): n, m = input().split() n = int(n) m = int(m) global maxValue maxValue = n*2 graph = [[] for _ in range(0, n)] for _ in range(0, m): u, v = input().split() u = int(u)-1 v = int(v)-1 graph[u].append(v) graph[v].append(u) diameters = [] distance = [maxValue]*n cc = [0]*n # los a lo sumo n-1 vertices en la misma componente conexa de i innerCc = [0]*n # los a lo sumo n-1 vertices en la misma componente conexa de i en distinto orden for i in range(0, n): if distance[i] == maxValue: ccLen = bfs_2k(graph, i, distance,cc) if(ccLen==None): print(-1) return diameters.append(distance[cc[ccLen-1]] if ccLen > 0 else 0) for v in range(0,ccLen): innerDist = [maxValue]*n bfs_2k(graph, cc[v], innerDist,innerCc) diameters[-1] = max(diameters[-1], innerDist[innerCc[ccLen-1]]) print(sum(diameters)) def bfs_2k(graph, initVertex, dist,cc): queue = deque() queue.append(initVertex) dist[initVertex] = 0 ccLen = 0 while queue: u = queue.popleft() for v in graph[u]: if(dist[v] == maxValue): dist[v] = dist[u] + 1 queue.append(v) cc[ccLen]=v ccLen+=1 if (dist[u] - dist[v]) % 2 == 0: return None return ccLen solve() ```
6,198
Provide tags and a correct Python 3 solution for this coding contest problem. Vova and Marina love offering puzzles to each other. Today Marina offered Vova to cope with the following task. Vova has a non-directed graph consisting of n vertices and m edges without loops and multiple edges. Let's define the operation of contraction two vertices a and b that are not connected by an edge. As a result of this operation vertices a and b are deleted and instead of them a new vertex x is added into the graph, and also edges are drawn from it to all vertices that were connected with a or with b (specifically, if the vertex was connected with both a and b, then also exactly one edge is added from x to it). Thus, as a result of contraction again a non-directed graph is formed, it contains no loops nor multiple edges, and it contains (n - 1) vertices. Vova must perform the contraction an arbitrary number of times to transform the given graph into a chain of the maximum length. A chain of length k (k β‰₯ 0) is a connected graph whose vertices can be numbered with integers from 1 to k + 1 so that the edges of the graph connect all pairs of vertices (i, i + 1) (1 ≀ i ≀ k) and only them. Specifically, the graph that consists of one vertex is a chain of length 0. The vertices that are formed as a result of the contraction are allowed to be used in the following operations of contraction. <image> The picture illustrates the contraction of two vertices marked by red. Help Vova cope with his girlfriend's task. Find the maximum length of the chain that can be obtained from the resulting graph or else determine that it is impossible to obtain the chain. Input The first line contains two integers n, m (1 ≀ n ≀ 1000, 0 ≀ m ≀ 100 000) β€” the number of vertices and the number of edges in the original graph. Next m lines contain the descriptions of edges in the format ai, bi (1 ≀ ai, bi ≀ n, ai β‰  bi), which means that there is an edge between vertices ai and bi. It is guaranteed that there is at most one edge between each pair of vertexes. Output If it is impossible to obtain a chain from the given graph, print - 1. Otherwise, print the maximum possible number of edges in the resulting chain. Examples Input 5 4 1 2 2 3 3 4 3 5 Output 3 Input 4 6 1 2 2 3 1 3 3 4 2 4 1 4 Output -1 Input 4 2 1 3 2 4 Output 2 Note In the first sample test you can contract vertices 4 and 5 and obtain a chain of length 3. In the second sample test it is initially impossible to contract any pair of vertexes, so it is impossible to achieve the desired result. In the third sample test you can contract vertices 1 and 2 and obtain a chain of length 2. Tags: graphs, shortest paths Correct Solution: ``` from collections import deque def solve(): global n, m n, m = map(lambda x: int(x), input().split()) global maxVal maxVal = n**2 graph = [[] for _ in range(0, n)] for _ in range(0, m): u, v = map(lambda x: int(x)-1, input().split()) graph[u].append(v) graph[v].append(u) ccNum = 0 cc = [0]*n # pueden ser a lo sumo vertices aislados innrCc = [0]*n dmtrs = [0]*n distance = [maxVal]*n for i in range(0, n): if distance[i] == maxVal: ccLen = bfs_2k(graph, i, distance, cc) if(ccLen is None): print(-1) return dmtrs[ccNum] = distance[cc[ccLen-1]] for v in range(0, ccLen): innrDst = [maxVal]*n bfs_2k(graph, cc[v], innrDst, innrCc) dmtrs[ccNum] = max(dmtrs[ccNum], innrDst[innrCc[ccLen-1]]) ccNum += 1 print(sum(dmtrs)) def bfs_2k(graph, s, dist, cc): queue = deque() queue.append(s) dist[s] = 0 ccLen = 0 while queue: u = queue.popleft() for v in graph[u]: if(dist[v] == maxVal): dist[v] = dist[u] + 1 queue.append(v) cc[ccLen] = v ccLen += 1 elif (dist[u] - dist[v]) % 2 == 0: return None return ccLen solve() ```
6,199