CodeforcesJul 15, 2025

Vitamins

Hazrat Ali

Codeforces

Each juice includes some set of vitamins in it. There are three types of vitamins: vitamin "A", vitamin "B" and vitamin "C". Each juice can contain one, two or all three types of vitamins in it.

Petya knows that he needs all three types of vitamins to stay healthy. What is the minimum total price of juices that Petya has to buy to obtain all three vitamins? Petya obtains some vitamin if he buys at least one juice containing it and drinks it.

Input

The first line contains a single integer n (1n1000) — the number of juices.

Each of the next n lines contains an integer ci (1ci100000) and a string si — the price of the i-th juice and the vitamins it contains. String si contains from 1 to 3 characters, and the only possible characters are "A", "B" and "C". It is guaranteed that each letter appears no more than once in each string si. The order of letters in strings si is arbitrary.

Output

Print -1 if there is no way to obtain all three vitamins. Otherwise print the minimum total price of juices that Petya has to buy to obtain all three vitamins.

Examples
Input
4
5 C
6 B
16 BAC
4 A
Output
15
Input
2
10 AB
15 BA
Output
-1
Input
5
10 A
9 BC
11 CA
4 A
5 B
Output
13
Input
6
100 A
355 BCA
150 BC
160 AC
180 B
190 CA
Output
250
Input
2
5 BA
11 CB
Output
16

Solution

#include <bits/stdc++.h>
#define INF (int) 1e9
using namespace std;

int main() {
  int n;
  cin >> n;
  vector<int> c(n);
  vector<string> s(n);
  map<string, int> memo;
  memo["A"] = memo["B"] = memo["C"] = INF;
  memo["AB"] = memo["AC"] = memo["BC"] = INF;
  memo["ABC"] = INF;
  for (int i = 0; i < n; i++) {
    cin >> c[i] >> s[i];
    sort(s[i].begin(), s[i].end());
    memo[s[i]] = min(memo[s[i]], c[i]);
  }
  int ans = memo["A"] + memo["B"] + memo["C"];
  ans = min(ans, memo["AB"] + memo["C"]);
  ans = min(ans, memo["AC"] + memo["B"]);
  ans = min(ans, memo["BC"] + memo["A"]);
  ans = min(ans, memo["AB"] + memo["AC"]);
  ans = min(ans, memo["AB"] + memo["BC"]);
  ans = min(ans, memo["AC"] + memo["BC"]);
  ans = min(ans, memo["ABC"]);
  if (ans == INF) {
    ans = -1;
  }
  cout << ans << endl;
  return 0;
}




Comments