#include <bits/stdc++.h>
using namespace std;
#define mod 1000000007
#define oo 2000000000
const int N = 10010;
int n , k;
vector< pair<int,int> > f[N];
vector< vector<int> > seg[N];

void merge(vector<int> &v1,vector<int> &v2,vector<int> &v3){
	int j = 0;
	for(int i=0;i<v2.size();i++){
		while(j < v3.size() && v3[j] < v2[i]) v1.push_back(v3[j++]);
		v1.push_back(v2[i]);
	}
	while(j < v3.size()) v1.push_back(v3[j++]);
}

void build(int s,int e,int idx,int cur){
	if(s == e){
		seg[cur][idx].push_back(f[cur][s].second);
		return ;
	}
	build(s,(s+e)/2,idx*2,cur);
	build((s+e)/2+1,e,idx*2+1,cur);
	merge(seg[cur][idx],seg[cur][idx*2],seg[cur][idx*2+1]);
}

int getsum(int s,int e,int idx,int l,int r,int cur,int val){
	if(s > r || e < l) return 0;
	if(s >= l && e <= r) return seg[cur][idx].end() - upper_bound(seg[cur][idx].begin(),seg[cur][idx].end(),val);
	return getsum(s,(s+e)/2,idx*2,l,r,cur,val) + getsum((s+e)/2+1,e,idx*2+1,l,r,cur,val);
}

int getsum2(int s,int e,int idx,int l,int r,int cur,int val){
	if(s > r || e < l) return 0;
	if(s >= l && e <= r) return seg[cur][idx].end() - lower_bound(seg[cur][idx].begin(),seg[cur][idx].end(),val);
	return getsum2(s,(s+e)/2,idx*2,l,r,cur,val) + getsum2((s+e)/2+1,e,idx*2+1,l,r,cur,val);
}

int getsum3(int s,int e,int idx,int l,int r,int cur,int val){
	if(s > r || e < l) return 0;
	if(s >= l && e <= r) return upper_bound(seg[cur][idx].begin(),seg[cur][idx].end(),val) - lower_bound(seg[cur][idx].begin(),seg[cur][idx].end(),val);
	return getsum2(s,(s+e)/2,idx*2,l,r,cur,val) + getsum2((s+e)/2+1,e,idx*2+1,l,r,cur,val);
}

