#include"stdafx.h"
#include<iostream>
#include<stdlib.h>
#include<string>
#include<iomanip>
#include<stdio.h>
using namespace std;
int main()
{
struct Date
{
int Adress;
int num;
int Next;
struct Date *next;
};
int all, ts, i = 0;
Date*head = (Date*)malloc(sizeof(Date));
Date*p1 = (Date*)malloc(sizeof(Date));
Date*p2 = (Date*)malloc(sizeof(Date));
scanf_s("%d %d %d", &head->Adress, &all,&ts);
while (i != all)
{
Date*p1 = (Date*)malloc(sizeof(Date));
scanf_s("%d %d %d", &p1->Adress, &p1->num, &p1->Next);
if (i == 0)
head->next = p1;
else
p2->next = p1;
p2 = p1;
i++;
}
p2->next = NULL;
Date*temp1 = (Date*)malloc(sizeof(Date));
Date*temp2 = (Date*)malloc(sizeof(Date));
Date*r = (Date*)malloc(sizeof(Date));
Date*p = (Date*)malloc(sizeof(Date));
temp1 = head;
temp2 = temp1->next;
while (temp1 != NULL)
{
while (temp2 != NULL)
{
if (head == temp1&&temp2->Adress == head->Adress)
{
p = temp1;
for (;;)
{
if (p->next == temp2)
{
p->next = temp2->next;
break;
}
else
{
p = p->next;
}
}
r = head->next;
head->next = temp2;
temp2->next = r;
break;
}
else if (temp2->Adress == temp1->Next&&temp2->Next != -1)
{
p = temp1;
for (;;)
{
if (p->next == temp2)
{
p->next = temp2->next;
break;
}
else
{
p = p->next;
}
}
r = temp1->next;
temp1->next = temp2;
temp2->next = r;
break;
}
else if (temp2->Adress == temp1->Next&&temp2->Next == -1)
{
p = temp1;
for (;;)
{
if (p->next == temp2)
{
p->next = temp2->next;
break;
}
else
{
p = p->next;
}
}
temp1->next = temp2;
temp2->next = NULL;
break;
}
else
{
temp2 = temp2->next;
continue;
}
}
if (temp1->next != NULL)
{
temp1 = temp1->next;
temp2 = temp1->next;
}
else
break;
}
int js = 0;
Date*check = (Date*)malloc(sizeof(Date));
check = head->next;
for (;;)
{
if (check->Next != -1)
{
check = check->next;
js++;
}
else if (check->Next == -1)
{
js++;
break;
}
}
int j;
all = js ;
if (ts == 1)
j = 0;
j =all/ ts;
temp1 = head;
temp2 = temp1->next;
i = 0;
for (int l=1; j > 0;l++, j--)
{
while (i != l*(ts-1))
{
temp2 = temp2->next;
i++;
}
p1 = temp2;
r = temp2->next;
p = temp1;
while (p->next != temp2)
{
for (;;)
{
if (p->next == temp2)
{
temp2->next = p;
temp2 = temp2->next;
p = temp1;
break;
}
else
{
p = p->next;
}
}
}
temp2->next = r;
temp1->next = p1;
while (temp1 != temp2)
{
temp1 = temp1->next;
}
if (temp1 == NULL)
break;
else
{
temp2 = temp1->next;
}
}
temp1 = head->next;
temp2 = temp1->next;
head->Adress = head->next->Adress;
for (i = 0; i < all-1 ; i++)
{
temp1->Next = temp2->Adress;
temp1 = temp1->next;
temp2 = temp1->next;
}
if(temp1->next==NULL)
temp1->Next = -1;
Date*out = (Date*)malloc(sizeof(Date));
out = head->next;
while (out != NULL)
{
if (out->Next != -1)
{
cout << setfill('0') << setw(5) << out->Adress << " " << out->num << " " << setfill('0') << setw(5) << out->Next << endl;
out = out->next;
}
else
{
cout << setfill('0') << setw(5) << out->Adress << " " << out->num << " " << out->Next << endl;
out = out->next;
}
}
return 0;
}