diff --git a/.DS_Store b/.DS_Store index fa501d1..6b19b25 100644 Binary files a/.DS_Store and b/.DS_Store differ diff --git a/FCFS/fcfs.py b/Algorithm/FCFS/fcfs.py similarity index 100% rename from FCFS/fcfs.py rename to Algorithm/FCFS/fcfs.py diff --git a/FCFS/question.txt b/Algorithm/FCFS/question.txt similarity index 100% rename from FCFS/question.txt rename to Algorithm/FCFS/question.txt diff --git a/Floodfill/Problem_statement.txt b/Algorithm/Floodfill/Problem_statement.txt similarity index 97% rename from Floodfill/Problem_statement.txt rename to Algorithm/Floodfill/Problem_statement.txt index 9ddda57..f36d41a 100644 --- a/Floodfill/Problem_statement.txt +++ b/Algorithm/Floodfill/Problem_statement.txt @@ -1,28 +1,28 @@ -For those who dont like regular images, ASCII Maps Inc. has created maps that are fully printable ASCII characters. Each map is a rectangular grid of lowercase English letters, where each letter stands for various locations. In particular, w stands for water and the other 25 letters represent various different land locations. For this problem, we are interested in counting the number of bodies of water on a given ASCII map. A body of water is a maximal set of contiguous grid squares on the ASCII map where each square in the body of water shares a boundary with at least one other square in the body of water. Thus, for two grid squares to be part of the same body of water, one must be above, below, to the left, or to the right of the other grid square. -Input -The first line of input consists of two space separated integers, r (1=r=50) and c (1=c=50), the number of rows and columns, respectively for the input map. The next r lines will each contain c lowercase English letters, representing the corresponding row of the input map. - -Output -On a line by itself, output the number of bodies of water in the input map. - -Sample test case 1: - -Input: -5 6 -waaaww -wawawc -bbbbwc -wwwwww -dddddd - -Output: -3 - -Sample test case 2: -Input: -2 8 -wxwxwxwx -xwxwxwxw - -Output: -8 +For those who dont like regular images, ASCII Maps Inc. has created maps that are fully printable ASCII characters. Each map is a rectangular grid of lowercase English letters, where each letter stands for various locations. In particular, w stands for water and the other 25 letters represent various different land locations. For this problem, we are interested in counting the number of bodies of water on a given ASCII map. A body of water is a maximal set of contiguous grid squares on the ASCII map where each square in the body of water shares a boundary with at least one other square in the body of water. Thus, for two grid squares to be part of the same body of water, one must be above, below, to the left, or to the right of the other grid square. +Input +The first line of input consists of two space separated integers, r (1=r=50) and c (1=c=50), the number of rows and columns, respectively for the input map. The next r lines will each contain c lowercase English letters, representing the corresponding row of the input map. + +Output +On a line by itself, output the number of bodies of water in the input map. + +Sample test case 1: + +Input: +5 6 +waaaww +wawawc +bbbbwc +wwwwww +dddddd + +Output: +3 + +Sample test case 2: +Input: +2 8 +wxwxwxwx +xwxwxwxw + +Output: +8 diff --git a/Floodfill/solution.java b/Algorithm/Floodfill/solution.java similarity index 95% rename from Floodfill/solution.java rename to Algorithm/Floodfill/solution.java index 2974a5a..a043c94 100644 --- a/Floodfill/solution.java +++ b/Algorithm/Floodfill/solution.java @@ -1,53 +1,53 @@ -import java.util.Arrays; -import java.util.Scanner; - -public class water { -public static void main(String[] args){ -Scanner kb=new Scanner(System.in); -System.out.println("Enter the dimensions of the map:"); -int n=kb.nextInt(); -int m=kb.nextInt(); -System.out.println("Enter the map:"); -char[][] x=new char[n][m]; -for(int i=0;i=0&&r=0&&c=0&&r=0&&c -#include - -int maxSubarraySum(int a[], int l) { - int max = INT_MIN, max_here = 0; - - for (int i = 0; i < l; i++) { - max_here = max_here + a[i]; - if (max < max_here) max = max_here; - if (max_here < 0) max_here = 0; - } - - return max; -} - -// int maxSubarraySum(int a[], int l) { -// int max = a[0], max_here = a[0]; - -// for (int i = 0; i < l; i++) { -// if (max_here > 0) max_here += a[i]; -// else max_here = a[i]; -// if (max_here > max) max = max_here; -// } - -// return max; -// } - -int main(int argc, char *argv[]) { - int arr[] = {-2, -3, 4, -1, -2, 1, 5, -3}; - int l = sizeof(arr) / sizeof(int); - - int m = maxSubarraySum(arr, l); - - printf("%d is the max subarray sum\n", m); - - return 0; +#include +#include + +int maxSubarraySum(int a[], int l) { + int max = INT_MIN, max_here = 0; + + for (int i = 0; i < l; i++) { + max_here = max_here + a[i]; + if (max < max_here) max = max_here; + if (max_here < 0) max_here = 0; + } + + return max; +} + +// int maxSubarraySum(int a[], int l) { +// int max = a[0], max_here = a[0]; + +// for (int i = 0; i < l; i++) { +// if (max_here > 0) max_here += a[i]; +// else max_here = a[i]; +// if (max_here > max) max = max_here; +// } + +// return max; +// } + +int main(int argc, char *argv[]) { + int arr[] = {-2, -3, 4, -1, -2, 1, 5, -3}; + int l = sizeof(arr) / sizeof(int); + + int m = maxSubarraySum(arr, l); + + printf("%d is the max subarray sum\n", m); + + return 0; } \ No newline at end of file diff --git a/Kadane's Algorithm/kadane.cpp b/Algorithm/Kadane's Algorithm/kadane.cpp similarity index 100% rename from Kadane's Algorithm/kadane.cpp rename to Algorithm/Kadane's Algorithm/kadane.cpp diff --git a/Kadane's Algorithm/kadane.py b/Algorithm/Kadane's Algorithm/kadane.py similarity index 100% rename from Kadane's Algorithm/kadane.py rename to Algorithm/Kadane's Algorithm/kadane.py diff --git a/Kadane's Algorithm/problem.txt b/Algorithm/Kadane's Algorithm/problem.txt similarity index 96% rename from Kadane's Algorithm/problem.txt rename to Algorithm/Kadane's Algorithm/problem.txt index ad9467e..1f05316 100644 --- a/Kadane's Algorithm/problem.txt +++ b/Algorithm/Kadane's Algorithm/problem.txt @@ -1,5 +1,5 @@ -Problem: -Find out the maximum continuous subarray sum in linear time - -Solution: -Kadane's algorithm can calculate the maximum subarray sum in linear time +Problem: +Find out the maximum continuous subarray sum in linear time + +Solution: +Kadane's algorithm can calculate the maximum subarray sum in linear time diff --git a/hot_potato/hot_potato.cpp b/Algorithm/hot_potato/hot_potato.cpp similarity index 100% rename from hot_potato/hot_potato.cpp rename to Algorithm/hot_potato/hot_potato.cpp diff --git a/hot_potato/question.txt b/Algorithm/hot_potato/question.txt similarity index 100% rename from hot_potato/question.txt rename to Algorithm/hot_potato/question.txt diff --git a/nQueen/Question.txt b/Algorithm/nQueen/Question.txt similarity index 100% rename from nQueen/Question.txt rename to Algorithm/nQueen/Question.txt diff --git a/nQueen/nQueen.cpp b/Algorithm/nQueen/nQueen.cpp old mode 100755 new mode 100644 similarity index 96% rename from nQueen/nQueen.cpp rename to Algorithm/nQueen/nQueen.cpp index 0cfd39c..505b926 --- a/nQueen/nQueen.cpp +++ b/Algorithm/nQueen/nQueen.cpp @@ -1,90 +1,90 @@ - -#include -using namespace std; - -char board[30][30]; - -void printBoard(char arr[][30], int n) { - for (int r = 0; r < n; ++r) { - for (int c = 0; c < n; ++c) { - cout << arr[r][c] << " " ; - } - cout << endl; - } -} - -void initialiseBoard(int n) { - for (int r = 0; r < n; ++r) { - for (int c = 0; c < n; ++c) { - board[r][c] = 'X'; - } - } -} - -bool canPlace(char board[][30], int N, int x, int y) -{ - //check the row if aqueen already exists - for (int r = 0; r < N; ++r) - { - if (board[r][y] == 'Q') - return false; - } - - int rInc[] = { -1, +1, +1, -1}; - int cInc[] = { -1, +1, -1, +1}; - //check diagonal if queen already exists - for (int dir = 0; dir < 4; ++dir) - { - int rowAdd = rInc[dir]; - int colAdd = cInc[dir]; - int r = x + rowAdd; - int c = y + colAdd; - //check that r c is within the board - while (r >= 0 && r < N && c >= 0 && c < N) - { - if (board[r][c] == 'Q') - return false; - r = r + rowAdd; - c = c + colAdd; - } - } - return true; -} - -bool nqueen(int r, int n) -{ - if (r == n)//base case if all queens are placed - { - return true; - } - //for every column, use hit and trial by placing a queen in the each cell of curr Row - for (int c = 0; c < n; ++c) - { - int x = r; - int y = c; - //check if queen can be placed on board[i][c] - if (canPlace(board, n, x, y)==true) - { - board[x][y] = 'Q'; //place queen in each column - bool isSuccessful = nqueen(r + 1, n); //recursion to place rest of queens - if (isSuccessful == true) - return true; - board[x][y] = 'X'; //else unmark the cell or backtrack - } - } - return false; //if queen cannot be placed in any row in this column then return false -} - -int main() -{ - int n; - cin >> n; - - initialiseBoard(n);//initialse all the board with X - bool isSuccessful = nqueen(0, n); - - if (isSuccessful) printBoard(board, n); - else cout << "Sorry man! You need to have a larger board!\n"; - - return 0; -} + +#include +using namespace std; + +char board[30][30]; + +void printBoard(char arr[][30], int n) { + for (int r = 0; r < n; ++r) { + for (int c = 0; c < n; ++c) { + cout << arr[r][c] << " " ; + } + cout << endl; + } +} + +void initialiseBoard(int n) { + for (int r = 0; r < n; ++r) { + for (int c = 0; c < n; ++c) { + board[r][c] = 'X'; + } + } +} + +bool canPlace(char board[][30], int N, int x, int y) +{ + //check the row if aqueen already exists + for (int r = 0; r < N; ++r) + { + if (board[r][y] == 'Q') + return false; + } + + int rInc[] = { -1, +1, +1, -1}; + int cInc[] = { -1, +1, -1, +1}; + //check diagonal if queen already exists + for (int dir = 0; dir < 4; ++dir) + { + int rowAdd = rInc[dir]; + int colAdd = cInc[dir]; + int r = x + rowAdd; + int c = y + colAdd; + //check that r c is within the board + while (r >= 0 && r < N && c >= 0 && c < N) + { + if (board[r][c] == 'Q') + return false; + r = r + rowAdd; + c = c + colAdd; + } + } + return true; +} + +bool nqueen(int r, int n) +{ + if (r == n)//base case if all queens are placed + { + return true; + } + //for every column, use hit and trial by placing a queen in the each cell of curr Row + for (int c = 0; c < n; ++c) + { + int x = r; + int y = c; + //check if queen can be placed on board[i][c] + if (canPlace(board, n, x, y)==true) + { + board[x][y] = 'Q'; //place queen in each column + bool isSuccessful = nqueen(r + 1, n); //recursion to place rest of queens + if (isSuccessful == true) + return true; + board[x][y] = 'X'; //else unmark the cell or backtrack + } + } + return false; //if queen cannot be placed in any row in this column then return false +} + +int main() +{ + int n; + cin >> n; + + initialiseBoard(n);//initialse all the board with X + bool isSuccessful = nqueen(0, n); + + if (isSuccessful) printBoard(board, n); + else cout << "Sorry man! You need to have a larger board!\n"; + + return 0; +} diff --git a/Array/Biggest_Sum_5_Consecutives_Integers/Biggest_Sum_5_Consecutives_Integers b/Array/Biggest_Sum_5_Consecutives_Integers/Biggest_Sum_5_Consecutives_Integers new file mode 100644 index 0000000..b526a8c --- /dev/null +++ b/Array/Biggest_Sum_5_Consecutives_Integers/Biggest_Sum_5_Consecutives_Integers @@ -0,0 +1,19 @@ +What's the biggest sum you can get from adding 5 consecutives integers in a array? + +Example: + Array = [1, 3, -2, 4, -9, 1, 4, 7] + Possibles Sums: + 1 + 3 + (-2) + 4 + (-9) = -3 + 3 + (-2) + 4 + (-9) + 1 = -3 + (-2) + 4 + (-9) + 1 + 4 = -2 + 4 + (-9) + 1 + 4 + 7 = 7 + + So the biggest Sum is 7. + +What's the biggest sum of 5 consecutives integers of the array below? + +Array = [1, 3, -5, 8, -9, 13, -2, -3, 8, 4, 3, 6, 1, 2, -2, -4, 8, -4, 1, 8, 2, 1, 3, 1, 2, 3, + 7, 8, -9, 5, 4, 3, 2, 4, 1, 2, 6, 6, 7, -15, 9, 7, 8, 16, -10, 1, 2, 6, 6, 4, -5, 2, 2 + 3, 6, 7, 8, 1, 2, 3, 3, 4, 5, 6, 1, -5,7, -9, 10, 1, 3, 4, 8, 7, 6, 4, 1, 1, 2, 3, 1] + +PS: There may or may not have different sequences that has the same sum. diff --git a/Array/Biggest_Sum_5_Consecutives_Integers/solution.c b/Array/Biggest_Sum_5_Consecutives_Integers/solution.c new file mode 100644 index 0000000..4a395d4 --- /dev/null +++ b/Array/Biggest_Sum_5_Consecutives_Integers/solution.c @@ -0,0 +1,23 @@ +#include +#include + +int main(){ + int i; + int size = 81; //SIZE OF THE ARRAY + int sum; + int biggestSum; + int array[] = {1, 3, -5, 8, -9, 13, -2, -3, 8, 4, 3, 6, 1, 2, -2, -4, 8, -4, 1, 8, 2, 1, 3, 1, 2, 3, 7, 8, -9, 5, 4, 3, 2, 4, 1, 2, 6, 6, 7, -15, 9, 7, 8, 16, -10, 1, 2, 6, 6, 4, -5, 2, 2, 3, 6, 7, 8, 1, 2, 3, 3, 4, 5, 6, 1, -5, 7, -9, 10, 1, 3, 4, 8, 7, 6, 4, 1, 1, 2, 3, 1}; + + //FIRST SUM + sum = array[0] + array[1] + array[2] + array[3] + array[4]; + biggestSum = sum; + + //OTHER SUMS + for(i = 1; i < (size - 4); i++){ //THERE ARE (size - 4) POSSIBLE SUMS, BUT WE ALREADY MADE 1, SO i STARTS AT 1 + sum = sum - array[i - 1] + array[i + 4]; //REMOVE THE FIRST OF THE OLD SUM, AND ADD THE NEW INTEGER + if(sum > biggestSum){ + biggestSum = sum; + } + } + printf("biggestSum = %d\n", biggestSum); //PRINT THE RESULT +} \ No newline at end of file diff --git a/Array/Circle Coloring/1408A.cpp b/Array/Circle Coloring/1408A.cpp new file mode 100644 index 0000000..d526a08 --- /dev/null +++ b/Array/Circle Coloring/1408A.cpp @@ -0,0 +1,52 @@ +#include + +using namespace std; + +int main() +{ + while() + { + int n; + cin>>n; + std::vector a(n), b(n), c(n), ans; + + for(int i=0; i>a[i]; + } + for(int i=0; i>b[i]; + } + for(int i=0; i>c[i]; + } + ans.push_back(a[0]); + + for(int i=1; i + +using namespace std; + +// Complete the hourglassSum function below. +int hourglassSum(vector> arr) { + + int sum[16]={0}; + int a[36]; + static int r=0,x=0; + + for(int i=0;i<6;i++){ + for(int j=0;j<6;j++,r++){ + a[r]=arr[i][j]; + } + } + + + for(int i=0;i<22;i++,x++){ + sum[x]=a[i]+a[i+1]+a[i+2]+a[i+7]+a[i+12]+a[i+13]+a[i+14]; + if(i==3 || i==9 || i==15) + i+=2; + cout << sum[x] << " "; + } + + int large = sum[0]; + + for(int i=1;i<16;i++){ + if(large> arr(6); + for (int i = 0; i < 6; i++) { + arr[i].resize(6); + + for (int j = 0; j < 6; j++) { + cin >> arr[i][j]; + } + + cin.ignore(numeric_limits::max(), '\n'); + } + + int result = hourglassSum(arr); + + fout << result << "\n"; + + fout.close(); + + return 0; +} \ No newline at end of file diff --git a/Lily's Homework/Question.txt b/Array/Lily's Homework/Question.txt similarity index 98% rename from Lily's Homework/Question.txt rename to Array/Lily's Homework/Question.txt index 502c95c..39f207f 100644 --- a/Lily's Homework/Question.txt +++ b/Array/Lily's Homework/Question.txt @@ -1,11 +1,11 @@ -Consider an array of distinct integers, arr = [a[0], a[1], ..., a[n-1]]. George can swap any two elements of the array any number of times. An array is beautiful if the sum of |arr[i] - arr[i-1]|among 0< i < n is minimal. - -Given the array , determine and return the minimum number of swaps that should be performed in order to make the array beautiful. - -For example, arr = [7, 15, 12, 3]. One minimal array is [3, 7, 12, 15]. To get there, George performed the following swaps: - -Swap Result - [7, 15, 12, 3] -3 7 [3, 15, 12, 7] -7 15 [3, 7, 12, 15] +Consider an array of distinct integers, arr = [a[0], a[1], ..., a[n-1]]. George can swap any two elements of the array any number of times. An array is beautiful if the sum of |arr[i] - arr[i-1]|among 0< i < n is minimal. + +Given the array , determine and return the minimum number of swaps that should be performed in order to make the array beautiful. + +For example, arr = [7, 15, 12, 3]. One minimal array is [3, 7, 12, 15]. To get there, George performed the following swaps: + +Swap Result + [7, 15, 12, 3] +3 7 [3, 15, 12, 7] +7 15 [3, 7, 12, 15] It took 2 swaps to make the array beautiful. This is minimal among the choice of beautiful arrays possible. \ No newline at end of file diff --git a/Lily's Homework/solution.py b/Array/Lily's Homework/solution.py similarity index 96% rename from Lily's Homework/solution.py rename to Array/Lily's Homework/solution.py index 8b29419..7783d49 100644 --- a/Lily's Homework/solution.py +++ b/Array/Lily's Homework/solution.py @@ -1,26 +1,26 @@ -def lilysHomework(arr): - m = {} - for i in range(len(arr)): - m[arr[i]] = i - sorted_arr = sorted(arr) - res = 0 - for i in range(len(arr)): - if(arr[i] != sorted_arr[i]): - res += 1 - x = m[sorted_arr[i]] - m[ arr[i] ] = m[ sorted_arr[i]] - arr[i],arr[x] = sorted_arr[i],arr[i] - return res - -if __name__ == '__main__': - fptr = open(os.environ['OUTPUT_PATH'], 'w') - - n = int(input()) - - arr = list(map(int, input().rstrip().split())) - - result = min(lilysHomework(list(arr)), lilysHomework(list(arr[::-1]))) - - fptr.write(str(result) + '\n') - - fptr.close() +def lilysHomework(arr): + m = {} + for i in range(len(arr)): + m[arr[i]] = i + sorted_arr = sorted(arr) + res = 0 + for i in range(len(arr)): + if(arr[i] != sorted_arr[i]): + res += 1 + x = m[sorted_arr[i]] + m[ arr[i] ] = m[ sorted_arr[i]] + arr[i],arr[x] = sorted_arr[i],arr[i] + return res + +if __name__ == '__main__': + fptr = open(os.environ['OUTPUT_PATH'], 'w') + + n = int(input()) + + arr = list(map(int, input().rstrip().split())) + + result = min(lilysHomework(list(arr)), lilysHomework(list(arr[::-1]))) + + fptr.write(str(result) + '\n') + + fptr.close() diff --git a/Array/Mislove Has Lost an Array/Question.txt b/Array/Mislove Has Lost an Array/Question.txt new file mode 100644 index 0000000..23182ac --- /dev/null +++ b/Array/Mislove Has Lost an Array/Question.txt @@ -0,0 +1,17 @@ +Mislove had an array a1, a2, ⋯, an of n positive integers, but he has lost it. He only remembers the following facts about it: + +1)The number of different numbers in the array is not less than l and is not greater than r. +2)For each array's element ai either ai=1 or ai is even and there is a number ai/2 in the array. + +For example, if n=5, l=2, r=3 then an array could be [1,2,2,4,4] or [1,1,1,1,2]; but it couldn't be [1,2,2,4,8] because this array contains 4 different numbers; it couldn't be [1,2,2,3,3] because 3 is odd and isn't equal to 1; and it couldn't be [1,1,2,2,16] because there is a number 16 in the array but there isn't a number 16/2=8. + +According to these facts, he is asking you to count the minimal and the maximal possible sums of all elements in an array. + +Input-1 +4 2 2 +Output +5 7 +Input-2 +5 1 5 +Output +5 31 diff --git a/Array/Mislove Has Lost an Array/Solution.cpp b/Array/Mislove Has Lost an Array/Solution.cpp new file mode 100644 index 0000000..841440f --- /dev/null +++ b/Array/Mislove Has Lost an Array/Solution.cpp @@ -0,0 +1,26 @@ +#include +using namespace std; +int main() +{ + long long int i,mini=1,mine=0,maxi=1,maxo=0,n,s,e; + cin>>n>>s>>e; + + for(i=1;i<=s-1;i++) + { + mini=2*mini; + mine+=mini; + } +mine+=n-s+1; + +for(i=1;i<=e-1;i++) +{ + maxi=2*maxi; + maxo+=maxi; +} +maxo+=1; + + +maxo+=(n-e)*(maxi); +cout< +using namespace std; +int main(void) +{ + int t; + cin>>t; + while(t--) + { + int r,c; + cin>>r>>c; + int arr[r][c+2]={0}; + arr[0][c+1]=0; + + for(int i=0;i>arr[i][j]; + + for(int i=r-2;i>=0;i--) + for(int j=1;j<=c;j++) + arr[i][j]+=max((arr[i+1][j-1]),max(arr[i+1][j],arr[i+1][j+1])); + + int max = INT_MIN; + for(int i=1;i<=c;i++) + if(arr[0][i]>max) + max = arr[0][i]; + + cout< +using namespace std; + +typedef long long int ll; + + +int main() +{ + ios::sync_with_stdio(false); + cin.tie(0); + cout.tie(0); + + ll x11,x12,y11,y12; + ll x21,x22,y21,y22; + ll x31,x32,y31,y32; + + ll area = 0; + + cin>>x11>>y11>>x12>>y12; + cin>>x21>>y21>>x22>>y22; + cin>>x31>>y31>>x32>>y32; + + area = abs(x11-x12)*abs(y11-y12); + x21 = max(x11,x21); + y21 = max(y11,y21); + x22 = min(x12,x22); + y22 = min(y12,y22); + x31 = max(x11,x31); + y31 = max(y11,y31); + x32 = min(x12,x32); + y32 = min(y12,y32); + ll a1,a2,b1,b2; + if(x21 < x22 && y21 < y22) area -= abs(x21-x22)*abs(y21-y22); + if(x31 < x32 && y31 < y32) area -= abs(x31-x32)*abs(y31-y32); + if((x21x31) || (x21x32)) + { + if((y21 < y31 && y22 > y31) || (y21 < y32 && y22 > y32)) + { + ll narea = 0; + + } + } + + a1 = max(x21,x31); + b1 = max(y21,y31); + a2 = min(x22,x32); + b2 = min(y22,y32); + + if(a1 < a2 && b1 < b2) area += abs(a2-a1)*abs(b2-b1); + + if(area > 0) cout<<"YES\n"; + else cout<<"NO\n"; + + return 0; +} \ No newline at end of file diff --git a/Array/triplet_problem/question.txt b/Array/triplet_problem/question.txt new file mode 100644 index 0000000..b1417a8 --- /dev/null +++ b/Array/triplet_problem/question.txt @@ -0,0 +1 @@ +Find a triplet such that sum of two equals to third element in an array. diff --git a/Array/triplet_problem/solution.c b/Array/triplet_problem/solution.c new file mode 100644 index 0000000..69ac10c --- /dev/null +++ b/Array/triplet_problem/solution.c @@ -0,0 +1,48 @@ +#include + +void sort(int a[],int); +void findtriplet(int a[],int n) +{ + sort(a,n); + for(int k=n-1;k>=0;k--) + { + int i=0,j=k-1; + while(i (a[i]+a[j])) + i++; + else + j--; + } + } + printf("No such triplet exists\n"); +} + +void sort(int a[],int n) +{ + for(int i=0;i a[j+1]) + { + int t; + t = a[j]; + a[j] = a[j+1]; + a[j+1] = t; + } + } + } +} + +int main() +{ + int a[9] = {5,32,1,7,10,50,15,21,2}; + findtriplet(a,9); + return 0; +} diff --git a/Backtracking/Generate_parenthesis/Generate_Parenthesis.cpp b/Backtracking/Generate_parenthesis/Generate_Parenthesis.cpp new file mode 100644 index 0000000..0b6a580 --- /dev/null +++ b/Backtracking/Generate_parenthesis/Generate_Parenthesis.cpp @@ -0,0 +1,31 @@ +#include +using namespace std; +void Generate_Parenthesis(int open, int close, vector &ans, string s) +{ + if (close == 0) + { + ans.push_back(s); + return; + } + if (open) + { + string temp = s; + temp += '('; + Generate_Parenthesis(open - 1, close, ans, temp); + } + if (close > open) + { + string temp = s; + temp += ')'; + Generate_Parenthesis(open, close - 1, ans, temp); + } +} +int main() +{ + int n; + cin >> n; + vector ans; + Generate_Parenthesis(n, n, ans, ""); + for (int i = 0; i < ans.size(); i++) + cout << ans[i] << endl; +} \ No newline at end of file diff --git a/Backtracking/Generate_parenthesis/Question.txt b/Backtracking/Generate_parenthesis/Question.txt new file mode 100644 index 0000000..9012c1d --- /dev/null +++ b/Backtracking/Generate_parenthesis/Question.txt @@ -0,0 +1,7 @@ +Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. + +Sample Input +n = 3 + +Sample Output +["((()))","(()())","(())()","()(())","()()()"] \ No newline at end of file diff --git a/Backtracking/SudokuSolver/Question.txt b/Backtracking/SudokuSolver/Question.txt new file mode 100644 index 0000000..eadd651 --- /dev/null +++ b/Backtracking/SudokuSolver/Question.txt @@ -0,0 +1,20 @@ +Given a partially filled NxN 2D array, the goal is to assign digits (from 1 to 9) +to the empty cells (cells assigned O value) so that every row, column,and subgrid +of size 3×3 contains exactly one instance of the digits from 1 to 9. We provide the +value of N and a partially filled sudoku as input. + +Sample Input: +4 +3 4 1 0 0 2 0 0 0 0 2 0 0 1 4 3 + +Sample Output: +============== +3 4 1 0 +0 2 0 0 +0 0 2 0 +0 1 4 3 +============== +3 4 1 2 +1 2 3 4 +4 3 2 1 +2 1 4 3 diff --git a/Backtracking/SudokuSolver/sudokuSolver.cpp b/Backtracking/SudokuSolver/sudokuSolver.cpp new file mode 100644 index 0000000..5013019 --- /dev/null +++ b/Backtracking/SudokuSolver/sudokuSolver.cpp @@ -0,0 +1,100 @@ +#include +#include +using namespace std; + +void print2D(int arr[][20], int M, int N) { + for (int i = 0; i < M; ++i) { + for (int j = 0; j < N; ++j) { + cout << arr[i][j] << " "; + } + cout << endl; + } +} + +bool myfixed[20][20] = {}; + +void input2D_soduku(int arr[][20], int M, int N) +{ + for (int i = 0; i < M; ++i) + { + for (int j = 0; j < N; ++j) + { + cin >> arr[i][j]; + if (arr[i][j] != 0) myfixed[i][j] = true; //so that our entry does not change + } + } +} + +bool canPlace(int board[][20], int N, int x, int y, int num) +{ + //check along row && col + for (int i = 0; i < N; ++i) + { + if (board[x][i] == num) return false; //check along row + if (board[i][y] == num) return false; //check along col + } + + //check in the box + int rootN = sqrt(N); + int boxRow = x / rootN; + int boxCol = y / rootN; + int startRow = boxRow * rootN; + int startCol = boxCol * rootN; + + for (int r = startRow; r < startRow + rootN; ++r) + { + for (int c = startCol; c < startCol + rootN; ++c) + { + if (board[r][c] == num) return false; + } + } + + return true; +} + + +bool solveSudoku(int board[][20], int N, int x, int y) +{ + if (x == N && y == 0) return true; //we have reached row 4 ---->sudoku over + + if (y == N) return solveSudoku(board, N, x + 1, 0);//stop y to go to column4-->goto nxt row + + if (myfixed[x][y]) return solveSudoku(board, N, x , y + 1); + + for (int num = 1; num <= N; ++num) + { + if (canPlace(board, N, x, y, num) == true) + { + board[x][y] = num; + bool isSuccessful = solveSudoku(board, N, x , y + 1); //recursion for nxt columns + if (isSuccessful) return true; + else board[x][y] = 0; + } + } + return false; +} + +int main() +{ + int board[20][20] = {}; + + int N; + cin >> N; + input2D_soduku(board, N, N); + for(int i=0;i>board[i][j]; + } + } + cout << "==============\n"; + + print2D(board, N, N); + + cout << "==============\n"; + + solveSudoku(board, N, 0, 0); + + print2D(board, N, N); + +} + diff --git a/Armstrong No/armstrongnum.c b/Basic Math/Armstrong No/armstrongnum.c similarity index 100% rename from Armstrong No/armstrongnum.c rename to Basic Math/Armstrong No/armstrongnum.c diff --git a/Average/Average-Question.txt b/Basic Math/Average/Average-Question.txt similarity index 100% rename from Average/Average-Question.txt rename to Basic Math/Average/Average-Question.txt diff --git a/Average/Solution.cpp b/Basic Math/Average/Solution.cpp similarity index 100% rename from Average/Solution.cpp rename to Basic Math/Average/Solution.cpp diff --git a/Counting-Change-Combinations/counting.txt b/Basic Math/Counting-Change-Combinations/counting.txt similarity index 100% rename from Counting-Change-Combinations/counting.txt rename to Basic Math/Counting-Change-Combinations/counting.txt diff --git a/Counting-Change-Combinations/solution.js b/Basic Math/Counting-Change-Combinations/solution.js similarity index 100% rename from Counting-Change-Combinations/solution.js rename to Basic Math/Counting-Change-Combinations/solution.js diff --git a/Divisibility_Check/Question.txt b/Basic Math/Divisibility_Check/Question.txt similarity index 100% rename from Divisibility_Check/Question.txt rename to Basic Math/Divisibility_Check/Question.txt diff --git a/Divisibility_Check/Solution.cpp b/Basic Math/Divisibility_Check/Solution.cpp similarity index 100% rename from Divisibility_Check/Solution.cpp rename to Basic Math/Divisibility_Check/Solution.cpp diff --git a/Divisible Sum Pairs/Problem Description.txt b/Basic Math/Divisible Sum Pairs/Problem Description.txt similarity index 98% rename from Divisible Sum Pairs/Problem Description.txt rename to Basic Math/Divisible Sum Pairs/Problem Description.txt index 7525f0e..1ffa981 100644 --- a/Divisible Sum Pairs/Problem Description.txt +++ b/Basic Math/Divisible Sum Pairs/Problem Description.txt @@ -1,2 +1,2 @@ -You are given an array of n integers, ar = [ar[0], ar[1], ... , ar[n-1]], and a positive integer k. Find and print the number of -(i,j) pairs where i < j and ar[i]+ar[j] is divisible by k. +You are given an array of n integers, ar = [ar[0], ar[1], ... , ar[n-1]], and a positive integer k. Find and print the number of +(i,j) pairs where i < j and ar[i]+ar[j] is divisible by k. diff --git a/Divisible Sum Pairs/solution.js b/Basic Math/Divisible Sum Pairs/solution.js similarity index 95% rename from Divisible Sum Pairs/solution.js rename to Basic Math/Divisible Sum Pairs/solution.js index d75bca6..7c65521 100644 --- a/Divisible Sum Pairs/solution.js +++ b/Basic Math/Divisible Sum Pairs/solution.js @@ -1,12 +1,12 @@ -function divisibleSumPairs(n, k, ar) { - let count =0; - for(let i=0; i -void main() -{ - int i; - for(i=1;i<=100;i++) - { - if(i%3!=0 && i%5!=0) printf("%d\n", i); - if(i%3 == 0 && i%5!=0)printf("Fizz\n"); - if(i%5 == 0 && i%3!=0)printf("Buzz\n"); - if(i%5 == 0 && i%3==0)printf("FizzBuzz\n"); - } -} +#include +void main() +{ + int i; + for(i=1;i<=100;i++) + { + if(i%3!=0 && i%5!=0) printf("%d\n", i); + if(i%3 == 0 && i%5!=0)printf("Fizz\n"); + if(i%5 == 0 && i%3!=0)printf("Buzz\n"); + if(i%5 == 0 && i%3==0)printf("FizzBuzz\n"); + } +} diff --git a/Fizz Buzz/fizzbuzz.cpp b/Basic Math/Fizz Buzz/fizzbuzz.cpp similarity index 95% rename from Fizz Buzz/fizzbuzz.cpp rename to Basic Math/Fizz Buzz/fizzbuzz.cpp index 22eea15..4d6c904 100644 --- a/Fizz Buzz/fizzbuzz.cpp +++ b/Basic Math/Fizz Buzz/fizzbuzz.cpp @@ -1,16 +1,16 @@ -#include -using namespace std; -int main() -{ - for(int i=1;i<=100;i++){ - if((i%3 == 0) && (i%5==0)) - cout<<"FizzBuzz\n"; - else if(i%3 == 0) - cout<<"Fizz\n"; - else if(i%5 == 0) - cout<<"Buzz\n"; - else - cout< +using namespace std; +int main() +{ + for(int i=1;i<=100;i++){ + if((i%3 == 0) && (i%5==0)) + cout<<"FizzBuzz\n"; + else if(i%3 == 0) + cout<<"Fizz\n"; + else if(i%5 == 0) + cout<<"Buzz\n"; + else + cout< +#include + +void words(int n, int c, int r) +{ + if(n==0 && c==1) + { + cout<<"Zero"<=20 || n==10) + { + cout<<" "<=14) + cout<<" "<>n; + int n1=n; + int count=0, rev=0; + while(n1!=0) + { + rev=rev*10+(n1%10); + count++; + n1=n1/10; + } + words(n,count,rev); + getch(); +} \ No newline at end of file diff --git a/Basic Math/Number to Words/problem_definition.txt b/Basic Math/Number to Words/problem_definition.txt new file mode 100644 index 0000000..0e39580 --- /dev/null +++ b/Basic Math/Number to Words/problem_definition.txt @@ -0,0 +1,4 @@ +Write code to convert a given number into words. +For example, +if “1234” is given as input +output should be “one thousand two hundred thirty four”. \ No newline at end of file diff --git a/Octal Decimal Calculator/Octal Decimal Calculator.txt b/Basic Math/Octal Decimal Calculator/Octal Decimal Calculator.txt similarity index 97% rename from Octal Decimal Calculator/Octal Decimal Calculator.txt rename to Basic Math/Octal Decimal Calculator/Octal Decimal Calculator.txt index 41b563a..0ff00e0 100644 --- a/Octal Decimal Calculator/Octal Decimal Calculator.txt +++ b/Basic Math/Octal Decimal Calculator/Octal Decimal Calculator.txt @@ -1,9 +1,9 @@ -Given an octal number it is required to convert to decimal and print it on the console - -Example: - -The octal number 567 is entered. - -The system calculates the equivalent number in decimal that is 375 and prints it on the console - +Given an octal number it is required to convert to decimal and print it on the console + +Example: + +The octal number 567 is entered. + +The system calculates the equivalent number in decimal that is 375 and prints it on the console + The decimal number for octal 567 is: 357 \ No newline at end of file diff --git a/Octal Decimal Calculator/OctalDecimalCalculator.java b/Basic Math/Octal Decimal Calculator/OctalDecimalCalculator.java similarity index 96% rename from Octal Decimal Calculator/OctalDecimalCalculator.java rename to Basic Math/Octal Decimal Calculator/OctalDecimalCalculator.java index 596c7d5..dac72a3 100644 --- a/Octal Decimal Calculator/OctalDecimalCalculator.java +++ b/Basic Math/Octal Decimal Calculator/OctalDecimalCalculator.java @@ -1,43 +1,43 @@ -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; - -public class OctalDecimalCalculator { - - private static int BASE_8 = 8; - private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); - private static final String RESULT_TEMPLATE = "The decimal number for octal %s is: %s"; - - public static void main(String[] args){ - - System.out.println("Please input octal number to convert"); - try { - String octal = br.readLine(); - String decimal = convertOctalToDecimal(Integer.parseInt(octal)); - - System.out.println(String.format(RESULT_TEMPLATE, octal, decimal)); - } catch (IOException e) { - e.printStackTrace(); - } - - } - - public static String convertOctalToDecimal(int octal){ - int result = 0; - String tmp = String.valueOf(octal); - int count = 0; - int multiple; - String caracter; - for (int i = tmp.length(); i > 0; i--) { - caracter = tmp.substring(i-1, i); - multiple = (int) Math.pow(BASE_8, count); - int value = (Integer.parseInt(caracter) * multiple); - count = count + 1; - result += value; - - } - - return String.valueOf(result); - } - -} +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class OctalDecimalCalculator { + + private static int BASE_8 = 8; + private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + private static final String RESULT_TEMPLATE = "The decimal number for octal %s is: %s"; + + public static void main(String[] args){ + + System.out.println("Please input octal number to convert"); + try { + String octal = br.readLine(); + String decimal = convertOctalToDecimal(Integer.parseInt(octal)); + + System.out.println(String.format(RESULT_TEMPLATE, octal, decimal)); + } catch (IOException e) { + e.printStackTrace(); + } + + } + + public static String convertOctalToDecimal(int octal){ + int result = 0; + String tmp = String.valueOf(octal); + int count = 0; + int multiple; + String caracter; + for (int i = tmp.length(); i > 0; i--) { + caracter = tmp.substring(i-1, i); + multiple = (int) Math.pow(BASE_8, count); + int value = (Integer.parseInt(caracter) * multiple); + count = count + 1; + result += value; + + } + + return String.valueOf(result); + } + +} diff --git a/Odd or Even Game/.idea/Odd or Even Game.iml b/Basic Math/Odd or Even Game/.idea/Odd or Even Game.iml similarity index 100% rename from Odd or Even Game/.idea/Odd or Even Game.iml rename to Basic Math/Odd or Even Game/.idea/Odd or Even Game.iml diff --git a/Odd or Even Game/.idea/misc.xml b/Basic Math/Odd or Even Game/.idea/misc.xml similarity index 100% rename from Odd or Even Game/.idea/misc.xml rename to Basic Math/Odd or Even Game/.idea/misc.xml diff --git a/Odd or Even Game/.idea/modules.xml b/Basic Math/Odd or Even Game/.idea/modules.xml similarity index 100% rename from Odd or Even Game/.idea/modules.xml rename to Basic Math/Odd or Even Game/.idea/modules.xml diff --git a/Odd or Even Game/.idea/vcs.xml b/Basic Math/Odd or Even Game/.idea/vcs.xml similarity index 100% rename from Odd or Even Game/.idea/vcs.xml rename to Basic Math/Odd or Even Game/.idea/vcs.xml diff --git a/Odd or Even Game/.idea/workspace.xml b/Basic Math/Odd or Even Game/.idea/workspace.xml similarity index 100% rename from Odd or Even Game/.idea/workspace.xml rename to Basic Math/Odd or Even Game/.idea/workspace.xml diff --git a/Odd or Even Game/OddEvenGame.txt b/Basic Math/Odd or Even Game/OddEvenGame.txt similarity index 100% rename from Odd or Even Game/OddEvenGame.txt rename to Basic Math/Odd or Even Game/OddEvenGame.txt diff --git a/Odd or Even Game/oddEvenGame.py b/Basic Math/Odd or Even Game/oddEvenGame.py similarity index 100% rename from Odd or Even Game/oddEvenGame.py rename to Basic Math/Odd or Even Game/oddEvenGame.py diff --git a/PROXY/question.txt b/Basic Math/PROXY/question.txt similarity index 100% rename from PROXY/question.txt rename to Basic Math/PROXY/question.txt diff --git a/PROXY/solution.cpp b/Basic Math/PROXY/solution.cpp similarity index 100% rename from PROXY/solution.cpp rename to Basic Math/PROXY/solution.cpp diff --git a/Prime_gen/Prime Generator(prime_gen) b/Basic Math/Prime_gen/Prime Generator(prime_gen) similarity index 100% rename from Prime_gen/Prime Generator(prime_gen) rename to Basic Math/Prime_gen/Prime Generator(prime_gen) diff --git a/Prime_gen/prime_gen.cpp b/Basic Math/Prime_gen/prime_gen.cpp similarity index 100% rename from Prime_gen/prime_gen.cpp rename to Basic Math/Prime_gen/prime_gen.cpp diff --git a/Save the Prisoner!/question.txt b/Basic Math/Save the Prisoner!/question.txt similarity index 100% rename from Save the Prisoner!/question.txt rename to Basic Math/Save the Prisoner!/question.txt diff --git a/Save the Prisoner!/solution.cpp b/Basic Math/Save the Prisoner!/solution.cpp similarity index 100% rename from Save the Prisoner!/solution.cpp rename to Basic Math/Save the Prisoner!/solution.cpp diff --git a/Sherlock-and-the-beast/Sherlock-and-the-beast-problem.md b/Basic Math/Sherlock-and-the-beast/Sherlock-and-the-beast-problem.md similarity index 100% rename from Sherlock-and-the-beast/Sherlock-and-the-beast-problem.md rename to Basic Math/Sherlock-and-the-beast/Sherlock-and-the-beast-problem.md diff --git a/Sherlock-and-the-beast/solution.cpp b/Basic Math/Sherlock-and-the-beast/solution.cpp similarity index 94% rename from Sherlock-and-the-beast/solution.cpp rename to Basic Math/Sherlock-and-the-beast/solution.cpp index 3e7dff3..166e378 100644 --- a/Sherlock-and-the-beast/solution.cpp +++ b/Basic Math/Sherlock-and-the-beast/solution.cpp @@ -1,66 +1,66 @@ -#include - -using namespace std; - - -// Complete the decentNumber function below. - -void decent(int digits) -{ - int flag=0; - - if(digits==4 || digits==7 || digits<3) - flag=0; - else if(digits==5) - { - flag=1; - cout<<"33333\n"; - - } - else if(digits%3 ==0) - { - flag=1; - //(no. of times, what needs to be printed) - cout<=8) - { - - int remain3,remain5,temp; - - temp=digits%3; - flag=1; - if(temp==1) - { - remain5=digits-10; - remain3=10; - } - else if(temp==2) - { - remain5=digits-5; - remain3=5; - } - - cout<>cases; - while(cases-->0) - { - cin>>input; - decent(input); - } - return 0; +#include + +using namespace std; + + +// Complete the decentNumber function below. + +void decent(int digits) +{ + int flag=0; + + if(digits==4 || digits==7 || digits<3) + flag=0; + else if(digits==5) + { + flag=1; + cout<<"33333\n"; + + } + else if(digits%3 ==0) + { + flag=1; + //(no. of times, what needs to be printed) + cout<=8) + { + + int remain3,remain5,temp; + + temp=digits%3; + flag=1; + if(temp==1) + { + remain5=digits-10; + remain3=10; + } + else if(temp==2) + { + remain5=digits-5; + remain3=5; + } + + cout<>cases; + while(cases-->0) + { + cin>>input; + decent(input); + } + return 0; } \ No newline at end of file diff --git a/The Additionator/The Additionator.txt b/Basic Math/The Additionator/The Additionator.txt similarity index 100% rename from The Additionator/The Additionator.txt rename to Basic Math/The Additionator/The Additionator.txt diff --git a/The Additionator/solution.java b/Basic Math/The Additionator/solution.java similarity index 100% rename from The Additionator/solution.java rename to Basic Math/The Additionator/solution.java diff --git a/The Prime Game/Problem_statement.txt b/Basic Math/The Prime Game/Problem_statement.txt similarity index 99% rename from The Prime Game/Problem_statement.txt rename to Basic Math/The Prime Game/Problem_statement.txt index 050d2b2..062ec10 100644 --- a/The Prime Game/Problem_statement.txt +++ b/Basic Math/The Prime Game/Problem_statement.txt @@ -1,9 +1,9 @@ -Manasa loves the nim game, in which there are n buckets, each having Ai balls. Two players play alternately. Each turn consists of removing some non-zero number of balls from one of the bucket. A player with lack of moves looses. But, Manasa having played it so many times, she gets bored one day. So she wants to change the rules of the game. She loves prime numbers, so she makes a new rule: any player can only remove a prime number of balls from a bucket. But there are infinite number prime numbers. So to keep the game simple, a player can only remove x balls from a bucket if x belongs to the set - -S = {2, 3, 5, 7, 11, 13} - -The whole game can now be described as follows: - -There are buckets, and the bucket contains balls. A player can choose a bucket and remove balls from that bucket where belongs to . A player loses if there are no more available moves. - +Manasa loves the nim game, in which there are n buckets, each having Ai balls. Two players play alternately. Each turn consists of removing some non-zero number of balls from one of the bucket. A player with lack of moves looses. But, Manasa having played it so many times, she gets bored one day. So she wants to change the rules of the game. She loves prime numbers, so she makes a new rule: any player can only remove a prime number of balls from a bucket. But there are infinite number prime numbers. So to keep the game simple, a player can only remove x balls from a bucket if x belongs to the set + +S = {2, 3, 5, 7, 11, 13} + +The whole game can now be described as follows: + +There are buckets, and the bucket contains balls. A player can choose a bucket and remove balls from that bucket where belongs to . A player loses if there are no more available moves. + Manasa plays the first move against Sandy. Who will win if both of them play optimally? \ No newline at end of file diff --git a/The Prime Game/Solution.py b/Basic Math/The Prime Game/Solution.py similarity index 96% rename from The Prime Game/Solution.py rename to Basic Math/The Prime Game/Solution.py index 7ec6413..4238403 100644 --- a/The Prime Game/Solution.py +++ b/Basic Math/The Prime Game/Solution.py @@ -1,12 +1,12 @@ -s = [0, 0, 1, 1, 2, 2, 3, 3, 4] -t = int(input()) -for ti in range(t): - n = int(input()) - a = [int(ai) for ai in input().strip().split(" ")] - ans = 0 - for i in range(n): - ans = ans^s[int(a[i]%len(s))] - if(ans>0): - print("Manasa") - else: - print("Sandy") +s = [0, 0, 1, 1, 2, 2, 3, 3, 4] +t = int(input()) +for ti in range(t): + n = int(input()) + a = [int(ai) for ai in input().strip().split(" ")] + ans = 0 + for i in range(n): + ans = ans^s[int(a[i]%len(s))] + if(ans>0): + print("Manasa") + else: + print("Sandy") diff --git a/When to take medicine/problem_statement.txt b/Basic Math/When to take medicine/problem_statement.txt similarity index 100% rename from When to take medicine/problem_statement.txt rename to Basic Math/When to take medicine/problem_statement.txt diff --git a/When to take medicine/when to take medicine_answer.txt b/Basic Math/When to take medicine/when to take medicine_answer.txt similarity index 100% rename from When to take medicine/when to take medicine_answer.txt rename to Basic Math/When to take medicine/when to take medicine_answer.txt diff --git a/find_factorial_of_a_number/find_factorial_of_a_number.txt b/Basic Math/find_factorial_of_a_number/find_factorial_of_a_number.txt similarity index 100% rename from find_factorial_of_a_number/find_factorial_of_a_number.txt rename to Basic Math/find_factorial_of_a_number/find_factorial_of_a_number.txt diff --git a/find_factorial_of_a_number/solution.cpp b/Basic Math/find_factorial_of_a_number/solution.cpp similarity index 100% rename from find_factorial_of_a_number/solution.cpp rename to Basic Math/find_factorial_of_a_number/solution.cpp diff --git a/project_euler problem12/Highly divisible triangular number.cpp b/Basic Math/project_euler problem12/Highly divisible triangular number.cpp similarity index 100% rename from project_euler problem12/Highly divisible triangular number.cpp rename to Basic Math/project_euler problem12/Highly divisible triangular number.cpp diff --git a/project_euler problem12/problem b/Basic Math/project_euler problem12/problem similarity index 100% rename from project_euler problem12/problem rename to Basic Math/project_euler problem12/problem diff --git a/Basic Program/A. Team/A.Team.cpp b/Basic Program/A. Team/A.Team.cpp new file mode 100644 index 0000000..05dfbeb --- /dev/null +++ b/Basic Program/A. Team/A.Team.cpp @@ -0,0 +1,24 @@ +#include + +int main() +{ + //Creation of vars + int n, a, b, c, count = 0; + //Take in input for n lines + std::cin >> n; + //Loop for n + for (int i = 0; i < n; i++) + { + //Take in user input + std::cin >> a; + std::cin >> b; + std::cin >> c; + //If more than 2 are sure then they will do the problem + if (a + b + c >= 2) + //Increase problem count + count++; + } + //Return problem count + std::cout << count; + return 0; +} diff --git a/Basic Program/A. Team/A.Team.txt b/Basic Program/A. Team/A.Team.txt new file mode 100644 index 0000000..f7d38b4 --- /dev/null +++ b/Basic Program/A. Team/A.Team.txt @@ -0,0 +1,34 @@ +A. Team [https://codeforces.com/contest/231/problem/A] + + +One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution. Otherwise, the friends won't write the problem's solution. + +This contest offers n problems to the participants. For each problem we know, which friend is sure about the solution. Help the friends find the number of problems for which they will write a solution. + +Input +The first input line contains a single integer n (1 ≤ n ≤ 1000) — the number of problems in the contest. Then n lines contain three integers each, each integer is either 0 or 1. If the first number in the line equals 1, then Petya is sure about the problem's solution, otherwise he isn't sure. The second number shows Vasya's view on the solution, the third number shows Tonya's view. The numbers on the lines are separated by spaces. + +Output +Print a single integer — the number of problems the friends will implement on the contest. + +Examples +INPUT +3 +1 1 0 +1 1 1 +1 0 0 +OUTPUT +2 + +INPUT +2 +1 0 0 +0 1 1 +OUTPUT +1 + +Note +In the first sample Petya and Vasya are sure that they know how to solve the first problem and all three of them know how to solve the second problem. That means that they will write solutions for these problems. Only Petya is sure about the solution for the third problem, but that isn't enough, so the friends won't take it. + +In the second sample the friends will only implement the second problem, as Vasya and Tonya are sure about the solution. + diff --git a/Basic Program/CollatzConjecture/CollatzConjecture.txt b/Basic Program/CollatzConjecture/CollatzConjecture.txt new file mode 100644 index 0000000..799a6b3 --- /dev/null +++ b/Basic Program/CollatzConjecture/CollatzConjecture.txt @@ -0,0 +1,24 @@ +Collatz Conjecture + +The Collatz Conjecture says that if you take any number and follow the following steps, you will never be stuck in a loop. + +If the number is even -> number = number/2; +If the number is odd -> number = 3*number + 1; + +If you continue to do this, at some point your number will be equal to 1. + +Example: number = 26 + 1 Step - number = 26/2 = 13 + 2 Step - number = 13*3 + 1 = 40 + 3 Step - number = 40/2 = 20 + 4 Step - number = 20/2 = 10 + 5 Step - number = 10/2 = 5 + 6 Step - number = 3*5 + 1 = 16 + 7 Step - number = 16/2 = 8 + 8 Step - number = 8/2 = 4 + 9 Step - number = 4/2 = 2 + 10 Step - number = 2/2 = 1 + +For the number 26, 10 steps are needed, create a solution that calculates the number of steps for a given N number, +and the biggest value the number had during the steps. + diff --git a/Basic Program/CollatzConjecture/solution.c b/Basic Program/CollatzConjecture/solution.c new file mode 100644 index 0000000..0f667da --- /dev/null +++ b/Basic Program/CollatzConjecture/solution.c @@ -0,0 +1,23 @@ +#include +#include + +int main(){ + long int N = 26; //CALCULATING FOR N = 26 + long int biggestValue = 0; + long int steps = 0; + + while(N != 1){ + if(N%2 == 0){ + N = N/2; + }else{ + N = N*3 + 1; + } + if(N>biggestValue){ + biggestValue = N; + } + steps++; + } + + printf("Number of Steps: %ld BiggestValue: %ld", steps, biggestValue); + +} \ No newline at end of file diff --git a/EncoderProblem/Encoder.java b/Basic Program/EncoderProblem/Encoder.java similarity index 100% rename from EncoderProblem/Encoder.java rename to Basic Program/EncoderProblem/Encoder.java diff --git a/EncoderProblem/problem.txt b/Basic Program/EncoderProblem/problem.txt similarity index 100% rename from EncoderProblem/problem.txt rename to Basic Program/EncoderProblem/problem.txt diff --git a/Leap Year/instructions.txt b/Basic Program/Leap Year/instructions.txt similarity index 100% rename from Leap Year/instructions.txt rename to Basic Program/Leap Year/instructions.txt diff --git a/Leap Year/ruby_solution.rb b/Basic Program/Leap Year/ruby_solution.rb similarity index 100% rename from Leap Year/ruby_solution.rb rename to Basic Program/Leap Year/ruby_solution.rb diff --git a/Sleep_In/sleep_in.py b/Basic Program/Sleep_In/sleep_in.py similarity index 100% rename from Sleep_In/sleep_in.py rename to Basic Program/Sleep_In/sleep_in.py diff --git a/how-can-create-a-hackthoberfest-infinite-loop-in-python/hacktoberfest-loop.txt b/Basic Program/how-can-create-a-hackthoberfest-infinite-loop-in-python/hacktoberfest-loop.txt similarity index 100% rename from how-can-create-a-hackthoberfest-infinite-loop-in-python/hacktoberfest-loop.txt rename to Basic Program/how-can-create-a-hackthoberfest-infinite-loop-in-python/hacktoberfest-loop.txt diff --git a/how-can-create-a-hackthoberfest-infinite-loop-in-python/infinity-hscktoberfest-loop.py b/Basic Program/how-can-create-a-hackthoberfest-infinite-loop-in-python/infinity-hscktoberfest-loop.py similarity index 100% rename from how-can-create-a-hackthoberfest-infinite-loop-in-python/infinity-hscktoberfest-loop.py rename to Basic Program/how-can-create-a-hackthoberfest-infinite-loop-in-python/infinity-hscktoberfest-loop.py diff --git a/Aggressive Cows Spoj/problem statement.txt b/Binary Search/Aggressive Cows Spoj/problem statement.txt similarity index 100% rename from Aggressive Cows Spoj/problem statement.txt rename to Binary Search/Aggressive Cows Spoj/problem statement.txt diff --git a/Aggressive Cows Spoj/solution1.cpp b/Binary Search/Aggressive Cows Spoj/solution1.cpp similarity index 100% rename from Aggressive Cows Spoj/solution1.cpp rename to Binary Search/Aggressive Cows Spoj/solution1.cpp diff --git a/Aggressive Cows Spoj/solution2.cpp b/Binary Search/Aggressive Cows Spoj/solution2.cpp similarity index 100% rename from Aggressive Cows Spoj/solution2.cpp rename to Binary Search/Aggressive Cows Spoj/solution2.cpp diff --git a/binary_search/binary_search.txt b/Binary Search/binary_search/binary_search.txt similarity index 100% rename from binary_search/binary_search.txt rename to Binary Search/binary_search/binary_search.txt diff --git a/binary_search/bs.class b/Binary Search/binary_search/bs.class similarity index 100% rename from binary_search/bs.class rename to Binary Search/binary_search/bs.class diff --git a/binary_search/bs.ctxt b/Binary Search/binary_search/bs.ctxt similarity index 100% rename from binary_search/bs.ctxt rename to Binary Search/binary_search/bs.ctxt diff --git a/binary_search/bs.java b/Binary Search/binary_search/bs.java similarity index 100% rename from binary_search/bs.java rename to Binary Search/binary_search/bs.java diff --git a/binary_search/solution.cpp b/Binary Search/binary_search/solution.cpp similarity index 100% rename from binary_search/solution.cpp rename to Binary Search/binary_search/solution.cpp diff --git a/binary_search/solution.py b/Binary Search/binary_search/solution.py similarity index 100% rename from binary_search/solution.py rename to Binary Search/binary_search/solution.py diff --git a/ZOMCAV/ZOMCAV.txt b/Bitwise Operation/ZOMCAV/ZOMCAV.txt similarity index 100% rename from ZOMCAV/ZOMCAV.txt rename to Bitwise Operation/ZOMCAV/ZOMCAV.txt diff --git a/ZOMCAV/codechef.class b/Bitwise Operation/ZOMCAV/codechef.class similarity index 100% rename from ZOMCAV/codechef.class rename to Bitwise Operation/ZOMCAV/codechef.class diff --git a/ZOMCAV/codechef.ctxt b/Bitwise Operation/ZOMCAV/codechef.ctxt similarity index 100% rename from ZOMCAV/codechef.ctxt rename to Bitwise Operation/ZOMCAV/codechef.ctxt diff --git a/ZOMCAV/codechef.java b/Bitwise Operation/ZOMCAV/codechef.java similarity index 100% rename from ZOMCAV/codechef.java rename to Bitwise Operation/ZOMCAV/codechef.java diff --git a/0-1 Knapsack Problem/Question.txt b/Dynamic Programming/0-1 Knapsack Problem/Question.txt similarity index 100% rename from 0-1 Knapsack Problem/Question.txt rename to Dynamic Programming/0-1 Knapsack Problem/Question.txt diff --git a/0-1 Knapsack Problem/Solution.c b/Dynamic Programming/0-1 Knapsack Problem/Solution.c similarity index 100% rename from 0-1 Knapsack Problem/Solution.c rename to Dynamic Programming/0-1 Knapsack Problem/Solution.c diff --git a/Dynamic Programming/Buy-and-Sell-Stock-for-Maximum-Profit/buyAndSellStock.py b/Dynamic Programming/Buy-and-Sell-Stock-for-Maximum-Profit/buyAndSellStock.py new file mode 100644 index 0000000..729a2a8 --- /dev/null +++ b/Dynamic Programming/Buy-and-Sell-Stock-for-Maximum-Profit/buyAndSellStock.py @@ -0,0 +1,40 @@ +''' +Ref: https://www.geeksforgeeks.org/maximum-profit-by-buying-and-selling-a-share-at-most-k-times/ + +''' +# Python program to maximize the profit +# by doing at most k transactions +# given stock prices for n days + +# Function to find out maximum profit by +# buying & selling a share atmost k times +# given stock price of n days +def maxProfit(prices, n, k): + + # Bottom-up DP approach + profit = [[0 for i in range(k + 1)] + for j in range(n)] + + # Profit is zero for the first + # day and for zero transactions + for i in range(1, n): + + for j in range(1, k + 1): + max_so_far = 0 + + for l in range(i): + max_so_far = max(max_so_far, prices[i] - + prices[l] + profit[l][j - 1]) + + profit[i][j] = max(profit[i - 1][j], max_so_far) + + return profit[n - 1][k] + +# Driver code +k = 2 +prices = [10, 22, 5, 75, 65, 80] +n = len(prices) + +print("Maximum profit is:", + maxProfit(prices, n, k)) + diff --git a/Dynamic Programming/Buy-and-Sell-Stock-for-Maximum-Profit/problem-statement.txt b/Dynamic Programming/Buy-and-Sell-Stock-for-Maximum-Profit/problem-statement.txt new file mode 100644 index 0000000..3d45433 --- /dev/null +++ b/Dynamic Programming/Buy-and-Sell-Stock-for-Maximum-Profit/problem-statement.txt @@ -0,0 +1,9 @@ +Ref: https://www.geeksforgeeks.org/maximum-profit-by-buying-and-selling-a-share-at-most-k-times/ + + +In share trading, a buyer buys shares and sells on a future date. Given the stock price of n days, the trader is allowed to make at most k transactions, where a new transaction can only start after the previous transaction is complete, find out the maximum profit that a share trader could have made. + +There are various versions of the problem. If we are allowed to buy and sell only once, then we can use Maximum difference between two elements algorithm. If we are allowed to make at most 2 transactions, we can follow approach discussed here. + +In this case, we are only allowed to make at max k transactions. The problem can be solved by using dynamic programming. + diff --git a/Dynamic Programming/Bytelandian-gold-coins/instructions.txt b/Dynamic Programming/Bytelandian-gold-coins/instructions.txt new file mode 100644 index 0000000..74c2c86 --- /dev/null +++ b/Dynamic Programming/Bytelandian-gold-coins/instructions.txt @@ -0,0 +1,27 @@ +In Byteland they have a very strange monetary system. + +Each Bytelandian gold coin has an integer number written on it. A coin n can be exchanged in a bank into three coins: n/2, n/3 and n/4. But these numbers are all rounded down (the banks have to make a profit). + +You can also sell Bytelandian coins for American dollars. The exchange rate is 1:1. But you can not buy Bytelandian coins. + +You have one gold coin. What is the maximum amount of American dollars you can get for it? +Input + +The input will contain several test cases (not more than 10). Each testcase is a single line with a number n, 0 <= n <= 1 000 000 000. It is the number written on your coin. +Output + +For each test case output a single line, containing the maximum amount of American dollars you can make. + +Example + +Input: +12 +2 + +Output: +13 +2 + +You can change 12 into 6, 4 and 3, and then change these into $6+$4+$3 = $13. +If you try changing the coin 2 into 3 smaller coins, you will get 1, 0 and 0, and later you can get no more than $1 out of them. +It is better just to change the 2 coin directly into $2. diff --git a/Dynamic Programming/Bytelandian-gold-coins/solution.cpp b/Dynamic Programming/Bytelandian-gold-coins/solution.cpp new file mode 100644 index 0000000..aebf1b2 --- /dev/null +++ b/Dynamic Programming/Bytelandian-gold-coins/solution.cpp @@ -0,0 +1,17 @@ +#include +using namespace std; +map dp; +long long optcoins(int n){ + if(n<12) + return n; + if(dp.count(n)) + return dp[n]; + dp[n]=optcoins(n/2)+optcoins(n/3)+optcoins(n/4); + return dp[n]; +} +int main(){ + int x; + while(scanf("%d",&x)!=EOF) + printf("%lld\n",optcoins(x)); + return 0; +} diff --git a/COINS/Question.txt b/Dynamic Programming/COINS/Question.txt similarity index 100% rename from COINS/Question.txt rename to Dynamic Programming/COINS/Question.txt diff --git a/COINS/Readme.md b/Dynamic Programming/COINS/Readme.md similarity index 100% rename from COINS/Readme.md rename to Dynamic Programming/COINS/Readme.md diff --git a/COINS/Solution.cpp b/Dynamic Programming/COINS/Solution.cpp similarity index 100% rename from COINS/Solution.cpp rename to Dynamic Programming/COINS/Solution.cpp diff --git a/DP- Min Steps to 1/Min Steps to 1 Problem Statement.txt b/Dynamic Programming/DP- Min Steps to 1/Min Steps to 1 Problem Statement.txt similarity index 100% rename from DP- Min Steps to 1/Min Steps to 1 Problem Statement.txt rename to Dynamic Programming/DP- Min Steps to 1/Min Steps to 1 Problem Statement.txt diff --git a/DP- Min Steps to 1/minsteps.java b/Dynamic Programming/DP- Min Steps to 1/minsteps.java similarity index 100% rename from DP- Min Steps to 1/minsteps.java rename to Dynamic Programming/DP- Min Steps to 1/minsteps.java diff --git a/Dynamic Programming/Gold mine problem/GoldMineProblem.txt b/Dynamic Programming/Gold mine problem/GoldMineProblem.txt new file mode 100644 index 0000000..76506c3 --- /dev/null +++ b/Dynamic Programming/Gold mine problem/GoldMineProblem.txt @@ -0,0 +1,7 @@ +Gold Mine Problem + +Given a gold mine of n*m dimensions. + Each field in this mine contains a positive integer which is the amount of gold in tons. +Initially the miner is at first column but can be at any row. + He can move only (right->,right up /,right down\) that is from a given cell, the miner can move to the cell diagonally up towards the right or right or diagonally down towards the right. +Find out maximum amount of gold he can collect. \ No newline at end of file diff --git a/Dynamic Programming/Gold mine problem/solution.cpp.txt b/Dynamic Programming/Gold mine problem/solution.cpp.txt new file mode 100644 index 0000000..13394ba --- /dev/null +++ b/Dynamic Programming/Gold mine problem/solution.cpp.txt @@ -0,0 +1,61 @@ +// C++ program to solve Gold Mine problem +#include +using namespace std; + +const int MAX = 100; + +// Returns maximum amount of gold that can be collected +// when journey started from first column and moves +// allowed are right, right-up and right-down +int getMaxGold(int gold[][MAX], int m, int n) +{ + // Create a table for storing intermediate results + // and initialize all cells to 0. The first row of + // goldMineTable gives the maximum gold that the miner + // can collect when starts that row + int goldTable[m][n]; + memset(goldTable, 0, sizeof(goldTable)); + + for (int col=n-1; col>=0; col--) + { + for (int row=0; row) + int right = (col==n-1)? 0: goldTable[row][col+1]; + + // Gold collected on going to the cell to right up (/) + int right_up = (row==0 || col==n-1)? 0: + goldTable[row-1][col+1]; + + // Gold collected on going to the cell to right down (\) + int right_down = (row==m-1 || col==n-1)? 0: + goldTable[row+1][col+1]; + + // Max gold collected from taking either of the + // above 3 paths + goldTable[row][col] = gold[row][col] + + max(right, max(right_up, right_down)); + + } + } + + // The max amount of gold collected will be the max + // value in first column of all rows + int res = goldTable[0][0]; + for (int i=1; i +using namespace std; +int main(){ + ios_base::sync_with_stdio(false); + int n,k;cin>>n>>k; + int a[n];long long int mod=1000000007; + int max=0; + for(int i=0;i>a[i]; + if(a[i]>max) + max=a[i]; + } + long int f[max+1]; + memset(f,0,sizeof(f)); + for(int i=0;iv; + for(int i=0;i<=max;i++) + if(f[i]) + v.push_back(f[i]); + long int l=v.size(); + k=k>l?l:k; + long int dpans[k+1][l],val; + val=v[0]+1; + memset(dpans,0,sizeof(dpans)); + dpans[0][0]=1; + dpans[1][0]=val; + long int total=0; + for(int i=2;i<=k;i++) + dpans[i][0]=val; + for(int i=1;i +#include +#include +using namespace std; +int solver(string s1,string s2,vector>&dp,int n,int m) +{ + if(s1.empty()||s2.empty()) + return 0; + if(dp[n][m] >= 0) + return dp[n][m]; + if(s1[0]==s2[0]) + { + int ans = 1 + solver(s1.substr(1),s2.substr(1),dp,n-1,m-1); + dp[n][m] = ans; + return ans; + } + int ans1 = solver(s1,s2.substr(1),dp,n,m-1); + int ans2 = solver(s1.substr(1),s2,dp,n-1,m); + dp[n][m] = max(ans1,ans2); + return max(ans1,ans2); +} +int lcs(string s1, string s2) +{ + int n = s1.length(),m=s2.length(); + vector>dp(n+1,vector(m+1,-1)); + int ans = solver( s1, s2, dp , s1.length(),s2.length()); + return ans; +} + +int main() +{ + string s1, s2; + cin >> s1 >> s2; + cout << lcs(s1, s2); +} diff --git a/Dynamic Programming/largest_comman_subsequece/question.txt b/Dynamic Programming/largest_comman_subsequece/question.txt new file mode 100644 index 0000000..5f6391b --- /dev/null +++ b/Dynamic Programming/largest_comman_subsequece/question.txt @@ -0,0 +1,3 @@ +LCS Problem Statement: Given two sequences, find the length of longest subsequence present in both of them. A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous. + + diff --git a/Product_of_lengths_all_cycles_undirected_graph/question.txt b/Graph/Product_of_lengths_all_cycles_undirected_graph/question.txt similarity index 100% rename from Product_of_lengths_all_cycles_undirected_graph/question.txt rename to Graph/Product_of_lengths_all_cycles_undirected_graph/question.txt diff --git a/Product_of_lengths_all_cycles_undirected_graph/solution.cpp b/Graph/Product_of_lengths_all_cycles_undirected_graph/solution.cpp similarity index 100% rename from Product_of_lengths_all_cycles_undirected_graph/solution.cpp rename to Graph/Product_of_lengths_all_cycles_undirected_graph/solution.cpp diff --git a/Greedy/Cutting_a_Rod/CuttingARod.java b/Greedy/Cutting_a_Rod/CuttingARod.java new file mode 100644 index 0000000..8a29c87 --- /dev/null +++ b/Greedy/Cutting_a_Rod/CuttingARod.java @@ -0,0 +1,33 @@ +/** + * Time Complexity : O(n^2) + * which is much better than the + * worst case time complexity of Naive Recursive implementation. + */ + +import java.util.*; +import java.io.*; + +class CuttingARod { + + public static int cutCutCut(int price[], int size) { + + int memory[] = new int[size+1]; + memory[0] = 0; + + for(int i=1; i<=size; i++){ + int maximum = Integer.MIN_VALUE; + for(int j=0; j + +using namespace std; + +int main() + +{ + +int N,i=0; + +cin>>N; + +while(i1) - { - for(int i =0;i1) + { + for(int i =0;i +using namespace std; + +/* Hi I am using my own class to use in insertion sort function*/ + +template +class LinearList{ + private: + int MaxSize; + Item *element; // 1D dynamic array + int len; + public: + /* Default constructor. + * Should create an empty list that not contain any elements*/ + LinearList() + { + element=nullptr; + len=0; + }; + + /* This constructor should create a list containing MaxSize elements. You can intialize the elements with any values.*/ + LinearList(const int& MaxListSize) + { + MaxSize=MaxListSize; + element = new Item[MaxSize]; + len=0; + + }; + + /* Destructor. + * Must free all the memory contained by the list */ + ~LinearList(){}; + + /* Indexing operator. + * It should behave the same way array indexing does. i.e, + * LinearList L; + * L[0] should refer to the first element; + * L[1] to the second element and so on. + * */ + Item& operator[](const int& i) + { + return element[i]; + }; //return i'th element of list + + /* Returns true if the list is empty, false otherwise. + * */ + bool isEmpty() + { + if(len==0) + { + return true; + } + else + { + return false; + } + }; + + /* Returns the actual length (number of elements) in the list. + * */ + int length() + { + return len; + }; + + /* Returns the maximum size of the list. + * */ + int maxSize() + { + return maxSize; + }; + + /* Returns the k-th element of the list. + * */ + Item returnListElement(const int k) + { + return element[k-1]; + }; + /* Set x to the k-th element and + * return true if k-th element is present otherwise return false. + * */ + bool find(const int k, Item& x) + { + if(x==element[k-1]) + { + return true; + } + else + { + + return false; + } + }; + + /* Search for x and + * return the position if found, else return 0. + * */ + int search(Item& x) + { + for(int i=0;ik;i--) + { + element[i]=element[i-1]; + } + element[k]=x; + len=len+1; + }; + + +}; + +//insertion sort function +void insertionSort(LinearList& A) + { + int i,j,temp,len; + i=j=0; + len=A.length(); + j=len; + for(i=1;i-1;j--) + { + if(temp> n; + LinearList l(100); + + for(i=0;i> temp; + l.insert(i,temp); + } + insertionSort(l); + for(i=0;i -using namespace std; - -void copyArr(int from[], int si, int ei, int * to) { - // while (si <= ei) *to++ = *si++; - while (si <= ei) { - *to = from[si]; - ++si; - ++to; - } -} - - -void mergeSortedArray(int arr[], int si, int ei, int mid) { - - int tmp_A[100]; - int tmp_B[100]; - - copyArr(arr, si, mid, tmp_A); - copyArr(arr, mid + 1, ei, tmp_B); - - int i = 0; - int j = 0; - int k = si; - - //while a has elements and b has elements, I have to do something - int size_A = mid - si + 1; - int size_B = ei - (mid + 1) + 1; - - while (i < size_A && j < size_B) { - if (tmp_A[i] < tmp_B[j]) { - arr[k] = tmp_A[i]; - i++; - k++; - } - else { - arr[k++] = tmp_B[j++]; - } - } - - while (i < size_A) { - arr[k++] = tmp_A[i++]; - } - - while (j < size_B) arr[k++] = tmp_B[j++]; - - -} - - -void mergeSort(int arr[], int si, int ei) { - if (si >= ei) { - //no elements - return; - } - - int mid = (si + ei) / 2; - //sort the left part - mergeSort(arr, si, mid); - mergeSort(arr, mid + 1, ei); - - mergeSortedArray(arr, si, ei, mid); - -} - - -int main() { - int arr[100]; - int n; - cin >> n; - inputArr(arr, n); - - mergeSort(arr, 0, n - 1); - - printArr(arr, n); -} + +#include "../helper.h" +#include +using namespace std; + +void copyArr(int from[], int si, int ei, int * to) { + // while (si <= ei) *to++ = *si++; + while (si <= ei) { + *to = from[si]; + ++si; + ++to; + } +} + + +void mergeSortedArray(int arr[], int si, int ei, int mid) { + + int tmp_A[100]; + int tmp_B[100]; + + copyArr(arr, si, mid, tmp_A); + copyArr(arr, mid + 1, ei, tmp_B); + + int i = 0; + int j = 0; + int k = si; + + //while a has elements and b has elements, I have to do something + int size_A = mid - si + 1; + int size_B = ei - (mid + 1) + 1; + + while (i < size_A && j < size_B) { + if (tmp_A[i] < tmp_B[j]) { + arr[k] = tmp_A[i]; + i++; + k++; + } + else { + arr[k++] = tmp_B[j++]; + } + } + + while (i < size_A) { + arr[k++] = tmp_A[i++]; + } + + while (j < size_B) arr[k++] = tmp_B[j++]; + + +} + + +void mergeSort(int arr[], int si, int ei) { + if (si >= ei) { + //no elements + return; + } + + int mid = (si + ei) / 2; + //sort the left part + mergeSort(arr, si, mid); + mergeSort(arr, mid + 1, ei); + + mergeSortedArray(arr, si, ei, mid); + +} + + +int main() { + int arr[100]; + int n; + cin >> n; + inputArr(arr, n); + + mergeSort(arr, 0, n - 1); + + printArr(arr, n); +} diff --git a/Mersort_In_C++/mergesort.txt b/Sorting/Mersort_In_C++/mergesort.txt similarity index 100% rename from Mersort_In_C++/mergesort.txt rename to Sorting/Mersort_In_C++/mergesort.txt diff --git a/Quicksort-JS/question.txt b/Sorting/Quicksort-JS/question.txt similarity index 100% rename from Quicksort-JS/question.txt rename to Sorting/Quicksort-JS/question.txt diff --git a/Quicksort-JS/quickSort.js b/Sorting/Quicksort-JS/quickSort.js similarity index 100% rename from Quicksort-JS/quickSort.js rename to Sorting/Quicksort-JS/quickSort.js diff --git a/Quicksort-python/Question.txt b/Sorting/Quicksort-python/Question.txt similarity index 100% rename from Quicksort-python/Question.txt rename to Sorting/Quicksort-python/Question.txt diff --git a/Quicksort-python/algorithm.txt b/Sorting/Quicksort-python/algorithm.txt similarity index 100% rename from Quicksort-python/algorithm.txt rename to Sorting/Quicksort-python/algorithm.txt diff --git a/Quicksort-python/quickSort.py b/Sorting/Quicksort-python/quickSort.py old mode 100755 new mode 100644 similarity index 100% rename from Quicksort-python/quickSort.py rename to Sorting/Quicksort-python/quickSort.py diff --git a/Sorting/bubble_sort_c/question.txt b/Sorting/bubble_sort_c/question.txt new file mode 100644 index 0000000..bd6c83d --- /dev/null +++ b/Sorting/bubble_sort_c/question.txt @@ -0,0 +1,2 @@ +Make a C program to bubble sort this array of integers (smallest to biggest): {303, -909, 101, 42, 0, 42, 21, 1, 2} +Expected result => {-909, 0, 1, 2, 21. 42, 42, 101, 303} diff --git a/Sorting/bubble_sort_c/solution/bubble_sort.c b/Sorting/bubble_sort_c/solution/bubble_sort.c new file mode 100644 index 0000000..8f7ab02 --- /dev/null +++ b/Sorting/bubble_sort_c/solution/bubble_sort.c @@ -0,0 +1,23 @@ +#include "bubble_sort.h" + +void swap_values(int *a, int *b) +{ + int buffer = *a; + *a = *b; + *b = buffer; +} + +int *bubble_sort(int *arr, size_t arr_len) +{ + size_t i = 0; + + while (i++ < arr_len) + { + if (arr[i] < arr[i-1]) + { + swap_values(&arr[i], &arr[i-1]); + i = 0; + } + } + return(arr); +} diff --git a/Sorting/bubble_sort_c/solution/bubble_sort.h b/Sorting/bubble_sort_c/solution/bubble_sort.h new file mode 100644 index 0000000..4e69c28 --- /dev/null +++ b/Sorting/bubble_sort_c/solution/bubble_sort.h @@ -0,0 +1,5 @@ +#include +#include + +int *bubble_sort(int *arr, size_t arr_len); +void print_array(int *arr, size_t arr_len); diff --git a/Sorting/bubble_sort_c/solution/main.c b/Sorting/bubble_sort_c/solution/main.c new file mode 100644 index 0000000..9616442 --- /dev/null +++ b/Sorting/bubble_sort_c/solution/main.c @@ -0,0 +1,12 @@ +#include "bubble_sort.h" + +int main(void) +{ + int to_sort[] = {303, -909, 101, 42, 0, 42, 21, 1, 2}; + size_t arr_len = sizeof(to_sort) / sizeof(to_sort[0]); + int *sorted = bubble_sort(to_sort, arr_len); + + print_array(sorted, arr_len); + + return(EXIT_SUCCESS); +} diff --git a/Sorting/bubble_sort_c/solution/print_array.c b/Sorting/bubble_sort_c/solution/print_array.c new file mode 100644 index 0000000..39c130a --- /dev/null +++ b/Sorting/bubble_sort_c/solution/print_array.c @@ -0,0 +1,10 @@ +#include "bubble_sort.h" + +void print_array(int *arr, size_t arr_len) +{ + size_t i; + + printf("Sorted array:\n"); + for (i = 0; i < arr_len; i++) + printf("%d\n", arr[i]); +} diff --git a/Stack/Binary numbers/Question.txt b/Stack/Binary numbers/Question.txt new file mode 100644 index 0000000..d540fa0 --- /dev/null +++ b/Stack/Binary numbers/Question.txt @@ -0,0 +1 @@ +The question is how to make binary numbers using a stack. \ No newline at end of file diff --git a/Stack/Binary numbers/solution.cpp b/Stack/Binary numbers/solution.cpp new file mode 100644 index 0000000..a388706 --- /dev/null +++ b/Stack/Binary numbers/solution.cpp @@ -0,0 +1,27 @@ +#include +#include +using namespace std; +int main() +{ + int a,b,l,c; + stack stos; + cout << "Number to change: "; + cin >> a; + l=a; + + while(a!=0) + { + b=a%2; + a=a/2; + stos.push(b); + } + cout << "Number " << l << " is equal to: "; + while(!stos.empty()) + { + cout << stos.top(); + stos.pop(); + } + cout << " in binary system."; + +return 0; +} diff --git a/Generate Parentheses/Question.txt b/Stack/Generate Parentheses/Question.txt similarity index 100% rename from Generate Parentheses/Question.txt rename to Stack/Generate Parentheses/Question.txt diff --git a/Generate Parentheses/Solution b/Stack/Generate Parentheses/Solution old mode 100755 new mode 100644 similarity index 100% rename from Generate Parentheses/Solution rename to Stack/Generate Parentheses/Solution diff --git a/Generate Parentheses/Solution.cpp b/Stack/Generate Parentheses/Solution.cpp similarity index 100% rename from Generate Parentheses/Solution.cpp rename to Stack/Generate Parentheses/Solution.cpp diff --git a/Street parade/code.cpp b/Stack/Street parade/code.cpp similarity index 100% rename from Street parade/code.cpp rename to Stack/Street parade/code.cpp diff --git a/Street parade/problem_statement.txt b/Stack/Street parade/problem_statement.txt similarity index 100% rename from Street parade/problem_statement.txt rename to Stack/Street parade/problem_statement.txt diff --git a/AnagramChecking/anagram_checking.py b/String/AnagramChecking/anagram_checking.py old mode 100755 new mode 100644 similarity index 100% rename from AnagramChecking/anagram_checking.py rename to String/AnagramChecking/anagram_checking.py diff --git a/AnagramChecking/anagram_checking.txt b/String/AnagramChecking/anagram_checking.txt similarity index 100% rename from AnagramChecking/anagram_checking.txt rename to String/AnagramChecking/anagram_checking.txt diff --git a/Arrangement_of_Queue/Question.txt b/String/Arrangement_of_Queue/Question.txt similarity index 100% rename from Arrangement_of_Queue/Question.txt rename to String/Arrangement_of_Queue/Question.txt diff --git a/Arrangement_of_Queue/README.md b/String/Arrangement_of_Queue/README.md similarity index 100% rename from Arrangement_of_Queue/README.md rename to String/Arrangement_of_Queue/README.md diff --git a/Arrangement_of_Queue/Solution.py b/String/Arrangement_of_Queue/Solution.py similarity index 100% rename from Arrangement_of_Queue/Solution.py rename to String/Arrangement_of_Queue/Solution.py diff --git a/Cenit-Polar-Crypt/Issue.txt b/String/Cenit-Polar-Crypt/Issue.txt similarity index 100% rename from Cenit-Polar-Crypt/Issue.txt rename to String/Cenit-Polar-Crypt/Issue.txt diff --git a/Cenit-Polar-Crypt/Solution.js b/String/Cenit-Polar-Crypt/Solution.js similarity index 100% rename from Cenit-Polar-Crypt/Solution.js rename to String/Cenit-Polar-Crypt/Solution.js diff --git a/Check_String_Palindrome/Source1.cpp b/String/Check_String_Palindrome/Source1.cpp similarity index 63% rename from Check_String_Palindrome/Source1.cpp rename to String/Check_String_Palindrome/Source1.cpp index 0fdda1d..8585e70 100644 --- a/Check_String_Palindrome/Source1.cpp +++ b/String/Check_String_Palindrome/Source1.cpp @@ -3,6 +3,7 @@ using namespace std; +//This is a function that returns a boolean value, after checking the string. bool checkStringPallindrome(string inputString); bool checkStringPallindrome(string inputString) { @@ -13,10 +14,11 @@ bool checkStringPallindrome(string inputString) { } return true; } -int main() { +void main() { - string input; - getline(cin, input); + clrscr(); //this inbuild function clears the screen + string input; //the string to check whether its palindrome or not + getline(cin, input); if (checkStringPallindrome(input)) { cout << "true" << endl; } @@ -24,6 +26,5 @@ int main() { cout << "false" << endl; } - system("pause"); - return 1; -} \ No newline at end of file + getch(); +} diff --git a/Check_String_Palindrome/problem.txt b/String/Check_String_Palindrome/problem.txt similarity index 100% rename from Check_String_Palindrome/problem.txt rename to String/Check_String_Palindrome/problem.txt diff --git a/FANCY/problem.txt b/String/FANCY/problem.txt similarity index 100% rename from FANCY/problem.txt rename to String/FANCY/problem.txt diff --git a/FANCY/solution.py b/String/FANCY/solution.py similarity index 100% rename from FANCY/solution.py rename to String/FANCY/solution.py diff --git a/Isograms/isograms.py b/String/Isograms/isograms.py similarity index 100% rename from Isograms/isograms.py rename to String/Isograms/isograms.py diff --git a/Isograms/problem_statement.txt b/String/Isograms/problem_statement.txt similarity index 100% rename from Isograms/problem_statement.txt rename to String/Isograms/problem_statement.txt diff --git a/Palindrome/palindrome.c b/String/Palindrome/palindrome.c similarity index 100% rename from Palindrome/palindrome.c rename to String/Palindrome/palindrome.c diff --git a/Palindrome/question.txt b/String/Palindrome/question.txt similarity index 100% rename from Palindrome/question.txt rename to String/Palindrome/question.txt diff --git a/Python_Palindrome/PalindromeQues.txt b/String/Python_Palindrome/PalindromeQues.txt similarity index 100% rename from Python_Palindrome/PalindromeQues.txt rename to String/Python_Palindrome/PalindromeQues.txt diff --git a/Python_Palindrome/solution.py b/String/Python_Palindrome/solution.py similarity index 100% rename from Python_Palindrome/solution.py rename to String/Python_Palindrome/solution.py diff --git a/Reverse string in place/question.txt b/String/Reverse string in place/question.txt similarity index 100% rename from Reverse string in place/question.txt rename to String/Reverse string in place/question.txt diff --git a/Reverse string in place/solution.java b/String/Reverse string in place/solution.java similarity index 100% rename from Reverse string in place/solution.java rename to String/Reverse string in place/solution.java diff --git a/ReverseChars/ReverseChars.java b/String/ReverseChars/ReverseChars.java similarity index 95% rename from ReverseChars/ReverseChars.java rename to String/ReverseChars/ReverseChars.java index 75aa58d..bd0c68e 100644 --- a/ReverseChars/ReverseChars.java +++ b/String/ReverseChars/ReverseChars.java @@ -1,26 +1,26 @@ -class main { - - public static void main(String[] args){ - - System.out.println(reverseChars("These Chars will be in reverse")); - - } - - public static String reverseChars(String reverseIt) { - - int stringLength; - String itReversed; - - reverseIt = reverseIt; - - stringLength = reverseIt.length(); - itReversed = ""; - - for (int i = 1; i <= stringLength; i++){ - char backwardChars = reverseIt.charAt(stringLength - i); - - itReversed += backwardChars; - } - return itReversed; - } +class main { + + public static void main(String[] args){ + + System.out.println(reverseChars("These Chars will be in reverse")); + + } + + public static String reverseChars(String reverseIt) { + + int stringLength; + String itReversed; + + reverseIt = reverseIt; + + stringLength = reverseIt.length(); + itReversed = ""; + + for (int i = 1; i <= stringLength; i++){ + char backwardChars = reverseIt.charAt(stringLength - i); + + itReversed += backwardChars; + } + return itReversed; + } } \ No newline at end of file diff --git a/ReverseChars/problem.txt b/String/ReverseChars/problem.txt similarity index 100% rename from ReverseChars/problem.txt rename to String/ReverseChars/problem.txt diff --git a/SplitString/Question.txt b/String/SplitString/Question.txt similarity index 100% rename from SplitString/Question.txt rename to String/SplitString/Question.txt diff --git a/SplitString/Solution.cpp b/String/SplitString/Solution.cpp similarity index 100% rename from SplitString/Solution.cpp rename to String/SplitString/Solution.cpp diff --git a/String_Permutation/question.txt b/String/String_Permutation/question.txt similarity index 100% rename from String_Permutation/question.txt rename to String/String_Permutation/question.txt diff --git a/String_Permutation/solution.cpp b/String/String_Permutation/solution.cpp similarity index 100% rename from String_Permutation/solution.cpp rename to String/String_Permutation/solution.cpp diff --git a/StrongPassword/solution.py b/String/StrongPassword/solution.py similarity index 100% rename from StrongPassword/solution.py rename to String/StrongPassword/solution.py diff --git a/StrongPassword/strongpasswordqn.txt b/String/StrongPassword/strongpasswordqn.txt similarity index 100% rename from StrongPassword/strongpasswordqn.txt rename to String/StrongPassword/strongpasswordqn.txt diff --git a/Subsequences/question.txt b/String/Subsequences/question.txt similarity index 100% rename from Subsequences/question.txt rename to String/Subsequences/question.txt diff --git a/Subsequences/subsequences.cpp b/String/Subsequences/subsequences.cpp old mode 100755 new mode 100644 similarity index 94% rename from Subsequences/subsequences.cpp rename to String/Subsequences/subsequences.cpp index b445c4f..9c0ec8c --- a/Subsequences/subsequences.cpp +++ b/String/Subsequences/subsequences.cpp @@ -1,27 +1,27 @@ -//find all the sub sequences of a string -#include -using namespace std; -char output[100] = ""; - -void printSubSeq(char str[], int be, int idx) -{ - if (str[be] == '\0') - { - output[idx] = '\0'; - cout << output << endl; - return; - } - - printSubSeq(str, be + 1, idx); - output[idx] = str[be]; - printSubSeq(str, be + 1, idx + 1); -} - - -int main() { - char str[100]; - cin >> str; - - - printSubSeq(str, 0, 0); -} +//find all the sub sequences of a string +#include +using namespace std; +char output[100] = ""; + +void printSubSeq(char str[], int be, int idx) +{ + if (str[be] == '\0') + { + output[idx] = '\0'; + cout << output << endl; + return; + } + + printSubSeq(str, be + 1, idx); + output[idx] = str[be]; + printSubSeq(str, be + 1, idx + 1); +} + + +int main() { + char str[100]; + cin >> str; + + + printSubSeq(str, 0, 0); +} diff --git a/The Reversed World/Solution.cpp b/String/The Reversed World/Solution.cpp similarity index 100% rename from The Reversed World/Solution.cpp rename to String/The Reversed World/Solution.cpp diff --git a/The Reversed World/The Reversed World.txt b/String/The Reversed World/The Reversed World.txt similarity index 100% rename from The Reversed World/The Reversed World.txt rename to String/The Reversed World/The Reversed World.txt diff --git a/ToyObsession/problem.c b/String/ToyObsession/problem.c similarity index 100% rename from ToyObsession/problem.c rename to String/ToyObsession/problem.c diff --git a/ToyObsession/solution.c b/String/ToyObsession/solution.c similarity index 100% rename from ToyObsession/solution.c rename to String/ToyObsession/solution.c diff --git a/Word_Frequency/question.txt b/String/Word_Frequency/question.txt similarity index 100% rename from Word_Frequency/question.txt rename to String/Word_Frequency/question.txt diff --git a/Word_Frequency/solution.js b/String/Word_Frequency/solution.js similarity index 100% rename from Word_Frequency/solution.js rename to String/Word_Frequency/solution.js diff --git a/ginortS/Question.txt b/String/ginortS/Question.txt similarity index 100% rename from ginortS/Question.txt rename to String/ginortS/Question.txt diff --git a/ginortS/Solution.py b/String/ginortS/Solution.py similarity index 100% rename from ginortS/Solution.py rename to String/ginortS/Solution.py diff --git a/size-of-tree-C++/problem_statement.txt b/Tree/size-of-tree-C++/problem_statement.txt similarity index 100% rename from size-of-tree-C++/problem_statement.txt rename to Tree/size-of-tree-C++/problem_statement.txt diff --git a/size-of-tree-C++/sizeoftree.cpp b/Tree/size-of-tree-C++/sizeoftree.cpp similarity index 100% rename from size-of-tree-C++/sizeoftree.cpp rename to Tree/size-of-tree-C++/sizeoftree.cpp diff --git a/Acronym/instructions.txt b/Unknown/Acronym/instructions.txt similarity index 100% rename from Acronym/instructions.txt rename to Unknown/Acronym/instructions.txt diff --git a/Acronym/ruby_solution.rb b/Unknown/Acronym/ruby_solution.rb similarity index 100% rename from Acronym/ruby_solution.rb rename to Unknown/Acronym/ruby_solution.rb diff --git a/CONTON/QUESTION.txt b/Unknown/CONTON/QUESTION.txt similarity index 100% rename from CONTON/QUESTION.txt rename to Unknown/CONTON/QUESTION.txt diff --git a/CONTON/solution.c b/Unknown/CONTON/solution.c similarity index 100% rename from CONTON/solution.c rename to Unknown/CONTON/solution.c diff --git a/Chefdil/ans.cpp b/Unknown/Chefdil/ans.cpp similarity index 100% rename from Chefdil/ans.cpp rename to Unknown/Chefdil/ans.cpp diff --git a/Chefdil/ques.txt b/Unknown/Chefdil/ques.txt similarity index 100% rename from Chefdil/ques.txt rename to Unknown/Chefdil/ques.txt diff --git a/Unknown/Chocolate_SPOJ/question.txt b/Unknown/Chocolate_SPOJ/question.txt new file mode 100644 index 0000000..8f45eef --- /dev/null +++ b/Unknown/Chocolate_SPOJ/question.txt @@ -0,0 +1,41 @@ +We are given a bar of chocolate composed of m*n square pieces. One should break the chocolate into single squares. Parts of the chocolate may be broken along the vertical and horizontal lines as indicated by the broken lines in the picture. + +A single break of a part of the chocolate along a chosen vertical or horizontal line divides that part into two smaller ones. Each break of a part of the chocolate is charged a cost expressed by a positive integer. This cost does not depend on the size of the part that is being broken but only depends on the line the break goes along. Let us denote the costs of breaking along consecutive vertical lines with x1, x2, ..., xm-1 and along horizontal lines with y1, y2, ..., yn-1. + +The cost of breaking the whole bar into single squares is the sum of the successive breaks. One should compute the minimal cost of breaking the whole chocolate into single squares. + + +For example, if we break the chocolate presented in the picture first along the horizontal lines, and next each obtained part along vertical lines then the cost of that breaking will be y1+y2+y3+4*(x1+x2+x3+x4+x5). + +Task +Write a program that for each test case: + +Reads the numbers x1, x2, ..., xm-1 and y1, y2, ..., yn-1 +Computes the minimal cost of breaking the whole chocolate into single squares, writes the result. +Input +One integer in the first line, stating the number of test cases, followed by a blank line. There will be not more than 20 tests. + +For each test case, at the first line there are two positive integers m and n separated by a single space, 2 <= m,n <= 1000. In the successive m-1 lines there are numbers x1, x2, ..., xm-1, one per line, 1 <= xi <= 1000. In the successive n-1 lines there are numbers y1, y2, ..., yn-1, one per line, 1 <= yi <= 1000. + +The test cases will be separated by a single blank line. + +Output +For each test case : write one integer - the minimal cost of breaking the whole chocolate into single squares. + + +Example +Input: +1 + +6 4 +2 +1 +3 +1 +4 +4 +1 +2 + +Output: +42 diff --git a/Unknown/Chocolate_SPOJ/solution.java b/Unknown/Chocolate_SPOJ/solution.java new file mode 100644 index 0000000..f04b8c2 --- /dev/null +++ b/Unknown/Chocolate_SPOJ/solution.java @@ -0,0 +1,182 @@ +import java.io.OutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PrintWriter; +import java.util.Arrays; +import java.io.BufferedWriter; +import java.io.Writer; +import java.io.OutputStreamWriter; +import java.util.InputMismatchException; +import java.io.IOException; +import java.io.InputStream; + +/** + * Built using CHelper plug-in + * Actual solution is at the top + * + * @author Rishabhdeep Singh + */ +public class Main { + public static void main(String[] args) { + InputStream inputStream = System.in; + OutputStream outputStream = System.out; + InputReader in = new InputReader(inputStream); + OutputWriter out = new OutputWriter(outputStream); + MultipleTestcases solver = new MultipleTestcases(); + int testCount = Integer.parseInt(in.next()); + for (int i = 1; i <= testCount; i++) + solver.solve(i, in, out); + out.close(); + } + + static class MultipleTestcases { + public void solve(int testNumber, InputReader in, OutputWriter out) { + int n = in.nextInt(); + int m = in.nextInt(); + --n; + --m; + int[] x = in.nextIntArray(n); + int[] y = in.nextIntArray(m); + int s1 = 0, s2 = 0; + for (int i = 0; i < n; i++) { + s1 += x[i]; + } + for (int i = 0; i < m; i++) { + s2 += y[i]; + } + Arrays.sort(x); + Arrays.sort(y); + int ans = s1 + s2; + for (int i = n - 1, j = m - 1; i >= 0 && j >= 0; ) { + if (y[j] >= x[i]) { + ans += s1; + s2 -= y[j]; + --j; + } else { + ans += s2; + s1 -= x[i]; + --i; + } + } + out.println(ans); + } + + } + + static class OutputWriter { + private final PrintWriter writer; + + public OutputWriter(OutputStream outputStream) { + writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); + } + + public OutputWriter(Writer writer) { + this.writer = new PrintWriter(writer); + } + + public void close() { + writer.close(); + } + + public void println(int i) { + writer.println(i); + } + + } + + static class InputReader { + private InputStream stream; + private byte[] buf = new byte[1024]; + private int curChar; + private int numChars; + private InputReader.SpaceCharFilter filter; + + public InputReader(InputStream stream) { + this.stream = stream; + } + + public int read() { + if (numChars == -1) { + throw new InputMismatchException(); + } + if (curChar >= numChars) { + curChar = 0; + try { + numChars = stream.read(buf); + } catch (IOException e) { + throw new InputMismatchException(); + } + if (numChars <= 0) { + return -1; + } + } + return buf[curChar++]; + } + + public int nextInt() { + int c = read(); + while (isSpaceChar(c)) { + c = read(); + } + int sgn = 1; + if (c == '-') { + sgn = -1; + c = read(); + } + int res = 0; + do { + if (c < '0' || c > '9') { + throw new InputMismatchException(); + } + res *= 10; + res += c - '0'; + c = read(); + } while (!isSpaceChar(c)); + return res * sgn; + } + + public String nextString() { + int c = read(); + while (isSpaceChar(c)) { + c = read(); + } + StringBuilder res = new StringBuilder(); + do { + if (Character.isValidCodePoint(c)) { + res.appendCodePoint(c); + } + c = read(); + } while (!isSpaceChar(c)); + return res.toString(); + } + + public boolean isSpaceChar(int c) { + if (filter != null) { + return filter.isSpaceChar(c); + } + return isWhitespace(c); + } + + public static boolean isWhitespace(int c) { + return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; + } + + public String next() { + return nextString(); + } + + public int[] nextIntArray(int n) { + int[] array = new int[n]; + for (int i = 0; i < n; ++i) array[i] = nextInt(); + return array; + } + + public interface SpaceCharFilter { + public boolean isSpaceChar(int ch); + + } + + } +} + diff --git a/Fair Rations/Answer.cpp b/Unknown/Fair Rations/Answer.cpp similarity index 100% rename from Fair Rations/Answer.cpp rename to Unknown/Fair Rations/Answer.cpp diff --git a/Fair Rations/Problem Statement .txt b/Unknown/Fair Rations/Problem Statement .txt similarity index 100% rename from Fair Rations/Problem Statement .txt rename to Unknown/Fair Rations/Problem Statement .txt diff --git a/Unknown/Industrial Nim/Industrial_Nim.cpp b/Unknown/Industrial Nim/Industrial_Nim.cpp new file mode 100644 index 0000000..680db05 --- /dev/null +++ b/Unknown/Industrial Nim/Industrial_Nim.cpp @@ -0,0 +1,35 @@ +#include +using namespace std; + +vector vec; +bool nim() /* return true if the first player will win */ +{ + long long x=0; + for(int i=0;i0; +} + +long long f(long long n) /* n&3 equivalent to n%4 */ +{ + long long x=n&3; + if(x==0) return n; if(x==1) return 1; + if(x==2) return n+1; if(x==3) return 0; +} + + + +int main() +{ + long long n,x,m; + cin>>n; + while(n--) + { + cin>>x>>m; + vec.push_back(f(x+m-1)^f(x-1)); + } + if(nim()) + cout<<"tolik"< + +using namespace std; + +typedef long long int LL; +typedef vector VLL; +typedef std::complex CD; + +#define PB push_back +#define F first +#define s second +#define SZ(x) x.size() +#define ALL(a) std::begin(a), std::end(a) +#define IN_REP int _t; cin >> _t ; while(_t--) +#define IOS ios::sync_with_stdio(false);cin.tie(NULL) +#define FOR(i, a, b) for(int i=(a);i<(b);i++) +#define REP(i, n) FOR(i,0,n) +const double PI = acos(-1); +typedef std::valarray CArray; + +// Cooley–Tukey FFT (in-place) +void fft(CArray &x) { + // const size_t N = x.size(); + int N = SZ(x); + if (N <= 1) return; + + // divide + CArray even = x[std::slice(0, N / 2, 2)]; + CArray odd = x[std::slice(1, N / 2, 2)]; + + // conquer + fft(even); + fft(odd); + + // combine + // for (size_t k = 0; k < N/2; ++k){ + for (int k = 0; k < N / 2; ++k) { + CD t = std::polar(1.0, -2 * PI * k / N) * odd[k]; + x[k] = even[k] + t; + x[k + N / 2] = even[k] - t; + } +} + +// inverse fft (in-place) +void ifft(CArray &x) { + // conjugate the complex numbers + x = x.apply(std::conj); + + // forward fft + fft(x); + + // conjugate the complex numbers again + x = x.apply(std::conj); + + // scale the numbers + x /= x.size(); +} + +int main() { + IOS; + IN_REP { + int n; + cin >> n; + n++; // Given in question + int size = 2 * (1 << int(ceil(log2(n)))); + + CArray x(size), y(size); + FOR(i, size - n, size) cin >> x[i]; + fft(x); + FOR(i, size - n, size) cin >> y[i]; + fft(y); + + CArray res(size); + res = x * y; + ifft(res); + VLL ans; + REP(i, size - 1) { + ans.PB(round(res[i].real())); + } + for (int i = size - 1 - (2 * n - 1); i < size - 1; i++) { + cout << ans[i] << " "; + } + cout << endl; + } + return 0; +} diff --git a/Unknown/Strange_Food_Chain/question.txt b/Unknown/Strange_Food_Chain/question.txt new file mode 100644 index 0000000..ae9b410 --- /dev/null +++ b/Unknown/Strange_Food_Chain/question.txt @@ -0,0 +1,37 @@ +There are 3 kinds of animals A,B and C. A can eat B,B can eat C,C can eat A. It's interesting,isn't it? + +Now we have n animals,numbered from 1 to n. Each of them is one of the 3 kinds of animals:A,B,C. + +Today Mary tells us k pieces of information about these n animals. Each piece has one of the two forms below: + +1 x y: It tells us the kind of x and y are the same. +2 x y: It tells us x can eat y. +Some of these k pieces are true,some are false. The piece is false if it satisfies one of the 3 conditions below, otherwise it's true. + +X or Y in this piece is larger than n. +This piece tells us X can eat X. +This piece conflicts to some true piece before. +Input +The first line contains a single integer t.t blocks follow. + +To every block,the first line contains two integers n(1<=n<=50000) and k (1<=k<=100000). k lines follow,each contains 3 positive integers D(1<=D<=2),X,Y,separated by single spaces. + + +Output +t lines,each contains a single integer - the number of false pieces in the corresponding block. + + +Example +Sample input: +1 +100 7 +1 101 1 +2 1 2 +2 2 3 +2 3 3 +1 1 3 +2 3 1 +1 5 5 + +Sample output: +3 diff --git a/Unknown/Strange_Food_Chain/solution.cpp b/Unknown/Strange_Food_Chain/solution.cpp new file mode 100644 index 0000000..ba8dc5b --- /dev/null +++ b/Unknown/Strange_Food_Chain/solution.cpp @@ -0,0 +1,51 @@ +#include +#include + +using namespace std; + +const int N = 5e4 + 10; + +int n, k; +int par[N], lab[N]; + +int anc(int u) { + if (u == par[u]) return u; + int tmp = par[u]; + par[u] = anc(par[u]); + lab[u] = lab[tmp] + lab[u]; + return par[u]; +} + +int main() { + // freopen("input.in", "r", stdin); +// freopen("output.out", "w", stdout); + + int test; scanf("%d", &test); + while (test--) { + scanf("%d%d", &n, &k); + for (int i = 1; i <= n; ++i) { + par[i] = i; + lab[i] = 0; + } + int answer = 0; + while (k--) { + int t, x, y; scanf("%d%d%d", &t, &x, &y); + if (x > n || y > n) { answer++; continue; } + int px = anc(x), py = anc(y); + t--; + if (px == py) { + int tmp = (lab[x] - lab[y]) % 3; if (tmp < 0) tmp += 3; + if (tmp != t) answer++; + } else { + par[px] = py; + int i = (lab[x] - lab[y] - t) % 3; + lab[px] = i < 0 ? -i : -i + 3; + } + } + printf("%d\n", answer); + } + + return 0; +} + + diff --git a/WATCHFB/Main.class b/Unknown/WATCHFB/Main.class similarity index 100% rename from WATCHFB/Main.class rename to Unknown/WATCHFB/Main.class diff --git a/WATCHFB/Main.ctxt b/Unknown/WATCHFB/Main.ctxt similarity index 100% rename from WATCHFB/Main.ctxt rename to Unknown/WATCHFB/Main.ctxt diff --git a/WATCHFB/Main.java b/Unknown/WATCHFB/Main.java similarity index 100% rename from WATCHFB/Main.java rename to Unknown/WATCHFB/Main.java diff --git a/WATCHFB/WATCHFB.txt b/Unknown/WATCHFB/WATCHFB.txt similarity index 100% rename from WATCHFB/WATCHFB.txt rename to Unknown/WATCHFB/WATCHFB.txt diff --git a/chusky_adventurer/problem_statement.txt b/Unknown/chusky_adventurer/problem_statement.txt similarity index 100% rename from chusky_adventurer/problem_statement.txt rename to Unknown/chusky_adventurer/problem_statement.txt diff --git a/chusky_adventurer/solution.cpp b/Unknown/chusky_adventurer/solution.cpp similarity index 100% rename from chusky_adventurer/solution.cpp rename to Unknown/chusky_adventurer/solution.cpp diff --git a/chusky_hunger/problem_statement.txt b/Unknown/chusky_hunger/problem_statement.txt similarity index 100% rename from chusky_hunger/problem_statement.txt rename to Unknown/chusky_hunger/problem_statement.txt diff --git a/chusky_hunger/solution.cpp b/Unknown/chusky_hunger/solution.cpp similarity index 100% rename from chusky_hunger/solution.cpp rename to Unknown/chusky_hunger/solution.cpp diff --git a/chusky_nightgame/problem_statement.txt b/Unknown/chusky_nightgame/problem_statement.txt similarity index 100% rename from chusky_nightgame/problem_statement.txt rename to Unknown/chusky_nightgame/problem_statement.txt diff --git a/chusky_nightgame/solution.cpp b/Unknown/chusky_nightgame/solution.cpp similarity index 100% rename from chusky_nightgame/solution.cpp rename to Unknown/chusky_nightgame/solution.cpp diff --git a/coin-piles/problem_statement.txt b/Unknown/coin-piles/problem_statement.txt similarity index 100% rename from coin-piles/problem_statement.txt rename to Unknown/coin-piles/problem_statement.txt diff --git a/coin-piles/solution.cpp b/Unknown/coin-piles/solution.cpp similarity index 100% rename from coin-piles/solution.cpp rename to Unknown/coin-piles/solution.cpp