int main() {
	//freopen("in.txt","r",stdin);
	scanf("%d%d",&n,&k);
	for(int i=0;i<n;i++){
		int a, b, c;
		scanf("%d%d%d",&a,&b,&c);
		f[c].push_back(make_pair(a,b));
	}
	for(int i=0;i<N;i++){
		if(f[i].size() == 0) continue;
		sort(f[i].begin(),f[i].end());
		seg[i].resize(4*f[i].size());
		build(0,f[i].size()-1,1,i);
	}
	long long ans = 0 ;
	for(int i=0;i<N;i++){
		for(int j=0;j<f[i].size();j++){
			for(int l=max(0,i-k);l<=i+k;l++){
				if(f[l].size() == 0) continue;
				int L = lower_bound(f[l].begin(),f[l].end(),make_pair(f[i][j].first-f[i][j].second,0)) - f[l].begin();
				int r = upper_bound(f[l].begin(),f[l].end(),make_pair(f[i][j].first+f[i][j].second,oo)) - f[l].begin() - 1;
				if(r < L) continue;
				if(l <= i)
					ans += getsum(0,f[l].size()-1,1,L,r,l,f[i][j].second);
				else
					ans += getsum2(0,f[l].size()-1,1,L,r,l,f[i][j].second);
			}
			if(j > 0){
				int idx = lower_bound(f[i].begin(),f[i].end(),make_pair(f[i][j].first-f[i][j].second,0)) - f[i].begin();
				if(idx < j)
					ans += getsum3(0,f[i].size()-1,1,idx,j-1,i,f[i][j].second);
			}
		}
	}
	cout << ans << endl;
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define mod 1000000007
#define oo 2000000000
const int N = 10010;
int n , k;
vector< pair<int,int> > f[N];
vector< vector<int> > seg[N];

void merge(vector<int> &v1,vector<int> &v2,vector<int> &v3){
	int j = 0;
	for(int i=0;i<v2.size();i++){
		while(j < v3.size() && v3[j] < v2[i]) v1.push_back(v3[j++]);
		v1.push_back(v2[i]);
	}
	while(j < v3.size()) v1.push_back(v3[j++]);
}

void build(int s,int e,int idx,int cur){
	if(s == e){
		seg[cur][idx].push_back(f[cur][s].second);
		return ;
	}
	build(s,(s+e)/2,idx*2,cur);
	build((s+e)/2+1,e,idx*2+1,cur);
	merge(seg[cur][idx],seg[cur][idx*2],seg[cur][idx*2+1]);
}

int getsum(int s,int e,int idx,int l,int r,int cur,int val){
	if(s > r || e < l) return 0;
	if(s >= l && e <= r) return seg[cur][idx].end() - upper_bound(seg[cur][idx].begin(),seg[cur][idx].end(),val);
	return getsum(s,(s+e)/2,idx*2,l,r,cur,val) + getsum((s+e)/2+1,e,idx*2+1,l,r,cur,val);
}

int getsum2(int s,int e,int idx,int l,int r,int cur,int val){
	if(s > r || e < l) return 0;
	if(s >= l && e <= r) return seg[cur][idx].end() - lower_bound(seg[cur][idx].begin(),seg[cur][idx].end(),val);
	return getsum2(s,(s+e)/2,idx*2,l,r,cur,val) + getsum2((s+e)/2+1,e,idx*2+1,l,r,cur,val);
}

int main() {
	//freopen("in.txt","r",stdin);
	scanf("%d%d",&n,&k);
	for(int i=0;i<n;i++){
		int a, b, c;
		scanf("%d%d%d",&a,&b,&c);
		f[c].push_back(make_pair(a,b));
	}
	for(int i=0;i<N;i++){
		if(f[i].size() == 0) continue;
		sort(f[i].begin(),f[i].end());
		seg[i].resize(4*f[i].size());
		build(0,f[i].size()-1,1,i);
	}
	long long ans = 0 ;
	for(int i=0;i<N;i++){
		for(int j=0;j<f[i].size();j++){
			for(int l=max(1,i-k);l<=i+k;l++){
				if(i == l) continue;
				if(f[l].size() == 0) continue;
				int L = lower_bound(f[l].begin(),f[l].end(),make_pair(f[i][j].first-f[i][j].second,0)) - f[l].begin();
				int r = upper_bound(f[l].begin(),f[l].end(),make_pair(f[i][j].first+f[i][j].second,oo)) - f[l].begin() - 1;
				if(r < L) continue;
				if(l > i)
					ans += getsum(0,f[l].size()-1,1,L,r,l,f[i][j].second);
				else
					ans += getsum2(0,f[l].size()-1,1,L,r,l,f[i][j].second);
			}

				int idx = lower_bound(f[i].begin(),f[i].end(),make_pair(f[i][j].first-f[i][j].second,0)) - f[i].begin();
				if(idx < j)
					ans += getsum2(0,f[i].size()-1,1,idx,j-1,i,f[i][j].second);
				int idx2 = upper_bound(f[i].begin(),f[i].end(),make_pair(f[i][j].first+f[i][j].second,oo)) - f[i].begin() - 1;
				if(j <= idx2)
					ans += getsum(0,f[i].size()-1,1,j,idx2,i,f[i][j].second);

		}
	}
	cout << ans << endl;
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define mod 1000000007
#define oo 2000000000
const int N = 10010;
int n , k;
vector< pair<int,int> > f[N];
vector< vector<int> > seg[N];

void merge(vector<int> &v1,vector<int> &v2,vector<int> &v3){
	int j = 0;
	for(int i=0;i<v2.size();i++){
		while(j < v3.size() && v3[j] < v2[i]) v1.push_back(v3[j++]);
		v1.push_back(v2[i]);
	}
	while(j < v3.size()) v1.push_back(v3[j++]);
}

void build(int s,int e,int idx,int cur){
	if(s == e){
		seg[cur][idx].push_back(f[cur][s].second);
		return ;
	}
	build(s,(s+e)/2,idx*2,cur);
	build((s+e)/2+1,e,idx*2+1,cur);
	merge(seg[cur][idx],seg[cur][idx*2],seg[cur][idx*2+1]);
}

int getsum(int s,int e,int idx,int l,int r,int cur,int val){
	if(s > r || e < l) return 0;
	if(s >= l && e <= r) return seg[cur][idx].end() - upper_bound(seg[cur][idx].begin(),seg[cur][idx].end(),val);
	return getsum(s,(s+e)/2,idx*2,l,r,cur,val) + getsum((s+e)/2+1,e,idx*2+1,l,r,cur,val);
}

int getsum2(int s,int e,int idx,int l,int r,int cur,int val){
	if(s > r || e < l) return 0;
	if(s >= l && e <= r) return seg[cur][idx].end() - lower_bound(seg[cur][idx].begin(),seg[cur][idx].end(),val);
	return getsum2(s,(s+e)/2,idx*2,l,r,cur,val) + getsum2((s+e)/2+1,e,idx*2+1,l,r,cur,val);
}

int getsum3(int s,int e,int idx,int l,int r,int cur,int val){
	if(s > r || e < l) return 0;
	if(s >= l && e <= r) return upper_bound(seg[cur][idx].begin(),seg[cur][idx].end(),val) - lower_bound(seg[cur][idx].begin(),seg[cur][idx].end(),val);
	return getsum2(s,(s+e)/2,idx*2,l,r,cur,val) + getsum2((s+e)/2+1,e,idx*2+1,l,r,cur,val);
}

int main() {
	//freopen("in.txt","r",stdin);
	scanf("%d%d",&n,&k);
	for(int i=0;i<n;i++){
		int a, b, c;
		scanf("%d%d%d",&a,&b,&c);
		f[c].push_back(make_pair(a,b));
	}
	for(int i=0;i<N;i++){
		if(f[i].size() == 0) continue;
		sort(f[i].begin(),f[i].end());
		seg[i].resize(4*f[i].size());
		build(0,f[i].size()-1,1,i);
	}
	long long ans = 0 ;
	for(int i=0;i<N;i++){
		for(int j=0;j<f[i].size();j++){
			for(int l=max(0,i-k);l<=i+k;l++){
				if(f[l].size() == 0) continue;
				int L = lower_bound(f[l].begin(),f[l].end(),make_pair(f[i][j].first-f[i][j].second,0)) - f[l].begin();
				int r = upper_bound(f[l].begin(),f[l].end(),make_pair(f[i][j].first+f[i][j].second,oo)) - f[l].begin() - 1;
				if(r < L) continue;
				if(l >= i)
					ans += getsum(0,f[l].size()-1,1,L,r,l,f[i][j].second);
				else
					ans += getsum2(0,f[l].size()-1,1,L,r,l,f[i][j].second);
			}
			if(j > 0){
				int idx = lower_bound(f[i].begin(),f[i].end(),make_pair(f[i][j].first-f[i][j].second,0)) - f[i].begin();
				if(idx < j)
					ans += getsum3(0,f[i].size()-1,1,idx,j-1,i,f[i][j].second);
			}
		}
	}
	cout << ans << endl;
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define mod 1000000007
#define oo 2000000000
const int N = 10010;
int n , k;
vector< pair<int,int> > f[N];
vector< vector<int> > seg[N];

void merge(vector<int> &v1,vector<int> &v2,vector<int> &v3){
	int j = 0;
	for(int i=0;i<v2.size();i++){
		while(j < v3.size() && v3[j] < v2[i]) v1.push_back(v3[j++]);
		v1.push_back(v2[i]);
	}
	while(j < v3.size()) v1.push_back(v3[j++]);
}

void build(int s,int e,int idx,int cur){
	if(s == e){
		seg[cur][idx].push_back(f[cur][s].second);
		return ;
	}
	build(s,(s+e)/2,idx*2,cur);
	build((s+e)/2+1,e,idx*2+1,cur);
	merge(seg[cur][idx],seg[cur][idx*2],seg[cur][idx*2+1]);
}

int getsum(int s,int e,int idx,int l,int r,int cur,int val){
	if(s > r || e < l) return 0;
	if(s >= l && e <= r) return seg[cur][idx].end() - upper_bound(seg[cur][idx].begin(),seg[cur][idx].end(),val);
	return getsum(s,(s+e)/2,idx*2,l,r,cur,val) + getsum((s+e)/2+1,e,idx*2+1,l,r,cur,val);
}

int getsum2(int s,int e,int idx,int l,int r,int cur,int val){
	if(s > r || e < l) return 0;
	if(s >= l && e <= r) return seg[cur][idx].end() - lower_bound(seg[cur][idx].begin(),seg[cur][idx].end(),val);
	return getsum2(s,(s+e)/2,idx*2,l,r,cur,val) + getsum2((s+e)/2+1,e,idx*2+1,l,r,cur,val);
}

int getsum3(int s,int e,int idx,int l,int r,int cur,int val){
	if(s > r || e < l) return 0;
	if(s >= l && e <= r) return upper_bound(seg[cur][idx].begin(),seg[cur][idx].end(),val) - lower_bound(seg[cur][idx].begin(),seg[cur][idx].end(),val);
	return getsum2(s,(s+e)/2,idx*2,l,r,cur,val) + getsum2((s+e)/2+1,e,idx*2+1,l,r,cur,val);
}

int main() {
	//freopen("in.txt","r",stdin);
	scanf("%d%d",&n,&k);
	for(int i=0;i<n;i++){
		int a, b, c;
		scanf("%d%d%d",&a,&b,&c);
		f[c].push_back(make_pair(a,b));
	}
	for(int i=0;i<N;i++){
		if(f[i].size() == 0) continue;
		sort(f[i].begin(),f[i].end());
		seg[i].resize(4*f[i].size());
		build(0,f[i].size()-1,1,i);
	}
	long long ans = 0 ;
	for(int i=0;i<N;i++){
		for(int j=0;j<f[i].size();j++){
			for(int l=max(0,i-k);l<=i+k;l++){
				if(f[l].size() == 0) continue;
				int L = lower_bound(f[l].begin(),f[l].end(),make_pair(f[i][j].first-f[i][j].second,0)) - f[l].begin();
				int r = upper_bound(f[l].begin(),f[l].end(),make_pair(f[i][j].first+f[i][j].second,oo)) - f[l].begin() - 1;
				if(r < L) continue;
				if(l > i)
					ans += getsum2(0,f[l].size()-1,1,L,r,l,f[i][j].second);
				else
					ans += getsum(0,f[l].size()-1,1,L,r,l,f[i][j].second);
			}
			if(j > 0){
				int idx = lower_bound(f[i].begin(),f[i].end(),make_pair(f[i][j].first-f[i][j].second,0)) - f[i].begin();
				if(idx < j)
					ans += getsum3(0,f[i].size()-1,1,idx,j-1,i,f[i][j].second);
			}
		}
	}
	cout << ans << endl;
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define mod 1000000007
#define oo 2000000000
const int N = 10010;
int n , k;
vector< pair<int,int> > f[N];
vector< vector<int> > seg[N];

void merge(vector<int> &v1,vector<int> &v2,vector<int> &v3){
	int j = 0;
	for(int i=0;i<v2.size();i++){
		while(j < v3.size() && v3[j] < v2[i]) v1.push_back(v3[j++]);
		v1.push_back(v2[i]);
	}
	while(j < v3.size()) v1.push_back(v3[j++]);
}

void build(int s,int e,int idx,int cur){
	if(s == e){
		seg[cur][idx].push_back(f[cur][s].second);
		return ;
	}
	build(s,(s+e)/2,idx*2,cur);
	build((s+e)/2+1,e,idx*2+1,cur);
	merge(seg[cur][idx],seg[cur][idx*2],seg[cur][idx*2+1]);
}

int getsum(int s,int e,int idx,int l,int r,int cur,int val){
	if(s > r || e < l) return 0;
	if(s >= l && e <= r) return seg[cur][idx].end() - upper_bound(seg[cur][idx].begin(),seg[cur][idx].end(),val);
	return getsum(s,(s+e)/2,idx*2,l,r,cur,val) + getsum((s+e)/2+1,e,idx*2+1,l,r,cur,val);
}

int getsum2(int s,int e,int idx,int l,int r,int cur,int val){
	if(s > r || e < l) return 0;
	if(s >= l && e <= r) return seg[cur][idx].end() - lower_bound(seg[cur][idx].begin(),seg[cur][idx].end(),val);
	return getsum2(s,(s+e)/2,idx*2,l,r,cur,val) + getsum2((s+e)/2+1,e,idx*2+1,l,r,cur,val);
}

int main() {
	//freopen("in.txt","r",stdin);
	scanf("%d%d",&n,&k);
	for(int i=0;i<n;i++){
		int a, b, c;
		scanf("%d%d%d",&a,&b,&c);
		f[c].push_back(make_pair(a,b));
	}
	for(int i=0;i<N;i++){
		if(f[i].size() == 0) continue;
		sort(f[i].begin(),f[i].end());
		seg[i].resize(4*f[i].size());
		build(0,f[i].size()-1,1,i);
	}
	long long ans = 0 ;
	for(int i=0;i<N;i++){
		for(int j=0;j<f[i].size();j++){
			for(int l=max(1,i-k);l<=i+k;l++){
				if(i == l) continue;
				if(f[l].size() == 0) continue;
				int L = lower_bound(f[l].begin(),f[l].end(),make_pair(f[i][j].first-f[i][j].second,0)) - f[l].begin();
				int r = upper_bound(f[l].begin(),f[l].end(),make_pair(f[i][j].first+f[i][j].second,oo)) - f[l].begin() - 1;
				if(r < L) continue;
				if(l <= i)
					ans += getsum(0,f[l].size()-1,1,L,r,l,f[i][j].second);
				else
					ans += getsum2(0,f[l].size()-1,1,L,r,l,f[i][j].second);
			}
			if(j > 0){
				int idx = lower_bound(f[i].begin(),f[i].end(),make_pair(f[i][j].first-f[i][j].second,0)) - f[i].begin();
				if(idx < j)
					ans += getsum2(0,f[i].size()-1,1,idx,j-1,i,f[i][j].second);
			}
		}
	}
	cout << ans << endl;
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define mod 1000000007
#define oo 2000000000
const int N = 10010;
int n , k;
vector< pair<int,int> > f[N];
vector< vector<int> > seg[N];

void merge(vector<int> &v1,vector<int> &v2,vector<int> &v3){
	int j = 0;
	for(int i=0;i<v2.size();i++){
		while(j < v3.size() && v3[j] < v2[i]) v1.push_back(v3[j++]);
		v1.push_back(v2[i]);
	}
	while(j < v3.size()) v1.push_back(v3[j++]);
}

void build(int s,int e,int idx,int cur){
	if(s == e){
		seg[cur][idx].push_back(f[cur][s].second);
		return ;
	}
	build(s,(s+e)/2,idx*2,cur);
	build((s+e)/2+1,e,idx*2+1,cur);
	merge(seg[cur][idx],seg[cur][idx*2],seg[cur][idx*2+1]);
}

int getsum(int s,int e,int idx,int l,int r,int cur,int val){
	if(s > r || e < l) return 0;
	if(s >= l && e <= r) return seg[cur][idx].end() - upper_bound(seg[cur][idx].begin(),seg[cur][idx].end(),val);
	return getsum(s,(s+e)/2,idx*2,l,r,cur,val) + getsum((s+e)/2+1,e,idx*2+1,l,r,cur,val);
}

int getsum2(int s,int e,int idx,int l,int r,int cur,int val){
	if(s > r || e < l) return 0;
	if(s >= l && e <= r) return seg[cur][idx].end() - lower_bound(seg[cur][idx].begin(),seg[cur][idx].end(),val);
	return getsum2(s,(s+e)/2,idx*2,l,r,cur,val) + getsum2((s+e)/2+1,e,idx*2+1,l,r,cur,val);
}

int main() {
	//freopen("in.txt","r",stdin);
	scanf("%d%d",&n,&k);
	for(int i=0;i<n;i++){
		int a, b, c;
		scanf("%d%d%d",&a,&b,&c);
		f[c].push_back(make_pair(a,b));
	}
	for(int i=0;i<N;i++){
		if(f[i].size() == 0) continue;
		sort(f[i].begin(),f[i].end());
		seg[i].resize(4*f[i].size());
		build(0,f[i].size()-1,1,i);
	}
	long long ans = 0 ;
	for(int i=0;i<N;i++){
		for(int j=0;j<f[i].size();j++){
			for(int l=max(1,i-k);l<=min(i+k,N-1);l++){
				if(i == l) continue;
				if(f[l].size() == 0) continue;
				int L = lower_bound(f[l].begin(),f[l].end(),make_pair(f[i][j].first-f[i][j].second,0)) - f[l].begin();
				int r = upper_bound(f[l].begin(),f[l].end(),make_pair(f[i][j].first+f[i][j].second,oo)) - f[l].begin() - 1;
				if(r < L) continue;
				if(l > i)
					ans += getsum(0,f[l].size()-1,1,L,r,l,f[i][j].second);
				else
					ans += getsum2(0,f[l].size()-1,1,L,r,l,f[i][j].second);
			}

				int idx = lower_bound(f[i].begin(),f[i].end(),make_pair(f[i][j].first-f[i][j].second,0)) - f[i].begin();
				if(idx < j)
					ans += getsum2(0,f[i].size()-1,1,idx,j-1,i,f[i][j].second);
				int idx2 = upper_bound(f[i].begin(),f[i].end(),make_pair(f[i][j].first+f[i][j].second,oo)) - f[i].begin() - 1;
				if(j <= idx2)
					ans += getsum(0,f[i].size()-1,1,j,idx2,i,f[i][j].second);

		}
	}
	cout << ans << endl;
	return 0;
}


#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
const int INF = 0x3f3f3f3f;
const int N = 100005;

struct Node
{
    int x,r,f,i;
    bool operator < (const Node& p) const {
        return r > p.r;
    }
}s[N];

int n,k,m;
int ans;
int tmp[N];
int bit[N];

bool cmp(const Node &a,const Node &b)
{
    return a.f < b.f;
}

int lowbit(int x)
{
    return x & (-x);
}

void add(int x,int d)
{
    //cout << "add " << x << " " << d <<  endl;
    while(x <= m)
    {
        bit[x] += d;
        x += lowbit(x);
    }
}

int sum(int x)
{
    //cout << "sum " << x << endl;
    int ans = 0;
    while(x > 0)
    {
        ans += bit[x];
        x -= lowbit(x);
    }
    return ans;
}

int sum(int l,int r)
{
    int ans = 0;
    if(l > 1) ans -= sum(l - 1);
    if(r > m) r = m;
    ans += sum(r);
    //cout << "sum " << l << " " << r << " = " << ans <<  endl;
    return ans;
}

void cdq(int l,int r)
{
    if(l >= r) return;
    int mid = (l + r) >> 1;
    cdq(l,mid);
    cdq(mid + 1,r);
    sort(s + l,s + r + 1,cmp);
    int L = l;
    int R = l;
    //printf("%d %d\n",l,r);

    for(int i = l;i <= r; ++i)
    {
        if(s[i].i <= mid) continue;
        while(R <= r && s[R].f <= s[i].f + k)
        {
            if(s[R].i <= mid) add(s[R].x,1);
            ++R;
        }
        while(L <= r && s[L].f < s[i].f - k)
        {
            if(s[L].i <= mid) add(s[L].x,-1);
            ++L;
        }
        //printf("%d %d %d\n",i,L,R - 1);
        //printf("%d %d\n",tmp[s[i].x - 1],s[i].r);
        int x = lower_bound(tmp,tmp + m,tmp[s[i].x - 1] - s[i].r) - tmp + 1;
        int y = lower_bound(tmp,tmp + m,tmp[s[i].x - 1] + s[i].r) - tmp + 1;
        //int k = tmp[s[i].x - 1] + s[i].r;
        //printf("k = %d, %d\n",k,lower_bound(tmp,tmp + m,k) - tmp + 1);
        //printf("(%d,%d) (%d,%d)\n",tmp[s[i].x - 1] - s[i].r,tmp[s[i].x - 1] + s[i].r,x,y);
        ans += sum(x,y);
    }

    while(L < R)
    {
        if(s[L].i <= mid)
            add(s[L].x,-1);
        ++L;
    }
}

int solve()
{
    sort(s,s + n);
    for(int i = 0;i < n; ++i)
        s[i].i = i;
    m = 0;
    for(int i = 0;i < n; ++i)
        tmp[m++] = s[i].x;
    sort(tmp,tmp + m);
    m = unique(tmp,tmp + m) - tmp;
    for(int i = 0;i < n; ++i)
        s[i].x = lower_bound(tmp,tmp + m,s[i].x) - tmp + 1;
    ans = 0;
    for(int i = 1;i <= m; ++i)
        bit[i] = 0;
    cdq(0,n - 1);
    return ans;
}

int main()
{
    scanf("%d%d",&n,&k);
    for(int i = 0;i < n; ++i)
        scanf("%d%d%d",&s[i].x,&s[i].r,&s[i].f);
    printf("%d\n",solve());
    return 0;
}


#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
const int INF = 0x3f3f3f3f;
const int N = 100005;
const int M = 10150;

struct Node
{
    int x,r,f;
    bool operator < (const Node& p) const {
        return r > p.r;
    }
}s[N];

struct Query
{
    int t,x,y,w;
    bool operator < (const Query &p) const {
        return x == p.x ? t < p.t : x < p.x;
    }
}query[N * 5],tmp[N * 5];

int n,k;
ll ans;
int bit[N];

int lowbit(int x)
{
    return x & (-x);
}

void add(int x,int d)
{
    while(x < M)
    {
        bit[x] += d;
        x += lowbit(x);
    }
}

int sum(int x)
{
    int ans = 0;
    while(x > 0)
    {
        ans += bit[x];
        x -= lowbit(x);
    }
    return ans;
}

void clear(int x)
{
    while(x < M)
    {
        bit[x] = 0;
        x += lowbit(x);
    }
}

void cdq(int L,int R)
{
    if(L >= R) return;
    int mid = (L + R) >> 1;
    cdq(L,mid);
    cdq(mid + 1,R);
    int l = L,r = mid + 1,o = L;

    while(l <= mid && r <= R)
    {
        if(query[l] < query[r])
        {
            if(query[l].t == 0)
                add(query[l].y,1);
            tmp[o++] = query[l++];
        }
        else
        {
            if(query[r].t == 1)
                ans += sum(query[r].y) * query[r].w;
            tmp[o++] = query[r++];
        }
    }

    while(l <= mid)
        tmp[o++] = query[l++];

    while(r <= R)
    {
        if(query[r].t == 1)
            ans += sum(query[r].y) * query[r].w;
        tmp[o++] = query[r++];
    }

    for(int i = L;i <= R; ++i)
    {
        if(query[i].t == 0)
            clear(query[i].y);
        query[i] = tmp[i];
    }
}

ll solve()
{
    sort(s,s + n);
    int idx = 0;
    for(int i = 0;i < n; ++i)
    {
        Node &e = s[i];
        int u1 = e.x - e.r,v1 = max(1,e.f - k);
        int u2 = e.x + e.r,v2 = e.f + k;
        query[idx++] = Query{1,u1 - 1,v1 - 1,1};
        query[idx++] = Query{1,u1 - 1,v2,-1};
        query[idx++] = Query{1,u2,v1 - 1,-1};
        query[idx++] = Query{1,u2,v2,1};
        query[idx++] = Query{0,e.x,e.f,0};
    }
    ans = 0;
    cdq(0,idx - 1);
    return ans;
}

int main()
{
    scanf("%d%d",&n,&k);
    for(int i = 0;i < n; ++i)
        scanf("%d%d%d",&s[i].x,&s[i].r,&s[i].f);
    printf("%lld\n",solve());
    return 0;
}


#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
const int INF = 0x3f3f3f3f;
const int N = 100005;
const int M = 10150;

struct Node
{
    int x,r,f;
    bool operator < (const Node& p) const {
        return r > p.r;
    }
}s[N];

struct Query
{
    int t,x,y,w;
    bool operator < (const Query &p) const {
        return x == p.x ? t < p.t : x < p.x;
    }
}query[N * 5],tmp[N * 5];

int n,k;
ll ans;
int bit[N];

int lowbit(int x)
{
    return x & (-x);
}

void add(int x,int d)
{
    while(x < M)
    {
        bit[x] += d;
        x += lowbit(x);
    }
}

int sum(int x)
{
    int ans = 0;
    while(x > 0)
    {
        ans += bit[x];
        x -= lowbit(x);
    }
    return ans;
}

void clear(int x)
{
    while(x < M)
    {
        bit[x] = 0;
        x += lowbit(x);
    }
}

void cdq(int L,int R)
{
    if(L >= R) return;
    int mid = (L + R) >> 1;
    cdq(L,mid);
    cdq(mid + 1,R);
    int l = L,r = mid + 1,o = L;

    while(l <= mid && r <= R)
    {
        if(query[l] < query[r])
        {
            if(query[l].t == 0)
                add(query[l].y,1);
            tmp[o++] = query[l++];
        }
        else
        {
            if(query[r].t == 1)
                ans += sum(query[r].y) * query[r].w;
            tmp[o++] = query[r++];
        }
    }

    while(l <= mid)
        tmp[o++] = query[l++];

    while(r <= R)
    {
        if(query[r].t == 1)
            ans += sum(query[r].y) * query[r].w;
        tmp[o++] = query[r++];
    }

    for(int i = L;i <= R; ++i)
    {
        if(query[i].t == 0)
            clear(query[i].y);
        query[i] = tmp[i];
    }
}

ll solve()
{
    sort(s,s + n);
    int idx = 0;
    for(int i = 0;i < n; ++i)
    {
        Node &e = s[i];
        int u1 = e.x - e.r,v1 = max(1,e.f - k);
        int u2 = e.x + e.r,v2 = e.f + k;
        query[idx++] = Query{0,e.x,e.f,0};
        query[idx++] = Query{1,u1 - 1,v1 - 1,1};
        query[idx++] = Query{1,u1 - 1,v2,-1};
        query[idx++] = Query{1,u2,v1 - 1,-1};
        query[idx++] = Query{1,u2,v2,1};
    }
    ans = 0;
    cdq(0,idx - 1);
    return ans - n;
}

int main()
{
    scanf("%d%d",&n,&k);
    for(int i = 0;i < n; ++i)
        scanf("%d%d%d",&s[i].x,&s[i].r,&s[i].f);
    printf("%lld\n",solve());
    return 0;
}


#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
const int INF = 0x3f3f3f3f;
const int N = 100005;

struct Node
{
    int x,r,f;
}s[N];

int n,k,m;
int ans;
int tmp[N];
int LL,RR;
int bit[N];
vector<int> f[N];

int lowbit(int x)
{
    return x & (-x);
}

void add(int x,int d)
{
    //cout << "add " << x << " " << d <<  endl;
    while(x <= m)
    {
        bit[x] += d;
        x += lowbit(x);
    }
}

int sum(int x)
{
    //cout << "sum " << x << endl;
    int ans = 0;
    while(x > 0)
    {
        ans += bit[x];
        x -= lowbit(x);
    }
    return ans;
}

int sum(int l,int r)
{
    if(l > r) return 0;
    int ans = 0;
    if(l > 1) ans -= sum(l - 1);
    if(r > m) r = m;
    ans += sum(r);
    //cout << "sum " << l << " " << r << " = " << ans <<  endl;
    return ans;
}

void calc(int now)
{
    vector<int> u,v;
    for(int i = max(LL,now - k);i <= min(RR,now + k); ++i)
    {
        int len = f[i].size();
        for(int j = 0;j < len; ++j)
            u.push_back(f[i][j]);
    }
    sort(u.begin(),u.end(), [&](int x,int y) {return s[x].x < s[y].x;} );
    m = u.size();
    for(int i = 0;i < m; ++i)
        v.push_back(i);
    sort(v.begin(),v.end(), [&](int x,int y) {return s[u[x]].x + s[u[x]].r < s[u[y]].x + s[u[y]].r;});
    int j = 0;
    for(int i = m;i >= 1; --i)
    {
        bit[i] = 0;
        add(i,1);
    }
    for(int i = 0;i < m; ++i)
    if(s[u[i]].f == now)
    {
        while(j < m && s[u[v[j]]].x + s[u[v[j]]].r < s[u[i]].x)
        {
            add(v[j] + 1,-1);
            ++j;
        }
        int l = 0,r = i - 1;
        int p = s[u[i]].x - s[u[i]].r;
        while(l < r)
        {
            int mid = (l + r) >> 1;
            if(s[u[mid]].x < p)
                l = mid + 1;
            else
                r = mid;
        }
        //cout << now << " sum = " << sum(l + 1,i + 1) << endl;
        ans += sum(l + 1,i);
    }
}

ll solve()
{
    for(int i = 0;i < n; ++i)
        f[s[i].f].push_back(i);
    ans = 0;
    for(int i = LL;i <= RR; ++i)
        calc(i);
    return ans;
}

int main()
{
    scanf("%d%d",&n,&k);
    LL = N,RR = -1;
    for(int i = 0;i < n; ++i)
    {
        scanf("%d%d%d",&s[i].x,&s[i].r,&s[i].f);
        RR = max(RR,s[i].f);
        LL = min(LL,s[i].f);
    }
    printf("%lld\n",solve());
    return 0;
}


#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
const int INF = 0x3f3f3f3f;
const int N = 100005;
const int M = 1015;

struct Node
{
    int x,r,f;
    bool operator < (const Node& p) const {
        return r > p.r;
    }
}s[N];

struct Query
{
    int t,x,y,w;
    bool operator < (const Query &p) const {
        return x == p.x ? t < p.t : x < p.x;
    }
}query[N * 5],tmp[N * 5];

int n,k;
ll ans;
int bit[N];

int lowbit(int x)
{
    return x & (-x);
}

void add(int x,int d)
{
    while(x < M)
    {
        bit[x] += d;
        x += lowbit(x);
    }
}

int sum(int x)
{
    int ans = 0;
    while(x > 0)
    {
        ans += bit[x];
        x -= lowbit(x);
    }
    return ans;
}

void clear(int x)
{
    while(x < M)
    {
        bit[x] = 0;
        x += lowbit(x);
    }
}

void cdq(int L,int R)
{
    if(L >= R) return;
    int mid = (L + R) >> 1;
    cdq(L,mid);
    cdq(mid + 1,R);
    int l = L,r = mid + 1,o = L;

    while(l <= mid && r <= R)
    {
        if(query[l] < query[r])
        {
            if(query[l].t == 0)
                add(query[l].y,1);
            tmp[o++] = query[l++];
        }
        else
        {
            if(query[r].t == 1)
                ans += sum(query[r].y) * query[r].w;
            tmp[o++] = query[r++];
        }
    }

    while(l <= mid)
        tmp[o++] = query[l++];

    while(r <= R)
    {
        if(query[r].t == 1)
            ans += sum(query[r].y) * query[r].w;
        tmp[o++] = query[r++];
    }

    for(int i = L;i <= R; ++i)
    {
        if(query[i].t == 0)
            clear(query[i].y);
        query[i] = tmp[i];
    }
}

ll solve()
{
    sort(s,s + n);
    int idx = 0;
    for(int i = 0;i < n; ++i)
    {
        Node &e = s[i];
        int u1 = e.x - e.r,v1 = max(1,e.f - k);
        int u2 = e.x + e.r,v2 = e.f + k;
        query[idx++] = Query{1,u1 - 1,v1 - 1,1};
        query[idx++] = Query{1,u1 - 1,v2,-1};
        query[idx++] = Query{1,u2,v1 - 1,-1};
        query[idx++] = Query{1,u2,v2,1};
        query[idx++] = Query{0,e.x,e.f,0};
    }
    ans = 0;
    cdq(0,idx - 1);
    return ans;
}

int main()
{
    scanf("%d%d",&n,&k);
    for(int i = 0;i < n; ++i)
        scanf("%d%d%d",&s[i].x,&s[i].r,&s[i].f);
    printf("%lld\n",solve());
    return 0;
}


#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
const int INF = 0x3f3f3f3f;
const int N = 100005;
const int M = 1015;

struct Node
{
    int x,r,f;
    bool operator < (const Node& p) const {
        return r > p.r;
    }
}s[N];

struct Query
{
    int t,x,y,w;
    bool operator < (const Query &p) const {
        return x == p.x ? t < p.t : x < p.x;
    }
}query[N * 5],tmp[N * 5];

int n,k;
ll ans;
int bit[N];

int lowbit(int x)
{
    return x & (-x);
}

void add(int x,int d)
{
    while(x < M)
    {
        bit[x] += d;
        x += lowbit(x);
    }
}

int sum(int x)
{
    int ans = 0;
    while(x > 0)
    {
        ans += bit[x];
        x -= lowbit(x);
    }
    return ans;
}

void clear(int x)
{
    while(x < M)
    {
        bit[x] = 0;
        x += lowbit(x);
    }
}

void cdq(int L,int R)
{
    if(L >= R) return;
    int mid = (L + R) >> 1;
    cdq(L,mid);
    cdq(mid + 1,R);
    int l = L,r = mid + 1,o = L;

    while(l <= mid && r <= R)
    {
        if(query[l] < query[r])
        {
            if(query[l].t == 0)
                add(query[l].y,1);
            tmp[o++] = query[l++];
        }
        else
        {
            if(query[r].t == 1)
                ans += sum(query[r].y) * query[r].w;
            tmp[o++] = query[r++];
        }
    }

    while(l <= mid)
        tmp[o++] = query[l++];

    while(r <= R)
    {
        if(query[r].t == 1)
            ans += sum(query[r].y) * query[r].w;
        tmp[o++] = query[r++];
    }

    for(int i = L;i <= R; ++i)
    {
        if(query[i].t == 0)
            clear(query[i].y);
        query[i] = tmp[i];
    }
}

int solve()
{
    sort(s,s + n);
    int idx = 0;
    for(int i = 0;i < n; ++i)
    {
        Node &e = s[i];
        int u1 = e.x - e.r,v1 = max(1,e.f - k);
        int u2 = e.x + e.r,v2 = e.f + k;
        query[idx++] = Query{1,u1 - 1,v1 - 1,1};
        query[idx++] = Query{1,u1 - 1,v2,-1};
        query[idx++] = Query{1,u2,v1 - 1,-1};
        query[idx++] = Query{1,u2,v2,1};
        query[idx++] = Query{0,e.x,e.f,0};
    }
    ans = 0;
    cdq(0,idx - 1);
    return ans;
}

int main()
{
    scanf("%d%d",&n,&k);
    for(int i = 0;i < n; ++i)
        scanf("%d%d%d",&s[i].x,&s[i].r,&s[i].f);
    printf("%lld\n",solve());
    return 0;
}


#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <cctype>
#include <cmath>
#include <vector>
#include <queue>
#include <set>
#include <map>

using namespace std;
typedef long long ll;
const int MAXN = 100010;
const int MAXF = 10020;

int n, k;

struct Item { // 每个点的信息
    int r, x, f;
    bool operator<( const Item &rhs ) const {
        return r > rhs.r; // 按照r值排序
    }
}item[MAXN];

inline int lowbit( int num ) { return num&(-num); }
namespace BIT { // 树状数组相关
    int c[MAXF] = {0};
    void add( int x, int v ) {
        for( ; x <= MAXF-1; x += lowbit(x) )
            c[x] += v;
    }
    int query( int x ) {
        int sum = 0;
        for( ; x; x -= lowbit(x) )
            sum += c[x];
        return sum;
    }
    int query( int l, int r ) {
        return query(r) - query(l-1);
    }
    void clear( int x ) {
        for( ; x <= MAXF-1; x += lowbit(x) )
            c[x] = 0;
    }
}

struct Query {
    int type, x, y, w;
    // type == 1 表示查询 type == 0 表示修改
    // w 表示查询对答案的贡献，为1或-1
    bool operator<( const Query &rhs ) const {
        if( x == rhs.x ) return type < rhs.type;
        return x < rhs.x;
    }
}query[MAXN*5], tmp[MAXN*5]; int qidx = 0;

ll ans = 0;

void cdq( int L, int R ) { // cdq分治主过程
    if( R-L <= 1 ) return;
    int M = (L+R)>>1; cdq(L,M); cdq(M,R);
    int p = L, q = M, o = L;
    while( p < M && q < R ) {
        if( query[p] < query[q] ) {
            if( query[p].type == 0 ) BIT::add( query[p].y, 1 );
            tmp[o++] = query[p++];
        } else {
            if( query[q].type == 1 ) ans += BIT::query( query[q].y ) * query[q].w;
            tmp[o++] = query[q++];
        }
    }
    while( p < M ) tmp[o++] = query[p++];
    while( q < R ) {
        if( query[q].type == 1 ) ans += BIT::query( query[q].y ) * query[q].w;
        tmp[o++] = query[q++];
    }
    for( int i = L; i < R; ++i ) {
        if( query[i].type == 0 ) BIT::clear( query[i].y );
        query[i] = tmp[i];
    }
}

int main() {
    scanf( "%d%d", &n, &k );
    for( int i = 0; i < n; ++i )
        scanf( "%d%d%d", &item[i].x, &item[i].r, &item[i].f );
    sort( item, item+n );
    for( int i = 0; i < n; ++i ) {
        Item &it = item[i]; // 转化为平面上的添加和查询问题
        int x1 = it.x-it.r, y1 = max( it.f-k, 1 );
        int x2 = it.x+it.r, y2 = it.f+k;
        query[qidx++] = (Query){ 1, x1-1, y1-1, 1 };
        query[qidx++] = (Query){ 1, x1-1, y2, -1 };
        query[qidx++] = (Query){ 1, x2, y1-1, -1 };
        query[qidx++] = (Query){ 1, x2, y2, 1 };
        query[qidx++] = (Query){ 0, it.x, it.f, 0 }; // 修改的w值没有意义
    }
    cdq(0,qidx);
    cout << ans << endl;
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<int, int> pii;
typedef pair<int, pii> pipii;
pipii p[100005];

map<int, int> ft[10005];
vector<int> del[100005];
void update(int k, int i, int v){
	for(;i<=1e9;i+=(i&-i)){
		ft[k][i] += v;
		if(ft[k][i] == 0) ft[k].erase(i);
	}
}
int query(int k, int i){
	int res = 0;
	for(;i>0;i-=(i&-i)){
		if(ft[k].count(i)) res+=ft[k][i];
	}
	return res;
}

int main(){
	int n, k;
	scanf("%d%d", &n, &k);
	for(int i=1;i<=n;i++){
		int x, r, f;
		scanf("%d%d%d", &x, &r, &f);
		p[i] = pipii(x, pii(r, f));
	}
	sort(p+1, p+1+n);
	LL ans = 0;

	vector<int> v;
	v.push_back(-2e9-1);
	for(int i=1;i<=n;i++) v.push_back(p[i].first);
	v.push_back(2e9+1);

	for(int i=1;i<=n;i++){
		for(int j=0;j<del[i].size();j++){
			int idx = del[i][j];
			int x = p[idx].first, r = p[idx].second.first, f = p[idx].second.second;
			update(f, x, -1);
		}
		int x = p[i].first, r = p[i].second.first, f = p[i].second.second;
		for(int j=max(1, f-k);j<=min(10000, f+k);j++){
			ans += query(j, x) - query(j, x-r-1);
		}
		update(f, x, 1);
		int nt = lower_bound(v.begin(), v.end(), x+r+1)-v.begin();
		del[nt].push_back(i);
	}
	printf("%lld\n", ans);
}


#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<int, int> pii;
typedef pair<int, pii> pipii;
pipii p[100005];

map<int, int> ft[10005];
vector<int> del[100005];
void update(int k, int i, int v){
	for(;i<=100000;i+=(i&-i)) ft[k][i] += v;
}
int query(int k, int i){
	int res = 0;
	for(;i>0;i-=(i&-i)){
		if(ft[k].count(i)) res+=ft[k][i];
	}
	return res;
}

int main(){
	int n, k;
	scanf("%d%d", &n, &k);
	for(int i=1;i<=n;i++){
		int x, r, f;
		scanf("%d%d%d", &x, &r, &f);
		p[i] = pipii(x, pii(r, f));
	}
	sort(p+1, p+1+n);
	LL ans = 0;

	vector<int> v;
	for(int i=1;i<=n;i++) v.push_back(p[i].first);

	for(int i=1;i<=n;i++){
		for(int j=0;j<del[i].size();j++){
			int idx = del[i][j];
			int x = p[idx].first, r = p[idx].second.first, f = p[idx].second.second;
			update(f, x, -1);
		}
		int x = p[i].first, r = p[i].second.first, f = p[i].second.second;
		for(int j=max(1, f-k);j<=min(10000, f+k);j++){
			ans += query(j, x) - query(j, x-r-1);
		}
		update(f, x, 1);

		int nt = lower_bound(v.begin(), v.end(), x+r+1)-v.begin();
		nt++;
		del[nt].push_back(i);
	}
	printf("%lld\n", ans);
}


#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<int, int> pii;
typedef pair<int, pii> pipii;
pipii p[100005];

vector<int> ft[10005];
vector<int> del[100005];
vector<int> idx[10005];

void update(int k, int i, int v){
	for(;i<idx[k].size();i+=(i&-i)){
		ft[k][i] += v;
	}
}
int query(int k, int i){
	int res = 0;
	for(;i>0;i-=(i&-i)){
		res+=ft[k][i];
	}
	return res;
}

int main(){
	int n, k;
	scanf("%d%d", &n, &k);
	for(int i=1;i<=n;i++){
		int x, r, f;
		scanf("%d%d%d", &x, &r, &f);
		p[i] = pipii(x, pii(r, f));
		idx[f].push_back(x);
	}
	for(int i=1;i<=10000;i++) idx[i].push_back(-2e9-2), idx[i].push_back(2e9+2), sort(idx[i].begin(), idx[i].end()), ft[i].resize(idx[i].size()+1);
	sort(p+1, p+1+n);
	LL ans = 0;

	vector<int> v;
	v.push_back(-2e9-1);
	for(int i=1;i<=n;i++) v.push_back(p[i].first);
	v.push_back(2e9+1);

	for(int i=1;i<=n;i++){
		for(int j=0;j<del[i].size();j++){
			int id = del[i][j];
			int x = p[id].first, r = p[id].second.first, f = p[id].second.second;
			int ix = lower_bound(idx[f].begin(), idx[f].end(), x) - idx[f].begin();
			update(f, ix, -1);
		}
		int x = p[i].first, r = p[i].second.first, f = p[i].second.second;
		for(int j=max(1, f-k);j<=min(10000, f+k);j++){

			int ix1 = upper_bound(idx[j].begin(), idx[j].end(), x) - idx[j].begin();
			ix1--;
			int ix2 = upper_bound(idx[j].begin(), idx[j].end(), x-r-1) - idx[j].begin();
			ix2--;

			ans += query(j, ix1) - query(j, ix2);
		}

		int ix = lower_bound(idx[f].begin(), idx[f].end(), x) - idx[f].begin();
		update(f, ix, 1);

		int nt = lower_bound(v.begin(), v.end(), x+r+1)-v.begin();
		del[nt].push_back(i);
	}
	printf("%lld\n", ans);
}


#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<int, int> pii;
typedef pair<int, pii> pipii;
pipii p[100005];

unordered_map<int, int> ft[10005];
vector<int> del[100005];
void update(int k, int i, int v){
	for(;i<=1e9;i+=(i&-i)){
		ft[k][i] += v;
		if(ft[k][i] == 0) ft[k].erase(i);
	}
}
int query(int k, int i){
	int res = 0;
	for(;i>0;i-=(i&-i)){
		if(ft[k].count(i)) res+=ft[k][i];
	}
	return res;
}

int main(){
	int n, k;
	scanf("%d%d", &n, &k);
	for(int i=1;i<=n;i++){
		int x, r, f;
		scanf("%d%d%d", &x, &r, &f);
		p[i] = pipii(x, pii(r, f));
	}
	sort(p+1, p+1+n);
	LL ans = 0;

	vector<int> v;
	v.push_back(-2e9-1);
	for(int i=1;i<=n;i++) v.push_back(p[i].first);
	v.push_back(2e9+1);

	for(int i=1;i<=n;i++){
		for(int j=0;j<del[i].size();j++){
			int idx = del[i][j];
			int x = p[idx].first, r = p[idx].second.first, f = p[idx].second.second;
			update(f, x, -1);
		}
		int x = p[i].first, r = p[i].second.first, f = p[i].second.second;
		for(int j=max(1, f-k);j<=min(10000, f+k);j++){
			ans += query(j, x) - query(j, x-r-1);
		}
		update(f, x, 1);
		int nt = lower_bound(v.begin(), v.end(), x+r+1)-v.begin();
		del[nt].push_back(i);
	}
	printf("%lld\n", ans);
}


#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<int, int> pii;
typedef pair<int, pii> pipii;
pipii p[100005];

map<int, int> ft[10005];
vector<int> del[100005];
void update(int k, int i, int v){
	for(;i<=100000;i+=(i&-i)) ft[k][i] += v;
}
int query(int k, int i){
	int res = 0;
	for(;i>0;i-=(i&-i)){
		if(ft[k].count(i)) res+=ft[k][i];
	}
	return res;
}

int main(){
	int n, k;
	scanf("%d%d", &n, &k);
	for(int i=1;i<=n;i++){
		int x, r, f;
		scanf("%d%d%d", &x, &r, &f);
		p[i] = pipii(x, pii(r, f));
	}
	sort(p+1, p+1+n);
	LL ans = 0;
	for(int i=1;i<=n;i++){
		for(int j=0;j<del[i].size();j++){
			int idx = del[i][j];
			int x = p[idx].first, r = p[idx].second.first, f = p[idx].second.second;
			update(f, x, -1);
		}
		int x = p[i].first, r = p[i].second.first, f = p[i].second.second;
		for(int j=max(1, f-k);j<=min(10000, f+k);j++){
			ans += query(j, x) - query(j, x-r-1);
		}
		update(f, x, 1);
		del[min(n+1, x+r+1)].push_back(i);
	}
	printf("%lld\n", ans);
}


#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<int, int> pii;
typedef pair<int, pii> pipii;
pipii p[100005];

map<int, int> ft[10005];
vector<int> del[100005];
void update(int k, int i, int v){
	for(;i<=100000;i+=(i&-i)) ft[k][i] += v;
}
int query(int k, int i){
	int res = 0;
	for(;i>0;i-=(i&-i)){
		if(ft[k].count(i)) res+=ft[k][i];
	}
	return res;
}

int main(){
	int n, k;
	scanf("%d%d", &n, &k);
	for(int i=1;i<=n;i++){
		int x, r, f;
		scanf("%d%d%d", &x, &r, &f);
		p[i] = pipii(x, pii(r, f));
	}
	sort(p+1, p+1+n);
	LL ans = 0;

	vector<int> v;
	v.push_back(-2e9-1);
	for(int i=1;i<=n;i++) v.push_back(p[i].first);
	v.push_back(2e9+1);

	for(int i=1;i<=n;i++){
		for(int j=0;j<del[i].size();j++){
			int idx = del[i][j];
			int x = p[idx].first, r = p[idx].second.first, f = p[idx].second.second;
			update(f, x, -1);
		}
		int x = p[i].first, r = p[i].second.first, f = p[i].second.second;
		for(int j=max(1, f-k);j<=min(10000, f+k);j++){
			ans += query(j, x) - query(j, x-r-1);
		}
		update(f, x, 1);
		int nt = lower_bound(v.begin(), v.end(), x+r+1)-v.begin();
		del[nt].push_back(i);
	}
	printf("%lld\n", ans);
}


#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<int, int> pii;
typedef pair<int, pii> pipii;
pipii p[100005];

map<int, int> ft[10005];
vector<int> del[100005];
void update(int k, int i, int v){
	for(;i<=1e9;i+=(i&-i)) ft[k][i] += v;
}
int query(int k, int i){
	int res = 0;
	for(;i>0;i-=(i&-i)){
		if(ft[k].count(i)) res+=ft[k][i];
	}
	return res;
}

int main(){
	int n, k;
	scanf("%d%d", &n, &k);
	for(int i=1;i<=n;i++){
		int x, r, f;
		scanf("%d%d%d", &x, &r, &f);
		p[i] = pipii(x, pii(r, f));
	}
	sort(p+1, p+1+n);
	LL ans = 0;

	vector<int> v;
	v.push_back(-2e9-1);
	for(int i=1;i<=n;i++) v.push_back(p[i].first);
	v.push_back(2e9+1);

	for(int i=1;i<=n;i++){
		for(int j=0;j<del[i].size();j++){
			int idx = del[i][j];
			int x = p[idx].first, r = p[idx].second.first, f = p[idx].second.second;
			update(f, x, -1);
		}
		int x = p[i].first, r = p[i].second.first, f = p[i].second.second;
		for(int j=max(1, f-k);j<=min(10000, f+k);j++){
			ans += query(j, x) - query(j, x-r-1);
		}
		update(f, x, 1);
		int nt = lower_bound(v.begin(), v.end(), x+r+1)-v.begin();
		del[nt].push_back(i);
	}
	printf("%lld\n", ans);
}


#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<int, int> pii;
typedef pair<int, pii> pipii;
pipii p[100005];

unordered_map<int, int> ft[10005];
vector<int> del[100005];
void update(int k, int i, int v){
	for(;i<=1e9;i+=(i&-i)){
		ft[k][i] += v;
	}
}
int query(int k, int i){
	int res = 0;
	for(;i>0;i-=(i&-i)){
		res+=ft[k][i];
	}
	return res;
}

int main(){
	int n, k;
	scanf("%d%d", &n, &k);
	for(int i=1;i<=n;i++){
		int x, r, f;
		scanf("%d%d%d", &x, &r, &f);
		p[i] = pipii(x, pii(r, f));
	}
	sort(p+1, p+1+n);
	LL ans = 0;

	vector<int> v;
	v.push_back(-2e9-1);
	for(int i=1;i<=n;i++) v.push_back(p[i].first);
	v.push_back(2e9+1);

	for(int i=1;i<=n;i++){
		for(int j=0;j<del[i].size();j++){
			int idx = del[i][j];
			int x = p[idx].first, r = p[idx].second.first, f = p[idx].second.second;
			update(f, x, -1);
		}
		int x = p[i].first, r = p[i].second.first, f = p[i].second.second;
		for(int j=max(1, f-k);j<=min(10000, f+k);j++){
			ans += query(j, x) - query(j, x-r-1);
		}
		update(f, x, 1);
		int nt = lower_bound(v.begin(), v.end(), x+r+1)-v.begin();
		del[nt].push_back(i);
	}
	printf("%lld\n", ans);
}


//线段树+暴力枚举
#include<bits/stdc++.h>
#define min(a,b) ((a)<(b)?(a):(b))
#define max(a,b) ((a)>(b)?(a):(b))
using namespace std;
char buffer[100001],*S,*T;
inline char read_char()
{
	if(S==T)
	{
		T=(S=buffer)+fread(buffer,1,100001,stdin);
		if(S==T) return EOF;
	}
	return *S++;
}
inline int read_int()
{
	int s=0;
	bool flag=false;
	char c=read_char();
	while(c<'0'||c>'9')
	{
		if(c=='-') flag=true;
		c=read_char();
	}
	while(c>='0'&&c<='9')
	{
		s=(s<<3)+(s<<1)+(c-'0');
		c=read_char();
	}
	return flag?-s:s;
}
const int N=1e5+5;
struct Node
{
	int x,r,f;
}node[N];
bool cmp(Node p,Node q)
{
	return p.r>q.r;
}
const int M=17e6+5;
int ls[M],rs[M],val[M];
int tot;
void modify(int k,int a,int b,int x,int s)
{
	val[k]+=s;
	if(a==b) return;
	int mid=(a+b)>>1;
	if(x<=mid)
	{
		if(!ls[k]) ls[k]=++tot;
		modify(ls[k],a,mid,x,s);
	}
	else
	{
		if(!rs[k]) rs[k]=++tot;
		modify(rs[k],mid+1,b,x,s);
	}
}
typedef long long ll;
ll ans;
void query(int k,int a,int b,int l,int r)
{
	if(l<=a&&b<=r)
	{
		ans+=val[k];
		return;
	}
	int mid=(a+b)>>1;
	if(l<=mid)
	{
		if(!ls[k]) ls[k]=++tot;
		query(ls[k],a,mid,l,r);
	}
	if(r>mid)
	{
		if(!rs[k]) rs[k]=++tot;
		query(rs[k],mid+1,b,l,r);
	}
}
int main()
{
	int n=read_int(),k=read_int();
	for(int i=1;i<=n;i++) node[i].x=read_int(),node[i].r=read_int(),node[i].f=read_int();
	sort(node+1,node+n+1,cmp);
	int F=1e4;
	tot=F;
	int X=1e9;
	for(int i=1;i<=n;i++)
	{
		int lf=max(1,node[i].f-k);
		int rf=min(F,node[i].f+k);
		for(int j=lf;j<=rf;j++) query(j,1,X,node[i].x-node[i].r,node[i].x+node[i].r);
		modify(node[i].f,1,X,node[i].x,1);
	}
	printf("%lld",ans);
	return 0;
}


//线段树+暴力枚举
#include<bits/stdc++.h>
#define min(a,b) ((a)<(b)?(a):(b))
#define max(a,b) ((a)>(b)?(a):(b))
using namespace std;
char buffer[100001],*S,*T;
inline char read_char()
{
	if(S==T)
	{
		T=(S=buffer)+fread(buffer,1,100001,stdin);
		if(S==T) return EOF;
	}
	return *S++;
}
inline int read_int()
{
	int s=0;
	bool flag=false;
	char c=read_char();
	while(c<'0'||c>'9')
	{
		if(c=='-') flag=true;
		c=read_char();
	}
	while(c>='0'&&c<='9')
	{
		s=(s<<3)+(s<<1)+(c-'0');
		c=read_char();
	}
	return flag?-s:s;
}
const int N=1e5+5;
struct Node
{
	int x,r,f;
}node[N];
bool cmp(Node p,Node q)
{
	return p.r>q.r;
}
const int M=17e6+5;
int ls[M],rs[M],val[M];
int tot;
void modify(int k,int a,int b,int x,int s)
{
	val[k]+=s;
	if(a==b) return;
	int mid=(a+b)>>1;
	if(x<=mid)
	{
		if(!ls[k]) ls[k]=++tot;
		modify(ls[k],a,mid,x,s);
	}
	else
	{
		if(!rs[k]) rs[k]=++tot;
		modify(rs[k],mid+1,b,x,s);
	}
}
typedef long long ll;
ll ans;
void query(int k,int a,int b,int l,int r)
{
	if(l<=a&&b<=r)
	{
		ans+=val[k];
		return;
	}
	int mid=(a+b)>>1;
	if(l<=mid&&ls[k]) query(ls[k],a,mid,l,r);
	if(r>mid&&rs[k]) query(rs[k],mid+1,b,l,r);
}
int main()
{
	int n=read_int(),k=read_int();
	for(int i=1;i<=n;i++) node[i].x=read_int(),node[i].r=read_int(),node[i].f=read_int();
	sort(node+1,node+n+1,cmp);
	int F=1e4;
	tot=F;
	int X=1e9;
	for(int i=1;i<=n;i++)
	{
		int lf=max(1,node[i].f-k);
		int rf=min(F,node[i].f+k);
		for(int j=lf;j<=rf;j++) query(j,1,X,node[i].x-node[i].r,node[i].x+node[i].r);
		modify(node[i].f,1,X,node[i].x,1);
	}
	printf("%lld",ans);
	return 0;
}


//后缀线性基
#include<bits/stdc++.h>
#define min(a,b) ((a)<(b)?(a):(b))
#define max(a,b) ((a)>(b)?(a):(b))
using namespace std;
const int N=3e5+5;
const int M=3e5+5;
const int Q=3e5+5;
int End[N<<1],Last[N],Next[N<<1],Len[N<<1],dis[N];
int e;
void addedge(int x,int y,int z)
{
	End[++e]=y;
	Next[e]=Last[x];
	Last[x]=e;
	Len[e]=z;
	End[++e]=x;
	Next[e]=Last[y];
	Last[y]=e;
	Len[e]=z;
}
void dfs(int x,int fa)
{
	for(int i=Last[x];i;i=Next[i])
	{
		int y=End[i];
		if(y!=fa)
		{
			dis[y]=dis[x]^Len[i];
			dfs(y,x);
		}
	}
}
int link[M];
struct query
{
	int x,l,r,id;
}p[Q];
int ans[Q];
bool cmp(query a,query b)
{
	return a.r<b.r;
}
int a[35],t[35];
int main()
{
	int n,m,q;
	scanf("%d%d%d",&n,&m,&q);
	for(int i=1;i<n;i++)
	{
		int u,v,w;
		scanf("%d%d%d",&u,&v,&w);
		addedge(u,v,w);
	}
	dfs(1,0);
	for(int i=1;i<=m;i++)
	{
		int u,v,w;
		scanf("%d%d%d",&u,&v,&w);
		link[i]=dis[u]^dis[v]^w;
	}
	for(int i=1;i<=q;i++)
	{
		int s,t;
		scanf("%d%d%d%d",&s,&t,&p[i].l,&p[i].r);
		p[i].x=dis[s]^dis[t];
		p[i].id=i;
	}
	sort(p+1,p+q+1,cmp);
	int now=1;
	for(int i=1;i<=m;i++)
	{
		int x=link[i];
		int k=i;
		for(int j=30;j>=0;j--)
			if(x&(1<<j))
			{
				if(!a[j])
				{
					a[j]=x;
					t[j]=k;
				}
				else
				{
					if(t[j]<k)
					{
						swap(x,a[j]);
						swap(k,t[j]);
					}
					x^=a[j];
				}
			}
		while(now<=q&&p[now].r==i)
		{
			int x=p[now].x;
			int k=p[now].l;
			for(int j=30;j>=0;j--)
				if(t[j]>=k) x=min(x,x^a[j]);
			ans[p[now++].id]=x;
		}
	}
	for(int i=1;i<=q;i++) printf("%d\n",ans[i]);
	return 0;
}


//线段树+暴力枚举
#include<bits/stdc++.h>
#define min(a,b) ((a)<(b)?(a):(b))
#define max(a,b) ((a)>(b)?(a):(b))
using namespace std;
char buffer[100001],*S,*T;
inline char read_char()
{
	if(S==T)
	{
		T=(S=buffer)+fread(buffer,1,100001,stdin);
		if(S==T) return EOF;
	}
	return *S++;
}
inline int read_int()
{
	int s=0;
	bool flag=false;
	char c=read_char();
	while(c<'0'||c>'9')
	{
		if(c=='-') flag=true;
		c=read_char();
	}
	while(c>='0'&&c<='9')
	{
		s=(s<<3)+(s<<1)+(c-'0');
		c=read_char();
	}
	return flag?-s:s;
}
const int N=1e5+5;
struct Node
{
	int x,r,f;
}node[N];
bool cmp(Node p,Node q)
{
	return p.r>q.r;
}
const int M=17e6+5;
int ls[M],rs[M],val[M];
int tot;
void modify(int k,int a,int b,int x,int s)
{
	val[k]+=s;
	if(a==b) return;
	int mid=(a+b)>>1;
	if(x<=mid)
	{
		if(!ls[k]) ls[k]=++tot;
		modify(ls[k],a,mid,x,s);
	}
	else
	{
		if(!rs[k]) rs[k]=++tot;
		modify(rs[k],mid+1,b,x,s);
	}
}
typedef long long ll;
ll ans;
void query(int k,int a,int b,int l,int r)
{
	if(l<=a&&b<=r)
	{
		ans+=val[k];
		return;
	}
	int mid=(a+b)>>1;
	if(l<=mid)
	{
		if(!ls[k]) ls[k]=++tot;
		query(ls[k],a,mid,l,r);
	}
	if(r>mid)
	{
		if(!rs[k]) rs[k]=++tot;
		query(rs[k],mid+1,b,l,r);
	}
}
int main()
{
	int n,k;
	scanf("%d%d",&n,&k);
	for(int i=1;i<=n;i++) scanf("%d%d%d",&node[i].x,&node[i].r,&node[i].f);
	sort(node+1,node+n+1,cmp);
	int F=1e4;
	tot=F;
	int X=1e9;
	for(int i=1;i<=n;i++)
	{
		int lf=max(1,node[i].f-k);
		int rf=min(F,node[i].f+k);
		for(int j=lf;j<=rf;j++) query(j,1,X,node[i].x-node[i].r,node[i].x+node[i].r);
		modify(node[i].f,1,X,node[i].x,1);
	}
	printf("%lld",ans);
	return 0;
}


#include <bits/stdc++.h>

using namespace std;

int main()
{
    long long t,a,nb;
    cin>>t;
    for(int i=0;i<t;i++)
    {
        int n;
        cin>>n;
        nb=0;
        for(long long i=1;i<=9;i++)
        {
            a=i;
            while(a<=n)
            {
                nb++;
                a=a*10+i;
            }
        }
        cout<<nb<<" "<<endl;
    }
}


#include <bits/stdc++.h>

using namespace std;

int main()
{
    long long t,a,nb=0;
    cin>>t;
    for(int i=0;i<t;i++)
    {
        int n;
        cin>>n;
        for(long long i=1;i<9;i++)
        {
            a=i;
            while(a<n)
            {
                a=a*10+i;
            }
        }
    }
}


#include <bits/stdc++.h>
using namespace std;

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	long open;
	cin>>open;
	while(open--){
	long long n,max=0,rem,minnext;;
	cin>>n;
	long long t=n;
	long minv=10;
	set<int>s;
	long x=1;
	while(n!=0){
		rem=n%10;
		n/=10;
		max++;
		x*=10;

		s.insert(rem);
	}
	x/=10;
	minv=t/x;

	x/=10;

	minnext=t/x;
	minnext=minnext-(minv*10);
	auto itr=s.begin();
	int y=*itr;

    if(t>99){

    	if(y<minv){
    if(minnext<=minv)
    	minv--;
    	}
    }
    else{
    	if(y<minv)
    	minv--;
    }

	long sum=0;
	long min=10;
	if(t<min)
	min=t;

	for(long i=1;i<=min;i++){
		if(i<=minv)
		sum+=max;

		else{
			if(max==1)
			sum+=1;
			else{
				if(i!=10)
		sum+=max-1;
			}
		}
	}
	if(t==1)
	cout<<1<<endl;
	else
	cout<<sum<<endl;
	}

	// your code goes here
	return 0;
}


#include <bits/stdc++.h>
using namespace std;

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	long test;
	cin>>test;
	while(test--){
	long long n,max=0,flag=0,rem;
	cin>>n;
	long long t=n,z=n;
	while(n!=0){
		n/=10;
		max++;
	}
	long minv=10;
	long prev=z%10;
	set<int>s;
	while(z!=0){
		rem=z%10;
		s.insert(rem);
		z/=10;
		if(rem<minv)
		minv=rem;

	}
	long sum=0;
	long min=10;
	if(t<min)
	min=t;

	for(long i=1;i<=min;i++){
		if(i<=minv)
		sum+=max;

		else{
			if(max==1)
			sum+=1;
			else{
				if(i!=10)
		sum+=max-1;
			}
		}
	}
	if(t==1)
	cout<<1<<endl;
	else
	cout<<sum<<endl;
	}

	// your code goes here
	return 0;
}


#include <iostream>
using namespace std;

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	long test;
	cin>>test;
	while(test--){
	long long n,max=0,flag=0,rem;
	cin>>n;
	long long t=n,z=n;
	while(n!=0){
		n/=10;
		max++;
	}
	long minv=9;
	long prev=z%10;
	while(z!=0){
		rem=z%10;
		z/=10;
		if(rem<minv){
		minv=rem;

		}
		if(rem!=prev&&rem<minv)
		flag=1;

	}
	long sum=0;
	long min=10;
	if(t<min)
	min=t;
	for(long i=1;i<=min;i++){
		if(i<minv)
		sum+=max;
		else if(flag==0&&i==minv)
		sum+=max;
		else{
			if(max==1)
			sum+=1;
			else{
				if(i!=10)
		sum+=max-1;
			}
		}
	}
	if(t==1)
	cout<<1<<endl;
	else
	cout<<sum<<endl;
	}

	// your code goes here
	return 0;
}


#include <bits/stdc++.h>
using namespace std;

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	long open;
	cin>>open;
	while(open--){
	long long n,max=0,rem;
	cin>>n;
	long long t=n;
	long minv=10;
	set<int>s;
	long zero=0,zerorem;
	zerorem=n%10;
	while(n!=0){
		rem=n%10;
		n/=10;
		max++;
		if(rem==0)
		zero++;
		if(rem<minv)
		minv=rem;
		s.insert(rem);
	}
	auto itr=s.begin();
	itr++;

	if(zero==1){
		if(zerorem==0){
		if(s.size()==2)
		minv=*itr-1;
		else
		minv=*itr;
		}
	}

	long sum=0;
	long min=10;
	if(t<min)
	min=t;

	for(long i=1;i<=min;i++){
		if(i<=minv)
		sum+=max;

		else{
			if(max==1)
			sum+=1;
			else{
				if(i!=10)
		sum+=max-1;
			}
		}
	}
	if(t==1)
	cout<<1<<endl;
	else
	cout<<sum<<endl;
	}

	// your code goes here
	return 0;
}


#include <bits/stdc++.h>
using namespace std;

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	long test;
	cin>>test;
	while(test--){
	long long n,max=0,rem;
	cin>>n;
	long long t=n;
	long minv=10;
	while(n!=0){
		rem=n%10;
		n/=10;
		max++;
		if(rem<minv)
		minv=rem;
	}
	long sum=0;
	long min=10;
	if(t<min)
	min=t;

	for(long i=1;i<=min;i++){
		if(i<=minv)
		sum+=max;

		else{
			if(max==1)
			sum+=1;
			else{
				if(i!=10)
		sum+=max-1;
			}
		}
	}
	if(t==1)
	cout<<1<<endl;
	else
	cout<<sum<<endl;
	}

	// your code goes here
	return 0;
}


#include <bits/stdc++.h>
using namespace std;

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	long open;
	cin>>open;
	while(open--){
	long long n,max=0,rem;
	cin>>n;
	long long t=n;
	long minv=10;
	set<int>s;
	long x=1;
	while(n!=0){
		rem=n%10;
		n/=10;
		max++;
		x*=10;

		s.insert(rem);
	}
	x/=10;
	minv=t/x;

	auto itr=s.begin();

	if((*itr)<(minv))
	minv--;

	long sum=0;
	long min=10;
	if(t<min)
	min=t;

	for(long i=1;i<=min;i++){
		if(i<=minv)
		sum+=max;

		else{
			if(max==1)
			sum+=1;
			else{
				if(i!=10)
		sum+=max-1;
			}
		}
	}
	if(t==1)
	cout<<1<<endl;
	else
	cout<<sum<<endl;
	}

	// your code goes here
	return 0;
}


#include <bits/stdc++.h>
using namespace std;

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	long open;
	cin>>open;
	while(open--){
	long long n,max=0,rem,minnext=0,flag=0;
	cin>>n;
	long long t=n,z=n;
	long minv=10;
	set<int>s;
	long x=1;
	while(n!=0){
		rem=n%10;
		n/=10;
		max++;
		x*=10;

		s.insert(rem);
	}
	x/=10;
	minv=z;
	if(x!=0){
		minv=z/x;
	}

	while(z!=0){
		rem=z%10;
		z/=10;
		if(rem>minv)
		flag=0;
		if(rem<minv)
		flag=1;
	}

	if(flag==1)
	minv--;

	long sum=0;
	long min=10;
	if(t<min)
	min=t;

	for(long i=1;i<=min;i++){
		if(i<=minv)
		sum+=max;

		else{
			if(max==1)
			sum+=1;
			else{
				if(i!=10)
		sum+=max-1;
			}
		}
	}
	if(t==1)
	cout<<1<<endl;
	else
	cout<<sum<<endl;
	}

	// your code goes here
	return 0;
}


#include <bits/stdc++.h>
using namespace std;

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	long open;
	cin>>open;
	while(open--){
	long long n,max=0,rem;
	cin>>n;
	long long t=n;
	long minv=10;
	while(n!=0){
		rem=n%10;
		n/=10;
		max++;
		if(rem<minv)
		minv=rem;
	}
	long sum=0;
	long min=10;
	if(t<min)
	min=t;

	for(long i=1;i<=min;i++){
		if(i<=minv)
		sum+=max;

		else{
			if(max==1)
			sum+=1;
			else{
				if(i!=10)
		sum+=max-1;
			}
		}
	}
	if(t==1)
	cout<<1<<endl;
	else
	cout<<sum<<endl;
	}

	// your code goes here
	return 0;
}


