2024年春季学期《算法分析与设计》练习15

问题 A: 简单递归求和

[命题人 : admin]

时间限制 : 1.000 sec  内存限制 : 128 MB

提交问题列表

解决: 749提交量: 1359统计

题目描述

使用递归编写一个程序求如下表达式前n项的计算结果:  (n<=100)
1 -  3 + 5 - 7 + 9 - 11 +......
输入n,输出表达式的计算结果。

输入

多组输入,每组输入一个n,n<=100。

输出

输出表达式的计算结果。

样例输入 Copy
1
2
样例输出 Copy
1
-2
# 使用递归计算表达式的结果
def alternating_sum(n):
    if n == 1:
        return 1
    else:
        if n % 2 == 0:
            return alternating_sum(n - 1) - (2 * n - 1)
        else:
            return alternating_sum(n - 1) + (2 * n - 1)
 
# 读取输入,计算表达式的结果并输出
while True:
    n = int(input())
    if n <= 100:
        result = alternating_sum(n)
        print(result)
    else:
        print()

问题 B: 文件存储

[命题人 : admin]

时间限制 : 1.000 sec  内存限制 : 128 MB

提交问题列表

解决: 838提交量: 1681统计

题目描述

如果有n个文件{F1,F2,F3,…,Fn}需要存放在大小为M的U盘中,文件i的大小为Si,1<=i<=n。请设计一个算法来提供一个存储方案,使得U盘中存储的文件数量最多。

输入

多组输入,对于每组测试数据,每1行的第1个数字表示U盘的容量M(以MB为单位,不超过256*1000MB),第2个数字表示待存储的文件个数n。
第2行表示待存储的n个文件的大小(以MB为单位)。

输出

输出最多可以存放的文件个数。

样例输入 Copy
10000 5
2000 1000 5000 3000 4000
样例输出 Copy
4
def max_files_in_usb(M, n, files):
    # Step 1: Sort the files by their size in ascending order
    files.sort()
     
    # Step 2: Initialize variables to keep track of the current used space and file count
    used_space = 0
    file_count = 0
     
    # Step 3: Iterate over the sorted file sizes and add them as long as they fit in the USB
    for file_size in files:
        if used_space + file_size <= M:
            used_space += file_size
            file_count += 1
        else:
            break
             
    return file_count
 
# Read input for multiple test cases
import sys
input = sys.stdin.read
data = input().split()
 
index = 0
while index < len(data):
    # Read M and n
    M = int(data[index])
    n = int(data[index + 1])
    index += 2
     
    # Read file sizes
    files = []
    for i in range(n):
        files.append(int(data[index + i]))
    index += n
     
    # Get the maximum number of files that can be stored
    result = max_files_in_usb(M, n, files)
     
    # Print the result
    print(result)

问题 C: 图的m着色问题

[命题人 : 201601090120]

时间限制 : 1.000 sec  内存限制 : 128 MB

提交问题列表

解决: 967提交量: 2230统计

题目描述

 给定无向连通图G和m种不同的颜色。用这些颜色为图G的各顶点着色,每个顶点着一种颜色。是否有一种着色法使G中每条边的2个顶点着不同颜色,请输出着色方案。

输入

输入第一行包含n,m,k分别代表n个结点,m条边,k种颜色,接下来m行每行有2个数u,v表示u和v之间有一条无向边,可能出现自环边,所以请忽略自环边。

输出

输出所有不同的着色方案,且按照字典序从小到大输出方案。

样例输入 Copy
3 3 3
1 2
1 3
2 3
样例输出 Copy
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
def is_valid(node, color, graph, colors):
    for neighbor in graph[node]:
        if colors[neighbor] == color:
            return False
    return True
 
def graph_coloring(graph, n, m, k, node, colors):
    if node == n:  # All nodes are colored
        return [colors[:]]
     
    valid_colorings = []
    for color in range(1, k + 1):
        if is_valid(node, color, graph, colors):
            colors[node] = color
            valid_colorings.extend(graph_coloring(graph, n, m, k, node + 1, colors))
            colors[node] = 0  # Backtrack
     
    return valid_colorings
 
def main():
    import sys
    input = sys.stdin.read
    data = input().split()
     
    n = int(data[0])
    m = int(data[1])
    k = int(data[2])
     
    edges = [(int(data[i * 2 + 3]), int(data[i * 2 + 4])) for i in range(m) if int(data[i * 2 + 3]) != int(data[i * 2 + 4])]
     
    graph = [[] for _ in range(n)]
    for u, v in edges:
        graph[u - 1].append(v - 1)
        graph[v - 1].append(u - 1)
 
    colors = [0] * n
    valid_colorings = graph_coloring(graph, n, m, k, 0, colors)
     
    valid_colorings.sort()
     
    for coloring in valid_colorings:
        print(" ".join(map(str, coloring)))
 
if __name__ == "__main__":
    main()

问题 D: N皇后问题

[命题人 : 201501010119]

时间限制 : 1.000 sec  内存限制 : 128 MB

提交问题列表

解决: 968提交量: 2087统计

题目描述

