ACM竞赛试题

合集下载

计算机acm试题及答案

计算机acm试题及答案

计算机acm试题及答案一、选择题1. 在计算机科学中,ACM代表什么?A. 人工智能与机器学习B. 计算机辅助制造C. 计算机辅助设计D. 国际计算机学会答案:D2. 下列哪个不是计算机程序设计语言?A. PythonB. JavaC. C++D. HTML答案:D3. 在计算机系统中,CPU代表什么?A. 中央处理单元B. 计算机辅助设计C. 计算机辅助制造D. 计算机辅助教学答案:A二、填空题1. 计算机的内存分为__________和__________。

答案:RAM;ROM2. 在编程中,__________是一种用于存储和操作数据的数据结构。

答案:数组3. 计算机病毒是一种__________,它能够自我复制并传播到其他计算机系统。

答案:恶意软件三、简答题1. 请简述计算机操作系统的主要功能。

答案:计算机操作系统的主要功能包括管理计算机硬件资源,提供用户界面,运行应用程序,以及控制其他系统软件和应用软件的运行。

2. 什么是云计算,它与传统的本地计算有何不同?答案:云计算是一种通过互联网提供计算资源(如服务器、存储、数据库、网络、软件等)的服务模式。

与传统的本地计算相比,云计算允许用户按需获取资源,无需购买和维护物理硬件,具有更高的灵活性和可扩展性。

四、编程题1. 编写一个程序,计算并输出从1到100(包括1和100)之间所有偶数的和。

答案:```pythonsum = 0for i in range(1, 101):if i % 2 == 0:sum += iprint(sum)```2. 给定一个字符串,编写一个函数,将字符串中的所有字符按ASCII 码值排序并返回。

答案:```pythondef sort_string(s):return ''.join(sorted(s))```五、论述题1. 论述计算机硬件和软件之间的关系及其对计算机系统性能的影响。

答案:计算机硬件是计算机系统的物质基础,包括CPU、内存、硬盘等,而软件则是运行在硬件上的程序和数据。

计算机学院ACM设计大赛初赛试题

计算机学院ACM设计大赛初赛试题

计算机学院ACM设计大赛初赛试题问题一:给定一个N位的二进制串b1 b2 …bN-1 bN将该串做旋转,即将b1移到bN后面,得到一个新的二进制串:b2 …bN-1 bN b1对新的二进制串再做旋转,得二进制串b3 b4 …bN-1 bN b1 b2重复旋转操作操作,可得N个二进制串,对这N个串排序,可得一个N*N的矩阵问:给定这种矩阵的最后一列,求出矩阵的第一行。

对于上面的例子,给出1 0 0 1 0,要你的程序输出0 0 0 1 1。

原题描述:Binary codesTime Limit: 1000MS Memory Limit: 65536KTotal Submissions: 4881 Accepted: 1847DescriptionConsider a binary string (b1…b N) with N binary digits. Given such a string, the matrix of Figure 1 is formed from the rotated versions of the string.b 1b2…b N−1b Nb 2b3…b N b1…b N−1b N…b N−3b N−2b N b1…b N−2b N−1Figure 1. The rotated matrixThen rows of the matrix are sorted in alphabetical order, where ‘0’ is before ‘1’. You are to write a program which, given the l ast column of the sorted matrix, finds the first row of the sorted matrix.As an example, consider the string (00110). The sorted matrix is0 0 0 1 10 0 1 1 00 1 1 0 01 0 0 0 11 1 0 0 0and the corresponding last column is (1 0 0 1 0). Given this last column your program should determine the first row, which is (0 0 0 1 1).InputThe first line contains one integer N≤ 3000, the number of binary digits in the binary string. The second line contains N integers, the binary digits in the last column from top to bottom.OutputThe first line contains N integers: the binary digits in the first row from left to right. Sample Input51 0 0 1 0Sample Output0 0 0 1 1问题二:某地的交通网由路口和公路构成:两个路口之间最多有一条公路,公路两个方向的行驶时间相同。

acm竞赛试题及答案

acm竞赛试题及答案

acm竞赛试题及答案ACM竞赛试题及答案1. 问题描述:给定一个整数数组,找出数组中没有出现的最小的正整数。

2. 输入格式:第一行包含一个整数n,表示数组的长度。

第二行包含n个整数,表示数组的元素。

3. 输出格式:输出一个整数,表示数组中没有出现的最小的正整数。

4. 样例输入:53 4 1 2 55. 样例输出:66. 问题分析:首先,我们需要理解题目要求我们找出数组中缺失的最小正整数。

这意味着我们需要检查数组中的每个元素,并确定最小的正整数是否在数组中。

7. 算法描述:- 遍历数组,使用一个哈希集合记录出现的数字。

- 从1开始,检查每个正整数是否在哈希集合中,直到找到不在集合中的最小正整数。

8. 代码实现:```pythondef find_missing_positive(nums):seen = set()for num in nums:if num <= 0:continuewhile num in seen or num > len(nums):num += 1seen.add(num)return min(set(range(1, len(nums) + 1)) - seen)```9. 测试用例:- 输入:[3, 4, -1, 1]- 输出:210. 答案解析:在给定的测试用例中,数组[3, 4, -1, 1]中没有出现的最小正整数是2。

这是因为-1不是正整数,所以可以忽略。

数组中已经出现了1和3,所以下一个最小的正整数就是2。

11. 注意事项:- 确保数组中的元素是整数。

- 考虑数组中可能包含0或负数的情况。

- 算法的时间复杂度应尽可能低。

12. 扩展思考:- 如果数组非常大,如何优化算法?- 如果数组中的元素可以是浮点数,算法应该如何修改?13. 参考答案:- 针对大数组,可以考虑使用更高效的数据结构,如平衡二叉搜索树。

- 如果元素是浮点数,需要先将其转换为整数,然后再进行处理。

acm大赛试题及答案

acm大赛试题及答案

acm大赛试题及答案ACM大赛试题及答案1. 题目一:字符串反转问题描述:编写一个程序,输入一个字符串,输出其反转后的字符串。

输入格式:输入包含一个字符串,字符串长度不超过100。

输出格式:输出反转后的字符串。

示例:输入:hello输出:olleh答案:```pythondef reverse_string(s):return s[::-1]input_string = input().strip()print(reverse_string(input_string))```2. 题目二:计算阶乘问题描述:编写一个程序,输入一个非负整数n,输出n的阶乘。

输入格式:输入包含一个非负整数n,n不超过20。

输出格式:输出n的阶乘。

示例:输入:5输出:120答案:```pythondef factorial(n):if n == 0:return 1else:return n * factorial(n - 1)n = int(input())print(factorial(n))```3. 题目三:寻找最大数问题描述:给定一个包含n个整数的数组,找出数组中的最大数。

输入格式:输入包含一个整数n,表示数组的大小,随后是n个整数。

输出格式:输出数组中的最大数。

示例:输入:5 1 2 3 4 5输出:5答案:```pythonn = int(input())numbers = list(map(int, input().split()))max_number = max(numbers)print(max_number)```4. 题目四:判断闰年问题描述:编写一个程序,输入一个年份,判断该年份是否为闰年。

输入格式:输入包含一个整数,表示年份。

输出格式:如果输入的年份是闰年,则输出"Yes",否则输出"No"。

示例:输入:2000输出:Yes答案:```pythonyear = int(input())if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):print("Yes")else:print("No")```5. 题目五:斐波那契数列问题描述:编写一个程序,输入一个非负整数n,输出斐波那契数列的第n项。

第三届ACM程序设计大赛试题new

第三届ACM程序设计大赛试题new

