HNUCM-2023 Spring Semester "Algorithm Analysis and Design" Exercise 1

Keep a record of your own learning.


Question A: The Space of the X-Stars

I haven’t tried it several times with python debugging, and then I changed it to multiple sets of input to capture exceptions (my compiler can pass oj, but it may be the reason for input and output)


Title description:

One day, the X-stars and Y-stars played a game of grabbing territory on a rectangular map.
Every time an X-star person grabs a piece of land, mark an "X" at the corresponding position on the map; every time a Y-star person grabs a piece of land, mark a "Y" at the corresponding position on the map; if a certain piece of land cannot be determined, mark a "" N".
The final count of who owns the largest territory is to count the number of "X" and "Y". If the number of "X" is large, it means that the X star people have a larger territory, and output "X
win"; on the contrary, if the Y star people have a larger territory, then output "Y win"; if the sites owned by X star people and Y star people The same size, then output "The same".

enter

Single group input. Line 1 inputs two positive integers m and n, representing the rows and columns of the map matrix. (both m and n are not more than 1000)
From line 2 to line m+1, input a matrix consisting of three characters 'X', 'Y' and 'N', each line contains n characters, a total of m OK.

output

If the territory owned by the alien X is large, output "X win"; if the territory owned by the alien Y is large, output "Y win"; if the territory owned by the alien is the same size, output "The same".

a, b = 0, 0
while True:
    try:
        s = input()
        if s == '':
            break
        a += s.count('X')
        b += s.count('Y')
    except:
        break
if a == b:
    print('The same')
elif a > b:
    print('X win')
else:
    print('Y win')

Question B: X Star Dormitory

simple mock questions


Title description:

The dormitory of X Star University is very interesting. Boys have 6-person dorms, and girls have 5-person dorms.
Now the gender of N students is known, and the gender is represented by '0' or '1', where '0' means a boy and '1' means a girl.
Please write a program to calculate the minimum number of male dormitories needed? How many female dormitories are there? (Note: It is not required that every dormitory is full).

enter

Single group input. Enter N 0 or 1, separated by English spaces, and N does not exceed 1000.

output

Output two integers, which respectively represent the minimum number of male dormitories and female dormitories, separated by English spaces.

