2021阿里笔试(8.16)

第一题

题目描述

牛牛刚学完C语言,他现在想自己写一个编译器,这个编译器的功能很简单:计算出一行变量定义代码中所有变量占用的字节数。

现在已知:

——单个int变量占用4字节

——单个long变量占用8字节

——单个char变量占用1字节

如,对于一行代码:

int a[20] [20],b,xyz;

占用的字节数为(20 ×20+1+1)×4=1608

输入描述

输入一行字符串S,S.length<=200,S的格式为:(int | long | char) + 空格(一个)+变量1,变量2,……,变量k;

输入的S保证不会存在语法错误。

输出描述

返回字节数

解题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
line=list(input().split())
str=list(line[1].split(','))
mul={'long':8,'int':4,'char':1}

def cal(str):
res1,res2=[],[]
for i,s in enumerate(str):
if s=='[':
res1.append(i)
elif s==']':
res2.append(i)

res=1
for x,y in zip(res1,res2):
res*=int(str[x+1:y])
return res

cnt=0
for s in str:
if s.find('[')!=-1:
cnt+=cal(s)
else:
cnt+=1

res=mul[line[0]]*cnt

print(res)

第二题

部队结盟,题目太长了懒得写,用并查集做

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
class UnionFind(object):
def __init__(self, n,nums):
self.uf = [-1 for i in range(n + 1)]
self.sig = [i for i in range(n+1)] #最小编号
self.pop=[n for n in nums] #人数

def find(self, p):
if self.uf[p] < 0:
return p
self.uf[p] = self.find(self.uf[p])
return self.uf[p]

def find_sig(self,p):
if self.find(p)==p:
return self.sig[p]+1
return self.sig[self.find(p)]+1

def find_pop(self,p):
if self.find(p)==p:
return self.pop[p]
return self.pop[self.find(p)]

def union(self, p, q):
proot = self.find(p)
qroot = self.find(q)
if proot == qroot:
return
elif self.uf[proot] > self.uf[qroot]:
self.uf[qroot] += self.uf[proot]
self.uf[proot] = qroot
else:
self.uf[proot] += self.uf[qroot]
self.uf[qroot] = proot
self.sig[self.find(p)]=min(p,q)
self.pop[self.find(p)]=self.find_pop(p)+self.find_pop(q)



def is_connected(self, p, q):
return self.find(p) == self.find(q)


n,m=map(int,input().split())
nums=[int(i) for i in input().split()]
uf=UnionFind(n,nums)

for _ in range(m):
t,a,b = map(int,input().split())
a-=1
b-=1
if t==1:
if not uf.is_connected(a,b):
money = (uf.find_sig(a)+uf.find_sig(b)) ^ abs(uf.find_pop(a) - uf.find_pop(b))
uf.union(a,b)

print(money)
if t==2:
if uf.is_connected(a,b):
print('YES')
else:
print('NO')
不要打赏,只求关注呀QAQ