// iostream is too mainstream
#include <cstdio>
// bitch please
#include <iostream>
#include <vector>
#include <set>
#include <map>
#include <string>
#include <queue>
#include <stack>
#include <algorithm>
#include <iomanip>
#define dibs reserve
#define OVER9000 1234567890
#define patkan 9
#define tisic 47
#define soclose 10e-7
#define ALL_THE(CAKE,LIE) for(auto LIE =CAKE.begin(); LIE != CAKE.end(); LIE++)
#define chocolate win
#define ff first
#define ss second
#define abs(x) ((x < 0)?-(x):(x))
// mylittlepony
using namespace std;
int main() {
cin.sync_with_stdio(0);
int N,K;
cin >> N >> K;
map<int,pair<int,int> > X[150000];
map<int,pair<int,int> > Y[150000];
vector< pair<int,int> > pl(N);
vector<int> F(N);
for(int i =0; i < N; i++) {
int x,y,f;
cin >> x >> y >> f;
pl[i] =make_pair(x,y);
F[i] =f;
X[x][y] =make_pair(i,f);
Y[y][x] =make_pair(i,f);}
vector< vector<int> > D(3,vector<int>(N,-1));
vector< vector<int> > ako(3,vector<int>(N,-1));
D[2][0] =F[0];
for(int i =0; i < 150000; i++) ALL_THE(X[i],jt) for(int j =0; j < 3; j++) if(D[j][jt->ss.ff] > 0) {
pair<int,int> p =make_pair(D[j][jt->ss.ff],3*(jt->ss.ff)+j);
// skok v smere x
int a =p.ss/3, t =p.ss%3;
auto it =X[pl[a].ff].find(pl[a].ss);
it++;
if(it != X[pl[a].ff].end()) {
pair<int,int> r =it->ss;
int d =(t == 0)?-min(K,F[a]):-K;
if(p.ff+d >= 0 && D[0][r.ff] < p.ff+d+r.ss) {
D[0][r.ff] =p.ff+d+r.ss;
ako[0][r.ff] =(t == 0 && F[a] < K)?ako[t][a]:p.ss;}
}
// v smere y
it =Y[pl[a].ss].find(pl[a].ff);
it++;
if(it != Y[pl[a].ss].end()) {
pair<int,int> r =it->ss;
int d =(t == 1)?-min(K,F[a]):-K;
if(p.ff+d >= 0 && D[1][r.ff] < p.ff+d+r.ss) {
D[1][r.ff] =p.ff+d+r.ss;
ako[1][r.ff] =(t == 1 && F[a] < K)?ako[t][a]:p.ss;}
}
}
cout << max(D[0][N-1],D[1][N-1]) << "\n";
int akt =3*(N-1)+1;
if(D[0][N-1] > D[1][N-1]) akt =3*(N-1);
vector<int> ans;
while(akt/3 > 0) {
ans.push_back(akt/3);
akt =ako[akt%3][akt/3];}
ans.push_back(0);
cout << ans.size() << "\n";
reverse(ans.begin(),ans.end());
for(int i =0; i < ans.size(); i++) cout << pl[ans[i]].ff << " " << pl[ans[i]].ss << "\n";
return 0;}
// look at my code
// my code is amazing
Ly8gaW9zdHJlYW0gaXMgdG9vIG1haW5zdHJlYW0KI2luY2x1ZGUgPGNzdGRpbz4KLy8gYml0Y2ggcGxlYXNlCiNpbmNsdWRlIDxpb3N0cmVhbT4KI2luY2x1ZGUgPHZlY3Rvcj4KI2luY2x1ZGUgPHNldD4KI2luY2x1ZGUgPG1hcD4KI2luY2x1ZGUgPHN0cmluZz4KI2luY2x1ZGUgPHF1ZXVlPgojaW5jbHVkZSA8c3RhY2s+CiNpbmNsdWRlIDxhbGdvcml0aG0+CiNpbmNsdWRlIDxpb21hbmlwPgojZGVmaW5lIGRpYnMgcmVzZXJ2ZQojZGVmaW5lIE9WRVI5MDAwIDEyMzQ1Njc4OTAKI2RlZmluZSBwYXRrYW4gOQojZGVmaW5lIHRpc2ljIDQ3CiNkZWZpbmUgc29jbG9zZSAxMGUtNwojZGVmaW5lIEFMTF9USEUoQ0FLRSxMSUUpIGZvcihhdXRvIExJRSA9Q0FLRS5iZWdpbigpOyBMSUUgIT0gQ0FLRS5lbmQoKTsgTElFKyspCiNkZWZpbmUgY2hvY29sYXRlIHdpbgojZGVmaW5lIGZmIGZpcnN0CiNkZWZpbmUgc3Mgc2Vjb25kCiNkZWZpbmUgYWJzKHgpICgoeCA8IDApPy0oeCk6KHgpKQovLyBteWxpdHRsZXBvbnkKdXNpbmcgbmFtZXNwYWNlIHN0ZDsKCQppbnQgbWFpbigpIHsKICAgIGNpbi5zeW5jX3dpdGhfc3RkaW8oMCk7CiAgICBpbnQgT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