├── Cover.png ├── LightOJ ├── 1002 │ ├── graph.png │ ├── graph2.png │ └── en.md ├── 1004 │ ├── 1004problem.png │ └── en.md ├── 1008 │ └── en.md ├── 1022 │ ├── 1022.png │ ├── problem-1022.png │ └── en.md ├── 1036 │ └── en.md ├── 1045 │ └── en.md ├── 1072 │ ├── 1072.png │ ├── problem1072.png │ └── en.md ├── 1075 │ └── en.md ├── 1107 │ ├── 1107.png │ └── en.md ├── 1116 │ └── en.md ├── 1136 │ └── en.md ├── 1182 │ └── en.md ├── 1202 │ ├── 1203pr.gif │ └── en.md ├── 1211 │ ├── 1211.png │ └── en.md ├── 1216 │ ├── 1216.png │ ├── problem1216.png │ └── en.md ├── 1294 │ └── en.md ├── 1305 │ ├── Formula.png │ ├── 1305problem.png │ └── en.md ├── 1311 │ └── en.md └── 1433 │ ├── 1433.png │ ├── problem-1433.png │ └── en.md ├── Chapter 02 ├── 2.3 │ ├── Exercise2.c │ ├── Exercise2.pdf │ ├── Timus │ │ └── 1068.c │ ├── Exercise3a.c │ ├── Exercise5.c │ ├── Exercise3b.c │ ├── Exercise4.c │ └── Exercise1.c ├── 2.4 │ ├── Exercise4.pdf │ ├── Exercise7.pdf │ ├── Exercise11.c │ ├── LightOJ │ │ ├── 1294.c │ │ ├── 1069.c │ │ ├── 1001.c │ │ ├── 1022.c │ │ ├── 1072.c │ │ ├── 1053.c │ │ ├── 1216.c │ │ ├── 1015.c │ │ ├── 1305.c │ │ ├── 1116.c │ │ ├── 1202.c │ │ ├── 1136.c │ │ ├── 1107.c │ │ ├── 1008.c │ │ ├── 1010.c │ │ ├── 1211.c │ │ ├── 1331.c │ │ ├── 1010.md │ │ ├── 1182.md │ │ └── 1311.md │ ├── Exercise3.c │ ├── Exercise1.c │ ├── Exercise10.c │ ├── Exercise2.c │ ├── Exercise7.c │ ├── Exercise4.c │ ├── Timus │ │ ├── 1083.c │ │ ├── 1209.c │ │ ├── 1086.c │ │ └── 1209.md │ ├── Exercise6.c │ ├── Exercise5.c │ ├── Exercise12.c │ ├── Exercise13.c │ ├── Exercise9.c │ └── Exercise8.c ├── 2.1 │ └── Timus │ │ ├── 1293.c │ │ ├── 1000.c │ │ ├── 1264.c │ │ └── 1409.c ├── 2.2 │ ├── Exercise4.c │ ├── Exercise5.c │ ├── Exercise3.c │ ├── Exercise1.c │ ├── Exercise2.c │ └── Exercise6.c └── 2.5 │ ├── Exercise1.c │ ├── Exercise2.c │ ├── Timus │ ├── Timus1001.java │ └── Timus1014.java │ ├── Exercise12.java │ ├── Exercise13.java │ ├── Exercise6.java │ ├── Exercise7.java │ ├── Exercise10.java │ ├── Exercise8.java │ ├── Exercise5.java │ ├── Exercise11.java │ ├── Exercise4.java │ ├── Exercise3.c │ └── Exercise9.java ├── Timus ├── 1293.c ├── 1000.c ├── 1264.c ├── 1409.c ├── 1068.c ├── 1083.c ├── 1209.c ├── Timus1001.java ├── 1086.c ├── 1209.md └── Timus1014.java ├── UVa └── 100.c ├── README.md └── LICENSE /Cover.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/showrav-ansary/Programming-Contest-Data-Structure-and-Algorithm-by-Md.-Mahbubul-Hasan/HEAD/Cover.png -------------------------------------------------------------------------------- /LightOJ/1022/1022.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/showrav-ansary/Programming-Contest-Data-Structure-and-Algorithm-by-Md.-Mahbubul-Hasan/HEAD/LightOJ/1022/1022.png -------------------------------------------------------------------------------- /LightOJ/1072/1072.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/showrav-ansary/Programming-Contest-Data-Structure-and-Algorithm-by-Md.-Mahbubul-Hasan/HEAD/LightOJ/1072/1072.png -------------------------------------------------------------------------------- /LightOJ/1107/1107.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/showrav-ansary/Programming-Contest-Data-Structure-and-Algorithm-by-Md.-Mahbubul-Hasan/HEAD/LightOJ/1107/1107.png -------------------------------------------------------------------------------- /LightOJ/1211/1211.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/showrav-ansary/Programming-Contest-Data-Structure-and-Algorithm-by-Md.-Mahbubul-Hasan/HEAD/LightOJ/1211/1211.png -------------------------------------------------------------------------------- /LightOJ/1216/1216.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/showrav-ansary/Programming-Contest-Data-Structure-and-Algorithm-by-Md.-Mahbubul-Hasan/HEAD/LightOJ/1216/1216.png -------------------------------------------------------------------------------- /LightOJ/1433/1433.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/showrav-ansary/Programming-Contest-Data-Structure-and-Algorithm-by-Md.-Mahbubul-Hasan/HEAD/LightOJ/1433/1433.png -------------------------------------------------------------------------------- /LightOJ/1002/graph.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/showrav-ansary/Programming-Contest-Data-Structure-and-Algorithm-by-Md.-Mahbubul-Hasan/HEAD/LightOJ/1002/graph.png -------------------------------------------------------------------------------- /LightOJ/1002/graph2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/showrav-ansary/Programming-Contest-Data-Structure-and-Algorithm-by-Md.-Mahbubul-Hasan/HEAD/LightOJ/1002/graph2.png -------------------------------------------------------------------------------- /LightOJ/1202/1203pr.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/showrav-ansary/Programming-Contest-Data-Structure-and-Algorithm-by-Md.-Mahbubul-Hasan/HEAD/LightOJ/1202/1203pr.gif -------------------------------------------------------------------------------- /LightOJ/1305/Formula.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/showrav-ansary/Programming-Contest-Data-Structure-and-Algorithm-by-Md.-Mahbubul-Hasan/HEAD/LightOJ/1305/Formula.png -------------------------------------------------------------------------------- /Chapter 02/2.3/Exercise2.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(){ 4 | double n; 5 | scanf("%lf", &n); 6 | printf("%lf\n", n*(n+1)*((n+2)/6)); 7 | return 0; 8 | } -------------------------------------------------------------------------------- /Chapter 02/2.3/Exercise2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/showrav-ansary/Programming-Contest-Data-Structure-and-Algorithm-by-Md.-Mahbubul-Hasan/HEAD/Chapter 02/2.3/Exercise2.pdf -------------------------------------------------------------------------------- /Chapter 02/2.4/Exercise4.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/showrav-ansary/Programming-Contest-Data-Structure-and-Algorithm-by-Md.-Mahbubul-Hasan/HEAD/Chapter 02/2.4/Exercise4.pdf -------------------------------------------------------------------------------- /Chapter 02/2.4/Exercise7.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/showrav-ansary/Programming-Contest-Data-Structure-and-Algorithm-by-Md.-Mahbubul-Hasan/HEAD/Chapter 02/2.4/Exercise7.pdf -------------------------------------------------------------------------------- /LightOJ/1004/1004problem.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/showrav-ansary/Programming-Contest-Data-Structure-and-Algorithm-by-Md.-Mahbubul-Hasan/HEAD/LightOJ/1004/1004problem.png -------------------------------------------------------------------------------- /LightOJ/1072/problem1072.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/showrav-ansary/Programming-Contest-Data-Structure-and-Algorithm-by-Md.-Mahbubul-Hasan/HEAD/LightOJ/1072/problem1072.png -------------------------------------------------------------------------------- /LightOJ/1216/problem1216.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/showrav-ansary/Programming-Contest-Data-Structure-and-Algorithm-by-Md.-Mahbubul-Hasan/HEAD/LightOJ/1216/problem1216.png -------------------------------------------------------------------------------- /LightOJ/1305/1305problem.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/showrav-ansary/Programming-Contest-Data-Structure-and-Algorithm-by-Md.-Mahbubul-Hasan/HEAD/LightOJ/1305/1305problem.png -------------------------------------------------------------------------------- /Timus/1293.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int n, a, b; 6 | scanf("%d %d %d", &n, &a, &b); 7 | printf("%d \n", 2*a*b*n); 8 | return 0; 9 | } -------------------------------------------------------------------------------- /LightOJ/1022/problem-1022.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/showrav-ansary/Programming-Contest-Data-Structure-and-Algorithm-by-Md.-Mahbubul-Hasan/HEAD/LightOJ/1022/problem-1022.png -------------------------------------------------------------------------------- /LightOJ/1433/problem-1433.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/showrav-ansary/Programming-Contest-Data-Structure-and-Algorithm-by-Md.-Mahbubul-Hasan/HEAD/LightOJ/1433/problem-1433.png -------------------------------------------------------------------------------- /Chapter 02/2.1/Timus/1293.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int n, a, b; 6 | scanf("%d %d %d", &n, &a, &b); 7 | printf("%d \n", 2*a*b*n); 8 | return 0; 9 | } -------------------------------------------------------------------------------- /Timus/1000.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int operand1, operand2; 6 | scanf("%d %d", &operand1, &operand2); 7 | printf("%d\n", operand1 + operand2); 8 | return 0; 9 | } -------------------------------------------------------------------------------- /Timus/1264.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int operand1, operand2; 6 | scanf("%d %d", &operand1, &operand2); 7 | printf("%d\n", operand1*(++operand2)); 8 | return 0; 9 | } -------------------------------------------------------------------------------- /Chapter 02/2.1/Timus/1000.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int operand1, operand2; 6 | scanf("%d %d", &operand1, &operand2); 7 | printf("%d\n", operand1 + operand2); 8 | return 0; 9 | } -------------------------------------------------------------------------------- /Chapter 02/2.1/Timus/1264.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int operand1, operand2; 6 | scanf("%d %d", &operand1, &operand2); 7 | printf("%d\n", operand1*(++operand2)); 8 | return 0; 9 | } -------------------------------------------------------------------------------- /Chapter 02/2.2/Exercise4.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(){ 5 | printf("Enter the the value r: "); 6 | double r; 7 | scanf("%lf", &r); 8 | printf("The area is : %lf\n", 2*M_PI*r); 9 | return 0; 10 | } -------------------------------------------------------------------------------- /Timus/1409.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int harry, larry, total; 6 | scanf("%d %d", &harry, &larry); 7 | total = harry + larry - 1; 8 | printf("%d %d\n", (total-harry),(total-larry)); 9 | return 0; 10 | } -------------------------------------------------------------------------------- /Chapter 02/2.1/Timus/1409.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int harry, larry, total; 6 | scanf("%d %d", &harry, &larry); 7 | total = harry + larry - 1; 8 | printf("%d %d\n", (total-harry),(total-larry)); 9 | return 0; 10 | } -------------------------------------------------------------------------------- /Chapter 02/2.4/Exercise11.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | printf("Enter the value of n : "); 6 | int n; 7 | scanf("%d", &n); 8 | int result = 1; 9 | for (int i = n; i > 0; i--) 10 | result *= i; 11 | 12 | printf("%d", result); 13 | 14 | return 0; 15 | } -------------------------------------------------------------------------------- /Chapter 02/2.2/Exercise5.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(){ 5 | printf("Enter a non-negative number : "); 6 | double number; 7 | scanf("%lf", &number); 8 | printf("Closet integer to the square root of %lf is : %lf\n",number,round(sqrt(number))); 9 | return 0; 10 | } -------------------------------------------------------------------------------- /Chapter 02/2.4/LightOJ/1294.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() 3 | { 4 | int t; 5 | long n, m, sum; 6 | scanf("%d", &t); 7 | for (int i = 1; i <= t; i++) 8 | { 9 | scanf("%ld %ld", &n, &m); 10 | sum = (n / 2) * m; 11 | printf("Case %d: %ld\n", i, sum); 12 | } 13 | return 0; 14 | } -------------------------------------------------------------------------------- /Timus/1068.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int n; 6 | scanf("%d", &n); 7 | if (fabs(n) <= 10000) 8 | if (n > 0) 9 | printf("%d",n*(n+1)/2); 10 | else if (n == 0) 11 | printf("1"); 12 | else 13 | printf("%d",(2-n)*(n+1)/2); 14 | return 0; 15 | } -------------------------------------------------------------------------------- /Chapter 02/2.2/Exercise3.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(){ 5 | printf("Enter the the values a, b and c separated by a space: "); 6 | double a,b,c; 7 | scanf("%lf %lf %lf", &a, &b, &c); 8 | double s = (a+b+c)/2; 9 | printf("Area : %lf", sqrt(s*(s-a)*(s-b)*(s-c))); 10 | return 0; 11 | } -------------------------------------------------------------------------------- /Chapter 02/2.3/Timus/1068.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int n; 6 | scanf("%d", &n); 7 | if (fabs(n) <= 10000) 8 | if (n > 0) 9 | printf("%d",n*(n+1)/2); 10 | else if (n == 0) 11 | printf("1"); 12 | else 13 | printf("%d",(2-n)*(n+1)/2); 14 | return 0; 15 | } -------------------------------------------------------------------------------- /Chapter 02/2.4/Exercise3.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | int main() 4 | { 5 | printf("Enter the value of n : "); 6 | int n; 7 | scanf("%d", &n); 8 | int sum = 0; 9 | for (int iterator = 1; iterator <= n; iterator++) 10 | sum += pow(iterator, iterator); 11 | printf("%d\n", sum); 12 | return 0; 13 | } -------------------------------------------------------------------------------- /Chapter 02/2.4/LightOJ/1069.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | int t; 7 | scanf("%d", &t); 8 | for (int i = 1; i <= t; i++) 9 | { 10 | int p1, p2; 11 | scanf("%d %d", &p1, &p2); 12 | printf("Case %d: %d\n", i, 4 * (p1 + (int)fabs(p1 - p2)) + 19); 13 | } 14 | return 0; 15 | } -------------------------------------------------------------------------------- /Chapter 02/2.4/LightOJ/1001.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | int n; 7 | scanf("%d", &n); 8 | for (int i = 0; i < n; i++) 9 | { 10 | int k; 11 | scanf("%d", &k); 12 | int m = ceil(k / 2.0); 13 | int n = floor(k / 2.0); 14 | printf("%d %d\n", m, n); 15 | } 16 | return 0; 17 | } -------------------------------------------------------------------------------- /Chapter 02/2.4/Exercise1.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | printf("Enter the value of n : "); 6 | int n; 7 | scanf("%d", &n); 8 | int sum = 0; 9 | for (int iterator = 1; iterator <= n; iterator++) 10 | sum += iterator; 11 | printf("%d\n", sum); 12 | /* 13 | formula solution : printf("%d\n", n*(n+1)/2) 14 | */ 15 | return 0; 16 | } -------------------------------------------------------------------------------- /Chapter 02/2.4/Exercise10.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | printf("Enter the value of n : "); 6 | int n; 7 | scanf("%d", &n); 8 | int divisor = 0; 9 | for(int i = 1; i <= n; i++) 10 | if(n%i == 0) 11 | divisor++; 12 | if(divisor == 2) 13 | printf("Prime\n"); 14 | else 15 | printf("Not Prime\n"); 16 | return 0; 17 | } -------------------------------------------------------------------------------- /Chapter 02/2.4/Exercise2.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | printf("Enter the value of n : "); 6 | int n; 7 | scanf("%d", &n); 8 | int sum = 0; 9 | for (int iterator = 1; iterator <= n; iterator++) 10 | sum += iterator*iterator; 11 | printf("%d\n", sum); 12 | /* 13 | formula solution : printf("%d\n", n*(n+1)*(2n+1)/6) 14 | */ 15 | return 0; 16 | } -------------------------------------------------------------------------------- /Chapter 02/2.4/LightOJ/1022.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | int t; 7 | double pi = 2.0 * acos(0.0); 8 | scanf("%d", &t); 9 | for (int i = 1; i <= t; i++) 10 | { 11 | double r; 12 | scanf("%lf", &r); 13 | double area = (4 * r * r) - (pi * r * r); 14 | printf("Case %d: %.2lf\n", i, area); 15 | } 16 | return 0; 17 | } -------------------------------------------------------------------------------- /Chapter 02/2.5/Exercise1.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int a[31], n, i; 6 | printf("Enter the decimal number: "); 7 | scanf("%d", &n); 8 | for (i = 0; n > 0; i++) 9 | { 10 | a[i] = n % 2; 11 | n = n / 2; 12 | } 13 | printf("\nBinary Number : "); 14 | for (i = i - 1; i >= 0; i--) 15 | { 16 | printf("%d", a[i]); 17 | } 18 | return 0; 19 | } -------------------------------------------------------------------------------- /Chapter 02/2.3/Exercise3a.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(){ 5 | printf("Enter the the values of x1 : "); 6 | double x1; 7 | scanf("%lf",&x1); 8 | printf("Enter the the values of x2 : "); 9 | double x2; 10 | scanf("%lf",&x2); 11 | if(x1>x2) 12 | printf("%lf is greater!\n",x1); 13 | else 14 | printf("%lf is greater!\n",x2); 15 | return 0; 16 | } -------------------------------------------------------------------------------- /Chapter 02/2.2/Exercise1.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(){ 5 | printf("Enter the the values of x1 and y1 separated by a space: "); 6 | double x1, y1; 7 | scanf("%lf %lf", &x1, &y1); 8 | printf("Enter the the values of x2 and y2 separated by a space: "); 9 | double x2, y2; 10 | scanf("%lf %lf", &x2, &y2); 11 | printf("The distance is : %lf",sqrt(pow(x1-x2,2)+pow(y1-y2,2))); 12 | return 0; 13 | } -------------------------------------------------------------------------------- /Chapter 02/2.4/Exercise7.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | printf("Enter the value of n : "); 6 | int n; 7 | scanf("%d", &n); 8 | int sum = 0; 9 | int j = n; 10 | for (int i = 1; i <= n; i++) 11 | { 12 | sum += j * i; 13 | j--; 14 | } 15 | printf("%d\n", sum); 16 | 17 | /* 18 | formula solution: printf("%d\n", (n*n*n+3*n*n+2*n)/6); 19 | */ 20 | 21 | return 0; 22 | } -------------------------------------------------------------------------------- /Chapter 02/2.4/LightOJ/1072.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | int main() 4 | { 5 | 6 | int t; 7 | scanf("%d", &t); 8 | double pi = 2 * acos(0.0); 9 | for (int i = 1; i <= t; i++) 10 | { 11 | double R; 12 | int n; 13 | scanf("%lf %d", &R, &n); 14 | double r = (R * sin(pi / n * 1.0)) / (1 + sin(pi / n * 1.0)); 15 | printf("Case %d: %.10lf\n", i, r); 16 | } 17 | return 0; 18 | } -------------------------------------------------------------------------------- /Chapter 02/2.2/Exercise2.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(){ 5 | printf("Enter the the values a, b and c separated by a space: "); 6 | double a,b,c; 7 | scanf("%lf %lf %lf", &a, &b, &c); 8 | printf("Angle A : %lf rad\n", acos((b*b+c*c-a*a)/(2*b*c))); 9 | printf("Angle B : %lf rad\n", acos((-b*b+c*c+a*a)/(2*a*c))); 10 | printf("Angle C : %lf rad\n", acos((b*b-c*c+a*a)/(2*b*a))); 11 | return 0; 12 | } -------------------------------------------------------------------------------- /Timus/1083.c: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | int main() 4 | { 5 | char marks[20]; 6 | int n; 7 | scanf("%d%s", &n, marks); 8 | int k = strlen(marks); 9 | int result = 1; 10 | if (k >= n) 11 | result = n; 12 | else{ 13 | int sum = 1; 14 | for(int i = 0; (n-i*k) > 0 ;i++ ){ 15 | sum *=(n-i*k); 16 | } 17 | result = sum; 18 | } 19 | printf("%d", result); 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /Chapter 02/2.4/LightOJ/1053.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int t; 6 | scanf("%d", &t); 7 | for (int i = 1; i <= t; i++) 8 | { 9 | int a, b, c; 10 | scanf("%d %d %d", &a, &b, &c); 11 | if (a * a == b * b + c * c || c * c == a * a + b * b || b * b == a * a + c * c) 12 | printf("Case %d: yes\n", i); 13 | else 14 | printf("Case %d: no\n", i); 15 | } 16 | 17 | return 0; 18 | } -------------------------------------------------------------------------------- /Chapter 02/2.4/Exercise4.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | printf("Enter the value of n : "); 6 | int n; 7 | scanf("%d", &n); 8 | /* 9 | formula solution : printf("%d\n", n * (n * n * n + 2 * n * n + 3 * n + 2) / 8); 10 | */ 11 | int j = 1; 12 | int sum = 0; 13 | for(int i = 1; i<=n; i++) 14 | for(int k = 1; k <=i; k++) 15 | sum += j++; 16 | printf("%d\n", sum); 17 | 18 | return 0; 19 | } -------------------------------------------------------------------------------- /Chapter 02/2.4/LightOJ/1216.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | double pi, r3; 7 | pi = 2.0*acos(0.0); 8 | int t, r1, r2, h, p; 9 | scanf("%d", &t); 10 | for (int i = 1; i <= t; i++) 11 | { 12 | scanf("%d %d %d %d", &r1, &r2, &h, &p); 13 | r3 = p/(h * 1.0) * (r1 - r2) + r2; 14 | printf("Case %d: %.10lf\n", i, (pi / 3.0) * p * (r3 * r3 + r2 * r2 + (r3 * r2))); 15 | } 16 | return 0; 17 | } -------------------------------------------------------------------------------- /Chapter 02/2.4/Timus/1083.c: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | int main() 4 | { 5 | char marks[20]; 6 | int n; 7 | scanf("%d%s", &n, marks); 8 | int k = strlen(marks); 9 | int result = 1; 10 | if (k >= n) 11 | result = n; 12 | else{ 13 | int sum = 1; 14 | for(int i = 0; (n-i*k) > 0 ;i++ ){ 15 | sum *=(n-i*k); 16 | } 17 | result = sum; 18 | } 19 | printf("%d", result); 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /Chapter 02/2.4/LightOJ/1015.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int t; 6 | scanf("%d", &t); 7 | for (int i = 1; i <= t; i++) 8 | { 9 | int n; 10 | scanf("%d", &n); 11 | int sum = 0; 12 | for (int j = 1; j <= n; j++) 13 | { 14 | int value; 15 | scanf("%d", &value); 16 | if (value > 0) 17 | sum += value; 18 | } 19 | printf("Case %d: %d\n", i, sum); 20 | } 21 | return 0; 22 | } -------------------------------------------------------------------------------- /Chapter 02/2.3/Exercise5.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | printf("Enter the the values of x and y separated by a space: "); 6 | double x, y; 7 | scanf("%lf %lf", &x, &y); 8 | if (x >= 0) 9 | { 10 | if (y >= 0) 11 | printf("First\n"); 12 | else 13 | printf("Fourth\n"); 14 | } 15 | else 16 | { 17 | if (y >= 0) 18 | printf("Second\n"); 19 | else 20 | printf("Third\n"); 21 | } 22 | 23 | return 0; 24 | } -------------------------------------------------------------------------------- /Chapter 02/2.4/Exercise6.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | printf("Enter the value of n : "); 6 | int n; 7 | scanf("%d", &n); 8 | 9 | int j = 1; 10 | int sum = 0; 11 | for (int i = 1; i <= n; i++) 12 | { 13 | int innerTerm = 1; 14 | for (int k = 1; k <= i; k++){ 15 | for(int l = 1; l <=k; l++) 16 | innerTerm *= j++; 17 | sum += innerTerm; 18 | innerTerm = 1; 19 | } 20 | } 21 | printf("%d\n", sum); 22 | 23 | return 0; 24 | } -------------------------------------------------------------------------------- /Chapter 02/2.4/Exercise5.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | printf("Enter the value of n : "); 6 | int n; 7 | scanf("%d", &n); 8 | int sum = 0; 9 | int sign = 1; 10 | for (int iterator = 1; iterator <= n; iterator++) 11 | { 12 | sum += iterator * sign; 13 | sign *= -1; 14 | } 15 | /* 16 | no loop solution: 17 | if(n%2 == 0) 18 | printf("%d", ceil(-n/2.0)); 19 | else 20 | printf("%d", ceil(n/2.0)); 21 | */ 22 | printf("%d\n", sum); 23 | return 0; 24 | } -------------------------------------------------------------------------------- /Timus/1209.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | int main(){ 4 | int n; 5 | double m; 6 | scanf("%d",&n); 7 | 8 | for (int i = 0; i 0) 11 | if( sqrt(8.0*m -7) == (int)sqrt(8.0*m -7)) 12 | printf(" 1"); 13 | else 14 | printf(" 0"); 15 | else 16 | if(sqrt(8.0*m -7) == (int)sqrt(8.0*m -7)) 17 | printf("1"); 18 | else 19 | printf("0"); 20 | 21 | } 22 | return 0; 23 | } -------------------------------------------------------------------------------- /Chapter 02/2.2/Exercise6.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | int main(){ 4 | printf("Enter the the values of x1 and y1 separated by a space: "); 5 | double x1, y1; 6 | scanf("%lf %lf", &x1, &y1); 7 | printf("Enter the the values of x2 and y2 separated by a space: "); 8 | double x2, y2; 9 | scanf("%lf %lf", &x2, &y2); 10 | printf("Enter the the values of x3 and y3 separated by a space: "); 11 | double x3, y3; 12 | scanf("%lf %lf", &x3, &y3); 13 | printf("Area : %lf\n",fabs(.5*(x1*(y2-y3)+x2*(y3-y1)+x3*(y1-y2)))); 14 | return 0; 15 | } -------------------------------------------------------------------------------- /Chapter 02/2.4/Timus/1209.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | int main(){ 4 | int n; 5 | double m; 6 | scanf("%d",&n); 7 | 8 | for (int i = 0; i 0) 11 | if( sqrt(8.0*m -7) == (int)sqrt(8.0*m -7)) 12 | printf(" 1"); 13 | else 14 | printf(" 0"); 15 | else 16 | if(sqrt(8.0*m -7) == (int)sqrt(8.0*m -7)) 17 | printf("1"); 18 | else 19 | printf("0"); 20 | 21 | } 22 | return 0; 23 | } -------------------------------------------------------------------------------- /Chapter 02/2.4/Exercise12.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | printf("Enter the value of n : "); 6 | int n; 7 | scanf("%d", &n); 8 | printf("Enter the value of r : "); 9 | int r; 10 | scanf("%d", &r); 11 | int resultN = 1; 12 | int resultR = 1; 13 | int resultNminusR = 1; 14 | for(int i = 1; i <=n; i++){ 15 | resultN *= i; 16 | if(i <= r) 17 | resultR *= i; 18 | if(i <= (n-r)) 19 | resultNminusR *= i; 20 | } 21 | printf("%d\n", resultN/(resultR*resultNminusR)); 22 | 23 | return 0; 24 | } -------------------------------------------------------------------------------- /Chapter 02/2.4/LightOJ/1305.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int t, ax, ay, bx, by, cx, cy, dx, dy, a; 6 | scanf("%d", &t); 7 | for (int i = 1; i <= t; i++) 8 | { 9 | scanf("%d %d %d %d %d %d", &ax, &ay, &bx, &by, &cx, &cy); 10 | dx = ax + cx - bx; 11 | dy = ay + cy - by; 12 | a = ((ax * by) + (bx * cy) + (cx * dy) + (dx * ay)) - ((ay * bx) + (by * cx) + (cy * dx) + (dy * ax)); 13 | if (a < 0) 14 | a *= -1; 15 | a *= 0.5; 16 | printf("Case %d: %d %d %d\n", i, dx, dy, a); 17 | } 18 | return 0; 19 | } -------------------------------------------------------------------------------- /Chapter 02/2.3/Exercise3b.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | printf("Enter the the values of x1 : "); 7 | double x1; 8 | scanf("%lf", &x1); 9 | printf("Enter the the values of x2 : "); 10 | double x2; 11 | scanf("%lf", &x2); 12 | printf("Enter the the values of x3 : "); 13 | double x3; 14 | scanf("%lf", &x3); 15 | if (x1 > x2 && x1 > x3) 16 | printf("%lf is greater!\n", x1); 17 | else if (x2 > x3) 18 | printf("%lf is greater!\n", x2); 19 | else 20 | printf("%lf is greater!\n", x3); 21 | return 0; 22 | } -------------------------------------------------------------------------------- /Chapter 02/2.4/LightOJ/1116.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int t; 6 | long n, m, w; 7 | scanf("%d", &t); 8 | for (int i = 1; i <= t; i++) 9 | { 10 | scanf("%ld", &w); 11 | if (w % 2 == 0) 12 | { 13 | n = w / 2; 14 | m = 2; 15 | while (n % 2 == 0) 16 | { 17 | n /= 2; 18 | m *= 2; 19 | } 20 | printf("Case %d: %ld %ld\n", i, n, m); 21 | } 22 | else 23 | printf("Case %d: Impossible\n", i); 24 | } 25 | return 0; 26 | } -------------------------------------------------------------------------------- /Chapter 02/2.5/Exercise2.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(){ 5 | printf("Please enter size of the binary array\n" ); 6 | int size; 7 | scanf("%d", &size); 8 | int array[size]; 9 | 10 | int result = 0; 11 | 12 | printf("Input the binary digits separated by a space\n" ); 13 | for(int i = 0; i < size;i++) 14 | scanf("%d", &array[i]); 15 | 16 | int power = 0; 17 | for(int i = size - 1; i >= 0; i--, power++) 18 | result += array[i] * pow(2,power); 19 | 20 | printf("The decimal number is : %d\n", result); 21 | 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /Chapter 02/2.4/Exercise13.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | printf("Enter the value of n : "); 7 | int n; 8 | scanf("%d", &n); 9 | printf("Enter the value of x for 0 <= x <= Pi/2 : "); 10 | double x; 11 | scanf("%lf", &x); 12 | int sign = 1; 13 | long double sum = 0; 14 | for (int i = 0; i <= n; i++) 15 | { 16 | int factorial = 1; 17 | for (int j = 2*i; j > 0; j--) 18 | factorial *= j; 19 | sum += sign * (pow(x,2*i)/factorial); 20 | sign *= -1; 21 | } 22 | printf("%Lf",sum); 23 | 24 | return 0; 25 | } -------------------------------------------------------------------------------- /Chapter 02/2.4/LightOJ/1202.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | int main() 4 | { 5 | int cases, c1, r1, c2, r2, c, r; 6 | scanf("%d", &cases); 7 | for (int i = 1; i <= cases; i++) 8 | { 9 | scanf("%d%d%d%d", &r1, &c1, &r2, &c2); 10 | c = abs(c1 - c2); 11 | r = abs(r1 - r2); 12 | if (c == r) 13 | printf("Case %d: 1\n", i); 14 | else 15 | { 16 | if (c % 2 == r % 2) 17 | printf("Case %d: 2\n", i); 18 | else 19 | printf("Case %d: impossible\n", i); 20 | } 21 | } 22 | return 0; 23 | } -------------------------------------------------------------------------------- /Timus/Timus1001.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.InputStreamReader; 3 | import java.util.Scanner; 4 | import java.util.Stack; 5 | 6 | public class Timus1001 { 7 | public static void main(String[] args) { 8 | Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))); 9 | Stack numbers = new Stack(); 10 | while(in.hasNextLong()){ 11 | long number = in.nextLong(); 12 | numbers.push(number); 13 | } 14 | while(!numbers.empty()) 15 | System.out.printf("%.4f%n", Math.sqrt((double) numbers.pop())); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Chapter 02/2.5/Timus/Timus1001.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.InputStreamReader; 3 | import java.util.Scanner; 4 | import java.util.Stack; 5 | 6 | public class Timus1001 { 7 | public static void main(String[] args) { 8 | Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))); 9 | Stack numbers = new Stack(); 10 | while(in.hasNextLong()){ 11 | long number = in.nextLong(); 12 | numbers.push(number); 13 | } 14 | while(!numbers.empty()) 15 | System.out.printf("%.4f%n", Math.sqrt((double) numbers.pop())); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Chapter 02/2.4/LightOJ/1136.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | long long countNumbers(int n) 4 | { 5 | if (n == 0) 6 | return 0; 7 | int divisibles; 8 | if (n % 3 == 0) 9 | { 10 | divisibles = n / 3; 11 | } 12 | else 13 | { 14 | divisibles = (n / 3) + 1; 15 | } 16 | return n - divisibles; 17 | } 18 | 19 | int main() 20 | { 21 | int cases; 22 | long long A, B; 23 | scanf("%d", &cases); 24 | for (int test = 1; test <= cases; test++) 25 | { 26 | scanf("%lld %lld", &A, &B); 27 | long long result = countNumbers(B) - countNumbers(A - 1); 28 | printf("Case %d: %lld\n", test, result); 29 | } 30 | } -------------------------------------------------------------------------------- /Chapter 02/2.4/LightOJ/1107.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int t, x1, y1, x2, y2, m, x, y; 6 | scanf("%d", &t); 7 | for (int i = 1; i <= t; i++) 8 | { 9 | scanf("%d", &x1); 10 | scanf("%d", &y1); 11 | scanf("%d", &x2); 12 | scanf("%d", &y2); 13 | scanf("%d", &m); 14 | printf("Case %d:\n", i); 15 | for (int j = 1; j <= m; j++) 16 | { 17 | scanf("%d", &x); 18 | scanf("%d", &y); 19 | if (x >= x1 && x <= x2 && y >= y1 && y <= y2) 20 | printf("Yes\n"); 21 | else 22 | printf("No\n"); 23 | } 24 | } 25 | return 0; 26 | } -------------------------------------------------------------------------------- /Chapter 02/2.3/Exercise4.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | printf("Enter the the values of x1 : "); 7 | double x1; 8 | scanf("%lf", &x1); 9 | printf("Enter the the values of x2 : "); 10 | double x2; 11 | scanf("%lf", &x2); 12 | printf("Enter the the values of x3 : "); 13 | double x3; 14 | scanf("%lf", &x3); 15 | if (x1 < x2 && x1 < x3) 16 | { 17 | printf("%lf", x1); 18 | if (x2 < x3) 19 | printf(" %lf %lf\n", x2, x3); 20 | else 21 | printf(" %lf %lf\n", x3, x2); 22 | } 23 | else if (x2 < x3 && x1 > x3) 24 | printf("%lf %lf %lf\n", x2, x3, x1); 25 | else 26 | printf("%lf %lf %lf\n", x3, x1, x2); 27 | return 0; 28 | } -------------------------------------------------------------------------------- /Chapter 02/2.4/Exercise9.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | printf("Enter the value of n : "); 6 | long long n, currentPalindromeNo = 1; 7 | scanf("%lld", &n); 8 | long long currentlyConsidering = 1; 9 | while (currentPalindromeNo != n) 10 | { 11 | long long workingWith = currentlyConsidering; 12 | long long reversed = 0; 13 | while (workingWith != 0) 14 | { 15 | reversed = reversed * 10; 16 | reversed = reversed + workingWith % 10; 17 | workingWith = workingWith / 10; 18 | } 19 | if(currentlyConsidering == reversed) 20 | currentPalindromeNo++; 21 | currentlyConsidering++; 22 | } 23 | printf("%d", currentlyConsidering-1); 24 | return 0; 25 | } -------------------------------------------------------------------------------- /Chapter 02/2.3/Exercise1.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(){ 4 | printf("Enter the term number : "); 5 | int n; 6 | scanf("%d", &n); 7 | if(n<11) 8 | printf("%d\n",n-1); 9 | else if(n<20) 10 | printf("%d\n",(n%10)*11); 11 | else if(n<30) 12 | printf("%d\n",(n%20)*10+101); 13 | else if(n<40) 14 | printf("%d\n",(n%30)*10+202); 15 | else if(n<50) 16 | printf("%d\n",(n%40)*10+303); 17 | else if(n<60) 18 | printf("%d\n",(n%50)*10+404); 19 | else if(n<70) 20 | printf("%d\n",(n%60)*10+505); 21 | else if(n<80) 22 | printf("%d\n",(n%70)*10+606); 23 | else if(n<90) 24 | printf("%d\n",(n%80)*10+707); 25 | else if(n<100) 26 | printf("%d\n",(n%90)*10+808); 27 | return 0; 28 | } -------------------------------------------------------------------------------- /Chapter 02/2.5/Exercise12.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.InputStreamReader; 3 | import java.util.Scanner; 4 | 5 | public class Exercise12 { 6 | public static void main(String[] args) { 7 | Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))); 8 | System.out.println("Enter date: DD/MM/YYYY"); 9 | String date = in.nextLine(); 10 | String[] informations = date.split("/"); 11 | int day = Integer.parseInt(informations[0]); 12 | int month = Integer.parseInt(informations[1]); 13 | int year = Integer.parseInt(informations[2]); 14 | System.out.println( 15 | "Day: " + day + "\n" + 16 | "Month: " + month + "\n" + 17 | "Year: " + year 18 | ); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Chapter 02/2.4/LightOJ/1008.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | int cases; 7 | scanf("%d", &cases); 8 | for (int i = 1; i <= cases; i++) 9 | { 10 | long long seconds, root, lackings, row, column; 11 | scanf("%lld", &seconds); 12 | root = ceil(sqrt(seconds * 1.0)); 13 | lackings = root * root - seconds; 14 | if (lackings < root){ 15 | row = root; 16 | column = lackings + 1; 17 | } 18 | else{ 19 | column = root; 20 | row = seconds - (root-1) * (root-1); 21 | } 22 | if(root % 2 == 0){ 23 | long long temp = column; 24 | column = row; 25 | row = temp; 26 | } 27 | printf("Case %d: %lld %lld\n",i, column, row); 28 | } 29 | 30 | return 0; 31 | } -------------------------------------------------------------------------------- /Chapter 02/2.5/Exercise13.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.InputStreamReader; 3 | import java.util.Scanner; 4 | 5 | public class Exercise13 { 6 | public static void main(String[] args) { 7 | Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))); 8 | System.out.println("Enter string A:"); 9 | String a = in.nextLine(); 10 | System.out.println("Enter string B:"); 11 | String b = in.nextLine(); 12 | int indexB = 0; 13 | for(int i = 0; i < a.length() && indexB < b.length();i++) 14 | if(a.charAt(i) == b.charAt(indexB)) 15 | indexB++; 16 | if(indexB == b.length()) 17 | System.out.println("B is a substring of A"); 18 | else 19 | System.out.println("B is not a substring of A"); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Timus/1086.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int Prime[15000], nPrime; 5 | int mark[1048576]; 6 | 7 | int main() 8 | { 9 | 10 | int limit = sqrt(1048576) + 2; 11 | mark[0] = 1; 12 | 13 | for (int i = 4; i < 1048576; i += 2) 14 | mark[i] = 1; 15 | 16 | Prime[nPrime++] = 2; 17 | 18 | for (int i = 3; i < 1048576; i += 2) 19 | { 20 | if (nPrime == 15000) 21 | break; 22 | if (!mark[i]) 23 | { 24 | Prime[nPrime++] = i; 25 | if (i <= limit) 26 | for (int j = i * i; j < 1048576; j += i * 2) 27 | mark[j] = 1; 28 | } 29 | } 30 | int k; 31 | scanf("%d", &k); 32 | int num; 33 | for (int i = 0; i < k; i++) 34 | { 35 | scanf("%d", &num); 36 | printf("%d\n", Prime[num - 1]); 37 | } 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /Chapter 02/2.4/Timus/1086.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int Prime[15000], nPrime; 5 | int mark[1048576]; 6 | 7 | int main() 8 | { 9 | 10 | int limit = sqrt(1048576) + 2; 11 | mark[0] = 1; 12 | 13 | for (int i = 4; i < 1048576; i += 2) 14 | mark[i] = 1; 15 | 16 | Prime[nPrime++] = 2; 17 | 18 | for (int i = 3; i < 1048576; i += 2) 19 | { 20 | if (nPrime == 15000) 21 | break; 22 | if (!mark[i]) 23 | { 24 | Prime[nPrime++] = i; 25 | if (i <= limit) 26 | for (int j = i * i; j < 1048576; j += i * 2) 27 | mark[j] = 1; 28 | } 29 | } 30 | int k; 31 | scanf("%d", &k); 32 | int num; 33 | for (int i = 0; i < k; i++) 34 | { 35 | scanf("%d", &num); 36 | printf("%d\n", Prime[num - 1]); 37 | } 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /Chapter 02/2.5/Exercise6.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.InputStreamReader; 3 | import java.util.Scanner; 4 | 5 | public class Exercise6{ 6 | 7 | private static int GetLengthOfStringWithCharArray(String string){ 8 | int length = 0; 9 | char[] charArray = string.toCharArray(); 10 | for(char character : charArray){ 11 | length++; 12 | } 13 | return length; 14 | } 15 | 16 | public static void main(String[] args) { 17 | Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))); 18 | System.out.println("Enter the input : "); 19 | String input = in.nextLine(); 20 | 21 | System.out.println("Result is (using `.length()`) : " + input.length()); 22 | System.out.println("Result is (custom method) : " + GetLengthOfStringWithCharArray(input)); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Chapter 02/2.4/LightOJ/1010.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(void) 4 | { 5 | int cases; 6 | 7 | scanf("%d", &cases); 8 | 9 | for (int i = 0; i < cases; i++) 10 | { 11 | int m, n, knights = 0; 12 | scanf("%d %d", &m, &n); 13 | 14 | int max = n; 15 | if (m > n) 16 | max = m; 17 | 18 | if (m == 1 || n == 1) 19 | knights = max; 20 | else if (m == 2 || n == 2) 21 | { 22 | knights = (max / 4) * 4; 23 | 24 | if (max % 4 == 1) 25 | { 26 | knights += 2; 27 | } 28 | else if (max % 4 > 1) 29 | { 30 | knights += 4; 31 | } 32 | } 33 | else 34 | { 35 | knights = ((m * n) + 1) / 2; 36 | } 37 | 38 | printf("Case %d: %d\n", i + 1, knights); 39 | } 40 | } -------------------------------------------------------------------------------- /Chapter 02/2.5/Exercise7.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.InputStreamReader; 3 | import java.util.Scanner; 4 | 5 | public class Exercise7{ 6 | 7 | public static void main(String[] args) { 8 | Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))); 9 | System.out.println("Enter the input : "); 10 | String input = in.nextLine(); 11 | 12 | int upperCase = 0; 13 | int lowerCase = 0; 14 | char[] characterArray = input.toCharArray(); 15 | for(char character : characterArray){ 16 | if(character >= 65 && character <= 90) 17 | upperCase++; 18 | else if(character >= 97 && character <= 122) 19 | lowerCase++; 20 | } 21 | 22 | System.out.println("Lower case : " + lowerCase); 23 | System.out.println("Upper case : " + upperCase); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Chapter 02/2.5/Exercise10.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.InputStreamReader; 3 | import java.util.Scanner; 4 | 5 | public class Exercise10 { 6 | public static void main(String[] args) { 7 | Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))); 8 | System.out.println("Enter the text: "); 9 | String text = in.nextLine(); 10 | boolean spaceStart = true; 11 | boolean spaceEnd = false; 12 | int wordCount = 0; 13 | for(int i = 0; i < text.length(); i++) { 14 | if(text.charAt(i) == ' ') { 15 | spaceEnd = false; 16 | spaceStart = true; 17 | } else { 18 | spaceEnd = true; 19 | if(spaceStart && spaceEnd) { 20 | wordCount++; 21 | spaceStart = false; 22 | } 23 | } 24 | } 25 | System.out.println(wordCount); 26 | } 27 | 28 | } -------------------------------------------------------------------------------- /UVa/100.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int i, j; 6 | 7 | while (scanf("%d %d", &i, &j) != EOF) 8 | { 9 | 10 | int tempI = i; 11 | int tempJ = j; 12 | 13 | if (i > j) 14 | { 15 | int temp = i; 16 | i = j; 17 | j = temp; 18 | } 19 | 20 | int maxLength = 0; 21 | int currentLength; 22 | 23 | while (i <= j) 24 | { 25 | unsigned int n = i; 26 | currentLength = 1; 27 | 28 | while (n != 1) 29 | { 30 | if (n % 2 == 1) 31 | n = 3 * n + 1; 32 | else 33 | n /= 2; 34 | currentLength++; 35 | } 36 | 37 | if (currentLength > maxLength) 38 | maxLength = currentLength; 39 | 40 | i++; 41 | } 42 | 43 | printf("%d %d %d\n", tempI, tempJ, maxLength); 44 | } 45 | 46 | return 0; 47 | } -------------------------------------------------------------------------------- /Timus/1209.md: -------------------------------------------------------------------------------- 1 | ### Prerequisite: 2 | * Knowledge of [Triangular Numbers](https://en.wikipedia.org/wiki/Triangular_number). 3 | 4 | ### Solution: 5 | 6 | Let's take a sequence: 7 | 8 | `1101001000` (from 100, appended upto 103) 9 |

10 | Let us observe the positions of `1` by appending in such a way: 11 | 12 | |Place|1|2|3|4|5|6|7|8|9|10| 13 | |-|-|-|-|-|-|-|-|-|-|-| 14 | |Digit|1|1|0|1|0|0|1|0|0|0| 15 | 16 |

17 | Let us now try to determine the position of `1`s, 18 | 19 | If we observe the positon of `1`s, their position in this kind of appended string is actually : 20 | 21 | ( (__T__Number of 0s) + __1__ )-th positon. 22 | Where, __Ti__ denotes the i-th triangular number. 23 | 24 |
25 | For example: 26 | 27 | In case of the `1` in `7`th position, it was obtained by appending __103__. 28 | 29 | Number of `0`s for (103 ) = __3__. 30 | 31 | __T3__ = 6 and (__T3__ +__1__) = __7__, which is the correct position of `1`. 32 | -------------------------------------------------------------------------------- /Chapter 02/2.5/Exercise8.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.InputStreamReader; 3 | import java.util.Scanner; 4 | 5 | public class Exercise8{ 6 | 7 | public static void main(String[] args) { 8 | Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))); 9 | 10 | System.out.println("Enter the input 1 : "); 11 | String input1 = in.nextLine(); 12 | System.out.println("Enter the input 2 : "); 13 | String input2 = in.nextLine(); 14 | 15 | // String result = input1 + input2; 16 | String resultConcat = input1.concat(input2); 17 | 18 | String result = ""; 19 | for(char x : input1.toCharArray()) 20 | result += Character.toString(x); 21 | 22 | for(char x : input2.toCharArray()) 23 | result += Character.toString(x); 24 | 25 | 26 | System.out.println("Result (using concat operator) : " + resultConcat); 27 | System.out.println("Result (joining characters) : " + result); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Chapter 02/2.4/Timus/1209.md: -------------------------------------------------------------------------------- 1 | ### Prerequisite: 2 | * Knowledge of [Triangular Numbers](https://en.wikipedia.org/wiki/Triangular_number). 3 | 4 | ### Solution: 5 | 6 | Let's take a sequence: 7 | 8 | `1101001000` (from 100, appended upto 103) 9 |

