acm程序设计大赛题目

合集下载

山东科技大学第二届ACM程序设计大赛试题

山东科技大学第二届ACM程序设计大赛试题

山东科技大学第二届ACM程序设计大赛试题册试题共14页,题目共计12道山东科技大学第二届ACM 程序设计大赛试题册Problem A 简单计算Description给出n 个十进制的数,找出这n 个数的二进制表示中1的个数最少的数。

Input输入的第一行为一个正整数T (1≤T ≤20),代表测试数据组数。

对于每组测试数据,输入的第一行为一个正整数n (1≤n ≤10000),第二行为n个正整数A 1、A 2、…、A n (1≤A i ≤109),每个数之间以空格分隔。

Output每组数据输出一行,先输出数据组数,再输出二进制中含1最少的数,如果存在多个数符合条件,输出最小的那个。

具体输出格式见样例输出。

Sample Input Sample Output山东科技大学第二届ACM 程序设计大赛试题册Problem B 关键字搜索Description我们的新网站具有了全新的搜索功能,使用了2个通配符“*”和“?”,其中“*”表示0或者多个小写字母,“?”代表1个字母。

当我们输入一个关键字的时候,我们在不确定的地方就使用通配符。

我们在数据库里面有多条记录,每条记录都是由小写字母组成,现在给出一个关键字,你能告诉我数据库里面有多少条与关键字相匹配的记录吗?例如: 如果关键字是j*y*m*y?,那么jiyanmoyu ,jyanmoyu ,jymyu 都是相匹配的记录。

Input第一行输入一个T (T ≤20),表示有T 组测试数据。

对于每组测试数据,第一行是输入的关键字,接下是数据库里面的所有记录的条数n ,1≤n ≤10000,每条记录的长度不超过50个小写字母。

Output对于每组测试数据,输出与关键字相匹配的总记录条数,占一行。

Sample Input Sample Output山东科技大学第二届ACM 程序设计大赛试题册Problem C 正方形Description在二维坐标轴内给出四个点,这四个点能否构成一个正方形。

计算机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程序设计大赛试题ACM(Association for Computing Machinery)程序设计大赛是一项面向大学生的编程竞赛,旨在提高参赛者在算法和数据结构方面的能力。

每年都会举办多个级别的比赛,包括区域赛、国家赛和世界总决赛。

ACM程序设计大赛试题通常涵盖广泛的计算机科学和编程知识,包括但不限于以下几个方面:1. 算法和数据结构,试题可能涉及各种经典算法和数据结构的应用,如排序、查找、图论、动态规划、贪心算法等。

参赛者需要能够理解这些算法的原理和实现方法,并能够根据问题的要求选择合适的算法进行解题。

2. 编程语言和编程技巧,参赛者需要熟练掌握至少一种编程语言,通常是C++、Java或Python。

他们需要能够使用该语言进行编程,实现算法和数据结构的代码,并能够处理输入输出、异常处理等编程任务。

此外,熟练掌握一些编程技巧,如优化算法、调试代码等也是非常重要的。

3. 数学和逻辑思维,ACM程序设计大赛试题可能涉及一些数学和逻辑问题,如数论、组合数学、概率统计等。

参赛者需要具备基本的数学知识,并能够将其应用到解题过程中。

4. 实际问题的建模和解决,ACM程序设计大赛试题通常基于实际问题,参赛者需要能够将问题抽象为计算机可解决的形式,并设计出高效的算法和数据结构进行求解。

这需要参赛者具备一定的问题建模和解决能力。

5. 时间和空间复杂度分析,参赛者在解决问题时需要考虑算法的时间和空间复杂度。

他们需要能够分析算法的运行时间和所需内存,并根据比赛规则和问题要求选择合适的算法以保证程序的效率。

总的来说,ACM程序设计大赛试题要求参赛者具备扎实的计算机科学和编程基础,能够独立思考和解决复杂的问题。

参赛者需要在规定的时间内完成试题,并保证程序的正确性和效率。

通过参加ACM程序设计大赛,参赛者能够提升自己的编程能力和解决问题的能力,同时也能够与其他优秀的程序员交流和学习。

河南省第四届ACM程序设计大赛原题

河南省第四届ACM程序设计大赛原题

所有题目时间限制:1秒【T1】序号互换Dr.Kong 设计了一个聪明的机器人卡多,卡多会对电子表格中的单元格坐标快速计算出来。

单元格的行坐标是由数字编号的数字序号,而列坐标使用字符序号。

观察字母序号,发现第1列到第26列的字母序号分别为A,B,……,Z,接着,第27列序号为AA,第28列为AB,以此类推。

若给Dr.Kong的机器人卡多一个数字序号(比如32),它能很快算出等价的字母序号(即AF),若给机器人一个字母序号(比如AA),它也能很快算出等价的数字序号(27),你能不能与卡多比试比试,看谁能算得更快更准。

【标准输入】第一行:N 表示有多少组测试数据。

接下来N行,每行或者是一个正整数,或者是一个仅由大写字母组成的字符串。

【标准输出】对于每一行测试数据,输出一行。

