Contest Link: Codeforces Round 944 (Div. 4)
Problem Link: 1971E - Find the Car
Submission: 260347418
Why does my solution gives wrong ans? I have cross validated the approach various times but still couldn't find what is wrong with my code.
Code:
#include <bits/stdc++.h>
using namespace std;
#define md 1000000007
#define pb push_back
#define endl " \n"
#define F first
#define S second
#define sz(x) (int)(x).size()
#define inp(v) \
for (auto &x : v) \
cin >> x
#define all(x) (x).begin(), (x).end()
#define rep(i, a, b) for (int i = a; i < (b); ++i)
#define fast_io \
cin.tie(0)->sync_with_stdio(0); \
cin.exceptions(cin.failbit);
using ll = long long;
using ull = unsigned long long;
using lld = long double;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
using vl = vector<ll>;
using vi = vector<int>;
void solve() {
ll n,k,q;
cin>>n>>k>>q;
vl nums(k+1);
nums[0] = 0;
for (ll i=1;i<=k;i++) cin>>nums[i];
vl time(k+1);
time[0] = 0;
for (ll i=1;i<=k;i++) cin>>time[i];
for (ll i=0;i<q;i++) {
ll x;
cin>>x;
ll left = 0,right = k, mid,result = 0;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] <= x) {
result = mid;
left = mid + 1;
} else {
right = mid - 1;
}
}
if (nums[result] == x) {
cout<<time[result]<<" ";
} else {
double speed = 1.0*(nums[result+1] - nums[result])/(time[result+1] - time[result]);
ll val = time[result] + floor((x - nums[result])/speed);
// cout<<nums[result]<<" "<<speed<<" ";
cout<<val<<" ";
}
}
cout<<endl;
}
int main() {
fast_io;
int t = 1;
cin >> t;
for (int i = 0; i < t; i++)
solve();
return 0;
}
Maybe you’ve linked the wrong submission? In it, you’ve used doubles but the code you’ve posted here doesn’t. Looks like it should AC.
Oh sorry, I pasted the code of my other submission. I have pasted the correct code now.
Two things:
Ok, I will try this out. Thanks.
Basically
(x - nums[result])/speed
Wrong answerbut
(x - nums[result])*(time[result+1] - time[result])/(nums[result+1] - nums[result])
AcceptedExplaination was provided by another user .
Got it. Thanks.
Doubles in c++ (idk about other languages) can cause errors.
For example: if you stored 5 in double variable it could be stored as 4.99999..... so the floor of this value will be 4 although it should be 5.
Conclusion: Don't use doubles when you don't have to :)
You can see my submission to see how I solved it without doubles: 260345692
Got it, thanks.