lunes, 24 de septiembre de 2012

Echenle ganas que quiero que me traigan una como ésta xD.

lunes, 10 de septiembre de 2012

Concurso Fes Acatlán




Les dejo el enlace para que vean los detalles: http://cimac.acatlan.unam.mx/?m=concurso#
quien este interesado en participar comuniquelo a los demas.

Raggedy, Raggedy Regional 2011 North America Mid Atlantic


Consider the problem of laying out text in lines of a fixed maximum width L (a.k.a., ``line filling'').
If you do a poor job,
the ends of the lines are unnecessarily
ragged - like
this paragraph. Now,
by convention, we allow the last line of a paragraph to be arbitrarily ragged. We don't mind if that final line contains just a few characters, but we expect the earlier lines to be of approximately uniform length, filling up the column in which we are setting the text.
\epsfbox{p5945.eps}
The straightforward approach of filling each line with as many words as will fit and then moving to the next line does not always yield the most aesthetically pleasing results. For example, the sequence
See if we care.
could be laid out in L = 6 like this:
See if
we
care.
That layout is, arguably, not as visually pleasing as
See
if we
care.
Define a ``word'' as any sequence of non-whitespace characters bounded by a line start or end or by a blank. The legal ``whitespace characters'' in this problem are blanks and the line terminator characters.
Given a sequence of N words of width w1, w2,..., wN, and a maximum line width L, with the guarantee that for all i, wi $ \leq$ L, define w(i, j) as the width of the line containing words i through j, inclusive, plus one blank space between each pair of words.
Then we can define the raggedness of a line containing words i though j as
r(i, j) = (L - w(i, j))2
Write a program to read paragraphs of text and to lay them out in a way that no line contains more than L characters, for a specified L, and so that you minimize the total raggedness added up over all lines except the last one. (The final line of a paragraph can be arbitrarily shorter then the lines above it.) Line terminator characters are not counted as part of the line width.

Input 

Input will consist of one or more datasets.
Each dataset begins with a line containing one integer, L, denoting the maximum line width (not counting line terminator characters). You are guaranteed that 0 < L $ \leq$ 80. A value of zero indicates the end of input.
The remainder of the dataset consists of up to 250 lines containing a paragraph of text, terminated by an empty line. Paragraphs may contain from 1 to 500 words, where a word is any consecutive sequence of non-whitespace characters.
No line of text will contain a word of length greater than L.

Output 

Print each paragraph laid out optimally as described above. After each paragraph print a line containing ``==='' (three equal signs).
If there is more than one way to fill a paragraph with the optimal raggedness, any such layout may be printed.

Sample Input 

6
See if we 
care.

25
Raggedy, raggedy are we.
Just as raggedy as raggedy can be.
We don't get nothin' for our labor.
So raggedy, raggedy are we.
- P Seeger

0

Sample Output 

See
if we
care.
===
Raggedy, raggedy are
we. Just as raggedy
as raggedy can be. We
don't get nothin' for
our labor. So raggedy,
raggedy are we. - P
Seeger
===

jueves, 2 de agosto de 2012

Problema de la UVA 12318

Recientemente elegimos este problema para trabajar con él. Básicamente, te dan un polinomio de grado k menor o igual a 10 y la idea es averiguar cuantos resultados distintos modulo n+1 (con n menor o igual a 10 000 000) podemos obtener evaluándolo con los enteros del 0 al m menor o igual a 100 000 . Todos los coeficientes del polinomio son mayores o iguales a 0 y menores o iguales a n. Creo que lo primero es ver cómo evaluar rápidamente el polinomio módulo n+1 y después ver cómo averiguar cuántos resultados fueron diferentes. El límite de tiempo es de 4 segundos, y el problema es multicasos. La descripción del problema es la siguiente:

  Digital Roulette 

John is developing a videogame that allows players to bet in a wall roulette. Players may bet for integer numbers from 0 to N, for some N$ \ge$ 0 that represents the maximum number in the roulette.