计算机工程学院第三届ACM程序设计大赛试题Problem A BridgeDescriptionn people wish to cross a bridge at night. A group of at most two people may cross at any time, and each group must have a flashlight. Only one flashlight is available among the n people, so some sort of shuttle arrangement must be arranged in order to return the flashlight so that more people may cross.Each person has a different crossing speed; the speed of a group is determined by the speed of the slower member. Your job is to determine a strategy that gets all n people across the bridge in the minimum time.InputThe first line of input contains n, followed by n lines giving the crossing times for each of the people. There are not more than 1000 people and nobody takes more than 100 seconds to cross the bridge. OutputThe first line of output must contain the total number of seconds required for all n people to cross the bridge. The following lines give a strategy for achieving this time. Each line contains either one or two integers, indicating which person or people form the next group to cross. (Each person is indicated by the crossing time specified in the input. Although many people may have the same crossing time the ambiguity is of no consequence.) Note that the crossings alternate directions, as it is necessary to return the flashlight so that more may cross. If more than one strategy yields the minimal time, any one will do.Sample Input(Input file: pa.txt)412510Sample Output171 215 1021 2Problem B LottoDescriptionIn the German Lotto you have to select 6 numbers from the set {1,2,...,49}. A popular strategy to play Lotto - although it doesn't increase your chance of winning - is to select a subset S containing k (k > 6) of these 49 numbers, and then play several games with choosing numbers only from S. For example, for k=8 and S = {1,2,3,5,8,13,21,34} there are 28 possible games: [1,2,3,5,8,13], [1,2,3,5,8,21],[1,2,3,5,8,34], [1,2,3,5,13,21], ... [3,5,8,13,21,34].Your job is to write a program that reads in the number k and the set S and then prints all possible games choosing numbers only from S.InputThe input will contain one or more test cases. Each test case consists of one line containing several integers separated from each other by spaces. The first integer on the line will be the number k (6 < k < 13). Then k integers, specifying the set S, will follow in ascending order. Input will be terminated by a value of zero (0) for k.OutputFor each test case, print all possible games, each game on one line. The numbers of each game have to be sorted in ascending order and separated from each other by exactly one space. The games themselves have to be sorted lexicographically, that means sorted by the lowest number first, then by the second lowest and so on, as demonstrated in the sample output below. The test cases have to be separated from each other by exactly one blank line. Do not put a blank line after the last test case.Sample Input(Input file: pb.txt)7 1 2 3 4 5 6 78 1 2 3 5 8 13 21 34Sample Output1 2 3 4 5 61 2 3 4 5 71 2 3 4 6 71 2 3 5 6 71 2 4 5 6 71 3 4 5 6 72 3 4 5 6 71 2 3 5 8 131 2 3 5 8 211 2 3 5 8 341 2 3 8 13 211 2 3 8 13 341 2 3 8 21 341 2 3 13 21 341 2 5 8 13 211 2 5 8 13 341 2 5 8 21 341 2 5 13 21 341 2 8 13 21 341 3 5 8 13 211 3 5 8 13 341 3 5 8 21 341 3 5 13 21 341 3 8 13 21 341 5 8 13 21 342 3 5 8 13 212 3 5 8 13 342 3 5 8 21 342 3 5 13 21 342 3 8 13 21 342 5 8 13 21 343 5 8 13 21 34Problem C EncryptChip and Dale have devised an encryption method to hide their (written) text messages. They first agree secretly on two numbers that will be used as the number of rows (R) and columns (C) in a matrix. The sender encodes an intermediate format using the following rules:1. The text is formed with uppercase letters [A-Z] and <space>.2. Each text character will be represented by decimal values as follows:<space> = 0, A = 1, B = 2, C = 3, ..., Y = 25, Z = 26The sender enters the 5 digit binary representation of the characters' values in a spiral pattern along the matrix as shown below. The matrix is padded out with zeroes (0) to fill the matrix completely. For example, if the text to encode is: "ACM" and R=4 and C=4, the matrix would be filled in as follows:A = 00001, C = 00011, M = 01101 (one extra 0)The bits in the matrix are then concatenated together in row major order and sent to the receiver. The example above would be encoded as: 0000110100101100Inputspace, and a string of binary digits that represents the contents of the matrix (R * C binary digits). The binary digits are in row major order.OutputFor each dataset, you should generate one line of output with the following values: The dataset number as a decimal integer (start counting at one), a space, and the decoded text message. You should throw away any trailing spaces and/or partial characters found while decoding.Sample Input(Input file: pc.txt)24 4 ACM5 2 HISample Output1 00001101001011002 0110000010Problem D ConnectionThere are N cities in the country and M bidirectional roads between the cities. The government wants to build some new roads such that for any pair of cities there is at least one path between them. Now you have to find out the minimal amount of roads that have to build.InputThe input may contain multiple test cases.For each test case, the first line is two integers N (1<=N<=100) and M (1<=M<=N*N/2),indicating the number of cities and the number of roads. Then the next M lines each contain two integers x and y (0<=x,y<n), meaning that there is a road between cities x and cities y.N=M=0 indicates the end of input.OutputFor each test case, print the answer in a single li ne.Sample Input(Input file: pd.txt)5 20 12 3Sample Output2Problem E GridlandBackgroundFor years, computer scientists have been trying to find efficient solutions to different computing problems. For some of them efficient algorithms are already available, these are the "easy" problems like sorting, evaluating a polynomial or finding the shortest path in a graph. For the "hard" ones only exponential-time algorithms are known. The traveling-salesman problem belongs to this latter group. Given a set of N towns and roads between these towns, the problem is to compute the shortest path allowing a salesman to visit each of the towns once and only once and return to the starting point.ProblemThe president of Gridland has hired you to design a program that calculates the length of the shortest traveling-salesman tour for the towns in the country. In Gridland, there is one town at each of the points of a rectangular grid. Roads run from every town in the directions North, Northwest, West, Southwest, South, Southeast, East, and Northeast, provided that there is a neighbouring town in that direction. The distance between neighbouring towns in directions North�CSouth or East�CWest is 1 unit. The length of the roads is measured by the Euclidean distance. For example, Figure 7 shows 2 �� 3-Gridland, i.e., a rectangular grid of dimensions 2 by 3. In 2 �� 3-Gridland, the shortest tour has length 6.Figure 7: A traveling-salesman tour in 2 �� 3-Gridland.InputThe first line contains the number of scenarios.For each scenario, the grid dimensions m and n will be given as two integer numbers in a single line, separated by a single blank, satisfying 1 < m < 50 and 1 < n < 50.OutputThe output for each scenario begins with a line containing "Scenario #i:", where i is the number of the scenario starting at 1. In the next line, print the length of the shortest traveling-salesman tour rounded to two decimal digits. The output for every scenario ends with a blank line.Sample Input(Input file: pe.txt)2Sample OutputScenario #1:4.00Scenario #2:6.00Problem F Digital RootsBackgroundThe digital root of a positive integer is found by summing the digits of the integer. If the resulting value is a single digit then that digit is the digital root. If the resulting value contains two or more digits, those digits are summed and the process is repeated. This is continued as long as necessary to obtain a single digit.For example, consider the positive integer 24. Adding the 2 and the 4 yields a value of 6. Since 6 is a single digit, 6 is the digital root of 24. Now consider the positive integer 39. Adding the 3 and the 9 yields 12. Since 12 is not a single digit, the process must be repeated. Adding the 1 and the 2 yeilds 3, a single digit and also the digital root of 39.InputThe input file will contain a list of positive integers, one per line. The end of the input will be indicated by an integer value of zero.OutputFor each integer in the input, output its digital root on a separate line of the output.Sample input(Input file: pf.txt)2439Sample Output63Problem G Counting NumbersStarting from a positive integer n (1<=n<=2001).On the left of the integer n ,you can place another integer m to form a new integer mn , where m must be less then or equal to half of the integer n ,If there is an integer k less then or equal to half of m, you can place integer k on the left of mn ,to form a new integer kmn,…,and so on .For Examole ,you can place 12 on the left of 30 to Form an integer 1230,and you can place 6 to the left of 1230 to form an integer 61230,…,and so onFor example , start from n=8.you can place integer 1,2,3and 4 to the left of 8 to get the integers 18,28,38,48.For number 18,you can not form a new integer using the procedure described as above.For number28 and 38,you can form new integers 128 and 138.For number 48 ,you can place 1 and 2 on the left of 48 to get new integers 148 and 248.For number 248,you can place 1 on the left of it to get a new integer 1248.In total, you can have the following 10 integers(includeing the integer you start with)8182838481281381482481248Give an integer n ,find the number of integers you can get using the procedure described above.InputAn integer nOutputAn integer witch represents the number of integer you can get.Sample input: (Input file: pg.txt)8Sample Output:10Problem H Buy Low, Buy LowerThe advice to "buy low" is half the formula to success in the stock market. But to be considered a great investor you must also follow this problems' advice:"Buy low, buy lower"That is, each time you buy a stock, you must purchase more at a lower price than the previous time you bought it. The more times you buy at a lower price than before, the better! Your goal is to see how many times you can continue purchasing at ever lower prices.You will be given the daily selling prices of a stock over a period of time. You can choose to buy stock on any of the days. Each time you choose to buy, the price must be lower than the previous time you bought stock. Write a program which identifies which days you should buy stock in order to maximize the number of times you buy.By way of example, suppose on successive days stock is selling like this:Day 1 2 3 4 5 6 7 8 9 10 11 12Price 68 69 54 64 68 64 70 67 78 62 98 87In the example above, the best investor (by this problem, anyway) can buy at most four times if they purchase at a lower price each time. One four day sequence (there might be others) of acceptable buys is:Day 2 5 6 10Price 69 68 64 62PROGRAM NAME: buylowInputLine 1: N (1 <= N <= 5000), the number of days for which stock prices are available.Line 2..etc: A series of N positive space-separated integers (which may require more than one line of data) that tell the price for that day. The integers will fit into 32 bits quite nicely.Outputthe length of the longest sequence of decreasing pricesSample input: (Input file: ph.txt)1268 69 54 64 68 64 70 67 78 62 98 87Sample Output:4注意事项:1、数据从文件输入,标准输出,注意输入文件名题中已经给出。