10 | Let us observe the positions of `1` by appending in such a way: 11 | 12 | |Place|1|2|3|4|5|6|7|8|9|10| 13 | |-|-|-|-|-|-|-|-|-|-|-| 14 | |Digit|1|1|0|1|0|0|1|0|0|0| 15 | 16 |

17 | Let us now try to determine the position of `1`s, 18 | 19 | If we observe the positon of `1`s, their position in this kind of appended string is actually : 20 | 21 | ( (__T__Number of 0s) + __1__ )-th positon. 22 | Where, __Ti__ denotes the i-th triangular number. 23 | 24 |
25 | For example: 26 | 27 | In case of the `1` in `7`th position, it was obtained by appending __103__. 28 | 29 | Number of `0`s for (103 ) = __3__. 30 | 31 | __T3__ = 6 and (__T3__ +__1__) = __7__, which is the correct position of `1`. 32 | -------------------------------------------------------------------------------- /Chapter 02/2.5/Exercise5.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.InputStreamReader; 3 | import java.util.Scanner; 4 | 5 | 6 | public class Exercise5{ 7 | public static void main(String[] args) { 8 | Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))); 9 | System.out.println("Enter the number of inputs : "); 10 | int length = in.nextInt(); 11 | 12 | int[] sumArray = new int[length]; 13 | 14 | System.out.println("Enter a number : "); 15 | sumArray[0] = in.nextInt(); 16 | 17 | for(int i = 1; i < length; i++){ 18 | System.out.println("Enter a number : "); 19 | sumArray[i] = in.nextInt() + sumArray[i-1]; 20 | } 21 | 22 | System.out.println("Enter the value of i (starting from 0) : "); 23 | int i = in.nextInt(); 24 | 25 | System.out.println("Enter the value of j (starting from 0) : "); 26 | int j = in.nextInt(); 27 | 28 | int result = 0; 29 | 30 | if(i == 0) 31 | result = sumArray[j]; 32 | else 33 | result = sumArray[j] - sumArray[i-1]; 34 | 35 | System.out.println("Result is : " + result); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Chapter 02/2.4/LightOJ/1211.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int t, n, x1, y1, z1, x2, y2, z2, xCommon, yCommon, zCommon; 6 | 7 | scanf("%d", &t); 8 | for (int i = 1; i <= t; i++) 9 | { 10 | int xFar = 0, yFar = 0, zFar = 0; 11 | int xNear = 1001, yNear = 1001, zNear = 1001; 12 | scanf("%d", &n); 13 | for (int j = 1; j <= n; j++) 14 | { 15 | scanf("%d %d %d %d %d %d", &x1, &y1, &z1, &x2, &y2, &z2); 16 | 17 | if (x1 > xFar) 18 | xFar = x1; 19 | 20 | if (y1 > yFar) 21 | yFar = y1; 22 | 23 | if (z1 > zFar) 24 | zFar = z1; 25 | 26 | if (x2 < xNear) 27 | xNear = x2; 28 | 29 | if (y2 < yNear) 30 | yNear = y2; 31 | 32 | if (z2 < zNear) 33 | zNear = z2; 34 | } 35 | xCommon = (xNear - xFar); 36 | yCommon = (yNear - yFar); 37 | zCommon = (zNear - zFar); 38 | 39 | if (xCommon > 0 && yCommon > 0 && zCommon > 0) 40 | printf("Case %d: %d\n", i, xCommon * yCommon * zCommon); 41 | else 42 | printf("Case %d: 0\n", i); 43 | } 44 | return 0; 45 | } -------------------------------------------------------------------------------- /Chapter 02/2.5/Exercise11.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.InputStreamReader; 3 | import java.util.Scanner; 4 | 5 | 6 | public class Exercise11 { 7 | public static void main(String[] args) { 8 | Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))); 9 | System.out.println("Enter string 1: "); 10 | String string1 = in.nextLine(); 11 | System.out.println("Enter string 2: "); 12 | String string2 = in.nextLine(); 13 | for(int i = 0; i < string1.length() && i < string2.length(); i++) { 14 | if(string1.charAt(i) < string2.charAt(i)) { 15 | System.out.println(string1 + " is lexiographically smaller."); 16 | break; 17 | }else if (string1.charAt(i) > string2.charAt(i)){ 18 | System.out.println(string2 + " is lexiographically smaller."); 19 | break; 20 | }else if (i == string1.length() - 1) { 21 | System.out.println(string1 + " is lexiographically smaller."); 22 | break; 23 | }else if (i == string2.length() -1){ 24 | System.out.println(string2 + " is lexiographically smaller."); 25 | break; 26 | } 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Timus/Timus1014.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.InputStreamReader; 3 | import java.util.Scanner; 4 | 5 | import java.util.Vector; 6 | 7 | public class Timus1014 { 8 | 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))); 11 | int number = in.nextInt(); 12 | 13 | // corner case 1 : n == 0 14 | if(number == 0) 15 | System.out.println(10); 16 | 17 | // corner case 2 : n == 1 18 | else if (number == 1) 19 | System.out.println(number); 20 | 21 | else{ 22 | Vector digits = new Vector<>(); 23 | for(int i = 9; i >= 2; i--){ 24 | while(number%i == 0){ 25 | digits.add(i); 26 | number /= i; 27 | } 28 | } 29 | 30 | // Reaching 1 means we have divided by all the digit factors possible within the range of 2 to 9, not a prime 31 | if(number == 1) 32 | for(int index = digits.size()-1; index >= 0; index--) 33 | System.out.print(digits.get(index)); 34 | // Prime number, thus reaching 1 was not possible 35 | else 36 | System.out.println(-1); 37 | 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Chapter 02/2.5/Timus/Timus1014.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.InputStreamReader; 3 | import java.util.Scanner; 4 | 5 | import java.util.Vector; 6 | 7 | public class Timus1014 { 8 | 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))); 11 | int number = in.nextInt(); 12 | 13 | // corner case 1 : n == 0 14 | if(number == 0) 15 | System.out.println(10); 16 | 17 | // corner case 2 : n == 1 18 | else if (number == 1) 19 | System.out.println(number); 20 | 21 | else{ 22 | Vector digits = new Vector<>(); 23 | for(int i = 9; i >= 2; i--){ 24 | while(number%i == 0){ 25 | digits.add(i); 26 | number /= i; 27 | } 28 | } 29 | 30 | // Reaching 1 means we have divided by all the digit factors possible within the range of 2 to 9, not a prime 31 | if(number == 1) 32 | for(int index = digits.size()-1; index >= 0; index--) 33 | System.out.print(digits.get(index)); 34 | // Prime number, thus reaching 1 was not possible 35 | else 36 | System.out.println(-1); 37 | 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Chapter 02/2.4/LightOJ/1331.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | double GetArea(double radius, double angle) 4 | { 5 | return 0.5 * radius * radius * angle; // Partial area formula 6 | } 7 | 8 | double GetAngle(double a, double b, double c) 9 | { 10 | return acos(((b * b) + (c * c) - (a * a)) / (2 * b * c)); // Oppposite angle formula 11 | } 12 | 13 | int main() 14 | { 15 | int testCases; 16 | double radius1, radius2, radius3, angleByCircle1, angleByCircle2, angleByCircle3, areaByCircle1, areaByCircle2, areaByCircle3, areaTriangle; 17 | scanf("%d", &testCases); 18 | 19 | for (int testCase = 1; testCase <= testCases; testCase++) 20 | { 21 | scanf("%lf %lf %lf", &radius1, &radius2, &radius3); 22 | 23 | // Calculate the angle created by each straight line that connects each pair of circles' centers 24 | angleByCircle3 = GetAngle(radius1 + radius2, radius2 + radius3, radius3 + radius1); 25 | angleByCircle1 = GetAngle(radius2 + radius3, radius3 + radius1, radius1 + radius2); 26 | angleByCircle2 = GetAngle(radius3 + radius1, radius1 + radius2, radius2 + radius3); 27 | 28 | // Calculate the area of the triangle 29 | double s = (radius1 + radius2 + radius3); 30 | areaTriangle = sqrt(s * (s - radius1 - radius2) * (s - radius2 - radius3) * (s - radius3 - radius1)); 31 | 32 | // Deduct area taken by the three circles 33 | areaTriangle -= GetArea(radius3, angleByCircle3); 34 | areaTriangle -= GetArea(radius1, angleByCircle1); 35 | areaTriangle -= GetArea(radius2, angleByCircle2); 36 | 37 | printf("Case %d: %lf\n", testCase, areaTriangle); 38 | } 39 | } -------------------------------------------------------------------------------- /LightOJ/1022/en.md: -------------------------------------------------------------------------------- 1 | # LOJ 1022 - Circle in Square # 2 | --- 3 | A circle is placed perfectly into a square. The term perfectly placed means that each side of the square is touched by the circle, but the circle doesn't have any overlapping part with the square. See the picture below. 4 | 5 |

6 | 7 | Now you are given the radius of the circle. You have to find the area of the shaded region (blue part). Assume that `pi = 2 * acos (0.0)` (acos means cos inverse). 8 | 9 | ### Input ### 10 | 11 | Input starts with an integer _T (≤ 1000)_, denoting the number of test cases. 12 | 13 | Each case contains a floating point number _r (0 < r ≤ 1000)_ denoting the radius of the circle. __And you can assume that _r_ contains at most four digits after the decimal point__. 14 | 15 | ### Output ### 16 | 17 | For each case, print the case number and the shaded area rounded to two places after the decimal point. 18 | 19 | ## Solution ## 20 | 21 |

22 | 23 | We know that the `area of a square = (length of any side)²` and the `area of a circle = π*(radius)²`. Here the `length of any side of the square = 2*radius of the circle`. We can easily calculate the `area of the blue part` 24 | 25 | ``` 26 | area of the blue part = area of the square - area of the circle 27 | = (2*r)² - π*r² 28 | ``` 29 | The above implementation is `accepted`. 30 | 31 | 32 | ## Solution in C ## 33 | 34 | ```c 35 | #include 36 | #include 37 | 38 | int main() 39 | { 40 | int t; 41 | double pi = 2.0 * acos(0.0); 42 | scanf("%d", &t); 43 | for (int i = 1; i <= t; i++) 44 | { 45 | double r; 46 | scanf("%lf", &r); 47 | double area = (2 * r * 2 * r) - (pi * r * r); 48 | printf("Case %d: %.2lf\n", i, area); 49 | } 50 | return 0; 51 | } 52 | ``` -------------------------------------------------------------------------------- /Chapter 02/2.5/Exercise4.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.InputStreamReader; 3 | import java.util.Scanner; 4 | 5 | 6 | public class Exercise4{ 7 | // The question has asked to do it by an array. So, we are taking it. 8 | 9 | private static int GetResult(int[] array){ 10 | int result = 0; 11 | int currentConsecutiveOnes = 0; 12 | for(int i = 0; i < array.length; i++){ 13 | if(array[i] == 1) 14 | currentConsecutiveOnes++; 15 | else 16 | currentConsecutiveOnes = 0; 17 | if(currentConsecutiveOnes > result) 18 | result = currentConsecutiveOnes; 19 | } 20 | return result; 21 | } 22 | 23 | public static void main(String[] args) { 24 | Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))); 25 | System.out.println("Enter the length of the array : "); 26 | int length = in.nextInt(); 27 | 28 | int[] inputs = new int[length]; 29 | 30 | // Could have done without the array if we are taking direct inputs 31 | // int currentConsecutiveOnes = 0; 32 | // int currentMax = 0; 33 | for(int i = 0; i < length; i++){ 34 | System.out.println("Enter a bit (1/0) : "); 35 | inputs[i] = in.nextInt(); 36 | /* If we choose not to take the array 37 | int input = in.nextInt(); 38 | if(input==0){ 39 | if(currentConsecutiveOnes > currentMax) 40 | currentMax = currentConsecutiveOnes; 41 | currentConsecutiveOnes = 0; 42 | }else{ 43 | currentConsecutiveOnes++; 44 | }*/ 45 | 46 | } 47 | System.out.println("Number of max consecutive ones : " 48 | + GetResult(inputs)); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Programming Contest: Data Structure & Algorithm by Md. Mahbubul Hasan (June, 2016) # 2 | --- 3 |

4 | 5 | 6 | This repo contains solutions to the problems and exercises provided in __প্রোগ্রামিং কন্টেস্ট : ডেটা স্ট্রাকচার ও অ্যালগরিদম__ by __মোঃ মাহবুবুল হাসান__ (2016). You are highly discouraged to look through the solutions without trying out a problem by yourself first. 7 | 8 | 9 | ## Guidelines for Contributor 10 | 11 | You are more than welcome to contribute and fix. Do standard `issue` > `branch out` > `pull request`. 12 | * Accepted programming languages : `Haskell`, `Java`, `C`, `C++`, `C#`, `Python`, `Go`, `JavaScript` and `Rust`. 13 | * Explanation languages : `English` and `Bengali`. 14 | * Explanation document : `PDF` and `Markdown` 15 | 16 | 17 | Please raise an `issue` first then do a `pull request` later upon implementing it. Your unresponded `issue` will be closed after `30` days if you are unavailable. 18 | 19 | Coding guidelines: 20 | 21 | * __USE PROPER VARIABLE/FUNCTION/METHOD NAMING__. 22 | * Do proper indentation. 23 | * Add comments so that people can relate to the explanations. 24 | * Follow the standards of your language. 25 | * If you are using a data structure specific to your language, mention the `insertion`/`deletion`/`mutation`/`look up`/`prepend`/`append` costs. 26 | * Include the driver code in the same file. 27 | 28 | ## Disclaimer 29 | 30 | [LightOJ](https://lightoj.com/home), [Codeforces](https://codeforces.com/), [Timus](https://acm.timus.ru/), [UVa](https://onlinejudge.org/), [Codechef](https://www.codechef.com/) and other online judges have their own copyright and agreements. Go through them if you want to copy any content directly from them. 31 | 32 | --- 33 | If you have any queries or want to get in touch with me, you can open a `Discussion` or simply `mail` me at `showrav.ansary.bd@gmail.com` or give me a knock at LinkedIn. 34 | -------------------------------------------------------------------------------- /Chapter 02/2.4/LightOJ/1010.md: -------------------------------------------------------------------------------- 1 | Contributed By : [Perdente](https://github.com/Perdente) on [LightOJ](https://lightoj.com/home) 2 | 3 | ### LOJ-1010 - Knights in Chessboard 4 | 5 | In this problem you are given "T" test cases where "n" and "m" are rows and columns respectively.For each test cases you have to print the total empty spaces for Two knights to place without attacking each other. 6 | 7 | Knights in the board travel in "L" shape.In this problem there are 3 cases mainly considerable. 8 | 9 | - **Case 1:** If any of the rows or columns is 1 then there is no "L" shaped formed. So answer is max of row and column. 10 | 11 | 12 | ![Knight-in-1-row](https://user-images.githubusercontent.com/58706003/99261396-df0e2500-2846-11eb-8b94-a99262f2a46a.jpg) 13 | 14 | - **Case 2:** If rows and columns are greater then 2 then just half the total of squares is the answer. 15 | 16 | - **Case 3:**(most important case) If either of the row or column is 2 then we just divide the total squares by 8 where 1st 4 blocks can be placed by knights and other 4 blocks are forbidden.The remaining blocks(if any) if less then or equals 4 then remaining blocks are added to the answer and if greater then we add 4 to the answer. 17 | 18 | 19 | ![Knight-in-2-row](https://user-images.githubusercontent.com/58706003/99261602-21cffd00-2847-11eb-9f34-43bde191856e.jpg) 20 | 21 | 22 | Code: 23 | ### C++ 24 | ----- 25 | ```cpp 26 | #include 27 | using namespace std; 28 | #define int long long int 29 | #define ll long long 30 | const int N=1e5+5; 31 | signed main() 32 | { 33 | ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); 34 | int t;cin>>t; 35 | int i=1; 36 | while(t--) 37 | { 38 | int n,m; 39 | cin>>n>>m; 40 | if(m==1 or n==1) 41 | { 42 | cout<<"Case "<=4?4:(m*n)%8)<9, 1 ≤ m)_. And you can assume that _n_ is divisible by _2*m_. 16 | 17 | 18 | ### Output 19 | 20 | For each case, print the case number and the summation separated by a space. 21 | 22 | ## Solution 23 | 24 | The problem statement has confirmed that `n = 2*m`. Which means that the series is __always possible__ to be split up in _pairs_. Let's observe the `series` for example of `n = 12` and `m = 3` : 25 | ``` 26 | Series = - 1 - 2 - 3 + 4 + 5 + 6 - 7 - 8 - 9 + 10 + 11 + 12 27 | = (4-1) + (5-2) + (6-3) + (10-7) + (11-8) + (12-9) 28 | = 3 + 3 + 3 + 3 + 3 + 3 29 | = 3 * 6 30 | = 18 31 | ``` 32 | In the above observation, we can see that each pair produced _3_ and here `3 = m`. More clearly, `i-th positive number` + `i-th negative number` = `m`. Examples: 1st positive number is `4` and 1st negative number is `-1` and `4 + (-1) = 3`. And since the problem has stated that `n = 2*m`, we are sure to find a `i-th postive number` for a corresponding `i-th negative number`. Also, _3_ has occured _6_ times where, `6 = 12/2 = n/2`. So, the `sum = 18 = 6*3 = (n/2)*m`. 33 | 34 | __Caution__ : Remember, we need `long` or similar data type that can hold integer values more than 109 because even if `n` and `m` alone does not need any data type more than 109, but `n*m` does! 35 | 36 | The above implementation is `accepted`. 37 | 38 | ## Solution in C 39 | 40 | ```c 41 | #include 42 | int main() 43 | { 44 | int t; 45 | long n, m, sum; 46 | scanf("%d", &t); 47 | for (int i = 1; i <= t; i++) 48 | { 49 | scanf("%ld %ld", &n, &m); 50 | sum = (n / 2) * m; 51 | printf("Case %d: %ld\n", i, sum); 52 | } 53 | return 0; 54 | } 55 | ``` -------------------------------------------------------------------------------- /Chapter 02/2.5/Exercise3.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | // For using 2 for loops, go for buble sort/insertion sort 5 | 6 | // There are a lot of sorting algorithms out there 7 | 8 | // I am implementing a generic quick sort algorithm 9 | 10 | // A generic slave method of quickSort(); nothing to tweak 11 | int partition(int array[], int leftIndex, int rightIndex){ 12 | int pivotValue = array[rightIndex]; 13 | int toBePivotIndex = (leftIndex - 1); 14 | for(int comparisonIndex = leftIndex; comparisonIndex <= rightIndex - 1; comparisonIndex++){ 15 | if ( 16 | // We are sorting in ascending order 17 | // Switch the condition if want to sort in descending order 18 | array[comparisonIndex] < pivotValue 19 | ) { 20 | // Take the bigger value to the right 21 | toBePivotIndex++; 22 | int temp = array[toBePivotIndex]; 23 | array[toBePivotIndex] = array[comparisonIndex]; 24 | array[comparisonIndex] = temp; 25 | } 26 | } 27 | // Take the pivot value in the correct position 28 | int temp = array[toBePivotIndex+1]; 29 | array[toBePivotIndex+1] = array[rightIndex]; 30 | array[rightIndex] = temp; 31 | 32 | return (toBePivotIndex + 1); // new pivot point 33 | } 34 | 35 | // A generic quickSort() method; nothing to tweak 36 | void quickSort(int array[], int leftIndex, int rightIndex){ 37 | // Pivot point can be chosen arbitarily; implement accordingly 38 | if (leftIndex < rightIndex) { 39 | int partitionIndex = partition(array, leftIndex, rightIndex); 40 | quickSort(array, leftIndex, partitionIndex - 1); 41 | quickSort(array, partitionIndex + 1, rightIndex); 42 | } 43 | } 44 | 45 | 46 | int main(){ 47 | printf("Please enter size of the array\n" ); 48 | int size; 49 | scanf("%d", &size); 50 | int array[size]; 51 | 52 | for(int i = 0; i < size;i++){ 53 | printf("Please enter number %d :\n", i+1 ); 54 | scanf("%d", &array[i]); 55 | } 56 | 57 | //sort array 58 | quickSort(array, 0, size-1); 59 | 60 | // The array for descending order 61 | // Of course we can simply start printing from righ to left 62 | int reversedArray[size]; 63 | for(int i = 0; i < size; i++) 64 | reversedArray[i] = array[size-i-1]; 65 | 66 | printf("Ascending order : \n"); 67 | for(int i = 0; i < size; i++) 68 | printf("%d\n",array[i] ); 69 | 70 | printf("Descending order : \n"); 71 | for(int i = 0; i < size; i++) 72 | printf("%d\n",reversedArray[i] ); 73 | 74 | 75 | 76 | 77 | } 78 | -------------------------------------------------------------------------------- /LightOJ/1305/en.md: -------------------------------------------------------------------------------- 1 | # LOJ 1305 - Area of a Parallelogram 2 | A parallelogram is a quadrilateral with two pairs of parallel sides. See the picture below: 3 | 4 |