如果输入为一个正整数序号,则输出等价的字母序号;如果输入为字符串,则输出等价的数字序号。

【约束条件】输入保证,所有数字序号和字母序号对应的数字序号均<=2*10^9【样例】【T2】节能Dr.kong 设计的机器人卡多越来越聪明。

最近市政府公司交给卡多一项任务,每天早晨5:00开始,它负责关掉ZK大道右侧上的所有路灯。

卡多每到早晨5:00准会在ZK大道上某盏灯的旁边,然后他开始关灯。

每盏灯都有一定的功率,机器人卡多有自觉的节能意识,它希望在关灯期间,ZK大道右侧上所有的路灯的耗电总量数是最少的。

机器人卡多以1m/s的速度行走。

假设关灯动作不需要花费额外的时间,因为当它通过某盏路灯时就顺手将灯关掉。

请编写程序,计算在给定路灯设置,灯泡功率以及机器人卡多的起始位置的情况下,卡多关灯期间,Zk大道上所有灯耗费的最小能量。

【标准输入】第一行N 表示ZK大道右侧路灯的数量(2<=N<=1000)第二行V 表示机器人卡多开始关灯的路灯号。

(1<=V<=N)接下来的N行中,每行包含两个空格隔开的整数D和W,用来描述每盏灯的参数D表示该路灯与ZK大道起点的距离(用米为单位来表示)W表示灯泡的功率,即每秒该灯泡所消耗的能量数。

acm程序设计大赛试题

acm程序设计大赛试题

acm程序设计大赛试题题目:旅游管理系统一、问题描述随着信息技术的飞速发展,旅游业作为全球经济的重要组成部分,其管理和服务水平也在不断提升。

为了更好地服务游客,提高工作效率,我们计划开发一个旅游管理系统。

该系统旨在帮助旅游公司管理客户信息、行程安排、预订情况以及费用结算等业务。

本文将详细介绍该系统的设计要求和功能特点。

二、功能需求1. 客户信息管理系统应能够记录客户的基本信息,包括姓名、联系方式、身份证号码等。

同时,应支持对客户信息的增加、修改和查询功能。

此外,系统还应具备客户信息的分类和统计功能,便于旅游公司对客户群体进行分析。

2. 行程安排旅游公司需要根据客户需求和旅游资源情况,为客户制定合适的旅游行程。

系统应提供行程规划功能,包括景点选择、活动安排、住宿和交通预订等。

同时,系统应能够根据实际情况调整行程,并及时更新相关信息。

3. 预订管理系统应能够处理客户的旅游预订,包括景点门票、酒店房间、交通工具等。

预订管理功能应包括预订的创建、修改、取消和确认等操作,并能够实时更新预订状态,确保信息的准确性。

4. 费用结算旅游费用的结算是旅游管理系统的核心功能之一。

系统应能够根据客户的预订情况和实际消费,自动计算应付费用。

同时,系统还应支持多种支付方式,如信用卡、支付宝、微信支付等,并能够生成详细的费用清单和发票。

5. 数据安全与备份鉴于旅游管理系统中涉及大量敏感信息,系统必须具备严格的数据安全措施。

包括但不限于用户权限管理、数据加密、防止SQL注入等。

此外,系统还应定期进行数据备份,以防数据丢失或损坏。

三、系统架构设计1. 前端设计系统的前端设计应注重用户体验,界面友好、操作简便。

可以使用HTML5、CSS3和JavaScript等技术开发响应式网页,以适应不同设备和屏幕尺寸。

同时,前端应提供丰富的交互功能,如日历选择、地图展示、图片上传等。

2. 后端设计后端设计主要负责处理业务逻辑、数据存储和安全保障。

第三届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、数据从文件输入,标准输出,注意输入文件名题中已经给出。

第八届程序设计大赛初赛试题及答案

第八届程序设计大赛初赛试题及答案

第八届程序设计大赛初赛试题说明:请将所有答案写到试卷第1页及第2页。