#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
int main()
{
   int t;
   cin>>t;
   while(t--)
   {
       int n;
       cin>>n;
      int ans=0;
      int base=10;
      int power=0;
      int x=n/base;
      int y=n%base;
      if(x==0)
      cout<<n<<endl;
      else
      {
          while(x!=0)
          {
              ++power;
              base*=10;
              x=n/base;
          }
          base/=10;
          power--;
          y=n%10;
          x=n/base;
           ans+=9;
           if(x!=1)
           {
          for(int i=1;i<=power;i++)
          ans+=9;
           }
          ans+=(x-1);
          if(y>=x)
         ans+=1;
         cout<<ans<<endl;
      }
   }
 return 0;
}


#include <iostream>
#include <string>
using namespace std;
int main()
{
   long long int t;
   cin>>t;

   while(t--)
   {

       int ans=0;
      string s;
      cin>>s;
      int c=stoi(s);
      int l=s.length();
      int power=l-1;
      ans+=9*power;
      ans+=((s[0]-'0')-1);

string str;
for(int i=0;i<l;i++)
str[i]=s[0];
int d=stoi(str);
if(c-d>=0)
ans+=1;
cout<<ans<<endl;

   }
 return 0;
}


#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
int main()
{
   long long int t;
   cin>>t;

   while(t--)
   {
         bool f =true;
       int ans=0;
      string s;
      cin>>s;
      int l=s.length();
      int power=l-1;
      ans+=9*power;
      ans+=((s[0]-'0')-1);
for(int i=1;i<l;i++)
{
    if(s[i]<s[0])
    {

    f=false;
    break;
    }
}
if(f)
ans+=1;
cout<<ans<<endl;

   }
 return 0;
}


