import java.util.Scanner;
class Node{
String address;
String data;
String Nextaddress;
Node next;
public Node() {
this.next = null;
}
public Node(String x, String y, String z) {
this.address = x;
this.data = y;
this.Nextaddress = z;
}
}
public class Main{
static Node creat(String head, String[][] a) {
String p = head;
Node n = new Node();
Node l = n;
while(p.equals("-1") == false) {
for(int i = 0; i < a.length; i ++) {
if(p.equals(a[i][0])) {
p = a[i][2];
Node newnode = new Node(a[i][0], a[i][1], a[i][2]);
n.next = newnode;
n = n.next;
break;
}
}
}
return l;
}
static Node reverse(int k, Node head) {
Node rhead = head;
if(k == 1) {
return head;
}
else {
int i = 0;
while(head.next != null) {
i ++;
head = head.next;
}
head = rhead;
Node pre = head.next;
Node pcur = pre.next;
int reverse = 1;
while(reverse <= i / k && pcur != null) {
Node n = head;
for(int x = 0; x < k + 1; x ++) {
n = n.next;
}
for(int c = 0; c < k - 1; c ++){
if(pcur.next != null) {
pre.next = pcur.next;
pcur.next = head.next;
head.next = pcur;
pcur = pre.next;
}
else {
pre.next = null;
pcur.next = head.next;
head.next = pcur;
pcur = pre.next;
}
}
if(pre.next != null) {
head = pre;
pre = head.next;
pcur = pre.next;
reverse ++;
}
}
head = rhead.next;
while(head.next != null) {
head.Nextaddress = head.next.address;
head = head.next;
}
if(i % k == 0) {
pre.Nextaddress = "-1";
}
return rhead;
}
}
static void print(Node n) {
Node l = n;
while(l.next != null) {
System.out.println(l.next.address + " " + l.next.data + " " + l.next.Nextaddress);
l = l.next;
}
}
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
String head = s.next();
int n = s.nextInt();
int k = s.nextInt();
String[][] a = new String[n][3];
for(int i = 0; i < n; i ++) {
for(int j = 0; j < 3; j ++) {
a[i][j] = s.next();
}
}
Node list = creat(head, a);
Node rlist = reverse(k, list);
print(rlist);
}
}