pat 甲级 1019

来源:互联网 发布:马龙职业生涯数据 编辑:程序博客网 时间:2024/05/01 23:44

1019. General Palindromic Number (20)

A number that will be the same when it is written forwards or backwards is known as a Palindromic Number. For example, 1234321 is a palindromic number. All single digit numbers are palindromic numbers.

Although palindromic numbers are most often considered in the decimal system, the concept of palindromicity can be applied to the natural numbers in any numeral system. Consider a number N > 0 in base b >= 2, where it is written in standard notation with k+1 digits ai as the sum of (aibi) for i from 0 to k. Here, as usual, 0 <= ai < b for all i and ak is non-zero. Then N is palindromic if and only if ai = ak-i for all i. Zero is written 0 in any base and is also palindromic by definition.

Given any non-negative decimal integer N and a base b, you are supposed to tell if N is a palindromic number in base b.

Input Specification:

Each input file contains one test case. Each case consists of two non-negative numbers N and b, where 0 <= N <= 109 is the decimal number and 2 <= b <= 109 is the base. The numbers are separated by a space.

Output Specification:

For each test case, first print in one line “Yes” if N is a palindromic number in base b, or “No” if not. Then in the next line, print N as the number in base b in the form “ak ak-1 … a0”. Notice that there must be no extra space at the end of output.

Sample Input 1:
27 2
Sample Output 1:
Yes
1 1 0 1 1
Sample Input 2:
121 5
Sample Output 2:
No
4 4 1

代码:

# -*- coding: utf-8 -*-#@author: cxlualine1 = input().split()N = int(line1[0])base = int(line1[1])def tobase(num, base):    res = []    while num != 0:        res.append(str(num % base))        num = int(num / base)    res.reverse()    return res      #此处不能return res.reverse(), 否则会返回Nonetypedef judgePa(numList):    k = len(numList) - 1    for i in range(int(len(numList) / 2)):        if numList[i] != numList[k - i]:            return False    return Trueif N == 0:      # 测试点5, 这种换进制的方法,对于0会返回空list,所以要单独考虑为0的情况    print('Yes')    print(0)else:    converted = tobase(N, base)    # print(converted)    if judgePa(converted):        print('Yes')    else:        print('No')    print(' '.join(converted))

1020. Tree Traversals (25)

Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, you are supposed to output the level order traversal sequence of the corresponding binary tree.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (<=30), the total number of nodes in the binary tree. The second line gives the postorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print in one line the level order traversal sequence of the corresponding binary tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.

Sample Input:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
Sample Output:
4 1 6 3 5 7 2

代码:

# -*- coding: utf-8 -*-#@author: cxluafrom queue import QueueN = int(input())postorder = [int(i) for i in input().split()]inorder = [int(i) for i in input().split()]class tree(object):    """docstring for treeNode"""    def __init__(self, leftTree = None, rightTree = None, nodeNum = None):        self.leftTree = leftTree        self.rightTree = rightTree        self.nodeNum = nodeNumdef creatTree(leftNode, rightNode):    if leftNode >= rightNode:        return None    global postorder, inorder    thisTree = tree()    # if leftNode == rightNode:     #错误代码,这样会多构建树,实则当列表为空,该节点应该直接为None    #   # print(leftNode)    #   thisTree.nodeNum = inorder[leftNode]    #   thisTree.leftTree = None    #   thisTree.rightTree = None    # else:    treeNodes = inorder[leftNode: rightNode]    root = postorder[max([postorder.index(i) for i in treeNodes])]      #后根遍历找到根节点    rootindex = inorder.index(root)                                 #找到根节点在中序遍历的索引    thisTree.nodeNum = root    thisTree.leftTree = creatTree(leftNode, rootindex)    if rootindex == N - 1:       ## 否则会有list index out of range的报错        thisTree.rightTree == None    else:        thisTree.rightTree = creatTree(rootindex + 1, rightNode)    return thisTreedef bfs(thisTree):    res = []    q = Queue()    q.put(thisTree)    while(q.qsize() != 0):        thisTree = q.get()        res.append(thisTree.nodeNum)        if thisTree.leftTree != None:           #先压入左子树,后压入右子树            q.put(thisTree.leftTree)        if thisTree.rightTree != None:            q.put(thisTree.rightTree)    return resfullTree = creatTree(0, N)# print(bfs(fullTree))res = [str(i) for i in bfs(fullTree)]print(' '.join(res))
  1. python构建二叉树:用节点class结合递归构造树的函数实现,class属性分别为左子树、右子树、该节点的键;
  2. python的class实现:类名后面(object)表示继承的类,没有特别继承的类时都是object, init()是构造函数,定义所有实例都包含的属性,类的方法第一个参数都是self, 表示类的实例;
  3. creatTree()函数递归构造树,后序遍历中,最后面的节点是根节点,该节点将中序遍历分为左子树和右子树;
  4. 用bfs实现层序遍历的输出,bfs显示使用队列数据结构(先进先出),q = queue.Queue()定义一个队列,q.put()向队列中加入元素,q.get()删除并返回队列的第一个元素;循环的每一步删除队列的当前最前元素,对于这个元素的所有相邻点,若没有被标记过,则标记并加入队列,循环终止的条件是队列为空,即不再有新的节点。

