├── uni-no-fiis ├── clase-11 │ ├── README.md │ └── problemas_resueltos.md ├── clase-06 │ ├── soluciones │ │ ├── README.md │ │ ├── p10.py │ │ ├── p08.cpp │ │ ├── p06.cpp │ │ ├── p04.cpp │ │ ├── p01.cpp │ │ ├── p05.cpp │ │ ├── p02.cpp │ │ ├── p09.cpp │ │ ├── p03.cpp │ │ └── p07.cpp │ └── ejemplos │ │ ├── big-oh.png │ │ ├── namespace.cpp │ │ └── struct.cpp ├── clase-07 │ ├── soluciones │ │ ├── README.md │ │ ├── G.cpp │ │ ├── H.cpp │ │ ├── F.cpp │ │ ├── J.cpp │ │ ├── C.cpp │ │ ├── A.cpp │ │ ├── M.cpp │ │ ├── E.cpp │ │ ├── L.cpp │ │ ├── B.cpp │ │ ├── K.cpp │ │ ├── D.cpp │ │ └── I.cpp │ └── pictures │ │ ├── heroe.jpg │ │ ├── peko.jpg │ │ ├── smile.jpg │ │ ├── smile2.jpg │ │ ├── viejo.jpg │ │ ├── dragon2.jpg │ │ ├── pekohero.gif │ │ ├── dragonduda.jpg │ │ ├── heroeayuda.jpg │ │ ├── pekohero2.jpg │ │ └── ping-pong.png ├── clase-08 │ ├── README.md │ ├── p3.py │ ├── p2.cpp │ ├── p4.cpp │ ├── p3.cpp │ ├── p1.cpp │ ├── p5.cpp │ └── p6.cpp ├── clase-03 │ └── pictures │ │ ├── coc.jpg │ │ ├── pig.png │ │ ├── bruja.jpg │ │ ├── dragon.png │ │ ├── Miner_22.png │ │ └── referencias.png ├── clase-05 │ ├── soluciones │ │ ├── 3.cpp │ │ ├── 5.cpp │ │ ├── 6.cpp │ │ ├── 2.cpp │ │ ├── 7.cpp │ │ ├── 9.cpp │ │ └── 8.cpp │ └── pictures │ │ ├── adios.jpg │ │ ├── alien.png │ │ ├── dios.jpg │ │ ├── loco.jpg │ │ ├── tememe.jpg │ │ └── comenzamos.jpg ├── clase-09 │ ├── pictures │ │ ├── Koch.gif │ │ └── Recursion.jpg │ ├── soluciones │ │ ├── p09.py │ │ ├── p04.cpp │ │ ├── p01.cpp │ │ ├── p02.cpp │ │ ├── p07.cpp │ │ ├── p03.cpp │ │ ├── p08.cpp │ │ ├── p06.cpp │ │ └── p05.cpp │ └── ejemplos │ │ ├── Fit_Squares_in_Triangle.cpp │ │ ├── All_Squares.cpp │ │ └── Connecting_Soldiers.cpp ├── clase-10 │ ├── pictures │ │ ├── patron.jpg │ │ ├── hadouken.jpg │ │ └── recursive.jpg │ └── ejemplos │ │ ├── subset-sum.cpp │ │ ├── 42-recursive.cpp │ │ ├── n-queen.cpp │ │ ├── patron.cpp │ │ └── 42-iterative.cpp ├── clase-12 │ └── pictures │ │ ├── Grafo1.png │ │ └── FiboGraph.PNG ├── clase-13 │ └── pictures │ │ ├── 1nhk.jpg │ │ ├── 2nhk.jpg │ │ ├── 3nhk.jpg │ │ ├── 4nhk.jpg │ │ ├── 5nhk.jpg │ │ └── 6nhk.jpg ├── clase-14 │ ├── pictures │ │ ├── minimax.png │ │ ├── ejercicio.png │ │ ├── tic-tac-toe.png │ │ ├── solucion-ejercicio.png │ │ └── games-clasification.jpg │ └── ejemplos │ │ ├── 10165.cpp │ │ ├── ASTRGAME.cpp │ │ ├── 10404.cpp │ │ └── GAME31.cpp ├── clase-02 │ ├── pictures │ │ └── imagen-01.png │ ├── soluciones │ │ ├── 220A.cpp │ │ ├── 00484.cpp │ │ ├── 11849.cpp │ │ ├── 10954.cpp │ │ ├── 137C.cpp │ │ ├── 01062.cpp │ │ ├── 352B.cpp │ │ └── 00540.cpp │ └── ejemplos │ │ ├── istringstream.cpp │ │ ├── UVA10324-Zeros-and-Ones.cpp │ │ ├── stack.cpp │ │ ├── sort.cpp │ │ └── stl.cpp ├── clase-04 │ ├── pictures │ │ ├── We-Must-Return.jpg │ │ ├── Do-You-Know-De-Wae.jpg │ │ └── I-Showed-You-De-Wae.png │ └── soluciones │ │ ├── p05.cpp │ │ ├── p06.cpp │ │ ├── p07.cpp │ │ ├── p02.cpp │ │ ├── p09.cpp │ │ ├── p01.cpp │ │ ├── p08.cpp │ │ ├── p03.cpp │ │ ├── p04.cpp │ │ └── p10.cpp ├── clase-01 │ ├── soluciones │ │ ├── p05-v2.cpp │ │ ├── p02-v2.cpp │ │ ├── README.md │ │ ├── p01-v2.cpp │ │ ├── p02-v1.cpp │ │ ├── p04-v2.cpp │ │ ├── p01-v1.cpp │ │ ├── p03-v2.cpp │ │ ├── p03-v1.cpp │ │ ├── p04-v1.cpp │ │ ├── p05-v1.cpp │ │ ├── p06-v2.cpp │ │ └── p06-v1.cpp │ └── ejemplos │ │ ├── 01-hola-mundo.cpp │ │ ├── 07-entrada-y-salida-ejemplo-2.cpp │ │ ├── 06-entrada-y-salida-ejemplo-1.cpp │ │ ├── 05-estructuras-de-repeticion.cpp │ │ ├── 08-vectores.cpp │ │ ├── 04-estructuras-de-control.cpp │ │ ├── 02-tipos-de-datos.cpp │ │ └── 09-string.cpp └── README.md ├── exámenes ├── 2015 │ └── 15_Algoritmos.pdf ├── 2017 │ ├── 17_RM.pdf │ └── 17_Algoritmos.pdf ├── 2018 │ ├── 18_RM.pdf │ ├── 18_Algoritmos.pdf │ └── solucionario │ │ ├── 18_solucion_rm.pdf │ │ ├── probC.py │ │ ├── probA.py │ │ ├── probC.cpp │ │ ├── probA.cpp │ │ ├── probB.py │ │ ├── probD.cpp │ │ ├── probBv1.cpp │ │ ├── probBv2.cpp │ │ └── probE.py └── 2019 │ └── 19_algoritmos.pdf ├── uni-fiis └── README.md ├── .gitignore ├── PASTMEMBERS.md └── README.md /uni-no-fiis/clase-11/README.md: -------------------------------------------------------------------------------- 1 | # Repaso backtrack 2 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-06/soluciones/README.md: -------------------------------------------------------------------------------- 1 | # [Contest](https://vjudge.net/contest/214970) 2 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-07/soluciones/README.md: -------------------------------------------------------------------------------- 1 | ## [Contest](https://vjudge.net/contest/215934 'Binary Search 1') 2 | -------------------------------------------------------------------------------- /exámenes/2017/17_RM.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/exámenes/2017/17_RM.pdf -------------------------------------------------------------------------------- /exámenes/2018/18_RM.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/exámenes/2018/18_RM.pdf -------------------------------------------------------------------------------- /uni-no-fiis/clase-08/README.md: -------------------------------------------------------------------------------- 1 | ## [Soluciones del primer contest mixto](https://a2oj.com/standings?ID=35903 'A2OJ') 2 | -------------------------------------------------------------------------------- /exámenes/2015/15_Algoritmos.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/exámenes/2015/15_Algoritmos.pdf -------------------------------------------------------------------------------- /exámenes/2017/17_Algoritmos.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/exámenes/2017/17_Algoritmos.pdf -------------------------------------------------------------------------------- /exámenes/2018/18_Algoritmos.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/exámenes/2018/18_Algoritmos.pdf -------------------------------------------------------------------------------- /exámenes/2019/19_algoritmos.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/exámenes/2019/19_algoritmos.pdf -------------------------------------------------------------------------------- /uni-no-fiis/clase-03/pictures/coc.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/uni-no-fiis/clase-03/pictures/coc.jpg -------------------------------------------------------------------------------- /uni-no-fiis/clase-03/pictures/pig.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/uni-no-fiis/clase-03/pictures/pig.png -------------------------------------------------------------------------------- /uni-no-fiis/clase-05/soluciones/3.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/uni-no-fiis/clase-05/soluciones/3.cpp -------------------------------------------------------------------------------- /uni-no-fiis/clase-03/pictures/bruja.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/uni-no-fiis/clase-03/pictures/bruja.jpg -------------------------------------------------------------------------------- /uni-no-fiis/clase-03/pictures/dragon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/uni-no-fiis/clase-03/pictures/dragon.png -------------------------------------------------------------------------------- /uni-no-fiis/clase-05/pictures/adios.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/uni-no-fiis/clase-05/pictures/adios.jpg -------------------------------------------------------------------------------- /uni-no-fiis/clase-05/pictures/alien.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/uni-no-fiis/clase-05/pictures/alien.png -------------------------------------------------------------------------------- /uni-no-fiis/clase-05/pictures/dios.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/uni-no-fiis/clase-05/pictures/dios.jpg -------------------------------------------------------------------------------- /uni-no-fiis/clase-05/pictures/loco.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/uni-no-fiis/clase-05/pictures/loco.jpg -------------------------------------------------------------------------------- /uni-no-fiis/clase-05/pictures/tememe.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/uni-no-fiis/clase-05/pictures/tememe.jpg -------------------------------------------------------------------------------- /uni-no-fiis/clase-06/ejemplos/big-oh.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/uni-no-fiis/clase-06/ejemplos/big-oh.png -------------------------------------------------------------------------------- /uni-no-fiis/clase-07/pictures/heroe.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/uni-no-fiis/clase-07/pictures/heroe.jpg -------------------------------------------------------------------------------- /uni-no-fiis/clase-07/pictures/peko.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/uni-no-fiis/clase-07/pictures/peko.jpg -------------------------------------------------------------------------------- /uni-no-fiis/clase-07/pictures/smile.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/uni-no-fiis/clase-07/pictures/smile.jpg -------------------------------------------------------------------------------- /uni-no-fiis/clase-07/pictures/smile2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/uni-no-fiis/clase-07/pictures/smile2.jpg -------------------------------------------------------------------------------- /uni-no-fiis/clase-07/pictures/viejo.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/uni-no-fiis/clase-07/pictures/viejo.jpg -------------------------------------------------------------------------------- /uni-no-fiis/clase-09/pictures/Koch.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/uni-no-fiis/clase-09/pictures/Koch.gif -------------------------------------------------------------------------------- /uni-no-fiis/clase-10/pictures/patron.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/uni-no-fiis/clase-10/pictures/patron.jpg -------------------------------------------------------------------------------- /uni-no-fiis/clase-12/pictures/Grafo1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/uni-no-fiis/clase-12/pictures/Grafo1.png -------------------------------------------------------------------------------- /uni-no-fiis/clase-13/pictures/1nhk.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/uni-no-fiis/clase-13/pictures/1nhk.jpg -------------------------------------------------------------------------------- /uni-no-fiis/clase-13/pictures/2nhk.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/uni-no-fiis/clase-13/pictures/2nhk.jpg -------------------------------------------------------------------------------- /uni-no-fiis/clase-13/pictures/3nhk.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/uni-no-fiis/clase-13/pictures/3nhk.jpg -------------------------------------------------------------------------------- /uni-no-fiis/clase-13/pictures/4nhk.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/uni-no-fiis/clase-13/pictures/4nhk.jpg -------------------------------------------------------------------------------- /uni-no-fiis/clase-13/pictures/5nhk.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/uni-no-fiis/clase-13/pictures/5nhk.jpg -------------------------------------------------------------------------------- /uni-no-fiis/clase-13/pictures/6nhk.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/uni-no-fiis/clase-13/pictures/6nhk.jpg -------------------------------------------------------------------------------- /uni-no-fiis/clase-03/pictures/Miner_22.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/uni-no-fiis/clase-03/pictures/Miner_22.png -------------------------------------------------------------------------------- /uni-no-fiis/clase-07/pictures/dragon2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/uni-no-fiis/clase-07/pictures/dragon2.jpg -------------------------------------------------------------------------------- /uni-no-fiis/clase-07/pictures/pekohero.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/uni-no-fiis/clase-07/pictures/pekohero.gif -------------------------------------------------------------------------------- /uni-no-fiis/clase-10/pictures/hadouken.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/uni-no-fiis/clase-10/pictures/hadouken.jpg -------------------------------------------------------------------------------- /uni-no-fiis/clase-14/pictures/minimax.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/uni-no-fiis/clase-14/pictures/minimax.png -------------------------------------------------------------------------------- /exámenes/2018/solucionario/18_solucion_rm.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/exámenes/2018/solucionario/18_solucion_rm.pdf -------------------------------------------------------------------------------- /uni-no-fiis/clase-02/pictures/imagen-01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/uni-no-fiis/clase-02/pictures/imagen-01.png -------------------------------------------------------------------------------- /uni-no-fiis/clase-03/pictures/referencias.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/uni-no-fiis/clase-03/pictures/referencias.png -------------------------------------------------------------------------------- /uni-no-fiis/clase-05/pictures/comenzamos.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/uni-no-fiis/clase-05/pictures/comenzamos.jpg -------------------------------------------------------------------------------- /uni-no-fiis/clase-07/pictures/dragonduda.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/uni-no-fiis/clase-07/pictures/dragonduda.jpg -------------------------------------------------------------------------------- /uni-no-fiis/clase-07/pictures/heroeayuda.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/uni-no-fiis/clase-07/pictures/heroeayuda.jpg -------------------------------------------------------------------------------- /uni-no-fiis/clase-07/pictures/pekohero2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/uni-no-fiis/clase-07/pictures/pekohero2.jpg -------------------------------------------------------------------------------- /uni-no-fiis/clase-07/pictures/ping-pong.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/uni-no-fiis/clase-07/pictures/ping-pong.png -------------------------------------------------------------------------------- /uni-no-fiis/clase-09/pictures/Recursion.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/uni-no-fiis/clase-09/pictures/Recursion.jpg -------------------------------------------------------------------------------- /uni-no-fiis/clase-10/pictures/recursive.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/uni-no-fiis/clase-10/pictures/recursive.jpg -------------------------------------------------------------------------------- /uni-no-fiis/clase-12/pictures/FiboGraph.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/uni-no-fiis/clase-12/pictures/FiboGraph.PNG -------------------------------------------------------------------------------- /uni-no-fiis/clase-14/pictures/ejercicio.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/uni-no-fiis/clase-14/pictures/ejercicio.png -------------------------------------------------------------------------------- /uni-no-fiis/clase-14/pictures/tic-tac-toe.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/uni-no-fiis/clase-14/pictures/tic-tac-toe.png -------------------------------------------------------------------------------- /uni-no-fiis/clase-04/pictures/We-Must-Return.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/uni-no-fiis/clase-04/pictures/We-Must-Return.jpg -------------------------------------------------------------------------------- /uni-no-fiis/clase-04/pictures/Do-You-Know-De-Wae.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/uni-no-fiis/clase-04/pictures/Do-You-Know-De-Wae.jpg -------------------------------------------------------------------------------- /uni-no-fiis/clase-14/pictures/solucion-ejercicio.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/uni-no-fiis/clase-14/pictures/solucion-ejercicio.png -------------------------------------------------------------------------------- /exámenes/2018/solucionario/probC.py: -------------------------------------------------------------------------------- 1 | ''' 2 | By: Victoralin10 3 | ''' 4 | 5 | n, m, a = (int(x) for x in input().split()) 6 | print (((n - 1)//a + 1)*((m - 1)//a + 1)) 7 | 8 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-04/pictures/I-Showed-You-De-Wae.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/uni-no-fiis/clase-04/pictures/I-Showed-You-De-Wae.png -------------------------------------------------------------------------------- /uni-no-fiis/clase-14/pictures/games-clasification.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GPC-UNI/Programacion-Competitiva/HEAD/uni-no-fiis/clase-14/pictures/games-clasification.jpg -------------------------------------------------------------------------------- /exámenes/2018/solucionario/probA.py: -------------------------------------------------------------------------------- 1 | ''' 2 | By: Victoralin10 3 | ''' 4 | 5 | n = int(input()) 6 | print ("SI" if n == sum([x for x in range(1, n) if n%x == 0]) else "No") 7 | 8 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-09/soluciones/p09.py: -------------------------------------------------------------------------------- 1 | # Pregunta con truco, recuerden usar Python de vez en cuando. 2 | 3 | t = int(input()) 4 | while t > 0: 5 | a,b = [int(x) for x in input().split()] 6 | print(a*b) 7 | t = t - 1 8 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-08/p3.py: -------------------------------------------------------------------------------- 1 | l, r, k = map(int, input().split()) 2 | ans = [] 3 | p = 1 4 | while True: 5 | if l <= p <= r: ans += [p] 6 | if p > r: break 7 | p *= k 8 | print(-1 if len(ans) == 0 else ' '.join(str(ans_i) for ans_i in ans)); 9 | -------------------------------------------------------------------------------- /exámenes/2018/solucionario/probC.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * By: Victoralin10 3 | */ 4 | 5 | #include 6 | 7 | using namespace std; 8 | 9 | int main() { 10 | int n, m, a; 11 | cin >> n >> m >> a; 12 | cout << (long long)((n -1 )/a + 1)*((m - 1)/a + 1) << endl; 13 | } 14 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-01/soluciones/p05-v2.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Usando Finding pattern or formula 3 | */ 4 | 5 | #include 6 | 7 | using namespace std; 8 | 9 | int n; 10 | 11 | int main() { 12 | while (~scanf("%d", &n)) printf("%d\n", n + n / 2); 13 | return (0); 14 | } -------------------------------------------------------------------------------- /uni-no-fiis/clase-01/soluciones/p02-v2.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Usando Finding pattern or formula 3 | */ 4 | 5 | #include 6 | 7 | using namespace std; 8 | 9 | int n, a, b; 10 | 11 | int main() { 12 | cin >> n >> a >> b; 13 | cout << min(n - a, b + 1) << endl; 14 | return (0); 15 | } -------------------------------------------------------------------------------- /exámenes/2018/solucionario/probA.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * By: Rmg_91 3 | */ 4 | #include 5 | using namespace std; 6 | 7 | int main(){ 8 | int n, sd = 0; 9 | cin >> n; 10 | for( int i = 1; i < n; ++i ){ 11 | if( n % i == 0 ) sd += i; 12 | } 13 | if( n == sd ) cout << "SI"; 14 | else cout << "NO"; 15 | return 0; 16 | } 17 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-01/ejemplos/01-hola-mundo.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // Este es un comentario en línea 4 | 5 | /* 6 | 7 | Esto 8 | es 9 | un 10 | comentario 11 | 12 | */ 13 | 14 | using namespace std; 15 | 16 | int main() { 17 | 18 | cout << "Hola mundo\n"; 19 | cout << "Hola mundo" << std::endl; 20 | 21 | return 0; 22 | } -------------------------------------------------------------------------------- /uni-no-fiis/clase-01/soluciones/README.md: -------------------------------------------------------------------------------- 1 | # Soluciones del [Contest 01](https://a2oj.com/standings?ID=35118 'contest 01') 2 | 3 | Dos soluciones para cada problema. 4 | 5 | La primera versión es con lo enseñado la última clase. 6 | 7 | La segunda versión es con temas que verán más adelante. Es para que se hagan una idea de que un mismo problema suele tener más de una solución. 8 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-14/ejemplos/10165.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | int n; 7 | while (scanf("%d", &n), n) { 8 | int xor_sum = 0; 9 | for (int i = 0, x_i; i < n; i++) { 10 | scanf("%d", &x_i); 11 | xor_sum ^= x_i; 12 | } 13 | puts(xor_sum == 0 ? "No" : "Yes"); 14 | } 15 | return (0); 16 | } 17 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-02/soluciones/220A.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int n, _diff; 6 | 7 | int main() { 8 | cin >> n; 9 | vector a(n), b(n); 10 | for (int i = 0; i < n; i++) cin >> a[i], b[i] = a[i]; 11 | sort(b.begin(), b.end()); 12 | for (int i = 0; i < n; i++) if (a[i] != b[i]) _diff++; 13 | puts(_diff <= 2 ? "YES" : "NO"); 14 | return (0); 15 | } -------------------------------------------------------------------------------- /uni-no-fiis/clase-06/soluciones/p10.py: -------------------------------------------------------------------------------- 1 | import math 2 | import functools 3 | 4 | def main(): 5 | while True: 6 | try: 7 | n, k = int(input()), input() 8 | z = list(map(int, input().split())) 9 | except EOFError: 10 | break 11 | print(math.factorial(n) // functools.reduce(lambda a, b: a * math.factorial(b), z, 1)) 12 | 13 | if __name__ == '__main__': 14 | main() 15 | 16 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-02/soluciones/00484.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int id, num; 6 | map frec, order; 7 | set vis; 8 | 9 | int main() { 10 | while (cin >> num) { 11 | frec[num]++; 12 | if (vis.find(num) == vis.end()) order[id++] = num; 13 | vis.insert(num); 14 | } 15 | for (int i = 0; i < id; i++) cout << order[i] << ' ' << frec[order[i]] << endl; 16 | return (0); 17 | } -------------------------------------------------------------------------------- /uni-no-fiis/clase-08/p2.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Link 3 | * http://codeforces.com/problemset/problem/626/C 4 | */ 5 | 6 | #include 7 | 8 | using namespace std; 9 | 10 | int n, m, ans; 11 | 12 | int main() { 13 | cin >> n >> m; 14 | while (true) { 15 | if ((n <= ans / 2) and 16 | (m <= ans / 3) and 17 | (n + m <= ans / 2 + ans / 3 - ans / 6)) break; 18 | ans++; 19 | } 20 | return (0); 21 | } 22 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-08/p4.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Link 3 | * http://codeforces.com/problemset/problem/276/D 4 | * Check this 5 | * https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html#Other-Builtins 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | 12 | long long l, r; 13 | 14 | int main() { 15 | cin >> l >> r; 16 | l == r ? cout << 0 << endl : cout << (1LL << (64 - __builtin_clzll(l xor r))) - 1 << endl; 17 | return (0); 18 | } 19 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-02/ejemplos/istringstream.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | string s; 6 | 7 | int main(){ 8 | 9 | //getline(cin, s); 10 | int x, n = 0, acum = 0; 11 | 12 | s = "10 20 30 40 -2 -5 0"; 13 | 14 | istringstream ss(s); 15 | 16 | while(ss >> x){ 17 | acum += x; 18 | n++; 19 | } 20 | 21 | cout << "Se ingresaron " << n << " numeros" << endl; 22 | cout << "La suma es: " << acum << "." << endl; 23 | 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-01/soluciones/p01-v2.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Usando sort 3 | */ 4 | 5 | #include 6 | 7 | using namespace std; 8 | 9 | int d1, d2, d3; 10 | vector routes; 11 | 12 | int main() { 13 | cin >> d1 >> d2 >> d3; 14 | routes.push_back(d1 + d1 + d2 + d2); 15 | routes.push_back(d1 + d3 + d2); 16 | routes.push_back(d1 + d3 + d3 + d1); 17 | routes.push_back(d2 + d3 + d3 + d2); 18 | sort(routes.begin(), routes.end()); 19 | cout << routes.front() << endl; 20 | return (0); 21 | } -------------------------------------------------------------------------------- /uni-no-fiis/clase-06/soluciones/p08.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define SIZE 60 4 | 5 | using namespace std; 6 | 7 | int n; 8 | string v[SIZE], s1, s2; 9 | 10 | bool cmp(const string& x, const string& y){ 11 | s1 = x + y, s2 = y + x; 12 | return (s1 > s2); 13 | } 14 | 15 | int main(){ 16 | while(scanf("%d", &n), n!=0){ 17 | for (int i = 0; i < n; i++) cin >> v[i]; 18 | sort(v, v + n, cmp); 19 | for (int i = 0; i < n; i++) cout << v[i]; cout << endl; 20 | } 21 | return(0); 22 | } 23 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-02/soluciones/11849.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int n, m, num, ans; 6 | 7 | int main() { 8 | while (scanf("%d %d", &n, &m), n or m) { 9 | set st; 10 | ans = 0; 11 | for (int i = 0; i < n; i++) scanf("%d", &num), st.insert(num); 12 | for (int i = 0; i < m; i++) { 13 | scanf("%d", &num); 14 | if (st.find(num) != st.end()) ans++; 15 | } 16 | printf("%d\n", ans); 17 | } 18 | return (0); 19 | } -------------------------------------------------------------------------------- /uni-no-fiis/clase-02/soluciones/10954.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int N, ans, num; 6 | 7 | int main() { 8 | while (cin >> N, N) { 9 | ans = 0; 10 | priority_queue v; 11 | for (int i = 0; i < N; i++) cin >> num, v.push(-num); 12 | for (int i = 1; i < N; i++) { 13 | int a = v.top(); v.pop(); 14 | int b = v.top(); v.pop(); 15 | ans -= a + b; 16 | v.push(a + b); 17 | } 18 | cout << ans << endl; 19 | } 20 | return (0); 21 | } -------------------------------------------------------------------------------- /uni-fiis/README.md: -------------------------------------------------------------------------------- 1 | ## Índice 2 | 3 | * [Clase 01: Programación Competitiva](https://github.com/Rmg91/Competitive-Programming/tree/master/clase-01 'Clase 01') 4 | * [Clase 02: El lenguaje C++](https://github.com/Rmg91/Competitive-Programming/tree/master/clase-02 'Clase 02') 5 | * [Clase 03: Problemas Ad Hoc](https://github.com/Rmg91/Competitive-Programming/tree/master/clase-03 'Clase 03') 6 | * [Clase 04: Análisis de Algoritmos](https://github.com/Rmg91/Competitive-Programming/tree/master/clase-04 'Clase 04') 7 | * [Ponencias](https://github.com/Rmg91/Competitive-Programming/tree/master/ponencias 'Ponencias') 8 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-01/soluciones/p02-v1.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * link : http://codeforces.com/problemset/problem/124/A 3 | * Problema: 4 | * Quieres determinar en cuantas posibles posiciones podrias estar 5 | */ 6 | 7 | /** 8 | * Solucion: 9 | * Prueba cada posicion y si es valida aumenta la respuesta en 1 10 | */ 11 | 12 | #include 13 | 14 | using namespace std; 15 | 16 | int n, a, b, ans; 17 | 18 | int main() { 19 | cin >> n >> a >> b; 20 | for (int pos = 1; pos <= n; pos++) 21 | if (pos - 1 <= b and a <= n - pos) 22 | ans++; 23 | cout << ans << endl; 24 | return (0); 25 | } -------------------------------------------------------------------------------- /uni-no-fiis/clase-01/soluciones/p04-v2.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Usando Finding pattern or formula 3 | */ 4 | 5 | #include 6 | 7 | using namespace std; 8 | 9 | const int MAX_N = 110; 10 | 11 | int n, ans[MAX_N][MAX_N]; 12 | 13 | int main() { 14 | cin >> n; 15 | for (int pos = 0; pos < n * n; pos++) 16 | ans[pos / n][pos % n] = pos & 1 ? n * n + 1 - ans[pos / n][pos % n - 1] : (pos / n) * n / 2 + (pos % n) / 2 + 1; 17 | for (int row = 0; row < n; row++) 18 | for (int col = 0; col < n; col++) 19 | printf(col == n - 1 ? "%d\n" : "%d ", ans[row][col]); 20 | return (0); 21 | } -------------------------------------------------------------------------------- /exámenes/2018/solucionario/probB.py: -------------------------------------------------------------------------------- 1 | ''' 2 | By: Victoralin10 3 | ''' 4 | 5 | notas = [int(x) for x in input().split()] 6 | a = [0 if x == -1 else x for x in notas] 7 | b = [20 if x == -1 else x for x in notas] 8 | 9 | ans = 0 10 | for pc1 in range(a[0], b[0] + 1): 11 | for pc2 in range(a[1], b[1] + 1): 12 | for pc3 in range(a[2], b[2] + 1): 13 | for pc4 in range(a[3], b[3] + 1): 14 | for ep in range(a[4], b[4] + 1): 15 | for ef in range(a[5], b[5] + 1): 16 | ans += (pc1 + pc2 + pc3 + pc4 - min([pc1, pc2, pc3, pc4]) + (ep + ef)*3>= 90) 17 | print(ans) 18 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-08/p3.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Link 3 | * http://codeforces.com/problemset/problem/614/A 4 | */ 5 | 6 | #include 7 | 8 | using namespace std; 9 | 10 | long long l, r, k; 11 | long double p = 1.0; 12 | bool found = false; 13 | 14 | int main() { 15 | cin >> l >> r >> k; 16 | while (true) { 17 | if (p > r) break; 18 | if (l <= p and p <= r) { 19 | long long pp = (long long) p; 20 | if (l <= pp and pp <= r) 21 | found = true, cout << pp << ' '; 22 | } 23 | p *= k; 24 | } 25 | not found ? cout << -1 << endl : cout << endl; 26 | return (0); 27 | } 28 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-02/ejemplos/UVA10324-Zeros-and-Ones.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define N 1000005 3 | 4 | using namespace std; 5 | 6 | string s; 7 | int n, x, y; 8 | int A[N]; 9 | 10 | 11 | int main(){ 12 | int caso = 1; 13 | 14 | while( cin >> s ){ 15 | A[1] = s[0]-'0'; 16 | for( int i = 1; i < s.length(); i++ ) 17 | A[i+1] = A[i]+(s[i]-'0'); 18 | 19 | scanf("%d",&n); 20 | printf("Case %d:\n",caso++); 21 | for( int i = 0; i < n; i++ ){ 22 | scanf("%d%d",&x,&y); 23 | if( x > y ) swap( x, y ); 24 | if( (y-x+1) == ( A[y+1] - A[x] ) || A[y+1] == A[x] ) puts("Yes"); 25 | else puts("No"); 26 | } 27 | } 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.out 2 | *.o 3 | /uni-no-fiis/clase-01/.ipynb_checkpoints/ 4 | /uni-no-fiis/clase-02/.ipynb_checkpoints/ 5 | /uni-no-fiis/clase-03/.ipynb_checkpoints/ 6 | /uni-no-fiis/clase-04/.ipynb_checkpoints/ 7 | /uni-no-fiis/clase-05/.ipynb_checkpoints/ 8 | /uni-no-fiis/clase-06/.ipynb_checkpoints/ 9 | /uni-no-fiis/clase-07/.ipynb_checkpoints/ 10 | /uni-no-fiis/clase-08/.ipynb_checkpoints/ 11 | /uni-no-fiis/clase-09/.ipynb_checkpoints/ 12 | /uni-no-fiis/clase-10/.ipynb_checkpoints/ 13 | /uni-no-fiis/clase-11/.ipynb_checkpoints/ 14 | /uni-no-fiis/clase-12/.ipynb_checkpoints/ 15 | /uni-no-fiis/clase-13/.ipynb_checkpoints/ 16 | /uni-no-fiis/clase-14/.ipynb_checkpoints/ 17 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-01/soluciones/p01-v1.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * link : http://codeforces.com/problemset/problem/599/A 3 | * Problema: 4 | * Se quiere encontrar el minimo recorrido posible para salir de mi casa, visitar las 2 tiendas y regresa a cada 5 | */ 6 | 7 | /** 8 | * Solucion: 9 | * Son hay 4 posibles rutas que nos podrian dar el minimo recorrido 10 | * Calculamos las 4 y respondemos cual es la de menor valor 11 | */ 12 | 13 | #include 14 | 15 | using namespace std; 16 | 17 | int d1, d2, d3; 18 | 19 | int main() { 20 | cin >> d1 >> d2 >> d3; 21 | cout << min(d1 + d1 + d2 + d2, min(d1 + d3 + d2, min(d1 + d3 + d3 + d1, d2 + d3 + d3 + d2))) << endl; 22 | return (0); 23 | } -------------------------------------------------------------------------------- /uni-no-fiis/clase-11/problemas_resueltos.md: -------------------------------------------------------------------------------- 1 | 1. [Torres de Hanoi](https://ideone.com/eDo8Pz) 2 | 2. [IEHOVA](https://ideone.com/to2ZJm) 3 | 3. [increasing paths](https://ideone.com/uYeEFa) 4 | 4. [knapsack 0/1 problem (optimability)](https://ideone.com/o9qXPj) 5 | 5. [knapsack 0/1 problem](https://ideone.com/fcCknI) 6 | 6. [struct of backtrack](https://ideone.com/4mtB8m) 7 | 7. [print all subset](https://ideone.com/S0CfzO) 8 | 9 | # lists 10 | 11 | 1. [Awesome Competitive Programming](http://codeforces.com/blog/entry/23054) 12 | 2. [Programming Contest Detailed Syllabus Along with Example Problems](https://discuss.codechef.com/questions/121107/programming-contest-detailed-syllabus-along-with-example-problems) 13 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-02/soluciones/137C.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int n, a, b, ans; 6 | vector > v; 7 | 8 | int main() { 9 | cin >> n; 10 | for (int i = 0; i < n; i++) cin >> a >> b, v.push_back({a, b}); 11 | sort(v.begin(), v.end(), [](const pair & x, const pair & y) { 12 | if (x.first != y.first) return x.first < y.first; 13 | return x.second > y.second; 14 | }); 15 | int mx = v[0].second; 16 | for (int i = 1; i < n; i++) { 17 | if (v[i].first > v[i - 1].first and v[i].second < mx) ans++; 18 | mx = max(mx, v[i].second); 19 | } 20 | cout << ans << endl; 21 | return (0); 22 | } -------------------------------------------------------------------------------- /uni-no-fiis/clase-10/ejemplos/subset-sum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int X, n, sum; 6 | vector a, choice; 7 | 8 | void backtracking(int idx = 0) { 9 | if (sum > X) return; 10 | if (sum == X) { 11 | for (int c_i : choice) cout << c_i << ' '; 12 | cout << endl; 13 | return; 14 | } 15 | if (idx == n) return; 16 | sum += a[idx]; 17 | choice.push_back(a[idx]); 18 | backtracking(idx + 1); 19 | sum -= a[idx]; 20 | choice.pop_back(); 21 | backtracking(idx + 1); 22 | } 23 | 24 | int main() { 25 | a = {2, 2, 2, 2, 2, 5, 5, 5, 10, 10, 10, 20}; 26 | n = a.size(); 27 | X = 20; 28 | backtracking(); 29 | return (0); 30 | } 31 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-08/p1.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Link 3 | * http://codeforces.com/problemset/problem/578/B 4 | */ 5 | 6 | #include 7 | 8 | using namespace std; 9 | 10 | const int MAX_N = 2e5 + 10; 11 | 12 | long long n, k, x, ans, prod = 1, arr[MAX_N], prefix[MAX_N], suffix[MAX_N]; 13 | 14 | int main() { 15 | cin >> n >> k >> x; 16 | while (k--) prod *= x; 17 | for (int i = 1; i <= n; i++) cin >> arr[i]; 18 | for (int i = 1; i <= n; i++) prefix[i] = arr[i] bitor prefix[i - 1]; 19 | for (int i = n; i >= 1; i--) suffix[i] = arr[i] bitor suffix[i + 1]; 20 | for (int i = 1; i <= n; i++) 21 | ans = max(ans, prefix[i - 1] bitor (arr[i] * prod) bitor suffix[i + 1]); 22 | cout << ans << endl; 23 | return (0); 24 | } 25 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-02/soluciones/01062.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int tc; 6 | string line; 7 | vector > simulation; 8 | 9 | int main() { 10 | while (cin >> line, line != "end") { 11 | simulation.clear(); 12 | simulation.push_back({line.front()}); 13 | for (int id = 1; id < line.size(); id++) { 14 | char ch = line[id]; 15 | bool inserted = false; 16 | for (int k = 0; k < simulation.size() and not inserted; k++) 17 | if (ch <= simulation[k].back()) simulation[k].push_back(ch), inserted = true; 18 | if (not inserted) simulation.push_back({ch}); 19 | } 20 | cout << "Case " << ++tc << ": " << simulation.size() << endl; 21 | } 22 | return (0); 23 | } -------------------------------------------------------------------------------- /exámenes/2018/solucionario/probD.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * By: Victoralin10 3 | */ 4 | 5 | #include 6 | 7 | using namespace std; 8 | 9 | #define MAXN 100005 10 | 11 | int S[MAXN], cs[10], cp[10]; 12 | 13 | int main() { 14 | int n, m, ans = 0; 15 | cin >> n >> m; 16 | for (int i = 0; i < n; i++) { 17 | cin >> S[i]; 18 | } 19 | for (int i = 0, p; i < m; i++) { 20 | cin >> p; 21 | cp[p]++; 22 | } 23 | for (int i = 0; i < m; i++) { 24 | cs[S[i]]++; 25 | } 26 | for (int i = m; i <= n; i++) { 27 | bool ok = 1; 28 | for (int j = 0; j < 10; j++) { 29 | ok = ok && (cs[j] == cp[j]); 30 | } 31 | ans += ok; 32 | cs[S[i]]++; 33 | cs[S[i - m]]--; 34 | } 35 | cout << ans << endl; 36 | } 37 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-01/soluciones/p03-v2.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Usando DP 3 | */ 4 | 5 | #include 6 | 7 | using namespace std; 8 | 9 | const int MAX_N = 1e6 + 10; 10 | 11 | int ct, a, b, dp[MAX_N]; 12 | long long n; 13 | 14 | int getAns(int a, int b) { 15 | int ans = 0; 16 | for (int it = a; it <= b; it++) 17 | if (dp[it] > ans) ans = dp[it]; 18 | return ans; 19 | } 20 | 21 | void precal() { 22 | for (int it = 1; it < MAX_N; it++) { 23 | ct = 1, n = it; 24 | while (n != 1) { 25 | ct++; 26 | n = (n & 1) ? 3 * n + 1 : n / 2; 27 | if (n < it) ct += dp[n] - 1, n = 1; 28 | } 29 | dp[it] = ct; 30 | } 31 | } 32 | 33 | int main(){ 34 | precal(); 35 | while(~scanf("%d %d", &a, &b)) printf("%d %d %d\n", a, b, getAns(min(a, b), max(a, b))); 36 | return(0); 37 | } -------------------------------------------------------------------------------- /uni-no-fiis/clase-02/ejemplos/stack.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | string s; 6 | 7 | int main(){ 8 | int tc; 9 | cin >> tc; 10 | 11 | getline(cin, s); 12 | 13 | while(tc--){ 14 | getline(cin, s); 15 | stackpila; 16 | 17 | bool ok = true; 18 | for(int i=0; ok and i 2 | 3 | using namespace std; 4 | 5 | const int SUM = 42, MAX_LEN = 7; 6 | 7 | int sum; 8 | string word; 9 | vector ans; 10 | 11 | void backtracking(char ch = 'a') { 12 | if (sum > SUM) return; 13 | if (sum == SUM and word.size() <= MAX_LEN) { 14 | do { 15 | ans.push_back(word); 16 | } while(next_permutation(begin(word), end(word))); 17 | } 18 | for (char nch = ch; nch <= 'z'; nch++) { 19 | sum += nch - 'a' + 1; 20 | word.push_back(nch); 21 | backtracking(nch); 22 | word.pop_back(); 23 | sum -= nch - 'a' + 1; 24 | } 25 | } 26 | 27 | int main() { 28 | backtracking(); 29 | sort(begin(ans), end(ans)); 30 | for (string ans_i : ans) cout << ans_i << endl; 31 | return (0); 32 | } 33 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-01/ejemplos/07-entrada-y-salida-ejemplo-2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | /** 7 | * Problema 8 | * Recibiremos un número t 9 | * Si t es 1 recibiremos 3 números y tenemos que imprimir la suma de ellos 10 | * Si t es 2 recibiremos 2 números y tendremos que imprimir el producto 11 | * Si t es 3 recibiremos un número y tendremos que imprimir ese número elevado al cuadrado 12 | * 13 | */ 14 | 15 | int t, num_1, num_2, num_3; 16 | cin >> t; 17 | if (t == 1) { 18 | cin >> num_1 >> num_2 >> num_3; 19 | cout << num_1 + num_2 + num_3 << endl; 20 | } 21 | else if (t == 2) { 22 | cin >> num_1 >> num_2; 23 | cout << num_1 * num_2 << endl; 24 | } 25 | else if (t == 3) { 26 | cin >> num_1; 27 | cout << num_1 * num_1 << endl; 28 | } 29 | return (0); 30 | } -------------------------------------------------------------------------------- /uni-no-fiis/clase-02/soluciones/352B.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int n, num; 6 | vector > v, ans; 7 | 8 | void check(int _start, int _end) { 9 | int _diff = (v[_end - 1].second - v[_start].second) / max(1, (_end - _start - 1)); 10 | while (++_start < _end) if (v[_start].second - v[_start - 1].second != _diff) return; 11 | ans.push_back(make_pair(v[--_start].first, _diff)); 12 | } 13 | 14 | int main() { 15 | cin >> n; 16 | for (int id = 0; id < n; id++) cin >> num, v.push_back(make_pair(num, id)); 17 | sort(v.begin(), v.end()); 18 | int _start = 0, _end = 0; 19 | while (_start < n) { 20 | while (_end < n and v[_start].first == v[_end].first) _end++; 21 | check(_start, _end); 22 | _start = _end; 23 | } 24 | cout << ans.size() << endl; 25 | for (auto pp : ans) cout << pp.first << ' ' << pp.second << endl; 26 | return (0); 27 | } -------------------------------------------------------------------------------- /PASTMEMBERS.md: -------------------------------------------------------------------------------- 1 | ## Ex Integrantes : 2 | 3 | | A - J | K - Z | 4 | | ------------- | ------------- | 5 | | Alex Velasque Espinoza | Kevin Bello Medina| 6 | | Anthony Polin Matos | Laurence Perales Guerrero | 7 | | Christian Huanatico Chombo | Leonardo León Vera | 8 | | Daniel Soncco Huarsaya | Maicol Gómez Zegarra | 9 | | David López Davalos | Manuel Loaiza Vásquez | 10 | | Diego López Gil | Mario Ynocente Castro | 11 | | Diego Mansilla Mallqui | Maritza Lapa Romero | 12 | | Edgar Huaranga Junco | Ricardo Zárate Aima | 13 | | Eduardo Meléndez Ramírez De Castilla | Roberto Hidalgo Castro | 14 | | Francisco Fernández Berrocal | Ronald Cardenas Acosta | 15 | | Giancarlo Vargas Mendieta | Roy Palacios Rezza | 16 | | Hans Evangelista Pérez | Víctor Chura Quispe | 17 | | Jair Loayza Suasnabar | Víctor Mandujano Gutiérrez | 18 | | Jason Martínez Vera 19 | | Jefferson Rondan Vilca 20 | | Jesús Lovon Melgarejo 21 | | Jonathan Durand Espinoza 22 | | Jorge Miranda Jaime 23 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-08/p5.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Link 3 | * https://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=131 4 | */ 5 | 6 | #include 7 | 8 | using namespace std; 9 | 10 | int T; 11 | string word; 12 | vector ans; 13 | 14 | bool cmp(string s_1, string s_2) { 15 | for (int i = 0; i < s_1.size(); i++) { 16 | if (s_1[i] == s_2[i]) continue; 17 | if (tolower(s_1[i]) != tolower(s_2[i])) return tolower(s_1[i]) < tolower(s_2[i]); 18 | return s_1[i] < s_2[i]; 19 | } 20 | } 21 | 22 | int main() { 23 | cin >> T; 24 | while (T--) { 25 | ans.clear(); 26 | cin >> word; 27 | sort(begin(word), end(word)); 28 | do { 29 | ans.push_back(word); 30 | } while(next_permutation(begin(word), end(word))); 31 | sort(begin(ans), end(ans), cmp); 32 | for (string s : ans) cout << s << endl; 33 | } 34 | return (0); 35 | } 36 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-06/soluciones/p06.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define SIZE 10 4 | #define LIM 1010 5 | 6 | using namespace std; 7 | 8 | int nt, nd, ct; 9 | char number[SIZE]; 10 | vector > aux; 11 | pair ss; 12 | 13 | char look_and_say_sequence(string s, int pos, int digit){ 14 | while (--pos) { 15 | aux.clear(); 16 | for (int i = 0; i < s.size() && i < LIM; ){ 17 | ss.first = s[i], ct = 0; 18 | for (; i < s.size() && i < LIM; i++) 19 | if (ss.first==s[i]) ct++; 20 | else break; 21 | ss.second = ct; 22 | aux.push_back(ss); 23 | } 24 | s = ""; 25 | for(int i = 0; i < aux.size(); i++){ 26 | s += to_string(aux[i].second); 27 | s += aux[i].first; 28 | } 29 | } 30 | return s[digit - 1]; 31 | } 32 | 33 | int main(){ 34 | while (scanf("%s %d %d\n", number, &nt, &nd), number[0]!=0 && nt && nd) 35 | printf("%c\n", look_and_say_sequence(string(number), nt, nd)); 36 | return(0); 37 | } 38 | 39 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-04/soluciones/p05.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * LINK DEL PROBLEMA: 3 | * https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=3084 4 | * 5 | * SOLUCIÓN: 6 | * Iteramos por todos los 1 en la representacion binaria de 'n' y con ello 7 | * vamos formando los números 'a' y 'b' 8 | * 9 | * COMPLEJIDAD: 10 | * O(log(n)) 11 | * 12 | * DETALLES DE LA IMPLEMENTACIÓN: 13 | * n & -n = 2 ** (posición del 1 más a la derecha de 'n') 14 | */ 15 | 16 | 17 | #include 18 | 19 | using namespace std; 20 | 21 | int n, a, b; 22 | 23 | void print() { 24 | cout << a << ' ' << b << endl; 25 | } 26 | 27 | void solve() { 28 | a = b = 0; 29 | bool flag = true; 30 | while (n) { 31 | flag ? a |= n bitand -n : b |= n bitand -n; 32 | n = n bitand (n - 1); 33 | flag = !flag; 34 | } 35 | } 36 | 37 | int main() { 38 | while (cin >> n, n) { 39 | solve(); 40 | print(); 41 | } 42 | return (0); 43 | } 44 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-06/soluciones/p04.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define LIM 40000 4 | 5 | using namespace std; 6 | 7 | int tc, lo, hi; 8 | vector Kaprekar_number; 9 | bool ok; 10 | 11 | bool check(int num, int sum) { 12 | int _left,_right,pib=1; 13 | _left = num, _right = 0; 14 | while (_left) { 15 | _right += pib * (_left % 10); 16 | _left /= 10; 17 | if(_left + _right == sum && _left * _right) return true; 18 | pib *= 10; 19 | } 20 | return false; 21 | } 22 | 23 | int main(){ 24 | for(int it = 1; it < LIM; it++) 25 | if (check(it * it, it)) Kaprekar_number.push_back(it); 26 | scanf("%d", &tc); 27 | for(int t = 1; t <= tc; t++){ 28 | ok = true; 29 | scanf("%d %d", &lo, &hi); 30 | printf("case #%d\n", t); 31 | for(int it = 0; it < Kaprekar_number.size(); it++) 32 | if(lo <= Kaprekar_number[it] && Kaprekar_number[it] <= hi) 33 | printf("%d\n", Kaprekar_number[it]), ok = false; 34 | if (ok) puts("no kaprekar numbers"); 35 | if (t != tc) putchar('\n'); 36 | } 37 | return(0); 38 | } 39 | 40 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-06/ejemplos/namespace.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Los 'namespace' nos permiten encapsular información (variables, funciones, structs, ...) 3 | * Así, podemos tener un función con el mismo nombre y que reciba los mismo parametros en 4 | * distintos 'namespace' sin que haya ambigüedad entre ellas 5 | * Usar 'namespace' puede ayudarnos a hacer nuestro código más organizado 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | 12 | namespace Espanol { 13 | void saludar() { 14 | cout << "Hola mundo" << endl; 15 | } 16 | } 17 | 18 | namespace Ingles { 19 | void saludar() { 20 | cout << "Hello world" << endl; 21 | } 22 | } 23 | 24 | namespace Marginal { 25 | void saludar() { 26 | cout << "WASAAAAA" << endl; 27 | } 28 | } 29 | 30 | void saludar() { 31 | cout << "Hola!" << endl; 32 | } 33 | 34 | int main() { 35 | saludar(); // equivalente ::saludar(); 36 | Espanol::saludar(); 37 | Ingles::saludar(); 38 | Marginal::saludar(); 39 | return (0); 40 | } 41 | -------------------------------------------------------------------------------- /exámenes/2018/solucionario/probBv1.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * By: Victoralin10 3 | */ 4 | 5 | #include 6 | 7 | using namespace std; 8 | 9 | int main() { 10 | int notas[6], a[6], b[6], ans = 0; 11 | for (int i = 0; i < 6; i++) { 12 | cin >> notas[i]; 13 | if (notas[i] == -1) { 14 | a[i] = 0, b[i] = 20; 15 | } else { 16 | a[i] = b[i] = notas[i]; 17 | } 18 | } 19 | 20 | for (int pc1 = a[0]; pc1 <= b[0]; pc1++) { 21 | for (int pc2 = a[1]; pc2 <= b[1]; pc2++) { 22 | for (int pc3 = a[2]; pc3 <= b[2]; pc3++) { 23 | for (int pc4 = a[3]; pc4 <= b[3]; pc4++) { 24 | for (int ep = a[4]; ep <= b[4]; ep++) { 25 | for (int ef = a[5]; ef <= b[5]; ef++) { 26 | ans += (pc1 + pc2 + pc3 + pc4 - min(min(pc1, pc2), min(pc3, pc4)) + (ef + ep)*3 >= 90); 27 | } 28 | } 29 | } 30 | } 31 | } 32 | } 33 | 34 | cout << ans << endl; 35 | } 36 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-14/ejemplos/ASTRGAME.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int T, N; 6 | string S, word; 7 | set dict; 8 | unordered_map memo; 9 | 10 | inline int _hash(const int& l, const int& r) { 11 | return l * S.size() + r; 12 | } 13 | 14 | int SGV (int l, int r) { 15 | if (r < l) return 0; 16 | int __hash = _hash(l, r); 17 | if (memo.find(__hash) != memo.end()) return memo[__hash]; 18 | int mex = 0; 19 | unordered_set Grundy; 20 | for (int i = l; i <= r; i++) 21 | for (int j = i; j <= r; j++) 22 | if (dict.find(string(S.begin() + i, S.begin() + j + 1)) != dict.end()) 23 | Grundy.insert(SGV(l, i - 1) xor SGV(j + 1, r)); 24 | while (Grundy.find(mex) != Grundy.end()) mex++; 25 | return memo[__hash] = mex; 26 | } 27 | 28 | int main () { 29 | cin >> T; 30 | while (T--) { 31 | memo.clear(); 32 | dict.clear(); 33 | cin >> S >> N; 34 | while (N--) cin >> word, dict.insert(word); 35 | puts(SGV(0, S.size() - 1) == 0 ? "Tracy" : "Teddy"); 36 | } 37 | return (0); 38 | } 39 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-06/soluciones/p01.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | struct Fraction { 6 | int num, den; 7 | Fraction() {} 8 | Fraction(const int& _num, const int& _den): 9 | num(_num), den(_den) {} 10 | bool operator < (const Fraction& other) const { 11 | return num * other.den < den * other.num; 12 | } 13 | inline void print() const { 14 | cout << num << "/" << den << endl; 15 | } 16 | }; 17 | 18 | int n, k; 19 | 20 | int main() { 21 | while (cin >> n >> k) { 22 | vector arr; 23 | for (int den = 1; den <= n; den++) 24 | for (int num = 1; num <= den; num++) 25 | // __gcd(a, b) = mcm(a, b) 26 | if (__gcd(num, den) == 1) 27 | arr.push_back(Fraction(num, den)); 28 | // Como solo queremos una posicion en el array ordenado 29 | nth_element(begin(arr), begin(arr) + k - 1, end(arr)); 30 | // Aunque tambien podemos usar sort() 31 | arr[k - 1].print(); 32 | } 33 | return (0); 34 | } 35 | -------------------------------------------------------------------------------- /exámenes/2018/solucionario/probBv2.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * By: Victoralin10 3 | */ 4 | 5 | #include 6 | 7 | using namespace std; 8 | 9 | int main() { 10 | int notas[6], a[6], b[6], ans = 0; 11 | for (int i = 0; i < 6; i++) { 12 | cin >> notas[i]; 13 | if (notas[i] == -1) { 14 | a[i] = 0, b[i] = 20; 15 | } else { 16 | a[i] = b[i] = notas[i]; 17 | } 18 | notas[i] = a[i]; 19 | } 20 | 21 | bool next = true; 22 | do { 23 | ans += (notas[0] + notas[1] + notas[2] + notas[3] 24 | - min(min(notas[0], notas[1]), min(notas[2], notas[3])) 25 | + (notas[4] + notas[5])*3 >= 90); 26 | 27 | next = false; 28 | for (int i = 0; i < 6; i++) { 29 | if (a[i] == b[i]) continue; 30 | if (notas[i] < b[i]) { 31 | notas[i]++; 32 | next = true; 33 | break; 34 | } else { 35 | notas[i] = a[i]; 36 | } 37 | } 38 | } while (next); 39 | 40 | cout << ans << endl; 41 | } 42 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-01/soluciones/p03-v1.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * link : https://uva.onlinejudge.org/index.php?option=onlinejudge&Itemid=99999999&page=show_problem&category=&problem=36&mosmsg=Submission+received+with+ID+20682109 3 | * Problema: 4 | * Sea una sequencia S = {s1, s2, ..., sn, ...} 5 | * Te daran dos valores a, b 6 | * Debes dar como respuesta el mayor si [i = a, a + 1, ..., b] 7 | */ 8 | 9 | /** 10 | * Solucion: 11 | * Itera desde a hasta b, ve generando el elemento que necesitamos de la 12 | * secuencia y busca el mayor 13 | */ 14 | 15 | #include 16 | 17 | using namespace std; 18 | 19 | int a, b; 20 | 21 | int getValue(int num) { 22 | int ret = 1; 23 | while (num != 1) { 24 | num = (num % 2 == 1) ? 3 * num + 1 : num / 2; 25 | ret++; 26 | } 27 | return ret; 28 | } 29 | 30 | int getAnswer(int a, int b) { 31 | int _max = 1; 32 | for (int it = a; it <= b; it++) 33 | _max = max(_max, getValue(it)); 34 | return _max; 35 | } 36 | 37 | int main() { 38 | while (cin >> a >> b) cout << a << ' ' << b << ' ' << getAnswer(min(a, b), max(a, b)) << endl; 39 | return (0); 40 | } -------------------------------------------------------------------------------- /uni-no-fiis/clase-14/ejemplos/10404.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define L_POS 1 4 | #define W_POS 2 5 | #define U_POS 3 6 | 7 | using namespace std; 8 | 9 | const int MAX_M = 12, MAX_N = 1e6 + 10; 10 | 11 | int n, m, s[MAX_M], dp[MAX_N]; 12 | 13 | void print () { 14 | puts(dp[n] == W_POS ? "Stan wins" : "Ollie wins"); 15 | } 16 | 17 | bool isNposition (int id) { 18 | bool ret = false; 19 | for (int k = 0; k < m and not ret; k++) if (id - s[k] >= 0) ret |= dp[id - s[k]] == L_POS; 20 | return ret; 21 | } 22 | 23 | void setWpositions (int id) { 24 | for (int k = 0; k < m; k++) if (id + s[k] <= n) dp[id + s[k]] = W_POS; 25 | } 26 | 27 | void solve () { 28 | dp[0] = L_POS; 29 | setWpositions(0); 30 | for (int id = 1; id <= n; id++) if (dp[id] == U_POS) dp[id] = isNposition(id) ? W_POS : L_POS; 31 | } 32 | 33 | void read () { 34 | for (int i = 0; i < m; i++) scanf("%d", s + i); 35 | } 36 | 37 | void clear () { 38 | fill(dp, dp + n + 1, U_POS); 39 | } 40 | 41 | int main () { 42 | while (~scanf("%d %d", &n, &m)) { 43 | clear(); 44 | read(); 45 | solve(); 46 | print(); 47 | } 48 | return (0); 49 | } 50 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Programación Competitiva UNI 2 | Material de programación competitiva elaborado por entrenadores de la Universidad Nacional de Ingeniería. Si utiliza este material para el dictado de un curso, favor de considerar la referencia. 3 | 4 | ## Entrenadores : 5 | * César Giglio Badoino 6 | * José García Gonzales 7 | * Josué Julcarima Calle 8 | * Luis Vásquez Vargas 9 | * Marco Cáceres Choqqe 10 | * Miguel Miní Huambachano 11 | * Rodolfo Mercado Gonzales 12 | * Víctor Cueva LLanos 13 | * Víctor Galván Oyola 14 | 15 | ## Integrantes del Grupo : 16 | * Andrés Ocaris Maldonado 17 | * Bryan Cipriano Tarazona 18 | * Claudio Flores Uceda 19 | * Cristian Lazo Quispe 20 | * Daniel Chávez Sánchez 21 | * Diego Hurtado de Mendoza 22 | * Diego López Gil 23 | * Diego Ucharima Ortiz 24 | * Felipe Montañez Sosa 25 | * Guillermo Inglis Vidal 26 | * Hans Acha Carranza 27 | * Hans Amaro Robladillo 28 | * Roger Huauya Mamaní 29 | * Sergio Sánchez Rojas 30 | 31 | [Ver ex-integrantes](https://github.com/PCUNI/Programacion-Competitiva/tree/master/PASTMEMBERS.md) 32 | 33 | Para estar al tanto de noticias sobre el grupo, nos puede seguir en [ProgramacionCompetitivaUNI](https://www.facebook.com/ProgramacionCompetitivaUNI/). 34 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-10/ejemplos/n-queen.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | const int N_ROWS = 8, N_COLS = 8; 6 | const char QUEEN = 'Q', EMPTY = '.'; 7 | 8 | int ans; 9 | char grid[N_ROWS + 1][N_COLS + 1]; 10 | 11 | bool valid(int row, int col) { 12 | for (int r = 0; r < N_ROWS; r++) 13 | for (int c = 0; c < N_COLS; c++) 14 | if ((r == row or c == col or abs(row - r) == abs(col - c)) and grid[r][c] == QUEEN) 15 | return false; 16 | return true; 17 | } 18 | 19 | void backtrack(int col = 0) { 20 | if (col == N_COLS) { 21 | printf("Configuración #: %2d\n", ++ans); 22 | for (int r = 0; r < N_ROWS; r++) 23 | for (int c = 0; c < N_COLS; c++) 24 | printf(c == N_COLS - 1 ? "%c\n" : "%c", grid[r][c]); 25 | puts(""); 26 | return; 27 | } 28 | for (int row = 0; row < N_ROWS; row++) { 29 | if (valid(row, col)) { 30 | grid[row][col] = QUEEN; 31 | backtrack(col + 1); 32 | grid[row][col] = EMPTY; 33 | } 34 | } 35 | } 36 | 37 | int main() { 38 | memset(grid, EMPTY, sizeof grid); 39 | backtrack(); 40 | return (0); 41 | } 42 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-07/soluciones/G.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | problem : http://codeforces.com/contest/760/problem/B 3 | approach: binary search, math 4 | 5 | solution: la idea consiste en hacer una piramide con 6 | altura maxima en la posicion k, vemos que si podemos 7 | hacer una piramide de altura h, claro que podemos hacer una menor. 8 | 9 | code: recuerde que se intenta hacer una piramide pero quizas 10 | salga algo mas raro. 11 | 12 | complexity: O(log(m - n)) 13 | **/ 14 | 15 | #include 16 | using namespace std; 17 | 18 | long long n, m, k; 19 | 20 | void input(){ 21 | scanf("%d %d %d", &n, &m, &k); 22 | m -= n; 23 | } 24 | 25 | 26 | bool p(long long x){ 27 | 28 | long long r = m - x; 29 | long long l1 = min(x-1, k-1); 30 | long long l2 = min(n-k, x-1); 31 | 32 | long long r1 = (x-l1-1)*(k-1) + l1*(l1+1)/2; 33 | long long r2 = (x-l2-1)*(n-k) + l2*(l2+1)/2; 34 | 35 | 36 | return r1+r2 <= r; 37 | } 38 | 39 | void solve(){ 40 | int lo = 0, hi = m; 41 | while(lo < hi){ 42 | int mid = lo + (hi - lo + 1)/2; 43 | if(p(mid)) lo = mid; 44 | else hi = mid-1; 45 | } 46 | 47 | printf("%d\n", lo+1); 48 | } 49 | 50 | 51 | int main(){ 52 | 53 | input(); 54 | solve(); 55 | 56 | return 0; 57 | } -------------------------------------------------------------------------------- /uni-no-fiis/clase-01/soluciones/p04-v1.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * link : http://codeforces.com/problemset/problem/334/A 3 | * Problema: 4 | * Tiene el conjunto A = {1, 2, ..., n * n} 5 | * Y debes crear n conjutos B de tamaño n tal que la union de todos esos conjuntos 6 | * sea A, que la interseccion entre cualquier de estos B sean nula y que la suma de sus elementos 7 | * sea la misma para cada B 8 | */ 9 | 10 | /** 11 | * Solucion: 12 | * sum(A) = n * n * (n * n + 1) / 2 13 | * Entonces 14 | * sum(B) = n * (n * n + 1) / 2 = (n / 2) * (n * n + 1) 15 | * Es decir, sea B = {b_1, b_2, ..., b_n} 16 | * estos deben ser tal que: 17 | * b_1 + b_n = n * n + 1 18 | * b_2 + b_(n - 1) = n * n + 1 19 | * b_3 + b_(n - 2) = n * n + 1 20 | * ... (Asi n / 2 ecuaciones) 21 | * Luego, podemos tomar para el primer B, b_1 = 1, b_n = n * n 22 | * Y contruir todos los conjuntos B a partir de ello 23 | */ 24 | 25 | #include 26 | 27 | using namespace std; 28 | 29 | int n, id_1, id_2; 30 | 31 | int main() { 32 | cin >> n; 33 | id_1 = 1, id_2 = n * n; 34 | for (int i = 0; i < n; i++) { 35 | for (int j = 0; j < n; j += 2) cout << id_1++ << ' ' << id_2-- << ' '; 36 | cout << endl; 37 | } 38 | return (0); 39 | } -------------------------------------------------------------------------------- /uni-no-fiis/clase-01/soluciones/p05-v1.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * link : https://uva.onlinejudge.org/index.php?option=onlinejudge&Itemid=99999999&page=show_problem&category=&problem=2091&mosmsg=Submission+received+with+ID+20682154 3 | * Problema: 4 | * Tiene n gaseosa 5 | * Si entregas 3 envases vacios te dan uno nuevo a cambio 6 | * Puedes prestarte un envase de un amigo si luego se lo devuelves 7 | * ¿ Cuantas gaseosas puedes tener como máximo ? 8 | */ 9 | 10 | /** 11 | * Solucion: 12 | * Ya tengo n gaseosas 13 | * De ellas puedo obtener n / 3 mas por la promocion y n % 3 no las usaria en la promocion 14 | * Puedo continuar aprovechandome de la promocion mientras tenga 3 gaseosas o mas 15 | * Si al final me sobran 2 gaseosas, puedo pedir a un amigo que me preste un envase 16 | * vacio, obtengo una gaseosa más con la promocion, la tomo y devuelvo el envase a mi amigo 17 | */ 18 | 19 | #include 20 | 21 | using namespace std; 22 | 23 | int n; 24 | 25 | int getAnwer(int num) { 26 | int ret = num; 27 | while (num >= 3) { 28 | ret += num / 3; 29 | num = num / 3 + num % 3; 30 | } 31 | if (num % 2 == 0) ret++; 32 | return ret; 33 | } 34 | 35 | int main() { 36 | while (cin >> n) cout << getAnwer(n) << endl; 37 | return (0); 38 | } -------------------------------------------------------------------------------- /uni-no-fiis/clase-10/ejemplos/patron.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | const int R = 3, C = 3, MIN_POINTS_TO_TAKE = 3; 6 | 7 | int grid[R + 1][C + 1], n_solution; 8 | int dr[] = {0, -1, -1, -1, 0, 1, 1, 1}; 9 | int dc[] = {1, 1, 0, -1, -1, -1, 0, 1}; 10 | 11 | void printGrid() { 12 | printf("Solution #: %0.4d\n", ++n_solution); 13 | for (int r = 0; r < R; r++) { 14 | for (int c = 0; c < C; c++) cout << grid[r][c]; 15 | cout << endl; 16 | } 17 | putchar('\n'); 18 | } 19 | 20 | inline bool isValid(const int r, const int c) { 21 | return 0 <= r and r < R and 0 <= c and c < C and grid[r][c] == 0; 22 | } 23 | 24 | void backtrack(int r, int c, int num = 2) { 25 | if (num > MIN_POINTS_TO_TAKE) printGrid(); 26 | for (int d = 0; d < 8; d++) { 27 | int nr = r + dr[d]; 28 | int nc = c + dc[d]; 29 | if (isValid(nr, nc)) { 30 | grid[nr][nc] = num; 31 | backtrack(nr, nc, num + 1); 32 | grid[nr][nc] = 0; 33 | } 34 | } 35 | } 36 | 37 | int main() { 38 | for (int r = 0; r < R; r++) 39 | for (int c = 0; c < C; c++) { 40 | grid[r][c] = 1; 41 | backtrack(r, c); 42 | grid[r][c] = 0; 43 | } 44 | return (0); 45 | } 46 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-06/soluciones/p05.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define LIM 2000000000L 4 | 5 | typedef long long ll; 6 | 7 | using namespace std; 8 | 9 | int idx; 10 | ll num; 11 | vector humble_number; 12 | 13 | int main(){ 14 | for(ll two = 1; two < LIM; two *= 2) 15 | for(ll three = 1; three < LIM; three *= 3) 16 | for(ll five = 1; five < LIM; five *= 5) 17 | for(ll seven = 1; seven < LIM; seven *= 7) { 18 | num = two * three * five * seven; 19 | if (num > LIM || num<0) break; 20 | if (two * three > LIM || two * five > LIM || two * seven > LIM) break; 21 | if (three * five > LIM || three * seven > LIM) break; 22 | if (five * seven > LIM) break; 23 | humble_number.push_back(num); 24 | } 25 | sort(humble_number.begin(), humble_number.end()); 26 | while (scanf("%d", &idx), idx) { 27 | printf("The %d",idx); 28 | if (idx % 10 == 1 && (idx / 10) % 10 != 1) printf("st"); 29 | else if (idx%10==2 && (idx / 10) % 10 != 1) printf("nd"); 30 | else if (idx%10==3 && (idx / 10) % 10 != 1) printf("rd"); 31 | else printf("th"); 32 | printf(" humble number is %d.\n", humble_number[idx-1]); 33 | } 34 | return(0); 35 | } 36 | 37 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-07/soluciones/H.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | problem : http://codeforces.com/contest/779/problem/D 3 | approach: binary search, string 4 | 5 | solution: sea el predicado P(x) : se puede formar al 6 | quitar los primero x elementos de la permutacion, entonces 7 | es claro que para todo y menor tambien se puede. 8 | 9 | code: se puede usar una array visitados para borrar 10 | temporalmente los elementos. 11 | 12 | complexity: O((|p| + |t|) x log(|p|)) 13 | **/ 14 | 15 | 16 | #include 17 | using namespace std; 18 | 19 | const int maxN = 2e5, OFFSET = 2; 20 | int n; 21 | string p, t; 22 | int a[maxN + OOFSET]; 23 | bool vis[maxN + OFFSET]; 24 | 25 | bool P(int x){ 26 | memset(vis, 0, sizeof vis); 27 | for(int i = 0; i < x; ++i) 28 | vis[a[i]] = 1; 29 | 30 | int k = 0; 31 | for(int i = 0; i < n; ++i){ 32 | if(vis[i]) continue; 33 | if(p[i] == t[k]) k++; 34 | if(k == t.size()) return 1; 35 | } 36 | 37 | return 0; 38 | } 39 | 40 | int main(){ 41 | 42 | 43 | cin >> p; 44 | cin >> t; 45 | 46 | n = p.size(); 47 | for(int i = 0; i < n; ++i){ 48 | cin >> a[i]; 49 | a[i]--; 50 | } 51 | 52 | int lo = 0, hi = n; 53 | while(lo < hi){ 54 | int mid = lo + (hi-lo+1)/2; 55 | if(P(mid)) lo = mid; 56 | else hi = mid-1; 57 | } 58 | 59 | cout << lo << endl; 60 | 61 | return 0; 62 | } -------------------------------------------------------------------------------- /uni-no-fiis/clase-08/p6.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Link 3 | * https://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=2162 4 | */ 5 | 6 | #include 7 | 8 | using namespace std; 9 | 10 | const int MAX_P = 1e4 + 100; 11 | 12 | int T, sq[MAX_P]; 13 | string line, word; 14 | bool valid; 15 | 16 | void perfectSquare() { 17 | for (int p = 1; p * p <= MAX_P; p++) sq[p * p] = p; 18 | } 19 | 20 | int main() { 21 | perfectSquare(); 22 | cin >> T; 23 | cin.ignore(); 24 | for (int t = 1; t <= T; t++) { 25 | cout << "Case #" << t << ':' << endl; 26 | getline(cin, line); 27 | word = ""; 28 | for (char ch : line) if (isalpha(ch)) word += ch; 29 | valid = sq[word.size()]; 30 | if (valid) { 31 | int k = word.size(); 32 | for (int i = 0; i < word.size() / 2; i++) 33 | if (word[i] != word[--k]) valid = false; 34 | k = word.size() - 1; 35 | int len = sq[word.size()]; 36 | for (int i = 0; i < len; i++, k--) 37 | for (int j = 0; j < len; j++) 38 | if (word[i + j * len] != word[k - j * len]) valid = false; 39 | } 40 | valid ? cout << sq[word.size()] << endl : cout << "No magic :(" << endl; 41 | } 42 | return (0); 43 | } 44 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-04/soluciones/p06.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * LINK DEL PROBLEMA: 3 | * https://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=2146 4 | * 5 | * SOLUCIÓN 6 | * Busquemos todas las posibles configuraciones 7 | * 8 | * COMPLEJIDAD: 9 | * O(N * log(N) * 2 ^ P) 10 | */ 11 | 12 | #include 13 | 14 | using namespace std; 15 | 16 | int T, P, N, ans; 17 | vector number; 18 | 19 | void print() { 20 | cout << ans << endl; 21 | } 22 | 23 | void solve() { 24 | for (int mask = 0; mask < (1 << P); mask++) { 25 | set required; 26 | for (int i = 0; i < number.size(); i++) required.insert(mask bitand number[i]); 27 | if (required.size() == N) ans = min(ans, (int)__builtin_popcount(mask)); 28 | } 29 | } 30 | 31 | void readCase() { 32 | cin >> P >> N; 33 | for (int i = 0; i < N; i++) { 34 | int num = 0; 35 | for (int j = 0, bit; j < P; j++) { 36 | cin >> bit; 37 | if (bit) num |= 1 << j; 38 | } 39 | number.push_back(num); 40 | } 41 | } 42 | 43 | void init() { 44 | number.clear(); 45 | ans = INT_MAX; 46 | } 47 | 48 | int main() { 49 | cin >> T; 50 | while (T--) { 51 | init(); 52 | readCase(); 53 | solve(); 54 | print(); 55 | } 56 | return (0); 57 | } 58 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-07/soluciones/F.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | problem : http://codeforces.com/contest/75/problem/C 3 | approach: binary search, sort, number theory 4 | 5 | solution: hallar los divisores del gcd(a, b) y hacer 6 | busqueda binaria para cada query con el predicado p(x) : Div[x] <= r, 7 | si se encuentra un valor ver que sea >= l 8 | 9 | code: 10 | ... 11 | 12 | complexity: O(sqrt(min(a, b)) + n x log(min(a, b)^{1/3})) 13 | **/ 14 | 15 | 16 | #include 17 | using namespace std; 18 | 19 | int a, b, n, l, r; 20 | vector Div; 21 | 22 | void input(){ 23 | scanf("%d %d", &a, &b); 24 | } 25 | 26 | void prepr(){ 27 | int g = __gcd(a, b); 28 | int d = 1; 29 | for(; d*d < g; ++d) 30 | if(g % d == 0){ 31 | Div.push_back(d); 32 | Div.push_back(g/d); 33 | } 34 | 35 | if(d*d == g) Div.push_back(d); 36 | 37 | sort(Div.begin(), Div.end()); 38 | } 39 | 40 | void querys(){ 41 | 42 | scanf("%d", &n); 43 | while(n--){ 44 | scanf("%d %d", &l, &r); 45 | 46 | int lo = 0, hi = (int)Div.size() - 1; 47 | while(lo < hi){ 48 | int mid = lo + (hi-lo+1)/2; 49 | if(Div[mid] <= r) lo = mid; 50 | else hi = mid-1; 51 | } 52 | 53 | if(l <= Div[lo] and Div[lo] <= r) printf("%d\n", Div[lo]); 54 | else puts("-1"); 55 | } 56 | } 57 | 58 | 59 | int main(){ 60 | 61 | input(); 62 | prepr(); 63 | querys(); 64 | 65 | return 0; 66 | } -------------------------------------------------------------------------------- /uni-no-fiis/clase-07/soluciones/J.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | problem : http://codeforces.com/contest/803/problem/D 3 | approach: binary search, next 4 | 5 | solution: sea el predicado p(x): se puede formar el texto con <= x 6 | de ancho, es claro que se puede formar para todo y > x. 7 | 8 | code: se debe usar un array R (next), que me permita ir al 9 | siguiente quiebre permitido. 10 | 11 | complexity: O(n x log(n)) 12 | **/ 13 | 14 | 15 | #include 16 | #define pb push_back 17 | #define fst first 18 | #define snd second 19 | using namespace std; 20 | typedef long long ll; 21 | const int N = 1000005; 22 | string s; 23 | int R[N]; 24 | int k, n; 25 | 26 | bool p(int pos, int x, int l){ 27 | 28 | if(l > k) return false; 29 | if(pos == n) return true; 30 | int y = pos; 31 | int in; 32 | while(y - pos <= x){ 33 | in = y; 34 | y = R[y]; 35 | } 36 | 37 | return p(in, x, l+1); 38 | } 39 | 40 | 41 | 42 | int main(){ 43 | 44 | 45 | cin >> k; 46 | cin.ignore(); 47 | getline(cin, s); 48 | 49 | n = s.size(); 50 | R[n] = 1000000000; 51 | R[n-1] = n; 52 | for(int i = n - 2; i >= 0; --i) 53 | if(s[i] == ' ' or s[i] == '-') R[i] = i+1; 54 | else R[i] = R[i+1]; 55 | 56 | int lo = 1, hi = n; 57 | while(lo < hi){ 58 | int mid = lo + (hi-lo)/2; 59 | if(not p(0, mid, 0)) lo = mid+1; 60 | else hi = mid; 61 | } 62 | 63 | 64 | cout << lo << endl; 65 | 66 | 67 | return 0; 68 | } -------------------------------------------------------------------------------- /uni-no-fiis/clase-02/soluciones/00540.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | const int LEN = 10; 6 | 7 | int tc, n, teams, member, team; 8 | deque , int>> dq; 9 | map mp; 10 | char command[LEN]; 11 | bool found; 12 | 13 | void getQueries() { 14 | while (scanf("%s", command), command[0] != 'S') { 15 | if (command[0] == 'D') { 16 | printf("%d\n", dq.front().first.front()); 17 | dq.front().first.pop_front(); 18 | if (dq.front().first.empty()) dq.pop_front(); 19 | } 20 | else { 21 | scanf("%d", &member); 22 | team = mp[member]; 23 | found = false; 24 | for (int i = 0; i < dq.size() and not found; i++) 25 | if (dq[i].second == team) dq[i].first.push_back(member), found = true; 26 | if (not found) dq.push_back({{member}, team}); 27 | } 28 | } 29 | } 30 | 31 | void getTeams() { 32 | while (teams--) { 33 | scanf ("%d", &n); 34 | while (n--) scanf("%d", &member), mp[member] = teams; 35 | } 36 | } 37 | 38 | void clear() { 39 | mp.clear(); 40 | dq.clear(); 41 | } 42 | 43 | int main() { 44 | while (scanf("%d", &teams), teams) { 45 | clear(); 46 | getTeams(); 47 | printf("Scenario #%d\n", ++tc); 48 | getQueries(); 49 | putchar('\n'); 50 | } 51 | return (0); 52 | } -------------------------------------------------------------------------------- /exámenes/2018/solucionario/probE.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # run on python3 3 | 4 | import sys 5 | import bisect as bs 6 | 7 | ls = [] 8 | ls.append(-4) # in case jl is less than 5 9 | for l in range(1, 12): 10 | for i in range(1< 18 | #include 19 | #include 20 | using namespace std; 21 | 22 | const int N = 1e5, OFFSET = 2; 23 | int a[N + OFFSET], b[N + OFFSET]; 24 | int n, k; 25 | 26 | 27 | void input(){ 28 | scanf("%d %d", &n, &k); 29 | for(int i = 0; i < n; ++i) 30 | scanf("%d", a+i); 31 | 32 | for(int i = 0; i < n; ++i) 33 | scanf("%d", b+i); 34 | } 35 | 36 | bool p(long long x){ 37 | 38 | long long magic = 0; 39 | for(int i = 0; i < n; ++i) 40 | magic += min(k+1ll, max(a[i]*x - b[i], 0ll)); 41 | 42 | return magic <= k; 43 | } 44 | 45 | void solve(){ 46 | 47 | long long lo = 0, hi = 2e9; 48 | while(lo < hi){ 49 | long long mid = lo + (hi-lo+1)/2; 50 | if(p(mid)) lo = mid; 51 | else hi = mid-1; 52 | } 53 | 54 | printf("%d\n", lo); 55 | } 56 | 57 | 58 | 59 | int main(){ 60 | 61 | input(); 62 | solve(); 63 | 64 | return 0; 65 | } -------------------------------------------------------------------------------- /uni-no-fiis/clase-07/soluciones/A.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | problem : http://codeforces.com/problemset/problem/812/C 3 | approach: binary search, sort 4 | 5 | solution: Debemos darnos cuenta que es una aplicacion directa de 6 | predicado, ya que si podemos comprar x elementos, entonces, podemos 7 | comprar menos que eso ya que el precio es creciente (pruebe eso). 8 | 9 | code: para codear el programa como queremos gastar menos por cada 10 | k, nosotros reemplazamos cada a[i] por a[i] + k * i, (1 <= i <= n) 11 | y luego escogemos los k menores (se puede hacer facilmente ordenando). 12 | 13 | complexity: O(n x log^2(n)) 14 | **/ 15 | 16 | #include 17 | #include 18 | #include 19 | using namespace std; 20 | 21 | const int maxN = 1e5, OFFSET = 2; 22 | int a[maxN + OFFSET]; 23 | long long b[maxN + OFFSET]; 24 | long long ans; 25 | int n, s; 26 | 27 | void input(){ 28 | scanf("%d %d", &n, &s); 29 | for(int i = 0; i < n; ++i) 30 | scanf("%d", a+i); 31 | } 32 | 33 | bool p(int k, int s){ 34 | 35 | for(int i = 0; i < n; ++i) 36 | b[i] = (i+1) * 1ll * k + a[i]; 37 | 38 | sort(b, b+n); 39 | 40 | ans = 0; 41 | for(int i = 0; i < k; ++i) 42 | ans += b[i]; 43 | 44 | return ans <= s; 45 | } 46 | 47 | void solve(){ 48 | 49 | int lo = 0, hi = n; 50 | while(lo < hi){ 51 | int mid = lo + (hi - lo + 1)/2; 52 | if(p(mid, s)) lo = mid; 53 | else hi = mid-1; 54 | } 55 | 56 | printf("%d %d\n", lo, (p(lo, s), ans)); 57 | } 58 | 59 | 60 | int main() { 61 | 62 | input(); 63 | solve(); 64 | 65 | return 0; 66 | } -------------------------------------------------------------------------------- /uni-no-fiis/clase-04/soluciones/p07.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * LINK DEL PROBLEMA: 3 | * https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=4763 4 | * 5 | * SOLUCIÓN: 6 | * Sea: 7 | * ans_1 = OR(a, a + 1, ..., b) 8 | * ans_2 = AND(a, a + 1, ..., b) 9 | * Si vemos a 'ans_1' y 'ans_2' como una máscara de bits, notemos: 10 | * ans_1[k] = 1 [Si a[k] = 1 o b[k] = 1 o algun c[k] = 1, donde a < c < b] 11 | * ans_1[k] = 0 [En caso contrario] 12 | * ans_2[k] = 1 [Si a[k] = 1 y b[k] = 1 y todo c[k] = 1, donde a < c < b] 13 | * ans_2[k] = 0 [En caso contrario] 14 | * Luego, notamos que: 15 | * Si a + 2 ** k < b: 16 | * Existe algun c / c[k] = 1 17 | * Existe algun c / c[k] = 0 18 | * Con esas observaciones podemos contruir 'ans_1' y 'ans_2' 19 | * 20 | * COMPLEJIDAD: 21 | * O(log(b)) 22 | * 23 | * DETALLES DE LA IMPLEMENTACIÓN: 24 | * 1LL << k = (long long) 2 ** k 25 | */ 26 | 27 | #include 28 | 29 | using namespace std; 30 | 31 | int tc, t; 32 | long long a, b, ans_1, ans_2; 33 | 34 | void solve() { 35 | ans_1 = ans_2 = 0; 36 | long long diff = b - a, k = 0; 37 | while (b) { 38 | long long pow2 = 1LL << k; 39 | if (b bitand 1 or a bitand 1 or diff > pow2) ans_1 |= pow2; 40 | if (b bitand 1 and a bitand 1 and diff < pow2) ans_2 |= pow2; 41 | a >>= 1, b >>= 1, k++; 42 | } 43 | } 44 | 45 | int main() { 46 | cin >> tc; 47 | while (tc--) { 48 | cin >> a >> b; 49 | solve(); 50 | cout << "Case " << ++t << ": " << ans_1 << ' ' << ans_2 << endl; 51 | } 52 | return (0); 53 | } 54 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-01/soluciones/p06-v2.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Usando Backtracking + bit manipulation 3 | */ 4 | 5 | #include 6 | 7 | using namespace std; 8 | 9 | const int MAX_N = 110; 10 | 11 | struct Word { 12 | int length; 13 | char ch_1, ch_2; 14 | }; 15 | 16 | int n, n_words, sum, ans; 17 | string ss; 18 | Word word[MAX_N]; 19 | 20 | int mark(int id, int used) { 21 | used |= 1 << (word[id].ch_1 - 'a'); 22 | used |= 1 << (word[id].ch_2 - 'a'); 23 | return used; 24 | } 25 | 26 | void backtrack(int id = 0, int used = 0) { 27 | if (__builtin_popcount(used) > 2) return; 28 | if (id == n_words) { 29 | ans = max(ans, sum); 30 | return; 31 | } 32 | if (__builtin_popcount(used) == __builtin_popcount(mark(id, used))) { 33 | sum += word[id].length; 34 | backtrack(id + 1, mark(id, used)); 35 | sum -= word[id].length; 36 | } 37 | else { 38 | sum += word[id].length; 39 | backtrack(id + 1, mark(id, used)); 40 | sum -= word[id].length; 41 | backtrack(id + 1, used); 42 | } 43 | } 44 | 45 | void include() { 46 | word[n_words].length = ss.length(); 47 | word[n_words].ch_1 = word[n_words].ch_2 = ss.front(); 48 | for (int pos = 1; pos < ss.size(); pos++) 49 | if (ss[pos] != word[n_words].ch_1) { 50 | if (word[n_words].ch_1 == word[n_words].ch_2) word[n_words].ch_2 = ss[pos]; 51 | else if (word[n_words].ch_2 != ss[pos]) return; 52 | } 53 | n_words++; 54 | } 55 | 56 | int main() { 57 | cin >> n; 58 | for (int i = 0; i < n; i++) cin >> ss, include(); 59 | backtrack(); 60 | cout << ans << endl; 61 | return (0); 62 | } -------------------------------------------------------------------------------- /uni-no-fiis/clase-01/ejemplos/06-entrada-y-salida-ejemplo-1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | /** 7 | * En CP la forma estándar de entrada y salida es de manera directa 8 | * es decir, no leemos la entrada de archivos ni escribimos la respuesta en uno 9 | * Además, las especificaciones de las entradas de los problemas siempre se cumplen 10 | * Entonces, no hay necesidad de verificar que la entrada que nos pasan es correcta 11 | * La salida se debe dar en el formato exacto señalado en el problema 12 | * Eso incluye número de espacios, salto de línea, etc 13 | * Y no se debe imprimir nada más que lo señalado en la salida 14 | * Por ejemplo 15 | * Problema: 16 | * Recibirás 2 números enteros a, b. 17 | * Imprimir la suma de ellos 18 | * Especificaciones de entrada: 19 | * 0 <= a, b < 100 20 | * Especificaciones de salida: 21 | * suma de a y b 22 | * Ejemplo de entrada 23 | * 4 5 24 | * Ejemplo de salida 25 | * 9 26 | * 27 | * Entonces, no tenemos la necesidad de verificar que nos vayan a ingresar números en ese rango 28 | * Además, solo debemos imprimir la suma de los numeros recibimos y nada más 29 | * Entonces, por ejemplo, si diera de respuesta "La suma de los números es 9" sería una respuesta incorrecta 30 | * Lo válida sería solo imprimir "9" para este caso de entrada 31 | */ 32 | 33 | // La solución del problema anterior sería: 34 | 35 | int a, b; 36 | cin >> a >> b; // Leo los numeros y los guardo en las variables a y b 37 | cout << a + b << endl; // Imprimo los números y añado un salto de línea 38 | 39 | 40 | return (0); 41 | } -------------------------------------------------------------------------------- /uni-no-fiis/README.md: -------------------------------------------------------------------------------- 1 | ## Índice 2 | 3 | * [Clase 01: Introducción a C++](https://github.com/PCUNI/Programacion-Competitiva/tree/master/uni-no-fiis/clase-01 'Clase 01') 4 | * [Clase 02: STL](https://github.com/PCUNI/Programacion-Competitiva/tree/master/uni-no-fiis/clase-02 'Clase 02') 5 | * [Clase 03: Fuerza Bruta I](https://github.com/PCUNI/Programacion-Competitiva/tree/master/uni-no-fiis/clase-03 'Clase 03') 6 | * [Clase 04: Fuerza Bruta II: Bitmask](https://github.com/PCUNI/Programacion-Competitiva/tree/master/uni-no-fiis/clase-04 'Clase 04') 7 | * [Clase 05: Fuerza Bruta III](https://github.com/PCUNI/Programacion-Competitiva/tree/master/uni-no-fiis/clase-05 'Clase 05') 8 | * [Clase 06: Repaso I](https://github.com/PCUNI/Programacion-Competitiva/tree/master/uni-no-fiis/clase-06 'Clase 06') 9 | * [Clase 07: Búsqueda Binaria](https://github.com/PCUNI/Programacion-Competitiva/tree/master/uni-no-fiis/clase-07 'Clase 07') 10 | * [Clase 08: Contest I](https://github.com/PCUNI/Programacion-Competitiva/tree/master/uni-no-fiis/clase-08 'Clase 08') 11 | * [Clase 09: Recursión](https://github.com/PCUNI/Programacion-Competitiva/tree/master/uni-no-fiis/clase-09 'Clase 09') 12 | * [Clase 10: Backtracking I](https://github.com/PCUNI/Programacion-Competitiva/tree/master/uni-no-fiis/clase-10 'Clase 10') 13 | * [Clase 11: Repaso](https://github.com/PCUNI/Programacion-Competitiva/tree/master/uni-no-fiis/clase-11 'Clase 12') 14 | * [Clase 12: Programación Dinámica I](https://github.com/PCUNI/Programacion-Competitiva/tree/master/uni-no-fiis/clase-12 'Clase 12') 15 | * [Clase 13: Teoría de Numeros I](https://github.com/PCUNI/Programacion-Competitiva/tree/master/uni-no-fiis/clase-13 'Clase 13') 16 | * [Clase 14: Teoría de Juegos](https://github.com/PCUNI/Programacion-Competitiva/tree/master/uni-no-fiis/clase-14 'Clase 14') 17 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-14/ejemplos/GAME31.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | const int LEN = 100, N_CARDS = 6; 6 | 7 | int ct[N_CARDS + 1]; 8 | char moves[LEN]; 9 | bool ans; 10 | 11 | namespace Minimax { 12 | int minVal(); 13 | int maxVal(); 14 | void solve(); 15 | } 16 | 17 | namespace Minimax { 18 | 19 | int sum; 20 | const int WIN = 1; 21 | const int FAIL = -1; 22 | 23 | int minVal () { 24 | if (sum > 31) return FAIL; 25 | int ret = WIN; 26 | for (int card = 1; card <= N_CARDS and ret != FAIL; card++) { 27 | if (ct[card]) { 28 | ct[card]--, sum += card; 29 | ret = min(ret, maxVal()); 30 | ct[card]++, sum -= card; 31 | } 32 | } 33 | return ret; 34 | } 35 | 36 | int maxVal () { 37 | if (sum > 31) return WIN; 38 | int ret = FAIL; 39 | for (int card = 1; card <= N_CARDS and ret != WIN; card++) { 40 | if (ct[card]) { 41 | ct[card]--, sum += card; 42 | ret = max(ret, minVal()); 43 | ct[card]++, sum -= card; 44 | } 45 | } 46 | return ret; 47 | } 48 | 49 | void solve () { 50 | sum = 0; 51 | int id; 52 | for (id = 0; moves[id]; id++) { 53 | ct[moves[id] - '0']--; 54 | sum += moves[id] - '0'; 55 | } 56 | int res = (id & 1) ? minVal() : maxVal(); 57 | ans = res == WIN; 58 | } 59 | } 60 | 61 | 62 | inline void print() { 63 | printf("%s %c\n", moves, "BA"[ans]); 64 | } 65 | 66 | inline bool read() { 67 | if (cin.getline(moves, LEN)) return true; 68 | return false; 69 | } 70 | 71 | inline void clear() { 72 | fill(ct, ct + N_CARDS, 4); 73 | } 74 | 75 | int main () { 76 | while (read()) { 77 | clear(); 78 | Minimax::solve(); 79 | print(); 80 | } 81 | return (0); 82 | } 83 | 84 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-04/soluciones/p02.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * LINK DEL PROBLEMA: 3 | * http://codeforces.com/problemset/problem/467/B 4 | * 5 | * SOLUCIÓN: 6 | * Notemos que tenemos esto: 7 | * x[0] = mask[0] 8 | * x[1] = mask[1] 9 | * ... 10 | * x[m] = mask[m] 11 | * Y queremos saber la cantidad de x[i] (i < m) tal que la cantidad de '1's de x[i] y x[m] difieran en <= k 12 | * Entonces, notemos que podemos iterar por todos los 'i's < m y comprobar si se cumple tal condicion 13 | * para aumentar un contador que sería la respuesta 14 | * Dicha comprobacioón la podemos hacer iterando por los 'n' bits de cada 'mask' 15 | * como en el problema anterior, o podemos darnos cuenta de que: 16 | * Sea result = una máscara de 'n' bits, donde 17 | * result[j] = 1 si mask[i] y mask[m] difieren la cantidad de '1' en el bit 'j' 18 | * result[j] = 0 si mask[i] y mask[m] no difieren la cantidad de '1' en el bit 'j' 19 | * Entonces 20 | * Si mask[i][j] = 1 y mask[m][j] = 1 -> result[j] = 0 21 | * Si mask[i][j] = 1 y mask[m][j] = 0 -> result[j] = 1 22 | * Si mask[i][j] = 0 y mask[m][j] = 1 -> result[j] = 1 23 | * Si mask[i][j] = 0 y mask[m][j] = 0 -> result[k] = 0 24 | * Así, tenemos que: result[j] = mask[i][j] ^ mask[m][j] 25 | * Luego, result = mask[i] ^ mask[m] 26 | * Y si la cantidad de '1's en result es <= k, entonces la respuesta aumenta en 1 27 | * 28 | * COMPLEJIDAD: 29 | * O(m) 30 | * 31 | * DETALLES DE IMPLEMENTACIÓN: 32 | * xor = ^ = XOR OPERATION 33 | */ 34 | #include 35 | 36 | using namespace std; 37 | 38 | const int MAX_M = 1000, OFFSET = 5; 39 | 40 | int n, m, k, x[MAX_M + OFFSET], ans; 41 | 42 | int main() { 43 | cin >> n >> m >> k; 44 | for (int i = 0; i <= m; i++) cin >> x[i]; 45 | for (int i = 0; i < m; i++) if (__builtin_popcount(x[i] xor x[m]) <= k) ans++; 46 | cout << ans << endl; 47 | return (0); 48 | } 49 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-06/soluciones/p02.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define SIZE 100 4 | #define MAX_CONT 110 5 | #define MAX_PROB 20 6 | 7 | using namespace std; 8 | 9 | struct part{ 10 | int c, np, penalty; 11 | } aux; 12 | 13 | int tc, cont, prob, tim, score[MAX_CONT][MAX_PROB]; 14 | char s[SIZE], ch; 15 | bool solved[MAX_CONT][MAX_PROB], submission[MAX_CONT]; 16 | vector ans; 17 | 18 | bool cmp(part x, part y) { 19 | if (x.np != y.np) return (x.np > y.np); 20 | if (x.penalty != y.penalty) return (x.penalty < y.penalty); 21 | return (x.c < y.c); 22 | } 23 | 24 | void fillRanking(){ 25 | for (int c = 1; c < 110; c++){ 26 | aux.c = c, aux.np = aux.penalty = 0; 27 | for (int p = 1; p <= 12; p++) if(solved[c][p]) aux.penalty += score[c][p], aux.np++; 28 | if (aux.np >= 1 || submission[c]) ans.push_back(aux); 29 | } 30 | } 31 | 32 | void printRanking(){ 33 | for(int i = 0; i < ans.size(); i++) printf("%d %d %d\n", ans[i].c, ans[i].np, ans[i].penalty); 34 | ans.clear(); 35 | memset(solved, false, sizeof solved); 36 | memset(score, 0, sizeof score); 37 | memset(submission, false, sizeof submission); 38 | } 39 | 40 | int main(){ 41 | scanf("%d\n", &tc); 42 | while (tc--) { 43 | while (cin.getline(s, SIZE)) { 44 | if (sscanf(s,"%d %d %d %c", &cont, &prob, &tim, &ch) == -1) break; 45 | submission[cont] = true; 46 | if (ch == 'R' || ch == 'U' || ch == 'E') continue; 47 | if (solved[cont][prob] == false) { 48 | if(ch == 'C') score[cont][prob] += tim, solved[cont][prob] = true; 49 | if (ch == 'I') score[cont][prob] += 20; 50 | } 51 | } 52 | fillRanking(); 53 | sort(begin(ans), end(ans), cmp); 54 | printRanking(); 55 | if (tc) puts(""); 56 | } 57 | return(0); 58 | } 59 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-07/soluciones/M.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | problem : http://codeforces.com/contest/729/problem/C 3 | approach: binary search, simulation 4 | 5 | solution: para este problema queremos buscar la minima cantidad 6 | de combustible tal que pueda completar el recorrido, para 7 | ello hacemos binary search sobre la cantidad de combustible 8 | que puede haber en el tanque, luego de eso elegimos cualquiera 9 | que tenga >= a esta capacidad. 10 | 11 | code: para simular simplemente elegimo la mejor opcion del modo 12 | acelerado y el modo normal, para ello recorremos con el modo normal 13 | y si aun me sobra gasolina toda esa la uso para el modo acelerado, 14 | y asi ganar tiempo. 15 | 16 | complexity: O(k x log(1e9) + n) 17 | **/ 18 | 19 | #include 20 | #include 21 | #include 22 | #include 23 | using namespace std; 24 | 25 | const int N = 200005; 26 | int n, k, s; 27 | long long t; 28 | long long c[N], v[N], g[N], a[N]; 29 | 30 | bool p(long long x){ 31 | 32 | long long acum = 0; 33 | for(int i = 0; i <= k; ++i) 34 | if(a[i] > x) return false; 35 | else acum += 2LL*a[i] - min(a[i], x-a[i]); 36 | return acum <= t; 37 | } 38 | 39 | int main(){ 40 | 41 | scanf("%d %d %d %lld", &n, &k, &s, &t); 42 | for(int i = 0; i < n; ++i) 43 | scanf("%lld %lld", c+i, v+i); 44 | 45 | for(int i = 0; i < k; ++i) 46 | scanf("%lld", g+i); 47 | 48 | sort(g, g+k); 49 | a[0] = g[0]; 50 | for(int i = 1; i < k; ++i) 51 | a[i] = g[i] - g[i-1]; 52 | a[k] = s - g[k-1]; 53 | 54 | int lo = 0, hi = 1000000000; 55 | while(lo < hi){ 56 | int mid = lo + (hi-lo)/2; 57 | if(p(mid)) hi = mid; 58 | else lo = mid+1; 59 | } 60 | 61 | if(p(lo)){ 62 | long long ans = INT_MAX; 63 | for(int i = 0; i < n; ++i) 64 | if(v[i] >= lo) ans = min(ans, c[i]); 65 | 66 | if(ans != INT_MAX) printf("%lld\n", ans); 67 | else puts("-1"); 68 | 69 | } 70 | else puts("-1"); 71 | 72 | return 0; 73 | } -------------------------------------------------------------------------------- /uni-no-fiis/clase-06/soluciones/p09.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define SIZE 20 4 | 5 | using namespace std; 6 | 7 | int n,tc; 8 | char source[SIZE][SIZE], target[SIZE][SIZE], aux[SIZE][SIZE]; 9 | bool ok; 10 | 11 | bool check(){ 12 | for (int i = 0;i < n; i++) 13 | for (int j = 0;j < n; j++) if(source[i][j] != target[i][j]) return false; 14 | return true; 15 | } 16 | 17 | void rotate(){ 18 | for (int i = 0; i < n; i++) 19 | for(int j = 0; j < n; j++) aux[i][j] = source[n - j - 1][i]; 20 | for (int i = 0; i < n; i++) 21 | for (int j = 0; j < n; j++) source[i][j] = aux[i][j]; 22 | } 23 | 24 | void reflect(){ 25 | for (int i = 0; i < n; i++) 26 | for (int j = 0; j < n; j++) aux[i][j] = source[n- i - 1][j]; 27 | for (int i = 0; i < n; i++) 28 | for (int j = 0; j < n; j++) source[i][j] = aux[i][j]; 29 | } 30 | 31 | int main(){ 32 | while (scanf("%d\n",&n)==1) { 33 | ok = false; 34 | for (int i = 0; i < n; i++) scanf("%s %s", source[i], target[i]); 35 | for(int i = 1; i <= 2 && ok == false;i++){ 36 | if (check()) { 37 | if (i == 1) printf("Pattern %d was preserved.\n", ++tc); 38 | else printf("Pattern %d was reflected vertically.\n", ++tc); 39 | ok = true; 40 | break; 41 | } 42 | for (int j = 1; j <= 3; j++) { 43 | rotate(); 44 | if (check()) { 45 | if (i == 1) printf("Pattern %d was rotated %d degrees.\n", ++tc, 90 * j); 46 | else printf("Pattern %d was reflected vertically and rotated %d degrees.\n", ++tc, 90 * j); 47 | ok = true; 48 | break; 49 | } 50 | } 51 | rotate(); 52 | reflect(); 53 | } 54 | if(ok == false) printf("Pattern %d was improperly transformed.\n",++tc); 55 | } 56 | return(0); 57 | } 58 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-06/soluciones/p03.cpp: -------------------------------------------------------------------------------- 1 | // Solución seleccionada aleatoriamente del contest 2 | // Solución de J_Ruegg 3 | 4 | #include 5 | 6 | using namespace std; 7 | 8 | int main() { 9 | vector names(4, ""); 10 | names[0] = "shata"; 11 | names[1] = "hajar"; 12 | names[2] = "lakh"; 13 | names[3] = "kuti"; 14 | vector digits(4); 15 | 16 | digits[0] = 2; 17 | digits[1] = 1; 18 | digits[2] = 2; 19 | digits[3] = 2; 20 | 21 | vector rDigits; 22 | 23 | string num; 24 | int caseNumber = 1; 25 | while(cin >> num) { 26 | string res = ""; 27 | int i = num.size(); 28 | int k = 0; 29 | while(i > 0) 30 | { 31 | i-=digits[k++]; 32 | k%=4; 33 | } 34 | if(i == -1) num.insert(0, "0"); 35 | 36 | i = num.size(); 37 | k = 0; 38 | rDigits.clear(); 39 | while(i > 0) { 40 | 41 | int tempNum = stoi(num.substr( num.size() - digits[k], digits[k])); 42 | rDigits.push_back(tempNum); 43 | 44 | 45 | for(int counter = 0; counter < digits[k]; counter++) { 46 | num.pop_back(); 47 | } 48 | i-=digits[k]; 49 | 50 | 51 | k++; 52 | k %= 4; 53 | } 54 | 55 | for(int j = rDigits.size() - 1; j > 0; j--) { 56 | if(j > 0 and j%4 == 0 and rDigits[j] == 0) res += " " + names[3]; 57 | if(rDigits[j] == 0) continue; 58 | res += " " + to_string(rDigits[j]); 59 | res += " " + names[(j+3)%4]; 60 | } 61 | if(rDigits[0] != 0 or rDigits.size() == 1) res += " " + to_string(rDigits[0]); 62 | 63 | cout << std::setw(4) << caseNumber++ << "." << res << endl; 64 | } 65 | 66 | } 67 | 68 | //’kuti’ (10000000), ’lakh’ (100000), ’hajar’ (1000), ’shata’ (100) 69 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-07/soluciones/E.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | problem : http://codeforces.com/contest/439/problem/D 3 | approach: binary search, discrete calculus 4 | 5 | solution: 6 | sea la funcion f(x) : la cantidad de minima de 7 | operaciones para que el maximo elemento de b sea 8 | <= x y el minimo elemento de a sea >= x. Numericamente 9 | es igual a sum( x - a[i], con a[i] < x) + 10 | sum(b[i] - x, con b[i] > x), ahora si nosotros 11 | derivamos respecto a x tenemos sum(1, con a[i] < x) + 12 | sum(-1, con b[i] > x), poddemos apreciar que al aumentar 13 | x hay >= cantidad de a[i] que son < x y <= cantidad 14 | de b[i] que son mayores a x, esto nos dice que 15 | la primera derivada es no decreciente, con lo cual la 16 | segunda derivada es no negativa, por tanto es una 17 | funcion convexa, entonces para hallar lo que queremos 18 | no necesitamos mas que hallar el minimo para esta funcion. 19 | 20 | code: 21 | ... 22 | 23 | 24 | complexity: O(n x log(max(a))) 25 | **/ 26 | 27 | 28 | #include 29 | using namespace std; 30 | 31 | const int maxN = 1e5, OFFSET = 2; 32 | int a[maxN + OFFSET], b[maxN + OFFSET]; 33 | int n, m; 34 | 35 | void input(){ 36 | scanf("%d %d", &n, &m); 37 | for(int i = 0; i < n; ++i) 38 | scanf("%d", a+i); 39 | for(int i = 0; i < m; ++i) 40 | scanf("%d", b+i); 41 | } 42 | 43 | long long f(int x){ 44 | long long ans = 0; 45 | for(int i = 0; i < n; ++i) 46 | ans += max(x - a[i], 0); 47 | for(int i = 0; i < m; ++i) 48 | ans += max(b[i] - x, 0); 49 | 50 | return ans; 51 | } 52 | 53 | long long df(int x){ 54 | return f(x+1) - f(x); 55 | } 56 | 57 | bool p(int x){ 58 | return df(x) < 0; 59 | } 60 | 61 | void solve(){ 62 | int lo = 1, hi = 1e9; 63 | while(lo < hi){ 64 | int mid = lo + (hi-lo)/2; 65 | if(p(mid)) lo = mid+1; 66 | else hi = mid; 67 | } 68 | 69 | printf("%lld\n", f(lo)); 70 | } 71 | 72 | 73 | int main(){ 74 | 75 | input(); 76 | solve(); 77 | 78 | return 0; 79 | } -------------------------------------------------------------------------------- /uni-no-fiis/clase-02/ejemplos/sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | /* 6 | Como tercer parametro de la funcion sort podemos agregar una funcion 7 | que retorne un booleano, esta funcion sera usada para ordenar el array o vector, 8 | el tipo de datos que reciben como parametro tiene que ser el mismo del array que 9 | deseamos ordenar, unos ejemplos: 10 | */ 11 | 12 | bool mycomp(const int&x, const int&y){ 13 | return x>y; 14 | } 15 | 16 | bool mycomp2(pairx, pairy){ 17 | if( x.first != y.first ) return x.first < y.first; 18 | return x.second < y.second; 19 | } 20 | 21 | int a[] = {1, 4, 5, 7, 1, 5, 10}; 22 | vectorv(5); 23 | pairP[10]; 24 | int b[100]; 25 | 26 | int main(){ 27 | 28 | /*Ordenar un array de forma decreciente 29 | por defecto al usar sort se odena de forma creciente 30 | */ 31 | sort(a, a+7, mycomp); 32 | 33 | for(int i=0; i<7; i++) cout << a[i] << " "; 34 | cout << endl; 35 | 36 | //Ordenar un vector 37 | 38 | v[0] = 10; 39 | v[1] = 2; 40 | v[2] = 4; 41 | v[3] = 6; 42 | v[4] = 5; 43 | 44 | sort(v.begin(), v.end(), mycomp); 45 | 46 | for(int i=0; i, pair... 52 | Para acceder al primer elemnto usamos first: x.first 53 | Para acceder al segundo elemnto usamos second: x.second 54 | */ 55 | 56 | P[0].first = 4; 57 | P[0].second = 10; 58 | 59 | 60 | P[1].first = 2; 61 | P[1].second = 8; 62 | 63 | //Otra forma de crear un pair 64 | P[2] = make_pair(2, 10); 65 | 66 | for(int i=0; i<3; i++){ 67 | cout << P[i].first << " " << P[i].second << endl; 68 | } 69 | 70 | cout << "Antes de ordenar" << endl; 71 | 72 | sort(P, P+3, mycomp2); 73 | 74 | cout << "Despues de ordenar " << endl; 75 | 76 | for(int i=0; i<3; i++){ 77 | cout << P[i].first << " " << P[i].second << endl; 78 | } 79 | 80 | return 0; 81 | } 82 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-04/soluciones/p09.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * LINK DEL PROBLEMA: 3 | * https://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=2746 4 | * 5 | * SOLUCIÓN: 6 | * Iteramos por todas las posibles columnas en las que podriamos poner las 7 | * piezaz, por cada configuracion elegida, eliminamos todas las piezas en 8 | * esa columna y luego chqueamos la cantidad de filas en las que aun quedan 9 | * piezas, si esta es menor o igual a la cantidad de piezas de la configuracion 10 | * que estamos iteracion, significa que podemos organizar esa configuracion 11 | * de tal manera que todas las piezas seas atacadas. Entonces, actualizamos 12 | * la respuesta de ser necesario 13 | * 14 | * COMPLEJIDAD: 15 | * O(2 ^ N * N * N) con N = 15 16 | */ 17 | 18 | #include 19 | 20 | using namespace std; 21 | 22 | const int N_ROWS = 15, N_COLS = 15, OFFSET = 2; 23 | const char EMPTY = '.', ENEMY = '#'; 24 | 25 | int ans; 26 | string grid[N_ROWS + OFFSET], tmp[N_ROWS + OFFSET]; 27 | 28 | void print() { 29 | cout << ans << endl; 30 | } 31 | 32 | int process(int cols_used) { 33 | copy(grid, grid + N_ROWS, tmp); 34 | for (int col = 0; col < N_COLS; col++) 35 | if ((cols_used >> col) bitand 1) { 36 | for (int row = 0; row < N_ROWS; row++) 37 | tmp[row][col] = EMPTY; 38 | } 39 | int remaining = 0; 40 | for (int row = 0; row < N_ROWS; row++) { 41 | for (int col = 0; col < N_COLS; col++) 42 | if (tmp[row][col] == ENEMY) { 43 | remaining++; 44 | break; 45 | } 46 | } 47 | if (__builtin_popcount(cols_used) >= remaining) return __builtin_popcount(cols_used); 48 | return INT_MAX; 49 | } 50 | 51 | void solve() { 52 | for (int mask = 0; mask < (1 << N_COLS); mask++) 53 | ans = min(ans, process(mask)); 54 | } 55 | 56 | bool readGrid() { 57 | cin >> grid[0]; 58 | if (grid[0][0] == 'E') return false; 59 | for (int row = 1; row < N_ROWS; row++) cin >> grid[row]; 60 | return true; 61 | } 62 | 63 | void init() { 64 | ans = INT_MAX; 65 | } 66 | 67 | int main() { 68 | while (readGrid()) { 69 | init(); 70 | solve(); 71 | print(); 72 | } 73 | return (0); 74 | } 75 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-04/soluciones/p01.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * LINK DEL PROBLEMA: 3 | * http://codeforces.com/problemset/problem/550/B 4 | * 5 | * SOLUCIÓN: 6 | * Básicamente tenemos un array 'c' con 'n' números y queremos saber 7 | * cuántos subconjuntos de 'c' podemos tomar tal que estos subconjuntos 8 | * tengan por lo menos 2 elementos, la suma de sus elementos sea >= 9 | * a 'x', su mínimo elemento sea >= a 'l' y su máximo elemento sea <= 'r'. 10 | * Ahora, si representamos esos subconjuntos como un string ('mask') de '1's y '0's 11 | * donde: 12 | * Si mask[i] = 1 -> Significa que ese conjunto contiene al elemento c[i] 13 | * Si mask[i] = 0 -> Significa que ese conjunto no continue al elemento c[i] 14 | * Entonces podemos generar todas las posibles configuraciones de 'mask' y 15 | * tener un contador que aumente en caso generemos un subconjunto válido para 16 | * asi conseguir la respuesta. 17 | * 18 | * COMPLEJIDAD: 19 | * Notemos que cada elemento de 'mask' puede tomar 2 valores ('1' o '0') 20 | * Entonces, la cantidad de posibles configuraciones de 'mask' es: 21 | * 2 * 2 * ... * 2 ('n' veces) = 2 ^ n 22 | * De manera que, podemos resolver el problema en O(2 ^ n) 23 | * 24 | * DETALLES DE LA IMPLEMENTACIÓN: 25 | * (1 << n) = 2 ^ n 26 | * continue = pasar a la siguiente iteración 27 | * __builtin_popcount(n) = 'cantidad de '1's de 'n' representado en binario' 28 | * INT_MAX = máximo int que soporta c++ 29 | * and = && 30 | * bitand = & 31 | */ 32 | 33 | #include 34 | 35 | using namespace std; 36 | 37 | const int MAX_N = 15, OFFSET = 1; 38 | 39 | int n, l, r, x, ans, c[MAX_N + OFFSET]; 40 | 41 | int main() { 42 | cin >> n >> l >> r >> x; 43 | for (int i = 0; i < n; i++) cin >> c[i]; 44 | for (int mask = 0; mask < (1 << n); mask++) { 45 | if (__builtin_popcount(mask) < 2) continue; 46 | int min_diff = INT_MAX, max_diff = 0, sum = 0; 47 | for (int bit = 0; bit < n; bit++) 48 | if ((mask >> bit) bitand 1) { 49 | sum += c[bit]; 50 | min_diff = min(min_diff, c[bit]); 51 | max_diff = max(max_diff, c[bit]); 52 | } 53 | if (l <= sum and sum <= r and (max_diff - min_diff) >= x) ans++; 54 | } 55 | cout << ans << endl; 56 | return (0); 57 | } 58 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-07/soluciones/L.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | problem : http://codeforces.com/contest/549/problem/H 3 | approach: binary search, math 4 | 5 | solution: como queremos hallar el minimo podemos hacer nuestro 6 | predicado p(x) : x es mayor o igual al minimo, aqui ocurre algo interesante 7 | sucede que si abs(a - b) <= x con b la mejor matriz posible, entonces 8 | b[i][j] pertenece al rango [x - a, x + a], ahora como ademas 9 | se debe cumplir que la matriz b tenga determinante igual a 0, entonces 10 | se cumple b[0][0] x b[1][1] == b[0][1] x b[1][0] pero como solo 11 | sabemos que b[i][j] esta en un rango, y ademas sabemos que el producto 12 | de dos rangos sigue siendo un rango, basta saber que el preoducto 13 | de los rango de b[0][0] y b[1][1] se intersecta con el producto de 14 | los rango de b[0][1] y b[1][0]. 15 | 16 | code: si tengo x que pertenece a [m, n] e y que pertenece a [p, q], 17 | entonces x.y pertenece al rango [min(min(m.p, m.q), min(n.p, n.q)), 18 | max(max(m.p, m.q), max(n.p, n.q))]. 19 | 20 | complexity: O(log(1e10)) 21 | **/ 22 | 23 | 24 | #include 25 | using namespace std; 26 | 27 | typedef pair segment; 28 | int a[4]; 29 | 30 | segment multiply(segment x, segment y){ 31 | 32 | long double lx = min(min(x.first * y.first, x.second * y.first), 33 | min(x.first * y.second, x.second * y.second)); 34 | long double rx = max(max(x.first * y.first, x.second * y.first), 35 | max(x.first * y.second, x.second * y.second)); 36 | 37 | return segment(lx, rx); 38 | } 39 | 40 | bool intersect(segment a, segment b){ 41 | return not (a.second < b.first or b.second < a.first); 42 | } 43 | 44 | bool p(long double x){ 45 | return intersect(multiply(segment(a[0] - x, a[0] + x), segment(a[3] - x, a[3] + x)), 46 | multiply(segment(a[1] - x, a[1] + x), segment(a[2] - x, a[2] + x))); 47 | } 48 | 49 | 50 | int main(){ 51 | 52 | for(int i = 0; i < 4; ++i) 53 | cin >> a[i]; 54 | 55 | long double lo = 0, hi = 1e10; 56 | for(int i = 0; i < 70; ++i){ 57 | long double mid = lo + (hi - lo)/2; 58 | if(p(mid)) hi = mid; 59 | else lo = mid; 60 | } 61 | 62 | cout << fixed << setprecision(9) << lo << endl; 63 | 64 | return 0; 65 | } -------------------------------------------------------------------------------- /uni-no-fiis/clase-01/ejemplos/05-estructuras-de-repeticion.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | 7 | /** 8 | * Existen 3 tipos de estructuras de repetición en c++ 9 | * for 10 | * while 11 | * do/while 12 | */ 13 | 14 | /** 15 | * estructura general del for 16 | * 17 | * for (inicialización; condiciones límites; actualización) { 18 | * Has algo; 19 | * } 20 | * 21 | * Nota 1: 22 | * 1. Se inicializan las variables declaradas en (inicialización) 23 | * 2. Se verifica si se cumplen (condiciones límites) [si se cumple se continúa con los siguientes pasos, sino ahí termina el bucle] 24 | * 2. Se ejecuta todo lo que este dentro del for 25 | * 3. Se hace lo que este dentro de (actualización) 26 | * 4. Se regresa al paso 2 27 | */ 28 | 29 | for (int i = 0; i < 3; i++) { 30 | cout << "i = " << i << endl; 31 | } 32 | 33 | /** 34 | * estructura general del while 35 | * 36 | * while (condición) { 37 | * has algo; 38 | * } 39 | * 40 | * Nota 1: 41 | * 1. Se verifica que se cumple (condición) [si se cumple se continua al paso 2, sino ahí termina el bucle] 42 | * 2. Se ejecuta todo lo que esta dentro del while y se regresa al paso 1 43 | */ 44 | 45 | int z = 6; 46 | while (z != 0) { 47 | cout << "z = " << z << endl; 48 | z--; 49 | } 50 | 51 | /** 52 | * estrucutura general del do / while 53 | * 54 | * do { 55 | * has algo; 56 | * } while (condición); 57 | * 58 | * Nota 1: 59 | * 1. Se ejecuta todo lo que este dentro del do 60 | * 2. Se verifica la (condición) [si se cumple se vuelve al paso 1, sino ahi termina el bucle] 61 | */ 62 | int a = 3; 63 | do { 64 | cout << "a = " << a << endl; 65 | a--; 66 | } while (a); // mientras a sea distinto de 0 67 | 68 | /** 69 | * Nota 1: 70 | * En realidad existen más 'tipos de estruturas de repetición' 71 | * for_each, ... (pero todas sirven para lo mismo : repetir sentencias) 72 | * Mas información de estructuras de repetición aquí: 73 | * http://www.cplusplus.com/doc/tutorial/control/ 74 | */ 75 | 76 | return (0); 77 | } -------------------------------------------------------------------------------- /uni-no-fiis/clase-02/ejemplos/stl.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main(){ 6 | 7 | //VECTOR EN 1D 8 | 9 | /*vector de una dimension 10 | En el primer parametro podemos especificar el tamaño 11 | En el segundo parametro podemos especificar un valor inicial para todos los elementos del vector 12 | */ 13 | vectorv1d(5, 0); 14 | 15 | //Eliminamos el ultimo elemento 16 | v1d.pop_back(); 17 | 18 | //Agregamos elementos al final 19 | v1d.push_back(3); 20 | v1d.push_back(10); 21 | 22 | for(int i=0; i >v2d(3, vector(4, 1)); 32 | 33 | //Accdemos primero a la fila y despues a la columna 34 | v2d[1][2] = 9; 35 | 36 | //Modificamos algunas filas 37 | v2d[0].pop_back(); 38 | v2d[2].push_back(5); 39 | 40 | cout << "2 dimensiones:" << endl; 41 | for(int i=0; is; 50 | 51 | //Agregamos valores usando insert: O(log n) 52 | s.insert(10); 53 | s.insert(3); 54 | s.insert(5); 55 | s.insert(3); 56 | 57 | //Consultamos si algun valor esta dentro de s: O(log n) 58 | if(s.find(100)!=s.end()) puts("Si esta"); 59 | else puts("No esta"); 60 | 61 | //Recorremos y vemos que un elemnto solo puede existir una vez 62 | cout << "Set:" << endl; 63 | for(set::iterator it = s.begin(); it!=s.end(); it++){ 64 | cout << *it << " "; 65 | } 66 | cout << endl; 67 | 68 | //MAP 69 | /*Nos permite crear una relacion clave->valor 70 | declaramos map 71 | */ 72 | 73 | mapmapa; 74 | 75 | //Agregamos elementos 76 | mapa[1000000] = 6; 77 | mapa[10000] = 4; 78 | mapa[100] = 1; 79 | 80 | //Modificamos: O(log n) 81 | mapa[100] += 1; 82 | 83 | //Recorremos el map 84 | //Vemos que esta ordenado de acuerdo a las claves 85 | cout << "Map: " << endl; 86 | for(map::iterator it = mapa.begin(); it!=mapa.end(); it++){ 87 | cout << it->first << " -> " << it->second << endl; 88 | } 89 | 90 | return 0; 91 | } 92 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-04/soluciones/p08.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * LINK DEL PROBLEMA: 3 | * https://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=3488 4 | * 5 | * SOLUCIÓN: 6 | * Probamos todas las posibles soluciones recorriendo usando máscara de bits 7 | * Y, de ser necesario, vamos actualizando la respuesta en cada iteracion 8 | * 9 | * COMPLEJIDAD: 10 | * O((N + P) * 2 ^ N) [En realidad es menos, pero esta cota esta cerca] 11 | */ 12 | 13 | #include 14 | 15 | using namespace std; 16 | 17 | const int MAX_N = 20, OFFSET = 2; 18 | 19 | int T, N, M, P, service[MAX_N + OFFSET], ans_1; 20 | vector > intersection; 21 | vector ans_2; 22 | 23 | void print() { 24 | cout << "Case Number " << ++T << endl; 25 | cout << "Number of Customers: " << ans_1 << endl; 26 | cout << "Locations recommended:"; 27 | for (int ai : ans_2) cout << ' ' << ai; 28 | cout << endl; 29 | cout << endl; 30 | } 31 | 32 | void solve() { 33 | for (int mask = 1; mask < (1 << N); mask++) { 34 | if (__builtin_popcount(mask) != M) continue; 35 | int sum = 0; 36 | vector tmp; 37 | for (int i = 0; i < N; i++) 38 | if ((mask >> i) bitand 1) 39 | sum += service[i], tmp.push_back(i + 1); 40 | for (int i = 0; i < P; i++) { 41 | int ct = 0; 42 | for (int j = 0; j + 1 < intersection[i].size(); j++) 43 | if ((mask >> (intersection[i][j] - 1)) bitand 1) 44 | ct++; 45 | if (ct) 46 | sum -= (ct - 1) * intersection[i].back(); 47 | } 48 | if (sum > ans_1 or (sum == ans_1 and tmp < ans_2)) { 49 | ans_1 = sum; 50 | ans_2 = tmp; 51 | } 52 | } 53 | } 54 | 55 | void readCase() { 56 | for (int i = 0; i < N; i++) cin >> service[i]; 57 | cin >> P; 58 | for (int i = 0, k; i < P; i++) { 59 | cin >> k; 60 | vector towers(k + 1); 61 | for (int i = 0; i <= k; i++) cin >> towers[i]; 62 | intersection.push_back(towers); 63 | } 64 | } 65 | 66 | void init() { 67 | intersection.clear(); 68 | ans_1 = 0; 69 | ans_2.clear(); 70 | } 71 | 72 | int main() { 73 | while (cin >> N >> M, N bitor M) { 74 | init(); 75 | readCase(); 76 | solve(); 77 | print(); 78 | } 79 | return (0); 80 | } 81 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-05/soluciones/5.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define all(v) (v).begin(),(v).end() 3 | #define pb push_back 4 | #define ppb pop_back 5 | #define mp make_pair 6 | #define ri(x) scanf("%d",&(x)) 7 | #define ri2(x,y) scanf("%d %d",&(x),&(y)) 8 | #define ri3(x,y,z) scanf("%d %d %d",&(x),&(y),&(z)) 9 | #define rll(x) scanf("%lld",&(x)) 10 | #define rll2(x,y) scanf("%lld %lld",&(x),&(y)) 11 | #define rll3(x,y,z) scanf("%lld %lld %lld",&(x),&(y),&(z)) 12 | #define rc(x) scanf("%c",&(x)) 13 | using namespace::std; 14 | 15 | const long double PI = acos(-1); 16 | const int MOD = 1000000000 +7; 17 | 18 | typedef long long ll; 19 | typedef pair pll; 20 | typedef pair tll; 21 | typedef pair ii; 22 | typedef pair iii; 23 | typedef vector vi; 24 | typedef vector vii; 25 | typedef vector viii; 26 | typedef vector vll; 27 | typedef vector vpll; 28 | typedef vector vtll; 29 | typedef vector vs; 30 | typedef set si; 31 | typedef set sii; 32 | typedef set siii; 33 | 34 | ll gcd(ll a, ll b){ return b==0?a:gcd(b,a%b);} 35 | 36 | int add(ll a, ll b){ return (a%MOD + b%MOD+2*MOD)%MOD;} 37 | 38 | int mul(ll a, ll b){ return ((a%MOD+MOD)*(b%MOD+MOD))%MOD;} 39 | 40 | ll pow_mod(ll a, ll b){ 41 | ll res = 1LL; 42 | a = add(a,0); 43 | while(b){ 44 | if(b&1) res = mul(res,a); 45 | b >>= 1; 46 | a = mul(a,a); 47 | } 48 | return res; 49 | } 50 | 51 | ll fastexp(ll a, ll b){ 52 | ll res = 1LL; 53 | while(b){ 54 | if(b&1) res = res*a; 55 | b >>= 1; 56 | a *= a; 57 | } 58 | return res; 59 | } 60 | 61 | int gcdExtendido(int a, int b, int *x, int *y){ 62 | if(a == 0){ 63 | *x = 0; 64 | *y = 1; 65 | return b; 66 | } 67 | int x1, y1; 68 | int gcd = gcdExtendido(b%a,a,&x1,&y1); 69 | 70 | *x = y1-(b/a)*x1; 71 | *y = x1; 72 | return gcd; 73 | }; 74 | 75 | int modInverso(int a, int m){ 76 | int x, y; 77 | int g = gcdExtendido(a,m,&x,&y); 78 | if(g!=1) return -1; 79 | else return (x%m + m)%m; 80 | } 81 | 82 | /**************************************** 83 | *************P*L*A*N*T*I*L*L*A************ 84 | *****************************************/ 85 | 86 | // Aprovechamos la funcion next_permutation 87 | 88 | string s; 89 | 90 | int main(){ 91 | while(getline(cin,s) and s!="#"){ 92 | if(next_permutation(all(s))){ 93 | cout << s << endl; 94 | } 95 | else puts("No Successor"); 96 | } 97 | return 0; 98 | } 99 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-07/soluciones/B.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | problem : http://codeforces.com/problemset/problem/231/C 3 | approach: binary search, sort, accumulate 4 | 5 | solution: 6 | 7 | hint 1: Si el elemento que mas se repide haciendo k 8 | cambios es x, entonces, los elementos que forman la 9 | respuesta en un inicio son <= x. 10 | 11 | hint 2: Si la respuesta es x con h operaciones y t 12 | repeticiones, para reducir h a lo menos posible los 13 | t elementos que se usan deben ser los mayores posibles 14 | que son <= x. 15 | 16 | hint 3: Como nos piden usar a lo mas k operaciones, 17 | y vez que el que mas se repite es y con q repeticiones y 18 | con m operaciones y el mayor elementos que usaste es z, 19 | con z < y entonces podemos reducir las opeaciones en 20 | (y - z)*q haciendo y = z. Esto nos dice que para que 21 | se gaste lo menos posibles, el elemento que se repite 22 | mas esta necesariamente en el array. 23 | 24 | 25 | code: 26 | si la respuesta es a[i], entonces buscaremos los que 27 | son mas cercanos a a[i] pero <= a el, para ello podemos 28 | ordenar los elementos y hacemos una busqueda binary sobre 29 | la cantidad de elementos que se repiten, vemos que esta 30 | funcion es a[i] * len - (sum[i] - sum[i - len + 1]), vemos 31 | que esta funcion es decreciente (pruebe eso), y por tanto 32 | es factible usar busqueda binaria. 33 | 34 | 35 | complexity: O(n x log(n)) 36 | **/ 37 | 38 | #include 39 | #include 40 | #include 41 | using namespace std; 42 | 43 | const int maxN = 1e5, OFFSET = 2; 44 | int a[maxN + OFFSET]; 45 | long long sum[maxN + OFFSET]; 46 | int n, k; 47 | 48 | void input(){ 49 | scanf("%d %d", &n, &k); 50 | for(int i = 1; i <= n; ++i) 51 | scanf("%d", a+i); 52 | } 53 | 54 | bool p(int x, int i){ 55 | return a[i] * 1ll * (i - x + 1) - (sum[i] - sum[x-1]) <= k; 56 | } 57 | 58 | void solve(){ 59 | 60 | sort(&a[1], &a[n+1]); 61 | 62 | for(int i = 1; i <= n; ++i) 63 | sum[i] = sum[i-1] + a[i]; 64 | 65 | int ans = 0, Min; 66 | for(int i = 1; i <= n; ++i){ 67 | int lo = 1, hi = i; 68 | while(lo < hi){ 69 | int mid = lo + (hi - lo)/2; 70 | if(not p(mid, i)) lo = mid + 1; 71 | else hi = mid; 72 | } 73 | 74 | if(ans < i - lo + 1){ 75 | ans = i - lo + 1; 76 | Min = a[i]; 77 | } 78 | } 79 | 80 | printf("%d %d\n", ans, Min); 81 | } 82 | 83 | 84 | int main() { 85 | 86 | input(); 87 | solve(); 88 | 89 | return 0; 90 | } -------------------------------------------------------------------------------- /uni-no-fiis/clase-01/soluciones/p06-v1.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * link : http://codeforces.com/problemset/problem/593/A 3 | * Problema: 4 | * Sea A = {word_1, word_2, ..., word_n} un conjunto de palabras 5 | * Sea B = {word_1, word_2, ..., word_m} [1 <= m <= n] un subconjunto de A 6 | * Sea length(word_i) = "tamaño de `word_i`" 7 | * Sea f(B) = suma {length(word_i) / word_i este en B} 8 | * Debes encontrar maximo(f(B)) para todo B subconjunto de A 9 | * que cumple que todos sus elementos esten formados por a lo mucho 2 unicos caracteres 10 | */ 11 | 12 | /** 13 | * Ejemplo: 14 | * Para A = {"abb", "cacc", "aaa", "bbb"} 15 | * Los B que cumplen las condiciones, son: 16 | * B_1 = {"abb"} f(B_1) = 3 17 | * B_2 = {"abb", "aaa"} f(B_2) = 6 18 | * B_3 = {"abb", "aaa", "bbb"} f(B_3) = 9 19 | * B_4 = {"aaa"} f(B_4) = 3 20 | * B_5 = {"aaa", "bbb"} f(B_5) = 6 21 | * B_6 = {"bbb"} f(B_6) = 3 22 | * B_7 = {"cacc"} f(B_7) = 4 23 | * B_8 = {"cacc", "aaa"} f(B_8) = 7 24 | * Encontes, la respuesta es maximo(f(B_1), f(B_2), ..., f(B_8)) = 9 25 | */ 26 | 27 | /** 28 | * Solucion: 29 | * Sea B un subconjunto de A, si suponemos que B cumple las condiciones del problema 30 | * Entonces exiten dos caracteres, sean (ch_1, ch_2) tal que todos los elementos de B estan formados por ellos 31 | * Pero ch_1 y ch_2 solo pueden tomar estos valores ('a', 'b', ..., 'y', 'z') 32 | * Entonces, podemos buscar con todas las configuraciones posibles de (ch_1, ch_2) y encontrar 33 | * subconjuntos B con la propiedad buscada y con ello encontrar maximo(f(B)) 34 | */ 35 | 36 | #include 37 | 38 | using namespace std; 39 | 40 | const int MAX_N = 110; 41 | 42 | int n, ans; 43 | string word[MAX_N]; 44 | 45 | bool isValid(int id, char ch_1, char ch_2) { 46 | for (int pos = 0; pos < word[id].size(); pos++) 47 | if (word[id][pos] != ch_1 and word[id][pos] != ch_2) return false; 48 | return true; 49 | } 50 | 51 | int main() { 52 | cin >> n; 53 | for (int i = 0; i < n; i++) cin >> word[i]; 54 | for (char ch_1 = 'a'; ch_1 <= 'z'; ch_1++) 55 | for (char ch_2 = ch_1; ch_2 <= 'z'; ch_2++) { 56 | int sum = 0; 57 | for (int id = 0; id < n; id++) sum += isValid(id, ch_1, ch_2) * word[id].size(); 58 | ans = max(ans, sum); 59 | } 60 | cout << ans << endl; 61 | return (0); 62 | } -------------------------------------------------------------------------------- /uni-no-fiis/clase-04/soluciones/p03.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * LINK DEL PROBLEMA: 3 | * http://codeforces.com/problemset/problem/114/B 4 | * 5 | * SOLUCIÓN: 6 | * Tenemos un array de 'n' elementos: nombre[1], nombre[2], ..., nombre[n] 7 | * Y 'm' pares: 'nombre_1', 'nombre_2' de personas que no se llevan bien 8 | * Luego, tenemos que encontrar un subconjunto del array dado tal que 9 | * no hayan 2 pares de individuos que se odien y que el conjunto sea tan 10 | * grande como sea posible. 11 | * Y la respuesta sera el tamaño de ese conjunto, seguido de sus elementos 12 | * impresos en orden lexicográfico 13 | * Entonces, podemos usar la misma táctica del problema 1: Crear una mascara 14 | * de 'n' bits, iterar por todas sus posibles configuraciones, ver si el 15 | * subconjunto asociado cumple las condiciones dadas y de ser así, actualizar 16 | * la respuesta de ser necesario. 17 | * 18 | * COMPLEJIDAD 19 | * O(m * 2 ^ n) 20 | * 21 | * DETALLES DE LA IMPLEMENTACIÓN: 22 | * EL uso del 'map' es para poder asociar un indice a cada nombre dado 23 | * La razón de ordenar el array dado antes de asociarle un indice a cada nombre 24 | * es para que cuando iteremos la 'mask' resultante como respuesta, obtengamos 25 | * los nombres en orden lexicográfico 26 | * hate[i] = {order[name_1], order[name_2]} = make_pair(order[name_1], order[name_2]) 27 | */ 28 | 29 | #include 30 | 31 | using namespace std; 32 | 33 | const int MAX_N = 16, MAX_M = 120, OFFSET = 5; 34 | 35 | int n, m, ans_k, ans_mask; 36 | map order; 37 | pair hate[MAX_M + OFFSET]; 38 | string name_1, name_2, name[MAX_N + OFFSET]; 39 | 40 | int main() { 41 | cin >> n >> m; 42 | for (int i = 0; i < n; i++) cin >> name[i]; 43 | sort(name, name + n); 44 | for (int i = 0; i < n; i++) order[name[i]] = i; 45 | for (int i = 0; i < m; i++) { 46 | cin >> name_1 >> name_2; 47 | hate[i] = {order[name_1], order[name_2]}; 48 | } 49 | for (int mask = 0; mask < (1 << n); mask++) { 50 | bool valid = true; 51 | for (int i = 0; i < m; i++) 52 | if ((mask >> hate[i].first) bitand 1 and (mask >> hate[i].second) bitand 1) 53 | valid = false; 54 | if (valid and ans_k < __builtin_popcount(mask)) { 55 | ans_k = __builtin_popcount(mask); 56 | ans_mask = mask; 57 | } 58 | } 59 | cout << ans_k << endl; 60 | for (int bit = 0; bit < n; bit++) if ((ans_mask >> bit) bitand 1) cout << name[bit] << endl; 61 | return (0); 62 | } 63 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-06/soluciones/p07.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define SIZE 20 4 | 5 | using namespace std; 6 | 7 | struct Team{ 8 | char name[SIZE], lower_name[SIZE]; 9 | int points, games, goals, sgoals, dif; 10 | }aux; 11 | 12 | int tc, t, g, pos1, pos2, g1, g2, j; 13 | char s[SIZE], team1[SIZE], team2[SIZE]; 14 | vector v; 15 | 16 | inline bool equals(Team x, Team y) { 17 | return (x.points == y.points && x.dif == y.dif && x.goals == y.goals); 18 | } 19 | 20 | bool cmp(const Team& x, const Team& y) { 21 | if(x.points != y.points) return (x.points > y.points); 22 | if(x.dif != y.dif) return (x.dif > y.dif); 23 | if(x.goals != y.goals) return (x.goals > y.goals); 24 | return (strcmp(x.lower_name, y.lower_name) < 0); 25 | } 26 | 27 | void lowerNames() { 28 | for(int i = 0; i < v.size(); i++){ 29 | for(j = 0; v[i].name[j]; j++) v[i].lower_name[j] = tolower(v[i].name[j]); 30 | v[i].lower_name[j] = '\0'; 31 | } 32 | } 33 | 34 | int findTeam(char x[]) { 35 | for(int i = 0; i < v.size(); i++) if(strcmp(v[i].name, x)==0) return i; 36 | } 37 | 38 | void printResults() { 39 | int it = 1; 40 | for(int i = 0; i < v.size(); i++, it++){ 41 | if(i == 0 || equals(v[i], v[i - 1]) == false) printf("%2d.", it); 42 | else printf(" "); 43 | printf("%16s %3d %3d %3d %3d %3d ", v[i].name, v[i].points, v[i].games, v[i].goals, v[i].sgoals, v[i].dif); 44 | if(v[i].games) printf("%6.2f\n", 100.0 * v[i].points / (3.0 * v[i].games)); 45 | else printf(" N/A\n"); 46 | } 47 | } 48 | 49 | int main(){ 50 | while (scanf("%d %d\n", &t, &g), t | g) { 51 | if (tc++) putchar('\n'); 52 | v.clear(); 53 | for (int i = 0; i < t; i++) scanf("%s", s), strcpy(aux.name, s), v.push_back(aux); 54 | for (int i = 0;i < g; i++){ 55 | scanf("%s %d - %d %s", team1, &g1, &g2, team2); 56 | pos1 = findTeam(team1); 57 | pos2 = findTeam(team2); 58 | if(g1 > g2) v[pos1].points += 3; 59 | else if(g1 < g2) v[pos2].points += 3; 60 | else v[pos1].points += 1, v[pos2].points += 1; 61 | v[pos1].games += 1, v[pos2].games += 1; 62 | v[pos1].goals += g1, v[pos2].goals += g2; 63 | v[pos1].sgoals += g2, v[pos2].sgoals += g1; 64 | v[pos1].dif += g1 - g2; 65 | v[pos2].dif += g2 - g1; 66 | } 67 | lowerNames(); 68 | sort(v.begin(), v.end(), cmp); 69 | printResults(); 70 | } 71 | return(0); 72 | } 73 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-07/soluciones/K.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | problem : http://codeforces.com/problemset/problem/555/D 3 | approach: binary search, math, simulation 4 | 5 | solution: para este problema el binary search sera un intermediario, 6 | vamos a simular el movimiento y tener cuidado con los bucles innecesarios 7 | (tal como que gire en un solo punto o que gire muchas veces por elementos), 8 | para probar la complejidad debemos ver que si voy del punto a para el punto b 9 | y luego a un punto c en medio de ellos, entonces el peor caso esta cuando 10 | c se encuentra en el punto medio del camino de a a b, esto ocurre ya que si 11 | la distancia es menor entonces el problema se reduce a un intervalo menor 12 | a la mitad, y si es mas que la mitad la cuerda piede mas de la mitad (en el 13 | primer caso la cuerda hace giros "inutiles" sobre los mismos elementos 14 | en la peor de todas las situaciones) 15 | 16 | code: hay que mapear los indices de los elementos, para poder hacer busqueda 17 | binaria sobre ellos, luego tenga el cuenta la direccion del giro y los casos 18 | que gire muchas veces sobre el mismo par de puntos. 19 | 20 | complexity: O(n x log(n) + m x log(n) x log(l)) 21 | **/ 22 | 23 | 24 | #include 25 | using namespace std; 26 | 27 | const int N = 200005; 28 | int X[N], inv[N]; 29 | pair B[N]; 30 | int n, m, a, l; 31 | 32 | 33 | int main(){ 34 | 35 | scanf("%d %d", &n, &m); 36 | for(int i = 1; i <= n; ++i){ 37 | scanf("%d", X+i); 38 | B[i] = {X[i], i}; 39 | } 40 | 41 | sort(B+1, B+n+1); 42 | for(int i = 1; i <= n; ++i) 43 | inv[B[i].second] = i; 44 | 45 | 46 | while(m--){ 47 | scanf("%d %d", &a, &l); 48 | 49 | a = inv[a]; 50 | int prev = -1; 51 | bool ok = 1; 52 | int lo, hi; 53 | while(l){ 54 | if(ok){ 55 | lo = a; hi = n; 56 | while(lo < hi){ 57 | int mid = lo + (hi-lo+1)/2; 58 | if(B[mid].first - B[a].first <= l) lo = mid; 59 | else hi = mid-1; 60 | } 61 | 62 | } 63 | else{ 64 | lo = 1; hi = a; 65 | while(lo < hi){ 66 | int mid = lo + (hi-lo)/2; 67 | if(B[a].first - B[mid].first > l) lo = mid+1; 68 | else hi = mid; 69 | } 70 | } 71 | 72 | 73 | if(lo == prev){ 74 | if(lo == a) break; 75 | l %= 2*abs(B[a].first - B[lo].first); 76 | if(l == 0) break; 77 | } 78 | 79 | 80 | if(l >= abs(B[a].first - B[lo].first)){ 81 | l -= abs(B[a].first - B[lo].first); 82 | prev = a; 83 | a = lo; 84 | ok ^= 1; 85 | } 86 | } 87 | 88 | printf("%d\n", B[a].second); 89 | } 90 | 91 | 92 | return 0; 93 | } -------------------------------------------------------------------------------- /uni-no-fiis/clase-10/ejemplos/42-iterative.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | vector ans; 6 | 7 | int sum(string s) { 8 | int ret = 0; 9 | for (char ch : s) ret += ch - 'a' + 1; 10 | return ret; 11 | } 12 | 13 | void generate(string s) { 14 | do { 15 | ans.push_back(s); 16 | } while (next_permutation(begin(s), end(s))); 17 | } 18 | 19 | int main() { 20 | string s = ""; 21 | for (char ch_1 = 'a'; ch_1 <= 'z'; ch_1++) { 22 | s += ch_1; 23 | for (char ch_2 = ch_1; ch_2 <= 'z'; ch_2++) { 24 | s += ch_2; 25 | if (sum(s) == 42) generate(s); 26 | if (sum(s) < 42) { 27 | for (char ch_3 = ch_2; ch_3 <= 'z'; ch_3++) { 28 | s += ch_3; 29 | if (sum(s) == 42) generate(s); 30 | if (sum(s) < 42) { 31 | for (char ch_4 = ch_3; ch_4 <= 'z'; ch_4++) { 32 | s += ch_4; 33 | if (sum(s) == 42) generate(s); 34 | if (sum(s) < 42) { 35 | for (char ch_5 = ch_4; ch_5 <= 'z'; ch_5++) { 36 | s += ch_5; 37 | if (sum(s) == 42) generate(s); 38 | if (sum(s) < 42) { 39 | for (char ch_6 = ch_5; ch_6 <= 'z'; ch_6++) { 40 | s += ch_6; 41 | if (sum(s) == 42) generate(s); 42 | if (sum(s) < 42) { 43 | for (char ch_7 = ch_6; ch_7 <= 'z'; ch_7++) { 44 | s += ch_7; 45 | if (sum(s) == 42) generate(s); 46 | s.pop_back(); 47 | } 48 | } 49 | s.pop_back(); 50 | } 51 | } 52 | s.pop_back(); 53 | } 54 | } 55 | s.pop_back(); 56 | } 57 | } 58 | s.pop_back(); 59 | } 60 | } 61 | s.pop_back(); 62 | } 63 | s.pop_back(); 64 | } 65 | sort(begin(ans), end(ans)); 66 | for (string ans_i : ans) cout << ans_i << endl; 67 | return (0); 68 | } 69 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-04/soluciones/p04.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * LINK DEL PROBLEMA: 3 | * https://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=3682 4 | * 5 | * SOLUCIÓN: 6 | * Simulemos todo el proceso 7 | * Sea 'arr' un array de los 2 ** N jugadores que indica si el jugador se ha retiraro (false) o no (true) 8 | * Por ejemplo, para N = 3, tenemos 9 | * arr[0] arr[1] arr[2] arr[3] arr[4] arr[5] arr[6] arr[7] [8 elementos] 10 | * \ / \ / \ / \ / 11 | * arr'[0] arr'[1] arr'[2] arr'[3] [4 elementos] 12 | * \ / \ / 13 | * arr''[0] arr''[1] [2 elementos] 14 | * \ / 15 | * arr''[0] [1 elemento ] 16 | * Entonces, para simular el proceso el array lo iteramos de 2 en 2 17 | * Y si de los dos elementos que estoy verificando, uno es falso, eso significa que estamos en un 18 | * w / o, asi que aumentamos un contador que será la respuesta y el elemento que agreguemos al nuevo 19 | * array sera verdadero si alguno de los elementos que estoy verificando lo es. Luego procedemos a hacer 20 | * lo mismo con el nuevo array formado, y continuamos con el proceso hasta que obtegamos un array de 1 elemento 21 | * 22 | * COMPLEJIDAD: 23 | * O(2 ^ (N + 1)) 24 | * 25 | * DETALLES DE LA IMPLEMENTACIÓN: 26 | * var >>= 1 'es igual a' var /= 2 'es igual a' var = var / 2 27 | * bitor = | = OR OPERATION 28 | * xor = ^ = XOR OPERATION 29 | */ 30 | 31 | #include 32 | 33 | using namespace std; 34 | 35 | const int N_PLAYERS = 1 << 10, OFFSET = 1; 36 | 37 | int T, N, M, ans; 38 | bool arr[N_PLAYERS + OFFSET]; 39 | 40 | void print() { 41 | cout << ans << endl; 42 | } 43 | 44 | void solve() { 45 | int limit = 1 << N; 46 | while (limit != 1) { 47 | for (int bit = 0; bit < limit; bit += 2) { 48 | bool bit_1 = arr[bit]; 49 | bool bit_2 = arr[bit + 1]; 50 | if (bit_1 xor bit_2) ans++; 51 | arr[bit >> 1] = bit_1 bitor bit_2; 52 | } 53 | limit >>= 1; 54 | } 55 | } 56 | 57 | void readCase() { 58 | cin >> N >> M; 59 | for (int player = 0; player < (1 << N); player++) arr[player] = true; 60 | for (int i = 0, player; i < M; i++) { 61 | cin >> player; 62 | arr[--player] = false; 63 | } 64 | } 65 | 66 | void init() { 67 | ans = 0; 68 | } 69 | 70 | int main() { 71 | cin >> T; 72 | while (T--) { 73 | init(); 74 | readCase(); 75 | solve(); 76 | print(); 77 | } 78 | return (0); 79 | } 80 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-07/soluciones/D.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | problem : http://codeforces.com/contest/578/problem/C 3 | approach: binary search, max array problem 4 | 5 | solution: 6 | hint 1: lo que nos piden es la maxima suma en un 7 | subarray de los elementos a[i] - x y los elementos 8 | x - a[i] separadamente. 9 | 10 | hint 2: si nosotros escogemos un x, denotemos 11 | fl(x) = a la maxima suma en subarray de los elementos 12 | a[i] - x, y fr(x) a la maxima suma en subarray de los 13 | elementos x - a[i], ahora sea la funcion G, definida 14 | G(x) = fl(x) - fr(x), vemos que esta funcion es decreciente 15 | ya que es logico que al disminuir la resta, hay mas positivos 16 | para hacer una suma mas grande y al aumentar hay mas negativos 17 | tal que x - a[i] se vuelve mas negativo por tanto fr aumenta, 18 | entonces, ya que fl(x) decrece y fr(x) aumenta al aumentar x 19 | tenemos G(x) es decreciente. 20 | 21 | hint 3: existe y tal que G(y) = 0, basta con ver que G(-100000) 22 | es la suma de los elementos + 10000*n que es >= 0 y que G(100000) 23 | da 0 ya que no hay elemento mayor a 0. Por tanto tenemos que debe 24 | existir y tal que G(y) = 0. 25 | 26 | 27 | code: 28 | Como existe y que da cero, basta con hacer busqueda binaria sobre 29 | fl(x) - fr(x) > 0 de donde queremos el primero que no cumpla. 30 | 31 | Sobre la implementacion debemos notar que si queremos hallar 32 | la maxima suma desde nuestra posicion actual, esta es igual 33 | a la maxima suma anterior + el elemento actual o 0 ya que no 34 | hay maxima suma (por que si es negativa no nos importa por 35 | eso se restringe los limites). 36 | 37 | 38 | complexity: O(n x log((max(a) - min(a))/eps)) 39 | **/ 40 | 41 | 42 | #include 43 | using namespace std; 44 | 45 | const int N = 2e5, OFFSET = 2; 46 | int n; 47 | int a[N + OFFSET]; 48 | double ans; 49 | 50 | void input(){ 51 | scanf("%d", &n); 52 | for(int i = 0; i < n; ++i) 53 | scanf("%d", a+i); 54 | } 55 | 56 | bool p(double x, bool ok = 0){ 57 | 58 | double lans = 0, lans_ = 0; 59 | for(int i = 0; i < n; ++i){ 60 | lans_ = max(lans_ + a[i] - x, 0.0d); 61 | lans = max(lans, lans_); 62 | } 63 | 64 | double rans = 0, rans_ = 0; 65 | for(int i = 0; i < n; ++i){ 66 | rans_ = max(rans_ + x - a[i], 0.0d); 67 | rans = max(rans, rans_); 68 | } 69 | 70 | if(ok) ans = max(lans, rans); 71 | 72 | return lans > rans; 73 | } 74 | 75 | void solve(){ 76 | 77 | double lo = *min_element(a, a+n), hi = *max_element(a, a+n); 78 | for(int i = 0; i < 80; ++i){ 79 | double mid = lo + (hi-lo)/2; 80 | if(p(mid)) lo = mid; 81 | else hi = mid; 82 | } 83 | 84 | printf("%.15Lf\n", (p(lo, 1), ans)); 85 | } 86 | 87 | 88 | 89 | int main(){ 90 | 91 | input(); 92 | solve(); 93 | 94 | return 0; 95 | } -------------------------------------------------------------------------------- /uni-no-fiis/clase-05/soluciones/6.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define all(v) (v).begin(),(v).end() 3 | #define pb push_back 4 | #define ppb pop_back 5 | #define mp make_pair 6 | #define ri(x) scanf("%d",&(x)) 7 | #define ri2(x,y) scanf("%d %d",&(x),&(y)) 8 | #define ri3(x,y,z) scanf("%d %d %d",&(x),&(y),&(z)) 9 | #define rll(x) scanf("%lld",&(x)) 10 | #define rll2(x,y) scanf("%lld %lld",&(x),&(y)) 11 | #define rll3(x,y,z) scanf("%lld %lld %lld",&(x),&(y),&(z)) 12 | #define rc(x) scanf("%c",&(x)) 13 | using namespace::std; 14 | 15 | const long double PI = acos(-1); 16 | const int MOD = 1000000000 +7; 17 | 18 | typedef long long ll; 19 | typedef pair pll; 20 | typedef pair tll; 21 | typedef pair ii; 22 | typedef pair iii; 23 | typedef vector vi; 24 | typedef vector vii; 25 | typedef vector viii; 26 | typedef vector vll; 27 | typedef vector vpll; 28 | typedef vector vtll; 29 | typedef vector vs; 30 | typedef set si; 31 | typedef set sii; 32 | typedef set siii; 33 | 34 | ll gcd(ll a, ll b){ return b==0?a:gcd(b,a%b);} 35 | 36 | int add(ll a, ll b){ return (a%MOD + b%MOD+2*MOD)%MOD;} 37 | 38 | int mul(ll a, ll b){ return ((a%MOD+MOD)*(b%MOD+MOD))%MOD;} 39 | 40 | ll pow_mod(ll a, ll b){ 41 | ll res = 1LL; 42 | a = add(a,0); 43 | while(b){ 44 | if(b&1) res = mul(res,a); 45 | b >>= 1; 46 | a = mul(a,a); 47 | } 48 | return res; 49 | } 50 | 51 | ll fastexp(ll a, ll b){ 52 | ll res = 1LL; 53 | while(b){ 54 | if(b&1) res = res*a; 55 | b >>= 1; 56 | a *= a; 57 | } 58 | return res; 59 | } 60 | 61 | int gcdExtendido(int a, int b, int *x, int *y){ 62 | if(a == 0){ 63 | *x = 0; 64 | *y = 1; 65 | return b; 66 | } 67 | int x1, y1; 68 | int gcd = gcdExtendido(b%a,a,&x1,&y1); 69 | 70 | *x = y1-(b/a)*x1; 71 | *y = x1; 72 | return gcd; 73 | }; 74 | 75 | int modInverso(int a, int m){ 76 | int x, y; 77 | int g = gcdExtendido(a,m,&x,&y); 78 | if(g!=1) return -1; 79 | else return (x%m + m)%m; 80 | } 81 | 82 | /**************************************** 83 | *************P*L*A*N*T*I*L*L*A************ 84 | *****************************************/ 85 | 86 | // Como todos son positivos, entonces nos basta una comparacion e iterar hasta que pueda caber. 87 | 88 | string v[] = {"127","32767","2147483647","9223372036854775807"}; 89 | 90 | int n; 91 | string s; 92 | string ans[] = {"byte","short","int","long","BigInteger"}; 93 | 94 | bool menor(string a, string b){ 95 | if(a.size() < b.size()) return true; 96 | if(a.size() > b.size()) return false; 97 | return a> s; 102 | n = s.size(); 103 | int pos = 0; 104 | while(pos < 4 and menor(v[pos],s)){ 105 | pos+=1; 106 | } 107 | cout << ans[pos] << endl; 108 | return 0; 109 | } 110 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-01/ejemplos/08-vectores.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | 7 | /** 8 | * Hay situaciones en las que necesitamos tener varias variables del mismo tipo 9 | * Entonces, en ves de declarar por ejemplo 10 int como: 10 | * int num_1, num_2, num_3, ..., num_10 11 | * Existe una estructura de datos llamada vector, ella nos permite almacenar datos del mismo tipo 12 | * Estructura general 13 | * 14 | * vector nombre_del_vector; 15 | * 16 | */ 17 | 18 | vector mi_vector; // creamos un vector vacío de enteros 19 | // mi_vector = [] 20 | mi_vector.push_back(3); // agregamos un elemento 21 | // mi_vector = [3] 22 | mi_vector.push_back(5); // agregamos otro elemento 23 | // mi_vector = [3, 5] 24 | mi_vector.push_back(8); // agregamos otro elemento 25 | // mi_vector = [3, 5, 8] 26 | mi_vector.pop_back(); // eliminamos el último elemento 27 | // mi_vector = [3, 5] 28 | mi_vector.push_back(10); // agregamos otro elemento 29 | // mi_vector = [3, 5, 10] 30 | 31 | /** 32 | * mi_vector = [3, 5, 10] 33 | * podemos acceder a cada elemento así: 34 | * mi_vector[índice] 35 | * entonces 36 | * mi_vector[0] : 3 37 | * mi_vector[1] : 5 38 | * mi_vector[2] : 10 39 | * Notemos que (índice) comienza a contarse desde 0 40 | * Luego, si queremos imprimir todos los elementos de nuestro vector podemos hacerlo de las siguientes maneras 41 | */ 42 | 43 | // método 1 44 | for (int elemento : mi_vector) std::cout << elemento << ' '; // como lo que esta dentro del for es solo una sentencia, puedo omitir los corchetes ({ }) 45 | cout << endl; 46 | 47 | // método 2 48 | for (int indice = 0; indice < mi_vector.size(); indice++) { 49 | cout << "mi_vector[" << indice << "] = " << mi_vector[indice] << endl; 50 | } 51 | 52 | // notemos que con el método 2 puedes saber el índice que corresponde a cada elemento y el valor en esa posición 53 | // mientras que con el método 1 solo el valor asociada a cada posición 54 | 55 | /** 56 | * Más información de vectores aqui: 57 | * http://www.cplusplus.com/reference/vector/vector/ 58 | */ 59 | 60 | /** 61 | * Los vectores son en realidad arrays dinámicos con ciertos métodos (funciones) ya que puedemos ir agregando y quitando elementos 62 | * Si deseamos un array estático (tenemos definido el número de elementos máximo) podemos declararlos así: 63 | * 64 | * tipo_de_dato nombre_de_variable[cantidad_de_elementos] 65 | * 66 | * Por ejemplo: 67 | * int v[100]; 68 | * es un array estático de 100 enteros 69 | * 70 | * Más información de arrays estáticos aquí: 71 | * http://www.cplusplus.com/doc/tutorial/arrays/ 72 | */ 73 | 74 | return (0); 75 | } -------------------------------------------------------------------------------- /uni-no-fiis/clase-09/soluciones/p04.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define all(v) (v).begin(),(v).end() 3 | #define pb push_back 4 | #define ppb pop_back 5 | #define mp make_pair 6 | #define ri(x) scanf("%d",&(x)) 7 | #define ri2(x,y) scanf("%d %d",&(x),&(y)) 8 | #define ri3(x,y,z) scanf("%d %d %d",&(x),&(y),&(z)) 9 | #define rll(x) scanf("%lld",&(x)) 10 | #define rll2(x,y) scanf("%lld %lld",&(x),&(y)) 11 | #define rll3(x,y,z) scanf("%lld %lld %lld",&(x),&(y),&(z)) 12 | #define rc(x) scanf("%c",&(x)) 13 | using namespace::std; 14 | 15 | const long double PI = acos(-1); 16 | const int MOD = 1000000000 +7; 17 | 18 | typedef long long ll; 19 | typedef pair pll; 20 | typedef pair tll; 21 | typedef pair ii; 22 | typedef pair iii; 23 | typedef vector vi; 24 | typedef vector vii; 25 | typedef vector viii; 26 | typedef vector vll; 27 | typedef vector vpll; 28 | typedef vector vtll; 29 | typedef vector vs; 30 | typedef set si; 31 | typedef set sii; 32 | typedef set siii; 33 | 34 | ll gcd(ll a, ll b){ return b==0?a:gcd(b,a%b);} 35 | 36 | int add(ll a, ll b){ return (a%MOD + b%MOD+2*MOD)%MOD;} 37 | 38 | int mul(ll a, ll b){ return ((a%MOD+MOD)*(b%MOD+MOD))%MOD;} 39 | 40 | ll pow_mod(ll a, ll b){ 41 | ll res = 1LL; 42 | a = a%MOD; 43 | while(b){ 44 | if(b&1) res = mul(res,a); 45 | b >>= 1; 46 | a = mul(a,a); 47 | } 48 | return res; 49 | } 50 | 51 | ll fastexp(ll a, ll b){ 52 | ll res = 1LL; 53 | while(b){ 54 | if(b&1) res = res*a; 55 | b >>= 1; 56 | a *= a; 57 | } 58 | return res; 59 | } 60 | 61 | int gcdExtendido(int a, int b, int *x, int *y){ 62 | if(a == 0){ 63 | *x = 0; 64 | *y = 1; 65 | return b; 66 | } 67 | int x1, y1; 68 | int gcd = gcdExtendido(b%a,a,&x1,&y1); 69 | 70 | *x = y1-(b/a)*x1; 71 | *y = x1; 72 | return gcd; 73 | }; 74 | 75 | int modInverso(int a, int m){ 76 | int x, y; 77 | int g = gcdExtendido(a,m,&x,&y); 78 | if(g!=1) return -1; 79 | else return (x%m + m)%m; 80 | } 81 | 82 | /**************************************** 83 | *************P*L*A*N*T*I*L*L*A************ 84 | *****************************************/ 85 | 86 | /* El concepto del problema es simple, obtener suma de cifras hasta llegar a 9 87 | * y sumar 1 cada vez que se de. 88 | * Como los numeros son grandes, la primera vez leemos como string. 89 | */ 90 | 91 | int n; 92 | string s; 93 | 94 | int f(int x){ 95 | if(x == 9) return 0; 96 | int s = 0; 97 | while(x){ 98 | s += x%10; 99 | x /= 10; 100 | } 101 | return 1+f(s); 102 | } 103 | 104 | int main(){ 105 | while(cin >> s and s!="0"){ 106 | printf("%s",s.c_str()); 107 | n = 1; 108 | int suma = 0; 109 | for(int i=0; i 2 | #define all(v) (v).begin(),(v).end() 3 | #define pb push_back 4 | #define ppb pop_back 5 | #define mp make_pair 6 | #define ri(x) scanf("%d",&(x)) 7 | #define ri2(x,y) scanf("%d %d",&(x),&(y)) 8 | #define ri3(x,y,z) scanf("%d %d %d",&(x),&(y),&(z)) 9 | #define rll(x) scanf("%lld",&(x)) 10 | #define rll2(x,y) scanf("%lld %lld",&(x),&(y)) 11 | #define rll3(x,y,z) scanf("%lld %lld %lld",&(x),&(y),&(z)) 12 | #define rc(x) scanf("%c",&(x)) 13 | using namespace::std; 14 | 15 | const long double PI = acos(-1); 16 | const int MOD = 1000000000 +7; 17 | 18 | typedef long long ll; 19 | typedef pair pll; 20 | typedef pair tll; 21 | typedef pair ii; 22 | typedef pair iii; 23 | typedef vector vi; 24 | typedef vector vii; 25 | typedef vector viii; 26 | typedef vector vll; 27 | typedef vector vpll; 28 | typedef vector vtll; 29 | typedef vector vs; 30 | typedef set si; 31 | typedef set sii; 32 | typedef set siii; 33 | 34 | ll gcd(ll a, ll b){ return b==0?a:gcd(b,a%b);} 35 | 36 | int add(ll a, ll b){ return (a%MOD + b%MOD+2*MOD)%MOD;} 37 | 38 | int mul(ll a, ll b){ return ((a%MOD+MOD)*(b%MOD+MOD))%MOD;} 39 | 40 | ll pow_mod(ll a, ll b){ 41 | ll res = 1LL; 42 | a = a%MOD; 43 | while(b){ 44 | if(b&1) res = mul(res,a); 45 | b >>= 1; 46 | a = mul(a,a); 47 | } 48 | return res; 49 | } 50 | 51 | ll fastexp(ll a, ll b){ 52 | ll res = 1LL; 53 | while(b){ 54 | if(b&1) res = res*a; 55 | b >>= 1; 56 | a *= a; 57 | } 58 | return res; 59 | } 60 | 61 | int gcdExtendido(int a, int b, int *x, int *y){ 62 | if(a == 0){ 63 | *x = 0; 64 | *y = 1; 65 | return b; 66 | } 67 | int x1, y1; 68 | int gcd = gcdExtendido(b%a,a,&x1,&y1); 69 | 70 | *x = y1-(b/a)*x1; 71 | *y = x1; 72 | return gcd; 73 | }; 74 | 75 | int modInverso(int a, int m){ 76 | int x, y; 77 | int g = gcdExtendido(a,m,&x,&y); 78 | if(g!=1) return -1; 79 | else return (x%m + m)%m; 80 | } 81 | 82 | /**************************************** 83 | *************P*L*A*N*T*I*L*L*A************ 84 | *****************************************/ 85 | 86 | /* Nos damos cuenta de que si usamos un triangulo rectangulo isosceles de base B 87 | * podemos llenar de cuadrados de 2x2 toda la base posible, si separamos por 88 | * casos: 89 | * B = 2k -> k cuadrados, pero 1 se parte por la hipotenusa, entonces k-1 90 | * B = 2k+1 -> k cuadrados, pero 1 se parte por la hipotenusa tambien, entonces k-1 91 | * Luego de esto, nos quedara un triangulo de base B-2 92 | * Casos base: B <= 3 -> 0 93 | * Recursion: f(B) = (B/2 - 1) + f(B-2) 94 | * 95 | * Complejidad por caso: O(Bmax) 96 | * Complejidad total: O(T*Bmax) 97 | */ 98 | 99 | int f(int B){ 100 | if(B <= 3) return 0; 101 | return (B/2 - 1) + f(B-2); 102 | } 103 | 104 | int main(){ 105 | int t, B; 106 | ri(t); 107 | while(t--){ 108 | ri(B); 109 | printf("%d\n",f(B)); 110 | } 111 | return 0; 112 | } 113 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-09/soluciones/p01.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define all(v) (v).begin(),(v).end() 3 | #define pb push_back 4 | #define ppb pop_back 5 | #define mp make_pair 6 | #define ri(x) scanf("%d",&(x)) 7 | #define ri2(x,y) scanf("%d %d",&(x),&(y)) 8 | #define ri3(x,y,z) scanf("%d %d %d",&(x),&(y),&(z)) 9 | #define rll(x) scanf("%lld",&(x)) 10 | #define rll2(x,y) scanf("%lld %lld",&(x),&(y)) 11 | #define rll3(x,y,z) scanf("%lld %lld %lld",&(x),&(y),&(z)) 12 | #define rc(x) scanf("%c",&(x)) 13 | using namespace::std; 14 | 15 | const long double PI = acos(-1); 16 | const int MOD = 1000000000 +7; 17 | 18 | typedef long long ll; 19 | typedef pair pll; 20 | typedef pair tll; 21 | typedef pair ii; 22 | typedef pair iii; 23 | typedef vector vi; 24 | typedef vector vii; 25 | typedef vector viii; 26 | typedef vector vll; 27 | typedef vector vpll; 28 | typedef vector vtll; 29 | typedef vector vs; 30 | typedef set si; 31 | typedef set sii; 32 | typedef set siii; 33 | 34 | ll gcd(ll a, ll b){ return b==0?a:gcd(b,a%b);} 35 | 36 | int add(ll a, ll b){ return (a%MOD + b%MOD+2*MOD)%MOD;} 37 | 38 | int mul(ll a, ll b){ return ((a%MOD+MOD)*(b%MOD+MOD))%MOD;} 39 | 40 | ll pow_mod(ll a, ll b){ 41 | ll res = 1LL; 42 | a = a%MOD; 43 | while(b){ 44 | if(b&1) res = mul(res,a); 45 | b >>= 1; 46 | a = mul(a,a); 47 | } 48 | return res; 49 | } 50 | 51 | ll fastexp(ll a, ll b){ 52 | ll res = 1LL; 53 | while(b){ 54 | if(b&1) res = res*a; 55 | b >>= 1; 56 | a *= a; 57 | } 58 | return res; 59 | } 60 | 61 | int gcdExtendido(int a, int b, int *x, int *y){ 62 | if(a == 0){ 63 | *x = 0; 64 | *y = 1; 65 | return b; 66 | } 67 | int x1, y1; 68 | int gcd = gcdExtendido(b%a,a,&x1,&y1); 69 | 70 | *x = y1-(b/a)*x1; 71 | *y = x1; 72 | return gcd; 73 | }; 74 | 75 | int modInverso(int a, int m){ 76 | int x, y; 77 | int g = gcdExtendido(a,m,&x,&y); 78 | if(g!=1) return -1; 79 | else return (x%m + m)%m; 80 | } 81 | 82 | /**************************************** 83 | *************P*L*A*N*T*I*L*L*A************ 84 | *****************************************/ 85 | 86 | /* 87 | * Tenemos la recursion: 88 | * f(N) = f(f(N+11)) N <= 100 89 | * f(N) = N-10 N >= 101 90 | * 91 | * Por la naturaleza de la funcion, de tomarse dos veces, nos damos cuenta de que eventualmente llegaremos a un N tal que N+11 >= 101 con las justas, lo que nos dara que 92 | * f(N+11) = (N+11)-10 -> f(N+1), lo que nos lleva a que f(N) para ese valor 93 | * sera igual a f(N+1), y analizando un poco mas a fondo, nos damos cuenta de que 94 | * se llegara a N = 100, lo que nos dara f(111) = 101 y f(101) = 91 95 | * 96 | * Por ello, se termina reduciendo a que 97 | * 98 | * f(N) = 91 N <= 100 99 | * f(N) = N-10 N >= 101 100 | * 101 | */ 102 | 103 | int f(int n){ 104 | return n<=100?91:n-10; 105 | } 106 | 107 | int main(){ 108 | int n; 109 | while(ri(n)==1 and n){ 110 | printf("f91(%d) = %d\n",n,f(n)); 111 | } 112 | return 0; 113 | } 114 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-09/ejemplos/All_Squares.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define all(v) (v).begin(),(v).end() 3 | #define pb push_back 4 | #define ppb pop_back 5 | #define mp make_pair 6 | #define ri(x) scanf("%d",&(x)) 7 | #define ri2(x,y) scanf("%d %d",&(x),&(y)) 8 | #define ri3(x,y,z) scanf("%d %d %d",&(x),&(y),&(z)) 9 | #define rll(x) scanf("%lld",&(x)) 10 | #define rll2(x,y) scanf("%lld %lld",&(x),&(y)) 11 | #define rll3(x,y,z) scanf("%lld %lld %lld",&(x),&(y),&(z)) 12 | #define rc(x) scanf("%c",&(x)) 13 | using namespace::std; 14 | 15 | const long double PI = acos(-1); 16 | const int MOD = 1000000000 +7; 17 | 18 | typedef long long ll; 19 | typedef pair pll; 20 | typedef pair tll; 21 | typedef pair ii; 22 | typedef pair iii; 23 | typedef vector vi; 24 | typedef vector vii; 25 | typedef vector viii; 26 | typedef vector vll; 27 | typedef vector vpll; 28 | typedef vector vtll; 29 | typedef vector vs; 30 | typedef set si; 31 | typedef set sii; 32 | typedef set siii; 33 | 34 | ll gcd(ll a, ll b){ return b==0?a:gcd(b,a%b);} 35 | 36 | int add(ll a, ll b){ return (a%MOD + b%MOD+2*MOD)%MOD;} 37 | 38 | int mul(ll a, ll b){ return ((a%MOD+MOD)*(b%MOD+MOD))%MOD;} 39 | 40 | ll pow_mod(ll a, ll b){ 41 | ll res = 1LL; 42 | a = a%MOD; 43 | while(b){ 44 | if(b&1) res = mul(res,a); 45 | b >>= 1; 46 | a = mul(a,a); 47 | } 48 | return res; 49 | } 50 | 51 | ll fastexp(ll a, ll b){ 52 | ll res = 1LL; 53 | while(b){ 54 | if(b&1) res = res*a; 55 | b >>= 1; 56 | a *= a; 57 | } 58 | return res; 59 | } 60 | 61 | int gcdExtendido(int a, int b, int *x, int *y){ 62 | if(a == 0){ 63 | *x = 0; 64 | *y = 1; 65 | return b; 66 | } 67 | int x1, y1; 68 | int gcd = gcdExtendido(b%a,a,&x1,&y1); 69 | 70 | *x = y1-(b/a)*x1; 71 | *y = x1; 72 | return gcd; 73 | }; 74 | 75 | int modInverso(int a, int m){ 76 | int x, y; 77 | int g = gcdExtendido(a,m,&x,&y); 78 | if(g!=1) return -1; 79 | else return (x%m + m)%m; 80 | } 81 | 82 | /**************************************** 83 | *************P*L*A*N*T*I*L*L*A************ 84 | *****************************************/ 85 | 86 | /* Para este problema, nos es mas sencillo usar como referencia el centro del 87 | * cuadrado que colocaremos, el cual tendra de lado 2k+1, por lo que las 88 | * esquinas tendran coordenadas 89 | * 90 | * (Ox-k,Oy-k) ------ (Ox-k,Oy+k) ------ (Ox+k,Oy-k) ------ (Ox+k,Oy+k) 91 | * 92 | * Preferimos usar una variable global para aumentarla en 1 cada vez que 93 | * encontramos un cuadrado que contenga el punto que nos dan 94 | * 95 | */ 96 | 97 | int ans; 98 | int x,y; 99 | 100 | void check(int k, int Ox, int Oy){ 101 | if(k == 0) return; 102 | if(Ox-k <= x and x <= Ox+k and Oy-k <= y and y <= Oy+k) ans++; 103 | check(k/2,Ox-k,Oy+k); 104 | check(k/2,Ox-k,Oy-k); 105 | check(k/2,Ox+k,Oy+k); 106 | check(k/2,Ox+k,Oy-k); 107 | } 108 | 109 | int main(){ 110 | int n; 111 | while(ri3(n,x,y)==3 and n){ 112 | ans = 0; 113 | check(n,1024,1024); 114 | printf("%3d\n",ans); 115 | } 116 | return 0; 117 | } 118 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-04/soluciones/p10.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * LINK DEL PROBLEMA: 3 | * https://icpcarchive.ecs.baylor.edu/index.php?option=onlinejudge&page=show_problem&problem=217 4 | * 5 | * SOLUCIÓN: 6 | * Primero, notemos que si queremos hallar la mínima cantidad de movimientos 7 | * para tener la cuadrícula dada con todos los elementos iguales, entonces 8 | * no debemos mover una ficha más de una vez, pues es ese caso, ese movimiento solo 9 | * revertiría el estado de esa posición. 10 | * Entonces, sabemos que si hay respuesta, esta consistirá en una serie de movimientos 11 | * en algunas fichas, esto es, si vemos la cuadrícula dada como un string 12 | * 'mask' de '1's y '0's donde si mask[i] = 1 significa mover la pieza grid[i / N_COLS][i % COLS] 13 | * Entonces, podemos iterar por todas las configuraciones de mask, simular los movimientos 14 | * y actualizar la respuesta si se cumplen las condiciones y tener una respuesta mejor 15 | * 16 | * COMPLEJIDAD: 17 | * O(k * 2 ^ 16) // donde con k = 5 * 16 podemos tener una cota superior 18 | * 19 | * DETALLES DE LA IMPLEMENTACIÓN: 20 | * ~num = Indica si 'num' != -1 (Representa -1 en binario y te darás cuenta) 21 | * not = ! 22 | * dr[] y dc[] funcionan como 'vectores de dirección'(Lo explicaré en clase) 23 | * const type& var (Lo explicaré en clase) 24 | * inline (Lo explicaré en clase) 25 | * copy = ¿Qué crees que haga ._.? (http://www.cplusplus.com/reference/algorithm/copy/) 26 | */ 27 | 28 | #include 29 | 30 | using namespace std; 31 | 32 | const int N_ROWS = 4, N_COLS = 4, N_DIR = 5, OFFSET = 1; 33 | 34 | int ans; 35 | string grid[N_ROWS + OFFSET], pib[N_ROWS + OFFSET]; 36 | int dr[] = {0, 0, -1, 0, 1}; 37 | int dc[] = {0, 1, 0, -1, 0}; 38 | 39 | inline void print() { 40 | ~ans ? cout << ans << endl : cout << "Impossible" << endl; 41 | } 42 | 43 | bool isAll(const char& ch) { 44 | for (int row = 0; row < N_ROWS; row++) 45 | for (int col = 0; col < N_COLS; col++) 46 | if (pib[row][col] != ch) return false; 47 | return true; 48 | } 49 | 50 | inline bool isValid(const int& r, const int& c) { 51 | return 0 <= r and 0 <= c and r < N_ROWS and c < N_COLS; 52 | } 53 | 54 | void markMoves(const int& pos) { 55 | int r = pos / N_COLS, c = pos % N_COLS; 56 | for (int d = 0; d < N_DIR; d++) { 57 | int nr = r + dr[d], nc = c + dc[d]; 58 | if (isValid(nr, nc)) pib[nr][nc] = (pib[nr][nc] == 'b') ? 'w' : 'b'; 59 | } 60 | } 61 | 62 | void solve() { 63 | for (int mask = 0; mask < (1 << (N_ROWS * N_COLS)); mask++) { 64 | if (__builtin_popcount(mask) > ans and ~ans) continue; 65 | copy(grid, grid + N_ROWS, pib); 66 | for (int bit = 0; bit < (N_ROWS * N_COLS); bit++) 67 | if ((mask >> bit) bitand 1) markMoves(bit); 68 | if (isAll('b') or isAll('w')) ans = __builtin_popcount(mask); 69 | } 70 | } 71 | 72 | inline void init() { 73 | ans = -1; 74 | } 75 | 76 | bool readBoard() { 77 | for (int row = 0; row < N_ROWS; row++) 78 | if (not (cin >> grid[row])) return false; 79 | return true; 80 | } 81 | 82 | int main() { 83 | while (readBoard()) { 84 | init(); 85 | solve(); 86 | print(); 87 | } 88 | return (0); 89 | } 90 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-09/soluciones/p02.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define all(v) (v).begin(),(v).end() 3 | #define pb push_back 4 | #define ppb pop_back 5 | #define mp make_pair 6 | #define ri(x) scanf("%d",&(x)) 7 | #define ri2(x,y) scanf("%d %d",&(x),&(y)) 8 | #define ri3(x,y,z) scanf("%d %d %d",&(x),&(y),&(z)) 9 | #define rll(x) scanf("%lld",&(x)) 10 | #define rll2(x,y) scanf("%lld %lld",&(x),&(y)) 11 | #define rll3(x,y,z) scanf("%lld %lld %lld",&(x),&(y),&(z)) 12 | #define rc(x) scanf("%c",&(x)) 13 | using namespace::std; 14 | 15 | const long double PI = acos(-1); 16 | const int MOD = 1000000000 +7; 17 | 18 | typedef long long ll; 19 | typedef pair pll; 20 | typedef pair tll; 21 | typedef pair ii; 22 | typedef pair iii; 23 | typedef vector vi; 24 | typedef vector vii; 25 | typedef vector viii; 26 | typedef vector vll; 27 | typedef vector vpll; 28 | typedef vector vtll; 29 | typedef vector vs; 30 | typedef set si; 31 | typedef set sii; 32 | typedef set siii; 33 | 34 | ll gcd(ll a, ll b){ return b==0?a:gcd(b,a%b);} 35 | 36 | int add(ll a, ll b){ return (a%MOD + b%MOD+2*MOD)%MOD;} 37 | 38 | int mul(ll a, ll b){ return ((a%MOD+MOD)*(b%MOD+MOD))%MOD;} 39 | 40 | ll pow_mod(ll a, ll b){ 41 | ll res = 1LL; 42 | a = a%MOD; 43 | while(b){ 44 | if(b&1) res = mul(res,a); 45 | b >>= 1; 46 | a = mul(a,a); 47 | } 48 | return res; 49 | } 50 | 51 | ll fastexp(ll a, ll b){ 52 | ll res = 1LL; 53 | while(b){ 54 | if(b&1) res = res*a; 55 | b >>= 1; 56 | a *= a; 57 | } 58 | return res; 59 | } 60 | 61 | int gcdExtendido(int a, int b, int *x, int *y){ 62 | if(a == 0){ 63 | *x = 0; 64 | *y = 1; 65 | return b; 66 | } 67 | int x1, y1; 68 | int gcd = gcdExtendido(b%a,a,&x1,&y1); 69 | 70 | *x = y1-(b/a)*x1; 71 | *y = x1; 72 | return gcd; 73 | }; 74 | 75 | int modInverso(int a, int m){ 76 | int x, y; 77 | int g = gcdExtendido(a,m,&x,&y); 78 | if(g!=1) return -1; 79 | else return (x%m + m)%m; 80 | } 81 | 82 | /**************************************** 83 | *************P*L*A*N*T*I*L*L*A************ 84 | *****************************************/ 85 | 86 | /* Problema de implementacion, usar recursion para resolver el problema y leer al mismo tiempo 87 | * Si tiene un 0 en la parte de peso, entonces plantear recursion para otro problema de mismas caracteristicas. 88 | * 89 | * 90 | * 91 | * 92 | * 93 | * 94 | * 95 | */ 96 | 97 | ii Read(){ 98 | int w1, d1, w2, d2; 99 | ri2(w1,d1); 100 | ri2(w2,d2); 101 | bool can = true; // Asumiendo que no hay ningun submovil 102 | ii submovil1 = mp(0,1), submovil2 = mp(0,1); // Equilibrio y peso 0 103 | if(w1 == 0){ 104 | submovil1 = Read(); // Resolvemos submovil y asignamos 105 | } 106 | if(w2 == 0){ 107 | submovil2 = Read(); // Resolvemos submovil y asignamos 108 | 109 | } 110 | if(!submovil1.second) can = false; 111 | if(!submovil2.second) can = false; 112 | w1 += submovil1.first; 113 | w2 += submovil2.first; 114 | if(w1*d1 == w2*d2){ 115 | return mp(w1+w2,1&can); 116 | } 117 | else return mp(w1+w2,0&can); 118 | } 119 | 120 | void solve(){ 121 | ii can = Read(); 122 | puts(can.second?"YES":"NO"); 123 | } 124 | 125 | int main(){ 126 | int t; 127 | ri(t); 128 | while(t--){ 129 | solve(); 130 | if(t) puts(""); 131 | } 132 | return 0; 133 | } 134 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-09/ejemplos/Connecting_Soldiers.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define all(v) (v).begin(),(v).end() 3 | #define pb push_back 4 | #define ppb pop_back 5 | #define mp make_pair 6 | #define ri(x) scanf("%d",&(x)) 7 | #define ri2(x,y) scanf("%d %d",&(x),&(y)) 8 | #define ri3(x,y,z) scanf("%d %d %d",&(x),&(y),&(z)) 9 | #define rll(x) scanf("%lld",&(x)) 10 | #define rll2(x,y) scanf("%lld %lld",&(x),&(y)) 11 | #define rll3(x,y,z) scanf("%lld %lld %lld",&(x),&(y),&(z)) 12 | #define rc(x) scanf("%c",&(x)) 13 | using namespace::std; 14 | 15 | const long double PI = acos(-1); 16 | const int MOD = 1000000000 +7; 17 | 18 | typedef long long ll; 19 | typedef pair pll; 20 | typedef pair tll; 21 | typedef pair ii; 22 | typedef pair iii; 23 | typedef vector vi; 24 | typedef vector vii; 25 | typedef vector viii; 26 | typedef vector vll; 27 | typedef vector vpll; 28 | typedef vector vtll; 29 | typedef vector vs; 30 | typedef set si; 31 | typedef set sii; 32 | typedef set siii; 33 | 34 | ll gcd(ll a, ll b){ return b==0?a:gcd(b,a%b);} 35 | 36 | int add(ll a, ll b){ return (a%MOD + b%MOD+2*MOD)%MOD;} 37 | 38 | int mul(ll a, ll b){ return ((a%MOD+MOD)*(b%MOD+MOD))%MOD;} 39 | 40 | ll pow_mod(ll a, ll b){ 41 | ll res = 1LL; 42 | a = a%MOD; 43 | while(b){ 44 | if(b&1) res = mul(res,a); 45 | b >>= 1; 46 | a = mul(a,a); 47 | } 48 | return res; 49 | } 50 | 51 | ll fastexp(ll a, ll b){ 52 | ll res = 1LL; 53 | while(b){ 54 | if(b&1) res = res*a; 55 | b >>= 1; 56 | a *= a; 57 | } 58 | return res; 59 | } 60 | 61 | int gcdExtendido(int a, int b, int *x, int *y){ 62 | if(a == 0){ 63 | *x = 0; 64 | *y = 1; 65 | return b; 66 | } 67 | int x1, y1; 68 | int gcd = gcdExtendido(b%a,a,&x1,&y1); 69 | 70 | *x = y1-(b/a)*x1; 71 | *y = x1; 72 | return gcd; 73 | }; 74 | 75 | int modInverso(int a, int m){ 76 | int x, y; 77 | int g = gcdExtendido(a,m,&x,&y); 78 | if(g!=1) return -1; 79 | else return (x%m + m)%m; 80 | } 81 | 82 | /**************************************** 83 | *************P*L*A*N*T*I*L*L*A************ 84 | *****************************************/ 85 | 86 | /* 87 | * Para empezar, este problema se basa en la siguiente recursion: 88 | * g(0) = 0 89 | * g(x) = x+1 + g(x-u-1) + g(u), donde u lo deberemos elegir como convenga y 1<=u<=x 90 | * Por la naturaleza de la funcion, son demostrables 2 puntos: 91 | * 92 | * 1) El maximo valor de g(x) se da cuando u=1 y el minimo cuando u = x/2 93 | * 94 | * 2) El rango efectivo de valores que puede tomar g(x) es [min(g(x)),max(g(x))] 95 | * 96 | * Usando los dos puntos anteriores, debemos verificar que el minimo de longitud para los puntos dados no sea mayor que lo disponible. 97 | * 98 | * Para obtener la respuesta, elegimos el maximo posible que no exceda a L, que se puede expresar como max(0,L-maximo[n]) pues asi nos ahorramos un condicional mas 99 | */ 100 | 101 | const int N = 50; 102 | 103 | int n,L; 104 | int Minimos[N], Maximos[N]; 105 | 106 | int main(){ 107 | for(int i=1; i L) puts("-1"); 116 | else cout << max(0,L-Maximos[n]) << endl; 117 | } 118 | return 0; 119 | } 120 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-01/ejemplos/04-estructuras-de-control.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | /** 7 | * Las estructuras de control permiten evaluar ciertas condiciones de acuerdo a las cuales decidir que 8 | * deberá hacer el programa en ejecución 9 | * 10 | * En c++ existren 3 formas de hacer ello 11 | * - if / else if / else 12 | * - switch 13 | * - Operador ternario exp_1 ? exp_2 : exp_3 14 | */ 15 | 16 | 17 | /** 18 | * Estructura general del if / else if / else: 19 | * 20 | * if (condicion_1) { 21 | * Has algo 22 | * } 23 | * else if (condicion_2) { 24 | * Has otra cosa; 25 | * } 26 | * else if (condicion_3) { 27 | * Has otra cosa; 28 | * } 29 | * . 30 | * - 31 | * . 32 | * else if (condicion_n) { 33 | * Has otra cosa; 34 | * } 35 | * else { 36 | * Has algo por defecto 37 | * } 38 | * 39 | */ 40 | 41 | int x = 2; 42 | if (x == 3) { 43 | cout << "x = 3" << endl; 44 | } 45 | else if (x == 2) { 46 | cout << "x = 2" << endl; 47 | } 48 | else cout << "x = " << x << endl; 49 | /** 50 | * Nota 1: El uso de los (else if) y (else) es opcional 51 | * Nota 2: Cuando lo que está dentro de un (if), (else if), (else), (for), (while), ... es una sola sentencia, se pueden omitir los corchetes ({ }) 52 | */ 53 | 54 | /** 55 | * Estructura general del switch: 56 | * 57 | * switch(expresion_base) { 58 | * case (expresion_1): 59 | * has algo; 60 | * break; 61 | * case (expresion_2): 62 | * has algo; 63 | * break; 64 | * . 65 | * . 66 | * . 67 | * case (expresion_n): 68 | * has algo; 69 | * break; 70 | * default: 71 | * has algo; 72 | * break; 73 | * } 74 | * 75 | * 76 | * Nota, en cada caso se evalua si (expresion_base == expresion_i) [i = 1, 2, 3, ..., n] 77 | */ 78 | 79 | int expresion_base = 14; 80 | switch (expresion_base) { 81 | case (1): 82 | cout << "expresion_base = 1" << endl; 83 | break; 84 | case (2): 85 | cout << "expresion_base = 2" << endl; 86 | break; 87 | default: 88 | cout << "expresion_base = " << expresion_base << endl; 89 | break; 90 | } 91 | 92 | /** 93 | * Muchas veces tenemos esta situación 94 | * if (condicion) { 95 | * expresion_1; 96 | * } 97 | * else { 98 | * expresion_2; 99 | * } 100 | * 101 | * Para simplificar eso existe el operador ternario 102 | * condicion ? expresion_1 : expresion_2 103 | */ 104 | 105 | int z; 106 | if (3 == 2) { 107 | z = 100; 108 | } 109 | else { 110 | z = 200; 111 | } 112 | 113 | // Lo anterior es equivalente a 114 | (3 == 2) ? z = 100 : z = 200; 115 | 116 | cout << "z = " << z << endl; 117 | 118 | /** 119 | * Nota 1: En realidad existe una cuarda estructura de control (goto), pero está extremadamente recomendado el no usarlo 120 | * Más información de estructuras de control aquí: 121 | * http://www.cplusplus.com/doc/oldtutorial/control/ 122 | */ 123 | 124 | return (0); 125 | } -------------------------------------------------------------------------------- /uni-no-fiis/clase-09/soluciones/p07.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define all(v) (v).begin(),(v).end() 3 | #define pb push_back 4 | #define ppb pop_back 5 | #define mp make_pair 6 | #define ri(x) scanf("%d",&(x)) 7 | #define ri2(x,y) scanf("%d %d",&(x),&(y)) 8 | #define ri3(x,y,z) scanf("%d %d %d",&(x),&(y),&(z)) 9 | #define rll(x) scanf("%lld",&(x)) 10 | #define rll2(x,y) scanf("%lld %lld",&(x),&(y)) 11 | #define rll3(x,y,z) scanf("%lld %lld %lld",&(x),&(y),&(z)) 12 | #define rc(x) scanf("%c",&(x)) 13 | using namespace::std; 14 | 15 | const long double PI = acos(-1); 16 | const int MOD = 1000000000 +7; 17 | 18 | typedef long long ll; 19 | typedef pair pll; 20 | typedef pair tll; 21 | typedef pair ii; 22 | typedef pair iii; 23 | typedef vector vi; 24 | typedef vector vii; 25 | typedef vector viii; 26 | typedef vector vll; 27 | typedef vector vpll; 28 | typedef vector vtll; 29 | typedef vector vs; 30 | typedef set si; 31 | typedef set sii; 32 | typedef set siii; 33 | 34 | ll gcd(ll a, ll b){ return b==0?a:gcd(b,a%b);} 35 | 36 | int add(ll a, ll b){ return (a%MOD + b%MOD+2*MOD)%MOD;} 37 | 38 | int mul(ll a, ll b){ return ((a%MOD+MOD)*(b%MOD+MOD))%MOD;} 39 | 40 | ll pow_mod(ll a, ll b){ 41 | ll res = 1LL; 42 | a = a%MOD; 43 | while(b){ 44 | if(b&1) res = mul(res,a); 45 | b >>= 1; 46 | a = mul(a,a); 47 | } 48 | return res; 49 | } 50 | 51 | ll fastexp(ll a, ll b){ 52 | ll res = 1LL; 53 | while(b){ 54 | if(b&1) res = res*a; 55 | b >>= 1; 56 | a *= a; 57 | } 58 | return res; 59 | } 60 | 61 | int gcdExtendido(int a, int b, int *x, int *y){ 62 | if(a == 0){ 63 | *x = 0; 64 | *y = 1; 65 | return b; 66 | } 67 | int x1, y1; 68 | int gcd = gcdExtendido(b%a,a,&x1,&y1); 69 | 70 | *x = y1-(b/a)*x1; 71 | *y = x1; 72 | return gcd; 73 | }; 74 | 75 | int modInverso(int a, int m){ 76 | int x, y; 77 | int g = gcdExtendido(a,m,&x,&y); 78 | if(g!=1) return -1; 79 | else return (x%m + m)%m; 80 | } 81 | 82 | /**************************************** 83 | *************P*L*A*N*T*I*L*L*A************ 84 | *****************************************/ 85 | 86 | /* Parecido a Not so Mobile, pero esta vez trabajaremos con las profundidades. 87 | * Debido a que si planteamos todo como un arbol binario, entonces en la 88 | * altura h se tendra un corte de longitud L/2^{h}, entonces el corte minimo es 89 | * aquel que tenga maxima altura de todos. 90 | * 91 | * Ademas de ello, considerar que "todos los cortes que se necesiten para llegar a la longitud minima" se refiere a todas las veces que se cortaron 92 | * desde el inicio hasta el momento en que se da ello, por lo que llevaremos un 93 | * contador que nos de la cantidad de cortes hasta el punto actual 94 | * Luego, al momento de comparar con la maxima altura actual, si nuestro 95 | * nodo esta en una altura mayor, actualizamos la maxima altura y la cantidad 96 | * de cortes. 97 | */ 98 | 99 | 100 | int n; 101 | int max_depth; 102 | int ans; 103 | int pos; 104 | int counter; 105 | string s; 106 | 107 | void solve(int depth){ 108 | if(s[pos] == '1') counter++; 109 | if(max_depth < depth){ 110 | ans = counter; 111 | max_depth = depth; 112 | } 113 | if(s[pos++] == '1'){ 114 | solve(depth+1); 115 | solve(depth+1); 116 | } 117 | } 118 | 119 | int main(){ 120 | int t = 10; 121 | while(t--){ 122 | ri(n); 123 | cin >> s; 124 | max_depth = 0; 125 | pos = 0; 126 | counter = 0; 127 | ans = 0; 128 | solve(0); 129 | printf("%d\n",ans); 130 | } 131 | return 0; 132 | } 133 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-01/ejemplos/02-tipos-de-datos.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | 7 | 8 | /** 9 | * int 10 | * Guarda números enteros en el rango (-2 ^ 32, 2 ^ 32) lo cual es aproximadamente [-2 * 10 ^ 9, 2 * 10 ^ 9] 11 | * Por defecto cuando inicializamos una variable como un número entero se guarda como un int 12 | */ 13 | int num_1 = 10; 14 | 15 | /** 16 | * long long 17 | * Guarda números enteros en el rango (-2 ^ 64, 2 ^ 64) lo cual es aproximadamente [-9 * 10 ^ 18, 9 * 10 ^ 18] 18 | * úsalo si requieres guardar números que no entran en el rango de un int 19 | * Nota 1: Para iniciar un número como un long long de manera directa debes agregar 'LL' al final del número, por ejemplo 20 | * 12LL : 12 (long long) mientras que 12 : 12 (int) 21 | * Nota 2: long long == long long int 22 | */ 23 | long long num_2 = 10000000000000000LL; 24 | 25 | /** 26 | * long 27 | * Guarda números enteros en un rango mayor al de un int, pero menor al de un long long 28 | * aunque esto por lo general varia entre cada computadora 29 | * si te ves en la tentativa de usarlo, prefiere usar un long long 30 | */ 31 | 32 | 33 | /** 34 | * Si deseas revisar los límites de cada tipo por ti mism@, puedes llamar a las siguientes constantes 35 | * INT_MIN // mínimo int que se puede guardar 36 | * INT_MAX // máximo int que se puede guardar 37 | * LONG_MIN // mínimo long que se puede guardar 38 | * LONG_MAX // máximo long que se puede guardar 39 | * LLONG_MIN // mínimo long long que se puede guardar 40 | * LLONG_MAX // máximo long long que se puede guardar 41 | * Más información de esto aquí: 42 | * http://www.cplusplus.com/reference/climits/ 43 | */ 44 | 45 | 46 | /** 47 | * float 48 | * Guarda números decimales de hasta 6 dígitos decimales con precisión 49 | * Nota 1: Para iniciar un número como un flotante se agrega una F al final del número 50 | */ 51 | float num_4 = 12.4F; 52 | 53 | /** 54 | * double 55 | * Guarda números decimales de hasta 15 dígitos decimales con precisión 56 | * Nota 1: Por defecto los decimales se guardan como double 57 | */ 58 | double num_5 = 234554.54554; 59 | 60 | 61 | /** 62 | * long double 63 | * Guarda números decimales de hasta 18 dígitos decimales con precisión 64 | * Nota 1: Para iniciar un número como long double se agrega una L al final del número 65 | */ 66 | long double num_6 = 1324345.5465656565655L; 67 | 68 | /** 69 | * Si deseas ver más sobre los limites de cada tipo flotante revisa la documentación de ellos aqui: 70 | * http://www.cplusplus.com/reference/cfloat/ 71 | */ 72 | 73 | 74 | /** 75 | * char 76 | * Un char guarda números entre (-2 ^ 8, 2 ^ 8), pero a cada número esta asociado una letra 77 | * y por defecto al imprimirlo te mostrará la letra asociada y no el número 78 | * Por lo general se usan para guardar letras minúsculas, mayúsculas, espacios, saltos de linea ('\n'), dígitos y 79 | * signos de interrogacion o exclamación, para otros simbolos se prefiere utilizar string 80 | */ 81 | char ch = 'M'; 82 | 83 | 84 | /** 85 | * bool 86 | * Un bool guarda una expresión booleanda (true o false) [verdadero o falso] 87 | */ 88 | bool ejemplo_1 = true; 89 | bool ejemplo_2 = false; 90 | 91 | /** 92 | * Más info de tipos de datos aquí: 93 | * http://www.cplusplus.com/doc/tutorial/variables/ 94 | */ 95 | 96 | return (0); 97 | } -------------------------------------------------------------------------------- /uni-no-fiis/clase-05/soluciones/2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define all(v) (v).begin(),(v).end() 3 | #define pb push_back 4 | #define ppb pop_back 5 | #define mp make_pair 6 | #define ri(x) scanf("%d",&(x)) 7 | #define ri2(x,y) scanf("%d %d",&(x),&(y)) 8 | #define ri3(x,y,z) scanf("%d %d %d",&(x),&(y),&(z)) 9 | #define rll(x) scanf("%lld",&(x)) 10 | #define rll2(x,y) scanf("%lld %lld",&(x),&(y)) 11 | #define rll3(x,y,z) scanf("%lld %lld %lld",&(x),&(y),&(z)) 12 | #define rc(x) scanf("%c",&(x)) 13 | using namespace::std; 14 | 15 | const long double PI = acos(-1); 16 | const int MOD = 1000000000 +7; 17 | 18 | typedef long long ll; 19 | typedef pair pll; 20 | typedef pair tll; 21 | typedef pair ii; 22 | typedef pair iii; 23 | typedef vector vi; 24 | typedef vector vii; 25 | typedef vector viii; 26 | typedef vector vll; 27 | typedef vector vpll; 28 | typedef vector vtll; 29 | typedef vector vs; 30 | typedef set si; 31 | typedef set sii; 32 | typedef set siii; 33 | 34 | ll gcd(ll a, ll b){ return b==0?a:gcd(b,a%b);} 35 | 36 | int add(ll a, ll b){ return (a%MOD + b%MOD+2*MOD)%MOD;} 37 | 38 | int mul(ll a, ll b){ return ((a%MOD+MOD)*(b%MOD+MOD))%MOD;} 39 | 40 | ll pow_mod(ll a, ll b){ 41 | ll res = 1LL; 42 | a = add(a,0); 43 | while(b){ 44 | if(b&1) res = mul(res,a); 45 | b >>= 1; 46 | a = mul(a,a); 47 | } 48 | return res; 49 | } 50 | 51 | ll fastexp(ll a, ll b){ 52 | ll res = 1LL; 53 | while(b){ 54 | if(b&1) res = res*a; 55 | b >>= 1; 56 | a *= a; 57 | } 58 | return res; 59 | } 60 | 61 | int gcdExtendido(int a, int b, int *x, int *y){ 62 | if(a == 0){ 63 | *x = 0; 64 | *y = 1; 65 | return b; 66 | } 67 | int x1, y1; 68 | int gcd = gcdExtendido(b%a,a,&x1,&y1); 69 | 70 | *x = y1-(b/a)*x1; 71 | *y = x1; 72 | return gcd; 73 | }; 74 | 75 | int modInverso(int a, int m){ 76 | int x, y; 77 | int g = gcdExtendido(a,m,&x,&y); 78 | if(g!=1) return -1; 79 | else return (x%m + m)%m; 80 | } 81 | 82 | /**************************************** 83 | *************P*L*A*N*T*I*L*L*A************ 84 | *****************************************/ 85 | 86 | /* 87 | * Para un par de puntos, la cantidad de triangulos que forma 88 | * es igual a la cantidad de puntos que no esten en su misma recta, 89 | * obviamente sin contar al mismo par de puntos 90 | */ 91 | 92 | const int N = 2000+5; 93 | 94 | typedef pair Recta; 95 | 96 | int n; 97 | int X[N], Y[N]; 98 | Recta O[N][N]; 99 | map v[N]; 100 | 101 | int main(){ 102 | ri(n); 103 | for(int i=0; i 2 | #define all(v) (v).begin(),(v).end() 3 | #define pb push_back 4 | #define ppb pop_back 5 | #define mp make_pair 6 | #define ri(x) scanf("%d",&(x)) 7 | #define ri2(x,y) scanf("%d %d",&(x),&(y)) 8 | #define ri3(x,y,z) scanf("%d %d %d",&(x),&(y),&(z)) 9 | #define rll(x) scanf("%lld",&(x)) 10 | #define rll2(x,y) scanf("%lld %lld",&(x),&(y)) 11 | #define rll3(x,y,z) scanf("%lld %lld %lld",&(x),&(y),&(z)) 12 | #define rc(x) scanf("%c",&(x)) 13 | using namespace::std; 14 | 15 | const long double PI = acos(-1); 16 | const int MOD = 1000000000 +7; 17 | 18 | typedef long long ll; 19 | typedef pair pll; 20 | typedef pair tll; 21 | typedef pair ii; 22 | typedef pair iii; 23 | typedef vector vi; 24 | typedef vector vii; 25 | typedef vector viii; 26 | typedef vector vll; 27 | typedef vector vpll; 28 | typedef vector vtll; 29 | typedef vector vs; 30 | typedef set si; 31 | typedef set sii; 32 | typedef set siii; 33 | 34 | ll gcd(ll a, ll b){ return b==0?a:gcd(b,a%b);} 35 | 36 | int add(ll a, ll b){ return (a%MOD + b%MOD+2*MOD)%MOD;} 37 | 38 | int mul(ll a, ll b){ return ((a%MOD+MOD)*(b%MOD+MOD))%MOD;} 39 | 40 | ll pow_mod(ll a, ll b){ 41 | ll res = 1LL; 42 | a = add(a,0); 43 | while(b){ 44 | if(b&1) res = mul(res,a); 45 | b >>= 1; 46 | a = mul(a,a); 47 | } 48 | return res; 49 | } 50 | 51 | ll fastexp(ll a, ll b){ 52 | ll res = 1LL; 53 | while(b){ 54 | if(b&1) res = res*a; 55 | b >>= 1; 56 | a *= a; 57 | } 58 | return res; 59 | } 60 | 61 | int gcdExtendido(int a, int b, int *x, int *y){ 62 | if(a == 0){ 63 | *x = 0; 64 | *y = 1; 65 | return b; 66 | } 67 | int x1, y1; 68 | int gcd = gcdExtendido(b%a,a,&x1,&y1); 69 | 70 | *x = y1-(b/a)*x1; 71 | *y = x1; 72 | return gcd; 73 | }; 74 | 75 | int modInverso(int a, int m){ 76 | int x, y; 77 | int g = gcdExtendido(a,m,&x,&y); 78 | if(g!=1) return -1; 79 | else return (x%m + m)%m; 80 | } 81 | 82 | /**************************************** 83 | *************P*L*A*N*T*I*L*L*A************ 84 | *****************************************/ 85 | 86 | // Clase BigInteger con suma implementada y basta con almacenamiento de los numeros de Fibonacci 87 | 88 | const int N = 5000+5; 89 | 90 | class Integer{ 91 | public: 92 | int n; 93 | vector v; 94 | Integer(){ 95 | n = 0; 96 | v.clear(); 97 | } 98 | 99 | void use(int x){ 100 | if(x == 0){ 101 | n = 1; 102 | v.pb(0); 103 | } 104 | else{ 105 | n = 0; 106 | v.clear(); 107 | while(x){ 108 | v.pb(x%10); 109 | x /= 10; 110 | n++; 111 | } 112 | } 113 | } 114 | 115 | void sumar(Integer b){ 116 | int tam = max(n,b.n); 117 | vector carry; 118 | for(int i=0; i 9){ 126 | if(i == tam-1){ 127 | carry.pb(carry[i]/10); 128 | carry[i] %= 10; 129 | } 130 | else{ 131 | carry[i+1] += carry[i]/10; 132 | carry[i] %= 10; 133 | } 134 | } 135 | } 136 | n = carry.size(); 137 | v = carry; 138 | } 139 | 140 | void Print(){ 141 | for(int i=n-1; i>=0; i--){ 142 | putchar('0'+v[i]); 143 | } 144 | } 145 | }; 146 | 147 | int n; 148 | Integer F[N]; 149 | 150 | int main(){ 151 | F[0].use(0); 152 | F[1].use(1); 153 | for(int i=2; i 2 | #define all(v) (v).begin(),(v).end() 3 | #define pb push_back 4 | #define ppb pop_back 5 | #define mp make_pair 6 | #define ri(x) scanf("%d",&(x)) 7 | #define ri2(x,y) scanf("%d %d",&(x),&(y)) 8 | #define ri3(x,y,z) scanf("%d %d %d",&(x),&(y),&(z)) 9 | #define rll(x) scanf("%lld",&(x)) 10 | #define rll2(x,y) scanf("%lld %lld",&(x),&(y)) 11 | #define rll3(x,y,z) scanf("%lld %lld %lld",&(x),&(y),&(z)) 12 | #define rc(x) scanf("%c",&(x)) 13 | using namespace::std; 14 | 15 | const long double PI = acos(-1); 16 | const int MOD = 1000000000 +7; 17 | 18 | typedef long long ll; 19 | typedef pair pll; 20 | typedef pair tll; 21 | typedef pair ii; 22 | typedef pair iii; 23 | typedef vector vi; 24 | typedef vector vii; 25 | typedef vector viii; 26 | typedef vector vll; 27 | typedef vector vpll; 28 | typedef vector vtll; 29 | typedef vector vs; 30 | typedef set si; 31 | typedef set sii; 32 | typedef set siii; 33 | 34 | ll gcd(ll a, ll b){ return b==0?a:gcd(b,a%b);} 35 | 36 | int add(ll a, ll b){ return (a%MOD + b%MOD+2*MOD)%MOD;} 37 | 38 | int mul(ll a, ll b){ return ((a%MOD+MOD)*(b%MOD+MOD))%MOD;} 39 | 40 | ll pow_mod(ll a, ll b){ 41 | ll res = 1LL; 42 | a = a%MOD; 43 | while(b){ 44 | if(b&1) res = mul(res,a); 45 | b >>= 1; 46 | a = mul(a,a); 47 | } 48 | return res; 49 | } 50 | 51 | ll fastexp(ll a, ll b){ 52 | ll res = 1LL; 53 | while(b){ 54 | if(b&1) res = res*a; 55 | b >>= 1; 56 | a *= a; 57 | } 58 | return res; 59 | } 60 | 61 | int gcdExtendido(int a, int b, int *x, int *y){ 62 | if(a == 0){ 63 | *x = 0; 64 | *y = 1; 65 | return b; 66 | } 67 | int x1, y1; 68 | int gcd = gcdExtendido(b%a,a,&x1,&y1); 69 | 70 | *x = y1-(b/a)*x1; 71 | *y = x1; 72 | return gcd; 73 | }; 74 | 75 | int modInverso(int a, int m){ 76 | int x, y; 77 | int g = gcdExtendido(a,m,&x,&y); 78 | if(g!=1) return -1; 79 | else return (x%m + m)%m; 80 | } 81 | 82 | /**************************************** 83 | *************P*L*A*N*T*I*L*L*A************ 84 | *****************************************/ 85 | 86 | /* F(i) es igual al digito de i que no sea 0 y que sea del menor orden posible. 87 | * Dado esto, separamos el problema en: 88 | * 89 | * G(i) = suma para k=0 hasta i de F(k) 90 | * 91 | * Entonces S(p,q) = G(q) - G(p-1) 92 | * 93 | * Ahora, para calcular G(i) nos damos cuenta de que es cuestion de recorrer orden 94 | * por orden: 95 | * 96 | * Para G(n): 97 | * 98 | * Supongamos que estamos en el orden k, entonces notamos que si los digitos a la izquierda son menores estrictos que los digitos de n, 99 | * entonces en el orden k podemos poner el digito que queramos y el numero 100 | * formado sera menor que n siempre. 101 | * Ahora, tambien, para que este digito en el orden k sea el que aporte a G(n), 102 | * todos los digitos a su derecha deben ser 0, por la definicion de F(n): 103 | * 104 | * Entonces, sumamos 45*(n/(10^{k+1})) al valor, pero ahora debemos considerar 105 | * el unico caso que nos falta, que es cuando los digitos a la izquierda son los 106 | * mismos que los de n. 107 | * Este caso es mas sencillo, pues nos damos cuenta de que la condicion para que 108 | * sea menor o igual a n es que el digito de orden k sea como maximo n_{k} (digito de n en el orden k), por lo que aporta (n_{k})(n_{k+1})/2. 109 | * 110 | * Usando esto, es sencillo calcular la respuesta. 111 | * 112 | */ 113 | 114 | int p,q; 115 | 116 | ll G(int x){ 117 | if(x == 0) return 0LL; 118 | ll suma = 45LL*(x/10); 119 | suma += (x%10)*(x%10+1)/2; 120 | return suma + G(x/10); 121 | } 122 | 123 | int main(){ 124 | while(ri2(p,q) and p+q >= 0){ 125 | printf("%lld\n",G(q)-G(p-1)); 126 | } 127 | return 0; 128 | } 129 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-09/soluciones/p08.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define all(v) (v).begin(),(v).end() 3 | #define pb push_back 4 | #define ppb pop_back 5 | #define mp make_pair 6 | #define ri(x) scanf("%d",&(x)) 7 | #define ri2(x,y) scanf("%d %d",&(x),&(y)) 8 | #define ri3(x,y,z) scanf("%d %d %d",&(x),&(y),&(z)) 9 | #define rll(x) scanf("%lld",&(x)) 10 | #define rll2(x,y) scanf("%lld %lld",&(x),&(y)) 11 | #define rll3(x,y,z) scanf("%lld %lld %lld",&(x),&(y),&(z)) 12 | #define rc(x) scanf("%c",&(x)) 13 | using namespace::std; 14 | 15 | const long double PI = acos(-1); 16 | const int MOD = 1000000000 +7; 17 | 18 | typedef long long ll; 19 | typedef pair pll; 20 | typedef pair tll; 21 | typedef pair ii; 22 | typedef pair iii; 23 | typedef vector vi; 24 | typedef vector vii; 25 | typedef vector viii; 26 | typedef vector vll; 27 | typedef vector vpll; 28 | typedef vector vtll; 29 | typedef vector vs; 30 | typedef set si; 31 | typedef set sii; 32 | typedef set siii; 33 | 34 | ll gcd(ll a, ll b){ return b==0?a:gcd(b,a%b);} 35 | 36 | int add(ll a, ll b){ return (a%MOD + b%MOD+2*MOD)%MOD;} 37 | 38 | int mul(ll a, ll b){ return ((a%MOD+MOD)*(b%MOD+MOD))%MOD;} 39 | 40 | ll pow_mod(ll a, ll b){ 41 | ll res = 1LL; 42 | a = a%MOD; 43 | while(b){ 44 | if(b&1) res = mul(res,a); 45 | b >>= 1; 46 | a = mul(a,a); 47 | } 48 | return res; 49 | } 50 | 51 | ll fastexp(ll a, ll b){ 52 | ll res = 1LL; 53 | while(b){ 54 | if(b&1) res = res*a; 55 | b >>= 1; 56 | a *= a; 57 | } 58 | return res; 59 | } 60 | 61 | int gcdExtendido(int a, int b, int *x, int *y){ 62 | if(a == 0){ 63 | *x = 0; 64 | *y = 1; 65 | return b; 66 | } 67 | int x1, y1; 68 | int gcd = gcdExtendido(b%a,a,&x1,&y1); 69 | 70 | *x = y1-(b/a)*x1; 71 | *y = x1; 72 | return gcd; 73 | }; 74 | 75 | int modInverso(int a, int m){ 76 | int x, y; 77 | int g = gcdExtendido(a,m,&x,&y); 78 | if(g!=1) return -1; 79 | else return (x%m + m)%m; 80 | } 81 | 82 | /**************************************** 83 | *************P*L*A*N*T*I*L*L*A************ 84 | *****************************************/ 85 | 86 | /* Simulacion: 87 | * 88 | * Primero, fijarnos que si C > max(A,B) o C mod gcd(A,B) != 0 no se puede obtener la cantidad en alguno de los recipientes. 89 | * Plantear como una ecuacion diofantica para ello. 90 | * 91 | * Caso truculento: C = 0, entonces la respuesta es 0 92 | * 93 | * Para el resto de los casos, plantear una simulacion considerando como "base" 94 | * uno de los dos valores de A y B. Ordenando de la siguiente manera: 95 | * 96 | * Recipiente 1, Recipiente 2, Base, Extra, Objetivo: 97 | * 98 | * El recipiente 1 sera el que se ira llenando y quitando, mientras que B se llena y cuando este en su capacidad maxima, deberemos vaciarlo. 99 | * Cantidad asociada al recipiente 1 <- A 100 | * Cantidad asociada al recipiente 2 <- B 101 | * 102 | * Verificar que movamos una cantidad que no haga que uno de los recipientes se rebalse o que exceda la cantidad que tiene el mismo. 103 | * Repetir hasta que uno de los recipientes llegue a tener la cantidad C. 104 | * 105 | */ 106 | 107 | 108 | int f(int r1, int r2, int A, int B, int C){ 109 | if(r1 == C or r2 == C) return 0; 110 | int pasos = 0; 111 | int mover = min(r1,B-r2); 112 | r2 += mover; 113 | r1 -= mover; 114 | pasos++; 115 | if(r1 == C or r2 == C) return pasos; 116 | if(r2 == B) r2 = 0, pasos++; 117 | else if(r1 ==0) r1 = A, pasos++; 118 | return pasos+f(r1,r2,A,B,C); 119 | } 120 | 121 | int main(){ 122 | int t; 123 | ri(t); 124 | int A,B,C; 125 | while(t--){ 126 | ri3(A,B,C); 127 | if(A < C and B < C) puts("-1"); 128 | else if(C == 0) puts("0"); 129 | else if(C % gcd(A,B)) puts("-1"); 130 | else{ 131 | printf("%d\n",1+min(f(A,0,A,B,C),f(B,0,B,A,C))); 132 | } 133 | } 134 | return 0; 135 | } 136 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-06/ejemplos/struct.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Ejemplo de como crear un 'struct' y como usarlo 3 | * 4 | * Problema 5 | * - Queremos tener un tipo de dato de represente una fracción 6 | * - Queremos poder ordenar fracciones siguiendo esta relación de orden 7 | * a1 a2 8 | * -- < -- <-> a1 * b2 < a2 * b1 9 | * b1 b2 10 | * - Queremos poder usar la operación '+' y '*' entre fracciones 11 | */ 12 | 13 | /** 14 | * Recibire un número 'n' seguido de 'n' fracciones 15 | * Debo imprimir 16 | * Las fracciones ordenadas 17 | * La suma de las fracciones 18 | * El producto de las fracciones 19 | */ 20 | 21 | // Para simplificar la solucion, aceptaré que las fracciones tenga 0 en el denominador 22 | 23 | #include 24 | 25 | using namespace std; 26 | 27 | struct Fraccion { 28 | int num, den; 29 | // Los constructores tienen el mismo nombre que mi estructura 30 | // Puedo tener más de un constructor 31 | // Estos se diferenciaran por los parametros que reciban 32 | Fraccion() {} 33 | Fraccion(int x, int y) { 34 | num = x; 35 | den = y; 36 | } 37 | // Puedo sobreescribir el operador '<' para poder usar la función 'sort' 38 | // - (Fraccion& otra) 39 | // Indica que esta función recibirá una referencia de la variable que invoque 40 | // este método. Así, no se creará una copia de esa variable para esta función 41 | // Lo que se haga con esta variable dentro de la función se vera reflejado en 42 | // la variable que la invocó 43 | // - (const Fraccion otra) 44 | // Indica que el valor de la variable 'otra' será constante en ese método 45 | // - () const { 46 | // Indica que este método no cambiará el estado de ningún atributo de la instancia 47 | // de esta 'struct' que invoque el método 48 | bool operator < (const Fraccion& otra) const { 49 | return num * otra.den < den * otra.num; 50 | } 51 | // Si deseo, puedo no usar 'const' y '&' 52 | // Pero esto será un poco más lento ya que crea copias innecesarias 53 | // Y al no definir qué es un 'const', no da libertad al compilador de 54 | // hacer optimizaciones 55 | Fraccion operator + (Fraccion otra) { 56 | return Fraccion(num * otra.den + den * otra.num, den * otra.den); 57 | } 58 | // Este operador cambiará el estado de la instancia que la invoque 59 | // por ello no podemos uasr () const { 60 | void operator *= (const Fraccion& otra){ 61 | num = num * otra.num; 62 | den = den * otra.den; 63 | } 64 | // Tambien puedo escribir funciones ('métodos') para este 'struct' 65 | void imprimir(string sep) { 66 | cout << num << '/' << den << sep; 67 | } 68 | }; // NO OLVIDAR PONER ';' al final de un 'struct' 69 | 70 | int n; 71 | vector arr; 72 | 73 | // Si no deseo sobreescribir el operador ('<') en mi 'struct', puedo definirlo 74 | // como una función, así: 75 | bool cmp(const Fraccion& X, const Fraccion& Y) { 76 | return X.num * Y.den < X.den * Y.num; 77 | } 78 | 79 | int main() { 80 | cin >> n; 81 | for (int i = 0; i < n; i++) { 82 | int num, den; 83 | cin >> num >> den; 84 | arr.push_back(Fraccion(num, den)); 85 | } 86 | sort(arr.begin(), arr.end()); 87 | //sort(arr.begin(), arr.end(), cmp); 88 | 89 | cout << "Las fracciones ordenadas" << endl; 90 | for (auto fraccion : arr) fraccion.imprimir(" "); 91 | cout << endl; 92 | 93 | Fraccion suma = Fraccion(0, 1); 94 | for (auto fraccion : arr) { 95 | suma = suma + fraccion; 96 | // Si quisiera usar suma += fraccion 97 | // Tendria que definir el operador '+=' 98 | } 99 | cout << "La suma de las fracciones es" << endl; 100 | suma.imprimir("\n"); 101 | 102 | Fraccion producto = Fraccion(1, 1); 103 | for (auto fraccion : arr) producto *= fraccion; 104 | cout << "El producto de las fracciones es" << endl; 105 | producto.imprimir("\n"); 106 | 107 | return (0); 108 | } 109 | 110 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-07/soluciones/I.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | *** REGIONAL PROBLEM *** 4 | 5 | problem : https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=5217 6 | approach: ternary search, geometry 7 | 8 | solution: 9 | 10 | Alguna vez hemos visto la ecuacion para hallar el area 11 | de un poligono, no es mas que sumar o restar las contribuciones 12 | de los triangulos que los forman desde un punto cualquiera, este 13 | punto puede ser el origen para mayor comodidad. 14 | 15 | Entonces si queremos hallar el area de un poligno de n 16 | puntos (x[i], y[i]) nuestra ecuacion seria: 17 | sum(x[i] * y[i+1] - y[i] * x[i+1], con 1 <= i < n) 18 | + x[n] * y[1] - y[n] * x[1], todo esto dividido entre 19 | dos pero, para nuetro problema eso no importa ya que no hallamos 20 | area sino volumen y la altura es 2, lo mas interesante 21 | de la ecuacion que hemos puesto que si yo quiero hallar 22 | el area des l a r, podria denotar ac[i] = ac[i-1] + x[i] * y[i+1] 23 | - y[i] * x[i+1], entonces nuestra area de l a r queda 24 | expresada de la forma ac[r-1] - ac[l-1] + cross(r, l), 25 | donde la funcion cross denota el producto vectorial del 26 | punto r y l, en ese orden. 27 | 28 | ahora que ya sabemos hallar area en O(1), lo unico que queda es ver 29 | que propiedades tiene el problema, si denotamos f(a, b) como 30 | el area de f(a, b) a medida de que b se acerca a a el area disminuye, 31 | pero esto de que sirve, que sucede con el complemento de nuestra area, 32 | vemos que aumenta... entonces si denotamos g(b) a la funcion area(a, b) 33 | - complemento del area(a, b) vemos que en g(a) la funcion es negativa, 34 | y g(a + n - 1) que es justo -g(a), entonces esta funcion es positiva... 35 | pues esto es todo lo que necesitamos, quieres decir que hay una recta 36 | que hace a las dos areas iguales... pero espera! solo podemos usar las rectas 37 | que pasan por a y otro punto, pues bien, aun asi debe haber un elemento 38 | lo bastante cerca a cero, tanto antes o despues de cero. 39 | 40 | Para hallar el que mas se le acerca tendriamos que buscar dos valores, quizas 41 | dos binarys ... o fijandonos en el que sigue, pero que pasa si ahora 42 | tomo h = abs(g) una nueva funcion, esta funcion que he creado a partir 43 | de una funcion binaria es convexa y alcanza el minimo justo en el 44 | punto que queremos (pruebe eso). 45 | 46 | 47 | 48 | code: 49 | 50 | entonces si a esta fijo podemos hallar un minimo y queremos el minimo para 51 | todo a, pues tendremos que recorrer todo posible a y buscar ese minimo, tal 52 | vez no sea tan facil hallar punto medio por que todo es modular y eso, para 53 | ello podemos multiplicar el array x 2 y copiarlo, tal que asi si me paro en 54 | i, entonces el rango [i, i+n-1] representa mi array pero rotado i veces. 55 | 56 | complexity: O(n x log(n)) 57 | **/ 58 | 59 | 60 | #include 61 | using namespace std; 62 | 63 | const int maxN = 2e5, OFFSET = 2; 64 | int x[maxN + OFFSET], y[maxN + OFFSET]; 65 | long long total, ac[maxN]; 66 | int n; 67 | 68 | long long cross(int a, int b){ 69 | return x[a] * 1ll * y[b] - y[a] * 1ll * x[b]; 70 | } 71 | 72 | long long area(int l, int r){ 73 | return abs(ac[r-1] - ac[l-1] + cross(r, l)); 74 | } 75 | 76 | long long f(int i, int mid){ 77 | return abs(total - 2*area(i, mid)); 78 | } 79 | 80 | long long df(int i, int mid){ 81 | return f(i, mid+1) - f(i, mid); 82 | } 83 | 84 | bool p(int i, int mid){ 85 | return df(i, mid) < 0; 86 | } 87 | 88 | 89 | int main(){ 90 | while(scanf("%d", &n) == 1){ 91 | 92 | for(int i = 1; i <= n; ++i){ 93 | scanf("%d %d", x+i, y+i); 94 | x[i+n] = x[i]; 95 | y[i+n] = y[i]; 96 | } 97 | 98 | for(int i = 1; i <= 2*n; ++i) 99 | ac[i] = ac[i-1] + cross(i, i+1); 100 | 101 | total = area(1, n); 102 | 103 | long long p1 = 0, p2 = 0; 104 | for(int i = 1; i <= n; ++i){ 105 | int lo = i + 2, hi = i + n - 2; 106 | 107 | while(lo < hi){ 108 | int mid = lo + (hi-lo)/2; 109 | if(p(i, mid)) lo = mid+1; 110 | else hi = mid; 111 | } 112 | 113 | if(max(p1, p2) < max(area(i, lo), total - area(i, lo))) 114 | p1 = area(i, lo), p2 = total - area(i, lo); 115 | } 116 | 117 | if(p1 < p2) swap(p1, p2); 118 | 119 | printf("%lld %lld\n", p1, p2); 120 | } 121 | return 0; 122 | } -------------------------------------------------------------------------------- /uni-no-fiis/clase-05/soluciones/9.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define all(v) (v).begin(),(v).end() 3 | #define pb push_back 4 | #define ppb pop_back 5 | #define mp make_pair 6 | #define ri(x) scanf("%d",&(x)) 7 | #define ri2(x,y) scanf("%d %d",&(x),&(y)) 8 | #define ri3(x,y,z) scanf("%d %d %d",&(x),&(y),&(z)) 9 | #define rll(x) scanf("%lld",&(x)) 10 | #define rll2(x,y) scanf("%lld %lld",&(x),&(y)) 11 | #define rll3(x,y,z) scanf("%lld %lld %lld",&(x),&(y),&(z)) 12 | #define rc(x) scanf("%c",&(x)) 13 | using namespace::std; 14 | 15 | const long double PI = acos(-1); 16 | const int MOD = 1000000000 +7; 17 | 18 | typedef long long ll; 19 | typedef pair pll; 20 | typedef pair tll; 21 | typedef pair ii; 22 | typedef pair iii; 23 | typedef vector vi; 24 | typedef vector vii; 25 | typedef vector viii; 26 | typedef vector vll; 27 | typedef vector vpll; 28 | typedef vector vtll; 29 | typedef vector vs; 30 | typedef set si; 31 | typedef set sii; 32 | typedef set siii; 33 | 34 | ll gcd(ll a, ll b){ return b==0?a:gcd(b,a%b);} 35 | 36 | int add(ll a, ll b){ return (a%MOD + b%MOD+2*MOD)%MOD;} 37 | 38 | int mul(ll a, ll b){ return ((a%MOD+MOD)*(b%MOD+MOD))%MOD;} 39 | 40 | ll pow_mod(ll a, ll b){ 41 | ll res = 1LL; 42 | a = add(a,0); 43 | while(b){ 44 | if(b&1) res = mul(res,a); 45 | b >>= 1; 46 | a = mul(a,a); 47 | } 48 | return res; 49 | } 50 | 51 | ll fastexp(ll a, ll b){ 52 | ll res = 1LL; 53 | while(b){ 54 | if(b&1) res = res*a; 55 | b >>= 1; 56 | a *= a; 57 | } 58 | return res; 59 | } 60 | 61 | int gcdExtendido(int a, int b, int *x, int *y){ 62 | if(a == 0){ 63 | *x = 0; 64 | *y = 1; 65 | return b; 66 | } 67 | int x1, y1; 68 | int gcd = gcdExtendido(b%a,a,&x1,&y1); 69 | 70 | *x = y1-(b/a)*x1; 71 | *y = x1; 72 | return gcd; 73 | }; 74 | 75 | int modInverso(int a, int m){ 76 | int x, y; 77 | int g = gcdExtendido(a,m,&x,&y); 78 | if(g!=1) return -1; 79 | else return (x%m + m)%m; 80 | } 81 | 82 | /**************************************** 83 | *************P*L*A*N*T*I*L*L*A************ 84 | *****************************************/ 85 | 86 | // Clase BigInteger con suma implementada 87 | 88 | const int N = 150+5; 89 | 90 | class BigInteger{ 91 | int len; 92 | vi a; 93 | public: 94 | BigInteger(){ 95 | len = 0; 96 | a.clear(); 97 | } 98 | 99 | void use(string x){ 100 | len = x.size(); 101 | a.assign(len,0); 102 | for(int i=len-1; i>=0; i--){ 103 | a[len-1-i] = x[i]-'0'; 104 | } 105 | } 106 | 107 | void sumar(BigInteger b){ 108 | int sum_lens = max(b.len,len); 109 | vi carry; 110 | carry.resize(sum_lens); 111 | for(int i=0; i len){ 115 | for(int i=len; i 9){ 126 | carry[i+1] += carry[i]/10; 127 | carry[i] %= 10; 128 | } 129 | } 130 | if(carry[sum_lens-1] > 9){ 131 | carry.pb(carry[sum_lens-1]/10); 132 | carry[sum_lens-1] %= 10; 133 | sum_lens += 1; 134 | } 135 | len = sum_lens; 136 | a = carry; 137 | } 138 | 139 | void multiply(BigInteger b){ 140 | int sum_lens = len + b.len-1; 141 | vi carry(sum_lens); 142 | for(int i=0; i 9){ 152 | if(i == carry.size()-1){ 153 | carry.pb(carry[i]/10); 154 | carry[i] %= 10; 155 | 156 | } 157 | else{ 158 | carry[i+1] += carry[i]/10; 159 | carry[i] %= 10; 160 | } 161 | } 162 | } 163 | while(carry.back()==0) carry.ppb(); 164 | len = carry.size(); 165 | a = carry; 166 | } 167 | 168 | void Print(){ 169 | for(int i=len-1; i>=0; i--){ 170 | putchar('0'+a[i]); 171 | } 172 | puts(""); 173 | } 174 | 175 | }; 176 | 177 | string s; 178 | BigInteger carry; 179 | BigInteger ans, ZERO; 180 | 181 | int main(){ 182 | ZERO.use("0"); 183 | ans.use("0"); 184 | while(getline(cin,s) and s!="0"){ 185 | carry.use(s); 186 | ans.sumar(carry); 187 | } 188 | ans.Print(); 189 | return 0; 190 | } 191 | -------------------------------------------------------------------------------- /uni-no-fiis/clase-05/soluciones/8.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define all(v) (v).begin(),(v).end() 3 | #define pb push_back 4 | #define ppb pop_back 5 | #define mp make_pair 6 | #define ri(x) scanf("%d",&(x)) 7 | #define ri2(x,y) scanf("%d %d",&(x),&(y)) 8 | #define ri3(x,y,z) scanf("%d %d %d",&(x),&(y),&(z)) 9 | #define rll(x) scanf("%lld",&(x)) 10 | #define rll2(x,y) scanf("%lld %lld",&(x),&(y)) 11 | #define rll3(x,y,z) scanf("%lld %lld %lld",&(x),&(y),&(z)) 12 | #define rc(x) scanf("%c",&(x)) 13 | using namespace::std; 14 | 15 | const long double PI = acos(-1); 16 | const int MOD = 1000000000 +7; 17 | 18 | typedef long long ll; 19 | typedef pair pll; 20 | typedef pair tll; 21 | typedef pair ii; 22 | typedef pair iii; 23 | typedef vector vi; 24 | typedef vector vii; 25 | typedef vector viii; 26 | typedef vector vll; 27 | typedef vector vpll; 28 | typedef vector vtll; 29 | typedef vector vs; 30 | typedef set si; 31 | typedef set sii; 32 | typedef set siii; 33 | 34 | ll gcd(ll a, ll b){ return b==0?a:gcd(b,a%b);} 35 | 36 | int add(ll a, ll b){ return (a%MOD + b%MOD+2*MOD)%MOD;} 37 | 38 | int mul(ll a, ll b){ return ((a%MOD+MOD)*(b%MOD+MOD))%MOD;} 39 | 40 | ll pow_mod(ll a, ll b){ 41 | ll res = 1LL; 42 | a = add(a,0); 43 | while(b){ 44 | if(b&1) res = mul(res,a); 45 | b >>= 1; 46 | a = mul(a,a); 47 | } 48 | return res; 49 | } 50 | 51 | ll fastexp(ll a, ll b){ 52 | ll res = 1LL; 53 | while(b){ 54 | if(b&1) res = res*a; 55 | b >>= 1; 56 | a *= a; 57 | } 58 | return res; 59 | } 60 | 61 | int gcdExtendido(int a, int b, int *x, int *y){ 62 | if(a == 0){ 63 | *x = 0; 64 | *y = 1; 65 | return b; 66 | } 67 | int x1, y1; 68 | int gcd = gcdExtendido(b%a,a,&x1,&y1); 69 | 70 | *x = y1-(b/a)*x1; 71 | *y = x1; 72 | return gcd; 73 | }; 74 | 75 | int modInverso(int a, int m){ 76 | int x, y; 77 | int g = gcdExtendido(a,m,&x,&y); 78 | if(g!=1) return -1; 79 | else return (x%m + m)%m; 80 | } 81 | 82 | /**************************************** 83 | *************P*L*A*N*T*I*L*L*A************ 84 | *****************************************/ 85 | 86 | // Clase BigInteger, la formula a calcular esta en el mismo enunciado 87 | 88 | const int N = 150+5; 89 | 90 | class BigInteger{ 91 | int len; 92 | vi a; 93 | public: 94 | BigInteger(){ 95 | len = 0; 96 | a.clear(); 97 | } 98 | 99 | void use(int x){ 100 | len = 0; 101 | if(x == 0){ 102 | len = 1; 103 | a.pb(0); 104 | return; 105 | } 106 | a.clear(); 107 | while(x){ 108 | a.pb(x%10); 109 | x /= 10; 110 | len += 1; 111 | } 112 | } 113 | 114 | void sumar(BigInteger b){ 115 | int sum_lens = max(b.len,len); 116 | vi carry; 117 | carry.resize(sum_lens); 118 | for(int i=0; i len){ 122 | for(int i=len; i 9){ 133 | carry[i+1] += carry[i]/10; 134 | carry[i] %= 10; 135 | } 136 | } 137 | if(carry[sum_lens-1] > 9){ 138 | carry.pb(carry[sum_lens-1]/10); 139 | carry[sum_lens-1] %= 10; 140 | sum_lens += 1; 141 | } 142 | len = sum_lens; 143 | a = carry; 144 | } 145 | 146 | void multiply(BigInteger b){ 147 | int sum_lens = len + b.len-1; 148 | vi carry(sum_lens); 149 | for(int i=0; i 9){ 159 | if(i == carry.size()-1){ 160 | carry.pb(carry[i]/10); 161 | carry[i] %= 10; 162 | 163 | } 164 | else{ 165 | carry[i+1] += carry[i]/10; 166 | carry[i] %= 10; 167 | } 168 | } 169 | } 170 | while(carry.back()==0) carry.ppb(); 171 | len = carry.size(); 172 | a = carry; 173 | } 174 | 175 | void Print(){ 176 | for(int i=len-1; i>=0; i--){ 177 | putchar('0'+a[i]); 178 | } 179 | puts(""); 180 | } 181 | 182 | }; 183 | 184 | int n, a; 185 | BigInteger ans, ZERO; 186 | BigInteger p[N]; 187 | 188 | int main(){ 189 | ZERO.use(0); 190 | for(int i=1; i 2 | #define all(v) (v).begin(),(v).end() 3 | #define pb push_back 4 | #define ppb pop_back 5 | #define mp make_pair 6 | #define ri(x) scanf("%d",&(x)) 7 | #define ri2(x,y) scanf("%d %d",&(x),&(y)) 8 | #define ri3(x,y,z) scanf("%d %d %d",&(x),&(y),&(z)) 9 | #define rll(x) scanf("%lld",&(x)) 10 | #define rll2(x,y) scanf("%lld %lld",&(x),&(y)) 11 | #define rll3(x,y,z) scanf("%lld %lld %lld",&(x),&(y),&(z)) 12 | #define rc(x) scanf("%c",&(x)) 13 | using namespace::std; 14 | 15 | const long double PI = acos(-1); 16 | const int MOD = 1000000000 +7; 17 | 18 | typedef long long ll; 19 | typedef pair pll; 20 | typedef pair tll; 21 | typedef pair ii; 22 | typedef pair iii; 23 | typedef vector vi; 24 | typedef vector vii; 25 | typedef vector viii; 26 | typedef vector vll; 27 | typedef vector vpll; 28 | typedef vector vtll; 29 | typedef vector vs; 30 | typedef set si; 31 | typedef set sii; 32 | typedef set siii; 33 | 34 | ll gcd(ll a, ll b){ return b==0?a:gcd(b,a%b);} 35 | 36 | int add(ll a, ll b){ return (a%MOD + b%MOD+2*MOD)%MOD;} 37 | 38 | int mul(ll a, ll b){ return ((a%MOD+MOD)*(b%MOD+MOD))%MOD;} 39 | 40 | ll pow_mod(ll a, ll b){ 41 | ll res = 1LL; 42 | a = a%MOD; 43 | while(b){ 44 | if(b&1) res = mul(res,a); 45 | b >>= 1; 46 | a = mul(a,a); 47 | } 48 | return res; 49 | } 50 | 51 | ll fastexp(ll a, ll b){ 52 | ll res = 1LL; 53 | while(b){ 54 | if(b&1) res = res*a; 55 | b >>= 1; 56 | a *= a; 57 | } 58 | return res; 59 | } 60 | 61 | int gcdExtendido(int a, int b, int *x, int *y){ 62 | if(a == 0){ 63 | *x = 0; 64 | *y = 1; 65 | return b; 66 | } 67 | int x1, y1; 68 | int gcd = gcdExtendido(b%a,a,&x1,&y1); 69 | 70 | *x = y1-(b/a)*x1; 71 | *y = x1; 72 | return gcd; 73 | }; 74 | 75 | int modInverso(int a, int m){ 76 | int x, y; 77 | int g = gcdExtendido(a,m,&x,&y); 78 | if(g!=1) return -1; 79 | else return (x%m + m)%m; 80 | } 81 | 82 | /**************************************** 83 | *************P*L*A*N*T*I*L*L*A************ 84 | *****************************************/ 85 | 86 | /* Como lo usual, para analizar el fractal primero planteamos recursiones para 87 | * ancho y alto: 88 | * h(n) = 2h(n-1) 89 | * w(n) = 2w(n-1) 90 | * Donde h(1) = 2 y w(1) = 4 91 | * Entonces 92 | * h(n) = 2^{n} 93 | * w(n) = 2^{n+1} 94 | * Luego, nos es sencillo notar que es mas facil fijar el (x,y) no en el centro, 95 | * sino en donde colocamos el primer '/' para formar el triangulo. 96 | * En este caso, la primera llamada sera f(d,n,0,2^{n}-1) por la indexacion en 0 97 | * Ademas, como son solo 10 profundidades, podriamos almacenar todas estas en una tabla, para no tener que volver a crear el fractal y simplemente imprimirlo. (de esto se encarga d que va a ser fijo siempre) 98 | * Para ello creamos un array de booleanos llamado done[N], donde done[i] 99 | * dira si es que la profundidad i ya se proceso, con el fin de usar respuestas 100 | * ya hechas. 101 | * 102 | * Regresando al momento de llenar el fractal, notamos que: 103 | * 104 | * El fractal de profundidad n tiene 3 fractales de profundidad n-1: 105 | * Uno con la misma posicion, otro a la izquierda y otro a la derecha. 106 | * Es sencillo notar que sus distancias son dx = h(n-1) y dy = w(n-1)/2, entonces 107 | * Llenamos los fractales con n > 1 de la siguiente manera: 108 | * f(d,n-1,x,y) 109 | * f(d,n-1,x+dx,y-dy) 110 | * f(d,n-1,x+dx,y+dy) 111 | * Donde dx = 1<<(n-1) y dy = 1<<(n-1) 112 | * 113 | */ 114 | 115 | const int MAX_DEPTH = 11; 116 | const int MAX_ROW = 1030; 117 | const int MAX_COL = 2050; 118 | 119 | bool done[MAX_DEPTH]; 120 | char tabla[MAX_DEPTH][MAX_ROW][MAX_COL]; 121 | 122 | void f(int depth, int n, int x, int y){ 123 | if(n == 1){ 124 | tabla[depth][x][y] = '/'; 125 | tabla[depth][x][y+1] = '\\'; 126 | tabla[depth][x+1][y-1] = '/'; 127 | tabla[depth][x+1][y+2] = '\\'; 128 | tabla[depth][x+1][y] = tabla[depth][x+1][y+1] = '_'; 129 | } 130 | else{ 131 | int dy = (1<<(n-1)); 132 | int dx = (1<<(n-1)); 133 | f(depth,n-1,x+dx,y-dy); 134 | f(depth,n-1,x+dx,y+dy); 135 | f(depth,n-1,x,y); 136 | } 137 | } 138 | 139 | int main(){ 140 | int n; 141 | while(ri(n) and n){ 142 | if(done[n]){ 143 | for(int i=0; i<(1< 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | /** 7 | * Un string guarda un vector de chars, es decir palabras 8 | * Por ejemplo, si quisiera guardar la palabra "Hola mundo" puedo hacerlo así 9 | */ 10 | string cadena_1 = "Hola mundo"; 11 | /** 12 | * Como un string es un vector de chars, entonces en realidad tenemos lo siguiente 13 | * cadena_1 = ['H', 'o', 'l', 'a', ' ', 'm', 'u', 'n', 'd', 'o'] 14 | * Luego, al igual que con los vectores podemos acceder a un elemento en particular 15 | * considerando que las posiciones se cuentan desde 0 16 | */ 17 | cout << "Primer elemento de la cadena_1 es : " << cadena_1[0] << endl; 18 | 19 | // Podemos iterar sus elemento al igual que con los vectores 20 | 21 | // método 1 22 | for (char elemento : cadena_1) cout << elemento; 23 | cout << endl; 24 | 25 | // método 2 26 | for (int pos = 0; pos < cadena_1.size(); pos++) { 27 | cout << "cadena_1[" << pos << "] = " << cadena_1[pos] << endl; 28 | } 29 | 30 | /** 31 | * Pero, tal como mencionamos, un char en realidad es un número 32 | * entonces podemos obtener que número esta asociado a cada letra forzando la conversion de char a int 33 | */ 34 | for (int pos = 0; pos < cadena_1.size(); pos++) { 35 | cout << "cadena_1[" << pos << "] = " << (int) cadena_1[pos] << endl; 36 | } 37 | 38 | /** 39 | * Por otro lado, una situación común en CP es tener que recorrer las letras del abecedario 40 | * Si bien podemos hacerlo así: 41 | * string abecedario = "abcd....xyz"; 42 | * for (char letra : abecedario) cout << letra << endl; 43 | * Una forma más sencilla se puede lograr utilizando el hecho de que el número asociado a las letras 44 | * del abecedario están distribuidos de forma continua 45 | * 46 | * 'a' : 97 47 | * 'b' : 98 48 | * 'c' : 99 49 | * . 50 | * . 51 | * . 52 | * 'x' : 120 53 | * 'y' : 121 54 | * 'z' : 122 55 | */ 56 | // recorriendo el abecedario 57 | for (char ch = 'a'; ch <= 'z'; ch++) cout << ch << endl; 58 | 59 | /** 60 | * Análogamente para las letras mayúsculas tenemos: 61 | * 62 | * 'A' : 65 63 | * 'B' : 66 64 | * 'C' : 67 65 | * . 66 | * . 67 | * . 68 | * 'X' : 88 69 | * 'Y' : 89 70 | * 'Z' : 90 71 | */ 72 | for (char ch = 'A'; ch <= 'Z'; ch++) cout << ch << endl; 73 | 74 | 75 | /** 76 | * Nota 1: En CP la entrada es en Inglés asi que no se considera la ñ 77 | */ 78 | 79 | /** 80 | * Además, en la actualidad el estándar de esas equivalencias entre números y caracteres 81 | * ya no se hace por el ASCII, se hacer por el UNICODE 82 | * Y como un char solo aguanta 2 ^ 8 números y además hay caracteres complicados en algunos lenguajes que están compuestas por varias letras 83 | * suceden situaciones en la que un caracter se guarda en más de un char, por ejemplo: 84 | */ 85 | 86 | string cadena_2 = "á"; 87 | 88 | // Tenemos un solo elemento, pero si imprimos en tamaño de la cadena notamos que nos da 2 89 | cout << "El tamaño de cadena_2 es : " << cadena_2.size() << endl; 90 | 91 | // Por ello, en general, la forma más segura de recorrer un string es 92 | for (char elemento : cadena_2) cout << elemento; 93 | cout << endl; 94 | 95 | // Pues, con este método nos saldrán resultados extraños en estas situaciones 96 | for (int pos = 0; pos < cadena_2.size(); pos++) { 97 | cout << "cadena_2[" << pos << "] = " << cadena_2[pos] << endl; 98 | } 99 | 100 | // Podemos observar mejor el porqué si vemos el número asociado al caracter 'á' 101 | for (int pos = 0; pos < cadena_2.size(); pos++) { 102 | cout << "cadena_2[" << pos << "] = " << (int) cadena_2[pos] << endl; 103 | } 104 | // cadena_2[0] = -61 105 | // cadena_2[1] = -95 106 | // notamos que 'á' esta guarda como una tupla de números (-61, -95) y no como un solo número que es el caso 'normal' 107 | 108 | /** 109 | * Esto es solo como cultura general y para responder a lo que preguntaron 110 | * En CP la entrada siempre es en Inglés asi que solo vienen caracteres a los que estan asociados un solo número 111 | * por lo que no hay necesidad de preocuparse de esta cuestión 112 | */ 113 | 114 | /** 115 | * Más informacion de strings aquí: 116 | * http://www.cplusplus.com/reference/string/string/ 117 | * Además, tambien es bueno que conoscan algunas funciones básicas usadas con chars, información aquí: 118 | * http://www.cplusplus.com/reference/cctype/ 119 | */ 120 | 121 | return (0); 122 | } -------------------------------------------------------------------------------- /uni-no-fiis/clase-09/soluciones/p05.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define all(v) (v).begin(),(v).end() 3 | #define pb push_back 4 | #define ppb pop_back 5 | #define mp make_pair 6 | #define ri(x) scanf("%d",&(x)) 7 | #define ri2(x,y) scanf("%d %d",&(x),&(y)) 8 | #define ri3(x,y,z) scanf("%d %d %d",&(x),&(y),&(z)) 9 | #define rll(x) scanf("%lld",&(x)) 10 | #define rll2(x,y) scanf("%lld %lld",&(x),&(y)) 11 | #define rll3(x,y,z) scanf("%lld %lld %lld",&(x),&(y),&(z)) 12 | #define rc(x) scanf("%c",&(x)) 13 | using namespace::std; 14 | 15 | const long double PI = acos(-1); 16 | const int MOD = 1000000000 +7; 17 | 18 | typedef long long ll; 19 | typedef pair pll; 20 | typedef pair tll; 21 | typedef pair ii; 22 | typedef pair iii; 23 | typedef vector vi; 24 | typedef vector vii; 25 | typedef vector viii; 26 | typedef vector vll; 27 | typedef vector vpll; 28 | typedef vector vtll; 29 | typedef vector vs; 30 | typedef set si; 31 | typedef set sii; 32 | typedef set siii; 33 | 34 | ll gcd(ll a, ll b){ return b==0?a:gcd(b,a%b);} 35 | 36 | int add(ll a, ll b){ return (a%MOD + b%MOD+2*MOD)%MOD;} 37 | 38 | int mul(ll a, ll b){ return ((a%MOD+MOD)*(b%MOD+MOD))%MOD;} 39 | 40 | ll pow_mod(ll a, ll b){ 41 | ll res = 1LL; 42 | a = a%MOD; 43 | while(b){ 44 | if(b&1) res = mul(res,a); 45 | b >>= 1; 46 | a = mul(a,a); 47 | } 48 | return res; 49 | } 50 | 51 | ll fastexp(ll a, ll b){ 52 | ll res = 1LL; 53 | while(b){ 54 | if(b&1) res = res*a; 55 | b >>= 1; 56 | a *= a; 57 | } 58 | return res; 59 | } 60 | 61 | int gcdExtendido(int a, int b, int *x, int *y){ 62 | if(a == 0){ 63 | *x = 0; 64 | *y = 1; 65 | return b; 66 | } 67 | int x1, y1; 68 | int gcd = gcdExtendido(b%a,a,&x1,&y1); 69 | 70 | *x = y1-(b/a)*x1; 71 | *y = x1; 72 | return gcd; 73 | }; 74 | 75 | int modInverso(int a, int m){ 76 | int x, y; 77 | int g = gcdExtendido(a,m,&x,&y); 78 | if(g!=1) return -1; 79 | else return (x%m + m)%m; 80 | } 81 | 82 | /**************************************** 83 | *************P*L*A*N*T*I*L*L*A************ 84 | *****************************************/ 85 | 86 | /* Se puede resolver este problema con pilas, sale de manera lineal y es sencillo. 87 | * El enfoque con recursion es el siguiente: 88 | * 89 | * Si tengo el rango [l,r] de la cadena S, entonces basta con probar si algun i 90 | * cumple con que S[l,i] esta balanceado y S[i+1,r] esta balanceado tambien, 91 | * en tal caso S[l,r] estaria correctamente balanceado. Iniciamos con toda la cadena 92 | * Suponiendo que la funcion que nos dice si esta bien balanceado o no es can(l,r) 93 | * Llamamos primero can(0,n-1). 94 | * 95 | * Sin embargo, este metodo daria TLE, pues faltan considerar optimizaciones: 96 | * 97 | * 1) Debemos asegurarnos de que cuando fijemos i, los extremos sean coherentes, 98 | * es decir, que S[l] + S[i] sea igual a "[]" o "()", para S[i+1] y S[r] NO nos 99 | * interesa puesto que no sabemos donde vamos a cortar en ese rango, solo 100 | * hemos fijado para el primer rango. 101 | * 102 | * 2) Con lo anterior no basta, asi que tambien nos fijamos que S[i+1] sea un simbolo de apertura, S[i+1] == '(' o S[i+1] == '[' 103 | * 104 | * 3) Aun podemos optimizar mas, dandonos cuenta de que una cadena bien balanceada debe tener longitud par, poner condicion (r-l+1) %2 debe ser 0 o automaticamente se vuelve falsa la expresion 105 | * 106 | * 4) Debido a la optimizacion anterior, no tomamos todos los i, sino los i tales que sean i = l+2k-1, para que la distancia entre i y l sea par. Claro esta que consideramos el caso en el que S[l]+S[r] == "[]" o S[l]+S[r] == "()" aparte 107 | * 108 | * 5) Si l+1 == r es un caso base, en el cual debe ser un "[]" o "()" para que sea verdadero. Otro caso base podria ser l >= r que automaticamente es falso, pero eso no lo analizamos mucho puesto que ya se considera al momento de verificar la longitud de la cadena 109 | * 110 | * Motivos por los cuales daria WA: 111 | * 112 | * - Dado que nos mencionan que la cadena vacia tambien puede ser balanceada, no 113 | * debemos olvidar el caso en que nos den una. Usar cin malogra el proceso, pues 114 | * no reconoce cadenas vacias. Usar getline en C++. 115 | * 116 | */ 117 | 118 | int n; 119 | int abre[300]; 120 | string s; 121 | 122 | bool can(int l, int r){ 123 | if((r-l+1)&1) return false; 124 | if(s[l] == ')' or s[l] == ']' or s[r] == '(' or s[r] == '[') return false; 125 | if(l >= r) return false; 126 | if(l+1 == r) return abre[s[r]] == s[l]; 127 | if(s[l] == abre[s[r]]){ 128 | if(can(l+1,r-1)) return true; 129 | } 130 | for(int i=l+1; i