使用回溯法求解N后问题。

 

输入

皇后的个数。

输出

每一种方案及总方案数。

样例输入 Copy
4
样例输出 Copy
0 1 0 0
0 0 0 2
3 0 0 0
0 0 4 0
----------------
0 0 1 0
2 0 0 0
0 0 0 3
0 4 0 0
----------------
总方案数为:2
def gulu(i, n, a, b, c, d, count):
    if i < n:
        for j in range(n):  # 列循环
            if b[j] == 0 and c[i - j + n - 1] == 0 and d[i + j] == 0:
                a[i][j] = i + 1
                b[j] = 1
                c[i - j + n - 1] = 1
                d[i + j] = 1
                count = gulu(i + 1, n, a, b, c, d, count)
                a[i][j] = 0
                b[j] = 0
                c[i - j + n - 1] = 0
                d[i + j] = 0
    else:
        for j in range(n):
            for l in range(n):
                print(a[j][l], end=" ")
            print()
        print("----------------")
        count += 1
    return count
 
def main():
    n = int(input())
    a = [[0] * n for _ in range(n)]
    b = [0] * n
    c = [0] * (2 * n - 1)
    d = [0] * (2 * n - 1)
    count = 0
    count = gulu(0, n, a, b, c, d, count)
    print(f"总方案数为:{count}")
 
if __name__ == "__main__":
    main()
 

问题 E: 马的遍历问题

[命题人 : 201501010119]

时间限制 : 1.000 sec  内存限制 : 128 MB

提交问题列表

解决: 1031提交量: 1887统计

题目描述

在5*4的棋盘中,马只能走斜“日”字。马从位置(x, y)处出发,把棋盘的每一格都走一次,且只走一次,请找出所有路径。

输入

x,y,表示马的初始位置。

输出

将每一格都走一次的路径总数,如果不存在该路径则输出“No solution!”。

样例输入 Copy
1 1
2 2
样例输出 Copy
32
No solution!
ROWS = 5
COLS = 4
SIZE = ROWS * COLS
 
dx = [-2, -2, -1, -1, 1, 1, 2, 2]
dy = [-1, 1, -2, 2, -2, 2, -1, 1]
a = [[0 for _ in range(COLS)] for _ in range(ROWS)]
count = 0
 
def miumiumama(x, y, b):
    global count
    for i in range(8):
        next_x = x + dx[i]
        next_y = y + dy[i]
        if 0 <= next_x < ROWS and 0 <= next_y < COLS:
            if a[next_x][next_y] == 0:
                a[next_x][next_y] = b
                if b == SIZE:
                    count += 1
                else:
                    miumiumama(next_x, next_y, b + 1)
                a[next_x][next_y] = 0
 
if __name__ == "__main__":
    while True:
        try:
            x, y = map(int, input().split())
            x -= 1  # 调整为从0开始的索引
            y -= 1  # 调整为从0开始的索引
            count = 0
            a[x][y] = 1
            miumiumama(x, y, 2)
            if count != 0:
                print(count)
            else:
                print("No solution!")
            a[x][y] = 0
        except ValueError:
            break

问题 F: 素数环

[命题人 : 201601090120]
时间限制 : 1.000 sec  内存限制 : 128 MB

提交问题列表
题目描述
现有1,2,3...,n,要求用这些数组成一个环,使得相邻的两个整数之和均为素数,要求你求出这些可能的环。
输入

输入正整数n。

输出
输出时从整数1开始逆时针输出,同一个环只输出一次,且满足条件的环应按照字典序从小到大输出。
注:每一个环都从1开始。
样例输入 Copy
<span style="background-color:#ffffff"><span style="color:#333333"><span style="background-color:#ffffff"><span style="color:#333333"><span style="background-color:#f5f5f5">6</span></span></span></span></span>
样例输出 Copy
def is_prime(num):
    if num < 2:
        return False
    for i in range(2, int(num**0.5) + 1):
        if num % i == 0:
            return False
    return True
 
def gulu(i, n, a, used):
    if i == n:
        # 输出当前序列
        for j in range(n):
            print(a[j], end=" ")
        print()
        return
     
    for j in range(1, n + 1):
        if not used[j - 1]:
            if i != n - 1 and is_prime(a[i - 1] + j):
                a[i] = j
                used[j - 1] = True
                gulu(i + 1, n, a, used)
                used[j - 1] = False
            elif i == n - 1 and is_prime(a[i - 1] + j) and is_prime(a[0] + j):
                a[i] = j
                used[j - 1] = True
                gulu(i + 1, n, a, used)
                used[j - 1] = False
 
if __name__ == "__main__":
    while True:
        try:
            n = int(input().strip())
            a = [0] * n
            used = [False] * n
            a[0] = 1
            used[0] = True
            gulu(1, n, a, used)
        except EOFError:
            break
<span style="background-color:#ffffff"><span style="color:#333333"><span style="background-color:#ffffff"><span style="color:#333333"><span style="background-color:#f5f5f5">1 4 3 2 5 6
1 6 5 2 3 4</span></span></span></span></span>
  • 24
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值