Skip to content

7 综合练习精选 16题

sy884: 统计一下 入门

https://sunnywhy.com/sfbj/3/7/884

给定一个区间 [L,R],其中 L 和 R 为正整数。你的任务是计算这个区间内所有整数的十进制表示中出现的数字 1 的总次数。

输入描述

输入包含两个整数 L 和 R(1LR10000),分别表示区间的左右端点。

输出描述

输出一个整数,表示区间 [L,R] 中所有整数的十进制表示中数字 出现的总次数。

样例1

输入

1 11

输出

4

解释

在区间 [1,11]中,数字 1、10、11 中的 1、10分别出现了 1 次,数字 11中的 1出现了 2 次,因此总共出现了 4 次 。

python
def count_ones_in_range(L, R):
    count = 0
    for num in range(L, R + 1):
        count += str(num).count('1')
    return count

if __name__ == "__main__":
    L, R = map(int, input().strip().split())
    result = count_ones_in_range(L, R)
    print(result)

sy569: 双向喜欢 入门

https://sunnywhy.com/sfbj/3/7/569

给定n个人的q组喜欢关系,问是否有双向喜欢的情况存在。

输入描述

第一行为两行数字n,q。

后面q行,每行两个数字x,y,表示x喜欢y,注意这里是单向喜欢。

$1 \le n \le 10 $

1q10

1x,yn

xy

输出描述

如果有双向喜欢的情况则输出Yes,否则输出No

样例1

输入

3 3
1 2
2 1
1 3

输出

Yes

样例2

输入

3 3
1 2
2 3
3 1

输出

No
python
# 周嘉豪24工学院
n,q=map(int,input().split())
Like=[]
for _ in range(q):
    x,y=input().split()
    Like.append(x+y)
    Like.append(y+x)
like=set(Like)
if len(like)==len(Like):
    print('No')
else:
    print('Yes')
python
def has_mutual_likes(n, q, likes):
    like_set = set()
    for x, y in likes:
        if (y, x) in like_set:
            return "Yes"
        like_set.add((x, y))
    return "No"

if __name__ == "__main__":
    n, q = map(int, input().strip().split())
    likes = [tuple(map(int, input().strip().split())) for _ in range(q)]
    result = has_mutual_likes(n, q, likes)
    print(result)

sy570: 三方欢喜 简单

https://sunnywhy.com/sfbj/3/7/570

给定n个人的q组喜欢关系,问是否有三方欢喜的情况存在,即a喜欢b ,b喜欢c,还有c也喜欢a。

输入描述

第一行为两行数字n,q。

后面q行,每行两个数字x,y,表示x喜欢y,注意这里是单向喜欢。

$1 \le n \le 10 $

1q10

1x,yn

xy

输出描述

如果有三方欢喜的情况则输出Yes,否则输出No

样例1

输入

3 3
1 2
2 1
1 3

输出

No

样例2

输入

3 3
1 2
2 3
3 1

输出

Yes

初始化一个字典用于存储喜欢关系。 遍历 q 行输入,记录每个喜欢关系。 检查是否存在三方欢喜的情况,即 a 喜欢 b,b 喜欢 c,c 喜欢 a。

python
def has_three_way_likes(n, q, likes):
    like_dict = {}
    for x, y in likes:
        if x not in like_dict:
            like_dict[x] = set()
        like_dict[x].add(y)
    
    for a in like_dict:
        for b in like_dict[a]:
            if b in like_dict:
                for c in like_dict[b]:
                    if c in like_dict and a in like_dict[c]:
                        return "Yes"
    return "No"

if __name__ == "__main__":
    n, q = map(int, input().strip().split())
    likes = [tuple(map(int, input().strip().split())) for _ in range(q)]
    result = has_three_way_likes(n, q, likes)
    print(result)

sy571: 四方坐标 入门

https://sunnywhy.com/sfbj/3/7/571

给定一个矩形在直角坐标系xOy上的两个对顶点的坐标,求这个矩形的面积。