ACM竞赛试题集锦(2020年九月整理).doc

ACM竞赛试题集锦(2020年九月整理).doc

ACM竞赛试题集锦(2020年九⽉整理).doc取⽯⼦游戏Time Limit:1S Memory Limit:1000KTotal Submit:505 Accepted:90Description有两堆⽯⼦,数量任意,可以不同。

游戏开始由两个⼈轮流取⽯⼦。

游戏规定,每次有两种不同的取法,⼀是可以在任意的⼀堆中取⾛任意多的⽯⼦;⼆是可以在两堆中同时取⾛相同数量的⽯⼦。

最后把⽯⼦全部取完者为胜者。

现在给出初始的两堆⽯⼦的数⽬,如果轮到你先取,假设双⽅都采取最好的策略,问最后你是胜者还是败者。

Input输⼊包含若⼲⾏,表⽰若⼲种⽯⼦的初始情况,其中每⼀⾏包含两个⾮负整数a 和b,表⽰两堆⽯⼦的数⽬,a和b都不⼤于1,000,000,000。

Output输出对应也有若⼲⾏,每⾏包含⼀个数字1或0,如果最后你是胜者,则为1,反之,则为0。

Sample Input2 18 44 7Sample Output1跳蚤Time Limit:1S Memory Limit:1000KTotal Submit:198 Accepted:44DescriptionZ城市居住着很多只跳蚤。

在Z城市周六⽣活频道有⼀个娱乐节⽬。

⼀只跳蚤将被请上⼀个⾼空钢丝的正中央。

钢丝很长,可以看作是⽆限长。

节⽬主持⼈会给该跳蚤发⼀张卡⽚。

卡⽚上写有N+1个⾃然数。

其中最后⼀个是M,⽽前N个数都不超过M,卡⽚上允许有相同的数字。

跳蚤每次可以从卡⽚上任意选择⼀个⾃然数S,然后向左,或向右跳S个单位长度。

⽽他最终的任务是跳到距离他左边⼀个单位长度的地⽅,并捡起位于那⾥的礼物。

⽐如当N=2,M=18时,持有卡⽚(10, 15, 18)的跳蚤,就可以完成任务:他可以先向左跳10个单位长度,然后再连向左跳3次,每次15个单位长度,最后再向右连跳3次,每次18个单位长度。

⽽持有卡⽚(12, 15, 18)的跳蚤,则怎么也不可能跳到距他左边⼀个单位长度的地⽅。

ACM选拔赛试题

ACM选拔赛试题

ACM选拔赛试题
注意:程序文件命名为:Test+题号
1、已知四位数3025有一个特殊性质:它的前两位数30和后两位数25的和是55,而55的平方刚好等于该数(55*55=3025),编写一个程序求出所有的具有这种性质的四位数。

2、有的三位数很独特,它们每位上的数字互不相同且都不大于7,特别是十位数正好是百位数和个位数之差,编写程序求所有这样的三位数。

3、某电台组织一次智力竞赛,计划奖励30人。

准备了50件奖品,得一等奖者可得3件,二等奖可得2件,三等奖可得1件。

希望把所有奖品都发到获奖者手中,请编程找出所有的设奖方案(即各等奖各有多少人)。

4、修改31743的某一位数字,使之成为823的倍数。

5、在自然数中,各位数字之和的11倍正好等于自身的自然数只有一个,编写程序请找出这个自然数。

6、小明的妈妈是负责分发单位工资的。

为了使分发时有足够的零钞,同时又尽量不使每个人领到的钱太零碎。

每个月她都要计算出各种面值的钞票(100元、50元、20元、10元、5元、2元、1元)各需多少张。

假设每个人的工资都是整数元,你能否为她设计一个程序,从键盘输入10个人的工资,再计算各种面值的钞票各需多少张?
7、4名专家对四款赛车进行评论:
A说:2号赛车是最好的。

B说:4号赛车是最好的。

C说:3号赛车不是最佳赛车。

D说:B说错了。

事实上,只有一款赛车最佳,且只有一名专家说对了,其他3人说错了,请编程输出最佳赛车的车号,以及哪一位专家说对了。

ACM软件大赛之编程大赛题目(附部分答案)

ACM软件大赛之编程大赛题目(附部分答案)

ACM软件大赛之编程大赛比赛注意事项:●比赛时间为3小时(180分钟);比赛分两个阶段:第一阶段限时30分钟,完成公示的3题,第二阶段限时150分钟(事先完成第一阶段题目的小组可提前进入第二阶段);●比赛第一阶段的3道题目将在前期宣传中告知参赛选手,比赛第二阶段的题目将由赛事主席当场公布竞赛题目;●前两阶段题目分为三个分值(5分、10分、15分),第一阶段3道公示题都为5分;第二阶段总共15道题,根据不同的难度分值不同,分别为5道5分题,5道10分题,5道15分题;第一阶段参赛队员不可参考任何相关资料;第二阶段参赛队员可以携带诸如书,手册,程序清单等参考资料。

比赛过程中队员不得携带任何电子媒质的资料;参赛者可以选择自己擅长的语言(C,C++,JAVA等等)进行编写●考虑到大一和大二学生的知识掌握程度,大一参加选手一开始就会有10分的分数,最后总分是由所做题目及初始的10分相加得到。

●每组队员根据安排使用电脑,小组人数为两人的使用一台电脑,超过两人的使用两台电脑,每台的电脑配置完全相同;●各小组每做完一题或几题,必须交予评委老师运行,评委老师当场给分;●如在比赛中发现作弊等行为,将取消比赛资格。

第一阶段公示题目:题目一:(5分)打印以下图形,纵遵从字母顺序,行字符数遵从斐波那契数列ABCCDDDEEEEEFFFFFFFFGGGGGGGGGGGGG#include<iostream>int f(int x){int a = 1 , b = 0;int max_ = x;int sum = 0;for(int i = 0; i < max_ ; i++){sum = a + b;a = b;b = sum;}return sum;}void loop_print(int num,char chr){for(int i = 0; i < num ;i++)std::cout<<chr;std::cout<<"\n";}int main(){int line_max = 7;char chr = 'A';for(int line = 0; line < line_max; line++){loop_print(f(line+1),chr);chr++;}return 0;}题目二:(5分)有个电子钟,12点显示为12:00(即12小时制),那么请问一天24时间内,出现连续3个相同数字的钟点有几个?#include<iostream>using namespace std;bool check(int time){int h=time/100;int m=time-100*h;return h<=12&&m<=59&&h>0?true:false;//12小时制}int main(){int time=0;int j(0);//总计数器while(time<1270){//max 12:59int t=time;int n[4];for(int i=0;i<4;i++){n[i]=t%10;t /= 10;}if(n[1]==n[2]&&(n[0]==n[1]||n[3]==n[1])&&check(time)){//cout<<n[3]<<n[2]<<":"<<n[1]<<n[0]<<"\n";//testj++;}time++;}cout<<"total: "<<j*2<<endl;}题目三:(5分)10进制的四位数中有几个符合如下特征:将其分别表示为16进制、10进制、12进制,在每种状态下,分别将各个位上的数相加,能得到3个相等10进制数。

