using System;
using System.Linq;
using System.Text;
namespace Task3Checkers
{
internal class Program
{
private static void Main(string[] args)
{
Console.OutputEncoding = Encoding.GetEncoding(866);
Console.WriteLine("Число цветов");
var colorsCount = int.Parse(Console.ReadLine());
var colorsBuckets = Enumerable
.Range(0, colorsCount)
.Select(c =>
{
Console.WriteLine($"Число шашек цвета {c + 1}");
return int.Parse(Console.ReadLine());
}).ToList();
var checkersCount = colorsBuckets.Sum();
if (checkersCount > 80 ||
checkersCount < 2)
throw new InvalidOperationException();
Node baseNode = null;
do
{
for (var color = 0; color < colorsCount; color++)
if (colorsBuckets[color] > 0)
{
colorsBuckets[color]--;
var node = new Node(color + 1);
if (baseNode == null)
{
baseNode = node;
node.Next = node;
node.Prev = node;
continue;
}
if (!TryInsertNode(baseNode, node))
{
Console.WriteLine("Ответ: невозможно");
Console.ReadKey();
return;
}
}
} while (colorsBuckets.Any(b => b > 0));
Console.WriteLine("Ответ: возможно");
Console.Write("Пример: -");
var iteratorNode = baseNode;
do
{
Console.Write($"{iteratorNode.Color}-");
iteratorNode = iteratorNode.Next;
} while (iteratorNode != baseNode);
Console.ReadKey();
}
private static bool TryInsertNode(Node baseNode, Node node)
{
var iteratorNode = baseNode;
do
{
var prev = iteratorNode;
iteratorNode = iteratorNode.Next;
var next = iteratorNode;
if (TryInsertNodeBetween(node, prev, next)) return true;
} while (iteratorNode != baseNode);
return false;
}
private static bool TryInsertNodeBetween(Node node, Node prev, Node next)
{
if (node.Color == prev.Color ||
node.Color == next.Color)
return false;
node.Prev = prev;
prev.Next = node;
node.Next = next;
next.Prev = node;
return true;
}
private class Node
{
public readonly int Color;
public Node Next;
public Node Prev;
public Node(int color)
{
Color = color;
}
}
}
}