#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
int main()
{
   int t;
   cin>>t;
   while(t--)
   {
       int n;
       cin>>n;
      int ans=0;
      int base=10;
      int power=0;
      int x=n/base;
      int y=n%base;
      if(x==0)
      cout<<n<<endl;
      else
      {
          while(x!=0)
          {
              ++power;
              base*=10;
              x=n/base;
          }
          base/=10;
          power--;
          y=n%10;
          x=n/base;
           ans+=9;
          for(int i=1;i<=power;i++)
          ans+=9;
          ans+=(x-1);
          if(y>=x)
         ans+=1;
         cout<<ans<<endl;
      }
   }
 return 0;
}


#include <iostream>
#include <string>
using namespace std;
int main()
{
   long long int t;
   cin>>t;

   while(t--)
   {
      int c=0;
      int d=0;
       int ans=0;
      string s;
      cin>>s;
      int l=s.length();
      int power=l-1;
      ans+=9*power;
      ans+=((s[0]-'0')-1);

string str(l,s[0]);
 d=stoi(str);
  c=stoi(s);
if(c-d>=0)
ans+=1;
cout<<ans<<endl;

   }
 return 0;
}


#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
int main()
{
   long long int t;
   cin>>t;
   while(t--)
   {
       long long int n;
       cin>>n;
      long long int ans=0;
      long long int base=10;
      long long int power=0;
      long long int x=n/base;
      long long int y=n%base;
      if(x==0)
      cout<<n<<endl;
      else
      {
          while(x!=0)
          {
              ++power;
              base*=10;
              x=n/base;
          }
          base/=10;
          power--;
          y=n%10;
          x=n/base;
           ans+=9;

          ans+=(9*power);

          ans+=(x-1);
          if(y>=x)
         ans+=1;
         cout<<ans<<endl;
      }
   }
 return 0;
}


#include<bits/stdc++.h>

using namespace std;

int main(){
    int t;
    scanf("%d",&t);
    while(t--){
        int n;
        scanf("%d",&n);
        int ans =0;
        int mini = 10;
        while(n>=10){
            ans+=9;
            mini = min(mini,n%10);
            n/=10;
        }
        ans += min(n, mini);
        printf("%d\n",ans);
    }
}


