220 likes | 740 Views
Sorting Sorting Applications Uniqueness Testing Deleting Duplicates Prioritizing Events Median/Selection Frequency Counting Reconstructing the Original Order Set Intersection/Union Finding a target Pair Efficient Searching. Program Design Example: Rating the Field
E N D
Sorting • Sorting Applications • Uniqueness Testing • Deleting Duplicates • Prioritizing Events • Median/Selection • Frequency Counting • Reconstructing the Original Order • Set Intersection/Union • Finding a target Pair • Efficient Searching
Program Design Example: Rating the Field • Pretty Polly has no shortage of gentlemen suitors who come a’ courting. Indeed, her biggest problem is keeping track of who the best ones are. She is smart enough to realize that a program which ranks the men from most to least desirable would simplify her life. She is also persuasive enough to have talked you into writing the program. • Polly really likes to dance, and has determined the optimal partner height is 180 centimeters tall. Her first criteria is finding someone who is as close as possible to this height; whether they are a little taller or shorter doesn’t matter. Among all candidates of the same height, she wants someone as close as possible o 75 kilograms without going over. If all equal-height candidates are over this limit, she will take the lightest of the bunch. If two or more people are identical by all these characteristics, sort them by last name, then by first name if it is necessary to break the tie.
Polly is only interested in seeing the candidates ranked by name, so the input file: George Bush 195 110 Harry Truman 180 75 Bill Clinton 180 75 John Kennedy 180 65 Ronald Reagan 165 110 Richard Nixon 170 70 Jimmy Carter 180 77yields the following output: Clinton, Bill Truman, Harry Kennedy, John Carter, Jimmy Nixon, Richard Bush, George Reagan, Ronald
#include <stdio.h> #include <string.h> #define NAMELENGTH 30 #define NSUITORS 100 #define BESTHEIGHT 180 #define BESTWEIGHT 75 typedef struct { char first[NAMELENGTH]; char last[NAMELENGTH]; int height; int weight; } suitor; suitor suitors[NSUITORS]; int nsuitors; main() { int i; int suitor_compare(); read_suitors(); qsort(suitors,nsuitors,sizeof(suitor),suitor_compare); for(i=0;i<nsuitors;i++) printf(“%s, %s\n”,suitors[i].last,suitors[i].first); }
read_suitors() { char first[NAMELENGTH],last[NAMELENGTH]; int height,weight; nsuitors=0; while(scanf(“%s %s %d %d\n”,suitors[nsuitors].first, suitors[nsuitors].last,&height,&weight)!=EOF) { suitors[nsuitors].height=abs(height-BESTHEIGHT); if(weight>BESTWEIGHT) suitors[nsuitors].weight=weight-BESTWEIGHT; else suitors[nsuitors].weight=-weight; nsuitors++; } }
int suitor_compare(suitor *a,suitor *b) { int result; if(aheight<bheight) return (-1); if(aheight>bheight) return (1); if(aweight<bweight) return (-1); if(aweight>bweight) return (1); if((result=strcmp(alast,blast))!=0) return result; return (strcmp(afirst,bfirst)); }
Exercises: http://online-judge.uva.es/problemset/
Problem : Vito’s Family UVa ID: 10041, Popularity: A. Success rate: high Level: 1 Background The world-known gangster Vito Deadstone is moving to New York. He has a very big family there, all of them living in Lamafia Avenue. Since he will visit all his relatives very often, he is trying to find a house close to them. Problem Vito wants to minimize the total distance to all of them and has blackmailed you to write a program that solves his problem. Input The input consists of several test cases. The first line contains the number of test cases. For each test case you will be given the integer number of relatives r ( 0 < r < 500) and the street numbers (also integers) where they live ( 0 < si < 30000 ). Note that several relatives could live in the same street number.
Output For each test case your program must write the minimal sum of distances from the optimal Vito's house to each one of his relatives. The distance between two street numbers si and sj is dij= |si-sj|. Sample Input 2 2 2 4 3 2 4 6 Sample Output 2 4
Problem : Stacks of Flapjacks UVa ID: 120, Popularity: B. Success rate: high Level: 2 Background Stacks and Queues are often considered the bread and butter of data structures and find use in architecture, parsing, operating systems, and discrete event simulation. Stacks are also important in the theory of formal languages. This problem involves both butter and sustenance in the form of pancakes rather than bread in addition to a finicky server who flips pancakes according to a unique, but complete set of rules Problem Given a stack of pancakes, you are to write a program that indicates how the stack can be sorted so that the largest pancake is on the bottom and the smallest pancake is on the top. The size of a pancake is given by the pancake's diameter. All pancakes in a stack have different diameters. Sorting a stack is done by a sequence of pancake ``flips''. A flip consists of inserting a spatula between two pancakes in a stack and flipping (reversing) the pancakes on the spatula (reversing the sub-stack). A flip is specified by giving the position of the pancake on the bottom of the sub-stack to be flipped (relative to the whole stack). The pancake on the bottom of the whole stack has position 1 and the pancake on the top of a stack of n pancakes has position n. A stack is specified by giving the diameter of each pancake in the stack in the order in which the pancakes appear.
For example, consider the three stacks of pancakes below (in which pancake 8 is the top-most pancake of the left stack): 8 7 2 4 6 5 6 4 8 7 8 4 5 5 6 2 2 7 The stack on the left can be transformed to the stack in the middle via flip(3). The middle stack can be transformed into the right stack via the command flip(1).
The Input The input consists of a sequence of stacks of pancakes. Each stack will consist of between 1 and 30 pancakes and each pancake will have an integer diameter between 1 and 100. The input is terminated by end-of-file. Each stack is given as a single line of input with the top pancake on a stack appearing first on a line, the bottom pancake appearing last, and all pancakes separated by a space. The Output For each stack of pancakes, the output should echo the original stack on one line, followed by some sequence of flips that results in the stack of pancakes being sorted so that the largest diameter pancake is on the bottom and the smallest on top. For each stack the sequence of flips should be terminated by a 0 (indicating no more flips necessary). Once a stack is sorted, no more flips should be made. Sample Input 1 2 3 4 5 5 4 3 2 1 5 1 2 3 4 Sample Output 1 2 3 4 5 0 5 4 3 2 1 1 0 5 1 2 3 4 1 2 0
Problem : Bridge UVa ID: 10037, Popularity: B. Success rate: low Level: 3 n 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. Input The input begins with a single positive integer on a line by itself indicating the number of the cases following, each of them as described below. This line is followed by a blank line, and there is also a blank line between two consecutive inputs. The 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.
Output For each test case, the output must follow the description below. The outputs of two consecutive cases will be separated by a blank line. The 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 1 4 1 2 5 10 Sample Output 17 1 2 1 5 10 2 1 2
Problem : Longest Nap UVa ID: 10191, Popularity: B. Success rate: average Level: 1 The Problem As you may already know, there are professors very busy with a filled schedule of work during the day. Your professor, let's call him Professor P, is a bit lazy and wants to take a nap during the day, but as his schedule is very busy, he doesn't have a lot of chances of doing this. He would REALLY like, however, to take one nap every day. Because he'll take just one nap, he wants to take the longest nap that it's possible given his schedule. He decided to write a program to help him in this task but, as we said, Professor P is very lazy. So, he finally decided that YOU must write the program! The Input The input will consist on an arbitrary number of test cases, each test case represents one day. The first line of each set contains a positive integer s (not greater than 100) representing the number of scheduled appointments during that day. In the next s lines there are the appointments in the following format: time1 time2 appointment Where time1 represents the time which the appointment starts and time2 the time it ends. All times will be in the hh:mm format, time1 will always be strictly less than time2, they will be separated by a single space and all times will be greater than or equal to 10:00 and less than or equal to 18:00. So, your response must be in this interval as well (i.e. no nap can start before 10:00 and last after 18:00). The appointment can be any sequence of characters, but will always be in the same line. You can assume that no line will be longer than 255 characters, that 10 <= hh <= 18 and that 0 <= mm < 60. You CAN'T assume, however, that the input will be in any specific order. You must read the input until you reach the end of file.
The Output For each test case, you must print the following line: Day #d: the longest nap starts at hh:mm and will last for [H hours and] M minutes. Where d stands for the number of the test case (starting from 1) and hh:mm is the time when the nap can start. To display the duration of the nap, follow these simple rules: if the total duration X in minutes is less than 60, just print "M minutes", where M = X. if the total duration X in minutes is greater or equal to 60, print "H hours and M minutes", where H = X div 60 (integer division, of course) and M = X mod 60. Notice that you don't have to worry with concordance (i.e. you must print "1 minutes" or "1 hours" if it's the case). The duration of the nap is calculated by the difference between the ending time free and the begining time free. That is, if an appointment ends at 14:00 and the next one starts at 14:47, then you have (14:47)-(14:00) = 47 minutes of possible nap. If there is more than one longest nap with the same duration, print the earliest one. You can assume that there won't be a day all busy (i.e. you may assume that there will be at least one possible nap).
Sample Input 4 10:00 12:00 Lectures 12:00 13:00 Lunch, like always. 13:00 15:00 Boring lectures... 15:30 17:45 Reading 4 10:00 12:00 Lectures 12:00 13:00 Lunch, just lunch. 13:00 15:00 Lectures, lectures... oh, no! 16:45 17:45 Reading (to be or not to be?) 4 10:00 12:00 Lectures, as everyday. 12:00 13:00 Lunch, again!!! 13:00 15:00 Lectures, more lectures! 15:30 17:15 Reading (I love reading, but should I schedule it?) 1 12:00 13:00 I love lunch! Have you ever noticed it? :) Sample Output Day #1: the longest nap starts at 15:00 and will last for 30 minutes. Day #2: the longest nap starts at 15:00 and will last for 1 hours and 45 minutes. Day #3: the longest nap starts at 17:15 and will last for 45 minutes. Day #4: the longest nap starts at 13:00 and will last for 5 hours and 0 minutes.
Problem : CDVII UVa ID: 10138, Popularity: C. Success rate: low Level: 2 Roman roads are famous for their longevity and sound engineering. Unfortunately, sound engineering does not come cheap, and a number of neo-Caesars have decided to recover the costs through automated tolling. A particular toll highway, the CDVII, has a fare structure that works as follows: travel on the road costs a certain amount per km travelled, depending on the time of day when the travel begins. Cameras at every entrance and every exit capture the license numbers of all cars entering and leaving. Every calendar month, a bill is sent to the registered owner for each km travelled (at a rate determined by the time of day), plus one dollar per trip, plus a two dollar account charge. Your job is to prepare the bill for one month, given a set of license plate photos. Input The input begins with a single positive integer on a line by itself indicating the number of the cases following, each of them as described below. This line is followed by a blank line, and there is also a blank line between two consecutive inputs. Standard input has two parts: the fare structure, and the license photos. The fare structure consists of a line with 24 non-negative integers denoting the toll (cents/km) from 00:00 - 00:59, the toll from 01:00 - 00:59, and so on for each hour in the day. Each photo record consists of the license number of the vehicle (up to 20 alphanumeric characters), the time and date (mm:dd:hh:mm), the word "enter" or "exit", and the location of the entrance or exit (in km from one end of the highway). All dates will be within a single month. Each "enter" record is paired with the chronologically next record for the same vehicle provided it is an "exit" record. "enter" records that are not paired with an "exit" record are ignored, as are "exit" records not paired with an "enter" record. You may assume that no two records for the same vehicle have the same time. Times are recorded using a 24-hour clock. There are not more than 1000 photo records.
Output For each test case, the output must follow the description below. The outputs of two consecutive cases will be separated by a blank line. Print a line for each vehicle indicating the license number, and the total bill, in alphabetical order by license number. Vehicles that don't use the highway shouldn't be listed. Sample Input 1 10 10 10 10 10 10 20 20 20 15 15 15 15 15 15 15 20 30 20 15 15 10 10 10 ABCD123 01:01:06:01 enter 17 765DEF 01:01:07:00 exit 95 ABCD123 01:01:08:03 exit 95 765DEF 01:01:05:59 enter 17 Sample Input 765DEF $10.80 ABCD123 $18.60
Problem : ShellSort UVa ID: 10152, Popularity: B. Success rate: average Level: 2 The Problem King Yertle wishes to rearrange his turtle throne to place his highest-ranking nobles and closest advisors nearer to the top. A single operation is available to change the order of the turtles in the stack: a turtle can crawl out of its position in the stack and climb up over the other turtles to sit on the top. Given an original ordering of a turtle stack and a required ordering for the same turtle stack, your job is to determine a minimal sequence of operations that rearranges the original stack into the required stack. The first line of the input consists of a single integer K giving the number of test cases. Each test case consist on an integer n giving the number of turtles in the stack. The next n lines specify the original ordering of the turtle stack. Each of the lines contains the name of a turtle, starting with the turtle on the top of the stack and working down to the turtle at the bottom of the stack. Turtles have unique names, each of which is a string of no more than eighty characters drawn from a character set consisting of the alphanumeric characters, the space character and the period (`.'). The next n lines in the input gives the desired ordering of the stack, once again by naming turtles from top to bottom. Each test case consists of exactly 2n+1 lines in total. The number of turtles (n) will be less than or equal to two hundred. For each test case, the output consists of a sequence of turtle names, one per line, indicating the order in which turtles are to leave their positions in the stack and crawl to the top. This sequence of operations should transform the original stack into the required stack and should be as short as possible. If more than one solution of shortest length is possible, any of the solutions may be reported. Print a blank line after each test case.
Sample Input 2 3 Yertle Duke of Earl Sir Lancelot Duke of Earl Yertle Sir Lancelot 9 Yertle Duke of Earl Sir Lancelot Elizabeth Windsor Michael Eisner Richard M. Nixon Mr. Rogers Ford Perfect Mack Yertle Richard M. Nixon Sir Lancelot Duke of Earl Elizabeth Windsor Michael Eisner Mr. Rogers Ford Perfect Mack
Sample Output Duke of Earl Sir Lancelot Richard M. Nixon Yertle