ACM比赛试题

ACM比赛试题

The 35th ACM-ICPC Asia Regional Contest (Hangzhou)Contest SectionOctober 24, 2010Sponsored by IBM & AlibabaZhejiang Sci-Tech UniversityThis problem set should contain 10 problems on numbered 24 pages. Please inform a runner immediately if something is missing from your problem set.Problem A. Naughty fairiesDescriptionOnce upon a time, there lived a kind of fairy in the world. Those fairies could hear the voice of fruit trees, and helped people with a harvest. But people did n’t know that fruits are also those fairies’ favorite food. After the fairies ate people’s fruits, they always did something to cover it up.One day a little fairy named Lily flew into an orchard and found a large peach tree. Hungry as Lily was, she started eating without thinking until her stomach was full. In the fairy world, when a fairy ate the fruits in a fruit tree, sometimes the fruit tree would feel honored and bore more fruits immediately. That’s why sometimes the number of fruits in a tree got increased after a fairy ate fruits of that tree.But the fairies didn’t want people to find out weird things such as fruits become more or less suddenly. Lily decided to use a magic spell so that the orchard owner couldn’t find the change of the number of p eaches.Suppose there were N peaches on a tree originally and there were M peaches left after Lily was full. M may be greater than, less than or equal to N. All M peaches were visible at first, and Lily wanted to make an illusion so that exactly N peaches are visible.Lily can do 3 kinds of spell to change the total visible number of peaches:1) “PAPADOLA”:This spell would increase the number of visible peaches by one.2) “EXPETO POTRONUM”:This spell would double the number of visible peaches.3) “SAVIDA LOHA”:This spell would decrease the number of visible peaches by one. Each spell would take one minute and Lily wanted to finish as fast as possible. Now please tell Lily the least time she needs to change the number of visible peaches to N.InputThere are several test cases, ended by “0 0”.For each test case, there are only one line containing two numbers separated by a blank, N and M, the original numbers of peaches and the numbers of peaches left(0<N,M<10500).There is no leading zero.OutputFor each test case, you should output just a number K indicating the minimum time (in minutes) Lily needed to finish her illusion magic.Sample Input5 21 9986 320 0Sample Output29812Problem B. Prison BreakDescriptionRompire is a robot kingdom and a lot of robots live there peacefully. But one day, the king of Rompire was captured by human beings. His thinking circuit was changed by human and thus became a tyrant. All those who are against him were put into jail, including our clever Micheal#1. Now it’s time to escape, but Micheal#1 needs an optimal plan and he contacts you, one of his human friends, for help.The jail area is a rectangle contains n×m little grids, each grid might be one of the following:1) Empty area, represented by a capital letter ‘S’.2) The starting position of Micheal#1, represented by a capital letter ‘F’.3) Energy pool, represented by a capital letter ‘G’. When entering a n energy pool, Micheal#1 can use it to charge his battery ONLY ONCE. After the charging, Micheal#1’s batt ery will become FULL and the energy pool will become an empty area. Of course, passing an energy pool without using it is allowed.4) Laser sensor, represented by a capital letter ‘D’. Since it is extremely sensitive, Micheal#1 cannot step into a grid with a laser sensor.5) Power switch, represented by a capital letter ‘Y’. Once Micheal#1 steps into a grid with a Power switch, he will certainly turn it off.In order to escape from the jail, Micheal#1 need to turn off all the power switches to stop the electric web on the roof—then he can just fly away. Moving to an adjacent grid (directly up, down, left or right) will cost 1 unit of energy and only moving operation costs energy. Of course, Micheal#1 cannot move when his battery contains no energy.The larger the battery is, the more energy it can save. But larger battery means more weight and higher probability of being found by the weight sensor. So Micheal#1 needs to make his battery as small as possible, and still large enough to hold all energy he need. Assuming that the size of the battery equals to maximum units of energy that can be saved in the battery, and Micheal#1 is fully charged at the beginning, Please tell him the minimum size of the battery needed for his Prison break.InputInput contains multiple test cases, ended by 0 0. For each test case, the first line contains two integer numbers n and m showing the size of the jail. Next n lines consist of m capital letters each, which stands for the description of the jail.You can assume that 1<=n,m<=15, and the sum of energy pools and power switches is less than 15.OutputFor each test case, output one integer in a line, representing the minimum size of the battery Micheal#1 needs. If Micheal#1 can’t escape, output -1.Sample Input5 5GDDSSSSSFSSYGYSSGSYSSSYSS0 0Sample Output4Problem C. To Be an Dream Architect DescriptionThe “dream architect” is the key role in a team of “dream extractors” who enter other’s dreams to steal secrets. A dream architect is responsible for crafting the virtual world that the team and the target will dream into. To avoid the target noticing the world is artificial, a dream architect must have powerful 3D imagination.Cobb uses a simple 3D imagination game to test whether a candidate has the potential to be an dream architect. He lets the candidate imagine a cube consisting of n×n×n blocks in a 3D coordinate system as Figure 1. The block at bottom left front corner is marked (1, 1, 1) and the diagonally opposite block is marked (n, n, n). Then he tells the candidate that the blocks on a certain line are eliminated. The line is always parallel to an axis. After m such block eliminations, the candidate is asked to tell how many blocks are eliminated. Note that one block can only be eliminated once even if it is on multiple lines.Here is a sample graph according to the first test case in the sample input:InputThe first line is the number of test cases.In each test case, the first line contains two integers n and m( 1 <= n <= 1000, 0 <= m <= 1000).,meaning that the cube is n x n x n and there are m eliminations.Each of the following m lines represents an elimination in the following format:axis_1=a, axis_2=bwhere axis_i (i=1, 2) is ‘X’ or ‘Y’, or ‘Z’ and axis_1 is not equal to axis_2. a and b ar e 32-bit signed integers.OutputFor each test case output the number of eliminated blocks.Sample Input23 2Y=1,Z=3X=3,Y=110 2X=3,Y=3Y=3,Z=3Sample Output519Problem D. GomokuDescriptionYou are probably not familiar with the title, “Gomoku”, but you must have played it a lot. Gomoku is an abstract strategy board game and is also called Five in a Row, or GoBang. It is traditionally played with go pieces (black and white stones) on a go board (19x19 intersections). Nowadays, standard chessboard of Gomoku has 15x15 intersections. Black plays first, and players alternate in placing a stone of their color on an empty intersection. The winner is the first player to get an unbroken row of five or more stones horizontally, vertically, or diagonally.For convenience, we coordinate the chessboard as illustrated above. The left-bottom intersection is (0,0). And the bottom horizontal edge is x-axis, while the left vertical line is y-axis.I am a fan of this game, actually. However, I have to admit t hat I don’t have a sharp mind. So I need a computer program to help me. What I want is quite simple. Given a chess layout, I want to know whether someone can win within 3 moves, assuming both players are clever enough. Take the picture above for example. There are 31 stones on it already, 16 black ones and 15 white ones. Then we know it is white turn. The white player must place a white stone at (5,8). Otherwise, the black player will win next turn. After that, however, the white player also gets a perfect situation that no matter how his opponent moves, he will win at the 3rd move.So I want a program to do similar things for me. Given the number of stones and positions of them, the program should tell me whose turn it is, and what will happen within 3 moves.InputThe input contains no more than 20 cases.Each case contains n+1 lines which are formatted as follows.nx1 y1 c1x2 y2 c2......x n y n c nThe first integer n indicates the number of all stones. n<=222 which means players have enough space to place stones. Then n lines follow. Each line contains three integers: x i and y i and c i. x i and y i are coordinates of the stone, and ci means the color of the stone. If c i=0 the stone is white. If c i=1 the stone is black. It is guaranteed that 0<=x i,y i<=14, and c i=0 or 1. No two stones are placed at the same position. It is also guaranteed that there is no five in a row already, in the given cases.The input is ended by n=0.OutputFor each test case:First of all, the program should check whose turn next. Le t’s call the player who will move next “Mr. Lucky”. Obviously, if the number of the black stone equals to the number of white, Mr. Lucky is the black player. If the number of the black stone equals to one plus the numbers of white, Mr. Lucky is the white player. If it is not the first situation or the second, print “Invalid.”A valid chess layout leads to four situations below:1)Mr. Lucky wins at the 1st move. In this situation, print :Place TURN at (x,y) to win in 1 move.“TURN” must be replaced by “black” or “white” according to the situation and (x,y) is the position of the move. If there are different moves to win, choose theone where x is the smallest. If there are still different moves, choose the one where y is the smallest.2)Mr. Lucky’s opp onent wins at the 2nd move. In this situation, print:Lose in 2 moves.3)Mr. Lucky wins at the 3rd move. If so, print:Place TURN at (x,y) to win in 3 moves.“TURN” should replaced by “black” or “white”, (x,y) is the position where the Mr.Lucky should place a stone at the 1st move. After he place a stone at (x,y), no matter what his opponent does, Mr. Lucky will win at the 3rd step. If there are multiple choices, do the same thing as described in situation 1.4)Nobody wins within 3 moves. If so, print:Cannot win in 3 moves.Sample Input313 3 13 4 03 5 03 6 04 4 14 5 14 7 05 3 05 4 05 5 15 6 15 7 15 9 16 4 16 5 16 6 06 7 16 8 06 9 07 5 17 6 07 7 17 8 17 9 08 5 08 6 18 7 08 8 18 9 09 7 110 8 017 7 117 7 0Sample OutputPlace white at (5,8) to win in 3 moves. Cannot win in 3 moves.Invalid.Problem E. GunshotsDescriptionPresident Bartlet was shot! A group of terrorists shot to the crowd when President Bartlet waved to cheering people after his address. Many people were shot by the irrational bullets. Senior FBI agent Don Epps takes responsibility for this case. According to a series of crime scene investigation, including analyzing shot shells, replaying video from closed-circle television and collecting testimony by witnesses, Don keeps all the information about where and how the terrorists shot to crowd, as well as the location of every single person when the gun shoot happened. Now he wants to know how many gunshot victims are there in this case.Imagine that each target person can be regarded as a polygon (can be concave or self-intersecting) and each gunshot can be regarded as a half-line. The bullet will be stopped by the first person it shoots. A person can be shot in three ways:To simplify the problem, we assume that any two polygons can be completely separated by a line. Also each start point of the gunshot can be separated from each polygon by a line. Now given M people and N gunshots, please work out which person has been shot by each bullet.InputThere are multiple test cases in the input. The first line of the input file is an integer T demonstrating the number of test cases. (T<=10).For each test case, the first line is an integer N, representing the number of people (polygons). Following lines demonstrates the polygons. For the i th polygon (0<=i<N), the first line is an integer Q i , representing the number of edges of this polygon. In each of the following Q i lines, there are two real numbers x i and y i representing a point. Every pair of adjacent points demonstrate an edge of this polygon (i.e. (x i , y i ) to (x i+1, y i+1) is an edge, in which 0<=i<Q i -1), and (x Qi-1, y Qi-1) to (x 0, y 0) also demonstrates an edge of this polygon.PersonPerson Person 1. Normal shot 2. The bullet’s path isparallel to an edge 3. The bullet’s path is tangent to an vertexThen there is a line contains an integer M representing the number of gunshots. In the following M lines, each line contains four real numbers x, y, dx and dy, representing the start point (x, y) and direction vector (dx, dy) of that gunshot.In all test cases, we assume that 0< N<=100, 0<Q i<=1000, 0<M<=10000.OutputFor each test case, output contains M lines and the i th line demonstrates the result of the i th gunshot.If the i th gunshot shoots the j th polygon, the i th line contains “HIT j”, otherwise it contains a word “MISS” (means that it does not shoot any target). The polygons are numbered in the order of their appearance in the input file, and the numbers start from 0.At the end of each test case, please output a single line with “*****”.Sample Input1140 01 10 11 02-1 0 1 0-2 0 -1 0Sample OutputHIT 0MISS*****HintThe figure of the first case in the samples is as follows:Problem F. Rotational PaintingDescriptionJosh Lyman is a gifted painter. One of his great works is a glass painting. He creates some well-designed lines on one side of a thick and polygonal glass, and renders it by some special dyes. The most fantastic thing is that it can generate different meaningful paintings by rotating the glass. This method of design is called “Rotatio nal Painting (RP)” which is created by Josh himself.You are a fan of Josh and you bought this glass at the astronomical sum of money. Since the glass is thick enough to put erectly on the table, you want to know in total how many ways you can put it so that you can enjoy as many as possible different paintings hiding on the glass. We assume that material of the glass is uniformly distributed. If you can put it erectly and stably in any ways on the table, you can enjoy it.More specifically, if the polygonal glass is like the polygon in Figure 1, you have just two ways to put it on the table, since all the other ways are not stable. However, the glass like the polygon in Figure 2 has three ways to be appreciated.Pay attention to the cases in Figure 3. We consider that those glasses are not stable.InputThe input file contains several test cases. The first line of the file contains an integer T representing the number of test cases.For each test case, the first line is an integer n representing the number of lines of the polygon. (3<=n<=50000). Then n lines follow. The i th line contains two real number x i and y i representing a point of the polygon. (x i, y i) to (x i+1, y i+1) represents a edge of the polygon (1<=i<n), and (x n,y n) to (x1, y1) also represents a edge of the polygon. The input data insures that the polygon is not self-crossed.OutputFor each test case, output a single integer number in a line representing the number of ways to put the polygonal glass stably on the table.Sample Input240 0100 099 11 160 00 101 101 110 110 0Sample Output23HintThe sample test cases can be demonstrated by Figure 1 and Figure 2 in Description part.Problem G. Traffic Real Time Query System DescriptionCity C is really a nightmare of all drivers for its traffic jams. To solve the traffic problem, the mayor plans to build a RTQS (Real Time Query System) to monitor all traffic situations. City C is made up of N crossings and M roads, and each road connects two crossings. All roads are bidirectional. One of the important tasks of RTQS is to answer some queries about route-choice problem. Specifically, the task is to find the crossings which a driver MUST pass when he is driving from one given road to another given road.InputThere are multiple test cases.For each test case:The first line contains two integers N and M, representing the number of the crossings and roads.The next M lines describe the roads. In those M lines, the i th line (i starts from 1)contains two integers X i and Y i, representing that road i connects crossing X i and Y i (X i≠Y i).The following line contains a single integer Q, representing the number of RTQs. Then Q lines follows, each describing a RTQ by two integers S and T(S≠T) meaning that a driver is now driving on the road s and he wants to reach road t . It will be always at least one way from road s to road t.The input ends with a line of “0 0”.Please note that: 0<N<=10000, 0<M<=100000, 0<Q<=10000, 0<X i,Y i<=N, 0<S,T<=M OutputFor each RTQ prints a line containing a single integer representing the number of crossings which the driver MUST pass.Sample Input5 61 22 33 44 53 522 32 40 0Sample Output 01Problem H. National Day ParadeDescriptionThere are n×n students preparing for the National Day parade on the playground. The playground can be considered as a n×m grid. The coordinate of the west north corner is (1,1) , and the coordinate of the east south corner is (n,m).When training, every students must stand on a line intersection and all students must form a n×n square. The figure above shows a 3×8 playground with 9 students training on it. The thick black dots stand for the students. You can see that 9 students form a 3×3 square.After training, the students will get a time to relax and move away as they like. To make it easy for their masters to control the training, the students are only allowed to move in the east-west direction. When the next training begins, the master would gather them to form a n×n square again, and the position of the square doesn’t matter. Of course, no student is allowed to stand outside the playground.You are given the coordinates of each student when they are having a rest. Your task is to figure out the minimum sum of distance that all students should move to form a n×n square.InputThere are at most 100 test cases.For each test case:The first line of one test case contain two integers n,m. (n<=56,m<=200)Then there are n×n lines. Each line contains two integers, 1<=X i<=n,1<= Y i<=m indicating that the coordinate of the i th student is (X i , Y i ). It is possible for more than one student to stand at the same grid point.The input is ended with 0 0.OutputYou should output one line for each test case. The line contains one integer indicating the minimum sum of distance that all students should move to form a n×n square. Sample Input2 1682 1011 1271 1052 900 0Sample Output41Problem I. SearchlightsDescriptionThere is a piece of grids land of size n×m. Chandler and his team take responsibility to guard it. There are some searchlights on some pieces and each of them has a capability to lighten a distance towards four directions: north, south, east and west. Different searchlight has different lightening capability shown in levels. Searchlight with level k means that it can lighten k grids (including the gird that the searchlight stands in) along any of the four directions. Shown in following figure, there is a searchlight of level 3 and the shadow grids are ones that can be lightened by it. Particularly, searchlight of level 1 means that it can only lighten the grid in which the searchlight stands.Figure: A searchlight of Level 3Each searchlight has a maximum level. You can decrease a searchlight’s level to save the energy. A searchlight whose maximum level is k can be turned to level k, k-1, k-2, …, 1 and 0. Level 0 means turning off the searchlight.A grid is well-guarded if and only if at least one of the following two conditions is satisfied:1.There is a searchlight in this grid, and it is not switched to level 0 (the light is on).2.The grid is lightened by at least two searchlights. One lightens it in horizontaldirection (east or west), and another lightens it in vertical direction (north or south).Chandler asks you to help finding a solution that he can turn on some of the searchlights so that:1.All the grids are well-guarded.2.All the searchlights turned on are in a same level.3.That same level mentioned above is as small as possible.More specifically, if you choose a same level Q, then all the searchlights whose maximum level are less than Q have to be turned off. Please help him to find a solution with the minimum same level.InputThe input file contains several test cases.For each test case, the first line is two integers n and m, representing a grids land of size n×m. (0<n<=100, 0<m<=10000). Following n lines describe an n×m matrix in which a i,j means the maximum level of the searchlight in grid (i, j). a i,j can be zero, which means there is no searchlight on that grid. For all the cases, a i, j<=10000.The input file ends with a line containing two zeros.OutputFor each test case, output a single line with an integer, representing the minimum level you have found. If there is no such a solution, output “NO ANSWER!”Sampl e Input2 20 23 02 20 21 00 0Sampl e Output2NO ANSWER!Problem J. Infinite monkey theorem DescriptionCould you imaging a monkey writing computer programs? Surely monkeys are smart among animals. But their limited intelligence is no match for our human beings. However, there is a theorem about monkeys, and it states that monkeys can write everything if given enough time.The theorem is called “Infinite monkey theorem”. It states that a monkey hitting keys at random on a typewriter keyboard for an infinite amount of time will almost surely type any given text, which of course includes the programs you are about to write (All computer programs can be represented as text, right?).It’s very easy to prove this theorem. A little calculation will show you that if the monkey types for an infinite length of time the probability that the output contains a given text will approach 100%.However, the time used is too long to be physically reasonable. The monkey will not be able to produce any useful programs even if it types until the death of the universe. To verify this and ensure that our human beings are not replaceable by monkeys, you are to calculate the probability that a monkey will get things right.InputThere will be several test cases.Each test case begins with a line containing two integers n and m separated by a whitespace (2<=n<=26, 1<=m<=1000). n is the number of keys on the typewriter and the monkey will hit these keys m times. Thus the typewriter will finally produce an output of m characters.The following n lines describe keys on the typewriter. Each line has a lower case letter and a real number separated by a whitespace. The letter indicates what the typewriter will produce if the monkey hits that key and the real number indicates the probability that the monkey will hit this key. Two hits of the monkey are independent of each other (Two different hits have the same probability for a same key), and sum of all the probabilities for each key is ensured to be 1.The last line of the test case contains a word composed of lower case letters. The length of the word will be less than or equal to 10.The input will end with a line of two zeros separated by a whitespace. This line should not be processed.OutputFor each test case, output one line containing the probability that the given word will appear in the typewriter’s output. The output should be in percentage format and numbers should be rounded to two digits after the decimal point.Sampl e Input4 10w 0.25o 0.25r 0.25d 0.25word2 10a 1.0b 0.0abc2 100a 0.312345b 0.687655abab0 0Sampl e Output2.73%0.00%98.54%。

