1034 Head of a Gang (30分)
One way that the police finds the head of a gang is to check people's phone calls. If there is a phone call between A and B, we say that A and B is related. The weight of a relation is defined to be the total time length of all the phone calls made between the two persons. A "Gang" is a cluster of more than 2 persons who are related to each other with total relation weight being greater than a given threshold K. In each gang, the one with maximum total weight is the head. Now given a list of phone calls, you are supposed to find the gangs and the heads.
Input Specification:
Each input file contains one test case. For each case, the first line contains two positive numbers N and K (both less than or equal to 1000), the number of phone calls and the weight threthold, respectively. Then N lines follow, each in the following format:
Name1 Name2 Time
where Name1
and Name2
are the names of people at the two ends of the call, and Time
is the length of the call. A name is a string of three capital letters chosen from A
-Z
. A time length is a positive integer which is no more than 1000 minutes.
Output Specification:
For each test case, first print in a line the total number of gangs. Then for each gang, print in a line the name of the head and the total number of the members. It is guaranteed that the head is unique for each gang. The output must be sorted according to the alphabetical order of the names of the heads.
Sample Input 1:
8 59
AAA BBB 10
BBB AAA 20
AAA CCC 40
DDD EEE 5
EEE DDD 70
FFF GGG 30
GGG HHH 20
HHH FFF 10
Sample Output 1:
2
AAA 3
GGG 3
Sample Input 2:
8 70
AAA BBB 10
BBB AAA 20
AAA CCC 40
DDD EEE 5
EEE DDD 70
FFF GGG 30
GGG HHH 20
HHH FFF 10
Sample Output 2:
0
题目描述:
给出K个边组成的一些图,找出满足条件的连通图和该连通图中满足条件的点。思路:并查集
代码:
class Union:
def __init__(self):
self.dic = {}
self.clas = {}
self.index=0
def union(self, c0, c1, weight):
if len(self.clas[c0][0])> len(self.clas[c1][0]):
c0, c1 = c1, c0
for idi in list(self.clas[c0][0]):
self.dic[idi][0]= c1
self.clas[c1][0] = self.clas[c1][0].union(self.clas[c0][0])
self.clas[c1][1] += (self.clas[c0][1] + weight)
self.clas.pop(c0)
def insert(self, id0, id1, weight):
a0 = self.dic.get(id0, [None, 0])[0]
a1 = self.dic.get(id1, [None, 0])[0]
if a0 and a0==a1:
self.dic[id0][1] += weight
self.dic[id1][1] += weight
self.clas[a0][1] += weight
elif a0 and a1 and not a0 ==a1:
self.dic[id0][1] += weight
self.dic[id1][1] += weight
self.union(a0, a1, weight)
elif a0 and not a1:
self.dic[id0][1] += weight
self.dic[id1] = [a0, weight]
self.clas[a0][0].add(id1)
self.clas[a0][1] += weight
elif a1 and not a0:
self.dic[id0] = [a1, weight]
self.dic[id1][1] += weight
self.clas[a1][0].add(id0)
self.clas[a1][1] += weight
elif not a0 and not a1:
self.dic[id0] = [f"{self.index}", weight]
self.dic[id1] = [f"{self.index}", weight]
self.clas[f"{self.index}"] = [set([id0, id1]), weight]
self.index+=1
n, t = list(map(int, input().split()))
un = Union()
for i in range(n):
id0, id1, weight = input().split()
un.insert(id0, id1, int(weight))
ans=[]
for c, cm in un.clas.items():
if len(cm[0])>2 and cm[1]>t:
num = len(cm[0])
gang = list(cm[0])
k = max( gang, key = lambda x:un.dic[x])
ans.append(" ".join([k,str(num)]))
print(len(ans))
ans = sorted(ans)
for a in ans:
print(a)
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
题目描述:
给定二叉树的后序遍历和中序遍历,输出其层次遍历结果。思路通过后序遍历找到头节点,其在中序遍历中的位置将树分成左右子树。利用该性质递归的重建该树,层次遍历该树输出结果。
代码:
class Tree:
def __init__(self, val):
self.val = val
self.left= None
self.right=None
def rebuild(porder, iorder):
if not porder:
return None
node = Tree(porder[-1])
for i, r in enumerate(iorder):
if r == porder[-1]:
break
node.left = rebuild(porder[:i], iorder[:i])
node.right = rebuild(porder[i:len(porder)-1], iorder[i+1: len(porder)])
return node
n = int(input())
postorder = input().split()
inorder = input().split()
root = rebuild(postorder, inorder)
ans, l = [], [root]
while l:
for i in range(len(l)):
li = l.pop(0)
ans.append(li.val)
if li.left:
l.append(li.left)
if li.right:
l.append(li.right)
print(" ".join(ans))
1064 Complete Binary Search Tree 分数 30
A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties:
- The left subtree of a node contains only nodes with keys less than the node's key.
- The right subtree of a node contains only nodes with keys greater than or equal to the node's key.
- Both the left and right subtrees must also be binary search trees.
A Complete Binary Tree (CBT) is a tree that is completely filled, with the possible exception of the bottom level, which is filled from left to right.
Now given a sequence of distinct non-negative integer keys, a unique BST can be constructed if it is required that the tree must also be a CBT. You are supposed to output the level order traversal sequence of this BST.
Input Specification:
Each input file contains one test case. For each case, the first line contains a positive integer N (≤1000). Then N distinct non-negative integer keys are given in the next line. All the numbers in a line are separated by a space and are no greater than 2000.
Output Specification:
For each test case, print in one line the level order traversal sequence of the corresponding complete binary search tree. All the numbers in a line must be separated by a space, and there must be no extra space at the end of the line.
Sample Input:
10
1 2 3 4 5 6 7 8 9 0
Sample Output:
6 3 8 1 5 7 9 0 2 4
题解:
题目给出n个树,将这些数组成完全二叉树,且满足该树是BST,输出其层次遍历。由于完全二叉树的层次遍历索引从0开始满足,根节点是i时,左节点索引是2i+1,右节点索引是2i+2。所以若知道该树的一个遍历结果,模拟该遍历过程时就可以恢复层次遍历的结果。由于BST的中序遍历结果是排序后的数组,因此通过模拟中序遍历过程,在遍历中等到层次遍历时各节点的值。
代码 :
n = int(input())
line = list(map(int, input().split()))
line = sorted(line)
t, ans = 0, [0]*len(line)
def inorder(i):
if i>=n:
return -1
global t
inorder(2*i+1)
ans[i]=line[t]
t+=1
inorder(2*i+2)
inorder(0)
print(" ".join(list(map(str, ans))))