Данные N косточек домино по правилам игры выкладываются в прямую цепочку, начиная с косточки, выбранной произвольно,в оба конца до тех пор, пока это возможно. Построить алгоритм, позволяющий определить такой вариант выкладывания заданных косточек, при котором к моменту, когда цепочка не может быть продолжена, "на руках" останется максимальное число очков. напиши код на c++
Assistant
The provided problem requires implementing an algorithm to determine the optimal way to lay out given domino tiles so that, by the time the chain cannot be extended further, the sum of points (pips) on the remaining tiles (those not used in the chain) is maximized. Essentially, we need to arrange the tiles in such a way that we use the tiles with the smallest total pips possible during the game.
Here's a C++ implementation using dynamic programming with memoization. This approach ensures that we explore all possible combinations of laying out the tiles while storing intermediate results to avoid redundant calculations.
cpp
#include <iostream>
#include <vector>
#include <unordered_map>
#include <tuple>
#include <algorithm>
using namespace std;
// Define a structure to represent a domino tile
struct Tile {
int id; // Unique identifier for the tile
int left; // Number on the left side
int right; // Number on the right side
int pips; // Total pips (left + right)
Tile(int _id, int _left, int _right) : id(_id), left(_left), right(_right) {
pips = left + right;
}
};
// Memoization map to store the results of subproblems
unordered_map<long long, int> memo;
// Function to create a unique key for memoization based on the current state
long long getKey(int head, int tail, long long mask) {
return (static_cast<long long>(head) << 48) | (static_cast<long long>(tail) << 32) | mask;
}
// Recursive DP function
int dp(int head, int tail, long long mask, const vector<Tile>& tiles, int maxNumber) {
if (memo.find(getKey(head, tail, mask)) != memo.end()) {
return memo[getKey(head, tail, mask)];
}
int minPips = INT_MAX;
bool canPlay = false;
for (size_t i = 0; i < tiles.size(); ++i) {
if (mask & (1LL << i)) {
continue; // Tile already used
}
const Tile& tile = tiles[i];
bool played = false;
// Try to match tile at the head
if (tile.left == head || tile.right == head) {
int newHead = (tile.left == head) ? tile.right : tile.left;
int pipsPlayed = tile.pips + dp(newHead, tail, mask | (1LL << i), tiles, maxNumber);
minPips = min(minPips, pipsPlayed);
canPlay = true;
played = true;
}
// Try to match tile at the tail
if (tile.left == tail || tile.right == tail) {
int newTail = (tile.left == tail) ? tile.right : tile.left;
int pipsPlayed = tile.pips + dp(head, newTail, mask | (1LL << i), tiles, maxNumber);
minPips = min(minPips, pipsPlayed);
canPlay = true;
played = true;
}
}
if (!canPlay) {
// No further moves can be made
minPips = 0;
}
memo[getKey(head, tail, mask)] = minPips;
return minPips;
}
int main() {
int N;
cout << "Enter the number of tiles: ";
cin >> N;
vector<Tile> tiles;
int totalPips = 0;
int maxNumber = -1;
cout << "Enter the tiles (left side and right side numbers):" << endl;
for (int i = 0; i < N; ++i) {
int left, right;
cin >> left >> right;
tiles.emplace_back(i, left, right);
totalPips += left + right;
maxNumber = max({maxNumber, left, right});
}
// Initialize memoization map
memo.clear();
// Start from any tile; try all possible starting tiles
int maxRemainingPips = -1;
for (size_t i = 0; i < tiles.size(); ++i) {
long long mask = 1LL << i;
int head = tiles[i].left;
int tail = tiles[i].right;
int pipsPlayed = tiles[i].pips + dp(head, tail, mask, tiles, maxNumber);
int remainingPips = totalPips - pipsPlayed;
if (remainingPips > maxRemainingPips) {
maxRemainingPips = remainingPips;
}
}
cout << "Maximum points remaining in hand: " << maxRemainingPips << endl;
return 0;
}
Explanation:
We represent each tile using the Tile struct, which includes the tile's left and right numbers, total pips, and a unique identifier.
The dp function is our recursive dynamic programming function, which attempts to play tiles from the current state and minimizes the total pips played.
The memo map uses a custom key combining the current head, tail, and mask (which represents the tiles used so far) to store the results of subproblems.
We attempt to start the game with each tile to find the arrangement that results in the maximum remaining pips.
The total pips of all tiles are calculated at the beginning to easily compute the remaining pips after the game ends.
We output the maximum points remaining in hand, which is the maximum total pips of the unused tiles when the chain cannot be extended further.
Note: This implementation assumes that the maximum number on any side of the tile isn't excessively large (since we shift bits to create the memoization key). For larger numbers, you might need to adjust the way the key is generated to avoid overflow or use a different method of memoization.