Of course, the roulette behaves digitally. As a matter of fact, John designed its way to choose a value in the interval 0..N (the result of spinning the roulette) with a digital trigger that moves the roulette with a force that depends on an integer value x randomly chosen in the interval 0..M, where M$ \ge$ 0 (M is the maximal appliable force). The roulette turns around a distance equivalent to P(x), where P is a polynomial with integer coefficients. One distance unit represents a displacement of one roulette number, counting clockwise.


It is clear that some result values may be produced by different chosen force values. Also, depending on the mechanism parameters, some numbers in the roulette may be not attainable regardless of the force value. For example, if N = 7, M = 5 and P(x) = x2 + 1, the mechanism can generate only three different results:

\epsfbox{p12318.eps}


John wants to know how many different result values may be attained by his mechanism. Can you help him?

Input 

There are several cases to analyze. Each case is described by three lines:
  • The first line contains two non-negative integer numbers N and M, separated by a blank ( 1 $ \leq$ N $ \leq$ 107, 0 $ \leq$ M $ \leq$ 105).
  • The second line contains an integer k, the grad of the polynomial P ( 0 $ \leq$ k $ \leq$ 10).
  • The third line contains k + 1 integers a0, a1,..., ak separated by blanks, indicating the integer coefficients that define the polynomial P, i.e., P(x) = akxk + ... + a1x + a0. You can assume that 0 $ \leq$ ai $ \leq$ N for each 0 $ \leq$ i $ \leq$ k. If k > 0 then you may assume that ak $ \neq$ 0.
The last test case is followed by a line containing two zeros.

Output 

For each case, print one line indicating how many different numbers are attainable by John's mechanism.

Sample Input 


7 5
2
1 0 1
99 10
0
5
99 10
1
5 25
99 10
1
3 29
99 10
2
3 29 31
0 0

Sample Output 


3
1
4
11
10



jueves, 21 de junio de 2012

Duda libreria iostream

Hola,

que saben acerca del uso de la libreria iostream?
del hecho de que deba ponerse.h o no para declarla?
que se deba poner using namespace std; o std:: antes de cada objeto o funcion?

Yo intente usar << de cout, sin poner using namespace std; y no lo compilaba bien codeblocks

lunes, 18 de junio de 2012

Problema de esta semana: COJ 1500 an express taxi

Descripción

In a long street the traffic of express taxies is organized in the following way: There is a taxi stop every one kilometer. An express taxi drives along the street from each stop 1, 2, 3, ... or 10 kilometers without a stop. For each of the ten distances a separate price is fixed and marked in the table, e.g. 1 12 2 21 3 31 4 40 5 49 6 58 7 69 8 79 9 90 10 101 A passenger wants to travel n (1 <= n <= 100) kilometers. Can you write a program to helping on that. Which driving distances does the passenger have to choose so that the journey would be the cheapest, and what is the total price of the journey.

Especificación de entrada

The input has two lines. The first line contains ten space separated integer numbers which are prices for driving 1, 2, 3, ... , 10 kilometers. The last line contains the number of kilometers (n) which the passenger has to travel.

Especificación de salida

Each line except the last one should contain two numbers which are the length of the route and the price of the ticket. The total price of the journey should be written in the last line of the output. If several solutions are possible, choose one of them where tickets (in ascending ordered by the distance) are minimum.

Ejemplo de entrada

12 21 31 40 49 58 69 79 90 101
15

Ejemplo de salida

3 31
6 58
6 58
147

miércoles, 30 de mayo de 2012

Resultados del concurso de hoy en el Politécnico

Quedamos en segundo lugar. ¡El próximo tenemos que ir por el primero! El score final fue el siguiente:


sábado, 26 de mayo de 2012

Teoria para revisar

Hola,

les dejo los links de 2 libros que me recomendaron:

http://acm.cs.buap.mx/downloads/Programming_Challenges.pdf
http://acm.uva.es/p/Art_of_Programming_Contest_SE_for_uva.pdf

viernes, 25 de mayo de 2012

Concurso de programación en el Politécnico

Hola a todos, espero estén bien. Este miércoles 30 de mayo habrá un concurso de programación en el ESCOM, que forma parte del Politécnico. El concurso es en equipos de 2 o 3 integrantes, con un examen de dos horas de duración. El sistema de evalución utilizado será el mismo que en un ACM ICPC (PC2) aunque habrá algunas diferencias (como la de la duración). Hay que hacer lo posible por participar, el link con la información es el siguiente:

http://148.204.58.221/capituloacm/?c=contenidos/portada.htm

Pues ¡a prepararnos!


domingo, 20 de mayo de 2012

No habrá curso del sábado 26 de mayo

Hola a todos, espero estén bien. El próximo sábado 26 de mayo se llevará a cabo en la Facultad el concurso de matemáticas Galois-Noether, motivo por el cual varios de los integrantes del club no podremos presentarnos a programar. Ese día no tendremos curso. Si les interesa el concurso Galois-Noether pueden ver la convocatoria y más información en el blog http://blog.nekomath.com/

Cambiando de tema, las próximas sesiones en el curso de programación trabajaremos con los problemas del libro Programming Challenges. La idea es resolverlos todos en el orden en que aparecen en el libro. Los primeros son muy sencillos, solo hay que cuidar algunos detalles en la implementación. Vayan revisándolos, los tres primeros tienen ID's 100, 10189 y 10137, de modo que el primero está en la carpeta Problem Set Volumes y los dos que siguen en la carpeta Contest Volumes. En el libro aparecen en las páginas de la 15 a la 17, o 35 a 37 en la versión en PDF. Estos problemas son sencillos, pero es importante hacerlos para practicar en la implementación. Debemos tener la mayor habilidad posible para implementar el código.

No duden en publicar dudas, comentarios, sugerencias o cualquier otra cosa, como avances en los problemas o códigos.


domingo, 13 de mayo de 2012

Problema para la tercera semana de mayo

Hola a todos. El problema para esta semana es de la UVA Online Judge. Es uno de esos problemas que involucran mapas de caracteres, lo que es en realidad bastante común. La idea es realizar una búsqueda de manera inteligente, una búsqueda de la ruta más corta. Tomen en cuenta los límites de las variables, que no son muy grandes. El tiempo límite es de 3 s. El problema es de la carpeta Contest Volumes, tiene el ID 10818. Publiquen todas sus dudas, comentarios y avances en la solución:


Problem E: Dora Trip
Time limit: 3 seconds


Nobita is in great trouble. Today he failed to hand in his homework again, so he was heavily punished at school. Learning that, his mother gets furious, and therefore assigns him many tasks to do - to buy vegetables at the market, to collect a parcel at the post office and a lot more. Nobita certainly does not want to see his teacher on his way, nor would he like to meet Jyian, the tough bully. As usual, he asks Doraemon for help.
"Oh no!" cried Doraemon. "My everywhere door is broken, and my small propellers have all run out of batteries..." Well, that means Nobita has got to go without Doraemon's magic tools. "Ah, I still have this. It may well be useful." From his 4th-dimensional pocket, Doraemon takes out a map of their living area. He then marks on it the places where Nobita has to visit by asterisks ('*'), and where Jyian or his teacher may appear by crosses ('X'). Now Nobita's job is simple - he has to find the shortest route, through which he would not visit any of the 'crosses', and he could finish the maximum number of the jobs (if not all) given by mum. What he needs is just a computer program that works out the path...
Imagine that you are Nobita. Write the program.

Input

The input file contains no more than 20 test cases. The details of each set are given as follows:
The first line of each case contains two integers r and c (1 <= r, c <= 20), which are the number of rows and columns of the map respectively. The next r lines, each with c characters, give the map itself. For each character, a space `` '' stands for an open space; a hash mark ``#'' stands for an obstructing wall; the capital letter ``S'' stands for the position of Nobita's house, which is where his journey is to start and end; the capital letter ``X'' stands for a dangerous place; and an asterisk ``*'' stands for a place he has to visit. The perimeter of the map is always closed, i.e., there is no way to get out from the coordinate of the ``S''. The number of places that Nobita has to visit is at most 10.
The input file is terminated by a null case where r = c = 0. This case should not be processed.

Output

For each test case, if Nobita cannot visit any target places at all, just print the line "Stay home!". Otherwise, your program should output the lexicographically smallest shortest path so that the number of target places that Nobita visits is maximized. Use the letters 'N', 'S', 'E' and 'W' to denote north, south, east and west respectively. Note that by 'north' we mean facing upwards. You can be sure that the length of a correct output path will never exceed 200.