大一acm竞赛试题及答案

大一acm竞赛试题及答案

大一acm竞赛试题及答案一、选择题(每题5分,共20分)1. 下列哪个算法的时间复杂度为O(n^2)?A. 快速排序B. 归并排序C. 插入排序D. 冒泡排序答案:C2. 在C++中,下列哪个关键字用于定义类?A. structB. classC. unionD. enum答案:B3. 下列哪个数据结构适合用于实现稀疏矩阵?A. 顺序存储B. 链式存储C. 压缩存储D. 散列存储答案:C4. 在图论中,下列哪个算法用于寻找最短路径?A. 深度优先搜索B. 广度优先搜索C. 迪杰斯特拉算法D. 弗洛伊德算法二、填空题(每题5分,共20分)1. 在二叉树的遍历算法中,______遍历会先访问根节点。

答案:前序2. 哈希表的冲突解决方法之一是______。

答案:链地址法3. 在数据库中,用于实现一对多关系的表结构是______。

答案:外键4. 动态规划算法的核心是______。

答案:状态转移方程三、编程题(每题30分,共60分)1. 编写一个函数,实现对一个整数数组进行排序,并返回排序后的数组。

答案:```pythondef sort_array(arr):arr.sort()return arr```2. 编写一个函数,实现计算给定整数n的阶乘。

