Starting with a even number coordinate, first step you'll have your number decreased by 1, and later every 4 steps decreased by 4. And if starting with odd number, instead of decreasing, you can increasing the coordinate by 1 in the very first step and 4 every 4 steps later.
Therefore:
r = (n-1)%4
x_n - x_0 = delta = -1 - (n-1)/4*4 + (r == 1? n: 0) + (r == 2? (n-1+ n): 0) + (r == 3? (-n + n - 1 + n - 2): 0)
=> ANSWER = x_n = x_0 + delta * (x_0 % 2 == 0? 1: -1)
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int cc;
cin >> cc;
while(cc--) {
ll st, n;
cin>>st>>n;
if(n == 0) {cout<<st<<'\n'; continue;}
int r = (n - 1) % 4;
// ll delta = -1 - (n-1)/4*4 + (r == 1 ? n : 0) + (r == 2? (n-1+n):0) + (r==3? (-n+n-1+n-2):0);
ll delta = -1 - (n-1)/4*4 + (r == 1 ? n : 0) + (r == 2? (2*n-1):0) + (r==3? (n-3):0);
cout<<st + delta*(st % 2 == 0? 1 : - 1)<<'\n';
}
return 0;
}
Complexity: O(1)
Minus every mininum number and keep update the global minimal number.
(Using variable 'del' to document the value change for rest of the elements)
sort(a), then iterate i [0, n-1] : ans = max(ans, ans - (a[i] + del)); del = del - (a[i]+del) = -a[i];
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main() {
// freopen("test.in","r",stdin);
ios::sync_with_stdio(false);
cin.tie(0);
int cc;
cin >> cc;
while(cc--) {
int n;
cin>>n;
vector<int> a(n);
for(int i = 0; i < n; i++) {
cin>>a[i];
}
sort(a.begin(), a.end());
ll ans = -1e12;
ll del = 0;
for(int i = 0; i < n; i++) {
// cout<<a[i]+del<<" ";
ans = max(ans, a[i] + del);
del = -a[i];
}
cout<<ans<<'\n';
}
return 0;
}
Complexity: O(N)
Link to D: Blue-Red-Permutation
Every a[i] given need to be placed between [1, n];
If possible, for each number in [1~|B|], it should be able to filled by a specific a[i] which is Blue.
<=> i <= min(B[i], B[2], ..., B[|B|])
and for each number in [|B|+1, n], it should be able to filled by a specific a[i] which is Red.
<=> i >= min(A[i-|B| - 1], A[i - |B|], ..., A[|A|]])
And after sorting, min(B[i], B[2], ..., B[|B|]) = B[i]; min(A[i-|B| - 1], A[i - |B|], ..., A[|A|]]) = A[i - |B| - 1];
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main() {
// freopen("test.in","r",stdin);
ios::sync_with_stdio(false);
cin.tie(0);
int cc;
cin >> cc;
while(cc--) {
int n;
cin>>n;
vector<int> a(n+1);
vector<int> red;
vector<int> blue;
for(int i = 1; i <= n; i++) {
cin >> a[i];
}
for(int i = 1; i <= n; i++) {
char t;
cin>>t;
if(t == 'R') red.push_back(a[i]);
else blue.push_back(a[i]);
}
sort(red.begin(),red.end());
sort(blue.begin(),blue.end());
int k = blue.size();
bool perm = true;
for(int i = 1; i <= n; i++) {
if(i <= k) {
if(i > blue[i-1]) {
perm = false;
break;
}
}
else {
if(i < red[i-1-k]) {
perm = false;
break;
}
}
}
if(perm) cout<<"YES\n";
else cout<<"NO\n";
}
return 0;
}
Complexity: O(N)