5 | 6 | Now you are given the co ordinates of __A__, __B__ and __C__, you have to find the coordinates of __D__ and the area of the parallelogram. The orientation of __ABCD__ should be same as in the picture. 7 | 8 | 9 | ### Input 10 | 11 | Input starts with an integer _T (≤ 1000)_, denoting the number of test cases. 12 | 13 | Each case starts with a line containing six integers __Ax, Ay, Bx, By, Cx, Cy__ where __(Ax, Ay)__ denotes the coordinate of __A__, __(Bx, By)__ denotes the coordinate of __B__ and __(Cx, Cy)__ denotes the coordinate of __C__. Value of any coordinate lies in the range __[-1000, 1000]__. And you can assume that __A__, __B__ and __C__ will not be collinear. 14 | 15 | 16 | ### Output 17 | 18 | For each case, print the case number and three integers where the first two should be the coordinate of __D__ and the third one should be the area of the parallelogram. 19 | 20 | ## Solution 21 | 22 | Since, it's a __parallelogram__, 23 | ``` 24 | AB = CD 25 | => Bx - Ax = Cx - Dx 26 | => Dx = Ax + Cx - Bx 27 | ``` 28 | Similarly, __Dy = Ay + Cy - By__. 29 | 30 | 31 | We know that the area of a __Parallelogram__, 32 | 33 |

34 | 35 | 36 | Simply __A = 1/2 * (((Ax*By)+(Bx*Cy)+(Cx*Dy)+(Dx*Ay))-((Ay*Bx)+(By*Cx)+(Cy*Dx)+(Dy*Ax)))__ 37 | 38 | We have to assign `A = A * -1` in case `A` comes in negative. 39 | 40 | If we now just simply plugin the values, we have all the answer now. 41 | 42 | The above implementation is `accepted`. 43 | 44 | ## Solution in C 45 | ```c 46 | #include 47 | 48 | int main() 49 | { 50 | int t, ax, ay, bx, by, cx, cy, dx, dy, a; 51 | scanf("%d", &t); 52 | for (int i = 1; i <= t; i++) 53 | { 54 | scanf("%d %d %d %d %d %d", &ax, &ay, &bx, &by, &cx, &cy); 55 | dx = ax + cx - bx; 56 | dy = ay + cy - by; 57 | a = 0.5 * (((ax * by) + (bx * cy) + (cx * dy) + (dx * ay)) - ((ay * bx) + (by * cx) + (cy * dx) + (dy * ax))); 58 | if (a < 0) 59 | a *= -1; 60 | printf("Case %d: %d %d %d\n", i, dx, dy, a); 61 | } 62 | return 0; 63 | } 64 | ``` 65 | -------------------------------------------------------------------------------- /LightOJ/1008/en.md: -------------------------------------------------------------------------------- 1 | # LOJ 1008 - Fibsieve's Fantabulous Birthday # 2 | --- 3 | 4 | In the first input, we will be given the number of test cases *T* . After that we will be given an input *S* upto *T* times, each of which represents the S-th second and we have to output which cell would light up by outputting the value of its column and row number separated by a single space. 5 | 6 | If we take few examples from the chess board, for 25, its row number is 5 and 5 = √25. For 24, its row number is 5 and 5 = ⌈√24⌉. However, for 16, its column number is 4 and 4 = ⌈√16⌉. Similarly, for 15, its column number is 4 and 4 = ⌈√15⌉. So, if ⌈√S⌉ is an even number, the ceiling value of the square root of *S* produces the column number and if it is an odd number, it produces the row number. 7 | 8 | For the column number of 24 it is 2 and here 2 = (closest square number to 24 ~ 24) + 1 = 25 - 24 + 1 = 2. In case of 15, its row number is 2 and 2 = (closest square number to 15 ~ 15) + 1 = 16 -15 + 1 = 2. In case of both 24 and 15, the closest square number is after them. 9 | 10 | But in case of 17, its column number is 5 and 5 = ⌈√17⌉ although here ⌈√17⌉ produced 5 which is an odd number and again the row number is 1 = (closest square number to 17 ~ 17) = 17 - 16 = 1. Now to determine whether the closest square number to *S* is after or before it, we can determine by whether ⌈√S⌉² - *S* > ⌈√S⌉ or not. If it is lesser than it then we know that the closest square number to *S* is before *S* and if it is greater then we know that the closest square number to *S* is after *S*. If we examine the closest square number to *S* when it is after *S*, that number is actually (⌈√S⌉ - 1)². Example: for 17, (⌈√17⌉ - 1)² = (5 - 1)² = 16 and from that, 17 - 16 = 1 which is the row number of 17. 11 | 12 | The above implementation is `Accepted`. 13 | 14 | ## Solution in C ## 15 | 16 | ```c 17 | #include 18 | #include 19 | 20 | int main() 21 | { 22 | int cases; 23 | scanf("%d", &cases); 24 | for (int i = 1; i <= cases; i++) 25 | { 26 | long long seconds, root, lackings, row, column; 27 | scanf("%lld", &seconds); 28 | root = ceil(sqrt(seconds * 1.0)); 29 | lackings = root * root - seconds; 30 | if (lackings < root){ 31 | row = root; 32 | column = lackings + 1; 33 | } 34 | else{ 35 | column = root; 36 | row = seconds - (root-1) * (root-1); 37 | } 38 | if(root % 2 == 0){ 39 | long long temp = column; 40 | column = row; 41 | row = temp; 42 | } 43 | printf("Case %d: %lld %lld\n",i, column, row); 44 | } 45 | 46 | return 0; 47 | } 48 | ``` 49 | -------------------------------------------------------------------------------- /LightOJ/1107/en.md: -------------------------------------------------------------------------------- 1 | # LOJ 1107 - How Cow # 2 | --- 3 | 4 | Mr Kopa Samsu is a farmer. He has a land of rectangular shape. But there are cows that disturb him a lot. The cows use to enter his land and ruin his crops. Now Mr Kopa Samsu has become smarter. He has a GPS system that will help him to know the position of the cows. So, you can think his land as a 2D grid, and cows can be treated as points. Now you are given the information of his land and cows. You have to tell him whether a cow is inside his land or not. 5 | 6 | ### Input 7 | 8 | Input starts with an integer _T (≤ 50)_, denoting the number of test cases. 9 | 10 | The first line of each case contains four integers _x1 y1 x2 y2_, where `(x1, y1)` is the lower left coordinate of his land and `(x2, y2)` is the upper right coordinate of his land. You can assume that the sides of the land are axis parallel. The next line contains an integer _M (1 ≤ M ≤ 100)_ denoting the number of cows. Each of the next M lines contains two integers each denoting _x y - the position of a cow_. __You can safely assume that no cow will lie on the boundary of the rectangle. All the coordinates will lie in the range [0, 10000].__ 11 | 12 | ### Output ### 13 | 14 | For each case you have to print the case number in a line first. Then for each cow, you have to print Yes or No depending whether the cow is inside the land or not. 15 | 16 | ## Solution ## 17 | 18 |

19 | 20 | We can easily visualize the scenario as shown above in the graph. It can easily be determined whether the cow is in the field or not simply by comparing the cow's coordinates with lower left coordinates and upper right coordinates of the field. For a cow to be in his field, the following conditions must be met: 21 | ``` 22 | lower left x-coordinate < cow's x-cordinate < upper right x-coordinate 23 | ``` 24 | and also 25 | ``` 26 | lower left y-coordinate < cow's y-cordinate < upper right y-coordinate 27 | ``` 28 | If any of the above mentioned conditions is not met, the cow can be said to not be within boundaries of the field. For example : I & E has the same y-coordinate as G as well as F & H has the same x-coordinate as G, yet none of them are in the field except G. 29 | 30 | The above implementation is `accepted`. 31 | 32 | ## Solution in C ## 33 | 34 | ```c 35 | #include 36 | 37 | int main() 38 | { 39 | int t, x1, y1, x2, y2, m, x, y; 40 | scanf("%d", &t); 41 | for (int i = 1; i <= t; i++) 42 | { 43 | scanf("%d", &x1); 44 | scanf("%d", &y1); 45 | scanf("%d", &x2); 46 | scanf("%d", &y2); 47 | scanf("%d", &m); 48 | printf("Case %d:\n", i); 49 | for (int j = 1; j <= m; j++) 50 | { 51 | scanf("%d", &x); 52 | scanf("%d", &y); 53 | if (x > x1 && x < x2 && y > y1 && y < y2) 54 | printf("Yes\n"); 55 | else 56 | printf("No\n"); 57 | } 58 | } 59 | return 0; 60 | } 61 | ``` -------------------------------------------------------------------------------- /LightOJ/1216/en.md: -------------------------------------------------------------------------------- 1 | # LOJ 1216 - Juice in the Glass # 2 | --- 3 | Once upon a time, there lived a mad programmer. He loved to solve creative problems other than anything. His wife loved him quite a lot but disliked his curiosity for the problems. One day he came from office, his wife gave him a glass of cold lime juice. She was in a romantic mood and waiting for some romantic stuff. But the programmer asked her curiously, "If I give u radius of the top and bottom part of the glass and the height, can you come up with the volume of the glass?" His wife became a bit disappointed but as she is smart she replied with a smile, "You already have drunk some juice, and the glass is not full. If I give you the height of the juice, can you find the volume of the remaining juice in the glass?" Then the programmer kissed his wife and said, "You are the best problem setter in the world!" 4 | 5 |

6 | 7 | Now he set the same problem for you. The radius of the upper part _r1_ and lower part _r2_ is given. If height of the glass is _h_ and height of the juice is _p_ what is the volume of the juice in the glass? 8 | 9 | ### Input 10 | 11 | Input starts with an integer __T (≤ 100)__, denoting the number of test cases. 12 | 13 | Each case starts with a line containing four integers __r1 r2 h p (1 ≤ r2 < r1 ≤ 100, 1 ≤ p ≤ h ≤ 100)__. 14 | 15 | ### Output 16 | 17 | For each case, print the case number and the volume of the juice in the glass. __Errors less than 10-6 will be ignored.__ 18 | 19 | ## Solution 20 | 21 |