1021. Deepest Root (25)

A graph which is connected and acyclic can be considered a tree. The height of the tree depends on the selected root. Now you are supposed to find the root that results in a highest tree. Such a root is called the deepest root.

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N (<=10000) which is the number of nodes, and hence the nodes are numbered from 1 to N. Then N-1 lines follow, each describes an edge by given the two adjacent nodes’ numbers.

Output Specification:

For each test case, print each of the deepest roots in a line. If such a root is not unique, print them in increasing order of their numbers. In case that the given graph is not a tree, print “Error: K components” where K is the number of connected components in the graph.

Sample Input 1:
5
1 2
1 3
1 4
2 5
Sample Output 1:
3
4
5
Sample Input 2:
5
1 3
1 4
2 5
3 4
Sample Output 2:
Error: 2 components

代码:

# -*- coding: utf-8 -*-N = int(input())records = []adjoints = []for i in range(N):    adjoints.append([])# graph = [[float('inf')] * N for i in range(N)]for i in range(N - 1):    records.append([int(i) - 1 for i in input().split()])    adjoints[records[i][0]].append(records[i][1])    adjoints[records[i][1]].append(records[i][0])# print(records)    # graph[records[i][0]][records[i][1]] = graph[records[i][1]][records[i][0]] = 1deepest = 0res = []res_2 = []def find(node):    global ide    # print(node)    while node != ide[node]:        ide[node] = ide[ide[node]]        node = ide[node]    return nodedef union(node1, node2):    global ide, sz, num    root1 = find(node1)    root2 = find(node2)    if root1 == root2:        return #False    if sz[root1] >= sz[root2]:        ide[root2] = root1        sz[root1] += sz[root2]    else:        ide[root1] = root2        sz[root2] += sz[root1]    num -= 1    return #Truedef dfs(node, depth):    global marked, adjoints, deepest, res    marked[node] = True    if depth > deepest:        deepest = depth        res = [node + 1]    elif depth == deepest:        res.append(node + 1)    for i in adjoints[node]:        if (not marked[i]):            dfs(i, depth + 1)            # print(res, deepest, depth + 1, start+1, node)    returndef dfs_2(node, depth):    global marked, adjoints, deepest, res_2    marked[node] = True    if depth > deepest:        deepest = depth        res_2 = [node + 1]    elif depth == deepest:        res_2.append(node + 1)    for i in adjoints[node]:        if (not marked[i]):            dfs_2(i, depth + 1)            # print(res, deepest, depth + 1, start+1, node)    returnsz = [1] * Nide = [i for i in range(N)]num = N# judge = []for i in range(N - 1):    # judge.append(union(records[i][0], records[i][1]))    union(records[i][0], records[i][1])if num > 1:    print('Error: ' + str(num) + ' components')else:    marked = [False] * N    # print('now', i + 1)    dfs(0, 0)    deepest = 0    marked = [False] * N    # print(res)    dfs_2(res[0] - 1, 0)    # print(res_2)    res.extend(res_2)    res = sorted(set(res)) ## 去重并排序    # print(res)    for i in res:        print(i)# if N == 1:        ##dfs函数先判depth,所以只有1的时候也会在res添加元素#   print('1')
  1. 先用并查集判断是不是树,因为只有N-1条路径,所以只要连通集合多于一个,就不是树(不会存在一个连通图中有环的情况)(注释掉的在Union中判断并返回是否有环);
  2. 开始的找最深根节点的思路是,从每一个节点做dfs,记录最深路径的开始节点,最后去重并排序(1021_dfs.py);
  3. 更省时间的方法是,先从任意节点开始做dfs,记录下到达的最深节点(list_1), 然后从list_1中任选一个节点dfs, 记录最深节点(list_2), 最后取两个list并集,注意去重并排序;
  4. 合并两个list, a.extend(b), 此时的a就是合并后的(a被改变)。(c = a.extend(b),c会返回空);
  5. 用邻接表代替邻接矩阵表示图,否则内存超限

