loigiai
unknown
c_cpp
a year ago
3.0 kB
10
Indexable
#include <iostream> #include <algorithm> #include <iomanip> // Structure to store material data struct Material { double x; // x coordinate double mass; // mass }; // Function to calculate gravitational force double gravitationalForce(double m1, double m2, double d) { return 6.67430e-11 * m1 * m2 / (d * d); } // Function to check if force from left side is greater than, less than or equal to force from right side int compareForces(Material materials[], int n, double mid) { double left_force = 0.0; double right_force = 0.0; // Calculate total mass double total_mass = 0.0; for (int i = 0; i < n; ++i) { total_mass += materials[i].mass; } // Calculate force from left side for (int i = 0; i < n; ++i) { double d = mid - materials[i].x; if (d > 0) { left_force += gravitationalForce(materials[i].mass, total_mass - materials[i].mass, d); } } // Calculate force from right side for (int i = 0; i < n; ++i) { double d = materials[i].x - mid; if (d > 0) { right_force += gravitationalForce(materials[i].mass, total_mass - materials[i].mass, d); } } // Compare forces if (left_force > right_force) { return 1; // Left force is greater } else if (left_force < right_force) { return -1; // Right force is greater } else { return 0; // Forces are equal } } // Function to find balance point using binary search double findBalancePoint(Material materials[], int n) { double left = materials[0].x; double right = materials[n - 1].x; while (right - left > 1e-9) { double mid = (left + right) / 2.0; int cmp = compareForces(materials, n, mid); if (cmp == 0) { return mid; } else if (cmp < 0) { left = mid; } else { right = mid; } } return (left + right) / 2.0; } int main() { freopen("Text.txt","r",stdin); for (int case_num = 1; case_num <= 10; ++case_num) { int n; std::cin >> n; Material* materials = new Material[n]; // Read x coordinates and masses for (int i = 0; i < n; ++i) { std::cin >> materials[i].x; } for (int i = 0; i < n; ++i) { std::cin >> materials[i].mass; } // Sort materials by x coordinate std::sort(materials, materials + n, [](const Material& a, const Material& b) { return a.x < b.x; }); // Find balance point double balance_point = findBalancePoint(materials, n); // Output result std::cout << "#" << case_num << " "; std::cout << std::fixed << std::setprecision(10) << balance_point << std::endl; // Free allocated memory delete[] materials; } return 0; }
Editor is loading...
Leave a Comment