答案:```pythondef factorial(n):if n == 0:return 1return n * factorial(n - 1)```四、算法题(每题30分,共30分)1. 给定一个整数数组,请设计一个算法找出数组中第二大的数。

答案:```pythondef find_second_max(nums):first_max = second_max = float('-inf')for num in nums:if num > first_max:second_max = first_maxfirst_max = numelif num > second_max and num != first_max:second_max = numreturn second_max```。

acm数学竞赛试题及答案

acm数学竞赛试题及答案

acm数学竞赛试题及答案# 题目一:数列问题问题描述:给定一个数列 \( a_1, a_2, a_3, \ldots, a_n \),数列中每个元素都是正整数,且满足 \( a_i = a_{i-1} + a_{i-2} \) 对于所有\( i \geq 3 \)。

如果 \( a_1 = 1 \) 且 \( a_2 = 1 \),请找出数列的第 \( n \) 项。

解答:根据题意,这是一个斐波那契数列。

第 \( n \) 项的值可以通过递归关系计算得出。

对于 \( n \) 的值,可以使用以下递归公式:\[ a_n = a_{n-1} + a_{n-2} \]其中,\( a_1 = 1 \) 和 \( a_2 = 1 \)。

因此,数列的前几项为 1, 1, 2, 3, 5, 8, 13, 21, ...。

对于任意的 \( n \),可以通过递归或动态规划方法计算出 \( a_n \)。

# 题目二:组合问题问题描述:从 \( n \) 个不同的元素中选择 \( k \) 个元素的所有可能组合的个数是多少?解答:这个问题可以通过组合数学中的二项式系数来解决。

从 \( n \) 个不同元素中选择 \( k \) 个元素的组合数 \( C(n, k) \) 可以用以下公式计算:\[ C(n, k) = \frac{n!}{k!(n-k)!} \]其中,\( n! \) 表示 \( n \) 的阶乘。

# 题目三:几何问题问题描述:在一个直角坐标系中,给定三个点 \( A(x_1, y_1) \),\( B(x_2, y_2) \) 和 \( C(x_3, y_3) \)。

如果 \( \overrightarrow{AB} \) 和 \( \overrightarrow{AC} \) 是垂直的,求证 \( A \) 是直角三角形 \( ABC \) 的直角顶点。

解答:如果 \( \overrightarrow{AB} \) 和 \( \overrightarrow{AC} \) 垂直,那么它们的数量积(点积)应该为零。

ACM程序设计竞赛例题

ACM程序设计竞赛例题

ACM程序设计竞赛例题备战ACM资料习题1. 0-1背包问题在0 / 1背包问题中,需对容量为c 的背包进行装载。

从n 个物品中选取装入背包的物品,每件物品i 的重量为wi ,价值为pi 。

对于可行的背包装载,背包中物品的总重量不能超过背包的容量,最佳装载是指所装入的物品价值最高。

