0% found this document useful (0 votes)
30 views

Ecigma C Java

This document provides information on C++ and Java basics including data structures, algorithms, and libraries. It discusses default files and data structures in C++ such as vectors, queues, stacks, and recommends replacing them with deques for better performance. It also covers priority queues, lists, sets, maps, stacks, queues, and their usage. The document concludes with tips on Codeblocks and Eclipse IDEs.

Uploaded by

Gustavo Granados
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Ecigma C Java

This document provides information on C++ and Java basics including data structures, algorithms, and libraries. It discusses default files and data structures in C++ such as vectors, queues, stacks, and recommends replacing them with deques for better performance. It also covers priority queues, lists, sets, maps, stacks, queues, and their usage. The document concludes with tips on Codeblocks and Eclipse IDEs.

Uploaded by

Gustavo Granados
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

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=a.begin();i!=a.end();++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 d.back();
13 #define x first 19 type d.front();
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 d.back();
19 typedef deque<int> di; 25 type d.front();
20 typedef deque<i> dii; 26 type d[pos];
21 typedef di::iterator dit; 27 int d.size();
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 q.top(); greater than val.
51 void q.pop(); 17
52 void q.push(type i); 18 // Example
53 int q.size(); 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 l.back(); 10
71 type l.front(); 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 l.erase(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 l.erase(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 l.insert(it, type i); // inserts i just before it. it 38
does not change. 39
79 void l.insert(it,int n,type i); // inserts n times i. 40
80 void l.insert(it,it0,it1); // inserts from it forward a 41 //sort usage:
copy of [it0..it1). 42
81 int l.size(); 43 sort(A,A+N); //Sort an array A of size N
82 44
83 45 sort(A.begin(),A.end()); //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(A.begin(),A.end()); //Reverse a vector or deque A
6 + Min

2
2 Librerias
2.1 BigInteger
1 import java.math.BigInteger;
2
3 public class BigInt {
4 /*
5 * Variables de la clase:
6 *
7 * BigInteger.ZERO: El cero ya construido en BigInteger.
8 * BigInteger.ONE: El uno ya construido en BigInteger.
9 * BigInteger.TEN: 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 = BigInteger.valueOf(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 * num1.add(num2); // Si se deja asi, no se guardara en ningun lado.
22 * num1 = num1.add(num2); // En cambio aca, se guardara en la variable num1 para su uso futuro.
23 */
24 System.out.println(num1.add(num2)); //min1+min2: 63.
25 System.out.println(num1.subtract(num2)); //min1-min2: 3.
26 System.out.println(num1.multiply(num2)); //min1*min2: 990.
27 System.out.println(num1.divide(num2)); //min1/min2: 1.
28 System.out.println(num1.abs()); //Valor absoluto: 33.
29 System.out.println(num1.mod(num2)); //33 mod 33 = 3.
30 System.out.println(num1.isProbablePrime(100)); //Probabilidad del parametro% de ser primo o no: false.
31 System.out.println(num1.compareTo(num2)); //-1, 0 or 1 si num1 es menor que, igual o mayor que num2: 1.
32 System.out.println(num1.min(num2)); //Retorna el minimo entre num1 y num2: 30
33 System.out.println(num1.max(num2)); //Retorna el maximo entre num1 y num2: 33
34 System.out.println(num1.or(num2)); // num1 | num2: 63
35 System.out.println(num1.and(num2)); // num1 & num2: 0
36 System.out.println(num1.andNot(num2)); // num1 & ~num2: 33
37 System.out.println(num1.shiftLeft(n)); // num1 << n: 138
38 System.out.println(num1.shiftRight(n)); // num1 >> n: 8
39 System.out.println(num1.flipBit(n)); // num1 ^ (1<<n)
40 System.out.println(num1.getLowestSetBit()); // 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 System.out.println(num1.signum()); // -1, 0 or 1 is el valor del BigInteger es negativo, cero o positivo: 1
42 System.out.println(num1.not()); // ~num1: -34
43 System.out.println(num1.modPow(num2, num1)); // num1^(num2) mod num1: 0
44 System.out.println(num1.negate()); // -num1: -33
45 System.out.println(num1.gcd(num2)); // GCD(num1.abs(), num2.abs()): 3
46 System.out.println(num1.pow(n)); // num1^n: 1089
47 System.out.println(num1.remainder(num2)); // num1 % num2 (A diferencia de mod, este puede retornar un numero negativo
): 3
48 System.out.println(num1.divideAndRemainder(num2)); // Retorna un BigInteger[] con dos valores: (num1 / num2) y (num1
% num2) (Direccion de memoria si se imprime directamente)
49 System.out.println(num1.nextProbablePrime()); //Siguiente numero probablemente primo: 37
50 System.out.println(num1.toByteArray()); //Retorna un byte[] con la representacion en complemento a dos del BigInteger
(Direccion de memoria si se imprime directamente).
51 System.out.println(num1.intValue()); //Retorna el valor entero del BigInteger.
52 System.out.println(num1.floatValue()); //Retorna el valor flotante del BigInteger.
53 System.out.println(num1.doubleValue()); //Retorna el valor en double del BigInteger.
54 System.out.println(num1.longValue()); // Retorna el valor en long del BigInteger.
55 }
56 }

