Advertisement
Margoshinka

perebor

Oct 30th, 2023
852
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.03 KB | None | 0 0
  1. class Program
  2. {
  3.     static void Main()
  4.     {
  5.         int N; int S;
  6.         int[] numbers;
  7.         using (StreamReader reader = new StreamReader("input.dat"))
  8.         {
  9.             string line;
  10.             line = reader.ReadLine();
  11.             string[] parts = line.Split(' ');
  12.             int.TryParse(parts[0], out N);
  13.             numbers = new int[N];
  14.             int.TryParse(parts[1], out S);
  15.             line = reader.ReadLine();
  16.             parts = line.Split(' ');
  17.             for (int i = 0; i < N; i++)
  18.             {
  19.                 int item;
  20.                 int.TryParse(parts[i], out item);
  21.                 numbers[i] = item;
  22.  
  23.             }
  24.         }
  25.        
  26.         int maxOperations = (int)Math.Pow(2, N - 1);
  27.         using (StreamWriter writer = new StreamWriter("output.dat"))
  28.         {
  29.             for (int i = 0; i < maxOperations; i++)
  30.             {
  31.                 int currentSum = numbers[0];
  32.                 List<char> operators = new List<char>();
  33.  
  34.                 for (int j = 0; j < N - 1; j++)
  35.                 {
  36.                     if ((i & (1 << j)) != 0)
  37.                     {
  38.                         currentSum += numbers[j + 1];
  39.                         operators.Add('+');
  40.                     }
  41.                     else
  42.                     {
  43.                         currentSum -= numbers[j + 1];
  44.                         operators.Add('-');
  45.                     }
  46.                 }
  47.  
  48.                 if (currentSum == S)
  49.                 {
  50.                     string resultExpression = numbers[0].ToString();
  51.                     for (int j = 0; j < N - 1; j++)
  52.                     {
  53.                         resultExpression += " " + operators[j] + " " + numbers[j + 1];
  54.                     }
  55.                     writer.Write(resultExpression + " = " + S);
  56.                     Console.WriteLine(resultExpression + " = " + S);
  57.                     return;
  58.                 }
  59.             }
  60.             writer.Write("No solution");
  61.             Console.WriteLine("No solution");
  62.         }
  63.     }
  64. }
  65.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement