#include<vector>
#include<iostream>
#include<algorithm>
#include<unordered_map>
#include<set>
#include<map>
#include<cstring>
#include<string>
#include<queue>
#include<array>
#include<stack>
using namespace std;
const int maxn = 100010;
struct Node
{
int address,data,next;
bool flag;
}node[maxn];
bool cmp(Node a, Node b)
{
if (a.flag == false || b.flag == false) {
return a.flag > b.flag;
}
else {
return a.data < b.data;
}
}
int main()
{
for (int i = 0; i < maxn; i++)
{
node[i].flag = false;
}
int n, s1, address, data, next;
cin >> n >> s1;
for (int i = 0; i < n; i++)
{
cin >> address >> data >> next;
node[address].address = address;
node[address].next = next;
node[address].data = data;
}
int p = s1, count = 0;
while (p != -1)
{
node[p].flag = true;
count++;
p = node[p].next;
}
if (count == 0)
{
cout << "0 -1";
}
else
{
sort(node, node + maxn, cmp);
printf("%d %05d
", count, node[0].address);
for (int i = 0; i < count; i++)
{
if (i != count - 1)
{
printf("%05d %d %05d
", node[i].address, node[i].data, node[i + 1].address);
}
else
{
printf("%05d %d -1
", node[i].address, node[i].data);
}
}
}
return 0;
}