CodeForces - 1730B Meeting on the Line
n people live on the coordinate line, the �i-th one lives at the point ��xi (1≤�≤�1≤i≤n). They want to choose a position �0x0 to meet. The �i-th person will spend ∣��−�0∣∣xi−x0∣ minutes to get to the meeting place. Also, the �i-th person needs ��ti minutes to get dressed, so in total he or she needs ��+∣��−�0∣ti+∣xi−x0∣ minutes.
Here ∣�∣∣y∣ denotes the absolute value of �y.
These people ask you to find a position �0x0 that minimizes the time in which all �n people can gather at the meeting place.
Input
The first line contains a single integer �t (1≤�≤1031≤t≤103) — the number of test cases. Then the test cases follow.
Each test case consists of three lines.
The first line contains a single integer �n (1≤�≤1051≤n≤105) — the number of people.
The second line contains �n integers �1,�2,…,��x1,x2,…,xn (0≤��≤1080≤xi≤108) — the positions of the people.
The third line contains �n integers �1,�2,…,��t1,t2,…,tn (0≤��≤1080≤ti≤108), where ��ti is the time �i-th person needs to get dressed.
It is guaranteed that the sum of �n over all test cases does not exceed 2⋅1052⋅105.
Output
For each test case, print a single real number — the optimum position �0x0. It can be shown that the optimal position �0x0 is unique.
Your answer will be considered correct if its absolute or relative error does not exceed 10−610−6. Formally, let your answer be �a, the jury's answer be �b. Your answer will be considered correct if ∣�−�∣���(1,∣�∣)≤10−6max(1,∣b∣)∣a−b∣≤10−6.
两种思路解题
(1)
贪心思想:
#include<bits/stdc++.h>
#define Acode ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
using namespace std;
typedef long long ll;
#define endl '\n'
const int inf = 0x3f3f3f3f;
const int N = 1e6 + 10;
ll x[N], t1[N];
int main()
{
Acode;
int t;
cin >> t;
while (t--)
{
int n;
cin >> n;
for (int i = 1; i <= n; i++) cin >> x[i];
for (int i = 1; i <= n; i++)cin >> t1[i];
ll min1 = inf, max1 = -inf;
for (int i = 1; i <= n; i++)
{
min1 = min(min1, x[i] - t1[i]);
max1 = max(max1, x[i] + t1[i]);
}
printf("%.10f\n", (min1 + max1) / 2.0);
}
return 0;
}
(2)
二分思想
#include<bits/stdc++.h>
#define Acode ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f3f;
#define endl '\n'
double ans = 0;
const int N = 1e6 + 10;
ll a[N], t[N];
int n;
bool check(double mid)
{
double l = -inf, r = inf;
for (int i = 1; i <= n; i++)
{
l = max(l, a[i] + t[i]-mid);
r = min(r, a[i] + mid - t[i]);
}
if (l <= r)
{
ans = (l + r) / 2;
return true;
}
else return false;
}
int main()
{
Acode;
int t1;
cin >> t1;
while (t1--)
{
cin >> n;
for (int i = 1; i <= n; i++) cin >> a[i];
for (int i = 1; i <= n; i++) cin >> t[i];
double l = 0, r = 1e9;
int cnt = 100;
while (cnt--)
{
double mid = (l + r) / 2;
if (check(mid)) l = mid;
else r = mid;
}
printf("%.10f\n", ans);
}
return 0;
}