#include <iostream>

using namespace std;

int
main (int argc, char* argv [])
{
    FILE* fp1;
    FILE* fp2;
    int n1;
    int n2;
    char p1file [64];
    char p2file [64];

    if (argc != 2)
    {
        cerr << "partition <n>" << endl;
        return -1;
    }

    n2 = atoi (argv [1]);
    n1 = n2 - 1;

    sprintf (p1file, "p%d", n1);
    fp1 = fopen (p1file, "r");
    cout << "opening " << p1file << " partition for input " << endl;

    sprintf (p2file, "p%d", n2);
    fp2 = fopen (p2file, "w");
    cout << "opening " << p2file << " partition for output " << endl;

    for (; !feof (fp1); )
    {
        int p1 [100] = {0};
        int i, r, rr;
        int t;
        char str [256] = {0};

        fgets (str, sizeof (str), fp1);

        // load all members into p1

        for (rr = 0, i = 0, r = 0;
             sscanf (str + r, "%d%n", &p1 [i], &rr) == 1;
             i++, r += rr) 
            ;

        t = i; // number of terms

        // skip blank lines

        if (t == 0) continue;

        // now output the partition based on this partition

        for (i = 0; i < t; i++)
        {
            for (int j = 0; j < t; j++)
            {
                fprintf (fp2, "%d ", i == j ? p1 [j] + 1 : p1 [j]);
            }
            
            fprintf (fp2, "\n");
        }
         
        for (int j = 0; j < t; j++)
        {
            fprintf (fp2, "%d ", p1 [j]);
        }
        
        fprintf (fp2, "1 \n");

        fprintf (fp2, "1 ");

        for (int j = 0; j < t; j++)
        {
            fprintf (fp2, "%d ", p1 [j]);
        }

        fprintf (fp2, "\n");
    }

    fclose (fp1);
    fclose (fp2);
}
