# December 2021 Silver Closest Cow Wins

tl;dr

I’m currently solving this problem, but for some reason I’m only getting 15/21 test cases. I tried implementing the solution that the editorial had, but I saw a flaw in that solution: what happens when you add twoCows - oneCows to your answer but oneCows isn’t added?

Here is my code:

``````#include <bits/stdc++.h>

using namespace std;
using ll = long long;
using vl = vector<ll>;
using pl = pair<ll, ll>;
using vpl = vector<pl>;

#define forn(i, n) for(ll i = 0; i < n; i++)
#define pb push_back
#define f first
#define s second
#define sor(x) sort(begin(x), end(x))
#define rsor(x) sort(begin(x), end(x), greater<ll>())

int main(){
ll k, m, n; cin >> k >> m >> n;
vpl locations; vl res;
forn(i, k){
ll p, t; cin >> p >> t;
locations.pb({p, t});
}
forn(i, m){
ll f; cin >> f;
locations.pb({f, -1});
}
sor(locations);
ll twoCow = 0, lst = -1;
forn(i, k + m){
if(locations[i].s != -1){
twoCow += locations[i].s;
} else {
if(lst == -1){
res.pb(twoCow);
} else {
ll oneCow = 0, curSum = 0;
ll l = lst + 1, r = lst + 1;
while(r <= i){
if(locations[r].s == -1){
break;
} else {
ll dist1 = (locations[r].f - locations[l].f);
ll dist2 = (locations[r].f - locations[lst].f);
ll dist3 = (locations[i].f - locations[r].f);
if(dist1 <= dist2 && dist1 <= dist3){
curSum += locations[r].s;
r++;
} else {
oneCow = max(oneCow, curSum);
curSum -= locations[l].s;
l++;
}
}
}
res.pb(oneCow);
res.pb(twoCow - oneCow);
}
lst = i;
twoCow = 0;
}
}
res.pb(twoCow);
rsor(res); ll ans = 0;
forn(i, n){
ans += res[i];
}
cout << ans << endl;
}
``````

The only thing I did differently here is that I used two-pointers instead of sliding window. Could this potentially be the issue in my code?