Sample Input

5 5
#####
#  S#
# XX#
#  *#
#####
5 5
#####
#* X#
###X#
#S *#
#####
5 5
#####
#S X#
#  X#
# #*#
#####
0 0

Sample Output

WWSSEEWWNNEE
EEWW
Stay home!


Problemsetter: Mak Yan Kei

domingo, 6 de mayo de 2012

Un problema de caribbean online judge

Descripción

Thank to cryptography, we are able to encrypt messages such that none (except the intended recipient) is able to read them. However, encrypted messages are of no use if they do not actually reach the recipient. These days, computer network is the most typical mean to send such messages. In this problem, we will study the issues the networking providers have to solve. And remember: since the message is encrypted, we do not need to care about the network privacy anymore.

The network cables joining computers (servers) belong to different companies. A new anti-monopoly legislation prevents any company from owning more than two cables from each server. Furthermore, to avoid wasting resources, there is also a law specifying that the cable system owned by any single company cannot be redundant, i.e., removal of any of the cables will disconnect some two previously connected servers. Since the companies buy and sell the cables all the time, it is quite difficult to enforce these regulations. Your task is to write a program that does so.

Especificación de entrada

The input contains several instances. The first line of each instance contains four integers N, M, C and T separated by spaces - the number of servers (1 <= N <= 8000), the number of cables (0 <= M <= 10^5), the number of companies (1 <= C <= 10^2), and the number of cable-selling transactions (0 <= T <= 10^5), respectively.

The following M lines describe the cables. Each of them contains three integers Sj1 , Sj2 and Kj , separated by spaces, giving the numbers of the servers Sj1 and Sj2 (1 <= Sj1 < Sj2 <= N) joined by that cable and the number of the company Kj (1 <= Kj <= C) initially owning the cable. For each pair of servers, there is at most one cable joining them. The initial state satisfies the regulations, i.e., each company owns at most two cables incident with each server, and the system of cables owned by a single company has no cycles.

Finally, each of the next T lines contains integers Si1 , Si2 and Ki describing one transaction in which the company Ki (1 <= Ki <= C) tries to buy a cable between servers Si1 and Si2 (1 <= Si1 < Si2 <= N).

The last instance is followed by a line containing four zeros.

Especificación de salida

For each input instance, output T lines describing the outcome of the transactions. The possible outcomes are:
  • "No such cable." if the pair of servers is not joined by a cable,
  • "Already owned." if the cable is already owned by the company Ki,
  • "Forbidden: monopoly." if the company Ki already owns two cables at Si1 or Si2,
  • "Forbidden: redundant." if Ki owns at most one cable at each of Si1 and Si2, but granting the ownership would create a cycle of cables owned by Ki,
  • "Sold." if none of the above restrictions apply. In this case, the ownership of the cable between Si1 and Si2 changes to Ki for the purpose of further transactions.
  • Print one empty line after each instance.

Ejemplo de entrada

4 5 3 5
1 2 1
2 3 1
3 4 2
1 4 2
1 3 3
1 2 3
1 2 3
1 4 3
2 3 3
2 4 3
2 1 1 1
1 2 1
1 2 1
0 0 0 0

Ejemplo de salida

Sold.
Already owned.
Forbidden: monopoly.
Forbidden: redundant.
No such cable.

Already owned.

Sugerencia(s)


Origen2010/2011 ACM-ICPC Central Europe Regional Contest
Adicionado porymondelo20
Fecha de adición2012-04-22
Tiempo límite (ms) 10000
Memoria límite (kb) 130000
Salida límite (mb) 64
Tamaño límite (bytes) 30000
Languages activados C  C#  C++  Java  Pascal  Perl  PHP  Python  Ruby  Text 
Arriba

domingo, 29 de abril de 2012

Problema para la primer semana de mayo

Cambiando un poco el rumbo, propongo ahora que trabajemos con el problema Minas de la OMI Trainingate. Comenten todas sus ideas, avances o cualquier otro comentario.


Buscaminas Reloaded