假设矩形的所有边均平行于x轴或y轴。

输入描述

两行,每行为一个整数坐标x,y,分别表示两个对顶点的坐标。

数据范围:

100x,y100

输出描述

一个整数,这个矩形的面积。数据保证矩形的面积不会为0。

样例1

输入

1 1
2 3

输出

2

解释

左下角坐标为(1,1),右上角坐标为(2,3),该矩形的面积是2

python
x1, y1 = map(int, input().split())
x2, y2 = map(int, input().split())
print(abs(x1 - x2) * abs(y1 - y2))

sy572: 五次求导 简单

https://sunnywhy.com/sfbj/3/7/572

给定一个多项式函数:

f(x)=a0xb0+a1xb1++an2xbn2+an1xbn1

对这个f(x)求五阶导函数f′′′′′(x)

问这个五阶导函数最后的表达式是什么。

输入描述

第一行为n。

第二行到n+1行为都为整数ai,bi表示这个有一项。

其中

1n10

10a10

1b10

输出描述

输出求导后的多项式,每一行两个整数,按照的次数从高到低输出他的系数和次数。

如果f′′′′′(x)=0则输出0 0

如果是有非零常数项,比如f′′′′′(x)=(aixbi)+C,则在最后一行输出C 0

样例1

输入

2
1 5
1 4

输出

120 0

解释

f(x)=x5+x4

那么有

f′′′′′(x)=120

python
def compute_kth_derivative(a, b, k):
    if b < k:
        return 0, 0
    coefficient = a
    exponent = b
    for i in range(k):
        coefficient *= exponent
        exponent -= 1
    return coefficient, exponent

if __name__ == "__main__":
    import sys
    input = sys.stdin.read
    data = input().strip().split()

    n = int(data[0])
    terms = [(int(data[i*2+1]), int(data[i*2+2])) for i in range(n)]

    k = 5
    result = {}
    for a, b in terms:
        coeff, exp = compute_kth_derivative(a, b, k)
        if coeff != 0:
            if exp in result:
                result[exp] += coeff
            else:
                result[exp] = coeff

    if not result:
        print("0 0")
    else:
        sorted_result = sorted(result.items(), key=lambda x: -x[0])
        for exp, coeff in sorted_result:
            if coeff == 0:
                continue
            print(coeff, exp)

sy573: 六小时差 入门

https://sunnywhy.com/sfbj/3/7/573

给定一个24小时制时间,包括小时和分钟,问六小时x分钟后,时间是多少。

如果时间跨天了,则按照跨天后的时间算。

输入描述

第一行,一个整数数字x。

第二行,两个数字,表示当天的时间,分别是小时h和分钟m。数据保证数据合法。

0x59

0h23

0m59

输出描述

6小时x分钟后的时间。

样例1

输入

6
0 0

输出

6 6

样例2

输入

1
23 59

输出

6 0
python
if __name__ == "__main__":
    import sys
    input = sys.stdin.read
    data = input().strip().split()

    x = int(data[0])
    h = int(data[1])
    m = int(data[2])

    # Add 6 hours and x minutes
    new_h = h + 6
    new_m = m + x

    # Handle minute overflow
    if new_m >= 60:
        new_h += new_m // 60
        new_m = new_m % 60

    # Handle hour overflow
    if new_h >= 24:
        new_h = new_h % 24

    print(new_h, new_m)

sy574: 周七迷踪 简单

https://sunnywhy.com/sfbj/3/7/574

给定年月日,问下一个周日是什么时候。

如果给定时间本身是周日,则输出当天时间。

输入描述

一行,3个数字,分别表示年月日,其中年月日保证数据合法,为2000年到2099年的某一天。

输出描述

下一个周天的时间,3个数字,分别是年月日。

样例1

输入

2000 1 1

输出

2000 1 2

解释

2000年的1月1号是周六。 那么2000年的1月2号是周日。

python
import datetime