一、读程序写结果(40分)1、(5分)2、(5分)3、(10分)结果:结果:结果:4、(10分)5、(5分)6、(5分)结果:结果:结果:二、代码填空(30分)1、(5分)2、(5分)空一:____acm / lg (5分)空一:if(begin>end) return (5分)3、(12分)4、(8分)空一:siruan /= 10 (3分)空一:s[i] - '0' (4分)空二:hm - lg (3分)空二:siruan[sum % 11] (4分)空三:lghm = acm(lghm) (6分)三、思维题(15分)数据1:T1=1,T2=2,T3=3,T4 = 4 数据2:T1=1,T2=2,T3=5,T4 = 10 答案:(acm)1 2->(siruan) 2min 答案:(acm)1 2->(siruan) 2min (acm) <-1 (siruan) 1min (acm) <-1 (siruan) 1min(acm) 1 3->(siruan) 3min (acm) 5 10->(siruan) 10min(acm) <-1 (siruan) 1min (acm) <-2 (siruan) 2min(acm) 1 4-> (siruan) 4min (acm) 1 2-> (siruan) 2min最短时间:2+1+3+1+4 = 11min 最短时间:2+1+10+2+2 = 17min数据3:T1 = 5,T2 = 2,T3=1,T4=10,T5=8 答案:(acm)1 2->(siruan) 2min(acm) <-1 (siruan) 1min(acm) 8 10->(siruan) 10min(acm) <-2 (siruan) 2min(acm) 1 2-> (siruan) 2min(acm) <-1 (siruan) 1min(acm) 1 5 ->(siruan) 5min最短时间:2+1+10+2+2+1+5 = 23min四、编程题(15分)程序代码:#include<stdio.h>#include<string.h>int s[110];int main(){int i;int a, n, m;while (scanf("%d%d", &a, &n)!=EOF){memset(s, 0x00, sizeof(s));m = n;for (i=0; i<m; i++){s[i] += a * (n--);s[i+1] = s[i] / 10;s[i] %= 10;}if (s[m]) printf("%d", s[i]);for (i=m-1; i>=0; i--)printf("%d", s[i]);printf("\n");}return 0;}一、读程序写结果(40分)1、(5分)#include <stdio.h>int main(){char acm[] = "I love acm!";char siruan[] = "I love siruan!";char def[] = "Welcome to join us!";int chose = 0;switch (chose){case 0: printf("%s\n", acm);case 1: printf("%s\n", siruan);default : printf("%s", def);}return 0;}输出结果:2.(5分)#include <stdio.h>int main(){int acm = 0, siruan = 1;if (acm = siruan) printf("%s", "May you success!");else printf("%s", "May you success,too!");return 0;}输出结果:3.(10分)#include <stdio.h>#include <math.h>int main(){int i,j,k,n;char lghm[14]="ILOVEACMSIRUAN";n = 3;for (i=0; i<n-1; i++) printf(" ");printf("%c\n",lghm[0]);for (i=1; i<n; i++){for (j=abs(n-i-1); j>0; j--) //abs(n)返回值为整形n的绝对值printf(" ");printf("%c",lghm[2*i-1]);for (k=1; k<=2*i-1; k++) printf(" ");printf("%c\n",lghm[2*i]);}for (i=n; i<=2*n-3; i++){for (j=abs(n-i-1); j>0; j--) printf(" ");printf("%c",lghm[2*i-1]);for (k=1; k<=4*n-5-2*i; k++) printf(" ");printf("%c\n",lghm[2*i]);}for (i=0; i<n-1; i++) printf(" ");printf("%c\n",lghm[4*n-5]);return 0;}输出结果:4.(10分)#include <stdio.h>#include <string.h>struct Student{char name[20];int num;} stu[5];{stu[0].num = 521; strcpy(stu[0].name, "sichuan wenchuan");stu[1].num = 521; strcpy(stu[1].name, "bless");stu[2].num = 420; strcpy(stu[2].name, "sichuan yaan");stu[3].num = 420; strcpy(stu[3].name, "love");stu[4].num = 420; strcpy(stu[4].name, "god");}void swap(int a, int b){struct Student tmp;tmp.num = stu[a].num;stu[a].num = stu[b].num;stu[b].num = tmp.num;strcpy(, stu[a].name);strcpy(stu[a].name, stu[b].name);strcpy(stu[b].name, );}void bubble_sort(int n){int i,j,flag,temp;for(i = 0; i < n-1; i++){flag = 1;for(j = 0; j < n-i-1; j++){if(stu[j].num > stu[j+1].num){swap(j, j+1);flag = 0;}else if (stu[j].num == stu[j+1].num && strcmp(stu[j].name,stu[j+1].name)<0){ swap(j, j+1);}}if(flag) break;}}int main(){init();bubble_sort(5);for (i=0; i<5; i++)printf("%-4d%s\n", stu[i].num, stu[i].name);return 0;}输出结果:6.(5分)#include <stdio.h>int acm(){int lg = 1314520;int hm = 0;while(lg > 0){hm = hm * 10 + lg % 10;lg /= 10;}return hm;}int main(){int siruan = acm();printf("%d", siruan);return 0;}输出结果:二、代码填空(30分)1.(5)如果没有计算器,我们如何求3的平方根?可以先猜测一个数,比如1.5,然后用3除以这个数字。

ACM校赛比赛题目及分析

ACM校赛比赛题目及分析

Problem A -- 超级难题Time Limit:1000ms Memory Limit:65535KBDescriptionACM程序设计大赛是大学级别最高的脑力竞赛,素来被冠以"程序设计的奥林匹克"的尊称。

大赛自1970年开始至今已有30年历史,是世界范围内历史最悠久、规模最大的程序设计竞赛。

比赛形式是:经过校级和地区级选拔的参赛组,于指定的时间、地点参加世界级的决赛,由3个成员组成的小组应用一台计算机解决6到8个生活中的实际问题。

参赛队员必须在5小时内编完程序并进行测试和调试。

此种大赛对参赛学生的逻辑分析能力、策略制定和脑力方面具有极大的挑战性。

大赛提倡在压力较大的情况下,培养学生的创造力、团队合作精神以解决竞赛的问题,从而挑选和发掘世界上最优秀的程序设计人才竞赛的历史可以上溯到1970年,当时在美国德克萨斯A&M大学举办了首届比赛。

当时的主办方是the Alpha Chapter of the UPE Computer Science Honor Society。

作为一种全新的发现和培养计算机科学顶尖学生的方式,竞赛很快得到美国和加拿大各大学的积极响应。

1977年,在ACM计算机科学会议期间举办了首次总决赛,并演变成为目前的一年一届的多国参与的国际性比赛。

迄今已经举办了29届ACM/ICPC以团队的形式代表各学校参赛,每队由3名队员组成。

每位队员必须是入校5年内的在校学生。

比赛期间,每队使用1台电脑需要在5个小时内使用C、C++、Pascal或Java中的一种编写程序解决8或10个问题。

程序完成之后提交裁判运行,并把运行结果及时通知参赛队。

而且有趣的是每队在正确完成一题后,组织者将在其位置上升起一只代表该题颜色的气球2009年的时候队伍A参加了ACM的区域赛,那次区域赛比赛总共有N个题,队伍A做了N个题中的M个。

队伍A 做第一题所用的时间为T1分钟,做第一题所用的时间为T2分钟,.......做第M题所用的时间为Tm分钟。

acm编程比赛题

acm编程比赛题

比赛试题主办方:迅翔计算机协会【问题描述】这是一个古老而又经典的问题。

用给定的几种钱币凑成某个钱数,一般而言有多种方式。

例如:给定了6种钱币面值为2、5、10、20、50、100,用来凑15元,可以用5个2元、1个5元,或者3个5元,或者1个5元、1个10元,等等。

显然,最少需要2个钱币才能凑成15元。

你的任务就是,给定若干个互不相同的钱币面值,编程计算,最少需要多少个钱币才能凑成某个给出的钱数。

【要求】【数据输入】输入可以有多个测试用例。

每个测试用例的第一行是待凑的钱数值M(1 <= M <= 2000,整数),接着的一行中,第一个整数K(1 <= K <= 10)表示币种个数,随后是K 个互不相同的钱币面值Ki(1 <= Ki <= 1000)。

输入M=0时结束。

【数据输出】每个测试用例输出一行,即凑成钱数值M最少需要的钱币个数。

如果凑钱失败,输出“Impossible”。

你可以假设,每种待凑钱币的数量是无限多的。

【样例输入】156 2 5 10 20 50 10011 2【样例输出】2Impossible【问题描述】Felicia 的生日是11月1日(和Kitty是同一天生的哦)。

于是Feli请来Kitty一起过生日。

Kitty带来了最新款的“Kitty猫”玩具准备送给Feli,不过她说,这份礼物可不是白送的。

Feli要帮她一个忙,才能够得到心仪已久的玩具。

Kitty说,“Kitty猫”玩具已经卖出了n!个,n<=10^100 *_*,Kitty想知道确切的数字,而不是无聊的“一个数加个感叹号”。

Feli 听了大吃一惊。

要知道,算出n!是一个无比艰巨的任务。

Feli告诉Kitty,就算Feli算出n!,Kitty也看不下去,因为当n=20 时,计算机的长整型已经存不下了(Kitty只能接受1-9之间的数字)。

于是Kitty说,你只要告诉我n!最后一位非0的数就可以了。

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大学生程序设计试题题目一:最大公约数(GCD)题目描述:给定两个正整数,求它们的最大公约数(GCD)。

输入两个正整数a和b(1 <= a, b <= 10^9),求它们的最大公约数。

输入格式:两个正整数,以空格分隔。

输出格式:输出一个整数,表示输入两个正整数的最大公约数。

示例:输入:14 21输出:7思路和分析:最大公约数(GCD)可以使用欧几里得算法来求解,即辗转相除法。

具体的步骤如下:1. 用较大的数除以较小的数,将得到的余数作为新的较大数。

2. 再用新的较大数除以较小数,将得到的余数作为新的较大数。

3. 如此重复,直到两个数可以整除,此时较小的数就是最大公约数。

代码实现:```cpp#include <iostream>using namespace std;int gcd(int a, int b) {if (b == 0)return a;return gcd(b, a % b);}int main() {int a, b;cin >> a >> b;int result = gcd(a, b);cout << result << endl;return 0;}```题目二:字符串反转题目描述:给定一个字符串,要求将其反转并输出。

输入一个字符串s(1 <= |s| <= 1000),输出该字符串的反转结果。

输入格式:一个字符串s,只包含大小写字母和数字。

输出格式:一个字符串,表示输入字符串的反转结果。

示例:输入:HelloWorld123输出:321dlroWolleH思路和分析:字符串反转可以使用双指针的方法来实现。

初始时,左指针指向字符串的开头,右指针指向字符串的末尾,然后交换左右指针所指向的字符,并向中间移动,直到左指针不小于右指针。

代码实现:```cpp#include <iostream>using namespace std;string reverseString(string s) {int left = 0, right = s.length() - 1; while (left < right) {swap(s[left], s[right]);left++;right--;}return s;}int main() {string s;cin >> s;string result = reverseString(s); cout << result << endl;return 0;}```题目三:字符串匹配题目描述:给定一个字符串s和一个模式串p,判断s中是否存在与p相匹配的子串。

