// 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