程序如下:#includevoid readdata();void search(int);void checkmax();void printresult();int c=35, n=10; //c:背包容量;n:物品数int w[10], v[10]; //w[i]、v[i]:第i件物品的重量和价值int a[10], max; //a数组存放当前解各物品选取情况;max:记录最大价值//a[i]=0表示不选第i件物品,a[i]=1表示选第i件物品int main() {readdata(); //读入数据search(0); //递归搜索printresult();}void search(int m){if(m>=n)checkmax(); //检查当前解是否是可行解,若是则把它的价值与max 比较else{a[m]=0; //不选第m件物品search(m+1); //递归搜索下一件物品a[m]=1; //不选第m件物品search(m+1); //递归搜索下一件物品}}void checkmax(){int i, weight=0, value=0;for(i=0;i<n;i++)< p="">{if(a[i]==1) //如果选取了该物品{weight = weight + w[i]; //累加重量value = value + v[i]; //累加价值}}if(weight<=c) //若为可行解if(value>max) //且价值大于maxmax=value; //替换max}void readdata(){int i;for(i=0;i<n;i++)< p="">scanf("%d%d",&w[i],&v[i]); //读入第i件物品重量和价值}void printresult(){printf("%d",max);}2.装载问题有两艘船,载重量分别是c1、c2,n个集装箱,重量是wi (i=1…n),且所有集装箱的总重量不超过c1+c2。

ACM试题

ACM试题

ACM试题1.开灯问题有n盏灯,编号为1-n。

第1个人把所有的灯打开,第二个人按下所有编号为2的倍数的开关(这些灯被关掉),第3个人按下所有边后卫3的倍数的开关(其中关掉的灯将被打开,打开的灯将被关闭),以此类推。

一共有k个人,问最后有哪些灯开着?输入:n和k,输出开着的灯的编号。

K≤n≤1000.样例输入:7 3样例输出:1 5 6 7测试数据样例输入:10 4样例输出:1 4 5 6 7 8样例输入:10 5样例输出:1 4 6 7 8 10样例输入:15 6样例输出:1 4 7 8 10 11 12 13 15源码:#include"stdio.h"#include"string.h"#define MAXN 1000+10int a[MAXN];int main(){int i,j,n,k,first=1;memset(a,0,sizeof(a));scanf("%d%d",&n,&k);for(i=1;i<=k;i++)for(j=1;j<=n;j++)if(j%i==0) a[j]=!a[j]; for(i=1;i<=n;i++)if(a[i]){if(first)first = 0;elseprintf(" ");printf("%d",i);}printf("\n");return 0;}2.蛇形填数在n*n方阵里填入1,2,3…..n*n,要求填成蛇形。

例如n=4时方阵为:10 11 12 19 16 13 28 15 14 37 6 5 4上面的方阵中,多余的空格只是为了便于观察规律,不必严格输出。

n≤8.样例输入:4样例输出:10 11 12 19 16 13 28 15 14 37 6 5 4测试数据样例输入:3样例输出:6 9 25 4 3样例输入:6样例输出:16 17 18 19 20 1153****221214 29 36 33 22 3132****423412 27 26 25 24 511 10 9 8 7 6源码:#include"stdio.h"#include"string.h"#define MAXN 10int a[MAXN][MAXN]; int main(){int n,x,y,tot=0;scanf("%d",&n);memset(a,0,sizeof(a));tot= a[x=0][y=n-1] = 1;while(tot<n*n)< p="">{while(x+1while(y-1>=0 && !a[x][y-1]) a[x][--y] = ++tot; while(x-1>=0 && !a[x-1][y]) a[--x][y] = ++tot; while(y+1<="">for(x=0;x<n;x++)< p="">{for(y=0;y<="">printf("\n");}return 0;}3.字母重排输入一个字典(用******结尾),然后再输入若干单词。

ACM程序设计竞赛例题[1]

ACM程序设计竞赛例题[1]

A C M程序设计竞赛例题[1]-CAL-FENGHAI.-(YICAI)-Company One1备战ACM资料习题1.0-1背包问题在0 / 1背包问题中,需对容量为c 的背包进行装载。

从n 个物品中选取装入背包的物品,每件物品i 的重量为wi ,价值为pi 。

对于可行的背包装载,背包中物品的总重量不能超过背包的容量,最佳装载是指所装入的物品价值最高。

程序如下:#include <>void readdata();void search(int);void checkmax();void printresult();int c=35, n=10; ");printf("\n");}printf("\n");}6.素数环问题把从1到20这20个数摆成一个环,要求相邻的两个数的和是一个素数。

分析:用回溯算法,考察所有可能的排列。

程序如下:#include <>#include <>void search(int);void init(); 表示空格;’X’表示墙。

程序如下:#include <>#include <>void search(int,int);int canplace(int,int);void readdata(); Floodfill给一个20×20的迷宫和一个起点坐标,用广度优先搜索填充所有的可到达的格子。

提示:参考第2题。

2. 电子老鼠闯迷宫如下图12×12方格图,找出一条自入口(2,9)到出口(11,8)的最短路本题给出完整的程序和一组测试数据。

状态:老鼠所在的行、列。

程序如下:#include<>void readdata();a[i][j]=0; ....注:测试数据可在运行时粘贴上去(点击窗口最左上角按钮,在菜单中选则“编辑”/“粘贴”即可)。

ACM程序大赛选拔初赛试题 - 参考答案