ACM程序设计试题

ACM程序设计试题

ACM程序设计试题1.平方数给出包含M个数字的列表,和列表中所有数字的所有质因数。

求出最长的子列表,使得子列表中所有数字的乘积是一个完全平方数。

输入输入文件包含多组测试数据。

第一行包含两个整数N , M ( 1 <= N <= 30 , 1 <= M <= 30000 ). N 是质因数的个数。

接下来一行有N个整数,给出所有的质因数。

然后一行包含M 个整数,给出列表。

输入文件结束于N = M = 0.输出对于每组数据,输出最长子列表的两个位置坐标l r。

l是该子列表在列表中的起始位置,r是结束位置。

如果多种情况都满足子列表长度最大,输出l最小的一个。

如果不存在这样的子列表输出“None”。

样例输入3 42 3 54 9 25 63 42 3 56 6 3 30 0样例输出1 31 42.母牛生小牛Problem设有一头小母牛,从出生第四年起每年生一头小母牛,按此规律,第N年时有几头母牛?Input本题有多组数据。

每组数据只有一个整数N,独占一行。

(1≤N≤50)Output对每组数据,输出一个整数(独占一行)表示第N年时母牛的数量Sample Input145Sample Output1238723.死亡迷宫背景很久以前,迷宫里住着一个恶魔。

一天,我们伟大的英雄Andy无意中踏入了这个迷宫。

不幸的是,他被困在这个迷宫当中了。

恶魔在迷宫中召唤出了许多怪物,想要阻止Andy逃脱。

在迷宫中,Andy遇到一个一位巫师。

他给了Andy迷宫的地图,并告诉他迷宫的入口很快会关闭。

Andy必须以非常快的速度到达入口,并且有足够的力气推开挡在入口的岩石。

于是,Andy带着地图一路向着出口走去……问题给出Andy和各怪物的能量, 攻击力, 防御力,和迷宫的地图,请你计算一下能量/耗时的最大值。

当Andy走到有怪物的地方时,Andy会先进行攻击,然后怪物攻击,然后Andy……当一方的能量小于等于0时攻击停止,并且小于等于0的一方死亡。

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程序设计竞赛II第一章

ACM程序设计竞赛II第一章


if(q >= y || (p < m && A[p] <= A[q]))//右边空,或者两边都不空且右边大

T[i++] = A[p++];//复制左边的

else
•3;] = A[q++];//复制右边的

*cnt += m-p;//是逆序数的数目

}
•}
• for(i = x; i < y; i++) A[i] = T[i];
count++;
printf("%d\n",count);
}
2021/8r/e2turn 0;
11
}
首先抽象数学模型
• 数据如何存储
– 问题一:顺序表、链表? – 问题三:二维数组?
• 对模型选择适当算法
– 问题one by one
• 求解
– 此处省略1万字
2021/8/2
12
关于字符串
• 基本:长度、拷贝、连接、比较、反串、判断回文 • 进阶:子串(模式匹配)
照号码的字典升序输出。如果输入数据中没有重复的号码,输出一行:
No duplicates
(注2意021N/8大/2 写)
19
Sample Input
问题六—(HDOJ-1800)
Flying to the Mars
2021/8/2
20
字符串哈希 HDOJ-1800题
• 除去马甲,本题的本质是——求相同级别(level)的人 最多是几个。
• 输出:每一行一个整数x,对应一组case,表示该组case的 字符串中所包含的最长回文长度.

福建农林大学思博杯第一届ACM程序设计大赛题目

福建农林大学思博杯第一届ACM程序设计大赛题目

福建农林大学思博杯第一届ACM程序设计大赛题目福建农林大学思博杯第一届ACM程序设计大赛题目1.多项式相乘(本题30分)(conv.cpp/c)【题目描述】编程实现若干个多项式相乘。

多项式的输入输出格式为:系数在前,指数在后,各项按指数递增排列,每个多项式输入时以两个0结束。

系数为0的项不输出。

例如:1+4X3-9X5输入格式为:1 0 0 1 0 2 4 3 0 4 -9 5 0 0或者 1 0 4 3 -9 5 0 0,其输出只能是:1 0 4 3 -9 5【输入】输入文件conv.in每行为一个多项式,多项式输入时以两个0结束。

数据为若干行的多项式,例如:1 0 1 1 0 01 0 -1 1 0 01 0 12 0 0表示(1+x)(1-x)(1+x2)【输出】输出文件conv.out包含1行,为上述多项式相乘结果。

上例的输出为:1 0 -1 4表示1-x4所有系数、指数均为整数(int类型)2.Total求和(本题60分)(total.cpp/c)【问题描述】编写程序实现从一字符串str中取出连续的数字作为一个正整数,计算所有这些正整数之和。

例如字符串str="abc123 x456,xy16639ghks-7890# zxy",按题目要求可以取出4个正整数:123,456,16639,7890。

这4个正整数之和为:25108【输入】输入文件total.in只有一行,是一个字符串(1≤字串长度≤500)。

