#include <bits/stdc++.h>
using namespace std;
template <class T>
bool checkmax(T& a, T b) {
  return a < b ? a = b, 1 : 0;
}
template <class T>
bool checkmin(T& a, T b) {
  return a > b ? a = b, 1 : 0;
}
template <class T>
void string_reader(string s, vector<T>& vec) {
  istringstream sin(s);
  copy(istream_iterator<T>(sin), istream_iterator<T>(), back_inserter(vec));
}
const int N = 3001;
int msg[N][N];
struct message {
  int a, b, t;
  bool operator<(const message& msg) const { return t > msg.t; }
  message(int a = 0, int b = 0, int t = 0) : a(a), b(b), t(t) {}
};
struct info {
  string a, b;
  info(string a, string b) : a(a), b(b) {}
};
const int M = 10001;
vector<info> same[M];
map<string, int> name_to_label;
int get_label(string& name, int& cnt) {
  auto iter = name_to_label.find(name);
  if (iter == name_to_label.end()) name_to_label.insert(make_pair(name, cnt++));
  iter = name_to_label.find(name);
  return iter->second;
}
int main() {
  int n, d, cnt, t;
  string a, b;
  while (cin >> n >> d) {
    vector<pair<string, string> > ans;
    priority_queue<message> pq;
    for (int i = 0; i < int(N); ++i) same[i].clear();
    memset(msg, 0, sizeof(msg));
    name_to_label.clear();
    cnt = 0;
    for (int i = 0; i < int(n); ++i) {
      cin >> a >> b >> t;
      same[t].push_back(info(a, b));
    }
    for (int i = 0; i < int(N); ++i) {
      while (pq.empty() == false && i - pq.top().t > d) {
        msg[pq.top().a][pq.top().b]--;
        pq.pop();
      }
      for (auto j : same[i]) {
        a = j.a, b = j.b;
        int idx_a = get_label(a, cnt);
        int idx_b = get_label(b, cnt);
        if (msg[idx_b][idx_a]) ans.push_back(make_pair(min(a, b), max(a, b)));
      }
      for (auto j : same[i]) {
        a = j.a, b = j.b;
        int idx_a = get_label(a, cnt);
        int idx_b = get_label(b, cnt);
        msg[idx_a][idx_b]++;
        pq.push(message(idx_a, idx_b, i));
      }
    }
    sort(ans.begin(), ans.end());
    ans.erase(unique(ans.begin(), ans.end()), ans.end());
    cout << ans.size() << endl;
    for (auto i : ans) cout << i.first << " " << i.second << endl;
  }
  return 0;
}