22 | 23 | To solve it, me must know how to calculate the volume of a [Conical Frustum](https://en.wikipedia.org/wiki/Frustum "Conical Frustum"). 24 | 25 | The `volume of a conical frustum, V = (π/3) * height * (radius1² + radius2² + (radius1 * radius2))`. So, if we know the 2 values of the __radii__, we can calculate __volume of the juice__. The only thing we need to figure out is, what is `r3`, the `radius` of glass at point `p`. Since, already `r2` and `r1` is given, we can find out the value of `r3` by doing some __tri-gonometric__ calculations. 26 | 27 | In the figure: 28 | ``` 29 | In △EGC, 30 | tan(α) = EG/EC 31 | = (r1-r2)/h ...(i) 32 | 33 | In △MNC, 34 | tan(α) = MN/MC 35 | = (r3-r2)/p 36 | => r3 - r2 = p*tan(α) 37 | => r3 = p*tan(α) + r2 38 | = p*(r1-r2)/h + r2 [From, (i)] 39 | ``` 40 | Now we can just simply plugin the value of `r3` in our formula, `V = (π/3) * p * (r3² + r2² + (r3 * r2))`. 41 | 42 | The above solution is `accepted`. 43 | 44 | ## Solution in C ## 45 | 46 | ```c 47 | #include 48 | #include 49 | 50 | int main() 51 | { 52 | double pi, r3; 53 | pi = 2.0*acos(0.0); 54 | int t, r1, r2, h, p; 55 | scanf("%d", &t); 56 | for (int i = 1; i <= t; i++) 57 | { 58 | scanf("%d %d %d %d", &r1, &r2, &h, &p); 59 | r3 = p/(h * 1.0) * (r1 - r2) + r2; 60 | printf("Case %d: %.10lf\n", i, (pi / 3.0) * p * (r3 * r3 + r2 * r2 + (r3 * r2))); 61 | } 62 | return 0; 63 | } 64 | ``` -------------------------------------------------------------------------------- /LightOJ/1116/en.md: -------------------------------------------------------------------------------- 1 | # LOJ 1116 - Ekka Dokka # 2 | --- 3 | Ekka and his friend Dokka decided to buy a cake. They both love cakes and that's why they want to share the cake after buying it. As the name suggested that Ekka is very fond of odd numbers and Dokka is very fond of even numbers, they want to divide the cake such that Ekka gets a share of __N__ square centimeters and Dokka gets a share of __M__ square centimeters where __N is odd and M is even. Both N and M are positive integers.__ 4 | 5 | They want to divide the cake such that `N * M = W`, where W is the dashing factor set by them. Now you know their dashing factor, you have to find whether they can buy the desired cake or not. 6 | 7 | ### Input ### 8 | 9 | Input starts with an integer _T (≤ 10000)_, denoting the number of test cases. 10 | 11 | Each case contains an integer _W (2 ≤ W < 263)_. And W will not be a power of 2. 12 | 13 | ### Output ### 14 | 15 | For each case, print the case number first. After that print `Impossible` if they can't buy their desired cake. If they can buy such a cake, you have to print `N` and `M`. __If there are multiple solutions, then print the result where M is as small as possible__ 16 | 17 | ## Solution ## 18 | 19 | This is just a simple implementation problem. First we have to determine wether `W` is `even` or `odd` simply by checking `W % 2 = 0 or not`. If `W is odd`, we already realize that it is `Impossible` for such `N` and `M` to exist. But when it is not, there can be both single or multiple solutions such that `N * M = W`. For example: if `W = 10`, the only solution is `N = 5` and `M = 2`. But in case of `W = 12`, `(N,M) = {(6,2),(3,4)}`. Now there are 2 conditions: 20 | 21 | 1. N must be odd. M must be even. 22 | 2. M must be as small as possible. 23 | 24 | Focusing on `Condition 2`, the equation can be solved as `(X/a)*(Y*a) = W` where to make `a` as small as possible so that `M` becomes not bigger than necessary as well as `(X/a)` becomes an `odd` number just like in case of `W = 12`. As we can see, `(N,M) = (6,2)`, here `M` is smaller than `4` but `N` is not odd. So, we will divide `M` by 2 and multiply that 2 to `N`, making `M = 3` an odd number and `N = 4` an even number. Furthermore dividing will make `M` bigger than necessary. To solve it, we will keep assigning `N = N/2` until it is an `odd` number and we will be also assigning `M = M*2`. 25 | 26 | Remember, you need `long` data type or similar data type that can hold an integer value of _263_ 27 | 28 | The above implementation is `accepted`. 29 | 30 | ## Solution in C ## 31 | 32 | ```c 33 | #include 34 | 35 | int main() 36 | { 37 | int t; 38 | long n, m, w; 39 | scanf("%d", &t); 40 | for (int i = 1; i <= t; i++) 41 | { 42 | scanf("%ld", &w); 43 | if (w % 2 == 0) 44 | { 45 | n = w / 2; 46 | m = 2; 47 | while (n % 2 == 0) 48 | { 49 | n /= 2; 50 | m *= 2; 51 | } 52 | printf("Case %d: %ld %ld\n", i, n, m); 53 | } 54 | else 55 | printf("Case %d: Impossible\n", i); 56 | } 57 | return 0; 58 | } 59 | ``` -------------------------------------------------------------------------------- /Chapter 02/2.4/Exercise8.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | printf("Enter the value of n : "); 6 | int n; 7 | scanf("%d", &n); 8 | printf("\n"); 9 | 10 | //pattern 1 11 | for (int i = 1; i <= n; i++) 12 | { 13 | for (int k = 1; k <= i; k++) 14 | printf("*"); 15 | for (int l = n - i; l > 0; l--) 16 | printf("."); 17 | printf("\n"); 18 | } 19 | printf("\n"); 20 | 21 | //pattern 2 22 | for (int i = n; i > 0; i--) 23 | { 24 | for (int l = n - i; l > 0; l--) 25 | printf("."); 26 | for (int k = 1; k <= i; k++) 27 | printf("*"); 28 | 29 | printf("\n"); 30 | } 31 | printf("\n"); 32 | 33 | //pattern 3 34 | for (int i = 1; i <= n; i++) 35 | { 36 | for (int l = n - i; l > 0; l--) 37 | printf("."); 38 | for (int k = 1; k <= i; k++) 39 | printf("*"); 40 | for (int k = 1; k < i; k++) 41 | printf("*"); 42 | for (int l = n - i; l > 0; l--) 43 | printf("."); 44 | printf("\n"); 45 | } 46 | printf("\n"); 47 | //pattern 4 48 | for (int i = n; i > 0; i--) 49 | { 50 | 51 | for (int k = n - i; k > 0; k--) 52 | printf("."); 53 | for (int l = 1; l <= i; l++) 54 | printf("%d", l); 55 | for (int k = i - 1; k > 0; k--) 56 | printf("%d", k); 57 | for (int k = n - i; k > 0; k--) 58 | printf("."); 59 | printf("\n"); 60 | } 61 | 62 | printf("\n"); 63 | 64 | //pattern 5 65 | for (int i = 1; i <= n; i++) 66 | { 67 | for (int l = n - i; l > 0; l--) 68 | printf("."); 69 | for (int k = 1; k <= i; k++) 70 | printf("*"); 71 | for (int k = 1; k < i; k++) 72 | printf("*"); 73 | for (int l = n - i; l > 0; l--) 74 | printf("."); 75 | printf("\n"); 76 | } 77 | for (int i = n - 1; i > 0; i--) 78 | { 79 | 80 | for (int k = n - i; k > 0; k--) 81 | printf("."); 82 | for (int l = 1; l <= i; l++) 83 | printf("*"); 84 | for (int k = i - 1; k > 0; k--) 85 | printf("*"); 86 | for (int k = n - i; k > 0; k--) 87 | printf("."); 88 | printf("\n"); 89 | } 90 | printf("\n"); 91 | 92 | //pattern 6 93 | 94 | for (int i = 1; i < n; i++) 95 | { 96 | for (int l = n - i; l > 0; l--) 97 | printf("."); 98 | for (int k = 1; k <= i; k++) 99 | printf("%d", k); 100 | for (int k = 1; k < i; k++) 101 | printf("%d", k); 102 | for (int l = n - i; l > 0; l--) 103 | printf("."); 104 | printf("\n"); 105 | } 106 | for (int i = n; i > 0; i--) 107 | { 108 | 109 | for (int k = n - i; k > 0; k--) 110 | printf("."); 111 | for (int l = 1; l <= i; l++) 112 | printf("%d", l); 113 | for (int k = i - 1; k > 0; k--) 114 | printf("%d", k); 115 | for (int k = n - i; k > 0; k--) 116 | printf("."); 117 | printf("\n"); 118 | } 119 | 120 | printf("\n"); 121 | 122 | printf("\n"); 123 | 124 | return 0; 125 | } -------------------------------------------------------------------------------- /LightOJ/1045/en.md: -------------------------------------------------------------------------------- 1 | # LOJ 1045 - Digits of Factorial 2 | --- 3 | Tags : Logarithms, Base Conversion, Factorials, Memoization 4 | 5 | We will be given the value of __N__, and the basis of the _number system_, __base__. We need to find out the number of digit(s) of the factorial of an integer (__N!__) in that __base__. 6 | 7 | ### Helpful Resources 8 | * [Logarithm - Britannica](https://www.britannica.com/science/logarithm#ref233783 "britannica") 9 | * [Logarithm - Wikipedia](https://en.wikipedia.org/wiki/Logarithm "WikiPedia") 10 | * [Memoization (1D, 2D and 3D) - Geeks for Geeks](https://www.geeksforgeeks.org/memoization-1d-2d-and-3d/ "Geeks for Geeks") 11 | 12 | ## Solution 13 | 14 | To solve this problem we can take help from logarithm formula and rules. 15 | 16 | The value of __N__ is given in __base - 10__ number system. 17 | Let's observe what we get when we put __base - 10__ numbers in __log10(X)__ : 18 | 19 | 20 | |Number|log10(Number)|⌊log10(Number)⌋|Digits| 21 | |:--|:--|:--|:--| 22 | |{1, ..., 9}|0.{something}|0|1| 23 | |{10, ..., 99}|1.{something}|1|2| 24 | |{100, ..., 999}|2.{something}|2|3| 25 | |...|...|...|...| 26 | |X|(Digits(X) - 1).{something}|Digits(X) - 1|__⌊log10(X)⌋ + 1__| 27 | 28 | But we need to determine the number of digits for __N!__. So, __⌊log10(N!)⌋ + 1__ will help us for __base - 10__. 29 | 30 | For __⌊log10(N!)⌋__, if we recall the formula for __log10(X1 * X2 * X3 * ... * Xn)__, 31 | 32 | 33 | __log10(X1 * X2 * X3 * ... * Xn) = log10(X1) + log10(X2) + log10(X3) + ... + log10(Xn)__ 34 | 35 | From the problem, we need to find out the number of digits for __B-based__ numbers instead of __10-based__. Now if we recall the base-conversion formula of logarithms, 36 | 37 | __logb1(X) = logb1(b2) * logb2(X)__ 38 | 39 | => __logb2(X) = (logb1(X))/(logb1(b2))__ 40 | 41 | Now we can just do this, 42 | 43 | __Digits = ⌊logb2(N!)⌋ + 1 = ⌊(log10(N!))/(log10(b2))⌋ + 1__ 44 | 45 | To avoid repetition for calculation, we can do __memoization__ in an array for __log10(1) + log10(2) + ... + log10(106)__. 46 | 47 | The above implementation is `accepted`. 48 | 49 | __Caution__ : Remember to take `digits` as an integer data type that can hold __106__ but avoid floating points. 50 | 51 | ## Solution in C 52 | ```cpp 53 | #include 54 | using namespace std; 55 | 56 | int main() 57 | 58 | { 59 | ios::sync_with_stdio(false); 60 | cin.tie(NULL); 61 | cout.tie(NULL); 62 | 63 | 64 | double memoizedArray[1000001];//Array for Memoization 65 | memoizedArray[0] = 0; //Don't do manual log for 0, it will throw an error 66 | 67 | //Memoizing the array 68 | for(int i=1;i<=1000000;i++){ 69 | memoizedArray[i] = memoizedArray[i-1] + log(i); 70 | } 71 | 72 | int testCase, base; 73 | long digits,n; 74 | 75 | cin >> testCase; 76 | 77 | for(int i = 1; i<= testCase; i++){ 78 | cin >> n >> base; 79 | //The formula 80 | digits = memoizedArray[n]/log(base) + 1; 81 | cout << "Case " << i << ": " << digits << "\n"; 82 | } 83 | 84 | return 0; 85 | } 86 | ``` 87 | -------------------------------------------------------------------------------- /LightOJ/1072/en.md: -------------------------------------------------------------------------------- 1 | # LOJ 1072 - Calm Down # 2 | --- 3 | George B. wants to be more than just a good American. He wants to make his daddy proud and become a hero. You know, like Shakib Khan. 4 | 5 | But sneaky as he is, he wants a special revolver that will allow him to shoot more often than just the usual six times. This way he can fool and kill the enemy easily (at least that's what he thinks, and that's the best he can think). George has kidnapped . . . uh, I mean . . ."invited" you and will only let you go if you help him with the math. The piece of the revolver that contains the bullets looks like this (examples for 6 and 17 bullets): 6 | 7 |

8 | 9 | There is a large circle with radius R and n little circles each having radius r, are placed inside on the border of the large circle. George wants his bullets to be as large as possible, so there should be no space between the circles. George will decide how large the whole revolver will be and how many bullets it shall contain. Your job is, given R and n, to compute r. You have decided to help, because you know that he can't make a revolver even if you help him with the math. 10 | 11 | 12 | ### Input 13 | 14 | Input starts with an integer _T (≤ 125)_, denoting the number of test cases. 15 | 16 | Each case contains a real number _R (0 < R < 1000)_ and contains up to at most two places after the decimal point and an integer _n (2 ≤ n ≤ 100)_. 17 | 18 | ### Output 19 | 20 | For each test case, print the _case number_ and _r_ in a single line. __Errors less than 10-6 will be ignored.__ 21 | 22 | 23 | ## Solution ## 24 | 25 |

26 | 27 | If we look at the picture above, we can see that a *smaller circle* within the *bigger circle* creates an **angle** `α` if we draw two **tangent line**s starting from the *bigger circle*'s **center** `A` on the two sides of the *smaller circle* touching the *bigger circle*'s **parameter line** which are`AD` and `AB` respectively. We know a circle produces an **angle** of `2*π`. And the *smaller circles* do not have any space among themselves, so `2*π = N*α` from which, we can get `α = 2π/N`. 28 | 29 | Also let's draw `AE` which goes through the **center** of the *small circle* `c` and here `AE = R (radius of the bigger circle) = AD = AB`. Drawing `AE` produces an **angle** `β`. Since the *smaller circle* is split straight through its **center**, `β = α/2` from which we can get `β = (2*π/N)/2 = π/N`. 30 | 31 | Now let's draw one **perpendicular line** from **point** `C` on `AB` which is `CF`. If we observe the figure, `CF = CE = r (radius of the smaller circle)`. Now we can easily find out the value of `r` using the `sin(β)` ratio. 32 | 33 | ``` 34 | sin(β) = CF/(AE-CE) 35 | = r/(R-r) 36 | => sin(π/N) = r/(R-r) 37 | => r = sin(π/N)*(R-r) 38 | = sin(π/N)*R - sin(π/N)*r 39 | => r + sin(π/N)*r = sin(π/N)*R 40 | => r*(1+ sin(π/N)) = sin(π/N)*R 41 | => r = sin(π/N)*R/(1+ sin(π/N)) 42 | 43 | ``` 44 | So, `r = sin(π/N)*R/(1+ sin(π/N))`. 45 | 46 | The above implementation is `Accepted`. 47 | 48 | ## Solution in C ## 49 | 50 | ```c 51 | #include 52 | #include 53 | int main() 54 | { 55 | 56 | int cases; 57 | scanf("%d", &cases); 58 | double pi = 2 * acos(0.0); 59 | for (int i = 1; i <= cases; i++) 60 | { 61 | double R; 62 | int n; 63 | scanf("%lf %d", &R, &n); 64 | double r = (R * sin(pi / n * 1.0)) / (1 + sin(pi / n * 1.0)); 65 | printf("Case %d: %.10lf\n", i, r); 66 | } 67 | return 0; 68 | } 69 | ``` -------------------------------------------------------------------------------- /LightOJ/1433/en.md: -------------------------------------------------------------------------------- 1 | # LOJ 1433 - Minimum Arc Distance 2 | --- 3 | You all probably know how to calculate the distance between two points in two dimensional cartesian plane. But in this problem you have to find the minimum arc distance between two points and they are on a circle centered at another point. 4 | 5 | You will be given the _co-ordinates_ of the points __A__ and __B__ and _co-ordinate_ of the center __O__. You just have to calculate the minimum _arc distance_ between __A__ and __B__. In the picture, you have to calculate the _length_ of _arc_ __ACB__. You can assume that __A__ and __B__ will always be on the circle centered at __O__. 6 | 7 |

8 | 9 | ### Input 10 | 11 | Input starts with an integer _T (≤ 100)_, denoting the number of test cases. 12 | 13 | Each case starts with a line containing six integers Ox, Oy, Ax, Ay, Bx, By where (Ox, Oy) indicates the co-ordinate of O, (Ax, Ay) denote the co-ordinate of A and (Bx, By) denote the co-ordinate of B. All the integers will lie in the range [1, 10000]. 14 | 15 | ### Output 16 | 17 | For each case, print the case number and the minimum arc distance. Errors less than 10-3 will be ignored. 18 | 19 | ## Solution 20 | 21 | ![graph](1433.png "Geometry Explained") 22 | 23 | To solve it, we first must remember the formula to calculate the [arc length](https://en.wikipedia.org/wiki/Arc_length "arc length") between 2 points of a __circle__, which is 24 | ``` 25 | arc length = (radius of the circle) * (angle created by the 2 points at the center of the circle, in radian) 26 | ``` 27 | 28 | To understand this formula in a quick look or to refresh our memories, we can see that the _arc length_ is proportional to the __θ__,_angle created at the center of a circle_. The bigger the _arc length_, the bigger becomes the _angle_ in between the 2 points of the cirlce and vice versa. We can see that the __Circumference__ is the longest arc length of a circle, also we know __C = 2 * π * (radius of the cirlce)__. 29 | ``` 30 | C is the arc length when θ = 2 * π 31 | 1 is the arc length when θ = (2 * π)/C 32 | = (2 * π)/(2 * π *r) 33 | = 1/r 34 | S is the arc length when θ = S/r 35 | 36 | So, S = θ * r 37 | ``` 38 | 39 | We can calculate the radius of the circle simply by taking the _distance_ of any _point of a circle_ to its _center_, __distance = √((P1x - P2x)² + (P1y - P2y)²)__. 40 | 41 | Now to calculate the _angle_ we can use the _cosine rule_ of triangles, 42 | ``` 43 | AB (Straight line, not the arc length) = √(OA²+OB²-2*OA*OB*cosθ) 44 | => AB² = OA²+OB²-2*OA*OB*cosθ 45 | => cosθ = (OA²+OB²-AB²)/2*OA*OB 46 | => θ = arccos ((OA²+OB²-AB²)/2*OA*OB) 47 | ``` 48 | We again use the _distance_ formula for each line and now we have the necessary values that we can plug into the _arc length_ formula. 49 | 50 | The above implementation is `accepted`. 51 | 52 | ## Solution in C 53 | ```c 54 | #include 55 | #include 56 | 57 | int main() 58 | { 59 | int testCases, ox, oy, ax, ay, bx, by; 60 | scanf("%d", &testCases); 61 | double OA, OB, AB, angle; 62 | for (int i = 1; i <= testCases; i++) 63 | { 64 | scanf("%d %d %d %d %d %d", &ox, &oy, &ax, &ay, &bx, &by); 65 | 66 | OA = sqrt(pow(ax - ox, 2) + pow(ay - oy, 2)); 67 | OB = sqrt(pow(bx - ox, 2) + pow(by - oy, 2)); 68 | AB = sqrt(pow(ax - bx, 2) + pow(ay - by, 2)); 69 | 70 | angle = acos((pow(OA, 2) + pow(OB, 2) - pow(AB, 2)) / (2 * OA * OB)); 71 | 72 | printf("Case %d: %.3lf\n", i, OA * angle); 73 | } 74 | return 0; 75 | } 76 | 77 | ``` -------------------------------------------------------------------------------- /LightOJ/1211/en.md: -------------------------------------------------------------------------------- 1 | # LOJ 1211 - Intersection of Cubes # 2 | --- 3 | You are given n cubes, each cube is described by two points in 3D space: _(x1, y1, z1)_ being one corner of the cube and _(x2, y2, z2)_ being the opposite corner. Assume that the sides of each of the cubes are parallel to the axis. Your task is to find the volume of their intersection. 4 | 5 | ### Input ### 6 | 7 | Input starts with an integer _T (≤ 100)_, denoting the number of test cases. 8 | 9 | Each case starts with a line containing an integer n (1 ≤ n ≤ 100). Each of the next n lines contains six integers _x1 y1 z1 x2 y2 z2_ __(1 ≤ x1, y1, z1, x2, y2, z2 ≤ 1000, x1 < x2, y1 < y2, z1 < z2)__ where __(x1, y1, z1)__ is the co-ordinate of one corner and __(x2, y2, z2)__ is the co-ordinate of the opposite corner. 10 | 11 | ### Output ### 12 | 13 | For each case, print the case number and volume of their intersection. 14 | 15 | ## Solution ## 16 |

17 | 18 | We know that the `Volume of a Cube = Height * Width * Length`. For any _P -axis_, we can find out _length_ of __the common part__ simply by, (p2 which is near to __0__ among all values of p2) - (p1 which is the most furthest from __0__ among all values of p1). More clearly, we need the __highest__ possible value among the inputs for `p1` and the __lowest__ possible value among the inputs for`p2` for any _P-axis_. And __length__ of the common part here will be __p2 - p1__. Note that, we are __not__ going to take the __absolute value__ because there may be a scenario where there is __no common part__ at all and in such case _negative_ value for __any single axis__ will indicate that it is `impossible`, or simply `Volume = 0`. 19 | 20 | Example of a valid case : from the graph, in X-axis, `Bx1` is the further from 0 than `Ax1` & `Ax2` is nearer to 0 than `Bx2`. Thus, `common length in X-axis = Ax2 - Bx1`. 21 | 22 | Example of an `impossible` case : `A = {(1,2),(2,5),(1,9)}` and `B = {(3,4),(2,5),(1,9)}`. Here, `xNear = 2` which belongs to `A` and `xFar = 3` which belongs to `B`. Even A and B has the same length in every axis but `xNear-xFar = -1`. Thus we know that even though the cubes have `same length in dimensions` but `no intersection`. 23 | 24 | When we have the common part from all the __axis__, multiplying them will give us the result, `Area = (xNear-xFar)*(yNear-yFar)*(zNear-zFar)`. And in case of a _negative common length_ for __any__ axis, the result will be `0`. 25 | 26 | The above implementation is `accepted`. 27 | 28 | ### Solution in C ### 29 | 30 | ```c 31 | #include 32 | 33 | int main() 34 | { 35 | int t, n, x1, y1, z1, x2, y2, z2, xCommon, yCommon, zCommon; 36 | 37 | scanf("%d", &t); 38 | for (int i = 1; i <= t; i++) 39 | { 40 | int xFar = 0, yFar = 0, zFar = 0; 41 | int xNear = 1001, yNear = 1001, zNear = 1001; 42 | scanf("%d", &n); 43 | for (int j = 1; j <= n; j++) 44 | { 45 | scanf("%d %d %d %d %d %d", &x1, &y1, &z1, &x2, &y2, &z2); 46 | 47 | if (x1 > xFar) 48 | xFar = x1; 49 | 50 | if (y1 > yFar) 51 | yFar = y1; 52 | 53 | if (z1 > zFar) 54 | zFar = z1; 55 | 56 | if (x2 < xNear) 57 | xNear = x2; 58 | 59 | if (y2 < yNear) 60 | yNear = y2; 61 | 62 | if (z2 < zNear) 63 | zNear = z2; 64 | } 65 | xCommon = (xNear - xFar); 66 | yCommon = (yNear - yFar); 67 | zCommon = (zNear - zFar); 68 | 69 | if (xCommon > 0 && yCommon > 0 && zCommon > 0) 70 | printf("Case %d: %d\n", i, xCommon * yCommon * zCommon); 71 | else 72 | printf("Case %d: 0\n", i); 73 | } 74 | return 0; 75 | } 76 | ``` -------------------------------------------------------------------------------- /LightOJ/1202/en.md: -------------------------------------------------------------------------------- 1 | # LOJ 1202 - Bishops # 2 | --- 3 |

4 | 5 | There is an infinite chessboard. Two bishops are there. (Bishop means the chess piece that moves diagonally). 6 | 7 | Now you are given the position of the two bishops. You have to find the minimum chess moves to take one to another. With a chess move, a bishop can be moved to a long distance (along the diagonal lines) with just one move. 8 | 9 | ### Input ### 10 | 11 | Input starts with an integer _T (≤ 10000)_, denoting the number of test cases. 12 | Each case contains four integers _r1 c1 r2 c2_ denoting the positions of the bishops. Each of the integers will be positive and not greater than 109. You can also assume that the positions will be distinct. 13 | 14 | ### Output ### 15 | 16 | For each case, print the case number and the minimum moves required to take one bishop to the other. Print `impossible` if it's not possible. 17 | 18 | ## Solution ## 19 | 20 | If a __Bishop__ makes a move from its __initial block__ to any __diagonal__ direction, the difference of new _x-coordinate_ and _y-coordinate_ from their __initial block__ is equal, `|c1-c2| = |r1-r2|`. This is how we know that the __destination block__ can be reached __diagonally__ directly in _1 move_. For example : from `(1,1)` to `(10,10)`, here `|1-10| = 9 = |1-10|`. If the condition is not met, either the position can not be taken in _1 move_ or it is `impossible`. 21 | 22 | Now to determine whether it can be reached at all or `impossible`, we need to know if the block we are trying reach is of the __same color__ of the __Bishop's initial block__ or not. We already know diagonal blocks can be reached in 1 move. But in case of switching to a block of the __same color__ of its current position that is not __directly diagonally connected__, observing the chessboard we can see that we need to move to another block that is already __diagonally__ connected to the __destination block__ we want. In other words, there is always at least __1 block__ and at best __2 blocks__ in common between the __destination block__ and __initial block__. For example: `(1,1)` and `(5,3)` have only `(4,4)` in common where as `(2,5)` and `(5,4)` have `{(4,3),(3,6)}`. So, in any case, a block of the __same color__ that needs to be reached via a __common block__ will require only _2 moves_. To check whether color of the __initial block__ and __destination block__ are same or not, we can check whether `|c1-c2| % 2 = |r1-r2| % 2` or not. For example : from `(1,1)` to `(5,3)`, here `|1-5| % 2 = 0 = |1-3| % 2`. Point to be noted, `|1-5| = 4` and `|5-3| = 2` are both __even__. In another example, `(4,5)` to `(3,2)` is reachable by `(4,5) -> (2,3) -> (3,2)`. But in this case, `|4-3| = 1` and `|5-2| = 3` are both __odd__ . But in case of from `(4,5)` to `(3,3)` is not possible because they have no __common diagonal block__ and also `|4-3| = 1` which is __odd__ and `|5-3| = 2` which is __even__. Thus if `|c1-c2| % 2 = |r1-r2| % 2` is `true` we now know that travelling is possible in _2 moves_. Else, the __destination block__ is not of the __same color__ as its __initial block__ and thus it is `impossible` to reach. 23 | 24 | The above implementation is `accepted`. 25 | 26 | ## Solution in C ## 27 | ```c 28 | #include 29 | #include 30 | int main() 31 | { 32 | int cases, c1, r1, c2, r2, c, r; 33 | scanf("%d", &cases); 34 | for (int i = 1; i <= cases; i++) 35 | { 36 | scanf("%d%d%d%d", &r1, &c1, &r2, &c2); 37 | c = abs(c1 - c2); 38 | r = abs(r1 - r2); 39 | if (c == r) 40 | printf("Case %d: 1\n", i); 41 | else 42 | { 43 | if (c % 2 == r % 2) 44 | printf("Case %d: 2\n", i); 45 | else 46 | printf("Case %d: impossible\n", i); 47 | } 48 | } 49 | return 0; 50 | } 51 | ``` -------------------------------------------------------------------------------- /Chapter 02/2.5/Exercise9.java: -------------------------------------------------------------------------------- 1 | // This problem can be solved using `Rabin-Karp` or `KMP` or any similar pattern matching algorithm 2 | // Refer to `Introduction to Algorithms` (CLRS), page 985 3 | 4 | import java.io.BufferedReader; 5 | import java.io.InputStreamReader; 6 | import java.util.Scanner; 7 | import java.util.Vector; 8 | 9 | public class Exercise9 { 10 | 11 | private static int[] prefixArray; // The pi-array; for global acces 12 | 13 | private static int patternLength; // m == pattern's length; for global acces 14 | 15 | private static int textLength; // n == text's length; for global access 16 | 17 | private static Vector patternShiftIndex; // At which indice the patterns are found after shifting 18 | 19 | private static int patternOccured = 0; // How many times the pattern occured 20 | 21 | // In Java, we can't directly iterate over the characters 22 | private static char[] patternArray; 23 | private static char[] textArray; 24 | 25 | // A slave method to compute prefix array 26 | private static void ComputePrefixArray(String pattern) { 27 | 28 | patternArray = new char[patternLength + 1]; 29 | for (int index = 1; index <= patternLength; index++) 30 | patternArray[index] = pattern.charAt(index - 1); 31 | 32 | // This is our pi-array 33 | prefixArray = new int[patternLength + 1]; 34 | 35 | prefixArray[1] = 0; // No proper prefix at length(pattern) == 0 36 | 37 | int prefixLength = 0; 38 | 39 | for (int patternIndex = 2; patternIndex <= patternLength; patternIndex++) { 40 | // Update prefix length 41 | while (prefixLength > 0 42 | && patternArray[prefixLength + 1] != patternArray[patternIndex]) 43 | prefixLength = prefixArray[prefixLength]; 44 | 45 | // Proper prefix == suffix 46 | if (patternArray[prefixLength + 1] == patternArray[patternIndex]) 47 | prefixLength++; 48 | // Assign prefix length 49 | prefixArray[patternIndex] = prefixLength; 50 | } 51 | } 52 | 53 | // Actual KMP matching 54 | private static void KMPMatcher(String text, String pattern) { 55 | // Populate the prefixArray (pi-array) 56 | ComputePrefixArray(pattern); 57 | 58 | patternShiftIndex = new Vector(); 59 | 60 | textArray = new char[textLength + 1]; 61 | 62 | for (int index = 1; index <= textLength; index++) 63 | textArray[index] = text.charAt(index - 1); 64 | 65 | int charactersMatched = 0; 66 | 67 | for (int textIndex = 1; textIndex <= textLength; textIndex++) { 68 | // update how many characters have matched currently using the prefix array 69 | while (charactersMatched > 0 70 | && patternArray[charactersMatched + 1] != textArray[textIndex]) 71 | charactersMatched = prefixArray[charactersMatched]; 72 | 73 | // Increment if characters matched 74 | if (patternArray[charactersMatched + 1] == textArray[textIndex]) 75 | charactersMatched++; 76 | 77 | // Check if pattern found 78 | if (charactersMatched == patternLength) { 79 | patternOccured++; 80 | patternShiftIndex.add(textIndex - patternLength); 81 | 82 | // Reset to the valid prefix 83 | charactersMatched = prefixArray[charactersMatched]; 84 | } 85 | 86 | } 87 | } 88 | 89 | public static void main(String[] args) { 90 | Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))); 91 | 92 | System.out.println("Enter the Text : "); 93 | String text = in.nextLine(); 94 | textLength = text.length(); 95 | 96 | System.out.println("Enter the Pattern : "); 97 | String pattern = in.nextLine(); 98 | patternLength = pattern.length(); 99 | 100 | KMPMatcher(text, pattern); 101 | 102 | System.out.println("Pattern has occured : " + patternOccured + " times!"); 103 | for (Integer i : patternShiftIndex) { 104 | System.out.println("Pattern can be found by shifting to text index : " + i); 105 | } 106 | 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /LightOJ/1311/en.md: -------------------------------------------------------------------------------- 1 | # LOJ 1311 - Unlucky Bird 2 | --- 3 | A bird was flying on a train line, singing and passing lazy times. After a while it saw a train coming from its behind, so, it speeded up a bit, but remained calm. After a while, it saw another train coming towards it from the front side. The bird remained calm thinking that the train coming towards him would be on another line. But it realized soon after that both the trains were on the same line! 4 | 5 | So, the stupid-brave bird made a plan to stop the accident. It flew towards the train which was coming from the front side, and after touching the train the bird turned back immediately and flew back until it could touch the other train. And after that, it turned back and continued this procedure. The birds' intention was to signal the drivers such that they could stop the train. 6 | 7 | When the trains were d meter way, the drivers realized the abnormal behavior of the strange bird and saw the opposite trains, and both drivers braked hard! They were able to stop the collision, but they managed to stop in front of each other leaving no space. A thousand lives saved, but the bird couldn't save itself! 8 | 9 | For simplicity, we denote the train (that was behind the bird) as the left train and the other one as the right train. The left train had velocity v1 m/s (meter per second) and the right train had velocity v2 m/s and they saw each other when they were __d__ meter away. The driver in the left train made a deceleration of a1 m/s2 and the driver in the right train made a deceleration of a2 m/s2. And the trains just avoided the collision. That means they just stopped when their distance was 0 meter. The bird had a constant velocity of v3 m/s. And assume that the bird can turn immediately and can keep its constant velocity. When the trains were d meter away, the bird was somewhere between the trains. Your task is to find the distance covered by the brave bird (from this moment) in meters before sacrificing its life for the thousand lives. 10 | 11 | 12 | ### Input 13 | 14 | Input starts with an integer __T (≤ 100)__, denoting the number of test cases. 15 | 16 | Each case starts with a line containing five positive real numbers: __v1 v2 v3 a1 a2 (v1 < v3, v2 < v3)__. No real number will be greater than 1000. And no number contains more than three digits after the decimal point. 17 | 18 | 19 | ### Output 20 | 21 | For each case, print the case number, __d__ and the distance covered by the bird. Errors less than 10-6 will be ignored. 22 | 23 | ## Solution 24 | 25 | 26 | We are given the __deaccelaration__ and __velocity__ of both the trains. If we divide the __velocity__ by __deaccelaration__, __ttrain = vtrain/atrain__, we can obtain the __time__, __ttrain__, taken by each individual train to stop. The __flight time__ of the bird (_when the trains noticed one another and pulled break_) will be the __maximum__ between these two trains because the bird could not fly any shorter duration than the collision time or else it would live and could easily fly away from the tracks. The bird died in between the trains, meaning that it kept flying until the train that took longer to stop had finally killed it. Now we only need to plug into __dbird = vbird * tbird__, and get __dbird__, the distance covered by the bird. And for the total distance covererd by trains we just need to __sum__ the distance covered by each individual trains, __dtrain = vtrain * ttrain - 1/2 * atrain * t2__ and then __dtotal = dtrain 1 + dtrain 2__. 27 | 28 | The above implementation is `accepted`. 29 | 30 | ## Solution in C 31 | ```c 32 | #include 33 | 34 | int main(){ 35 | int testCase; 36 | scanf("%d", &testCase); 37 | double v1,v2,v3,a1,a2,t1,t2,t3, bird, trains; 38 | for(int i = 1; i <= testCase; i++){ 39 | scanf("%lf %lf %lf %lf %lf", &v1, &v2, &v3, &a1, &a2); 40 | t1 = v1/a1; 41 | t2 = v2/a2; 42 | t3 = t1; 43 | if(t1 < t2) 44 | t3 = t2; 45 | bird = v3 * t3; 46 | trains = v1 * t1 - .5 * a1 * t1 * t1; 47 | trains += v2 * t2 - .5 * a2 * t2 * t2; 48 | printf("Case %d: %.10lf %.10lf\n", i, trains, bird); 49 | 50 | } 51 | return 0; 52 | } 53 | ``` 54 | 55 | -------------------------------------------------------------------------------- /Chapter 02/2.4/LightOJ/1311.md: -------------------------------------------------------------------------------- 1 | # LOJ 1311 - Unlucky Bird 2 | --- 3 | A bird was flying on a train line, singing and passing lazy times. After a while it saw a train coming from its behind, so, it speeded up a bit, but remained calm. After a while, it saw another train coming towards it from the front side. The bird remained calm thinking that the train coming towards him would be on another line. But it realized soon after that both the trains were on the same line! 4 | 5 | So, the stupid-brave bird made a plan to stop the accident. It flew towards the train which was coming from the front side, and after touching the train the bird turned back immediately and flew back until it could touch the other train. And after that, it turned back and continued this procedure. The birds' intention was to signal the drivers such that they could stop the train. 6 | 7 | When the trains were d meter way, the drivers realized the abnormal behavior of the strange bird and saw the opposite trains, and both drivers braked hard! They were able to stop the collision, but they managed to stop in front of each other leaving no space. A thousand lives saved, but the bird couldn't save itself! 8 | 9 | For simplicity, we denote the train (that was behind the bird) as the left train and the other one as the right train. The left train had velocity v1 m/s (meter per second) and the right train had velocity v2 m/s and they saw each other when they were __d__ meter away. The driver in the left train made a deceleration of a1 m/s2 and the driver in the right train made a deceleration of a2 m/s2. And the trains just avoided the collision. That means they just stopped when their distance was 0 meter. The bird had a constant velocity of v3 m/s. And assume that the bird can turn immediately and can keep its constant velocity. When the trains were d meter away, the bird was somewhere between the trains. Your task is to find the distance covered by the brave bird (from this moment) in meters before sacrificing its life for the thousand lives. 10 | 11 | 12 | ### Input 13 | 14 | Input starts with an integer __T (≤ 100)__, denoting the number of test cases. 15 | 16 | Each case starts with a line containing five positive real numbers: __v1 v2 v3 a1 a2 (v1 < v3, v2 < v3)__. No real number will be greater than 1000. And no number contains more than three digits after the decimal point. 17 | 18 | 19 | ### Output 20 | 21 | For each case, print the case number, __d__ and the distance covered by the bird. Errors less than 10-6 will be ignored. 22 | 23 | ## Solution 24 | 25 | 26 | We are given the __deaccelaration__ and __velocity__ of both the trains. If we divide the __velocity__ by __deaccelaration__, __ttrain = vtrain/atrain__, we can obtain the __time__, __ttrain__, taken by each individual train to stop. The __flight time__ of the bird (_when the trains noticed one another and pulled break_) will be the __maximum__ between these two trains because the bird could not fly any shorter duration than the collision time or else it would live and could easily fly away from the tracks. The bird died in between the trains, meaning that it kept flying until the train that took longer to stop had finally killed it. Now we only need to plug into __dbird = vbird * tbird__, and get __dbird__, the distance covered by the bird. And for the total distance covererd by trains we just need to __sum__ the distance covered by each individual trains, __dtrain = vtrain * ttrain - 1/2 * atrain * t2__ and then __dtotal = dtrain 1 + dtrain 2__. 27 | 28 | The above implementation is `accepted`. 29 | 30 | ## Solution in C 31 | ```c 32 | #include 33 | 34 | int main(){ 35 | int testCase; 36 | scanf("%d", &testCase); 37 | double v1,v2,v3,a1,a2,t1,t2,t3, bird, trains; 38 | for(int i = 1; i <= testCase; i++){ 39 | scanf("%lf %lf %lf %lf %lf", &v1, &v2, &v3, &a1, &a2); 40 | t1 = v1/a1; 41 | t2 = v2/a2; 42 | t3 = t1; 43 | if(t1 < t2) 44 | t3 = t2; 45 | bird = v3 * t3; 46 | trains = v1 * t1 - .5 * a1 * t1 * t1; 47 | trains += v2 * t2 - .5 * a2 * t2 * t2; 48 | printf("Case %d: %.10lf %.10lf\n", i, trains, bird); 49 | 50 | } 51 | return 0; 52 | } 53 | ``` 54 | 55 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Creative Commons Legal Code 2 | 3 | CC0 1.0 Universal 4 | 5 | CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE 6 | LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN 7 | ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS 8 | INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES 9 | REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS 10 | PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM 11 | THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED 12 | HEREUNDER. 13 | 14 | Statement of Purpose 15 | 16 | The laws of most jurisdictions throughout the world automatically confer 17 | exclusive Copyright and Related Rights (defined below) upon the creator 18 | and subsequent owner(s) (each and all, an "owner") of an original work of 19 | authorship and/or a database (each, a "Work"). 20 | 21 | Certain owners wish to permanently relinquish those rights to a Work for 22 | the purpose of contributing to a commons of creative, cultural and 23 | scientific works ("Commons") that the public can reliably and without fear 24 | of later claims of infringement build upon, modify, incorporate in other 25 | works, reuse and redistribute as freely as possible in any form whatsoever 26 | and for any purposes, including without limitation commercial purposes. 27 | These owners may contribute to the Commons to promote the ideal of a free 28 | culture and the further production of creative, cultural and scientific 29 | works, or to gain reputation or greater distribution for their Work in 30 | part through the use and efforts of others. 31 | 32 | For these and/or other purposes and motivations, and without any 33 | expectation of additional consideration or compensation, the person 34 | associating CC0 with a Work (the "Affirmer"), to the extent that he or she 35 | is an owner of Copyright and Related Rights in the Work, voluntarily 36 | elects to apply CC0 to the Work and publicly distribute the Work under its 37 | terms, with knowledge of his or her Copyright and Related Rights in the 38 | Work and the meaning and intended legal effect of CC0 on those rights. 39 | 40 | 1. Copyright and Related Rights. A Work made available under CC0 may be 41 | protected by copyright and related or neighboring rights ("Copyright and 42 | Related Rights"). Copyright and Related Rights include, but are not 43 | limited to, the following: 44 | 45 | i. the right to reproduce, adapt, distribute, perform, display, 46 | communicate, and translate a Work; 47 | ii. moral rights retained by the original author(s) and/or performer(s); 48 | iii. publicity and privacy rights pertaining to a person's image or 49 | likeness depicted in a Work; 50 | iv. rights protecting against unfair competition in regards to a Work, 51 | subject to the limitations in paragraph 4(a), below; 52 | v. rights protecting the extraction, dissemination, use and reuse of data 53 | in a Work; 54 | vi. database rights (such as those arising under Directive 96/9/EC of the 55 | European Parliament and of the Council of 11 March 1996 on the legal 56 | protection of databases, and under any national implementation 57 | thereof, including any amended or successor version of such 58 | directive); and 59 | vii. other similar, equivalent or corresponding rights throughout the 60 | world based on applicable law or treaty, and any national 61 | implementations thereof. 62 | 63 | 2. Waiver. To the greatest extent permitted by, but not in contravention 64 | of, applicable law, Affirmer hereby overtly, fully, permanently, 65 | irrevocably and unconditionally waives, abandons, and surrenders all of 66 | Affirmer's Copyright and Related Rights and associated claims and causes 67 | of action, whether now known or unknown (including existing as well as 68 | future claims and causes of action), in the Work (i) in all territories 69 | worldwide, (ii) for the maximum duration provided by applicable law or 70 | treaty (including future time extensions), (iii) in any current or future 71 | medium and for any number of copies, and (iv) for any purpose whatsoever, 72 | including without limitation commercial, advertising or promotional 73 | purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each 74 | member of the public at large and to the detriment of Affirmer's heirs and 75 | successors, fully intending that such Waiver shall not be subject to 76 | revocation, rescission, cancellation, termination, or any other legal or 77 | equitable action to disrupt the quiet enjoyment of the Work by the public 78 | as contemplated by Affirmer's express Statement of Purpose. 79 | 80 | 3. Public License Fallback. Should any part of the Waiver for any reason 81 | be judged legally invalid or ineffective under applicable law, then the 82 | Waiver shall be preserved to the maximum extent permitted taking into 83 | account Affirmer's express Statement of Purpose. In addition, to the 84 | extent the Waiver is so judged Affirmer hereby grants to each affected 85 | person a royalty-free, non transferable, non sublicensable, non exclusive, 86 | irrevocable and unconditional license to exercise Affirmer's Copyright and 87 | Related Rights in the Work (i) in all territories worldwide, (ii) for the 88 | maximum duration provided by applicable law or treaty (including future 89 | time extensions), (iii) in any current or future medium and for any number 90 | of copies, and (iv) for any purpose whatsoever, including without 91 | limitation commercial, advertising or promotional purposes (the 92 | "License"). The License shall be deemed effective as of the date CC0 was 93 | applied by Affirmer to the Work. Should any part of the License for any 94 | reason be judged legally invalid or ineffective under applicable law, such 95 | partial invalidity or ineffectiveness shall not invalidate the remainder 96 | of the License, and in such case Affirmer hereby affirms that he or she 97 | will not (i) exercise any of his or her remaining Copyright and Related 98 | Rights in the Work or (ii) assert any associated claims and causes of 99 | action with respect to the Work, in either case contrary to Affirmer's 100 | express Statement of Purpose. 101 | 102 | 4. Limitations and Disclaimers. 103 | 104 | a. No trademark or patent rights held by Affirmer are waived, abandoned, 105 | surrendered, licensed or otherwise affected by this document. 106 | b. Affirmer offers the Work as-is and makes no representations or 107 | warranties of any kind concerning the Work, express, implied, 108 | statutory or otherwise, including without limitation warranties of 109 | title, merchantability, fitness for a particular purpose, non 110 | infringement, or the absence of latent or other defects, accuracy, or 111 | the present or absence of errors, whether or not discoverable, all to 112 | the greatest extent permissible under applicable law. 113 | c. Affirmer disclaims responsibility for clearing rights of other persons 114 | that may apply to the Work or any use thereof, including without 115 | limitation any person's Copyright and Related Rights in the Work. 116 | Further, Affirmer disclaims responsibility for obtaining any necessary 117 | consents, permissions or other rights required for any use of the 118 | Work. 119 | d. Affirmer understands and acknowledges that Creative Commons is not a 120 | party to this document and has no duty or obligation with respect to 121 | this CC0 or use of the Work. 122 | -------------------------------------------------------------------------------- /LightOJ/1002/en.md: -------------------------------------------------------------------------------- 1 | # LOJ 1002 - Country Roads 2 | --- 3 | Tags : graph, single source shortest path, 4 | 5 | 6 | We will be given information of an area map (_undirected graph / bi-directional graph_) through the number of cities (_nodes_),number of roads (_edges_) in total and the cost (_weight_) for each _pair_ of linked cities via the road. And we will also be given __t__ the home town (_the staring node_) and we have to print out the minimum cost to reach this town from other cities. 7 | 8 | ### Helpful Resources 9 | 10 | * [Graph (abstract data type)](https://en.wikipedia.org/wiki/Graph_(abstract_data_type) "Graph (abstract data type) - WikiPedia") 11 | 12 | * [Dijkstra's algorithm](https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm "Dijkstra's algorithm - WikiPedia") 13 | 14 | * [Dijkstra’s shortest path algorithm - GeeksForGeeks](https://www.geeksforgeeks.org/dijkstras-shortest-path-algorithm-greedy-algo-7/https://www.geeksforgeeks.org/dijkstras-shortest-path-algorithm-greedy-algo-7/ "Dijkstra’s shortest path algorithm | Greedy Algo-7") 15 | 16 | * [Abdul Bari's Explanation of Dijsktra (Video)](https://www.youtube.com/watch?v=XB4MIexjvY0 "Abdul Bari's Explanation of Dijsktra - YouTube") 17 | 18 | 19 | ## Solution 20 | 21 | At first we will simply create a _graph_ structure for the _Area Map_ in any preferred method (adj. matrix/ linked list). The problem statement has confirmed : (1) there shall be no negative cost for the roads and (2) the _graph_ is a _bi-directional_/_undirected graph_. We can apply _Dijsktra's Algorihtm_ or its derivative or any similar. But we must keep in mind that we are finding _many dedicated optimal paths(one path per one city), not one optimal path to traverse all the cities in 1 go_. For each __individual city's optimal path__, we take the _minimum_ from _all the path's costs_. Here, a __path's cost = maximum weighted road encountered__ which we will be saving in a separate _array/list_. 22 | 23 | 24 | We at first __update__ the __cost__ if the two cities have _directly_ connected edges among them, and in that case we will only keep the _lowest possible weight_. It's a _duplicate_ we get rid off while taking inputs for _edges_. Let's look at the `Case 2`'s inputs': 25 | ``` 26 | 5 4 27 | 0 1 5 28 | 0 1 4 29 | 2 1 3 30 | 3 4 7 31 | 1 32 | ``` 33 | In this case, `0 1 5` and `0 1 4` are inputs for `0 -- 1` edge along with the weight/cost. We will `update` while taking `inputs` and update from `cost[0,1] = 5` to `cost[0,1] = 4` as it is minimum among those two __directly connected edges__. 34 | 35 | Now we need to traverse and update costs. We will go full __brute force__ by not leaving any route for a _home town_ to _another city_ untried. For example: 36 | 37 | ![graph](graph.png "Example") 38 | 39 | __All the possible paths for `1 to 2`__: 40 | 41 | | Route | Max Road Cost | Update | 42 | | :--- | :---- | :--- | 43 | | 1 -- 0 -- 3 -- 4 -- 2 | 8 | From `infinity` to `8` | 44 | | 1 -- 4 -- 3 -- 0 -- 2 | 9 | No | 45 | | 1 -- 0 -- 2 | 9 | No | 46 | | 1 -- 4 -- 2 | 7 | From `8` to `7` | 47 | 48 | This is how we are traversing, leaving no path untried. We just update the distance array/list for `[1,2] = 7` as it is the _minimum_. We are only updating the cost of the _destination_. We repeat this process for from _home town_ to all the other cities and ultimately get the distance array/list. 49 | 50 | __What would happen if we had marked to avoid repetition so that we find _just one single optimal path to travel them all in 1 go_?__ 51 | 52 | | Current City | Visited | Next City (City with lower cost) | Update | Highest Road Cost | 53 | | :--- | :--- | :--- | :---| :---| 54 | | 1 | {} | 0 | [1,0] = 2| 2| 55 | | 0 |{0}| 3|[1,3] = 3 | 3| 56 | |3| {0,3}| 4 | [1,4] = 8|8| 57 | |4|{0,3,4}|2| [1,2] = 8| 8| 58 | |2|{0,3,4,2}|All City Traversed| N/A | 8| 59 | 60 | 61 | ![graph](graph2.png "Example 2") 62 | 63 | We have constructed a single optimal path, but the only thing wrong here is `[1,2] = 8` which is the wrong answer. Thus we are not to use _any algorithm that_ re-maps the whole area or does not check all possible routes in a _brute force_ manner. 64 | 65 | __Caution__ : Remember to use fast I/O for your preferred language as per the suggestion from the problem statement and find out what may disrupt them to avoid it. 66 | 67 | The above implementation is `accepted`. 68 | 69 | ## Solution in C++ 70 | ```cpp 71 | 72 | #include 73 | using namespace std; 74 | 75 | int main() 76 | { 77 | //Enabling fast I/O for Cpp. Don't use anything that disrupts fast I/O (For example: `endl`). 78 | ios::sync_with_stdio(false); 79 | cin.tie(NULL); 80 | cout.tie(NULL); 81 | 82 | int testCases, numberOfCities, numberOfRoads, 83 | sourceCity, destinationCity, roadCost, homeTown, maxCostFound; 84 | /* 85 | sourceCity = edge's first endpoint 86 | destinationCity = edge's second endpoint 87 | homeTown = source node from where we traverse 88 | 89 | */ 90 | 91 | cin >> testCases; 92 | 93 | for (int i = 1; i <= testCases; i++) 94 | { 95 | cin >> numberOfCities >> numberOfRoads; 96 | 97 | vector areaMap[numberOfCities]; //actual graph 98 | int distanceFromHomeTown[numberOfCities]; //distance output array 99 | int cost[numberOfCities][numberOfCities]; //road costs 100 | 101 | memset(cost, 0, sizeof(cost)); //initially setting the costs as not specified 102 | for (int i = 0; i <= numberOfCities; i++) 103 | distanceFromHomeTown[i] = INT_MAX; 104 | 105 | //Adding each given roads while checking if already a low cost road exist between them or not 106 | for (int i = 0; i < numberOfRoads; i++) 107 | { 108 | cin >> sourceCity >> destinationCity >> roadCost; 109 | 110 | if (cost[sourceCity][destinationCity]) //checking any previous road exists or not 111 | { 112 | cost[sourceCity][destinationCity] = cost[destinationCity][sourceCity] = min(cost[sourceCity][destinationCity], roadCost); 113 | } 114 | else 115 | { 116 | //adding new road 117 | areaMap[sourceCity].push_back(destinationCity); 118 | areaMap[destinationCity].push_back(sourceCity); 119 | cost[sourceCity][destinationCity] = cost[destinationCity][sourceCity] = roadCost; 120 | } 121 | } 122 | 123 | cin >> homeTown; 124 | 125 | queue cityQueue; //making a queue to traverse through each of the city 126 | 127 | cityQueue.push(homeTown); //pushing the home town as our start point or source node 128 | 129 | distanceFromHomeTown[homeTown] = 0; 130 | 131 | while (!cityQueue.empty()) 132 | { 133 | 134 | 135 | int startingCity = cityQueue.front(); 136 | 137 | cityQueue.pop(); //taking it out since it will be traversed now 138 | 139 | //Checking the other cities that can be reached via startingCity 140 | 141 | /* 142 | don't sum previous road costs along the way and update. 143 | as per problem requirement, we only update the `distance array` by `maximum weight` encountered, not the `cost` array. 144 | don't check for duplicate enqueue as we may find a better path that has lesser max value. 145 | we need to go full brute force leaving no path unchecked because of the problem requirements. 146 | */ 147 | 148 | for (int i = 0; i < areaMap[startingCity].size(); i++) 149 | { 150 | int currentCity = areaMap[startingCity][i]; 151 | maxCostFound = max(distanceFromHomeTown[startingCity], 152 | cost[startingCity][currentCity]); 153 | if (distanceFromHomeTown[currentCity] > maxCostFound) 154 | { 155 | distanceFromHomeTown[currentCity] = maxCostFound; 156 | cityQueue.push(currentCity); 157 | } 158 | } 159 | } 160 | 161 | cout << "Case " << i << ":\n"; 162 | for (int i = 0; i < numberOfCities; i++) 163 | if (distanceFromHomeTown[i] == INT_MAX) 164 | cout << "Impossible\n"; 165 | else 166 | cout << distanceFromHomeTown[i] << "\n"; 167 | } 168 | 169 | return 0; 170 | } 171 | 172 | 173 | ``` 174 | -------------------------------------------------------------------------------- /LightOJ/1004/en.md: -------------------------------------------------------------------------------- 1 | # LOJ 1004 - Monkey Banana Problem 2 | --- 3 | Tags : Dynamic Programming, Memoization 4 | 5 | You are in the world of mathematics to solve the great "Monkey Banana Problem". It states that, a monkey enters into a diamond shaped two dimensional array and can jump in any of the adjacent cells down from its current position (see figure). While moving from one cell to another, the monkey eats all the bananas kept in that cell. The monkey enters into the array from the upper part and goes out through the lower part. Find the maximum number of bananas the monkey can eat. 6 | 7 | ![problem image](1004problem.png "Banana Matrix") 8 | 9 | ### Input 10 | 11 | Input starts with an integer __T (≤ 50)__, denoting the number of test cases. 12 | 13 | Every case starts with an integer __N (1 ≤ N ≤ 100)__. It denotes that, there will be __2*N - 1__ rows. The __i__th __(1 ≤ i ≤ N)__ line of the next __N__ lines contains exactly __i__ numbers. Then there will be __N - 1__ lines. The __j__th __(1 ≤ j < N)__ line contains __N - j__ integers. Each number is greater than __zero__ and less than 215. 14 | 15 | ### Output 16 | 17 | For each case, print the case number and maximum number of bananas eaten by the monkey. 18 | 19 | 20 | ### Helpful Resources 21 | 22 | * [Memoization - WikiPedia](https://en.wikipedia.org/wiki/Memoization "Memoization - WikiPedia") 23 | 24 | * [Memoization (1D, 2D and 3D) - GeeksForGeeks](https://www.geeksforgeeks.org/memoization-1d-2d-and-3d/ "Memoization (1D, 2D and 3D)") 25 | 26 | * [What is Dynamic Programming ? - educative.io](https://www.educative.io/courses/grokking-dynamic-programming-patterns-for-coding-interviews/m2G1pAq0OO0 "[What is Dynamic Programming?") 27 | 28 | * [Dynamic Programming, Memoization, Tabulation - freeCodeCamp.org 29 | (Video)](https://www.youtube.com/watch?v=oBt53YbR9Kk "FreeCodeCamp - YouTube") 30 | 31 | ## Solution 32 | 33 | To solve this we must construct a _matrix_ (array/linked list/any similar data structure) to take inputs. We can take inputs in any preferred _indexing_ as long as we can easily determine by ourselves __which 2 blocks are adjacent from upper row for a particular block__. 34 | For example: 35 | 36 | | R/C | 0 | 1 | 2 | 3 | 37 | |---|---|---|----|----| 38 | | __0__ | 7 |0|0 |0 | 39 | | __1__ | 6 | 4 |0 |0 | 40 | | __2__ | 2 | 5 | 10 |0 | 41 | | __3__ | 9 | 8 | 12 | 2 | 42 | | __4__ |0| 2 | 12 | 7 | 43 | | __5__ |0|0| 8 | 2 | 44 | | __6__ |0|0|0 | 10 | 45 | 46 | Here in this kind of indexing, the __2 adjacent blocks__ from __upper row__ for block __BR C__ is, __B(R-1) C__ & __B(R-1) (C-1)__ (i.e.: block2 1's adjacent blocks from upper row are block1 1 and block1 0 where block2 0 has only block1 0 ). __Remember, we need to avoid negative index__. 47 | 48 | We will take another matrix of the same dimension to store the _max possible value can be reached for each particular block_. Now we just simply start updating the values for each block from its upper row and ultimately will obtain the max possible value for __end block__. 49 | ``` 50 | In our implementation, 51 | 52 | adjacent blocks from upper row for block[row][column] 53 | = { block[row-1][column], block[row-1][column-1] } 54 | * for block[row][0], adjacent block = block[row-1][0] only 55 | 56 | maxBanana[row][column] 57 | = ( maximum( block[row-1][column], block[row-1][column-1] ) ) 58 | + actualBanaMatrix[row][column] 59 | ``` 60 | | Block(R,C) | Cumulative Banana (B[R-1][C-1]) | Cumulative Banana (B[R-1][C]) | Max among Cumulative Bananas (Upper Row) |Actual Banana Count | Update Cumulative Banana (This Block) | 61 | |:---:|---|---|----|----|----| 62 | | 0,0 | N/A | N/A | N/A | 7 | 7| 63 | | 1,0 | N/A | 7 | 7 | 6 | 7 + 6 = 13| 64 | | 1,1 | 7 | 0 | 7 | 4 | 7 + 4 = 11| 65 | | 2,0 | N/A | 13 | 13 | 3 | 13 + 2 = 15| 66 | | 2,1 | 11 | 13 | 13 | 5 | 13 + 5 = 18| 67 | | 2,2 | 11 | 0 | 11 | 10 | 11 + 10 = 21| 68 | | 3,0 | N/A | 15 | 15 | 9 | 15 + 9 = 24| 69 | | 3,1 | 15 | 18 | 18 | 8 | 18 + 8 = 26| 70 | | 3,2 | 18 | 21 | 21 | 12 | 21 + 12 = 33| 71 | | 3,3 | 21 | 0 | 21 | 2 | 21 + 2 = 23| 72 | | 4,1 | 24 | 26 | 26 | 2 | 26 + 2 = 28| 73 | | 4,2 | 26 | 33 | 33 | 12 | 33 + 12 = 45| 74 | | 4,3 | 33 | 23 | 33 | 7 | 33 + 7 = 40| 75 | | 5,2 | 28 | 45 | 45 | 8 | 45 + 8 = 53| 76 | | 5,3 | 45 | 40 | 45 | 2 | 45 + 2 = 47| 77 | | __6,3__ | 53 | 47 | 53 | 10 | 53 + 10 = __63__| 78 | 79 | The matrix for cumulative sum looks like this: 80 | 81 | | R/C | 0 | 1 | 2 | 3 | 82 | |---|---|---|----|----| 83 | | __0__ | 7 |0|0 |0 | 84 | | __1__ | 13 |11 |0 |0 | 85 | | __2__ | 15 | 18 | 21 |0 | 86 | | __3__ | 24 | 26 | 33 | 23 | 87 | | __4__ |0| 28 | 45 | 40 | 88 | | __5__ |0|0| 53 | 47 | 89 | | __6__ |0|0|0 | __63__ | 90 | 91 | As we can see, the __end block__ has the __answer__. 92 | 93 | The above implementation is `accepted`. 94 | 95 | __Caution__ : Remember to use fast I/O for your preferred language as per the suggestion from the problem statement and find out what may disrupt them, so we can avoid it. 96 | 97 | __Notes__: 98 | * You can take input in any _pattern_, a different _pattern_ will have different _indices_ to point out the _adjacent blocks_. Compare and update according to your implementation. 99 | * You can use _linked list_/_vector_/_an implementation of similar data structure_, too. Just remember that the __read/write__ time should be _constant_. 100 | * You can solve this problem by a _recursive_ implementation. Memory limit for this particular problem is __64 MB__, so stacks from _recursion states_ won't throw `Memory Limit Exceeded` exception. 101 | 102 | ## Solution in C++ 103 | 104 | ```cpp 105 | #include 106 | using namespace std; 107 | 108 | int main() 109 | { 110 | //Enabling fast I/O 111 | ios::sync_with_stdio(false); 112 | cin.tie(NULL); 113 | cout.tie(NULL); 114 | 115 | int testCases, numberOfColumns; 116 | 117 | cin >> testCases; 118 | for (int i = 1; i <= testCases; i++) 119 | { 120 | cin >> numberOfColumns; 121 | int bananaMatrix[2 * numberOfColumns - 1][numberOfColumns]; //Input matrix 122 | int maxBanana[2 * numberOfColumns - 1][numberOfColumns]; //Memoized matrix 123 | 124 | memset(maxBanana, 0, sizeof(maxBanana)); //Setting 0 to all cell, will update for maximum 125 | memset(bananaMatrix, 0, sizeof(bananaMatrix)); //Setting 0 to all cell, will update for inputs 126 | 127 | //Input for upper triangle 128 | for (int row = 0; row < numberOfColumns; row++) 129 | for (int column = 0; column <= row; column++) 130 | cin >> bananaMatrix[row][column]; 131 | 132 | //Input for lower triangle 133 | int shiftedPosition = 1; 134 | for (int row = numberOfColumns; row < (numberOfColumns * 2) - 1; row++) 135 | { 136 | for (int column = shiftedPosition; column < numberOfColumns; column++) 137 | cin >> bananaMatrix[row][column]; 138 | shiftedPosition++; 139 | } 140 | 141 | /* 142 | Now we memoize the maxBanna array. 143 | We will start from the 2nd row (array[1][*]). 144 | We will check which ever 2 adjacent blocks from up can give more banana and update from the max. 145 | */ 146 | 147 | //Memoizing the upper triangle to store max value 148 | maxBanana[0][0] = bananaMatrix[0][0]; 149 | for (int row = 1; row < numberOfColumns; row++) 150 | { 151 | for (int column = 0; column <= row; column++) 152 | if (column == 0)//Caution for negative indexes. 153 | maxBanana[row][column] = maxBanana[row - 1][column] + bananaMatrix[row][column]; 154 | else 155 | maxBanana[row][column] = max(maxBanana[row - 1][column], maxBanana[row - 1][column - 1]) + bananaMatrix[row][column]; 156 | } 157 | 158 | //Memoizing the lower triangle to store the max value 159 | shiftedPosition = 1; 160 | for (int row = numberOfColumns; row < (numberOfColumns * 2) - 1; row++) 161 | { 162 | for (int column = shiftedPosition; column < numberOfColumns; column++) 163 | maxBanana[row][column] = max(maxBanana[row - 1][column], maxBanana[row - 1][column - 1]) + bananaMatrix[row][column]; 164 | shiftedPosition++; 165 | } 166 | cout << "Case " << i << ": " << maxBanana[2 * numberOfColumns - 2][numberOfColumns - 1] << "\n"; 167 | } 168 | 169 | return 0; 170 | } 171 | ``` 172 | -------------------------------------------------------------------------------- /LightOJ/1075/en.md: -------------------------------------------------------------------------------- 1 | # LOJ 1075 - Finding Routes 2 | --- 3 | Tags : Associative Array, Map, Dictionary, Key-Value Pair 4 | 5 | Shakil has been the greatest boy-scout in Bangladesh and has become quite a superstar because he always organized the most wonderful scavenger hunts (you know, where the kids have to find a certain route following certain hints). Shakil has retired now, but a nation-wide election quickly found a successor for him, a guy called Nabil. He does a poor job though, and wants to learn from Shakil's routes. Unfortunately Shakil has left only a few notes for his successor. 6 | 7 | Shakil never wrote down his routes completely, he only left lots of little sheets on which he had written two consecutive steps of the routes. He then mixed these sheets and memorized his routes similarly to how some people learn for exams: practicing again and again, always reading thef irst step and trying to remember the following. This made much sense, since one step always required something from the previous step. Nabil however would like to have a route written down as one long sequence of all the steps in the correct order. Please help him make the nation happy again by reconstructing the routes. Shakil never visited a single place twice. 8 | 9 | ### Input 10 | 11 | Input starts with an integer __T (≤ 80)__, denoting the number of test cases. 12 | 13 | Each case contains one route and its first line tells you how many steps __(3 ≤ S ≤ 333)__ the route has. The next __S - 1__ lines, each contains one consecutive pair of the steps on the route separated by a single space. The name of each step is always a single string of letters. 14 | 15 | ### Output 16 | 17 | For each case, print the case number in a single line. Then print __S__ lines containing the steps of the route in the correct order. Print a blank line after each case. 18 | 19 | ### Helpful Resources 20 | * [Associative array - Wikipedia](https://en.wikipedia.org/wiki/Associative_array "WikiPedia") 21 | * [Introduction to Hash Tables and Dictionaries (Data Structures & Algorithms #13) - CS Dojo -YouTube](https://www.youtube.com/watch?v=sfWyugl4JWA "Maps and Hash tables") 22 | * [Map in C++ Standard Template Library (STL) - GeeksForGeeks - YouTube](https://youtu.be/kDwXAmLz47w "C++ Programming Language Tutorial | Map in C++ STL | GeeksforGeeks") 23 | * [Map (Go Programming Language) - GeeksforGeeks - YouTube](https://www.youtube.com/watch?v=j5KA7K0-gbY) 24 | * [Python Maps - TutorialsPoint](https://www.tutorialspoint.com/python_data_structure/python_maps.htm "Python - Maps") 25 | 26 | ## Solution 27 | This is an implementation problem that we can solve with map/associative-array/dictionary/similar key-value pair data structure. 28 | 29 | To keep record of the unique places, will assign an __unique number/ID__ to each __unique place's name__. We will have two arrays: 30 | - __Count array__ : This will store the how many places are __directly__ connected to it. The number of __directly connected places__ can help us determine if this _particular_ place is the __ultimate start/end point or not__. The __ultimate start point__ will have __no__ other place __before__ that leads to it since it is the place from where traversing __starts__, in other words the _count_ will be `1`. Similarly, for __ultimate end point__, the _count_ will be `1` too and there will be no place to go to __after__ it. 31 | 32 | - __Next Destination array__ : This array's `index = initial destination` (here, _initial destination_ does __not__ mean the ultimate start point) and `value = next destination`. Basically, `index ---> value = currentPoint ---> nextPoint`. It will help us storing we can go from where to where. Note that we will __not__ be updating this array as if the places were _bi-directional_ links. What we __won't__ do : `nextDestination[ID1] = ID2 & so nextDestination[ID2] = ID1`. __We are not updating in a bi-directional way__. 33 | 34 | 35 | 36 | For input, we take two maps: 37 | - ____ map: will save the inputs taking the __place's name__ as the __key__. 38 | 39 | - ____ map: will save the inputs taking the __unique number assigned to that place__ as the __key__. 40 | 41 | A map itself can avoid duplication of `key` entry, however if we push it anyways then the `value` will get updated which we don't want, so we will check if a `key` (Place's Name) has been added or not. We are keeping two maps so that we can __easily search up a place's unique number by putting it to the map and vice versa__ in a __constant__ time. 42 | 43 | Now when we finally have everything done we can easily determine the __ultimate start point__ by the help of both `count` and `nextDestination` arrays. For example let's take a set of inputs: 44 | 45 | ``` 46 | 4 47 | SwimmingPool OldTree 48 | BirdsNest Garage 49 | Garage SwimmingPool 50 | ``` 51 | 52 | Now if we have done everything according to above mentioned procedures, we will have `nextDestination` and `count` array like this: 53 | 54 | |Index (Unique Number)|Count| Next Destination| Start Point?| 55 | |--|--|--|--| 56 | |1|2|2|False| 57 | |2|__1__|__0__|Ultimate End Point| 58 | |__3__|__1__|__4__|__True__| 59 | |4|2|1|False| 60 | 61 | Since now we know the __ultimate start point__ we can start traversing as we also have __what is next, after that, then again after that... to the ultimate end point__. 62 | 63 | Now if we just loop the following until the number of `steps` required, we get all the outputs. 64 | ``` 65 | Current Place's Name = [Current Place's ID] 66 | Next Place's ID = Next Destination[Current Place's ID] 67 | Current Place's ID = Next Place's ID 68 | ``` 69 | The above implementation is `accepted`. 70 | 71 | ## Solution in C++ 72 | ```cpp 73 | #include 74 | using namespace std; 75 | 76 | int main() 77 | { 78 | //Enable fast I/O 79 | ios::sync_with_stdio(false); 80 | cin.tie(NULL); 81 | cout.tie(NULL); 82 | 83 | int testCases, steps, uniqueNumber, startPoint; 84 | string firstPoint, secondPoint; 85 | 86 | cin >> testCases; 87 | 88 | for (int test = 1; test <= testCases; test++) 89 | { 90 | cin >> steps; 91 | 92 | //Index is the origin and Value is the destination 93 | int nextDestination[steps + 1]; 94 | 95 | 96 | //How many destinations are directly linked? 97 | int count[steps + 1]; 98 | 99 | 100 | memset(nextDestination, 0, sizeof(nextDestination));//Setting to 0 for false 101 | memset(count, 0, sizeof(count));//Setting 0 for no direct connections 102 | 103 | map placeIndexMap;//Map to store index as value 104 | map indexPlaceMap;//Map to store string as value 105 | 106 | uniqueNumber = 1; 107 | for (int i = 1; i < steps; i++) 108 | { 109 | cin >> firstPoint >> secondPoint; 110 | 111 | //Checking if duplicate key or not 112 | if (!placeIndexMap[firstPoint]) 113 | { 114 | placeIndexMap[firstPoint] = uniqueNumber; 115 | indexPlaceMap[uniqueNumber] = firstPoint; 116 | uniqueNumber++; 117 | } 118 | 119 | //Checking if duplicate key or not 120 | if (!placeIndexMap[secondPoint]) 121 | { 122 | placeIndexMap[secondPoint] = uniqueNumber; 123 | indexPlaceMap[uniqueNumber] = secondPoint; 124 | uniqueNumber++; 125 | } 126 | 127 | /* 128 | Remember we are updating the array for one direction. 129 | Thus, when a count of a place is 1 but nextDestination array has 0 for that uniqueNumber, 130 | means that the place is the ultimate end point. 131 | And when count is relation is not 0 and count is not more than 1, 132 | it means that it is the ultimate start point. 133 | */ 134 | 135 | //Updating a for the next point 136 | nextDestination[placeIndexMap[firstPoint]] = placeIndexMap[secondPoint]; 137 | //We won't be updating the nextDestination for the other way around 138 | 139 | count[placeIndexMap[firstPoint]]++;//Incrementing how many places are directly linked 140 | count[placeIndexMap[secondPoint]]++;//Incrementing how many places are directly linked 141 | } 142 | 143 | //Finding the ultimate startPoint 144 | for (int i = 1; i < uniqueNumber; i++) 145 | if (nextDestination[i] && count[i] == 1) 146 | { 147 | startPoint = i; 148 | break; 149 | } 150 | 151 | cout << "Case " << test << ":\n"; 152 | 153 | for (int i = 1; i <= steps; i++) 154 | { 155 | cout << indexPlaceMap[startPoint] << "\n"; 156 | //Assigining the next start point (current start point's end point) 157 | startPoint = nextDestination[placeIndexMap[indexPlaceMap[startPoint]]]; 158 | } 159 | 160 | cout << "\n"; 161 | } 162 | 163 | return 0; 164 | } 165 | ``` 166 | -------------------------------------------------------------------------------- /LightOJ/1136/en.md: -------------------------------------------------------------------------------- 1 | Written by: [Rahat Hossain](https://github.com/rahathossain690) 2 | 3 | # LOJ 1136 - Division by 3 4 | 5 | ## Problem 6 | Straight from the statement: "There is sequence 1, 12, 123, 1234, ..., 12345678910, ... . Now you are given two integers **A** and **B**, you have to find the number of integers from **A**th number to **B**th (inclusive) number, which are divisible by 3. 7 | 8 | For example, let **A** = 3. **B** = 5. So, the numbers in the sequence are, 123, 1234, 12345. And 123, 12345 are divisible by 3. So, the result is 2." 9 | 10 | Looking a bit into the sequence you will find out that for a certain position **A** the number can be found by simply appending all natural numbers from 1 upto **A** one after another. So if **A** = 5: sequence is 12345, if **A** = 12: sequence is 123456789101112. 11 | 12 | Now you will be given two numbers **A** and **B**. You have to find out how many numbers on that sequence are divisible by 3 on the position of **A**, **A+1**, ..., **B** (from position **A** to position **B** inclusive). 13 | 14 | ## Constrains: 15 | Test cases T (≤ 10000) and 1 ≤ A ≤ B < 2^31 16 | 17 | ## Observation 18 | 1. By looking at the constrains, it is quite sure that bruteforce approach is going to gift us TLE. (If you calculate all the number from range **A** to **B** and try to find out who amoung them are divisible by 3 you will get time limit exceeded). So we need a very effecient approach. 19 | 2. Numbers can be quite big. 20 | 21 | ## Understanding 1 22 | Let get our hands dirty by finding out if numbers from the sequence are divisible by 3. 23 | 24 | | Position at the sequence | Number | Is divisible by 3 | 25 | |--------------------------|-------------|-------------------| 26 | | 1 | 1 | false | 27 | | 2 | 12 | true | 28 | | 3 | 123 | true | 29 | | 4 | 1234 | false | 30 | | 5 | 12345 | true | 31 | | 6 | 123456 | true | 32 | | 7 | 1234567 | false | 33 | | 8 | 12345678 | true | 34 | | 9 | 123456789 | true | 35 | | 10 | 12345678910 | false | 36 | 37 | We can clearly see a repeatitive pattern. Here {1, 4, 7, 10...} positions are not divisible by 3 and rests are. 38 | 39 | Curious minds will want to know "why?". Simple! 40 | 41 | First, you may know that calcuting if a number is divisible by 3 is super easy. You just add all digits and see if the sum is divisible by 3 or not. So finding out if 123456 is divisible by 3 is equal to finding out if (1 + 2 + 3 + 4 + 5 + 6) = 21 is divisible by 3 or not. 42 | 43 | Now focus on the table. Each time we construct new position we just add the position-number to the previous value of the sequence, right? Let's follow an example. We have found out the 5th position in this sequence is 12345 which is divisible by 3 (12345 % 3 = 0; 12345 modulo 3 is zero. Also in other words (1 + 2 + 3 + 4 + 5) % 3 = 0). Now we construct 6th position in the sequence by just appending 6 to the last of the 5th number (123456). To calcuate if new number is divisible by 3 we can check that (1 + 2 + 3 + 4 + 5 + 6) % 3 is equal to 0 or not. Now after messing with paranthesis, you can see that (1 + 2 + 3 + 4 + 5 + 6) % 3 = ( (1 + 2 + 3 + 4 + 5) + 6) % 3. In other words for every **n***, *seq[n]** % 3 = (**seq[n - 1]** + n) % 3 = (**seq[n - 1]** % 3 + n % 3) % 3 (From modular arithmatic). 44 | 45 | Now look at this table: 46 | | Position at the sequence | Number | Number % 3 | Previous_number % 3 | Position % 3 | (Previous_number % 3 + Position % 3) % 3 | 47 | |--------------------------|-------------|------------|---------------------|--------------|------------------------------------------| 48 | | 1 | 1 | 1 | - | 1 | Default value to 1 | 49 | | 2 | 12 | 0 | 1 | 2 | ( 1 % 3 + 2 % 3) % 3 = 0 | 50 | | 3 | 123 | 0 | 0 | 0 | ( 0 % 3 + 0 % 3) % 3 = 0 | 51 | | 4 | 1234 | 1 | 0 | 1 | ( 0 % 3 + 1 % 3) % 3 = 1 | 52 | | 5 | 12345 | 0 | 1 | 2 | ( 1 % 3 + 2 % 3) % 3 = 0 | 53 | | 6 | 123456 | 0 | 0 | 0 | ( 0 % 3 + 0 % 3) % 3 = 0 | 54 | | 7 | 1234567 | 1 | 0 | 1 | ( 0 % 3 + 1 % 3) % 3 = 1 | 55 | | 8 | 12345678 | 0 | 1 | 2 | ( 1 % 3 + 2 % 3) % 3 = 0 | 56 | | 9 | 123456789 | 0 | 0 | 0 | ( 0 % 3 + 0 % 3) % 3 = 0 | 57 | | 10 | 12345678910 | 1 | 0 | 1 | ( 0 % 3 + 1 % 3) % 3 = 1 | 58 | 59 | Does the pattern make sense now? 60 | 61 | ## Understanding 2 62 | Previous undestanding is not enough to give you an AC, right? Now Let's look at the table a bit differently. Now we will add cumulative sum too and replace true/false with one/zero. 63 | 64 | | Position at the sequence | Number | Is divisible by 3 | Cumulative sum over divisibility | 65 | |--------------------------|-------------|-------------------|----------------------------------| 66 | | 1 | 1 | 0 | 0 | 67 | | 2 | 12 | 1 | 1 | 68 | | 3 | 123 | 1 | 2 | 69 | | 4 | 1234 | 0 | 2 | 70 | | 5 | 12345 | 1 | 3 | 71 | | 6 | 123456 | 1 | 4 | 72 | | 7 | 1234567 | 0 | 4 | 73 | | 8 | 12345678 | 1 | 5 | 74 | | 9 | 123456789 | 1 | 6 | 75 | | 10 | 12345678910 | 0 | 6 | 76 | 77 | Here cumulative sum for position **n** simply says "Between position 1 to **n** how many numbers are divisible by 3". Now can you tell how many numbers are divisible by 3 from position 4 to 7? We simply take the cumulative sum of position 7 and substract cumilative sum of position 3 (Because cumulative sum for position 7 says how many number are divisible by 3 from position 1 to 7, and we just substract how many numbers where divisible by 3 before the 4rth position). 78 | 79 | ## Understanding 3 80 | Now we know that cumulative sum can be the key to success. We just have to find it smartly. By looking at the last table we can get that {1, 4, 7, 10, ...} are not divisible by 3. And all this positions are also 1 modulo 3 (position % 3 = 1). So if we get a position which is 1 modulo 3 it will not be divisible, right? (If position % 3 = 1 then not divisible by 3.) 81 | 82 | Now, finding out how many numbers are divisible by 3 from 1 to **n** is quite equal to finding how many numbers are not divisible by 3 and substract the answer from **n**. (numbers_divisible_by_3_from_1_to_n = n - numbers_not_divisible_by_3). Now our problem has become smaller. Here we can see that for every three consecutive position starting from 1, first position is not divisible by 3. So to calculate how many numbers are not divisible by 3 in range of position 1 to **n**... 83 | 1. If n % 3 = 0 then exactly (n / 3) integers are not divisible by 3. 84 | 2. If n % 3 = 1 then exactly floor(n / 3) + 1 integers are not divisible by 3. 85 | 3. If n % 3 = 2 then exactly floor(n / 3) + 1 integers are not divisible by 3. 86 | So now we will get how many numbers are divisible by 3 by simply substracting the result found above from the number **n**. 87 | 88 | c function to calculate this is going to be (Beware of n = 1 case also)... 89 | ``` 90 | long long countNumbers(int n) 91 | { 92 | if (n == 0) 93 | return 0; 94 | int divisibles; 95 | if (n % 3 == 0) 96 | { 97 | divisibles = n / 3; 98 | } 99 | else 100 | { 101 | divisibles = (n / 3) + 1; 102 | } 103 | return n - divisibles; 104 | } 105 | ``` 106 | We solve this problem in O(1) right now. So as we will be given **A** and **B** and we need to find how many numbers from these range are divisible by 3 we simply do this. 107 | ``` 108 | long long result = numbers_divisible_by_3_from_1_to_n (B) - numbers_divisible_by_3_from_1_to_n (A - 1); 109 | ``` 110 | So overall complexity of the solution is O(1). Super handy! 111 | 112 | ## Solution in C ## 113 | ```c 114 | #include 115 | 116 | long long countNumbers(int n) 117 | { 118 | if (n == 0) 119 | return 0; 120 | int divisibles; 121 | if (n % 3 == 0) 122 | { 123 | divisibles = n / 3; 124 | } 125 | else 126 | { 127 | divisibles = (n / 3) + 1; 128 | } 129 | return n - divisibles; 130 | } 131 | 132 | int main() 133 | { 134 | int cases; 135 | long long A, B; 136 | scanf("%d", &cases); 137 | for (int test = 1; test <= cases; test++) 138 | { 139 | scanf("%lld %lld", &A, &B); 140 | long long result = countNumbers(B) - countNumbers(A - 1); 141 | printf("Case %d: %lld\n", test, result); 142 | } 143 | } 144 | ``` 145 | 146 | Happy Coding! 147 | 148 | 149 | -------------------------------------------------------------------------------- /LightOJ/1036/en.md: -------------------------------------------------------------------------------- 1 | # LOJ 1036 - A Refining Company 2 | 3 | --- 4 | Tags: Dynamic Programming, Best Cumulative Sum, Memoization 5 | 6 | The problem statement has these key points: 7 | 8 | 1. Conveyor belts moving up-down in the same column from block __b__ to the __radium refinery__ can be added up as long as there is no left-right conveyor belt moving in between them. 9 | 2. Conveyor belts moving left-right in the same row from block __b__ to the __uranium__ can be added up as long as there is no up-down conveyor belt moving in between them. 10 | 3. Any kind of conveyor is NOT _bi-directional_ when it comes to collection. It has to reach the refinery, in one direction. Either from right->left or from down->up, BUT left->right or up->down is not possible as the refineries’ placement is already given. This plays a heavy role in how to implement and memoize left-right (left->right or right->left?) and up-down (up->down or down->up?). 11 | 12 | We need to find the maximum possible cumulative sum that can be reached by following the above-mentioned rules. 13 | 14 | ### Helpful Resources 15 | 16 | * [Memoization - WikiPedia](https://en.wikipedia.org/wiki/Memoization "Memoization - Wikipedia") 17 | 18 | * [Memoization (1D, 2D and 3D) - GeeksForGeeks](https://www.geeksforgeeks.org/memoization-1d-2d-and-3d/ "Memoization (1D, 2D and 3D)") 19 | 20 | * [What is Dynamic Programming? - educative.io](https://www.educative.io/courses/grokking-dynamic-programming-patterns-for-coding-interviews/m2G1pAq0OO0 "[What is Dynamic Programming?") 21 | 22 | ## Solution (Key Points) 23 | 24 | There are 2 main sub-problems that we need to solve to get the final answer. They are: 25 | 26 | 1. What is the cumulation of each block resource variation-wise separately? We need this for comparison. 27 | 2. A block should be part of which type of conveyor? The actual decision-making part. 28 | 29 | ## 1. What is the cumulation of each block resource variation-wise separately? 30 | 31 | For this just add up the immediately previous block’s value with the current block’s value according to the conveyor type while taking inputs. Here the direction is important. We need to cumulative in the opposite direction of the refineries. Since the refineries are in left and up, cumulative in right and down direction. For `uraniumMatrix` it's `[row][column-1]` and for `radiumMatrix` it's `[row-1][column]`. 32 | 33 | ### Why does cumulation direction matter? 34 | 35 | Compare the following 2 for a simple left-right cumulation. 36 | 37 | Towards the refinery: 38 | 39 | ||0|1|2|3| 40 | |---|---|---|---|---| 41 | |0|<|<|^|x| 42 | 43 | If we cumulate towards the refinery, the direction of cumulation will be `(0,3) -> (0,2) -> (0,1) -> (0,0)`. But `(0,2)` cuts the path. So both `(0,0)` and `(0,1)` is _faulty_ cumulated. 44 | 45 | Opposite of the refinery: 46 | 47 | ||0|1|2|3| 48 | |---|---|---|---|---| 49 | |0|>|>|^|x| 50 | 51 | In this case, `(0,0) -> (0,1) -> (0,2) -> (0,3)` is the direction. So `(0,0)`, `(0,1)` is still correctly cumulated even if `(0,2)` is going upwards. 52 | 53 | ## 2. A block should be part of which type of conveyor? 54 | 55 | While addressing subproblem-1, we did not take into account the alternative resource for any of the matrices. We just do a tweaked cumulation sum comparing these 2 matrices and take the best among them in a third matrix, `memoizationMatrix`. 56 | 57 | ### What are the cases for ultimate cumulation? 58 | 59 | * Uranium is more: `memoizationMatrix[i-1][j] + uraniumMatrix[i][j]`. 60 | * Radium is more: `memoizationMatrix[i][j-1] + radiumMatrix[i][j]`. 61 | 62 | ### How are we doing the ultimate cumulation (reason behind choosing between `memoizationMatrix[i-1][j] + uraniumMatrix[i][j]` or `memoizationMatrix[i][j-1] + radiumMatrix[i][j]`)? 63 | 64 | ||0|1|2|3| 65 | |---|---|---|---|---| 66 | |0|x|x|x|x| 67 | |1|x|x|x|x| 68 | |2|x|x|x|x| 69 | |3|x|x|x|x| 70 | |4|x|x|x|x| 71 | 72 | Taking a look at the above, we need to know what is the ultimate cumulative sum of from `(0,0)` to `(2,3)` if we consider a block has been carrying the summation of its previous blocks either left-right (uranium/left-right) or up-down (radium/up-down)? 73 | 74 | left-right: 75 | 76 | ||0|1|2|3| 77 | |---|---|---|---|---| 78 | |0|>|>|>|>| 79 | |1|>|>|>|>| 80 | |2|>|>|>|>| 81 | 82 | {`>` is summed up with its value and the __IMMEDIATE__ previous block's value} 83 | 84 | Here, `((0,3) + (1,3) + (2,3))` [this is up->down, look at the image] = ULTIMATE CUMULATIVE SUM. Because while __solving sub-problem-1__, we made sure `(0,3) = (0,0) + (0,1) + (0,2) + (0,3)`, `(1,3) = (1,0) + (1,1) + (1,2) + (1,3)` and `(2,3) = (2,0) + (2,1) + (2,2) + (2,3)`, which was adding left->right. But we need `sum(each cumulated block)`, which is __actually__ from up->down of the cumulated left-right blocks. Basically, __(M0,j + M1,j + ... + Mn,j)__ is applicable for left-right ULTIMATE CUMULATIVE SUM for up to __Mn,j__ block. 85 | 86 | up-down: 87 | 88 | ||0|1|2|3| 89 | |---|---|---|---|---| 90 | |0|v|v|v|v| 91 | |1|v|v|v|v| 92 | |2|v|v|v|v| 93 | 94 | {`v` is summed up with its value and the __IMMEDIATE__ previous block's value} 95 | 96 | Similarly, here, `((2,0) + (2,1) + (2,2) + (2,3))` [this is left->right, look at the image] = ULTIMATE CUMULATIVE SUM. Because while __solving sub-problem-1__, we made sure `(2,0) = (0,0) + (1,0) + (2,0)`, `(2,1) = (0,1) + (1,1) + (2+1)`, `(2,2) = (0,2) + (1,2) + (2,2)` and `(2,3) = (0,3) + (1,3) + (2,3)`, which was adding up->down. But we need `sum(each cumulated block)`, which is __actually__ from left->right of the cumulated up->down blocks. Basically, __(Mi,0 + Mi,1 + ... + Mi,n)__ is applicable for up-down ULTIMATE CUMULATIVE SUM for up to __Mi,n__ block. 97 | 98 | We have established how are we doing full matrix cumulation up to a certain block left-right or up-down wise. 99 | 100 | Now for a matrix, 101 | 102 | ||0|1|2|3| 103 | |---|---|---|---|---| 104 | |0|x|x|x|x| 105 | |1|x|x|x|x| 106 | |2|x|x|x|x| 107 | |3|x|x|x|x| 108 | |4|x|x|x|x| 109 | 110 | If `x` holds the updated value then we can easily apply any of the above-mentioned block-wise cumulations, and then compare, right? The 3rd matrix is required for that. That's why `memoizationMatrix[i-1][j]` is the replacement of `uraniumMatrix[i-1][j]` and `memoizationMatrix[i][j-1]` is the replacement of `radiumMatrix[i][j-1]` to apply the left-right and up-down ULTIMATE CUMULATION SUM respectively. And if we have the updated value, it becomes irrelevant how `x` was obtained because the ultimate goal is to carry out the maximum cumulative sum block by block until the last block is met. THE CROSS PATHS WERE ALREADY HANDLED IN SUB-PROBLEM 1. 111 | 112 | ### Why a 3rd Matrix and not just update the values of the original? 113 | 114 | We can't over-write the original 2 matrices because while iterating, we can't be sure if there exists a single block of a particular conveyor that can outweigh the whole alternative conveyor up to that block. 115 | 116 | The above implementation is `accepted`. 117 | 118 | ## Time Complexity 119 | 120 | 2D Array -> mutation : O(1) 121 | 122 | 2D Array -> look up : O(1) 123 | 124 | Whole 2D Array -> iteration : O(row x column) 125 | 126 | Overall Complexity : O(3 x row x column) = O(row x column) 127 | 128 | ## Solution in Java (Iterative) 129 | 130 | * `Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));` will throw `TLE` or `MLE`. 131 | 132 | ```java 133 | import java.io.DataInputStream; 134 | import java.io.IOException; 135 | 136 | /* 137 | The `Reader` class aids only in taking inputs. Use any alternative that satisfies the time and memory constraints. 138 | https://www.geeksforgeeks.org/fast-io-in-java-in-competitive-programming/ - 4th implementation for fast Java I/O. 139 | */ 140 | 141 | class Reader { 142 | final private int BUFFER_SIZE = 1 << 16; 143 | private DataInputStream din; 144 | private byte[] buffer; 145 | private int bufferPointer, bytesRead; 146 | 147 | public Reader() { 148 | din = new DataInputStream(System.in); 149 | buffer = new byte[BUFFER_SIZE]; 150 | bufferPointer = bytesRead = 0; 151 | } 152 | 153 | public int nextInt() throws IOException { 154 | int ret = 0; 155 | byte c = read(); 156 | while (c <= ' ') { 157 | c = read(); 158 | } 159 | boolean neg = (c == '-'); 160 | if (neg) 161 | c = read(); 162 | do { 163 | ret = ret * 10 + c - '0'; 164 | } while ((c = read()) >= '0' && c <= '9'); 165 | 166 | if (neg) 167 | return -ret; 168 | return ret; 169 | } 170 | 171 | private void fillBuffer() throws IOException { 172 | bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); 173 | if (bytesRead == -1) 174 | buffer[0] = -1; 175 | } 176 | 177 | private byte read() throws IOException { 178 | if (bufferPointer == bytesRead) 179 | fillBuffer(); 180 | return buffer[bufferPointer++]; 181 | } 182 | 183 | public void close() throws IOException { 184 | if (din == null) 185 | return; 186 | din.close(); 187 | } 188 | } 189 | 190 | 191 | 192 | public class Main{ 193 | 194 | private static int FindMax(int a, int b){ 195 | return a > b ? a : b; 196 | } 197 | 198 | public static void main(String[] args) throws IOException { 199 | Reader in = new Reader(); 200 | int[][] radiumMatrix; // East to West. 201 | int[][] uraniumMatrix; // South to North. 202 | int[][] memoizationMatrix; // Result matrix and updated value holder. 203 | 204 | int testCases = in.nextInt(); 205 | 206 | for(int testCase = 1; testCase <= testCases; testCase++){ 207 | int m = in.nextInt(); 208 | int n = in.nextInt(); 209 | 210 | radiumMatrix = new int[m+1][n+1]; 211 | uraniumMatrix = new int[m+1][n+1]; 212 | memoizationMatrix = new int[m+1][n+1]; 213 | 214 | // Input for Uranium 215 | for(int i = 1; i <= m; i++){ 216 | for(int j = 1; j <= n; j++){ 217 | uraniumMatrix[i][j] = in.nextInt(); 218 | 219 | // East to West cumulative sum memoization 220 | uraniumMatrix[i][j] += uraniumMatrix[i][j-1]; 221 | } 222 | } 223 | 224 | // Input for Radium 225 | for(int i = 1; i <= m; i++){ 226 | for(int j = 1; j <= n; j++){ 227 | radiumMatrix[i][j] = in.nextInt(); 228 | 229 | // South to North cumulative sum memoization 230 | radiumMatrix[i][j] += radiumMatrix[i-1][j]; 231 | } 232 | } 233 | 234 | /*Memoization Matrix 235 | - Treat this as the actual matrix for cumulation from the previous block 236 | */ 237 | for(int i = 1; i <= m; i++) 238 | for(int j = 1; j <= n; j++) 239 | memoizationMatrix[i][j] = FindMax( 240 | memoizationMatrix[i-1][j] + uraniumMatrix[i][j], 241 | memoizationMatrix[i][j-1] + radiumMatrix[i][j]); 242 | 243 | System.out.println(String.format("Case %s: %s",testCase ,memoizationMatrix[m][n])); 244 | } 245 | } 246 | } 247 | ``` 248 | --------------------------------------------------------------------------------