02-线性结构4 Pop Sequence (PTA)

Given a stack which can keep M numbers at most. Push N numbers in the order of 1, 2, 3, …, N and pop randomly. You are supposed to tell if a given sequence of numbers is a possible pop sequence of the stack. For example, if M is 5 and N is 7, we can obtain 1, 2, 3, 4, 5, 6, 7 from the stack, but not 3, 2, 1, 7, 5, 6, 4.

Input Specification:

Each input file contains one test case. For each case, the first line contains 3 numbers (all no more than 1000): M (the maximum capacity of the stack), N (the length of push sequence), and K (the number of pop sequences to be checked). Then K lines follow, each contains a pop sequence of N numbers. All the numbers in a line are separated by a space.

Output Specification:

For each pop sequence, print in one line “YES” if it is indeed a possible pop sequence of the stack, or “NO” if not.

Sample Input:

5 7 5
1 2 3 4 5 6 7
3 2 1 7 5 6 4
7 6 5 4 3 2 1
5 6 4 3 7 2 1
1 7 6 5 4 3 2

      
    

Sample Output:

YES
NO
NO
YES
NO

编译器:Python(python3)

这题的思路就是用list的append和pop来模拟堆栈,思路比较清晰,大概调试了2个小时(笑哭

M, N, K = map(int,input().split(' '))

std_list = [x for x in range(N+1)]

while K:
    K -=1
    input_list = [int(x) for x in input().split(' ')]
    stack = [0]
    i = 1
    j = 0
    while(len(stack)<=M+1):
        if stack[-1] == input_list[j]:
            stack.pop()
            j+=1
            if j == N:
                print('YES')
                break
        else:
            if i <= N:
                stack.append(std_list[i])
                i+=1
            else:
                break
    if j != N:
        print('NO')        
    

02-线性结构3 Reversing Linked List (PTA)

Given a constant K and a singly linked list L, you are supposed to reverse the links of every K elements on L. For example, given L being 1→2→3→4→5→6, if K=3, then you must output 3→2→1→6→5→4; if K=4, you must output 4→3→2→1→5→6.

Input Specification:

Each input file contains one test case. For each case, the first line contains the address of the first node, a positive N (≤10​5​​) which is the total number of nodes, and a positive K (≤N) which is the length of the sublist to be reversed. The address of a node is a 5-digit nonnegative integer, and NULL is represented by -1.

Then N lines follow, each describes a node in the format:

Address Data Next

where Address is the position of the node, Data is an integer, and Next is the position of the next node.

Output Specification:

For each case, output the resulting ordered linked list. Each node occupies a line, and is printed in the same format as in the input.

Sample Input:

00100 6 4
00000 4 99999
00100 1 12309
68237 6 -1
33218 3 00000
99999 5 68237
12309 2 33218

Sample Output:

00000 4 33218
33218 3 12309
12309 2 00100
00100 1 99999
99999 5 68237
68237 6 -1

Python 的代码在第五个测试点“ 最大N,最后剩K-1不反转 ”,运行超时。C++代码可以AC。

思路相同, 先读取有效的数据,排除不在链表上的节点 ,然后用有序列表的部分反转操作达到反转。Python效率不如C++,C++用4ms算完的,Python要22ms,最大长度C++花了200多ms,而这题限制400ms。也想不出优化的地方了。

编译器:Python(python3)

d={}

start_addr, L, K = input().split(' ')
L = int(L)
K = int(K)

for i in range(L):
    addr1, data, next_addr = input().split(' ')
    d[addr1] = [data,next_addr]

addr_list = []
count = 0
temp_addr = start_addr 
for i in range(L):
    if temp_addr == '-1':
        break
    else:
        count += 1
        addr_list.append(temp_addr)
        temp_addr = d[temp_addr][1]

res_index = 0
while(res_index + K <= count):
    sub_list = addr_list[res_index:res_index+K]
    addr_list[res_index:res_index+K] = sub_list[::-1]
    res_index += K

for i in range(len(addr_list) - 1):
    print(addr_list[i],d[ addr_list[i] ][0],addr_list[i+1])
print(addr_list[-1],d[ addr_list[-1] ][0],'-1') 

编译器:C++(g++)

#include <iostream>
#include <algorithm>
#define MAXSIZE 100000
using namespace std;

struct LNode
{
    int data;
    int next;
}node[MAXSIZE];

int List[MAXSIZE];

int main()
{
    int head_addr, n, k;
    cin >> head_addr >> n >> k;

    int addr, data, next;
    for(int i = 0; i < n; i++)
    {
        cin >> addr;
        cin >> data;
        cin >> next;
        node[addr].data = data;
        node[addr].next = next;
    }

    int count = 0;
    int p_next = head_addr;

    while(p_next!=-1)
    {
        List[count] = p_next;
        p_next = node[p_next].next;
        count = count + 1;
    }

    int first = 0;
    while (first + k <= count)
    {
        reverse(&List[first], &List[first + k]);
        first += k;
    }
    
    for(first = 0; first < count-1; first++)
        printf("%05d %d %05d\n", List[first], node[List[first]].data, List[first + 1]);
    printf("%05d %d -1\n", List[first], node[List[first]].data);
    return 0;
} 

02-线性结构2 一元多项式的乘法与加法运算 (PTA)

设计函数分别求两个一元多项式的乘积与和。

输入格式:

输入分2行,每行分别先给出多项式非零项的个数,再以指数递降方式输入一个多项式非零项系数和指数(绝对值均为不超过1000的整数)。数字间以空格分隔。

输出格式:

输出分2行,分别以指数递降方式输出乘积多项式以及和多项式非零项的系数和指数。数字间以空格分隔,但结尾不能有多余空格。零多项式应输出0 0

输入样例:

4 3 4 -5 2  6 1 -2 0
3 5 20  -7 4  3 1

输出样例:

15 24 -25 22 30 21 -10 20 -21 8 35 6 -33 5 14 4 -15 3 18 2 -6 1
5 20 -4 4 -5 2 9 1 -2 0

编译器:Python(python3)

p1 = list(input().split())
p2 = list(input().split())

d1 = {}
d1c = {}
d2 = {}
d2c = {}

d3 = {}
d4 = {}

list1 = []
list2 = []

for i in range(1,len(p1),2):
    if int(p1[i]) !=0:
        d1[int(p1[i+1])] = int(p1[i])
for i in range(1,len(p2),2):
    if int(p2[i]) !=0:
        d2[int(p2[i+1])] = int(p2[i])
    
#polu multi    
d1c = d1.copy()
d2c = d2.copy()
for k1 in d1c:
    for k2 in d2c:
        temp = d4.get(k1+k2,0) + d1c.get(k1)*d2c.get(k2)
        if temp !=0:
            d4[k1+k2] = temp
        else:
            del d4[k1+k2]
            
if len(d4) != 0:            
    for i in sorted(d4.keys(),reverse = True):
        list1.append(str(d4[i]))
        list1.append(str(i))
else:
    list1.append(str(0))
    list1.append(str(0))




#poly plus
d3 = d2.copy()
for k1 in d1:
    temp = d3.get(k1,0) + d1.get(k1)
    if (temp!=0):
        d3[k1] = temp
    else:
        del d3[k1]

if len(d3) != 0: 
    for i in sorted(d3.keys(),reverse = True):
        list2.append(str(d3[i]))
        list2.append(str(i))
else:
    list2.append(str(0))
    list2.append(str(0))

print(' '.join(list1))
print(' '.join(list2))  

1002 A+B for Polynomials (PTA)

This time, you are supposed to find A+B where A and B are two polynomials.

Input Specification:

Each input file contains one test case. Each case occupies 2 lines, and each line contains the information of a polynomial:

K N​1​​ aN​1​​​​ N​2​​ aN​2​​​​ … NK​​ aNK​​​​

where K is the number of nonzero terms in the polynomial, Ni​​ and aNi​​​​ (i=1,2,⋯,K) are the exponents and coefficients, respectively. It is given that 1≤K≤10,0≤NK​​<⋯<N​2​​<N​1​​≤1000.

Output Specification:

For each test case you should output the sum of A and B in one line, with the same format as the input. Notice that there must be NO extra space at the end of each line. Please be accurate to 1 decimal place.

Sample Input:

2 1 2.4 0 3.2
2 2 1.5 1 0.5

Sample Output:

3 2 1.5 1 2.9 0 3.2

编译器:Python(python3)

p1 = list(input().split())
p2 = list(input().split())
d1 = {}
d2 = {}
d3 = {}
k = []

for i in range(1,len(p1),2):
    d1[int(p1[i])] = d1.get(int(p1[i]),float(p1[i+1]))
for i in range(1,len(p2),2):
    d2[int(p2[i])] = d2.get(int(p2[i]),float(p2[i+1]))

d3 = d2.copy()
for k1 in d1:
    temp = d3.get(k1,0) + d1.get(k1)
    if (temp!=0):
        d3[k1] = temp
    else:
        del d3[k1]

list1 = [str(len(d3))]

for i in sorted(d3.keys(),reverse = True):
    list1.append(str(i))
    list1.append(str(round(d3[i], 1)))
print(' '.join(list1)) 

1001 A+B Format (PTA)

Calculate a+b and output the sum in standard format — that is, the digits must be separated into groups of three by commas (unless there are less than four digits).

Input Specification:

Each input file contains one test case. Each case contains a pair of integers a and b where −10​6​​≤a,b≤10​6​​. The numbers are separated by a space.

Output Specification:

For each test case, you should output the sum of a and b in one line. The sum must be written in the standard format.

Sample Input:

-1000000 9

Sample Output:

-999,991

编译器:Python(python3)

a, b =input().split(' ')
c = int(a) + int(b)
print("{:,}".format(c)) 

自测-5 Shuffling Machine (PTA)

Shuffling is a procedure used to randomize a deck of playing cards. Because standard shuffling techniques are seen as weak, and in order to avoid “inside jobs” where employees collaborate with gamblers by performing inadequate shuffles, many casinos employ automatic shuffling machines. Your task is to simulate a shuffling machine.

The machine shuffles a deck of 54 cards according to a given random order and repeats for a given number of times. It is assumed that the initial status of a card deck is in the following order:

S1, S2, ..., S13, 
H1, H2, ..., H13, 
C1, C2, ..., C13, 
D1, D2, ..., D13, 
J1, J2

where “S” stands for “Spade”, “H” for “Heart”, “C” for “Club”, “D” for “Diamond”, and “J” for “Joker”. A given order is a permutation of distinct integers in [1, 54]. If the number at the i-th position is j, it means to move the card from position i to position j. For example, suppose we only have 5 cards: S3, H5, C1, D13 and J2. Given a shuffling order {4, 2, 5, 3, 1}, the result will be: J2, H5, D13, S3, C1. If we are to repeat the shuffling again, the result will be: C1, H5, S3, J2, D13.

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer K (≤20) which is the number of repeat times. Then the next line contains the given order. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print the shuffling results in one line. All the cards are separated by a space, and there must be no extra space at the end of the line.

Sample Input:

2
36 52 37 38 3 39 40 53 54 41 11 12 13 42 43 44 2 4 23 24 25 26 27 6 7 8 48 49 50 51 9 10 14 15 16 5 17 18 19 1 20 21 22 28 29 30 31 32 33 34 35 45 46 47

Sample Output:

S7 C11 C10 C12 S1 H7 H8 H9 D8 D9 S11 S12 S13 D10 D11 D12 S3 S4 S6 S10 H1 H2 C13 D2 D3 D4 H6 H3 D13 J1 J2 C1 C2 C3 C4 D1 S5 H5 H11 H12 C6 C7 C8 C9 S2 S8 S9 H10 D5 D6 D7 H4 H13 C5

编译器:Python(python3)

spade = ['S' + str(i) for i in range(1, 14, 1)]
heart = ['H' + str(i) for i in range(1, 14, 1)]
club = ['C' + str(i) for i in range(1, 14, 1)]
diam = ['D' + str(i) for i in range(1, 14, 1)]
joker = ['J1', 'J2']
cards = spade + heart + club + diam + joker
result = [None]*len(cards)

K = int(input())
order = list(map(int, input().split()))

for i in range(len(cards)):
    index = i
    for j in range(K):
        index = order[index] - 1
    result[index] = cards[i]
    
print(' '.join(result)) 

1023/自测-4 Have Fun with Numbers (PTA)

Notice that the number 123456789 is a 9-digit number consisting exactly the numbers from 1 to 9, with no duplication. Double it we will obtain 246913578, which happens to be another 9-digit number consisting exactly the numbers from 1 to 9, only in a different permutation. Check to see the result if we double it again!

Now you are suppose to check if there are more numbers with this property. That is, double a given number with k digits, you are to tell if the resulting number consists of only a permutation of the digits in the original number.

Input Specification:

Each input contains one test case. Each case contains one positive integer with no more than 20 digits.

Output Specification:

For each test case, first print in a line “Yes” if doubling the input number gives a number that consists of only a permutation of the digits in the original number, or “No” if not. Then in the next line, print the doubled number.

Sample Input:

1234567899

Sample Output:

Yes
2469135798

编译器:Python(python3)

N = int(input())
doubleN = N*2

str_N = str(N)
str_doubleN = str(doubleN)

Set_N = set(str_N)
Set_doubleN = set(str_doubleN)

if Set_N == Set_doubleN:
    print("Yes")
else:
    print("No")
    
print(doubleN) 

自测-3 数组元素循环右移问题 (PTA)

一个数组A中存有N(>0)个整数,在不允许使用另外数组的前提下,将每个整数循环向右移M(≥0)个位置,即将A中的数据由(A​0​​A​1​​⋯AN−1​​)变换为(ANM​​⋯AN−1​​A​0​​A​1​​⋯ANM−1​​)(最后M个数循环移至最前面的M个位置)。如果需要考虑程序移动数据的次数尽量少,要如何设计移动的方法?

输入格式:

每个输入包含一个测试用例,第1行输入N(1≤N≤100)和M(≥0);第2行输入N个整数,之间用空格分隔。

输出格式:

在一行中输出循环右移M位以后的整数序列,之间用空格分隔,序列结尾不能有多余空格。

输入样例:

6 2
1 2 3 4 5 6

输出样例:

5 6 1 2 3 4

编译器:Python(python3)

N, M = input().split(' ')
string = input().split(' ')
N = int(N)
M = int(M)
result = string[N-M:] + string[:N-M]
print(' '.join(result)) 

自测-2 素数对猜想 (PTA)

让我们定义dn​​为:dn​​=pn+1​​−pn​​,其中pi​​是第i个素数。显然有d​1​​=1,且对于n>1有dn​​是偶数。“素数对猜想”认为“存在无穷多对相邻且差为2的素数”。

现给定任意正整数N(<10​5​​),请计算不超过N的满足猜想的素数对的个数。

输入格式:

输入在一行给出正整数N

输出格式:

在一行中输出不超过N的满足猜想的素数对的个数。

输入样例:

20

输出样例:

4

编译器:Python(python3)

 def eratosthenes(n):
    IsPrime = [True] * (n + 1)
    for i in range(2, int(n ** 0.5) + 1):
        if IsPrime[i]:
            for j in range(i * i, n + 1, i):
                IsPrime[j] = False
    return [x for x in range(2, n + 1) if IsPrime[x]]
n=int(input())
result = eratosthenes(n)
#print(result)
count = 0;
for i in range(len(result) - 1):
    if result[i+1]-result[i]== 2:
        count +=1;
print(count) 

Python的问题还是消耗的资源多,用普通的算法最大N总是超时,这里使用了Sieve of Eratosthenes

https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
https://zh.wikipedia.org/wiki/%E5%9F%83%E6%8B%89%E6%89%98%E6%96%AF%E7%89%B9%E5%B0%BC%E7%AD%9B%E6%B3%95
中文的wiki上有现成的代码

自测-1 打印沙漏 (PTA)

本题要求你写个程序把给定的符号打印成沙漏的形状。例如给定17个“*”,要求按下列格式打印

*****
 ***
  *
 ***
*****

所谓“沙漏形状”,是指每行输出奇数个符号;各行符号中心对齐;相邻两行符号数差2;符号数先从大到小顺序递减到1,再从小到大顺序递增;首尾符号数相等。

给定任意N个符号,不一定能正好组成一个沙漏。要求打印出的沙漏能用掉尽可能多的符号。

输入格式:

输入在一行给出1个正整数N(≤1000)和一个符号,中间以空格分隔。

输出格式:

首先打印出由给定符号组成的最大的沙漏形状,最后在一行中输出剩下没用掉的符号数。

输入样例:

19 *

输出样例:

*****
 ***
  *
 ***
*****
2

编译器:Python(python3)

import numpy as np

num, ch =input().split(' ')
num = int(num)

N = np.sqrt((num+1)/2);

N = int(N)

residue = num - (2*np.square(N) - 1)

layers = 2*N - 1

for i in range(layers):
    seq = abs(i - (N - 1)) +1
    rep = 2*seq-1
    str = rep*ch
    zeros = (layers + rep)/2
    zeros = int(zeros)
    #str = str.center(layers,' ')
    str = str.rjust(zeros)
    print(str,end='\n')
    
print(residue)