Karelov III 2007
Tiempo: 1 segundo
Seguramente ya conoces el juego de buscaminas, en el cual tu empiezas con una cuadricula cubierta de cuadrados sin idea de qué hay en ellos. Seleccionando un cuadrado revela que hay en él(puede ser una mina o un espacio vacio).
Si encuentras un cuadro con un espacio vacío un número es impreso dentro de ese cuadro diciéndote cuántas minas son adyacentes a ese espacio vacío.
Un buen día te topaste con un juego de buscaminas con unicamente 2 filas y con N columnas.
Decidiste aventurarte un poco y seleccionaste todos los cuadrados de una de las filas, y como estabas de suerte, ninguno de los cuadrados de la fila resultó tener minas.
Sin embargo, en dicha fila aparecieron muchos números indicando cuántas minas había adyacentes a cada cuadro(todas las minas resultaron estar en la otra fila).

Problema

Dados los números que aparecieron en la fila que seleccionaste, determina en qué lugares de la otra fila debe haber minas.

Entrada

La primera línea contendrá un número entero 1≤N≤200, la segunda línea contendrá unicamente N dígitos(números del 1 al 9) sin espacios representando el contenido de los cuadrados de la fila que seleccionaste.

Salida

Deberá contener una sola línea con N caracteres, cada caracter deberá ser un '.' si no hay mina en su posición correspondiente o un '*' si la hay. Se garantiza que siempre habrá una y solo una solución posible.

Ejemplo


Entrada
6
112110
Salida
.*.*..

Consideraciones

Se garantiza que siempre habrá solamente una solución posible, además 1≤N≤200.




sábado, 28 de abril de 2012

Carta de Apoyo

Esta es la carta que presentamos en direccion el Viernes 13 de abril.


Viernes 13 de abril de 2012
Directora de la Facultad de Ciencias

PRESENTE:

Por medio de este conducto hacemos de su conocimiento las actividades que ha desempeñado el Club de Programación PUMASMAS (Pu++) y de la situación en la que se encuentra. Este club ha sido integrado por alumnos de esta facultad con el propósito de aprender a programar e integrar equipos para participar en diversos concursos representando a la Facultad de Ciencias. Actualmente contamos con varios integrantes y hemos tomado parte ya en algunos concursos.
Sin embargo, pese a nuestro entusiasmo, hemos tenido que enfrentarnos a una serie de dificultades:
- Falta de un espacio con equipos de cómputo para trabajar.
- Falta de un asesor con experiencia en C++ que nos entrene para los concursos.
- Falta de apoyo para solventar gastos que se generan al tomar parte de los concursos. (Inscripción, transporte, alimentación, hospedaje, etc.)
No obstante, a pesar de esto, hemos logrado representar a la Facultad de Ciencias en varios concursos obteniendo los siguientes resultados:

Evento
Lugar y fecha de realización
Lugar obtenido
ACM-ICPC
México Occidente y Pacífico
24 de septiembre de 2011
16° lugar-50 equipos
ACM-ICPC ITAM
(Examen de preparación)
15 de octubre de 2011
ITAM
2° lugar-23 equipos
2° Concurso Nacional de Programación en Software Libre
20 de octubre de 2011
3° Congreso Nacional de Tecnología Computacional e Informática (FES Acatlán)
3° lugar-20 equipos
ACM ICPC
México y Centroamérica
5 de noviembre de 2011
ITESO, Guadalajara
7° lugar 160 equipos
Considerando esto, quisiéramos solicitar su apoyo para poder exponer nuestro caso a las instancias pertinentes y así poder contar con un espacio para trabajar, un asesor y apoyo económico para cubrir los gastos generados por los concursos. Esto, con la finalidad de que el club siga creciendo y podamos hacer un mejor papel en eventos futuros.
Agradecemos su atención y esperamos que pueda prestarnos su apoyo.
A T E N T A M E N T E
Club de programación “PUMASMAS”

domingo, 22 de abril de 2012

Problema de la semana: 714 UVA Online Judge

Continuando con los problemas de la UVA Online Judge, propongo que trabajemos con el siguiente problema. Por favor, escriban sus dudas, comentarios o avances en la solución. Probablemente el sábado revisemos la solución de este problema y el de la semana pasada.


  Copying Books 

