ECIGMA - C++ and Java basics
Grupo de Maratonistas
Escuela Colombiana de Ingenierı́a Julio Garavito
14-04-2016
Contents
1 C++ 1
1.1 Default file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Data structures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.3 Algorithm library. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
2 Librerias 3
2.1 BigInteger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.2 BigDecimal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.3 GregorianCalendar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.4 Java RegEx . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
3 Tips 6
3.1 Codeblocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
3.2 Eclipse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1 C++ 3
4 //----------------------------------------------------
5
1.1 Default file 6 //We recommend replacing vectors, queues and stacks with
deques.
1 #include <bits/stdc++.h> 7
2 #define loop(i,a,b) for(i=a;i<b;++i) 8 // deque: double ended queue. Allows:
3 #define rev(i,a,b) for(i=a;i>=b;--i) 9 // 1. Constant access to front and back.
4 #define itloop(i,a) for(i=[Link]();i!=[Link]();++i) 10 // 2. Constant push back/front element.
5 #define SET(a,c) memset(a,c,sizeof(a)) 11 // 3. Constant pop back/front.
6 #define READ(file) freopen(file, "r", stdin) 12 // 4. Constant [pos] access.
7 #define WRITE(file) freopen(file, "w", stdout) 13
8 #define pb(a) push_back(a) 14 // Declare:
9 #define pf(a) push_front(a) 15 deque<type> d;
10 #define tup(a,b) make_pair(a,b) 16
11 #define popb() pop_back() 17 // Methods:
12 #define popf() pop_front() 18 type [Link]();
13 #define x first 19 type [Link]();
14 #define y second 20 void d.push_back(type i);
15 21 void d.push_front(type i);
16 using namespace std; 22 void d.pop_back();
17 typedef long long large; 23 void d.pop_front();
18 typedef pair<int,int> ii; 24 type [Link]();
19 typedef deque<int> di; 25 type [Link]();
20 typedef deque<i> dii; 26 type d[pos];
21 typedef di::iterator dit; 27 int [Link]();
22 28
23 int main(){ 29 //----------------------------------------------
24 return 0; 30
25 } 31 // priorityQueue: heap. Allows:
32 // 1. Constant access to minimal element.
1.2 Data structures. 33 // 2. Logarithmic removal of minimal element.
34 // 3. Logarithmic push of an element.
35
1 // From now on, ’type’ can be replaced with any data type 36 // Declare:
or class such as 37 // a.) default cmp (lesser):
2 // int, char, pair<int,int>, double, etc.
1
38 priority_queue<type> q; 7 + Reverse
39 8 + Sort
40 // b.) greater cmp: 9 + Swap
41 priority_queue< type, vector<type>, greater<type> > q; 10 */
42 11
43 // c.) desired cmp: 12 // lower/upper_bound usage: (binary search)
44 class cmp{public: bool operator()(const type a,const type b13
)const{ 14 // Given a sorted array (or deque or vector),
45 return a<b; 15 // + lower_bound returns an iterator pointing to the first
46 } }; element in the range [first,last) which does not
47 priority_queue<type,vector<type>,cmp> q; compare less than val.
48 16 // + upper_bound returns an iterator pointing to the first
49 // Methods: element in the range [first,last) which compares
50 type [Link](); greater than val.
51 void [Link](); 17
52 void [Link](type i); 18 // Example
53 int [Link](); 19 // i: 0 1 2 3 4 5 6 7 8 9
54 20 // A[i]: 0 2 4 6 8 10 12 14 16 18
55 //---------------------------------------------- 21 // LowerBound :
56 22 // 7: < < < < >= >= >= >= >= >= lowerbound for 7 :
57 // list: linked list. Allows: 4
58 // 0. NON Constant [pos] access. 23 // -1: >= >= >= >= >= >= >= >= >= >= lowerbound for -1 :
59 // 1. Constant access to front and back. 0
60 // 2. Constant push back/front element. 24 // 30: < < < < < < < < < < lowerbound for 30 :
61 // 3. Constant pop back/front. 10
62 // 4. Constant removal of element at iterator. 25 // 12: < < < < < < >= >= >= >= lowerbound for 12 :
63 // 5. Constant removal of element in [it1..it2). 6
64 // 6. Constant insert of element at iterator. 26 // UpperBound :
65 27 // 7: <= <= <= <= > > > > > > upperbound for 7 :
66 // Declare: 4
67 list<type> l; 28 // -1: > > > > > > > > > > upperbound for -1 :
68 0
69 // Methods: 29 // 30: <= <= <= <= <= <= <= <= <= <= upperbound for 30 :
70 type [Link](); 10
71 type [Link](); 30 // 12: <= <= <= <= <= <= <= > > > upperbound for 12 :
72 void l.push_back(type i); 7
73 void l.push_front(type i); 31
74 void l.pop_back(); 32 int A[10];
75 void l.pop_front(); 33 loop(i,0,10) A[i]=2*i;
76 void [Link](l<type>::iterator it); // removes at it. 34 j = lower_bound(A,A+10, 7)-A; // j is 4.
returns it to next position. 35 j = lower_bound(A,A+10,-1)-A; // j is 0.
77 void [Link](it0, it1); // removes [it0..it1). it1 does not36 j = lower_bound(A,A+10,30)-A; // j is 10.
change. 37 j = lower_bound(A,A+10,12)-A; // j is 6.
78 void [Link](it, type i); // inserts i just before it. it 38
does not change. 39
79 void [Link](it,int n,type i); // inserts n times i. 40
80 void [Link](it,it0,it1); // inserts from it forward a 41 //sort usage:
copy of [it0..it1). 42
81 int [Link](); 43 sort(A,A+N); //Sort an array A of size N
82 44
83 45 sort([Link](),[Link]()); //Sort a vector or deque A
84 //---------------------------------------------- 46
85 47 bool myCmp(int a, int b){ return a>b; }
86 // set: multiset. Allows: 48 sort(A,A+N,myCmp); //Sort using your own compare
87 function.
88 //---------------------------------------------- 49
89 50 //Swap usage: Given a and b of the same type or class, swap
90 // map: dictionary. Allows: their content with
91 51
92 //---------------------------------------------- 52 int a=0,b=1;
93 53 swap(a,b);
94 // iterators: pointer-like. Allows: 54 // now a is 1 and b is 0.
55
1.3 Algorithm library. 56 swap(A[7],A[6]); // swap elements in a vector
57
58
1 /* 59 //reverse usage:
2 Contents: 60
3 + Lower bound (binary search) 61 reverse(A,A+N); //Reverse an array A of size N
4 + Upper bound (binary search) 62
5 + Max 63 sort([Link](),[Link]()); //Reverse a vector or deque A
6 + Min
2
2 Librerias
2.1 BigInteger
1 import [Link];
2
3 public class BigInt {
4 /*
5 * Variables de la clase:
6 *
7 * [Link]: El cero ya construido en BigInteger.
8 * [Link]: El uno ya construido en BigInteger.
9 * [Link]: El diez ya construido en BigInteger.
10 */
11 public static void main(String[] args) {
12 String numero = "33";
13 int numero2 = 30;
14 int n = 2;
15 long i = 300;
16 BigInteger num1 = new BigInteger(numero); //El constructor es un String
17 BigInteger num2 = new BigInteger(numero2+""); //"Metodo inusual" para construir con enteros.
18 BigInteger num3 = [Link](i); // Construye un BigInteger a partir de un long.
19 /*
20 * Todas las operaciones de aca en adelante, deben ser guardadas en una variable, por ejemplo:
21 * [Link](num2); // Si se deja asi, no se guardara en ningun lado.
22 * num1 = [Link](num2); // En cambio aca, se guardara en la variable num1 para su uso futuro.
23 */
24 [Link]([Link](num2)); //min1+min2: 63.
25 [Link]([Link](num2)); //min1-min2: 3.
26 [Link]([Link](num2)); //min1*min2: 990.
27 [Link]([Link](num2)); //min1/min2: 1.
28 [Link]([Link]()); //Valor absoluto: 33.
29 [Link]([Link](num2)); //33 mod 33 = 3.
30 [Link]([Link](100)); //Probabilidad del parametro% de ser primo o no: false.
31 [Link]([Link](num2)); //-1, 0 or 1 si num1 es menor que, igual o mayor que num2: 1.
32 [Link]([Link](num2)); //Retorna el minimo entre num1 y num2: 30
33 [Link]([Link](num2)); //Retorna el maximo entre num1 y num2: 33
34 [Link]([Link](num2)); // num1 | num2: 63
35 [Link]([Link](num2)); // num1 & num2: 0
36 [Link]([Link](num2)); // num1 & ~num2: 33
37 [Link]([Link](n)); // num1 << n: 138
38 [Link]([Link](n)); // num1 >> n: 8
39 [Link]([Link](n)); // num1 ^ (1<<n)
40 [Link]([Link]()); // Devuelve el indice del bit 1 mas a la derecha (el numero de bits cero
a la derecha del bit 1 mas a la derecha) o -1 si no tiene bits. Equivalente a: num1 == 0 ? -1 : log2(num1 & -num1)).
41 [Link]([Link]()); // -1, 0 or 1 is el valor del BigInteger es negativo, cero o positivo: 1
42 [Link]([Link]()); // ~num1: -34
43 [Link]([Link](num2, num1)); // num1^(num2) mod num1: 0
44 [Link]([Link]()); // -num1: -33
45 [Link]([Link](num2)); // GCD([Link](), [Link]()): 3
46 [Link]([Link](n)); // num1^n: 1089
47 [Link]([Link](num2)); // num1 % num2 (A diferencia de mod, este puede retornar un numero negativo
): 3
48 [Link]([Link](num2)); // Retorna un BigInteger[] con dos valores: (num1 / num2) y (num1
% num2) (Direccion de memoria si se imprime directamente)
49 [Link]([Link]()); //Siguiente numero probablemente primo: 37
50 [Link]([Link]()); //Retorna un byte[] con la representacion en complemento a dos del BigInteger
(Direccion de memoria si se imprime directamente).
51 [Link]([Link]()); //Retorna el valor entero del BigInteger.
52 [Link]([Link]()); //Retorna el valor flotante del BigInteger.
53 [Link]([Link]()); //Retorna el valor en double del BigInteger.
54 [Link]([Link]()); // Retorna el valor en long del BigInteger.
55 }
56 }
2.2 BigDecimal
1 import [Link];
2 import [Link];
3 public class BigDeci {
4 /* Tipos de redondeo:
5 * BigDecimal.ROUND_CEILING: Redondea hacia el infinito positivo.
3
6 * BigDecimal.ROUND_DOWN: Redondea hacia el cero.
7 * BigDecimal.ROUND_FLOOR: Redondea hacia el infinito negativo.
8 * BigDecimal.ROUND_HALF_EVEN: Redondea hacia el "vecino mas cercano" a menos que ambos vecinos sean equidistantes, en
ese caso redondea hacia abajo.
9 * BigDecimal.ROUND_HALF_UP: Redondea hacia el "vecino mas cercano" a menos que ambos vecinos sean equidistantes, en
ese caso redondea hacia arriba.
10 * BigDecimal.ROUND_UNNECESSARY: Redondea afirmando que la operacion tiene un resultado exacto, por lo tanto, no es
necesario un redondeo.
11 * BigDecimal.ROUND_UP: Redondea hacia arriba de cero.
12 * Variables de la clase:
13 * [Link]: El valor de 10, con una escala de 0.
14 * [Link]: El valor de 0, con una escala de 0.
15 */
16 public static void main(String[] args) {
17 String numero = "33";
18 int numero2 = 30;
19 int n = 2;
20 long i = 300;
21 double h = 100;
22 BigDecimal num1 = new BigDecimal(numero); //El constructor es un String
23 BigDecimal num2 = new BigDecimal(numero2+""); //"Metodo inusual" para construir con enteros.
24 BigDecimal num3 = new BigDecimal(new BigInteger("3000")); //BigDecimal tambien se puede construir a partir de un
BigInteger.
25 BigInteger num4 = [Link](); //Se puede construir un BigInteger a partir de un BigDecimal, con la escala.
26 num4 = [Link](); // Se puede construir un BigInteger tambien a partir de un BigDecimal, pero esta ves sin
su escala.
27 BigDecimal num5 = [Link](i); //Construir un BigDecimal a partir de un long, con escala de cero.
28 num5 = [Link](i,BigDecimal.ROUND_DOWN); // Tambien se puede definir la escala cuando se construye con
Long.
29 BigDecimal num6 = [Link](h); // Construir un BigDecimal a partir de un double.
30 /*
31 * Todas las operaciones de aca en adelante, deben ser guardadas en una variable, por ejemplo:
32 * [Link](num2); // Si se deja asi, no se guardara en ningun lado.
33 * num1 = [Link](num2); // En cambio aca, se guardara en la variable num1 para su uso futuro.
34 */
35 [Link]([Link](num2)); //min1+min2: 63.
36 [Link]([Link](num2)); //min1-min2: 3.
37 [Link]([Link](num2)); //min1*min2: 990.
38 [Link]([Link](num2)); //min1/min2: 1.
39 [Link]([Link]()); //Valor absoluto: 33.
40 [Link]([Link](num2)); //-1, 0 or 1 si num1 es menor que, igual o mayor que num2: 1.
41 [Link]([Link](num2)); //Retorna el minimo entre num1 y num2: 30
42 [Link]([Link](num2)); //Retorna el maximo entre num1 y num2: 33
43 [Link]([Link]()); // -1, 0 or 1 is el valor del BigInteger es negativo, cero o positivo: 1
44 [Link]([Link]()); // -num1: -33
45 [Link]([Link](n)); // num1^n: 1089
46 [Link]([Link](num2)); // num1 % num2 (A diferencia de mod, este puede retornar un numero negativo
): 3
47 [Link]([Link](num2)); // Retorna un BigInteger[] con dos valores: (num1 / num2) y (num1
% num2) (Direccion de memoria si se imprime directamente)
48 [Link]([Link](n)); // Retorna un BigDecimal moviendo n-veces a la izquierda el punto decimal:
0.33
49 [Link]([Link](n)); // Retorna un BigDecimal moviendo n-veces a la derecha el punto decimal:
3300
50 [Link]([Link]()); //Retorna el valor entero del BigInteger.
51 [Link]([Link]()); //Retorna el valor flotante del BigInteger.
52 [Link]([Link]()); //Retorna el valor en double del BigInteger.
53 [Link]([Link]()); // Retorna el valor en long del BigInteger.
54 [Link]([Link]()); // Retorna la representacion en String del BigDecimal.
55 [Link]([Link](n)); // Agregar una escala de (parametro) digitos: 3000.00
56 [Link]([Link](n, BigDecimal.ROUND_FLOOR)); // Ademas de definir una escala, elige el tipo de
redondeo, especificados al comienzo: 3000.00
57 }
58 }
2.3 GregorianCalendar
1 import [Link];
2 public class GC{
3 /*
4 Constants
5 ERA ,AD ,YEAR ,MONTH
6 DAY_OF_MONTH, DAY_OF_WEEK ,WEEK_OF_MONTH
4
7 ,DAY_OF_WEEK_IN_MONTH ,AM_PM,HOUR, HOUR_OF_DAY, MINUTE, SECOND, MILLISECOND
8 */
9 public static void main(String args[]){
10 Calendar calendar = new GregorianCalendar(); // 0 params = Current time
11 // print out a bunch of interesting things
12 [Link]("ERA: " + [Link]([Link]));
13 [Link]("YEAR: " + [Link]([Link]));
14 [Link]("MONTH: " + [Link]([Link]));
15 [Link]("WEEK_OF_YEAR: " + [Link](Calendar.WEEK_OF_YEAR));
16 [Link]("WEEK_OF_MONTH: " + [Link](Calendar.WEEK_OF_MONTH));
17 [Link]("DATE: " + [Link]([Link]));
18 [Link]("DAY_OF_MONTH: " + [Link](Calendar.DAY_OF_MONTH));
19 [Link]("DAY_OF_YEAR: " + [Link](Calendar.DAY_OF_YEAR));
20 //Month is indexed from 0 to 11
21 GregorianCalendar gc = new GregorianCalendar(2014 , 11 , 24); //Construct a date with params year, month, day
22 int diasAdd = 50;
23 [Link]([Link], diasAdd); // Adding days to the date
24 //Days of differce between two Dates
25 GregorianCalendar a = new GregorianCalendar(a1 , m1 , d1);
26 GregorianCalendar b = new GregorianCalendar(a2 , m2, d2);
27 long res = [Link]([Link]() - [Link]());
28 long z = (res /(86400000));
29 [Link](z);
30 //Setting time Zone
31 [Link]([Link]("GMT"));
32 }
33 }
2.4 Java RegEx
1 import [Link];
2 import [Link];
3 import [Link];
4 import [Link];
5
6 public class Main {
7 public static int elem (char c) {
8 switch(c) {
9 case ’C’: return 0;
10 case ’H’: return 1;
11 case ’O’: return 2;
12 case ’N’: return 3;
13 default: return -1;
14 }
15 }
16 public static void main(String[] args)throws Exception {
17 BufferedReader br= new BufferedReader (new InputStreamReader([Link]));
18 double[] mol= {12.01,1.008,16.00,14.01};
19 int N= [Link]([Link]().trim());
20 Pattern pat = [Link]("[CHON]([0-9]+)?");
21 double res;
22 int h;
23 String l, r;
24 for (int i=0; i<N;i++) {
25 res=0d;
26 l=[Link]().trim();
27 Matcher mat = [Link](l);
28 while ([Link]()) {
29 r=[Link]();
30 if ([Link]()>1) h=[Link]([Link](1));
31 else h=1;
32 res+=mol[elem([Link](0))]*h;
33 }
34 [Link]("%.3f\n",res);
35 }
36 [Link]();
37 }
38 }
39
40 /*
41 * boolean b = [Link]("a*b", "aaaaab");
42 * realiza la busqueda de una cadena en otra. Complejidad O(n),
43 * en el peor de los casos es O(2^n), donde en es a lo sumo 25.
5
44 *
45 * [Link]
46 */
3 Tips
3.1 Codeblocks
1. Settings - Editor - Use tab character, tab indents, tab size 2,
2. Settings - Editor - Default code.
3. Settings - Editor - Strip trailing blanks.
4. Settings - Editor - Brace completion.
5. Settings - Editor - Keyboard shortcuts - Close file.
6. Settings - Editor - Brace indention off.
3.2 Eclipse
1. Settings