#include<bits/stdc++.h>

using namespace std;

int main(){
    int t;
    scanf("%d",&t);
    while(t--){
        int n;
        scanf("%d",&n);
        int ans =0;
        for(int i=1;i<10;i++){
            int num = 1;
            for (int j=1;j<i;j++){
                num = num*10+1;
            }
            for(int j=1;j<10;j++){
                if(num*j>n)
                    break;
                ans++;
            }
        }
        printf("%d\n", ans);
    }
}


#include<bits/stdc++.h>

using namespace std;

int main(){
    int t;
    scanf("%d",&t);
    while(t--){
        string s;
        cin >> s;
        if(s.size() == 1){
            printf("%c\n",s[0]);
            continue;
        }
        int ans = 9*(s.size()-1);
        int n = s[0]-'0';
        ans+=n;
        bool foo = true;
        for(int i=1;i<s.size();i++){
            if(s[i]-'0' < n){
                ans--;
                break;
            }
        }
        printf("%d\n",ans);
    }
}


#include<bits/stdc++.h>

using namespace std;

int main(){
    int t;
    scanf("%d",&t);
    while(t--){
        int n;
        scanf("%d",&n);
        int ans =0;
        int mini = 10;
        while(n>=10){
            ans+=9;
            mini = min(mini,n%10);
            n/=10;
        }
        if(n>mini){
            ans+=n-1;
        }else{
            ans+=n;
        }
        printf("%d\n",ans);
    }
}


#include<bits/stdc++.h>

using namespace std;

int main(){
    int t;
    scanf("%d",&t);
    while(t--){
        int n;
        scanf("%d",&n);
        int ans =0;
        int prev = 9;
        while(n>=10){
            ans+=9;
            prev = n;
            n/=10;
        }
        ans += min(n, prev % 10);
        printf("%d\n",ans);
    }
}


#include <cstdio>
#include <cstring>

using namespace std;

int main() {

    int t, i, j, k, len, first, cnt = 0;
    bool flag;

    scanf("%d", &t);

    for (i = 0; i < t; i++) {
        char in[11];
        scanf("%s", in);
        len = strlen(in);
        cnt = 0;
        first = in[0] - '0';
        flag = true;

        if (len == 1) {
            cnt += first;
        }
        else {
            cnt += (len-1) * 9;

            for (j = 1; j < len-1; j++) {
                if (in[j] < in[0]) {
                    for (k = 1; k < j; k++) {
                        if (in[k] > in[0]) break;
                    }
                }
                if (k == j) {
                    flag = false;
                    break;
                }
            }

            if (flag) {
                cnt += first;
            } else {
                cnt += first - 1;
            }
        }

        printf("%d\n", cnt);
    }

    return 0;
}


#include <cstdio>
#include <cstring>

using namespace std;

int main() {

    int t, i, j, k, len, first, cnt = 0;
    bool flag;

    scanf("%d", &t);

    for (i = 0; i < t; i++) {
        char in[11];
        scanf("%s", in);
        len = strlen(in);
        cnt = 0;
        first = in[0] - '0';
        flag = true;

        if (len == 1) {
            cnt += first;
        }
        else {
            cnt += (len-1) * 9;

            for (j = 1; j < len; j++) {
                if (in[j] < in[0]) {
                    for (k = 1; k < j; k++) {
                        if (in[k] > in[0]) break;
                    }
                    if (k == j) {
                        flag = false;
                        break;
                    }
                }
            }

            if (flag) {
                cnt += first;
            } else {
                cnt += first - 1;
            }
        }

        printf("%d\n", cnt);
    }

    return 0;
}


#include <cstdio>
#include <cstring>

using namespace std;

int main() {

    int t, i, j, len, first, cnt = 0;
    bool flag = false;

    scanf("%d", &t);

    for (i = 0; i < t; i++) {
        char in[11];
        scanf("%s", in);
        len = strlen(in);
        cnt = 0;
        first = in[0] - '0';
        flag = true;

        if (len == 1) {
            cnt += first;
        }
        else {
            cnt += (len-1) * 9;
            if (in[len-1] >= in[0]) {
                // 이상만되도 ok
                for (j = 1; j < len - 1; j++) {
                    if (in[j] < in[0]) {
                        flag = false;
                        break;
                    }
                }
            }
            else {
                    // 반드시 모두 초과여야함
                    for (j = 1; j < len - 1; j++) {
                        if (in[j] <= in[0]) {
                        flag = false;
                        break;
                    }
                }
            }
            if (flag) {
                cnt += first;
            } else {
                cnt += first - 1;
            }
        }

        printf("%d\n", cnt);
    }

    return 0;
}


#include <cstdio>
#include <cstring>

using namespace std;

int main() {

    int t, i, j, len, first, cnt = 0;

    scanf("%d", &t);

    for (i = 0; i < t; i++) {
        char in[11];
        scanf("%s", in);
        len = strlen(in);
        cnt = 0;
        first = in[0] - '0';

        if (len == 1) {
            cnt += first;
        }
        else {
            cnt += (len-1) * 9;
            for (j = 0; j < len - 1; j++) if (in[j] != in[j+1] && in[j] > in[j+1]) break;
            if (j == len - 1) {
                cnt += first;
            } else {
                cnt += first - 1;
            }
        }

        printf("%d\n", cnt);
    }

    return 0;
}


#include <cstdio>
#include <cstring>

using namespace std;

int main() {

    int t, i, j, len, first, cnt = 0;

    scanf("%d", &t);

    for (i = 0; i < t; i++) {
        char in[11];
        scanf("%s", in);
        len = strlen(in);
        cnt = 0;
        first = in[0] - '0';

        if (len == 1) {
            cnt += first;
        }
        else {
            cnt += (len-1) * 9;
            for (j = 1; j < len; j++) if (in[j-1] != in[j] && in[j] < in[0]) break;
            if (j == len) {
                cnt += first;
            } else {
                cnt += first - 1;
            }
        }

        printf("%d\n", cnt);
    }

    return 0;
}


#include <cstdio>
#include <cstring>

using namespace std;

int main() {

    int t, i, j, len, first, cnt = 0;

    scanf("%d", &t);

    for (i = 0; i < t; i++) {
        char in[11];
        scanf("%s", in);
        len = strlen(in);
        cnt = 0;
        first = in[0] - '0';

        if (len == 1) {
            cnt += first;
        }
        else {
            cnt += (len-1) * 9;
            for (j = 1; j < len; j++) if ( !(j == len-1 && in[j] == '0') && in[j-1] != in[j] && in[j] < in[0]) break;
            if (j == len) {
                cnt += first;
            } else {
                cnt += first - 1;
            }
        }

        printf("%d\n", cnt);
    }

    return 0;
}


    #include<bits/stdc++.h>
#define mdw 1000000007
#define mdd 998244353
#define m18 1e18+1
#define ll long long
#define forr(i,a,n) for(int i=a;i<n;i++)
#define forrll(i,a,n) for(long long i=a;i<n;i++)
#define forrlle(i,a,n) for(long long i=a;i<=n;i++)
#define forrllr(i,n,a) for(long long i=n-1;i>=a;i--)
#define pb push_back
#define vi vector<int>
#define mi unordered_map<int,int>
#define vll vector<long long>
#define vs vector<string>
#define mll unordered_map<long long,long long>
//#define mp make_pair
#define gcd __gcd
#define umap unordered_map
// #define maxe *max_element
// #define mine *min_element
#define lb lower_bound
#define ub upper_bound
#define endll "\n"
 using namespace std;

ll bpo(ll a,ll b) {
    if (b == 0)
        return 1;
    ll res = bpo(a, b / 2);
    if (b % 2)
        return res * res * a;
    else
        return res * res;
}

ll po(ll x,ll y,ll m){
    if(y==0){
        return 1;
    }
    ll temp=po(x,y/2,m);
    if(y%2==0){
        return ((temp%m)*(temp%m))%m;
    }else{
        return (((x%m)*(temp%m))%m*(temp)%m)%m;
    }
}

ll modinverse(ll a,ll m){
    return po(a,m-2,m);
}

ll myncr(int n, int r, int p)
{
   if (r==0)
      return 1;
    ll fac[n+1];
    fac[0] = 1;
    for (ll i=1 ; i<=n; i++)
        fac[i] = fac[i-1]*i%p;

    return (fac[n]* modinverse(fac[r], p) % p *
            modinverse(fac[n-r], p) % p) % p;
}

ll lcm(ll a, ll b){
    return (a*b)/(gcd(a, b));
}
ll max(ll a, ll b){
  if (a > b)
    return a;
  return b;
}
ll min(ll a, ll b){
  if (a < b)
    return a;
  return b;
}

bool comp(pair<pair<int,int>,pair<int,char>>a,pair<pair<int,int>,pair<int,char>>b)
{
   return a.first.first<b.first.first;
}
bool comp1(pair<pair<int,int>,pair<int,char>>a,pair<pair<int,int>,pair<int,char>>b)
{
   return a.second.first<b.second.first;
}
bool comp2(ll a,ll b){
    return a>b;
}

int main()
{

    ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    ll t;
    cin>>t;
    //   t=1;
    while(t--){

    string s;
    cin>>s;
    ll minn=mdw;
    forrll(i,0,s.size())minn=min(minn,s[i]);
    ll a=minn-48;
    if(a==0)a=s[0]-49;
    a+=9*(s.size()-1);
    cout<<a<<endll;

    }
}


    #include<bits/stdc++.h>
#define mdw 1000000007
#define mdd 998244353
#define m18 1e18+1
#define ll long long
#define forr(i,a,n) for(int i=a;i<n;i++)
#define forrll(i,a,n) for(long long i=a;i<n;i++)
#define forrlle(i,a,n) for(long long i=a;i<=n;i++)
#define forrllr(i,n,a) for(long long i=n-1;i>=a;i--)
#define pb push_back
#define vi vector<int>
#define mi unordered_map<int,int>
#define vll vector<long long>
#define vs vector<string>
#define mll unordered_map<long long,long long>
//#define mp make_pair
#define gcd __gcd
#define umap unordered_map
// #define maxe *max_element
// #define mine *min_element
#define lb lower_bound
#define ub upper_bound
#define endll "\n"
 using namespace std;

ll bpo(ll a,ll b) {
    if (b == 0)
        return 1;
    ll res = bpo(a, b / 2);
    if (b % 2)
        return res * res * a;
    else
        return res * res;
}

ll po(ll x,ll y,ll m){
    if(y==0){
        return 1;
    }
    ll temp=po(x,y/2,m);
    if(y%2==0){
        return ((temp%m)*(temp%m))%m;
    }else{
        return (((x%m)*(temp%m))%m*(temp)%m)%m;
    }
}

ll modinverse(ll a,ll m){
    return po(a,m-2,m);
}

ll myncr(int n, int r, int p)
{
   if (r==0)
      return 1;
    ll fac[n+1];
    fac[0] = 1;
    for (ll i=1 ; i<=n; i++)
        fac[i] = fac[i-1]*i%p;

    return (fac[n]* modinverse(fac[r], p) % p *
            modinverse(fac[n-r], p) % p) % p;
}

ll lcm(ll a, ll b){
    return (a*b)/(gcd(a, b));
}
ll max(ll a, ll b){
  if (a > b)
    return a;
  return b;
}
ll min(ll a, ll b){
  if (a < b)
    return a;
  return b;
}

bool comp(pair<pair<int,int>,pair<int,char>>a,pair<pair<int,int>,pair<int,char>>b)
{
   return a.first.first<b.first.first;
}
bool comp1(pair<pair<int,int>,pair<int,char>>a,pair<pair<int,int>,pair<int,char>>b)
{
   return a.second.first<b.second.first;
}
bool comp2(ll a,ll b){
    return a>b;
}

int main()
{

    ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    ll t;
    cin>>t;
    //   t=1;
    while(t--){

    string s;
    cin>>s;
    ll minn=mdw;
    forrll(i,0,s.size())minn=min(minn,s[i]);
    ll a=minn-48;
    a+=9*(s.size()-1);
    cout<<a<<endll;

    }
}


    #include<bits/stdc++.h>
#define mdw 1000000007
#define mdd 998244353
#define m18 1e18+1
#define ll long long
#define forr(i,a,n) for(int i=a;i<n;i++)
#define forrll(i,a,n) for(long long i=a;i<n;i++)
#define forrlle(i,a,n) for(long long i=a;i<=n;i++)
#define forrllr(i,n,a) for(long long i=n-1;i>=a;i--)
#define pb push_back
#define vi vector<int>
#define mi unordered_map<int,int>
#define vll vector<long long>
#define vs vector<string>
#define mll unordered_map<long long,long long>
//#define mp make_pair
#define gcd __gcd
#define umap unordered_map
// #define maxe *max_element
// #define mine *min_element
#define lb lower_bound
#define ub upper_bound
#define endll "\n"
 using namespace std;

ll bpo(ll a,ll b) {
    if (b == 0)
        return 1;
    ll res = bpo(a, b / 2);
    if (b % 2)
        return res * res * a;
    else
        return res * res;
}

ll po(ll x,ll y,ll m){
    if(y==0){
        return 1;
    }
    ll temp=po(x,y/2,m);
    if(y%2==0){
        return ((temp%m)*(temp%m))%m;
    }else{
        return (((x%m)*(temp%m))%m*(temp)%m)%m;
    }
}

ll modinverse(ll a,ll m){
    return po(a,m-2,m);
}

ll myncr(int n, int r, int p)
{
   if (r==0)
      return 1;
    ll fac[n+1];
    fac[0] = 1;
    for (ll i=1 ; i<=n; i++)
        fac[i] = fac[i-1]*i%p;

    return (fac[n]* modinverse(fac[r], p) % p *
            modinverse(fac[n-r], p) % p) % p;
}

ll lcm(ll a, ll b){
    return (a*b)/(gcd(a, b));
}
ll max(ll a, ll b){
  if (a > b)
    return a;
  return b;
}
ll min(ll a, ll b){
  if (a < b)
    return a;
  return b;
}

bool comp(pair<pair<int,int>,pair<int,char>>a,pair<pair<int,int>,pair<int,char>>b)
{
   return a.first.first<b.first.first;
}
bool comp1(pair<pair<int,int>,pair<int,char>>a,pair<pair<int,int>,pair<int,char>>b)
{
   return a.second.first<b.second.first;
}
bool comp2(ll a,ll b){
    return a>b;
}

int main()
{

    ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    ll t;
    cin>>t;
    //   t=1;
    while(t--){

    string s,s1;
    cin>>s;
    forrll(i,0,s.size())s1.pb(s[0]);
    if(s1>s){
        s1.clear();
        forrll(i,0,s.size()-1)s1.pb('9');
        if(s[0]!='1'){s[0]--;s1=s[0]+s1;}
    }
    ll a=s1[0]-48;
    a+=9*(s1.size()-1);
    cout<<a<<endll;

    }
}


    #include<bits/stdc++.h>
#define mdw 1000000007
#define mdd 998244353
#define m18 1e18+1
#define ll long long
#define forr(i,a,n) for(int i=a;i<n;i++)
#define forrll(i,a,n) for(long long i=a;i<n;i++)
#define forrlle(i,a,n) for(long long i=a;i<=n;i++)
#define forrllr(i,n,a) for(long long i=n-1;i>=a;i--)
#define pb push_back
#define vi vector<int>
#define mi unordered_map<int,int>
#define vll vector<long long>
#define vs vector<string>
#define mll unordered_map<long long,long long>
//#define mp make_pair
#define gcd __gcd
#define umap unordered_map
// #define maxe *max_element
// #define mine *min_element
#define lb lower_bound
#define ub upper_bound
#define endll "\n"
 using namespace std;

