diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 48fbbf67..00000000 --- a/.gitignore +++ /dev/null @@ -1,54 +0,0 @@ -# Prerequisites -*.d - -# Object files -*.o -*.ko -*.obj -*.elf - -# Linker output -*.ilk -*.map -*.exp - -# Precompiled Headers -*.gch -*.pch - -# Libraries -*.lib -*.a -*.la -*.lo - -# Shared objects (inc. Windows DLLs) -*.dll -*.so -*.so.* -*.dylib - -# Executables -*.exe -*.out -*.app -*.i*86 -*.x86_64 -*.hex - -# Debug files -*.dSYM/ -*.su -*.idb -*.pdb - -# Kernel Module Compile Results -*.mod* -*.cmd -.tmp_versions/ -modules.order -Module.symvers -Mkfile.old -dkms.conf - -.idea diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 00000000..39aaa1c0 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,5 @@ +{ + "files.associations": { + "NewtonRaphson.C": "cpp" + } +} \ No newline at end of file diff --git a/04. Arrays${file_base_name} b/04. Arrays${file_base_name} deleted file mode 100644 index ac927ced..00000000 Binary files a/04. Arrays${file_base_name} and /dev/null differ diff --git a/06. Sorting/cocktail_sort.py b/06. Sorting/cocktail_sort.py index 752ea1bf..78f85217 100644 --- a/06. Sorting/cocktail_sort.py +++ b/06. Sorting/cocktail_sort.py @@ -1,53 +1,52 @@ -# Python program for implementation of Cocktail Sort - - -def cocktailSort(a): - n = len(a) +# GitHub username: grvkr777 (Gaurav Kar) +# Python program for implementation of Cocktail Sort + +def cocktailSort(a): + n = len(a) swapped = True start = 0 end = n-1 - while (swapped == True): - - # reset the swapped flag on entering the loop, - # because it might be true from a previous - # iteration. + while (swapped == True): + + # reset the swapped flag on entering the loop, + # because it might be true from a previous + # iteration. swapped = False - - # loop from left to right same as the bubble - # sort - for i in range(start, end): - if (a[i] > a[i + 1]): - a[i], a[i + 1] = a[i + 1], a[i] + + # loop from left to right same as the bubble + # sort + for i in range (start, end): + if (a[i] > a[i + 1]) : + a[i], a[i + 1]= a[i + 1], a[i] swapped = True - - # if nothing moved, then array is sorted. - if (swapped == False): + + # if nothing moved, then array is sorted. + if (swapped == False): break - - # otherwise, reset the swapped flag so that it - # can be used in the next stage + + # otherwise, reset the swapped flag so that it + # can be used in the next stage swapped = False - - # move the end point back by one, because - # item at the end is in its rightful spot + + # move the end point back by one, because + # item at the end is in its rightful spot end = end-1 - - # from right to left, doing the same - # comparison as in the previous stage - for i in range(end-1, start-1, -1): - if (a[i] > a[i + 1]): - a[i], a[i + 1] = a[i + 1], a[i] + + # from right to left, doing the same + # comparison as in the previous stage + for i in range(end-1, start-1, -1): + if (a[i] > a[i + 1]): + a[i], a[i + 1] = a[i + 1], a[i] swapped = True - - # increase the starting point, because - # the last stage would have moved the next - # smallest number to its rightful spot. + + # increase the starting point, because + # the last stage would have moved the next + # smallest number to its rightful spot. start = start + 1 - - -# Driver code -a = [5, 1, 4, 2, 8, 0, 2] -cocktailSort(a) -print("Sorted array is:") -for i in range(len(a)): - print("% d" % a[i]) + +# Driver code to test above +a = [5, 1, 4, 2, 8, 0, 2] +cocktailSort(a) +print("Sorted array is:") +for i in range(len(a)): + print ("% d" % a[i]), \ No newline at end of file diff --git a/06. Sorting/heapsort.cpp b/06. Sorting/heapsort.cpp index a30bff55..21da10c4 100644 --- a/06. Sorting/heapsort.cpp +++ b/06. Sorting/heapsort.cpp @@ -1,65 +1,52 @@ -// C++ program for implementation of Heap Sort -#include -using namespace std; - -// To heapify a subtree rooted with node i which is -// an index in arr[]. n is size of heap -void heapify(int arr[], int n, int i) -{ - int largest = i; // Initialize largest as root - int l = 2 * i + 1; // left = 2*i + 1 - int r = 2 * i + 2; // right = 2*i + 2 - - // If left child is larger than root - if (l < n && arr[l] > arr[largest]) - largest = l; - - // If right child is larger than largest so far - if (r < n && arr[r] > arr[largest]) - largest = r; - - // If largest is not root - if (largest != i) { - swap(arr[i], arr[largest]); - - // Recursively heapify the affected sub-tree - heapify(arr, n, largest); - } +#include +using namespace std; + +void heapify(int arr[], int n, int i) +{ + int largest = i; + int l = 2*i + 1; + int r = 2*i + 2; + if (l < n && arr[l] > arr[largest]) + largest = l; + + if (r < n && arr[r] > arr[largest]) + largest = r; + + if (largest != i) + { + swap(arr[i], arr[largest]); + heapify(arr, n, largest); + } +} + +void buildheap(int arr[],int n){ + for (int i = n / 2 - 1; i >= 0; i--) + heapify(arr, n, i); } -// main function to do heap sort -void heapSort(int arr[], int n) -{ - // Build heap (rearrange array) - for (int i = n / 2 - 1; i >= 0; i--) - heapify(arr, n, i); +void heapSort(int arr[], int n) +{ + buildheap(arr,n); - // One by one extract an element from heap - for (int i = n - 1; i >= 0; i--) { - // Move current root to end + for (int i=n-1; i>0; i--) + { swap(arr[0], arr[i]); + heapify(arr, i, 0); + } +} - // call max heapify on the reduced heap - heapify(arr, i, 0); - } -} - -/* A utility function to print array of size n */ -void printArray(int arr[], int n) -{ - for (int i = 0; i < n; ++i) - cout << arr[i] << " "; - cout << "\n"; -} - -// Driver program -int main() +int main(void) { - int arr[] = { 12, 11, 13, 5, 6, 7 }; - int n = sizeof(arr) / sizeof(arr[0]); - - heapSort(arr, n); - - cout << "Sorted array is \n"; - printArray(arr, n); -} + int a[10]; + cout << "Enter 10 elements of array: " << endl; + for (int i=0; i<10; i++) + cin >> a[i]; + cout << "Original Array is: "; + for (int i=0; i<10; i++) + cout << a[i] << " "; + int n=sizeof(a)/sizeof(a[0]); + cout <<"\nArray after sorting is: "; + heapSort(a,n); + for(int x: a) + cout< -using namespace std; - -// Function to reverse every sub-array formed by -// consecutive k elements -void reverse(int arr[], int n, int k) -{ - for (int i = 0; i < n; i += k) - { - int left = i; - - // to handle case when k is not multiple of n - int right = min(i + k - 1, n - 1); - - // reverse the sub-array [left, right] - while (left < right) - swap(arr[left++], arr[right--]); - - } -} - -// Driver code -int main() -{ - int arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; - int k = 3; - - int n = sizeof(arr) / sizeof(arr[0]); - - reverse(arr, n, k); - - for (int i = 0; i < n; i++) - cout << arr[i] << " "; - - return 0; -} +// C++ program to reverse every sub-array formed by +// consecutive k elements +#include +using namespace std; + +// Function to reverse every sub-array formed by +// consecutive k elements +void reverse(int arr[], int n, int k) +{ + for (int i = 0; i < n; i += k) + { + int left = i; + + // to handle case when k is not multiple of n + int right = min(i + k - 1, n - 1); + + // reverse the sub-array [left, right] + while (left < right) + swap(arr[left++], arr[right--]); + + } +} + +// Driver code +int main() +{ + int arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; + int k = 3; + + int n = sizeof(arr) / sizeof(arr[0]); + + reverse(arr, n, k); + + for (int i = 0; i < n; i++) + cout << arr[i] << " "; + + return 0; +} diff --git a/1. Two sums.cpp b/30. CPP Programs/1. Two sums.cpp similarity index 96% rename from 1. Two sums.cpp rename to 30. CPP Programs/1. Two sums.cpp index a9ebf041..2a26a0fc 100644 --- a/1. Two sums.cpp +++ b/30. CPP Programs/1. Two sums.cpp @@ -1,21 +1,21 @@ -class Solution -{ -public: - vector twoSum(vector &nums, int target) - { - vector ans = {}; - unordered_map hashMap; - for (int i = 0; i < nums.size(); i++) - { - if (hashMap.find(target - nums[i]) != hashMap.end()) - { - ans.push_back(hashMap[target - nums[i]]); - ans.push_back(i); - return ans; - } - hashMap[nums[i]] = i; - } - return ans; - } -}; -// https://leetcode.com/problems/two-sum/discuss/?currentPage=1&orderBy=hot&query= +class Solution +{ +public: + vector twoSum(vector &nums, int target) + { + vector ans = {}; + unordered_map hashMap; + for (int i = 0; i < nums.size(); i++) + { + if (hashMap.find(target - nums[i]) != hashMap.end()) + { + ans.push_back(hashMap[target - nums[i]]); + ans.push_back(i); + return ans; + } + hashMap[nums[i]] = i; + } + return ans; + } +}; +// https://leetcode.com/problems/two-sum/discuss/?currentPage=1&orderBy=hot&query= diff --git a/10. Container With Most Water.cpp b/30. CPP Programs/10. Container With Most Water.cpp similarity index 95% rename from 10. Container With Most Water.cpp rename to 30. CPP Programs/10. Container With Most Water.cpp index 5f9085b4..164a5344 100644 --- a/10. Container With Most Water.cpp +++ b/30. CPP Programs/10. Container With Most Water.cpp @@ -1,28 +1,28 @@ -#include -using namespace std; - -class Solution -{ -public: - int maxArea(int height[], int j) - { - int i=0; - int maxArea=0; - while(i +using namespace std; + +class Solution +{ +public: + int maxArea(int height[], int j) + { + int i=0; + int maxArea=0; + while(i maxSlidingWindow(vector& nums, int k) { - deque> D; //declaring a deque of pairs for storing max elements and their indices - vector ret; // declaring a vector to store the max elements and return them in the end - for(int i=0; i=k-1) //checking have we clear the first k elements - ret.push_back(D.front().first); - } - return ret; - } -}; +class Solution { +public: + vector maxSlidingWindow(vector& nums, int k) { + deque> D; //declaring a deque of pairs for storing max elements and their indices + vector ret; // declaring a vector to store the max elements and return them in the end + for(int i=0; i=k-1) //checking have we clear the first k elements + ret.push_back(D.front().first); + } + return ret; + } +}; diff --git a/12. Sort according to height.cpp b/30. CPP Programs/12. Sort according to height.cpp similarity index 95% rename from 12. Sort according to height.cpp rename to 30. CPP Programs/12. Sort according to height.cpp index dbccc336..ffbdb6ba 100644 --- a/12. Sort according to height.cpp +++ b/30. CPP Programs/12. Sort according to height.cpp @@ -1,34 +1,34 @@ -#include -using namespace std; -int main() -{ - int arr[] = {-1, 150, 190, 170, -1, -1, 160, 180}; - int n = sizeof(arr)/sizeof(arr[0]); - vector brr; - for(int i = 0; i < n; i++) - { - if(arr[i] != -1) - { - brr.push_back(arr[i]); - - } - - } - int m = brr.size(); - sort(brr.begin(), brr.end()); - int crr[n]; - int j = 0; - for(int i = 0; i < n; i ++) - { - if(arr[i] == -1) crr[i] = -1; - else - { - crr[i] = brr[j]; - j++; - } - } - for(int i = 0; i < n; i++) - { - cout << crr[i] << " "; - } -} +#include +using namespace std; +int main() +{ + int arr[] = {-1, 150, 190, 170, -1, -1, 160, 180}; + int n = sizeof(arr)/sizeof(arr[0]); + vector brr; + for(int i = 0; i < n; i++) + { + if(arr[i] != -1) + { + brr.push_back(arr[i]); + + } + + } + int m = brr.size(); + sort(brr.begin(), brr.end()); + int crr[n]; + int j = 0; + for(int i = 0; i < n; i ++) + { + if(arr[i] == -1) crr[i] = -1; + else + { + crr[i] = brr[j]; + j++; + } + } + for(int i = 0; i < n; i++) + { + cout << crr[i] << " "; + } +} diff --git a/13. Remove Duplicates from Sorted Array.cpp b/30. CPP Programs/13. Remove Duplicates from Sorted Array.cpp similarity index 95% rename from 13. Remove Duplicates from Sorted Array.cpp rename to 30. CPP Programs/13. Remove Duplicates from Sorted Array.cpp index e30cbdde..866c8976 100644 --- a/13. Remove Duplicates from Sorted Array.cpp +++ b/30. CPP Programs/13. Remove Duplicates from Sorted Array.cpp @@ -1,17 +1,17 @@ -#define INF 1e3 -class Solution { -public: - int removeDuplicates(vector& nums) { - for(int i=1;i& nums) { + for(int i=1;i& prices) { - int minPrice = INT_MAX; - int maxProf = 0; - for(int i = 0; i < prices.size(); i++) - { - minPrice = min(minPrice, prices[i]); - maxProf = max(maxProf, prices[i] - minPrice); - } - return maxProf; - } -}; - -// https://leetcode.com/problems/best-time-to-buy-and-sell-stock/submissions/ +class Solution { +public: + int maxProfit(vector& prices) { + int minPrice = INT_MAX; + int maxProf = 0; + for(int i = 0; i < prices.size(); i++) + { + minPrice = min(minPrice, prices[i]); + maxProf = max(maxProf, prices[i] - minPrice); + } + return maxProf; + } +}; + +// https://leetcode.com/problems/best-time-to-buy-and-sell-stock/submissions/ diff --git a/3. Contains Duplicate.cpp b/30. CPP Programs/3. Contains Duplicate.cpp similarity index 95% rename from 3. Contains Duplicate.cpp rename to 30. CPP Programs/3. Contains Duplicate.cpp index 922ae6fc..d53f3016 100644 --- a/3. Contains Duplicate.cpp +++ b/30. CPP Programs/3. Contains Duplicate.cpp @@ -1,20 +1,20 @@ -class Solution { -public: - bool containsDuplicate(vector& nums) { - - sort(nums.begin(), nums.end()); - for(int i = 0; i < nums.size() - 1; i++) - { - if(nums[i] == nums[i+1]) - { - return true; - } - else - { - continue; - } - }return false; - } -}; - -//https://leetcode.com/problems/contains-duplicate +class Solution { +public: + bool containsDuplicate(vector& nums) { + + sort(nums.begin(), nums.end()); + for(int i = 0; i < nums.size() - 1; i++) + { + if(nums[i] == nums[i+1]) + { + return true; + } + else + { + continue; + } + }return false; + } +}; + +//https://leetcode.com/problems/contains-duplicate diff --git a/4. Product of Array Except Self.cpp b/30. CPP Programs/4. Product of Array Except Self.cpp similarity index 96% rename from 4. Product of Array Except Self.cpp rename to 30. CPP Programs/4. Product of Array Except Self.cpp index 70924efc..4819660f 100644 --- a/4. Product of Array Except Self.cpp +++ b/30. CPP Programs/4. Product of Array Except Self.cpp @@ -1,28 +1,28 @@ -class Solution { -public: - vector productExceptSelf(vector&nums) { - int n = nums.size(); - vector output; - if(n < 1) - return output; - int product = 1; - //LEFT section - for(int i = 0; i < n; i++) - { - product *= nums[i]; - output.push_back(product); - } - - //Traverse from right and update the input array - product = 1; - for(int i = n-1; i > 0; i--) - { - output[i] = output[i-1]*product; - product *= nums[i]; - } - output[0] = product; - return output; - } -}; - -//https://leetcode.com/problems/product-of-array-except-self/ +class Solution { +public: + vector productExceptSelf(vector&nums) { + int n = nums.size(); + vector output; + if(n < 1) + return output; + int product = 1; + //LEFT section + for(int i = 0; i < n; i++) + { + product *= nums[i]; + output.push_back(product); + } + + //Traverse from right and update the input array + product = 1; + for(int i = n-1; i > 0; i--) + { + output[i] = output[i-1]*product; + product *= nums[i]; + } + output[0] = product; + return output; + } +}; + +//https://leetcode.com/problems/product-of-array-except-self/ diff --git a/5. Maximum Sum Subarray.cpp b/30. CPP Programs/5. Maximum Sum Subarray.cpp similarity index 95% rename from 5. Maximum Sum Subarray.cpp rename to 30. CPP Programs/5. Maximum Sum Subarray.cpp index c9a0a0d0..c8d1fa10 100644 --- a/5. Maximum Sum Subarray.cpp +++ b/30. CPP Programs/5. Maximum Sum Subarray.cpp @@ -1,16 +1,16 @@ -class Solution { -public: - int maxSubArray(vector& nums) { - int sum = 0; - int maxSum = nums[0]; - for(auto i: nums) - { - sum += i; - maxSum = max(sum,maxSum); - if(sum < 0) sum = 0; - } - return maxSum; - } -}; - -//https://leetcode.com/problems/maximum-subarray/ +class Solution { +public: + int maxSubArray(vector& nums) { + int sum = 0; + int maxSum = nums[0]; + for(auto i: nums) + { + sum += i; + maxSum = max(sum,maxSum); + if(sum < 0) sum = 0; + } + return maxSum; + } +}; + +//https://leetcode.com/problems/maximum-subarray/ diff --git a/6. Maximum Product Subarray.cpp b/30. CPP Programs/6. Maximum Product Subarray.cpp similarity index 96% rename from 6. Maximum Product Subarray.cpp rename to 30. CPP Programs/6. Maximum Product Subarray.cpp index 6a4addb1..5b2596e1 100644 --- a/6. Maximum Product Subarray.cpp +++ b/30. CPP Programs/6. Maximum Product Subarray.cpp @@ -1,17 +1,17 @@ -class Solution { -public: - int maxProduct(vector& nums) { - int max1 = nums[0]; - int prev_max = nums[0], prev_min = nums[0]; - for(int i = 1; i < nums.size(); i++) - { - int prev_max1 = prev_max; - prev_max = max({nums[i], nums[i]*prev_max, nums[i]*prev_min}); - prev_min = min({nums[i], nums[i]*prev_max1, nums[i]*prev_min}); - max1 = max(max1,prev_max); - } - return max1; - } -}; - -//https://leetcode.com/problems/maximum-product-subarray/ +class Solution { +public: + int maxProduct(vector& nums) { + int max1 = nums[0]; + int prev_max = nums[0], prev_min = nums[0]; + for(int i = 1; i < nums.size(); i++) + { + int prev_max1 = prev_max; + prev_max = max({nums[i], nums[i]*prev_max, nums[i]*prev_min}); + prev_min = min({nums[i], nums[i]*prev_max1, nums[i]*prev_min}); + max1 = max(max1,prev_max); + } + return max1; + } +}; + +//https://leetcode.com/problems/maximum-product-subarray/ diff --git a/7. Find Minimum in Rotated Sorted Array.cpp b/30. CPP Programs/7. Find Minimum in Rotated Sorted Array.cpp similarity index 96% rename from 7. Find Minimum in Rotated Sorted Array.cpp rename to 30. CPP Programs/7. Find Minimum in Rotated Sorted Array.cpp index 6753295a..b97cfce0 100644 --- a/7. Find Minimum in Rotated Sorted Array.cpp +++ b/30. CPP Programs/7. Find Minimum in Rotated Sorted Array.cpp @@ -1,22 +1,22 @@ -class Solution -{ -public: - int findMin(vector& nums) - { - int size = nums.size()-1; - // Check if array is fully sorted - if(nums[size]>nums[0]) return nums[0]; - int left = 0; - int right = size; - while(left < right) - { - int midpoint = left + (right- left)/2; - if(midpoint > 0 && nums[midpoint] < nums[midpoint - 1]) return nums[midpoint]; - else if(nums[left] <= nums[midpoint] && nums[midpoint] > nums[right]) left = midpoint + 1; - else right = midpoint - 1; - } - return nums[left]; - } -}; - -//https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/ +class Solution +{ +public: + int findMin(vector& nums) + { + int size = nums.size()-1; + // Check if array is fully sorted + if(nums[size]>nums[0]) return nums[0]; + int left = 0; + int right = size; + while(left < right) + { + int midpoint = left + (right- left)/2; + if(midpoint > 0 && nums[midpoint] < nums[midpoint - 1]) return nums[midpoint]; + else if(nums[left] <= nums[midpoint] && nums[midpoint] > nums[right]) left = midpoint + 1; + else right = midpoint - 1; + } + return nums[left]; + } +}; + +//https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/ diff --git a/8. Search in Rotated Sorted Array.cpp b/30. CPP Programs/8. Search in Rotated Sorted Array.cpp similarity index 96% rename from 8. Search in Rotated Sorted Array.cpp rename to 30. CPP Programs/8. Search in Rotated Sorted Array.cpp index eeb05138..6887c029 100644 --- a/8. Search in Rotated Sorted Array.cpp +++ b/30. CPP Programs/8. Search in Rotated Sorted Array.cpp @@ -1,36 +1,36 @@ -class Solution { -public: - int search(vector& nums, int target) { - if(nums.size() == 0) return -1; - - int left = 0; - int right = nums.size() - 1; - - while(left < right) - { - int mid = left + (right-left)/2; - if(nums[mid] > nums[right]) left = mid + 1; - else right = mid; - } - - int start = left; // lowest index or the pivot point - left = 0; - right = nums.size() - 1; - - if(target >= nums[start] && target <= nums[right]) - left = start; - else right= start; - - while (left <= right) - { - int midpoint = left + (right-left)/2; - if(nums[midpoint] == target)return midpoint; - else if (nums[midpoint] < target) left = midpoint + 1; - else right = midpoint - 1; - - } - return -1; - } -}; - -//https://leetcode.com/problems/search-in-rotated-sorted-array/ +class Solution { +public: + int search(vector& nums, int target) { + if(nums.size() == 0) return -1; + + int left = 0; + int right = nums.size() - 1; + + while(left < right) + { + int mid = left + (right-left)/2; + if(nums[mid] > nums[right]) left = mid + 1; + else right = mid; + } + + int start = left; // lowest index or the pivot point + left = 0; + right = nums.size() - 1; + + if(target >= nums[start] && target <= nums[right]) + left = start; + else right= start; + + while (left <= right) + { + int midpoint = left + (right-left)/2; + if(nums[midpoint] == target)return midpoint; + else if (nums[midpoint] < target) left = midpoint + 1; + else right = midpoint - 1; + + } + return -1; + } +}; + +//https://leetcode.com/problems/search-in-rotated-sorted-array/ diff --git a/9. 3Sum.cpp b/30. CPP Programs/9. 3Sum.cpp similarity index 97% rename from 9. 3Sum.cpp rename to 30. CPP Programs/9. 3Sum.cpp index 1ee8293e..317580b7 100644 --- a/9. 3Sum.cpp +++ b/30. CPP Programs/9. 3Sum.cpp @@ -1,32 +1,32 @@ -class Solution { -public: - vector> threeSum(vector& nums) { - int n = nums.size(); - if(n < 3) return {}; //cannot look for triplets so send empty vector - vector > result; - sort(nums.begin(),nums.end()); // sort in order to skip duplicate numbers - for(int i = 0; i < n-2; i++) // n- 2 because we have to look for two more elements; avoiding overflow - { - if(i == 0 || nums[i] != nums[i-1]) //if it's the 1st element or if it doesn't have a duplicate - { - int j = i + 1, k = n-1;// two variables one ahead and another from the last one - while(j < k) //these two points do not meet - { - int sum = nums[i] + nums[j] + nums[k]; //add them - if(sum ==0) //check if they're being added to zero - { - result.push_back({nums[i], nums[j], nums[k]}); //then push them in as a vector - while(j < k && nums[j] == nums[j + 1]) j++; // skip for j duplicate - while( j < k && nums[k] == nums[k -1]) k--; //skip for k duplicate - j++;k--;// move ahead now - } - else if(sum > 0) k--; // remove the largest element as it is sorted - else j++; // if sum < 0 remove fhe smallest element as it is sorted - } - - } - } - return result; - - } -}; +class Solution { +public: + vector> threeSum(vector& nums) { + int n = nums.size(); + if(n < 3) return {}; //cannot look for triplets so send empty vector + vector > result; + sort(nums.begin(),nums.end()); // sort in order to skip duplicate numbers + for(int i = 0; i < n-2; i++) // n- 2 because we have to look for two more elements; avoiding overflow + { + if(i == 0 || nums[i] != nums[i-1]) //if it's the 1st element or if it doesn't have a duplicate + { + int j = i + 1, k = n-1;// two variables one ahead and another from the last one + while(j < k) //these two points do not meet + { + int sum = nums[i] + nums[j] + nums[k]; //add them + if(sum ==0) //check if they're being added to zero + { + result.push_back({nums[i], nums[j], nums[k]}); //then push them in as a vector + while(j < k && nums[j] == nums[j + 1]) j++; // skip for j duplicate + while( j < k && nums[k] == nums[k -1]) k--; //skip for k duplicate + j++;k--;// move ahead now + } + else if(sum > 0) k--; // remove the largest element as it is sorted + else j++; // if sum < 0 remove fhe smallest element as it is sorted + } + + } + } + return result; + + } +}; diff --git a/AdjacencyMatrix.cpp b/30. CPP Programs/AdjacencyMatrix.cpp similarity index 100% rename from AdjacencyMatrix.cpp rename to 30. CPP Programs/AdjacencyMatrix.cpp diff --git a/Airline Restrictions b/30. CPP Programs/Airline_Restrictions.cpp similarity index 100% rename from Airline Restrictions rename to 30. CPP Programs/Airline_Restrictions.cpp diff --git a/Best_Time_To_Sell_Stock_With_CoolDown.cpp b/30. CPP Programs/Best_Time_To_Sell_Stock_With_CoolDown.cpp similarity index 100% rename from Best_Time_To_Sell_Stock_With_CoolDown.cpp rename to 30. CPP Programs/Best_Time_To_Sell_Stock_With_CoolDown.cpp diff --git a/BinaryTreeZIgzagLevelOrderTraversal.cpp b/30. CPP Programs/BinaryTreeZIgzagLevelOrderTraversal.cpp similarity index 100% rename from BinaryTreeZIgzagLevelOrderTraversal.cpp rename to 30. CPP Programs/BinaryTreeZIgzagLevelOrderTraversal.cpp diff --git a/Binary_tree_is_symmetirc_or_not.cpp b/30. CPP Programs/Binary_tree_is_symmetirc_or_not.cpp similarity index 100% rename from Binary_tree_is_symmetirc_or_not.cpp rename to 30. CPP Programs/Binary_tree_is_symmetirc_or_not.cpp diff --git a/Decimal To Octal Conversion.cpp b/30. CPP Programs/Decimal To Octal Conversion.cpp similarity index 100% rename from Decimal To Octal Conversion.cpp rename to 30. CPP Programs/Decimal To Octal Conversion.cpp diff --git a/Distance_Queries.cpp b/30. CPP Programs/Distance_Queries.cpp similarity index 95% rename from Distance_Queries.cpp rename to 30. CPP Programs/Distance_Queries.cpp index 52e97f64..85ff8e69 100644 --- a/Distance_Queries.cpp +++ b/30. CPP Programs/Distance_Queries.cpp @@ -1,94 +1,94 @@ -// Problem Link: https://cses.fi/problemset/task/1135/ -#include -using namespace std; -typedef long long ll; -typedef unsigned long long ull; -#define mod 10000000000000007 -#define FOR(i,x) for(ll i = 0; i < x; i++) -#define For(i,x,y) for(ll i = x; i <= y; i++) -#define rep(i,x,y) for(int i = x; i >= y; i--) -#define vint vector -#define vl vector -#define vll vector -#define um unordered_map -#define pb push_back -#define pll pair -#define mone cout<<-1<<"\n" -#define yess cout<<"YES\n" -#define noo cout<<"NO\n" -#define nl cout<<"\n" -#define all(x) x.begin(),x.end() -#define oset tree -#define INF 1000000000000000000 -const ll mx = 2*1e5; -const ll logofn = log2(mx); -void dfs(vector v[], vector> &par, ll n, ll p, vector &lvl) -{ - lvl[n] = lvl[p]+1; - par[n][0] = p; - For(i,1,logofn) - par[n][i] = par[par[n][i-1]][i-1]; - FOR(i,v[n].size()) - { - ll y = v[n][i]; - if(y != p) - dfs(v,par,y,n,lvl); - } -} -ll find_lca(vector v[], vector> &par, ll a, ll b, vector &lvl) -{ - if(lvl[a] < lvl[b]) - swap(a,b); - ll d = lvl[a]-lvl[b]; - while(d > 0) - { - ll z = log2(d); - a = par[a][z]; - d -= (1<>n>>q; - vector v[n+1]; - FOR(i,n-1) - { - ll a,b; - cin>>a>>b; - v[a].pb(b); - v[b].pb(a); - } - vector> par(n+1,vector(logofn+1,0)); - vector lvl(n+1,0); - dfs(v,par,1,0,lvl); - while(q--) - { - ll a,b; - cin>>a>>b; - ll z = find_lca(v,par,a,b,lvl); - cout< +using namespace std; +typedef long long ll; +typedef unsigned long long ull; +#define mod 10000000000000007 +#define FOR(i,x) for(ll i = 0; i < x; i++) +#define For(i,x,y) for(ll i = x; i <= y; i++) +#define rep(i,x,y) for(int i = x; i >= y; i--) +#define vint vector +#define vl vector +#define vll vector +#define um unordered_map +#define pb push_back +#define pll pair +#define mone cout<<-1<<"\n" +#define yess cout<<"YES\n" +#define noo cout<<"NO\n" +#define nl cout<<"\n" +#define all(x) x.begin(),x.end() +#define oset tree +#define INF 1000000000000000000 +const ll mx = 2*1e5; +const ll logofn = log2(mx); +void dfs(vector v[], vector> &par, ll n, ll p, vector &lvl) +{ + lvl[n] = lvl[p]+1; + par[n][0] = p; + For(i,1,logofn) + par[n][i] = par[par[n][i-1]][i-1]; + FOR(i,v[n].size()) + { + ll y = v[n][i]; + if(y != p) + dfs(v,par,y,n,lvl); + } +} +ll find_lca(vector v[], vector> &par, ll a, ll b, vector &lvl) +{ + if(lvl[a] < lvl[b]) + swap(a,b); + ll d = lvl[a]-lvl[b]; + while(d > 0) + { + ll z = log2(d); + a = par[a][z]; + d -= (1<>n>>q; + vector v[n+1]; + FOR(i,n-1) + { + ll a,b; + cin>>a>>b; + v[a].pb(b); + v[b].pb(a); + } + vector> par(n+1,vector(logofn+1,0)); + vector lvl(n+1,0); + dfs(v,par,1,0,lvl); + while(q--) + { + ll a,b; + cin>>a>>b; + ll z = find_lca(v,par,a,b,lvl); + cout< 20*30*10 + 40*20*10 + 40*10*30 - -////////////////////// -Time Complexity:O(n^3) -Space Complexity: O(n^2) -*/ - -// C++ program using memoization -#include -using namespace std; -int dp[100][100]; - -// Function for matrix chain multiplication -int matrixChainMemoised(int *p, int i, int j) -{ - if (i == j) - { - return 0; - } - if (dp[i][j] != -1) - { - return dp[i][j]; - } - dp[i][j] = INT_MAX; - for (int k = i; k < j; k++) - { - dp[i][j] = min( - dp[i][j], matrixChainMemoised(p, i, k) + matrixChainMemoised(p, k + 1, j) + p[i - 1] * p[k] * p[j]); - } - return dp[i][j]; -} -int MatrixChainOrder(int *p, int n) -{ - int i = 1, j = n - 1; - return matrixChainMemoised(p, i, j); -} - -// Driver Code -int main() -{ - int arr[] = {40, 20, 30, 10, 30}; - int n = sizeof(arr) / sizeof(arr[0]); - memset(dp, -1, sizeof dp); - - cout << "Minimum number of multiplications is " - << MatrixChainOrder(arr, n); -} +/* +find the most efficient way to multiply these matrices together. +The efficient way is the one that involves the least number of multiplications. +The dimensions of the matrices are given in an array arr[] of size N (such that N = number of matrices + 1) +where the ith matrix has the dimensions (arr[i-1] x arr[i]). + + +/////////////////////////////// +Input: p[] = {40, 20, 30, 10, 30} +Output: 26000 +explanation :There are 4 matrices of dimensions 40x20, 20x30, 30x10 and 10x30. +Let the input 4 matrices be A, B, C and D. The minimum number of +multiplications are obtained by putting parenthesis in following way +(A(BC))D --> 20*30*10 + 40*20*10 + 40*10*30 + +////////////////////// +Time Complexity:O(n^3) +Space Complexity: O(n^2) +*/ + +// C++ program using memoization +#include +using namespace std; +int dp[100][100]; + +// Function for matrix chain multiplication +int matrixChainMemoised(int *p, int i, int j) +{ + if (i == j) + { + return 0; + } + if (dp[i][j] != -1) + { + return dp[i][j]; + } + dp[i][j] = INT_MAX; + for (int k = i; k < j; k++) + { + dp[i][j] = min( + dp[i][j], matrixChainMemoised(p, i, k) + matrixChainMemoised(p, k + 1, j) + p[i - 1] * p[k] * p[j]); + } + return dp[i][j]; +} +int MatrixChainOrder(int *p, int n) +{ + int i = 1, j = n - 1; + return matrixChainMemoised(p, i, j); +} + +// Driver Code +int main() +{ + int arr[] = {40, 20, 30, 10, 30}; + int n = sizeof(arr) / sizeof(arr[0]); + memset(dp, -1, sizeof dp); + + cout << "Minimum number of multiplications is " + << MatrixChainOrder(arr, n); +} diff --git a/MaxDepth_of_binary_tree.cpp b/30. CPP Programs/MaxDepth_of_binary_tree.cpp similarity index 100% rename from MaxDepth_of_binary_tree.cpp rename to 30. CPP Programs/MaxDepth_of_binary_tree.cpp diff --git a/Merge Sort.cpp b/30. CPP Programs/Merge Sort.cpp similarity index 100% rename from Merge Sort.cpp rename to 30. CPP Programs/Merge Sort.cpp diff --git a/30. CPP Programs/PalindromePalindrome.cpp b/30. CPP Programs/PalindromePalindrome.cpp new file mode 100644 index 00000000..748e5810 --- /dev/null +++ b/30. CPP Programs/PalindromePalindrome.cpp @@ -0,0 +1,30 @@ +#include +#include +using namespace std; +void main() +{ + int i, j, len, flag = 1; + char a[20]; + + cout << "Enter a string:"; + cin >> a; + + for (len = 0; a[len] != '\0'; ++len) + ; + + for (i = 0, j = len - 1; i < len / 2; ++i, --j) + { + if (a[j] != a[i]) + flag = 0; + } + + if (flag == 1) + { + cout << "\nString is Palindrome"; + } + else + { + cout << "\nString is not Palindrome"; + } + getch(); +} diff --git a/30. CPP Programs/Product_of_Array_Except_Self.cpp b/30. CPP Programs/Product_of_Array_Except_Self.cpp new file mode 100644 index 00000000..945b578f --- /dev/null +++ b/30. CPP Programs/Product_of_Array_Except_Self.cpp @@ -0,0 +1,55 @@ +/* +Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i]. +The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. +You must write an algorithm that runs in O(n) time and without using the division operation. +*/ + +/* +Input: nums = [1,2,3,4] +Output: [24,12,8,6] +*/ + +/* +Input: nums = [-1,1,0,-3,3] +Output: [0,0,9,0,0] +*/ + +#include +using namespace std; +int main() +{ + int n; + cout << "Enter the number of elements in the array: "; + cin >> n; + vector nums(n); + cout << "Enter the elements of the array: "; + for (int i = 0; i < n; i++) + { + cin >> nums[i]; + // mult = mult * a[i]; + } + // for(int i=0;i result(nums.size(), 1); + int i; + for (i = 0; i < nums.size(); i++) + { + result[i] = left; + left = left * nums[i]; + } + for (i = nums.size() - 1; i >= 0; i--) + { + result[i] = result[i] * right; + right = right * nums[i]; + } + // return result; + for (i = 0; i < result.size(); i++) + { + cout << result[i] << " "; + } +} diff --git a/30. CPP Programs/Product_of_Array_Except_Self.exe b/30. CPP Programs/Product_of_Array_Except_Self.exe new file mode 100644 index 00000000..bacc7395 Binary files /dev/null and b/30. CPP Programs/Product_of_Array_Except_Self.exe differ diff --git a/Square _root _of _a_number.cpp b/30. CPP Programs/Square _root _of _a_number.cpp similarity index 100% rename from Square _root _of _a_number.cpp rename to 30. CPP Programs/Square _root _of _a_number.cpp diff --git a/Subarray_with_sum_Zero.cpp b/30. CPP Programs/Subarray_with_sum_Zero.cpp similarity index 100% rename from Subarray_with_sum_Zero.cpp rename to 30. CPP Programs/Subarray_with_sum_Zero.cpp diff --git a/Two_Knights.cpp b/30. CPP Programs/Two_Knights.cpp similarity index 100% rename from Two_Knights.cpp rename to 30. CPP Programs/Two_Knights.cpp diff --git a/agnosticsearch.cpp b/30. CPP Programs/agnosticsearch.cpp similarity index 100% rename from agnosticsearch.cpp rename to 30. CPP Programs/agnosticsearch.cpp diff --git a/airline_restriction.cpp b/30. CPP Programs/airline_restriction.cpp similarity index 100% rename from airline_restriction.cpp rename to 30. CPP Programs/airline_restriction.cpp diff --git a/atcoder 220 FG operation solution.cpp b/30. CPP Programs/atcoder 220 FG operation solution.cpp similarity index 100% rename from atcoder 220 FG operation solution.cpp rename to 30. CPP Programs/atcoder 220 FG operation solution.cpp diff --git a/cc-shufflingparities.cpp b/30. CPP Programs/cc-shufflingparities.cpp similarity index 96% rename from cc-shufflingparities.cpp rename to 30. CPP Programs/cc-shufflingparities.cpp index 9250eac4..9455ce08 100644 --- a/cc-shufflingparities.cpp +++ b/30. CPP Programs/cc-shufflingparities.cpp @@ -1,33 +1,33 @@ - -/*PROBLEM STATEMENT LINK- https://www.codechef.com/SEPT21C/problems/SHUFFLIN */ - -#include -using namespace std; -int main() -{ int t; // test cases - cin>>t; - while(t--) - { - int n; //number of integers - cin>>n; - int a[n]; - - for(int i=0;i>a[i]; - } - int e=0,o=0; // e for even number , o for odd number - for (int i = 0; i < n; i++) - { - if(a[i]%2==0) - e++; - else - o++; - } - int ne=n/2; // number of even indices - int no=n-ne; // number of odd indices - cout< +using namespace std; +int main() +{ int t; // test cases + cin>>t; + while(t--) + { + int n; //number of integers + cin>>n; + int a[n]; + + for(int i=0;i>a[i]; + } + int e=0,o=0; // e for even number , o for odd number + for (int i = 0; i < n; i++) + { + if(a[i]%2==0) + e++; + else + o++; + } + int ne=n/2; // number of even indices + int no=n-ne; // number of odd indices + cout< -using namespace std; - -// Find the peak element in the array -int findPeak(int arr[], int n) -{ - // first or last element is peak element - if (n == 1) - return 0; - if (arr[0] >= arr[1]) - return 0; - if (arr[n - 1] >= arr[n - 2]) - return n - 1; - - // check for every other element - for (int i = 1; i < n - 1; i++) { - - // check if the neighbors are smaller - if (arr[i] >= arr[i - 1] && arr[i] >= arr[i + 1]) - return i; - } -} - -// Driver Code -int main() -{ - int arr[] = { 1, 3, 20, 4, 1, 0 }; - int n = sizeof(arr) / sizeof(arr[0]); - cout << "Index of a peak point is " - << findPeak(arr, n); - return 0; +// Find a peak element. An array element is a peak if it is NOT smaller than its neighbours. +#include +using namespace std; + +// Find the peak element in the array +int findPeak(int arr[], int n) +{ + // first or last element is peak element + if (n == 1) + return 0; + if (arr[0] >= arr[1]) + return 0; + if (arr[n - 1] >= arr[n - 2]) + return n - 1; + + // check for every other element + for (int i = 1; i < n - 1; i++) { + + // check if the neighbors are smaller + if (arr[i] >= arr[i - 1] && arr[i] >= arr[i + 1]) + return i; + } +} + +// Driver Code +int main() +{ + int arr[] = { 1, 3, 20, 4, 1, 0 }; + int n = sizeof(arr) / sizeof(arr[0]); + cout << "Index of a peak point is " + << findPeak(arr, n); + return 0; } \ No newline at end of file diff --git a/Bubble Sort in Java.java b/32. Java Programs/Bubble Sort in Java.java similarity index 100% rename from Bubble Sort in Java.java rename to 32. Java Programs/Bubble Sort in Java.java diff --git a/GetHashValue.java b/32. Java Programs/GetHashValue.java similarity index 100% rename from GetHashValue.java rename to 32. Java Programs/GetHashValue.java diff --git a/isPanagram.java b/32. Java Programs/isPanagram.java similarity index 100% rename from isPanagram.java rename to 32. Java Programs/isPanagram.java diff --git a/Square of n numbers.py b/33. Python Programs/Square of n numbers.py similarity index 100% rename from Square of n numbers.py rename to 33. Python Programs/Square of n numbers.py diff --git a/binconversion.py b/33. Python Programs/binconversion.py similarity index 100% rename from binconversion.py rename to 33. Python Programs/binconversion.py diff --git a/Height of a Binary Tree.c b/36. C Programs/Height of a Binary Tree.c similarity index 100% rename from Height of a Binary Tree.c rename to 36. C Programs/Height of a Binary Tree.c diff --git a/NewtonRaphson.C b/36. C Programs/NewtonRaphson.C similarity index 100% rename from NewtonRaphson.C rename to 36. C Programs/NewtonRaphson.C diff --git a/Rock_paper_scissor.c b/36. C Programs/Rock_paper_scissor.c similarity index 93% rename from Rock_paper_scissor.c rename to 36. C Programs/Rock_paper_scissor.c index b6000401..19481855 100644 --- a/Rock_paper_scissor.c +++ b/36. C Programs/Rock_paper_scissor.c @@ -1,79 +1,79 @@ - -#include -#include -#include -#include - - -int Game(char user_input, char AI_response) -{ - - if (user_input== AI_response) - return -1; - - - if (user_input== 's' && AI_response == 'p') - return 0; - - else if (user_input== 'p' && AI_response == 's') return 1; - - - if (user_input== 's' && AI_response == 'z') - return 1; - - - else if (user_input== 'z' && AI_response == 's') - return 0; - - - if (user_input== 'p' && AI_response == 'z') - return 0; - - else if (user_input== 'z' && AI_response == 'p') - return 1; -} - - -int main() -{ - - int n; - - char you, AI_response, result; - - - srand(time(NULL)); - - n = rand() % 100; - - if (n < 33) - - - AI_response = 's'; - - else if (n > 33 && n < 66) - - - AI_response = 'p'; - else - AI_response = 'z'; - - printf("\n\n\n\n\t\t\t\tEnter 's' for STONE, 'p' for PAPER and 'z' for SCISSOR\n\t\t\t\t\t\t\t"); - - scanf("%c", &you); - - result = Game(you, AI_response); - - if (result == -1) { - printf("\n\n\t\t\t\tGame Draw!\n"); - } - else if (result == 1) { - printf("\n\n\t\t\t\tWow! You have won the game!\n"); - } - else { - printf("\n\n\t\t\t\tOh! You have lost the game!\n"); - } - printf("\t\t\t\tYou choose : '%c' and Computer choose : '%c'\n", you, AI_response); - - return 0; -} + +#include +#include +#include +#include + + +int Game(char user_input, char AI_response) +{ + + if (user_input== AI_response) + return -1; + + + if (user_input== 's' && AI_response == 'p') + return 0; + + else if (user_input== 'p' && AI_response == 's') return 1; + + + if (user_input== 's' && AI_response == 'z') + return 1; + + + else if (user_input== 'z' && AI_response == 's') + return 0; + + + if (user_input== 'p' && AI_response == 'z') + return 0; + + else if (user_input== 'z' && AI_response == 'p') + return 1; +} + + +int main() +{ + + int n; + + char you, AI_response, result; + + + srand(time(NULL)); + + n = rand() % 100; + + if (n < 33) + + + AI_response = 's'; + + else if (n > 33 && n < 66) + + + AI_response = 'p'; + else + AI_response = 'z'; + + printf("\n\n\n\n\t\t\t\tEnter 's' for STONE, 'p' for PAPER and 'z' for SCISSOR\n\t\t\t\t\t\t\t"); + + scanf("%c", &you); + + result = Game(you, AI_response); + + if (result == -1) { + printf("\n\n\t\t\t\tGame Draw!\n"); + } + else if (result == 1) { + printf("\n\n\t\t\t\tWow! You have won the game!\n"); + } + else { + printf("\n\n\t\t\t\tOh! You have lost the game!\n"); + } + printf("\t\t\t\tYou choose : '%c' and Computer choose : '%c'\n", you, AI_response); + + return 0; +} diff --git a/binary search.c b/36. C Programs/binary search.c similarity index 100% rename from binary search.c rename to 36. C Programs/binary search.c diff --git a/36. C Programs/calendar.c b/36. C Programs/calendar.c new file mode 100644 index 00000000..01548202 --- /dev/null +++ b/36. C Programs/calendar.c @@ -0,0 +1,58 @@ +/* A program to take an input year from the user +* And display that year's :- Calender using user defined function in c. +*/ +#include + +/*User defined function*/ +void gotoxy(int x,int y) +{ + while(y--)printf("\n"); + while(x--)printf(" "); +} + +/*The month handle function*/ +void printmonth(int day,int start) +{ + gotoxy(5,0); + printf(" S M T W T F S"); + gotoxy(10,2); + for(int i=1;i -int main() -{ - int binary,decimal=0,weight=1,rem; - printf ("Enter any Binary number to convert it into decimal : "); - scanf ("%d",&binary); - while (binary!=0) - { - rem=binary%10; - decimal=decimal+rem*weight; - weight=weight*2; - binary=binary/10; - } - printf ("The Decimal representation of the given binary number is : %d",decimal); - return 0; -} +#include +int main() +{ + int binary,decimal=0,weight=1,rem; + printf ("Enter any Binary number to convert it into decimal : "); + scanf ("%d",&binary); + while (binary!=0) + { + rem=binary%10; + decimal=decimal+rem*weight; + weight=weight*2; + binary=binary/10; + } + printf ("The Decimal representation of the given binary number is : %d",decimal); + return 0; +} diff --git a/PalindromePalindrome.cpp b/PalindromePalindrome.cpp deleted file mode 100644 index 2055ac05..00000000 --- a/PalindromePalindrome.cpp +++ /dev/null @@ -1,29 +0,0 @@ -#include -#include - -void main() -{ -int i,j,len,flag=1; -char a[20]; - -cout<<"Enter a string:"; -cin>>a; - -for(len=0;a[len]!='\0';++len); - -for(i=0,j=len-1;i -using namespace std; -int main() -{ - - cout<<"Enter the number of elements in the array: "; - cin>>n; - vector nums(n); - cout<<"Enter the elements of the array: "; - for(int i=0;i>nums[i]; - // mult = mult * a[i]; - } - // for(int i=0;i result(nums.size(),1); - int i; - for(i=0;i=0;i--) - { - result[i]=result[i]*right; - right=right*nums[i]; - } - return result; -} diff --git a/codeforces_745_C_solution b/codeforces_745_C_solution deleted file mode 100644 index 6e721f75..00000000 --- a/codeforces_745_C_solution +++ /dev/null @@ -1,141 +0,0 @@ -//manish kumar patel -/* PLEASE MERGE THIS IN THE LABEL OF hacktoberfest-accepted as a part of my genuine work for hacktoberfest*/ -//thanks -//problem link -// https://codeforces.com/contest/1581/problem/C -#include -using namespace std; - - - -#define ll long long -#define ld long double -#define rep(i,a,b) for(ll i=a;i=b;i--) -#define err() cout<<"--------------------------"< -#define pll pair -#define V vector -#define S set -#define VV vector -#define Vpll vector - -#define endl "\n" -ll binaryexp(ll a,ll b,ll i) -{ - if(b==0) - return 1LL; - if(b==1) - return a; - ll k=binaryexp(a,b/2,i); - if(b&1) - { - return (((k*k)%i)*a)%i; - } - else - return (k*k)%i; -} -int main() - { - ios_base::sync_with_stdio(false); - cin.tie(NULL); cout.tie(NULL); - #ifndef ONLINE_JUDGE - clock_t tStart = clock(); - freopen("input.txt","r",stdin); - freopen("output.txt","w",stdout); - #endif - int t; - cin>>t; - // t=1; - - while(t--) - { - ll n,m; - cin>>n>>m; - VV a(n,V(m)); - rep(i,0,n) - { - string s; - cin>>s; - rep(j,0,m) - { - if(s[j]=='1') - { - a[i][j]=1; - } - else - { - a[i][j]=0; - } - } - } - - VV dp(n+1,V(m+1,0)); - rep(i,0,n) - { - rep(j,0,m) - { - dp[i+1][j+1]=dp[i][j+1]+dp[i+1][j]-dp[i][j]+a[i][j]; - } - } - - VV up(n+1,V(m+1,0)); - VV left(n+1,V(m+1,0)); - rep(i,0,n) - { - rep(j,0,m) - { - left[i+1][j+1]=left[i+1][j]+a[i][j]; - } - } - rep(i,0,n) - { - rep(j,0,m) - { - up[i+1][j+1]=up[i][j+1]+a[i][j]; - } - } - ll ans=INT_MAX; - // ll ind1,ind2; - rep(i,0,n) - { - for(ll j=i+4;jdp[j+1][k-3]-dp[i][k-3]+2*dp[i+1][k-3+1]-2*dp[j][k-3+1]-2*(k)+4+a[i][k-3]+a[j][k-3]) - { - mm=min(mm,dp[j+1][k-3]-dp[i][k-3]+2*dp[i+1][k-3+1]-2*dp[j][k-3+1]-2*(k)+4+a[i][k-3]+a[j][k-3]); - idx=k-3; - } - ans=min(ans,2*inner-outer+2*(j-i+k)+mm-2+a[i][k]+a[j][k]); - } - } - } - - cout< %.10fs\n", (double)(clock()-tStart) / CLOCKS_PER_SEC); - #endif -} diff --git a/cses tree solution-distinct colours b/cses tree solution-distinct colours deleted file mode 100644 index b561a4c4..00000000 --- a/cses tree solution-distinct colours +++ /dev/null @@ -1,138 +0,0 @@ -#include -using namespace std; -//problem link -//https://cses.fi/problemset/task/1139 -//please merge this as hacktoberfest-accepted label -//this problem uses very good use of pointer . -//hope u like this -//thanks - - -#define ll long long -#define ld long double -#define rep(i,a,b) for(ll i=a;i=b;i--) -#define err() cout<<"--------------------------"< -#define pll pair -#define V vector -#define S set -#define VV vector -#define Vpll vector - -#define endl "\n" - -ll binaryexp(ll a,ll b,ll i) -{ - if(b==0) - return 1LL; - if(b==1) - return a; - ll k=binaryexp(a,b/2,i); - if(b&1) - { - return (((k*k)%i)*a)%i; - } - else - return (k*k)%i; -} - -V col(200005); -set *st[200005]; -V ans(200005); -void dfs(VV &a,int i,int p) -{ - int mxs=-1,mxi=-1; - int n=a.size(); - for(auto x:a[i]) - { - if(x!=p) - { - dfs(a,x,i); - int jj=st[x]->size(); - if(jj>mxs) - { - mxs=st[x]->size(); - mxi=x; - } - } - } - // err1(mxi); - if(mxi==-1) - { - st[i]=new set(); - st[i]->insert(col[i]); - } - else - { - st[i]=st[mxi]; - for(auto x:a[i]) - { - if(x!=p && x!=mxi) - { - for(auto kk: *st[x]) - st[i]->insert(kk); - } - } - st[i]->insert(col[i]); - } - ans[i]=st[i]->size(); - -} -int main() - { - ios_base::sync_with_stdio(false); - cin.tie(NULL); cout.tie(NULL); - #ifndef ONLINE_JUDGE - clock_t tStart = clock(); - freopen("input.txt","r",stdin); - freopen("output.txt","w",stdout); - #endif - int t; - // cin>>t; - t=1; - - while(t--) - { - int n; - cin>>n; - VV a(n); - rep(i,0,n) - { - cin>>col[i]; - } - rep(i,0,n-1) - { - int x,y; - cin>>x>>y; - x-=1; - y-=1; - a[x].pb(y); - a[y].pb(x); - } - dfs(a,0,-1); - rep(i,0,n) - { - cout< %.10fs\n", (double)(clock()-tStart) / CLOCKS_PER_SEC); - #endif -}