if __name__ == "__main__":
    import sys
    input = sys.stdin.read
    data = input().strip().split()

    year = int(data[0])
    month = int(data[1])
    day = int(data[2])

    given_date = datetime.date(year, month, day)
    day_of_week = given_date.weekday()  # Monday is 0 and Sunday is 6

    # Calculate days to add to reach next Sunday
    days_to_add = (6 - day_of_week) % 7

    next_sunday = given_date + datetime.timedelta(days=days_to_add)

    print(next_sunday.year, next_sunday.month, next_sunday.day)

sy575: 八次翻转 入门

https://sunnywhy.com/sfbj/3/7/575

给定一个字符串S,下标从0开始,按照顺序对这个字符串进行如下操作8次,操作为对字符串下标区间[Li,Ri)的元素进行一次翻转(即字符串逆置)。

输出的最终状态。

输入描述

第一行是一个字符串S

第2到9行为Li,Ri,表示一次操作的下标区间。

1len(S)1000

0Li<Rilen(S)

输出描述

八次翻转之后最终的S

样例1

输入

ab
0 2
0 2
0 2
0 2
0 2
0 2
0 2
0 2

输出

ab
python
def reverse_substring(s, l, r):
    return s[:l] + s[l:r][::-1] + s[r:]

def main():
    import sys
    input = sys.stdin.read
    data = input().strip().split('\n')
    
    s = data[0]
    for i in range(1, 9):
        l, r = map(int, data[i].split())
        s = reverse_substring(s, l, r)
    
    print(s)

if __name__ == "__main__":
    main()

sy576: 九阵寻词 简单

https://sunnywhy.com/sfbj/3/7/576

给定一个9 x 9的小写字母方阵。

问单词S是否在这个方阵中,其中S存在的形式可以是横向(从左到右)或竖向(从上到下)。

输入描述

1到9行为一个长度为9的小写字符串。

第10行为S。

1len(S)9

输出描述

如果S存在这个方阵中,则输出Yes,否则输出No

样例1

输入

srnosuios
dmakyisab
qvwmiyxch
xzulwrfve
nbsfclffj
lplflenmc
mpwvldpoe
wgeeaeyvi
inzyaapfv
lmwi

输出

Yes
python
def main():
    import sys
    input = sys.stdin.read
    data = input().strip().split('\n')

    matrix = data[:9]
    word = data[9]

    # Check rows
    for row in matrix:
        if word in row:
            print("Yes")
            return

    # Check columns
    for col in range(9):
        column = ''.join(matrix[row][col] for row in range(9))
        if word in column:
            print("Yes")
            return

    print("No")

if __name__ == "__main__":
    main()

sy577: 一O交错 入门

https://sunnywhy.com/sfbj/3/7/577

给定一个01字符串S,问最长的和的交错区间的长度。

其中0和1的交错区间是指,在这个区间范围的任意两个相邻的数字都不同。例如01010是交错的,001不是交错的。

输入描述

一行,一个01字符串S。

1<|S|<1000

输出描述

一个整数,最长的0和1的交错区间的长度。

注意交错没有0和1先后之分。

样例1

输入

10

输出

2

样例2

输入

00

输出

1

样例3

输入

000101000

输出

5

解释

中间的01010是交错区间,长度为5。

python
def longest_alternating_substring(s):
    if len(s) < 2:
        return len(s)
    
    max_length = 1
    current_length = 1
    
    for i in range(1, len(s)):
        if s[i] != s[i - 1]:
            current_length += 1
        else:
            max_length = max(max_length, current_length)
            current_length = 1
    
    max_length = max(max_length, current_length)
    return max_length

if __name__ == "__main__":
    import sys
    input = sys.stdin.read
    s = input().strip()
    print(longest_alternating_substring(s))

sy578: 一一相依 中等

https://sunnywhy.com/sfbj/3/7/578

给定一个字符串,只包含字符0和1,现在能把这个数组里的最多k个0变为1,操作后,最长的连续1的子串有多长。