ll bpo(ll a,ll b) {
    if (b == 0)
        return 1;
    ll res = bpo(a, b / 2);
    if (b % 2)
        return res * res * a;
    else
        return res * res;
}

ll po(ll x,ll y,ll m){
    if(y==0){
        return 1;
    }
    ll temp=po(x,y/2,m);
    if(y%2==0){
        return ((temp%m)*(temp%m))%m;
    }else{
        return (((x%m)*(temp%m))%m*(temp)%m)%m;
    }
}

ll modinverse(ll a,ll m){
    return po(a,m-2,m);
}

ll myncr(int n, int r, int p)
{
   if (r==0)
      return 1;
    ll fac[n+1];
    fac[0] = 1;
    for (ll i=1 ; i<=n; i++)
        fac[i] = fac[i-1]*i%p;

    return (fac[n]* modinverse(fac[r], p) % p *
            modinverse(fac[n-r], p) % p) % p;
}

ll lcm(ll a, ll b){
    return (a*b)/(gcd(a, b));
}
ll max(ll a, ll b){
  if (a > b)
    return a;
  return b;
}
ll min(ll a, ll b){
  if (a < b)
    return a;
  return b;
}

bool comp(pair<pair<int,int>,pair<int,char>>a,pair<pair<int,int>,pair<int,char>>b)
{
   return a.first.first<b.first.first;
}
bool comp1(pair<pair<int,int>,pair<int,char>>a,pair<pair<int,int>,pair<int,char>>b)
{
   return a.second.first<b.second.first;
}
bool comp2(ll a,ll b){
    return a>b;
}

int main()
{

    ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    ll t;
    cin>>t;
    //   t=1;
    while(t--){

    string s;
    cin>>s;
    ll minn=mdw;
    forrll(i,0,s.size())minn=min(minn,s[i]);
    ll a=minn-48;
    if(a<s[0]-48)a=s[0]-49;
    a+=9*(s.size()-1);
    cout<<a<<endll;

    }
}


    #include<bits/stdc++.h>
#define mdw 1000000007
#define mdd 998244353
#define m18 1e18+1
#define ll long long
#define forr(i,a,n) for(int i=a;i<n;i++)
#define forrll(i,a,n) for(long long i=a;i<n;i++)
#define forrlle(i,a,n) for(long long i=a;i<=n;i++)
#define forrllr(i,n,a) for(long long i=n-1;i>=a;i--)
#define pb push_back
#define vi vector<int>
#define mi unordered_map<int,int>
#define vll vector<long long>
#define vs vector<string>
#define mll unordered_map<long long,long long>
//#define mp make_pair
#define gcd __gcd
#define umap unordered_map
// #define maxe *max_element
// #define mine *min_element
#define lb lower_bound
#define ub upper_bound
#define endll "\n"
 using namespace std;

ll bpo(ll a,ll b) {
    if (b == 0)
        return 1;
    ll res = bpo(a, b / 2);
    if (b % 2)
        return res * res * a;
    else
        return res * res;
}

ll po(ll x,ll y,ll m){
    if(y==0){
        return 1;
    }
    ll temp=po(x,y/2,m);
    if(y%2==0){
        return ((temp%m)*(temp%m))%m;
    }else{
        return (((x%m)*(temp%m))%m*(temp)%m)%m;
    }
}

ll modinverse(ll a,ll m){
    return po(a,m-2,m);
}

ll myncr(int n, int r, int p)
{
   if (r==0)
      return 1;
    ll fac[n+1];
    fac[0] = 1;
    for (ll i=1 ; i<=n; i++)
        fac[i] = fac[i-1]*i%p;

    return (fac[n]* modinverse(fac[r], p) % p *
            modinverse(fac[n-r], p) % p) % p;
}

ll lcm(ll a, ll b){
    return (a*b)/(gcd(a, b));
}
ll max(ll a, ll b){
  if (a > b)
    return a;
  return b;
}
ll min(ll a, ll b){
  if (a < b)
    return a;
  return b;
}

bool comp(pair<pair<int,int>,pair<int,char>>a,pair<pair<int,int>,pair<int,char>>b)
{
   return a.first.first<b.first.first;
}
bool comp1(pair<pair<int,int>,pair<int,char>>a,pair<pair<int,int>,pair<int,char>>b)
{
   return a.second.first<b.second.first;
}
bool comp2(ll a,ll b){
    return a>b;
}

int main()
{

    ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    ll t;
    cin>>t;
    //   t=1;
    while(t--){

    string s;
    cin>>s;
    ll minn=mdw;
    forrll(i,0,s.size()-1)minn=min(minn,s[i]);
    if(minn==mdw)minn=s[0];
    ll a=minn-48;
    a+=9*(s.size()-1);
    cout<<a<<endll;

    }
}


#include <bits/stdc++.h>
#define ll long long int

using namespace std;

int main()
{
    ll t;
    cin>>t;
    while(t--)
    {
       string ss;
       cin>>ss;
       ll l=ss.length();
       ll ans=0,f=0,f1=0;
       if(ss[1]>ss[0])
       {
           f1=1;
       }
       ll sum=0;
       vector<char>v;
       for(ll i=1;i<l;i++)
       {
           if(ss[i]==ss[0])
           {
               v.push_back(ss[i]);
           }
       }
       ll len=v.size()+1;
       if(len==l)
       {
           f=1;
       }
      // cout<<9*(l-1)<< " "<<(ss[0]-'0')<< " ";
       ans=9*(l-1)+(ss[0]-'0')-1;
       if(f || f1)
       {
           ans++;
       }

       cout<<ans<<endl;
       /* string s;cin>>s;
        int n = s.length();
        int ans = 9 * (n-1);
       // cout<<ans<< " ";
        int ex = s[0] - '0'-1;
        //cout<<ex<< " ";
        bool cond = true;
        //cout<<cond<< " ";
        //cout<<endl;
        for(int i = 1 ; i < n ; i++)
        {
            if(s[i] > s[0])
                break;
            else if(s[i] < s[0])
            {
                cond = false;
                break;
            }
        }
       // cout<<cond<< " ";
        cout<<ans + ex + cond<<endl;*/
    }
    return 0;
}


#include <bits/stdc++.h>
#define ll long long int

using namespace std;

int main()
{
    ll t;
    cin>>t;
    while(t--)
    {
       string ss;
       cin>>ss;
       ll l=ss.length();
       ll ans=0,f=0;
       for(ll i=1;i<l-1;i++)
       {
           if((ss[i]-'0')<(ss[0]-'0'))
           {
               f=1;
               break;
           }
       }
       ans=9*(l-1)+(ss[0]-'0');
       if(f)
       {
           ans=ans-1;
       }

       cout<<ans<<endl;
    }
    return 0;
}


#include <bits/stdc++.h>
#define ll long long int

using namespace std;

int main()
{
    ll t;
    cin>>t;
    while(t--)
    {
       string ss;
       cin>>ss;
       ll l=ss.length();
       ll ans=0,f=0;
       for(ll i=0;i<l-1;i++)
       {
           if((ss[i+1]-'0')<(ss[i]-'0'))
           {
               f=1;
               break;
           }
       }
       if(f)
       {
           ans=9*(l-1)+(ss[0]-'0')-1;
       }
       else
       {
           ans=9*(l-1)+(ss[0]-'0');
       }

       cout<<ans<<endl;
    }
    return 0;
}


#include <bits/stdc++.h>
#define ll long long int

using namespace std;

int main()
{
    ll t;
    cin>>t;
    while(t--)
    {
       string ss;
       cin>>ss;
       ll l=ss.length();
       ll ans=0,f=0;
       for(ll i=0;i<l-1;i++)
       {
           if((ss[i+1]-'0')<(ss[i]-'0'))
           {
               f=1;
               break;
           }
       }
       if(f)
       {
           ans=9*(l-1)+(ss[0]-'0')-1;
       }
       else
       {
           ans=9*(l-1)+(ss[0]-'0');
       }
       cout<<ans<<endl;
    }
    return 0;
}


#include <bits/stdc++.h>
#define ll long long int

using namespace std;

int main()
{
    ll t;
    cin>>t;
    while(t--)
    {
       string ss;
       cin>>ss;
       ll l=ss.length();
       ll ans=0,f=0,f1=0;
       if(ss[1]>ss[0])
       {
           f1=1;
       }
       ll sum=0;
       vector<char>v;
       for(ll i=0;i<l;i++)
       {
           if(ss[i]==ss[0])
           {
               v.push_back(ss[i]);
           }
       }
       ll len=v.size();
       if(len==l)
       {
           f=1;
       }
      // cout<<9*(l-1)<< " "<<(ss[0]-'0')<< " ";
       ans=9*(l-1)+(ss[0]-'0')-1;
       if(f || f1)
       {
           ans++;
       }

       cout<<ans<<endl;
       /* string s;cin>>s;
        int n = s.length();
        int ans = 9 * (n-1);
       // cout<<ans<< " ";
        int ex = s[0] - '0'-1;
        //cout<<ex<< " ";
        bool cond = true;
        //cout<<cond<< " ";
        //cout<<endl;
        for(int i = 1 ; i < n ; i++)
        {
            if(s[i] > s[0])
                break;
            else if(s[i] < s[0])
            {
                cond = false;
                break;
            }
        }
       // cout<<cond<< " ";
        cout<<ans + ex + cond<<endl;*/
    }
    return 0;
}


#include <bits/stdc++.h>
#define ll long long int

using namespace std;

int main()
{
    ll t;
    cin>>t;
    while(t--)
    {
       string ss;
       cin>>ss;
       ll l=ss.length();
       ll ans=0,f=0;
       for(ll i=1;i<l;i++)
       {
           if((ss[i]-'0')<(ss[0]-'0'))
           {
               f=1;
               break;
           }
       }
       ans=9*(l-1)+(ss[0]-'0');
       if(f)
       {
           ans=ans-1;
       }

       cout<<ans<<endl;
    }
    return 0;
}


#include <bits/stdc++.h>
#define ll long long int

using namespace std;

int main()
{
    ll t;
    cin>>t;
    while(t--)
    {
       string ss;
       cin>>ss;
       ll l=ss.length();
       ll ans=0,f=0;
       for(ll i=1;i<l;i++)
       {
           if((ss[i]-'0')<(ss[0]-'0'))
           {
               f=1;
               break;
           }
       }
      // cout<<9*(l-1)<< " "<<(ss[0]-'0')<< " ";
       ans=9*(l-1)+(ss[0]-'0')-1;
       if(!f)
       {
           ans++;
       }

       cout<<ans<<endl;
        /*string s;cin>>s;
        int n = s.length();
        int ans = 9 * (n-1);
        cout<<ans<< " ";
        int ex = s[0] - '0'-1;
        cout<<ex<< " ";
        bool cond = true;
        cout<<cond<< " ";
        cout<<endl;
        for(int i = 1 ; i < n ; i++)
        {
            if(s[i] > s[0])
                break;
            else if(s[i] < s[0])
            {
                cond = false;
                break;
            }
        }
        cout<<cond<< " ";
        cout<<ans + ex + cond<<endl;*/
    }
    return 0;
}


#include <bits/stdc++.h>
#define ll long long int

using namespace std;

int main()
{
    ll t;
    cin>>t;
    while(t--)
    {
/*string ss;
       cin>>ss;
       ll l=ss.length();
       ll ans=0,f=0;
       for(ll i=1;i<l;i++)
       {
           if((ss[i]-'0')<(ss[0]-'0'))
           {
               f=1;
               break;
           }
       }
      // cout<<9*(l-1)<< " "<<(ss[0]-'0')<< " ";
       ans=9*(l-1)+(ss[0]-'0')-1;
       if(!f)
       {
           ans++;
       }

       cout<<ans<<endl;*/
        string s;cin>>s;
        int n = s.length();
        int ans = 9 * (n-1);
       // cout<<ans<< " ";
        int ex = s[0] - '0'-1;
        //cout<<ex<< " ";
        bool cond = true;
        //cout<<cond<< " ";
        //cout<<endl;
        for(int i = 1 ; i < n ; i++)
        {
            if(s[i] > s[0])
                break;
            else if(s[i] < s[0])
            {
                cond = false;
                break;
            }
        }
       // cout<<cond<< " ";
        cout<<ans + ex + cond<<endl;
    }
    return 0;
}


#include <bits/stdc++.h>
using namespace std;

typedef long long int ll;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<vi> vvi;
typedef vector<vl> vvl;
typedef vector<string>vst;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef vector<pii> vii;
typedef vector<pll> vll;
typedef map<int,int> dct;

#define fastio ios_base::sync_with_stdio(false);cin.tie(0)
#define all(ct) ct.begin() , ct.end()
#define endl "\n"
#define fr(i,a) for(auto i:a)
#define f(i,a,b) for(int i=a;i<b;++i)
#define fd(i,a,b) for(int i=a;i>=b;--i)
#define pb push_back
#define in(d,v) d.find(v)!=d.end()
#define mp make_pair
#define pi 3.14159265

bool compare(pll a, pll b){
    return (a.first*b.second) < (a.second*b.first);
}

const ll mod = 1e9 + 7;
const ll inf = ll(1e18);

ll modexp(ll x,ll n){
    if(n==0)return 1;
    if(n%2==0)return modexp((x*x)%mod,n/2);
    return (x*modexp((x*x)%mod,n/2))%mod;
}

int main(){
    fastio;
    //clock_t tm = clock();
    int n,m,k,l,r,x,y,t,q;string s;
    cin>>t;
    while(t--){
        cin>>n;
        x=n;
        int ans=0;r=0;
        while(x>0){
            if(x<=9)break;
            ans+=9;
            x/=10;
        }
        int flag=0;
        while(n>0){
            if((n%10)<x)flag=1;
            n/=10;
        }
        ans=ans+x-flag;
        cout<<ans<<endl;
    }
    //cout<<((clock()-tm)*1.0)/CLOCKS_PER_SEC<<endl;
}


#include <bits/stdc++.h>
using namespace std;

typedef long long int ll;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<vi> vvi;
typedef vector<vl> vvl;
typedef vector<string>vst;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef vector<pii> vii;
typedef vector<pll> vll;
typedef map<int,int> dct;

#define fastio ios_base::sync_with_stdio(false);cin.tie(0)
#define all(ct) ct.begin() , ct.end()
#define endl "\n"
#define fr(i,a) for(auto i:a)
#define f(i,a,b) for(int i=a;i<b;++i)
#define fd(i,a,b) for(int i=a;i>=b;--i)
#define pb push_back
#define in(d,v) d.find(v)!=d.end()
#define mp make_pair
#define pi 3.14159265

bool compare(pll a, pll b){
    return (a.first*b.second) < (a.second*b.first);
}

const ll mod = 1e9 + 7;
const ll inf = ll(1e18);

ll modexp(ll x,ll n){
    if(n==0)return 1;
    if(n%2==0)return modexp((x*x)%mod,n/2);
    return (x*modexp((x*x)%mod,n/2))%mod;
}

