Search is not available for this dataset
name
stringlengths
2
112
description
stringlengths
29
13k
source
int64
1
7
difficulty
int64
0
25
solution
stringlengths
7
983k
language
stringclasses
4 values
1103_D. Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k β€” your skill in Cardbluff. Each judge has a number a_i β€” an indicator of uncertainty about your entrance to the professional layer and a number e_i β€” an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x β‹… y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≀ n ≀ 10^6, 1 ≀ k ≀ 10^{12}) β€” the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≀ a_i ≀ 10^{12}) β€” the uncertainty of i-th judge The third line contains n integers in the same format (1 ≀ e_i ≀ 10^9), e_i β€” the experience of i-th judge. Output Print the single integer β€” minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1
2
10
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashMap; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import java.util.Map; import java.util.Map.Entry; import java.io.BufferedReader; import java.util.Collections; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, FastScanner in, PrintWriter out) { int n = in.nextInt(); long k = in.nextLong(); Judge[] judges = new Judge[n]; long g = 0; for (int i = 0; i < n; i++) { judges[i] = new Judge(); judges[i].a = in.nextLong(); g = gcd(g, judges[i].a); } for (int i = 0; i < n; i++) { judges[i].e = in.nextInt(); } Factor[] factors = factorize(g); for (int i = 0; i < n; i++) { long na = 1; for (Factor f : factors) { while (judges[i].a % f.p == 0) { judges[i].a /= f.p; na *= f.p; } } judges[i].a = na; } Arrays.sort(judges); int m = factors.length; { List<Judge> bestJudges = new ArrayList<>(); for (int i = 0; i < n; ) { int j = i; while (j < n && judges[i].a == judges[j].a) { ++j; } for (int it = i; it < j && it < i + m; it++) { bestJudges.add(judges[it]); } i = j; } judges = bestJudges.toArray(new Judge[0]); n = judges.length; } long[] prod = new long[1 << m]; long[] factorRaisedToPow = new long[m]; boolean[] canCover = new boolean[1 << m]; final long infinity = Long.MAX_VALUE / 2; long[][] d = new long[m + 1][1 << m]; for (long[] arr : d) { Arrays.fill(arr, infinity); } d[0][0] = 0; Map<ListOfMasks, List<Judge>> byList = new HashMap<>(); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { Factor f = factors[j]; long x = judges[i].a; long y = 1; while (x % f.p == 0) { x /= f.p; y *= f.p; } factorRaisedToPow[j] = y; } prod[0] = 1; canCover[0] = true; List<Integer> masksThatCanBeCovered = new ArrayList<>(); for (int mask = 1; mask < 1 << m; mask++) { int j = Integer.numberOfTrailingZeros(mask); prod[mask] = prod[mask ^ (1 << j)] * factorRaisedToPow[j]; // canCover[mask] = prod[mask] <= k; if (prod[mask] <= k) { masksThatCanBeCovered.add(mask); } } ListOfMasks key = new ListOfMasks(masksThatCanBeCovered); List<Judge> js = byList.get(key); if (js == null) { js = new ArrayList<>(); byList.put(key, js); } js.add(judges[i]); } for (Map.Entry<ListOfMasks, List<Judge>> list : byList.entrySet()) { List<Judge> js = list.getValue(); Collections.sort(js, (u, v) -> Integer.compare(u.e, v.e)); int judgeId = -1; for (Judge j : js) { ++judgeId; if (judgeId >= m) { break; } for (int used = m - 1; used >= 0; used--) { for (int mask : list.getKey().a) { int other = ((1 << m) - 1) ^ mask; for (int covered = other; ; covered = (covered - 1) & other) { if (d[used + 1][covered | mask] > d[used][covered] + j.e) { d[used + 1][covered | mask] = d[used][covered] + j.e; } if (covered == 0) { break; } } } } } } long ans = infinity; for (int x = 0; x <= m; x++) { long y = d[x][(1 << m) - 1]; if (y < infinity) { ans = Math.min(ans, x * y); } } if (ans >= infinity) { ans = -1; } out.println(ans); } private long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } private Factor[] factorize(long n) { List<Factor> res = new ArrayList<>(); for (long p = 2; p * p <= n; p++) { if (n % p == 0) { Factor f = new Factor(); f.p = p; while (n % p == 0) { n /= p; ++f.s; } res.add(f); } } if (n > 1) { Factor f = new Factor(); f.p = n; f.s = 1; res.add(f); } return res.toArray(new Factor[0]); } class Judge implements Comparable<Judge> { long a; int e; public int compareTo(Judge o) { if (a != o.a) { return a < o.a ? -1 : 1; } if (e != o.e) { return e < o.e ? -1 : 1; } return 0; } } class Factor { long p; int s; } class ListOfMasks { int[] a; ListOfMasks(List<Integer> ms) { a = new int[ms.size()]; for (int i = 0; i < a.length; i++) { a[i] = ms.get(i); } } public int hashCode() { return Arrays.hashCode(a); } public boolean equals(Object obj) { return Arrays.equals(a, ((ListOfMasks) obj).a); } } } static class FastScanner { private BufferedReader in; private StringTokenizer st; public FastScanner(InputStream stream) { in = new BufferedReader(new InputStreamReader(stream)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
JAVA
1103_D. Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k β€” your skill in Cardbluff. Each judge has a number a_i β€” an indicator of uncertainty about your entrance to the professional layer and a number e_i β€” an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x β‹… y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≀ n ≀ 10^6, 1 ≀ k ≀ 10^{12}) β€” the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≀ a_i ≀ 10^{12}) β€” the uncertainty of i-th judge The third line contains n integers in the same format (1 ≀ e_i ≀ 10^9), e_i β€” the experience of i-th judge. Output Print the single integer β€” minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1
2
10
#include <bits/stdc++.h> using namespace std; template <class T> inline T Tmin(const T &lch, const T &rch) { if (lch < rch) return lch; return rch; } template <class T> inline T Tmax(const T &lch, const T &rch) { if (lch < rch) return rch; return lch; } template <class T> inline T Tabs(const T &ch) { if (ch < 0) return -ch; return ch; } const long long LLInf = 10000000000000000LL; const double Pi = acos(-1.0); const int Inf = 0x3f3f3f3f; const int Mod = 998244353; const unsigned long long Big_Mod = 1e9 + 9; const unsigned long long Rp = 13; const unsigned long long Mp = 17; const int Gp = 3; inline int R_int() { register int n = 0; register char ch = getchar(); register bool I = false; while (ch < '0' || ch > '9') I = (ch == '-' ? 1 : 0), ch = getchar(); while (ch >= '0' && ch <= '9') n = (n << 1) + (n << 3) + (ch ^ '0'), ch = getchar(); return I ? -n : n; } inline int Add(int a, int b) { int ans = (a + b); ans = (ans >= Mod ? ans - Mod : ans); return ans; } inline int Mis(int a, int b) { int ans = a - b; ans = (ans < 0 ? ans + Mod : ans); return ans; } inline int Mul(int a, int b) { return a * 1ll * b % Mod; } inline int Pow(int a, long long k) { int ans = 1; while (k) { if (k & 1) ans = Mul(ans, a); a = Mul(a, a); k = k >> 1; } return ans; } const int maxn = 1000000 + 3; const int maxc = 13; struct Node { long long a; int e; Node() {} inline bool operator<(const Node &ch) const { return e < ch.e; } }; long long f[2][maxc][(1 << maxc) + 1]; int res[(1 << maxc) + 1]; long long rev[(1 << maxc) + 1]; long long Prime[maxn]; Node v[maxn]; int tot = 0; int n, m; long long k; map<long long, int> M; inline long long Gcd(long long a, long long b) { return b == 0 ? a : Gcd(b, a % b); } signed main() { n = R_int(); scanf("%I64d", &k); for (int i = 1; i <= n; i++) scanf("%I64d", &v[i].a); for (int i = 1; i <= n; i++) v[i].e = R_int(); long long d = v[1].a; for (int i = 2; i <= n; i++) d = Gcd(d, v[i].a); if (d == 1) { puts("0"); return 0; } for (long long i = 2; i * i <= d; i++) { if (d % i == 0) { Prime[++tot] = i; while (d % i == 0) d /= i; } } if (d != 1) Prime[++tot] = d; sort(v + 1, v + n + 1); int ALL = (1 << tot) - 1, u = 0, r = 1; for (int i = 0; i <= tot; i++) { for (int j = 1; j <= ALL; j++) { f[u][i][j] = LLInf; } } rev[0] = 1; int m = tot; for (int i = 1; i <= n; i++) { long long sum = 1, w = v[i].a, cur = 1; for (int j = 1; j <= m; j++) { if (w % Prime[j] == 0) { cur = 1; while (w % Prime[j] == 0) { cur *= Prime[j]; w /= Prime[j]; } rev[1 << (j - 1)] = cur; sum *= cur; } } if (++M[sum] > m) continue; swap(u, r); memcpy(f[u], f[r], sizeof(f[u])); for (int s = 1; s <= ALL; s++) { int t = s & (-s); rev[s] = rev[t] * rev[s ^ t]; if (rev[s] > k) continue; if (++res[s] > m) continue; int es = ALL ^ s; for (int c = 0; c < m; c++) { for (int h = es; h; h = (h - 1) & es) f[u][c + 1][s | h] = Tmin(f[u][c + 1][s | h], f[r][c][h] + v[i].e); f[u][c + 1][s] = Tmin(f[u][c + 1][s], v[i].e * 1ll); } } } long long ans = LLInf; for (int i = 1; i <= m; i++) { ans = Tmin(ans, f[u][i][ALL] * i); } if (ans == LLInf) ans = -1; printf("%I64d\n", ans); return 0; }
CPP
1103_D. Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k β€” your skill in Cardbluff. Each judge has a number a_i β€” an indicator of uncertainty about your entrance to the professional layer and a number e_i β€” an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x β‹… y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≀ n ≀ 10^6, 1 ≀ k ≀ 10^{12}) β€” the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≀ a_i ≀ 10^{12}) β€” the uncertainty of i-th judge The third line contains n integers in the same format (1 ≀ e_i ≀ 10^9), e_i β€” the experience of i-th judge. Output Print the single integer β€” minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1
2
10
#include <bits/stdc++.h> using namespace std; struct data { int x, y; long long val; }; long long read() { long long tmp = 0; char c = getchar(); while (c < '0' || c > '9') c = getchar(); while (c >= '0' && c <= '9') { tmp = tmp * 10 + c - '0'; c = getchar(); } return tmp; } data change[2000000]; long long val[1000010], num[13000], prime[100], mx, mi[13000][100], ch[100], f[20][2100]; bool able[13000][2100]; int cnt_change; int cost[1000010], tot_prime, cnt, type[1000010], peo[1000010], full, sum_type[13000], sum_trans[2100]; map<long long, int> id; bool cmp(int a, int b) { return cost[a] < cost[b]; } long long get_gcd(long long a, long long b) { if (a == 0) return b; long long y = a % b; while (y) { a = b; b = y; y = a % b; } return b; } void dfs(int dep, long long cur) { if (dep > tot_prime) { num[++cnt] = cur; id[cur] = cnt; for (int i = 1; i <= dep; i++) mi[cnt][i] = ch[i]; return; } ch[dep] = 1; while (mx / cur >= prime[dep]) { ch[dep] *= prime[dep]; cur *= prime[dep]; dfs(dep + 1, cur); } } void get_trans(int x, int cost) { for (int i = 1; i <= tot_prime; i++) { if (f[i - 1][0] != -1 && (f[i - 1][0] + cost < f[i][x] || f[i][x] == -1)) change[++cnt_change] = (data){i, x, f[i - 1][0] + cost}; for (int s = full - x; s; s = (s - 1) & (full - x)) { if (f[i - 1][s] != -1 && (f[i - 1][s] + cost < f[i][s + x] || f[i][s + x] == -1)) change[++cnt_change] = (data){i, s + x, f[i - 1][s] + cost}; } } } int main() { int n = read(); long long K = read(), g = 0; for (int i = 1; i <= n; i++) { val[i] = read(); g = get_gcd(g, val[i]); mx = max(mx, val[i]); peo[i] = i; } if (g == 1) { puts("0"); return 0; } for (int i = 1; i <= n; i++) cost[i] = read(); for (int i = 2; (long long)i * i <= g; i++) if (g % i == 0) { prime[++tot_prime] = i; while (g % i == 0) g /= i; } if (g != 1) prime[++tot_prime] = g; dfs(1, 1); for (int i = 1; i <= n; i++) { long long now = 1; for (int j = 1; j <= tot_prime; j++) while (val[i] % prime[j] == 0) { val[i] /= prime[j]; now *= prime[j]; } type[i] = id[now]; } full = (1 << tot_prime) - 1; for (int i = 1; i <= cnt; i++) for (int j = 1; j <= full; j++) { long long need = 1; for (int k = 1; k <= tot_prime; k++) if ((j >> k - 1) & 1) need *= mi[i][k]; if (need <= K) able[i][j] = 1; } sort(peo + 1, peo + n + 1, cmp); for (int i = 0; i <= tot_prime; i++) for (int j = 0; j <= full; j++) f[i][j] = -1; f[0][0] = 0; for (int i = 1; i <= n; i++) { int tmp = peo[i]; if (sum_type[type[tmp]] < tot_prime) { sum_type[type[tmp]]++; cnt_change = 0; for (int j = 0; j <= full; j++) if (sum_trans[j] < tot_prime && able[type[tmp]][j]) { sum_trans[j]++; get_trans(j, cost[tmp]); } for (int j = 1; j <= cnt_change; j++) f[change[j].x][change[j].y] = change[j].val; } } long long res = -1; for (int i = 1; i <= tot_prime; i++) if (f[i][full] != -1 && (i * f[i][full] < res || res == -1)) res = i * f[i][full]; printf("%lld\n", res); return 0; }
CPP
1103_D. Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k β€” your skill in Cardbluff. Each judge has a number a_i β€” an indicator of uncertainty about your entrance to the professional layer and a number e_i β€” an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x β‹… y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≀ n ≀ 10^6, 1 ≀ k ≀ 10^{12}) β€” the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≀ a_i ≀ 10^{12}) β€” the uncertainty of i-th judge The third line contains n integers in the same format (1 ≀ e_i ≀ 10^9), e_i β€” the experience of i-th judge. Output Print the single integer β€” minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1
2
10
#include <bits/stdc++.h> #pragma comment(linker, "/STACK:512000000") using namespace std; using li = long long; using ld = long double; void solve(bool); void precalc(); clock_t start; int main() { start = clock(); int t = 1; cout.sync_with_stdio(0); cin.tie(0); cout.precision(20); cout << fixed; precalc(); while (t--) { solve(true); } cout.flush(); return 0; } template <typename T> T binpow(T q, T w, T mod) { if (!w) return 1 % mod; if (w & 1) return q * 1LL * binpow(q, w - 1, mod) % mod; return binpow(q * 1LL * q % mod, w / 2, mod); } template <typename T> T gcd(T q, T w) { while (w) { q %= w; swap(q, w); } return q; } template <typename T> T lcm(T q, T w) { return q / gcd(q, w) * w; } template <typename T> void make_unique(vector<T>& vec) { sort(vec.begin(), vec.end()); vec.erase(unique(vec.begin(), vec.end()), vec.end()); } template <typename T> void relax_min(T& cur, T val) { cur = min(cur, val); } template <typename T> void relax_max(T& cur, T val) { cur = max(cur, val); } mt19937 rng( (unsigned long long)chrono::steady_clock::now().time_since_epoch().count()); void precalc() {} li dp[2][12][1 << 12]; void solve(__attribute__((unused)) bool read) { int n; li k; if (read) { cin >> n >> k; } else { n = 1e6; k = (li)1e12; } vector<li> a(n), cost(n); li g = 0; for (int i = 0; i < n; ++i) { if (read) { cin >> a[i]; } else { a[i] = 200560490130LL; } g = gcd(a[i], g); } for (int i = 0; i < n; ++i) { if (read) { cin >> cost[i]; } else { cost[i] = rand(); } } vector<li> primes; for (li p = 2; p * p <= g; ++p) { if (g % p == 0) { primes.push_back(p); while (g % p == 0) { g /= p; } } } if (g > 1) { primes.push_back(g); } if (primes.empty()) { cout << "0\n"; return; } vector<pair<li, li>> mapa; for (int i = 0; i < n; ++i) { li cur_val = 1; for (int j = 0; j < primes.size(); ++j) { auto p = primes[j]; while (a[i] % p == 0) { a[i] /= p; cur_val *= p; } } mapa.push_back({cur_val, cost[i]}); } sort(mapa.begin(), mapa.end()); vector<vector<li>> vecs; vector<li> costs; for (int i = 0; i < mapa.size();) { int j = i; vector<li> vec; auto cur_val = mapa[i].first; vector<li> key(primes.size(), 1); for (int r = 0; r < primes.size(); ++r) { while (cur_val % primes[r] == 0) { cur_val /= primes[r]; key[r] *= primes[r]; } } while (j < mapa.size() && mapa[j].first == mapa[i].first) { vec.push_back(mapa[j].second); ++j; } i = j; int enough_space = (int)primes.size(); if (vec.size() > enough_space) { vec.resize(enough_space); } for (li c : vec) { vecs.push_back(key); costs.push_back(c); } } const li INF = (li)1e18; int full_mask = (1 << primes.size()) - 1; auto clear_dp = [&](int par) { for (int cnt = 0; cnt <= primes.size(); ++cnt) { for (int mask = 0; mask <= full_mask; ++mask) { dp[par][cnt][mask] = INF; } } }; int par = 0; for (int i = 0; i < 2; ++i) { clear_dp(i); } dp[par][0][full_mask] = 0; vector<li> prods; for (int i = 0; i < vecs.size(); ++i) { for (int cnt = 0; cnt <= primes.size(); ++cnt) { for (int mask = 0; mask <= full_mask; ++mask) { dp[par ^ 1][cnt][mask] = dp[par][cnt][mask]; } } prods.assign(1 << primes.size(), 1); for (int mask = 0; mask < (1 << primes.size()); ++mask) { for (int j = 0; j < primes.size(); ++j) { if (mask & (1 << j)) { prods[mask] *= vecs[i][j]; } } } for (int cnt = 0; cnt <= primes.size(); ++cnt) { for (int mask = 0; mask <= full_mask; ++mask) { li cur_dp = dp[par][cnt][mask]; if (cur_dp == INF) { continue; } for (int s = mask; s > 0; s = (s - 1) & mask) { li prod = prods[s]; if (prod <= k) { relax_min(dp[par ^ 1][cnt + 1][mask ^ s], cur_dp + costs[i]); } } } } par ^= 1; } li res = INF; for (int cnt = 0; cnt <= primes.size(); ++cnt) { li cur_dp = dp[par][cnt][0]; if (cur_dp == INF) { continue; } relax_min(res, cnt * cur_dp); } if (res == INF) { res = -1; } cout << res << "\n"; }
CPP
1103_D. Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k β€” your skill in Cardbluff. Each judge has a number a_i β€” an indicator of uncertainty about your entrance to the professional layer and a number e_i β€” an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x β‹… y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≀ n ≀ 10^6, 1 ≀ k ≀ 10^{12}) β€” the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≀ a_i ≀ 10^{12}) β€” the uncertainty of i-th judge The third line contains n integers in the same format (1 ≀ e_i ≀ 10^9), e_i β€” the experience of i-th judge. Output Print the single integer β€” minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1
2
10
#include <bits/stdc++.h> using namespace std; inline long long read() { long long x = 0, f = 1; char ch = getchar(); while (!isdigit(ch)) { if (ch == '-') f = -1; ch = getchar(); } while (isdigit(ch)) { x = (x << 1) + (x << 3) + ch - '0'; ch = getchar(); } return x * f; } const int maxn = 1e6 + 1e2; long long val[maxn], num[maxn]; long long prime[maxn]; long long n, m, tot, k; pair<long long, long long> b[maxn]; unordered_map<long long, long long> used; long long cost[maxn]; int ci[maxn]; long long f[14][4010]; long long g[14][4010]; long long ptx[maxn]; long long cnt[maxn]; long long lim; long long lowbit(long long x) { return x & (-x); } long long gcd(long long a, long long b) { if (!b) return a; else return gcd(b, a % b); } signed main() { n = read(), lim = read(); for (int i = 1; i <= n; i++) num[i] = read(); long long gc = num[1]; for (int i = 2; i <= n; i++) gc = gcd(gc, num[i]); if (gc == 1) { cout << 0 << endl; return 0; } for (int i = 1; i <= n; i++) val[i] = read(); long long now = gc; for (long long i = 2; i * i <= gc; i++) { if (now % i == 0) { prime[++m] = i; while (now % i == 0) now /= i, ci[m]++; } } if (now > 1) prime[++m] = now, ci[m] = 1; for (int i = 1; i <= n; i++) { long long now = 1; for (int j = 1; j <= m; j++) while (num[i] % prime[j] == 0) now *= prime[j], num[i] /= prime[j]; b[++tot] = make_pair(val[i], now); } sort(b + 1, b + 1 + n); memset(f, 127 / 3, sizeof(f)); f[0][0] = 0; for (int i = 1; i <= n; i++) { bool flag = 0; if (used[b[i].second] > m) continue; used[b[i].second]++; cost[0] = 1; ptx[0] = 1; long long ymh = b[i].second; for (int j = 1; j <= m; j++) { cost[1 << j - 1] = 1; while (ymh % prime[j] == 0) { cost[1 << j - 1] *= prime[j]; ymh /= prime[j]; } } memcpy(g, f, sizeof(g)); for (int j = 0; j < (1 << m); j++) { ptx[j] = ptx[j ^ lowbit(j)] * cost[lowbit(j)]; long long now = ((1 << m) - 1) ^ j; if (ptx[j] > lim) continue; for (int k = now; k; k = (k - 1) & now) { for (int p = 1; p <= m; p++) if (g[p - 1][k] + b[i].first <= f[p][j | k]) f[p][j | k] = g[p - 1][k] + b[i].first, flag = 1; } if (g[0][0] + b[i].first <= f[1][j]) f[1][j] = g[0][0] + b[i].first, flag = 1; } } long long ans = 1e18; for (long long i = 1; i <= m; i++) if (f[i][(1 << m) - 1] != f[13][4002]) ans = min(ans, f[i][(1 << m) - 1] * i); if (ans == 1e18) ans = -1; cout << ans << endl; return 0; }
CPP
1103_D. Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k β€” your skill in Cardbluff. Each judge has a number a_i β€” an indicator of uncertainty about your entrance to the professional layer and a number e_i β€” an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x β‹… y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≀ n ≀ 10^6, 1 ≀ k ≀ 10^{12}) β€” the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≀ a_i ≀ 10^{12}) β€” the uncertainty of i-th judge The third line contains n integers in the same format (1 ≀ e_i ≀ 10^9), e_i β€” the experience of i-th judge. Output Print the single integer β€” minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1
2
10
#include <bits/stdc++.h> using namespace std; const int N = 3e6 + 10; const int maxn = 1000020; namespace Prime { const int N = 2000005; int p[N], h[N], mn[N], cnt; void init() { for (int i = 2; i <= N; i++) { if (!h[i]) p[++cnt] = i; for (int j = 1; j <= cnt; j++) { if (p[j] * i > N) break; h[i * p[j]] = 1; mn[i * p[j]] = p[j]; if (i % p[j] == 0) break; } } } } // namespace Prime using namespace Prime; const int M = (1 << 11) + 10; struct node { int S; long long mul[M]; vector<int> w; } dt[12200]; int n, w[maxn], tot, tot2, S, val[maxn]; long long a[maxn], lim, d; map<long long, int> vis; map<pair<long long, long long>, int> num; vector<long long> vec; vector<int> best[maxn]; long long gcd(long long a, long long b) { return b ? gcd(b, a % b) : a; } void factor(long long n) { for (int i = 1; i <= cnt; i++) { if ((long long)p[i] * p[i] > n) break; if (n % p[i] == 0) { vec.push_back(p[i]); while (n % p[i] == 0) n /= p[i]; } } if (n > 1) vec.push_back(n); sort(vec.begin(), vec.end()); S = (1 << vec.size()) - 1; } int sum[maxn]; void pre() { init(); long long d = 0; for (int i = 1; i <= n; i++) d = gcd(d, a[i]); if (d == 1) return; factor(d); for (int i = 1; i <= n; i++) { long long cur = 1, x = a[i]; for (int j = 0; j < int(vec.size()); j++) while (x % vec[j] == 0) x /= vec[j], cur *= vec[j]; int &id = vis[cur]; if (!id) { id = ++tot; x = a[i]; for (int j = 0; j < int(vec.size()); j++) { long long y = 1; while (x % vec[j] == 0) x /= vec[j], y *= vec[j]; dt[tot].mul[1 << j] = y; } dt[tot].mul[0] = 1; for (int j = 1; j <= S; j++) for (int k = 0; k < int(vec.size()); k++) { if ((j & (1 << k))) { dt[tot].mul[j] = dt[tot].mul[j ^ (1 << k)] * dt[tot].mul[1 << k]; break; } } } dt[id].w.push_back(w[i]); } for (int i = 1; i <= tot; i++) { sort(dt[i].w.begin(), dt[i].w.end()); sum[i] = sum[i - 1] + dt[i].w.size(); } priority_queue<pair<long long, long long> > heap; for (int k = 1; k <= S; k++) { while (heap.size()) heap.pop(); for (int i = 1; i <= tot; i++) { if (dt[i].mul[k] <= lim) { for (int j = 0; j < int(dt[i].w.size()); j++) { if (heap.size() < vec.size()) heap.push(make_pair(dt[i].w[j], sum[i - 1] + j)); else if (heap.top().first > dt[i].w[j]) { heap.pop(); heap.push(make_pair(dt[i].w[j], sum[i - 1] + j)); } else break; } } } while (heap.size()) { pair<long long, long long> cur = heap.top(); int &id = num[cur]; heap.pop(); if (!id) id = ++tot2, val[tot2] = cur.first; best[id].push_back(k); } } } long long f[15][M], g[15][M]; void Update(long long &x, long long y) { if (x == -1) x = y; else x = min(x, y); } void solve() { if (!vec.size()) { puts("0"); return; } memset(f, -1, sizeof(f)); f[0][0] = 0; for (int j = 1; j <= tot2; j++) { memcpy(g, f, sizeof(f)); for (int k = 0; k < int(best[j].size()); k++) { int s = best[j][k], s2 = S ^ s; for (int i = vec.size() - 1; i >= 0; i--) { for (int l = s2; l; l = (l - 1) & s2) { if (g[i][l] == -1) continue; Update(f[i + 1][l | s], g[i][l] + val[j]); } Update(f[i + 1][s], g[i][0] + val[j]); } } } long long ans = -1; for (int i = 1; i <= int(vec.size()); i++) if (f[i][S] != -1) Update(ans, f[i][S] * i); printf("%lld\n", ans); } int main() { scanf("%d%lld", &n, &lim); for (int i = 1; i <= n; i++) scanf("%lld", &a[i]); for (int i = 1; i <= n; i++) scanf("%d", &w[i]); pre(); solve(); }
CPP
1103_D. Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k β€” your skill in Cardbluff. Each judge has a number a_i β€” an indicator of uncertainty about your entrance to the professional layer and a number e_i β€” an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x β‹… y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≀ n ≀ 10^6, 1 ≀ k ≀ 10^{12}) β€” the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≀ a_i ≀ 10^{12}) β€” the uncertainty of i-th judge The third line contains n integers in the same format (1 ≀ e_i ≀ 10^9), e_i β€” the experience of i-th judge. Output Print the single integer β€” minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1
2
10
#include <bits/stdc++.h> using namespace std; inline long long read() { long long x = 0; int f = 1; char ch = getchar(); for (; !isdigit(ch); ch = getchar()) if (ch == '-') f = -1; for (; isdigit(ch); ch = getchar()) x = x * 10 + (ch ^ 48); return x * f; } void print(long long x) { if (x < 0) putchar('-'), x = -x; if (x > 9) print(x / 10); putchar(x % 10 + '0'); } long long gcd(long long a, long long b) { return b ? gcd(b, a % b) : a; } const int N = 1000100; int n, m, S, c[N]; long long d, k, a[N], p[N], f[13][1 << 12], ans; bool vis[1 << 12]; map<long long, vector<int> > mp; int main() { n = read(), k = read(); for (int i = 1; i <= n; i++) d = gcd(a[i] = read(), d); for (int i = 1; i <= n; i++) c[i] = read(); for (long long i = 2; i * i <= d; i++) if (d % i == 0) { p[m++] = i; while (d % i == 0) d /= i; } if (d > 1) p[m++] = d; S = (1 << m) - 1; for (int i = 1; i <= n; i++) { long long res = 1; for (int k = 0; k < m; k++) while (a[i] % p[k] == 0) a[i] /= p[k], res *= p[k]; mp[res].push_back(c[i]); } for (int i = 0; i < 13; i++) for (int j = 0; j < (1 << 12); j++) f[i][j] = 1000000000000000000ll; f[0][0] = 0; for (auto pr : mp) { long long x = pr.first; auto v = pr.second; sort(v.begin(), v.end()); if (v.size() > m) v.resize(m); for (int t = 0; t <= S; t++) { long long y = x; for (int i = 0; i < m; i++) if (t & (1 << i)) while (y % p[i] == 0) y /= p[i]; vis[t] = (x / y <= k); } for (int cost : v) { bool fl = 0; for (int i = m - 1; ~i; i--) for (int j = 0; j <= S; j++) if (f[i][j] < 1000000000000000000ll) for (int k = (j + 1) | j; k <= S; k = (k + 1) | j) if (vis[k ^ j]) if (f[i + 1][k] > f[i][j] + cost) fl = 1, f[i + 1][k] = f[i][j] + cost; if (!fl) break; } } ans = 1000000000000000000ll; for (long long i = 0; i <= m; i++) if (f[i][S] < 1000000000000000000ll) ans = min(ans, i * f[i][S]); if (ans == 1000000000000000000ll) puts("-1"); else print(ans), putchar('\n'); return 0; }
CPP
1103_D. Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k β€” your skill in Cardbluff. Each judge has a number a_i β€” an indicator of uncertainty about your entrance to the professional layer and a number e_i β€” an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x β‹… y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≀ n ≀ 10^6, 1 ≀ k ≀ 10^{12}) β€” the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≀ a_i ≀ 10^{12}) β€” the uncertainty of i-th judge The third line contains n integers in the same format (1 ≀ e_i ≀ 10^9), e_i β€” the experience of i-th judge. Output Print the single integer β€” minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1
2
10
#include <bits/stdc++.h> using namespace std; const int N = (int)1e6 + 5; const int M = 2048; int n; long long kk, gcdd; pair<long long, int> juds[N]; vector<int> msk[M], nmsk[M]; int cnt[M]; void init(); int actv_num; vector<int> actv_conf[14]; bool dp_flg[M][14]; long long dp_res[M][14]; vector<long long> fac; vector<int> candi_maxl_v, maxl_v; long long gcd_fac[12], jud_fac[12]; int main() { init(); int i, j, k, a, b, c; long long cur_tmp, rem; k = 1 << fac.size(); for (i = k - 1; i >= 0; i--) { for (j = 0; j < fac.size(); j++) { if (i & (1 << j)) msk[i].push_back(j); else nmsk[i].push_back(j); } rem = kk; for (auto s : msk[i]) rem /= gcd_fac[s]; if (!rem) continue; candi_maxl_v.push_back(i); } actv_num = 0; actv_conf[0].push_back(0); dp_flg[0][0] = true; dp_res[0][0] = 0LL; for (i = 0; i < n; i++) { if (!candi_maxl_v.size()) continue; maxl_v.clear(); juds[i].first /= gcdd; for (j = 0; j < fac.size(); j++) { jud_fac[j] = gcd_fac[j]; while (juds[i].first % fac[j] == 0) juds[i].first /= fac[j], jud_fac[j] *= fac[j]; } a = 0; for (k = 0; k < candi_maxl_v.size(); k++) { auto ss = candi_maxl_v[k]; rem = kk; for (auto s : msk[ss]) rem /= jud_fac[s]; if (!rem) { candi_maxl_v[a++] = ss; continue; } if (++cnt[ss] < fac.size()) candi_maxl_v[a++] = ss; for (j = 0; j < nmsk[ss].size(); j++) if (jud_fac[nmsk[ss][j]] <= rem) break; if (j < nmsk[ss].size()) continue; maxl_v.push_back(ss); } while (a < candi_maxl_v.size()) candi_maxl_v.pop_back(); if (!maxl_v.size()) continue; for (a = actv_num; a >= 0; a--) { for (auto t : actv_conf[a]) { for (auto s : maxl_v) { if ((s & t) == s) continue; k = (s | t); j = a + 1; cur_tmp = dp_res[t][a] + juds[i].second; if (!dp_flg[k][j]) { if (j > actv_num) actv_num = j; actv_conf[j].push_back(k); dp_flg[k][j] = true; dp_res[k][j] = cur_tmp; } else if (cur_tmp < dp_res[k][j]) dp_res[k][j] = cur_tmp; } } } } int goal = (1 << fac.size()) - 1; long long cur_min = LLONG_MAX; if (!goal) cur_min = 0LL; for (i = 0; i <= fac.size(); i++) if (dp_flg[goal][i] && 1LL * i * dp_res[goal][i] < cur_min) cur_min = 1LL * i * dp_res[goal][i]; if (cur_min < LLONG_MAX) printf("%I64d\n", cur_min); else printf("-1\n"); return 0; } struct ooi_ioo { static const int _buf_size = 1 << 24; char buf[_buf_size], *_pos = buf; ooi_ioo() { fread(buf, 1, _buf_size, stdin); } void renew() { int rem = _buf_size - (_pos - buf); if (rem >= n * 10 + 20) return; memcpy(buf, _pos, rem); fread(buf + rem, 1, _pos - buf, stdin); _pos = buf; } ooi_ioo &operator>>(int &res) { while (!isdigit(*_pos)) _pos++; res = *_pos++ & 15; while (isdigit(*_pos)) (res *= 10) += *_pos++ & 15; return *this; } ooi_ioo &operator>>(long long &res) { while (!isdigit(*_pos)) _pos++; res = *_pos++ & 15; while (isdigit(*_pos)) (res *= 10) += *_pos++ & 15; return *this; } } oi_io; inline long long gcd(long long a, long long b) { while (b) swap(a = a % b, b); return a; } bool comp(const pair<long long, int> &a, const pair<long long, int> &b) { return a.second < b.second; } void init() { int i, j, k; long long tmp; oi_io >> n >> kk; oi_io >> juds[0].first; gcdd = juds[0].first; for (i = 1; i < n; i++) { oi_io >> juds[i].first; gcdd = gcd(gcdd, juds[i].first); } oi_io.renew(); for (i = 0; i < n; i++) oi_io >> juds[i].second; sort(juds, juds + n, comp); tmp = gcdd; k = 0; for (long long ii = 2; ii * ii <= tmp; ii++) { if (tmp % ii == 0) { fac.push_back(ii); gcd_fac[k] = 1LL; while (tmp % ii == 0) tmp /= ii, gcd_fac[k] *= ii; k++; } } if (tmp > 1) { fac.push_back(tmp); gcd_fac[k++] = tmp; } }
CPP
1103_D. Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k β€” your skill in Cardbluff. Each judge has a number a_i β€” an indicator of uncertainty about your entrance to the professional layer and a number e_i β€” an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x β‹… y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≀ n ≀ 10^6, 1 ≀ k ≀ 10^{12}) β€” the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≀ a_i ≀ 10^{12}) β€” the uncertainty of i-th judge The third line contains n integers in the same format (1 ≀ e_i ≀ 10^9), e_i β€” the experience of i-th judge. Output Print the single integer β€” minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1
2
10
#include <bits/stdc++.h> using namespace std; const int N = 1e6 + 5; int n, tick; long long k; long long a[N], e[N]; vector<long long> dv_id[N], costs[N]; vector<int> ok_masks[N]; map<long long, int> M; long long gcd(long long a, long long b) { while (b) { a %= b; swap(a, b); } return a; } int main() { scanf("%d %lld", &n, &k); long long g = 0; for (int i = 1; i <= n; i++) { scanf("%lld", a + i); g = gcd(g, a[i]); } for (int i = 1; i <= n; i++) scanf("%lld", e + i); vector<long long> pr; for (long long i = 2; i * i <= g; i++) { if (g % i == 0) { pr.push_back(i); while (g % i == 0) g /= i; } } if (g > 1) pr.push_back(g); if (pr.empty()) { puts("0"); return 0; } for (int i = 1; i <= n; i++) { vector<long long> dv; long long all = 1; for (int j = 0; j < pr.size(); j++) { long long x = pr[j]; long long tmp = a[i]; long long mul = 1; while (tmp % x == 0) { tmp /= x; mul *= x; } all *= mul; dv.push_back(mul); } int &id = M[all]; if (!id) id = ++tick; dv_id[id] = dv; costs[id].push_back(e[i]); } vector<vector<long long>> dp( pr.size() + 1, vector<long long>(1 << pr.size(), (long long)1e15)); dp[0][0] = 0; vector<vector<pair<long long, int>>> best_of(1 << pr.size()); n = 1; for (int i = 1; i <= tick; i++) { sort(costs[i].begin(), costs[i].end()); if (costs[i].size() > pr.size()) costs[i].resize(pr.size()); for (int mask = 0; mask < (1 << dv_id[i].size()); mask++) { long long mul = 1; for (int j = 0; j < dv_id[i].size(); j++) { if (mask & (1 << j)) mul *= dv_id[i][j]; } if (mul <= k) { for (int j = 0; j < costs[i].size(); j++) { long long c = costs[i][j]; best_of[mask].insert( lower_bound(best_of[mask].begin(), best_of[mask].end(), pair<long long, int>{c, 0}), {c, n + j}); if (best_of[mask].size() > pr.size()) best_of[mask].pop_back(); } } } n += costs[i].size(); } for (int mask = 0; mask < (1 << pr.size()); mask++) { for (auto &tmp : best_of[mask]) { ok_masks[tmp.second].push_back(mask); } } n = 0; for (int id = 1; id <= tick; id++) { for (auto c : costs[id]) { ++n; vector<vector<long long>> n_dp = dp; for (int i = (int)pr.size() - 1; i >= 0; i--) { for (int dpmask = 0; dpmask < (1 << pr.size()); dpmask++) { for (auto mask : ok_masks[n]) { n_dp[i + 1][dpmask | mask] = min(n_dp[i + 1][dpmask | mask], dp[i][dpmask] + c); } } } dp = n_dp; } } long long ans = 1e15; for (int i = 1; i <= pr.size(); i++) ans = min(ans, dp[i][(1 << pr.size()) - 1] * i); if (ans > 8e14) puts("-1"); else printf("%lld\n", ans); return 0; }
CPP
1103_D. Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k β€” your skill in Cardbluff. Each judge has a number a_i β€” an indicator of uncertainty about your entrance to the professional layer and a number e_i β€” an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x β‹… y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≀ n ≀ 10^6, 1 ≀ k ≀ 10^{12}) β€” the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≀ a_i ≀ 10^{12}) β€” the uncertainty of i-th judge The third line contains n integers in the same format (1 ≀ e_i ≀ 10^9), e_i β€” the experience of i-th judge. Output Print the single integer β€” minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1
2
10
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.PrintStream; import java.util.Arrays; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import java.math.BigInteger; import java.io.BufferedReader; import java.util.Collections; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, FastScanner in, PrintWriter out) { int n = in.nextInt(); long k = in.nextLong(); Judge[] judges = new Judge[n]; long g = 0; for (int i = 0; i < n; i++) { judges[i] = new Judge(); judges[i].a = in.nextLong(); g = gcd(g, judges[i].a); } for (int i = 0; i < n; i++) { judges[i].e = in.nextInt(); } Factor[] factors = factorize(g); for (int i = 0; i < n; i++) { long na = 1; // Remove the prime factors that do not occur in the gcd // by leaving only those that do. for (Factor f : factors) { while (judges[i].a % f.p == 0) { judges[i].a /= f.p; na *= f.p; } } judges[i].a = na; } Arrays.sort(judges); // if (true) { if (false) { countEquivalenceClassesWorstCase(); } int m = factors.length; { List<Judge> bestJudges = new ArrayList<>(); for (int i = 0; i < n; ) { int j = i; while (j < n && judges[i].a == judges[j].a) { ++j; } // At most |m| judges in every equivalence class are needed. for (int it = i; it < j && it < i + m; it++) { bestJudges.add(judges[it]); } i = j; } judges = bestJudges.toArray(new Judge[0]); n = judges.length; for (int i = 0; i < n; i++) { judges[i].sortedId = i; } } long[] prod = new long[1 << m]; long[] factorRaisedToPow = new long[m]; List<Judge>[] judgesThatCanCoverMask = new List[1 << m]; for (int mask = 0; mask < 1 << m; mask++) { judgesThatCanCoverMask[mask] = new ArrayList<>(); } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { Factor f = factors[j]; long x = judges[i].a; long y = 1; while (x % f.p == 0) { x /= f.p; y *= f.p; } factorRaisedToPow[j] = y; } prod[0] = 1; for (int mask = 1; mask < 1 << m; mask++) { int j = Integer.numberOfTrailingZeros(mask); prod[mask] = prod[mask ^ (1 << j)] * factorRaisedToPow[j]; if (prod[mask] <= k) { judgesThatCanCoverMask[mask].add(judges[i]); } } } List<Integer>[] masksCoveredByJudge = new List[n]; for (int mask = 0; mask < 1 << m; mask++) { List<Judge> js = judgesThatCanCoverMask[mask]; Collections.sort(js, (u, v) -> Integer.compare(u.e, v.e)); // By the exchange argument, only |m| best judges // that can cover this mask are needed. for (int it = 0; it < m && it < js.size(); it++) { int id = js.get(it).sortedId; if (masksCoveredByJudge[id] == null) { masksCoveredByJudge[id] = new ArrayList<>(); } masksCoveredByJudge[id].add(mask); } } final long infinity = Long.MAX_VALUE / 2; long[][] d = new long[m + 1][1 << m]; for (long[] arr : d) { Arrays.fill(arr, infinity); } d[0][0] = 0; for (int judgeId = 0; judgeId < n; judgeId++) { if (masksCoveredByJudge[judgeId] == null) { continue; } for (int used = m - 1; used >= 0; used--) { // At most m*(1<<m) masks are in total in all the |masksCoveredByJudge| lists combined. // Every mask occurs at most m times (so we cannot have, say, the worst mask occur too often). // Therefore, the overall complexity of these nested 4 for loops is O(m^2 * 3^m). for (int mask : masksCoveredByJudge[judgeId]) { int other = ((1 << m) - 1) ^ mask; for (int covered = other; ; covered = (covered - 1) & other) { if (d[used + 1][covered | mask] > d[used][covered] + judges[judgeId].e) { d[used + 1][covered | mask] = d[used][covered] + judges[judgeId].e; } if (covered == 0) { break; } } } } } long ans = infinity; for (int x = 0; x <= m; x++) { long y = d[x][(1 << m) - 1]; if (y < infinity) { ans = Math.min(ans, x * y); } } if (ans >= infinity) { ans = -1; } out.println(ans); } private void countEquivalenceClassesWorstCase() { final long LIMIT = (long) 1e12; final int N = 100; boolean[] isPrime = new boolean[N]; Arrays.fill(isPrime, true); int[] primes = new int[N]; int numPrimes = 0; BigInteger prod = BigInteger.ONE; for (int i = 2; i < N; i++) { if (!isPrime[i]) { continue; } primes[numPrimes++] = i; prod = prod.multiply(BigInteger.valueOf(i)); if (prod.compareTo(BigInteger.valueOf(LIMIT)) > 0) { break; } for (int j = i + i; j < N; j += i) { isPrime[j] = false; } } System.out.printf("Product of the first %d primes exceeds the limit of %d\n", numPrimes, LIMIT); primes = Arrays.copyOf(primes, numPrimes - 1); System.out.printf("Number of equivalence classes when using only the first several primes:\n"); System.out.printf("num primes: num classes\n"); for (int i = 1; i <= primes.length; i++) { System.out.printf("%d: %d\n", i, rec(0, 1, LIMIT, Arrays.copyOf(primes, i))); } } private long rec(int pos, long prod, long limit, int[] primes) { if (pos == primes.length) { return prod <= limit ? 1 : 0; } long res = 0; while (prod <= limit / primes[pos]) { prod *= primes[pos]; // Every prime must occur at least once. res += rec(pos + 1, prod, limit, primes); } return res; } private long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } private Factor[] factorize(long n) { List<Factor> res = new ArrayList<>(); for (long p = 2; p * p <= n; p++) { if (n % p == 0) { Factor f = new Factor(); f.p = p; while (n % p == 0) { n /= p; ++f.s; } res.add(f); } } if (n > 1) { Factor f = new Factor(); f.p = n; f.s = 1; res.add(f); } return res.toArray(new Factor[0]); } class Judge implements Comparable<Judge> { long a; int e; int sortedId; public int compareTo(Judge o) { if (a != o.a) { return a < o.a ? -1 : 1; } if (e != o.e) { return e < o.e ? -1 : 1; } return 0; } } class Factor { long p; int s; } } static class FastScanner { private BufferedReader in; private StringTokenizer st; public FastScanner(InputStream stream) { in = new BufferedReader(new InputStreamReader(stream)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
JAVA
1103_D. Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k β€” your skill in Cardbluff. Each judge has a number a_i β€” an indicator of uncertainty about your entrance to the professional layer and a number e_i β€” an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x β‹… y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≀ n ≀ 10^6, 1 ≀ k ≀ 10^{12}) β€” the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≀ a_i ≀ 10^{12}) β€” the uncertainty of i-th judge The third line contains n integers in the same format (1 ≀ e_i ≀ 10^9), e_i β€” the experience of i-th judge. Output Print the single integer β€” minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1
2
10
#include <bits/stdc++.h> using namespace std; template <typename T, typename U> std::istream& operator>>(std::istream& i, pair<T, U>& p) { i >> p.first >> p.second; return i; } template <typename T> std::istream& operator>>(std::istream& i, vector<T>& t) { for (auto& v : t) { i >> v; } return i; } template <typename T, typename U> std::ostream& operator<<(std::ostream& o, const pair<T, U>& p) { o << p.first << ' ' << p.second; return o; } template <typename T> std::ostream& operator<<(std::ostream& o, const vector<T>& t) { if (t.empty()) o << '\n'; for (size_t i = 0; i < t.size(); ++i) { o << t[i] << " \n"[i == t.size() - 1]; } return o; } template <typename T> using minheap = priority_queue<T, vector<T>, greater<T>>; template <typename T> using maxheap = priority_queue<T, vector<T>, less<T>>; template <typename T> bool in(T a, T b, T c) { return a <= b && b < c; } unsigned int logceil(long long first) { return first ? 8 * sizeof(long long) - __builtin_clzll(first) : 0; } namespace std { template <typename T, typename U> struct hash<pair<T, U>> { hash<T> t; hash<U> u; size_t operator()(const pair<T, U>& p) const { return t(p.first) ^ (u(p.second) << 7); } }; } // namespace std template <typename T, typename F> T bsh(T l, T h, const F& f) { T r = -1, m; while (l <= h) { m = (l + h) / 2; if (f(m)) { l = m + 1; r = m; } else { h = m - 1; } } return r; } template <typename F> double bshd(double l, double h, const F& f, double p = 1e-9) { unsigned int r = 3 + (unsigned int)log2((h - l) / p); while (r--) { double m = (l + h) / 2; if (f(m)) { l = m; } else { h = m; } } return (l + h) / 2; } template <typename T, typename F> T bsl(T l, T h, const F& f) { T r = -1, m; while (l <= h) { m = (l + h) / 2; if (f(m)) { h = m - 1; r = m; } else { l = m + 1; } } return r; } template <typename F> double bsld(double l, double h, const F& f, double p = 1e-9) { unsigned int r = 3 + (unsigned int)log2((h - l) / p); while (r--) { double m = (l + h) / 2; if (f(m)) { h = m; } else { l = m; } } return (l + h) / 2; } template <typename T> T gcd(T a, T b) { if (a < b) swap(a, b); return b ? gcd(b, a % b) : a; } template <typename T> class vector2 : public vector<vector<T>> { public: vector2() {} vector2(size_t a, size_t b, T t = T()) : vector<vector<T>>(a, vector<T>(b, t)) {} }; template <typename T> class vector3 : public vector<vector2<T>> { public: vector3() {} vector3(size_t a, size_t b, size_t c, T t = T()) : vector<vector2<T>>(a, vector2<T>(b, c, t)) {} }; template <typename T> class vector4 : public vector<vector3<T>> { public: vector4() {} vector4(size_t a, size_t b, size_t c, size_t d, T t = T()) : vector<vector3<T>>(a, vector3<T>(b, c, d, t)) {} }; template <typename T> class vector5 : public vector<vector4<T>> { public: vector5() {} vector5(size_t a, size_t b, size_t c, size_t d, size_t e, T t = T()) : vector<vector4<T>>(a, vector4<T>(b, c, d, e, t)) {} }; constexpr long long INF = 1e18; class DProfessionalLayer { public: void solve(istream& cin, ostream& cout) { int N; cin >> N; long long K; cin >> K; vector<long long> A(N); cin >> A; vector<int> E(N); cin >> E; long long g = A[0]; for (long long a : A) g = gcd(g, a); if (g == 1) { cout << 0 << endl; return; } long long gg = g; vector<long long> F; for (long long first = 2; first * first <= g; ++first) { if (g % first == 0) { while (g % first == 0) g /= first; F.push_back(first); } } if (g != 1) F.push_back(g); int M = F.size(); map<long long, vector<std::pair<int, int>>> H; for (int j = 0; j < N; ++j) { long long X = A[j] / gg; for (int k = 0; k < M; ++k) while (X % F[k] == 0) X /= F[k]; auto& h = H[A[j] / X]; h.emplace_back(E[j], j); } vector<vector<std::pair<int, int>>> U(1 << M); for (auto& h : H) { sort(h.second.begin(), h.second.end()); if (h.second.size() > M) h.second.resize(M); vector<long long> P(M, 1); long long X = h.first; for (int i = 0; i < M; ++i) while (X % F[i] == 0) { P[i] *= F[i]; X /= F[i]; } for (int i = 1; i < (1 << M); ++i) { long long p = 1; for (int k = 0; k < M; ++k) if (i & (1 << k)) p *= P[k]; if (p <= K) { for (std::pair<int, int> hh : h.second) { U[i].push_back(hh); if (U[i].size() >= 2 * M) { sort(U[i].begin(), U[i].end()); U[i].resize(M); } } } } } for (int i = 1; i < (1 << M); ++i) { sort(U[i].begin(), U[i].end()); if (U[i].size() > M) U[i].resize(M); } map<int, vector<int>> G; for (int i = 1; i < (1 << M); ++i) { for (std::pair<int, int> u : U[i]) { G[u.second].emplace_back(i); } } vector2<long long> D(1 << M, M + 1, INF); D[0][0] = 0; for (auto& g : G) { auto Q = D; for (int i = 0; i < (1 << M); ++i) { for (int k = 0; k < M; ++k) { if (D[i][k] == INF) continue; for (int j : g.second) { if ((i & j) == 0) { Q[i | j][k + 1] = min(Q[i | j][k + 1], D[i][k] + E[g.first]); } } } } swap(Q, D); } long long ans = INF; for (int i = 1; i <= M; ++i) ans = min(ans, D.back()[i] * i); if (ans == INF) cout << "-1\n"; else cout << ans << endl; } }; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); DProfessionalLayer solver; std::istream& in(std::cin); std::ostream& out(std::cout); solver.solve(in, out); return 0; }
CPP
1103_D. Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k β€” your skill in Cardbluff. Each judge has a number a_i β€” an indicator of uncertainty about your entrance to the professional layer and a number e_i β€” an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x β‹… y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≀ n ≀ 10^6, 1 ≀ k ≀ 10^{12}) β€” the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≀ a_i ≀ 10^{12}) β€” the uncertainty of i-th judge The third line contains n integers in the same format (1 ≀ e_i ≀ 10^9), e_i β€” the experience of i-th judge. Output Print the single integer β€” minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1
2
10
#include <bits/stdc++.h> using namespace std; long long int A[1000005], memo[1 << 12]; int E[1000005]; long long int dp[12][1 << 12]; long long int gcd(long long int x, long long int y) { if (x == 0) return y; return gcd(y % x, x); } int main() { int n; long long int lim; scanf("%d %lld", &n, &lim); long long int g = 0; for (int i = 0; i < n; i++) { scanf("%lld", &A[i]); g = gcd(g, A[i]); } for (int i = 0; i < n; i++) scanf("%d", &E[i]); vector<pair<long long int, int> > vx; vector<long long int> pr; for (long long int i = 2; i * i <= g; i++) { if (g % i == 0) { pr.push_back(i); while (g % i == 0) g /= i; } } if (g != 1) pr.push_back(g); for (int i = 0; i < n; i++) { long long int a = 1; for (int j = 0; j < pr.size(); j++) { long long int p = pr[j]; while (A[i] % p == 0) { a *= p; A[i] /= p; } } vx.push_back(pair<long long int, int>(a, E[i])); } sort(vx.begin(), vx.end()); int sz = 0; for (int i = 0; i < vx.size(); i++) { if (i >= 11 && vx[i - 11].first == vx[i].first) continue; A[sz] = vx[i].first, E[sz] = vx[i].second; sz++; } n = sz; memset(dp, -1, sizeof(dp)); dp[0][0] = 0; for (int i = 0; i < n; i++) { for (int S = 0; S < 1 << pr.size(); S++) memo[S] = 1; for (int j = 0; j < pr.size(); j++) { long long int p = pr[j]; while (A[i] % p == 0) { A[i] /= p; memo[1 << j] *= p; } } for (int S = 0; S < 1 << pr.size(); S++) { for (int j = 0; j < pr.size(); j++) { if ((S >> j & 1) && S != (1 << j)) memo[S] *= memo[1 << j]; } } for (int S = (1 << pr.size()) - 1; S >= 0; S--) { for (int j = 0; j < pr.size(); j++) { if (dp[j][S] == -1) continue; int T = (1 << pr.size()) - S - 1; for (int K = T; K > 0; K = (K - 1) & T) { if (memo[K] <= lim) { if (dp[j + 1][S + K] == -1) dp[j + 1][S + K] = dp[j][S] + E[i]; else dp[j + 1][S + K] = min(dp[j + 1][S + K], dp[j][S] + E[i]); } } } } } long long int ret = -1; for (int i = 0; i <= pr.size(); i++) { if (dp[i][(1 << pr.size()) - 1] != -1) { if (ret == -1) ret = dp[i][(1 << pr.size()) - 1] * (long long int)i; else ret = min(ret, dp[i][(1 << pr.size()) - 1] * (long long int)i); } } printf("%lld\n", ret); return 0; }
CPP
1103_D. Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k β€” your skill in Cardbluff. Each judge has a number a_i β€” an indicator of uncertainty about your entrance to the professional layer and a number e_i β€” an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x β‹… y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≀ n ≀ 10^6, 1 ≀ k ≀ 10^{12}) β€” the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≀ a_i ≀ 10^{12}) β€” the uncertainty of i-th judge The third line contains n integers in the same format (1 ≀ e_i ≀ 10^9), e_i β€” the experience of i-th judge. Output Print the single integer β€” minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1
2
10
#include <bits/stdc++.h> using namespace std; const int P = 1e9 + 7; const long long INF = 0x3f3f3f3f3f3f3f3f; long long gcd(long long a, long long b) { return b ? gcd(b, a % b) : a; } long long qpow(long long a, long long n) { long long r = 1 % P; for (a %= P; n; a = a * a % P, n >>= 1) if (n & 1) r = r * a % P; return r; } long long inv(long long first) { return first <= 1 ? 1 : inv(P % first) * (P - P / first) % P; } const int N = 1e6 + 10; int n, w[N]; long long k, g; struct _ { long long a; int e; bool operator<(const _ &rhs) const { return e < rhs.e; } } a[N]; vector<long long> A; map<long long, int> vis; map<long long, int> vis1; long long dp[2][12][1 << 11], num[1 << 11]; void factor(long long g) { int mx = sqrt(g + 0.5); for (int i = 2; i <= mx; ++i) if (g % i == 0) { A.push_back(i); while (g % i == 0) g /= i; } if (g > 1) A.push_back(g); } void chkmin(long long &first, long long second) { first = min(first, second); } int main() { scanf("%d%lld", &n, &k); for (int i = 1; i <= n; ++i) scanf("%lld", &a[i].a), g = gcd(g, a[i].a); if (g == 1) return puts("0"), 0; for (int i = 1; i <= n; ++i) scanf("%d", &a[i].e); sort(a + 1, a + 1 + n); factor(g); int r = A.size(), S = (1 << r) - 1, cur = 0; memset(dp[0], 0x3f, sizeof dp[0]); dp[0][0][0] = 0; for (int i = 1; i <= n; ++i) { long long b = 1; for (int j = 0; j <= r - 1; ++j) if (a[i].a % A[j] == 0) { long long t = 1; while (a[i].a % A[j] == 0) a[i].a /= A[j], t *= A[j]; num[1 << j] = t; b *= t; } if (++vis[b] > r) continue; num[0] = 1; cur ^= 1; memcpy(dp[cur], dp[cur ^ 1], sizeof dp[cur]); for (int j = 1; j <= S; ++j) { num[j] = num[j ^ j & -j] * num[j & -j]; if (num[j] > k) continue; if (++vis1[j] > r) continue; long long first = ~j & S; for (int t = r - 1; t >= 0; --t) { for (int second = first; second; second = (second - 1) & first) if (dp[cur ^ 1][t][second] != INF) { chkmin(dp[cur][t + 1][second ^ j], dp[cur ^ 1][t][second] + a[i].e); } chkmin(dp[cur][t + 1][j], dp[cur ^ 1][t][0] + a[i].e); } } } long long ans = INF; for (int i = 1; i <= r; ++i) if (dp[cur][i][S] != INF) { ans = min(ans, dp[cur][i][S] * i); } printf("%lld\n", ans == INF ? -1 : ans); }
CPP
1103_D. Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k β€” your skill in Cardbluff. Each judge has a number a_i β€” an indicator of uncertainty about your entrance to the professional layer and a number e_i β€” an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x β‹… y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≀ n ≀ 10^6, 1 ≀ k ≀ 10^{12}) β€” the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≀ a_i ≀ 10^{12}) β€” the uncertainty of i-th judge The third line contains n integers in the same format (1 ≀ e_i ≀ 10^9), e_i β€” the experience of i-th judge. Output Print the single integer β€” minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1
2
10
#include <bits/stdc++.h> using namespace std; namespace io { const int L = (1 << 20) + 1; char buf[L], *S, *T, c; char getchar() { if (__builtin_expect(S == T, 0)) { T = (S = buf) + fread(buf, 1, L, stdin); return (S == T ? EOF : *S++); } return *S++; } int inp() { int x = 0, f = 1; char ch; for (ch = getchar(); !isdigit(ch); ch = getchar()) if (ch == '-') f = -1; for (; isdigit(ch); x = x * 10 + ch - '0', ch = getchar()) ; return x * f; } unsigned inpu() { unsigned x = 0; char ch; for (ch = getchar(); !isdigit(ch); ch = getchar()) ; for (; isdigit(ch); x = x * 10 + ch - '0', ch = getchar()) ; return x; } long long inp_ll() { long long x = 0; int f = 1; char ch; for (ch = getchar(); !isdigit(ch); ch = getchar()) if (ch == '-') f = -1; for (; isdigit(ch); x = x * 10 + ch - '0', ch = getchar()) ; return x * f; } char B[25], *outs = B + 20, *outr = B + 20; template <class T> inline void print(register T a, register char x = 0) { if (x) *--outs = x, x = 0; if (!a) *--outs = '0'; else while (a) *--outs = (a % 10) + 48, a /= 10; if (x) *--outs = x; fwrite(outs, outr - outs, 1, stdout); outs = outr; } }; // namespace io using io ::inp; using io ::inp_ll; using io ::inpu; using io ::print; using i32 = int; using i64 = long long; using u8 = unsigned char; using u32 = unsigned; using u64 = unsigned long long; using f64 = double; using f80 = long double; long long power(long long a, long long b, long long p) { if (!b) return 1; long long t = power(a, b / 2, p); t = t * t % p; if (b & 1) t = t * a % p; return t; } long long gcd(long long a, long long b) { return b ? gcd(b, a % b) : a; } template <class T> inline void freshmin(T &a, const T &b) { if (a > b) a = b; } template <class T> inline void freshmax(T &a, const T &b) { if (a < b) a = b; } const int MAXN = 1000010; const int MAXP = 10000000; const int MOD = 1000000007; const f80 MI = f80(1) / MOD; const long long INF = 10000000000000000LL; const long long inf = 5000000000000LL; int n; long long k; struct node { long long a; int e; bool operator<(const node &A) const { return e < A.e; } } a[MAXN]; int m; vector<long long> p; map<long long, int> H; int h[1 << 11], pcnt[1 << 11]; long long v[1 << 11]; long long F[12][1 << 11], G[12][1 << 11]; int main() { n = inp(); k = inp_ll(); for (int i = 1; i <= n; ++i) a[i].a = inp_ll(); for (int i = 1; i <= n; ++i) a[i].e = inp(); sort(a + 1, a + n + 1); long long d = a[1].a; for (int i = 1; i <= n; ++i) d = gcd(d, a[i].a); if (d == 1) { puts("0"); return 0; } for (long long i = 2; i * i <= d; ++i) if (d % i == 0) { p.push_back(i); while (d % i == 0) d /= i; } if (d > 1) p.push_back(d); m = p.size(); for (int i = 0; i <= m; ++i) for (int s = 1; s < 1 << m; ++s) F[i][s] = INF; for (int i = 1; i <= n; ++i) { long long cur = 1; for (int j = 0; j < m; ++j) { long long d = 1; while (a[i].a % p[j] == 0) { d *= p[j]; a[i].a /= p[j]; } cur *= d; v[1 << j] = d; } if (++H[cur] > m) continue; memcpy(G, F, sizeof(F)); v[0] = 1; for (int s = 1; s < 1 << m; ++s) { int low = s & -s; v[s] = v[s ^ low] * v[low]; if (v[s] > k) continue; if (++h[s] > m) continue; int c = ((1 << m) - 1) ^ s; for (int x = 0; x < m; ++x) { for (int t = c; t; t = (t - 1) & c) freshmin(F[x + 1][t | s], G[x][t] + a[i].e); freshmin(F[x + 1][s], (long long)a[i].e); } } } long long ans = INF; for (int i = 1; i <= m; ++i) ans = min(ans, F[i][(1 << m) - 1] * i); if (ans == INF) ans = -1; cout << ans << endl; return 0; }
CPP
1103_D. Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k β€” your skill in Cardbluff. Each judge has a number a_i β€” an indicator of uncertainty about your entrance to the professional layer and a number e_i β€” an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x β‹… y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≀ n ≀ 10^6, 1 ≀ k ≀ 10^{12}) β€” the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≀ a_i ≀ 10^{12}) β€” the uncertainty of i-th judge The third line contains n integers in the same format (1 ≀ e_i ≀ 10^9), e_i β€” the experience of i-th judge. Output Print the single integer β€” minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1
2
10
#include <bits/stdc++.h> using namespace std; using ll = long long; template <class t, class u> void chmax(t& first, u second) { if (first < second) first = second; } template <class t, class u> void chmin(t& first, u second) { if (second < first) first = second; } template <class t> using vc = vector<t>; template <class t> using vvc = vc<vc<t>>; using pi = pair<ll, ll>; using vi = vc<ll>; template <class t, class u> ostream& operator<<(ostream& os, const pair<t, u>& p) { return os << "{" << p.first << "," << p.second << "}"; } template <class t> ostream& operator<<(ostream& os, const vc<t>& v) { os << "{"; for (auto e : v) os << e << ","; return os << "}"; } using uint = unsigned; using ull = unsigned long long; template <ll i, class T> void print_tuple(ostream&, const T&) {} template <ll i, class T, class H, class... Args> void print_tuple(ostream& os, const T& t) { if (i) os << ","; os << get<i>(t); print_tuple<i + 1, T, Args...>(os, t); } template <class... Args> ostream& operator<<(ostream& os, const tuple<Args...>& t) { os << "{"; print_tuple<0, tuple<Args...>, Args...>(os, t); return os << "}"; } void print(ll x, ll suc = 1) { cout << x; if (suc == 1) cout << endl; if (suc == 2) cout << " "; } ll read() { ll i; cin >> i; return i; } vi readvi(ll n, ll off = 0) { vi v(n); for (ll i = ll(0); i < ll(n); i++) v[i] = read() + off; return v; } template <class T> void print(const vector<T>& v, ll suc = 1) { for (ll i = ll(0); i < ll(v.size()); i++) print(v[i], i == ll(v.size()) - 1 ? suc : 2); } string readString() { string s; cin >> s; return s; } template <class T> T sq(const T& t) { return t * t; } void yes(bool ex = true) { cout << "Yes" << endl; if (ex) exit(0); } void no(bool ex = true) { cout << "No" << endl; if (ex) exit(0); } constexpr ll ten(ll n) { return n == 0 ? 1 : ten(n - 1) * 10; } const ll infLL = LLONG_MAX / 3; const ll inf = infLL; ll topbit(signed t) { return t == 0 ? -1 : 31 - __builtin_clz(t); } ll topbit(ll t) { return t == 0 ? -1 : 63 - __builtin_clzll(t); } ll popcount(signed t) { return __builtin_popcount(t); } ll popcount(ll t) { return __builtin_popcountll(t); } bool ispow2(ll i) { return i && (i & -i) == i; } bool inc(ll first, ll second, ll c) { return first <= second && second <= c; } template <class t> void mkuni(vc<t>& v) { sort(v.begin(), v.end()); v.erase(unique(v.begin(), v.end()), v.end()); } ll rand_int(ll l, ll r) { static random_device rd; static mt19937 gen(rd()); return uniform_int_distribution<ll>(l, r)(gen); } ll gcd(ll first, ll second) { return second ? gcd(second, first % second) : first; } signed main() { cin.tie(0); ios::sync_with_stdio(0); cout << fixed << setprecision(20); ll n, k; cin >> n >> k; vi first = readvi(n), e = readvi(n); ll g = 0; for (auto v : first) g = gcd(g, v); if (g == 1) { cout << 0 << endl; return 0; } vi p; for (ll i = 2; i * i <= g; i++) { if (g % i == 0) { p.push_back(i); while (g % i == 0) g /= i; } } if (g > 1) p.push_back(g); vc<pi> c; vi xs; for (ll i = ll(0); i < ll(n); i++) { ll x = 1; for (auto v : p) while (first[i] % v == 0) { first[i] /= v; x *= v; } c.emplace_back(e[i], x); xs.push_back(x); } sort(c.begin(), c.end()); mkuni(xs); vi cnt(xs.size()); ll m = p.size(); vc<ll> d(1 << m, 0); vc<pi> f; for (auto w : c) { { ll i = lower_bound(xs.begin(), xs.end(), w.second) - xs.begin(); if (cnt[i] == m) continue; cnt[i]++; } vi z(m, 1); for (ll i = ll(0); i < ll(p.size()); i++) { ll x = w.second; while (x % p[i] == 0) { z[i] *= p[i]; x /= p[i]; } } bool u = false; for (ll bit = ll(1); bit < ll(1 << m); bit++) { ll x = 1; for (ll i = ll(0); i < ll(m); i++) if (bit & 1 << i) x *= z[i]; if (x <= k) { if (d[bit] < m) { d[bit]++; u = true; } } } if (u) f.push_back(w); } vvc<ll> dp(1 << m, vi(m + 1, inf / m)); dp[0][0] = 0; for (auto w : f) { vi z(m, 1); for (ll i = ll(0); i < ll(p.size()); i++) { ll x = w.second; while (x % p[i] == 0) { z[i] *= p[i]; x /= p[i]; } } void(0); vi q; for (ll bit = ll(1); bit < ll(1 << m); bit++) { ll x = 1; for (ll i = ll(0); i < ll(m); i++) if (bit & 1 << i) x *= z[i]; if (x <= k) { q.push_back(bit); } } for (ll bit = ll(1 << m) - 1; bit >= 0; bit--) { for (ll i = ll(1); i < ll(m + 1); i++) { for (auto v : q) if ((v & bit) == v) chmin(dp[bit][i], dp[bit - v][i - 1] + w.first); } } } ll ans = inf / m; for (ll i = ll(1); i < ll(m + 1); i++) chmin(ans, dp[(1 << m) - 1][i] * i); if (ans == inf / m) ans = -1; cout << ans << endl; }
CPP
1103_D. Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k β€” your skill in Cardbluff. Each judge has a number a_i β€” an indicator of uncertainty about your entrance to the professional layer and a number e_i β€” an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x β‹… y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≀ n ≀ 10^6, 1 ≀ k ≀ 10^{12}) β€” the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≀ a_i ≀ 10^{12}) β€” the uncertainty of i-th judge The third line contains n integers in the same format (1 ≀ e_i ≀ 10^9), e_i β€” the experience of i-th judge. Output Print the single integer β€” minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1
2
10
#include <bits/stdc++.h> using namespace std; const int N = (int)1e6 + 5; const int M = 2048; int sp[20]; vector<int> msk[M], nmsk[M]; bool gathered[M]; int n; long long kk, gcdd; pair<long long, long long> juds[N]; vector<long long> fac; set<int> candi_maxl_v; unordered_map<long long, int> jud_map; vector<int> v_adj[M]; bool valid[N]; int cnt[N]; vector<int> maxl_v[N]; int num_pt_j; void init(); int actv_num; vector<int> actv_conf[14]; bool dp_flg[M][14]; long long dp_res[M][14]; long long gcd_fac[20], jud_fac[20]; void make_pt_judge(long long trt) { int i, j, k; long long rem; for (int j = 0; j < fac.size(); j++) jud_fac[j] *= gcd_fac[j]; jud_map[trt] = num_pt_j; valid[num_pt_j] = true; for (auto ss : candi_maxl_v) { rem = kk; for (auto s : msk[ss]) rem /= jud_fac[s]; if (!rem) continue; for (i = 0; i < nmsk[ss].size(); i++) if (jud_fac[nmsk[ss][i]] <= rem) break; if (i < nmsk[ss].size()) continue; maxl_v[num_pt_j].push_back(ss); v_adj[ss].push_back(num_pt_j); } if (!maxl_v[num_pt_j].size()) valid[num_pt_j] = false; num_pt_j++; } deque<int> v_q, jud_q; void reduce(int idx) { int i, j, k; set<int>::iterator it; valid[idx] = false; jud_q.push_back(idx); while (!jud_q.empty()) { idx = jud_q.front(); jud_q.pop_front(); for (auto s : maxl_v[idx]) { if (gathered[s]) continue; it = candi_maxl_v.find(s); while (it != candi_maxl_v.begin()) { if ((*it & s) == *it) { gathered[*it] = true; v_q.push_back(*it); candi_maxl_v.erase(it--); } else it--; } } while (!v_q.empty()) { k = v_q.back(); v_q.pop_back(); for (auto t : v_adj[k]) { if (!valid[t]) continue; if (++cnt[t] >= maxl_v[t].size()) { valid[t] = false; jud_q.push_back(t); } } } } } int main() { init(); int i, j, k, a, b, c; long long cur_tmp; k = sp[fac.size()]; for (i = 0; i < k; i++) { cur_tmp = kk; for (auto s : msk[i]) cur_tmp /= gcd_fac[s]; if (!cur_tmp) continue; candi_maxl_v.insert(i); } actv_num = 0; actv_conf[0].push_back(0); dp_flg[0][0] = true; dp_res[0][0] = 0LL; for (i = 0; i < n; i++) { juds[i].first /= gcdd; for (j = 0; j < fac.size(); j++) { jud_fac[j] = 1LL; while (juds[i].first % fac[j] == 0) juds[i].first /= fac[j], jud_fac[j] *= fac[j]; } juds[i].first = 1LL; for (j = 0; j < fac.size(); j++) juds[i].first *= jud_fac[j]; int jud_idx; auto tt = jud_map.find(juds[i].first); if (tt == jud_map.end()) { make_pt_judge(juds[i].first); jud_idx = num_pt_j - 1; } else jud_idx = tt->second; if (!valid[jud_idx]) continue; for (a = actv_num; a >= 0; a--) { for (auto t : actv_conf[a]) { for (auto s : maxl_v[jud_idx]) { if (gathered[s] || (s & t) == s) continue; k = (s | t); j = a + 1; cur_tmp = dp_res[t][a] + juds[i].second; if (j > actv_num) actv_num = j; if (!dp_flg[k][j]) { actv_conf[j].push_back(k); dp_flg[k][j] = true; dp_res[k][j] = cur_tmp; } else if (cur_tmp < dp_res[k][j]) dp_res[k][j] = cur_tmp; } } } if (++cnt[jud_idx] >= maxl_v[jud_idx].size()) reduce(jud_idx); } int goal = sp[fac.size()] - 1; long long cur_min = LLONG_MAX; if (!goal) cur_min = 0LL; for (i = 0; i <= fac.size(); i++) if (dp_flg[goal][i] && 1LL * i * dp_res[goal][i] < cur_min) cur_min = 1LL * i * dp_res[goal][i]; if (cur_min < LLONG_MAX) printf("%I64d\n", cur_min); else printf("-1\n"); return 0; } inline long long gcd(long long a, long long b) { long long ttr; while (b) ttr = a % b, a = b, b = ttr; return a; } struct ooi_ioo { static const int _buf_size = 1 << 25; char buf[_buf_size], *_pos = buf; ooi_ioo() { fread(buf, 1, _buf_size, stdin); } ooi_ioo &operator>>(long long &res) { while (!isdigit(*_pos)) _pos++; res = *_pos++ & 15; while (isdigit(*_pos)) (res *= 10) += *_pos++ & 15; return *this; } } oi_io; bool isprm[500005]; bool comp(const pair<long long, long long> &a, const pair<long long, long long> &b) { return a.second < b.second; } void init() { int i, j, k; long long tmp; for (i = 0; i < 20; i++) sp[i] = 1 << i; oi_io >> tmp >> kk; n = tmp; oi_io >> juds[0].first; gcdd = juds[0].first; for (i = 1; i < n; i++) { oi_io >> juds[i].first; gcdd = gcd(gcdd, juds[i].first); } for (i = 0; i < n; i++) oi_io >> juds[i].second; sort(juds, juds + n, comp); if (gcdd % 2 == 0) fac.push_back(2); for (i = 3; i < 1000005; i += 2) { if (isprm[i >> 1]) continue; if (gcdd % i == 0) fac.push_back(i); for (tmp = ((long long)i) * i; tmp < 1000005; tmp += i + i) isprm[tmp >> 1] = true; } tmp = gcdd; for (i = 0; i < fac.size(); i++) { gcd_fac[i] = 1LL; while (tmp % fac[i] == 0) { tmp /= fac[i]; gcd_fac[i] *= fac[i]; } } if (tmp > 1) { fac.push_back(tmp); gcd_fac[i] = tmp; } k = sp[fac.size()]; for (i = 0; i < k; i++) { for (j = 0; j < fac.size(); j++) { if (i & sp[j]) msk[i].push_back(j); else nmsk[i].push_back(j); } } }
CPP
1103_D. Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k β€” your skill in Cardbluff. Each judge has a number a_i β€” an indicator of uncertainty about your entrance to the professional layer and a number e_i β€” an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x β‹… y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≀ n ≀ 10^6, 1 ≀ k ≀ 10^{12}) β€” the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≀ a_i ≀ 10^{12}) β€” the uncertainty of i-th judge The third line contains n integers in the same format (1 ≀ e_i ≀ 10^9), e_i β€” the experience of i-th judge. Output Print the single integer β€” minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1
2
10
#include <bits/stdc++.h> using namespace std; const int inf = (int)1.01e9; const long long infll = (long long)1.01e18; const long double eps = 1e-9; const long double pi = acos((long double)-1); mt19937 mrand(chrono::steady_clock::now().time_since_epoch().count()); int rnd(int x) { return mrand() % x; } void precalc() {} long long gcd(long long a, long long b) { return (b ? gcd(b, a % b) : a); } const long long maxx = (long long)1e12; const int maxn = (int)1e6 + 5; int n; long long b; long long a[maxn]; int e[maxn]; bool read() { if (scanf("%d%lld", &n, &b) < 2) { return false; } for (int i = 0; i < n; i++) { scanf("%lld", &a[i]); } for (int i = 0; i < n; i++) { scanf("%d", &e[i]); } return true; } pair<long long, int> tosort[maxn]; int isGood[maxn]; int k; vector<long long> ps; vector<vector<int>> good; bool add(int msk, int id) { if (((int)(good[msk]).size()) >= k && e[good[msk].back()] <= e[id]) { return false; } if (((int)(good[msk]).size()) >= k) { good[msk].pop_back(); } int pos = ((int)(good[msk]).size()); good[msk].push_back(id); while (pos && e[good[msk][pos]] < e[good[msk][pos - 1]]) { swap(good[msk][pos], good[msk][pos - 1]); pos--; } return true; } vector<vector<long long>> dp, ndp; void solve() { long long g = a[0]; for (int i = 1; i < n; i++) { g = gcd(g, a[i]); } if (g == 1) { printf("0\n"); return; } { ps.clear(); long long x = g; for (long long d = 2; d * d <= x; d++) { if (!(x % d)) { ps.push_back(d); while (!(x % d)) { x /= d; } } } if (x > 1) { ps.push_back(x); } } k = ((int)(ps).size()); for (int i = 0; i < n; i++) { long long x = 1; auto &cur = a[i]; for (int j = 0; j < k; j++) { while (!(cur % ps[j])) { cur /= ps[j]; x *= ps[j]; } } cur = x; } for (int i = 0; i < n; i++) { tosort[i] = make_pair(a[i], e[i]); } sort(tosort, tosort + n); for (int i = 0; i < n; i++) { a[i] = tosort[i].first; e[i] = tosort[i].second; } good.clear(); good.resize((1 << k)); for (int i = 0; i < n; i++) { isGood[i] = false; } for (int j = 0; j < n;) { int i = j; while (j < n && a[j] == a[i]) { j++; } vector<int> qs(k, 0); { long long x = a[i]; for (int it = 0; it < k; it++) { while (!(x % ps[it])) { x /= ps[it]; qs[it]++; } } } for (int msk = 0; msk < (1 << k); msk++) { long long y = 1; for (int it = 0; it < k; it++) { if (!(msk & (1 << it))) { continue; } for (int it0 = 0; it0 < qs[it]; it0++) { y *= ps[it]; } } if (y > b) { continue; } int pos = i; while (pos < j) { if (!add(msk, pos)) { break; } isGood[pos] = true; pos++; } } } dp = vector<vector<long long>>((1 << k), vector<long long>(k + 1, infll)); dp[0][0] = 0; int ob = 0; for (int i = 0; i < n; i++) { if (!isGood[i]) { continue; } ob++; ndp = vector<vector<long long>>((1 << k), vector<long long>(k + 1, infll)); vector<int> qs(k, 0); { long long x = a[i]; for (int it = 0; it < k; it++) { while (!(x % ps[it])) { x /= ps[it]; qs[it]++; } } } vector<int> ok(1 << k); for (int msk = 0; msk < (1 << k); msk++) { long long y = 1; for (int it = 0; it < k; it++) { if (!(msk & (1 << it))) { continue; } for (int it0 = 0; it0 < qs[it]; it0++) { y *= ps[it]; } } ok[msk] = (y <= b); } for (int msk = 0; msk < (1 << k); msk++) { for (int cnt = 0; cnt <= k; cnt++) { auto cur = dp[msk][cnt]; if (cur >= infll) { continue; } { auto &nxt = ndp[msk][cnt]; nxt = min(nxt, cur); } if (cnt >= k) { continue; } int msk1 = (((1 << k) - 1) ^ msk); for (int nmsk = msk1; nmsk > 0; nmsk = ((nmsk - 1) & msk1)) { if (!ok[nmsk]) { continue; } auto &nxt = ndp[msk | nmsk][cnt + 1]; nxt = min(nxt, cur + e[i]); } } } swap(dp, ndp); } long long res = infll; for (int cnt = 1; cnt <= k; cnt++) { if (dp[(1 << k) - 1][cnt] < infll) { res = min(res, cnt * dp[(1 << k) - 1][cnt]); } } if (res >= infll) { res = -1; } printf("%lld\n", res); if (ob > 1000) cout << k << " " << ob; } int main() { precalc(); while (read()) { solve(); } return 0; }
CPP
1103_D. Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k β€” your skill in Cardbluff. Each judge has a number a_i β€” an indicator of uncertainty about your entrance to the professional layer and a number e_i β€” an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x β‹… y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≀ n ≀ 10^6, 1 ≀ k ≀ 10^{12}) β€” the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≀ a_i ≀ 10^{12}) β€” the uncertainty of i-th judge The third line contains n integers in the same format (1 ≀ e_i ≀ 10^9), e_i β€” the experience of i-th judge. Output Print the single integer β€” minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1
2
10
#include <bits/stdc++.h> inline long long in() { long long k = 0; char ch = getchar(); bool p = 1; while (ch < '-') ch = getchar(); if (ch == '-') p = 0, ch = getchar(); while (ch > '-') k = k * 10 + ch - '0', ch = getchar(); return p ? k : -k; } const int N = 1e6 + 5; const long long inf = 1ll << 60; long long dp[2][13][1 << 13], k; int w[N], fz[N]; long long a[N], p[13], np[13], b[N], Cnt[1 << 13]; int c[13], nc[13], cnt, S, now = 1, id[N]; long long gcd(long long a, long long b) { return b ? gcd(b, a % b) : a; } inline void cmin(long long &x, long long y) { if (x > y) x = y; } inline void calc(int w) { for (int i = 1; i <= cnt; ++i) for (int j = 0; j <= S; ++j) dp[now][i][j] = dp[now ^ 1][i][j]; static int fz[1 << 12]; for (int i = 1; i <= S; ++i) { long long res = 1; for (int j = 0; j < cnt; ++j) if (i >> j & 1) res *= np[j + 1]; fz[i] = res <= k; } for (int i = 1; i <= S; ++i) { if (!fz[i]) continue; if (++Cnt[i] > cnt) continue; cmin(dp[now][1][i], w); for (int t = S ^ i, r = t;; t = (t - 1) & r) { for (int j = 2; j <= cnt; ++j) cmin(dp[now][j][t | i], dp[now ^ 1][j - 1][t] / (j - 1) * j + 1ll * j * w); if (!t) break; } } } inline bool cmp(const int &x, const int &y) { return a[x] == a[y] ? w[x] < w[y] : a[x] < a[y]; } inline bool cmp1(const int &x, const int &y) { return w[x] < w[y]; } int main() { int n = in(); long long g = 0; k = in(); for (int i = 1; i <= n; ++i) a[i] = in(), g = gcd(g, a[i]); for (int i = 1; i <= n; ++i) w[i] = in(), id[i] = i; long long x = g; if (g == 1) return puts("0"), 0; for (long long i = 2; i * i <= x; ++i) if (x % i == 0) { p[++cnt] = i; while (x % i == 0) x /= i, ++c[cnt]; } if (x > 1) p[++cnt] = x, c[cnt] = 1; for (int i = 1; i <= cnt; ++i) { long long res = 1; for (int j = 1; j <= c[j]; ++j) res *= p[j]; if (res > k) return puts("-1"), 0; } std::sort(id + 1, id + n + 1, cmp); int m = n; n = 0; memcpy(b, a, sizeof a); memcpy(fz, w, sizeof w); for (int i = 1, ct = 0; i <= m; ++i) if (b[id[i]] == b[id[i - 1]]) { if (ct >= cnt) continue; ++ct; a[++n] = b[id[i]], w[n] = fz[id[i]]; } else ct = 1, a[++n] = b[id[i]], w[n] = fz[id[i]]; for (int i = 1; i <= n; ++i) id[i] = i; std::sort(id + 1, id + n + 1, cmp1); S = 1 << cnt; --S; for (int i = 1; i <= cnt; ++i) for (int j = 0; j <= S; ++j) dp[now][i][j] = inf; for (int i = 1; i <= n; ++i) { long long x = a[id[i]]; now ^= 1; for (int j = 1; j <= cnt; ++j) np[j] = 1; for (int j = 1; j <= cnt; ++j) while (x % p[j] == 0) ++nc[j], x /= p[j], np[j] *= p[j]; calc(w[id[i]]); } long long ans = inf; for (int i = 1; i <= cnt; ++i) ans = std::min(ans, dp[now][i][S]); printf("%lld\n", ans == inf ? -1ll : ans); return 0; }
CPP
1103_D. Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k β€” your skill in Cardbluff. Each judge has a number a_i β€” an indicator of uncertainty about your entrance to the professional layer and a number e_i β€” an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x β‹… y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≀ n ≀ 10^6, 1 ≀ k ≀ 10^{12}) β€” the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≀ a_i ≀ 10^{12}) β€” the uncertainty of i-th judge The third line contains n integers in the same format (1 ≀ e_i ≀ 10^9), e_i β€” the experience of i-th judge. Output Print the single integer β€” minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1
2
10
#include <bits/stdc++.h> using namespace std; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); long long gcd(long long x, long long y) { return y == 0 ? x : gcd(y, x % y); } const long long INF = (long long)1e16; const int N = (int)1e6 + 55; const int K = 11; const int M = (1 << K) + 5; int n; pair<long long, long long> a[N]; long long e[K]; long long d[M]; int m; long long p[K]; long long r[N]; vector<pair<long long, int> > c[N]; int ID; long long dp[K + 1][M]; pair<long long, int> trans[M][K]; vector<int> trans2[N]; long long k; void addTrans(int mask, pair<long long, int> w) { for (int i = 0; i < m; i++) { if (w < trans[mask][i]) swap(w, trans[mask][i]); } } int main() { scanf("%d%lld", &n, &k); long long X = 0; for (int i = 0; i < n; i++) { scanf("%lld", &a[i].first); X = gcd(X, a[i].first); } for (int i = 0; i < n; i++) scanf("%lld", &a[i].second); for (long long x = 2; x * x <= X; x++) { if (X % x) continue; p[m++] = x; while (X % x == 0) X /= x; } if (X > 1) { p[m++] = X; } for (int mask = 0; mask < (1 << m); mask++) for (int i = 0; i <= m; i++) dp[i][mask] = INF; dp[0][0] = 0; for (int i = 0; i < n; i++) { long long x = a[i].first, y = 1; for (int j = 0; j < m; j++) { while (x % p[j] == 0) { x /= p[j]; y *= p[j]; } } a[i].first = y; } sort(a, a + n); ID = -1; for (int i = 0; i < n; i++) { if (i == 0 || a[i].first != a[i - 1].first) { ID++; r[ID] = a[i].first; } c[ID].push_back(make_pair(a[i].second, i)); } ID++; for (int mask = 0; mask < (1 << m); mask++) for (int i = 0; i < m; i++) trans[mask][i] = make_pair(INF, -1); for (int it = 0; it < ID; it++) { while ((int)c[it].size() > m) c[it].pop_back(); long long x = r[it]; for (int i = 0; i < m; i++) { e[i] = 1; while (x % p[i] == 0) { e[i] *= p[i]; x /= p[i]; } } d[0] = 1; for (int mask = 1; mask < (1 << m); mask++) { int pos = 0; while (((mask >> pos) & 1) == 0) pos++; d[mask] = d[mask ^ (1 << pos)] * e[pos]; if (d[mask] <= k) { for (int i = 0; i < (int)c[it].size(); i++) { addTrans(mask, c[it][i]); } } } } for (int mask = 0; mask < (1 << m); mask++) for (int i = 0; i < m; i++) if (trans[mask][i].second != -1) { trans2[trans[mask][i].second].push_back(mask); } for (int i = 0; i < n; i++) { if (trans2[i].empty()) continue; for (int s = m; s > 0; s--) for (int nmask : trans2[i]) { int all = (1 << m) - 1 - nmask; for (int mask = all;; mask = (mask - 1) & all) { dp[s][mask ^ nmask] = min(dp[s][mask ^ nmask], dp[s - 1][mask] + a[i].second); if (mask == 0) break; } } } long long ans = INF; for (int i = 0; i <= m; i++) if (dp[i][(1 << m) - 1] < INF) ans = min(ans, i * dp[i][(1 << m) - 1]); if (ans == INF) printf("-1\n"); else printf("%lld\n", ans); return 0; }
CPP
1103_D. Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k β€” your skill in Cardbluff. Each judge has a number a_i β€” an indicator of uncertainty about your entrance to the professional layer and a number e_i β€” an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x β‹… y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≀ n ≀ 10^6, 1 ≀ k ≀ 10^{12}) β€” the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≀ a_i ≀ 10^{12}) β€” the uncertainty of i-th judge The third line contains n integers in the same format (1 ≀ e_i ≀ 10^9), e_i β€” the experience of i-th judge. Output Print the single integer β€” minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1
2
10
#include <bits/stdc++.h> #pragma comment(linker, "/STACK:512000000") using namespace std; using li = long long; using ld = long double; void solve(bool); void precalc(); clock_t start; int main() { start = clock(); int t = 1; cout.sync_with_stdio(0); cin.tie(0); cout.precision(20); cout << fixed; precalc(); while (t--) { solve(true); } cout.flush(); return 0; } template <typename T> T binpow(T q, T w, T mod) { if (!w) return 1 % mod; if (w & 1) return q * 1LL * binpow(q, w - 1, mod) % mod; return binpow(q * 1LL * q % mod, w / 2, mod); } template <typename T> T gcd(T q, T w) { while (w) { q %= w; swap(q, w); } return q; } template <typename T> T lcm(T q, T w) { return q / gcd(q, w) * w; } template <typename T> void make_unique(vector<T>& vec) { sort(vec.begin(), vec.end()); vec.erase(unique(vec.begin(), vec.end()), vec.end()); } template <typename T> void relax_min(T& cur, T val) { cur = min(cur, val); } template <typename T> void relax_max(T& cur, T val) { cur = max(cur, val); } mt19937 rng( (unsigned long long)chrono::steady_clock::now().time_since_epoch().count()); void precalc() {} li dp[2][12][1 << 12]; void solve(__attribute__((unused)) bool read) { int n; li k; if (read) { cin >> n >> k; } else { n = 1e6; k = (li)1e12; } vector<li> a(n), cost(n); li g = 0; for (int i = 0; i < n; ++i) { if (read) { cin >> a[i]; } else { a[i] = 200560490130LL; } g = gcd(a[i], g); } for (int i = 0; i < n; ++i) { if (read) { cin >> cost[i]; } else { cost[i] = rand(); } } vector<li> primes; for (li p = 2; p * p <= g; ++p) { if (g % p == 0) { primes.push_back(p); while (g % p == 0) { g /= p; } } } if (g > 1) { primes.push_back(g); } if (primes.empty()) { cout << "0\n"; return; } vector<pair<li, li>> mapa; for (int i = 0; i < n; ++i) { li cur_val = 1; for (int j = 0; j < primes.size(); ++j) { auto p = primes[j]; while (a[i] % p == 0) { a[i] /= p; cur_val *= p; } } mapa.push_back({cur_val, cost[i]}); } sort(mapa.begin(), mapa.end()); vector<vector<li>> vecs; vector<li> costs; for (int i = 0; i < mapa.size();) { int j = i; vector<li> vec; auto cur_val = mapa[i].first; vector<li> key(primes.size(), 1); for (int r = 0; r < primes.size(); ++r) { while (cur_val % primes[r] == 0) { cur_val /= primes[r]; key[r] *= primes[r]; } } while (j < mapa.size() && mapa[j].first == mapa[i].first) { vec.push_back(mapa[j].second); ++j; } i = j; int enough_space = 0; li cur_prod = 1; for (li x : key) { if (x > k) { continue; } if (x * cur_prod <= k) { if (cur_prod == 1) { ++enough_space; } cur_prod *= x; continue; } else { ++enough_space; cur_prod = x; } } if (vec.size() > enough_space) { vec.resize(enough_space); } for (li c : vec) { vecs.push_back(key); costs.push_back(c); } } const li INF = (li)1e18; int full_mask = (1 << primes.size()) - 1; auto clear_dp = [&](int par) { for (int cnt = 0; cnt <= primes.size(); ++cnt) { for (int mask = 0; mask <= full_mask; ++mask) { dp[par][cnt][mask] = INF; } } }; int par = 0; for (int i = 0; i < 2; ++i) { clear_dp(i); } dp[par][0][full_mask] = 0; vector<li> prods; for (int i = 0; i < vecs.size(); ++i) { for (int cnt = 0; cnt <= primes.size(); ++cnt) { for (int mask = 0; mask <= full_mask; ++mask) { dp[par ^ 1][cnt][mask] = dp[par][cnt][mask]; } } prods.assign(1 << primes.size(), 1); for (int mask = 0; mask < (1 << primes.size()); ++mask) { for (int j = 0; j < primes.size(); ++j) { if (mask & (1 << j)) { prods[mask] *= vecs[i][j]; } } } for (int cnt = 0; cnt <= primes.size(); ++cnt) { for (int mask = 0; mask <= full_mask; ++mask) { li cur_dp = dp[par][cnt][mask]; if (cur_dp == INF) { continue; } for (int s = mask; s > 0; s = (s - 1) & mask) { li prod = prods[s]; if (prod <= k) { relax_min(dp[par ^ 1][cnt + 1][mask ^ s], cur_dp + costs[i]); } } } } par ^= 1; } li res = INF; for (int cnt = 0; cnt <= primes.size(); ++cnt) { li cur_dp = dp[par][cnt][0]; if (cur_dp == INF) { continue; } relax_min(res, cnt * cur_dp); } if (res == INF) { res = -1; } cout << res << "\n"; }
CPP
1103_D. Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k β€” your skill in Cardbluff. Each judge has a number a_i β€” an indicator of uncertainty about your entrance to the professional layer and a number e_i β€” an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x β‹… y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≀ n ≀ 10^6, 1 ≀ k ≀ 10^{12}) β€” the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≀ a_i ≀ 10^{12}) β€” the uncertainty of i-th judge The third line contains n integers in the same format (1 ≀ e_i ≀ 10^9), e_i β€” the experience of i-th judge. Output Print the single integer β€” minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1
2
10
#include <bits/stdc++.h> using namespace std; const int N = (int)1e6 + 5; const int M = 2048; int n; long long kk, gcdd; pair<long long, int> juds[N]; int sp[20]; vector<int> msk[M], nmsk[M]; int cnt[M]; void init(); int actv_num; vector<int> actv_conf[14]; bool dp_flg[M][14]; long long dp_res[M][14]; vector<long long> fac; set<int> candi_maxl_v; vector<int> maxl_v; long long gcd_fac[20], jud_fac[20]; int main() { init(); int i, j, k, a, b, c; long long cur_tmp, rem; k = sp[fac.size()]; for (i = 0; i < k; i++) { cur_tmp = kk; for (auto s : msk[i]) cur_tmp /= gcd_fac[s]; if (!cur_tmp) continue; candi_maxl_v.insert(i); } actv_num = 0; actv_conf[0].push_back(0); dp_flg[0][0] = true; dp_res[0][0] = 0LL; for (i = 0; i < n; i++) { if (!candi_maxl_v.size()) continue; maxl_v.clear(); juds[i].first /= gcdd; for (j = 0; j < fac.size(); j++) { jud_fac[j] = gcd_fac[j]; while (juds[i].first % fac[j] == 0) juds[i].first /= fac[j], jud_fac[j] *= fac[j]; } auto it = candi_maxl_v.begin(); while (it != candi_maxl_v.end()) { auto rit = it++; auto ss = *rit; rem = kk; for (auto s : msk[ss]) rem /= jud_fac[s]; if (!rem) continue; if (++cnt[ss] >= fac.size()) candi_maxl_v.erase(rit); for (j = 0; j < nmsk[ss].size(); j++) if (jud_fac[nmsk[ss][j]] <= rem) break; if (j < nmsk[ss].size()) continue; maxl_v.push_back(ss); } if (!maxl_v.size()) continue; for (a = actv_num; a >= 0; a--) { for (auto t : actv_conf[a]) { for (auto s : maxl_v) { if ((s & t) == s) continue; k = (s | t); j = a + 1; cur_tmp = dp_res[t][a] + juds[i].second; if (j > actv_num) actv_num = j; if (!dp_flg[k][j]) { actv_conf[j].push_back(k); dp_flg[k][j] = true; dp_res[k][j] = cur_tmp; } else if (cur_tmp < dp_res[k][j]) dp_res[k][j] = cur_tmp; } } } } int goal = sp[fac.size()] - 1; long long cur_min = LLONG_MAX; if (!goal) cur_min = 0LL; for (i = 0; i <= fac.size(); i++) if (dp_flg[goal][i] && 1LL * i * dp_res[goal][i] < cur_min) cur_min = 1LL * i * dp_res[goal][i]; if (cur_min < LLONG_MAX) printf("%I64d\n", cur_min); else printf("-1\n"); return 0; } inline long long gcd(long long a, long long b) { long long ttr; while (b) ttr = a % b, a = b, b = ttr; return a; } struct ooi_ioo { static const int _buf_size = 1 << 25; char buf[_buf_size], *_pos = buf; ooi_ioo() { fread(buf, 1, _buf_size, stdin); } ooi_ioo &operator>>(long long &res) { while (!isdigit(*_pos)) _pos++; res = *_pos++ & 15; while (isdigit(*_pos)) (res *= 10) += *_pos++ & 15; return *this; } } oi_io; bool comp(const pair<long long, long long> &a, const pair<long long, long long> &b) { return a.second < b.second; } void init() { int i, j, k; long long tmp; for (i = 0; i < 20; i++) sp[i] = 1 << i; oi_io >> tmp >> kk; n = tmp; oi_io >> juds[0].first; gcdd = juds[0].first; for (i = 1; i < n; i++) { oi_io >> juds[i].first; gcdd = gcd(gcdd, juds[i].first); } for (i = 0; i < n; i++) oi_io >> tmp, juds[i].second = tmp; sort(juds, juds + n, comp); tmp = gcdd; k = 0; for (long long ii = 2; ii * ii <= tmp; ii++) { if (tmp % ii == 0) { fac.push_back(ii); gcd_fac[k] = 1LL; while (tmp % ii == 0) tmp /= ii, gcd_fac[k] *= ii; k++; } } if (tmp > 1) { fac.push_back(tmp); gcd_fac[k++] = tmp; } k = sp[fac.size()]; for (i = 0; i < k; i++) { for (j = 0; j < fac.size(); j++) { if (i & sp[j]) msk[i].push_back(j); else nmsk[i].push_back(j); } } }
CPP
1103_D. Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k β€” your skill in Cardbluff. Each judge has a number a_i β€” an indicator of uncertainty about your entrance to the professional layer and a number e_i β€” an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x β‹… y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≀ n ≀ 10^6, 1 ≀ k ≀ 10^{12}) β€” the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≀ a_i ≀ 10^{12}) β€” the uncertainty of i-th judge The third line contains n integers in the same format (1 ≀ e_i ≀ 10^9), e_i β€” the experience of i-th judge. Output Print the single integer β€” minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1
2
10
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import java.io.BufferedReader; import java.util.Collections; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, FastScanner in, PrintWriter out) { int n = in.nextInt(); long k = in.nextLong(); Judge[] judges = new Judge[n]; long g = 0; for (int i = 0; i < n; i++) { judges[i] = new Judge(); judges[i].a = in.nextLong(); g = gcd(g, judges[i].a); } for (int i = 0; i < n; i++) { judges[i].e = in.nextInt(); } Factor[] factors = factorize(g); for (int i = 0; i < n; i++) { long na = 1; for (Factor f : factors) { while (judges[i].a % f.p == 0) { judges[i].a /= f.p; na *= f.p; } } judges[i].a = na; } Arrays.sort(judges); int m = factors.length; { List<Judge> bestJudges = new ArrayList<>(); for (int i = 0; i < n; ) { int j = i; while (j < n && judges[i].a == judges[j].a) { ++j; } for (int it = i; it < j && it < i + m; it++) { bestJudges.add(judges[it]); } i = j; } judges = bestJudges.toArray(new Judge[0]); n = judges.length; for (int i = 0; i < n; i++) { judges[i].sortedId = i; } } long[] prod = new long[1 << m]; long[] factorRaisedToPow = new long[m]; boolean[] canCover = new boolean[1 << m]; final long infinity = Long.MAX_VALUE / 2; long[][] d = new long[m + 1][1 << m]; for (long[] arr : d) { Arrays.fill(arr, infinity); } d[0][0] = 0; List<Judge>[] bestJudgesForMask = new List[1 << m]; for (int mask = 0; mask < 1 << m; mask++) { bestJudgesForMask[mask] = new ArrayList<>(); } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { Factor f = factors[j]; long x = judges[i].a; long y = 1; while (x % f.p == 0) { x /= f.p; y *= f.p; } factorRaisedToPow[j] = y; } prod[0] = 1; canCover[0] = true; for (int mask = 1; mask < 1 << m; mask++) { int j = Integer.numberOfTrailingZeros(mask); prod[mask] = prod[mask ^ (1 << j)] * factorRaisedToPow[j]; if (prod[mask] <= k) { bestJudgesForMask[mask].add(judges[i]); } } } List<Integer>[] bestMasksForJudge = new List[n]; for (int mask = 0; mask < 1 << m; mask++) { List<Judge> js = bestJudgesForMask[mask]; Collections.sort(js, (u, v) -> Integer.compare(u.e, v.e)); for (int it = 0; it < m && it < js.size(); it++) { int id = js.get(it).sortedId; if (bestMasksForJudge[id] == null) { bestMasksForJudge[id] = new ArrayList<>(); } bestMasksForJudge[id].add(mask); } } for (int judgeId = 0; judgeId < n; judgeId++) { if (bestMasksForJudge[judgeId] == null) { continue; } for (int used = m - 1; used >= 0; used--) { for (int mask : bestMasksForJudge[judgeId]) { int other = ((1 << m) - 1) ^ mask; for (int covered = other; ; covered = (covered - 1) & other) { if (d[used + 1][covered | mask] > d[used][covered] + judges[judgeId].e) { d[used + 1][covered | mask] = d[used][covered] + judges[judgeId].e; } if (covered == 0) { break; } } } } } long ans = infinity; for (int x = 0; x <= m; x++) { long y = d[x][(1 << m) - 1]; if (y < infinity) { ans = Math.min(ans, x * y); } } if (ans >= infinity) { ans = -1; } out.println(ans); } private long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } private Factor[] factorize(long n) { List<Factor> res = new ArrayList<>(); for (long p = 2; p * p <= n; p++) { if (n % p == 0) { Factor f = new Factor(); f.p = p; while (n % p == 0) { n /= p; ++f.s; } res.add(f); } } if (n > 1) { Factor f = new Factor(); f.p = n; f.s = 1; res.add(f); } return res.toArray(new Factor[0]); } class Judge implements Comparable<Judge> { long a; int e; int sortedId; public int compareTo(Judge o) { if (a != o.a) { return a < o.a ? -1 : 1; } if (e != o.e) { return e < o.e ? -1 : 1; } return 0; } } class Factor { long p; int s; } } static class FastScanner { private BufferedReader in; private StringTokenizer st; public FastScanner(InputStream stream) { in = new BufferedReader(new InputStreamReader(stream)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
JAVA
1103_D. Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k β€” your skill in Cardbluff. Each judge has a number a_i β€” an indicator of uncertainty about your entrance to the professional layer and a number e_i β€” an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x β‹… y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≀ n ≀ 10^6, 1 ≀ k ≀ 10^{12}) β€” the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≀ a_i ≀ 10^{12}) β€” the uncertainty of i-th judge The third line contains n integers in the same format (1 ≀ e_i ≀ 10^9), e_i β€” the experience of i-th judge. Output Print the single integer β€” minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1
2
10
#include <bits/stdc++.h> using namespace std; inline long long read() { long long s = 0, w = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') w = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { s = s * 10 + ch - '0'; ch = getchar(); } return s * w; } long long gcd(long long a, long long b) { return b ? gcd(b, a % b) : a; } const int N = 1e6 + 7; struct node { long long a, w; bool operator<(const node a) const { return w < a.w; } } c[N]; vector<long long> ok; long long n, m, K, res, f[12][1 << 11], g[1 << 11]; map<long long, vector<long long>> mp; void init() { n = read(), K = read(); for (int i = 1; i <= n; i++) { c[i].a = read(); res = gcd(res, c[i].a); } for (int i = 1; i <= n; i++) c[i].w = read(); if (res == 1) puts("0"), exit(0); for (int i = 2; i <= 1e6 && 1ll * i * i <= res; i++) if (res % i == 0) { ok.push_back(i); while (res % i == 0) res /= i; } if (res - 1) ok.push_back(res); m = ok.size(); for (int i = 1; i <= n; i++) { long long z = 1; for (auto j : ok) while (c[i].a % j == 0) c[i].a /= j, z *= j; mp[z].push_back(c[i].w); } } void solve() { memset(f, 2, sizeof(f)); f[0][0] = 0; for (auto t : mp) { long long x = t.first; sort(t.second.begin(), t.second.end()); if (t.second.size() > m) t.second.resize(m); vector<long long> a; for (int i = 0; i < 1 << m; i++) { long long times = 1, p = x; for (int j = 0; j < m; j++) if (i & (1 << j)) while (p % ok[j] == 0) p /= ok[j], times *= ok[j]; a.push_back(times); } for (auto p : t.second) { bool flg = 0; for (int i = m - 1; i >= 0; i--) for (int j = 0; j < 1 << m; j++) if (f[i][j] <= 1e12) { int tmp = (1 << m) - 1 - j; for (int k = tmp; k; k = (k - 1) & tmp) if (a[k] <= K) if (f[i + 1][j | k] > f[i][j] + p) f[i + 1][j | k] = f[i][j] + p, flg = 1; } if (!flg) break; } } long long ans = 1e18; for (int i = 1; i <= m; i++) ans = min(ans, f[i][(1 << m) - 1] * i); if (ans > 1e12) puts("-1"); else printf("%lld\n", ans); } int main() { init(); solve(); return 0; }
CPP
1103_D. Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k β€” your skill in Cardbluff. Each judge has a number a_i β€” an indicator of uncertainty about your entrance to the professional layer and a number e_i β€” an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x β‹… y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≀ n ≀ 10^6, 1 ≀ k ≀ 10^{12}) β€” the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≀ a_i ≀ 10^{12}) β€” the uncertainty of i-th judge The third line contains n integers in the same format (1 ≀ e_i ≀ 10^9), e_i β€” the experience of i-th judge. Output Print the single integer β€” minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1
2
10
#include <bits/stdc++.h> using std::cerr; using std::endl; inline long long read() { long long x = 0, f = 1; char ch = getchar(); while (!isdigit(ch)) { if (ch == '-') f = -1; ch = getchar(); } while (isdigit(ch)) { x = x * 10 + ch - '0'; ch = getchar(); } return x * f; } const int MAXN = 1000005; int n, cnt, mp2[(1 << 11) + 5]; long long K, d, p[MAXN], q[MAXN][12]; long long f[12][(1 << 11) + 5]; bool valid[MAXN]; std::vector<int> vec[MAXN]; std::map<long long, int> mp; struct info { long long num; int w; inline friend bool operator<(info x, info y) { return x.w < y.w; } } a[MAXN]; inline long long gcd(long long x, long long y) { if (!x || !y) return x + y; while (y) { std::swap(x, y); y %= x; } return x; } int main() { n = read(), K = read(); for (int i = (1); i <= (n); ++i) d = gcd(d, a[i].num = read()); for (int i = (1); i <= (n); ++i) a[i].w = read(); std::sort(a + 1, a + n + 1); int lim = sqrt((long double)d) + 0.5; for (int i = (2); i <= (lim); ++i) { if (d % i) continue; while (d % i == 0) d /= i; p[++cnt] = i; } if (d > 1) p[++cnt] = d; if (!cnt) { printf("0\n"); return 0; } for (int i = (1); i <= (n); ++i) { long long temp = 1; for (int j = (1); j <= (cnt); ++j) { long long temp2 = 1; while (a[i].num % p[j] == 0) { a[i].num /= p[j]; temp *= p[j]; temp2 *= p[j]; } q[i][j] = temp2; } if (mp[temp] < cnt) { ++mp[temp]; valid[i] = true; for (int s = (0); s <= ((1 << cnt) - 1); ++s) { long long temp2 = 1; for (int j = (1); j <= (cnt); ++j) if ((s >> (j - 1)) & 1) temp2 *= q[i][j]; if (temp2 <= K && mp2[s] < cnt) { ++mp2[s]; vec[i].push_back(s); } } } } memset(f, 0x3f, sizeof f); f[0][0] = 0; for (int i = (1); i <= (n); ++i) { if (!valid[i]) continue; for (int j = (cnt); j >= (1); --j) { for (auto t : vec[i]) { for (int s = t;; s = ((s + 1) | t)) { f[j][s] = std::min(f[j][s], f[j - 1][s ^ t] + a[i].w); if (s == (1 << cnt) - 1) break; } } } } long long ans = 1e18; for (int i = (1); i <= (cnt); ++i) if (f[i][(1 << cnt) - 1] < 1e18) ans = std::min(ans, i * f[i][(1 << cnt) - 1]); printf("%I64d\n", ans < 1e18 ? ans : -1); return 0; }
CPP
1103_D. Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k β€” your skill in Cardbluff. Each judge has a number a_i β€” an indicator of uncertainty about your entrance to the professional layer and a number e_i β€” an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x β‹… y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≀ n ≀ 10^6, 1 ≀ k ≀ 10^{12}) β€” the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≀ a_i ≀ 10^{12}) β€” the uncertainty of i-th judge The third line contains n integers in the same format (1 ≀ e_i ≀ 10^9), e_i β€” the experience of i-th judge. Output Print the single integer β€” minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1
2
10
#include <bits/stdc++.h> using namespace std; inline long long read() { long long a = 0; char c = getchar(); while (!isdigit(c)) c = getchar(); while (isdigit(c)) { a = a * 10 + c - 48; c = getchar(); } return a; } inline long long gcd(long long a, long long b) { long long r = a % b; while (r) { a = b; b = r; r = a % b; } return b; } const long long MAXN = 1e6 + 7; struct zt { long long num, w; bool operator<(const zt a) const { return w < a.w; } } now[MAXN]; vector<long long> in; long long N, K, allGcd, dp[12][1 << 11], calc[1 << 11]; map<long long, vector<long long> > lsh; signed main() { N = read(); K = read(); for (long long i = 1; i <= N; ++i) { now[i].num = read(); allGcd = gcd(allGcd, now[i].num); } for (long long i = 1; i <= N; ++i) now[i].w = read(); if (allGcd == 1) return puts("0"), 0; for (long long i = 2; i <= 1e6 && 1ll * i * i <= allGcd; ++i) if (allGcd % i == 0) { in.push_back(i); while (allGcd % i == 0) allGcd /= i; } if (allGcd - 1) in.push_back(allGcd); long long M = in.size(); for (long long i = 1; i <= N; ++i) { long long z = 1; for (auto j : in) while (now[i].num % j == 0) { now[i].num /= j; z *= j; } lsh[z].push_back(now[i].w); } memset(dp, 2, sizeof(dp)); dp[0][0] = 0; for (auto t : lsh) { long long x = t.first; sort(t.second.begin(), t.second.end()); if (t.second.size() > M) t.second.resize(M); vector<long long> num; for (long long i = 0; i < 1 << M; ++i) { long long times = 1, p = x; for (long long j = 0; j < M; ++j) if (i & (1 << j)) while (p % in[j] == 0) { p /= in[j]; times *= in[j]; } num.push_back(times); } for (auto p : t.second) { bool flg = 0; for (long long i = M - 1; i >= 0; --i) for (long long j = 0; j < 1 << M; ++j) if (dp[i][j] <= 1e12) { long long all = (1 << M) - 1 - j; for (long long k = all; k; k = (k - 1) & all) if (num[k] <= K) if (dp[i + 1][j | k] > dp[i][j] + p) { dp[i + 1][j | k] = dp[i][j] + p; flg = 1; } } if (!flg) break; } } long long minN = 1e18; for (long long i = 1; i <= M; ++i) minN = min(minN, dp[i][(1 << M) - 1] * i); if (minN > 1e12) cout << -1; else cout << minN; return 0; }
CPP
1103_D. Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k β€” your skill in Cardbluff. Each judge has a number a_i β€” an indicator of uncertainty about your entrance to the professional layer and a number e_i β€” an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x β‹… y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≀ n ≀ 10^6, 1 ≀ k ≀ 10^{12}) β€” the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≀ a_i ≀ 10^{12}) β€” the uncertainty of i-th judge The third line contains n integers in the same format (1 ≀ e_i ≀ 10^9), e_i β€” the experience of i-th judge. Output Print the single integer β€” minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1
2
10
#include <bits/stdc++.h> using namespace std; namespace IO { const int maxn(1 << 21 | 1); char ibuf[maxn], *iS, *iT, c; int f; inline char Getc() { return iS == iT ? (iT = (iS = ibuf) + fread(ibuf, 1, maxn, stdin), (iS == iT ? EOF : *iS++)) : *iS++; } template <class Int> void In(Int &x) { for (f = 1, c = Getc(); c < '0' || c > '9'; c = Getc()) f = c == '-' ? -1 : 1; for (x = 0; c >= '0' && c <= '9'; c = Getc()) x = x * 10 + (c ^ 48); x *= f; } } // namespace IO using IO ::In; const int maxn(1e6 + 5); int n, e[maxn], tot, id[maxn], e2[maxn], vis[1 << 11], num, st[maxn]; long long d, k, g, pr[maxn], a[maxn], b[maxn], val[maxn][12]; long long f[2][12][1 << 11], inf, ret, v[1 << 11]; map<long long, vector<int> > mp; map<long long, vector<int> >::iterator it; vector<int> tmp; inline long long Gcd(long long x, long long y) { return !y ? x : Gcd(y, x % y); } inline int Cmp(int x, int y) { return e2[x] < e2[y]; } inline long long DP() { int i, j, now, cur, lst = 0, nxt = 1, s = 1 << tot, flg; memset(f, 63, sizeof(f)), inf = ret = f[0][0][0], f[0][0][0] = 0; for (i = 1; i <= num; ++i) { for (j = 0; j < s; ++j) v[j] = 0; for (j = 1; j <= tot; ++j) v[1 << (j - 1)] = val[id[i]][j]; for (j = v[0] = 1; j < s; ++j) if (!v[j]) v[j] = v[j ^ (j & -j)] * v[j & -j]; for (now = 0; now < s; ++now) if (vis[now] <= 50) { for (flg = 0, j = min(i, tot); ~j; --j) { f[nxt][j][now] = min(f[nxt][j][now], f[lst][j][now]); if (now) { for (cur = now & st[id[i]]; cur; cur = (cur - 1) & now) if (v[cur] <= k && f[lst][j][now ^ cur] != inf) f[nxt][j + 1][now] = min(f[nxt][j + 1][now], f[lst][j][now ^ cur] + e2[id[i]]), flg = 1; } } vis[now] += flg; } swap(lst, nxt); } for (j = 0; j <= tot; ++j) if (f[lst][j][s - 1] != inf) ret = min(ret, f[lst][j][s - 1] * j); return ret == inf ? -1 : ret; } int main() { int i, j, l; In(n), In(k); for (i = 1; i <= n; ++i) In(a[i]), g = Gcd(a[i], g); for (i = 1; i <= n; ++i) In(e[i]); for (d = 2; d * d <= g; ++d) if (g % d == 0) { if (d > k) return puts("-1"), 0; pr[++tot] = d; while (g % d == 0) g /= d; } if (g > 1) pr[++tot] = g; if (g > k) return puts("-1"), 0; for (i = 1; i <= n; ++i) { for (ret = a[i], j = 1; j <= tot; ++j) while (ret % pr[j] == 0) ret /= pr[j]; a[i] /= ret; } for (i = 1; i <= n; ++i) mp[a[i]].push_back(e[i]); for (it = mp.begin(); it != mp.end(); ++it) { tmp = it->second, sort(tmp.begin(), tmp.end()), l = min(tot, (int)tmp.size()); for (i = 0; i < l; ++i) e2[++num] = tmp[i], b[num] = it->first, id[num] = num; } sort(id + 1, id + num + 1, Cmp); for (i = 1; i <= num; ++i) { for (j = 1; j <= tot; ++j) val[i][j] = 1; for (j = 1; j <= tot; ++j) while (b[i] % pr[j] == 0) st[i] |= 1 << (j - 1), b[i] /= pr[j], val[i][j] *= pr[j]; } printf("%lld\n", DP()); return 0; }
CPP
1103_D. Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k β€” your skill in Cardbluff. Each judge has a number a_i β€” an indicator of uncertainty about your entrance to the professional layer and a number e_i β€” an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x β‹… y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≀ n ≀ 10^6, 1 ≀ k ≀ 10^{12}) β€” the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≀ a_i ≀ 10^{12}) β€” the uncertainty of i-th judge The third line contains n integers in the same format (1 ≀ e_i ≀ 10^9), e_i β€” the experience of i-th judge. Output Print the single integer β€” minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1
2
10
#include <bits/stdc++.h> using namespace std; const int N1 = (int)(1e6 + 0.5); const long long N2 = (long long)(1e12 + 0.5); struct emt { long long a, cost; }; bool cmp(emt u, emt v) { return u.cost < v.cost; } emt e[N1 + 5]; unordered_map<long long, int> CNT; long long gcd(long long x, long long y) { return !x ? y : gcd(y % x, x); } vector<long long> decomdd; int prime_decomp_dd(long long x) { for (int y = 2; y <= N1; y++) { if (x % y) continue; decomdd.push_back(y); while (x % y == 0) x /= y; } if (x > 1) decomdd.push_back(x); return decomdd.size(); } long long prime_decomp_a(long long x) { long long t = 1; for (long long y : decomdd) while (x % y == 0) x /= y, t *= y; return t; } long long dp[12][1 << 11], dp1[12][1 << 11]; void work(int S, long long cost, int LEN) { int S1 = ((1 << LEN) - 1) ^ S; for (int i = 1; i <= LEN; i++) { for (int j = S1; j; j = (j - 1) & S1) dp[i][j | S] = min(dp[i][j | S], dp1[i - 1][j] + cost); dp[i][S] = min(dp[i][S], dp1[i - 1][0] + cost); } } int used[1 << 11]; int main() { int n; long long K, dd = 0; cin >> n >> K; for (int i = 1; i <= n; i++) { scanf("%lld", &e[i].a); dd = gcd(dd, e[i].a); } if (dd == 1) { puts("0"); return 0; } int LEN = prime_decomp_dd(dd); for (int i = 1; i <= n; i++) { scanf("%lld", &e[i].cost); e[i].a = prime_decomp_a(e[i].a); } sort(e + 1, e + n + 1, cmp); memset(dp, 1, sizeof(dp)); dp[0][0] = 0; for (int i = 1; i <= n; i++) { if (++CNT[e[i].a] > LEN) continue; long long mul[11], prod[1 << 11]; prod[0] = 1; for (int j = 0; j < LEN; j++) { mul[j] = 1; while (e[i].a % decomdd[j] == 0) e[i].a /= decomdd[j], mul[j] *= decomdd[j]; } bool FST = 0; for (int j = 0; j < LEN; j++) { for (int k = (1 << j); k < (1 << (j + 1)); k++) { prod[k] = prod[k ^ (1 << j)] * mul[j]; if (prod[k] <= K && used[k]++ < LEN) { if (!FST) memcpy(dp1, dp, sizeof(dp1)), FST = 1; work(k, e[i].cost, LEN); } } } } long long ans = 1e13; for (int i = 1; i <= LEN; i++) ans = min(ans, dp[i][(1 << LEN) - 1] * i); if (ans >= 1e13) ans = -1; cout << ans << endl; return 0; }
CPP
1103_D. Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k β€” your skill in Cardbluff. Each judge has a number a_i β€” an indicator of uncertainty about your entrance to the professional layer and a number e_i β€” an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x β‹… y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≀ n ≀ 10^6, 1 ≀ k ≀ 10^{12}) β€” the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≀ a_i ≀ 10^{12}) β€” the uncertainty of i-th judge The third line contains n integers in the same format (1 ≀ e_i ≀ 10^9), e_i β€” the experience of i-th judge. Output Print the single integer β€” minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1
2
10
//package round534; import java.io.*; import java.util.ArrayDeque; import java.util.Arrays; import java.util.InputMismatchException; import java.util.Queue; public class D { InputStream is; FastWriter out; long Q = 2L*3*5*7*11*13*17*19*23*29*31*37; // String INPUT = "3 " + (114514) + " " + Q + " " + Q + " " + Q + " 114 514 810"; String INPUT = ""; int[] primes = sieveEratosthenes(1000000); void solve() { int n = ni(); long K = nl(); long[] a = nal(n); int[] es = na(n); long[][] ae = new long[n][]; for(int i = 0;i < n;i++){ ae[i] = new long[]{a[i], es[i]}; } Arrays.sort(ae, (x, y) -> Long.compare(x[1], y[1])); for(int i = 0;i < n;i++){ es[i] = (int)ae[i][1]; a[i] = ae[i][0]; } long g = 0; for(long v : a){ g = gcd(g, v); } if (g == 1){ out.println(0); return; } long[][] F = factor(g, primes); int u = F.length; byte[][] as = new byte[u][n]; for(int i = 0;i < n;i++){ long v = a[i]; int q = 0; for(long[] w : F){ while(v % w[0] == 0){ v /= w[0]; as[q][i]++; } q++; } } int[][] sts = new int[1<<u][]; for(int i = 0;i < u;i++){ long r = 1; int ee = 0; for(int j = 0;;j++){ r *= F[i][0]; if(r <= K){ ee++; }else{ break; } } int[] st = new int[u]; int sp = 0; for(int j = 0;j < n;j++){ if(as[i][j] <= ee){ st[sp++] = j; if(sp == u)break; } } if(sp == 0){ out.println(-1); return; } sts[1<<i] = Arrays.copyOf(st, sp); } for(int i = 1;i < 1<<u;i++){ if(sts[i] != null)continue; int sp = 0; long zpr = 1; for(int k = 0;k < u;k++){ if(i<<~k<0){ zpr *= F[k][0]; } } if(zpr > K){ sts[i] = new int[0]; continue; } int[] st = new int[u]; for(int j = 0;j < n;j++){ long pr = 1; for(int k = 0;k < u;k++){ if(i<<~k<0){ for(int l = 0;l < as[k][j];l++){ pr *= F[k][0]; } } } if(pr > K)continue; st[sp++] = j; if(sp == u)break; } sts[i] = Arrays.copyOf(st, sp); } sts[0] = new int[0]; int[][] ig = invGraph(sts); long[][] dp = new long[u+1][1<<u]; for(int j = 0;j <= u;j++) { Arrays.fill(dp[j], Long.MAX_VALUE / 15); } dp[0][0] = 0; for(int i = 0;i < ig.length;i++){ for(int k = u-1;k >= 0;k--) { for(int e : ig[i]){ for (int j = 0; j < 1 << u; j++) { dp[k+1][j | e] = Math.min(dp[k+1][j | e], dp[k][j] + es[i]); } } } } long ans = Long.MAX_VALUE; for(int i = 1;i <= u;i++){ ans = Math.min(ans, dp[i][(1<<u)-1] * i); } out.println(ans); } public static int[][] invGraph(int[][] g) { int n = g.length; int nn = 0; for(int[] row : g){ for(int v : row){ nn = Math.max(nn, v); } } nn++; int[] p = new int[nn]; for(int f = 0;f < n;f++){ for(int t : g[f])p[t]++; } int[][] r = new int[nn][]; for(int i = 0;i < nn;i++)r[i] = new int[p[i]]; for(int f = n-1;f >= 0;f--){ for(int t : g[f])r[t][--p[t]] = f; } return r; } static long[][] factor(long n, int[] primes) { long[][] ret = new long[13][2]; int rp = 0; for(int p : primes){ if((long)p * p > n)break; int i; for(i = 0;n % p == 0;n /= p, i++); if(i > 0){ ret[rp][0] = p; ret[rp][1] = i; rp++; } } if(n > 1){ ret[rp][0] = n; ret[rp][1] = 1; rp++; } return Arrays.copyOf(ret, rp); } public static long gcd(long a, long b) { while (b > 0) { long c = a; a = b; b = c % b; } return a; } public static int[] sieveEratosthenes(int n) { if (n <= 32) { int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31}; for (int i = 0; i < primes.length; i++) { if (n < primes[i]) { return Arrays.copyOf(primes, i); } } return primes; } int u = n + 32; double lu = Math.log(u); int[] ret = new int[(int) (u / lu + u / lu / lu * 1.5)]; ret[0] = 2; int pos = 1; int[] isnp = new int[(n + 1) / 32 / 2 + 1]; int sup = (n + 1) / 32 / 2 + 1; int[] tprimes = {3, 5, 7, 11, 13, 17, 19, 23, 29, 31}; for (int tp : tprimes) { ret[pos++] = tp; int[] ptn = new int[tp]; for (int i = (tp - 3) / 2; i < tp << 5; i += tp) ptn[i >> 5] |= 1 << (i & 31); for (int j = 0; j < sup; j += tp) { for (int i = 0; i < tp && i + j < sup; i++) { isnp[j + i] |= ptn[i]; } } } // 3,5,7 // 2x+3=n int[] magic = {0, 1, 23, 2, 29, 24, 19, 3, 30, 27, 25, 11, 20, 8, 4, 13, 31, 22, 28, 18, 26, 10, 7, 12, 21, 17, 9, 6, 16, 5, 15, 14}; int h = n / 2; for (int i = 0; i < sup; i++) { for (int j = ~isnp[i]; j != 0; j &= j - 1) { int pp = i << 5 | magic[(j & -j) * 0x076be629 >>> 27]; int p = 2 * pp + 3; if (p > n) break; ret[pos++] = p; if ((long) p * p > n) continue; for (int q = (p * p - 3) / 2; q <= h; q += p) isnp[q >> 5] |= 1 << q; } } return Arrays.copyOf(ret, pos); } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new FastWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new D().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private long[] nal(int n) { long[] a = new long[n]; for(int i = 0;i < n;i++)a[i] = nl(); return a; } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[][] nmi(int n, int m) { int[][] map = new int[n][]; for(int i = 0;i < n;i++)map[i] = na(m); return map; } private int ni() { return (int)nl(); } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } public static class FastWriter { private static final int BUF_SIZE = 1<<13; private final byte[] buf = new byte[BUF_SIZE]; private final OutputStream out; private int ptr = 0; private FastWriter(){out = null;} public FastWriter(OutputStream os) { this.out = os; } public FastWriter(String path) { try { this.out = new FileOutputStream(path); } catch (FileNotFoundException e) { throw new RuntimeException("FastWriter"); } } public FastWriter write(byte b) { buf[ptr++] = b; if(ptr == BUF_SIZE)innerflush(); return this; } public FastWriter write(char c) { return write((byte)c); } public FastWriter write(char[] s) { for(char c : s){ buf[ptr++] = (byte)c; if(ptr == BUF_SIZE)innerflush(); } return this; } public FastWriter write(String s) { s.chars().forEach(c -> { buf[ptr++] = (byte)c; if(ptr == BUF_SIZE)innerflush(); }); return this; } private static int countDigits(int l) { if (l >= 1000000000) return 10; if (l >= 100000000) return 9; if (l >= 10000000) return 8; if (l >= 1000000) return 7; if (l >= 100000) return 6; if (l >= 10000) return 5; if (l >= 1000) return 4; if (l >= 100) return 3; if (l >= 10) return 2; return 1; } public FastWriter write(int x) { if(x == Integer.MIN_VALUE){ return write((long)x); } if(ptr + 12 >= BUF_SIZE)innerflush(); if(x < 0){ write((byte)'-'); x = -x; } int d = countDigits(x); for(int i = ptr + d - 1;i >= ptr;i--){ buf[i] = (byte)('0'+x%10); x /= 10; } ptr += d; return this; } private static int countDigits(long l) { if (l >= 1000000000000000000L) return 19; if (l >= 100000000000000000L) return 18; if (l >= 10000000000000000L) return 17; if (l >= 1000000000000000L) return 16; if (l >= 100000000000000L) return 15; if (l >= 10000000000000L) return 14; if (l >= 1000000000000L) return 13; if (l >= 100000000000L) return 12; if (l >= 10000000000L) return 11; if (l >= 1000000000L) return 10; if (l >= 100000000L) return 9; if (l >= 10000000L) return 8; if (l >= 1000000L) return 7; if (l >= 100000L) return 6; if (l >= 10000L) return 5; if (l >= 1000L) return 4; if (l >= 100L) return 3; if (l >= 10L) return 2; return 1; } public FastWriter write(long x) { if(x == Long.MIN_VALUE){ return write("" + x); } if(ptr + 21 >= BUF_SIZE)innerflush(); if(x < 0){ write((byte)'-'); x = -x; } int d = countDigits(x); for(int i = ptr + d - 1;i >= ptr;i--){ buf[i] = (byte)('0'+x%10); x /= 10; } ptr += d; return this; } public FastWriter write(double x, int precision) { if(x < 0){ write('-'); x = -x; } x += Math.pow(10, -precision)/2; // if(x < 0){ x = 0; } write((long)x).write("."); x -= (long)x; for(int i = 0;i < precision;i++){ x *= 10; write((char)('0'+(int)x)); x -= (int)x; } return this; } public FastWriter writeln(char c){ return write(c).writeln(); } public FastWriter writeln(int x){ return write(x).writeln(); } public FastWriter writeln(long x){ return write(x).writeln(); } public FastWriter writeln(double x, int precision){ return write(x, precision).writeln(); } public FastWriter write(int... xs) { boolean first = true; for(int x : xs) { if (!first) write(' '); first = false; write(x); } return this; } public FastWriter write(long... xs) { boolean first = true; for(long x : xs) { if (!first) write(' '); first = false; write(x); } return this; } public FastWriter writeln() { return write((byte)'\n'); } public FastWriter writeln(int... xs) { return write(xs).writeln(); } public FastWriter writeln(long... xs) { return write(xs).writeln(); } public FastWriter writeln(char[] line) { return write(line).writeln(); } public FastWriter writeln(char[]... map) { for(char[] line : map)write(line).writeln(); return this; } public FastWriter writeln(String s) { return write(s).writeln(); } private void innerflush() { try { out.write(buf, 0, ptr); ptr = 0; } catch (IOException e) { throw new RuntimeException("innerflush"); } } public void flush() { innerflush(); try { out.flush(); } catch (IOException e) { throw new RuntimeException("flush"); } } public FastWriter print(byte b) { return write(b); } public FastWriter print(char c) { return write(c); } public FastWriter print(char[] s) { return write(s); } public FastWriter print(String s) { return write(s); } public FastWriter print(int x) { return write(x); } public FastWriter print(long x) { return write(x); } public FastWriter print(double x, int precision) { return write(x, precision); } public FastWriter println(char c){ return writeln(c); } public FastWriter println(int x){ return writeln(x); } public FastWriter println(long x){ return writeln(x); } public FastWriter println(double x, int precision){ return writeln(x, precision); } public FastWriter print(int... xs) { return write(xs); } public FastWriter print(long... xs) { return write(xs); } public FastWriter println(int... xs) { return writeln(xs); } public FastWriter println(long... xs) { return writeln(xs); } public FastWriter println(char[] line) { return writeln(line); } public FastWriter println(char[]... map) { return writeln(map); } public FastWriter println(String s) { return writeln(s); } public FastWriter println() { return writeln(); } } public void trnz(int... o) { for(int i = 0;i < o.length;i++)if(o[i] != 0)System.out.print(i+":"+o[i]+" "); System.out.println(); } // print ids which are 1 public void trt(long... o) { Queue<Integer> stands = new ArrayDeque<>(); for(int i = 0;i < o.length;i++){ for(long x = o[i];x != 0;x &= x-1)stands.add(i<<6|Long.numberOfTrailingZeros(x)); } System.out.println(stands); } public void tf(boolean... r) { for(boolean x : r)System.out.print(x?'#':'.'); System.out.println(); } public void tf(boolean[]... b) { for(boolean[] r : b) { for(boolean x : r)System.out.print(x?'#':'.'); System.out.println(); } System.out.println(); } public void tf(long[]... b) { if(INPUT.length() != 0) { for (long[] r : b) { for (long x : r) { for (int i = 0; i < 64; i++) { System.out.print(x << ~i < 0 ? '#' : '.'); } } System.out.println(); } System.out.println(); } } public void tf(long... b) { if(INPUT.length() != 0) { for (long x : b) { for (int i = 0; i < 64; i++) { System.out.print(x << ~i < 0 ? '#' : '.'); } } System.out.println(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
JAVA
1103_D. Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k β€” your skill in Cardbluff. Each judge has a number a_i β€” an indicator of uncertainty about your entrance to the professional layer and a number e_i β€” an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x β‹… y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≀ n ≀ 10^6, 1 ≀ k ≀ 10^{12}) β€” the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≀ a_i ≀ 10^{12}) β€” the uncertainty of i-th judge The third line contains n integers in the same format (1 ≀ e_i ≀ 10^9), e_i β€” the experience of i-th judge. Output Print the single integer β€” minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1
2
10
#include <bits/stdc++.h> using namespace std; const int N = 1e6 + 10, M = (1 << 11) + 10; inline long long rd() { long long x = 0, w = 1; char ch = 0; while (ch < '0' || ch > '9') { if (ch == '-') w = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = (x << 3) + (x << 1) + (ch ^ 48); ch = getchar(); } return x * w; } long long gcd(long long a, long long b) { return b ? gcd(b, a % b) : a; } int n, m, nn, h[M]; long long kk, d[13], b[13], g[M], f[2][13][M], ans = 1e18; map<long long, int> c1; int c2[M]; struct node { long long a, w; bool operator<(const node &bb) const { return w < bb.w; } } a[N]; int main() { n = rd(), kk = rd(); for (int i = 1; i <= n; ++i) a[i].a = rd(); for (int i = 1; i <= n; ++i) a[i].w = rd(); sort(a + 1, a + n + 1); long long gg = a[1].a; for (int i = 2; i <= n; ++i) gg = gcd(gg, a[i].a); if (gg == 1) return puts("0"), 0; long long sqt = sqrt(gg); for (int i = 2; i <= sqt && gg > 1; ++i) if (gg % i == 0) { d[++m] = i; while (gg % i == 0) gg /= i; } if (gg > 1) d[++m] = gg; nn = 1 << m; for (int i = 1; i <= m; ++i) h[1 << (i - 1)] = i; memset(f, 1, sizeof(f)); long long inf = f[0][0][0]; int nw = 1, la = 0; f[0][0][0] = 0, g[0] = 1; for (int i = 1; i <= n; ++i) { long long sd = 1; for (int j = 1; j <= m; ++j) { b[j] = 1; while (a[i].a % d[j] == 0) sd *= d[j], b[j] *= d[j], a[i].a /= d[j]; } if (c1[sd] > m + 1) continue; ++c1[sd]; memcpy(f[nw], f[la], sizeof(f[la])); for (int j = 1; j < nn; ++j) { g[j] = g[j ^ (j & (-j))] * b[h[j & (-j)]]; if (g[j] > kk || c2[j] > m + 1) continue; ++c2[j]; for (int k = m - 1; ~k; --k) for (int l = 0; l < nn; ++l) f[nw][k + 1][j | l] = min(f[nw][k + 1][j | l], f[la][k][l] + a[i].w); } nw ^= 1, la ^= 1; } for (int i = 1; i <= m; ++i) ans = min(ans, 1ll * f[la][i][nn - 1] * i); cout << (ans < inf ? ans : -1); return 0; }
CPP
1103_D. Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k β€” your skill in Cardbluff. Each judge has a number a_i β€” an indicator of uncertainty about your entrance to the professional layer and a number e_i β€” an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x β‹… y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≀ n ≀ 10^6, 1 ≀ k ≀ 10^{12}) β€” the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≀ a_i ≀ 10^{12}) β€” the uncertainty of i-th judge The third line contains n integers in the same format (1 ≀ e_i ≀ 10^9), e_i β€” the experience of i-th judge. Output Print the single integer β€” minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1
2
10
#include <bits/stdc++.h> using namespace std; const int N1 = (int)(1e6 + 0.5); const long long N2 = (long long)(1e12 + 0.5); struct emt { long long a, cost; }; bool cmp(emt u, emt v) { return u.cost < v.cost; } emt e[N1 + 5]; unordered_map<long long, int> CNT; long long gcd(long long x, long long y) { return !x ? y : gcd(y % x, x); } long long decomdd[11], LEN; void prime_decomp_dd(long long x) { for (int y = 2; y <= N1; y++) { if (x % y) continue; decomdd[LEN++] = y; while (x % y == 0) x /= y; } if (x > 1) decomdd[LEN++] = x; } long long prime_decomp_a(long long x) { long long t = 1; for (int i = 0; i < LEN; i++) while (x % decomdd[i] == 0) x /= decomdd[i], t *= decomdd[i]; return t; } long long dp[12][1 << 11], dp1[12][1 << 11]; void work(int S, long long cost) { int S1 = ((1 << LEN) - 1) ^ S; for (int i = 1; i <= LEN; i++) { for (int j = S1; j; j = (j - 1) & S1) dp[i][j | S] = min(dp[i][j | S], dp1[i - 1][j] + cost); dp[i][S] = min(dp[i][S], dp1[i - 1][0] + cost); } } int used[1 << 11]; int main() { int n; long long K, dd = 0; cin >> n >> K; for (int i = 1; i <= n; i++) { scanf("%lld", &e[i].a); dd = gcd(dd, e[i].a); } if (dd == 1) { puts("0"); return 0; } prime_decomp_dd(dd); for (int i = 1; i <= n; i++) { scanf("%lld", &e[i].cost); e[i].a = prime_decomp_a(e[i].a); } sort(e + 1, e + n + 1, cmp); memset(dp, 1, sizeof(dp)); dp[0][0] = 0; for (int i = 1; i <= n; i++) { if (++CNT[e[i].a] > LEN) continue; long long mul[11], prod[1 << 11]; prod[0] = 1; for (int j = 0; j < LEN; j++) { mul[j] = 1; while (e[i].a % decomdd[j] == 0) e[i].a /= decomdd[j], mul[j] *= decomdd[j]; } bool FST = 0; for (int j = 0; j < LEN; j++) { for (int k = (1 << j); k < (1 << (j + 1)); k++) { prod[k] = prod[k ^ (1 << j)] * mul[j]; if (prod[k] <= K && used[k]++ < LEN) { if (!FST) memcpy(dp1, dp, sizeof(dp1)), FST = 1; work(k, e[i].cost); } } } } long long ans = 1e13; for (int i = 1; i <= LEN; i++) ans = min(ans, dp[i][(1 << LEN) - 1] * i); if (ans >= 1e13) ans = -1; cout << ans << endl; return 0; }
CPP
1103_D. Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k β€” your skill in Cardbluff. Each judge has a number a_i β€” an indicator of uncertainty about your entrance to the professional layer and a number e_i β€” an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x β‹… y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≀ n ≀ 10^6, 1 ≀ k ≀ 10^{12}) β€” the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≀ a_i ≀ 10^{12}) β€” the uncertainty of i-th judge The third line contains n integers in the same format (1 ≀ e_i ≀ 10^9), e_i β€” the experience of i-th judge. Output Print the single integer β€” minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1
2
10
#include <bits/stdc++.h> #pragma GCC optimize("Ofast") #pragma GCC optimize("unroll-loops") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") using namespace std; const int N = 1e6 + 1, PC = 11, Q = 2048; int n; long long k, g; long long a[N], e[N]; long long deg[N][PC]; bool die[N]; long long gcd(long long x, long long y) { while (y != 0) { x %= y; x ^= y ^= x ^= y; } return x; } int pc = 0; long long p[PC]; void factor() { long long h = g; for (long long i = 2; i * i <= h; i++) { if (h % i == 0) { while (h % i == 0) h /= i; p[pc++] = i; } } if (h != 1) p[pc++] = h; } pair<pair<long long, long long>, int> ord[N]; long long save[Q]; int lg[Q]; int got[Q]; vector<int> bois[N]; long long dp[2][PC + 1][Q]; void in(int& x) { char c = getchar(); while (c < 48 || c > 57) c = getchar(); x = 0; while (c >= 48 && c <= 57) { x = x * 10 + c - 48; c = getchar(); } } void in(long long& x) { char c = getchar(); while (c < 48 || c > 57) c = getchar(); x = 0; while (c >= 48 && c <= 57) { x = x * 10 + c - 48; c = getchar(); } } int main() { ios::sync_with_stdio(false); in(n); in(k); for (int i = 1; i <= n; i++) { in(a[i]); g = gcd(a[i], g); } for (int i = 1; i <= n; i++) in(e[i]); factor(); if (g == 1) { cout << "0\n"; return 0; } for (int i = 1; i <= n; i++) { long long cur = a[i]; for (int j = 0; j < pc; j++) { deg[i][j] = 1; while (cur % p[j] == 0) cur /= p[j], deg[i][j] *= p[j]; } ord[i] = {{a[i] / cur, e[i]}, i}; } sort(ord + 1, ord + n + 1); int cnt = 0; for (int i = 1; i <= n; i++) { if (ord[i].first.first != ord[i - 1].first.first) cnt = 0; ++cnt; if (cnt > pc) die[ord[i].second] = true; } for (int i = 1; i <= n; i++) ord[i] = {{e[i], 0}, i}; sort(ord + 1, ord + n + 1); for (int i = 0; i < pc; i++) lg[(1 << i)] = i; for (int i = 1; i <= n; i++) { int cur = ord[i].second; if (die[cur]) continue; save[0] = 1; for (int j = 1; j < (1 << pc); j++) { save[j] = save[j ^ (j & -j)] * deg[cur][lg[j & -j]]; if (save[j] <= k && got[j] <= pc - __builtin_popcount(j)) { ++got[j]; bois[cur].push_back(j); } } } for (int i = 0; i <= pc; i++) for (int j = 0; j < (1 << pc); j++) dp[1][i][j] = 1e17; dp[1][0][0] = 0; for (int i = 1; i <= n; i++) { if (bois[i].empty()) continue; for (int r = 0; r <= pc; r++) for (int j = 0; j < (1 << pc); j++) dp[0][r][j] = dp[1][r][j]; for (auto mk : bois[i]) { int flip = mk ^ ((1 << pc) - 1); for (int j = pc - 1; j >= 0; j--) { for (int r = flip; true; r = (r - 1) & flip) { dp[1][j + 1][r | mk] = min(dp[1][j + 1][r | mk], dp[0][j][r] + e[i]); if (r == 0) break; } } } } long long ans = 1e18; for (int i = 1; i <= pc; i++) { ans = min(ans, i * dp[1][i][(1 << pc) - 1]); } if (ans >= 1e17) cout << "-1\n"; else cout << ans << endl; }
CPP
1103_D. Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k β€” your skill in Cardbluff. Each judge has a number a_i β€” an indicator of uncertainty about your entrance to the professional layer and a number e_i β€” an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x β‹… y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≀ n ≀ 10^6, 1 ≀ k ≀ 10^{12}) β€” the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≀ a_i ≀ 10^{12}) β€” the uncertainty of i-th judge The third line contains n integers in the same format (1 ≀ e_i ≀ 10^9), e_i β€” the experience of i-th judge. Output Print the single integer β€” minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1
2
10
#include <bits/stdc++.h> using namespace std; const long long INF = 1e17; const int N = 1000010; struct dat { long long u, e; inline bool operator<(const dat &b) const { return e < b.e; } } a[N]; long long n, k, num = 0; long long dp[12][1 << 11], dp1[12][1 << 11]; long long had1[1 << 11], part[1 << 11], p[20], pk[20]; map<long long, int> had; long long GCD(long long x, long long y) { long long r; while (x) r = y % x, y = x, x = r; return y; } int main() { scanf("%lld%lld", &n, &k); long long gcd = 0; for (int i = (1); i <= (n); ++i) { scanf("%lld", &a[i].u); gcd = GCD(gcd, a[i].u); } for (int i = (1); i <= (n); ++i) scanf("%lld", &a[i].e); if (gcd == 1) { puts("0"); return 0; } sort(a + 1, a + n + 1); for (int i = 2; 1LL * i * i <= gcd; i++) { if (gcd % i == 0) { p[++num] = i; while (gcd % i == 0) gcd /= i; } } if (gcd > 1) p[++num] = gcd; for (int i = 0; i <= num; i++) for (int j = 0; j < (1 << num); j++) dp[i][j] = (j == 0) ? 0 : INF; for (int i = (1); i <= (n); ++i) { long long nw = 1; for (int j = 1; j <= num; j++) { pk[j] = 1; while (a[i].u % p[j] == 0) nw *= p[j], pk[j] *= p[j], a[i].u /= p[j]; } if (had[nw] >= num) continue; ++had[nw]; memcpy(dp1, dp, sizeof(dp)); part[0] = 1; for (int s = 0; s < num; s++) { for (int S = 0; S < 1 << s; S++) { part[S | (1 << s)] = part[S] * pk[s + 1]; if (part[S | (1 << s)] > k || had1[S | (1 << s)] >= num) continue; had1[S | (1 << s)]++; for (int l = 0; l < num; l++) for (int SS = 0; SS < (1 << num); SS++) dp[l + 1][S | SS | (1 << s)] = min(dp[l + 1][S | SS | (1 << s)], dp1[l][SS] + a[i].e); } } } long long ans = INF; for (int i = (1); i <= (num); ++i) ans = min(ans, dp[i][(1 << num) - 1] * i); cout << (ans == INF ? -1 : ans) << endl; return 0; }
CPP
1103_D. Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k β€” your skill in Cardbluff. Each judge has a number a_i β€” an indicator of uncertainty about your entrance to the professional layer and a number e_i β€” an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x β‹… y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≀ n ≀ 10^6, 1 ≀ k ≀ 10^{12}) β€” the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≀ a_i ≀ 10^{12}) β€” the uncertainty of i-th judge The third line contains n integers in the same format (1 ≀ e_i ≀ 10^9), e_i β€” the experience of i-th judge. Output Print the single integer β€” minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1
2
10
#include <bits/stdc++.h> using namespace std; inline long long read() { long long x = 0, f = 1; char c = getchar(); for (; !isdigit(c); c = getchar()) if (c == '-') f = -1; for (; isdigit(c); c = getchar()) x = x * 10 + c - '0'; return x * f; } const long long MAXN = 1000010; const long long INF = 1e15; long long N, K; struct data { long long a, e; } q[MAXN + 1], p[MAXN + 1]; long long a[MAXN + 1], e[MAXN + 1]; long long top, sta[MAXN + 1]; long long n; long long numt[12][301000]; inline long long gcd(long long a, long long b) { if (!b) return a; return gcd(b, a % b); } pair<long long, long long> val[MAXN + 1], Ts[MAXN + 1]; long long tot; vector<long long> Tns[301000]; bool cmp(data a, data b) { if (a.a != b.a) return a.a < b.a; return a.e < b.e; } long long f[13][(1 << 13)]; int main() { N = read(), K = read(); long long G = 0; for (long long i = 1; i <= N; i++) { a[i] = read(); G = gcd(G, a[i]); } for (long long i = 1; i <= N; i++) e[i] = read(); for (long long i = 2; i * i <= G; i++) { if (G % i == 0) { sta[++top] = i; while (G % i == 0) G /= i; } } if (G != 1) sta[++top] = G; for (long long i = 1; i <= N; i++) { long long x = 1; for (long long j = 1; j <= top; j++) while (a[i] % sta[j] == 0) x = x * sta[j], a[i] /= sta[j]; a[i] = x; q[i].a = a[i]; q[i].e = e[i]; } sort(q + 1, q + N + 1, cmp); long long n = 0; for (long long i = 1, r; i <= N; i = r + 1) { r = i; while (r <= N && q[r].a == q[i].a) ++r; --r; for (long long j = 1; j <= min(r - i + 1, 12LL); j++) p[++n] = q[j + i - 1]; } for (long long i = 1; i <= top; i++) for (long long j = 1; j <= n; j++) { numt[i][j] = 1; while (p[j].a % sta[i] == 0) p[j].a /= sta[i], numt[i][j] = numt[i][j] * sta[i]; } for (long long s = 1; s < (1 << top); s++) { long long tot = 0; for (long long i = 1; i <= n; i++) { long long mul = 1; for (long long j = 1; j <= top; j++) { if (s & (1 << (j - 1))) { mul = mul * numt[j][i]; if (mul > K) break; } } if (mul <= K) { val[++tot] = make_pair(p[i].e, i); } } sort(val + 1, val + tot + 1); for (long long i = 1; i <= min(12LL, tot); i++) Tns[val[i].second].push_back(s); } for (long long d = 0; d <= top; d++) for (long long k = 0; k < (1 << top); k++) f[d][k] = INF; f[0][0] = 0; for (long long i = 1; i <= n; i++) { long long tot = 0; for (long long j = 0, sz = Tns[i].size(); j < sz; j++) { long long s = Tns[i][j]; long long lf = ((1 << top) - 1) ^ s; for (long long k = lf;; k = (k - 1) & lf) { Ts[++tot] = make_pair(-k, s); if (!k) break; } } sort(Ts + 1, Ts + tot + 1); for (long long d = top - 1; d >= 0; d--) { for (long long j = 1; j <= tot; j++) { long long k = -Ts[j].first, s = Ts[j].second; f[d + 1][k | s] = min(f[d + 1][k | s], f[d][k] + p[i].e); } } } long long ans = INF; if (!top) ans = 0; for (long long d = 1; d <= top; d++) ans = min(ans, f[d][(1 << top) - 1] * d); if (ans < INF) printf("%lld\n", ans); else puts("-1"); return 0; }
CPP
1103_D. Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k β€” your skill in Cardbluff. Each judge has a number a_i β€” an indicator of uncertainty about your entrance to the professional layer and a number e_i β€” an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x β‹… y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≀ n ≀ 10^6, 1 ≀ k ≀ 10^{12}) β€” the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≀ a_i ≀ 10^{12}) β€” the uncertainty of i-th judge The third line contains n integers in the same format (1 ≀ e_i ≀ 10^9), e_i β€” the experience of i-th judge. Output Print the single integer β€” minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1
2
10
#include <bits/stdc++.h> using namespace std; const int N = 1e6 + 16; const int M = 22; const long long inf = 1e18; long long gcd(long long x, long long y) { if (!y) return x; return gcd(y, x % y); } long long Q(long long x, long long y) { long long t = x; while (t % y == 0) { t /= y; } return x / t; } int n, m, w, b[N]; long long k, g, a[N], e[N], c[N], d[2222], f[M][2222], h[M][2222], r[M][2222], rr[M][2222]; long long p[M]; map<long long, int> E; vector<long long> v[N]; int main() { int i, j, l, o, t; long long x, gg, u; scanf("%d%lld", &n, &k); g = 0; for (i = 1; i <= n; i = i + 1) scanf("%lld", a + i), g = gcd(g, a[i]); for (i = 1; i <= n; i = i + 1) scanf("%d", e + i); gg = g; for (x = 2; x * x <= g; x = x + 1) { if (g % x) continue; p[m] = x; while (g % x == 0) { g /= x; } m++; } if (g > 1) { p[m] = g; m++; } g = gg; for (i = 1; i <= n; i = i + 1) { x = 1; while (1) { u = gcd(g, a[i]); a[i] /= u; x *= u; if (u == 1) break; } a[i] = x; if (E.find(a[i]) != E.end()) b[i] = E[a[i]]; else { E[a[i]] = ++w; b[i] = w; c[w] = a[i]; } v[b[i]].push_back(e[i]); } for (i = 0; i <= m; i = i + 1) for (j = 0; j < (1 << m); j = j + 1) r[i][j] = inf; r[0][0] = 0; for (i = 1; i <= w; i = i + 1) { sort(v[i].begin(), v[i].end()); d[0] = 1; for (j = 0; j < m; j = j + 1) d[1 << j] = Q(c[i], p[j]); for (j = 1; j < (1 << m); j = j + 1) d[j] = d[j & -j] * d[j ^ (j & -j)]; for (j = 0; j < (1 << m); j = j + 1) f[0][j] = inf, h[0][j] = 0; f[0][0] = 0; h[0][0] = 1; for (o = 0; o < m && o < v[i].size(); o = o + 1) { for (j = 0; j < (1 << m); j = j + 1) f[o + 1][j] = inf, h[o + 1][j] = 0; for (j = 0; j < (1 << m); j = j + 1) if (h[o][j]) { for (l = j; l < (1 << m); l = (l + 1) | j) if (d[l ^ j] <= k && f[o + 1][l] > f[o][j] + v[i][o]) f[o + 1][l] = f[o][j] + v[i][o], h[o + 1][l] = 1; } } for (o = 0; o <= m; o = o + 1) for (j = 0; j < (1 << m); j = j + 1) rr[o][j] = inf; for (o = 1; o <= m && o <= v[i].size(); o = o + 1) { for (j = 0; j < (1 << m); j = j + 1) if (h[o][j]) { for (t = 0; t + o <= m; t = t + 1) { for (l = j; l < (1 << m); l = (l + 1) | j) if (rr[t + o][l] > r[t][l ^ j] + f[o][j]) rr[t + o][l] = r[t][l ^ j] + f[o][j]; } } } for (o = 0; o <= m; o = o + 1) for (j = 0; j < (1 << m); j = j + 1) r[o][j] = min(r[o][j], rr[o][j]); } x = inf; for (i = 0; i <= m; i = i + 1) { if (r[i][(1 << m) - 1] < inf) x = min(x, (long long)r[i][(1 << m) - 1] * i); } if (x >= inf) x = -1; cout << x; return 0; }
CPP
1103_D. Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k β€” your skill in Cardbluff. Each judge has a number a_i β€” an indicator of uncertainty about your entrance to the professional layer and a number e_i β€” an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x β‹… y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≀ n ≀ 10^6, 1 ≀ k ≀ 10^{12}) β€” the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≀ a_i ≀ 10^{12}) β€” the uncertainty of i-th judge The third line contains n integers in the same format (1 ≀ e_i ≀ 10^9), e_i β€” the experience of i-th judge. Output Print the single integer β€” minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1
2
10
#include <bits/stdc++.h> #pragma GCC optimize(2) #pragma GCC optimize(3) #pragma GCC optimize("Ofast") #pragma GCC optimize("inline") using namespace std; inline long long read() { long long s = 0, f = 1; char c = getchar(); ; while (c < '0' || c > '9') { if (c == '-') f = -1; c = getchar(); ; } while (c >= '0' && c <= '9') { s = s * 10 + c - '0'; c = getchar(); ; } return s * f; } const int N = 1e6 + 5; const int M = 2048; const long long Inf = 1ll << 60; int n, m, U, w[N]; long long K, D, Ans, a[N], p[12], dp[12][M]; unordered_map<long long, vector<int>> mp; unordered_map<long long, vector<long long>> H; vector<int> G[N]; struct cmp { bool operator()(int x, int y) { return w[x] < w[y]; } }; priority_queue<int, vector<int>, cmp> q; long long Gcd(long long a, long long b) { return !b ? a : Gcd(b, a % b); } int Ins(int x) { if (q.size() < m) return q.push(x), 1; else if (w[q.top()] > w[x]) return q.pop(), q.push(x), 1; return 0; } int main() { n = read(), K = read(); for (int i = 1; i <= n; i++) a[i] = read(), D = !D ? a[i] : Gcd(D, a[i]); for (int i = 1; i <= n; i++) w[i] = read(); for (int i = 2; 1ll * i * i <= D; i++) if (D % i == 0) { p[m++] = i; while (D % i == 0) D /= i; } if (D > 1) p[m++] = D; U = (1 << m) - 1; if (m == 0) return printf("0"), 0; for (int i = 1; i <= n; i++) { long long res = 1, tp = 1; for (int j = 0; j < m; j++) while (a[i] % p[j] == 0) a[i] /= p[j], res *= p[j]; mp[a[i] = res].push_back(i); if (!H[a[i]].size()) { vector<long long> F; F.resize(U + 1); for (int j = 0; j < m; j++) { F[1 << j] = 1; while (res % p[j] == 0) res /= p[j], F[1 << j] *= p[j]; } F[0] = 1; for (int S = 1; S <= U; S++) F[S] = F[S - (S & -S)] * F[S & -S]; H[a[i]] = F; } } for (auto T : mp) { vector<int> F; for (auto t : T.second) Ins(t); while (q.size()) F.push_back(q.top()), q.pop(); reverse(F.begin(), F.end()), mp[T.first] = F; } for (int S = 1; S <= U; S++) { for (auto T : mp) { if (H[T.first][S] > K) continue; for (auto t : T.second) if (!Ins(t)) break; } while (q.size()) G[q.top()].push_back(S), q.pop(); } for (int i = 0; i <= m; i++) for (int S = 0; S <= U; S++) dp[i][S] = Inf; Ans = Inf, dp[0][0] = 0; for (int i = 1; i <= n; i++) if (G[i].size()) for (int j = m; j >= 1; j--) for (auto S : G[i]) { int C = U ^ S; for (int T = C;; (--T) &= C) { dp[j][T | S] = min(dp[j][T | S], dp[j - 1][T] + w[i]); if (!T) break; } } for (int i = 0; i <= m; i++) if (dp[i][U] < Inf) Ans = min(Ans, dp[i][U] * i); printf("%lld", Ans < Inf ? Ans : -1); return 0; }
CPP
1103_D. Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k β€” your skill in Cardbluff. Each judge has a number a_i β€” an indicator of uncertainty about your entrance to the professional layer and a number e_i β€” an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x β‹… y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≀ n ≀ 10^6, 1 ≀ k ≀ 10^{12}) β€” the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≀ a_i ≀ 10^{12}) β€” the uncertainty of i-th judge The third line contains n integers in the same format (1 ≀ e_i ≀ 10^9), e_i β€” the experience of i-th judge. Output Print the single integer β€” minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1
2
10
#include <bits/stdc++.h> #pragma GCC optimize("O3") #pragma GCC target("sse4") using namespace std; const int SITO_MAX = 1000000; int f[SITO_MAX + 1]; vector<int> prosti; template <class T> T gcd(T a, T b) { T t; while (a) { t = a; a = b % a; b = t; } return b; } struct sito { sito() { for (int i = 2; i <= SITO_MAX; i++) { if (f[i] == 0) { f[i] = i; prosti.push_back(i); } int j = 0; while (j < (int)prosti.size()) { if (prosti[j] > f[i]) { break; } int x = i * prosti[j]; if (x > SITO_MAX) { break; } f[x] = prosti[j]; j++; } } } } sito_obj_983431; vector<pair<long long, int>> factor(long long x) { vector<pair<long long, int>> v; for (int p : prosti) { if (x % p == 0) { int c = 0; while (x % p == 0) { x /= p; c++; } v.push_back({p, c}); } } if (x > 1) { v.push_back({x, 1}); } return v; } int n, m; long long p[11], k, a[1000005], g; int e[1000005]; long long gg[1000005][11]; bool cmp_eid(int i, int j) { return e[i] < e[j]; } map<long long, basic_string<int>> mp; basic_string<int> choose_m(basic_string<int> a, basic_string<int> b) { basic_string<int> out(2 * m, 0); int elems = merge(a.begin(), a.end(), b.begin(), b.end(), out.begin(), cmp_eid) - out.begin(); elems = unique(out.begin(), out.begin() + elems) - out.begin(); elems = min(elems, m); out.resize(elems); return out; } basic_string<int> masks[1 << 11]; basic_string<int> inv_masks[1000005]; long long dp[2][1 << 11][12]; long long mul(long long x, long long y) { if (x * 1.0 * y > 1e18) return 1e18; return x * y; } void mn(long long& x, long long y) { x = min(x, y); } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); cerr.tie(nullptr); cin >> n >> k; for (int i = 0; i < n; i++) { cin >> a[i]; g = gcd(g, a[i]); } for (int i = 0; i < n; i++) cin >> e[i]; if (g == 1) { cout << "0\n"; return 0; } { auto v = factor(g); for (auto ee : v) { p[m++] = ee.first; } } for (int i = 0; i < n; i++) { long long tmp = a[i], prod = 1; for (int j = 0; j < m; j++) { long long p = ::p[j]; gg[i][j] = 1; while (tmp % p == 0) { tmp /= p; prod *= p; gg[i][j] *= p; } } mp[prod] += i; } for (auto& ee : mp) { sort(ee.second.begin(), ee.second.end(), cmp_eid); int sz = min((int)ee.second.size(), m); ee.second.resize(sz); auto alpha = gg[ee.second[0]]; for (int mask = 0; mask < (1 << m); mask++) { long long prod = 1; for (int i = 0; i < m; i++) if (mask & (1 << i)) prod *= alpha[i]; if (prod <= k) { for (int x : ee.second) inv_masks[x] += mask; } } } auto ol = dp[0], nu = dp[1]; memset(ol, 63, sizeof(dp[0])); ol[0][0] = 0; int fm = (1 << m) - 1; for (int i = 0; i < n; i++) { if (inv_masks[i].size()) { memset(nu, 63, sizeof(dp[0])); for (int diff_mask : inv_masks[i]) { for (int mask = fm - diff_mask; mask; mask = (mask - 1) & (fm - diff_mask)) { for (int br = 0; br < m; br++) { mn(nu[mask | diff_mask][br + 1], ol[mask][br] + e[i]); } } for (int br = 0; br < m; br++) { mn(nu[0 | diff_mask][br + 1], ol[0][br] + e[i]); } } for (int mask = 0; mask <= fm; mask++) { for (int br = 0; br <= m; br++) { mn(nu[mask][br], ol[mask][br]); } } swap(ol, nu); } } long long sol_all = 123123123123123123ll; for (int i = 1; i <= m; i++) { mn(sol_all, mul(i, ol[fm][i])); } if (sol_all == 123123123123123123ll) sol_all = -1; cout << sol_all << '\n'; }
CPP
1103_D. Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k β€” your skill in Cardbluff. Each judge has a number a_i β€” an indicator of uncertainty about your entrance to the professional layer and a number e_i β€” an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x β‹… y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≀ n ≀ 10^6, 1 ≀ k ≀ 10^{12}) β€” the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≀ a_i ≀ 10^{12}) β€” the uncertainty of i-th judge The third line contains n integers in the same format (1 ≀ e_i ≀ 10^9), e_i β€” the experience of i-th judge. Output Print the single integer β€” minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1
2
10
#include <bits/stdc++.h> using namespace std; const int inf = (int)1.01e9; const long long infll = (long long)1.01e18; const long double eps = 1e-9; const long double pi = acos((long double)-1); mt19937 mrand(chrono::steady_clock::now().time_since_epoch().count()); int rnd(int x) { return mrand() % x; } void precalc() {} long long gcd(long long a, long long b) { return (b ? gcd(b, a % b) : a); } const long long maxx = (long long)1e12; const int maxn = (int)1e6 + 5; int n; long long b; long long a[maxn]; int e[maxn]; bool read() { if (scanf("%d%lld", &n, &b) < 2) { return false; } for (int i = 0; i < n; i++) { scanf("%lld", &a[i]); } for (int i = 0; i < n; i++) { scanf("%d", &e[i]); } return true; } pair<long long, int> tosort[maxn]; int isGood[maxn]; int k; vector<long long> ps; vector<vector<int>> good; bool add(int msk, int id) { if (((int)(good[msk]).size()) >= k && e[good[msk].back()] <= e[id]) { return false; } if (((int)(good[msk]).size()) >= k) { good[msk].pop_back(); } int pos = ((int)(good[msk]).size()); good[msk].push_back(id); while (pos && e[good[msk][pos]] < e[good[msk][pos - 1]]) { swap(good[msk][pos], good[msk][pos - 1]); pos--; } return true; } vector<vector<long long>> dp, ndp; void solve() { long long g = a[0]; for (int i = 1; i < n; i++) { g = gcd(g, a[i]); } if (g == 1) { printf("0\n"); return; } { ps.clear(); long long x = g; for (long long d = 2; d * d <= x; d++) { if (!(x % d)) { ps.push_back(d); while (!(x % d)) { x /= d; } } } if (x > 1) { ps.push_back(x); } } k = ((int)(ps).size()); for (int i = 0; i < n; i++) { long long x = 1; auto &cur = a[i]; for (int j = 0; j < k; j++) { while (!(cur % ps[j])) { cur /= ps[j]; x *= ps[j]; } } cur = x; } for (int i = 0; i < n; i++) { tosort[i] = make_pair(a[i], e[i]); } sort(tosort, tosort + n); for (int i = 0; i < n; i++) { a[i] = tosort[i].first; e[i] = tosort[i].second; } good.clear(); good.resize((1 << k)); for (int i = 0; i < n; i++) { isGood[i] = false; } for (int j = 0; j < n;) { int i = j; while (j < n && a[j] == a[i]) { j++; } vector<int> qs(k, 0); { long long x = a[i]; for (int it = 0; it < k; it++) { while (!(x % ps[it])) { x /= ps[it]; qs[it]++; } } } for (int msk = 0; msk < (1 << k); msk++) { long long y = 1; for (int it = 0; it < k; it++) { if (!(msk & (1 << it))) { continue; } for (int it0 = 0; it0 < qs[it]; it0++) { y *= ps[it]; } } if (y > b) { continue; } int pos = i; while (pos < j) { if (!add(msk, pos)) { break; } isGood[pos] = true; pos++; } } } dp = vector<vector<long long>>((1 << k), vector<long long>(k + 1, infll)); dp[0][0] = 0; int ob = 0; for (int i = 0; i < n; i++) { if (!isGood[i]) { continue; } ob++; ndp = vector<vector<long long>>((1 << k), vector<long long>(k + 1, infll)); vector<int> qs(k, 0); { long long x = a[i]; for (int it = 0; it < k; it++) { while (!(x % ps[it])) { x /= ps[it]; qs[it]++; } } } vector<int> ok(1 << k); for (int msk = 0; msk < (1 << k); msk++) { long long y = 1; for (int it = 0; it < k; it++) { if (!(msk & (1 << it))) { continue; } for (int it0 = 0; it0 < qs[it]; it0++) { y *= ps[it]; } } ok[msk] = (y <= b); } for (int msk = 0; msk < (1 << k); msk++) { for (int cnt = 0; cnt <= k; cnt++) { auto cur = dp[msk][cnt]; if (cur >= infll) { continue; } { auto &nxt = ndp[msk][cnt]; nxt = min(nxt, cur); } if (cnt >= k) { continue; } int msk1 = (((1 << k) - 1) ^ msk); for (int nmsk = msk1; nmsk > 0; nmsk = ((nmsk - 1) & msk1)) { if (!ok[nmsk]) { continue; } auto &nxt = ndp[msk | nmsk][cnt + 1]; nxt = min(nxt, cur + e[i]); } } } swap(dp, ndp); } long long res = infll; for (int cnt = 1; cnt <= k; cnt++) { if (dp[(1 << k) - 1][cnt] < infll) { res = min(res, cnt * dp[(1 << k) - 1][cnt]); } } if (res >= infll) { res = -1; } printf("%lld\n", res); if (ob > 205) cout << k << " " << ob; } int main() { precalc(); while (read()) { solve(); } return 0; }
CPP
1103_D. Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k β€” your skill in Cardbluff. Each judge has a number a_i β€” an indicator of uncertainty about your entrance to the professional layer and a number e_i β€” an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x β‹… y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≀ n ≀ 10^6, 1 ≀ k ≀ 10^{12}) β€” the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≀ a_i ≀ 10^{12}) β€” the uncertainty of i-th judge The third line contains n integers in the same format (1 ≀ e_i ≀ 10^9), e_i β€” the experience of i-th judge. Output Print the single integer β€” minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1
2
10
#include <bits/stdc++.h> using namespace std; inline int gi() { int f = 1, sum = 0; char ch = getchar(); while (ch > '9' || ch < '0') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { sum = (sum << 3) + (sum << 1) + ch - '0'; ch = getchar(); } return f * sum; } inline long long gl() { long long f = 1, sum = 0; char ch = getchar(); while (ch > '9' || ch < '0') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { sum = (sum << 3) + (sum << 1) + ch - '0'; ch = getchar(); } return f * sum; } const int N = 1000010; const long long Inf = 1e18 + 10; struct node { long long a; int e; bool operator<(const node b) const { return e < b.e; } } a[N]; int n, m; long long k, Gcd; long long f[12][5010], g[12][5010], v[5010], p[N]; int h[5010]; map<long long, int> H; int lowbit(int x) { return x & (-x); } long long gcd(long long a, long long b) { if (!b) return a; return gcd(b, a % b); } int main() { n = gi(); k = gl(); for (int i = 1; i <= n; i++) a[i].a = gl(); for (int i = 1; i <= n; i++) a[i].e = gi(); sort(a + 1, a + n + 1); Gcd = a[1].a; for (int i = 1; i <= n; i++) Gcd = gcd(Gcd, a[i].a); if (Gcd == 1) { puts("0"); return 0; } for (long long i = 2; i * i <= Gcd; i++) if (Gcd % i == 0) { p[m++] = i; while (Gcd % i == 0) Gcd /= i; } if (Gcd > 1) p[m++] = Gcd; for (int i = 0; i <= m; i++) for (int j = 1; j < 1 << m; j++) f[i][j] = Inf; for (int i = 1; i <= n; i++) { long long now = 1; for (int j = 0; j < m; j++) { long long Now = 1; while (a[i].a % p[j] == 0) { Now *= p[j]; a[i].a /= p[j]; } now *= Now; v[1 << j] = Now; } if (++H[now] > m) continue; memcpy(g, f, sizeof(f)); v[0] = 1; for (int s = 1; s < (1 << m); s++) { int low = lowbit(s); v[s] = v[s ^ low] * v[low]; if (v[s] > k) continue; if (++h[s] > m) continue; int c = ((1 << m) - 1) ^ s; for (int x = 0; x < m; x++) { for (int s2 = c; s2; s2 = (s2 - 1) & c) f[x + 1][s2 | s] = min(f[x + 1][s2 | s], g[x][s2] + a[i].e); f[x + 1][s] = min(f[x + 1][s], (long long)a[i].e); } } } long long ans = Inf; for (int i = 1; i <= m; i++) ans = min(ans, f[i][(1 << m) - 1] * i); if (ans == Inf) ans = -1; printf("%lld\n", ans); return 0; }
CPP
1103_D. Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k β€” your skill in Cardbluff. Each judge has a number a_i β€” an indicator of uncertainty about your entrance to the professional layer and a number e_i β€” an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x β‹… y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≀ n ≀ 10^6, 1 ≀ k ≀ 10^{12}) β€” the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≀ a_i ≀ 10^{12}) β€” the uncertainty of i-th judge The third line contains n integers in the same format (1 ≀ e_i ≀ 10^9), e_i β€” the experience of i-th judge. Output Print the single integer β€” minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1
2
10
#include <bits/stdc++.h> using namespace std; inline long long read() { long long data = 0, w = 1; char ch = 0; while (ch != '-' && (ch < '0' || ch > '9')) ch = getchar(); if (ch == '-') w = -1, ch = getchar(); while (ch >= '0' && ch <= '9') data = data * 10 + ch - '0', ch = getchar(); return data * w; } long long n, K, p[1000005]; void SP(long long x) { if (!p[0]) { for (long long i = 2; i * i <= x; i++) { if (x % i == 0) p[++p[0]] = i; while (x % i == 0) x /= i; } if (x > 1) p[++p[0]] = x; } else { long long m = 0; for (long long i = 1; i <= p[0]; i++) if (x % p[i] == 0) p[++m] = p[i]; p[0] = m; } } struct node { long long a, e, s[12]; } t[1000005]; long long num[1000005], mul[1000005], Log[1000005], f[12][(1 << 11) + 5]; int main() { n = read(), K = read(); for (long long i = 1; i <= n; i++) t[i].a = read(), SP(t[i].a); for (long long i = 1; i <= n; i++) { long long x = t[i].a; t[i].a = 1; for (long long j = 1; j <= p[0]; j++) { t[i].s[j] = 1; while (x % p[j] == 0) t[i].s[j] *= p[j], x /= p[j]; t[i].a *= t[i].s[j]; } } for (long long i = 1; i <= n; i++) t[i].e = read(); sort(t + 1, t + n + 1, [](node A, node B) { return A.a < B.a || A.a == B.a && A.e < B.e; }); long long m = 0; for (long long i = 1, j; i <= n; i = j) { j = i; while (t[j].a == t[i].a) ++j; for (long long k = i; k <= min(j - 1, i + p[0] - 1); k++) t[++m] = t[k]; } n = m; sort(t + 1, t + n + 1, [](node A, node B) { return A.e < B.e; }); for (long long i = 0; i <= p[0]; i++) Log[1 << i] = i + 1; memset(f, 0x3f, sizeof(f)); int M = (1 << p[0]) - 1; f[0][M] = 0; for (long long i = 1; i <= n; i++) { mul[0] = 1; for (long long st = 1; st <= M; st++) { if ((st & -st) == st) mul[st] = t[i].s[Log[st]]; else mul[st] = mul[st & -st] * mul[st ^ st & -st]; } for (long long s1 = 1; s1 <= M; s1++) num[s1] += (mul[s1] <= K); for (long long j = p[0] - 1; j >= 0; j--) for (long long s1 = 1; s1 <= M; s1++) { if (mul[s1] <= K) if (num[s1] <= p[0]) for (long long s = s1; s < 1 << p[0]; s = (s + 1) | s1) if (f[j][s] < 1e18) f[j + 1][s ^ s1] = min(f[j + 1][s ^ s1], f[j][s] + t[i].e); } } long long Ans = 1e18; for (long long i = 0; i <= p[0]; i++) if (f[i][0] < 1e18) Ans = min(Ans, f[i][0] * i); if (Ans == 1e18) puts("-1"); else cout << Ans << '\n'; return 0; }
CPP
1103_D. Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k β€” your skill in Cardbluff. Each judge has a number a_i β€” an indicator of uncertainty about your entrance to the professional layer and a number e_i β€” an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x β‹… y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≀ n ≀ 10^6, 1 ≀ k ≀ 10^{12}) β€” the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≀ a_i ≀ 10^{12}) β€” the uncertainty of i-th judge The third line contains n integers in the same format (1 ≀ e_i ≀ 10^9), e_i β€” the experience of i-th judge. Output Print the single integer β€” minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1
2
10
#include <bits/stdc++.h> using namespace std; namespace mine { long long qread() { long long ans = 0, f = 1; char c = getchar(); while (c < '0' or c > '9') { if (c == '-') f = -1; c = getchar(); } while ('0' <= c and c <= '9') ans = ans * 10 + c - '0', c = getchar(); return ans * f; } void write(long long num) { if (num < 0) putchar('-'), num = -num; if (num >= 10) write(num / 10); putchar('0' + num % 10); } void write1(long long num) { write(num); putchar(' '); } void write2(long long num) { write(num); putchar('\n'); } template <typename T> inline bool chmax(T &a, const T &b) { return a < b ? a = b, 1 : 0; } template <typename T> inline bool chmin(T &a, const T &b) { return a > b ? a = b, 1 : 0; } long long gcd(long long x, long long y) { return y ? gcd(y, x % y) : x; } bool IN(long long x, long long l, long long r) { return l <= x and x <= r; } void GG() { puts("-1"); exit(0); } const double eps = 1e-8; const int INF = 0x3f3f3f3f; const int MOD = 998244353; int mm(const int x) { return x >= MOD ? x - MOD : x; } template <typename T> void add(T &x, const int &y) { x = (x + y >= MOD ? x + y - MOD : x + y); } long long qpower(long long x, long long e, int mod = MOD) { long long ans = 1; while (e) { if (e & 1) ans = ans * x % mod; x = x * x % mod; e >>= 1; } return ans; } long long invm(long long x) { return qpower(x, MOD - 2); } const int MM = 1e6 + 10; long long fac[MM], facinv[MM], Inv[MM]; long long Comb(int n, int m) { return n < 0 or m < 0 or n < m ? 0 : fac[n] * facinv[m] % MOD * facinv[n - m] % MOD; } void PRE() { fac[0] = 1; for (int i = (1), I = (MM - 1); i <= I; i++) fac[i] = fac[i - 1] * i % MOD; facinv[MM - 1] = invm(fac[MM - 1]); for (int i = (MM - 1), I = (1); i >= I; i--) facinv[i - 1] = facinv[i] * i % MOD; Inv[1] = 1; for (int i = (2), I = (MM - 1); i <= I; i++) Inv[i] = (MOD - MOD / i) * Inv[MOD % i] % MOD; } const int N = 1e6 + 10; map<long long, vector<int> > num; pair<long long, long long> a[N]; long long f[15][1 << 15], g[15][1 << 15]; vector<int> can[N]; void main() { long long n = qread(), K = qread(), D = 0; for (int i = (1), I = (n); i <= I; i++) a[i].first = qread(), D = gcd(D, a[i].first); for (int i = (1), I = (n); i <= I; i++) a[i].second = qread(); vector<long long> pr; for (long long d = 2; d * d <= D; d++) if (D % d == 0) { pr.push_back(d); while (D % d == 0) D /= d; } if (D > 1) pr.push_back(D); int z = ((int)(pr).size()); for (int i = (1), I = (n); i <= I; i++) { long long nw = 1; for (auto p : pr) while (a[i].first % p == 0) a[i].first /= p, nw *= p; num[nw].push_back(a[i].second); } n = 0; for (auto i : num) { sort((i.second).begin(), (i.second).end()); for (int j = (0), I = (((int)(i.second).size()) - 1); j <= I; j++) if (j < z) a[++n] = {i.first, i.second[j]}; } for (int s = (1), I = ((1ll << (z)) - 1); s <= I; s++) { priority_queue<pair<int, int> > q; for (int i = (1), I = (n); i <= I; i++) { long long ss = 1, now = a[i].first; for (int i = (0), I = (z - 1); i <= I; i++) if (s & (1ll << (i))) while (now % pr[i] == 0) now /= pr[i], ss *= pr[i]; if (ss <= K) { if (((int)(q).size()) < z) q.push({a[i].second, i}); else if (q.top().first > a[i].second) q.pop(), q.push({a[i].second, i}); } } while (((int)(q).size())) can[q.top().second].push_back(s), q.pop(); } memset(f, 0x3f, sizeof f); f[0][0] = 0; for (int i = (1), I = (n); i <= I; i++) if (((int)(can[i]).size())) { for (int ct = (0), I = (z); ct <= I; ct++) for (int s = (0), I = ((1ll << (z)) - 1); s <= I; s++) g[ct][s] = f[ct][s]; for (int ct = (0), I = (z - 1); ct <= I; ct++) for (auto ad : can[i]) for (auto s = ad; s < (1ll << (z)); s = (s + 1) | ad) chmin(f[ct + 1][s], g[ct][s ^ ad] + a[i].second); } long long ans = (1ll << (62)); for (int ct = (0), I = (z); ct <= I; ct++) if (f[ct][(1ll << (z)) - 1] < f[0][1]) chmin(ans, ct * f[ct][(1ll << (z)) - 1]); write(ans >= (1ll << (62)) ? -1 : ans); } }; // namespace mine signed main() { srand(time(0)); mine::main(); printf(""); }
CPP
1103_D. Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k β€” your skill in Cardbluff. Each judge has a number a_i β€” an indicator of uncertainty about your entrance to the professional layer and a number e_i β€” an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x β‹… y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≀ n ≀ 10^6, 1 ≀ k ≀ 10^{12}) β€” the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≀ a_i ≀ 10^{12}) β€” the uncertainty of i-th judge The third line contains n integers in the same format (1 ≀ e_i ≀ 10^9), e_i β€” the experience of i-th judge. Output Print the single integer β€” minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1
2
10
#include <bits/stdc++.h> using namespace std; int n; long long k; long long p[1100]; long long dp[1 << 12][13]; long long dp1[1 << 12][13]; long long ff[1 << 12]; int used[1 << 12]; int len; long long a[1100000]; long long b[1100000]; long long mul[1100000]; int id[1100000]; int e[1100000]; unordered_map<long long, int> app; bool cmp(int x, int y) { return e[x] < e[y]; } long long gcd(long long x, long long y) { if (!x) return y; return gcd(y % x, x); } void conv(int mask, int e) { for (int i = len - 1; i >= 0; i--) for (int j = 0; j < (1 << len); j++) if (__builtin_popcount(j & mask) == 0) dp[j | mask][i + 1] = min(dp[j | mask][i + 1], dp1[j][i] + e); } int main() { scanf("%d%lld", &n, &k); for (int i = 1; i <= n; i++) scanf("%lld", &a[i]); for (int i = 1; i <= n; i++) scanf("%d", &e[i]); long long GCD = 0; for (int i = 1; i <= n; i++) GCD = gcd(GCD, a[i]); for (long long ll = 2; ll * ll <= GCD; ll++) if (GCD % ll == 0) { p[len] = ll; len++; while (GCD % ll == 0) GCD /= ll; } if (GCD > 1) p[len++] = GCD; if (len == 0) { printf("0\n"); return 0; } for (int i = 1; i <= n; i++) { b[i] = 1; for (int j = 0; j < len; j++) while (a[i] % p[j] == 0) { b[i] *= p[j]; a[i] /= p[j]; } } for (int i = 1; i <= n; i++) id[i] = i; sort(id + 1, id + n + 1, cmp); for (int i = 0; i < (1 << len); i++) for (int j = 0; j <= len; j++) dp[i][j] = 1e16; dp[0][0] = 0; for (int i = 1; i <= n; i++) { app[b[id[i]]]++; if (app[b[id[i]]] > len) continue; for (int j = 0; j < len; j++) { mul[j] = 1; while (b[id[i]] % p[j] == 0) { mul[j] *= p[j]; b[id[i]] /= p[j]; } } bool FIRST = false; ff[0] = 1; for (int j = 1; j < 1 << len; ++j) { int p = __builtin_ctz(j); ff[j] = ff[j ^ 1 << p] * mul[p]; if (ff[j] <= k && used[j] < len) { if (!FIRST) { memcpy(dp1, dp, sizeof dp); FIRST = true; } conv(j, e[id[i]]); used[j]++; } } } long long ans = 1e18; for (int i = 1; i <= len; i++) ans = min(ans, 1LL * i * dp[(1 << len) - 1][i]); if (ans < 1e15) printf("%lld\n", ans); else printf("-1\n"); }
CPP
1103_D. Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k β€” your skill in Cardbluff. Each judge has a number a_i β€” an indicator of uncertainty about your entrance to the professional layer and a number e_i β€” an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x β‹… y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≀ n ≀ 10^6, 1 ≀ k ≀ 10^{12}) β€” the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≀ a_i ≀ 10^{12}) β€” the uncertainty of i-th judge The third line contains n integers in the same format (1 ≀ e_i ≀ 10^9), e_i β€” the experience of i-th judge. Output Print the single integer β€” minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1
2
10
#include <bits/stdc++.h> #pragma comment(linker, "/STACK:512000000") using namespace std; void solve(__attribute__((unused)) bool); void precalc(); clock_t start; int main() { start = clock(); int t = 1; cout.sync_with_stdio(0); cin.tie(0); precalc(); cout.precision(10); cout << fixed; int testNum = 1; while (t--) { solve(true); } cout.flush(); return 0; } template <typename T> T binpow(T q, T w, T mod) { if (!w) return 1 % mod; if (w & 1) return q * 1LL * binpow(q, w - 1, mod) % mod; return binpow(q * 1LL * q % mod, w / 2, mod); } template <typename T> T gcd(T q, T w) { while (w) { q %= w; swap(q, w); } return q; } template <typename T> T lcm(T q, T w) { return q / gcd(q, w) * w; } template <typename T> void make_unique(vector<T>& a) { sort(a.begin(), a.end()); a.erase(unique(a.begin(), a.end()), a.end()); } template <typename T> void relax_min(T& cur, T val) { cur = min(cur, val); } template <typename T> void relax_max(T& cur, T val) { cur = max(cur, val); } void precalc() {} long long dp[2][12][1 << 12]; void solve(__attribute__((unused)) bool read) { long long n, k; if (read) { cin >> n >> k; } else { n = 1e6; k = 1e12; } vector<long long> a(n), cost(n); long long g = 0; for (long long i = 0; i < n; ++i) { if (read) { cin >> a[i]; } else { a[i] = 200560490130LL; } g = gcd(a[i], g); } for (long long i = 0; i < n; ++i) { if (read) { cin >> cost[i]; } else { cost[i] = rand(); } } vector<long long> primes; for (long long p = 2; p * p <= g; ++p) { if (g % p == 0) { primes.push_back(p); while (g % p == 0) { g /= p; } } } if (g > 1) { primes.push_back(g); } if (primes.empty()) { cout << "0\n"; return; } vector<pair<long long, long long>> mapa; for (long long i = 0; i < n; ++i) { long long cur_val = 1; for (long long j = 0; j < primes.size(); ++j) { auto p = primes[j]; while (a[i] % p == 0) { a[i] /= p; cur_val *= p; } } mapa.push_back({cur_val, cost[i]}); } sort(mapa.begin(), mapa.end()); vector<vector<long long>> vecs; vector<long long> costs; for (long long i = 0; i < mapa.size();) { long long j = i; vector<long long> vec; auto cur_val = mapa[i].first; vector<long long> key(primes.size(), 1); for (long long r = 0; r < primes.size(); ++r) { while (cur_val % primes[r] == 0) { cur_val /= primes[r]; key[r] *= primes[r]; } } while (j < mapa.size() && mapa[j].first == mapa[i].first) { vec.push_back(mapa[j].second); ++j; } i = j; long long enough_space = 0; long long cur_prod = 1; for (long long x : key) { if (x > k) { continue; } if (x * cur_prod <= k) { if (cur_prod == 1) { ++enough_space; } cur_prod *= x; continue; } else { ++enough_space; cur_prod = x; } } enough_space = primes.size(); if (vec.size() > enough_space) { vec.resize(enough_space); } for (long long c : vec) { vecs.push_back(key); costs.push_back(c); } } const long long INF = (long long)1e18; long long full_mask = (1 << primes.size()) - 1; auto clear_dp = [&](long long par) { for (long long cnt = 0; cnt <= primes.size(); ++cnt) { for (long long mask = 0; mask <= full_mask; ++mask) { dp[par][cnt][mask] = INF; } } }; long long par = 0; for (long long i = 0; i < 2; ++i) { clear_dp(i); } dp[par][0][full_mask] = 0; vector<long long> prods; for (long long i = 0; i < vecs.size(); ++i) { for (long long cnt = 0; cnt <= primes.size(); ++cnt) { for (long long mask = 0; mask <= full_mask; ++mask) { dp[par ^ 1][cnt][mask] = dp[par][cnt][mask]; } } prods.assign(1 << primes.size(), 1); for (long long mask = 0; mask < (1 << primes.size()); ++mask) { for (long long j = 0; j < primes.size(); ++j) { if (mask & (1 << j)) { prods[mask] *= vecs[i][j]; } } } for (long long cnt = 0; cnt <= primes.size(); ++cnt) { for (long long mask = 0; mask <= full_mask; ++mask) { long long cur_dp = dp[par][cnt][mask]; if (cur_dp == INF) { continue; } for (long long s = mask; s > 0; s = (s - 1) & mask) { long long prod = prods[s]; if (prod <= k) { relax_min(dp[par ^ 1][cnt + 1][mask ^ s], cur_dp + costs[i]); } } } } par ^= 1; } long long res = INF; for (long long cnt = 0; cnt <= primes.size(); ++cnt) { long long cur_dp = dp[par][cnt][0]; if (cur_dp == INF) { continue; } relax_min(res, cnt * cur_dp); } if (res == INF) { res = -1; } cout << res << "\n"; }
CPP
1103_D. Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k β€” your skill in Cardbluff. Each judge has a number a_i β€” an indicator of uncertainty about your entrance to the professional layer and a number e_i β€” an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x β‹… y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≀ n ≀ 10^6, 1 ≀ k ≀ 10^{12}) β€” the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≀ a_i ≀ 10^{12}) β€” the uncertainty of i-th judge The third line contains n integers in the same format (1 ≀ e_i ≀ 10^9), e_i β€” the experience of i-th judge. Output Print the single integer β€” minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1
2
10
#include <bits/stdc++.h> using namespace std; inline long long read() { long long x = 0, f = 1; char ch = getchar(); while (!isdigit(ch)) { if (ch == '-') f = -1; ch = getchar(); } while (isdigit(ch)) { x = (x << 1) + (x << 3) + ch - '0'; ch = getchar(); } return x * f; } const int maxn = 1e6 + 1e2; long long val[maxn], num[maxn]; long long prime[maxn]; long long n, m, tot, k; pair<long long, long long> b[maxn]; unordered_map<long long, long long> used; long long cost[maxn]; int ci[maxn]; long long f[14][4010]; long long g[14][4010]; long long ptx[maxn]; long long cnt[maxn]; long long lim; long long lowbit(long long x) { return x & (-x); } long long gcd(long long a, long long b) { if (!b) return a; else return gcd(b, a % b); } signed main() { n = read(), lim = read(); for (int i = 1; i <= n; i++) num[i] = read(); long long gc = num[1]; for (int i = 2; i <= n; i++) gc = gcd(gc, num[i]); if (gc == 1) { cout << 0 << endl; return 0; } for (int i = 1; i <= n; i++) val[i] = read(); long long now = gc; for (long long i = 2; i * i <= gc; i++) { if (now % i == 0) { prime[++m] = i; while (now % i == 0) now /= i, ci[m]++; } } if (now > 1) prime[++m] = now, ci[m] = 1; for (int i = 1; i <= n; i++) { long long now = 1; for (int j = 1; j <= m; j++) while (num[i] % prime[j] == 0) now *= prime[j], num[i] /= prime[j]; b[++tot] = make_pair(val[i], now); } sort(b + 1, b + 1 + n); memset(f, 127 / 3, sizeof(f)); f[0][0] = 0; for (int i = 1; i <= n; i++) { bool flag = 0; if (used[b[i].second] > m) continue; used[b[i].second]++; cost[0] = 1; ptx[0] = 1; long long ymh = b[i].second; for (int j = 1; j <= m; j++) { cost[1 << j - 1] = 1; while (ymh % prime[j] == 0) { cost[1 << j - 1] *= prime[j]; ymh /= prime[j]; } } memcpy(g, f, sizeof(g)); for (int j = 0; j < (1 << m); j++) { ptx[j] = ptx[j ^ lowbit(j)] * cost[lowbit(j)]; long long now = ((1 << m) - 1) ^ j; if (ptx[j] > lim) continue; for (int k = now; k; k = (k - 1) & now) { for (int p = 1; p <= m; p++) if (g[p - 1][k] + b[i].first <= f[p][j | k]) f[p][j | k] = g[p - 1][k] + b[i].first, flag = 1; } if (g[0][0] + b[i].first <= f[1][j]) f[1][j] = g[0][0] + b[i].first, flag = 1; } } long long ans = 1e18; for (long long i = 1; i <= m; i++) if (f[i][(1 << m) - 1] != f[13][4002]) ans = min(ans, f[i][(1 << m) - 1] * i); if (ans == 1e18) ans = -1; cout << ans << endl; return 0; }
CPP
1103_D. Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k β€” your skill in Cardbluff. Each judge has a number a_i β€” an indicator of uncertainty about your entrance to the professional layer and a number e_i β€” an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x β‹… y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≀ n ≀ 10^6, 1 ≀ k ≀ 10^{12}) β€” the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≀ a_i ≀ 10^{12}) β€” the uncertainty of i-th judge The third line contains n integers in the same format (1 ≀ e_i ≀ 10^9), e_i β€” the experience of i-th judge. Output Print the single integer β€” minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1
2
10
#include <bits/stdc++.h> using namespace std; int n, m; long long k, G; long long A[1000006]; int E[1000006]; vector<long long> fac; inline long long gcd(long long a, long long b) { return b ? gcd(b, a % b) : a; } map<long long, vector<int> > M; int ok[1000006]; inline void FWTand(int* A, int len) { for (int mid = 2; mid <= len; mid <<= 1) for (int i = 0; i < len; i += mid) for (int j = i; j < i + (mid >> 1); ++j) A[j] += A[j + (mid >> 1)]; } long long dp[12][(1 << 11) + 6]; void solve() { cin >> n >> k; for (int i = (1), iend = (n); i <= iend; ++i) scanf("%lld", A + i), G = !G ? A[i] : gcd(G, A[i]); for (int i = (1), iend = (n); i <= iend; ++i) scanf("%d", E + i); long long c = G; if (G == 1) return void(puts("0")); for (long long i = 2; i * i <= G; ++i) if (c % i == 0) { while (c % i == 0) c /= i; fac.push_back(i); } if (c != 1) fac.push_back(c); m = fac.size(); for (int i = (1), iend = (n); i <= iend; ++i) { long long t = 1, a = A[i]; for (int j = (0), jend = (m - 1); j <= jend; ++j) while (a % fac[j] == 0) t *= fac[j], a /= fac[j]; M[t].push_back(E[i]); } vector<int> us; memset(dp, 0x3f, sizeof dp); dp[0][0] = 0; for (auto& t : M) { sort(t.second.begin(), t.second.end()); long long x, y; for (int i = (1), iend = ((1 << m) - 1); i <= iend; ++i) { x = t.first, y = 1; for (int j = (0), jend = (m - 1); j <= jend; ++j) if (i & (1 << j)) while (x % fac[j] == 0) x /= fac[j], y *= fac[j]; if (y <= k) ok[i] = 1; } FWTand(ok, (1 << m)); us.clear(); for (int i = (0), iend = ((1 << m) - 1); i <= iend; ++i) { if (ok[i] == 1) us.push_back(i); ok[i] = 0; } for (auto& v : t.second) { bool flg = 0; for (int i = ((1 << m) - 1), iend = (0); i >= iend; --i) for (int j = (m - 1), jend = (0); j >= jend; --j) for (auto& q : us) if (dp[j + 1][i | q] > dp[j][i] + v) dp[j + 1][i | q] = dp[j][i] + v, flg = 1; if (!flg) break; } } long long res = 0x3f3f3f3f3f3f3f3f; for (int i = (1), iend = (m); i <= iend; ++i) if (dp[i][(1 << m) - 1] < 0x3f3f3f3f3f3f3f3f) res = ((res) < (i * dp[i][(1 << m) - 1]) ? (res) : (i * dp[i][(1 << m) - 1])); printf("%lld\n", res == 0x3f3f3f3f3f3f3f3f ? -1 : res); } signed main() { solve(); }
CPP
1103_D. Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k β€” your skill in Cardbluff. Each judge has a number a_i β€” an indicator of uncertainty about your entrance to the professional layer and a number e_i β€” an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x β‹… y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≀ n ≀ 10^6, 1 ≀ k ≀ 10^{12}) β€” the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≀ a_i ≀ 10^{12}) β€” the uncertainty of i-th judge The third line contains n integers in the same format (1 ≀ e_i ≀ 10^9), e_i β€” the experience of i-th judge. Output Print the single integer β€” minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1
2
10
#include <bits/stdc++.h> using namespace std; int const N = 1000000; long long const inf = 1e18; int const infs = 1e9; int n; long long k, x[N]; map<long long, vector<long long> > fc, c; vector<vector<char> > cn; vector<vector<vector<long long> > > dp; vector<vector<int> > fr, mn; long long gcd(long long a, long long b) { return b ? gcd(b, a % b) : a; } inline void up(long long &x, long long y) { x = min(x, y); } inline void up(int &x, int y) { x = min(x, y); } void fl(vector<char> &c, vector<long long> const &v, int i = 0, long long x = 1ll, int msk = 0) { if (i == (int)v.size()) { c[msk] = true; return; } fl(c, v, i + 1, x, msk); if (x <= k / v[i]) fl(c, v, i + 1, x * v[i], msk | 1 << i); } int main() { scanf("%d%lld", &n, &k); for (int i = 0; i < (int)(n); ++i) scanf("%lld", x + i); long long g = x[0]; for (int i = 1; i < (int)(n); ++i) g = gcd(g, x[i]); if (g == 1) { printf("0\n"); return 0; } vector<long long> pr; long long t = g; for (int i = 2; (long long)i * i <= t; ++i) if (t % i == 0) { pr.push_back(i); t /= i; while (t % i == 0) t /= i; } if (t != 1) pr.push_back(t); for (int i = 0; i < (int)(n); ++i) { vector<long long> v(pr.size(), 1ll); for (int j = 0; j < (int)(pr.size()); ++j) while (x[i] % pr[j] == 0) x[i] /= pr[j], v[j] *= pr[j]; long long t = 1; for (int j = 0; j < (int)(v.size()); ++j) t *= v[j]; int cst; scanf("%d", &cst); if (c.find(t) == c.end()) fc[t] = v; c[t].push_back(cst); } cn.resize(c.size(), vector<char>(1 << pr.size(), false)); int i = 0; for (map<long long, vector<long long> >::iterator it = fc.begin(); it != fc.end(); ++it, ++i) fl(cn[i], it->second); fr.resize(1 << pr.size()); for (int i = 0; i < (int)(fr.size()); ++i) for (int j = 1; j < (int)(fr.size()); ++j) if (!(i & j)) fr[i].push_back(j); mn.resize(c.size(), vector<int>(1 << pr.size(), infs)); i = 0; for (map<long long, vector<long long> >::iterator it = c.begin(); it != c.end(); ++it, ++i) { sort(it->second.begin(), it->second.end()); for (int i = 1; i < (int)(it->second.size()); ++i) it->second[i] += it->second[i - 1]; mn[i][0] = 0; for (int j = 0; j < (int)(1 << pr.size()); ++j) if (mn[i][j] < (int)it->second.size()) for (int w = 0; w < (int)(fr[j].size()); ++w) if (cn[i][fr[j][w]]) up(mn[i][j | fr[j][w]], mn[i][j] + 1); } dp.resize(c.size() + 1, vector<vector<long long> >(1 << pr.size(), vector<long long>(pr.size() + 1, inf))); dp[0][0][0] = 0; i = 0; for (map<long long, vector<long long> >::iterator it = c.begin(); it != c.end(); ++it, ++i) for (int j = 0; j < (int)(1 << pr.size()); ++j) for (int k = 0; k < (int)(pr.size() + 1); ++k) if (dp[i][j][k] != inf) { up(dp[i + 1][j][k], dp[i][j][k]); for (int w = 0; w < (int)(fr[j].size()); ++w) if (mn[i][fr[j][w]] != infs) up(dp[i + 1][j | fr[j][w]][k + mn[i][fr[j][w]]], dp[i][j][k] + it->second[mn[i][fr[j][w]] - 1]); } long long an = inf; for (int i = 1; i < (int)(pr.size() + 1); ++i) if (dp[c.size()][(1 << pr.size()) - 1][i] != inf) up(an, dp[c.size()][(1 << pr.size()) - 1][i] * i); printf("%lld\n", an == inf ? -1 : an); }
CPP
1103_D. Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k β€” your skill in Cardbluff. Each judge has a number a_i β€” an indicator of uncertainty about your entrance to the professional layer and a number e_i β€” an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x β‹… y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≀ n ≀ 10^6, 1 ≀ k ≀ 10^{12}) β€” the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≀ a_i ≀ 10^{12}) β€” the uncertainty of i-th judge The third line contains n integers in the same format (1 ≀ e_i ≀ 10^9), e_i β€” the experience of i-th judge. Output Print the single integer β€” minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1
2
10
#include <bits/stdc++.h> using namespace std; inline long long read() { long long s = 0, w = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') w = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { s = s * 10 + ch - '0'; ch = getchar(); } return s * w; } const int N = 1e6 + 10, M = 15; long long n, K, res, fac[M], tot, f[M][1 << M], S, inv[M] = {1}, ans, inf; bool vis[1 << M]; struct node { long long a, e; } c[N]; map<long long, vector<long long> > mp; long long gcd(long long a, long long b) { return b ? gcd(b, a % b) : a; } void init() { n = read(), K = read(); for (int i = 1; i <= n; i++) c[i].a = read(); for (int i = 1; i <= n; i++) c[i].e = read(); res = c[1].a; for (int i = 2; i <= n; i++) res = gcd(res, c[i].a); if (!(res ^ 1)) puts("0"), exit(0); for (long long i = 2; i * i <= res; i++) if (!(res % i)) { fac[tot++] = i; while (!(res % i)) res /= i; } if (res ^ 1) fac[tot++] = res; for (int i = 1; i <= n; i++) { long long tmp = 1; for (int j = 0; j <= tot - 1; j++) { while (!(c[i].a % fac[j])) { tmp *= fac[j]; c[i].a /= fac[j]; } } mp[tmp].push_back(c[i].e); } } void solve() { memset(f, 63, sizeof(f)); inf = ans = f[0][0]; f[0][0] = 0; S = (1 << tot) - 1; for (int i = 1; i <= tot; i++) inv[i] = inv[i - 1] << 1; for (auto i : mp) { long long x = i.first; sort(i.second.begin(), i.second.end()); if (i.second.size() > tot) i.second.resize(tot); for (int j = 0; j <= S; j++) { long long y = x, z = 1; for (int k = 0; k <= tot - 1; k++) { if (j & inv[k]) while (!(y % fac[k])) y /= fac[k], z *= fac[k]; vis[j] = (z <= K); } } for (auto j : i.second) { bool flg = 0; for (int k = tot - 1; k >= 0; k--) { for (int p = 0; p <= S; p++) if (f[k][p] < inf) for (long long q = (p + 1) | p; q <= S; q = (q + 1) | p) if (vis[q ^ p]) if (f[k + 1][q] > f[k][p] + j) flg = 1, f[k + 1][q] = f[k][p] + j; } if (!flg) break; } } for (int i = 0; i <= tot; i++) if (f[i][S] < inf) ans = min(ans, f[i][S] * i); if (ans ^ inf) printf("%lld\n", ans); else puts("-1"); } int main() { init(); solve(); return 0; }
CPP
1103_D. Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k β€” your skill in Cardbluff. Each judge has a number a_i β€” an indicator of uncertainty about your entrance to the professional layer and a number e_i β€” an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x β‹… y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≀ n ≀ 10^6, 1 ≀ k ≀ 10^{12}) β€” the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≀ a_i ≀ 10^{12}) β€” the uncertainty of i-th judge The third line contains n integers in the same format (1 ≀ e_i ≀ 10^9), e_i β€” the experience of i-th judge. Output Print the single integer β€” minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1
2
10
#include <bits/stdc++.h> using namespace std; template <typename T> inline void read(T &data) { data = 0; int w = 1; register char ch = 0; while (!isdigit(ch) && ch != '-') ch = getchar(); if (ch == '-') w = -1, ch = getchar(); while (isdigit(ch)) data = data * 10 + ch - '0', ch = getchar(); data *= w; } const int MAX_N = 1e6 + 5; const long long INF = 3e18; long long gcd(long long a, long long b) { if (b == 0) return a; else return gcd(b, a % b); } int N, cnt; long long K, G, a[MAX_N], e[MAX_N], p[MAX_N], f[13][1 << 13]; map<long long, vector<long long> > mp; int main() { for (int i = 0; i < 13; i++) for (int s = 0; s < (1 << 13); s++) f[i][s] = INF; read(N), read(K); for (int i = 1; i <= N; i++) read(a[i]); for (int i = 1; i <= N; i++) read(e[i]); G = a[1]; for (int i = 2; i <= N; i++) G = gcd(G, a[i]); for (long long i = 2ll; i * i <= G; i++) { if (G % i != 0) continue; p[cnt] = i; while (G % i == 0) G /= i; ++cnt; } if (G != 1ll) p[cnt] = G, ++cnt; for (int i = 1; i <= N; i++) { long long res = 1, tmp = a[i]; for (int j = 0; j < cnt; j++) while (tmp % p[j] == 0) res *= p[j], tmp /= p[j]; mp[res].push_back(e[i]); } f[0][0] = 0; for (map<long long, vector<long long> >::iterator ite = mp.begin(); ite != mp.end(); ++ite) { long long x = ite->first; vector<int> vec; for (int i = 0; i < (1 << cnt); i++) { long long y = x, z = 1; for (int j = 0; j < cnt; j++) if ((i >> j) & 1) while (y % p[j] == 0) y /= p[j], z *= p[j]; if (z <= K) vec.push_back(i); } sort(ite->second.begin(), ite->second.end()); if ((int)ite->second.size() > cnt) ite->second.resize(cnt); for (vector<long long>::iterator it = ite->second.begin(); it != ite->second.end(); ++it) { bool update = 0; for (int i = cnt - 1; ~i; i--) { for (vector<int>::iterator t = vec.begin(); t != vec.end(); ++t) { int tmp = ((1 << cnt) - 1) ^ *t; for (int j = tmp;; j = (j - 1) & tmp) { long long tt = f[i][j] + *it; if (tt < f[i + 1][*t ^ j]) f[i + 1][*t ^ j] = tt, update = 1; if (!j) break; } } } if (update == 0) break; } } long long ans = INF; for (int i = 0; i <= cnt; i++) if (f[i][(1 << cnt) - 1] != INF) ans = min(ans, f[i][(1 << cnt) - 1] * i); if (ans >= INF) ans = -1; cout << ans << endl; return 0; }
CPP
1103_D. Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k β€” your skill in Cardbluff. Each judge has a number a_i β€” an indicator of uncertainty about your entrance to the professional layer and a number e_i β€” an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge. Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x β‹… y seconds. Print minimal time to enter to the professional layer or -1 if it's impossible. Input There are two numbers in the first line n and k (1 ≀ n ≀ 10^6, 1 ≀ k ≀ 10^{12}) β€” the number of judges and your skill in Cardbluff. The second line contains n integers, where i-th number a_i (1 ≀ a_i ≀ 10^{12}) β€” the uncertainty of i-th judge The third line contains n integers in the same format (1 ≀ e_i ≀ 10^9), e_i β€” the experience of i-th judge. Output Print the single integer β€” minimal number of seconds to pass exam, or -1 if it's impossible Examples Input 3 6 30 30 30 100 4 5 Output 18 Input 1 1000000 1 100 Output 0 Input 3 5 7 7 7 1 1 1 Output -1
2
10
#include <bits/stdc++.h> using namespace std; const int N = 1e6 + 10, M = (1 << 11) + 10; int n, cot, S; long long ans, g, K, inf, dp[12][M], ys[12], xs[12]; pair<long long, long long> p[N]; map<long long, vector<long long>> ex; vector<long long> cn; bool vs[M]; char cp; template <class T> inline void rd(T &x) { cp = getchar(); x = 0; for (; !isdigit(cp); cp = getchar()) ; for (; isdigit(cp); cp = getchar()) x = x * 10 + (cp ^ 48); } inline long long gcd(long long x, long long y) { return (!y) ? x : gcd(y, x % y); } inline void dn(long long &x, long long y) { if (y < x) x = y; } int main() { int i, j; long long u, v; rd(n); rd(K); for (i = 0; i < n; ++i) rd(p[i].second); for (i = 0; i < n; ++i) rd(p[i].first); for (g = p[0].second, i = 1; i < n; ++i) g = gcd(g, p[i].second); if (g == 1LL) { puts("0"); return 0; } sort(p, p + n); for (i = 2; (long long)i * i <= g; ++i) if (!(g % i)) { ys[cot++] = i; for (; !(g % i); g /= i) ; } if (g > 1) ys[cot++] = g; S = 1 << cot; if (ys[cot - 1] > K) { puts("-1"); return 0; } for (i = 0; i < n; ++i) { u = p[i].second; for (j = 0; j < cot; ++j) for (v = ys[j]; !(u % v); u /= v) ; v = p[i].second / u; if (ex[v].size() < cot) ex[v].push_back(p[i].first); } memset(dp, 0x3f, sizeof(dp)); inf = dp[0][0]; dp[0][0] = 0LL; for (auto nw : ex) { u = nw.first; cn.clear(); for (i = 0; i < cot; ++i) { xs[i] = 1; for (v = ys[i]; !(u % v); u /= v) xs[i] *= v; } memset(vs, false, sizeof(vs)); for (i = S - 1; i; --i) if (!vs[i]) { for (u = 1LL, j = 0; j < cot; ++j) if ((i >> j) & 1) u *= xs[j]; if (u <= K) { for (j = i; j; j = i & (j - 1)) vs[j] = true; cn.push_back(i); } } for (auto vl : nw.second) { for (i = cot - 1; ~i; --i) for (j = 0; j < S; ++j) if ((v = dp[i][j] + vl) < inf) for (int s : cn) dn(dp[i + 1][j | s], v); } } for (ans = inf, S--, i = 1; i <= cot; ++i) if (dp[i][S] < inf / i) dn(ans, dp[i][S] * i); if (ans == inf) ans = -1LL; printf("%I64d", ans); return 0; }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> using namespace std; const int INF = 1e9; const int maxn = 2005; long long n, m; long long d[maxn]; int vis[maxn]; vector<long long> g[maxn], w[maxn]; char s[maxn][maxn]; void dfs(int x) { vis[x] = 1; for (int i = 0; i < g[x].size(); i++) { int nxt = g[x][i]; int wgt = w[x][i]; if (d[nxt] < d[x] + wgt) { d[nxt] = d[x] + wgt; if (vis[nxt]) { cout << "No" << endl; exit(0); } dfs(nxt); } } vis[x] = 0; } int main() { cin >> n >> m; for (int i = 1; i <= n; i++) cin >> (s[i] + 1); for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (s[i][j] == '=') g[i].push_back(j + n), g[j + n].push_back(i), w[i].push_back(0), w[j + n].push_back(0); else if (s[i][j] == '>') g[j + n].push_back(i), w[j + n].push_back(1); else if (s[i][j] == '<') g[i].push_back(j + n), w[i].push_back(1); } } for (int i = 1; i <= n + m; i++) dfs(i); cout << "Yes" << endl; for (int i = 1; i <= n; i++) cout << d[i] + 1 << " "; cout << endl; for (int i = n + 1; i <= n + m; i++) cout << d[i] + 1 << " "; cout << endl; return 0; }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Rustam Musin (t.me/musin_acm) */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); DViborGurmana solver = new DViborGurmana(); solver.solve(1, in, out); out.close(); } static class DViborGurmana { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); int m = in.readInt(); char[][] a = in.readTable(n, m); DSU dsu = new DSU(n + m); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (a[i][j] == '=') { dsu.unite(i, n + j); } } } boolean ok = true; List<Integer>[] g = new List[n + m]; for (int i = 0; i < n + m; i++) { g[i] = new ArrayList<>(); } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int gi = dsu.find(i); int gj = dsu.find(n + j); if (gi == gj) { ok &= a[i][j] == '='; continue; } if (a[i][j] == '<') { g[gi].add(gj); } if (a[i][j] == '>') { g[gj].add(gi); } } } int[] answer = topsort(g); if (answer == null) { ok = false; } else { int[] ans = new int[n + m]; for (int i = 0; i < n; i++) { ans[i] = answer[dsu.find(i)]; } for (int i = 0; i < m; i++) { ans[n + i] = answer[dsu.find(n + i)]; } compress(answer = ans); } if (!ok) { out.print("No"); return; } out.printLine("Yes"); for (int i = 0; i < n; i++) { out.print(answer[i] + 1 + " "); } out.printLine(); for (int i = 0; i < m; i++) { out.print(answer[n + i] + 1 + " "); } } int[] unique(int[] a) { Arrays.sort(a = a.clone()); int sz = 1; for (int i = 1; i < a.length; i++) { if (a[i] != a[i - 1]) { a[sz++] = a[i]; } } return Arrays.copyOfRange(a, 0, sz); } void compress(int[] a) { int[] u = unique(a); for (int i = 0; i < a.length; i++) { a[i] = Arrays.binarySearch(u, a[i]); } } int[] topsort(List<Integer>[] g) { int n = g.length; int[] inDegree = new int[n]; for (int i = 0; i < n; i++) { for (int to : g[i]) { inDegree[to]++; } } int[] q = new int[n]; int qs = 0; for (int i = 0; i < n; i++) { if (inDegree[i] == 0) { q[qs++] = i; } } int[] answer = new int[n]; for (int qh = 0; qh < qs; qh++) { int v = q[qh]; for (int to : g[v]) { answer[to] = Math.max(answer[to], answer[v] + 1); if (--inDegree[to] == 0) { q[qs++] = to; } } } if (qs != n) { return null; } return answer; } class DSU { int[] parent; DSU(int n) { parent = new int[n]; for (int i = 0; i < n; i++) { parent[i] = i; } } int find(int v) { if (parent[v] == v) { return v; } return parent[v] = find(parent[v]); } int unite(int u, int v) { u = find(u); v = find(v); if (u == v) { return -1; } parent[u] = v; return v; } } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void printLine() { writer.println(); } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public char[] readCharArray(int size) { char[] array = new char[size]; for (int i = 0; i < size; i++) { array[i] = readCharacter(); } return array; } public char[][] readTable(int rowCount, int columnCount) { char[][] table = new char[rowCount][]; for (int i = 0; i < rowCount; i++) { table[i] = this.readCharArray(columnCount); } return table; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public char readCharacter() { int c = read(); while (isSpaceChar(c)) { c = read(); } return (char) c; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
JAVA
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
#!/usr/bin/env python2 """ This file is part of https://github.com/cheran-senthil/PyRival Copyright 2019 Cheran Senthilkumar <[email protected]> """ from __future__ import division, print_function import itertools import os import sys from atexit import register from io import BytesIO class dict(dict): """dict() -> new empty dictionary""" def items(self): """D.items() -> a set-like object providing a view on D's items""" return dict.iteritems(self) def keys(self): """D.keys() -> a set-like object providing a view on D's keys""" return dict.iterkeys(self) def values(self): """D.values() -> an object providing a view on D's values""" return dict.itervalues(self) def gcd(x, y): """greatest common divisor of x and y""" while y: x, y = y, x % y return x range = xrange filter = itertools.ifilter map = itertools.imap zip = itertools.izip sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size)) sys.stdout = BytesIO() register(lambda: os.write(1, sys.stdout.getvalue())) input = lambda: sys.stdin.readline().rstrip('\r\n') class UnionFind: def __init__(self, n): self.parent = list(range(n)) self.size = [1] * n self.num_sets = n def find(self, a): to_update = [] while a != self.parent[a]: to_update.append(a) a = self.parent[a] for b in to_update: self.parent[b] = a return self.parent[a] def merge(self, a, b): a = self.find(a) b = self.find(b) if a == b: return if self.size[a] < self.size[b]: a, b = b, a self.num_sets -= 1 self.parent[b] = a self.size[a] += self.size[b] def set_size(self, a): return self.size[self.find(a)] def main(): n, m = map(int, input().split()) A = [input() for _ in range(n)] same_dish = UnionFind(n + m) for i, Ai in enumerate(A): for j, Aij in enumerate(Ai): if Aij == '=': same_dish.merge(i, n + j) graph = [[] for _ in range(n + m)] for i, Ai in enumerate(A): for j, Aij in enumerate(Ai): node_1, node_2 = same_dish.find(i), same_dish.find(n + j) if Aij == '>': graph[node_1].append(node_2) if Aij == '<': graph[node_2].append(node_1) indeg, idx = [0] * (n + m), [0] * (n + m) for node in graph: for child in node: indeg[child] += 1 roots = [i for i in range(n + m) if indeg[i] == 0] q = roots[:] nr = 0 while q: top = q.pop() idx[top], nr = nr, nr + 1 for e in graph[top]: indeg[e] -= 1 if indeg[e] == 0: q.append(e) if nr != n + m: print('No') return print('Yes') res = [1 if graph[i] == [] else -1 for i in range(n + m)] visited = [False] * (n + m) def dfs(node): if res[node] == 1: return for child in graph[node]: if not visited[child]: visited[child] = True dfs(child) res[node] = max(res[child] for child in graph[node]) + 1 for root in roots: dfs(root) res = [res[same_dish.find(i)] for i in range(n + m)] print(*res[:n]) print(*res[n:]) if __name__ == '__main__': main()
PYTHON
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
// package CodeForces; // / import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.InputMismatchException; import java.util.LinkedList; public class Round541D { public static int[] parent; public static int[] size; public static void makeSet(int v) { parent[v] = v; size[v] = 1; } public static int findSet(int v) { if (v == parent[v]) { return v; } return parent[v] = findSet(parent[v]); } public static void unionSet(int u, int v) { u = findSet(u); v = findSet(v); if (u == v) { return; } if (size[u] > size[v]) { size[u] += size[v]; parent[v] = u; return; } size[v] += size[u]; parent[u] = v; } public static LinkedList<Integer> adj[]; public static int[] ans; public static boolean checkCyclePlusTopo () { int n = ans.length; LinkedList<Integer> q = new LinkedList<Integer>(); int[] inDegree = new int[n]; int totDegree = 0; for (int i = 0; i < n; i++) { for (Integer x : adj[i]) { inDegree[x]++; totDegree++; } } for (int i = 0; i < n; i++) { if (inDegree[i] == 0) { q.add(i); } } int currVal = 1; while (!q.isEmpty()) { LinkedList<Integer> next = new LinkedList<Integer>(); while (!q.isEmpty()) { int top = q.removeFirst(); ans[top] = currVal; for (Integer x : adj[top]) { inDegree[x]--; totDegree--; if (inDegree[x] == 0) { next.add(x); } } } if (!next.isEmpty()) { q = next; currVal++; } } return totDegree == 0; } public static void solve() { int n = s.nextInt(); int m = s.nextInt(); parent = new int[n + m]; size = new int[n + m]; for (int i = 0; i < n + m; i++) { makeSet(i); } String[] comparison = new String[n]; for (int i = 0; i < n; i++) { comparison[i] = s.next(); for (int j = 0; j < m; j++) { if (comparison[i].charAt(j) == '=') { int first = i; int second = n + j; unionSet(first, second); } } } HashMap<Integer, Integer> distincts = new HashMap<Integer, Integer>(); int ptr = 0; for (int i = 0; i < n + m; i++) { int parent = findSet(i); if (!distincts.containsKey(parent)) { distincts.put(parent, ptr); ptr++; } } int[] belongsTo = new int[n + m]; HashMap<Integer, ArrayList<Integer>> sets = new HashMap<Integer, ArrayList<Integer>>(); for (int i = 0; i < n + m; i++) { int parent = findSet(i); parent = distincts.get(parent); belongsTo[i] = parent; if (sets.containsKey(parent)) { sets.get(parent).add(i); } else { ArrayList<Integer> value = new ArrayList<Integer>(); value.add(i); sets.put(parent, value); } } adj = new LinkedList[sets.size()]; for (int i = 0; i < sets.size(); i++) { adj[i] = new LinkedList<Integer>(); } for (int i = 0; i < n; i++) { int first = belongsTo[i]; for (int j = 0; j < m; j++) { int second = belongsTo[n + j]; char currSymbol = comparison[i].charAt(j); if (currSymbol == '<') { adj[first].add(second); } else if (currSymbol == '>') { adj[second].add(first); } } } ans = new int[sets.size()]; boolean ans_ = checkCyclePlusTopo(); if (!ans_) { out.println("No"); } else { out.println("Yes"); for (int i = 0; i < n; i++) { out.print(ans[belongsTo[i]] + " "); } out.println(); for (int i = 0; i < m; i++) { out.print(ans[belongsTo[i + n]] + " "); } } } public static void main(String[] args) { new Thread(null, null, "Thread", 1 << 27) { public void run() { try { out = new PrintWriter(new BufferedOutputStream(System.out)); s = new FastReader(System.in); solve(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } }.start(); } public static PrintWriter out; public static FastReader s; public static class FastReader { private InputStream stream; private byte[] buf = new byte[4096]; private int curChar, snumChars; public FastReader(InputStream stream) { this.stream = stream; } public int read() { if (snumChars == -1) { throw new InputMismatchException(); } if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException E) { throw new InputMismatchException(); } } if (snumChars <= 0) { return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int number = 0; do { number *= 10; number += c - '0'; c = read(); } while (!isSpaceChar(c)); return number * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } long sgn = 1; if (c == '-') { sgn = -1; c = read(); } long number = 0; do { number *= 10L; number += (long) (c - '0'); c = read(); } while (!isSpaceChar(c)); return number * sgn; } public int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = this.nextInt(); } return arr; } public long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = this.nextLong(); } return arr; } public String next() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndofLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndofLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
JAVA
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> using namespace std; string inttostr(long long a) { string ans = ""; if (a == 0) return "0"; stringstream ss; while (a > 0) { string ch; ss << a % 10; ss >> ch; ss.clear(); ans = ch + ans; a /= 10; } return ans; } long long strtoint(string s) { long long ans = 0; for (long long i = s.size() - 1; i >= 0; --i) { long long o = s[i] - '0'; if (s[i] == 0) o = 0; ans += o * pow(10, s.size() - 1 - i); } return ans; } long long gcd(long long a, long long b) { long long r; while (b != 0) { r = a % b; a = b; b = r; } return a; } long long lcm(long long a, long long b) { return ((a * b) / gcd(a, b)); } long long fastpow(long long a, long long step) { if (step == 0) return 1; if (step % 2 == 0) return (fastpow(a * a, step / 2)); else return (fastpow(a, step - 1) * a); } vector<long long> parent, siz, ans; vector<vector<long long> > g; vector<bool> used; long long get_parent(long long a) { if (parent[a] == a) return a; else return parent[a] = get_parent(parent[a]); } void uni(long long a, long long b) { a = get_parent(a); b = get_parent(b); if (siz[a] < siz[b]) { parent[a] = b; siz[b] += siz[a]; } else { parent[b] = a; siz[a] += siz[b]; } } long long anse, n, m; vector<long long> top; vector<vector<char> > a; void dfs(long long v) { used[v] = true; for (auto u : g[v]) { if (!used[u]) dfs(u); } top.push_back(v); } signed main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> n >> m; g.resize(n + m); a.resize(n, vector<char>(m)); used.resize(n + m, false); ans.resize(n + m, 0); for (long long i = 0; i < n + m; ++i) { parent.push_back(i); siz.push_back(1); } for (long long i = 0; i < n; ++i) { for (long long j = 0; j < m; ++j) { cin >> a[i][j]; if (a[i][j] == '=') uni(i, j + n); } } for (long long i = 0; i < n + m; ++i) long long x = get_parent(i); for (long long i = 0; i < n; ++i) { for (long long j = 0; j < m; ++j) { if (a[i][j] == '>') g[parent[i]].push_back(parent[j + n]); if (a[i][j] == '<') g[parent[j + n]].push_back(parent[i]); } } for (long long i = 0; i < n + m; ++i) { if (!used[parent[i]]) dfs(parent[i]); } for (auto x : top) { long long ma = 0; for (auto v : g[x]) { if (ans[v] == 0) { cout << "No"; return 0; } ma = max(ma, ans[v]); } ans[x] = ma + 1; } for (long long i = 0; i < n + m; ++i) { ans[i] = ans[parent[i]]; } long long mi = 1e9; for (long long i = 0; i < n + m; ++i) { mi = min(ans[i], mi); } for (long long i = 0; i < n + m; ++i) { ans[i] -= mi - 1; } cout << "Yes\n"; for (long long i = 0; i < n + m; ++i) { if (i == n) cout << '\n'; cout << ans[i] << ' '; } }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> using namespace std; int n, m; vector<int> graph[2005]; int ans[2005]; int father[2005]; int inedge[2005]; char inputs[1005][1005]; int avai; int find(int a) { if (a != father[a]) father[a] = find(father[a]); return father[a]; } int que[2005], head, tail; int main() { cin >> n >> m; avai = n + m; for (int i = 1; i <= n + m; i++) father[i] = i; for (int i = 1; i <= n; i++) { getchar(); for (int j = 1; j <= m; j++) { inputs[i][j] = getchar(); if (inputs[i][j] == '=') { father[find(n + j)] = find(i); avai--; } } } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (inputs[i][j] != '=' && find(i) == find(n + j)) { cout << "No"; return 0; } if (inputs[i][j] == '>') { graph[find(n + j)].push_back(find(i)); inedge[find(i)]++; } else if (inputs[i][j] == '<') { graph[find(i)].push_back(find(n + j)); inedge[find(n + j)]++; } } } for (int i = 1; i <= n; i++) { if (find(i) != i) continue; if (!inedge[i]) { que[tail++] = i; ans[i] = 1; } } for (int i = 1; i <= m; i++) { if (find(i + n) != n + i) continue; if (!inedge[i + n]) { que[tail++] = i + n; ans[n + i] = 1; } } int c; while (head < tail) { c = que[head]; for (int i = 0; i < graph[c].size(); i++) { ans[graph[c][i]] = max(ans[graph[c][i]], ans[c] + 1); inedge[graph[c][i]]--; if (!inedge[graph[c][i]]) que[tail++] = graph[c][i]; } head++; } if (tail < avai) { cout << "No"; } else { cout << "Yes" << endl; for (int i = 1; i <= n; i++) cout << ans[find(i)] << " "; cout << endl; for (int i = 1; i <= m; i++) cout << ans[find(n + i)] << " "; } return 0; }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> using namespace std; int n, m, tot, totcol, cnt[100005], val[100005], vis[100005]; int col[5555], head[2000005], nxt[2000005], point[2000005]; int a[2005][2005], con[2005][2005]; vector<int> v[100005]; set<pair<int, int> > all; char s[1005][1005]; void gotohell() { puts("No"); exit(0); } void addedge(int x, int y) { point[++tot] = y, nxt[tot] = head[x], head[x] = tot; point[++tot] = x, nxt[tot] = head[y], head[y] = tot; } void addedge2(int x, int y) { v[x].push_back(y); } void dfs(int x, int c) { col[x] = c; vis[x] = 1; for (int i = head[x]; i; i = nxt[i]) { int y = point[i]; if (!vis[y]) dfs(y, c); } } void dfs2(int x) { vis[x] = 1; val[x] = 1; for (int i = 0; i < v[x].size(); i++) { int y = v[x][i]; if (!vis[y]) dfs2(y); else if (vis[y] == 1) gotohell(); val[x] = max(val[x], val[y] + 1); } vis[x] = 2; } int main() { scanf("%d%d", &n, &m); for (int i = 1; i <= n; i++) scanf("%s", s[i] + 1); for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (s[i][j] == '>') a[i][j] = 1; else if (s[i][j] == '<') a[i][j] = -1; else addedge(i, j + n); } } for (int i = 1; i <= n + m; i++) if (!vis[i]) dfs(i, ++totcol); for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (a[i][j] == 1) { if (col[i] == col[j + n]) gotohell(); con[col[i]][col[j + n]] = 1; } else if (a[i][j] == -1) { if (col[i] == col[j + n]) gotohell(); con[col[j + n]][col[i]] = 1; } } } for (int i = 1; i <= totcol; i++) { for (int j = 1; j <= totcol; j++) { if (con[i][j]) { addedge2(i, j); } } } for (int i = 1; i <= totcol; i++) vis[i] = 0; for (int i = 1; i <= totcol; i++) if (!vis[i]) dfs2(i); puts("Yes"); for (int i = 1; i <= n; i++) printf("%d ", val[col[i]]); puts(""); for (int i = n + 1; i <= n + m; i++) printf("%d ", val[col[i]]); return 0; }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> #pragma GCC optimize(3, "Ofast", "inline") using namespace std; long long qpow(long long a, long long b) { long long res = 1; while (b) { if (b & 1) res = res * a; a = a * a; b >>= 1; } return res; } long long qpow(long long a, long long b, long long mod) { long long res = 1; while (b) { if (b & 1) res = res * a % mod; a = a * a % mod; b >>= 1; } return res; } long long inv(long long a, long long mod) { return qpow(a, mod - 2, mod); } long long gcd(long long a, long long b) { return b ? gcd(b, a % b) : a; } long long lcm(long long a, long long b) { return a * b / gcd(a, b); } template <typename T> inline void read(T &x) { x = 0; T f = 1; char c = getchar(); for (; !isdigit(c); c = getchar()) if (c == '-') f = -1; for (; isdigit(c); c = getchar()) x = (x << 1) + (x << 3) + (c ^ 48); x *= f; } template <typename T> inline void write(T x) { if (x < 0) { putchar('-'); x = -x; } if (x > 9) write(x / 10); putchar(x % 10 + '0'); } const double eps = 1e-10; const long long inf = 0x3f3f3f3f, base = 137, mod = 1e9 + 7; const int N = 1e3 + 5, M = N * N + 5, S = 1e6 + 5; char c; vector<pair<int, int> > vc[N << 1]; int d[N << 1]; int v[N << 1]; bool flag; int n, m; int cnt[N << 1]; bool spfa(int st) { queue<int> q; memset(d, -1, sizeof d); memset(v, 0, sizeof v); d[st] = 0; v[st] = 1; cnt[st] = 1; q.push(st); while (q.size()) { int x = q.front(); q.pop(); v[x] = 0; for (int i = 0; i < vc[x].size(); i++) { int y = vc[x][i].first, z = vc[x][i].second; if (d[y] < d[x] + z) { d[y] = d[x] + z; if (!v[y]) { cnt[y]++; if (cnt[y] >= n + m + 1) return false; v[y] = 1; q.push(y); } } } } return true; } void solve() { scanf("%d%d", &n, &m); for (int i = 1; i <= n; i++) { getchar(); for (int j = 1; j <= m; j++) { scanf("%c", &c); if (c == '>') { vc[j + n].push_back({i, 1}); } else if (c == '<') { vc[i].push_back({j + n, 1}); } else { vc[j + n].push_back({i, 0}); vc[i].push_back({j + n, 0}); } } } for (int i = 1; i <= n + m; i++) vc[0].push_back({i, 1}); flag = spfa(0); if (flag) { for (int i = 1; i <= n + m; i++) { if (d[i] == -1) { flag = 0; break; } } } if (flag) { printf("Yes\n"); for (int i = 1; i <= n; i++) printf("%d ", d[i]); printf("\n"); for (int i = n + 1; i <= n + m; i++) printf("%d ", d[i]); } else printf("No\n"); } int main() { int T = 1; while (T--) { solve(); } }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> using namespace std; const int maxn = 2010; vector<int> G[maxn]; int n, m, d[maxn], par[maxn], a[maxn], vis[maxn], flag = 1; char s[1005][1005]; int find(int u) { if (par[u] != u) par[u] = find(par[u]); return par[u]; } struct node { int u, w; node(int a, int b) { u = a, w = b; } }; void topo() { queue<node> q; for (int i = 1; i <= n + m; i++) { int fa = find(i); if (!d[fa] && !vis[fa]) q.push(node(fa, 1)), vis[fa] = 1; } while (!q.empty()) { node e = q.front(); q.pop(); int u = e.u; a[u] = max(a[u], e.w); for (int i = 0; i < G[u].size(); i++) { int v = G[u][i]; a[v] = max(a[u] + 1, a[v]); d[v]--; if (d[v] == 0) q.push(node(v, a[v])); } } for (int i = 1; i <= n + m; i++) if (d[i]) puts("No"), exit(0); } void add(int i, int j) { int fa = find(i), fb = find(j); if (fa == fb) puts("No"), exit(0); d[fa]++; G[fb].push_back(fa); } int main() { scanf("%d%d", &n, &m); for (int i = 1; i <= n + m; i++) par[i] = i; for (int i = 1; i <= n; i++) { scanf("%s", s[i] + 1); for (int j = 1; j <= m; j++) if (s[i][j] == '=') { int fa = find(i), fb = find(j + n); par[fa] = fb; } } for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) if (s[i][j] == '>') add(i, n + j); else if (s[i][j] == '<') add(n + j, i); topo(); puts("Yes"); for (int i = 1; i < n; i++) printf("%d ", a[find(i)]); printf("%d\n", a[find(n)]); for (int i = 1; i < m; i++) printf("%d ", a[find(i + n)]); printf("%d\n", a[find(n + m)]); }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
import java.util.*; import java.io.*; public class Main { public static void main(String args[]) {new Main().run();} FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); void run(){ work(); out.flush(); } long mod=1000000007; long gcd(long a,long b) { return a==0?b:b>=a?gcd(b%a,a):gcd(b,a); } int[][] A; int[] dp; int[] id; int[] color; void work() { int n=in.nextInt(),m=in.nextInt(); dp=new int[n+m]; A=new int[n+m][n+m]; id=new int[n+m]; color=new int[n+m]; for(int i=0;i<n+m;i++) { id[i]=i; } for(int[] a:A)Arrays.fill(a, -1); for(int i=0;i<n;i++) { String s=in.next(); for(int j=0;j<m;j++) { char c=s.charAt(j); if(c=='<') { A[j+n][i]=1; }else if(c=='>') { A[i][j+n]=1; }else { A[i][j+n]=0; A[j+n][i]=0; union(i,j+n); } } } for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(A[i][j+n]==1) { A[find(i)][find(j+n)]=1; } if(A[j+n][i]==1) { A[find(j+n)][find(i)]=1; } } } for(int i=0;i<n+m;i++) { if(id[i]==i&&!dfs(i)) { out.println("No"); return; } } out.println("Yes"); for(int i=0;i<n;i++) { out.print(dp[find(i)]+" "); } out.println(); for(int i=n;i<m+n;i++) { out.print(dp[find(i)]+" "); } } private void union(int p, int q) { int proot=find(p); int qroot=find(q); if(proot!=qroot) { id[proot]=qroot; } } private int find(int q) { if(id[q]!=q) { id[q]=find(id[q]); } return id[q]; } private boolean dfs(int node) { if(color[node]==1) { return false; } if(color[node]==2) { return true; } color[node]=1; int r=1; for(int nn=0;nn<A.length;nn++) { if(id[nn]!=nn||A[node][nn]==-1)continue; if(!dfs(nn)) { return false; } r=Math.max(r, dp[nn]+1); } dp[node]=r; color[node]=2; return true; } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br=new BufferedReader(new InputStreamReader(System.in)); } public String next() { if(st==null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } }
JAVA
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
import java.util.*; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; public class tr0 { static PrintWriter out; static StringBuilder sb; static int mod = 1000000007; static long inf = (long) 1e16; static int[][] ad; static int n, m; static long[][][] memo; static HashSet<Integer> h; static long[] a; static HashSet<Integer> leaves; static TreeMap<pair, Long> dp; static ArrayList<Long> ar; static boolean f; public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); out = new PrintWriter(System.out); n = sc.nextInt(); m = sc.nextInt(); unionfind uf = new unionfind(n + m); char[][] g = new char[n][m]; for (int i = 0; i < n; i++) g[i] = sc.nextLine().toCharArray(); f = true; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (g[i][j] == '>') { if (uf.sameSet(i, j + n)) f = false; uf.ha[uf.findSet(j + n)].add(uf.findSet(i)); } if (g[i][j] == '<') { if (uf.sameSet(i, j + n)) f = false; uf.ha[uf.findSet(i)].add(uf.findSet(j + n)); } if (g[i][j] == '=') { uf.combine(i, j + n); } } } uf.bfs(); if (!f) { System.out.println("No"); return; } System.out.println("Yes"); int[] pr1 = new int[n]; for (int i = 0; i < n; i++) pr1[i] = uf.ans[uf.findSet(i)]; int[] pr2 = new int[m]; for (int i = 0; i < m; i++) pr2[i] = uf.ans[uf.findSet(i + n)]; for (int i = 0; i < n; i++) out.print(pr1[i] + " "); out.println(); for (int i = 0; i < m; i++) out.print(pr2[i] + " "); out.close(); } static class unionfind { int[] p; int[] size; int[] max; int num; int[] ans; HashSet<Integer>[] ha; unionfind(int n) { p = new int[n]; size = new int[n]; ha = new HashSet[n]; ans = new int[n]; for (int i = 0; i < n; i++) { p[i] = i; ha[i] = new HashSet<>(); } Arrays.fill(size, 1); num = n; } int findSet(int v) { if (v == p[v]) return v; p[v] = findSet(p[v]); return p[v]; } boolean sameSet(int a, int b) { a = findSet(a); b = findSet(b); if (a == b) return true; return false; } boolean combine(int a, int b) { a = findSet(a); b = findSet(b); if (a == b) return true; // System.out.println(num+" ppp"); num--; if (size[a] > size[b]) { p[b] = a; size[a] += size[b]; size[b] = -1; ha[a].addAll(ha[b]); ha[b].clear(); } else { p[a] = b; size[b] += size[a]; size[a] = -1; ha[b].addAll(ha[a]); ha[a].clear(); } return false; } void bfs() { //System.out.println(Arrays.toString(ha)); // System.out.println(Arrays.toString(size)); int si = size.length; int[] dist = new int[si]; Queue<Integer> q = new LinkedList(); Arrays.fill(dist, -1); int[] pa = new int[si]; for (int i = 0; i < si; i++) if (size[i] == -1) continue; else { for (int v : ha[i]) pa[findSet(v)]++; } for (int i = 0; i < si; i++) if (pa[i] == 0 && size[i] != -1) { q.add(findSet(i)); ans[findSet(i)] = dist[findSet(i)] = 1; } // System.out.println(q); // System.out.println(Arrays.toString(pa)); while (!q.isEmpty()) { int u = q.poll(); for (int v : ha[u]) { // System.out.println(u+" "+findSet(v)+" "+pa[findSet(v)]); pa[findSet(v)]--; if(pa[findSet(v)]==0) { q.add(findSet(findSet(v))); ans[findSet(v)] = ans[findSet(u)] + 1; } } } for (int i = 0; i < si; i++) if (pa[i] > 0) f = false; } } static class pair implements Comparable<pair> { int to; long number; pair(int t, long n) { number = n; to = t; } public String toString() { return to + " " + number; } @Override public int compareTo(pair o) { if (to == o.to) return Long.compare(number, o.number); return to - o.to; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public int[] nextArrInt(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextArrLong(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } }
JAVA
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> using namespace std; int n, m; vector<vector<int>> g, gr, mat; void add_edge(int u, int v) { g[u].push_back(v); gr[v].push_back(u); mat[u][v] = 1; } vector<bool> used; vector<int> order, component; vector<vector<int>> components; void dfs1(int v) { used[v] = true; for (auto u : g[v]) if (!used[u]) dfs1(u); order.push_back(v); } void dfs2(int v) { used[v] = true; component.push_back(v); for (auto u : gr[v]) if (!used[u]) dfs2(u); } bool check_component() { for (auto v : component) if (v < n) { for (auto u : component) { if (u < n) continue; if (mat[v][u] && mat[u][v]) continue; else return false; } } return true; } int type(vector<int>& v) { bool b1 = true, b2 = true; for (auto e : v) if (e >= n) b1 = false; for (auto e : v) if (e < n) b2 = false; if (b1) return 1; if (b2) return 2; return 0; } int main() { cin >> n >> m; g.resize(n + m); gr.resize(n + m); mat.assign(n + m, vector<int>(n + m, 0)); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { char c; cin >> c; if (c == '>') add_edge(i, n + j); if (c == '<') add_edge(n + j, i); if (c == '=') { add_edge(i, n + j); add_edge(n + j, i); } } } used.assign(n + m, false); for (int i = 0; i < n + m; i++) if (!used[i]) dfs1(i); used.assign(n + m, false); for (int i = 0; i < n + m; i++) { int v = order[n + m - 1 - i]; if (!used[v]) { dfs2(v); if (!check_component()) { cout << "No" << endl; exit(0); } components.push_back(component); component.clear(); } } reverse(components.begin(), components.end()); int l = components.size(); set<int> s; for (int i = 0; i < l - 1; i++) { auto v1 = components[i], v2 = components[i + 1]; if ((type(v1) == 1 && type(v2) == 1) || (type(v1) == 2 && type(v2) == 2)) s.insert(i); } int counter = 1; vector<int> res(n + m); for (int i = 0; i < l; i++) { for (auto e : components[i]) res[e] = counter; if (!s.count(i)) counter += 1; } cout << "Yes" << endl; for (int i = 0; i < n; i++) cout << res[i] << " "; cout << endl; for (int i = n; i < n + m; i++) cout << res[i] << " "; cout << endl; }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> using namespace std; const long long N = 2010; struct DSU { long long connected; long long par[N], sz[N]; void init(long long n) { for (long long i = 1; i <= n; i++) { par[i] = i; sz[i] = 1; } connected = n; } long long getPar(long long k) { while (k != par[k]) { par[k] = par[par[k]]; k = par[k]; } return k; } long long getSize(long long k) { return sz[getPar(k)]; } void unite(long long u, long long v) { long long par1 = getPar(u), par2 = getPar(v); if (par1 == par2) return; connected--; if (sz[par1] > sz[par2]) swap(par1, par2); sz[par2] += sz[par1]; sz[par1] = 0; par[par1] = par[par2]; } }; long long n, m; long long val[N], vis[N], vis2[N]; char a[N][N]; vector<long long> g[N]; DSU dsu; bool findLoop(long long v) { if (vis[v] == 1) return 1; if (vis[v] == 2) return 0; vis[v] = 1; for (auto &it : g[v]) { if (findLoop(it)) return 1; } vis[v] = 2; return 0; } bool checkLoop() { fill(vis + 1, vis + n + 1, 0); for (long long i = 1; i <= n + m; i++) { if (!vis[i] && findLoop(i)) return 1; } return 0; } void dfs(long long u) { if (vis2[u]) return; vis2[u] = 1; for (auto &it : g[u]) dfs(it); val[u] = 1; for (auto &it : g[u]) val[u] = max(val[u], val[it] + 1); } int32_t main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); ; cin >> n >> m; dsu.init(n + m); for (long long i = 1; i <= n; i++) { for (long long j = 1; j <= m; j++) { cin >> a[i][j]; if (a[i][j] == '=') { dsu.unite(i, j + n); } } } for (long long i = 1; i <= n; i++) { for (long long j = 1; j <= m; j++) { if (a[i][j] == '>') g[dsu.getPar(i)].push_back(dsu.getPar(j + n)); if (a[i][j] == '<') g[dsu.getPar(j + n)].push_back(dsu.getPar(i)); } } if (checkLoop()) { cout << "No"; return 0; } for (long long i = 1; i <= n + m; i++) dfs(i); cout << "Yes" << "\n"; for (long long i = 1; i <= n + m; i++) { cout << val[dsu.getPar(i)] << " "; if (i == n) cout << "\n"; } cout << "\n"; return 0; }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> using namespace std; template <typename _T> inline void read(_T &f) { f = 0; _T fu = 1; char c = getchar(); while (c < '0' || c > '9') { if (c == '-') fu = -1; c = getchar(); } while (c >= '0' && c <= '9') { f = (f << 3) + (f << 1) + (c & 15); c = getchar(); } f *= fu; } template <typename T> void print(T x) { if (x < 0) putchar('-'), x = -x; if (x < 10) putchar(x + 48); else print(x / 10), putchar(x % 10 + 48); } template <typename T> void print(T x, char t) { print(x); putchar(t); } template <typename T> struct hash_map_t { vector<T> v, val, nxt; vector<int> head; int mod, tot, lastv; T lastans; bool have_ans; hash_map_t(int md = 0) { head.clear(); v.clear(); val.clear(); nxt.clear(); tot = 0; mod = md; nxt.resize(1); v.resize(1); val.resize(1); head.resize(mod); have_ans = 0; } bool count(int x) { int u = x % mod; for (register int i = head[u]; i; i = nxt[i]) { if (v[i] == x) { have_ans = 1; lastv = x; lastans = val[i]; return 1; } } return 0; } void ins(int x, int y) { int u = x % mod; nxt.push_back(head[u]); head[u] = ++tot; v.push_back(x); val.push_back(y); } int qry(int x) { if (have_ans && lastv == x) return lastans; count(x); return lastans; } }; const int N = 2005; vector<int> adj[N], adj2[N]; char c[N][N]; int n, m; int low[N], dfn[N], col[N], st[N], top, inst[N], f[N], in[N], cnt, color, gs; void tarjan(int u) { low[u] = dfn[u] = ++cnt; st[++top] = u; inst[u] = 1; for (register unsigned i = 0; i < adj[u].size(); i++) { int v = adj[u][i]; if (!dfn[v]) { tarjan(v); low[u] = min(low[u], low[v]); } else if (inst[v]) low[u] = min(low[u], dfn[v]); } if (low[u] == dfn[u]) { ++color; while (st[top + 1] != u) { int tmp = st[top--]; col[tmp] = color; inst[tmp] = 0; } } } int main() { read(n); read(m); for (register int i = 1; i <= n; i++) scanf("%s", c[i] + 1); for (register int i = 1; i <= n; i++) { for (register int j = 1; j <= m; j++) { if (c[i][j] == '=') { adj[i].push_back(j + n); adj[j + n].push_back(i); } } } for (register int i = 1; i <= n + m; i++) if (!dfn[i]) tarjan(i); for (register int i = 1; i <= n + m; i++) adj[i].clear(); for (register int i = 1; i <= n; i++) { for (register int j = 1; j <= m; j++) { if (c[i][j] == '<') { if (col[i] == col[j + n]) { cout << "No" << endl; return 0; } adj[col[i]].push_back(col[j + n]); ++in[col[j + n]]; } if (c[i][j] == '>') { if (col[i] == col[j + n]) { cout << "No" << endl; return 0; } adj[col[j + n]].push_back(col[i]); ++in[col[i]]; } } } queue<int> q; for (register int i = 1; i <= color; i++) { if (!in[i]) { q.push(i); f[i] = 1; } } while (!q.empty()) { int u = q.front(); q.pop(); ++gs; for (register unsigned i = 0; i < adj[u].size(); i++) { int v = adj[u][i]; --in[v]; f[v] = max(f[v], f[u] + 1); if (!in[v]) q.push(v); } } if (gs != color) { cout << "No" << endl; return 0; } cout << "Yes" << endl; for (register int i = 1; i <= n; i++) print(f[col[i]], ' '); putchar('\n'); for (register int i = 1; i <= m; i++) print(f[col[i + n]], ' '); putchar('\n'); return 0; }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> using namespace std; int dir4[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; long double eps = 1e-7; const int N = 1e3 + 5; int a[N][N]; long long dsu[2 * N], h[2 * N], num[2 * N], fath[2 * N]; pair<long long, long long> dp[2 * N]; vector<int> v[2 * N]; int vis[2 * N]; int root(int x) { if (x == dsu[x]) return x; return dsu[x] = root(dsu[x]); } void merge(int x, int y) { int rx = root(x); int ry = root(y); if (rx != ry) { if (h[rx] < h[ry]) dsu[rx] = ry; else { dsu[ry] = rx; if (h[rx] == h[ry]) h[rx]++; } } } int cntnodes = 0; void getSum(int node) { vis[node] = 1; cntnodes++; for (long long i = 0; i < v[node].size(); i++) { int son = v[node][i]; if (!vis[son]) getSum(son); } } void go(int node, long long cnt) { num[node] = max(cnt, num[node]); vis[node] = 1; for (long long i = 0; i < v[node].size(); i++) { int son = v[node][i]; if (!vis[son]) go(son, cnt + 1); } } bool back; void found(int node) { if (vis[node] == 1) { back = 1; return; } else if (vis[node] == 2) return; else vis[node] = 1; for (long long i = 0; i < v[node].size(); i++) { int son = v[node][i]; found(son); if (back) { vis[node] = 2; return; } } vis[node] = 2; } int main() { ios_base::sync_with_stdio(false); int n, m; scanf("%d%d", &n, &m); for (long long i = 1; i <= n + m; i++) dsu[i] = i; for (long long i = 1; i <= n; i++) { for (long long j = 1; j <= m; j++) { char ch; scanf(" %c", &ch); if (ch == '<') a[i][j] = 0; else if (ch == '=') a[i][j] = 1, merge(i, j + n); else a[i][j] = 2; } } for (long long i = 1; i <= n; i++) { for (long long j = 1; j <= m; j++) { if (!a[i][j]) { int ri = root(i); int rj = root(n + j); v[ri].push_back(rj); } else if (a[i][j] == 2) { int ri = root(i); int rj = root(n + j); v[rj].push_back(ri); } } } for (long long i = 1; i <= n + m; i++) fath[i] = root(i); for (long long i = 1; i <= n + m; i++) { int ri = fath[i]; if (vis[ri] == 0) { found(ri); if (back) break; } } if (back) { printf("No"); return 0; } for (long long i = 1; i <= n + m; i++) { int ri = fath[i]; memset(vis, 0, sizeof vis); cntnodes = 0; getSum(ri); dp[i] = {cntnodes, i}; } sort(dp + 1, dp + 1 + m + n); reverse(dp + 1, dp + 1 + m + n); for (long long i = 1; i <= n + m; i++) num[i] = 1; for (long long i = 1; i <= n + m; i++) { int ri = fath[dp[i].second]; memset(vis, 0, sizeof vis); go(ri, num[ri]); } printf("Yes\n"); for (long long i = 1; i <= n; i++) printf("%d ", num[root(i)]); printf("\n"); for (long long i = 1; i <= m; i++) printf("%d ", num[root(n + i)]); }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> using namespace std; const int maxn = 1000100; inline int read() { char ch = getchar(); int x = 0, f = 0; while (ch < '0' || ch > '9') f |= ch == '-', ch = getchar(); while (ch >= '0' && ch <= '9') x = x * 10 + ch - '0', ch = getchar(); return f ? -x : x; } int n, m, el, head[2020], to[maxn], nxt[maxn], q[2020], h = 1, r, deg[2020], fa[2020], val[maxn]; char mp[1010][1010]; bool vis[2020]; inline void add(int u, int v) { to[++el] = v; nxt[el] = head[u]; head[u] = el; deg[v]++; } int getfa(int x) { return x == fa[x] ? x : fa[x] = getfa(fa[x]); } void unite(int x, int y) { x = getfa(x); y = getfa(y); if (x != y) fa[x] = y; } int main() { n = read(); m = read(); for (int i = (1); i <= (n); i++) scanf("%s", mp[i] + 1); for (int i = (1); i <= (n + m); i++) fa[i] = i; for (int i = (1); i <= (n); i++) for (int j = (1); j <= (m); j++) if (mp[i][j] == '=') unite(i, j + n); for (int i = (1); i <= (n); i++) for (int j = (1); j <= (m); j++) { if (mp[i][j] == '<') add(getfa(i), getfa(j + n)); if (mp[i][j] == '>') add(getfa(j + n), getfa(i)); } for (int i = (1); i <= (n + m); i++) if (i == getfa(i) && !deg[i]) q[++r] = i, val[i] = 1, vis[i] = true; while (h <= r) { int u = q[h++]; for (int i = head[u]; i; i = nxt[i]) { int v = to[i]; if (vis[v]) continue; if (!--deg[v]) { vis[v] = true; val[v] = val[u] + 1; q[++r] = v; } } } for (int i = (1); i <= (n + m); i++) if (i == getfa(i) && !vis[i]) return puts("No"), 0; puts("Yes"); for (int i = (1); i <= (n); i++) printf("%d ", val[getfa(i)]); puts(""); for (int i = (1); i <= (m); i++) printf("%d ", val[getfa(i + n)]); }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> using namespace std; namespace atcoder { struct dsu { public: dsu() : _n(0) {} dsu(int n) : _n(n), parent_or_size(n, -1) {} int merge(int a, int b) { assert(0 <= a && a < _n); assert(0 <= b && b < _n); int x = leader(a), y = leader(b); if (x == y) return x; if (-parent_or_size[x] < -parent_or_size[y]) std::swap(x, y); parent_or_size[x] += parent_or_size[y]; parent_or_size[y] = x; return x; } bool same(int a, int b) { assert(0 <= a && a < _n); assert(0 <= b && b < _n); return leader(a) == leader(b); } int leader(int a) { assert(0 <= a && a < _n); if (parent_or_size[a] < 0) return a; return parent_or_size[a] = leader(parent_or_size[a]); } int size(int a) { assert(0 <= a && a < _n); return -parent_or_size[leader(a)]; } std::vector<std::vector<int>> groups() { std::vector<int> leader_buf(_n), group_size(_n); for (int i = 0; i < _n; i++) { leader_buf[i] = leader(i); group_size[leader_buf[i]]++; } std::vector<std::vector<int>> result(_n); for (int i = 0; i < _n; i++) { result[i].reserve(group_size[i]); } for (int i = 0; i < _n; i++) { result[leader_buf[i]].push_back(i); } result.erase( std::remove_if(result.begin(), result.end(), [&](const std::vector<int>& v) { return v.empty(); }), result.end()); return result; } private: int _n; std::vector<int> parent_or_size; }; } // namespace atcoder const int MAXN = 2010; string s[MAXN]; bool z[MAXN][MAXN]; int in[MAXN]; int ans[MAXN]; bool cz[MAXN]; int h[MAXN]; int main() { ios::sync_with_stdio(false); cin.tie(0); int n, m; cin >> n >> m; for (int i = 0; i < n; ++i) cin >> s[i]; atcoder::dsu dsu(n + m); for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (s[i][j] == '=') dsu.merge(i, n + j); } } bool flag = true; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (s[i][j] == '=') continue; if (dsu.same(i, n + j)) flag = false; } } if (!flag) { cout << "No\n"; return 0; } vector<int> leaders; for (int i = 0; i < n + m; ++i) { leaders.push_back(dsu.leader(i)); } sort(leaders.begin(), leaders.end()); leaders.erase(unique(leaders.begin(), leaders.end()), leaders.end()); int nm = leaders.size(); for (int i = 0; i < nm; ++i) h[leaders[i]] = i; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (s[i][j] == '=') continue; int a = dsu.leader(i), b = dsu.leader(n + j); if (s[i][j] == '<') { z[h[a]][h[b]] = true; } else { z[h[b]][h[a]] = true; } } } for (int i = 0; i < nm; ++i) { for (int j = 0; j < nm; ++j) { if (z[i][j]) ++in[j]; } } queue<int> Q; for (int i = 0; i < nm; ++i) { if (in[i] == 0) { Q.push(i); cz[i] = true; ans[i] = 1; } } while (!Q.empty()) { int a = Q.front(); Q.pop(); for (int i = 0; i < nm; ++i) { if (z[a][i]) { --in[i]; ans[i] = max(ans[i], ans[a] + 1); if (in[i] == 0) { Q.push(i); cz[i] = true; } } } } int cnt = 0; for (int i = 0; i < nm; ++i) { if (cz[i]) ++cnt; } if (cnt != leaders.size()) { cout << "No\n"; return 0; } cout << "YES\n"; for (int i = 0; i < n; ++i) { cout << ans[h[dsu.leader(i)]] << " "; } cout << '\n'; for (int i = 0; i < m; ++i) { cout << ans[h[dsu.leader(n + i)]] << " "; } cout << '\n'; return 0; }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
import java.io.*; import java.util.*; public class Main { static long mod=1000000007; public static void main(String[] args){ int n=ni(),m=ni(); int[][] ta=new int[n][m]; int[][] ta2=new int[m][n]; for(int i=0;i<n;i++){ String str=next(); for(int j=0;j<m;j++){ char ch=str.charAt(j); if(ch=='>'){ ta[i][j]=1; }else if(ch=='<'){ ta[i][j]=-1; }else ta[i][j]=0; ta2[j][i]=-ta[i][j]; } } int[] first=sol(ta,n,m); int[] second=sol(ta2,m,n); boolean ch=true; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ if(ta[i][j]==1){ if(!(first[i]>second[j])) ch=false; } if(ta[i][j]==0){ if(!(first[i]==second[j])) ch=false; } if(ta[i][j]==-1){ if(!(first[i]<second[j])) ch=false; } } } if(!ch){ pl("No"); }else{ pl("Yes"); for(int i=0;i<n;i++){ pr(first[i]+(i==(n-1)?"\n":" ")); } for(int i=0;i<m;i++){ pr(second[i]+(i==(m-1)?"\n":" ")); } } flush(); } static int[] sol(int[][] ta,int n,int m){ int[] f=new int[n],s=new int[m]; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ f[i]+=ta[i][j]; } } Integer[] find=sortedIndex(f); int[] ruif=new int[n+1]; for(int i=1;i<n;i++){ if(f[find[i]]==f[find[i-1]]) continue; ruif[i]++; } boolean[] ju=new boolean[n+1]; for(int i=0;i<m;i++){ int sita=0,ue=0; for(int j=0;j<n;j++){ if(ta[j][i]==1) ue++; else if(ta[j][i]==-1) sita++; } if((ue+sita)<n) continue; if(ju[sita]) continue; ruif[sita]++; ju[sita]=true; } ruif[0]++; int sum=0; int[] ten=new int[n]; for(int i=0;i<n;i++){ sum+=ruif[i]; ten[i]=sum; } int[] first=new int[n]; for(int i=0;i<n;i++){ first[find[i]]=ten[i]; } //pl(Arrays.toString(first)); return first; } private static final byte[] buffer = new byte[1024]; private static int ptr = 0; private static int buflen = 0; private static boolean hasNextByte() { if (ptr < buflen) return true; else{ ptr = 0; try { buflen = System.in.read(buffer); } catch (IOException e) {e.printStackTrace();} if (buflen <= 0) return false; } return true; } private static int readByte() { return hasNextByte() ? buffer[ptr++] : -1;} private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;} private static void skipUnprintable() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++;} public static boolean hasNext() { skipUnprintable(); return hasNextByte();} public static String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); for(int b = readByte();isPrintableChar(b);b = readByte()) { sb.appendCodePoint(b); } return sb.toString(); } public static int nextInt() {return (int)nextLong();} public static long nextLong() { if (!hasNext()) throw new NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) throw new NumberFormatException(); while(true){ if ('0' <= b && b <= '9') n = n * 10 + b-'0'; else if(b == -1 || !isPrintableChar(b)) return minus ? -n : n; else throw new NumberFormatException(); b = readByte(); } } public static long[] nextLongArray(int i){ long[] result=new long[i]; for(int j=0;j<i;j++) result[j]=nextLong(); return result; } public static void nextLongArray(long[]... arrays){ for(int j=0;j<arrays[0].length;j++) for(long[] array:arrays) array[j]=nextLong(); } public static int[] nextIntArray(int i){ int[] result=new int[i]; for(int j=0;j<i;j++) result[j]=nextInt(); return result; } public static void nextIntArray(int[]... arrays){ for(int j=0;j<arrays[0].length;j++) for(int[] array:arrays) array[j]=nextInt(); } public static int ni(){return nextInt();} public static long nl(){return nextLong();} public static int[] nia(int n){return nextIntArray(n);} public static long[] nla(int n){return nextLongArray(n);} public static String ne(){return next();} static StringBuilder sb=new StringBuilder(); public static void flush(){ System.out.print(sb); sb=new StringBuilder(); } public static void pr(Object o){sb.append(o);} public static void pl(Object o){sb.append(o).append("\n");} public static void pl(){sb.append("\n");} public static int lastLowerIndex(long[] array,long lo){return lastLowerOrEqualIndex(array,lo-1);} public static int lastLowerOrEqualIndex(long[] array,long lo){ int res=Arrays.binarySearch(array,lo); return res<0?-res-2:res; } public static long gcd(long a,long b){ if(a>b)a%=b; while(a>0){ b%=a; if(b==0)return a; a%=b; } return b; } public static long modPow(long a,long b,long mod){ long c=1; while(b>0){ if(b%2==1) c=(c*a)%mod; a=(a*a)%mod; b/=2; } return c; } public static long inv(long a,long mod){ long b=mod; long p = 1, q = 0; while (b > 0) { long c = a / b; long d=a; a = b; b = d % b; d = p; p = q; q = d - c * q; } return p < 0 ? p + mod : p; } static long time=0; public static void time(){ if(time==0) time=System.nanoTime(); else{ long t=System.nanoTime(); pl((t-time)/1000000000.0+"sec"); time=t; } } public static Integer[] sortedIndex(int[] a){ Integer[] res=new Integer[a.length]; for(int i=0;i<a.length;i++) res[i]=i; mergesortIndex(res,a,0,a.length); return res; } private static Integer[] stem=new Integer[200005]; private static void mergesortIndex(Integer[] index,int[] a, int s, int e){//uwi's if(e - s <= 1)return; int h = s+e>>1; mergesortIndex(index,a, s, h); mergesortIndex(index,a, h, e); int p = 0; int i= s, j = h; for(;i < h && j < e;)stem[p++] = a[(int)index[i]] < a[(int)index[j]] ? index[i++] : index[j++]; while(i < h)stem[p++] = index[i++]; while(j < e)stem[p++] = index[j++]; System.arraycopy(stem, 0, index, s, e-s); } private static long[] stmp=new long[200005]; private static void mergesort(long[] a, int s, int e){//uwi's if(e - s <= 1)return; int h = s+e>>1; mergesort(a, s, h); mergesort(a, h, e); int p = 0; int i= s, j = h; for(;i < h && j < e;)stmp[p++] = a[i] < a[j] ? a[i++] : a[j++]; while(i < h)stmp[p++] = a[i++]; while(j < e)stmp[p++] = a[j++]; System.arraycopy(stmp, 0, a, s, e-s); } }
JAVA
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
import java.io.*; import java.util.*; public class Task { public static void main(String[] args) throws IOException { new Task().go(); } PrintWriter out; Reader in; BufferedReader br; Task() throws IOException { try { //br = new BufferedReader( new FileReader("input.txt") ); in = new Reader("input.txt"); out = new PrintWriter( new BufferedWriter(new FileWriter("output.txt")) ); } catch (Exception e) { //br = new BufferedReader( new InputStreamReader( System.in ) ); in = new Reader(); out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.out)) ); } } void go() throws IOException { int t = 1; while (t > 0) { solve(); //out.println(); t--; } out.flush(); out.close(); } int inf = 2000000000; int mod = 1000000007; double eps = 0.000000001; int n; int m; int[][] a; int[][] dir = new int[2000][2000]; ArrayList<Integer>[] g; void solve() throws IOException { int n = in.nextInt(); int m = in.nextInt(); g = new ArrayList[n + m]; a = new int[n][m]; DSU dsu = new DSU(n + m); for (int i = 0; i < n + m; i++) g[i] = new ArrayList<>(); for (int i = 0; i < n; i++) { String s = in.next(); for (int j = 0; j < m; j++) { a[i][j] = s.charAt(j); if (s.charAt(j) == '=') dsu.union(i, j + n); } } for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { int x = dsu.get(i); int y = dsu.get(j + n); if (a[i][j] == '>') { g[y].add(x); dir[y][x] = 1; } else if (a[i][j] == '<') { g[x].add(y); dir[x][y] = 1; } } for (int i = 0; i < n + m; i++) { int x = dsu.get(i); if (used[x] == 0) dfs(x); } Collections.reverse(ts); if (!ok) { out.println("No"); return; } for (int v : ts) if (marks[v] == 0) { dfs(v, 1); } for (int i = 0; i < n + m; i++) if (marks[i] != 0) for (int j = 0; j < n + m; j++) if (dsu.same(i, j)) marks[j] = marks[i]; out.println("Yes"); for (int i = 0; i < n; i++) out.print(marks[i] + " "); out.println(); for (int i = 0; i < m; i++) out.print(marks[i + n] + " "); } int[] marks = new int[10000]; int[] used = new int[10000]; boolean ok = true; ArrayList<Integer> ts = new ArrayList<>(); void dfs(int v) { used[v] = 1; for (int u : g[v]) if (used[u] == 0) dfs(u); else if (used[u] == 1) ok = false; ts.add(v); used[v] = 2; } void dfs(int v, int mark) { marks[v] = mark; for (int u : ts) if (marks[u] == 0 && dir[v][u] == 1) dfs(u, mark + 1); } class DSU { int[] set; int[] rank; DSU(int n) { set = new int[n]; rank = new int[n]; Arrays.fill(rank, 1); for (int i = 0; i < n; i++) set[i] = i; } int get(int a) { if (set[a] == a) return a; return set[a] = get(set[a]); } void union(int a, int b) { a = get(a); b = get(b); if (a == b) return; if (rank[b] > rank[a]) { a ^= b; b ^= a; a ^= b; } set[b] = a; rank[a] += rank[b]; } boolean same(int a, int b) { return get(a) == get(b); } } class Pair implements Comparable<Pair>{ int a; int b; Pair(int a, int b) { this.a = a; this.b = b; } public int compareTo(Pair p) { if (a > p.a) return 1; if (a < p.a) return -1; if (b > p.b) return 1; if (b < p.b) return -1; return 0; } } class Item { int a; int b; int c; Item(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } } class Reader { BufferedReader br; StringTokenizer tok; Reader(String file) throws IOException { br = new BufferedReader( new FileReader(file) ); } Reader() throws IOException { br = new BufferedReader( new InputStreamReader(System.in) ); } String next() throws IOException { while (tok == null || !tok.hasMoreElements()) tok = new StringTokenizer(br.readLine()); return tok.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.valueOf(next()); } long nextLong() throws NumberFormatException, IOException { return Long.valueOf(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.valueOf(next()); } String nextLine() throws IOException { return br.readLine(); } int[] nextIntArray(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } ArrayList<Integer>[] nextGraph(int n, int m) throws IOException { ArrayList<Integer>[] g = new ArrayList[n]; for (int i = 0; i < n; i++) g[i] = new ArrayList<>(); for (int i = 0; i < m; i++) { int x = nextInt() - 1; int y = nextInt() - 1; g[x].add(y); g[y].add(x); } return g; } } }
JAVA
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> using namespace std; inline int read() { int x = 0, f = 1; char c = getchar(); while (c < '0' || c > '9') { if (c == '-') f = -1; c = getchar(); } while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = getchar(); } return x * f; } inline long long readl() { long long x = 0, f = 1; char c = getchar(); while (c < '0' || c > '9') { if (c == '-') f = -1; c = getchar(); } while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = getchar(); } return x * f; } int power(int a, int b) { int ans = 1; while (b) { if (b & 1) ans = ans * a; b >>= 1; a = a * a; } return ans; } int power_mod(int a, int b, int mod) { a %= mod; int ans = 1; while (b) { if (b & 1) ans = (ans * a) % mod; b >>= 1, a = (a * a) % mod; } return ans; } long long powerl(long long a, long long b) { long long ans = 1ll; while (b) { if (b & 1ll) ans = ans * a; b >>= 1ll; a = a * a; } return ans; } long long power_modl(long long a, long long b, long long mod) { a %= mod; long long ans = 1ll; while (b) { if (b & 1ll) ans = (ans * a) % mod; b >>= 1ll, a = (a * a) % mod; } return ans; } long long gcdl(long long a, long long b) { return b == 0 ? a : gcdl(b, a % b); } long long abssl(long long a) { return a > 0 ? a : -a; } int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } int abss(int a) { return a > 0 ? a : -a; } const int MAXN = 2000 + 5; int n, m, ino[MAXN], f[MAXN], ans[MAXN], vis[MAXN]; vector<int> G[MAXN]; char s[MAXN][MAXN]; queue<pair<int, int> > q; int find(int x) { return x == f[x] ? x : f[x] = find(f[x]); } int main() { memset(ino, 0, sizeof ino); cin >> n >> m; for (int i = 1; i <= n + m; ++i) f[i] = i; for (int i = 1; i <= n; ++i) scanf("%s", s[i] + 1); for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { if (s[i][j] == '=') { int x = find(i), y = find(j + n); if (x != y) f[x] = y; } } } for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { if (s[i][j] == '>') { int y; G[find(i)].push_back(y = find(j + n)); ++ino[y]; } if (s[i][j] == '<') { int y; G[find(j + n)].push_back(y = find(i)); ++ino[y]; } } } for (int y, i = 1; i <= n + m; ++i) if (ino[y = find(i)] == 0 && !vis[y]) q.push(make_pair(y, 1)), vis[y] = 1; int maxv = 0; while (!q.empty()) { pair<int, int> p = q.front(); q.pop(); ans[p.first] = p.second; maxv = max(maxv, p.second); for (int i = 0; i < (int)G[p.first].size(); ++i) { int v = G[p.first][i]; --ino[v]; if (ino[v] == 0) q.push(make_pair(v, p.second + 1)); } } int fl = 0; for (int i = 1; i <= n + m; ++i) if (ino[i] != 0) fl = 1; if (fl) printf("No\n"); else { printf("Yes\n"); for (int i = 1; i <= n; ++i) printf("%d ", maxv - ans[find(i)] + 1); puts(""); for (int i = 1; i <= m; ++i) printf("%d ", maxv - ans[find(i + n)] + 1); } return 0; }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
import java.util.*; import java.io.*; import java.text.*; //Solution Credits: Taranpreet Singh public class Main{ //SOLUTION BEGIN void pre() throws Exception{} void solve(int TC) throws Exception{ int n = ni(), m = ni(), xx = 0; int[] set = new int[n+m]; for(int i = 0; i< n+m; i++)set[i] = i; char[][] g = new char[n][m]; for(int i = 0; i< n; i++){ String s = n(); for(int j = 0; j< m; j++){ g[i][j] = s.charAt(j); if(g[i][j]=='='){ set[find(set, n+j)] = i;xx++; } } } boolean val = true; int[][] e = new int[n*m-xx][];xx = 0; for(int i = 0; i< n && val; i++) for(int j = 0; j< m && val; j++){ if(g[i][j]!='='){ int x = find(set, i), y = find(set, n+j); if(x==y)val = false; } if(g[i][j]=='<')e[xx++] = new int[]{find(set, i), find(set, n+j)}; else if(g[i][j]=='>')e[xx++] = new int[]{find(set, n+j), find(set, i)}; } if(!val){ pn("No");return; } int[][] gr = makeD(n+m, e); if(isCyclic(gr))pn("No"); else{ int[] deg = new int[n+m]; TreeSet<Integer> se = new TreeSet<>(); int[] ans = new int[n+m]; for(int[] ee:e)deg[ee[1]]++; for(int i = 0; i< n+m; i++){ if(find(set, i)!=i)continue; if(deg[i]==0){ ans[i] = 1; se.add(i); } } while(!se.isEmpty()){ int x = se.pollFirst(); for(int v:gr[x]){ deg[v]--; if(deg[v]==0){ ans[v] = ans[x]+1; se.add(v); } } } pn("Yes"); for(int i = 0; i< n; i++)p(ans[find(set, i)]+" ");pn(""); for(int i = 0; i< m; i++)p(ans[find(set, n+i)]+" ");pn(""); } } private boolean isCyclicUtil(int[][] g, int i, boolean[] visited, boolean[] recStack){ if (recStack[i])return true; if (visited[i])return false; visited[i] = true; recStack[i] = true; for(int x:g[i]) if(isCyclicUtil(g, x, visited, recStack)) return true; recStack[i] = false; return false; } private boolean isCyclic(int[][] g){ boolean[] visited = new boolean[g.length]; boolean[] recStack = new boolean[g.length]; // Call the recursive helper function to // detect cycle in different DFS trees for (int i = 0; i < g.length; i++) if (isCyclicUtil(g, i, visited, recStack)) return true; return false; } int[][] makeD(int n, int[][] edge){ int[][] g = new int[n][]; ;int[] cnt = new int[n]; for(int i = 0; i< edge.length; i++)cnt[edge[i][0]]++; for(int i = 0; i< n; i++)g[i] = new int[cnt[i]]; for(int i = 0; i< edge.length; i++)g[edge[i][0]][--cnt[edge[i][0]]] = edge[i][1]; return g; } int find(int[] set, int i){ if(set[i]==i)return i; return set[i] = find(set, set[i]); } //SOLUTION END void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");} long mod = (long)1e9+7, IINF = (long)1e18; final int INF = (int)1e9, MX = (int)5e6+2; DecimalFormat df = new DecimalFormat("0.00000000000"); double PI = 3.1415926535897932384626433832792884197169399375105820974944, eps = 1e-8; static boolean multipleTC = false, memory = false; FastReader in;PrintWriter out; void run() throws Exception{ in = new FastReader(); out = new PrintWriter(System.out); int T = (multipleTC)?ni():1; //Solution Credits: Taranpreet Singh pre();for(int t = 1; t<= T; t++)solve(t); out.flush(); out.close(); } public static void main(String[] args) throws Exception{ if(memory)new Thread(null, new Runnable() {public void run(){try{new Main().run();}catch(Exception e){e.printStackTrace();}}}, "1", 1 << 28).start(); else new Main().run(); } long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);} int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);} int bit(long n){return (n==0)?0:(1+bit(n&(n-1)));} void p(Object o){out.print(o);} void pn(Object o){out.println(o);} void pni(Object o){out.println(o);out.flush();} String n()throws Exception{return in.next();} String nln()throws Exception{return in.nextLine();} int ni()throws Exception{return Integer.parseInt(in.next());} long nl()throws Exception{return Long.parseLong(in.next());} double nd()throws Exception{return Double.parseDouble(in.next());} class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws Exception{ br = new BufferedReader(new FileReader(s)); } String next() throws Exception{ while (st == null || !st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); }catch (IOException e){ throw new Exception(e.toString()); } } return st.nextToken(); } String nextLine() throws Exception{ String str = ""; try{ str = br.readLine(); }catch (IOException e){ throw new Exception(e.toString()); } return str; } } }
JAVA
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> using namespace std; void fun() {} int md = 1e9 + 7; int __gcd(int a, int b) { if (b == 0) return a; return __gcd(b, a % b); } int poww(int a, int b, int md) { if (b < 0) return 0; if (a == 0) return 0; int res = 1; while (b) { if (b & 1) { res = (1ll * res * a) % md; } a = (1ll * a * a) % md; b >>= 1; } return res; } int poww(int a, int b) { if (b < 0) return 0; if (a == 0) return 0; int res = 1; while (b) { if (b & 1) { res = (1ll * res * a); } a = (1ll * a * a); b >>= 1; } return res; } void ainp(int arr[], int n) { for (int i = 1; i <= n; i++) cin >> arr[i]; } void disp(int arr[], int n) { for (int i = 1; i <= n; i++) cout << arr[i] << " "; cout << "\n"; } void dispv(vector<int> &v) { for (int i = 0; i < v.size(); i++) cout << v[i] << " "; cout << "\n"; } int divide(int a, int b, int md) { int rr = a * (poww(b, md - 2, md)); rr %= md; return rr; } const int size = 2004; char arr[size][size]; int ans[size]; vector<int> g[size]; int vis[size]; int parent[size]; int n, m; void pre() { for (int i = 1; i < size; i++) parent[i] = i; } int findp(int node) { if (parent[node] == node) return node; return parent[node] = findp(parent[node]); } void unite(int par, int child) { par = findp(par), child = findp(child); if (par == child) return; parent[child] = par; } bool check(int par) { if (vis[par] == 2) return 0; if (vis[par] == 1) return 1; vis[par] = 1; for (int child : g[par]) if (check(child)) return 1; vis[par] = 2; return 0; } bool checkloop() { for (int i = 1; i <= n + m; i++) if (!vis[i] && check(i)) return 1; return 0; } void dfs(int par) { if (vis[par]) return; ans[par] = 1; vis[par] = 1; for (int child : g[par]) { dfs(child); ans[par] = max(ans[child] + 1, ans[par]); } } signed main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); fun(); pre(); cin >> n >> m; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { cin >> arr[i][j]; if (arr[i][j] == '=') unite(i, j + n); } } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (arr[i][j] == '>') g[findp(i)].push_back(findp(j + n)); else if (arr[i][j] == '<') g[findp(j + n)].push_back(findp(i)); } } if (checkloop()) return cout << "NO\n", 0; memset(vis, 0, sizeof(vis)); for (int i = 1; i <= n + m; i++) dfs(i); cout << "YES\n"; for (int i = 1; i <= n + m; i++) { cout << ans[findp(i)] << " "; if (i == n) cout << "\n"; } cout << "\n"; return 0; }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> using namespace std; const int INF = 0x3f3f3f3f; const int N = 2005; int pre[N]; int find(int x) { return (x == pre[x]) ? x : pre[x] = find(pre[x]); } void join(int x, int y) { int rx = find(x), ry = find(y); if (rx == ry) return; pre[rx] = ry; } int in[N]; vector<int> G[N]; char mp[1005][1005]; int num[N]; bool vis[N]; int main() { ios::sync_with_stdio(false); cin.tie(0); int n, m; cin >> n >> m; for (int i = 1; i <= (int)(n + m); ++i) pre[i] = i; for (int i = 1; i <= (int)(n); ++i) { for (int j = 1; j <= (int)(m); ++j) { char tmp; cin >> tmp; mp[i][j] = tmp; if (tmp == '=') join(i, j + n); } } for (int i = 1; i <= (int)(n); ++i) { for (int j = 1; j <= (int)(m); ++j) { char tmp = mp[i][j]; int ri = find(i); int rj = find(j + n); if (tmp == '<') { G[ri].push_back(rj); in[rj]++; } else if (tmp == '>') { G[rj].push_back(ri); in[ri]++; } } } queue<int> q; int curn = 1; for (int i = 1; i <= (int)(n + m); ++i) { if (in[i] == 0 && find(i) == i) { q.push(i); num[i] = curn; } } curn++; while (!q.empty()) { int x = q.front(); int flag = 0; q.pop(); if (vis[x]) continue; vis[x] = true; for (int i = 0; i < (int)(G[x].size()); ++i) { int end = G[x][i]; in[end]--; if (in[end] == 0 && find(end) == end) { q.push(end); num[end] = curn; flag = 1; } } if (flag == 1) ++curn; flag = 0; } int flag = 0; for (int i = 1; i <= (int)(n + m); ++i) { if (!vis[pre[i]]) flag = 1; } if (flag) { cout << "NO"; return 0; } cout << "YES" << endl; for (int i = 1; i <= (int)(n); ++i) { cout << num[find(i)] << ' '; } cout << endl; for (int i = (int)(n + 1); i <= (int)(n + m); ++i) cout << num[find(i)] << ' '; }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> using namespace std; int n, m, f[100005], mp[2005][2005], in[2005], vis[2005], q[200005], dis[200005], head = 0, tail = 0, cnt = 0; char a[1005][1005]; int find(int x) { if (f[x] == x) return x; return f[x] = find(f[x]); } void link(int x, int y) { x = find(x), y = find(y); if (x == y) return; f[x] = y; } int main() { scanf("%d%d", &n, &m); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) scanf(" %c", &a[i][j]); for (int i = 1; i <= n + m; i++) f[i] = i; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) if (a[i][j] == '=') link(i, n + j); for (int i = 1; i <= n + m; i++) vis[find(i)] = 1; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { int x = find(i), y = find(n + j); if (x == y && a[i][j] != '=') { printf("No"); return 0; } if (a[i][j] == '<') { if (mp[x][y] == 0) in[y]++; mp[x][y] = 1; } else if (a[i][j] == '>') { if (mp[y][x] == 0) in[x]++; mp[y][x] = 1; } } for (int i = 1; i <= n + m; i++) { if (vis[i] && in[i] == 0) { q[++tail] = i; dis[i] = 1; } if (vis[i]) { cnt++; } } while (head < tail) { head++; int u = q[head]; for (int i = 1; i <= n + m; i++) if (mp[u][i]) { in[i]--; dis[i] = max(dis[i], dis[u] + 1); if (in[i] == 0) q[++tail] = i; } } if (tail < cnt) { printf("No"); return 0; } printf("Yes\n"); for (int i = 1; i <= n; i++) printf("%d ", dis[find(i)]); printf("\n"); for (int i = 1; i <= m; i++) printf("%d ", dis[find(i + n)]); return 0; }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
r,c = map(int, input().split()) m = [] p = [i for i in range(0,r+c)] tree = [[] for i in range(0, r+c)] for i in range(0,r): s = input().split('\n')[0] m.append(list(s)) def find(i): if p[i] ==i: return i par = find(p[i]) p[i] = par return p[i] def join(i,j): p[find(i)] = find(j) for i in range(0,r): for j in range(0,c): if m[i][j] == '=': join(i,r+j) elif m[i][j] == '>': tree[i].append(r+j) elif m[i][j] == '<': tree[r+j].append(i) v = [False for i in range(0, r+c)] v2 = [False for i in range(0, r+c)] a = [1 for i in range(0,r+c)] l = [[] for i in range(0,r+c)] for i in range(0,r+c): l[find(i)].append(i) import sys def dfs(i): i = find(i) if v[i]: return sys.maxsize elif v2[i]: return a[i] v[i] = True for k in l[i]: for j in tree[k]: a[i] = max(dfs(j)+1, a[i]) v[i] = False v2[i] = True return a[i] A = [] ans = True for i in range(0,r+c): A.append(dfs(i)) if A[i] > r+c: ans = False m = {} index = 0 pre = -1 for i in sorted(A): if pre == i: m[i] = index else: pre = i index+=1 m[i] = index for i in range(0,r+c): A[i] = m[A[i]] if ans: print("Yes") print(str(A[:r]).replace(',','').replace('[','').replace(']','')) print(str(A[r:]).replace(',','').replace('[','').replace(']','')) else: print("No")
PYTHON3
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> using namespace std; const int inf = 0x3f3f3f3f; const int maxn = 1000010; int n, m, r, h = 1; char mp[1010][1010]; bool vis[2020]; int pre[2020], deg[2020], q[2020], val[1000010]; int head[2020], tot = 0; struct node { int v, next, w; node(int _v = 0, int _next = 0, int _w = 0) : v(_v), next(_next), w(_w) {} } edge[maxn]; inline void add(int u, int v) { edge[++tot].v = v; edge[tot].next = head[u]; head[u] = tot; deg[v]++; } int Find(int x) { return x == pre[x] ? x : pre[x] = Find(pre[x]); } void join(int x, int y) { pre[Find(x)] = Find(y); } int main() { cin >> n >> m; for (int i = 1; i <= n; ++i) scanf("%s", mp[i] + 1); for (int i = 1; i < 2005; ++i) pre[i] = i; for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) if (mp[i][j] == '=') join(i, j + n); for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { if (mp[i][j] == '<') add(Find(i), Find(j + n)); if (mp[i][j] == '>') add(Find(j + n), Find(i)); } } for (int i = 1; i <= n + m; ++i) if (i == Find(i) && !deg[i]) q[++r] = i, val[i] = 1, vis[i] = 1; while (h <= r) { int u = q[h++]; for (int i = head[u]; i; i = edge[i].next) { int v = edge[i].v; if (vis[v]) continue; deg[v]--; if (!deg[v]) { vis[v] = 1; val[v] = val[u] + 1; q[++r] = v; } } } for (int i = 1; i <= n + m; ++i) { if (i == Find(i) && !vis[i]) { cout << "No" << endl; return 0; } } cout << "Yes" << endl; for (int i = 1; i <= n; i++) cout << val[Find(i)] << " "; cout << endl; for (int i = 1; i <= m; i++) cout << val[Find(i + n)] << " "; cout << endl; return 0; }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> using namespace std; const int maxn = 1e6 + 5; int fa[maxn]; int find(int x) { return x == fa[x] ? x : fa[x] = find(fa[x]); } int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n, m; cin >> n >> m; vector<string> s(n); for (auto& x : s) cin >> x; for (int i = 0; i < n + m; i++) { fa[i] = i; } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (s[i][j] == '=') { int a = find(i), b = find(n + j); if (a == b) continue; fa[b] = a; } } } vector<int> deg(n + m, 0), ans(n + m, 0); vector<vector<int>> G(n + m); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { switch (s[i][j]) { case '>': G[find(n + j)].push_back(find(i)), ++deg[find(i)]; break; case '<': G[find(i)].push_back(find(n + j)), ++deg[find(n + j)]; break; default: break; } } } queue<int> Q; for (int i = 0; i < n + m; i++) { if (i == find(i) && !deg[i]) { ans[i] = 1; Q.push(i); } } while (!Q.empty()) { int u = Q.front(); Q.pop(); for (int v : G[u]) { ans[v] = max(ans[u] + 1, ans[v]); if (--deg[v] == 0) Q.push(v); } } for (int i = 0; i < n + m; i++) { if (deg[i] != 0) { cout << "No" << endl; return 0; } } cout << "Yes" << endl; for (int i = 0; i < n; i++) cout << ans[find(i)] << " "; cout << "\n"; for (int i = n; i < n + m; i++) cout << ans[find(i)] << " "; cout << "\n"; }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
import time debug = False n1, m2 = map(int, input().split()) tests = [] for i in range(n1): tests.append(list(input())) if debug: print (tests) begin = time.time() if debug: print("---") marks1 = [] result1 = [] for i in range(n1): marks1.append([i,0.0]) result1.append(0) marks2 = [] result2 = [] for j in range(m2): marks2.append([j,0.0]) result2.append(0) for i in range(n1): for j in range(m2): test = tests[i][j] if test == ">": marks1[i][1] += 1.0 elif test == "<": marks2[j][1] += 1.0 else: marks1[i][1] += 0.0001 marks2[j][1] += 0.0001 marks1.sort(key=lambda val: val[1]) marks2.sort(key=lambda val: val[1]) if debug: print(marks1) print(marks2) i = 0 j = 0 value = 0 lastmark = -1 lastItem = [0,0] while i < n1 or j < m2: LetAdd = 0 if i < n1 and j < m2: test = tests[marks1[i][0]][marks2[j][0]] if test == ">": LetAdd = 2 else: LetAdd = 1 elif i < n1: LetAdd = 1 else: LetAdd = 2 if LetAdd == 1: if marks1[i][1] != lastmark and lastItem[0] != 2 or lastItem[0] == 2 and tests[marks1[i][0]][lastItem[1]] != '=': if debug: if lastItem[0] == 2: print(1, lastmark, lastItem, marks1[i][0], tests[marks1[i][0]][lastItem[1]]) else: print(1, lastmark, lastItem, marks1[i][0]) value += 1 lastmark = marks1[i][1] result1[marks1[i][0]] = value lastItem = [1,marks1[i][0]] i += 1 else: if marks2[j][1] != lastmark and lastItem[0] != 1 or lastItem[0] == 1 and tests[lastItem[1]][marks2[j][0]] != '=': if debug: if lastItem[0] == 1: print(2, lastmark, lastItem, marks2[j][0], tests[lastItem[1]][marks2[j][0]]) else: print(2, lastmark, lastItem, marks2[j][0]) value += 1 lastmark = marks2[j][1] result2[marks2[j][0]] = value lastItem = [2,marks2[j][0]] j += 1 if debug: print("Set ", lastItem, " to ", value) CheckCorrect = True for i in range(n1): for j in range(m2): test = tests[i][j] if test == ">": if result1[i] <= result2[j]: CheckCorrect = False elif test == "<": if result1[i] >= result2[j]: CheckCorrect = False else: if result1[i] != result2[j]: CheckCorrect = False if debug: print("---") if debug: print("Time: ", time.time() - begin) if CheckCorrect: print ("Yes") else: print ("No") if CheckCorrect or debug: print (*result1) print (*result2)
PYTHON3
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> using namespace std; const int N = 2010; int n, m; char s[N][N]; int fa[N], deg[N], vis[N], len[N]; vector<int> g[N]; int getfa(int x) { return fa[x] == x ? x : fa[x] = getfa(fa[x]); } void dfs(int u) { vis[u] = 1; len[u] = 1; for (int i = 0; i < (int)g[u].size(); i++) { int v = g[u][i]; if (v == u) { puts("No"); exit(0); } if (vis[v] == 1) { puts("No"); exit(0); } else if (vis[v] == 2) { len[u] = max(len[u], len[v] + 1); } else { dfs(v); len[u] = max(len[u], len[v] + 1); } } vis[u] = 2; } int main() { scanf("%d%d", &n, &m); for (int i = 1; i <= n + m; i++) fa[i] = i; for (int i = 1; i <= n; i++) scanf("%s", s[i] + 1); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) if (s[i][j] == '=') fa[getfa(i)] = getfa(j + n); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { if (s[i][j] == '>') g[getfa(i)].push_back(getfa(j + n)), deg[getfa(j + n)]++; else if (s[i][j] == '<') g[getfa(j + n)].push_back(getfa(i)), deg[getfa(i)]++; } for (int i = 1; i <= n + m; i++) if (!deg[i]) dfs(i); for (int i = 1; i <= n + m; i++) if (vis[i] != 2) { puts("No"); return 0; } puts("Yes"); for (int i = 1; i <= n; i++) printf("%d ", len[getfa(i)]); puts(""); for (int i = 1; i <= m; i++) printf("%d ", len[getfa(i + n)]); puts(""); return 0; }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> using namespace std; const long long MOD = 1e9 + 7; int n, m, par[2010], gx[2010][2010], ans[2010], num[2010], dg[2010]; string s[1010]; vector<int> g[2010], topo; bool vis[2010]; int FIND(int pos) { if (par[pos] != pos) par[pos] = FIND(par[pos]); return par[pos]; } void UNION(int pos1, int pos2) { par[FIND(pos1)] = FIND(pos2); } void dfs(int pos) { if (vis[pos]) return; vis[pos] = true; for (int i = 0; i < g[pos].size(); i++) dfs(g[pos][i]); topo.push_back(pos); } int dfs2(int pos) { if (ans[pos] != 0) return ans[pos]; int ret = 1; for (int i = 0; i < g[pos].size(); i++) ret = max(ret, dfs2(g[pos][i]) + 1); return ans[pos] = ret; } int main() { memset(gx, -1, sizeof(gx)); for (int i = 0; i < 2005; i++) par[i] = i; cin >> n >> m; for (int i = 0; i < n; i++) { cin >> s[i]; for (int j = 0; j < m; j++) if (s[i][j] == '=') UNION(i, j + n); } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int pos1 = FIND(i), pos2 = FIND(j + n); if (s[i][j] == '=') { if ((gx[pos1][pos2] != -1 && gx[pos1][pos2] != 2) || (gx[pos2][pos1] != -1 && gx[pos2][pos1] != 2)) { puts("No"); return 0; } gx[pos1][pos2] = gx[pos2][pos1] = 2; continue; } if (s[i][j] == '>') { if ((gx[pos1][pos2] != -1 && gx[pos1][pos2] != 0) || (gx[pos2][pos1] != -1 && gx[pos2][pos1] != 1)) { puts("No"); return 0; } if (gx[pos1][pos2] == -1 && pos1 != pos2) g[pos1].push_back(pos2), dg[pos2]++; gx[pos1][pos2] = 0; gx[pos2][pos1] = 1; } else { if ((gx[pos1][pos2] != -1 && gx[pos1][pos2] != 1) || (gx[pos2][pos1] != -1 && gx[pos2][pos1] != 0)) { puts("No"); return 0; } if (gx[pos2][pos1] == -1 && pos1 != pos2) g[pos2].push_back(pos1), dg[pos1]++; gx[pos1][pos2] = 1; gx[pos2][pos1] = 0; } } } int all = 0; for (int i = 0; i < m + n; i++) if (FIND(i) == i) all++; for (int i = 0; i < m + n; i++) { if (vis[FIND(i)] || dg[FIND(i)] > 0) continue; dfs(FIND(i)); } if (topo.size() != all) { puts("No"); return 0; } reverse(topo.begin(), topo.end()); for (int i = 0; i < topo.size(); i++) num[topo[i]] = i; for (int i = 0; i < topo.size(); i++) { for (int j = 0; j < g[topo[i]].size(); j++) { if (num[g[topo[i]][j]] < num[topo[i]]) { puts("No"); return 0; } } } for (int i = 0; i < m + n; i++) { if (ans[FIND(i)] != 0) continue; dfs2(FIND(i)); } for (int i = 0; i < m + n; i++) if (ans[i] == 0) ans[i] = ans[FIND(i)]; puts("Yes"); for (int i = 0; i < n; i++) printf("%d ", ans[i]); cout << endl; for (int i = n; i < m + n; i++) printf("%d ", ans[i]); cout << endl; return 0; }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> using namespace std; set<int> polaczenia[5005]; int lider[5005]; int war[5005]; int wch[5005]; int f(int a) { if (lider[a] != a) lider[a] = f(lider[a]); return lider[a]; } void u(int a, int b) { lider[f(a)] = f(b); } void pre(int a) { for (int x = 1; x <= a; x++) lider[x] = x; } bool czy = false; bool odw[5005]; bool tmp[5005]; void dfs(int a) { odw[a] = true; tmp[a] = true; for (auto x : polaczenia[a]) { if (tmp[lider[x]] == true) czy = true; if (odw[lider[x]] == false) dfs(lider[x]); } tmp[a] = false; } queue<int> q; int main() { ios_base::sync_with_stdio(0); cin.tie(0); int a, b; cin >> a >> b; char znak; pre(a + b + 5); for (int x = 1; x <= a; x++) for (int y = a + 1; y <= a + b; y++) { cin >> znak; if (znak == '=') u(x, y); else if (znak == '>') polaczenia[y].insert(x); else polaczenia[x].insert(y); } for (int x = 1; x <= a + b; x++) f(x); for (int x = 1; x <= a + b; x++) if (lider[x] != x) for (auto y : polaczenia[x]) polaczenia[lider[x]].insert(y); for (int x = 1; x <= a + b; x++) if (odw[x] == false && lider[x] == x) dfs(x); for (int x = 1; x <= a + b; x++) if (lider[x] == x) for (auto y : polaczenia[x]) wch[lider[y]]++; if (czy == true) { cout << "No"; return 0; } for (int x = 1; x <= a + b; x++) if (lider[x] == x && wch[x] == 0) q.push(x); int pom; while (q.empty() == false) { pom = q.front(); q.pop(); for (auto y : polaczenia[pom]) { wch[lider[y]]--; if (wch[lider[y]] == 0) q.push(lider[y]); war[lider[y]] = max(war[lider[y]], war[pom] + 1); } } cout << "Yes" << '\n'; for (int x = 1; x <= a; x++) cout << war[lider[x]] + 1 << " "; cout << '\n'; for (int x = a + 1; x <= a + b; x++) cout << war[lider[x]] + 1 << " "; return 0; }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> using namespace std; char mm[10005][10005]; vector<int> vc[10005]; int in[10005]; int vis[10005]; int reword[10005 << 2]; int n, m; int f[10005]; void init() { for (int i = 0; i < 10005; i++) f[i] = i, vc[i].clear(), in[i] = reword[i] = 0; } int get(int x) { return x == f[x] ? x : f[x] = get(f[x]); } void unite(int u, int v) { f[get(u)] = get(v); } void topo() { queue<int> que; for (int i = 1; i <= n + m; i++) if (in[i] == 0) que.push(i), vis[i] = 1, reword[i] = 1; int num = 0; while (que.size()) { num++; int u = que.front(); in[u]--; que.pop(); for (int i = 0; i < vc[u].size(); i++) { int v = vc[u][i]; in[v]--; if (in[v] == 0) que.push(v), vis[v] = 1, reword[v] = reword[u] + 1; } } if (num != n + m) printf("No\n"); else { printf("Yes\n"); for (int i = 1; i <= n; i++) printf("%d ", reword[get(i)]); printf("\n"); for (int i = n + 1; i <= n + m; i++) printf("%d ", reword[get(i)]); printf("\n"); } } int main() { init(); scanf("%d%d", &n, &m); for (int i = 1; i <= n; i++) scanf("%s", mm[i] + 1); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) if (mm[i][j] == '=') { unite(i, j + n); } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (mm[i][j] == '<') vc[get(i)].push_back(get(j + n)), in[get(j + n)]++; else if (mm[i][j] == '>') vc[get(j + n)].push_back(get(i)), in[get(i)]++; } } topo(); return 0; }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> using namespace std; void execution(); int main() { ios_base::sync_with_stdio(0); execution(); return 0; } char in[1001][1001]; long long komp[2002], us[2002], ans[2002], raz[2002]; vector<long long> g[2002]; void konec() { cout << "No"; exit(0); } long long pol(long long v) { if (komp[v] == v) return v; komp[v] = pol(komp[v]); return komp[v]; } void obhod1(long long v) { us[v] = 1; for (long long& i : g[v]) { if (us[i] == 1) konec(); if (!us[i]) obhod1(i); } us[v] = 2; } long long obhod2(long long v) { if (us[v]) return ans[v]; us[v] = 1; long long k = 0; for (long long& i : g[v]) { k = max(k, obhod2(i)); } ans[v] = k + 1; return ans[v]; } void execution() { long long n, m; cin >> n >> m; for (long long i = 1; i <= n; i++) for (long long j = 1; j <= m; j++) cin >> in[i][j]; for (long long i = 1; i <= n + m; i++) komp[i] = i, raz[i] = 1; for (long long i = 1; i <= n; i++) for (long long j = 1; j <= m; j++) { if (in[i][j] == '=') { long long pri = pol(i), prj = pol(j + n); if (raz[pri] > raz[prj]) { komp[prj] = pri; } else if (raz[prj] < raz[pri]) { komp[pri] = prj; } else { komp[prj] = pri; raz[pri]++; } } } for (long long i = 1; i <= n + m; i++) komp[i] = pol(i); for (long long i = 1; i <= n; i++) for (long long j = 1; j <= m; j++) { if (in[i][j] == '=') continue; long long pri = komp[i], prj = komp[j + n]; if (in[i][j] == '<') g[prj].push_back(pri); else g[pri].push_back(prj); } vector<long long> ver; for (long long i = 1; i <= n + m; i++) if (komp[i] == i) ver.push_back(i); for (long long& i : ver) { if (!us[i]) obhod1(i); } memset(us, 0, sizeof us); for (long long& i : ver) { if (!us[i]) obhod2(i); } cout << "Yes\n"; for (long long i = 1; i <= n + m; i++) { ans[i] = ans[pol(i)]; cout << ans[i] << ' '; if (i == n) cout << '\n'; } }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
import java.io.*; import java.text.*; import java.util.*; import java.math.*; public class template { public static void main(String[] args) throws Exception { new template().run(); } int[] par, sz; public void run() throws Exception { FastScanner f = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int r = f.nextInt(), c = f.nextInt(); par = new int[r+c]; sz = new int[r+c]; for(int i = 0; i < r+c; i++) { par[i] = i; sz[i] = 1; } char[][] input = new char[r][c]; for(int i = 0; i < r; i++) { input[i] = f.next().toCharArray(); for(int j = 0; j < c; j++) if(input[i][j] == '=') merge(i, r+j); } LinkedList<Integer>[] adj = new LinkedList[r+c]; for(int i = 0; i < r+c; i++) adj[i] = new LinkedList<>(); int[] cnts = new int[r+c]; for(int i = 0; i < r; i++) for(int j = 0; j < c; j++) { int a = find(i), b = find(r+j); if(input[i][j] == '>') { adj[a].add(b); cnts[b]++; } else if(input[i][j] == '<') { adj[b].add(a); cnts[a]++; } } int[] vals = new int[r+c]; for(int i = 0; i < r+c; i++) vals[i] = 1000000; LinkedList<Integer> ll = new LinkedList<Integer>(); for(int i = 0; i < r+c; i++) if(cnts[i] == 0) ll.add(i); while(!ll.isEmpty()) { int i = ll.poll(); for(int j : adj[i]) { vals[j] = vals[i]-1; if(--cnts[j] == 0) ll.add(j); } } int min = 1000000; for(int i = 0; i < r+c; i++) min = Math.min(min, vals[i] = vals[find(i)]); boolean works = true; for(int i = 0; i < r; i++) for(int j = 0; j < c; j++) if(input[i][j] == '>') works &= works && vals[find(i)] > vals[find(r+j)]; else if(input[i][j] == '<') works &= works && vals[find(i)] < vals[find(r+j)]; if(works) { out.println("Yes"); for(int i = 0; i < r; i++) out.print(vals[i] - min + 1 + " "); out.println(); for(int i = 0; i < c; i++) out.print(vals[r+i] - min + 1 + " "); out.println(); } else out.println("No"); out.flush(); } public void merge(int x, int y) { x = find(x); y = find(y); if(sz[x] < sz[y]) par[x] = y; else par[y] = x; } public int find(int x) { if(par[x] == x) return x; return par[x] = find(par[x]); } static class FastScanner { public BufferedReader reader; public StringTokenizer tokenizer; public FastScanner() { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { try { return reader.readLine(); } catch(IOException e) { throw new RuntimeException(e); } } } }
JAVA
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
import java.lang.*; import java.math.*; import java.util.*; import java.io.*; public class Main { void solve() { n=ni(); m=ni(); s=new char[n][m]; for(int i=0;i<n;i++)s[i]=ns().toCharArray(); g=new ArrayList[n+m+1]; g2=new ArrayList[n+m+1]; for(int i=1;i<=n+m;i++) g[i]=new ArrayList<>(); for(int i=1;i<=n+m;i++) g2[i]=new ArrayList<>(); for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ int u=i+1,v=n+j+1; if(s[i][j]=='='){ g2[u].add(v) ; g2[v].add(u); } } } int N=n+m; vis=new int[N+1]; C=new int[N+1]; for(int i=1;i<=N;i++){ if(vis[i]==0){ ++cc; dfs(i); } } for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ if(s[i][j]=='=') continue; int u=i+1,v=n+j+1; int c1=C[u],c2=C[v]; if(c1==c2){ pw.println("No"); return; } if(s[i][j]=='>') g[c1].add(c2); else g[c2].add(c1); } } Arrays.fill(vis,0); int ans[]=new int[cc+1]; for(int i=1;i<=cc;i++){ if(vis[i]!=0) continue; if(!dfs2(i,-1)){ pw.println("No"); return; } } cc=0; for(int v : stk){ int mx=0; for(int u : g[v]) mx=Math.max(mx,ans[u]); ans[v]=Math.max(mx+1,cc); cc=Math.max(mx+1,cc); } pw.println("Yes"); for(int i=1;i<=n;i++){ pw.print(ans[C[i]]+" "); } pw.println(""); for(int j=n+1;j<=n+m;j++){ pw.print(ans[C[j]]+" "); } pw.println(""); } char s[][]; int n,m; ArrayList<Integer> g[]; ArrayList<Integer> g2[]; int vis[]; Stack<Integer> stk=new Stack<>(); int cc=0; int C[]; void dfs(int v){ vis[v]=1; C[v]=cc; for(int u : g2[v]){ if(vis[u]==0) dfs(u); } } boolean dfs2(int v,int pr){ vis[v]=1; // pw.println(v); for(int u: g[v]){ if(u==pr) continue; if(vis[u]==0){ if(!dfs2(u,v)) return false; }else if(vis[u]==1)return false; } stk.push(v); vis[v]=2; return true; } long M = (long)1e9+7; InputStream is; PrintWriter pw; String INPUT = ""; void run() throws Exception { is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); pw = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); pw.flush(); if (!INPUT.isEmpty()) tr(System.currentTimeMillis() - s + "ms"); } public static void main(String[] args) throws Exception { new Main().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char) skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n && !(isSpaceChar(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if (INPUT.length() > 0) System.out.println(Arrays.deepToString(o)); } }
JAVA
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> using namespace std; const int MAXN = 2222; int size[MAXN], link[MAXN]; int numbers[MAXN], inDegree[MAXN]; vector<int> conn[MAXN]; char c[1005][1005]; int find(int a) { return a == link[a] ? a : link[a] = find(link[a]); } void unite(int a, int b) { a = find(a); b = find(b); if (a == b) return; if (size[a] < size[b]) swap(a, b); size[a] += size[b]; link[b] = a; } int main() { int n, m; scanf("%d %d", &n, &m); int N = n + m; for (int i = 0; i < N; ++i) size[i] = 1, link[i] = i; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { cin >> c[i][j]; if (c[i][j] == '=') unite(i, n + j); } } for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (c[i][j] == '>') conn[find(n + j)].emplace_back(find(i)); else if (c[i][j] == '<') conn[find(i)].emplace_back(find(n + j)); } } for (int i = 0; i < N; ++i) numbers[i] = -1; for (int i = 0; i < N; ++i) { for (int& x : conn[i]) { inDegree[x]++; } } set<int> zeros, nextZeros; for (int i = 0; i < N; ++i) if (link[i] == i and inDegree[i] == 0) zeros.emplace(i); int ans = 0; while (!zeros.empty()) { ans++; for (const int& a : zeros) { numbers[a] = ans; for (const int& b : conn[a]) { inDegree[b]--; if (inDegree[b] == 0) nextZeros.emplace(b); } } zeros = nextZeros; nextZeros = set<int>(); } for (int i = 0; i < N; i++) if (link[i] == i and numbers[i] == -1) return !printf("No"); puts("Yes"); for (int i = 0; i < N; ++i) { if (i == n) puts(""); printf("%d ", numbers[find(i)]); } }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> using namespace std; class dsu { vector<long long int> parent, rank; long long int totalComponents; public: dsu(long long int n) { parent.resize(n); rank.resize(n); for (long long int i = 0; i < n; i++) parent[i] = i, rank[i] = 0; totalComponents = n; } long long int get(long long int a) { if (a == parent[a]) return a; return parent[a] = get(parent[a]); } void union_set(long long int a, long long int b) { a = get(a); b = get(b); if (a != b) { if (rank[a] < rank[b]) swap(a, b); parent[b] = a; if (rank[a] == rank[b]) rank[a]++; totalComponents--; } } }; vector<pair<long long int, long long int> > edges; vector<long long int> adjList[3004]; long long int depth[3004] = {0}; bool KyaNodeAlreadyVisitedHai[3004] = {0}; bool visited[3004] = {0}; bool KyaCycleHai = false; void FindDepth(long long int node) { if (visited[node]) return; if (KyaCycleHai) return; if (KyaNodeAlreadyVisitedHai[node]) { KyaCycleHai = true; return; } KyaNodeAlreadyVisitedHai[node] = true; long long int d = 0; for (auto children : adjList[node]) { FindDepth(children); d = max(d, depth[children]); } depth[node] = d + 1; KyaNodeAlreadyVisitedHai[node] = false; visited[node] = true; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); long long int n, m; cin >> n >> m; dsu g(n + m); for (long long int i = 0; i < n; i++) { for (long long int j = 0; j < m; j++) { char ch; cin >> ch; if (ch == '=') g.union_set(i, n + j); else if (ch == '>') edges.push_back({i, n + j}); else edges.push_back({n + j, i}); } } for (auto e : edges) adjList[g.get(e.first)].push_back(g.get(e.second)); for (long long int i = 0; i < n + m; i++) { if (!visited[g.get(i)]) { FindDepth(g.get(i)); } } if (KyaCycleHai) { cout << "No"; } else { cout << "Yes" << endl; for (long long int i = 0; i < n; i++) cout << depth[g.get(i)] << ' '; cout << endl; for (long long int j = 0; j < m; j++) cout << depth[g.get(n + j)] << ' '; cout << endl; } return 0; }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
import java.util.*; import java.io.*; public class D541 { static Map<Integer, ArrayList<Integer>> adj = new HashMap<>(); static int [] rank; static int [] vis; static boolean ok; static ArrayList<Integer> top; public static void main(String[] args) { MyScanner sc = new MyScanner(); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); int n = sc.nextInt(); int m = sc.nextInt(); int [][] a = new int[n][m]; UF dsu = new UF(n + m); int z = 0; for (int i = 0; i < n; i++) { String s = sc.next(); for (int j = 0; j < m; j++) { if (s.charAt(j) == '>') a[i][j] = 1; else if (s.charAt(j) == '<') a[i][j] = -1; else { dsu.union(i, j + n); ++z; } } } if (z == n * m) { out.println("Yes"); for (int i = 0; i < n; i++) out.print(1 + " "); out.println(); for (int i = 0; i < m; i++) out.print(1 + " "); out.close(); return; } adj = new HashMap<>(); ok = true; int [] in = new int[n + m + 1]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (a[i][j] == -1) { int par = dsu.find(j + n); if (!adj.containsKey(par)) adj.put(par, new ArrayList<>()); int next = dsu.find(i); adj.get(par).add(next); in[next]++; if (!adj.containsKey(next)) adj.put(next, new ArrayList<>()); } else if (a[i][j] == 1) { int par = dsu.find(i); if (!adj.containsKey(par)) adj.put(par, new ArrayList<>()); int next = dsu.find(j + n); adj.get(par).add(next); in[next]++; if (!adj.containsKey(next)) adj.put(next, new ArrayList<>()); } } } rank = new int[n + m]; top = new ArrayList<>(); Arrays.fill(rank, 1); vis = new int[n + m]; if (adj.size() == 1) { out.println("No"); out.close(); return; } for (int i = 0; i < n + m; i++) { if (!adj.containsKey(i)) continue; if (vis[i] == 0) dfs(i); } if (!ok) { out.println("No"); out.close(); return; } for (Integer node: top) { int r = 1; for (Integer next: adj.getOrDefault(node, new ArrayList<>())) { r = Math.max(rank[next] + 1, r); } rank[node] = r; } out.println("Yes"); for (int i = 0; i < n; i++) { out.print(rank[dsu.find(i)] + " "); } out.println(); for (int j = 0; j < m; j++) { out.print(rank[dsu.find(j + n)] + " "); } out.close(); } static void dfs(int cur) { vis[cur] = 1; for (Integer next: adj.getOrDefault(cur, new ArrayList<>())) { if (vis[next] == 0) { dfs(next); } else if (vis[next] == 1) { ok = false; return; } } top.add(cur); vis[cur] = 2; } static class UF { private int[] parent; // parent[i] = parent of i private byte[] rank; // rank[i] = rank of subtree rooted at i (never more than 31) private int count; // number of components private int[] size; public UF(int n) { if (n < 0) throw new IllegalArgumentException(); count = n; parent = new int[n]; rank = new byte[n]; size = new int[n]; for (int i = 0; i < n; i++) { parent[i] = i; rank[i] = 0; size[i] = 1; } } public int find(int p) { while (p != parent[p]) { parent[p] = parent[parent[p]]; // path compression by halving p = parent[p]; } return p; } public int count() { return count; } public boolean connected(int p, int q) { return find(p) == find(q); } public void union(int p, int q) { int rootP = find(p); int rootQ = find(q); if (rootP == rootQ) return; // make root of smaller rank point to root of larger rank if (rank[rootP] < rank[rootQ]) { parent[rootP] = rootQ; size[rootQ] = size[rootQ] + size[rootP]; } else if (rank[rootP] > rank[rootQ]) { parent[rootQ] = rootP; size[rootP] = size[rootP] + size[rootQ]; } else { parent[rootQ] = rootP; size[rootP] = size[rootP] + size[rootQ]; rank[rootP]++; } count--; } } //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
JAVA
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> using namespace std; const int maxn = 2e3 + 50; int fa[maxn]; string s[maxn]; vector<int> v[maxn]; int ans[maxn]; int in[maxn]; int vis[maxn]; int fin(int f) { return f == fa[f] ? f : fa[f] = fin(fa[f]); } int main() { int n, m; cin >> n >> m; for (int i = 0; i < n + m; ++i) fa[i] = i; for (int i = 0; i < n; ++i) { cin >> s[i]; for (int j = 0; j < m; ++j) { if (s[i][j] == '=') { int fi = fin(i), fj = fin(j + n); if (fi != fj) { fa[fj] = fi; } } } } for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (s[i][j] == '>') { v[fin(n + j)].push_back(fin(i)); ++in[fin(i)]; } else if (s[i][j] == '<') { v[fin(i)].push_back(fin(n + j)); ++in[fin(n + j)]; } } } queue<int> q; for (int i = 0; i < n + m; ++i) { if (!in[fin(i)]) { ans[fin(i)] = 1; q.push(fin(i)); } } while (!q.empty()) { int tmp = q.front(); q.pop(); if (vis[tmp]) { continue; } vis[tmp] = 1; for (auto i : v[tmp]) { ans[fin(i)] = max(ans[(fin(i))], ans[fin(tmp)] + 1); --in[fin(i)]; if (!in[fin(i)]) q.push(fin(i)); } } for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (s[i][j] == '=') { if (ans[fin(i)] != ans[fin(n + j)]) { cout << "No" << endl; return 0; } } if (s[i][j] == '<') { if (ans[fin(i)] >= ans[fin(j + n)]) { cout << "No" << endl; return 0; } } if (s[i][j] == '>') { if (ans[fin(i)] <= ans[fin(j + n)]) { cout << "No" << endl; return 0; } } } } cout << "Yes" << endl; for (int i = 0; i < n; ++i) { cout << ans[fin(i)] << " "; } cout << endl; for (int i = 0; i < m; ++i) { cout << ans[fin(i + n)] << " "; } cout << endl; return 0; }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
import java.io.*; import java.util.*; public class D { public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); Solver solver = new Solver(); solver.solve(in, out); out.close(); } private static class Solver { // DSU private int[] parent; private int[] rank; private void make(int n) { parent = new int[n]; rank = new int[n]; for (int v = 0; v < n; v++) { parent[v] = v; rank[v] = 0; } } private int find(int v) { if (parent[v] == v) return v; return parent[v] = find(parent[v]); } private void unite(int v, int u) { v = find(v); u = find(u); if (v != u) { if (rank[v] < rank[u]) { v ^= u; u ^= v; v ^= u; // swap } parent[u] = v; if (rank[v] == rank[u]) rank[v]++; } } // private List<Set<Integer>> g; private int[] vis; private int[] ans; private int max(int a, int b) { return a < b ? b : a; } private void dfs(int v) { vis[v] = ans[v] = 1; for (int u : g.get(v)) { if (vis[u] == 1) { System.out.println("NO"); System.exit(0); } if (vis[u] == 0) dfs(u); ans[v] = max(ans[v], ans[u] + 1); } vis[v] = 2; } private void solve(InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); make(n + m); char[][] a = new char[n][m]; for (int i = 0; i < n; i++) { a[i] = in.next().toCharArray(); for (int j = 0; j < m; j++) { if (a[i][j] == '=') unite(i, n + j); } } g = new ArrayList<>(n + m); for (int i = 0; i < n + m; i++) g.add(new HashSet<>()); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (a[i][j] == '>') g.get(find(i)).add(find(n + j)); else if (a[i][j] == '<') g.get(find(n + j)).add(find(i)); } } vis = new int[n + m]; ans = new int[n + m]; for (int i = 0; i < n + m; i++) { if (vis[find(i)] == 0) dfs(find(i)); } out.println("YES"); for (int i = 0; i < n; i++) out.print(ans[find(i)] + " "); out.println(); for (int i = n; i < n + m; i++) out.print(ans[find(i)] + " "); out.println(); } } private static class InputReader { private BufferedReader br; private StringTokenizer st; public InputReader(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); } private int nextInt() { return Integer.parseInt(next()); } private long nextLong() { return Long.parseLong(next()); } private double nextDouble() { return Double.parseDouble(next()); } private String nextLine() { String s = ""; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return s; } private String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } } }
JAVA
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> using namespace std; const int N = 2000 + 5; int p[N], indeg[N], ans[N]; char c[N][N]; vector<int> edge[N]; int findx(int x) { return x == p[x] ? x : findx(p[x]); } void unite(int x, int y) { x = findx(x); y = findx(y); p[x] = y; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); int n, m; cin >> n >> m; int total = n + m; for (int i = 0; i < total; i++) p[i] = i; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> c[i][j]; if (c[i][j] == '=') unite(i, n + j); } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (c[i][j] == '>') { edge[findx(n + j)].push_back(findx(i)); indeg[findx(i)]++; } else if (c[i][j] == '<') { edge[findx(i)].push_back(findx(n + j)); indeg[findx(n + j)]++; } } } queue<int> q; for (int i = 0; i < total; i++) if (!indeg[i]) { q.push(i); ans[i] = 1; } while (!q.empty()) { int u = q.front(); q.pop(); for (auto v : edge[u]) { --indeg[v]; if (indeg[v] == 0) { q.push(v); ans[v] = ans[u] + 1; } } } bool have_circle = false; for (int i = 0; i < total; i++) { if (indeg[i]) have_circle = true; } if (have_circle) cout << "No" << endl; else { cout << "Yes" << endl; for (int i = 0; i < n; i++) { cout << ans[findx(i)] << " \n"[i == n - 1]; } for (int i = 0; i < m; i++) { cout << ans[findx(n + i)] << " \n"[i == m - 1]; } } return 0; }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> using namespace std; int n, m; char x[1011][1022]; int biga[1001], smla[1001], bigb[1001], smlb[1001]; bool cmpa(int i, int j) { if (biga[i] != biga[j]) return biga[i] > biga[j]; return smla[i] < smla[j]; } bool cmpb(int i, int j) { if (bigb[i] != bigb[j]) return bigb[i] > bigb[j]; return smlb[i] < smlb[j]; } bool check(int *a, int *b) { for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (x[i][j] == '<' && !(a[i] < b[j])) return 1; if (x[i][j] == '=' && !(a[i] == b[j])) return 1; if (x[i][j] == '>' && !(a[i] > b[j])) return 1; } } return 0; } int main() { cin >> n >> m; for (int i = 1; i <= n; i++) { scanf("%s", x[i] + 1); } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (x[i][j] == '<') { biga[i]++; smlb[j]++; } else if (x[i][j] == '>') { bigb[j]++; smla[i]++; } } } int a[1001], b[1001]; for (int i = 1; i <= n; i++) a[i] = i; sort(a + 1, a + 1 + n, cmpa); for (int j = 1; j <= m; j++) b[j] = j; sort(b + 1, b + 1 + m, cmpb); int ara = 1, arb = 1; int now = 0; int ansa[1001], ansb[1001]; while (ara <= n && arb <= m) { int A = a[ara], B = b[arb]; if (x[A][B] != '<') { ansb[B] = now + 1; arb++; while (arb <= m) { if (bigb[b[arb]] == bigb[b[arb - 1]] && smlb[b[arb]] == smlb[b[arb - 1]]) { ansb[b[arb]] = now + 1; arb++; continue; } break; } } if (x[A][B] != '>') { ansa[A] = now + 1; ara++; while (ara <= n) { if (biga[a[ara]] == biga[a[ara - 1]] && smla[a[ara]] == smla[a[ara - 1]]) { ansa[a[ara]] = now + 1; ara++; continue; } break; } } now++; } while (ara <= n) { ansa[a[ara]] = now + 1; ara++; while (ara <= n) { if (biga[a[ara]] == biga[a[ara - 1]] && smla[a[ara]] == smla[a[ara - 1]]) { ansa[a[ara]] = now + 1; ara++; continue; } break; } now++; } while (arb <= m) { ansb[b[arb]] = now + 1; arb++; while (arb <= m) { if (bigb[b[arb]] == bigb[b[arb - 1]] && smlb[b[arb]] == smlb[b[arb - 1]]) { ansb[b[arb]] = now + 1; arb++; continue; } break; } now++; } if (!check(ansa, ansb)) { printf("Yes\n"); for (int i = 1; i <= n; i++) printf("%d%c", ansa[i], (i == n ? '\n' : ' ')); for (int i = 1; i <= m; i++) printf("%d%c", ansb[i], (i == m ? '\n' : ' ')); } else { printf("No\n"); } }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> using namespace std; template <class T> inline void amin(T &x, const T &y) { if (y < x) x = y; } template <class T> inline void amax(T &x, const T &y) { if (x < y) x = y; } using LL = long long; using PII = pair<int, int>; using VI = vector<int>; const int INF = 0x3f3f3f3f; const int MOD = 1e9 + 7; const int MAXN = 1005; int n, m; string g[MAXN]; int find(VI &f, int x) { return x == f[x] ? x : f[x] = find(f, f[x]); } void uni(VI &f, int x, int y) { f[find(f, x)] = find(f, y); } void MAIN() { cin >> n >> m; string s[n]; VI f(n + m); for (int i = (0); i < (n + m); i++) f[i] = i; for (int i = (0); i < (n); i++) { cin >> s[i]; for (int j = (0); j < (m); j++) { if (s[i][j] == '=') { uni(f, i, n + j); } } } VI group(n + m, -1); int len = 0; for (int i = (0); i < (n + m); i++) { int fa = find(f, i); if (group[fa] == -1) group[fa] = len++; } { ((void)0); }; VI g[len]; VI deg(len); for (int i = (0); i < (n); i++) { for (int j = (0); j < (m); j++) { int gi = group[find(f, i)], gj = group[find(f, n + j)]; { ((void)0); } { ((void)0); } if (s[i][j] == '>') { g[gj].push_back(gi); deg[gi]++; } else if (s[i][j] == '<') { g[gi].push_back(gj); deg[gj]++; } } } VI col(len, 1); queue<int> que; int vis = 0; for (int i = (0); i < (len); i++) if (!deg[i]) que.push(i), vis++; while ((int)que.size()) { int cur = que.front(); que.pop(); for (auto &v : g[cur]) { amax(col[v], col[cur] + 1); if (--deg[v] == 0) que.push(v), vis++; } } assert(vis <= len); if (vis < len) { cout << "No" << endl; } else { cout << "Yes" << endl; for (int i = (0); i < (n); i++) cout << col[group[find(f, i)]] << " "; cout << endl; for (int j = (0); j < (m); j++) cout << col[group[find(f, n + j)]] << " "; cout << endl; } } int main() { ios::sync_with_stdio(false); cin.tie(0); int TC = 1; for (int tc = (0); tc < (TC); tc++) { MAIN(); } return 0; }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> const int N = 1005, M = N * 2, L = 1e6 + 5; int n, m, fa[M], ecnt, nxt[L], adj[M], go[L], d[M], H, T, Q[M], f[M]; char s[N][N]; void add_edge(int u, int v) { nxt[++ecnt] = adj[u]; adj[u] = ecnt; go[ecnt] = v; d[v]++; } int cx(int x) { if (fa[x] != x) fa[x] = cx(fa[x]); return fa[x]; } void zm(int x, int y) { int ix = cx(x), iy = cx(y); if (ix != iy) fa[iy] = ix; } int main() { std::cin >> n >> m; for (int i = 1; i <= n; i++) scanf("%s", s[i] + 1); for (int i = 1; i <= n + m; i++) fa[i] = i; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) if (s[i][j] == '=') zm(i, j + n); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) if (s[i][j] == '<') add_edge(cx(i), cx(j + n)); else if (s[i][j] == '>') add_edge(cx(j + n), cx(i)); int cnt = 0; for (int i = 1; i <= n + m; i++) { if (fa[i] == i && !d[i]) Q[++T] = i, f[i] = 1; if (fa[i] == i) cnt++; } while (H < T) { int u = Q[++H]; for (int e = adj[u], v = go[e]; e; e = nxt[e], v = go[e]) { if (!(--d[v])) Q[++T] = v; f[v] = std::max(f[v], f[u] + 1); } } if (T < cnt) return puts("No"), 0; puts("Yes"); for (int i = 1; i <= n; i++) printf("%d ", f[cx(i)]); std::cout << std::endl; for (int i = 1; i <= m; i++) printf("%d ", f[cx(i + n)]); std::cout << std::endl; return 0; }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> using namespace std; template <class T> inline T gcd(T a, T b) { return (b) == 0 ? (a) : gcd((b), ((a) % (b))); } template <class T> inline T lcm(T a, T b) { return ((a) / gcd((a), (b)) * (b)); } template <class T> inline T BigMod(T Base, T power, T M = 1000000007) { if (power == 0) return 1; if (power & 1) return ((Base % M) * (BigMod(Base, power - 1, M) % M)) % M; else { T y = BigMod(Base, power / 2, M) % M; return (y * y) % M; } } template <class T> inline T ModInv(T A, T M = 1000000007) { return BigMod(A, M - 2, M); } int fx[] = {-1, +0, +1, +0, +1, +1, -1, -1, +0}; int fy[] = {+0, -1, +0, +1, +1, -1, +1, -1, +0}; int day[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int n, m; string s[2000]; vector<int> v[200005]; int vis[200005]; int black[200005], mata[200005], grey[200005], visited[200005]; stack<int> st; int val[200005], ck[200005], visit[200005]; vector<int> par[200005]; bool dfs(int s) { bool x = false; if (grey[s]) return true; if (black[s]) return false; grey[s] = 1; vis[s] = 1; for (auto it : v[s]) { x = x | dfs(it); } grey[s] = 0; black[s] = 1; return x; } void dfs2(int s) { if (visited[s]) return; visited[s] = 1; for (auto it : v[s]) { dfs2(it); } st.push(s); } int findMata(int s) { if (mata[s] == s) return s; else return mata[s] = findMata(mata[s]); } bool cycle() { bool x; for (int i = 0; i < n + m; i++) { if (vis[findMata(i)] == 0) { x = dfs(findMata(i)); if (x) return true; } } return false; } void dfs3(int s, int value) { if (visit[s]) return; visit[s] = 1; val[s] = value; for (auto it : v[s]) dfs3(it, value + 1); } bool WA() { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (s[i][j] == '=' && val[i] != val[n + j] || s[i][j] == '<' && val[i] >= val[n + j] || s[i][j] == '>' && val[n + j] >= val[i]) { return true; } } } return false; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin >> n >> m; for (int i = 0; i < n; i++) cin >> s[i]; for (int i = 0; i < n + m; i++) mata[i] = i; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (s[i][j] == '=') { int x = findMata(i); int y = findMata(n + j); mata[x] = mata[y]; } } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int x = findMata(i); int y = findMata(n + j); if (s[i][j] == '<') v[x].push_back(y), par[y].push_back(x); else if (s[i][j] == '>') v[y].push_back(x), par[x].push_back(y); } } bool x = cycle(); if (x) cout << "No"; else { int cnt = 1; memset(ck, -1, sizeof(ck)); for (int i = 0; i < n + m; i++) if (visited[findMata(i)] == 0) dfs2(findMata(i)); while (!st.empty()) { int x = st.top(); st.pop(); val[x] = 1; for (auto it : par[x]) val[x] = max(val[x], val[it] + 1); } for (int i = 0; i < n + m; i++) val[i] = val[findMata(i)]; if (WA()) { cout << "No" << endl; } else { cout << "Yes" << endl; for (int i = 0; i < n; i++) cout << val[findMata(i)] << " "; cout << endl; for (int i = n; i < n + m; i++) cout << val[findMata(i)] << " "; } } return 0; }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> using namespace std; vector<int> e[2010]; int v[2010], in[2010], d[2020], n, m, i, j, k; char s[2010][2010]; int f(int x) { return x == v[x] ? x : (v[x] = f(v[x])); } bool ch() { for (int i = 1; i <= n + m; i++) { v[i] = i; } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (s[i][j] == '=') { v[f(i)] = f(j + n); } } } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (s[i][j] == '=') { continue; } if (f(i) == f(j + n)) { return 0; } if (s[i][j] == '<') { e[f(i)].push_back(f(j + n)); } else { e[f(j + n)].push_back(f(i)); } } } for (int i = 1; i <= n + m; i++) { sort(e[i].begin(), e[i].end()); } for (int i = 1; i <= n + m; i++) { e[i].erase(unique(e[i].begin(), e[i].end()), e[i].end()); } for (int i = 1; i <= n + m; i++) { for (int j = 0; j < e[i].size(); j++) { in[e[i][j]]++; } } queue<int> q; for (int i = 1; i <= n + m; i++) { d[i] = 1; if (in[i] == 0) { q.push(i); } } while (!q.empty()) { int u = q.front(); q.pop(); for (int i = 0; i < e[u].size(); i++) { in[e[u][i]]--; if (in[e[u][i]] == 0) { q.push(f(e[u][i])); } d[e[u][i]] = max(d[u] + 1, d[e[u][i]]); } } if (*max_element(in + 1, in + n + m + 1) > 0) { return 0; } } int main() { cin >> n >> m; for (i = 1; i <= n; i++) { for (j = 1; j <= m; j++) { cin >> s[i][j]; } } if (ch()) { cout << "Yes\n"; for (i = 1; i <= n; i++) { cout << d[f(i)] << " "; } cout << "\n"; for (j = 1; j <= m; j++) { cout << d[f(j + n)] << " "; } } else { cout << "No"; } }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
import java.io.*; import java.util.*; import java.util.stream.IntStream; public class Main { public static void main(String[] args) { try (PrintWriter out = new PrintWriter(System.out)) { Solution solution = new Solution(); solution.in = new InputReader(getInput()); solution.out = out; solution.solve(); } } static InputStream getInput() { String inputFile = getInputFileName(); if (inputFile == null) { return System.in; } try { return new FileInputStream(Main.class.getClassLoader().getResource(inputFile).getFile()); } catch (FileNotFoundException e) { throw new RuntimeException(e); } } static String getInputFileName() { try { return System.getProperty("compet.input"); } catch (Exception ex) { return null; } } } class Solution { InputReader in; PrintWriter out; int n; int m; class Node { List<Integer> ls = new ArrayList<>(); int gr = 0; List<Integer> eq = new ArrayList<>(); } void solve() { n = in.nextInt(); m = in.nextInt(); String[] a = new String[n]; for (int i = 0; i < n; i++) { a[i] = in.next(); } int sz = n+m; Node[] nodes = IntStream.range(0, sz).mapToObj(i -> new Node()).toArray(Node[]::new); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int v = i; int u = n + j; switch (a[i].charAt(j)) { case '>': nodes[v].gr++; nodes[u].ls.add(v); break; case '<': nodes[u].gr++; nodes[v].ls.add(u); break; case '=': nodes[u].eq.add(v); nodes[v].eq.add(u); break; } } } boolean[] was = new boolean[sz]; int wasCnt = 0; boolean bad = false; int num = 1; int[] ans = new int[sz]; while (wasCnt < sz && !bad) { boolean[] curMask = new boolean[sz]; for (int v = 0; v < sz; v++) { if (!was[v] && nodes[v].gr == 0) { curMask[v] = true; } } Queue<Integer> queue = new ArrayDeque<>(sz); boolean[] visited = new boolean[sz]; for (int v = 0; v < sz; v++) { if (!curMask[v]) { queue.add(v); visited[v] = true; } } while (!queue.isEmpty()) { int v = queue.poll(); curMask[v] = false; for (int u: nodes[v].eq) { if (!visited[u]) { visited[u] = true; queue.add(u); } } } List<Integer> cur = new ArrayList<>(sz); for (int v = 0; v < sz; v++) { if (curMask[v]) { cur.add(v); } } if (cur.size() == 0) { bad = true; break; } for (int v: cur) { wasCnt++; was[v] = true; ans[v] = num; for (int u: nodes[v].ls) { nodes[u].gr--; } } num++; } out.println(bad ? "No" : "Yes"); if (!bad) { for (int i = 0; i < sz; i++) { if (i == n) { out.println(); } out.print(ans[i] + " "); } } } } class InputReader { BufferedReader reader; StringTokenizer tokenizer; InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } }
JAVA
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> using namespace std; int power(int x, unsigned int y, int p) { int res = 1; x = x % p; while (y > 0) { if (y & 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } int mI(int a, int m) { return power(a, m - 2, m); } class ds { vector<int> v1; unordered_map<int, int> parent; unordered_map<int, int> rank1; public: ds(vector<int> v) { v1 = v; for (int t : v1) { parent[t] = t; rank1[t] = 0; } } void union1(int a, int b) { a = find(a); b = find(b); if (rank1[a] > rank1[b]) { parent[b] = a; } else if (rank1[b] > rank1[a]) { parent[a] = b; } else { parent[a] = b; rank1[b]++; } } int find(int x) { if (parent[x] == x) return x; else return find(parent[x]); } }; vector<int> par; vector<vector<int> > g; vector<int> vis; vector<int> viss; int dfs(int i) { if (vis[i] == 1) { return 1e9 - 1; } if (viss[i] != 0) return viss[i]; vis[i] = 1; int c = 1; for (auto it : g[i]) { c = max(c, 1 + dfs(it)); } vis[i] = 0; return viss[i] = c; } int32_t main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n, m; cin >> n >> m; vector<int> v1(n + m); for (int i = 0; i < n + m; i++) v1[i] = i; ds ans(v1); vector<string> v(n); for (int i = 0; i < n; i++) cin >> v[i]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (v[i][j] == '=') { ans.union1(i, n + j); } } } par.resize(n + m); for (int i = 0; i < n + m; i++) par[i] = ans.find(i); g.resize(n + m); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (v[i][j] == '>') g[par[i]].push_back(par[n + j]); else if (v[i][j] == '<') g[par[n + j]].push_back(par[i]); } } vector<int> anss(n + m, 0); vis.resize(n + m, 0); for (int i = 0; i < n + m; i++) { if (anss[par[i]] != 0) { anss[i] = anss[par[i]]; } else { vis.clear(); vis.resize(n + m, 0); viss.clear(); viss.resize(n + m, 0); int val = dfs(par[i]); if (val >= 1e9) { cout << "No"; return 0; } anss[i] = val; anss[par[i]] = val; } } cout << "Yes" << endl; for (int i = 0; i < n; i++) cout << anss[i] << " "; cout << endl; for (int i = n; i < n + m; i++) cout << anss[i] << " "; }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> using namespace std; int roots[2001]; int heights[2001]; bool in_stack[2001]; int nums[2001]; bool visited[2001]; vector<vector<int>> adj_list(2001); vector<pair<int, int>> lesser; int root(int a) { while (a != roots[a]) a = roots[a]; return a; } void join(int a, int b) { a = root(a); b = root(b); if (a != b) { if (heights[a] >= heights[b]) { roots[b] = a; if (heights[a] == heights[b]) heights[a]++; } else { roots[a] = b; } } } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int rows, cols; cin >> rows >> cols; for (int i = 0; i < rows + cols; i++) { roots[i] = i; heights[i] = 0; nums[i] = 0; in_stack[i] = false; visited[i] = false; } for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { char inp; cin >> inp; if (inp == '=') join(i, rows + j); else if (inp == '<') lesser.push_back(make_pair(i, rows + j)); else lesser.push_back(make_pair(rows + j, i)); } } for (int i = 0; i < lesser.size(); i++) { int a = lesser[i].first; int b = lesser[i].second; a = root(a); b = root(b); adj_list[a].push_back(b); } bool yes = true; stack<pair<int, int>> dfs; for (int i = 0; i < rows + cols && yes; i++) { int u = root(i); if (i <= u && !visited[u]) { i = u; dfs.push(make_pair(1, i)); nums[i] = 1; while (!dfs.empty() && yes) { int dist = dfs.top().first; int node = dfs.top().second; if (in_stack[node]) { dfs.pop(); visited[node] = true; in_stack[node] = !in_stack[node]; continue; } in_stack[node] = !in_stack[node]; for (int j = 0; j < adj_list[node].size(); j++) { int next = adj_list[node][j]; if (in_stack[next]) yes = false; else if (dist + 1 > nums[next]) { dfs.push(make_pair(dist + 1, next)); nums[next] = dist + 1; } } } } } if (!yes) { cout << "No" << "\n"; } else { cout << "Yes" << "\n"; for (int i = 0; i < rows; i++) { cout << nums[root(i)] << " "; } cout << "\n"; for (int i = rows; i < rows + cols; i++) { cout << nums[root(i)] << " "; } cout << "\n"; } }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> using namespace std; const long long int MAXN = 2e5 + 10; const long long int MINN = 1e5 + 10; const long long int inf = 1e9 + 7; int n, m, ans[2005], vis[2005], col[2005], visdfs[2005], par[2005], ran[2005]; char a[1005][1005]; vector<int> gr[2005], inc[2005]; stack<int> topo; map<int, int> fin; void error() { cout << "NO" << endl; exit(0); } void dfs1(int x) { vis[x] = 1; for (auto& el : gr[x]) if (!vis[el]) dfs1(el); topo.push(x); return; } bool dfs(int x) { col[x] = 1; for (auto& el : gr[x]) { if (col[el] == 2) continue; else if (col[el] == 1) return true; else dfs(el); } col[x] = 2; return false; } bool cycle() { bool f = false; for (int i = 1; i <= (n + m); ++i) if (col[i] == 0) f |= dfs(i); return f; } int find(int x) { if (x == par[x]) return par[x]; par[x] = find(par[x]); return par[x]; } void merge(int x, int y) { int p1 = find(x); int p2 = find(y); if (ran[p1] > ran[p2]) par[y] = p1; else if (ran[p1] < ran[p2]) par[x] = p2; else { par[y] = p1; ++ran[p1]; } return; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cin.exceptions(cin.failbit); mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); cin >> n >> m; for (int i = 1; i <= (n + m); ++i) par[i] = i; for (int i = 1; i <= (n); ++i) for (int j = 1; j <= (m); ++j) { cin >> a[i][j]; if (a[i][j] == '=') merge(i, n + j); } for (int i = 1; i <= (n); ++i) for (int j = 1; j <= (m); ++j) { if (a[i][j] == '>') { if (par[n + j] == par[i]) error(); gr[par[n + j]].push_back(par[i]); inc[par[i]].push_back(par[n + j]); } if (a[i][j] == '<') { if (par[i] == par[n + j]) error(); gr[par[i]].push_back(par[n + j]); inc[par[n + j]].push_back(par[i]); } } if (cycle()) error(); else { cout << "YES" << endl; set<int> tmp; for (int i = 1; i <= (n + m); ++i) tmp.insert(par[i]); for (auto& el : tmp) if (!vis[el]) dfs1(el); vector<int> ts; set<int> roo; while (!topo.empty()) { ts.push_back(topo.top()); topo.pop(); } for (int i = 0; i < (ts.size()); ++i) { if (!inc[ts[i]].size()) { roo.insert(ts[i]); } else break; } for (int i = 1; i <= (n + m); ++i) if (roo.count(par[i])) fin[i] = 1; for (auto& el : ts) { if (inc[el].size() == 0) continue; int val = -1; for (auto& el1 : inc[el]) val = max(val, fin[el1]); fin[el] = val + 1; } for (int i = 1; i <= (n); ++i) cout << fin[par[i]] << " "; cout << endl; for (int i = n + 1; i <= (n + m); ++i) cout << fin[par[i]] << " "; cout << endl; } return 0; }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
n, m = map(int, input().split()) dishes = [0 for _ in range(n + m)] father = [-1 for _ in range(n + m)] e_out = dict() v_in = [0 for _ in range(n + m)] def get_father(n): if father[n] == -1: return n else: father[n] = get_father(father[n]) return father[n] compare_matrix = [] for i in range(n): compare_matrix.append(input()) for i in range(n): for j in range(m): if compare_matrix[i][j] == "=": fi = get_father(i) fj = get_father(j + n) if fi != fj: father[fj] = fi children = dict() for i in range(n + m): fi = get_father(i) if fi != i: if fi not in children: children[fi] = [i] else: children[fi].append(i) for i in range(n): for j in range(m): if compare_matrix[i][j] == "=": continue fi = get_father(i) fj = get_father(j + n) if fi == fj: print("NO") exit(0) if compare_matrix[i][j] == ">": v_in[fi] += 1 if fj in e_out: e_out[fj].append(fi) else: e_out[fj] = [fi] if compare_matrix[i][j] == "<": v_in[fj] += 1 if fi in e_out: e_out[fi].append(fj) else: e_out[fi] = [fj] # print(v_in) # print(e_out) score = 1 visited = [False for _ in range(n + m)] v_total = 0 q = [v for v in range(n + m) if v_in[v] == 0] while q: t = [] for i in q: dishes[i] = score v_total += 1 if i in children: for j in children[i]: dishes[j] = score v_total += 1 if i in e_out: for j in e_out[i]: v_in[j] -= 1 if v_in[j] == 0: t.append(j) q = t score += 1 if v_total < n + m: print("NO") exit(0) print("YES") for i in dishes[:n]: print(i, end=" ") print() for i in dishes[n:n + m]: print(i, end=" ")
PYTHON3
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n Γ— m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000) β€” the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers β€” evaluations of dishes from the first set, and on the third line print m integers β€” evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
2
10
import java.util.*; import java.io.*; import java.math.BigInteger; public class A{ static PrintWriter out; static InputReader in; public static void main(String args[]){ out = new PrintWriter(System.out); in = new InputReader(); new A(); out.flush(); out.close(); } final int max = 2010; int n, m, p[], r[], tot; int from[] = new int[max * max], to[] = new int[max * max], e = 0; int ja[][], c[]; char ch[][]; boolean sp[]; boolean rs = true; ArrayList<Integer> al[] = new ArrayList[max]; int get(int u){ return p[u] == u ? u : (p[u] = get(p[u])); } void merge(int u, int v){ int pu = get(u), pv = get(v); if(r[pu] == r[pv])r[pu]++; if(r[pu] < r[pv]){ pu ^= pv; pv ^= pu; pu ^= pv; } p[pv] = pu; } A(){ n = in.nextInt(); m = in.nextInt(); tot = n + m + 1; p = new int[tot]; r = new int[tot]; for(int i = 1; i < tot; i++){ p[i] = i; } ch = new char[n][]; for(int i = 0; i < n; i++)ch[i] = in.next().trim().toCharArray(); for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ if(ch[i][j] == '='){ merge(i + 1, n + j + 1); } } } for(int i = 0; i < max; i++)al[i] = new ArrayList<>(); sp = new boolean[tot]; for(int i = 1; i < tot; i++){ p[i] = get(i); al[p[i]].add(i); sp[p[i]] = true; } o : for(int i = 0; i < max; i++){ int sz = al[i].size(); if(sz < 2)continue; // System.out.println(al[i]); for(int j = 0; j < sz; j++){ int f = al[i].get(j); if(f > n)continue; for(int k = 0; k < sz; k++){ int s = al[i].get(k); if(s <= n)continue; s -= n; if(ch[f - 1][s - 1] != '='){ rs = false; break o; } } } } for(int i = 1; i <= n; i++){ if(sp[p[i]] == true){ int sz = al[p[i]].size(); for(int j = 0; j < sz; j++){ int t = al[p[i]].get(j); if(t <= n){ for(int k = 1; k <= m; k++){ if(ch[t - 1][k - 1] == '=')continue; if(ch[t - 1][k - 1] == '>'){ from[e] = p[k + n]; to[e++] = p[i]; }else{ from[e] = p[i]; to[e++] = p[k + n]; } } }else{ t -= n; for(int k = 1; k <= n; k++){ if(ch[k - 1][t - 1] == '=')continue; if(ch[k - 1][t - 1] == '>'){ from[e] = p[i]; to[e++] = p[k]; }else{ from[e] = p[k]; to[e++] = p[i]; } } } } sp[p[i]] = false; } } ja = new int[tot][]; c = new int[tot]; for(int i = 0; i < e; i++){ c[from[i]]++; cc[to[i]]++; // System.out.println(from[i] + " " + to[i]); } for(int i = 1; i < tot; i++){ ja[i] = new int[c[i]]; c[i] = 0; } for(int i = 0; i < e; i++){ ja[from[i]][c[from[i]]++] = to[i]; } for(int i = 1; i < tot; i++){ if(cc[p[i]] == 0 && !visit[p[i]]){ int u = p[i]; ad.add(u); order[u] = 1; visit[u] = true; } } while(!ad.isEmpty()){ // System.out.println(ad); int u = ad.pollFirst(); for(int v : ja[u]){ if(--cc[v] == 0){ ad.addLast(v); order[v] = order[u] + 1; visit[v] = true; } } } for(int i = 1; i < tot; i++){ if(!visit[p[i]]){ rs = false; break; } } if(!rs){ out.print("No"); }else{ out.println("Yes"); for(int i = 1; i <= n; i++){ out.print(order[p[i]] + " "); } out.println(); for(int i = 1; i <= m; i++){ out.print(order[p[i + n]] + " "); } } // solve(); } ArrayDeque<Integer> ad = new ArrayDeque<>(); boolean visit[] = new boolean[max]; int order[] = new int[max]; int cc[] = new int[max]; void solve(){ int n = in.nextInt(); long ans = 0; long ap = 0, bp = 0; for(int i = 0; i < n; i++){ long a = in.nextLong(), b = in.nextLong(); if(ap == a && bp == b && i != 0)continue; ans += Math.max(Math.min(a, b) - Math.max(ap, bp) + 1, 0); ap = a; bp = b; }out.print(ans); } public static class InputReader{ BufferedReader br; StringTokenizer st; InputReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } public int nextInt(){ return Integer.parseInt(next()); } public long nextLong(){ return Long.parseLong(next()); } public double nextDouble(){ return Double.parseDouble(next()); } public String next(){ while(st == null || !st.hasMoreTokens()){ try{ st = new StringTokenizer(br.readLine()); }catch(IOException e){} } return st.nextToken(); } } }
JAVA