输入描述

第一行两个数字n,k,表示字符串的长度和可操作次数k。

第二行为一个字符串。

0<n30

0k30

注意n和k没有互相限制关系。

输出描述

输出操作后的最长的连续1的子串的长度。

样例1

输入

20 2
11111011111110111110

输出

19

说明

本题有时间复杂度为O(n)的算法,请比赛期间独立思考。

这是一个经典的“双指针 / 滑动窗口”问题,可以用 O(n) 的时间复杂度解决。


思路讲解

题目要求:

最多将 k 个 '0' 翻转为 '1',求操作后最长连续 '1' 子串长度。

滑动窗口思路:

  • 维护一个窗口 [left, right)
  • right 指针向右移动,每加入一个字符:
    • 若它是 '0',我们就让可用的 k 减 1;
    • 如果此时 k < 0,说明窗口中 0 的数量超过可翻转上限,我们就需要移动 left
      • 当左端离开一个 '0',我们就恢复一个翻转机会 (k += 1)。
  • 过程中记录窗口最大长度即可。
python
n, k = map(int, input().split())
s = input().strip()

left = 0
max_len = 0

for right in range(n):
    if s[right] == '0':
        k -= 1
    while k < 0:
        if s[left] == '0':
            k += 1
        left += 1
    max_len = max(max_len, right - left + 1)

print(max_len)

时间复杂度:O(n)

Plan

  1. Read the input values ( n ) and ( k ).
  2. Read the binary string.
  3. Use a sliding window approach to find the longest substring of 1s that can be obtained by flipping at most ( k ) 0s to 1s.
  4. Initialize two pointers, left and right, to represent the window's boundaries.
  5. Use a variable to count the number of 0s in the current window.
  6. Expand the window by moving the right pointer and update the count of 0s.
  7. If the count of 0s exceeds ( k ), move the left pointer to shrink the window until the count of 0s is less than or equal to ( k ).
  8. Keep track of the maximum length of the window that meets the condition.
  9. Output the maximum length.

Code

python
def longest_ones_after_k_flips(n, k, s):
    left = 0
    max_length = 0
    zero_count = 0

    for right in range(n):
        if s[right] == '0':
            zero_count += 1

        while zero_count > k:
            if s[left] == '0':
                zero_count -= 1
            left += 1

        max_length = max(max_length, right - left + 1)

    return max_length

if __name__ == "__main__":
    import sys
    input = sys.stdin.read
    data = input().strip().split()
    
    n = int(data[0])
    k = int(data[1])
    s = data[2]
    
    print(longest_ones_after_k_flips(n, k, s))

sy579: 二三乃大 入门

https://sunnywhy.com/sfbj/3/7/579

给定一个数字字符串S,现在把这个字符串里面2和3拿出来,重新组合一个新的整数,问最大能组合出的整数。

如果无法组合,则输出0。

输入描述

一个数字字符串S

0<Length(S)1000

输出描述

输出最大能组合出的整数

样例1

输入

12321

输出

322

样例2

输入

44

输出

0
python
def max_combination(s):
    digits = [char for char in s if char in '23']
    if not digits:
        return 0
    digits.sort(reverse=True)
    return int(''.join(digits))

if __name__ == "__main__":
    import sys
    input = sys.stdin.read
    s = input().strip()
    print(max_combination(s))

sy580: 四面楚歌 简单

https://sunnywhy.com/sfbj/3/7/580

给定一个的n×m数字矩阵,每个数字都为1到9。

现在选定一个位置,记该位置所在列的最上方的数字为A、该位置所在行的最右侧的数字为B、该位置所在列的最下方的数字为C、该位置所在行的最左侧的数字为D。将这四个数字组成一个新的整数ABCD。

问选取哪个位置(对应的数字为x),可以使得x×ABCD的值最大。输出这个最大值。

输入描述

第一行为两个数字n,m,分别表示这个数字的矩阵的行数和列数。