Before the invention of book-printing, it was very hard to make a copy of a book. All the contents had to be re-written by hand by so called scribers. The scriber had been given a book and after several months he finished its copy. One of the most famous scribers lived in the 15th century and his name was Xaverius Endricus Remius Ontius Xendrianus (Xerox). Anyway, the work was very annoying and boring. And the only way to speed it up was to hire more scribers.


Once upon a time, there was a theater ensemble that wanted to play famous Antique Tragedies. The scripts of these plays were divided into many books and actors needed more copies of them, of course. So they hired many scribers to make copies of these books. Imagine you have m books (numbered $1, 2, \dots, m$) that may have different number of pages ( $p_1, p_2, \dots, p_m$) and you want to make one copy of each of them. Your task is to divide these books among k scribes, $k \le m$. Each book can be assigned to a single scriber only, and every scriber must get a continuous sequence of books. That means, there exists an increasing succession of numbers$0 = b_0 <
b_1 < b_2, \dots < b_{k-1} \le b_k = m$ such that i-th scriber gets a sequence of books with numbers between bi-1+1 and bi. The time needed to make a copy of all the books is determined by the scriber who was assigned the most work. Therefore, our goal is to minimize the maximum number of pages assigned to a single scriber. Your task is to find the optimal assignment.

Input 

The input consists of N cases. The first line of the input contains only positive integer N. Then follow the cases. Each case consists of exactly two lines. At the first line, there are two integers m and k$1 \le k \le m \le 500$. At the second line, there are integers$p_1, p_2, \dots p_m$ separated by spaces. All these values are positive and less than 10000000.

Output 