ACM程序大赛选拔初赛试题 - 参考答案
int size,i=1,a[100]={0}; scanf("%d",&size); for(int n=0;n<size;n++)
a[n]=n+1; int x=0; while(n>=1) {
if(a[i]!=0) {
if(x%2==0) { if(n==2) printf("\n"); printf("%d ",a[i]); n--; a[i]=0; } x++; } if(i+1>=size) i=0; else i++; } }
4、解方程 难度系数:★★☆☆☆
(注意此题只供 10 级的同学,08,09 级的同学请做第三题) 题意:形如 ax2+bx+c=d 的方程。其中 a,c,d 均为整数,b 为正整数。请你用计算机求出对 应的 x 的值(只考虑实数根)。
输入:依次输入 a,b,c,d 的值。注意:只要输入一组数据。用空格隔开。
char temp,str[10]; scanf("%s",str);
for(int i=0;i<9;i++) for(int j=i+1;j<10;j++) if(str[i]>str[j]) { temp=str[i]; str[i]=str[j]; str[j]=temp; }
cout<<str<<endl; }
输入:依次输入函数的四个系数中的 a,b,c,d 的值。用空格隔开。
输出:如果有极值点则全部输出,结果保留两位小数,格式为“(x1=#,y1=#) (x2=#,y2=#)”,如果没有则输入“no answer。

acm初级试题及答案

acm初级试题及答案

acm初级试题及答案1. 题目:字符串反转- 描述:编写一个函数,实现对输入字符串的反转。

- 输入:一个字符串。

- 输出:反转后的字符串。

答案:```pythondef reverse_string(s):return s[::-1]```2. 题目:求最大公约数- 描述:编写一个函数,计算两个正整数的最大公约数。

- 输入:两个正整数。

- 输出:两个数的最大公约数。

答案:```pythondef gcd(a, b):while b:a, b = b, a % breturn a```3. 题目:计算阶乘- 描述:编写一个函数,计算一个非负整数的阶乘。

- 输入:一个非负整数。

- 输出:该整数的阶乘。

答案:```pythondef factorial(n):if n == 0:return 1else:return n * factorial(n-1)```4. 题目:判断素数- 描述:编写一个函数,判断一个正整数是否为素数。

- 输入:一个正整数。

- 输出:如果该数是素数,返回True;否则返回False。

答案:```pythondef is_prime(n):if n <= 1:return Falsefor i in range(2, int(n0.5) + 1):if n % i == 0:return Falsereturn True```5. 题目:寻找数组中第二大的数- 描述:编写一个函数,找出数组中第二大的数。

- 输入:一个整数数组。

- 输出:数组中第二大的数。

答案:```pythondef find_second_max(arr):first = second = float('-inf')for num in arr:if num > first:second = firstfirst = numelif num > second and num != first: second = numreturn second```。

全国ACM比赛试题

全国ACM比赛试题

ACM比赛试题一、RailroadTime Limit: 10 Seconds Memory Limit: 32768 KBIt is Friday evening and Jill hates two things which are common to all trains:1. They are always late.2. The posted schedule is always wrong.Nevertheless, tomorrow in the early morning hours Jill will have to travel from Tuttlingen to Freiburg in order to get to the Regional Programming Contest. Since she is afraid of arriving too late and being excluded from the contest, she is looking for the train which gets her to Freiburg as early as possible. However, she dislikes getting to the station too early, so if there are several schedules with the same arrival time, she will choose the one with the latest departure time.Jill asks you to help her with her problem, so that she can sleep a bit longer tomorrow. You are given a set of railroad schedules from which you have to compute the fastest connection among those with the earliest arrival time for going from one location to another. One good thing: Jill is very experienced in switching trains: she can do this instantaneously, i.e., in zero time!!!InputThe input file contains several scenarios. Each of them consists of three parts.Part one lists the names of all cities connected by the railroads. It starts with a line containing an integer C (1 <= C <= 100) followed by C lines containing city names. These names consist of letters. Part two describes all the trains running during the day. It starts with a number T <= 1000 followed by T train descriptions. Each train description consists of one line with a number ti <= 100 and ti more lines with a time and a city name, meaning that passengers can get on or off the train at that time at that city. The times are given in the 24-hour format hhmm.Part three consists of three lines: Line one contains the earliest possible starting time for the journey, line two the name of the city where she starts, and line three the destination city. The two cities are always different.The end of the input file is marked by a line containing only a zero (instead of C). Do not process this line.OutputFor each scenario print the line ��Scenario #n�� where n is the number of the scenario starting at 1.If a connection exists then print the two lines containing zero padded timestamps and locations as shown in the sample output. Use blanks to achieve the indentation. If no connection exists on the same day (i.e., arrival before midnight), then print a line containing ��No connection��.After each scenario print a blank line.Sample Input3TuttlingenConstanceFreiburg320949 Tuttlingen1006 Constance21325 Tuttlingen1550 Freiburg21205 Constance1411 Freiburg0800TuttlingenFreiburg2UlmVancouver120100 Ulm2300 Vancouver0800UlmVancouverSample OutputScenario #1Departure 0949 TuttlingenArrival 1411 FreiburgScenario #2No connection二、Strategic GameTime Limit: 10 Seconds Memory Limit: 32768 KBBob enjoys playing computer games, especially strategic games, but sometimes he cannot find the solution fast enough and then he is very sad. Now he has the following problem. He must defend a medieval city, the roads of which form a tree. He has to put the minimum number of soldiers on the nodes so that they can observe all the edges. Can you help him?Your program should find the minimum number of soldiers that Bob has to put for a given tree. The input file contains several data sets in text format. Each data set represents a tree with the following description:the number of nodesthe description of each node in the following formatnode_identifier:(number_of_roads) node_identifier1 node_identifier2 ... node_identifierornode_identifier:(0)The node identifiers are integer numbers between 0 and n-1, for n nodes (0 < n <= 1500). Every edge appears only once in the input data.For example for the tree:the solution is one soldier ( at the node 1).The output should be printed on the standard output. For each given input data set, print one integer number in a single line that gives the result (the minimum number of soldiers). An example is given in the following table:Input40:(1) 11:(2) 2 32:(0)3:(0)53:(3) 1 4 21:(1) 02:(0)0:(0)4:(0)Output12三、CoursesTime Limit: 10 Seconds Memory Limit: 32768 KBConsider a group of N students and P courses. Each student visits zero, one or more than one courses. Your task is to determine whether it is possible to form a committee of exactly P students that satisfies simultaneously the conditions:every student in the committee represents a different course (a student can represent a course if he/she visits that course).each course has a representative in the committeeYour program should read sets of data from a text file. The first line of the input file contains the number of the data sets. Each data set is presented in the following format:P NCount1 Student1 1 Student1 2 ... Student1 Count1Count2 Student2 1 Student2 2 ... Student2 Count2CountP StudentP 1 StudentP 2 ... StudentP CountPThe first line in each data set contains two positive integers separated by one blank: P (1 <= P <= 100) - the number of courses and N (1 <= N <= 300) - the number of students. The next P lines describe in sequence of the courses . from course 1 to course P, each line describing a course. The description of course i is a line that starts with an integer Count i (0 <= Count i <= N) representing the number of students visiting course i. Next, after a blank, you��ll find the Count i students, visiting the course, each two consecutive separated by one blank. Students are numbered with the positive integers from 1 to N.There are no blank lines between consecutive sets of data. Input data are correct.The result of the program is on the standard output. For each input data set the program prints on a single line ��YES�� if it is possible to form a committee and ��NO�� otherwise. There should not be any leading blanks at the start of the line.An example of program input and output:Input23 33 1 2 32 1 21 13 32 1 32 1 31 1OutputYESNO四、Square CoinsTime Limit: 2 Seconds Memory Limit: 65536 KBPeople in Silverland use square coins. Not only they have square shapes but also their values are square numbers. Coins with values of all square numbers up to 289 (=17^2), i.e., 1-credit coins, 4-credit coins, 9-credit coins, ..., and 289-credit coins, are available in Silverland.There are four combinations of coins to pay ten credits:ten 1-credit coins,one 4-credit coin and six 1-credit coins,two 4-credit coins and two 1-credit coins, andone 9-credit coin and one 1-credit coin.Your mission is to count the number of ways to pay a given amount using coins of Silverland.InputThe input consists of lines each containing an integer meaning an amount to be paid, followed by a line containing a zero. You may assume that all the amounts are positive and less than 300.OutputFor each of the given amount, one line containing a single integer representing the number of combinations of coins should be output. No other characters should appear in the output.Sample Input21030Sample Output1427五、The TriangleTime Limit: 1000MS Memory Limit: 10000KTotal Submissions: 35853 Accepted: 21467Description73 88 1 02 7 4 44 5 2 6 5(Figure 1)Figure 1 shows a number triangle. Write a program that calculates the highest sum of numbers passed on a route that starts at the top and ends somewhere on the base. Each step can go either diagonally down to the left or diagonally down to the right。

蓝桥杯ACM决赛经典试题及其详解

蓝桥杯ACM决赛经典试题及其详解

/*入门训练A+B问题问题描述输入A、B,输出A+B。

说明:在“问题描述”这部分,会给出试题的意思,以及所要求的目标。

输入格式输入的第一行包括两个整数,由空格分隔,分别表示A、B。

说明:“输入格式”是描述在测试你的程序时,所给的输入一定满足的格式。

做题时你应该假设所给的输入是一定满足输入格式的要求的,所以你不需要对输入的格式进行检查。

多余的格式检查可能会适得其反,使用你的程序错误。

在测试的时候,系统会自动将输入数据输入到你的程序中,你不能给任何提示。

比如,你在输入的时候提示“请输入A、B”之类的话是不需要的,这些多余的输出会使得你的程序被判定为错误。

输出格式输出一行,包括一个整数,表示A+B的值。

说明:“输出格式”是要求你的程序在输出结果的时候必须满足的格式。

在输出时,你的程序必须满足这个格式的要求,不能少任何内容,也不能多任何内容。

如果你的内容和输出格式要求的不一样,你的程序会被判断为错误,包括你输出了提示信息、中间调试信息、计时或者统计的信息等。

样例输入12 45说明:“样例输入”给出了一组满足“输入格式”要求的输入的例子。

这里给出的输入只是可能用来测试你的程序的一个输入,在测试的时候,还会有更多的输入用来测试你的程序。

样例输出57说明:“样例输出”给出了一组满足“输出格式”要求的输出的例子。

样例输出中的结果是和样例输入中的是对应的,因此,你可以使用样例的输入输出简单的检查你的程序。

要特别指出的是,能够通过样例输入输出的程序并不一定是正确的程序,在测试的时候,会用很多组数据进行测试,而不局限于样例数据。

有可能一个程序通过了样例数据,但测试的时候仍只能得0分,可能因为这个程序只在一些类似样例的特例中正确,而不具有通用性,再测试更多数据时会出现错误。

比如,对于本题,如果你写一个程序不管输入是什么都输入57,则样例数据是对的,但是测试其他数据,哪怕输入是1和2,这个程序也输出57,则对于其他数据这个程序都不正确。

相关主题
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
相关文档
最新文档