2.2 BigDecimal
1 import java.math.BigDecimal;
2 import java.math.BigInteger;
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 * BigDecimal.TEN: El valor de 10, con una escala de 0.
14 * BigDecimal.ZERO: 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 = num3.toBigInteger(); //Se puede construir un BigInteger a partir de un BigDecimal, con la escala.
26 num4 = num3.unscaledValue(); // Se puede construir un BigInteger tambien a partir de un BigDecimal, pero esta ves sin
su escala.
27 BigDecimal num5 = BigDecimal.valueOf(i); //Construir un BigDecimal a partir de un long, con escala de cero.
28 num5 = BigDecimal.valueOf(i,BigDecimal.ROUND_DOWN); // Tambien se puede definir la escala cuando se construye con
Long.
29 BigDecimal num6 = BigDecimal.valueOf(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 * num1.add(num2); // Si se deja asi, no se guardara en ningun lado.
33 * num1 = num1.add(num2); // En cambio aca, se guardara en la variable num1 para su uso futuro.
34 */
35 System.out.println(num1.add(num2)); //min1+min2: 63.
36 System.out.println(num1.subtract(num2)); //min1-min2: 3.
37 System.out.println(num1.multiply(num2)); //min1*min2: 990.
38 System.out.println(num1.divide(num2)); //min1/min2: 1.
39 System.out.println(num1.abs()); //Valor absoluto: 33.
40 System.out.println(num1.compareTo(num2)); //-1, 0 or 1 si num1 es menor que, igual o mayor que num2: 1.
41 System.out.println(num1.min(num2)); //Retorna el minimo entre num1 y num2: 30
42 System.out.println(num1.max(num2)); //Retorna el maximo entre num1 y num2: 33
43 System.out.println(num1.signum()); // -1, 0 or 1 is el valor del BigInteger es negativo, cero o positivo: 1
44 System.out.println(num1.negate()); // -num1: -33
45 System.out.println(num1.pow(n)); // num1^n: 1089
46 System.out.println(num1.remainder(num2)); // num1 % num2 (A diferencia de mod, este puede retornar un numero negativo
): 3
47 System.out.println(num1.divideAndRemainder(num2)); // Retorna un BigInteger[] con dos valores: (num1 / num2) y (num1
% num2) (Direccion de memoria si se imprime directamente)
48 System.out.println(num1.movePointLeft(n)); // Retorna un BigDecimal moviendo n-veces a la izquierda el punto decimal:
0.33
49 System.out.println(num1.movePointRight(n)); // Retorna un BigDecimal moviendo n-veces a la derecha el punto decimal:
3300
50 System.out.println(num1.intValue()); //Retorna el valor entero del BigInteger.
51 System.out.println(num1.floatValue()); //Retorna el valor flotante del BigInteger.
52 System.out.println(num1.doubleValue()); //Retorna el valor en double del BigInteger.
53 System.out.println(num1.longValue()); // Retorna el valor en long del BigInteger.
54 System.out.println(num1.toString()); // Retorna la representacion en String del BigDecimal.
55 System.out.println(num3.setScale(n)); // Agregar una escala de (parametro) digitos: 3000.00
56 System.out.println(num3.setScale(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 java.util.GregorianCalendar;
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 System.out.println("ERA: " + calendar.get(Calendar.ERA));
13 System.out.println("YEAR: " + calendar.get(Calendar.YEAR));
14 System.out.println("MONTH: " + calendar.get(Calendar.MONTH));
15 System.out.println("WEEK_OF_YEAR: " + calendar.get(Calendar.WEEK_OF_YEAR));
16 System.out.println("WEEK_OF_MONTH: " + calendar.get(Calendar.WEEK_OF_MONTH));
17 System.out.println("DATE: " + calendar.get(Calendar.DATE));
18 System.out.println("DAY_OF_MONTH: " + calendar.get(Calendar.DAY_OF_MONTH));
19 System.out.println("DAY_OF_YEAR: " + calendar.get(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 a.add(a.DATE, 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 = Math.abs(a.getTimeInMillis() - b.getTimeInMillis());
28 long z = (res /(86400000));
29 System.out.println(z);
30 //Setting time Zone
31 a.setTimeZone(TimeZone.getTimeZone("GMT"));
32 }
33 }

2.4 Java RegEx


1 import java.io.BufferedReader;
2 import java.io.InputStreamReader;
3 import java.util.regex.Pattern;
4 import java.util.regex.Matcher;
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(System.in));
18 double[] mol= {12.01,1.008,16.00,14.01};
19 int N= Integer.parseInt(br.readLine().trim());
20 Pattern pat = Pattern.compile("[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=br.readLine().trim();
27 Matcher mat = pat.matcher(l);
28 while (mat.find()) {
29 r=mat.group();
30 if (r.length()>1) h=Integer.parseInt(r.substring(1));
31 else h=1;
32 res+=mol[elem(r.charAt(0))]*h;
33 }
34 System.out.printf("%.3f\n",res);
35 }
36 br.close();
37 }
38 }
39
40 /*
41 * boolean b = Pattern.matches("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 * http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
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

You might also like