第2到n+1行为数字矩阵每一行的数字,用空格分开。

1n,m100

输出描述

输出一个整数,表示能得到的最大值。

样例1

输入

3 3
1 8 2
5 9 7
3 6 4

输出

78885

解释

选中间9的时候,值为9*(8765)=78885,此时是最大的。

Pseudocode:

  1. Parse the input to get the dimensions of the matrix ( n ) and ( m ).
  2. Read the matrix values.
  3. Initialize a variable to store the maximum value.
  4. Iterate through each position in the matrix:
    • For each position, determine the values of ( A ), ( B ), ( C ), and ( D ).
    • Form the integer ( ABCD ) from these values.
    • Calculate the product of the current position's value and ( ABCD ).
    • Update the maximum value if the current product is greater.
  5. Output the maximum value.

Code:

python
def find_max_value(n, m, matrix):
    max_value = 0

    for i in range(n):
        for j in range(m):
            A = matrix[0][j]
            B = matrix[i][m-1]
            C = matrix[n-1][j]
            D = matrix[i][0]
            ABCD = int(f"{A}{B}{C}{D}")
            current_value = matrix[i][j] * ABCD
            max_value = max(max_value, current_value)

    return max_value

if __name__ == "__main__":
    import sys
    input = sys.stdin.read
    data = input().split()
    
    n = int(data[0])
    m = int(data[1])
    matrix = []
    index = 2
    for i in range(n):
        row = list(map(int, data[index:index + m]))
        matrix.append(row)
        index += m
    
    result = find_max_value(n, m, matrix)
    print(result)

sy581: 六的倍数

https://sunnywhy.com/sfbj/3/7/581

该网站上,这个题目不见了

已知一个非负整数的所有数位相加,如果结果是3的倍数,那么这个数字能被3整除。

现在问一个数字x,问它是否能被6整除。

输入描述

一个整数字符串。

数据范围:

0x101000

输出描述

如果数字能被整除,输出Yes;否则输出No

样例1

输入

123

输出

No

样例2

输入

18

输出

Yes
python
def is_divisible_by_6(x):
    # Check if the last digit is even
    if int(x[-1]) % 2 != 0:
        return "No"
    
    # Calculate the sum of all digits
    digit_sum = sum(int(digit) for digit in x)
    
    # Check if the sum of digits is divisible by 3
    if digit_sum % 3 == 0:
        return "Yes"
    else:
        return "No"

if __name__ == "__main__":
    import sys
    input = sys.stdin.read().strip()
    result = is_divisible_by_6(input)
    print(result)

sy582: 七次选择

https://sunnywhy.com/sfbj/3/7/582

该网站上,这个题目不见了

求组合数Cn7

其中Cn7=n!7!(n7)!

输入描述

一个整数N。

7N50

输出描述

组合数Cn7的值。

数据保证1Cn72×109

样例1

输入

7

输出

1
python
import math

def combination_n_7(n):
    if n < 7:
        return 0
    return math.factorial(n) // (math.factorial(7) * math.factorial(n - 7))

if __name__ == "__main__":
    import sys
    input = sys.stdin.read
    n = int(input().strip())
    result = combination_n_7(n)
    print(result)

sy583: 抽象三角图形

https://sunnywhy.com/sfbj/3/7/583

该网站上,这个题目不见了

输出一个腰长为n(n2)的抽象等腰直角三角形。

比如n = 2时输出

text
 #
##

n = 3时,输出

text
  #
 ##
###

其中空白部分为空格。

输入描述

一个整数n。

2n100

输出描述

参照题目描述。

样例1

输入

3

输出

  #
 ##
###
python
def print_isosceles_right_triangle(n):
    for i in range(1, n + 1):
        spaces = ' ' * (n - i)
        hashes = '#' * i
        print(spaces + hashes)

if __name__ == "__main__":
    import sys
    input = sys.stdin.read
    n = int(input().strip())
    print_isosceles_right_triangle(n)
python