【输出】输出文件total.out也只有一行,从输入一字符串中取出连续的数字作为一个正整数,输出所有这些正整数之和(1位整数≤和≤100位整数)。

3. FBI树(本题60分)(fbi.cpp/c)【问题描述】我们可以把由“0”和“1”组成的字符串分为三类:全“0”串称为B串,全“1”串称为I串,既含“0”又含“1”的串则称为F串。

FBI树是一种二叉树,它的结点类型也包括F结点,B结点和I结点三种。

2019年安康学院ACM程序设计大赛java试题

2019年安康学院ACM程序设计大赛java试题

2019年安康学院ACM程序设计大赛java试题1、微机内存按______。

[单选题] *A:二进制位编址B:十进制位编址C:字长编址D:字节编址(正确答案)2、16.在Internet.上浏览时,浏览器和Www服务器之间传输网页使用的协议是()。

[单选题] *A.Http(正确答案)B.IPC.FtpD.Smtp3、42.在因特网上,一台计算机可以作为另一台主机的远程终端,使用该主机的资源,该项服务称为()。

[单选题] *A.Telnet(正确答案)B.BBSC.FTPD.WWW4、计算机系统软件中,最基本、最核心的软件是______。

[单选题] *A:操作系统(正确答案)B:数据库管理系统C:程序语言处理系统D:系统维护工具5、计算机网络中,为了使计算机或终端之间能够正确传送信息,必须按照()来相互通信。

易[单选题] *A. 信息交换方式B. 网卡C. 传输装置D. 网络协议(正确答案)6、机器在开机时自检正常,但键盘上的三个键WSX不起作用,试判断故障原因()。

[单选题] *A.键盘与主机连线有误B.键盘电路板故障(正确答案)C.CMOS设置错误D.主机上键盘控制电路故障7、目前在“打印预览”状态,如果要打印文档,则()[单选题] *A. 必须退出打印预览状态才能进行打印B. 从预览状态不能进行打印C. 可直接从预览状态执行打印(正确答案)8、TA直通线与TB直通线网速相比较()快。

[单选题] *ATABTBC一样DUSOC()(正确答案)9、36.在标准ASCII码表中,已知英文字母K的十六进制码值是4B,则二进制ASCII码1001000对应的字符是()。

[单选题] *A.GB.H(正确答案)C.ID.J10、虚拟专用网VPN 采用的类似点对点通信的安全技术是()。

中[单选题] *A.加密技术B.身份认证技术C.隧道技术(正确答案)D.密钥管理技术11、字长是CPU的主要性能指标之一,它表示_______。

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大学生程序试题及答案

acm大学生程序试题及答案1. 题目:字符串反转描述:给定一个字符串,编写一个函数来将字符串中的字符按相反的顺序重新排列。

输入:一个字符串输出:反转后的字符串答案:```pythondef reverse_string(s):return s[::-1]```2. 题目:寻找最大数描述:给定一个整数数组,找出数组中的最大数。

输入:一个整数数组输出:数组中的最大数答案:```pythondef find_max(nums):return max(nums)```3. 题目:两数之和描述:给定一个整数数组和一个目标值,找出数组中和为目标值的两个数的索引(从1开始计数)。

输入:一个整数数组和一个目标值输出:两个数的索引,如果没有则返回空数组答案:```pythondef two_sum(nums, target):num_to_index = {}for i, num in enumerate(nums):complement = target - numif complement in num_to_index:return [num_to_index[complement] + 1, i + 1] num_to_index[num] = ireturn []```4. 题目:无重复字符的最长子串描述:给定一个字符串,请你找出其中不含有重复字符的最长子串的长度。

输入:一个字符串输出:最长子串的长度答案:```pythondef length_of_longest_substring(s):char_map = {}start = max_length = 0for end in range(len(s)):if s[end] in char_map:start = max(start, char_map[s[end]] + 1)char_map[s[end]] = endmax_length = max(max_length, end - start + 1)return max_length```5. 题目:整数转罗马数字描述:将一个整数转换为罗马数字。

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进制数。

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