1022. Digital Library (30)

A Digital Library contains millions of books, stored according to their titles, authors, key words of their abstracts, publishers, and published years. Each book is assigned an unique 7-digit number as its ID. Given any query from a reader, you are supposed to output the resulting books, sorted in increasing order of their ID’s.

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N (<=10000) which is the total number of books. Then N blocks follow, each contains the information of a book in 6 lines:

Line #1: the 7-digit ID number;
Line #2: the book title – a string of no more than 80 characters;
Line #3: the author – a string of no more than 80 characters;
Line #4: the key words – each word is a string of no more than 10 characters without any white space, and the keywords are separated by exactly one space;
Line #5: the publisher – a string of no more than 80 characters;
Line #6: the published year – a 4-digit number which is in the range [1000, 3000].
It is assumed that each book belongs to one author only, and contains no more than 5 key words; there are no more than 1000 distinct key words in total; and there are no more than 1000 distinct publishers.

After the book information, there is a line containing a positive integer M (<=1000) which is the number of user’s search queries. Then M lines follow, each in one of the formats shown below:

1: a book title
2: name of an author
3: a key word
4: name of a publisher
5: a 4-digit number representing the year
Output Specification:

For each query, first print the original query in a line, then output the resulting book ID’s in increasing order, each occupying a line. If no book is found, print “Not Found” instead.

Sample Input:
3
1111111
The Testing Book
Yue Chen
test code debug sort keywords
ZUCS Print
2011
3333333
Another Testing Book
Yue Chen
test code sort keywords
ZUCS Print2
2012
2222222
The Testing Book
CYLL
keywords debug book
ZUCS Print2
2011
6
1: The Testing Book
2: Yue Chen
3: keywords
4: ZUCS Print
5: 2011
3: blablabla
Sample Output:
1: The Testing Book
1111111
2222222
2: Yue Chen
1111111
3333333
3: keywords
1111111
2222222
3333333
4: ZUCS Print
1111111
5: 2011
1111111
2222222
3: blablabla
Not Found

代码:

N = int(input())books = {}for i in range(N):    ID = input()    books[ID] = {}    books[ID]['title'] = input()    books[ID]['author'] = input()    books[ID]['key words'] = input().split()    books[ID]['publisher'] = input()    books[ID]['year'] = input()# print(books)M = int(input())index = {'1': 'title', '2': 'author', '3': 'key words', '4': 'publisher', '5': 'year'}search = []for i in range(M):    temp = input()    search.append({})    search[i][temp] = []    s = temp.split(': ')    for key, value in books.items():        if s[0] == '3':            if s[1] in value[index[s[0]]]:                search[i][temp].append(key)        else:            if s[1] == value[index[s[0]]]:                search[i][temp].append(key)    search[i][temp] = sorted(search[i][temp])# print(search[0])for i in search:    temp = tuple(i.items())    print(temp[0][0])    if len(temp[0][1]) == 0:        print('Not Found')    else:        for i in temp[0][1]:            print(i)

字典不会按照输入顺序输出,排序后再变成字典也是乱序