a = list(map(int, input().split()))
x = a.count(0)
y = a.count(1)
if x % 6 == 0:
    print(x // 6, end=' ')
else:
    print(x // 6 + 1, end=' ')
if y % 5 == 0:
    print(y // 5)
else:
    print(y // 5 + 1)

Question C: One Two Three

It has always been 50% and I don’t know why (the same method can be used in C++). Later, it was found that there were spaces in the sample input, and the function of removing spaces still failed.
The idea is very simple, just enumerate it.


topic description

Your brother has just learned to write one, two and three in English. He wrote a lot of 1, 2, 3 on the paper, but unfortunately some letters were wrong
. It is known that at most one letter of each word is wrong (the length of the word is definitely not wrong), can you recognize what he wrote?

enter

The first line is the number of words (no more than 10). Each of the following lines is a word, the word length is correct, and at most one letter is misspelled. All letters are lowercase.

output

For each set of test data, output a line, which is the Arabic numerals of the word. Input is guaranteed to have only one way to understand it.

def check(s):
   if len(s) == 5:
       return 3
   else:
       if (s[0] == 't' and s[1] == 'w') or (s[0] == 't' and s[2] == 'o') or (s[1] == 'w' and s[2] == '0'):
           return 2
       else:
           return 1


t = int(input())
num = [input().strip() for i in range(t)]   #  strip()函数去掉字符串前面和后面的空格
for word in num:
   print(check(word))

#include<iostream>
#include<string.h>
using namespace std;
int main()
{
    
    
   char c[10];
   int n;
   while(cin>>n)
   {
    
    
       for(int i=0;i<n;i++)
       {
    
    
           cin>>c;
           if(strlen(c)==5)
               cout<<3<<endl;
           else
           {
    
    
 
                   if((c[0]=='o'&&c[1]=='n')||(c[0]=='o'&&c[2]=='e')||(c[1]=='n'&&c[2]=='e'))
                       cout<<1<<endl;
                   else
                       cout<<2<<endl;
           }
       }
   }
   return 0;
}

Question D: Three families

Idea: first find the average number of days that each of the three wives of ABC should clean. The amount that Mrs. A deserves is the percentage of the number of days that Mrs. A helped Mrs. C clean to the number of days that Mrs. C should clean multiplied by the money paid by Mrs. C.
topic description

There are three families who have a garden in total, and the wives of each family need to help tidy up the garden. Mrs. A worked for 5 days, and Mrs. B worked for 4 days before finishing the garden. Mrs. C
paid 90 yuan because she was pregnant with Liujia and was unable to join them. May I ask how to distribute this money to the two wives A and B more appropriately? How much does A deserve?
90/(5+4)*5=50 yuan? If you think so, you are fooled! The correct answer is 60 yuan. If you haven't figured it out, think again. Let's answer a general question: Assuming that
Mrs. A worked x days, Mrs. B worked y days, and Mrs. C paid 90 yuan, how much should Mrs. A get? Input guarantees that both wives should receive non-negative integer yuan.

enter

Enter the number of data sets T ( T <= 20) in the first row. Each set of data has only one line, containing three integers x , y , z (1<= x , y <=10, 1<= z
<=1000).

output

For each set of data, output an integer, which is the amount that Mrs. A deserves (unit: yuan).

T = int(input())
for _ in range(T):
    a, b, c = map(float, input().split())
    average = (a+b) / 3  # 平均天数
    a1 = a - average  # A太太多做的天数
    s = a1/average*c
    print(int(s))


Problem E: Soda Bottles

Just look at the code comments.


topic description

There is such a puzzle: "A certain store stipulates that three empty soda bottles can be exchanged for one soda. Xiao Zhang has ten empty soda bottles, how many bottles of soda can she exchange at most?" The answer is 5 bottles, and the method is as follows : First exchange 9 empty bottles for 3 bottles of soda, drink 3 full bottles, after drinking 4 empty bottles, use 3 for another bottle, drink the full bottles, then there are 2 empty bottles left. Then you ask the boss to lend you a bottle of soda first, drink the full bottle, and then exchange 3 empty bottles for a full bottle and return it to the boss. If Xiao Zhang has n empty soda bottles in his hand, how many bottles of soda can he drink at most?

enter

The input file contains at most 10 sets of test data, each data occupies one line, and only contains a positive integer n (1<=n<=100), indicating the number of empty soda bottles in Xiao Zhang's hand. n=0 means the end of input, your program should not process this line.

output

For each set of test data, output a row indicating the maximum number of soda bottles that can be drunk. If you can't drink a bottle, output 0.

while True:
    try:
        n = int(input())
        if n == 0:
            break
        s = 0  # 最终兑换数量
        i = 0  # 兑换而来的汽水数量
        while n:
            if n == 1:
                break
            elif n == 2:
                s += 1
                break
            else:
                i = n // 3
                s += i
                n = n % 3 + i  # 兑换之后剩余的空瓶子
        print(s)
    except:
        break

Problem F: Number Divisibility

Due to the characteristics of the python language, it is possible to directly handle large number operations.


topic description

Theorem: Remove the unit digit of a positive integer with at least two digits, and then subtract 5 times the unit digit from the remaining number. The original number is also a multiple of 17 if and only if the difference is a multiple of 17.

例如,34是17的倍数,因为3-20=-17是17的倍数;201不是17的倍数,因为20-5=15不是17的倍数。输入   一个正整数n,你的任务是判断它是否是17的倍数。

enter

The input file contains at most 10 sets of test data, each data occupies one line, and only contains a positive integer n (1<=n<=10 to the 100th power), which represents the positive integer to be judged. n=0 means the end of input, your program should not process this line.

output

For each set of test data, output a row indicating whether the corresponding n is a multiple of 17. 1 means yes, 0 means no.

while True:
    n = int(input())
    if n == 0:
        break
    if n % 17 == 0:
        print(1)
    else:
        print(0)

Problem G: Super large LED display

Idea: Use a dictionary to store the unit power consumption represented by each number, then write a time function to calculate the seconds of two time periods, and then write a check function to calculate the total power consumption, which is simulation, see the code I get it. Pay attention to two boundary conditions, one is the beginning of the game and the first score, and the other is the time point of the last score and the end of the game, which need to be handled specially.


topic description

You are the Sports Minister of the Student Union, responsible for organizing the annual school basketball game. The final is coming soon, and you want to attract more people to watch the game, so you plan to update the equipment and use a large
LED screen to display the score. Of course, electricity is not free, so you decide to analyze the games of previous years and estimate how much electricity will be consumed. As shown in the figure above, each number
is composed of 7 line segments, and each lit line segment consumes 1 unit of power per second. No power consumption when the line segment is not lit. In order to save power, the score does not display the leading 0 (but the number 0 is displayed when the score is
0). Your LED display contains a total of 6 numbers, that is, the scores of both sides have 3 digits each.

score table

enter

The input contains no more than 100 sets of data. The first line of each set of data is "START hh:mm:ss", indicating that the start time of the game is hh:mm:ss. The last line is "END
hh:mm:ss", which is the end time of the game. There will be at least one SCORE information between the two, the format is "SCORE hh:mm:ss team
score", where team is either "home" (home) or "guest" (away), score means score, which is 1, 2 or
3. The information is guaranteed to be arranged in the order of time from early to late, and the time of any two SCORE messages is different. The game starts no earlier than
9:00 and ends no later than 21:00 on the same day. Note that if the match starts at 09:00:00 and ends at 09:00:01, the match length is
1 second, not 2 seconds.

output

For each set of data, output the test point number and total power consumption.

dist = {
    
    '0': 6,
        '1': 2,
        '2': 5,
        '3': 5,
        '4': 4,
        '5': 5,
        '6': 6,
        '7': 3,
        '8': 7,
        '9': 6}
def time(s1, s2):
    res1 = s1[1].split(':')
    res2 = s2[1].split(':')
    sec = 0
    sec += (int(res2[0]) - int(res1[0])) * 3600
    sec += (int(res2[1]) - int(res1[1])) * 60
    sec += (int(res2[2]) - int(res1[2]))
    return sec
def check(num):
    home, guest = 0, 0  # 得分
    res = 0  # 答案
    s = time(num[0], num[1])  # 秒数
    res += 2*(dist['0']*s)  # 开始和第一次得分
    for i in range(1, len(num)):
        if i + 1 == len(num) - 1:  # 最后一次得分和比赛结束
            s = time(num[i], num[i + 1])
            x, y = 0, 0
            for i in str(home):
                x += dist[i]
            for i in str(guest):
                y += dist[i]
            res += (x+y) * s
            break
        else:
            s = time(num[i], num[i + 1])
            x, y = 0, 0
            if num[i][2] == 'home':
                home += int(num[i][3])
                for i in str(home):
                    x += dist[i]
                for i in str(guest):
                    y += dist[i]
                res += (x+y) * s
            else:
                guest += int(num[i][3])
                for i in str(home):
                    x += dist[i]
                for i in str(guest):
                    y += dist[i]
                res += (x+y) * s
    return res
count = 0
while True:
    try:
        count += 1
        a = []
        while True:
            s = input().split(' ')
            if s[0] == 'END':
                a.append(s)
                break
            else:
                a.append(s)
        a.append(s)  # 防止列表越界,对结果并没有影响
        print(f'Case {
      
      count}: {
      
      check(a)}')
    except:
        break

Question H: The chat ends with hehe

Idea: Use a dictionary to store the last paragraph of the dialogue between two people (how to determine the two people speaking is reflected in the code), and then write a function to change the dialogue according to the requirements of the topic, and write a function to check whether the dialogue is qualified.


topic description

(Modern version) As the saying goes: Gossip ends with wise men, and chat ends with hehe. Enter a chat record, and your task is to count how many conversations "stop at hehe", that is, the last sentence of the conversation contains the word
hehe or its deformation. Specifically, we first extract the last sentence of the conversation, replace all non-alphabetic characters with spaces, replace all characters
with lowercase, and then export a list of words (separated by spaces), as long as any word in the list It's hehe, this conversation is counted as "stopping hehe". For example, "Hi! Are
you OK?" becomes four words: hi, are, you, ok. Note that the word list can be empty (for example, this sentence is: "?!?!!").
Some people like to use the variants of hehe, which should also be regarded as "huh". For the sake of simplicity, this question only considers words formed by connecting n (n>1) hes, such as
hehehe or hehehehe. Note that other words with hehe as continuous substrings should not be regarded as "呵呵", such as hehee, or ehehe.
All conversations between every two different people count as "one conversation".

enter

The input contains only one set of data, each line is a dialogue, the format is:

Name 1->Name 2: One sentence.

Each line can contain up to 1000 characters and a maximum of 100 lines.

output

Outputs the percentage of dialogue passages that "stop at huh", rounded to the nearest whole number. The input data guarantees that the answer will not be closest to two integers at the same time.

dist = {
    
    }
def check(s):
   if len(s) % 2 != 0:
       return False
   for i in range(0, len(s), 2):
       new_s = s[i:i + 2:]
       if new_s != 'he':
           return False
   return True
def f(s):
   new_word = ''
   s = s.lower()
   for i in range(len(s)):
       if not s[i].isalpha():
           new_word += ' '
       else:
           new_word += s[i]
   return new_word.split()
while True:
   try:
       people, word = input().split(': ')
       s = people.split('->')
       if s[0] > s[1]:
           s[0], s[1] = s[1], s[0]
       t = ''.join(s)
       if t not in dist:
           dist[t] = f(word)
       else:
           dist[t] = f(word)
   except:
       # print(dist)
       count = 0
       sum_word = len(dist)
       for word in dist.values():
           for words in word:
               if check(words) and len(words) >= 4:
                   count += 1
       res = count * 100 / sum_word
       print("%.f" % res + '%')
       break

Summarize

There is no algorithm for the questions, they are all thinking questions and simulations based on the meaning of the questions.

Guess you like

Origin blog.csdn.net/weixin_62988040/article/details/129323700