The Mailboxes Manufacturers ProblemTime Limit:1000MS Memory Limit:65536KTotal Submit:299 Accepted:227DescriptionIn the good old days when Swedish children were still allowed to blowup their fingers with fire-crackers, gangs of excited kids would plague certain smaller cities during Easter time, with only one thing in mind: To blow things up. Small boxes were easyto blow up, and thus mailboxes became a popular target. Now, a small mailbox manufacturer is interested in how many fire-crackers his new mailbox prototype can withstand without exploding and has hired you to help him. He will provide you with k(1 ≤ k≤ 10) identical mailbox prototypes each fitting up to m(1 ≤ m≤ 100) crackers. However, he is not sure of how many firecrackers he needs to provide you with in order for you to be able to solve his problem, so he asks you. You think for a while and then say, “Well,if I blow up a mailbox I can’t use it again, so if you would provide me with only k = 1 mailboxes, I would have to start testing with 1 cracker, then 2 crackers, and so on until it finally exploded. In the worst case, that is if it does not blow up ev en when filled with m crackers, I would need 1 + 2 + 3 + … + m = m ×(m+ 1) ⁄ 2 crackers. If m = 100 that would mean more than 5000 fire-crackers!” “That’s too many,” he replies. “What if I give you more than k = 1 mailboxes? Can you find a strategy that requires less crackers?”Can you? And what is the minimum number of crackers that you should ask him to provide you with?You may assume the following:1.If a mailbox can withstand x fire-crackers, it can also withstand x− 1fire-crackers.2.Upon an explosion, a mailbox is either totally destroyed (blown up) orunharmed, which means that it can be reused in another test explosion.Note: If the mailbox can withstand a full load of m fire-crackers, then the manufacturer will of course be satisfied with that answer. But otherwise he is looking for the maximum number of crackers that his mailboxes can withstand.InputThe input starts with a single integer N(1 ≤ N≤ 10) indicating the number of test cases to follow. Each test case is described by a line containing two integers: k and m, separated by a single space.OutputFor each test case print one line with a single integer indicating the minimum number of fire-crackers that is needed, in the worst case, in order to figure out how many crackers the mailbox prototype can withstand.Sample Input41 101 1003 735 100Sample Output555050382495SourceSvenskt Mästerskap i Programmering/Norgesmesterskapet 2002 #include <iostream>using namespace std;const int INF = 1 << 28;int d[11][101][101];int sum(int i, int j) {int ret = 0, k;for (k=i; k<=j; k++) ret += k;return ret;}int max(int a, int b) {return a > b ? a : b;}int main() {int caseTime;int i, j, k, t, K, M, l;scanf("%d", &caseTime);while (caseTime--) {scanf("%d%d", &K, &M);for (i=1; i<=M; i++) {for (j=i; j<=M; j++) {d[1][i][j] = sum(i, j);}}for (k=2; k<=K; k++) {for (l=0; l<M; l++) {for (i=1; i+l<=M; i++) {j = i + l;if (i == j) {d[k][i][j] = i;continue;}d[k][i][j] = INF;for (t=i; t<=j; t++) {int tmp;if (t == i) tmp = d[k][i+1][j];else if (t == j) tmp = d[k-1][i][j-1];else tmp = max(d[k-1][i][t-1], d[k-1][t+1][j]); tmp = max(d[k-1][i][t-1], d[k][t+1][j]);if (d[k][i][j] > t + tmp) d[k][i][j] = t + tmp; }}}}printf("%d\n", d[K][1][M]);}return 0;}Bugs Integrated, Inc.Time Limit:15000MS MemoryLimit:30000KTotal Submit:1180 Accepted:309 Case Time Limit:5000MSDescriptionBugs Integrated, Inc. is a major manufacturer of advanced memory chips. They are launching production of a new six terabyte Q-RAM chip. Each chip consists of six unit squares arranged in a form of a 2*3 rectangle. The way Q-RAM chips are made is such that one takes a rectangular plate of silicon divided into N*M unit squares. Then all squares are tested carefully and the bad ones are marked with a black marker.Finally, the plate of silicon is cut into memory chips. Each chip consists of 2*3 (or 3*2) unit squares. Of course, no chip can contain any bad (marked) squares. It might not be possible to cut the plate so that every good unit square is a part ofsome memory chip. The corporation wants to waste as little good squares as possible. Therefore they would like to know how to cut the plate to make the maximum number of chips possible.TaskYou are given the dimensions of several silicon plates and a list of all bad unit squares for each plate. Your task is to write a program that computes for each plate the maximum number of chips that can be cut out of the plate.InputThe first line of the input file consists of a single integer D (1 <= D <= 5), denoting the number of silicon plates. D blocks follow, each describing one silicon plate. The first line of each block contains three integers N (1 <= N <= 150), M (1 <= M <= 10), K (0 <= K <= MN) separated by single spaces. N is the length of the plate, M is its height and K is the number of bad squares in the plate. The following K lines contain a list of bad squares. Each line consists of two integers x and y (1 <= x <= N, 1 <= y <= M) ?coordinates of one bad square (the upper left square has coordinates [1, 1], the bottom right is [N,M]).OutputFor each plate in the input file output a single line containing the maximum number of memory chips that can be cut out of the plate.Sample Input26 6 51 44 62 23 66 46 5 43 36 16 26 4Sample Output34SourceCEOI 2002CODE:#include <iostream>using namespace std;int g[150][10], blk[10];int d[4][60000];int e[11] = {1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683, 59049};int n, m, kn;int can1, can2, b[10][60000];int *l0, *l1, *l2, *l3, *bit0, *bit1, *bit2;void build() {int i, j, tmp;for (i=0; i<e[10]; i++) {j = 0; tmp = i;while (tmp > 0) {b[j][i] = tmp % 3;tmp /= 3;j++;}}}inline int maxt(int a, int b) {return a > b ? a : b;}void solve() {int i, j, k, x, y, a1, a2, p, c;scanf("%d%d%d", &n, &m, &kn);memset(g, 0, sizeof(g));memset(d, 0, sizeof(d));for (i=0; i<kn; i++) {scanf("%d%d", &x, &y);g[x-1][y-1] = 1;}for (i=0; i<m; i++) blk[i] = 1 - g[0][i];for (i=1, c=2; i<n; i++) {for (j=0; j<m; j++) {if (g[i][j]) blk[j] = 0;else blk[j]++;c = (c+1)%4;can1 = (j>0 && blk[j]>2 && blk[j-1]>2);can2 = (j>1 && blk[j]>1 && blk[j-1]>1 && blk[j-2]>1);a1 = 2*e[j]+2*e[j-1];a2 = e[j]+e[j-1]+e[j-2];l0 = d[c]; l1 = d[(c+3)%4]; l2 = d[(c+2)%4]; l3 = d[(c+1)%4];bit0 = b[j];if (j>0) bit1 = b[j-1];if (j>1) bit2 = b[j-2];for (p=0; p<e[m]; p++) {if (bit0[p]) {l0[p] = l1[p-e[j]];} else {l0[p] = l1[p];if (j>0 && !bit1[p]) {if (can1) l0[p] = maxt(l0[p],l2[p+a1]+1);if (can2 && !bit2[p]) l0[p] = maxt(l0[p], l3[p+a2]+1); }}}}}printf("%d\n", d[c][0]);}int main() {build();int caseTime;scanf("%d", &caseTime);while (caseTime--) {solve();}return 0;}Silver Cow PartyTime Limit:2000MS MemoryLimit:65536KTotal Submit:1112 Accepted:326 DescriptionOne cow from each of N farms (1 ≤ N≤ 1000) conveniently numbered 1..N is going to attend the big cow party to be held at farm #X(1 ≤ X≤ N). A total of M (1 ≤ M≤ 100,000) unidirectional (one-way roads connects pairs of farms; road i requires T i(1 ≤ T i≤ 100) units of time to traverse.Each cow must walk to the party and, when the party is over, return to her farm. Each cow is lazy and thus picks an optimal route with the shortest time. A cow's return route might be different from her original route to the party since roads are one-way.Of all the cows, what is the longest amount of time a cow must spend walking to the party and back?Line 1: Three space-separated integers, respectively: N, M, and XLines 2..M+1: Line i+1 describes road i with three space-separated integers: A i, B i, and T i. The described road runs from farm A i to farm B i, requiring T i time units to traverse.OutputLine 1: One integer: the maximum of time any one cow must walk.Sample Input4 8 21 2 41 3 21 4 72 1 12 3 53 1 23 4 44 2 3Sample Output10HintCow 4 proceeds directly to the party (3 units) and returns via farms 1 and 3 (7 units), for a total of 10 time units.USACO 2007 February Silver#include <iostream>using namespace std;const int INF = 1 << 28;int adj[1001][1001], adjw[1001][1001], na[1001];int n, m, x;//heap sink,swim,getmin,insert参数均为外部编号,wt为其权值int heap[100001], id[100001], hsize;int *key;void init(int s, int *wt) {int i;hsize = s;key = wt;for (i=1; i<=hsize; i++) {heap[i] = i;id[i] = i;}}void swim(int u) {int p = id[u], q = p >> 1, ku = key[u];while (q && ku < key[heap[q]]) {id[heap[q]] = p;heap[p] = heap[q];p = q;q = p >> 1;}id[u] = p;heap[p] = u;}void sink(int u) {int p = id[u],q = p << 1, ku = key[u];while (q <= hsize) {if (q < hsize && key[heap[q+1]] < key[heap[q]]) q++;if (key[heap[q]] >= ku) break;id[heap[q]] = p;heap[p] = heap[q];p = q;q = p << 1;}id[u] = p;heap[p] = u;}int getmin() {int ret = heap[1];id[ret] = -1;id[heap[hsize]] = 1;heap[1] = heap[hsize];hsize--;sink(heap[1]);return ret;}void insert(int u) {heap[++hsize] = u;id[u] = hsize;swim(u);}void build() {int i;for (i=hsize/2; i>0; i--) sink(heap[i]); }bool isEmpty() {return hsize == 0;}int dijkstraHeap(int beg, int end=-1) {int i, j, k, u, v, w;int dist[1001], chk[1001];for (i=1; i<=n; i++) {dist[i] = INF;chk[i] = 0;}init(n, dist);dist[beg] = 0; swim(beg);while (!isEmpty()) {u = getmin();if (u == end) break;chk[u] = 1;for (i=0; i<na[u]; i++) {v = adj[u][i];w = adjw[u][i];if (dist[v] > dist[u] + w) { dist[v] = dist[u] + w;swim(v);}}}if (end == -1) return dist[n];return dist[end];}int main() {int i, j, k, u, v, w;int val[1001];scanf("%d%d%d", &n, &m, &x);for (i=0; i<m; i++) {scanf("%d%d%d", &u, &v, &w);adj[u][na[u]] = v;adjw[u][na[u]] = w;na[u]++;}dijkstraHeap(x);memcpy(val, key, sizeof(val));int ans = 0;for (i=1; i<=n; i++) {int tmp = dijkstraHeap(i,x);if (tmp+val[i] > ans) ans = tmp + val[i]; }printf("%d\n", ans);return 0;}。

相关文档
最新文档