For each case, print exactly one line. The line must contain the input succession $p_1, p_2, \dots p_m$ divided into exactly k parts such that the maximum sum of a single part should be as small as possible. Use the slash character (`/') to separate the parts. There must be exactly one space character between any two successive numbers and between the number and the slash.


If there is more than one solution, print the one that minimizes the work assigned to the first scriber, then to the second scriber etc. But each scriber must be assigned at least one book.

Sample Input 

2
9 3
100 200 300 400 500 600 700 800 900
5 4
100 100 100 100 100

Sample Output 

100 200 300 400 500 / 600 700 / 800 900
100 / 100 / 100 / 100 100



Miguel A. Revilla
2000-02-15

lunes, 16 de abril de 2012

¡¡Va el de esta semana!!

Este problema es de un concurso de la UVA Online Judge.
Yo intente resolverlo, segun creo mi programa lo resuelve, pero no el tiempo indicado.

C
Consistent Verdicts
In a 2D plane N persons are standing and each of them has a gun in his hand. The plane is so big that the persons can be considered as points and their locations are given as Cartesian coordinates. Each of the N persons fire the gun in his hand exactly once and no two of them fire at the same or similar time (the sound of two gun shots are never heard at the same time by anyone so no sound is missed due to concurrency). The hearing ability of all these persons is exactly same. That means if one person can hear a sound at distance R1, so can every other person and if one person cannot hear a sound at distance R2 the other N-1 persons cannot hear a sound at distance R2 as well.
The N persons are numbered from 1 to N. After all the guns are fired, all of them are asked how many gun shots they have heard (not including their own shot) and they give their verdict. It is not possible for you to determine whether their verdicts are true but it is possible for you to judge if their verdicts are consistent. For example, look at the figure above. There are five persons and their coordinates are (1, 2), (3, 1), (5, 1), (6, 3) and (1, 5) and they are numbered as 1, 2, 3, 4 and 5 respectively. After all five of them have shot their guns, you ask them how many shots each of them have heard. Now if there response is 1, 1, 1, 2 and 1 respectively then you can represent it as (1, 1, 1, 2, 1). But this is an inconsistent verdict because if person 4 hears 2 shots then he must have heard the shot fired by person 2, then obviously person 2 must have heard the shot fired by person 1, 3 and 4 (person 1 and 3 are nearer to person 2 than person 4). But their opinions show that Person 2 says that he has heard only 1 shot. On the other hand (1, 2, 2, 1, 0) is a consistent verdict for this scenario so is (2, 2, 2, 1, 1). In this scenario (5, 5, 5, 4, 4) is not a consistent verdict because a person can hear at most 4 shots.
Given the locations of N persons, your job is to find the total number of different consistent verdicts for that scenario. Two verdicts are different if opinion of at least one person is different.


Input

The first line of input will contain T (≤ 550) denoting the number of cases.
Each case starts with a line containing a positive integer N. Each of the next N lines contains two integers xi yi (0 ≤ xi, yi ≤ 30000) denoting a co-ordinate of a person. Assume that all the co-ordinates are distinct.
1)      For 10 cases, N = 1000.
2)      For 15 cases, 100 ≤ N < 1000.
3)      For others, N < 100.

Output

For each case, print the case number and the total number of different consistent verdicts for the given scenario.

Sample Input

Output for Sample Input

2
3
1 1
2 2
4 4
2
1 1
5 5
Case 1: 4
Case 2: 2

"Problemas semanales"

Anteriormente he publicado algunos problemas que no he podido resolver, sin embargo, algunos no los han visto ya que usualmente no revisan su correo o el blog.
Considero que seria apropiado que resolvieramos por lo menos un problema a la semana, ademas de los que hacemos el sabado, por lo que les propongo lo siguiente:

Cada lunes, antes de las 10:00 p.m, Alain o Yo propondremos un problema a resolver (no es mucho pedir que  revisen el blog una vez a la semana). Si lo resuelven publiquen su respuesta, si no pongan sus avances, dudas, etc. que sera enriquecedor al grupo.

sábado, 14 de abril de 2012

Problem B: Ultra-QuickSort

In this problem, you have to analyze a particular sorting algorithm. The algorithm processes a sequence of n distinct integers by swapping two adjacent sequence elements until the sequence is sorted in ascending order. For the input sequence
9 1 0 5 4 ,
Ultra-QuickSort produces the output
0 1 4 5 9 .
Your task is to determine how many swap operations Ultra-QuickSort needs to perform in order to sort a given input sequence.

The input contains several test cases. Every test case begins with a line that contains a single integer n < 500,000 -- the length of the input sequence. Each of the the following n lines contains a single integer 0 ≤ a[i] ≤ 999,999,999, the i-th input sequence element. Input is terminated by a sequence of length n = 0. This sequence must not be processed.

For every input sequence, your program prints a single line containing an integer number op, the minimum number of swap operations necessary to sort the given input sequence.

sábado, 24 de marzo de 2012

Solución al problema Moscas de la Omi Training Gate

Este problema ejemplifica el uso de la idea subyacente en el algoritmo de ordenación por conteo (también conocido como ordenación por cubetas). Una posible solución es la siguiente:

#include<stdio.h>
long n[60002],i,s,k,x,y,m;
int main(){
scanf("%ld",&k);
for(i=0;i<k;i++){
scanf("%ld %ld",&x,&y);
n[x]++;
n[y]--;
}
for(i=0;i<60001;i++){
s=s+n[i];
if(s>m)
m=s;
}
x=0;
y=0;
printf("%ld\n",m);
for(i=0;i<60001;i++){
if(s==m&&s+n[i]<m)
printf("%ld %ld ",x,i);
if(s<m&&s+n[i]==m)
x=i;
s=s+n[i];
}
}


miércoles, 21 de marzo de 2012

Concurso de la UVA Online Judge

Les dejo el link donde podran ver los problemas del concurso en linea de la UVA:
http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=13&page=show_contest&contest=296

Yo intente hacer el C y el H, pero mis algoritmos no eran eficientes, por lo que no me los aceptaron. Se los dejo como comentarios.

Si a alguien se le ocurre como resolverlos, o algun otro de la UVA, posteen su codigo.

sábado, 17 de marzo de 2012

Un número redivisible es aquel que es divisible entre su número de divisores positivos. Por ejemplo 1(1 divisor), 12(6 divisores) y 9(3 divisores) pero no 7(2 divisores) ni 16(5 divisores)

Escribe un programa que dados dos enteros l y h, diga cuántos números refactorizables hay entre l y h, inclusive.