Programming exercise on 14 August

A.Zero Sum Game

The sum of the NN people’s score is always 00. Denoting by ANA_N the score of person NN, we have A1+A2++AN1+AN=0A_1+A_2+ \cdots +A_{N−1}+A_N=0, so AN=(A1+A2++AN1)A_N=−(A_1+ A_2+ \cdots +A_{N−1}).

It is sufficient to receive the scores of the (N1)(N−1) people, find the sum, multiply it by 1−1, and print the result.

N = int(input())
A = list(map(int, input().split()))
print(-sum(A))

B

First, we count the occurrences of each character in SS. Prepare a length-2626 array cntcnt; for i=1,2,,26i=1,2,\cdots,26, let cnt[i]cnt[i]= (the number of occurrences of the ii-th character of the alphabet in SS).

Next, for each integer ii greater than or equal to 11, we inspect the number of occurrences of ii in cntcnt. Prepare a length-100100 array cnt2cnt2; for i=1,2,,100i=1,2,\cdots,100, let cnt2[i]cnt2[i]= (the number of occurrences of ii in cntcnt).

After filling these arrays, cnt2[i]cnt2[i] equals the number of distinct characters that occur exactly ii times in SS. Hence, one can answer the original problem by checking if all values of cnt2cnt2 are 00 or 22.

Sample code (Python)

S = input()
cnt = [0] * 26
for c in S:
    cnt[ord(c) - ord("a")] += 1
cnt2 = [0] * 101
for c in cnt:
    if c > 0:
        cnt2[c] += 1
print("Yes" if all(c in (0, 2) for c in cnt2) else "No")

C

Let SiS_i denote the ii-th character of SS, and TjT_j the jj-th character of TT.

First of all, capitalize all characters of SS.

If TT does not end with X, one can determine if TT is a substring of SS.

If TT ends with X, one can determine if the first two characters of TT is a substring of SS.

Finally, we describe how to determine if a string TT is a substring of SS. This can be achieved by corresponding each character of TT to a character of SS, greedily from the left, and checking if it succeeds to the end of TT. More formally, it can be determined by the following greedy algorithm:

  1. Initialize k1k\leftarrow1.
  2. For each j=1,2,,Tj=1,2,\cdots,|T|, do the following:
    1. If there is no ii such that Si=TjS_i=T_j and kiSk \le i \le |S|, return No and terminate.
    2. If there is a conforming ii, let ii′ be the smallest one. Setki+1 k \leftarrow i′+1
  3. Return Yes and terminate.

Sample code (Python)

s = input() + 'x'
t = input()

p = 0
indexes = []
for c in t.lower():
    a = s.find(c, p)
    p = a + 1
    indexes.append(a)

i, j, k = indexes

ans = 'Yes' if (i < j < k) else 'No'

print(ans)