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
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 cf { static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(Reader in) { br = new BufferedReader(in); } public FastScanner() { this(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; } int[] nextIntArray(int n) { int[] a = new int[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextInt(); } return a; } } static char[][] grid; static ArrayList<Integer>[] adj; static int[] val; static boolean[] vis; static boolean[] recStack; public static void main(String[] args) { FastScanner sc = new FastScanner(); PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(), m = sc.nextInt(); adj = new ArrayList[n+m]; for(int i=0;i<n+m;i++) { adj[i] = new ArrayList<Integer>(); } grid = new char[n][m]; for(int i=0;i<n;i++) { grid[i] = sc.nextLine().toCharArray(); } vis = new boolean[n+m]; Arrays.fill(vis, false); val = new int[n+m]; recStack = new boolean[n+m]; Arrays.fill(recStack, false); DSU d = new DSU(n+m); d.createSet(); // organize sets based off equality for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(grid[i][j] == '=') { d.union(i, n+j); } } } // construct graph int pi = -1, pj = -1; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { pi = d.find(i); pj = d.find(n+j); if(grid[i][j] == '>') { adj[pi].add(pj); } else if(grid[i][j] == '<') { adj[pj].add(pi); } else { continue; } } } // check cyclic nature (self loops, etc) for(int i=0;i<n+m;i++) { if(!vis[d.find(i)]) { if(isCyclic(d.find(i))) { pw.println("No"); pw.close(); return; } } } // dfs Arrays.fill(vis, false); for(int i=0;i<n+m;i++) { if(!vis[d.find(i)]) { dfs(d.find(i)); } } pw.println("Yes"); for(int i=0;i<n;i++) { pw.print(val[d.find(i)] + " "); } pw.println(); for(int i=n;i<n+m;i++) { pw.print(val[d.find(i)] + " "); } pw.println(); pw.close(); } static int dfs(int v) { vis[v] = true; Iterator<Integer> itr = adj[v].iterator(); int max = 0; while(itr.hasNext()) { int next = itr.next(); if(!vis[next]) { max = Math.max(max, dfs(next)); } else { max = Math.max(max, val[next]); } } val[v] = max + 1; return val[v]; } static boolean isCyclic(int v) { if(recStack[v]) { return true; } if(vis[v]) { return false; } vis[v] = true; recStack[v] = true; Iterator<Integer> itr = adj[v].iterator(); while(itr.hasNext()) { int next = itr.next(); if(isCyclic(next)) { return true; } } recStack[v] = false; return false; } static class DSU { int n; int[] rank; int[] parent; public DSU(int n) { this.n = n; rank = new int[n]; parent = new int[n]; } public void createSet() { for(int i=0;i<n;i++) { parent[i] = i; rank[i] = 0; } } public int find(int p) { if(parent[p] == p) { return p; } parent[p] = find(parent[p]); return parent[p]; } public void union(int p, int q) { int i = find(p); int j = find(q); if(i == j) { return; } if(rank[i] > rank[j]) { parent[j] = i; } else if(rank[j] > rank[i]) { parent[i] = j; } else { parent[i] = j; rank[j]++; } } } }
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.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.List; import java.util.Arrays; import java.util.InputMismatchException; import java.io.IOException; import java.util.Collections; import java.util.ArrayList; 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; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public static int[] createSets(int size) { int[] p = new int[size]; for (int i = 0; i < size; i++) p[i] = i; return p; } public static int root(int[] p, int x) { return x == p[x] ? x : (p[x] = root(p, p[x])); } public static boolean unite(int[] p, int a, int b) { a = root(p, a); b = root(p, b); if (a != b) { p[a] = b; return true; } return false; } static int dfs(List<Integer>[] graph, int u, int[] color, int[] next) { color[u] = 1; for (int v : graph[u]) { next[u] = v; if (color[v] == 0) { int cycleStart = dfs(graph, v, color, next); if (cycleStart != -1) { return cycleStart; } } else if (color[v] == 1) { return v; } } color[u] = 2; return -1; } public static boolean findCycle(List<Integer>[] graph) { int n = graph.length; int[] color = new int[n]; int[] next = new int[n]; for (int u = 0; u < n; u++) { if (color[u] != 0) continue; int cycleStart = dfs(graph, u, color, next); if (cycleStart != -1) { List<Integer> cycle = new ArrayList<>(); cycle.add(cycleStart); for (int i = next[cycleStart]; i != cycleStart; i = next[i]) { cycle.add(i); } cycle.add(cycleStart); return true; } } return false; } static void dfs(List<Integer>[] graph, boolean[] used, List<Integer> order, int u) { used[u] = true; for (int v : graph[u]) if (!used[v]) dfs(graph, used, order, v); order.add(u); } public static List<Integer> topologicalSort(List<Integer>[] graph) { int n = graph.length; boolean[] used = new boolean[n]; List<Integer> order = new ArrayList<>(); for (int i = 0; i < n; i++) if (!used[i]) dfs(graph, used, order, i); Collections.reverse(order); return order; } public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); char[][] a = new char[n][]; int[] p = createSets(n + m); 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++) { a[i] = in.next().toCharArray(); for (int j = 0; j < m; j++) { if (a[i][j] == '=') { unite(p, i, j + n); } } } List<Integer>[] map = new List[n + m]; for (int i = 0; i < map.length; i++) { map[i] = new ArrayList<>(); } for (int i = 0; i < n + m; i++) { map[root(p, i)].add(i); } for (int i = 0; i < n; i++) { int ri = root(p, i); for (int j = 0; j < m; j++) { int rj = root(p, n + j); if (ri == rj && a[i][j] != '=') { out.println("No"); return; } if (a[i][j] == '<') { g[ri].add(rj); } if (a[i][j] == '>') { g[rj].add(ri); } } } if (findCycle(g)) { out.println("No"); return; } List<Integer> order = topologicalSort(g); int[] res = new int[n + m]; Arrays.fill(res, 1); for (int i : order) { for (int j : g[i]) { res[j] = Math.max(res[j], res[i] + 1); } } int[] res2 = new int[n + m]; for (int i = 0; i < n + m; i++) { if (!map[i].isEmpty()) { for (int j : map[i]) { res2[j] = res[i]; } } } out.println("Yes"); for (int i = 0; i < n + m; i++) { out.print(res2[i] + " "); if (i == n - 1) out.println(); } out.println(); } } static class InputReader { final InputStream is; final byte[] buf = new byte[1024]; int pos; int size; public InputReader(InputStream is) { this.is = is; } public int nextInt() { int c = read(); while (isWhitespace(c)) c = read(); int sign = 1; if (c == '-') { sign = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = res * 10 + c - '0'; c = read(); } while (!isWhitespace(c)); return res * sign; } public String next() { int c = read(); while (isWhitespace(c)) c = read(); StringBuilder sb = new StringBuilder(); do { sb.append((char) c); c = read(); } while (!isWhitespace(c)); return sb.toString(); } int read() { if (size == -1) throw new InputMismatchException(); if (pos >= size) { pos = 0; try { size = is.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (size <= 0) return -1; } return buf[pos++] & 255; } static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || 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> inline int read() { char c = getchar(); int x = 0; bool sgn = false; while (c < '0' || c > '9') { if (c == '-') { sgn = true; } c = getchar(); } while (c >= '0' && c <= '9') { x = (x << 1) + (x << 3) + (c & 15); c = getchar(); } return sgn ? -x : x; } inline char readOpt() { char c = getchar(); while (c != '<' && c != '=' && c != '>') { c = getchar(); } return c; } const int maxN = 2005; int n, m, ts, vol, l = 1, r, dfn[maxN], low[maxN], stack[maxN], col[maxN], deg[maxN], q[maxN], dis[maxN], e[maxN][maxN]; char c[maxN][maxN]; bool ins[maxN]; void tarjan(int u) { dfn[u] = low[u] = ++ts; stack[++vol] = u; int tmp = vol; ins[u] = true; for (int i = 1; i <= n + m; i++) { if (c[u][i] == '=') { if (!dfn[i]) { tarjan(i); low[u] = std::min(low[u], low[i]); } else if (ins[i]) { low[u] = std::min(low[u], dfn[i]); } } } if (dfn[u] == low[u]) { for (int i = tmp; i <= vol; i++) { ins[stack[i]] = false; col[stack[i]] = u; } vol = tmp - 1; } } int main() { n = read(); m = read(); memset(c, ' ', sizeof(c)); for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { c[i][n + j] = readOpt(); if (c[i][n + j] == '=') { c[n + j][i] = '='; } if (c[i][n + j] == '>') { c[n + j][i] = '<'; c[i][n + j] = ' '; } } } for (int i = 1; i <= n + m; i++) { if (!dfn[i]) { tarjan(i); } } for (int i = 1, u; i <= n + m; i++) { u = col[i]; for (int j = 1, v; j <= n + m; j++) { v = col[j]; if (c[i][j] == '<') { if (u == v) { printf("No\n"); return 0; } else { e[u][v]++; deg[v]++; } } } } for (int i = 1; i <= n + m; i++) { if (col[i] == i && !deg[i]) { q[++r] = i; } } for (int u, v; l <= r; l++) { u = q[l]; for (int i = 1; i <= n + m; i++) { if (e[u][i]) { v = i; deg[v] -= e[u][i]; if (!deg[v]) { q[++r] = v; } dis[v] = std::max(dis[v], dis[u] + 1); } } } for (int i = 1; i <= n + m; i++) { if (col[i] == i && deg[i]) { printf("No\n"); return 0; } } printf("Yes\n"); for (int i = 1; i <= n; i++) { printf("%d ", dis[col[i]] + 1); } printf("\n"); for (int i = 1; i <= m; i++) { printf("%d ", dis[col[n + i]] + 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; bool vis[2005], root[2005], dad[2005]; int n, m, h, id[2005]; vector<vector<int> > g(2005); char a[1005][1005]; struct dsu { int p[2005], r[2005]; dsu() { for (int i = 0; i <= n + m; i++) { p[i] = i; r[i] = 0; } } int find_(int node) { return p[node] == node ? node : p[node] = find_(p[node]); } void union_(int a, int b) { int pa = find_(a); int pb = find_(b); if (pa == pb) return; if (r[pa] > r[pb]) p[pb] = pa; else if (r[pb] > r[pa]) p[pa] = pb; else { p[pb] = pa; r[pa]++; } } }; void topo(int node, int dep) { if (dad[node]) { cout << "No" << endl; exit(0); } else if (vis[node]) return; vis[node] = 1; dad[node] = 1; for (int i = 0; i < g[node].size(); i++) { int child = g[node][i]; topo(child, dep + 1); } h = max(h, dep); dad[node] = 0; return; } int dfs(int node) { if (vis[node]) return id[node]; vis[node] = 1; for (int i = 0; i < g[node].size(); i++) { int child = g[node][i]; id[node] = max(id[node], 1 + dfs(child)); } id[node] = max(id[node], 1); return id[node]; } int main() { cin >> n >> m; dsu u; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { cin >> a[i][j]; if (a[i][j] == '=') u.union_(i, n + j); } for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { if (a[i][j] == '=') continue; else { int pi = u.find_(i); int pj = u.find_(n + j); if (pi == pj) return cout << "No" << endl, 0; if (a[i][j] == '>') { g[pi].push_back(pj); root[pj] = 1; } else { g[pj].push_back(pi); root[pi] = 1; } } } for (int i = 1; i <= n + m; i++) { int pp = u.find_(i); if (!root[pp]) topo(pp, 1); } for (int i = 0; i <= m + n; i++) vis[i] = 0; for (int i = 1; i <= n + m; i++) { int pp = u.find_(i); if (!root[pp]) dfs(pp); } if (h == 0) return cout << "No" << endl, 0; cout << "Yes" << endl; for (int i = 1; i <= n; i++) { int pp = u.find_(i); cout << id[pp] << " "; } cout << endl; for (int i = 1; i <= m; i++) { int pp = u.find_(n + i); cout << id[pp] << " "; } 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> const int N = 1002; int n, m, p[N + N], g[N + N][N + N], d[N + N], q[N + N], l, r = -1, f[N + N]; char a[N][N]; int Find(int k) { return k == p[k] ? k : p[k] = Find(p[k]); } int main() { int u, v; scanf("%d%d", &n, &m); for (int i = 1; i <= n; i++) scanf("%s", a[i] + 1); for (u = 1; u <= n + m; u++) p[u] = u; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) if (a[i][j] == '=') p[Find(i)] = Find(j + n); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) if (a[i][j] != '=') { u = Find(i), v = Find(j + n); if (u == v) return 0 * puts("No"); else { if (a[i][j] == '>' && !g[v][u]) g[v][u] = 1, d[u]++; if (a[i][j] == '<' && !g[u][v]) g[u][v] = 1, d[v]++; } } for (u = 1; u <= n + m; u++) if (!d[u]) f[u] = 1, q[++r] = u; for (; l <= r;) { u = q[l++]; for (v = 1; v <= n + m; v++) if (g[u][v] && !--d[v]) q[++r] = v, f[v] = f[u] + 1; } for (u = 1; u <= n + m; u++) if (d[u]) return 0 * puts("No"); puts("Yes"); for (u = 1; u <= n; u++) printf("%d ", f[Find(u)]); puts(""); for (u = n + 1; u <= n + m; u++) printf("%d ", f[Find(u)]); 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
#!/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 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, nr = roots[:], 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 res = [1 if graph[i] == [] else -1 for i in range(n + m)] visited = [False] * (n + m) def dfs(node): if res[node] != 1: 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('Yes') print(*res[:n]) print(*res[n:]) return 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
#include <bits/stdc++.h> using namespace std; const int maxn = 1e4 + 7; const int mod = 1e9 + 7; const long long INFLL = 0x3f3f3f3f3f3f3f3fLL; const int INF = 0x3f3f3f3f; using namespace std; int n, m, a[maxn], fa[maxn], du[maxn]; char mp[maxn][maxn]; vector<int> v[maxn]; int Find(int x) { return fa[x] == x ? x : fa[x] = Find(fa[x]); } int main() { scanf("%d %d", &n, &m); for (int i = 0; i < maxn; i++) fa[i] = i; for (int i = 1; i <= n; i++) { scanf("%s", mp[i] + 1); for (int j = 1; j <= m; j++) if (mp[i][j] == '=') fa[Find(i)] = Find(j + n); } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (mp[i][j] == '>') v[Find(n + j)].push_back(Find(i)), du[Find(i)]++; if (mp[i][j] == '<') v[Find(i)].push_back(Find(n + j)), du[Find(j + n)]++; } } queue<int> q; for (int i = 1; i <= n + m; i++) if (Find(i) == i && du[i] == 0) q.push(i), a[i] = 1; while (!q.empty()) { int cnt = q.front(); q.pop(); for (int i = 0; i < v[cnt].size(); i++) { int nxt = v[cnt][i]; du[nxt]--; if (du[nxt] == 0) q.push(nxt), a[nxt] = a[cnt] + 1; } } for (int i = 1; i <= n + m; i++) if (a[Find(i)] == 0) return 0 * printf("No\n"); printf("Yes\n"); for (int i = 1; i <= n; i++) printf("%d ", a[Find(i)]); printf("\n"); for (int i = n + 1; i <= n + m; i++) printf("%d ", a[Find(i)]); printf("\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; long long int dsu[(20ll + (long long int)2000)]; long long int hei[(20ll + (long long int)2000)]; void init(long long int n) { for (long long int i = 0; i <= n; i++) dsu[i] = i, hei[i] = 1; } long long int xfind(long long int i) { if (dsu[i] == i) return i; return xfind(dsu[i]); } void xmerge(long long int l, long long int r) { long long int rl = xfind(l); long long int rr = xfind(r); if (hei[rl] > hei[rr]) { dsu[rr] = rl; } else if (hei[rl] < hei[rr]) { dsu[rl] = rr; } else { hei[rl]++; dsu[rl] = rr; } } char ship[1001][1001]; long long int graph[2001][2001]; long long int node[2001]; long long int visit[2001]; long long int degree[2001]; long long int n, m; long long int mx; bool dfs(long long int pa, long long int& pm) { bool cir = false; if (node[pa]) return pm = node[pa], false; if (!visit[pa]) visit[pa] = 1; else { visit[pa] = 0; return true; } long long int maxpm = 0; for (int i = 1; i <= mx; i++) { long long int v = 0; if (graph[pa][i]) cir |= dfs(i, v); maxpm = max(maxpm, v); } pm = maxpm + 1; node[pa] = pm; visit[pa] = 0; return cir; } int main() { scanf( "%lld" "%lld", &n, &m); mx = n + m; init(mx); for (long long int i = 1; i <= n; i++) { for (long long int j = 1; j <= m; j++) { char c = getchar(); if (isspace(c)) { j--; continue; } ship[i][j] = c; if (c == '=') { xmerge(i, (n + j)); } } } bool fail = false; for (long long int i = 1; i <= n; i++) { for (long long int j = 1; j <= m; j++) { if (ship[i][j] == '>') { graph[xfind(i)][xfind((n + j))] = 1; degree[xfind((n + j))]++; if (xfind(i) == xfind((n + j))) fail = true; } else if (ship[i][j] == '<') { graph[xfind((n + j))][xfind(i)] = 1; degree[xfind(i)]++; if (xfind(i) == xfind((n + j))) fail = true; } } } if (fail) { printf("%s\n", "No"); return 0; } set<long long int> sp; for (long long int i = 1; i <= n; i++) { if (!degree[xfind(i)]) sp.insert(xfind(i)); } for (long long int j = 1; j <= m; j++) { if (!degree[xfind((n + j))]) sp.insert(xfind((n + j))); } if (sp.empty()) fail = true; for (auto e : sp) { long long int unused; fail |= dfs(e, unused); } if (fail) { printf("%s\n", "No"); return 0; } else { printf("%s\n", "Yes"); } for (long long int i = 1; i <= n; i++) printf("%lld%c", node[xfind(i)], i == n ? 10 : 32); for (long long int j = 1; j <= m; j++) printf("%lld%c", node[xfind((n + j))], j == m ? 10 : 32); 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; vector<int> edge[2002]; vector<int> gath[2002]; vector<int> gage[2002]; bool check[2002][2002]; bool vis[2002]; int ans[2002]; int in[2002]; int f[2002]; queue<int> q; int find(int x) { if (x == f[x]) return x; return f[x] = find(f[x]); } void topsort() { while (!q.empty()) { int u = q.front(); q.pop(); for (int i = 0; i < gage[u].size(); ++i) { int v = gage[u][i]; ans[v] = max(ans[v], ans[u] + 1); --in[v]; if (in[v] == 0) q.push(v); } } } int main() { cin >> n >> m; for (int i = 1; i <= n + m; ++i) f[i] = i; for (int i = 1; i <= n; ++i) { getchar(); for (int j = 1; j <= m; ++j) { char ch; ch = getchar(); if (ch == '>') edge[n + j].push_back(i); if (ch == '<') edge[i].push_back(n + j); if (ch == '=') f[find(j + n)] = f[i]; } } bool flag = false; for (int i = 1; i <= n + m; ++i) { gath[find(i)].push_back(i); vis[f[i]] = true; } for (int i = 1; i <= n + m; ++i) { for (int j = 0; j < gath[i].size(); ++j) { int u = gath[i][j]; for (int k = 0; k < edge[u].size(); ++k) { int v = find(edge[u][k]); if (v == i) { flag = true; break; } if (check[i][v] == false) { check[i][v] = true; ++in[v]; gage[i].push_back(v); } } if (flag) break; } if (flag) break; } if (flag) cout << "No" << endl; else { for (int i = 1; i <= m + n; ++i) if (vis[i] && in[i] == 0) { ans[i] = 1; q.push(i); } if (q.empty()) cout << "No" << endl; else topsort(); for (int i = 1; i <= m + n; ++i) if (vis[i] && in[i] != 0) { flag = true; break; } if (flag) cout << "No" << endl; else { cout << "Yes" << endl; for (int i = 1; i <= n; ++i) cout << ans[f[i]] << " "; cout << endl; for (int i = n + 1; i <= m + n; ++i) cout << ans[f[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; const int INF = 0x3f3f3f3f; const int Maxn = 1000 + 10; int pre[Maxn * 2], Hash[Maxn * 2], in[Maxn * 2], u[Maxn * Maxn * 2]; vector<int> G[Maxn * 2]; char table[Maxn][Maxn]; int Find(int x) { if (pre[x] != x) pre[x] = Find(pre[x]); return pre[x]; } void union_(int x, int y) { int xx = Find(x); int yy = Find(y); pre[xx] = yy; } int main(void) { int n, m; char op; scanf("%d%d", &n, &m); for (int i = 1; i <= n + m; ++i) pre[i] = i; memset(in, 0, sizeof(in)); for (int i = 1; i <= n; ++i) scanf("%s", table[i] + 1); for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { if (table[i][j] == '=') union_(i, j + n); } } int cnt = 0; for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { int x = Find(i), y = Find(j + n); u[cnt++] = x; u[cnt++] = y; if (table[i][j] == '=') continue; if (x == y) { printf("NO\n"); return 0; } if (table[i][j] == '>') { G[y].push_back(x); in[x]++; } else if (table[i][j] == '<') { G[x].push_back(y); in[y]++; } } } sort(u, u + cnt); cnt = unique(u, u + cnt) - u; int p, num = 1, ct = cnt; while (ct) { p = -1; for (int j = 0; j < cnt; ++j) { if (in[u[j]] == 0) { p = u[j]; in[p] = -1; ct--; Hash[p] = num; } } num++; if (p == -1 && ct != 0) { printf("NO\n"); return 0; } for (int i = 0; i < cnt; ++i) { p = u[i]; if (in[p] == -1) { in[p] = -2; for (int j = 0; j < G[p].size(); ++j) in[G[p][j]]--; } } } printf("YES\n"); for (int i = 1; i <= n; ++i) printf("%d ", Hash[pre[i]]); printf("\n"); for (int i = n + 1; i <= n + m; ++i) printf("%d ", Hash[pre[i]]); printf("\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.util.*; import java.io.*; public class Q3 { static int mod = (int) (1e9+7); static InputReader in; static PrintWriter out; static ArrayList<ArrayList<Integer>> list; static int[] rt; static int[] size; static void initialize(int n){ rt = new int[n + 1]; size = new int[n + 1]; for(int i = 0; i < rt.length; i++){ rt[i] = i; size[i] = 1; } } static int root(int x){ while(rt[x] != x){ rt[x] = rt[rt[x]]; x = rt[x]; } return x; } static boolean union(int x,int y){ int root_x = root(x); int root_y = root(y); if(root_x == root_y) return true; if(size[root_x]<size[root_y]){ rt[root_x] = rt[root_y]; size[root_y] += size[root_x]; } else{ rt[root_y] = rt[root_x]; size[root_x] += size[root_y]; } return false; } static boolean hasCycle(int u, boolean[] vis, boolean[] stack) { if(!vis[u]) { vis[u] = true; stack[u] = true; for(int v: list.get(u)) { if(!vis[v] && hasCycle(v, vis, stack)) return true; else if(stack[v]) return true; } } stack[u] = false; return false; } static boolean check() { boolean[] vis = new boolean[list.size()]; boolean[] stack = new boolean[list.size()]; for(int i = 0; i < list.size(); i++) if(hasCycle(i, vis, stack)) return true; return false; } static void solve() { in = new InputReader(System.in); out = new PrintWriter(System.out); int n = in.nextInt(); int m = in.nextInt(); initialize(n + m); list = new ArrayList<ArrayList<Integer>>(); for(int i = 0; i < n + m; i++) list.add(new ArrayList<Integer>()); char[][] c = new char[n][m]; for(int i = 0; i < n; i++) { c[i] = in.nextLine().toCharArray(); for(int j = 0; j < m; j++) { if(c[i][j] == '=') { union(i, n + j); } } } int[] size = new int[n + m]; for(int i = 0; i < n; i++) { int x = root(i); for(int j = 0; j < m; j++) { int y = root(n + j); if(c[i][j] == '>') { list.get(y).add(x); size[x]++; } else if(c[i][j] == '<') { list.get(x).add(y); size[y]++; } } } if(check()) { out.println("No"); } else { out.println("Yes"); Queue<Integer> queue = new LinkedList<Integer>(); int[] res = new int[n + m]; for(int i = 0; i < n + m; i++) if(size[i] == 0) { queue.add(i); res[i] = 1; } while(!queue.isEmpty()) { int u = queue.poll(); for(int v: list.get(u)) { size[v]--; res[v] = max(res[v], res[u] + 1); if(size[v] == 0) queue.add(v); } } for(int i = 0; i < n; i++) out.print(res[root(i)] + " "); out.println(); for(int i = 0; i < m; i++) out.print(res[root(n + i)] + " "); out.println(); } out.close(); } public static void main(String[] args) { new Thread(null ,new Runnable(){ public void run() { try{ solve(); } catch(Exception e){ e.printStackTrace(); } } },"1",1<<26).start(); } static int[][] graph(int from[], int to[], int n) { int g[][] = new int[n][]; int cnt[] = new int[n]; for (int i = 0; i < from.length; i++) { cnt[from[i]]++; cnt[to[i]]++; } for (int i = 0; i < n; i++) { g[i] = new int[cnt[i]]; } Arrays.fill(cnt, 0); for (int i = 0; i < from.length; i++) { g[from[i]][cnt[from[i]]++] = to[i]; g[to[i]][cnt[to[i]]++] = from[i]; } return g; } static class Pair implements Comparable<Pair>{ int x,y,i; Pair (int x,int y,int i){ this.x=x; this.y=y; this.i=i; } Pair (int x,int y){ this.x=x; this.y=y; } public int compareTo(Pair o) { if(this.x!=o.x) return Integer.compare(this.x,o.x); else return Integer.compare(this.y,o.y); //return 0; } public boolean equals(Object o) { if (o instanceof Pair) { Pair p = (Pair)o; return p.x == x && p.y == y && p.i==i; } return false; } public int hashCode() { return new Integer(x).hashCode() * 31 + new Integer(y).hashCode()+new Integer(i).hashCode()*37; } } static String rev(String s) { StringBuilder sb = new StringBuilder(s); sb.reverse(); return sb.toString(); } static long gcd(long x, long y) { if (y == 0) { return x; } else { return gcd(y, x % y); } } static int gcd(int x, int y) { if (y == 0) { return x; } else { return gcd(y, x % y); } } static int abs(int a, int b) { return (int) Math.abs(a - b); } static long abs(long a, long b) { return (long) Math.abs(a - b); } static int max(int a, int b) { if (a > b) { return a; } else { return b; } } static int min(int a, int b) { if (a > b) { return b; } else { return a; } } static long max(long a, long b) { if (a > b) { return a; } else { return b; } } static long min(long a, long b) { if (a > b) { return b; } else { return a; } } static long pow(long n, long p, long m) { long result = 1; if (p == 0) { return 1; } while (p != 0) { if (p % 2 == 1) { result *= n; } if (result >= m) { result %= m; } p >>= 1; n *= n; if (n >= m) { n %= m; } } return result; } static long pow(long n, long p) { long result = 1; if (p == 0) { return 1; } if (p == 1) { return n; } while (p != 0) { if (p % 2 == 1) { result *= n; } p >>= 1; n *= n; } return result; } static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { 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 = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public long[] nextLongArray(int n) { long a[] = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } 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
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<List<Integer>> g; private int[] vis; private int[] ans; private int max(int a, int b) { return a < b ? b : a; } private boolean dfs(int v) { vis[v] = ans[v] = 1; for (int u : g.get(v)) { if (vis[u] == 1) return false; if (vis[u] == 0 && !dfs(u)) return false; ans[v] = max(ans[v], ans[u] + 1); } vis[v] = 2; return true; } 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 ArrayList<>()); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int v = find(i); int u = find(n + j); if (a[i][j] == '>') g.get(v).add(u); if (a[i][j] == '<') g.get(u).add(v); } } 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("NO"); return; } } out.println("YES"); for (int i = 0; i < n; i++) out.print(ans[find(i)] + (i == n - 1 ? "\n" : " ")); for (int i = n; i < n + m; i++) out.print(ans[find(i)] + (i == n + m - 1 ? "\n" : " ")); } } 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; string s[2009]; int indegree[3 * 2009], ans[3 * 2009], timer[3 * 2009], ctrid[2009], ctr = 0, comp_no[3 * 2009], res[3 * 2009], comp = 0; vector<int> g[3 * 2009], rev[3 * 2009], scc[3 * 2009], main_g[3 * 2009]; bool reached[3 * 2009]; inline void rev_dfs(int pos) { reached[pos] = true; for (int i = 0; i < rev[pos].size(); i++) { if (!reached[rev[pos][i]]) { rev_dfs(rev[pos][i]); } } timer[pos] = (++ctr); ctrid[ctr] = pos; } inline void find_scc(int pos) { reached[pos] = true; scc[comp].push_back(pos); comp_no[pos] = comp; for (int i = 0; i < g[pos].size(); i++) { if (!reached[g[pos][i]]) { find_scc(g[pos][i]); } } } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int n, m; cin >> n >> m; for (int i = 1; i <= n; i++) { cin >> s[i]; } for (int i = 1; i <= n; i++) { for (int j = 0; j < m; j++) { if (s[i][j] == '=') { g[i].push_back(n + j + 1); g[n + j + 1].push_back(i); rev[i].push_back(n + j + 1); rev[n + j + 1].push_back(i); } else if (s[i][j] == '>') { g[n + j + 1].push_back(i); rev[i].push_back(n + j + 1); } else { g[i].push_back(n + j + 1); rev[n + j + 1].push_back(i); } } } for (int i = 1; i <= n + m; i++) { if (!reached[i]) { rev_dfs(i); } } memset(reached, false, sizeof(reached)); for (int i = n + m; i >= 1; i--) { if (!reached[ctrid[i]]) { ++comp; find_scc(ctrid[i]); } } for (int i = 1; i <= n + m; i++) { for (int j = 0; j < g[i].size(); j++) { if (comp_no[i] != comp_no[g[i][j]]) { main_g[comp_no[i]].push_back(comp_no[g[i][j]]); indegree[comp_no[g[i][j]]]++; } } } queue<int> q; for (int i = 1; i <= comp; i++) { if (indegree[i] == 0) { q.push(i); res[i] = 1; } } while (!q.empty()) { int pos = q.front(); q.pop(); for (int i = 0; i < main_g[pos].size(); i++) { indegree[main_g[pos][i]]--; if (indegree[main_g[pos][i]] == 0) { q.push(main_g[pos][i]); res[main_g[pos][i]] = res[pos] + 1; } } } for (int i = 1; i <= comp; i++) { for (int j = 0; j < scc[i].size(); j++) { ans[scc[i][j]] = res[i]; } } bool flag = true; for (int i = 1; i <= n; i++) { for (int j = 0; j < m; j++) { if (s[i][j] == '=') { if (ans[i] != ans[n + j + 1]) { flag = false; break; } } else if (s[i][j] == '>') { if (ans[i] <= ans[n + j + 1]) { flag = false; break; } } else { if (ans[i] >= ans[n + j + 1]) { flag = false; break; } } } } if (!flag) { cout << "No" << endl; return 0; } cout << "Yes" << endl; for (int i = 1; i <= n; i++) { cout << ans[i] << " "; } cout << endl; for (int i = n + 1; i <= n + m; i++) { cout << 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; char s[1111][1111]; int lessthan[2222]; vector<int> morethan[2222]; int f[2222], in[2222]; int root(int u) { return u == f[u] ? u : f[u] = root(f[u]); } void merge(int u, int v) { f[root(u)] = root(v); } int main() { int n, m; scanf("%d %d", &n, &m); int N = n + m; for (int i = 1; i <= n; ++i) { scanf("%s", s[i] + 1); } for (int i = 1; i <= N; ++i) f[i] = i; for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { if (s[i][j] == '=') { merge(i, n + j); } } } for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { if (s[i][j] == '>') { morethan[root(n + j)].push_back(root(i)); } else if (s[i][j] == '<') { morethan[root(i)].push_back(root(n + j)); } } } for (int i = 1; i <= N; ++i) { for (auto x : morethan[i]) { lessthan[x]++; } } set<int> st1, st2; for (int i = 1; i <= N; ++i) { if (f[i] == i && lessthan[i] == 0) st1.insert(i); } int cnt = 0; while (!st1.empty()) { ++cnt; for (int i : st1) { in[i] = cnt; for (int &j : morethan[i]) { --lessthan[j]; if (lessthan[j] == 0) { st2.insert(j); } } } st1 = st2; st2.clear(); } for (int i = 1; i <= N; ++i) { if (f[i] == i && !in[i]) { puts("No"); return 0; } } puts("Yes"); for (int i = 1; i <= N; ++i) { printf("%d ", in[root(i)]); if (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; template <typename T1, typename T2> inline void chmin(T1& a, T2 b) { if (a > b) a = b; } template <typename T1, typename T2> inline void chmax(T1& a, T2 b) { if (a < b) a = b; } const long long MOD = 998244353; const long long MAX = 50000; const double pi = acos(-1); const double EPS = 1e-12; const long long INF = 1e18; void test() { std::random_device rnd; } long long siz[MAX]; long long par[MAX]; long long Rank[MAX]; void init(long long n) { for (long long i = 0; i < n; ++i) { par[i] = i; Rank[i] = 0; siz[i] = 1; } } long long find(long long x) { if (par[x] == x) { return x; } else { return par[x] = find(par[x]); } } void unite(long long x, long long y) { x = find(x); y = find(y); if (x == y) return; if (Rank[x] < Rank[y]) { par[x] = y; siz[x] += siz[y]; siz[y] = siz[x]; } else { siz[y] += siz[x]; siz[x] = siz[y]; par[y] = x; if (Rank[x] == Rank[y]) Rank[x]++; } } bool same(long long x, long long y) { return find(x) == find(y); } void no() { cout << ("No") << '\n'; exit(0); } char A[1010][1010]; long long ans[5050]; bool active[5050]; bool visited[5050]; set<long long> chi[5050]; long long dfs(long long n) { if (ans[n] > 0) return ans[n]; visited[n] = true; active[n] = true; long long res = 1; for (auto nxt : chi[n]) { if (active[nxt]) no(); res = max(res, dfs(nxt) + 1); } ans[n] = res; active[n] = false; return res; } void solve() { long long N, M; cin >> N >> M; init(3000); for (long long i = 0; i < N; ++i) for (long long j = 0; j < M; ++j) { cin >> A[i][j]; if (A[i][j] == '=') unite(i + 1000, j); } for (long long i = 0; i < N; ++i) for (long long j = 0; j < M; ++j) { if (same(i + 1000, j) && A[i][j] != '=') no(); if (A[i][j] == '>') { chi[find(i + 1000)].insert(find(j)); } else if (A[i][j] == '<') chi[find(j)].insert(find(i + 1000)); } for (long long i = 0; i < N; ++i) { long long v = find(i + 1000); ans[i + 1000] = dfs(v); } for (long long j = 0; j < M; ++j) { long long v = find(j); ans[j] = dfs(v); } cout << ("Yes") << '\n'; for (long long i = 0; i < N; ++i) cout << (ans[find(i + 1000)]) << " "; cout << endl; for (long long j = 0; j < M; ++j) cout << (ans[find(j)]) << " "; cout << endl; } signed main() { cin.tie(0); ios::sync_with_stdio(false); 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 N = 1e6 + 7; int ans[N], fa[N], n, m, head[N], cnt, col[N], tot, in[N], num; char a[1005][1005]; int vis[N]; struct ii { int to, next; } e[N]; inline void add(int u, int v) { e[++cnt].to = v; e[cnt].next = head[u]; head[u] = cnt; in[v]++; } inline int find(int x) { return fa[x] == x ? x : fa[x] = find(fa[x]); } inline void unionn(int x, int y) { fa[find(x)] = find(y); } bool topsort() { queue<int> q; for (int i = 1; i <= tot; i++) { if (in[i] == 0) q.push(i); ans[i] = 1; } while (!q.empty()) { int x = q.front(); q.pop(); num++; for (int i = head[x]; i; i = e[i].next) { int v = e[i].to; in[v]--; ans[v] = ans[x] + 1; if (in[v] == 0) q.push(v); } } if (num == tot) return 1; return 0; } int main() { scanf("%d%d", &n, &m); char s[1005]; for (int i = 1; i <= n; i++) { scanf("%s", s + 1); for (int j = 1; j <= m; j++) { a[i][j] = s[j]; } } 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 (a[i][j] == '=') unionn(find(i), find(j + n)); } } for (int i = 1, k; i <= n + m; i++) { if (vis[k = find(i)]) col[i] = vis[k]; else col[i] = vis[k] = ++tot; } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (a[i][j] == '>') add(col[j + n], col[i]); else if (a[i][j] == '<') add(col[i], col[j + n]); } } if (topsort()) { printf("Yes\n"); for (int i = 1; i <= n; i++) printf("%d ", ans[col[i]]); printf("\n"); for (int i = n + 1; i <= n + m; i++) printf("%d ", ans[col[i]]); } else printf("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.util.*; import java.io.*; import static java.lang.Math.*; public class MainS { static final long MOD = 1_000_000_007, INF = 1_000_000_000_000_000_000L; static final int INf = 1_000_000_000; static FastReader reader; static PrintWriter writer; public static void main(String[] args) { Thread t = new Thread(null, new O(), "Integer.MAX_VALUE", 100000000); t.start(); } static class O implements Runnable { public void run() { try { magic(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } } public static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { 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; } } static int N, baap[], weight[],dp[]; static ArrayList<Integer> adj[]; static boolean vis[], inStack[], cycleDetected = false; static int assigned[]; static void magic() throws IOException { reader = new FastReader(); writer = new PrintWriter(System.out, true); int n = reader.nextInt(), m = reader.nextInt(); N = n + m; baap = new int[N+1]; weight = new int[N+1]; char c[][] = new char[n][m]; for(int i=0;i<n;++i) { c[i] = reader.next().toCharArray(); } //writer.println("yaha0"); init(N); for(int i=0;i<n;++i) { for(int j=0;j<m;++j) { if(c[i][j]=='=') { un(i+1, n+j+1); } } } //writer.println("yaha1"); int indeg[] = new int[N+1]; dp = new int[N+1]; Arrays.fill(dp, -1); adj = new ArrayList[N+1]; for(int i=1;i<=N;++i) { adj[i] = new ArrayList<>(); } for(int i=0;i<n;++i) { for(int j=0;j<m;++j) { if(c[i][j]=='>') { int ra = gr(n+j+1); int rb = gr(i+1); if(ra==rb) { writer.println("No"); System.exit(0); } adj[rb].add(ra); indeg[ra]++; } else if(c[i][j]=='<') { int ra = gr(i+1); int rb = gr(n+j+1); if(ra==rb) { writer.println("No"); System.exit(0); } adj[rb].add(ra); indeg[ra]++; } } } //writer.println("yaha2"); vis = new boolean[N+1]; inStack = new boolean[N+1]; for(int i=1;i<=N;++i) { if(!vis[gr(i)]) { dfs(gr(i)); if(cycleDetected) { writer.println("No"); System.exit(0); } } } // writer.println("new vertices corresponding to old: "); // for(int i=1;i<=N;++i) { // writer.print(gr(i) + " "); // } // writer.println(); // writer.println("yaha3"); vis = new boolean[N+1]; assigned = new int[N+1]; for(int i=1;i<=N;++i) { if(indeg[gr(i)]>0) { continue; } //writer.println("Starting DFS from vertex: "+i); if(!vis[gr(i)]) { dfs1(gr(i)); } } //writer.println("yaha4"); writer.println("Yes"); for(int i=1;i<=n;++i) { writer.print(dp[gr(i)] + " "); } writer.println(); for(int i=n+1;i<=n+m;++i) { writer.print(dp[gr(i)] + " "); } writer.println(); } static int dfs1(int x) { if(dp[x]!=-1) { return dp[x]; } int max = 0; vis[x] = true; for(int e : adj[x]) { if(true) { max = max(max, dfs1(e)); } } return dp[x] = 1+max; } static void dfs(int x) { vis[x] = inStack[x] = true; for(int e : adj[x]) { if(!vis[e]) { dfs(e); } else if(inStack[e]) { cycleDetected = true; } } inStack[x] = false; } static void init(int n) { baap = new int[n+1]; weight = new int[n+1]; for(int i=0;i<=n;++i) { baap[i] = i; ++weight[i]; } } static int gr(int a) { if(baap[a]==a) return a; return baap[a] = gr(baap[a]); } static boolean un(int a,int b) { int ra = gr(a); int rb = gr(b); if(ra==rb) return false; if(weight[rb]>weight[ra]) { weight[rb]+=weight[ra]; baap[ra] = rb; } else { weight[ra]+=weight[rb]; baap[rb] = ra; } return true; } }
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.*; import java.util.stream.Collectors; import java.util.stream.IntStream; import static java.lang.System.exit; public class D { public static void main(String[] args) throws IOException { Scanner s = new Scanner(new BufferedInputStream(System.in, 1 << 20)); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out), 1 << 20); int n = s.nextInt(), m = s.nextInt(); char[][] rs = new char[n][]; for (int i = 0; i < n; i++) { rs[i] = s.next().toCharArray(); } Map<Integer, HashSet<Integer>> vToSet = new HashMap<>(10000); for (int i = 0; i < n; i++) vToSet.put(1024 + i, new HashSet<>(Arrays.asList(1024 + i))); for (int i = 0; i < m; i++) vToSet.put(i, new HashSet<>(Arrays.asList(i))); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (rs[i][j] == '=') { int a = 1024 + i; int b = j; if (!vToSet.get(a).contains(b)) { HashSet<Integer> joined; if (vToSet.get(a).size() > vToSet.get(b).size()) { joined = vToSet.get(a); joined.addAll(vToSet.get(b)); for (Integer v : vToSet.get(b)) vToSet.put(v, joined); } else { joined = vToSet.get(b); joined.addAll(vToSet.get(a)); for (Integer v : vToSet.get(a)) vToSet.put(v, joined); } } } } } HashMap<Integer, Long> vToId = new HashMap<>(); { long id = 0; for (HashSet<Integer> set : vToSet.values()) { for (Integer v : set) { vToId.put(v, id); } ++id; } } Map<Long, Set<Long>> gt = new HashMap<>(10000); for (Long id : vToId.values()) { gt.put(id, new HashSet<>()); } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (rs[i][j] == '=') continue; Long aId = vToId.get(1024 + i); Long bId = vToId.get(j); if (rs[i][j] == '>') { if (gt.get(bId).contains(aId)) { out.write("No"); out.flush(); exit(0); } gt.get(aId).add(bId); } if (rs[i][j] == '<') { if (gt.get(aId).contains(bId)) { out.write("No"); out.flush(); exit(0); } gt.get(bId).add(aId); } } } Map<Long, Set<Long>> lt = new HashMap<>(); for (Map.Entry<Long, Set<Long>> gtEntry : gt.entrySet()) { for (Long lesser : gtEntry.getValue()) { if (!lt.containsKey(lesser)) lt.put(lesser, new HashSet<>()); lt.get(lesser).add(gtEntry.getKey()); } } Map<Long, Integer> rates = new HashMap<>(); List<Long> minSets = gt.keySet().stream() .filter(key -> gt.get(key).isEmpty()) .collect(Collectors.toList()); for (int i = 1; !gt.isEmpty(); ++i) { if (minSets.isEmpty()) { out.write("No"); out.flush(); exit(0); } List<Long> nextMinSets = new ArrayList<>(); for (Long minId : minSets) { gt.remove(minId); for (Long gtId : lt.getOrDefault(minId, new HashSet<>())) { Set<Long> gtIds = gt.get(gtId); gtIds.remove(minId); if (gtIds.isEmpty()) { nextMinSets.add(gtId); } } rates.put(minId, i); } if (nextMinSets.isEmpty() && !gt.isEmpty()) { out.write("No"); out.flush(); exit(0); } minSets = nextMinSets; } out.write("Yes\n"); out.write(IntStream.range(0, n) .mapToObj(i -> rates.get(vToId.get(1024 + i)).toString()) .collect(Collectors.joining(" "))); out.write("\n"); out.write(IntStream.range(0, m) .mapToObj(j -> rates.get(vToId.get(j)).toString()) .collect(Collectors.joining(" "))); out.flush(); } }
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.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.List; import java.util.Arrays; import java.util.Iterator; import java.util.Collection; import java.util.HashMap; import java.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; 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; FastReader in = new FastReader(inputStream); PrintWriter out = new PrintWriter(outputStream); DGourmetChoice solver = new DGourmetChoice(); solver.solve(1, in, out); out.close(); } static class DGourmetChoice { public void solve(int testNumber, FastReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); char[][] map = in.nextCharacterMap(n, m); DJSet djSet = new DJSet(n + m); for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (map[i][j] == '=') { djSet.union(i, n + j); } } } HashMap<Integer, Integer> comp = new HashMap<>(); for (int i = 0; i < n + m; ++i) { int root = djSet.root(i); if (comp.containsKey(root)) continue; comp.put(root, comp.size()); } 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) { if (map[i][j] == '>') { int f1 = djSet.root(i); f1 = comp.get(f1); int f2 = djSet.root(n + j); f2 = comp.get(f2); g[f2].add(f1); } else if (map[i][j] == '<') { int f1 = djSet.root(i); f1 = comp.get(f1); int f2 = djSet.root(n + j); f2 = comp.get(f2); g[f1].add(f2); } } } int[] indeg = new int[n + m]; for (int cur = 0; cur < n + m; ++cur) { for (Integer next : g[cur]) { ++indeg[next]; } } int[] score = new int[n + m]; ArrayUtils.fill(score, 1); int[] ret = new int[n + m]; int ptr = 0; //sources for (int i = 0; i < n + m; ++i) if (indeg[i] == 0) { ret[ptr++] = i; score[i] = 1; } //remaining nodes for (int start = 0; start < ptr; ++start) { for (Integer next : g[ret[start]]) { --indeg[next]; score[next] = Math.max(score[next], score[ret[start]] + 1); if (indeg[next] == 0) { ret[ptr++] = next; } } } //loop for (int i = 0; i < n; ++i) { if (indeg[i] > 0) { out.println("No"); return; } } out.println("Yes"); ArrayList<Integer> ans1 = new ArrayList<>(); ArrayList<Integer> ans2 = new ArrayList<>(); for (int i = 0; i < n + m; ++i) { int r = djSet.root(i); r = comp.get(r); if (i < n) ans1.add(score[r]); if (i >= n) ans2.add(score[r]); } ArrayUtils.printArray(out, ans1); ArrayUtils.printArray(out, ans2); } } static class FastReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar; private int pnumChars; public FastReader(InputStream stream) { this.stream = stream; } private int pread() { if (pnumChars == -1) { throw new InputMismatchException(); } if (curChar >= pnumChars) { curChar = 0; try { pnumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (pnumChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = pread(); while (isSpaceChar(c)) c = pread(); int sgn = 1; if (c == '-') { sgn = -1; c = pread(); } int res = 0; do { if (c == ',') { c = pread(); } if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = pread(); } while (!isSpaceChar(c)); return res * sgn; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public char nextCharacter() { int c = pread(); while (isSpaceChar(c)) c = pread(); return (char) c; } public char[] nextCharacterArray(int n) { char[] chars = new char[n]; for (int i = 0; i < n; i++) { chars[i] = nextCharacter(); } return chars; } public char[][] nextCharacterMap(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) { map[i] = nextCharacterArray(m); } return map; } } static class DJSet { public int[] upper; public int count; public DJSet(int n) { upper = new int[n]; count = n; Arrays.fill(upper, -1); } public int root(int x) { return upper[x] < 0 ? x : (upper[x] = root(upper[x])); } public boolean union(int x, int y) { x = root(x); y = root(y); if (x != y) { if (upper[y] < upper[x]) { int d = x; x = y; y = d; } upper[x] += upper[y]; upper[y] = x; --count; return true; } return false; } } static class ArrayUtils { public static void fill(int[] array, int value) { Arrays.fill(array, value); } public static <T> void printArray(PrintWriter out, Collection<T> array) { if (array.size() == 0) return; int size = array.size(); Iterator<T> iterator = array.iterator(); int ct = 0; for (; ct < size && iterator.hasNext(); ct++) { if (ct != 0) out.print(" "); out.print(iterator.next()); } out.println(); } } }
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.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.*; import java.util.*; import java.util.LinkedList; import java.math.*; import java.lang.*; import java.util.PriorityQueue; import static java.lang.Math.*; @SuppressWarnings("unchecked") public class Solution implements Runnable { static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public InputReader(InputStream stream) { this.stream = stream; } 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 String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { 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 long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long 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 double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { 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 boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static long min(long a,long b) { if(a>b) { return b; } return a; } public static int min(int a,int b) { if(a>b) { return b; } return a; } public static long max(long a,long b) { if(a>b) { return a; } return b; } public static int max(int a,int b) { if(a>b) { return a; } return b; } static class pair { long x; long y; pair(long x,long y) { this.x = x; this.y = y; } } public static int gcd(int a,int b) { if(a==0) return b; if(b==0) return a; while((a%=b)!=0&&(b%=a)!=0); return a^b; } public static long mod(long x) { if(x>0) { return x; } return -x; } static int mod = (int)1e9+7; public static long[][] mult(long[][] a,long[][] b) { int n = a.length; int m = b[0].length; long[][] res = new long[n][m]; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { for(int k=0;k<a[0].length;k++) { res[i][j] = (res[i][j]+a[i][k]*b[k][j])%mod; } } } return res; } static int[] height; static int[] parent; public static int parent(int u) { if(u==parent[u]) { return u; } return parent[u] = parent(parent[u]); } public static void join(int u,int v) { int pu = parent(u); int pv = parent(v); if(pu==pv){ return; } if(height[pu]>height[pv]) { parent[pv] = pu; } else if(height[pu]<height[pv]) { parent[pu] = pv; } else { parent[pu] = pv; height[pu]++; } } public static boolean cycle1(int u,boolean[] visit,boolean[] stck) { visit[u] = true; stck[u] = true; for(Integer v:list[u]) { if(visit[v]&&stck[v]) { return true; } if(!visit[v]) { if(cycle1(v,visit,stck)){ return true; } } } stck[u] = false; return false; } public static boolean cycle(boolean[] visit,boolean[] stck) { for(int i=0;i<visit.length;i++) { if(!visit[i]&&cycle1(i,visit,stck)) { return true; } } return false; } public static void dfs(int u,boolean[] visit,int[] ans) { visit[u] = true; int max = 0; for(Integer v:list[u]) { if(!visit[v]) { dfs(v,visit,ans); } max = max(max,ans[v]); } ans[u] = max+1; } static ArrayList<Integer>[] list; public static int random(int min,int max) { return min+(int)((max-min)*Math.random()); } public static void main(String args[]) throws Exception { new Thread(null, new Solution(),"Main",1<<26).start(); } public void run() { InputReader sc = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int t1 = 1; while(t1-->0) { int n = sc.nextInt(); int m = sc.nextInt(); char[][] c = new char[n][]; for(int i=0;i<n;i++) { c[i] = sc.readString().toCharArray(); } height = new int[n+m]; parent = new int[n+m]; for(int i=0;i<n+m;i++) { parent[i] = i; } for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(c[i][j]=='=') { join(i,n+j); } } } int[] hash = new int[n+m]; int ind = 0; for(int i=0;i<n+m;i++) { if(parent[i]==i) { hash[i] = ind++; } } list = new ArrayList[ind]; for(int i=0;i<ind;i++) { list[i] = new ArrayList<>(); } for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { int pi = parent(i); int pj = parent(n+j); if(c[i][j]=='>') { list[hash[pi]].add(hash[pj]); } else if(c[i][j]=='<') { list[hash[pj]].add(hash[pi]); } } } boolean[] visit = new boolean[ind]; boolean[] stack1 = new boolean[ind]; if(cycle(visit,stack1)) { out.println("NO"); } else { out.println("YES"); Arrays.fill(visit,false); int[] ans = new int[ind]; for(int i=0;i<ind;i++) { if(!visit[i]) { dfs(i,visit,ans); } } for(int i=0;i<n;i++) { out.print(ans[hash[parent(i)]]+" "); } out.println(); for(int j=0;j<m;j++) { out.print(ans[hash[parent(n+j)]]+" "); } out.println(); } } out.close(); } }
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 long long MAXN = 2e3 + 69, MOD = 1e9 + 7; char arr[MAXN][MAXN]; long long n, m, mark[MAXN], par[MAXN], sz[MAXN], ans[MAXN]; vector<long long> topol, g[MAXN], rev[MAXN]; long long find(long long v) { if (par[v] == 0) return v; return par[v] = find(par[v]); } void merge(long long v, long long u) { v = find(v), u = find(u); if (v == u) return; if (sz[v] < sz[u]) swap(v, u); par[u] = v, sz[v] += sz[u]; } void dfs(long long v) { mark[v] = 1; for (auto u : g[v]) if (!mark[u]) dfs(u); topol.push_back(v); } int32_t main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> n >> m; for (long long i = 1; i < MAXN; i++) sz[i] = 1; for (long long i = 1; i <= n; i++) for (long long j = 1; j <= m; j++) { cin >> arr[i][j]; if (arr[i][j] == '=') merge(find(i), find(n + j)); } for (long long i = 1; i <= n; i++) for (long long j = 1; j <= m; j++) { if (arr[i][j] == '<') { g[find(i)].push_back(find(n + j)); rev[find(n + j)].push_back(find(i)); } if (arr[i][j] == '>') { g[find(n + j)].push_back(find(i)); rev[find(i)].push_back(find(n + j)); } } for (long long i = 1; i <= n + m; i++) if (!mark[find(i)]) dfs(i); memset(mark, 0, sizeof mark); reverse(topol.begin(), topol.end()); for (long long i = 0; i < (long long)topol.size(); i++) { if (rev[topol[i]].size() == 0) { ans[topol[i]] = 1; continue; } for (auto u : rev[topol[i]]) ans[topol[i]] = max(ans[topol[i]], ans[u] + 1); } for (long long i = 1; i <= n; i++) for (long long j = 1; j <= n; j++) if ((arr[i][j] == '<' and ans[find(i)] >= ans[find(n + j)]) or (arr[i][j] == '=' and ans[find(i)] != ans[find(n + j)]) or (arr[i][j] == '>' and ans[find(i)] <= ans[find(n + j)])) return cout << "No\n", 0; cout << "Yes\n"; for (long long i = 1; i <= n; i++) cout << ans[find(i)] << " "; cout << "\n"; for (long long i = n + 1; 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
#include <bits/stdc++.h> using namespace std; int N, M, n; char a[2000][2000]; bool G[2000][2000]; int comp[2000], C = 0, smaller[2000], val[2000]; queue<int> todo; void eq_DFS(int u) { comp[u] = C; for (int v = 0; v < n; v++) if (a[u][v] == '=' && comp[v] == -1) eq_DFS(v); } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cin >> N >> M; for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) { cin >> a[i][j + N]; if (a[i][j + N] == '=') a[j + N][i] = '='; else if (a[i][j + N] == '<') a[j + N][i] = '>'; else a[j + N][i] = '<'; } n = N + M; for (int i = 0; i < n; i++) comp[i] = -1; for (int i = 0; i < n; i++) { if (comp[i] == -1) { eq_DFS(i); C++; } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (a[i][j] == '<') G[comp[i]][comp[j]] = true; else if (a[i][j] == '>') G[comp[j]][comp[i]] = true; } } for (int i = 0; i < C; i++) { for (int j = 0; j < C; j++) { if (G[i][j]) smaller[j]++; } } int act = 1; while (true) { for (int i = 0; i < C; i++) if (smaller[i] == 0 && val[i] == 0) todo.push(i); if (todo.empty()) break; while (!todo.empty()) { int i = todo.front(); todo.pop(); val[i] = act; for (int j = 0; j < n; j++) if (G[i][j]) smaller[j]--; } act++; } for (int i = 0; i < C; i++) { if (val[i] == 0) { cout << "No" << endl; return 0; } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if ((a[i][j] == '=' && comp[i] != comp[j]) || (a[i][j] == '<' && val[comp[i]] >= val[comp[j]]) || (a[i][j] == '>' && val[comp[i]] <= val[comp[j]])) { cout << "No" << endl; return 0; } } } cout << "Yes" << endl; for (int i = 0; i < N; i++) cout << val[comp[i]] << " "; cout << endl; for (int i = N; i < N + M; i++) cout << val[comp[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; inline int read() { int x = 0, f = 1; char ch = getchar(); for (; !isdigit(ch); ch = getchar()) if (ch == '-') f = -1; for (; isdigit(ch); ch = getchar()) x = x * 10 + ch - '0'; return x * f; } const int N = 2000005; int deg[N], bel[N], fa[N], dis[N], n, m; char s[1005][1005]; struct Tu { int En, head[N], nxt[N], to[N]; void add_edge(int u, int v, int flag) { if (flag) deg[v]++; ++En; nxt[En] = head[u]; to[En] = v; head[u] = En; } } G, T; int find(int x) { return x == fa[x] ? x : fa[x] = find(fa[x]); } bool pd(int cnt, int TOT) { static int q[N]; int head = 0, tail = 0; for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) if (bel[i] == bel[j + n] && s[i][j] != '=') return 0; for (int i = 1; i <= cnt; ++i) if (!deg[i]) q[tail++] = i, dis[i] = 1; while (head < tail) { int u = q[head++]; for (int i = T.head[u]; i; i = T.nxt[i]) { int v = T.to[i]; dis[v] = max(dis[v], dis[u] + 1); --deg[v]; if (!deg[v]) q[tail++] = v; } } if (tail < cnt) return false; cout << "Yes\n"; for (int i = 1; i <= n; ++i) cout << dis[bel[i]] << " "; cout << "\n"; for (int i = n + 1; i <= n + m; ++i) cout << dis[bel[i]] << " "; return true; } int main() { n = read(), m = read(); int cnt = 0; for (int i = 1; i <= n + m; ++i) fa[i] = i * i; 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] == '>') G.add_edge(j + n, i, 0); else if (s[i][j] == '<') G.add_edge(i, j + n, 0); else fa[find(i)] = find(j + n); } for (int i = 1; i <= n + m; ++i) if (fa[i] == i) bel[i] = ++cnt; for (int i = 1; i <= n + m; ++i) if (fa[i] != i) bel[i] = bel[find(i)]; for (int u = 1; u <= n + m; ++u) for (int i = G.head[u]; i; i = G.nxt[i]) { int v = G.to[i]; if (bel[u] != bel[v]) T.add_edge(bel[u], bel[v], 1); } if (!pd(cnt, n + m)) cout << "No"; 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 gourmet { int N, M, nodeN, compN; int[] compID, inEdges, dishScores; boolean[][] adj, rawAdj, equalAdj; gourmet(BufferedReader in, PrintWriter out) throws IOException { StringTokenizer st = new StringTokenizer(in.readLine()); N = Integer.parseInt(st.nextToken()); M = Integer.parseInt(st.nextToken()); nodeN = N + M; rawAdj = new boolean[nodeN][nodeN]; equalAdj = new boolean[nodeN][nodeN]; for (int i = 0; i < N; i++) { String str = in.readLine(); for (int j = 0; j < M; j++) { char c = str.charAt(j); if (c == '>') { rawAdj[N+j][i] = true; } else if (c == '<') { rawAdj[i][N+j] = true; } else { equalAdj[N+j][i] = true; equalAdj[i][N+j] = true; } } } // Generate components compN = 0; compID = new int[nodeN]; Arrays.fill(compID, -1); for (int i = 0; i < nodeN; i++) { if (compID[i] == -1) dfsComp(i, compN++); } // Now, create the actual graph using these components adj = new boolean[compN][compN]; inEdges = new int[compN]; for (int i = 0; i < nodeN; i++) { for (int j = 0; j < nodeN; j++) { if (rawAdj[i][j] && !adj[compID[i]][compID[j]]) { inEdges[compID[j]]++; adj[compID[i]][compID[j]] = true; } } } // Generate topological ordering (if possible) dishScores = new int[compN]; for (int i = 0; i < compN; i++) { if (inEdges[i] == 0) { toEval.add(i); dishScores[i] = 1; } } int c; while (!toEval.isEmpty()) { c = toEval.poll(); // Spread to neighbors for (int i = 0; i < compN; i++) { if (adj[c][i]) { inEdges[i]--; if (inEdges[i] == 0) { dishScores[i] = dishScores[c] + 1; toEval.add(i); } } } } // If it got here, this is probably valid...? // System.out.println(Arrays.toString(inEdges)); for (int i = 0; i < compN; i++) { if (inEdges[i] != 0) { // Not all dishes were rated (cycle exists) out.println("No"); return; } } // Valid out.println("Yes"); for (int i = 0; i < nodeN; i++) { if (i == N) out.println(); else if (i != 0) out.print(' '); out.print(dishScores[compID[i]]); } out.println(); } void dfsComp(int n, int id) { compID[n] = id; for (int i = 0; i < nodeN; i++) { if (equalAdj[n][i] && compID[i] == -1) dfsComp(i, id); } } boolean[] checked; boolean checkEqual(int n) { checked[n] = true; for (int i = 0; i < nodeN; i++) { if (equalAdj[n][i] && !checked[i]) { if (dishScores[i] != dishScores[n]) return false; else if (!checkEqual(i)) return false; } } return true; } Queue<Integer> toEval = new LinkedList<>(); public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); new gourmet(in, out); in.close(); out.close(); } }
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; long long MOD = 1000000007; long double EPS = 1e-9; int binpow(int b, int p, int mod) { int ans = 1; b %= mod; for (; p; p >>= 1) { if (p & 1) ans = ans * b % mod; b = b * b % mod; } return ans; } void pre() {} vector<string> ss; int n, m; vector<vector<int> > g; vector<int> dfsnum, low, st, vis, scc; int num, num_scc, stack_sz; int SCC(int x) { if (dfsnum[x] == -1) low[x] = dfsnum[x] = num++; else return low[x]; st[stack_sz++] = x; for (int i = 0; i < (int)g[x].size(); ++i) if (scc[g[x][i]] == -1) low[x] = min(low[x], SCC(g[x][i])); if (low[x] == dfsnum[x]) { while (scc[x] != num_scc) scc[st[--stack_sz]] = num_scc; ++num_scc; } return low[x]; } void initSCC(int n) { scc.assign(n + 1, -1); dfsnum.assign(n + 1, -1); low.assign(n + 1, -1); st.resize(n + 1); num_scc = num = stack_sz = 0; for (int i = 0; i < n; ++i) SCC(i + 1); } struct UnionFind { int n, set_size, *parent, *rank; UnionFind() {} UnionFind(int a) { n = set_size = a; parent = new int[n + 1]; rank = new int[n + 1]; for (int i = 1; i <= n; ++i) parent[i] = i, rank[i] = 1; } inline int find(int x) { if (x != parent[x]) return parent[x] = find(parent[x]); return x; } inline void merge(int x, int y) { int xroot = find(x), yroot = find(y); if (xroot != yroot) { if (rank[xroot] >= rank[yroot]) { parent[yroot] = xroot; rank[xroot] += rank[yroot]; } else { parent[xroot] = yroot; rank[yroot] += rank[xroot]; } set_size -= 1; } } void reset() { set_size = n; for (int i = 1; i <= n; i++) parent[i] = i, rank[i] = 1; } int size() { return set_size; } }; int rname[100010]; int viss[100010]; vector<int> topo; void mydfs(int nn, int pp) { for (auto v : g[nn]) { if (viss[v] == 0 && v != pp) { viss[v] = 1; mydfs(v, nn); } } topo.emplace_back(nn); } int dgval[100010]; void solve() { int n, m; cin >> n >> m; ss.resize(n); for (int i = 0; i < (n); ++i) { cin >> ss[i]; } g.resize(n + m + 1); UnionFind uf(n + m + 1); for (int i = 0; i < (n); ++i) { for (int j = 0; j < (m); ++j) { if (ss[i][j] == '=') { uf.merge(i + 1, n + j + 1); } } } int curn = 1; for (int i = 1; i <= n + m; ++i) { if (rname[uf.find(i)] == 0) { rname[uf.find(i)] = curn++; } } curn--; int pos = 1; for (int i = 0; i < (n); ++i) { for (int j = 0; j < (m); ++j) { if (ss[i][j] == '<') { if (uf.find(i + 1) == uf.find(n + j + 1)) { {}; pos = 0; } g[rname[uf.find(n + j + 1)]].emplace_back(rname[uf.find(i + 1)]); } else if (ss[i][j] == '>') { if (uf.find(i + 1) == uf.find(n + j + 1)) { {}; pos = 0; } g[rname[uf.find(i + 1)]].emplace_back(rname[uf.find(n + j + 1)]); } } } if (pos == 0) { cout << "No\n"; return; } initSCC(curn); if (num_scc < curn) { cout << "No\n"; return; } cout << "Yes\n"; for (int i = 1; i <= curn; ++i) { if (!viss[i]) { viss[i] = 1; mydfs(i, -1); } } for (int i = 0; i < (topo.size()); ++i) { int nn = topo[i]; dgval[nn] = 1; for (auto v : g[nn]) { (dgval[nn] = max((dgval[nn]), (dgval[v] + 1))); } } for (int i = 1; i <= n; ++i) { cout << dgval[rname[uf.find(i)]] << " "; } cout << '\n'; for (int i = n + 1; i <= m + n; ++i) { cout << dgval[rname[uf.find(i)]] << " "; } } signed main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); pre(); int t = 1; for (int i = 1; i <= t; i++) { 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; int head[2222], num[2222], in[2222], ans[2222]; char M[1111][1111]; struct node { int u, v, next; } e[1111111]; int fa[2222]; int find(int u) { return u == fa[u] ? u : fa[u] = find(fa[u]); } int tot, k; int n, m; void add(int u, int v) { e[tot].v = v; e[tot].next = head[u]; head[u] = tot++; } int toposort() { queue<int> q; int num = 0; for (int i = 1; i <= n + m; i++) if (i == fa[i] && !in[i]) q.push(i), ans[i] = 1, num++; while (!q.empty()) { int u = q.front(); q.pop(); for (int i = head[u]; i != -1; i = e[i].next) { int v = e[i].v; if (--in[v] == 0) { ans[v] = ans[u] + 1; q.push(v); num++; } } } return num; } int main() { while (cin >> n >> m) { tot = 0; for (int i = 1; i <= n + m; i++) head[i] = -1, fa[i] = i, in[i] = 0, ans[i] = 0; for (int i = 0; i < n; i++) { cin >> M[i]; for (int j = 0; j < m; j++) { if (M[i][j] == '=') { int u = find(i + 1), v = find(j + 1 + n); if (u != v) fa[u] = v; } } } k = 0; for (int i = 1; i <= m + n; i++) { if (i == find(i)) num[i] = ++k; } int flag = 1; for (int i = 0; i < n; i++) { if (!flag) break; for (int j = 0; j < m; j++) { if (M[i][j] == '<') { int u = find(i + 1), v = find(j + 1 + n); if (u == v) { flag = 0; cout << "No" << '\n'; break; } add(u, v); in[v]++; } if (M[i][j] == '>') { int u = find(i + 1), v = find(j + 1 + n); if (u == v) { flag = 0; cout << "No" << '\n'; break; } add(v, u); in[u]++; } } } if (flag) { if (toposort() != k) { cout << "No" << endl; continue; } puts("Yes"); for (int i = 1; i <= n + m; i++) { int fx = find(i); cout << ans[fx] << " "; if (i == n) cout << endl; } 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; class UnionFind { public: explicit UnionFind(int size) : m_size(size, 1), m_subgroups(size) { m_parent.reserve(size); for (int i = 0; i < size; ++i) m_parent.push_back(i); } int subgroups() const { return m_subgroups; } int groupSize(int i) { return m_size[root(i)]; } int root(int i) { return (m_parent[i] == i) ? i : (m_parent[i] = root(m_parent[i])); } bool connected(int i, int j) { return root(i) == root(j); } void connect(int i, int j) { int root1 = root(i); int root2 = root(j); if (root1 != root2) { if (m_size[root1] < m_size[root2]) { m_parent[root1] = root2; m_size[root2] += m_size[root1]; } else { m_parent[root2] = root1; m_size[root1] += m_size[root2]; } --m_subgroups; } } private: vector<int> m_parent, m_size; int m_subgroups; }; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); int n, m; cin >> n >> m; cin.ignore(); UnionFind uf(n + m); vector<pair<int, int>> edgeList; edgeList.reserve(n * m); for (int i = 0; i < n; ++i) { string s; cin >> s; cin.ignore(); for (int j = 0; j < m; ++j) { if (s[j] == '=') uf.connect(i, n + j); else if (s[j] == '<') edgeList.emplace_back(i, n + j); else edgeList.emplace_back(n + j, i); } } vector<vector<int>> edges(n + m); vector<int> predCount(n + m); for (auto& p : edgeList) { int r1 = uf.root(p.first), r2 = uf.root(p.second); edges[r1].push_back(r2); ++predCount[r2]; } vector<int> entryPoints; for (int i = 0; i < n + m; ++i) { if (uf.root(i) == i && predCount[i] == 0) entryPoints.push_back(i); } vector<int> eval(n + m); int evalCount = 0; for (int cur = 1; !entryPoints.empty(); ++cur) { vector<int> nextEntryPoints; for (int i : entryPoints) { eval[i] = cur; for (int j : edges[i]) { if (--predCount[j] == 0) { nextEntryPoints.push_back(j); } } } evalCount += entryPoints.size(); entryPoints.swap(nextEntryPoints); } if (evalCount == uf.subgroups()) { cout << "Yes" << endl; for (int i = 0; i < n; ++i) cout << eval[uf.root(i)] << ' '; cout << endl; for (int i = 0; i < m; ++i) cout << eval[uf.root(n + i)] << ' '; cout << endl; } else { cout << "No" << 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
class mergefind: 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 __len__(self): return self.num_sets def toposort(C, n): indeg = [0]*n for i,neighs in enumerate(C): for neigh in neighs: indeg[neigh] += 1 S = [i for i in range(n) if indeg[i] == 0] nparent = indeg[:] topo = [] while S: cur = S.pop() topo.append(cur) for neigh in C[cur]: nparent[neigh] -= 1 if nparent[neigh] == 0: S.append(neigh) # nparent[cur] = -1 return topo n,m = map(int,input().split()) A = [input() for _ in range(n)] mf = mergefind(n+m) # merge equal elements for i in range(n): for j in range(m): if A[i][j] == '=': mf.merge(i,n+j) # Connections: smaller -> larger C = [set() for _ in range(n+m)] for i in range(n): for j in range(m): if A[i][j] == '<': C[mf.find(i)].add(mf.find(n+j)) elif A[i][j] == '>': C[mf.find(n+j)].add(mf.find(i)) # Walk through graph in toposort order # What I'm pointing to must be at least # my value + 1 D = [1]*(n+m) for cur in toposort(C, n+m): for neigh in C[cur]: D[neigh] = max(D[neigh], D[cur]+1) # Propagate values within equal clusters D = [D[mf.find(i)] for i in range(n+m)] # Validate answer ok = True for i in range(n): for j in range(m): if A[i][j] == '<': if D[i] >= D[n+j]: ok = False elif A[i][j] == '>': if D[i] <= D[n+j]: ok = False else: if D[i] != D[n+j]: ok = False if ok: print('Yes') print(*D[:n]) print(*D[n:]) 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> #pragma GCC optimize("O3") #pragma GCC optimize("unroll-loops") #pragma GCC target("avx2") using namespace std; vector<vector<int> > g; vector<vector<int> > g1; vector<set<int> > gcol; vector<int> col; int nw = 0; void dfs(int v) { col[v] = nw; for (auto t : g[v]) if (col[t] == -1) dfs(t); } int main() { ios::sync_with_stdio(false); cin.tie(0); int n, m; cin >> n >> m; col.resize(n + m, -1); g.resize(n + m, vector<int>()); g1.resize(n + m, vector<int>()); char q[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> q[i][j]; if (q[i][j] == '>') g1[i].push_back(n + j); else if (q[i][j] == '<') g1[n + j].push_back(i); else { g[i].push_back(n + j); g[n + j].push_back(i); } } } for (int i = 0; i < n + m; i++) { if (col[i] == -1) { dfs(i); nw++; } } gcol.resize(nw, set<int>()); for (int i = 0; i < n + m; i++) { for (auto t : g1[i]) gcol[col[i]].insert(col[t]); } vector<int> ans(nw, 0); vector<int> us(nw, 0); int ost = nw; for (int i = 1; ost > 0; i++) { vector<int> del; for (int j = 0; j < nw; j++) { if (!us[j] && gcol[j].size() == 0) { ans[j] = i; us[j] = 1; del.push_back(j); ost--; } } if (del.size() == 0) break; for (auto t : del) { for (int j = 0; j < nw; j++) gcol[j].erase(t); } } if (ost > 0) { cout << "No\n"; } else { for (int i = 0; i < n + m; i++) { col[i] = ans[col[i]]; } bool ok = true; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (q[i][j] == '=' && col[i] != col[n + j]) ok = false; if (q[i][j] == '>' && col[i] <= col[n + j]) ok = false; if (q[i][j] == '<' && col[i] >= col[n + j]) ok = false; } } if (!ok) cout << "No"; else { cout << "Yes\n"; for (int i = 0; i < n; i++) cout << col[i] << " "; cout << "\n"; for (int i = n; i < n + m; i++) cout << col[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 cnt[1005][3]; bool comp(int i, int j) { if (cnt[i][2] != cnt[j][2]) return cnt[i][2] < cnt[j][2]; if (cnt[i][1] != cnt[j][1]) return cnt[i][1] < cnt[j][1]; else return cnt[i][0] < cnt[j][0]; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int n, m; cin >> n >> m; string a[n]; vector<int> b(n); for (int i = 0; i < n; i++) b[i] = i; for (int i = 0; i < n; i++) { cin >> a[i]; for (int j = 0; j < m; j++) { if (a[i][j] == '<') cnt[i][0]++; else if (a[i][j] == '>') cnt[i][2]++; else cnt[i][1]++; } } sort(b.begin(), b.end(), comp); for (int j = 0; j < m; j++) { for (int idx = 1; idx <= n - 1; idx++) { char ch = a[b[idx]][j], chp = a[b[idx - 1]][j]; if (chp == '=' && ch == '<') { cout << "No" << endl; return 0; } else if (chp == '>' && (ch == '<' || ch == '=')) { cout << "No" << endl; return 0; } } } vector<int> resa(n), resb(m); for (int j = 0; j < m; j++) { int i = b[0]; if (a[i][j] == '>') resb[j] = 1; else if (a[i][j] == '=') { if (cnt[i][2]) resb[j] = 2; else resb[j] = 1; } if (cnt[i][2]) resa[i] = 2; else resa[i] = 1; } for (int idx = 1; idx <= n - 1; idx++) { int i = b[idx], j = b[idx - 1]; if (cnt[i][2] == cnt[j][2] && cnt[i][1] == cnt[j][1]) { resa[i] = resa[j]; continue; } int mx = resa[j]; for (int t = 0; t < m; t++) mx = max(resb[t], mx); mx = max(mx, resa[j]); mx++; if (cnt[i][2] < cnt[j][2] + cnt[j][1]) { cout << "No" << endl; return 0; } bool yes = false; for (int t = 0; t < m; t++) { if (a[i][t] == '>' && !resb[t]) { yes = true; resb[t] = mx; } } if (yes) mx++; resa[i] = mx; for (int t = 0; t < m; t++) if (a[i][t] == '=') resb[t] = mx; } int mx = resa[b[n - 1]]; mx++; for (int j = 0; j < m; j++) if (resb[j] == 0) resb[j] = mx; cout << "YES" << endl; for (auto it = resa.begin(); it != resa.end(); it++) cout << *it << ' '; cout << endl; ; for (auto it = resb.begin(); it != resb.end(); it++) cout << *it << ' '; 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
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.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author yizheng */ 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); D solver = new D(); solver.solve(1, in, out); out.close(); } static class D { public static int[] topologicalSort(Graph graph) { int count = graph.vertexCount(); int[] order = new int[count]; int[] degree = new int[count]; int[] score = new int[count]; int size = 0; for (int i = 0; i < graph.edgeCount(); i++) { if (!graph.isRemoved(i)) { degree[graph.destination(i)]++; } } for (int i = 0; i < count; i++) { if (degree[i] == 0) { order[size++] = i; score[i] = 1; } } for (int i = 0; i < size; i++) { int current = order[i]; int curScore = score[order[i]]; for (int j = graph.firstOutbound(current); j != -1; j = graph.nextOutbound(j)) { int next = graph.destination(j); if (--degree[next] == 0) { score[next] = curScore + 1; order[size++] = next; } } } if (size != count) { return null; } return score; } public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); int m = in.readInt(); char[][] table = in.readTable(n, m); RecursiveIndependentSetSystem iss = new RecursiveIndependentSetSystem(n + m); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (table[i][j] == '=') { if (iss.get(i) != iss.get(n + j)) { iss.join(i, n + j); } } else { if (iss.get(i) == iss.get(n + j)) { out.print("No"); return; } } } } Graph graph = new Graph(n + m); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (table[i][j] == '<') { graph.addEdge(iss.get(i), iss.get(n + j), 0, 0, -1); } else if (table[i][j] == '>') { graph.addEdge(iss.get(n + j), iss.get(i), 0, 0, -1); } } } int[] res = topologicalSort(graph); if (res == null) { out.print("No"); return; } out.printLine("Yes"); for (int i = 0; i < n; i++) { out.print(res[iss.get(i)]); out.print(" "); } out.printLine(); for (int i = 0; i < m; i++) { out.print(res[iss.get(n + i)]); out.print(" "); } out.printLine(); } } static class RecursiveIndependentSetSystem implements IndependentSetSystem { private final int[] color; private final int[] rank; private int setCount; private IndependentSetSystem.Listener listener; public RecursiveIndependentSetSystem(int size) { color = new int[size]; rank = new int[size]; for (int i = 0; i < size; i++) { color[i] = i; } setCount = size; } public RecursiveIndependentSetSystem(RecursiveIndependentSetSystem other) { color = other.color.clone(); rank = other.rank.clone(); setCount = other.setCount; } public boolean join(int first, int second) { first = get(first); second = get(second); if (first == second) { return false; } if (rank[first] < rank[second]) { int temp = first; first = second; second = temp; } else if (rank[first] == rank[second]) { rank[first]++; } setCount--; color[second] = first; if (listener != null) { listener.joined(second, first); } return true; } public int get(int index) { int start = index; while (color[index] != index) { index = color[index]; } while (start != index) { int next = color[start]; color[start] = index; start = next; } return index; } } 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); } } 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(); } public void print(int i) { writer.print(i); } } static interface Edge { } static class Graph { public static final int REMOVED_BIT = 0; protected int vertexCount; protected int edgeCount; private int[] firstOutbound; private int[] firstInbound; private Edge[] edges; private int[] nextInbound; private int[] nextOutbound; private int[] from; private int[] to; private long[] weight; public long[] capacity; private int[] reverseEdge; private int[] flags; public Graph(int vertexCount) { this(vertexCount, vertexCount); } public Graph(int vertexCount, int edgeCapacity) { this.vertexCount = vertexCount; firstOutbound = new int[vertexCount]; Arrays.fill(firstOutbound, -1); from = new int[edgeCapacity]; to = new int[edgeCapacity]; nextOutbound = new int[edgeCapacity]; flags = new int[edgeCapacity]; } public int addEdge(int fromID, int toID, long weight, long capacity, int reverseEdge) { ensureEdgeCapacity(edgeCount + 1); if (firstOutbound[fromID] != -1) { nextOutbound[edgeCount] = firstOutbound[fromID]; } else { nextOutbound[edgeCount] = -1; } firstOutbound[fromID] = edgeCount; if (firstInbound != null) { if (firstInbound[toID] != -1) { nextInbound[edgeCount] = firstInbound[toID]; } else { nextInbound[edgeCount] = -1; } firstInbound[toID] = edgeCount; } this.from[edgeCount] = fromID; this.to[edgeCount] = toID; if (capacity != 0) { if (this.capacity == null) { this.capacity = new long[from.length]; } this.capacity[edgeCount] = capacity; } if (weight != 0) { if (this.weight == null) { this.weight = new long[from.length]; } this.weight[edgeCount] = weight; } if (reverseEdge != -1) { if (this.reverseEdge == null) { this.reverseEdge = new int[from.length]; Arrays.fill(this.reverseEdge, 0, edgeCount, -1); } this.reverseEdge[edgeCount] = reverseEdge; } if (edges != null) { edges[edgeCount] = createEdge(edgeCount); } return edgeCount++; } protected final GraphEdge createEdge(int id) { return new GraphEdge(id); } public final int vertexCount() { return vertexCount; } public final int edgeCount() { return edgeCount; } public final int firstOutbound(int vertex) { int id = firstOutbound[vertex]; while (id != -1 && isRemoved(id)) { id = nextOutbound[id]; } return id; } public final int nextOutbound(int id) { id = nextOutbound[id]; while (id != -1 && isRemoved(id)) { id = nextOutbound[id]; } return id; } public final int destination(int id) { return to[id]; } public final boolean flag(int id, int bit) { return (flags[id] >> bit & 1) != 0; } public final boolean isRemoved(int id) { return flag(id, REMOVED_BIT); } protected void ensureEdgeCapacity(int size) { if (from.length < size) { int newSize = Math.max(size, 2 * from.length); if (edges != null) { edges = resize(edges, newSize); } from = resize(from, newSize); to = resize(to, newSize); nextOutbound = resize(nextOutbound, newSize); if (nextInbound != null) { nextInbound = resize(nextInbound, newSize); } if (weight != null) { weight = resize(weight, newSize); } if (capacity != null) { capacity = resize(capacity, newSize); } if (reverseEdge != null) { reverseEdge = resize(reverseEdge, newSize); } flags = resize(flags, newSize); } } protected final int[] resize(int[] array, int size) { int[] newArray = new int[size]; System.arraycopy(array, 0, newArray, 0, array.length); return newArray; } private long[] resize(long[] array, int size) { long[] newArray = new long[size]; System.arraycopy(array, 0, newArray, 0, array.length); return newArray; } private Edge[] resize(Edge[] array, int size) { Edge[] newArray = new Edge[size]; System.arraycopy(array, 0, newArray, 0, array.length); return newArray; } protected class GraphEdge implements Edge { protected int id; protected GraphEdge(int id) { this.id = id; } } } static interface IndependentSetSystem { public static interface Listener { public void joined(int joinedRoot, int root); } } }
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; vector<int> par; vector<int> sz; vector<long long> w; vector<vector<char> > a; vector<vector<int> > lessy; vector<vector<int> > more; vector<int> color; vector<bool> used; vector<int> order; bool globok = true; int find_set(int v) { if (par[v] == v) return v; else return par[v] = find_set(par[v]); } void make_set(int v) { par[v] = v; sz[v] = 1; } void union_sets(int a, int b) { a = find_set(a); b = find_set(b); if (a != b) { if (sz[a] < sz[b]) swap(a, b); par[b] = a; sz[a] += sz[b]; } } void dfs(int v) { color[v] = 1; for (int i = 0; i < lessy[v].size(); i++) { int to = lessy[v][i]; if (color[to] == 0) { dfs(to); } else { if (color[to] == 1) { cout << "No"; exit(0); } } } color[v] = 2; order.push_back(v); } int main() { int n, m; cin >> n >> m; w.resize(n + m); par.resize(n + m); a.resize(n); lessy.resize(n + m); color.resize(n + m); more.resize(n + m); used.resize(n + m); sz.resize(n + m); for (int i = 0; i < par.size(); i++) make_set(i); for (int i = 0; i < w.size(); i++) w[i] = -LONG_LONG_MAX; for (int i = 0; i < n; i++) { a[i].resize(m); for (int j = 0; j < m; j++) { cin >> a[i][j]; if (a[i][j] == '=') { union_sets(i, n + j); } } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (a[i][j] != '=') { int x = find_set(n + j); int y = find_set(i); if (a[i][j] == '<') { lessy[x].push_back(y); more[y].push_back(x); } else { lessy[y].push_back(x); more[x].push_back(y); } } } } for (int i = 0; i < n + m; i++) { int it = find_set(i); if (color[it] == 0) dfs(it); } if (!globok) { cout << "No"; return 0; } cout << "Yes" << endl; for (int i = 0; i < order.size(); i++) { long long rate = 0; for (int j = 0; j < lessy[order[i]].size(); j++) { rate = max(rate, w[lessy[order[i]][j]] + 1); } w[order[i]] = rate; } for (int i = 0; i < n; i++) { cout << w[find_set(i)] + 1 << ' '; } cout << endl; for (int i = n; i < n + m; i++) { cout << w[find_set(i)] + 1 << ' '; } }
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 T; int n, m; int num[4001], ans[4001]; char c[2001][2001]; struct Edge { int to, next; } edge[4000001]; int head[4001], sze; int ru[4001], fa[4001]; bool vis[4001]; inline void add(int u, int v) { edge[++sze] = (Edge){v, head[u]}, head[u] = sze; } inline int find(int x) { return fa[x] == x ? fa[x] : fa[x] = find(fa[x]); } inline void hb(int x, int y) { int fx = find(x), fy = find(y); if (fx != fy) fa[fx] = fy; } inline void init() { scanf("%d%d", &n, &m); sze = 0, memset(head, 0, sizeof head), memset(ru, 0, sizeof ru); int i, j; for (i = 1; i <= n + m; i++) { fa[i] = i; } for (i = 1; i <= n; i++) { for (j = 1; j <= m; j++) { cin >> c[i][j]; if (c[i][j] == '=') hb(i, j + n); } } for (i = 1; i <= n; i++) { for (j = 1; j <= m; j++) { int fx = find(i), fy = find(j + n); if (c[i][j] == '>') add(fy, fx), ru[fx]++; if (c[i][j] == '<') add(fx, fy), ru[fy]++; } } } inline void solve() { memset(vis, false, sizeof vis); queue<int> q; int i; for (i = 1; i <= n + m; i++) { int p = find(i); if (!vis[p] && !ru[p]) q.push(p), vis[p] = true, num[p] = 1; } while (!q.empty()) { int u = q.front(); q.pop(); for (i = head[u]; i; i = edge[i].next) { int v = edge[i].to; ru[v]--; if (!ru[v] && !vis[v]) num[v] = num[u] + 1, q.push(v), vis[v] = true; } } int cnt = 0; for (i = 1; i <= n + m; i++) { if (vis[find(i)]) cnt++; } if (cnt != n + m) printf("No\n"); else { printf("Yes\n"); for (i = 1; i <= n; i++) { printf("%d ", num[find(i)]); } printf("\n"); for (i = 1; i <= m; i++) { printf("%d ", num[find(i + n)]); } printf("\n"); } } int main() { init(); solve(); 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; inline int rd() { int x = 0; char c = getchar(); while (!isdigit(c)) c = getchar(); while (isdigit(c)) { x = x * 10 + (c ^ 48); c = getchar(); } return x; } char a[2005][2005]; int n, m, f[2005], tot, hd[2005], deg[2005]; int find(int x) { return x == f[x] ? x : f[x] = find(f[x]); } inline void merge(int x, int y) { f[find(x)] = find(y); } struct edge { int to, nxt; } e[2005 * 2005]; inline void add(int u, int v) { e[++tot].to = v; ++deg[v]; e[tot].nxt = hd[u]; hd[u] = tot; } int cnt, mn[2005]; queue<int> q; inline void toposort() { for (int i = 1; i <= n + m; ++i) if (deg[i] == 0) q.push(i); while (!q.empty()) { ++cnt; int u = q.front(); q.pop(); for (int i = hd[u], v; i; i = e[i].nxt) { --deg[v = e[i].to]; mn[v] = max(mn[v], mn[u] + 1); if (!deg[v]) q.push(v); } } } int main() { n = rd(); m = rd(); for (int i = 1; i <= n + m; ++i) f[i] = i; char c; for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) { c = getchar(); while (c != '>' && c != '<' && c != '=') c = getchar(); a[i][j] = c; if (c == '=') merge(i, j + n); } for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) if (a[i][j] != '=') { if (find(i) == find(j + n)) { puts("No"); return 0; } if (a[i][j] == '<') add(find(i), find(j + n)); else add(find(j + n), find(i)); } toposort(); if (cnt != n + m) { puts("No"); return 0; } puts("Yes"); for (int i = 1; i <= n; ++i) printf("%d ", mn[find(i)] + 1); puts(""); for (int i = 1; i <= m; ++i) printf("%d ", mn[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 sys sys.setrecursionlimit(2000) def dfs1(v, mintime): localtime = mintime vis1[v] = 1 for v2 in range(m): if a[v][v2] == ">": if not vis2[v2]: dfs2(v2, 1) localtime = max(localtime, time2[v2] + 1) for v2 in range(m): if a[v][v2] == "=": if not vis2[v2]: dfs2(v2, localtime) localtime = max(localtime, time2[v2]) time1[v] = localtime def dfs2(v, mintime): localtime = mintime vis2[v] = 1 for v2 in range(n): if a[v2][v] == "<": if not vis1[v2]: dfs1(v2, 1) localtime = max(localtime, time1[v2] + 1) for v2 in range(n): if a[v2][v] == "=": if not vis1[v2]: dfs1(v2, localtime) localtime = max(localtime, time1[v2]) time2[v] = localtime n, m = map(int, input().split()) a = [input() for i in range(n)] time1 = [0] * n time2 = [0] * m vis1 = [0] * n vis2 = [0] * m time = 0 try: for v in range(n): if not time1[v]: dfs1(v, 1) for v in range(m): if not time2[v]: dfs2(v, 1) correct = True for v1 in range(n): for v2 in range(m): if a[v1][v2] == "=" and time1[v1] != time2[v2]: correct = False if a[v1][v2] == ">" and time1[v1] <= time2[v2]: correct = False if a[v1][v2] == "<" and time1[v1] >= time2[v2]: correct = False if correct: print("Yes") print(*time1) print(*time2) else: print("No") except RecursionError: 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
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.StringTokenizer; public class D{ static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { 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; } } static class Dsu { int n; int[] parent; int[] rank; public Dsu(int n) { this.n = n; parent = new int[n]; rank = new int[n]; } public void createSet() { for(int i = 0; i < n; i++) { parent[i] = i; rank[i] = 0; } } public int findParent(int x) { if(parent[x] == x) return x; parent[x] = findParent(parent[x]); return parent[x]; } public void mergeSet(int a,int b) { int pa = findParent(a); int pb = findParent(b); if(pa == pb) return; if(rank[pa] > rank[pb]) { parent[pb] = pa; } else if(rank[pa] < rank[pb]) { parent[pa] = pb; } else { parent[pb] = pa; rank[pa]++; } } } public static int dfs(int s) { vis[s] = true; Iterator<Integer> itr = ar[s].iterator(); int max = 0; while(itr.hasNext()) { int n = itr.next(); if(!vis[n]) { max = Math.max(max,dfs(n)); } else { max = Math.max(max,val[n]); } } val[s] = max+1; return val[s]; } public static boolean isCyclic(int s) { if(recStack[s] == true) return true; if(vis[s] == true) return false; vis[s] = true; recStack[s] = true; Iterator<Integer> itr = ar[s].iterator(); while(itr.hasNext()) { int n = itr.next(); if(isCyclic(n)) { return true; } } recStack[s] = false; return false; } static char mat[][]; static List<Integer> ar[]; static int val[]; static boolean vis[]; static boolean recStack[]; public static void main(String[] args) { OutputStream outputStream = System.out; FastReader sc = new FastReader(); PrintWriter out = new PrintWriter(outputStream); int n = sc.nextInt(); int m = sc.nextInt(); ar = new List[n+m]; for(int i = 0; i < n+m; i++) { ar[i] = new ArrayList<>(); } mat = new char[n][m]; for(int i = 0; i < n; i++) { mat[i] = sc.nextLine().toCharArray(); } vis = new boolean[n+m]; Arrays.fill(vis,false); recStack = new boolean[n+m]; Arrays.fill(recStack,false); val = new int[n+m]; Dsu d = new Dsu(n+m); //System.out.println("Next up finding equality"); d.createSet(); for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { if(mat[i][j] == '=') { d.mergeSet(i, n+j); } } } //System.out.println("Next up graph building"); int pi = -1,pj = -1; for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { pi = d.findParent(i); pj = d.findParent(n+j); if(mat[i][j] == '>') { ar[pi].add(pj); } else if(mat[i][j] == '<') { ar[pj].add(pi); } else { continue; } } } //System.out.println("Next up cyclic nature"); for(int i = 0; i < n+m; i++) { if(!vis[d.findParent(i)]) { if(isCyclic(d.findParent(i))) { out.println("No"); out.close(); return; } } } Arrays.fill(vis,false); //System.out.println("Next up dfs"); for(int i = 0; i < n+m; i++) { if(!vis[d.findParent(i)]) dfs(d.findParent(i)); } out.println("Yes"); for(int i = 0; i < n; i++) { out.print(val[d.findParent(i)]+" "); } out.println(); for(int i = n; i < n+m; i++) { out.print(val[d.findParent(i)]+" "); } out.close(); } }
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 = 2e3 + 5, mod = 998244353; template <class o> inline void qr(o &x) { x = 0; char c = getchar(); int f = 1; while (c < '0' || c > '9') { if (c == '-') f = -1; c = getchar(); } while (c >= '0' && c <= '9') { x = x * 10 + (c ^ 48); c = getchar(); } x *= f; } template <class o> void qw(o x) { if (x / 10) qw(x / 10); putchar(x % 10 + 48); } template <class o> void pr1(o x) { if (x < 0) putchar('-'), x = -x; qw(x); putchar(' '); } template <class o> void pr2(o x) { if (x < 0) putchar('-'), x = -x; qw(x); puts(""); } inline int ksm(int a, int b = mod - 2) { int ans = 1; for (; b; b >>= 1, a = 1ll * a * a % mod) if (b & 1) ans = 1ll * ans * a % mod; return ans; } inline int add(int a, int b) { return a += b, a >= mod ? a - mod : a; } inline int sub(int a, int b) { return a -= b, a < 0 ? a + mod : a; } int fa[N], d[N], edg[N][N], q[N], ans[N]; char s[N][N]; int get(int x) { return x == fa[x] ? x : fa[x] = get(fa[x]); } void solve() { int n, m; qr(n), qr(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] == '=') fa[get(j + n)] = get(i); for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) if (s[i][j] != '=') { int x = get(i), y = get(j + n); if (x == y) { puts("No"); return; } if (s[i][j] == '>') { if (!edg[y][x]) edg[y][x] = 1, ++d[x]; } else if (!edg[x][y]) edg[x][y] = 1, ++d[y]; } int l = 1, r = 0; for (int i = 1; i <= n + m; ++i) if (!d[i] && i == get(i)) q[++r] = i, ans[i] = 1; for (int x = q[l]; l <= r; x = q[++l]) { for (int y = 1; y <= n + m; ++y) if (edg[x][y]) { --edg[x][y]; --d[y]; ans[y] = max(ans[y], ans[x] + 1); if (!d[y]) q[++r] = y; } } for (int i = 1; i <= n + m; ++i) if (d[i]) { puts("No"); return; } puts("Yes"); for (int i = 1; i <= n + m; ++i) ans[i] = ans[get(i)]; for (int i = 1; i <= n; ++i) pr1(ans[i]); puts(""); for (int i = 1; i <= m; ++i) pr1(ans[i + n]); } int main() { solve(); 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 N = 2005; string str[N]; int pr[N]; int find(int r) { if (pr[r] == r) return r; else return pr[r] = find(pr[r]); } vector<pair<int, int> > edges; set<int> g[N]; int vis[N]; void dfs(int node) { vis[node] = 1; for (int i : g[node]) { if (vis[i] == 2) continue; if (vis[i] == 1) { cout << "No\n"; exit(0); } dfs(i); } vis[node] = 2; } int dis[N], deg[N]; int main() { ios_base::sync_with_stdio(0); cin.tie(nullptr); int n, m; cin >> n >> m; for (int i = 0; i < n + m; i++) pr[i] = i; for (int i = 0; i < n; i++) { cin >> str[i]; for (int j = 0; j < m; j++) { if (str[i][j] == '<') { edges.push_back(make_pair(i, n + j)); } else if (str[i][j] == '>') { edges.push_back(make_pair(n + j, i)); } else { int u = find(i); int v = find(n + j); pr[v] = u; } } } for (int i = 0; i < edges.size(); i++) { int u = edges[i].first; int v = edges[i].second; if (find(u) == find(v)) { cout << "No\n"; return 0; } u = find(u); v = find(v); if (g[u].find(v) == g[u].end()) { g[u].insert(v); deg[v]++; } } for (int i = 0; i < n + m; i++) { if (find(i) == i and vis[i] == 0) { dfs(i); } } queue<int> Q; for (int i = 0; i < n + m; i++) { if (find(i) != i) continue; if (deg[i] == 0) Q.push(i); } while (!Q.empty()) { int node = Q.front(); Q.pop(); int cur = dis[node]; for (int i : g[node]) { dis[i] = max(dis[i], 1 + cur); deg[i]--; if (deg[i] == 0) Q.push(i); } } cout << "Yes\n"; for (int i = 0; i < n; i++) { cout << dis[find(i)] + 1 << " "; } cout << "\n"; for (int i = 0; i < m; i++) { cout << dis[find(i + n)] + 1 << " "; } 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; template <typename S, typename T> ostream &operator<<(ostream &out, pair<S, T> const &p) { out << p.first << " " << p.second; return out; } template <typename T> ostream &operator<<(ostream &out, vector<T> const &v) { long long int l = v.size(); for (long long int i = 0; i < l - 1; i++) out << v[i] << ' '; if (l > 0) out << v[l - 1]; return out; } template <typename T> void trace(const char *name, T &&arg1) { cout << name << " : " << arg1 << "\n"; } template <typename T, typename... Args> void trace(const char *names, T &&arg1, Args &&...args) { const char *comma = strchr(names + 1, ','); cout.write(names, comma - names) << " : " << arg1 << " | "; trace(comma + 1, args...); } vector<long long int> adj[2000]; long long int comp[2000]; bool v[2000]; void dfs(long long int second, long long int com) { v[second] = 1; comp[second] = com; for (auto &e : adj[second]) { if (v[e] == 0) { dfs(e, com); } } } vector<long long int> adj1[2000]; vector<long long int> top; bool first = 1; long long int vis[2000]; void dfs1(long long int second) { vis[second] = 1; for (auto &e : adj1[second]) { if (vis[e] == 0) dfs1(e); else if (vis[e] == 1) first = 0; } top.push_back(second); vis[second] = 2; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); long long int n, m; cin >> n >> m; char arr[n][m]; for (long long int i = 0; i < n; i++) { for (long long int j = 0; j < m; j++) cin >> arr[i][j]; } for (long long int i = 0; i < n; i++) { for (long long int j = 0; j < m; j++) { if (arr[i][j] == '=') { adj[i].push_back(n + j); adj[n + j].push_back(i); } } } long long int com = 0; for (long long int i = 0; i < n + m; i++) { if (v[i] == 0) { dfs(i, com); com++; } } for (long long int i = 0; i < n; i++) { for (long long int j = 0; j < m; j++) { if (arr[i][j] == '>') { adj1[comp[i]].push_back(comp[n + j]); } else if (arr[i][j] == '<') { adj1[comp[n + j]].push_back(comp[i]); } } } for (long long int i = 0; i < com; i++) { if (vis[i] == 0) dfs1(i); } if (first == 0) { cout << "No\n"; return 0; } reverse(top.begin(), top.end()); long long int dp[com]; for (long long int i = com - 1; i >= 0; i--) { long long int node = top[i]; dp[node] = 1; long long int maxi = 0; for (auto &e : adj1[node]) { maxi = max(maxi, dp[e]); } dp[node] += maxi; } cout << "Yes\n"; for (long long int i = 0; i < n; i++) { cout << dp[comp[i]] << ' '; } cout << "\n"; for (long long int i = 0; i < m; i++) { cout << dp[comp[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
#include <bits/stdc++.h> using namespace std; const int maxn = 1005; int n, m; char c; vector<pair<int, int> > vec[maxn * 2]; int du[maxn * 2]; int dis[maxn * 2], vis[maxn * 2], cnt[maxn * 2]; const int INF = 0x3f3f3f3f; bool spfa(int s) { memset(dis, -1, sizeof(dis)); memset(vis, 0, sizeof(vis)); queue<int> que; que.push(s); dis[s] = 0; vis[s] = 1; cnt[s] = 1; while (!que.empty()) { int u = que.front(); que.pop(); vis[u] = 0; for (int i = 0; i < vec[u].size(); i++) { int v = vec[u][i].first, cost = vec[u][i].second; if (dis[v] < dis[u] + cost) { dis[v] = dis[u] + cost; if (!vis[v]) { cnt[v]++; if (cnt[v] >= n + m + 1) return 0; vis[v] = 1; que.push(v); } else { } } } } return 1; } int main() { 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 == '>') { vec[j + n].push_back(make_pair(i, 1)); } else if (c == '<') { vec[i].push_back(make_pair(j + n, 1)); } else { vec[j + n].push_back(make_pair(i, 0)); vec[i].push_back(make_pair(j + n, 0)); } } } for (int i = 1; i <= n + m; i++) { vec[0].push_back(make_pair(i, 1)); } bool ok = spfa(0); if (ok) { for (int i = 1; i <= n + m; i++) { if (dis[i] == -1) { ok = false; break; } } } if (ok) { puts("Yes"); for (int i = 1; i <= n; i++) { printf("%d ", dis[i]); } printf("\n"); for (int i = n + 1; i <= n + m; i++) { printf("%d ", dis[i]); } printf("\n"); } else { puts("No"); } 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("Ofast") using namespace std; const long long Mod = 1000000007LL, INF = 1e9, LINF = 1e18; const long double Pi = 3.141592653589793116, EPS = 1e-9, Gold = ((1 + sqrt(5)) / 2); long long keymod[] = {1000000007LL, 1000000009LL, 1000000021LL, 1000000033LL}; long long keyCount = sizeof(keymod) / sizeof(long long); mt19937 rng32(chrono::steady_clock::now().time_since_epoch().count()); mt19937_64 rng64(chrono::steady_clock::now().time_since_epoch().count()); template <class T> int getbit(T s, int i) { return (s >> i) & 1; } template <class T> T onbit(T s, int i) { return s | (T(1) << i); } template <class T> T offbit(T s, int i) { return s & (~(T(1) << i)); } template <class T> int cntbit(T s) { return __builtin_popcountll(s); } auto TimeStart = chrono::steady_clock::now(); auto TimeEnd = chrono::steady_clock::now(); void ControlIO(int argc, char* argv[]); void TimerStart(); void TimerStop(); void Exit(); string cppstr_infile = "FILE.IN"; string cppstr_outfile = "FILE.OUT"; long long n, m; vector<vector<char>> a; vector<vector<long long>> W; map<pair<long long, long long>, set<pair<long long, long long>>> adjOut, adjIn; map<pair<long long, long long>, pair<long long, long long>> DSUpar; map<pair<long long, long long>, long long> DSUsize; map<pair<long long, long long>, vector<pair<long long, long long>>> DSUlist; pair<long long, long long> DSUfind(pair<long long, long long> ID) { while (DSUpar.find(ID) != DSUpar.end()) ID = DSUpar[ID]; return ID; } void DSUmerge(pair<long long, long long> x, pair<long long, long long> y) { x = DSUfind(x); y = DSUfind(y); if (x == y) return; if (DSUsize[x] < DSUsize[y]) swap(x, y); DSUpar[y] = x; DSUsize[x] += DSUsize[y]; for (auto z : DSUlist[y]) DSUlist[x].push_back(z); } bool DFS(pair<long long, long long> z, map<pair<long long, long long>, long long>& vis) { vis[z] = 2; W[z.first][z.second] = 1; for (auto it = adjOut[z].begin(); it != adjOut[z].end(); it++) { pair<long long, long long> t = *it; if (vis[t] == 1) { W[z.first][z.second] = max(W[z.first][z.second], W[t.first][t.second] + 1); continue; } if (vis[t] == 2) return true; bool hasCycle = DFS(t, vis); if (hasCycle) return true; W[z.first][z.second] = max(W[z.first][z.second], W[t.first][t.second] + 1); } for (auto t : DSUlist[z]) W[t.first][t.second] = W[z.first][z.second]; vis[z] = 1; return false; } bool Toposort() { map<pair<long long, long long>, long long> vis; for (long long i = 0; i < n; i++) vis[make_pair(0, i)] = 0; for (long long j = 0; j < m; j++) vis[make_pair(1, j)] = 0; for (long long i = 0; i < n; i++) { if (vis[make_pair(0, i)]) continue; if (DSUfind(make_pair(0, i)) != make_pair(0LL, i)) continue; bool hasCycle = DFS(make_pair(0, i), vis); if (hasCycle) return false; } for (long long j = 0; j < m; j++) { if (vis[make_pair(1, j)]) continue; if (DSUfind(make_pair(1, j)) != make_pair(1LL, j)) continue; bool hasCycle = DFS(make_pair(1, j), vis); if (hasCycle) return false; } return true; } void Input() { cin >> n >> m; a.resize(n, vector<char>(m, '=')); W.resize(2); W[0].resize(n, -LINF); W[1].resize(m, -LINF); for (long long i = 0; i < n; i++) { for (long long j = 0; j < m; j++) { cin >> a[i][j]; } } for (long long i = 0; i < n; i++) { DSUsize[make_pair(0, i)] = 1; DSUlist[make_pair(0, i)].push_back(make_pair(0, i)); } for (long long j = 0; j < m; j++) { DSUsize[make_pair(1, j)] = 1; DSUlist[make_pair(1, j)].push_back(make_pair(1, j)); } } void Solve() { for (long long i = 0; i < n; i++) { for (long long j = 0; j < m; j++) { if (a[i][j] == '=') DSUmerge(make_pair(0, i), make_pair(1, j)); } } for (long long i = 0; i < n; i++) { for (long long j = 0; j < m; j++) { if (DSUfind(make_pair(0, i)) != DSUfind(make_pair(1, j))) continue; if (a[i][j] != '=') { cout << "No\n"; return; } } } for (long long i = 0; i < n; i++) { for (long long j = 0; j < m; j++) { if (a[i][j] == '>') { adjOut[DSUfind(make_pair(0, i))].insert(DSUfind(make_pair(1, j))); adjIn[DSUfind(make_pair(1, j))].insert(DSUfind(make_pair(0, i))); } if (a[i][j] == '<') { adjOut[DSUfind(make_pair(1, j))].insert(DSUfind(make_pair(0, i))); adjIn[DSUfind(make_pair(0, i))].insert(DSUfind(make_pair(1, j))); } } } if (!Toposort()) { cout << "No\n"; return; } cout << "Yes\n"; for (long long x = 0; x < 2; x++) { for (auto z : W[x]) cout << z << " "; cout << '\n'; } } int main(int argc, char* argv[]) { ControlIO(argc, argv); ios_base::sync_with_stdio(0); cin.tie(NULL); Input(); TimerStart(); Solve(); TimerStop(); return 0; } void ControlIO(int argc, char* argv[]) { char* infile = new char[cppstr_infile.size() + 1]; char* outfile = new char[cppstr_outfile.size() + 1]; strcpy(infile, cppstr_infile.c_str()); strcpy(outfile, cppstr_outfile.c_str()); } void TimerStart() {} void TimerStop() {} void Exit() { TimerStop(); exit(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.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * @description: 模拟搜索(dfs、dsu、dp、……) * @Auther: wuxianhui * @Create: 2019/3/6 09:06 */ public class SimulationSearch { private static short[] scoresArray; private static short[] equalLeaderArray; private static short[] equalLeaderCountArray; private static short[] inDegreeArray; private static List<Set<Short>> betterList = new ArrayList<>(); public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)) ; String input = br.readLine(); String[] temp = input.split("\\s+"); if (temp.length>=2){ short firstDayTastes = Short.parseShort(temp[0]); short secondDayTastes = Short.parseShort(temp[1]); short totalNum = (short) (firstDayTastes + secondDayTastes); scoresArray = new short[totalNum]; equalLeaderArray = new short[totalNum]; equalLeaderCountArray = new short[totalNum]; inDegreeArray = new short[totalNum]; for (short i = 0; i < totalNum; i++){ scoresArray[i] = 0; equalLeaderArray[i] = i; equalLeaderCountArray[i] = 1; inDegreeArray[i]= 0; betterList.add(null); } List<String> compareList = new ArrayList<>(); for (short i = 0; i < firstDayTastes; i++) { input = br.readLine(); compareList.add(input); } // 合并相等关系 for (short i = 0; i < firstDayTastes; i++) { input = compareList.get(i); for (short j = 0; j < secondDayTastes; j++){ if('='==input.charAt(j)){ short secondIndex = (short) (firstDayTastes+j); updateEqualEvent(i, secondIndex); } } } // 构建关系图 boolean success = true; for (short i = 0; i < firstDayTastes; i++){ input = compareList.get(i); for (short j = 0; j < secondDayTastes; j++){ short secondIndex = (short) (firstDayTastes+j); if ('>'==input.charAt(j)){ success = updateBetterEvent(i, secondIndex); } else if('<'==input.charAt(j)){ success = updateBetterEvent(secondIndex, i); } if (!success){ break; } } if (!success){ break; } } // 计算评分 if (success){ Set<Short> firstLeaders = new HashSet<>(); for (short i = 0; i < totalNum; i++){ short leader = findEqualLeader(i); if (inDegreeArray[leader]==0 && !firstLeaders.contains(leader)){ firstLeaders.add(leader); } } // 从顶点开始更新,先更新leader的值,采用拓扑排序算法(有环则更新不完) updateLeaderScore(firstLeaders); // 补充更新非leader的值 for (short i = 0; i < totalNum; i++){ if (scoresArray[i]>0){ continue; } short leader = findEqualLeader(i); if (scoresArray[leader]<=0){ // 存在环,导致leader未赋值 success = false; break; } scoresArray[i] = scoresArray[leader]; } } // 打印结果 if (success){ System.out.println("Yes"); for (short i = 0; i < firstDayTastes; i++){ if (i>0){ System.out.print(" " + scoresArray[i]); } else{ System.out.print(scoresArray[i]); } } System.out.println(""); for (short i = firstDayTastes; i < totalNum; i++){ if (i>firstDayTastes){ System.out.print(" " + scoresArray[i]); } else{ System.out.print(scoresArray[i]); } } System.out.println(""); } else{ System.out.println("No"); } } br.close(); } /** * 处理大于关系 * @param betterIndex * @param poorerIndex * @return */ private static boolean updateBetterEvent(short betterIndex, short poorerIndex){ // 在同一层的leader节点构建better关系图,采用集合保存直接大于当前节点的其他节点 short betterLeader = findEqualLeader(betterIndex); short poorLeader = findEqualLeader(poorerIndex); if (betterLeader==poorLeader){ // 关系冲突 return false; } Set<Short> upperSet = betterList.get(poorLeader); if (upperSet==null){ upperSet = new HashSet<>(); betterList.set(poorLeader, upperSet); } if (!upperSet.contains(betterLeader)) { upperSet.add(betterLeader); inDegreeArray[betterLeader] ++; } return true; } /** * 处理等于关系:dsu-合并群组 * @param firstIndex * @param secondIndex * @return */ private static boolean updateEqualEvent(short firstIndex, short secondIndex){ // 添加相等关系,采用dsu(并查集)结构 short firstLeader = findEqualLeader(firstIndex); short secondLeader = findEqualLeader(secondIndex); if (firstLeader!=secondLeader){ // 相等合并 if (equalLeaderCountArray[firstLeader]>equalLeaderCountArray[secondLeader]){ equalLeaderArray[secondLeader] = firstLeader; } else{ if (equalLeaderCountArray[firstLeader]==equalLeaderCountArray[secondLeader]){ equalLeaderCountArray[secondLeader] ++; } equalLeaderArray[firstLeader] = secondLeader; } } return true; } /** * dsu:查找相等群组leader,压缩路径,并同步better节点以及最差节点标识 * @param index * @return */ private static short findEqualLeader(short index){ if (equalLeaderArray[index]==index){ return index; } short leader = findEqualLeader(equalLeaderArray[index]); if (equalLeaderArray[index]!=leader){ equalLeaderArray[index] = leader; } return leader; } /** * 从一个leader节点触发,级联更新其他相关节点的分数。采用dfs深度搜索的方式 * @param currLeaders 第一批(入度为0)leader集合 * @return */ private static void updateLeaderScore(Set<Short> currLeaders){ short score = 1; Set<Short> tempLeaders = new HashSet<>(); while (!currLeaders.isEmpty()){ for (short leader : currLeaders){ scoresArray[leader] = score; Set<Short> betterSet = betterList.get(leader); if (betterSet!=null && betterSet.size()>0){ for (short betterIndex : betterSet){ // 删边 inDegreeArray[betterIndex] --; // 边删完了再设值,避免重复设置,且取的是最大值 if (inDegreeArray[betterIndex]==0){ tempLeaders.add(betterIndex); } } } } currLeaders.clear(); currLeaders.addAll(tempLeaders); tempLeaders.clear(); score ++; } } }
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
def prov(mass, now): check = True for i in range(n): for k in range(m): if now[i][k] == '>' and mass[i] <= mass[n + k]: check = False break elif now[i][k] == '<' and mass[i] >= mass[n + k]: check = False break elif now[i][k] == '=' and mass[i] != mass[n + k]: check = False break if not check: break return check def prog(mass, n, m): prov = True for i in range(1, m): for k in range(n): if mass[i][k] < mass[i - 1][k]: prov = False break if not prov: break if not prov: return False else: mass_new = [] for i in range(1, m): mass_n = [] for k in range(n): mass_n.append(mass[i][k] - mass[i - 1][k]) mass_new.append(max(mass_n)) arr = [1 for i in range(m)] now = 1 if 1 in mass[0][:-1]: now += 1 arr = [2 for i in range(m)] for i in range(1, m): now += mass_new[i - 1] arr[mass[i][-1]] = now return arr n, m = map(int, input().split()) if n + m <= 6: now = [] for i in range(n): now.append(input()) ppp = True for i1 in range(n + m): for i2 in range(n + m): for i3 in range(n + m): for i4 in range(n + m): for i5 in range(n + m): for i6 in range(n + m): mass = [i1 + 1, i2 + 1, i3 + 1, i4 + 1, i5 + 1, i6 + 1][:n + m] if prov(mass, now) and ppp: print('Yes') print(*mass[:n]) print(*mass[n:]) ppp = False if ppp: print('No') else: mass = [[] for i in range(m)] mass1 = [[] for i in range(n)] for i in range(n): now = input() for k in range(m): if now[k] == '<': mass[k].append(1) mass1[i].append(-1) elif now[k] == '=': mass[k].append(0) mass1[i].append(0) else: mass[k].append(-1) mass1[i].append(1) for i in range(m): mass[i].append(i) for i in range(n): mass1[i].append(i) mass.sort() mass1.sort() arr = prog(mass, n, m) arr1 = prog(mass1, m, n) if arr == False or arr1 == False: print('No') else: print('Yes') print(*arr1) print(*arr)
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.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; import java.util.StringTokenizer; public class temp4 { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { 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; } } /* static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } */ static class Print { private final BufferedWriter bw; public Print() { bw=new BufferedWriter(new OutputStreamWriter(System.out)); } public void print(String str)throws IOException { bw.append(str); } public void println(String str)throws IOException { print(str); bw.append("\n"); } public void close()throws IOException { bw.close(); }} static int[]pa; public static void main(String[] args) throws IOException { FastReader scn=new FastReader(); Print pr=new Print(); int n=scn.nextInt(),m=scn.nextInt(); pa=new int[n+m+1]; for(int i=1;i<=n+m;i++){ pa[i]=i; } String[] arr=new String[n+1]; for(int i=1;i<=n;i++){ arr[i]=scn.next(); } for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++){ if(arr[i].charAt(j-1)=='=')pa[find(i)]=find(n+j); } } ArrayList<Integer>[] gr=new ArrayList[n+m+1]; for(int i=1;i<=n+m;i++){ gr[i]=new ArrayList<>(); } int[] rnk=new int[n+m+1]; for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++){ int x=find(i),y=find(n+j); if(arr[i].charAt(j-1)=='>'){ gr[y].add(x);rnk[x]++; } if(arr[i].charAt(j-1)=='<'){ gr[x].add(y);rnk[y]++; } } } Queue<Integer> q=new LinkedList<>(); int cnt=0; for(int i=1;i<=n+m;i++){ if(pa[i]==i){ cnt++; if(rnk[i]==0)q.add(i); } } int[] id=new int[n+m+1]; while(!q.isEmpty()){ int x=q.poll();cnt--; for(int i=0;i<gr[x].size();i++){ int ngb=gr[x].get(i); rnk[ngb]--; if(rnk[ngb]==0){ q.add(ngb); id[ngb]=id[x]+1; } } } if(cnt>0){ pr.println("No"); } else{ pr.println("Yes"); for(int i=1;i<=n;i++){ pr.print((id[find(i)]+1)+" "); } pr.println(""); for(int i=1;i<=m;i++){ pr.print((id[find(n+i)]+1)+" "); } } pr.close(); } public static int find(int x){ if(pa[x]==x)return x; return pa[x]=find(pa[x]); } public static class node{ int a; int b; public node(int a,int b){ this.a=a;this.b=b; } } }
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; vector<int> v[3005]; int r[3005]; int f(int a) { if (r[a] == a) return a; else return r[a] = f(r[a]); } void u(int a, int b) { a = f(a); b = f(b); if (a == b) return; r[a] = b; } vector<int> o[3005], in[3005]; vector<int> top; int st[3005]; bool ff; void dfs(int node) { if (st[node] == 1) { ff = true; return; } if (st[node] == 2) return; st[node] = 1; for (auto u : o[node]) { dfs(u); } top.push_back(node); st[node] = 2; return; } int ans[3005]; int main() { ios_base::sync_with_stdio(0); cin.tie(0); ; cout.tie(0); long long n, m; memset(st, 0, sizeof st); memset(ans, -1, sizeof ans); cin >> n >> m; for (int i = 1; i <= n + m; i++) { r[i] = i; } string s[n + 1]; for (int i = 1; i <= n; i++) { cin >> s[i]; int p = n + 1; for (auto x : s[i]) { int a = f(i), b = f(p); if (x == '=') { u(a, b); } p++; } } for (int i = 1; i <= n; i++) { int p = n + 1; for (auto x : s[i]) { int a = f(i), b = f(p); if (x == '=') { } else if (x == '<') { int a = f(i), b = f(p); if (a == b) { ff = true; } o[a].push_back(b); in[b].push_back(a); } else { int a = f(i), b = f(p); if (a == b) { ff = true; } swap(a, b); o[a].push_back(b); in[b].push_back(a); } p++; } } for (int i = 1; i <= n + m; i++) { if (f(i) == i && st[i] == 0) { dfs(i); } } if (ff) { cout << "No"; return 0; } cout << "Yes\n"; reverse(top.begin(), top.end()); for (int u : top) { int mx = 0; for (auto x : in[u]) { if (ans[x] != -1) { mx = max(ans[x], mx); } } ans[u] = mx + 1; } for (int i = 1; i <= n + m; i++) { cout << ans[f(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
#include <bits/stdc++.h> using namespace std; const long long inf = 0x3f3f3f3f; const int mx = 2000 + 10; int fa[mx], ma[mx][mx], co[mx], score[mx]; int n, m; char str[mx]; vector<int> ve[mx]; queue<int> qu; int find(int x) { return x == fa[x] ? x : fa[x] = find(fa[x]); } int main() { scanf("%d%d", &n, &m); for (int i = 1; i <= n + m; i++) { fa[i] = i; score[i] = co[i] = 0; } for (int i = 1; i <= n; i++) { scanf("%s", str + 1); for (int j = 1; j <= m; j++) { if (str[j] == '>') ma[i][j + n] = 1; else if (str[j] == '<') ma[i][j + n] = -1; else { int a = find(i), b = find(j + n); fa[a] = b; } } } int a, b; bool ok = 1; for (int i = 1; i <= n && ok; i++) { for (int j = 1 + n; j <= n + m && ok; j++) { a = find(i); b = find(j); if (ma[i][j] == 1) { if (a == b) { ok = 0; break; } co[a]++; ve[b].push_back(a); } else if (ma[i][j] == -1) { if (a == b) { ok = 0; break; } co[b]++; ve[a].push_back(b); } } } if (ok == 0) { puts("No"); return 0; } for (int i = 1; i <= n + m; i++) { if (i == find(i) && co[i] == 0) { score[i] = 1; qu.push(i); } } int te; while (!qu.empty()) { te = qu.front(); qu.pop(); for (int i = 0; i < ve[te].size(); i++) { int v = ve[te][i]; co[v]--; if (co[v] == 0) { score[v] = score[te] + 1; qu.push(v); } } } for (int i = 1; i <= n + m; i++) { if (i == find(i) && score[i] == 0) { puts("No"); return 0; } } puts("Yes"); for (int i = 1; i <= n; i++) { int a = find(i); if (i == 1) printf("%d", score[a]); else printf(" %d", score[a]); } puts(""); for (int i = 1; i <= m; i++) { int a = find(i + n); if (i == 1) printf("%d", score[a]); else printf(" %d", score[a]); } 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 int N = 1e4 + 5; const int M = 1e6 + 5; int n, m; char ch[N][N]; int fa[N], num[N], d[N], d2[N]; int Next[M], ver[M], tot, head[N], ans; int find(int x) { return x == fa[x] ? x : fa[x] = find(fa[x]); } void add(int x, int y) { ver[++tot] = y; Next[tot] = head[x]; head[x] = tot; } queue<int> q; void topu() { for (int i = 0; i < n + m; i++) { if (d[i] == 0 && d2[i]) { q.push(i); num[i] = 1; } if (d[i] == 0 && d2[i] == 0) ans++; } while (q.size()) { int x = q.front(); q.pop(); ans++; for (int i = head[x]; i; i = Next[i]) { int y = ver[i]; if (--d[y] == 0) { q.push(y); num[y] = num[x] + 1; } } } } int main() { scanf("%d%d", &n, &m); for (int i = 0; i < n; i++) scanf("%s", ch[i]); for (int i = 0; i <= n + m; i++) fa[i] = i, num[i] = 1; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (ch[i][j] == '=') { if (find(i) != find(n + j)) fa[find(i)] = find(n + j); } } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (ch[i][j] == '<' || ch[i][j] == '>') { if (find(i) == find(n + j)) { cout << "No" << endl; return 0; } } if (ch[i][j] == '<') { add(find(i), find(n + j)); d[find(n + j)]++; d2[find(i)]++; } else if (ch[i][j] == '>') { add(find(n + j), find(i)); d[find(i)]++; d2[find(n + j)]++; } } } topu(); if (ans != n + m) { cout << "No" << endl; return 0; } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (ch[i][j] == '=') { num[i] = num[find(i)]; num[n + j] = num[find(n + j)]; } } } cout << "Yes" << endl; for (int i = 0; i < n; i++) cout << num[i] << " "; cout << endl; for (int i = n; i < n + m; i++) cout << num[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; const int INF = 0x3f3f3f3f; int grid[1010][1010]; int id[2010]; int sz[2010]; int ans[2020]; vector<int> nodes[2020]; int vis[2020]; int deg[2020]; bool flag = false; void dfs(int v) { vis[v] = 1; for (auto x : nodes[v]) { if (vis[x] == 1) flag = true; if (vis[x]) continue; dfs(x); } vis[v] = 2; } int find(int a) { if (id[a] == a) return a; return id[a] = find(id[a]); } void join(int a, int b) { a = find(a); b = find(b); if (a == b) return; if (sz[a] < sz[b]) swap(a, b); id[b] = id[a]; sz[a] += sz[b]; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int n, m; cin >> n >> m; for (int i = 0; i < n + m; i++) { id[i] = i; sz[i] = 1; } string lol; getline(cin, lol); for (int i = 0; i < n; i++) { getline(cin, lol); for (int j = 0; j < m; j++) { if (lol[j] == '=') grid[i][j] = 0; if (lol[j] == '<') grid[i][j] = -1; if (lol[j] == '>') grid[i][j] = 1; } } for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) if (grid[i][j] == 0) join(i, j + n); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (grid[i][j] == 1) { nodes[find(j + n)].push_back(find(i)); deg[find(i)]++; } else if (grid[i][j] == -1) { nodes[find(i)].push_back(find(j + n)); deg[find(j + n)]++; } } } for (int i = 0; i < n + m; i++) { if (vis[find(i)]) continue; dfs(find(i)); } if (flag) { cout << "No" << endl; return 0; } for (int i = 0; i < n + m; i++) if (!deg[find(i)]) ans[find(i)] = 1; set<int> s; for (int i = 0; i < n + m; i++) if (!deg[find(i)]) s.insert(find(i)); while (!s.empty()) { int pai = *s.begin(); s.erase(s.begin()); for (auto x : nodes[pai]) { deg[x]--; ans[x] = max(ans[x], 1 + ans[pai]); if (!deg[x]) s.insert(x); } } cout << "Yes" << endl; for (int i = 0; i < n; i++) cout << ans[find(i)] << " "; cout << endl; for (int i = 0; i < m; i++) cout << ans[find(n + 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
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.FilterInputStream; import java.io.BufferedInputStream; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Jenish */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; ScanReader in = new ScanReader(inputStream); PrintWriter out = new PrintWriter(outputStream); DGourmetChoice solver = new DGourmetChoice(); solver.solve(1, in, out); out.close(); } static class DGourmetChoice { int[] arr; int[] size; ArrayList<Integer>[] arrayList; int[] visited; boolean[] visit; int[] val; int n; int m; public void solve(int testNumber, ScanReader in, PrintWriter out) { n = in.scanInt(); m = in.scanInt(); char ccc[][] = new char[n][m]; arrayList = new ArrayList[n + m]; visited = new int[n + m]; for (int i = 0; i < n + m; i++) arrayList[i] = new ArrayList<>(); val = new int[n + m + 1]; arr = new int[n + m + 1]; size = new int[n + m + 1]; for (int i = 0; i < m + n; i++) { arr[i] = i; size[i] = 1; } for (int i = 0; i < n; i++) ccc[i] = in.scanString().toCharArray(); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (ccc[i][j] == '=') { if (root(i) != root(j + n)) { w_union(i, j + n); } } } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (ccc[i][j] == '>') { arrayList[root(i)].add(root(j + n)); } else if (ccc[i][j] == '<') { arrayList[root(j + n)].add(root(i)); } } } if (checkLoop()) { out.println("No"); return; } visit = new boolean[n + m]; for (int i = 0; i < n + m; i++) dfs(i); out.println("Yes"); for (int i = 0; i < n; i++) out.print(val[root(i)] + " "); out.println(); for (int i = n; i < n + m; i++) out.print(val[root(i)] + " "); } int root(int i) { while (arr[i] != i) { i = arr[i]; } return i; } void w_union(int A, int B) { int root_A = root(A); int root_B = root(B); if (size[root_A] < size[root_B]) { arr[root_A] = arr[root_B]; size[root_B] += size[root_A]; size[root_A] = 0; } else { arr[root_B] = arr[root_A]; size[root_A] += size[root_B]; size[root_B] = 0; } } boolean findLoop(int v) { if (visited[v] == 1) return true; if (visited[v] == 2) return false; visited[v] = 1; for (int it : arrayList[v]) { if (findLoop(it)) return true; } visited[v] = 2; return false; } boolean checkLoop() { visited = new int[n + m + 1]; for (int i = 0; i < n + m; i++) { if (visited[i] == 0 && findLoop(i)) return true; } return false; } void dfs(int u) { if (visit[u]) return; visit[u] = true; for (int it : arrayList[u]) dfs(it); val[u] = 1; for (int it : arrayList[u]) val[u] = Math.max(val[u], val[it] + 1); } } static class ScanReader { private byte[] buf = new byte[4 * 1024]; private int INDEX; private BufferedInputStream in; private int TOTAL; public ScanReader(InputStream inputStream) { in = new BufferedInputStream(inputStream); } private int scan() { if (INDEX >= TOTAL) { INDEX = 0; try { TOTAL = in.read(buf); } catch (Exception e) { e.printStackTrace(); } if (TOTAL <= 0) return -1; } return buf[INDEX++]; } public int scanInt() { int I = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { I *= 10; I += n - '0'; n = scan(); } } return neg * I; } public String scanString() { int c = scan(); while (isWhiteSpace(c)) c = scan(); StringBuilder RESULT = new StringBuilder(); do { RESULT.appendCodePoint(c); c = scan(); } while (!isWhiteSpace(c)); return RESULT.toString(); } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; else return false; } } }
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> #pragma GCC optimize(3, "Ofast", "inline") using namespace std; bool Finish_read; template <class T> inline void read(T &x) { Finish_read = 0; x = 0; int f = 1; char ch = getchar(); while (!isdigit(ch)) { if (ch == '-') f = -1; if (ch == EOF) return; ch = getchar(); } while (isdigit(ch)) x = x * 10 + ch - '0', ch = getchar(); x *= f; Finish_read = 1; } template <class T> inline void print(T x) { if (x / 10 != 0) print(x / 10); putchar(x % 10 + '0'); } template <class T> inline void writeln(T x) { if (x < 0) putchar('-'); x = abs(x); print(x); putchar('\n'); } template <class T> inline void write(T x) { if (x < 0) putchar('-'); x = abs(x); print(x); } int n, m; int p[2005], g[2005]; int find(int x) { return (p[x] == x ? p[x] : p[x] = find(p[x])); } void merge(int a, int b) { int x = find(a), y = find(n + b); if (x == y) return; p[x] = y; } int h[1005][1005], cnt = 0; vector<int> E[2005]; int in[2005], ans[2005]; int main() { scanf("%d%d", &n, &m); for (int i = 1; i <= n + m; i++) p[i] = i; for (int i = 1; i <= n; i++) { getchar(); for (int j = 1; j <= m; j++) { char c = getchar(); if (c == '=') { merge(i, j); h[i][j] = -1; } else if (c == '<') h[i][j] = 0; else h[i][j] = 1; } } for (int i = 1; i <= n + m; i++) { int x = find(i); if (g[x] == 0) { g[x] = ++cnt; } } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (h[i][j] == -1) continue; int x = g[find(i)], y = g[find(n + j)]; if (x == y) { puts("No"); return (0); } if (h[i][j]) swap(x, y); E[x].push_back(y); in[y]++; } } set<pair<int, int> > st; for (int i = 1; i <= cnt; i++) { st.insert(pair<int, int>{in[i], i}); } while (st.size()) { set<pair<int, int> >::iterator it = st.begin(); if (it->first > 0) { puts("No"); return (0); } int u = (it->second); st.erase(it); for (int i = 0; i < E[u].size(); i++) { st.erase(pair<int, int>{in[E[u][i]], E[u][i]}); in[E[u][i]]--; st.insert(pair<int, int>{in[E[u][i]], E[u][i]}); ans[E[u][i]] = max(ans[E[u][i]], ans[u] + 1); } } puts("Yes"); for (int i = 1; i <= n; i++) { printf("%d ", ans[g[find(i)]] + 1); } printf("\n"); for (int i = 1; i <= m; i++) printf("%d ", ans[g[find(n + i)]] + 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; long long read() { long long x = 0, f = 0; char ch = getchar(); while (!isdigit(ch)) f |= ch == '-', ch = getchar(); while (isdigit(ch)) x = (x << 1) + (x << 3) + (ch ^ 48), ch = getchar(); return f ? -x : x; } const int N = 2005, M = N * N; int fa[N]; void ufs_init(int n) { for (int i = 1; i <= n; i++) fa[i] = i; } int getf(int x) { return fa[x] == x ? x : fa[x] = getf(fa[x]); } void Merge(int a, int b) { fa[getf(a)] = getf(b); } int n, m, c, cnt = 0; int id[N]; vector<int> e[N]; char s[N][N]; int dfn[N], Time = 0, inst[N]; int Tarjan(int x) { dfn[x] = ++Time, inst[x] = 1; for (auto y : e[x]) if (!dfn[y]) { if (!Tarjan(y)) return 0; } else if (inst[y]) if (dfn[y] < dfn[x]) return 0; inst[x] = 0; return 1; } int in[N]; int q[N], head = 0, tail = 0; int val[N]; int main() { n = read(), m = read(), c = n + m; ufs_init(c); for (int i = 1; i <= n; i++) { scanf("%s", s[i] + 1); for (int j = 1; j <= m; j++) if (s[i][j] == '=') Merge(i, j + n); } for (int i = 1; i <= c; i++) if (fa[i] == i) id[i] = ++cnt; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { if (getf(i) == getf(j + n) && s[i][j] != '=') return puts("No"), 0; if (s[i][j] == '<') e[id[getf(i)]].push_back(id[getf(j + n)]); else if (s[i][j] == '>') e[id[getf(j + n)]].push_back(id[getf(i)]); } for (int i = 1; i <= cnt; i++) if (!dfn[i]) if (!Tarjan(i)) return puts("No"), 0; memset(in, 0, sizeof(in)), memset(val, 0, sizeof(val)); for (int x = 1; x <= cnt; x++) for (auto y : e[x]) in[y]++; for (int i = 1; i <= cnt; i++) if (!in[i]) q[++tail] = i; while (head != tail) { int x = q[++head]; val[x]++; for (auto y : e[x]) { val[y] = max(val[y], val[x]); if (!--in[y]) q[++tail] = y; } } puts("Yes"); for (int i = 1; i <= n; i++) printf("%d ", val[id[getf(i)]]); puts(""); for (int i = 1; i <= m; i++) printf("%d ", val[id[getf(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
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.Reader; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.StringTokenizer; import java.util.TreeSet; public class D2 { public static void main(String[] args) { var scanner = new BufferedScanner(); var writer = new PrintWriter(new BufferedOutputStream(System.out)); var t = 1;//scanner.nextInt(); for (int tc = 0; tc < t; tc++) { var n = scanner.nextInt(); var m = scanner.nextInt(); var total = n + m; var evaluations = new String[n]; var dsu = new DSU(total); for (int i = 0; i < n; i++) { evaluations[i] = scanner.next(); for (int j = 0; j < m; j++) { int a = i; int b = n + j; if (evaluations[i].charAt(j) == '=') { dsu.merge(a, b); } } } int size = dsu.disjoint; int[] number = new int[total]; Arrays.fill(number, -1); { int work = 0; for (int i = 0; i < total; i++) { int s = dsu.findSet(i); if (number[s] == -1) { number[s] = work++; } } } ListInt[] inAdj = new ListInt[size]; for (int i = 0; i < size; i++) { inAdj[i] = new ListInt(); } int[] outDeg = new int[size]; for (int i = 0; i < n; i++) { int u = number[dsu.findSet(i)]; for (int j = 0; j < m; j++) { if (evaluations[i].charAt(j) == '<') { int v = number[dsu.findSet(n + j)]; inAdj[u].add(v); outDeg[v]++; } else if (evaluations[i].charAt(j) == '>') { int v = number[dsu.findSet(n + j)]; inAdj[v].add(u); outDeg[u]++; } } } var q = new TreeSet<Integer>((i, j) -> { if (outDeg[i] != outDeg[j]) { return outDeg[i] - outDeg[j]; } else { return i - j; } }); for (int i = 0; i < size; i++) { q.add(i); } var ok = true; var score = 1; var assignment = new int[size]; while (!q.isEmpty()) { if (outDeg[q.first()] > 0) { ok = false; break; } var outDegDelta = new int[size]; var changed = new HashSet<Integer>(); Arrays.fill(outDegDelta, 0); while (!q.isEmpty() && outDeg[q.first()] == 0) { int x = q.pollFirst(); assignment[x] = score; q.remove(x); for (var p : inAdj[x]) { outDegDelta[p]++; changed.add(p); } } for (var x : changed) { q.remove(x); outDeg[x] -= outDegDelta[x]; q.add(x); } score++; } if (ok) { writer.println("Yes"); for (int i = 0; i < n; i++) { int s = dsu.findSet(i); writer.print(assignment[number[s]] + " "); } writer.println(); for (int i = 0; i < m; i++) { int s = dsu.findSet(n + i); writer.print(assignment[number[s]] + " "); } } else { writer.println("No"); } } scanner.close(); writer.flush(); writer.close(); } static class DSU { int n; int[] parent; int[] size; int disjoint; DSU(int n) { this.n = n; parent = new int[n]; size = new int[n]; for (int i = 0; i < n; i++) { parent[i] = i; size[i] = 1; } disjoint = n; } int findSet(int x) { if (x == parent[x]) { return x; } return parent[x] = findSet(parent[x]); } void merge(int a, int b) { a = findSet(a); b = findSet(b); if (a == b) { return; } if (size[a] > size[b]) { int tmp = a; a = b; b = tmp; } parent[a] = b; size[b] += size[a]; disjoint--; } } static class ListInt extends ArrayList<Integer> {} public static class BufferedScanner { BufferedReader br; StringTokenizer st; public BufferedScanner(Reader reader) { br = new BufferedReader(reader); } public BufferedScanner() { this(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; } void close() { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } static long gcd(long a, long b) { if (a < b) { return gcd(b, a); } while (b > 0) { long tmp = b; b = a % b; a = tmp; } return a; } static long inverse(long a, long m) { long[] ans = extgcd(a, m); return ans[0] == 1 ? (ans[1] + m) % m : -1; } private static long[] extgcd(long a, long m) { if (m == 0) { return new long[]{a, 1, 0}; } else { long[] ans = extgcd(m, a % m); long tmp = ans[1]; ans[1] = ans[2]; ans[2] = tmp; ans[2] -= ans[1] * (a / m); return ans; } } private static List<Integer> primes(double upperBound) { var limit = (int) Math.sqrt(upperBound); var isComposite = new boolean[limit + 1]; var primes = new ArrayList<Integer>(); for (int i = 2; i <= limit; i++) { if (isComposite[i]) { continue; } primes.add(i); int j = i + i; while (j <= limit) { isComposite[j] = true; j += i; } } return primes; } }
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 = 4e6 + 10; int head[maxn], in[maxn], dep[maxn], vis[maxn]; struct Edge { int f, t, next; Edge(int f = 0, int t = 0, int next = 0) : f(f), t(t), next(next) {} } edge[maxn * 2]; string G[1005]; int cnt; int fa[maxn], equ[maxn]; int findset(int e) { return fa[e] == e ? e : fa[e] = findset(fa[e]); } bool check(int a, int b) { return findset(a) == findset(b); } void un(int a, int b) { fa[findset(a)] = findset(b); } void addedge(int f, int t) { edge[cnt] = Edge(f, t, head[f]); head[f] = cnt++; } int cnt2[maxn]; int ok = 1; int n, m; vector<int> topo; void bfs() { queue<int> q; for (int i = 1; i <= n + m; i++) if (!in[i]) { vis[i] = dep[i] = 1; q.push(i); } while (!q.empty()) { int u = q.front(); topo.push_back(u); q.pop(); for (int i = head[u]; ~i; i = edge[i].next) { int v = edge[i].t; if (--in[v] == 0) { dep[v] = dep[u] + 1; q.push(v); } } } } bool check() { for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (G[i][j - 1] == '=' and dep[i] != dep[j + n]) return 0; if (G[i][j - 1] == '>' and dep[i] <= dep[j + n]) return 0; if (G[i][j - 1] == '<' and dep[i] >= dep[j + n]) return 0; } } return 1; } signed main() { ios::sync_with_stdio(0); cin.tie(0); cin >> n >> m; for (int i = 1; i <= n + m; i++) { head[i] = -1; dep[i] = 1; fa[i] = i; } for (int i = 1; i <= n; i++) { cin >> G[i]; for (int j = 1; j <= m; j++) { int f = i, t = j + n; if (G[i][j - 1] == '=') un(f, t); } } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { int f = findset(i), t = findset(j + n); if (G[i][j - 1] == '>') { in[f]++; addedge(t, f); } else if (G[i][j - 1] == '<') { in[t]++; addedge(f, t); } } } int ecnt = 0; for (int i = 1; i <= n + m; i++) if (fa[i] == i) ecnt++; bfs(); int qwq = 1; for (int i = 1; i <= n + m; i++) { dep[i] = dep[findset(i)]; } if (check()) cout << "Yes\n"; else { cout << "No\n"; return 0; } for (int i = 1; i <= n; i++) cout << dep[i] << " "; cout << endl; for (int i = 1; i <= m; i++) cout << dep[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; template <class c> struct rge { c b, e; }; template <class c> rge<c> range(c i, c j) { return rge<c>{i, j}; } template <class c> auto dud(c *x) -> decltype(cerr << *x, 0); template <class c> char dud(...); struct debug { ~debug() { cerr << endl; } template <class c> typename enable_if<sizeof dud<c>(0) != 1, debug &>::type operator<<(c i) { cerr << boolalpha << i; return *this; } template <class c> typename enable_if<sizeof dud<c>(0) == 1, debug &>::type operator<<(c i) { return *this << range(begin(i), end(i)); } template <class c, class b> debug &operator<<(pair<b, c> d) { return *this << "(" << d.first << ", " << d.second << ")"; } template <class c> debug &operator<<(rge<c> d) { *this << "["; for (auto it = d.b; it != d.e; ++it) *this << ", " + 2 * (it == d.b) << *it; return *this << "]"; } }; int n, m; vector<int> adj[1000001]; vector<int> eq[100001]; vector<int> visited(100011); vector<int> top_order; bool possible; vector<bool> used(100001); void dfs(int v) { used[v] = 1; for (int to : adj[v]) { if (!used[to]) { dfs(to); } } top_order.push_back(v); } int c; bool topological_sort() { visited.assign(n + 1, 0); top_order.clear(); for (int i = 0; i < c; ++i) { if (visited[i] == 0) dfs(i); } if (possible == 1) return false; return true; } vector<int> ans(100001, 0); int comp[100001]; void dfs1(int v, int col) { comp[v] = col; for (auto it : eq[v]) { if (comp[it] == -1) dfs1(it, col); } } void solve() { cin >> n >> m; char mat[n][m]; for (int i = 0; i < n; i++) { string s; cin >> s; for (int j = 0; j < m; j++) { mat[i][j] = s[j]; if (s[j] == '=') { eq[i].push_back(n + j); eq[n + j].push_back(i); } } } memset(comp, -1, sizeof(comp)); for (int i = 0; i < n + m; ++i) { if (comp[i] == -1) { dfs1(i, c); cerr << endl; ++c; } } for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (mat[i][j] == '>') { adj[comp[i]].push_back(comp[n + j]); } else if (mat[i][j] == '<') { adj[comp[n + j]].push_back(comp[i]); } } } bool ok = topological_sort(); for (auto it : top_order) { int ma = 0; for (auto to : adj[it]) { if (ans[to] == 0) { cout << "NO" << endl; return; } ma = max(ma, ans[to]); } ans[it] = ma + 1; } puts("Yes"); for (int i = 0; i < n; ++i) { printf("%d ", ans[comp[i]]); } puts(""); for (int i = 0; i < m; ++i) { printf("%d ", ans[comp[n + i]]); } puts(""); } int main() { int t = 1; while (t--) solve(); 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 N = 150010; int a[2100]; int pre[2100]; int n, m; char s[1100][1100]; vector<int> v[2100]; int in[2100]; int f(int x) { return x == pre[x] ? x : pre[x] = f(pre[x]); } int main() { int ans = 0; scanf("%d%d", &n, &m); for (int i = 1; i <= 2000; i++) pre[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 xx = f(i); int yy = f(j + 1000); if (xx == yy) continue; pre[yy] = xx; ans++; } } } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (s[i][j] == '=') continue; int xx = f(i); int yy = f(j + 1000); if (s[i][j] == '<') { v[xx].push_back(yy); in[yy]++; } else { v[yy].push_back(xx); in[xx]++; } } } queue<int> q; for (int i = 1; i <= n; i++) { if (pre[i] == i && in[i] == 0) { q.push(i); a[i] = 1; ans++; } } for (int i = 1001; i <= m + 1000; i++) { if (pre[i] == i && in[i] == 0) { q.push(i); a[i] = 1; ans++; } } if (q.empty()) printf("No\n"); else { while (!q.empty()) { int u = q.front(); q.pop(); for (int i = 0; i < v[u].size(); i++) { int to = v[u][i]; in[to]--; if (a[to] == 0) a[to] = a[u] + 1; else a[to] = max(a[to], a[u] + 1); if (in[to] == 0) { ans++; q.push(to); } } } if (ans != n + m) { printf("No\n"); return 0; } printf("Yes\n"); for (int i = 1; i <= n; i++) { if (pre[i] != i) a[i] = a[f(i)]; printf("%d%c", a[i], " \n"[i == n]); } for (int i = 1001; i <= m + 1000; i++) { if (pre[i] != i) a[i] = a[f(i)]; printf("%d%c", a[i], " \n"[i == m + 1000]); } } 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 sym[1000][1000 + 1]; vector<int> f; int getF(int x) { return f[x] == x ? x : f[x] = getF(f[x]); } void read_data() { cin >> n >> m; f.resize(n + m); for (int i = 0; i < n + m; i++) f[i] = i; for (int i = 0; i < n; i++) { scanf(" %s", sym[i]); for (int j = 0; j < m; j++) if (sym[i][j] == '=') { int fi = getF(i); int fj = getF(n + j); f[fi] = fj; } } } bool deal() { vector<vector<bool> > g; vector<int> cnt; cnt.assign(n + m, -1); for (int i = 0; i < n + m; i++) cnt[getF(i)] = 0; g.resize(n + m); for (int i = 0; i < n + m; i++) g[i].assign(n + m, false); for (int i = 0; i < n; i++) { int fi = getF(i); for (int j = 0; j < m; j++) { int fj = getF(j + n); if (fi == fj && sym[i][j] != '=') return false; if (sym[i][j] == '>' && !g[fj][fi]) { g[fj][fi] = true; cnt[fi]++; } else if (sym[i][j] == '<' && !g[fi][fj]) { g[fi][fj] = true; cnt[fj]++; } } } vector<int> ans; ans.resize(n + m); queue<int> q; for (int i = 0; i < n + m; i++) if (cnt[i] == 0) { q.push(i); ans[i] = 1; } while (!q.empty()) { int u = q.front(); q.pop(); for (int i = 0; i < n + m; i++) if (g[u][i]) { cnt[i]--; ans[i] = max(ans[i], ans[u] + 1); if (cnt[i] == 0) q.push(i); } } for (int i = 0; i < n + m; i++) if (cnt[i] > 0) return false; cout << "Yes" << endl; for (int i = 0; i < n; i++) { int fi = getF(i); cout << ans[fi] << ' '; } cout << endl; for (int j = 0; j < m; j++) { int fj = getF(j + n); cout << ans[fj] << ' '; } cout << endl; return true; } int main() { read_data(); if (!deal()) { cout << "No" << 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 N = 1e3 + 5; struct edge { int y, nxt, z; } e[N * N]; int p[2 * N], deg[2 * N], ans[N * 2], fa[N * 2]; int eid, n, m; char s[N][N]; int getf(int x) { if (fa[x] == x) return x; else return fa[x] = getf(fa[x]); } void merge(int x, int y) { fa[getf(x)] = getf(y); } bool topo() { queue<int> q; int ct = 0, tot = 0; for (int i = 1; i <= n + m; ++i) if (fa[i] == i) { tot++; if (!deg[i]) q.push(i), ans[i] = 1, ct++; } while (q.size()) { int x = q.front(); q.pop(); for (int i = p[x]; ~i; i = e[i].nxt) { int y = e[i].y; ans[y] = max(ans[y], ans[x] + e[i].z); if (--deg[y] == 0) q.push(y), ct++; } } if (ct == tot) return 0; else return 1; } void add(int x, int y, int z) { e[eid] = edge{y, p[x], z}; p[x] = eid++; } 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 + m; ++i) fa[i] = i; for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) if (s[i][j] == '=') merge(i, j + n); memset(p, -1, sizeof(p)); for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) if (s[i][j] != '=') { if (getf(i) == getf(j + n)) { puts("No"); return 0; } int x = getf(i), y = getf(j + n); if (s[i][j] == '>') add(y, x, 1), deg[x]++; else add(x, y, 1), deg[y]++; } if (topo()) { puts("No"); return 0; } else { puts("Yes"); for (int i = 1; i <= n; ++i) printf("%d ", ans[getf(i)]); puts(""); for (int i = n + 1; i <= n + m; ++i) printf("%d ", ans[getf(i)]); 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; int nedge, head[2005]; struct Edge { int to, nxt; } edge[2000005]; int in[2005]; void add(int x, int y) { edge[++nedge].nxt = head[x]; edge[nedge].to = y; head[x] = nedge; in[y]++; } int fa[2005], ans[2005]; int Find(int x) { return x == fa[x] ? x : fa[x] = Find(fa[x]); } queue<int> q; char s[1005][1005]; int main() { int n, m; scanf("%d%d\n", &n, &m); for (int i = 1; i <= n + m; i++) fa[i] = i; for (int i = 1; i <= n; i++) gets(s[i] + 1); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) if (s[i][j] == '=') fa[Find(i)] = Find(n + j); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { if (s[i][j] == '>') add(Find(j + n), Find(i)); if (s[i][j] == '<') add(Find(i), Find(j + n)); } for (int i = 1; i <= n + m; i++) if (Find(i) == i && !in[i]) { q.push(i); ans[i] = 1; } while (!q.empty()) { int x = q.front(); q.pop(); for (int i = head[x]; i; i = edge[i].nxt) { int y = edge[i].to; ans[y] = max(ans[x] + 1, ans[y]); in[y]--; if (!in[y]) q.push(y); } } for (int i = 1; i <= n + m; i++) if (Find(i) == i && in[i]) return puts("No"), 0; puts("Yes"); for (int i = 1; i <= n; i++) printf("%d ", ans[Find(i)]); puts(""); for (int i = 1; i <= m; i++) printf("%d ", ans[Find(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
import java.io.*; import java.util.*; public class D { static class DSU { private final int n; private final int[] root; DSU(int n) { this.n = n; root = new int[n + 1]; for (int i = 0; i <= n; i++) { root[i] = i; } } int findRoot(int x) { if (root[x] == x) { return x; } return root[x] = findRoot(root[x]); } void unite(int x, int y) { x = findRoot(x); y = findRoot(y); if (x != y) { root[x] = y; } } } public static void main(String[] args) throws IOException { try (Input input = new StandardInput(); PrintWriter writer = new PrintWriter(System.out)) { int n = input.nextInt(), m = input.nextInt(); char[][] g = new char[n][]; DSU dsu = new DSU(n + m); for (int i = 0; i < n; i++) { g[i] = input.next().toCharArray(); for (int j = 0; j < m; j++) { if (g[i][j] == '=') { dsu.unite(i, n + j); } } } int[][] graph = new int[n + m][n + m]; int[] incoming = new int[n + m]; for (int i = 0; i < n; i++) { int u = dsu.findRoot(i); for (int j = 0; j < m; j++) { if (g[i][j] == '=') { continue; } int v = dsu.findRoot(n + j); if (u == v) { writer.println("No"); return; } if (g[i][j] == '<' && graph[u][v] == 0) { graph[u][v] = 1; incoming[v]++; } else if (g[i][j] == '>' && graph[v][u] == 0) { graph[v][u] = 1; incoming[u]++; } } } int[] grade = new int[n + m]; Queue<Integer> q = new LinkedList<>(); for (int i = 0; i < n + m; i++) { if (incoming[i] == 0 && dsu.findRoot(i) == i) { q.add(i); grade[i] = 1; } } boolean[] visited = new boolean[n + m]; while (!q.isEmpty()) { int u = q.poll(); visited[u] = true; for (int v = 0; v < n + m; v++) { if (graph[u][v] == 0) { continue; } incoming[v]--; grade[v] = Math.max(grade[v], grade[u] + 1); if (incoming[v] == 0) { q.add(v); } } } for (int i = 0; i < n + m; i++) { int root = dsu.findRoot(i); if (root != i) { grade[i] = grade[root]; } if (grade[i] == 0 || !visited[root]) { writer.println("No"); return; } } writer.println("Yes"); for (int[] x : new int[][]{{0, n}, {n, m}}) { int offset = x[0]; int count = x[1]; for (int i = 0; i < count; i++) { writer.print(grade[i + offset] + " "); } writer.println(); } } } interface Input extends Closeable { String next() throws IOException; default int nextInt() throws IOException { return Integer.parseInt(next()); } default long nextLong() throws IOException { return Long.parseLong(next()); } } private static class StandardInput implements Input { private final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); private StringTokenizer stringTokenizer; @Override public void close() throws IOException { reader.close(); } @Override public String next() throws IOException { if (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) { stringTokenizer = new StringTokenizer(reader.readLine()); } return stringTokenizer.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; using LL = long long; const int inf = 1e9 + 4; const int M = 3e3 + 5; vector<int> vt[M]; char s[M][M]; int in[M]; int pre[M]; int ori[M], res[M]; int findroot(int r) { if (r == pre[r]) return r; return pre[r] = findroot(pre[r]); } int main() { int n, m, l, r, len, cnt = 0; scanf("%d%d", &n, &m); len = n + m; for (int i = 1; i <= len; i++) pre[i] = i; for (int i = 1; i <= n; i++) { scanf("%s", s[i] + 1); for (int j = 1; j <= m; j++) { l = findroot(i); if (s[i][j] == '=') { r = findroot(n + j); if (l ^ r) pre[l] = r; } } } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { l = findroot(i); if (s[i][j] == '>') { r = findroot(n + j); if (l == r) { puts("No"); exit(0); } in[l]++; vt[r].push_back(l); } else if (s[i][j] == '<') { r = findroot(n + j); if (l == r) { puts("No"); exit(0); } in[r]++; vt[l].push_back(r); } } } queue<int> q; int n1 = 0; for (int i = 1; i <= len; i++) { res[i] = 1; if (i == findroot(i)) { n1++; if (!in[i]) { q.push(i); res[i] = 1; } } } while (!q.empty()) { int pos = q.front(); q.pop(); ori[++cnt] = pos; for (auto &e : vt[pos]) { if ((--in[e]) == 0) q.push(e); } } if (cnt < n1) { puts("No"); exit(0); } puts("Yes"); for (int i = 1; i <= n1; i++) { int u = ori[i]; for (auto &e : vt[u]) res[e] = max(res[e], res[u] + 1); } for (int i = 1; i <= len; i++) { l = findroot(i); res[i] = res[l]; } for (int i = 1; i < n; i++) printf("%d ", res[i]); printf("%d\n", res[n]); for (int i = n + 1; i < len; i++) printf("%d ", res[i]); printf("%d\n", res[len]); 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 c[1010][1010]; vector<int> g[200001]; vector<int> larger[200001]; int component[200001]; int timer = 0; void dfsinit(int v) { component[v] = timer; for (auto to : g[v]) { if (!component[to]) dfsinit(to); } } int used[200001]; int dp[200001]; int timer1 = 0; void dfs(int v) { used[v] = 1; int maxx = 0; for (auto to : larger[v]) { if (used[to] == 1) { cout << "No"; exit(0); } if (used[to] == 0) dfs(to); maxx = max(maxx, dp[to]); } dp[v] = maxx + 1; used[v] = 2; } int32_t main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int n, m; cin >> n >> m; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { cin >> c[i][j]; if (c[i][j] == '=') { g[i].push_back(j + n); g[j + n].push_back(i); } } } for (int i = 1; i <= n + m; i++) { if (!component[i]) { timer++; dfsinit(i); } } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (c[i][j] == '<') { larger[component[j + n]].push_back(component[i]); } if (c[i][j] == '>') { larger[component[i]].push_back(component[j + n]); } } } for (int i = 1; i <= timer; i++) { if (!used[i]) dfs(i); } cout << "Yes\n"; for (int i = 1; i <= n; i++) cout << dp[component[i]] << " "; cout << '\n'; for (int i = n + 1; i <= n + m; i++) cout << dp[component[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
#include <bits/stdc++.h> using namespace std; const int maxn = 1111 * 2; vector<int> G[maxn]; char mp[maxn][maxn]; int du[maxn], num[maxn]; int cnt = 1; int fa[maxn]; int find(int x) { return x == fa[x] ? x : fa[x] = find(fa[x]); } void uni(int x, int y) { x = find(x), y = find(y); if (x != y) fa[y] = x; } 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++) for (int j = n; j < n + m; j++) { cin >> mp[i][j]; if (mp[i][j] == '=') uni(i, j); } memset(du, 0, sizeof(du)); for (int i = 0; i < n; i++) for (int j = n; j < n + m; j++) if (mp[i][j] == '<') G[find(i)].push_back(find(j)), du[find(j)]++; else if (mp[i][j] == '>') G[find(j)].push_back(find(i)), du[find(i)]++; queue<int> q; for (int i = 0; i < n + m; i++) if (!du[find(i)]) q.push(find(i)), du[find(i)]--, num[find(i)] = 1; while (!q.empty()) { int u = q.front(); q.pop(); for (int v : G[u]) { v = find(v); if (!(--du[v])) q.push(v), du[v]--, num[v] = num[find(u)] + 1; } } int is = 1; for (int i = 0; i < n + m; i++) if (du[find(i)] > 0) is = 0; if (is) { cout << "Yes" << endl; for (int i = 0; i < n; i++) cout << num[find(i)] << ' '; cout << endl; for (int i = n; i < m + n; i++) cout << num[find(i)] << ' '; } else { cout << "No" << 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; long long n, m, i, p[2020], b[2020], d[2020], ta, tb, taa, tbb, j; char a[2020][2020]; vector<long long> v[2020]; long long car(long long aa) { if (aa == p[aa]) return aa; else return p[aa] = car(p[aa]); } void dfs(long long aa) { b[aa] = 1; long long ii; for (ii = 0; ii < v[aa].size(); ii++) { if (b[v[aa][ii]] == 1) { cout << "No\n"; exit(0); } else if (!b[v[aa][ii]]) dfs(v[aa][ii]); } b[aa] = 2; } long long depe(long long aa) { if (d[aa] == -1) { d[aa] = 1; long long ii; for (ii = 0; ii < v[aa].size(); ii++) d[aa] = max(d[aa], depe(v[aa][ii]) + 1); } return d[aa]; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); cin >> n >> m; for (i = 1; i <= n + m; i++) p[i] = i; for (i = 1; i <= n; i++) for (j = 1; j <= m; j++) { cin >> a[i][j]; if (a[i][j] == '=') { ta = i; tb = n + j; taa = car(ta); tbb = car(tb); p[taa] = tbb; } } memset(d, -1, sizeof(d)); for (i = 1; i <= n; i++) for (j = 1; j <= m; j++) { if (a[i][j] == '<') v[car(n + j)].push_back(car(i)); else if (a[i][j] == '>') v[car(i)].push_back(car(n + j)); } for (i = 1; i <= n + m; i++) if (!b[car(i)]) dfs(car(i)); cout << "Yes\n"; for (i = 1; i <= n; i++) { cout << depe(car(i)); if (i < n) cout << " "; else cout << "\n"; } for (i = 1; i <= m; i++) { cout << depe(car(n + i)); if (i < m) cout << " "; else 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
/*Author: Satyajeet Singh, Delhi Technological University*/ import java.io.*; import java.util.*; import java.text.*; import java.lang.*; public class Main { /*********************************************Constants******************************************/ static PrintWriter out=new PrintWriter(new OutputStreamWriter(System.out)); static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static long mod=(long)1e9+7; static long mod1=998244353; static boolean sieve[]; static ArrayList<Integer> primes; static ArrayList<Long> factorial; static HashSet<Integer> graph[]; /****************************************Solutions Begins*****************************************/ static int dsu[]; static int dsu_size[]; static void setInit(int n){ dsu=new int[n]; dsu_size=new int[n]; Arrays.fill(dsu,-1); Arrays.fill(dsu_size,0); } static void makeSet(int v){ dsu[v]=v; dsu_size[v]=1; } static int findSet(int v){ if(dsu[v]==v){ return v; } int v1=findSet(dsu[v]); dsu[v]=v1; return v1; } static void union(int s1,int s2){ int a=findSet(s1); int b=findSet(s2); if(a!=b){ if(dsu_size[s1]>dsu_size[s2]){ int temp=s1; s1=s2; s2=temp; } dsu[s1]=s2; dsu_size[s1]+=dsu_size[s2]; } } public static void main (String[] args) throws Exception { String st[]=br.readLine().split(" "); int n=Integer.parseInt(st[0]); int m=Integer.parseInt(st[1]); setInit(n+m); Makegraph(n+m); String input[]=new String[n]; for(int i=0;i<n+m;i++){ makeSet(i); } for(int i=0;i<n;i++){ st=br.readLine().split(" "); input[i]=st[0]; for(int j=0;j<m;j++){ char a=st[0].charAt(j); if(a=='='){ union(i,n+j); } } } int indeg[]=new int[n+m]; Arrays.fill(indeg,0); for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ if(input[i].charAt(j)=='>'){ int ii=findSet(i); int jj=findSet(n+j); addEdge(ii,jj); } else if(input[i].charAt(j)=='<'){ int ii=findSet(i); int jj=findSet(n+j); addEdge(jj,ii); } } } for(int i=0;i<n+m;i++){ for(int u:graph[i]){ indeg[u]++; } } // //debug(set); // debug(graph); Queue<Integer> q=new ArrayDeque<>(); boolean vis[]=new boolean[n+m]; Arrays.fill(vis,false); int dp[]=new int[n+m]; Arrays.fill(dp,1001); for(int i=0;i<n+m;i++){ int id=findSet(i); if(indeg[id]==0&&!vis[id]){ q.add(id); vis[id]=true; } } //topological Sort // debug(indeg); int itr=0; while(!q.isEmpty()){ // System.out.println("HI"); // debug(q); itr++; if(itr>1000000){ System.out.println("Problem"); return; } int a=q.remove(); for(int u:graph[a]){ if(vis[u]){ out.println("No"); out.flush(); return; } else{ indeg[u]--; if(indeg[u]==0){ q.add(u); dp[u]=dp[a]-1; vis[u]=true; } } } } for(int i=0;i<n+m;i++){ if(indeg[i]>0){ out.println("No"); out.flush(); return; } } out.println("Yes"); // debug(dp); int min=Integer.MAX_VALUE; for(int i=0;i<n+m;i++){ min=Math.min(min,dp[i]); } for(int i=0;i<n+m;i++){ dp[i]-=min-1; } //debug(dp); for(int i=0;i<n;i++){ int idx=findSet(i); out.print(dp[idx]+" "); } out.println(); for(int i=0;i<m;i++){ int idx=findSet(n+i); out.print(dp[idx]+" "); } // debug(dsu); /****************************************Solutions Ends**************************************************/ out.flush(); out.close(); } /****************************************Template Begins************************************************/ /***************************************Precision Printing**********************************************/ static void printPrecision(double d){ DecimalFormat ft = new DecimalFormat("0.00000000000000000"); out.println(ft.format(d)); } /******************************************Graph*********************************************************/ static void Makegraph(int n){ graph=new HashSet[n]; for(int i=0;i<n;i++){ graph[i]=new HashSet<>(); } } static void addEdge(int a,int b){ graph[a].add(b); } /*********************************************PAIR********************************************************/ static class PairComp implements Comparator<Pair>{ public int compare(Pair p1,Pair p2){ if(p1.u>p2.u){ return 1; } else if(p1.u<p2.u){ return -1; } else{ return p1.v-p2.v; } } } static class Pair implements Comparable<Pair> { int u; int v; int index=-1; public Pair(int u, int v) { this.u = u; this.v = v; } public int hashCode() { int hu = (int) (u ^ (u >>> 32)); int hv = (int) (v ^ (v >>> 32)); return 31 * hu + hv; } public boolean equals(Object o) { Pair other = (Pair) o; return u == other.u && v == other.v; } public int compareTo(Pair other) { if(index!=other.index) return Long.compare(index, other.index); return Long.compare(v, other.v)!=0?Long.compare(v, other.v):Long.compare(u, other.u); } public String toString() { return "[u=" + u + ", v=" + v + "]"; } } static class PairCompL implements Comparator<Pairl>{ public int compare(Pairl p1,Pairl p2){ if(p1.u>p2.u){ return 1; } else if(p1.u<p2.u){ return -1; } else{ return 0; } } } static class Pairl implements Comparable<Pair> { long u; long v; int index=-1; public Pairl(long u, long v) { this.u = u; this.v = v; } public int hashCode() { int hu = (int) (u ^ (u >>> 32)); int hv = (int) (v ^ (v >>> 32)); return 31 * hu + hv; } public boolean equals(Object o) { Pair other = (Pair) o; return u == other.u && v == other.v; } public int compareTo(Pair other) { if(index!=other.index) return Long.compare(index, other.index); return Long.compare(v, other.v)!=0?Long.compare(v, other.v):Long.compare(u, other.u); } public String toString() { return "[u=" + u + ", v=" + v + "]"; } } /*****************************************DEBUG***********************************************************/ public static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } /************************************MODULAR EXPONENTIATION***********************************************/ static long modulo(long a,long b,long c) { long x=1; long y=a; while(b > 0){ if(b%2 == 1){ x=(x*y)%c; } y = (y*y)%c; // squaring the base b /= 2; } return x%c; } /********************************************GCD**********************************************************/ static long gcd(long x, long y) { if(x==0) return y; if(y==0) return x; long r=0, a, b; a = (x > y) ? x : y; // a is greater number b = (x < y) ? x : y; // b is smaller number r = b; while(a % b != 0) { r = a % b; a = b; b = r; } return r; } /******************************************SIEVE**********************************************************/ static void sieveMake(int n){ sieve=new boolean[n]; Arrays.fill(sieve,true); sieve[0]=false; sieve[1]=false; for(int i=2;i*i<n;i++){ if(sieve[i]){ for(int j=i*i;j<n;j+=i){ sieve[j]=false; } } } primes=new ArrayList<Integer>(); for(int i=0;i<n;i++){ if(sieve[i]){ primes.add(i); } } } /********************************************End***********************************************************/ }
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 getint() { int ans = 0, f = 1; char c = getchar(); while (c > '9' || c < '0') { if (c == '-') f = -1; c = getchar(); } while (c >= '0' && c <= '9') { ans = ans * 10 + c - '0'; c = getchar(); } return ans * f; } int f[10010]; int _(int x) { return x == f[x] ? x : f[x] = _(f[x]); } struct bian { int e, n; }; bian b[2000010]; int s[10010], tot = 0; void add(int x, int y) { tot++; b[tot].e = y; b[tot].n = s[x]; s[x] = tot; } int p[10010], in[10010], cnt = 0; int n; bool topo() { for (int i = 1; i <= n; i++) { for (int j = s[i]; j; j = b[j].n) { in[b[j].e]++; } } queue<int> q; for (int i = 1; i <= n; i++) if (!in[i]) q.push(i), p[i] = 1; while (q.size()) { int f = q.front(); q.pop(); ++cnt; for (int i = s[f]; i; i = b[i].n) { in[b[i].e]--; if (!in[b[i].e]) q.push(b[i].e), p[b[i].e] = p[f] + 1; } } return cnt == n; } char c[1010][1010]; int main() { int x = getint(), y = getint(); n = x + y; for (int i = 1; i <= x + y; i++) f[i] = i; for (int i = 0; i < x; i++) { for (int j = 0; j < y; j++) { c[i][j] = getchar(); while (c[i][j] != '<' && c[i][j] != '>' && c[i][j] != '=') c[i][j] = getchar(); if (c[i][j] == '=') f[_(i + 1)] = f[_(x + j + 1)]; } } for (int i = 0; i < x; i++) { for (int j = 0; j < y; j++) { if (c[i][j] == '<') add(_(i + 1), _(x + j + 1)); if (c[i][j] == '>') add(_(x + j + 1), _(i + 1)); } } if (!topo()) return puts("No"), 0; else puts("Yes"); for (int i = 0; i < x; i++) cout << p[_(i + 1)] << " "; cout << endl; for (int i = 0; i < y; i++) cout << p[_(x + 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.util.*; import java.util.stream.*; public class D { public Object solve () { int N = sc.nextInt(), M = sc.nextInt(); char [][] S = sc.nextChars(N); int [][] A = new int [N][M]; for (int i : rep(N)) for (int j : rep(M)) A[i][j] = eval(S[i][j]); int [][] Z = new int [N+M][]; for (int i : rep(N)) { int D = 0; for (int j : rep(M)) D += A[i][j]; Z[i] = new int [] { 0, i, D }; } for (int j : rep(M)) { int D = 0; for (int i : rep(N)) D -= A[i][j]; Z[j+N] = new int [] { 1, j, D }; } try { sort (Z, (x, y) -> compare(A, x, y)); } catch (Throwable t) { return "No"; } int [][] res = { new int [N], new int [M] }; res[Z[0][0]][Z[0][1]] = 1; for (int i : rep(1, N+M)) { int [] z = Z[i], y = Z[i-1]; int V = res[y[0]][y[1]]; if (compare(A, z, y) > 0) ++V; res[z[0]][z[1]] = V; } for (int i : rep(N)) for (int j : rep(M)) if (A[i][j] != Integer.signum(res[0][i] - res[1][j])) return "No"; print("Yes"); for (int i : rep(2)) print(res[i]); return null; } int compare (int [][] A, int [] x, int [] y) { if (x[0] == 0 && y[0] == 1) return A[x[1]][y[1]]; else if (x[0] == 1 && y[0] == 0) return -A[y[1]][x[1]]; else return x[2] - y[2]; } int eval (char c) { switch(c) { case '<': return -1; case '=': return 0; case '>': return 1; default: throw new Error(); } } private static final int CONTEST_TYPE = 1; private static void init () { } private static int [] rep (int N) { return rep(0, N); } private static int [] rep (int S, int T) { if (S >= T) return new int [0]; int [] res = new int [T-S]; for (int i = S; i < T; ++i) res[i-S] = i; return res; } private static <T> T [] sort(T [] A, Comparator<T> C) { Arrays.sort(A, C); return A; } //////////////////////////////////////////////////////////////////////////////////// OFF private static IOUtils.MyScanner sc = new IOUtils.MyScanner(); private static Object print (Object o, Object ... A) { IOUtils.print(o, A); return null; } private static class IOUtils { public static class MyScanner { public String next () { newLine(); return line[index++]; } public int nextInt () { return Integer.parseInt(next()); } public char [] nextChars () { return next ().toCharArray (); } public char[][] nextChars (int N) { return IntStream.range(0, N).mapToObj(i -> nextChars()).toArray(char[][]::new); } ////////////////////////////////////////////// private boolean eol () { return index == line.length; } private String readLine () { try { return r.readLine(); } catch (Exception e) { throw new Error (e); } } private final java.io.BufferedReader r; private MyScanner () { this(new java.io.BufferedReader(new java.io.InputStreamReader(System.in))); } private MyScanner (java.io.BufferedReader r) { try { this.r = r; while (!r.ready()) Thread.sleep(1); start(); } catch (Exception e) { throw new Error(e); } } private String [] line; private int index; private void newLine () { if (line == null || eol()) { line = split(readLine()); index = 0; } } private String [] split (String s) { return s.length() > 0 ? s.split(" ") : new String [0]; } } private static String build (Object o, Object ... A) { return buildDelim(" ", o, A); } private static String buildDelim (String delim, Object o, Object ... A) { StringBuilder b = new StringBuilder(); append(b, o, delim); for (Object p : A) append(b, p, delim); return b.substring(delim.length()); } ////////////////////////////////////////////////////////////////////////////////// private static final java.text.DecimalFormat formatter = new java.text.DecimalFormat("#.#########"); private static void start () { if (t == 0) t = millis(); } private static void append (java.util.function.Consumer<Object> f, java.util.function.Consumer<Object> g, final Object o) { if (o.getClass().isArray()) { int len = java.lang.reflect.Array.getLength(o); for (int i = 0; i < len; ++i) f.accept(java.lang.reflect.Array.get(o, i)); } else if (o instanceof Iterable<?>) ((Iterable<?>)o).forEach(f::accept); else g.accept(o instanceof Double ? formatter.format(o) : o); } private static void append (final StringBuilder b, Object o, final String delim) { append(x -> { append(b, x, delim); }, x -> b.append(delim).append(x), o); } private static java.io.PrintWriter pw = new java.io.PrintWriter(System.out); private static void print (Object o, Object ... A) { String res = build(o, A); if (DEBUG == 2) err(res, '(', time(), ')'); pw.println(res); if (DEBUG == 1) { pw.flush(); System.out.flush(); } } private static void err (Object o, Object ... A) { System.err.println(build(o, A)); } private static int DEBUG; private static void exit () { String end = "------------------" + System.lineSeparator() + time(); switch(DEBUG) { case 1: print(end); break; case 2: err(end); break; } IOUtils.pw.close(); System.out.flush(); System.exit(0); } private static long t; private static long millis () { return System.currentTimeMillis(); } private static String time () { return "Time: " + (millis() - t) / 1000.0; } private static void run (int N) { try { DEBUG = Integer.parseInt(System.getProperties().get("DEBUG").toString()); } catch (Throwable t) {} for (int n = 1; n <= N; ++n) { Object res = new D().solve(); if (res != null) { @SuppressWarnings("all") Object o = CONTEST_TYPE == 0 ? "Case #" + n + ": " + build(res) : res; print(o); } } exit(); } } //////////////////////////////////////////////////////////////////////////////////// public static void main (String[] args) { init(); @SuppressWarnings("all") int N = CONTEST_TYPE == 1 ? 1 : sc.nextInt(); IOUtils.run(N); } }
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 sys import random, math from collections import defaultdict def union(a,b): global de for el in de[b]: ds[el] = a de[a].add(el) del(de[b]) n,m = [int(__) for __ in raw_input().split()] arr = list() arc = [[] for x in range(m)] ds = dict() de = defaultdict(set) darr = defaultdict(set) darc = defaultdict(set) for i in range(n): st = raw_input() darr[st].add(i) arr.append(st) for j in range(m): arc[j].append(st[j]) for i in range(m): darc[''.join(arc[i])].add(i+10000) for row in darr: targ = -1 for el in darr[row]: if targ == -1: targ = el if el not in ds: ds[el] = targ de[targ].add(el) elif targ == ds[el]: de[targ].add(el) else: union(ds[el],targ) for col in darc: targ = -1 for el in darc[col]: if targ == -1: targ = el if el not in ds: ds[el] = targ de[targ].add(el) elif targ == ds[el]: de[targ].add(el) else: union(ds[el],targ) for i in range(n): for j in range(m): if arr[i][j] == '=': if ds[i] != ds[j+10000]: x = ds[j+10000] union(ds[i],ds[j+10000]) nodes = set() dgs = defaultdict(set) dgt = defaultdict(set) for i in range(n): for j in range(m): a = ds[i] b = ds[j + 10000] if arr[i][j] == '<': nodes.add((a,b)) dgt[a].add(b) dgs[b].add(a) elif arr[i][j] == '>': nodes.add((b,a)) dgt[b].add(a) dgs[a].add(b) cur = 1 lv = list() for k in dgt: if k not in dgs: lv.append(k) d = dict() if len(dgt) == 0: d[ds[0]] = 1 while len(lv): l = lv.pop() d[l] = cur for el in dgt[l]: dgs[el].remove(l) if len(dgs[el]) == 0: lv.append(el) cur += 1 res = list() for i in range(n): if ds[i] not in d: print('NO') exit() res.append(str(d[ds[i]])) res2 = list() for j in range(m): if ds[j+10000] not in d: print('NO') exit() res2.append(str(d[ds[j+10000]])) print('YES') print(' '.join(res)) print(' '.join(res2)) #print(d) #print(nodes) #print(de) #print(ds)
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
#include <bits/stdc++.h> using namespace std; const int N = 1000 + 1; char a[N][N]; int f[N * 2], head[1000001], vis[2 * N], d[N * 2], d1[N * 2], bj[N * 2]; int ask(int x) { return x == f[x] ? x : f[x] = ask(f[x]); } struct node { int next, to; } e[N * N]; int tot; void add(int x, int y) { e[++tot].to = y; e[tot].next = head[x]; head[x] = tot; } int cnt; int solve() { queue<int> q; for (int i = 1; i <= cnt; i++) { if (d[i] == 0) q.push(i); } while (!q.empty()) { int p = q.front(); q.pop(); for (int i = head[p]; i; i = e[i].next) { int u = e[i].to; d[u]--; if (d[u] == 0) q.push(u); } } for (int i = 1; i <= cnt; i++) if (d[i]) return 1; return 0; } void dfs(int u, int w) { bj[u] = w; for (int i = head[u]; i; i = e[i].next) { int v = e[i].to; if (bj[v] < w + 1) dfs(v, w + 1); } } void solve1() { queue<int> q; for (int i = 1; i <= cnt; i++) if (!d1[i]) q.push(i), bj[i] = 1; while (!q.empty()) { int p = q.front(); q.pop(); for (int i = head[p]; i; i = e[i].next) { int u = e[i].to; d1[u]--; bj[u] = max(bj[u], bj[p] + 1); if (!d1[u]) q.push(u); } } } int main() { ios::sync_with_stdio(false), cin.tie(0), cout.tie(0); int n, m; cin >> n >> m; for (int i = 1; i <= n + m; i++) f[i] = i; for (int i = 1; i <= n; i++) { cin >> a[i] + 1; } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { int f1 = ask(i), f2 = ask(n + j); if (a[i][j] != '=') { if (f1 == f2) { cout << "No\n"; return 0; } } else { f[f1] = f2; } } } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { int f1 = ask(i), f2 = ask(n + j); if (!vis[f1]) vis[f1] = ++cnt; if (!vis[f2]) vis[f2] = ++cnt; if (a[i][j] != '=') { if (f1 == f2) { cout << "No\n"; return 0; } if (a[i][j] == '<') add(vis[f1], vis[f2]), d[vis[f2]]++, d1[vis[f2]]++; else add(vis[f2], vis[f1]), d[vis[f1]]++, d1[vis[f1]]++; } } } if (solve()) { cout << "No\n"; return 0; } solve1(); cout << "Yes\n"; for (int i = 1; i <= n + m; i++) { cout << bj[vis[ask(i)]] << " "; if (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; int n, m, par[5005]; vector<int> sz[5005]; string s[5005]; int f(int i) { if (par[i] != i) par[i] = f(par[i]); return par[i]; } void merge(int a, int b) { a = f(a), b = f(b); if (a == b) return; if (sz[a].size() < sz[b].size()) { par[a] = b; for (__typeof(sz[a].begin()) it = sz[a].begin(); it != sz[a].end(); it++) sz[b].push_back(*it); return; } par[b] = a; for (__typeof(sz[b].begin()) it = sz[b].begin(); it != sz[b].end(); it++) sz[a].push_back(*it); } vector<int> v[5005]; int d[5005]; int main() { ios_base::sync_with_stdio(false); cin >> n >> m; for (int i = 0; i <= n - 1; i++) cin >> s[i]; for (int i = 1; i <= n + m; i++) par[i] = i; for (int i = 0; i <= n - 1; i++) { for (int j = 0; j <= m - 1; j++) { if (s[i][j] == '=') merge(i + 1, n + j + 1); } } for (int i = 0; i <= n - 1; i++) { for (int j = 0; j <= m - 1; j++) { int x = f(i + 1), y = f(n + j + 1); if (s[i][j] == '<') { if (x == y) { cout << "No"; return 0; } v[x].push_back(y); d[y]++; } else if (s[i][j] == '>') { if (x == y) { cout << "No"; return 0; } v[y].push_back(x); d[x]++; } } } int vis[5005] = {0}, ans[5005] = {0}; queue<int> q; for (int i = 1; i <= n + m; i++) { int x = f(i); if (vis[x] == 0 && d[x] == 0) { q.push(x); vis[x] = 1; ans[x] = 1; } } while (!q.empty()) { int at = q.front(); q.pop(); for (__typeof(v[at].begin()) it = v[at].begin(); it != v[at].end(); it++) { int to = *it; int tt = f(to); d[tt]--; if (d[tt] == 0) { q.push(tt); ans[tt] = ans[at] + 1; } } } for (int i = 1; i <= n + m; i++) { if (d[i]) { cout << "No"; return 0; } } cout << "Yes\n"; for (int i = 1; i <= n; i++) { cout << ans[f(i)]; cout << " "; } cout << "\n"; for (int i = 1; i <= m; i++) { cout << ans[f(n + i)]; cout << " "; } 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 getint() { int ans = 0, f = 1; char c = getchar(); while (c > '9' || c < '0') { if (c == '-') f = -1; c = getchar(); } while (c >= '0' && c <= '9') { ans = ans * 10 + c - '0'; c = getchar(); } return ans * f; } int f[10010]; int _(int x) { return x == f[x] ? x : f[x] = _(f[x]); } struct bian { int e, n; }; bian b[2000010]; int s[10010], tot = 0; void add(int x, int y) { tot++; b[tot].e = y; b[tot].n = s[x]; s[x] = tot; } int p[10010], in[10010], cnt = 0; int n; bool topo() { for (int i = 1; i <= n; i++) { for (int j = s[i]; j; j = b[j].n) { in[b[j].e]++; } } queue<int> q; for (int i = 1; i <= n; i++) if (!in[i]) q.push(i), p[i] = 1; while (q.size()) { int f = q.front(); q.pop(); ++cnt; for (int i = s[f]; i; i = b[i].n) { in[b[i].e]--; if (!in[b[i].e]) q.push(b[i].e), p[b[i].e] = p[f] + 1; } } return cnt == n; } char c[1010][1010]; int main() { int x = getint(), y = getint(); n = x + y; for (int i = 1; i <= x + y; i++) f[i] = i; for (int i = 0; i < x; i++) { for (int j = 0; j < y; j++) { c[i][j] = getchar(); while (c[i][j] != '<' && c[i][j] != '>' && c[i][j] != '=') c[i][j] = getchar(); if (c[i][j] == '=') f[_(i + 1)] = f[_(x + j + 1)]; } } for (int i = 0; i < x; i++) { for (int j = 0; j < y; j++) { if (c[i][j] == '<') add(_(i + 1), _(x + j + 1)); if (c[i][j] == '>') add(_(x + j + 1), _(i + 1)); } } if (!topo()) return puts("No"), 0; else puts("Yes"); for (int i = 0; i < x; i++) cout << p[_(i + 1)] << " "; cout << endl; for (int i = 0; i < y; i++) cout << p[_(x + 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
#include <bits/stdc++.h> using namespace std; const int N = 1005; char s[N][N]; int fa[2 * N], st[N * 2], ans[N * 2], deg[N * 2]; int n, m, in_path[N * 2]; vector<int> E[N * 2]; int find(int x) { if (fa[x] == x) return x; return fa[x] = find(fa[x]); } void dfs(int u, int& _c) { if (!_c) return; in_path[u] = 1; for (auto& v : E[u]) { if (in_path[v]) { _c = 0; return; } dfs(v, _c); } in_path[u] = 0; } int topo() { queue<int> q; for (int i = 1; i <= n + m; ++i) if (deg[i] == 0) q.push(i); int in_times = 0; while (!q.empty()) { ++in_times; int u = q.front(); q.pop(); for (auto& v : E[u]) { if (--deg[v] == 0) q.push(v), ans[v] = ans[u] + 1; } } return in_times; } 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 + m; ++i) fa[i] = i, ans[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) continue; fa[x] = y; } memset(deg, -1, sizeof deg); int fuck = 0; for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) { if (s[i][j] == '=') continue; int x = find(i), y = find(j + n); if (deg[x] == -1) deg[x] = 0, ++fuck; if (deg[y] == -1) deg[y] = 0, ++fuck; if (x == y) return puts("No"), 0; if (s[i][j] == '<') E[x].push_back(y), ++deg[y]; else E[y].push_back(x), ++deg[x]; } if (topo() != fuck) return puts("No"), 0; puts("Yes"); for (int i = 1; i <= n; ++i) printf("%d ", ans[find(i)]); puts(""); for (int i = 1; i <= m; ++i) printf("%d ", ans[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
#include <bits/stdc++.h> using namespace std; int n, m, f[2005], fa[2005], g[2005]; vector<int> d[2005], d2[2005]; queue<int> q; set<int> s; int Find(int x) { return fa[x] == x ? x : fa[x] = Find(fa[x]); } void Union(int x, int y) { fa[Find(x)] = Find(y); } 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++) for (int j = 1; j <= m; j++) { char ch = getchar(); while (ch != '<' && ch != '=' && ch != '>') ch = getchar(); if (ch == '=') Union(i, n + j); if (ch == '<') d[i].push_back(n + j); if (ch == '>') d[n + j].push_back(i); } for (int i = 1; i <= n + m; i++) { s.insert(Find(i)); for (auto j : d[i]) { if (Find(i) == Find(j)) return printf("No\n"), 0; d2[Find(i)].push_back(Find(j)), g[Find(j)]++; } } for (auto i : s) { f[i] = 1; if (!g[i]) q.push(i); } while (!q.empty()) { int cur = q.front(); q.pop(); s.erase(cur); for (auto nxt : d2[cur]) { f[nxt] = max(f[nxt], f[cur] + 1); g[nxt]--; if (!g[nxt]) q.push(nxt); } } if (!s.empty()) return printf("No\n"), 0; for (int i = 1; i <= n + m; i++) f[i] = f[Find(i)]; printf("Yes\n"); for (int i = 1; i <= n; i++) printf("%d%c", f[i], i < n ? ' ' : '\n'); for (int i = n + 1; i <= n + m; i++) printf("%d%c", f[i], i < n + m ? ' ' : '\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 int mod = 1e9 + 7; const int INF = INT_MAX; const long double pi = 4 * atan((long double)1); vector<int> AdjList[2005]; int ran[2005]; int parent[2005], siz[2005], up[2005]; bool check; int visited[2005]; bool les[2005], pass[2005]; void make_set(int v) { parent[v] = v; siz[v] = 1; } int find_set(int v) { if (parent[v] == v) return v; return parent[v] = find_set(parent[v]); } void union_set(int a, int b) { a = find_set(a), b = find_set(b); if (a == b) return; if (siz[a] < siz[b]) swap(a, b); parent[b] = a; siz[a] += siz[b]; } void dfs(int start, int rk) { ran[start] = rk; visited[start] = 1; if (check) return; for (int i = 0; i < AdjList[start].size(); i++) { int u = AdjList[start][i]; if (visited[u] == 1) { check = true; return; } if (visited[u] == 2) { if (ran[u] < rk + 1) dfs(u, rk + 1); else if (ran[u] > rk + 1) continue; } else dfs(u, rk + 1); } visited[start] = 2; } signed main() { ios::sync_with_stdio(); cin.tie(0); cout.tie(0); ; int n, m; cin >> n >> m; for (int i = 1; i <= n + m; i++) make_set(i); string str[n + 2]; for (int i = 1; i <= n; i++) { cin >> str[i]; for (int j = 0; j < str[i].length(); j++) { if (str[i][j] == '=') { union_set(i, j + 1 + n); } } } for (int i = 1; i <= n + m; i++) parent[i] = find_set(i); for (int i = 1; i <= n; i++) { for (int j = 0; j < str[i].length(); j++) { if (str[i][j] == '>') { if (parent[j + 1 + n] == parent[i]) { cout << "No"; return 0; } AdjList[parent[j + 1 + n]].push_back(parent[i]); les[parent[i]] = true; } if (str[i][j] == '<') { if (parent[j + 1 + n] == parent[i]) { cout << "No"; return 0; } AdjList[parent[i]].push_back(parent[j + 1 + n]); les[parent[j + 1 + n]] = true; } } } for (int i = 1; i <= n + m; i++) { if (!les[parent[i]]) { dfs(parent[i], 1); } if (check) { cout << "No"; return 0; } } cout << "Yes" << endl; for (int i = 1; i <= n; i++) cout << ran[parent[i]] << " "; cout << endl; for (int i = n + 1; i <= n + m; i++) cout << ran[parent[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
import java.util.*; import java.io.*; import java.math.*; import java.util.Comparator; public class Main { static int[] p; public static void main(String[] args)throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer stk = new StringTokenizer(br.readLine()); int n = Integer.parseInt(stk.nextToken()); int m = Integer.parseInt(stk.nextToken()); char[][] map = new char[n][m]; p = new int[n+m]; for(int i=0;i<p.length;i++){ p[i] = i; } ArrayList<Integer>[] edge = new ArrayList[n+m]; int[] indegree = new int[n+m]; for(int i=0;i<n+m;i++){ edge[i] = new ArrayList<>(); } for(int i=0;i<n;i++){ String s = br.readLine(); for(int j=0;j<m;j++){ map[i][j] = s.charAt(j); if(map[i][j] == '='){ int x = find(i); int y = find(j+n); if(x!=y){ if(edge[y].size()>= edge[x].size()){ for(int k=0;k<edge[x].size();k++){ edge[y].add(edge[x].get(k)); } p[x] = y; indegree[y] += indegree[x]; } else{ for(int k=0;k<edge[y].size();k++){ edge[x].add(edge[y].get(k)); } p[y] = x; indegree[x] += indegree[y]; } } } else if(map[i][j] == '<'){ edge[find(i)].add(find(n+j)); indegree[find(n+j)] ++; } else{ edge[find(n+j)].add(find(i)); indegree[find(i)] ++; } } } int[] ans = new int[n+m]; boolean[] vis = new boolean[n+m]; Queue<Integer> q =new LinkedList<>(); for(int i=0;i<n+m;i++){ if(indegree[find(i)] == 0 && !vis[find(i)]) { vis[find(i)] = true; ans[find(i)] = 1; q.add(find(i)); } } while(!q.isEmpty()){ int p = q.poll(); vis[p] = true; int x = find(p); for(int i=0;i<edge[x].size();i++){ int y= find(edge[x].get(i)); indegree[y]--; ans[y] = Math.max(ans[y],ans[x]+1); if(indegree[y] == 0){ q.add(y); } } } for(int i=0;i<n+m;i++){ if(indegree[find(i)] != 0){ System.out.println("No"); return; } } for(int i=0;i<n+m;i++){ ans[i] = ans[find(i)]; } System.out.println("Yes"); StringBuilder sb= new StringBuilder(); for(int i=0;i<n;i++){ sb.append(ans[i]+" "); } sb.append('\n'); for(int j=n;j<n+m;j++){ sb.append(ans[j]+" "); } System.out.println(sb); } public static int find(int x){ if(p[x] == x) return x; return p[x] = find(p[x]); } }
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.*; public class Main { static ArrayList<Node> V = new ArrayList<>(); /** * @param args the command line arguments */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); char[][] c = new char[n][m]; for (int i = 0; i < n; i++) { String line = sc.next(); for (int j = 0; j < m; j++) { c[i][j] = line.charAt(j); } } int[] a = new int[n]; int[] b = new int[m]; Arrays.fill(a, -1); Arrays.fill(b, -1); for (int i = 0; i < n; i++) { if (a[i] == -1) { ArrayDeque<Integer> qa = new ArrayDeque<>(); ArrayDeque<Integer> qb = new ArrayDeque<>(); qa.add(i); int count = V.size(); V.add(new Node()); while (!qa.isEmpty() || !qb.isEmpty()) { if (!qa.isEmpty()) { int j = qa.removeFirst(); if (a[j] != -1) continue; a[j] = count; for (int k = 0; k < m; k++) { if (c[j][k] == '=') { qb.add(k); } else if (c[j][k] == '>') { V.get(count).adjFirstB.add(k); } } } else { int j = qb.removeFirst(); if (b[j] != -1) continue; b[j] = count; for (int k = 0; k < n; k++) { if (c[k][j] == '=') { qa.add(k); } else if (c[k][j] == '<') { V.get(count).adjFirstA.add(k); } } } } } } for (int i = 0; i < m; i++) { if (b[i] == -1) { ArrayDeque<Integer> qa = new ArrayDeque<>(); ArrayDeque<Integer> qb = new ArrayDeque<>(); qb.add(i); int count = V.size(); V.add(new Node()); while (!qa.isEmpty() || !qb.isEmpty()) { if (!qa.isEmpty()) { int j = qa.removeFirst(); if (a[j] != -1) continue; a[j] = count; for (int k = 0; k < m; k++) { if (c[j][k] == '=') { qb.add(k); } else if (c[j][k] == '>') { V.get(count).adjFirstB.add(k); } } } else { int j = qb.removeFirst(); if (b[j] != -1) continue; b[j] = count; for (int k = 0; k < n; k++) { if (c[k][j] == '=') { qa.add(k); } else if (c[k][j] == '<') { V.get(count).adjFirstA.add(k); } } } } } } for (Node v : V) { HashSet<Integer> adj = new HashSet<>(); for (int i : v.adjFirstA) { adj.add(a[i]); } for (int i : v.adjFirstB) { adj.add(b[i]); } for (int i : adj) { v.adj.add(i); } } int[] scoreA = new int[n]; int[] scoreB = new int[m]; for (int i = 0; i < n; i++) { scoreA[i] = getScore(a[i]); } for (int i = 0; i < m; i++) { scoreB[i] = getScore(b[i]); } boolean pos = true; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (c[i][j] == '>' && scoreA[i] <= scoreB[j]) pos = false; if (c[i][j] == '<' && scoreA[i] >= scoreB[j]) pos = false; if (c[i][j] == '=' && scoreA[i] != scoreB[j]) pos = false; } } if (pos) { System.out.println("Yes"); for (int i = 0; i < n; i++) { System.out.print(scoreA[i] + " "); } System.out.println(); for (int i = 0; i < m; i++) { System.out.print(scoreB[i] + " "); } System.out.println(); } else { System.out.println("No"); } } static int getScore(int i) { if (V.get(i).visited) return V.get(i).score; V.get(i).visited = true; for (int j : V.get(i).adj) { V.get(i).score = Math.max(V.get(i).score, getScore(j) + 1); } return V.get(i).score; } } class Node { ArrayList<Integer> adjFirstA = new ArrayList<>(); ArrayList<Integer> adjFirstB = new ArrayList<>(); ArrayList<Integer> adj = new ArrayList<>(); int score = 1; boolean visited = false; }
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.ArrayList; public class P1131D { private static int n, m; private static int[][] a; private static ArrayList<Dishes> dishes1, dishes2; private static class Dishes { private ArrayList<Dishes> more, equal; private boolean progressing, checked; private int score; private Dishes() { this.more = new ArrayList<Dishes>(); this.equal = new ArrayList<Dishes>(); this.score = 0; } protected int setScore(int score) { if (this.score == 0) { this.score = score; for (Dishes d : this.equal) { d.setScore(score); } return score; } else if (this.score == score) { return score; } else { throw new UnsupportedOperationException(); } } } private static int setScore(Dishes currentDish) { if (currentDish.checked) { return currentDish.score; } if (currentDish.progressing) { throw new UnsupportedOperationException(); } currentDish.progressing = true; int lowerBound = 0; for (Dishes d : currentDish.more) { if (setScore(d) > lowerBound) { lowerBound = d.score; } } currentDish.progressing = false; if (currentDish.equal.size() == 0) { currentDish.setScore(lowerBound + 1); currentDish.checked = true; return lowerBound + 1; } else { Dishes firstEqual = currentDish.equal.get(0); for (Dishes d : firstEqual.more) { if (setScore(d) > lowerBound) { currentDish.setScore(lowerBound + 2); d.setScore(lowerBound + 1); currentDish.checked = true; return lowerBound + 2; } } currentDish.setScore(lowerBound + 1); currentDish.checked = true; return lowerBound + 1; } } public static void main(String[] args) throws IOException, NumberFormatException { BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); String inputLine = input.readLine(); String[] numberTokens = inputLine.split(" "); n = Integer.parseInt(numberTokens[0]); m = Integer.parseInt(numberTokens[1]); a = new int[n][m]; dishes1 = new ArrayList<Dishes>(n); dishes2 = new ArrayList<Dishes>(m); for (int i = 0; i < n; i++) { dishes1.add(new Dishes()); } for (int i = 0; i < m; i++) { dishes2.add(new Dishes()); } char[] tokens; for (int i = 0; i < n; i++) { inputLine = input.readLine(); tokens = inputLine.toCharArray(); for (int j = 0; j < m; j++) { if (tokens[j] == '>') { a[i][j] = 1; dishes1.get(i).more.add(dishes2.get(j)); } else if (tokens[j] == '=') { a[i][j] = 0; dishes1.get(i).equal.add(dishes2.get(j)); dishes2.get(j).equal.add(dishes1.get(i)); } else if (tokens[j] == '<') { a[i][j] = -1; dishes2.get(j).more.add(dishes1.get(i)); } else { throw new AssertionError(); } } } StringBuilder resultString = new StringBuilder(); try { for (int i = 0; i < n; i++) { resultString.append(setScore(dishes1.get(i)) + " "); } resultString.append("\n"); for (int i = 0; i < m; i++) { resultString.append(setScore(dishes2.get(i)) + " "); } System.out.print("YES\n" + resultString.toString()); } catch (UnsupportedOperationException e) { System.out.print("NO"); } } }
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 sys from collections import deque sys.setrecursionlimit(10**6) readline = sys.stdin.readline N, M = map(int, readline().split()) L = [readline().strip() for i in range(N)] def root(x): if x == p[x]: return x p[x] = y = root(p[x]) return y def unite(x, y): px = root(x); py = root(y) if px < py: p[py] = px else: p[px] = py *p, = range(N+M) for i in range(N): for j, c in enumerate(L[i]): if c == '=': unite(i, N+j) G = [[] for i in range(N+M)] RG = [[] for i in range(N+M)] deg = [0]*(N+M) for i in range(N): x = root(i) for j, c in enumerate(L[i]): y = root(N+j) if c == '<': G[x].append(y) RG[y].append(x) deg[y] += 1 elif c == '>': G[y].append(x) RG[x].append(y) deg[x] += 1 A = [-1]*(N+M) que = deque() for i in range(N+M): if root(i) == i and deg[i] == 0: que.append(i) while que: v = que.popleft() lb = 0 for w in RG[v]: lb = max(lb, A[w]) A[v] = lb+1 for w in G[v]: deg[w] -= 1 if deg[w] == 0: que.append(w) if any(root(i) == i and A[i] == -1 for i in range(N+M)): print("No") else: for i in range(N+M): A[i] = A[root(i)] print("Yes") print(*A[:N]) print(*A[N:])
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; inline void in(int &n) { n = 0; int ch = getchar(); int sign = 1; while (ch < '0' || ch > '9') { if (ch == '-') sign = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { n = (n << 3) + (n << 1) + ch - '0', ch = getchar(); } n = n * sign; } int P[2005]; int findPar(int n) { if (P[n] == n) return n; int x = findPar(P[n]); P[n] = x; return x; } int main() { int n, m; scanf("%d %d", &n, &m); for (int i = 0; i < n; ++i) { P[i] = i; } for (int i = n; i < n + m; ++i) { P[i] = i; } char a[n][m]; for (int i = 0; i < n; ++i) { scanf("%s", a[i]); } for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (a[i][j] == '=') { int pi = findPar(i); int pj = findPar(n + j); if (pi != pj) { P[pj] = pi; } } } } set<int> S; for (int i = 0; i < n; ++i) { S.insert(findPar(i)); } for (int i = n; i < n + m; ++i) { S.insert(findPar(i)); } map<int, int> M; int cnt = 0; for (set<int>::iterator it = S.begin(); it != S.end(); it++) { M.insert(pair<int, int>(*it, cnt)); cnt++; } int inDegree[cnt]; for (int i = 0; i < cnt; ++i) { inDegree[i] = 0; } vector<int> graph[cnt]; bool isPossible = true; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (a[i][j] == '<') { int pi = findPar(i); int pj = findPar(n + j); if (pi == pj) { isPossible = false; break; } else { graph[M[pi]].push_back(M.find(pj)->second); inDegree[M[pj]]++; } } else if (a[i][j] == '>') { int pi = findPar(i); int pj = findPar(n + j); if (pi == pj) { isPossible = false; break; } else { graph[M[pj]].push_back(M.find(pi)->second); inDegree[M[pi]]++; } } } if (isPossible == false) { break; } } if (!isPossible) { printf("No\n"); return 0; } int ans[cnt]; queue<int> Q; for (int i = 0; i < cnt; ++i) { if (inDegree[i] == 0) { Q.push(i); ans[i] = 1; } } bool visited[cnt]; for (int i = 0; i < cnt; ++i) { visited[i] = false; } while (!(Q.empty())) { int curr = Q.front(); visited[curr] = true; Q.pop(); for (int i = 0; i < graph[curr].size(); i++) { int next = graph[curr][i]; if (visited[next] == false) { inDegree[next]--; if (inDegree[next] == 0) { Q.push(next); ans[next] = ans[curr] + 1; } } } } for (int i = 0; i < cnt; ++i) { if (inDegree[i]) { isPossible = false; } } if (isPossible) { printf("Yes\n"); for (int i = 0; i < n; ++i) { int pi = findPar(i); printf("%d ", ans[M.find(pi)->second]); } printf("\n"); for (int i = n; i < n + m; ++i) { int pi = findPar(i); printf("%d ", ans[M.find(pi)->second]); } printf("\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
n, m = (int(t) for t in input().split(' ')) def direction(c): if c == '=': return 0 if c == '>': return 1 return -1 mx = [[direction(c) for c in input()] for _ in range(n)] index = 0 class DSet(object): def __init__(self, value): global index self.values = set([value]) self.index = index index += 1 self.edges_to = set() self.edges_from = set() def __len__(self): return len(self.values) def update(self, other_dset): self.values.update(other_dset.values) def add_edge_to(self, i): self.edges_to.add(i) def add_edge_from(self, i): self.edges_from.add(i) def remove_edge_from(self, i): self.edges_from.remove(i) dsu = [DSet(i) for i in range(n+m)] def union(v1, v2): if len(dsu[v1]) > len(dsu[v2]): d = dsu[v1] d.update(dsu[v2]) else: d = dsu[v2] d.update(dsu[v1]) dsu[v1] = dsu[v2] = d for i in range(n): for j in range(m): if not mx[i][j]: union(i, n + j) for i in range(n): for j in range(m): if mx[i][j] > 0: dsu[i].add_edge_from(dsu[n + j].index) dsu[n+j].add_edge_to(dsu[i].index) elif mx[i][j] < 0: dsu[n + j].add_edge_from(dsu[i].index) dsu[i].add_edge_to(dsu[n+j].index) weights = [1] * (n+m) dsu_by_index = { d.index: d for d in dsu } while True: try: v = next(d for d in range(n+m) if not len(dsu[d].edges_from) and len(dsu[d].edges_to)) except: break dsuv = dsu[v] for edge in dsu[v].edges_to: dsue = dsu_by_index[edge] dsue.remove_edge_from(dsuv.index) for value in dsue.values: weights[value] = weights[v] + 1 dsu[v].edges_to.clear() ok = all(not len(d.edges_from) and not len(d.edges_to) for d in dsu) if ok: print('Yes') print(*weights[0:n]) print(*weights[n:]) 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> #pragma GCC optimize("O3") #pragma GCC optimize("unroll-loops") #pragma GCC target("avx2") using namespace std; vector<vector<int> > g; vector<vector<int> > g1; vector<set<int> > gcol; vector<int> col; int nw = 0; void dfs(int v) { col[v] = nw; for (auto t : g[v]) if (col[t] == -1) dfs(t); } int main() { ios::sync_with_stdio(false); cin.tie(0); int n, m; cin >> n >> m; col.resize(n + m, -1); g.resize(n + m, vector<int>()); g1.resize(n + m, vector<int>()); char q[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> q[i][j]; if (q[i][j] == '>') g1[i].push_back(n + j); else if (q[i][j] == '<') g1[n + j].push_back(i); else { g[i].push_back(n + j); g[n + j].push_back(i); } } } for (int i = 0; i < n + m; i++) { if (col[i] == -1) { dfs(i); nw++; } } gcol.resize(nw, set<int>()); for (int i = 0; i < n + m; i++) { for (auto t : g1[i]) gcol[col[i]].insert(col[t]); } vector<int> ans(nw, 0); vector<int> us(nw, 0); int ost = nw; for (int i = 1; ost > 0; i++) { vector<int> del; for (int j = 0; j < nw; j++) { if (!us[j] && gcol[j].size() == 0) { ans[j] = i; us[j] = 1; del.push_back(j); ost--; } } if (del.size() == 0) break; for (auto t : del) { for (int j = 0; j < nw; j++) gcol[j].erase(t); } } if (ost > 0) { cout << "No\n"; } else { for (int i = 0; i < n + m; i++) { col[i] = ans[col[i]]; } bool ok = true; if (!ok) cout << "No"; else { cout << "Yes\n"; for (int i = 0; i < n; i++) cout << col[i] << " "; cout << "\n"; for (int i = n; i < n + m; i++) cout << col[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> const int N = 1e3; const int inf = 1e7; using namespace std; int n, m, fa[N * 2 + 5], id[N + 5][N + 5], idc, mp[N * 2 + 5][N * 2 + 5], f[N * 2 + 5], d[N * 2 + 5], q[N * N + 5]; char ch[N + 5][N + 5]; int find(int x) { if (fa[x] == x) return x; return fa[x] = find(fa[x]); } void topo() { int l = 1, r = 0; for (int i = 1; i <= n + m; i++) if (!d[i] && fa[i] == i) { f[i] = 1; q[++r] = i; } while (l <= r) { int u = q[l++]; for (int i = 1; i <= n + m; i++) if (mp[u][i]) { f[i] = max(f[i], f[u] + 1); d[i]--; if (!d[i]) q[++r] = i; } } } int main() { scanf("%d%d", &n, &m); for (int i = 1; i <= n; i++) scanf("%s", ch[i] + 1); for (int i = 1; i <= n + m; i++) fa[i] = i; int las = 0; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) if (ch[i][j] == '=') { if (!las) { las = i; fa[j + n] = i; } else fa[find(j + n)] = find(i); } for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { int X = find(i), Y = find(j + n); if (ch[i][j] == '<') { if (mp[Y][X] || Y == X) { cout << "No" << endl; return 0; } if (mp[X][Y]) continue; mp[X][Y] = 1; d[Y]++; } if (ch[i][j] == '>') { if (mp[X][Y] || Y == X) { cout << "No" << endl; return 0; } if (mp[Y][X]) continue; mp[Y][X] = 1; d[X]++; } } topo(); for (int i = 1; i <= n + m; i++) if (d[find(i)]) { cout << "No" << endl; return 0; } cout << "Yes" << endl; for (int i = 1; i <= n; i++) printf("%d ", f[find(i)]); cout << endl; for (int i = n + 1; i <= m + n; i++) printf("%d ", f[find(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
import java.io.*; import java.util.*; public class MainClass { static int n, m; static char[][] A; static BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); static StringBuilder stringBuilder = new StringBuilder(); static boolean[] visited; static int[] ids; static List<Integer>[] adj; static List<Integer> postOrder = new ArrayList<>(); static Set<Integer> set = new HashSet<>(); public static void main(String[] args)throws IOException { String s1[] = in.readLine().split(" "); n = Integer.parseInt(s1[0]); m = Integer.parseInt(s1[1]); A = new char[n][m]; visited = new boolean[n + m]; ids = new int[n + m]; adj = new ArrayList[n + m]; for (int i=0;i<n + m;i++) adj[i] = new ArrayList<>(); for (int i=0;i<n;i++) A[i] = in.readLine().toCharArray(); for (int i=0;i<n + m;i++) ids[i] = i; solve(); } public static void solve() { for (int i=0;i<n;i++) for (int j=0;j<m;j++) if (A[i][j] == '=') ids[i] = ids[n + j] = Math.min(ids[i], ids[n + j]); for (int i=0;i<n;i++) for (int j=0;j<m;j++) if (A[i][j] != '=') { if (ids[i] == ids[n + j]) { System.out.println("No"); System.exit(0); } if (A[i][j] == '>') adj[ids[n + j]].add(ids[i]); else adj[ids[i]].add(ids[n + j]); } for (int i=0;i<n + m;i++) if (!visited[i]) explore(i, -1); long[] dp = new long[n + m]; for (int i: postOrder) { dp[i] = 1L; long max = 0L; for (int u: adj[i]) max = Math.max(dp[u], max); dp[i] += max; } long max = 1L; for (int i=0;i<n + m;i++) max = Math.max(max, dp[i]); stringBuilder.append("Yes\n"); for (int i=0;i<n;i++) stringBuilder.append(max - dp[ids[i]] + 1).append(" "); stringBuilder.append("\n"); for (int i=0;i<m;i++) stringBuilder.append(max - dp[ids[n + i]] + 1).append(" "); System.out.println(stringBuilder); } public static void explore(int v, int par) { visited[v] = true; set.add(v); for (int u: adj[v]) { if (u == par) continue; else if (!visited[u]) explore(u, v); else if (set.contains(u)) { System.out.println("No"); System.exit(0); } } set.remove(v); postOrder.add(v); } } class Reader { final private int BUFFER_SIZE = 1 << 16; private final DataInputStream din; private final byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } }
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> #pragma comment(linker, "/stack:200000000") #pragma GCC optimize("Ofast") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") #pragma GCC optimize("unroll-loops") using namespace std; char ara[1005][1005]; int par[2005], levv[2005], mini; vector<int> ls[2005]; bool vis[2005], app[2005], p; int findp(int x) { if (par[x] == x) return x; return par[x] = findp(par[x]); } void dfs(int x, int lev) { app[x] = true; mini = min(mini, lev); int ret = 0; for (int v : ls[findp(x)]) { if (levv[findp(v)] > lev - 1) { if (app[findp(v)]) { p = true; return; } levv[findp(v)] = min(levv[findp(v)], lev - 1); dfs(findp(v), levv[findp(v)]); if (p) return; } } vis[findp(x)] = true; app[x] = false; return; } int main() { ios_base::sync_with_stdio(false); int n, m; cin >> n >> m; for (int i = 0; i < n + m; i++) par[i] = i; p = false; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { char c; cin >> c; ara[i][j] = c; int fi = findp(i + m); int fj = findp(j); if (c == '=') par[fi] = fj; } for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { char c; c = ara[i][j]; int fi = findp(i + m); int fj = findp(j); if (c != '=' && fi == fj) p = true; if (c == '>') ls[fi].push_back(fj); else if (c == '<') ls[fj].push_back(fi); } if (p) return cout << "No" << endl, 0; for (int i = 0; i < n + m; i++) if (ls[findp(i)].size() > 0 && vis[findp(i)] == 0) dfs(findp(i), 0); if (p) return cout << "No" << endl, 0; cout << "Yes" << endl; for (int i = 0; i < n; i++) cout << levv[findp(i + m)] - mini + 1 << " "; cout << endl; for (int i = 0; i < m; i++) cout << levv[findp(i)] - mini + 1 << " "; }
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.*; public class ACM { private static int find(int k, int[] fa) { fa[k] = (fa[k] == k ? k : find(fa[k], fa)); return fa[k]; } public static void main(String[] args) { int N = 2010; Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); ArrayList<String> a = new ArrayList<>(); ArrayList<Integer> res1 = new ArrayList<>(); ArrayList<ArrayList<Integer>> edges = new ArrayList<>(); int[] fa = new int[N]; int[] in = new int[N]; for (int i = 0; i < N; ++i) { res1.add(null); edges.add(new ArrayList<>()); } for (int i = 0; i < N; ++i) { fa[i] = i; } for (int i = 0; i < n; ++i) { String s = sc.next(); a.add(s); for (int j = 0; j < s.length(); ++j) { char c = s.charAt(j); if (c == '=') { fa[ find(j + n , fa)] = i; } } } for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { char c = a.get(i).charAt(j); int faI = find(i, fa); int faJ = find(n + j, fa); // System.out.println(i+","+j+"," + faI + "," + faJ); if (c == '<') { edges.get(faI).add(faJ); in[faJ]++; } else if (c == '>') { edges.get(faJ).add(faI); in[faI]++; } } } ArrayList<Integer> queue = new ArrayList<>(); for (int i = 0; i < n + m; ++i) { int fai = find(i, fa); if (in[fai] == 0 && !queue.contains(fai)) { queue.add(fai); res1.set(fai,1); } } while (!queue.isEmpty()) { int i = queue.get(queue.size() - 1); queue.remove(queue.size() - 1); for (Integer to : edges.get(i)) { in[to]--; if (in[to] == 0) { queue.add(to); res1.set(to,res1.get(i) + 1); } } } boolean f = false; for (int i = 0; i < n && !f; ++i) { for (int j = n; j < n + m && !f; ++j) { int fai = find(i, fa); int faj = find(j, fa); if (res1.get(fai) == null || res1.get(faj) == null) { f = true; break; } char c = a.get(i).charAt(j - n); if (c == '=' && res1.get(fai) != res1.get(faj)) { f = true; break; } else if (c == '>' && res1.get(fai) <= res1.get(faj)) { f = true; break; } else if (c == '<' && res1.get(fai) >= res1.get(faj)) { f = true; break; } } } // for (int i = 0; i < n + m; ++i) { // if (i == n) { // System.out.println(); // } // System.out.print(res1.get(find(i, fa)) + " "); // } if (f) { System.out.print("No"); } else { System.out.println("Yes"); for (int i = 0; i < n + m; ++i) { if (i == n) { System.out.println(); } System.out.print(res1.get(find(i, fa)) + " "); } } } }
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.*; 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; } } } Set<Integer> was = new HashSet<>(); boolean bad = false; int num = 1; int[] ans = new int[sz]; while (was.size() < sz && !bad) { Set<Integer> cur = new HashSet<>(); for (int v = 0; v < sz; v++) { if (!was.contains(v) && nodes[v].gr == 0) { cur.add(v); } } Queue<Integer> queue = new ArrayDeque<>(); boolean[] visited = new boolean[sz]; List<Integer> toRm = new ArrayList<>(); for (int v = 0; v < sz; v++) { if (!cur.contains(v)) { queue.add(v); visited[v] = true; } } while (!queue.isEmpty()) { int v = queue.poll(); toRm.add(v); for (int u: nodes[v].eq) { if (!visited[u]) { visited[u] = true; queue.add(u); } } } cur.removeAll(toRm); if (cur.size() == 0) { bad = true; break; } for (int v: cur) { was.add(v); 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.printf("%d ", 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
import sys import collections def main(): input = iter(sys.stdin) N, M = map(int, next(input).split()) dsu = DSU(N + M) edges = [] for i in range(N): line = next(input).strip() for j, sign in enumerate(line): j = j + N if sign == '=': dsu.merge(i, j) else: edges.append((i, j) if sign == '<' else (j, i)) incoming = collections.defaultdict(set) outgoing = collections.defaultdict(set) nodes = sorted(set([dsu.root(i) for i in range(N + M)])) for i, j in edges: incoming[dsu.root(i)].add(dsu.root(j)) outgoing[dsu.root(j)].add(dsu.root(i)) no_incoming = list(set(i for i in nodes if i not in incoming)) ordering = [] while no_incoming: node = no_incoming.pop(-1) ordering.append(node) for n in outgoing[node]: incoming[n].discard(node) if not incoming[n]: no_incoming.append(n) if len(ordering) != len(nodes): return 'NO' root_to_index = {} for n in reversed(ordering): if not outgoing[n]: root_to_index[n] = 0 else: root_to_index[n] = max(root_to_index[x] for x in outgoing[n]) + 1 s = ['YES'] s.append(' '.join(str(root_to_index[dsu.root(i)] + 1) for i in range(N))) s.append(' '.join(str(root_to_index[dsu.root(i + N)] + 1) for i in range(M))) return '\n'.join(s) class DSU(): def __init__(self, n): self.parents = [i for i in range(n)] def root(self, i): try: if self.parents[i] != i: self.parents[i] = self.root(self.parents[i]) except: print(i, len(self.parents)) raise return self.parents[i] def merge(self, i, j): r1 = self.root(i) r2 = self.root(j) if r1 != r2: self.parents[r1] = r2 if __name__ == '__main__': print(main())
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.io.*; import java.util.*; import java.util.function.Function; public class MainD { static int N, M; static char[][] C; public static void main(String[] args) { FastScanner sc = new FastScanner(System.in); N = sc.nextInt(); M = sc.nextInt(); C = new char[N][]; for (int i = 0; i < N; i++) { C[i] = sc.next().toCharArray(); } boolean ans = solve(); System.out.println(ans ? "Yes" : "No"); if( ans ) { StringJoiner j = new StringJoiner(" "); for (int n : NC) { j.add(String.valueOf(n)); } System.out.println( j.toString() ); j = new StringJoiner(" "); for (int m : MC) { j.add(String.valueOf(m)); } System.out.println( j.toString() ); } } static int[] NC; static int[] MC; static boolean solve() { UnionFind uf = new UnionFind(N+M); for (int n = 0; n < N; n++) { for (int m = 0; m < M; m++) { if( C[n][m] == '=' ) { uf.unite(n, N+m); } } } List<int[]> E = new ArrayList<>(); for (int n = 0; n < N; n++) { for (int m = 0; m < M; m++) { char c = C[n][m]; if( c == '>' ) { if( uf.isSame(N+m, n) ) { return false; } E.add( new int[]{uf.root(N+m), uf.root(n)} ); } else if( c == '<' ) { if( uf.isSame(n, N+m) ) { return false; } E.add( new int[]{uf.root(n), uf.root(N+m)} ); } } } int[][] G = adjD(N+M, E); int[][] topo = khan(N+M, G); if( topo == null ) return false; // debug(topo); // 多分分けないほうが楽だがもう動いたし... NC = new int[N]; MC = new int[M]; for (int[] vr : topo) { int v = vr[0]; int rank = vr[1]; if( uf.isRoot(v) ) { if( vr[0] < N ) { NC[vr[0]] = rank; } else { MC[vr[0]-N] = rank; } } } for (int i = 0; i < N+M; i++) { if( !uf.isRoot(i) ) { int r = uf.root(i); (i < N ? NC:MC)[i < N ? i : i-N] = (r < N ? NC:MC)[r < N ? r : r-N]; } } return true; } static int[][] khan(int V, int[][] G) { int[] deg = new int[V]; for (int[] tos : G) { for (int to : tos) { deg[to]++; } } int[][] q = new int[V][2]; int a = 0, b = 0; for (int v = 0; v < V; v++) { if( deg[v] == 0 ) { q[b][0] = v; q[b][1] = 1; b++; } } int[][] ret = new int[V][2]; int idx = 0; while( a != b ) { int[] vr = q[a++]; ret[idx++] = vr; int v = vr[0]; int r = vr[1]; for (int to : G[v]) { deg[to]--; if( deg[to] == 0 ) { q[b][0] = to; q[b][1] = r+1; b++; } } } for (int v = 0; v < V; v++) { if( deg[v] != 0 ) return null; } return ret; } static int[][] adjD(int n, List<int[]> es) { int[][] adj = new int[n][]; int[] cnt = new int[n]; for (int[] e : es) { cnt[e[0]]++; } for (int i = 0; i < n; i++) { adj[i] = new int[cnt[i]]; } for (int[] e : es) { adj[e[0]][--cnt[e[0]]] = e[1]; } return adj; } static boolean useThisEdge(int[] e, UnionFind uf) { return uf.isRoot(e[0]) && uf.isRoot(e[1]); } static class UnionFind { private final int[] parent; private final int[] rank; public UnionFind(int n) { parent = new int[n]; rank = new int[n]; for (int i = 0; i < n; i++) { parent[i] = i; rank[i] = 0; } } public int root(int i) { if( parent[i] == i ) { return i; } else { return parent[i] = root(parent[i]); } } public boolean isRoot(int i) { return root(i) == i; } public void unite(int i, int j) { int ri = root(i); int rj = root(j); if( ri == rj ) return; if( rank[ri] < rank[rj] ) { parent[ri] = rj; } else { parent[rj] = ri; if( rank[ri] == rank[rj] ) { rank[ri]++; } } } public boolean isSame(int a, int b) { return root(a) == root(b); } } @SuppressWarnings("unused") static class FastScanner { private BufferedReader reader; private StringTokenizer tokenizer; FastScanner(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); tokenizer = null; } String next() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } String nextLine() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken("\n"); } long nextLong() { return Long.parseLong(next()); } int nextInt() { return Integer.parseInt(next()); } int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArray(int n, int delta) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt() + delta; return a; } long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } } static <A> void writeLines(A[] as, Function<A, String> f) { PrintWriter pw = new PrintWriter(System.out); for (A a : as) { pw.println(f.apply(a)); } pw.flush(); } static void writeLines(int[] as) { PrintWriter pw = new PrintWriter(System.out); for (int a : as) pw.println(a); pw.flush(); } static void writeLines(long[] as) { PrintWriter pw = new PrintWriter(System.out); for (long a : as) pw.println(a); pw.flush(); } static int max(int... as) { int max = Integer.MIN_VALUE; for (int a : as) max = Math.max(a, max); return max; } static int min(int... as) { int min = Integer.MAX_VALUE; for (int a : as) min = Math.min(a, min); return min; } static void debug(Object... args) { StringJoiner j = new StringJoiner(" "); for (Object arg : args) { if (arg instanceof int[]) j.add(Arrays.toString((int[]) arg)); else if (arg instanceof long[]) j.add(Arrays.toString((long[]) arg)); else if (arg instanceof double[]) j.add(Arrays.toString((double[]) arg)); else if (arg instanceof Object[]) j.add(Arrays.toString((Object[]) arg)); else j.add(arg.toString()); } System.err.println(j.toString()); } }
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 = 20001; int p[N], a[N]; int n, m, judge = 0; int t[N], ans[N], b[N]; char s[1020][1020]; vector<int> v[2080]; int f(int x) { if (p[x] == x) return x; return p[x] = f(p[x]); } void unite(int x, int y) { int xx = f(x), yy = f(y); p[yy] = p[xx]; } int main() { memset(b, 0, sizeof(b)); memset(t, 0, sizeof(t)); scanf("%d %d", &n, &m); for (int i = 1; i <= n + m; i++) p[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] == '=') { unite(i, j + n); } } } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (s[i][j] == '>') v[f(j + n)].push_back(f(i)), t[f(i)]++; else if (s[i][j] == '<') v[f(i)].push_back(f(j + n)), t[f(j + n)]++; } } priority_queue<pair<int, int> > q; for (int i = 1; i <= n + m; i++) if (f(i) == i) judge++; for (int i = 1; i <= n + m; i++) { if (!t[p[i]] && !b[p[i]]) { q.push(make_pair(p[i], 1)); b[p[i]] = 1; } } int sum = 0, num = 1; while (!q.empty()) { int now = q.top().first, w = q.top().second; q.pop(); sum++; ans[now] = w; for (int i = 0; i < v[now].size(); i++) { int pos = v[now][i]; t[pos]--; if (!t[pos]) { q.push(make_pair(pos, w + 1)); } } } if (sum < judge) { puts("No"); return 0; } puts("Yes"); for (int i = 1; i <= n; i++) printf("%d ", ans[p[i]]); puts(""); for (int i = n + 1; i <= m + n; i++) printf("%d ", ans[p[i]]); 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; vector<int> g[2007]; char s[1007][1007]; int fa[2007], vis[2007], shu[2007]; int find(int x) { return x == fa[x] ? x : fa[x] = find(fa[x]); } int flag = 0; void dfs(int u) { vis[u] = -1; shu[u] = 1; for (int i = 0; i < g[u].size(); i++) { int v = g[u][i]; if (vis[v] == -1) { flag = 1; return; } else if (vis[v]) { shu[u] = max(shu[u], shu[v] + 1); } else dfs(v), shu[u] = max(shu[u], shu[v] + 1); } vis[u] = 1; } int main() { int n, m; cin >> 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 k = 1; k <= m; k++) { if (s[i][k] == '=') { int x = find(i), y = find(n + k); if (x != y) fa[x] = y; } } } for (int i = 1; i <= n; i++) { for (int k = 1; k <= m; k++) { int x = find(i), y = find(n + k); if (s[i][k] == '>') { if (x == y) flag = 1; g[x].push_back(y); } else if (s[i][k] == '<') { if (x == y) flag = 1; g[y].push_back(x); } } } for (int i = 1; i <= n + m; i++) { int x = find(i); if (!vis[x]) { dfs(x); } } if (flag) { printf("No"); return 0; } else printf("Yes\n"); for (int i = 1; i <= n; i++) { int x = find(i); printf("%d ", shu[x]); } cout << "\n"; for (int k = 1; k <= m; k++) { int x = find(n + k); printf("%d ", shu[x]); } 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
var nums = readline().split(" ").map(function(x) { return parseInt(x); }); var n = nums[0], m = nums[1]; var s = Array(n).fill([]); for (var i=0; i<n; i++) { var q = readline(); s[i] = []; for (var j=0; j<m; j++) s[i].push(q[j]); } var rank = Array(n+m).fill(0); var ppp = Array(n+m).fill(0); for (var i=0; i<n+m; i++) ppp[i] = i; find_set = function(v) { if (v !== ppp[v]) ppp[v] = find_set(ppp[v]); return ppp[v]; }; Union = function(x,y) { if (rank[x] < rank[y]) ppp[x] = y; else ppp[y] = x; rank[x] += rank[y]===rank[x]; }; for (var i=0; i<n; i++) for (var j=0; j<m; j++) if (s[i][j] === '=') Union(find_set(i), find_set(j+n)); var e = Array(n+m).fill([]); for (var i=0; i<n+m; i++) { var t = []; e[i] = t; } add_edge = function(a,b) { e[a].push(b); }; for (var i=0; i<n; i++) for (var j=0; j<m; j++) if (s[i][j] === '<') add_edge(find_set(i), find_set(j+n)); else if (s[i][j] === '>') add_edge(find_set(j+n), find_set(i)); var nnew = Array(n+m).fill(0); var lst = []; for (var i=0; i<n+m; i++) if (nnew[find_set(i)] === 0) { lst.push(find_set(i)); nnew[find_set(i)] = 1; } nnew = Array(n+m).fill(0); /* write(" LST = ", lst); write("\n"); write(" Edges = "); write(" n = ",n); write(" m = ",m); for (var i=0; i<n+m; i++) { var t = []; write(" i = ",i," e = ",e[i]); //for (var j=0; j<e[i].length; i++) t.push(e[i][j]); //write(t.join(" ")); write("\n"); } write("\n");*/ var ans = []; var Ok = 1; dfs = function(v) { if (!Ok) return; nnew[v] = 1; for (var i=0; i<e[v].length; i++) { var to = e[v][i]; if (!nnew[to]) dfs(to); else { if (nnew[to] == 1) { Ok = 0; return; } } } if (!Ok) return; ans.push(v); nnew[v] = 2; }; for (var i=0; i<n+m; i++) if (!nnew[i]) dfs(i); if (!Ok) { write("No"); } else { ans.reverse(); //write(" Ans = ", ans); //write("\n"); write("Yes"); var sum = Array(n+m).fill(0); for (var i=0; i<ans.length; i++) { if (sum[ans[i]] === 0) sum[ans[i]] = 1; for (var j=0; j<e[ans[i]].length; j++) sum[e[ans[i]][j]] = Math.max(sum[e[ans[i]][j]], sum[ans[i]] + 1); } var real_ans = Array(n+m).fill(1); for (var i=0; i<n+m; i++) real_ans[i] = sum[find_set(i)]; var p1 = []; for (var i=0; i<n; i++) p1.push(real_ans[i]); var p2 = []; for (var i=n; i<n+m; i++) p2.push(real_ans[i]); write("\n"); write(p1.join(" ")); write("\n"); write(p2.join(" ")); }
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.*; public class toy { static int[] f=new int[2123]; public static int F(int x) { return x==f[x]?x:(f[x]=F(f[x])); } public static void U(int a,int b) { f[F(a)]=F(b); } public static void main(String[] args) { Scanner in=new Scanner(System.in); int n=in.nextInt(); int m=in.nextInt(); String[] s=new String[n]; for (int i=0;i<n+m;++i) f[i]=i; for (int i=0;i<n;++i) s[i]=in.next(); for (int i=0;i<n;++i) for (int j=0;j<m;++j) if (s[i].charAt(j)=='=') U(i,j+n); ArrayList<Integer>[] G=new ArrayList[n+m]; int[] deg=new int[n+m]; int[] dp=new int[n+m]; boolean[] vis=new boolean[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) if (s[i].charAt(j)=='>') { ++deg[F(i)]; G[F(j+n)].add(F(i)); } else if (s[i].charAt(j)=='<') { ++deg[F(j+n)]; G[F(i)].add(F(j+n)); } Queue<Integer> que=new LinkedList<Integer>(); for (int i=0;i<n+m;++i) if (deg[i]==0&&F(i)==i) { que.add(i); dp[i]=1; vis[i]=true; } while (!que.isEmpty()) { int u=que.peek(); que.poll(); for (int i=0;i<G[u].size();++i) { int v=G[u].get(i); --deg[v]; dp[v]=Math.max(dp[v],dp[u]+1); if (deg[v]==0) { que.add(v); vis[v]=true; } } } boolean flag=false; for (int i=0;i<n+m;++i) if (F(i)==i&&!vis[i]) flag=true; if (flag) { System.out.println("No"); return; } System.out.println("Yes"); for (int i=0;i<n;++i) System.out.printf("%d%c",dp[F(i)],i+1==n?'\n':' '); for (int i=0;i<m;++i) System.out.printf("%d%c",dp[F(i+n)],i+1==m?'\n':' '); } }
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; vector<vector<int> > P; vector<int> par, rang; vector<bool> used; vector<int> used1; vector<int> Count; int pred(int v) { if (par[v] == v) return v; else return par[v] = pred(par[v]); } void in(int a, int b) { a = pred(a); b = pred(b); if (a != b && rang[a] < rang[b]) { swap(a, b); } par[b] = a; if (rang[a] == rang[b]) { rang[a]++; } } void dfs(int v) { if (used1[v] == 1) { cout << "No"; exit(0); } used1[v] = 1; int min1 = 0; int cnt = 0; for (int i = 0; i < P[v].size(); i++) { if (used1[P[v][i]] != 2) { dfs(P[v][i]); } min1 = max(min1, Count[P[v][i]]); } if (P[v].size() == 0) { Count[v] = 1; } else { Count[v] = min1 + 1; } used1[v] = 2; } int main() { int n, m; cin >> n >> m; par.resize(n + m); for (int i = 0; i < n + m; i++) { par[i] = i; } Count.resize(n + m, 0); rang.resize(n + m, 1); vector<vector<char> > A(n, vector<char>(m)); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> A[i][j]; } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (A[i][j] == '=') { in(i, j + n); } } } int count = 0; used.resize(n + m, false); for (int i = 0; i < n + m; ++i) { if (!used[pred(i)]) { count++; used[pred(i)] = true; } } P.resize(n + m); for (int i = 0; i < n + m; i++) { used[i] = false; } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (A[i][j] == '>') { if (par[i] == par[j + n]) { cout << "No"; return 0; } P[par[i]].push_back(par[j + n]); used[par[j + n]] = true; } else if (A[i][j] == '<') { if (par[i] == par[j + n]) { cout << "No"; return 0; } P[par[j + n]].push_back(par[i]); used[par[i]] = true; } } } int start = -1; used1.resize(n + m, 0); for (int i = 0; i < m + n; i++) { if (used1[par[i]] != 2) { dfs(par[i]); } } cout << "Yes" << endl; for (int i = 0; i < n; i++) { cout << Count[pred(i)] << " "; } cout << endl; for (int i = n; i < m + n; i++) { cout << Count[pred(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; const int N = 2e3 + 5; int par[N]; int Find(int i) { if (par[i] != i) par[i] = Find(par[i]); return par[i]; } int Union(int a, int b) { a = Find(a), b = Find(b); if (a == b) return 0; par[b] = a; return 1; } char G[N][N]; vector<int> adj[N]; int vis[N]; int hasCycle(int v) { vis[v] = 1; for (auto it : adj[v]) { if (vis[it] == 1) return 1; if (vis[it] == 2) continue; if (hasCycle(it)) return 1; } vis[v] = 2; return 0; } int dp[N]; int fun(int v) { if (dp[v]) return dp[v]; for (auto it : adj[v]) { dp[v] = max(dp[v], fun(it)); } return ++dp[v]; } int main() { ios::sync_with_stdio(0); cin.tie(0); int n, m; 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 >> G[i][j]; if (G[i][j] == '=') { Union(i, n + j); } } } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (G[i][j] == '>') { adj[Find(i)].push_back(Find(n + j)); } else if (G[i][j] == '<') { adj[Find(n + j)].push_back(Find(i)); } } } for (int i = 1; i <= n + m; i++) { int j = Find(i); if (not vis[j]) { if (hasCycle(j)) { cout << "No\n"; exit(0); } } } cout << "Yes\n"; for (int i = 1; i <= n; i++) { int j = Find(i); cout << fun(j) << " "; } cout << "\n"; for (int i = 1; i <= m; i++) { int j = Find(n + i); cout << fun(j) << " "; } 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.math.BigInteger; import java.util.*; public class Main { public static class FastReader { BufferedReader br; StringTokenizer root; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (root == null || !root.hasMoreTokens()) { try { root = new StringTokenizer(br.readLine()); } catch (Exception addd) { addd.printStackTrace(); } } return root.nextToken(); } int nextInt() { return Integer.parseInt(next()); } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (Exception addd) { addd.printStackTrace(); } return str; } } public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out)); public static FastReader sc = new FastReader(); static int mod = (int) (1e9+7),MAX=(int) (2e5); static List<Integer>[] edges; static int[] in; public static void main(String[] args) { int n = sc.nextInt(); int m = sc.nextInt(); edges = new ArrayList[n+m+1]; in = new int[n+m+1]; DSU dsu = new DSU(n+m+1); for(int i=0;i<edges.length;++i) edges[i] = new ArrayList<>(); char[][] tab = new char[n+1][]; for(int i=1;i<=n;++i) { tab[i]= ("#"+sc.next()).toCharArray(); for(int j=1;j<=m;++j) { if(tab[i][j] == '=') dsu.unite(i,n+j); } } for(int i=1;i<=n;++i) { int u = dsu.findRoot(i); for(int j=1;j<=m;++j) { int v = dsu.findRoot(n+j); if(tab[i][j] == '>') { in[v]++; edges[u].add(v); }else if(tab[i][j] == '<') { edges[v].add(u); in[u]++; } } } Queue<Integer> q = new LinkedList<>(); for(int i=1;i<in.length;++i) if(dsu.findRoot(i) == i && in[i] == 0) q.add(i); // adding all the source node with indegree 0. List<Integer> order = new ArrayList<>(); while(q.size() > 0) { int x = q.poll(); order.add(x); for(int node : edges[x]) { if(--in[node] == 0) q.add(node); // adding only when it becomes source } } int[] dp = new int[n+m+1]; for(int i=order.size()-1;i>=0;--i) { int v = order.get(i); int ans = 1; for(int node : edges[v]) { ans = Math.max(ans,dp[node]+1); } dp[v] = ans; } boolean cycle = false; for(int i=1;i<dp.length;++i) { if(dsu.findRoot(i) == i && dp[i] == 0) cycle = true; // not in any group and value is not calc i.e cycle is present } if(cycle) out.println("No"); else { out.println("Yes"); for(int i=1;i<=n+m;++i) { out.print(dp[dsu.findRoot(i)]+" "); if(i == n) out.println(); } } out.close(); } static class DSU { int n; int[] parent, size; public DSU(int v) { n = v; parent = new int[n]; size = new int[n]; for(int i = 0; i < n; i++) { parent[i] = i; size[i] = 1; } } public int findRoot(int curr) { if(curr == parent[curr]) return curr; return parent[curr] = findRoot(parent[curr]); } public boolean unite(int a, int b) { int rootA = findRoot(a); int rootB = findRoot(b); if(rootA == rootB) return true; if(size[rootA] > size[rootB]) { parent[rootB] = rootA; size[rootA] += size[rootB]; } else { parent[rootA] = rootB; size[rootB] += size[rootA]; } return false; } } }
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.BigInteger; public class Main { static final long mod=(int)1e9+7; static ArrayList<Integer>[] adj; static int[] parent,size,arr,vis; public static void main(String[] args) throws Exception { FastReader in=new FastReader(); PrintWriter pw=new PrintWriter(System.out); int n=in.nextInt(); int m=in.nextInt(); char[][] mat=new char[n][]; for(int i=0;i<n;i++) mat[i]=in.next().toCharArray(); adj=new ArrayList[n+m]; parent=new int[n+m]; size=new int[n+m]; arr=new int[n+m]; vis=new int[n+m]; for(int i=0;i<n+m;i++) { parent[i]=i; size[i]=1; adj[i]=new ArrayList(); } for(int i=0;i<n;i++) { for(int j=0;j<m;j++) if(mat[i][j]=='=') union(i,n+j); } for(int i=0;i<n;i++) { for(int j=0;j<m;j++) if(mat[i][j]=='>') adj[find(i)].add(find(n+j)); else if(mat[i][j]=='<') adj[find(n+j)].add(find(i)); } for(int i=0;i<n+m;i++) { if(vis[parent[i]]==0) { boolean f=dfs(parent[i]); if(!f) { System.out.print("No"); return; } } } pw.println("Yes"); for(int i=0;i<n+m;i++) { pw.print(arr[find(i)]+" "); if(i==n-1) pw.println(); } pw.flush(); } static boolean dfs(int a) { vis[a]=1; arr[a]=1; boolean f=true; for(int i:adj[a]) { if(vis[i]==1) return false; if(vis[i]==0) f=dfs(i); if(!f) return false; arr[a]=Math.max(arr[a],arr[i]+1); } vis[a]=2; return true; } static void union(int a,int b) { int c=find(a); int d=find(b); if(size[c]<size[d]) { int t=c; c=d; d=t; } parent[d]=c; size[c]+=size[d]; } static int find(int a) { if(parent[a]==a) return a; return parent[a]=find(parent[a]); } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br=new BufferedReader(new InputStreamReader(System.in)); } public String next() throws IOException { if(st==null || !st.hasMoreElements()) { st=new StringTokenizer(br.readLine()); } return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { 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
'''input 3 3 >>> <<< >>> ''' #print(input().split()) n, m = list(map(int, input().split())) #exit(0) g = [] for i in range(n): g += [input()] # print(g) memo = {} def dfs(u): if u not in memo: memo[u] = res = 1 if u < n: for v in range(m): if g[u][v] == '>': res = max(res, dfs(n + v) + 1) for v in range(m): if g[u][v] == '=': res = max(res, dfs(n + v)) for v in range(m): if g[u][v] == '=': memo[n + v] = max(memo[n + v], res) else: for v in range(n): if g[v][u - n] == '<': res = max(res, dfs(v) + 1) for v in range(n): if g[v][u - n] == '=': res = max(res, dfs(v)) for v in range(n): if g[v][u - n] == '=': memo[v] = max(memo[v], res) memo[u] = res return memo[u] ans = [0] * (n + m) for i in range(n + m): ans[i] = dfs(i) for i in range(n): for j in range(m): if g[i][j] == '=' and ans[i] != ans[n + j]: print("No") exit(0) if g[i][j] == '<' and ans[i] >= ans[n + j]: print("No") exit(0) if g[i][j] == '>' and ans[i] <= ans[n + j]: print("No") exit(0) print("Yes") print(*ans[:n]) print(*ans[n:])
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; struct node { int to, next; } q[4012030]; char a[1020][1020]; int fa[2013], head[2013], ss, rd[2013], V[2013], que[2013]; bool vis[2013]; inline int find(int x) { return fa[x] == x ? x : fa[x] = find(fa[x]); } inline void Union(int x, int y) { int a = find(x), b = find(y); if (a ^ b) { fa[a] = b; } } void addedge(int x, int y) { ++rd[y]; q[++ss] = (node){y, head[x]}; head[x] = ss; } inline int read() { int n = 0; char a; bool z = false; while (a = getchar()) { if (a > '9' || a < '0') if (z) break; else continue; if (!z) z = true; n = (n << 1) + (n << 3) + (a ^ 48); } return n; } int main() { int n = read(), m = read(), f = 1, e = 0; for (int i = 1; i <= n; ++i) scanf("%s", a[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 (a[i][j] == '=') Union(i, j + n); for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) if (a[i][j] != '=' && (find(i) == find(j + n))) return !printf("No"); for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) if (a[i][j] == '<') addedge(find(i), find(j + n)); else if (a[i][j] == '>') addedge(find(j + n), find(i)); for (int i = 1; i <= n + m; ++i) if (fa[i] == i && !rd[i]) que[++e] = i, V[i] = 1, vis[i] = true; while (f <= e) { int u = que[f++]; vis[u] = true; for (int j = head[u]; j; j = q[j].next) { int t = q[j].to; --rd[t]; V[t] = max(V[t], V[u] + 1); if (!rd[t]) que[++e] = t; } } for (int i = 1; i <= n + m; ++i) if (fa[i] == i && !vis[i]) return !printf("No"); printf("Yes\n"); for (int i = 1; i <= n; ++i) printf("%d ", V[find(i)]); putchar('\n'); for (int i = n + 1; i <= n + m; ++i) printf("%d ", V[find(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; const int N = 2005; int low[N], num[N], cnt; vector<int> S; int scc_cnt, scc[N]; int vis[N]; vector<int> g[N]; void tarjanSCC(int u) { low[u] = num[u] = ++cnt; vis[u] = 1; S.push_back(u); for (int v : g[u]) { if (!num[v]) tarjanSCC(v); if (vis[v]) low[u] = min(low[u], low[v]); } if (low[u] == num[u]) { scc[u] = ++scc_cnt; int v; do { v = S.back(); S.pop_back(); vis[v] = 0; scc[v] = scc_cnt; } while (u != v); } } vector<int> h[N]; int f(int u) { int &ans = vis[u]; if (~ans) return ans; ans = 1; for (int v : h[u]) { ans = max(ans, f(v) + 1); } return ans; } int n, m; char mat[N][N]; int main() { scanf("%d %d", &n, &m); for (int i = 0; i < n; i++) scanf(" %s", mat[i]); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (mat[i][j] == '=') { g[i].push_back(n + j); g[n + j].push_back(i); } if (mat[i][j] == '>') { g[i].push_back(n + j); } if (mat[i][j] == '<') { g[n + j].push_back(i); } } } for (int i = 0; i < n + m; i++) if (!num[i]) tarjanSCC(i); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (mat[i][j] != '=') { if (scc[i] == scc[n + j]) { printf("No\n"); return 0; } } } } for (int i = 0; i < n + m; i++) { for (int j : g[i]) { if (scc[i] == scc[j]) continue; h[scc[i]].push_back(scc[j]); } } memset(vis, -1, sizeof vis); printf("Yes\n"); for (int i = 0; i < n; i++) { printf("%d%c", f(scc[i]), " \n"[i + 1 == n]); } for (int j = 0; j < m; j++) { printf("%d%c", f(scc[n + j]), " \n"[j + 1 == 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
#include <bits/stdc++.h> using namespace std; const long long mod = 1e9 + 7; const int MX = 2e3 + 5; vector<int> g[MX]; int in[MX]; int fa[MX]; char mp[MX][MX]; int ans[MX]; int found(int x) { if (fa[x] == x) return x; return fa[x] = found(fa[x]); } 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 >> mp[i]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (mp[i][j] == '=') { int fi = found(i), fj = found(j + n); if (fi != fj) fa[fj] = fa[fi]; } } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int fi = found(i), fj = found(j + n); if (mp[i][j] == '<') { g[fi].push_back(fj); in[fj]++; } if (mp[i][j] == '>') { g[fj].push_back(fi); in[fi]++; } } } set<int> ss; for (int i = 0; i < n + m; i++) { int fi = found(i); if (in[fi] == 0) ss.insert(fi); } queue<pair<int, int> > q; for (auto i : ss) q.push(make_pair(i, 0)), ans[i] = 0; while (!q.empty()) { auto now = q.front(); q.pop(); ans[now.first] = now.second + 1; for (auto i : g[now.first]) { in[i]--; if (in[i] == 0) q.push(make_pair(i, now.second + 1)); } } for (int i = 0; i < n + m; i++) if (ans[found(i)] == 0) { puts("No"); return 0; } puts("Yes"); for (int i = 0; i < n; i++) cout << ans[found(i)] << ' '; cout << endl; for (int i = n; i < m + n; i++) cout << ans[found(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
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 boolean dfs(int v) { vis[v] = ans[v] = 1; for (int u : g.get(v)) { if (vis[u] == 1) return false; if (vis[u] == 0 && !dfs(u)) return false; ans[v] = max(ans[v], ans[u] + 1); } vis[v] = 2; return true; } 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 TreeSet<>()); 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("NO"); return; } } 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