int main(){
    fastio;
    //clock_t tm = clock();
    int n,m,k,l,r,x,y,t,q;string s;
    cin>>t;
    while(t--){
        cin>>n;
        x=n;
        int ans=0;r=0;
        while(x>0){
            ans++;
            r=r*10+x%10;x/=10;
        }
        ans--;
        ans=ans*9;
        x=r%10;int flag=0;
        while(n>0){
            if(n%10<x)flag=1;
            n/=10;
        }
        //cout<<ans<<endl;
        cout<<ans+x-flag<<endl;
    }
    //cout<<((clock()-tm)*1.0)/CLOCKS_PER_SEC<<endl;
}


#include <bits/stdc++.h>
using namespace std;

typedef long long int ll;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<vi> vvi;
typedef vector<vl> vvl;
typedef vector<string>vst;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef vector<pii> vii;
typedef vector<pll> vll;
typedef map<int,int> dct;

#define fastio ios_base::sync_with_stdio(false);cin.tie(0)
#define all(ct) ct.begin() , ct.end()
#define endl "\n"
#define fr(i,a) for(auto i:a)
#define f(i,a,b) for(int i=a;i<b;++i)
#define fd(i,a,b) for(int i=a;i>=b;--i)
#define pb push_back
#define in(d,v) d.find(v)!=d.end()
#define mp make_pair
#define pi 3.14159265

bool compare(pll a, pll b){
    return (a.first*b.second) < (a.second*b.first);
}

const ll mod = 1e9 + 7;
const ll inf = ll(1e18);

ll modexp(ll x,ll n){
    if(n==0)return 1;
    if(n%2==0)return modexp((x*x)%mod,n/2);
    return (x*modexp((x*x)%mod,n/2))%mod;
}

int main(){
    fastio;
    //clock_t tm = clock();
    int n,m,k,l,r,x,y,t,q;string s;
    cin>>t;
    while(t--){
        cin>>n;
        x=n;
        int ans=0;ll rv=0;
        while(x>0){
            rv=rv*10+x%10;
            if(x<=9)break;
            ans+=9;
            x/=10;
        }
        int flag=0;
        while(n>0){
            if(n%10<x){
                flag=1;
            }
            if(n%10>x)flag=0;
            n/=10;
        }
        ans=ans+x-flag;
        cout<<ans<<endl;
    }
    //cout<<((clock()-tm)*1.0)/CLOCKS_PER_SEC<<endl;
}


#include <bits/stdc++.h>
using namespace std;

typedef long long int ll;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<vi> vvi;
typedef vector<vl> vvl;
typedef vector<string>vst;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef vector<pii> vii;
typedef vector<pll> vll;
typedef map<int,int> dct;

#define fastio ios_base::sync_with_stdio(false);cin.tie(0)
#define all(ct) ct.begin() , ct.end()
#define endl "\n"
#define fr(i,a) for(auto i:a)
#define f(i,a,b) for(int i=a;i<b;++i)
#define fd(i,a,b) for(int i=a;i>=b;--i)
#define pb push_back
#define in(d,v) d.find(v)!=d.end()
#define mp make_pair
#define pi 3.14159265

bool compare(pll a, pll b){
    return (a.first*b.second) < (a.second*b.first);
}

const ll mod = 1e9 + 7;
const ll inf = ll(1e18);

ll modexp(ll x,ll n){
    if(n==0)return 1;
    if(n%2==0)return modexp((x*x)%mod,n/2);
    return (x*modexp((x*x)%mod,n/2))%mod;
}

int main(){
    fastio;
    //clock_t tm = clock();
    int n,m,k,l,r,x,y,t,q;string s;
    cin>>t;
    while(t--){
        cin>>n;
        x=n;
        int ans=0;ll rv=0;
        while(x>0){
            rv=rv*10+x%10;
            if(x<=9)break;
            ans+=9;
            x/=10;
        }
        int flag=0;
        while(rv>0){
            if(rv%10>x)break;
            if(rv%10<x){
                flag=1;break;
            }
            rv/=10;
        }
        ans=ans+x-flag;
        cout<<ans<<endl;
    }
    //cout<<((clock()-tm)*1.0)/CLOCKS_PER_SEC<<endl;
}


#include <bits/stdc++.h>
using namespace std;

typedef long long int ll;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<vi> vvi;
typedef vector<vl> vvl;
typedef vector<string>vst;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef vector<pii> vii;
typedef vector<pll> vll;
typedef map<int,int> dct;

#define fastio ios_base::sync_with_stdio(false);cin.tie(0)
#define all(ct) ct.begin() , ct.end()
#define endl "\n"
#define fr(i,a) for(auto i:a)
#define f(i,a,b) for(int i=a;i<b;++i)
#define fd(i,a,b) for(int i=a;i>=b;--i)
#define pb push_back
#define in(d,v) d.find(v)!=d.end()
#define mp make_pair
#define pi 3.14159265

bool compare(pll a, pll b){
    return (a.first*b.second) < (a.second*b.first);
}

const ll mod = 1e9 + 7;
const ll inf = ll(1e18);

ll modexp(ll x,ll n){
    if(n==0)return 1;
    if(n%2==0)return modexp((x*x)%mod,n/2);
    return (x*modexp((x*x)%mod,n/2))%mod;
}

int main(){
    fastio;
    //clock_t tm = clock();
    ll n,m,k,l,r,x,y,t,q;string s;
    cin>>t;
    while(t--){
        cin>>n;
        x=n;
        ll ans=0;r=0;
        while(x>0){
            ans++;
            if(x<=9)break;
            x/=10;
        }
        ans=max(0ll,ans-1);
        ans=ans*9;
        int flag=0;
        while(n>0){
            if(n%10<x)flag=1;
            n/=10;
        }
        cout<<ans+x-flag<<endl;
    }
    //cout<<((clock()-tm)*1.0)/CLOCKS_PER_SEC<<endl;
}


/**Bismillahir Rahmanir Raheem
    Author:Refat(BSMRSTU)**/
#include<bits/stdc++.h>
using namespace std;

#define ll long long
#define ull unsigned long long
#define ff first
#define ss second
#define pb push_back
#define vi vector<int>
#define pii pair<int,int>
#define pil pair<int,ll>
const int N = 1e5 + 5;
const int M = 1e9 + 7;
const double pi=2*acos(0.0);
const double esp=1e-9;
int Set(int N,int pos) {
    return N=N | (1<<pos);
}
int reset(int N,int pos) {
    return N= N & ~(1<<pos);
}
bool check(int N,int pos) {
    return (bool)(N & (1<<pos));
}
int main() {
    /// freopen("input.txt","r",stdin);
    /// freopen("output.txt","w",stdout);
    int test=1,mn=INT_MAX,ans=0;
    string s;
    scanf("%d",&test);
    for(int cs=1; cs<=test; cs++) {
        cin>>s;
        ans=0;
        int len=(int)s.length();
        mn=INT_MAX;
        if(len==1) {
            cout<<s<<endl;
        } else {
            ans+=(len-2)*9;
            for(int i=1; i<len; i++) {
                mn=min(mn,s[i]-'0');
            }
            if(mn==0&&s[1]<=s[0]) {
                if((s[0]-'0')!=1) {
                    ans+=((s[0]-'0')-1);
                }
            } else {
                if(mn>=s[0]-'0'||s[1]>s[0])
                    ans+=1;
                if((s[0]-'0')!=1) {
                    ans+=((s[0]-'0')-1);
                }
            }
            cout<<ans+9<<endl;
        }
    }
    return 0;
}


/**Bismillahir Rahmanir Raheem
    Author:Refat(BSMRSTU)**/
#include<bits/stdc++.h>
using namespace std;

#define ll long long
#define ull unsigned long long
#define ff first
#define ss second
#define pb push_back
#define vi vector<int>
#define pii pair<int,int>
#define pil pair<int,ll>
const int N = 1e5 + 5;
const int M = 1e9 + 7;
const double pi=2*acos(0.0);
const double esp=1e-9;
int Set(int N,int pos) {
    return N=N | (1<<pos);
}
int reset(int N,int pos) {
    return N= N & ~(1<<pos);
}
bool check(int N,int pos) {
    return (bool)(N & (1<<pos));
}
int main() {
    /// freopen("input.txt","r",stdin);
    /// freopen("output.txt","w",stdout);
    int test=1,mn=INT_MAX,ans=0;
    string s;
    scanf("%d",&test);
    for(int cs=1; cs<=test; cs++) {
        cin>>s;
        ans=0;
        int len=(int)s.length();
        mn=INT_MAX;
        if(len==1) {
            cout<<s[0]-'0'<<endl;
        } else {
            ans+=(len-2)*9;
            for(int i=1; i<len; i++) {
                mn=min(mn,s[i]-'0');
            }
            if(mn==0&&s[1]<=s[0]) {
                if((s[0]-'0')!=1) {
                    ans+=((s[0]-'0')-1);
                }
            } else {
                if(mn>=s[0]-'0'||s[1]>s[0])
                    ans+=1;
                if((s[0]-'0')!=1) {
                    ans+=((s[0]-'0')-1);
                }
            }
            cout<<ans+9<<endl;
        }
    }
    return 0;
}


/**Bismillahir Rahmanir Raheem
    Author:Refat(BSMRSTU)**/
#include<bits/stdc++.h>
using namespace std;

#define ll long long
#define ull unsigned long long
#define ff first
#define ss second
#define pb push_back
#define vi vector<int>
#define pii pair<int,int>
#define pil pair<int,ll>
const int N = 1e5 + 5;
const int M = 1e9 + 7;
const double pi=2*acos(0.0);
const double esp=1e-9;
int Set(int N,int pos) {
    return N=N | (1<<pos);
}
int reset(int N,int pos) {
    return N= N & ~(1<<pos);
}
bool check(int N,int pos) {
    return (bool)(N & (1<<pos));
}
int main() {
    /// freopen("input.txt","r",stdin);
    /// freopen("output.txt","w",stdout);
    int test,mn=INT_MAX,ans=0;
    string s;
    scanf("%d",&test);
    for(int cs=1; cs<=test; cs++) {
        cin>>s;
        ans=0;
        int len=(int)s.length();
        mn=INT_MAX;
        if(len==1) {
            cout<<s[0]-'0'<<endl;
        } else {
            ans+=(len-2)*9;
            for(int i=1; i<len; i++) {
                mn=min(mn,s[i]-'0');
            }
            if(mn==0&&s[1]<=s[0]) {
                if((s[0]-'0')!=1) {
                    ans+=((s[0]-'0')-1);
                }
            } else {
                if(mn>=s[0]-'0'||s[1]>s[0])
                    ans+=1;
                if((s[0]-'0')!=1) {
                    ans+=((s[0]-'0')-1);
                }
            }
            cout<<ans+9<<endl;
        }
    }
    return 0;
}


/**Bismillahir Rahmanir Raheem
    Author:Refat(BSMRSTU)**/
#include<bits/stdc++.h>
using namespace std;

#define ll long long
#define ull unsigned long long
#define ff first
#define ss second
#define pb push_back
#define vi vector<int>
#define pii pair<int,int>
#define pil pair<int,ll>
const int N = 1e5 + 5;
const int M = 1e9 + 7;
const double pi=2*acos(0.0);
const double esp=1e-9;
int Set(int N,int pos) {
    return N=N | (1<<pos);
}
int reset(int N,int pos) {
    return N= N & ~(1<<pos);
}
bool check(int N,int pos) {
    return (bool)(N & (1<<pos));
}
int main() {
    /// freopen("input.txt","r",stdin);
    /// freopen("output.txt","w",stdout);
    int test=1,mn=INT_MAX,ans=0;
    string s;
    scanf("%d",&test);
    for(int cs=1; cs<=test; cs++) {
        cin>>s;
        ans=0;
        mn=INT_MAX;
        if(s.length()==1) {
            cout<<s<<endl;
        } else {
            ans+=((int)s.length()-2)*9;
            for(int i=1; i<(int)s.length(); i++) {
                mn=min(mn,s[i]-'0');
            }
            if(mn==0) {
                if((s[0]-'0')!=1) {
                    ans+=((s[0]-'0')-1);
                }
            } else {
                if(mn>=s[0]-'0')
                    ans+=1;
                if(s[0]-'0'!=1){
                    ans+=(s[0]-'0')-1;
                }
            }
            cout<<ans+9<<endl;
        }
    }
    return 0;
}


/**Bismillahir Rahmanir Raheem
    Author:Refat(BSMRSTU)**/
#include<bits/stdc++.h>
using namespace std;

#define ll long long
#define ull unsigned long long
#define ff first
#define ss second
#define pb push_back
#define vi vector<int>
#define pii pair<int,int>
#define pil pair<int,ll>
const int N = 1e5 + 5;
const int M = 1e9 + 7;
const double pi=2*acos(0.0);
const double esp=1e-9;
int Set(int N,int pos) {
    return N=N | (1<<pos);
}
int reset(int N,int pos) {
    return N= N & ~(1<<pos);
}
bool check(int N,int pos) {
    return (bool)(N & (1<<pos));
}
int main() {
    /// freopen("input.txt","r",stdin);
    /// freopen("output.txt","w",stdout);
    int test,mn=INT_MAX,ans=0;
    string s;
    scanf("%d",&test);
    for(int cs=1; cs<=test; cs++) {
        cin>>s;
        ans=0;
        int len=(int)s.length();
        mn=INT_MAX;
        if(len==1) {
            cout<<s[0]-'0'<<endl;
        } else {
            ans+=(len-2)*9;
            for(int i=1; i<len; i++) {
                mn=min(mn,s[i]-'0');
            }
            if(mn==0&&s[1]<=s[0]) {
                if((s[0]-'0')!=1) {
                    ans+=((s[0]-'0')-1);
                }
            } else {
                if(mn>=(s[0]-'0')||s[1]-'0'>s[0]-'0')
                    ans+=1;
                if((s[0]-'0')!=1) {
                    ans+=((s[0]-'0')-1);
                }
            }
            cout<<ans+9<<endl;
        }
    }
    return 0;
}


/**Bismillahir Rahmanir Raheem
    Author:Refat(BSMRSTU)**/
#include<bits/stdc++.h>
using namespace std;

#define ll long long
#define ull unsigned long long
#define ff first
#define ss second
#define pb push_back
#define vi vector<int>
#define pii pair<int,int>
#define pil pair<int,ll>
const int N = 1e5 + 5;
const int M = 1e9 + 7;
const double pi=2*acos(0.0);
const double esp=1e-9;
int Set(int N,int pos) {
    return N=N | (1<<pos);
}
int reset(int N,int pos) {
    return N= N & ~(1<<pos);
}
bool check(int N,int pos) {
    return (bool)(N & (1<<pos));
}
int main() {
    /// freopen("input.txt","r",stdin);
    /// freopen("output.txt","w",stdout);
    int test=1,mn=INT_MAX,ans=0;
    string s;
    scanf("%d",&test);
    for(int cs=1; cs<=test; cs++) {
        cin>>s;
        ans=0;
        mn=INT_MAX;
        if((int)s.length()==1) {
            cout<<s<<endl;
        } else {
            ans+=((int)s.length()-2)*9;
            for(int i=1; i<(int)s.length(); i++) {
                mn=min(mn,s[i]-'0');
            }
            if(mn==0&&s[1]<=s[0]) {
                if((s[0]-'0')!=1) {
                    ans+=((s[0]-'0')-1);
                }
            } else {
                if(mn>=s[0]-'0'||s[1]>s[0])
                    ans+=1;
                if(s[0]-'0'!=1) {
                    ans+=((s[0]-'0')-1);
                }
            }
            cout<<ans+9<<endl;
        }
    }
    return 0;
}