Cod sursă (job #558146)

Utilizator avatar VladTZY Tiganila Vlad VladTZY IP ascuns
Problemă Immortal (clasele 9-10) Compilator cpp | 2.31 kb
Rundă Arhiva de probleme Status evaluat
Dată 6 iun. 2020 16:31:31 Scor 100
#include <fstream>
#include <iostream>
#include <algorithm>

#define x first
#define y second
#define NMAX 16

using namespace std;

ifstream f("immortal.in");
ofstream g("immortal.out");

short n, m, players, ended, total;
short a[25][25];

int total_calls;

pair <int, int> v[NMAX];
struct Final{
    short x1, y1, x2, y2;
};
Final out[NMAX];

short dx[] = {-1, 0, 1, 0};
short dy[] = {0, 1, 0, -1};

void backTrack(short left_in_game)
{
    total_calls++;
    if(left_in_game == 1)
    {
        for(short i = 1; i < players; i++)
            g << out[i].x1 << " " << out[i].y1 << " " << out[i].x2 << " " << out[i].y2 << "\n";
        ended = 1;

        return;
    }
    if(ended)
        return;

    for(short i = players; i >= 1; i--)
    {
        if(ended)
            return;

        if(a[v[i].x][v[i].y] == 1)
        {
            for(short dir = 0; dir < 4; dir++)
            {
                short line = v[i].x;
                short col = v[i].y;

                short new_x = line + 2 * dx[dir];
                short new_y = col + 2 * dy[dir];

                if(new_x >= 1 && new_x <= n && new_y >= 1 && new_y <= m && a[new_x][new_y] == 0 && a[new_x - dx[dir]][new_y - dy[dir]] == 1)
                {
                    total++;
                    out[total].x1 = line;
                    out[total].y1 = col;
                    out[total].x2 = new_x;
                    out[total].y2 = new_y;

                    a[line][col] = 0;
                    a[line + dx[dir]][col + dy[dir]] = 0;
                    a[new_x][new_y] = 1;

                    v[i].x = new_x;
                    v[i].y = new_y;

                    backTrack(left_in_game - 1);
                    if(ended)
                        return;

                    total--;
                    v[i].x = line;
                    v[i].y = col;

                    a[line][col] = 1;
                    a[line + dx[dir]][col + dy[dir]] = 1;
                    a[new_x][new_y] = 0;
                }
            }
        }
    }
}

int main()
{
    f >> n >> m >> players;
    for(short i = 1; i <= players; i++)
    {
        f >> v[i].x >> v[i].y;
        a[v[i].x][v[i].y] = 1;
    }

    sort(v + 1, v + 1 + players);
    backTrack(players);
    return 0;
}