#include <bits/stdc++.h>using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m, p, k;
if (!(cin >> n >> m >> p >> k)) return 0;
struct Ball { long long x, y, w; };
vector<Ball> a(k);
for (auto& b : a) cin >> b.x >> b.y >> b.w;
long long ans = 0;
{
vector<Ball> v = a;
sort(v.begin(), v.end(), [](const Ball& A, const Ball& B) {
if (A.x != B.x) return A.x < B.x;
return A.y < B.y;
});
int i = 0;
while (i < k) {
int j = i;
while (j < k && v[j].x == v[i].x) ++j;
long long s = 0;
int L = i;
for (int R = i; R < j; ++R) {
s += v[R].w;
while (v[R].y - v[L].y > p) { s -= v[L].w; ++L; }
ans = max(ans, s);
}
i = j;
}
}
{
vector<Ball> v = a;
sort(v.begin(), v.end(), [](const Ball& A, const Ball& B) {
if (A.y != B.y) return A.y < B.y;
return A.x < B.x;
});
int i = 0;
while (i < k) {
int j = i;
while (j < k && v[j].y == v[i].y) ++j;
long long s = 0;
int L = i;
for (int R = i; R < j; ++R) {
s += v[R].w;
while (v[R].x - v[L].x > p) { s -= v[L].w; ++L; }
ans = max(ans, s);
}
i = j;
}
}
cout << ans << '\n';
return 0;
}