#include <iostream>
#include <vector>
#include <map>
#include <cmath>
#include <algorithm>
using namespace std;
struct node {
int adress, value, next;
} nodes[100001];
int main(){
int s, n;
vector<node> v, re;
map<int, int> ma;
cin >> s >> n;
for (int i = 0; i < n; i++) {
int a, b, c;
cin >> a >> b >> c;
nodes[a] = {a, b, c};
}
int head = s;
while (head != -1) {
v.push_back(nodes[head]);
int t = abs(nodes[head].value);
if (ma[t]) {
v.pop_back();
re.push_back(nodes[head]);
}else{
ma[t] = 1;
}
head = nodes[head].next;
}
if (v.size() > 0) {
for (int i = 0; i < v.size(); i++) {
if(i == 0) printf("%05d %d", v[i].adress, v[i].value);
else printf(" %05d\n%05d %d", v[i].adress, v[i].adress, v[i].value);
}
cout << " -1\n";
}
if (re.size() > 0) {
for (int i = 0; i < re.size(); i++) {
if(i == 0) printf("%05d %d", re[i].adress, re[i].value);
else printf(" %05d\n%05d %d", re[i].adress, re[i].adress, re[i].value);
}
cout << " -1\n";
}
return 0;
}