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
#include <bits/stdc++.h> using namespace std; const int o = 1005; int head[2010], value[2 * o], indeg[2 * o], outdeg[2 * o]; vector<int> adj[2 * o]; vector<int> go[2 * o], come[2 * o]; void dfs(int node, int val) { if (head[node] != -1) return; head[node] = val; for (int v : adj[node]) { dfs(v, val); } } void remove(int node) { int max_value = 0; for (int g : go[node]) max_value = max(max_value, value[g]); value[node] = max_value + 1; } int main() { memset(head, -1, sizeof(head)); memset(value, -1, sizeof(value)); int n, m; cin >> n >> m; string grid[n]; for (int i = 0; i < n; i++) { cin >> grid[i]; for (int j = 0; j < m; j++) { if (grid[i][j] == '=') { adj[i].push_back(o + j); adj[o + j].push_back(i); } } } for (int i = 0; i < n; i++) { if (head[i] == -1) { dfs(i, i); } } for (int j = o; j < o + m; j++) { if (head[j] == -1) { dfs(j, j); } } bool possible = true; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (grid[i][j] == '>') { if (head[i] == head[o + j]) possible = false; go[head[i]].push_back(head[o + j]); come[head[o + j]].push_back(head[i]); indeg[head[o + j]]++; outdeg[head[i]]++; } if (grid[i][j] == '<') { if (head[i] == head[o + j]) possible = false; go[head[o + j]].push_back(head[i]); come[head[i]].push_back(head[o + j]); indeg[head[i]]++; outdeg[head[o + j]]++; } } } if (!possible) { cout << "No" << endl; return 0; } queue<int> qe; for (int i = 0; i < n; i++) { if (outdeg[i] == 0) qe.push(i); } for (int i = o; i < m + o; i++) { if (outdeg[i] == 0) qe.push(i); } while (!qe.empty()) { int node = qe.front(); qe.pop(); remove(node); for (int v : come[node]) { outdeg[v]--; if (outdeg[v] == 0) qe.push(v); } } for (int i = 0; i < n; i++) { if (value[head[i]] == -1) { possible = false; } } for (int j = o; j < m + o; j++) { if (value[head[j]] == -1) { possible = false; } } if (!possible) { cout << "No" << endl; return 0; } else { cout << "Yes" << endl; for (int i = 0; i < n; i++) { cout << value[head[i]] << " "; } cout << endl; for (int j = o; j < m + o; j++) { cout << value[head[j]] << " "; } cout << endl; } }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n × m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≤ n, m ≤ 1000) — the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers — evaluations of dishes from the first set, and on the third line print m integers — evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> #pragma GCC optimize("Ofast") using namespace std; long long n, m; long long component = -1, answer = 0; vector<int> used; vector<int> used1, used2, used3; vector<long long> p, comp; vector<vector<long long>> f_g, g, rg; vector<int> order; vector<vector<char>> mat; map<long long, long long> ans; bool cycle = false; void dfs1(int v) { used[v] = 1; comp[v] = component; for (int i = 0; i < f_g[v].size(); ++i) { int to = f_g[v][i]; if (used[to] == 0) { dfs1(to); } } } void dfs3(int v) { used2[v] = 1; for (int i = 0; i < g[v].size(); ++i) { int to = g[v][i]; if (!used2[to]) dfs3(to); } order.push_back(v); } void dfs4(int v, int cur) { ans[v] = cur; used3[v] = 1; for (int i = 0; i < g[v].size(); ++i) { int to = g[v][i]; dfs4(to, cur + 1); } } int main() { cin >> n >> m; used.resize(n + m, 0), f_g.resize(m + n), used1.resize(n + m, 0), used2.resize(n + m, 0), used3.resize(n + m, 0); mat.resize(n, vector<char>(m)); comp.resize(n + m); for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { cin >> mat[i][j]; if (mat[i][j] == '=') { f_g[i].push_back(j + n); f_g[j + n].push_back(i); } } } for (int i = 0; i < n + m; ++i) { if (used[i] == 0) { component++; dfs1(i); } } component++; g.resize(n + m); for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (mat[i][j] == '<') { if (comp[i] == comp[j + n]) { cout << "No"; return 0; } g[comp[i]].push_back(comp[j + n]); } else if (mat[i][j] == '>') { if (comp[i] == comp[j + n]) { cout << "No"; return 0; } g[comp[j + n]].push_back(comp[i]); } } } for (int i = 0; i < component; ++i) { if (used2[i] == 0) { dfs3(i); } } answer = 1; reverse(order.begin(), order.end()); vector<long long> ans(n + m, 1); for (auto i : order) { for (auto to : g[i]) { ans[to] = ans[i] + 1; } } bool flag = true; for (long long i = 0; i < n; i++) { for (long long j = 0; j < m; j++) { if (mat[i][j] == '<' && ans[comp[i]] >= ans[comp[j + n]]) { flag = false; } if (mat[i][j] == '=' && ans[comp[i]] != ans[comp[j + n]]) { flag = false; } if (mat[i][j] == '>' && ans[comp[i]] <= ans[comp[j + n]]) { flag = false; } } } if (!flag) { cout << "No"; } else { cout << "Yes" << endl; for (long long i = 0; i < n; i++) cout << ans[comp[i]] << ' '; cout << endl; for (long long j = n; j < m + n; j++) cout << ans[comp[j]] << ' '; } return 0; }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n × m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≤ n, m ≤ 1000) — the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers — evaluations of dishes from the first set, and on the third line print m integers — evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> using namespace std; const long long MAX_N = 2e3 + 6; long long n, m; bool Mark[MAX_N]; long long dp[MAX_N]; int num[MAX_N], cnt = 1; string table[MAX_N]; vector<int> G[MAX_N]; vector<int> Grev[MAX_N]; vector<int> topo; vector<int> comp[MAX_N]; vector<int> Gcomp[MAX_N]; void dfs(int v) { Mark[v] = true; for (int i = 0; i < G[v].size(); i++) if (!Mark[G[v][i]]) dfs(G[v][i]); topo.push_back(v); } void dfs_rev(int v, int c) { num[v] = c; for (int i = 0; i < Grev[v].size(); i++) if (!num[Grev[v][i]]) dfs_rev(Grev[v][i], c); comp[c].push_back(v); } int main() { ios::sync_with_stdio(false), cin.tie(0); cin >> n >> m; for (int i = 0; i < n; i++) cin >> table[i]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { if (table[i][j] == '=' || table[i][j] == '<') { G[i].push_back(j + n); Grev[j + n].push_back(i); } if (table[i][j] == '=' || table[i][j] == '>') { G[j + n].push_back(i); Grev[i].push_back(j + n); } } for (int i = 0; i < n + m; i++) if (!Mark[i]) dfs(i); reverse(topo.begin(), topo.end()); for (int i = 0; i < n + m; i++) if (!num[topo[i]]) { dfs_rev(topo[i], cnt); cnt++; } for (int i = 1; i < cnt; i++) for (int j = 0; j < comp[i].size(); j++) if (comp[i][j] < n) for (int h = 0; h < comp[i].size(); h++) if (n <= comp[i][h]) if (table[comp[i][j]][comp[i][h] - n] != '=') { cout << "No\n"; return 0; } for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) if (num[i] != num[j + n]) { if (table[i][j] == '=' || table[i][j] == '>') Gcomp[num[i]].push_back(num[j + n]); if (table[i][j] == '=' || table[i][j] == '<') Gcomp[num[j + n]].push_back(num[i]); } for (int i = 0; i <= cnt; i++) { dp[i] = 1; for (int j = 0; j < Gcomp[i].size(); j++) dp[i] = max(dp[i], 1 + dp[Gcomp[i][j]]); } cout << "Yes\n"; for (int i = 0; i < n; i++) cout << dp[num[i]] << " "; cout << "\n"; for (int i = n; i < n + m; i++) cout << dp[num[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; long long int gcd(long long int a, long long int b) { return b == 0 ? a : gcd(b, a % b); } const double PI = 3.1415926535897932; const double EPS = 1e-10; const int INF = 0x3f3f3f3f; const int maxn = 1e3 + 100; const int hashmaxn = 8388608; int lowbit(int x) { return x & (-x); } int root[maxn << 1]; char ch[maxn][maxn]; vector<int> edge[maxn << 1]; int answer[maxn << 1]; int du[maxn << 1]; int n, m, sum; int findroot(int i) { return i == root[i] ? root[i] : root[i] = findroot(root[i]); } void megeroot(int i, int j) { int x = findroot(i); int y = findroot(j + n); if (x != y) { root[x] = y; sum++; } } void toolsort() { queue<int> q; for (long long int i = 1; i < n + m + 1; i++) { if (du[i] == 0 && root[i] == i) { sum++; answer[i] = 1; q.push(i); } } while (!q.empty()) { int a = q.front(); q.pop(); for (int i = 0; i < edge[a].size(); i++) { du[edge[a][i]]--; if (du[edge[a][i]] == 0) { sum++; answer[edge[a][i]] = answer[a] + 1; q.push(edge[a][i]); } } } } int main() { ios::sync_with_stdio(0); cin >> n >> m; for (long long int i = 1; i < n + m + 1; i++) root[i] = i; for (long long int i = 1; i < n + 1; i++) { for (long long int j = 1; j < m + 1; j++) { cin >> ch[i][j]; if (ch[i][j] == '=') { megeroot(i, j); } } } for (long long int i = 1; i < n + 1; i++) for (long long int j = 1; j < m + 1; j++) { if (ch[i][j] == '=') continue; int x = findroot(i), y = findroot(j + n); if (ch[i][j] == '<') { edge[x].push_back(y); du[y]++; } else { edge[y].push_back(x); du[x]++; } } toolsort(); if (sum != n + m) cout << "No" << endl; else { cout << "Yes" << endl; for (long long int i = 1; i < n + 1; i++) cout << answer[findroot(i)] << " "; cout << endl; for (long long int i = n + 1; i < n + m + 1; i++) { if (i != n + m) cout << answer[findroot(i)] << " "; else cout << answer[findroot(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
import java.util.*; import java.io.*; /* BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); Integer.parseInt(st.nextToken()); Long.parseLong(st.nextToken()); Scanner sc = new Scanner(System.in); */ public class Waw{ static HashMap<Integer,Node> luckup = new HashMap<Integer,Node>(); static class Node{ int id; int nb; LinkedList<Integer> neighbers = new LinkedList<Integer>(); int precedent; public Node(int i){ id = i; precedent = 0; nb = 0; } } static Node getNode(int id){ return luckup.get(id); } static void addEdges(int first,int second){ Node node = getNode(first); node.neighbers.add(second); getNode(second).precedent++; } static boolean bfs(int n,int m,boolean[] exist){ Node node; int nb = 1; LinkedList<Integer> nextToVisit = new LinkedList<Integer>(); boolean ok = true; while(ok){ ok = false; for(int i=1;i<=n+m;i++){ if(!exist[i]) continue; if(getNode(i).precedent==0 && getNode(i).nb==0) { ok = true; nextToVisit.add(i); } } while(!nextToVisit.isEmpty()){ node = getNode(nextToVisit.poll()); node.nb = nb; for(int i:node.neighbers){ getNode(i).precedent--; } } nb++; } for(int i=1;i<=n+m;i++){ if(!exist[i]) continue; if(getNode(i).nb==0) return false; } return true; } /* static boolean cycle(int n,int m){ boolean ok = false; boolean[] visited = new boolean[n+m+1]; for(int i=1;i<=n+m;i++){ Arrays.fill(visited,false); ok = cycle(i,n,m,visited); if(ok) return true; } return false; } static boolean cycle(int k,int n,int m,boolean[] visited){ LinkedList<Integer> nextToVisit = new LinkedList<Integer>(); Node node; nextToVisit.add(k); visited[k] = true; while(!nextToVisit.isEmpty()){ node = getNode(nextToVisit.poll()); for(int i:node.neighbers){ if(i==k) return true; if(visited[i]) continue; visited[i] = true; nextToVisit.add(i); } } return false; } */ static boolean isCyclicUtil(int i, boolean[] visited, boolean[] recStack) { // Mark the current node as visited and // part of recursion stack if (recStack[i]) return true; if (visited[i]) return false; visited[i] = true; recStack[i] = true; for (int c: getNode(i).neighbers) if (isCyclicUtil(c, visited, recStack)) return true; recStack[i] = false; return false; } static boolean isCyclic(int n,int m,boolean[] exist) { // Mark all the vertices as not visited and // not part of recursion stack boolean[] visited = new boolean[n+m+1]; boolean[] recStack = new boolean[n+m+1]; // Call the recursive helper function to // detect cycle in different DFS trees for (int i = 1; i <= n+m; i++) { if(!exist[i]) continue; if (isCyclicUtil(i, visited, recStack)) return true; } return false; } static class Subset{ int parent; int rank; public Subset(int p,int r){ parent = p; rank = r; } } static int find(Subset[] subsets,int i){ if(subsets[i].parent!=i) subsets[i].parent = find(subsets,subsets[i].parent); return subsets[i].parent; } static void union(Subset[] subsets,int x,int y){ int xroot = find(subsets,x); int yroot = find(subsets,y); if(subsets[xroot].rank<subsets[xroot].rank) subsets[xroot].parent = yroot; else if(subsets[yroot].rank<subsets[xroot].rank) subsets[yroot].parent = xroot; else{ subsets[xroot].parent = yroot; subsets[yroot].rank++; } } public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); Subset[] subsets = new Subset[n+m+1]; for(int i=1;i<=n+m;i++){ subsets[i] = new Subset(i,0); } PrintWriter out = new PrintWriter(System.out); String[] s = new String[n]; for(int i=0;i<n;i++){ s[i] = br.readLine(); } int x,y; for(int i=0;i<n;i++){ x = i+1; for(int j=0;j<m;j++){ y = n+j+1; if(s[i].charAt(j)=='='){ union(subsets,x,y); } } } boolean[] exist = new boolean[n+m+1]; for(int i=1;i<=n+m;i++){ if(subsets[i].parent==i) { exist[i] = true; luckup.put(i,new Node(i)); } } for(int i=0;i<n;i++){ x = i+1; for(int j=0;j<m;j++){ y = n+j+1; if(s[i].charAt(j)=='>'){ addEdges(find(subsets,y),find(subsets,x)); } else if(s[i].charAt(j)=='<'){ addEdges(find(subsets,x),find(subsets,y)); } } } boolean ok = false; //ok = cycle(n,m); ok = isCyclic(n,m,exist); if(ok){ out.println("No"); } else{ ok = bfs(n,m,exist); if(!ok){ out.println("No"); } else{ out.println("Yes"); out.print(getNode(find(subsets,1)).nb); for(int i=2;i<=n;i++) { out.print(" "+getNode(find(subsets,i)).nb); } out.println(""); out.print(getNode(find(subsets,n+1)).nb); for(int i=n+2;i<=n+m;i++) { out.print(" "+getNode(find(subsets,i)).nb); } out.println(""); } } 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
#include <bits/stdc++.h> using namespace std; void fast() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); } long long n, m; vector<long long> parent; vector<long long> ra; vector<pair<long long, long long> > edges; vector<vector<long long> > adj; vector<bool> vis; vector<long long> depth; vector<long long> instack; long long get_parent(long long a) { if (a == parent[a]) return a; return parent[a] = get_parent(parent[a]); } void join(long long a, long long b) { a = get_parent(a); b = get_parent(b); if (a != b) { if (ra[b] > ra[a]) swap(a, b); parent[b] = a; if (ra[a] == ra[b]) ra[a]++; } } bool cycle_rec(long long node) { vis[node] = true; instack[node] = true; for (auto child : adj[node]) { if (!vis[child] and cycle_rec(child)) return true; if (instack[child]) return true; } instack[node] = false; return false; } bool cycle_exist() { for (long long i = 0; i < n + m; i++) if (!vis[get_parent(i)] and cycle_rec(i)) return true; return false; } void find_depth(long long node) { if (depth[node] != -1) return; vis[node] = true; long long d = 0; for (auto child : adj[node]) { find_depth(child); d = max(d, depth[child]); } depth[node] = d + 1; vis[node] = false; } int32_t main() { fast(); cin >> n >> m; parent.resize(n + m); ra.resize(n + m); for (long long i = 0; i < parent.size(); i++) { parent[i] = i; ra[i] = 0; } for (long long i = 0; i < n; i++) { for (long long j = 0; j < m; j++) { char ch; cin >> ch; if (ch == '=') join(i, n + j); else if (ch == '>') edges.push_back({i, n + j}); else edges.push_back({n + j, i}); } } adj.resize(n + m), vis.resize(n + m, false), instack.resize(n + m, false), depth.resize(n + m, -1); for (auto e : edges) adj[get_parent(e.first)].push_back(get_parent(e.second)); if (cycle_exist()) { cout << "No\n"; return 0; } for (long long i = 0; i < n + m; i++) vis[i] = false; for (long long i = 0; i < n + m; i++) if (!vis[i]) find_depth(i); cout << "Yes\n"; for (long long i = 0; i < n; i++) cout << depth[get_parent(i)] << " "; cout << "\n"; for (long long j = 0; j < m; j++) cout << depth[get_parent(n + 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.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++) { 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
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 void unite(int[] p, int a, int b) { a = root(p, a); b = root(p, b); p[a] = b; } 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> using namespace std; const long long MOD = (long long)1e9 + 7; int n, m, dat[1009], fe[1009], an[1009], am[1009], mk[1009], afe[1009]; string nm[1009]; vector<int> vec[1009]; bool solve(int pos, int cnt, char c, int j) { bool db = false; if (afe[pos]) return false; if (fe[pos]) { db = true; } else fe[pos] = 1; int p1 = pos - 1, p2 = pos; bool ck1 = false, ck2 = false; if (p1 < 0) ck1 = true; if (p2 >= n) ck2 = true; while (!ck1 && !ck2) { while (fe[p1] == 0 && nm[dat[p1]][j] == c) { p1--; } if (fe[p1]) ck1 = true; while (fe[p2 + 1] == 0 && nm[dat[p2]][j] != c) { p2++; } if (fe[p2 + 1]) ck2 = true; if (nm[dat[p1]][j] != c && nm[dat[p2]][j] == c) { if (!db) swap(dat[p1], dat[p2]); else return false; } } p1 = pos - 1; int tmp = 0; while (p1 >= 0 && nm[dat[p1]][j] == c) { if (c == '=' && tmp) { afe[p1 + 1] = 1; } p1--; tmp++; } if (tmp == cnt) return true; return false; } int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n >> m; fe[0] = 1; fe[n] = 1; for (int i = 0; i < n; i++) cin >> nm[i]; for (int i = 0; i < n; i++) dat[i] = i; bool ok = true; for (int j = 0; j < m; j++) { int cnt0 = 0, cnt1 = 0; for (int i = 0; i < n; i++) { if (nm[i][j] == '<') cnt0++; if (nm[i][j] == '=') { cnt1++; mk[j] = i; } } if (cnt1 == 0) vec[cnt0].push_back(j); if (!solve(cnt0, cnt0, '<', j)) ok = false; if (!solve(cnt0 + cnt1, cnt1, '=', j)) ok = false; if (!ok) break; } if (!ok) { cout << "No\n"; } else { cout << "Yes\n"; int cur = 0; for (int i = 0; i <= n; i++) { if (!vec[i].empty()) { cur++; for (int j = 0; j < (int)vec[i].size(); j++) { am[vec[i][j]] = cur; } } if (fe[i]) { cur++; } if (i < n) an[dat[i]] = cur; } for (int i = 0; i < n; i++) cout << an[i] << " "; puts(""); for (int i = 0; i < m; i++) { if (am[i]) cout << am[i] << " "; else cout << an[mk[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; const int N = 2005; int n, m, fa[N], inDeg[N], val[N]; string s[1005]; vector<int> g[N]; int fi(int x) { return fa[x] == x ? x : fi(fa[x]); } void unite(int x, int y) { fa[fi(y)] = fi(x); } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cin >> n >> m; for (int i = 0; i < n + m; i++) fa[i] = i; for (int i = 0; i < n; i++) { cin >> s[i]; for (int j = 0; j < m; j++) { if (s[i][j] == '=') unite(i, j + n); } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (s[i][j] == '<') { g[fi(i)].emplace_back(fi(j + n)); inDeg[fi(j + n)]++; } if (s[i][j] == '>') { g[fi(j + n)].emplace_back(fi(i)); inDeg[fi(i)]++; } } } queue<int> q; for (int i = 0; i < n + m; i++) { if (fi(i) == i && !inDeg[i]) { q.push(i); val[i] = 1; } } while (!q.empty()) { int u = q.front(); q.pop(); for (int i = 0; i < g[u].size(); i++) { inDeg[g[u][i]]--; val[g[u][i]] = max(val[g[u][i]], val[u] + 1); if (!inDeg[g[u][i]]) q.push(g[u][i]); } } for (int i = 0; i < n + m; i++) { if (inDeg[i]) { cout << "NO" << endl; return 0; } } cout << "YES" << endl; for (int i = 0; i < n; i++) cout << val[fi(i)] << " "; cout << endl; for (int i = n; i < n + m; i++) cout << val[fi(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; int n, m; char mp[1005][1005]; int pre[2 * 1005]; int in[2 * 1005]; int ans[2 * 1005]; vector<int> g[2 * 1005]; struct no { int a, c; }; int found(int x) { int re = x; while (re != pre[re]) { re = pre[re]; } while (x != pre[x]) { int t = pre[x]; pre[x] = re; x = t; } return re; } void join(int x, int y) { int fx = found(x), fy = found(y); if (fx != fy) { pre[fx] = pre[fy]; } } void addarc(int from, int to) { g[from].push_back(to); in[to]++; } void topo(int st) { queue<no> q; q.push((no){st, 1}); while (!q.empty()) { no now = q.front(); q.pop(); ans[now.a] = now.c; for (int i = 0; i < (int)g[now.a].size(); i++) { int to = g[now.a][i]; in[to]--; if (in[to] == 0) q.push((no){to, now.c + 1}); } g[now.a].clear(); } } int main() { ios::sync_with_stdio(false); cin >> n >> m; for (int i = 0; i < n; i++) cin >> mp[i]; int kk = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (mp[i][j] != '=') { kk = 1; } } } if (kk == 0) { cout << "Yes" << endl; for (int i = 0; i < m + n; i++) { cout << 1 << ' '; if (i == n - 1) cout << endl; } return 0; } for (int i = 0; i < m + n; i++) pre[i] = i; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (mp[i][j] == '=') { join(i, j + n); } } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (found(i) == found(j + n) && mp[i][j] != '=') { cout << "No"; return 0; } int fx = found(i), fy = found(j + n); if (mp[i][j] == '>') { addarc(fy, fx); } if (mp[i][j] == '<') { addarc(fx, fy); } } } int i; for (i = 0; i < m + n; i++) { if (in[i] == 0 && g[i].size()) { topo(i); } } for (int i = 0; i < m + n; i++) { if (in[i] != 0) { cout << "No"; return 0; } } cout << "Yes" << endl; for (int i = 0; i < m + n; i++) { if (ans[i] == 0) { ans[i] = ans[found(i)]; } cout << ans[i] << ' '; if (i == n - 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; int par[20005], sz[20005], visit[20005], rev[20005], indeg[20006], hgt[20006]; vector<int> adj[20006]; char S[1006][1006]; int loop; int find_parent(int x) { if (par[x] == x) return x; find_parent(par[x]); } void unite(int u, int v) { u = find_parent(u); v = find_parent(v); if (u == v) return; if (u < v) swap(u, v); sz[u] += sz[v]; par[v] = par[u]; } void dfs0(int node) { if (visit[node]) return; visit[node] = 1; rev[node] = 1; for (int i = 0; i < adj[node].size(); i++) { if (visit[adj[node][i]] && rev[adj[node][i]]) loop = 1; dfs0(adj[node][i]); } rev[node] = 0; } void dfs(int node) { if (visit[node]) return; visit[node] = 1; for (int i = 0; i < adj[node].size(); i++) dfs(adj[node][i]); hgt[node] = 1; for (int i = 0; i < adj[node].size(); i++) { hgt[node] = max(hgt[node], hgt[adj[node][i]] + 1); } } int main() { int N, M, i, j, k; cin >> N >> M; for (i = 1; i <= N + M; i++) { sz[i] = 1; par[i] = i; } for (i = 1; i <= N; i++) { for (j = 1; j <= M; j++) { cin >> S[i][j]; if (S[i][j] == '=') unite(i, N + j); } } for (i = 1; i <= N; i++) { for (j = 1; j <= M; j++) { if (S[i][j] == '>') { adj[find_parent(i)].push_back(find_parent(N + j)); indeg[find_parent(N + j)]++; } else if (S[i][j] == '<') { adj[find_parent(N + j)].push_back(find_parent(i)); indeg[find_parent(i)]++; } } } for (i = 1; i <= N + M; i++) { dfs0(i); } if (loop) { cout << "No\n"; return 0; } memset(rev, 0, sizeof(rev)); memset(visit, 0, sizeof(visit)); queue<int> Q; for (i = 1; i <= N + M; i++) { dfs(i); } cout << "Yes\n"; for (i = 1; i <= N; i++) cout << hgt[find_parent(i)] << " "; cout << endl; for (i = 1; i <= M; i++) cout << hgt[find_parent(N + 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; long long arr[2005] = {0}, par[2005] = {0}, sz[2005] = {0}, vis1[2005] = {0}; long long vis3[2005] = {0}, vis2[2005] = {0}, flag = 0, val[2005] = {0}; long long find_root(long long a) { while (par[a] != a) { a = par[a]; } return a; } long long unite(long long a, long long b) { long long root_a, root_b; root_a = find_root(a); root_b = find_root(b); if (sz[root_a] > sz[root_b]) { sz[root_a] += sz[root_b]; par[root_b] = root_a; } else { sz[root_b] += sz[root_a]; par[root_a] = root_b; } return 0; } long long check_cyclic(vector<set<long long> > &v, long long n) { if (vis2[n] == 1) { flag = 1; return 0; } if (vis1[n] == 1) return 0; vis1[n] = 1; vis2[n] = 1; for (auto it = v[n].begin(); it != v[n].end(); it++) { check_cyclic(v, (*it)); } vis2[n] = 0; return 0; } long long find_nums(vector<set<long long> > &v, long long n) { if (vis3[n] == 1) return 0; vis3[n] = 1; val[n] = 1; long long maxi = 1; for (auto it = v[n].begin(); it != v[n].end(); it++) { find_nums(v, *it); maxi = max(val[(*it)] + 1, maxi); } val[n] = maxi; return 0; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); vector<set<long long> > v(2005); long long n, m, i, j, k, rot[2005] = {0}; char comp[1005][1005]; cin >> n >> m; for (i = 0; i < n; i++) for (j = 0; j < m; j++) cin >> comp[i + 1][j + 1]; for (i = 1; i <= (n + m); i++) { par[i] = i; sz[i] = 1; } for (i = 1; i <= n; i++) for (j = 1; j <= m; j++) { if (comp[i][j] == '=') { unite(i, n + j); } } for (i = 1; i <= (n + m); i++) rot[i] = find_root(i); for (i = 1; i <= n; i++) for (j = 1; j <= m; j++) { if (comp[i][j] == '>') { v[rot[i]].insert(rot[n + j]); } else if (comp[i][j] == '<') { v[rot[n + j]].insert(rot[i]); } } for (i = 1; i <= (n + m); i++) check_cyclic(v, i); if (flag) { cout << "NO"; return 0; } for (i = 1; i <= (n + m); i++) find_nums(v, i); cout << "YES\n"; for (i = 1; i <= n; i++) cout << val[rot[i]] << " "; cout << "\n"; for (i = 1; i <= m; i++) cout << val[rot[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; const int N = 2e3 + 5; int g[N][N]; int arr[N]; int d[N]; char str[2005][2005]; int f[N]; int find(int i) { if (i == arr[i]) return i; return arr[i] = find(arr[i]); } int main() { int n, m; cin >> n >> m; for (int i = 0; i <= 2000; i++) arr[i] = i; for (int i = 1; i <= n; i++) { scanf("%s", str[i] + 1); for (int j = 1; j <= m; j++) { if (str[i][j] == '=') arr[find(i)] = find(j + n); } } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (str[i][j] != '=') { int u = find(i); int v = find(j + n); if (u == v) { cout << "No" << endl; return 0; } if (str[i][j] == '>' && !g[v][u]) g[v][u] = 1, d[u]++; else if (str[i][j] == '<' && !g[u][v]) g[u][v] = 1, d[v]++; } } } queue<int> q; for (int i = 1; i <= n + m; i++) { if (arr[i] == i && d[i] == 0) f[i] = 1, q.push(i); } while (!q.empty()) { int x = q.front(); q.pop(); for (int i = 1; i <= n + m; i++) { if (g[x][i] && !(--d[i])) { q.push(i); f[i] = f[x] + 1; } } } for (int i = 1; i <= n; i++) { if (d[i]) { cout << "No" << endl; return 0; } } puts("Yes"); for (int i = 1; i <= n; i++) printf("%d ", f[find(i)]); printf("\n"); for (int j = 1; j <= m; j++) printf("%d ", f[find(j + 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 N = 2010; bool vis[N] = {false}; bool flag = 0; int d[N]; vector<pair<int, int> > adj[N]; void dfs(int s) { vis[s] = 1; int v, c; for (int i = 0; i < adj[s].size(); i++) { v = adj[s][i].first; c = adj[s][i].second; if (d[v] < d[s] + c) { d[v] = d[s] + c; if (vis[v]) { flag = 1; return; } dfs(v); } } vis[s] = 0; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int n, m; cin >> n >> m; for (int i = 0; i <= n + m; i++) { d[i] = 0; } string s; for (int i = 1; i <= n; i++) { cin >> s; s = '0' + s; for (int j = 1; j <= m; j++) { if (s[j] == '=') { adj[i].push_back({n + j, 0}); adj[n + j].push_back({i, 0}); } else if (s[j] == '<') { adj[i].push_back({n + j, 1}); } else if (s[j] == '>') { adj[n + j].push_back({i, 1}); } } } for (int i = 1; i <= n + m; i++) { dfs(i); } if (flag == 1) { cout << "No"; return 0; } cout << "Yes\n"; for (int i = 1; i <= n; i++) { cout << d[i] + 1 << " "; } cout << "\n"; for (int i = n + 1; i <= n + m; i++) { cout << d[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; const long long MAX_N = 2009; vector<long long> g[MAX_N]; vector<long long> rg[MAX_N]; string s[MAX_N]; long long n, m; bool used[MAX_N]; long long ts[MAX_N]; long long cnt; long long c[MAX_N]; vector<long long> g1[MAX_N]; long long h[MAX_N]; void dfs(long long v) { used[v] = true; for (long long to : g[v]) { if (!used[to]) dfs(to); } ts[cnt] = v; cnt++; } void find_comp(long long v) { used[v] = true; c[v] = cnt; for (long long to : rg[v]) { if (!used[to]) find_comp(to); } } void find_ans(long long v) { h[v] = 1; used[v] = true; for (long long to : g1[v]) { if (!used[to]) find_ans(to); h[v] = max(h[v], h[to] + 1); } } signed main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n >> m; for (long long i = 0; i < n; i++) { cin >> s[i]; for (long long e = 0; e < m; e++) { if (s[i][e] == '<') { g[i].push_back(e + n); rg[e + n].push_back(i); } else if (s[i][e] == '>') { g[e + n].push_back(i); rg[i].push_back(e + n); } else { g[i].push_back(e + n); g[e + n].push_back(i); rg[i].push_back(e + n); rg[e + n].push_back(i); } } } for (long long i = 0; i < n + m; i++) { if (!used[i]) dfs(i); } cnt = 0; for (long long i = 0; i < n + m; i++) used[i] = false; for (long long i = m + n - 1; i >= 0; i--) { long long v = ts[i]; if (!used[v]) { find_comp(v); cnt++; } } for (long long i = 0; i < n + m; i++) { for (long long to : rg[i]) { if (c[i] != c[to] && c[i] > c[to]) g1[c[i]].push_back(c[to]); } used[i] = false; } for (long long i = 0; i < cnt; i++) { if (!used[i]) find_ans(i); } for (long long i = 0; i < n + m; i++) c[i] = h[c[i]]; for (long long i = 0; i < n; i++) { for (long long e = 0; e < m; e++) { if ((s[i][e] == '=' && c[i] == c[e + n]) || (s[i][e] == '>' && c[i] > c[e + n]) || (s[i][e] == '<' && c[i] < c[e + n])) continue; else { cout << "No"; return 0; } } } cout << "Yes\n"; for (long long i = 0; i < n; i++) cout << c[i] << " "; cout << "\n"; for (long long i = 0; i < m; i++) cout << c[i + n] << " "; }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n × m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≤ n, m ≤ 1000) — the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers — evaluations of dishes from the first set, and on the third line print m integers — evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> using namespace std; FILE *in = stdin; FILE *out = stdout; int n, m; vector<int> v[2005]; int color[2005]; int find(int x) { if (x == color[x]) { return x; } else { return color[x] = find(color[x]); } } int indegree[2005]; char c[1005][1005]; int main() { fscanf(in, "%d %d", &n, &m); for (int i = 1; i <= n + m; i++) { color[i] = i; } for (int i = 1; i <= n; i++) { for (int j = n + 1; j <= n + m; j++) { fscanf(in, " %c", &c[i][j]); if (c[i][j] == '=') { int w1 = find(i); int w2 = find(j); color[w1] = w2; } } } for (int i = 1; i <= n + m; i++) { color[i] = find(i); } for (int i = 1; i <= n; i++) { for (int j = n + 1; j <= n + m; j++) { if (c[i][j] == '<') { v[color[i]].push_back(color[j]); indegree[color[j]]++; } else if (c[i][j] == '>') { v[color[j]].push_back(color[i]); indegree[color[i]]++; } } } int ans[200001]; queue<int> que; for (int i = 1; i <= n + m; i++) { if (!indegree[i]) { ans[i] = 1; que.push(i); } } int nummax = 0; while (!que.empty()) { int pos = que.front(); que.pop(); nummax++; for (int i = 0; i < v[pos].size(); i++) { indegree[v[pos][i]]--; if (!indegree[v[pos][i]]) { ans[v[pos][i]] = ans[pos] + 1; que.push(v[pos][i]); } } } if (nummax != n + m) { fprintf(out, "NO"); return 0; } else { fprintf(out, "YES\n"); for (int i = 1; i <= n; i++) { fprintf(out, "%d ", ans[color[i]]); } fprintf(out, "\n"); for (int i = n + 1; i <= n + m; i++) { fprintf(out, "%d ", ans[color[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.lang.*; public class draw{ public static void main(String[] args) { solveGourmet(); } public static void solveGourmet(){ Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int m = scan.nextInt(); scan.nextLine(); String[] strs = new String[n]; for(int i=0;i<n;i++){ strs[i] = scan.nextLine(); } int[] parent = new int[n+m]; for(int i=0;i<m+n;i++){ parent[i] = i; } int group_size = m+n; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ char c = strs[i].charAt(j); if(c=='='){ int parent_i = findParent(parent, i); int parent_j = findParent(parent, n+j); if(parent_i!=parent_j){ parent[parent_i] = parent[parent_j]; group_size--; } } } } Map<Integer,Set<Integer>> map = new HashMap<>(); int[] indegree = new int[n+m]; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ char c=strs[i].charAt(j); if(c=='='){ continue; } int parent_i = findParent(parent, i); int parent_j = findParent(parent, n+j); if(parent_i==parent_j){ System.out.println("NO"); return; } if(c=='>'){ if(map.containsKey(parent_i) && map.get(parent_i).contains(parent_j)){ System.out.println("NO"); return; } if(map.containsKey(parent_j)==false){ map.put(parent_j, new HashSet<>()); }else if(map.get(parent_j).contains(parent_i)){ continue; } map.get(parent_j).add(parent_i); indegree[parent_i]++; }else if(c=='<'){ if(map.containsKey(parent_j) && map.get(parent_j).contains(parent_i)){ System.out.println("NO"); return; } if(map.containsKey(parent_i)==false){ map.put(parent_i, new HashSet<>()); }else if(map.get(parent_i).contains(parent_j)){ continue; } map.get(parent_i).add(parent_j); indegree[parent_j]++; } } } Map<Integer, Integer> affine = new HashMap<>(); Queue<Integer> queue = new LinkedList<>(); boolean[] visited = new boolean[m+n]; for(int i=0;i<m+n;i++){ int parent_id = findParent(parent, i); //System.out.println("prent " + parent_id +" 's indegree is :" + indegree[parent_id]); if(indegree[parent_id]==0 && visited[parent_id]==false){ visited[parent_id] = true; queue.offer(parent_id); } } int count = 0; while(queue.size()!=0){ int size = queue.size(); //System.out.println("size: "+size); count++; while(size--!=0){ int cur_id = queue.poll(); //System.out.println(cur_id); affine.put(cur_id, count); if(map.containsKey(cur_id)==false){ continue; } for(int ele: map.get(cur_id)){ int parent_ele = findParent(parent, ele); indegree[parent_ele]--; if(indegree[parent_ele] == 0 && visited[parent_ele]==false){ visited[parent_ele] = true; queue.offer(parent_ele); } } } } if(affine.size()!=group_size){ System.out.println("NO"); return; } int[] res = new int[m+n]; //System.out.println("check"); for(int i=0;i<m+n;i++){ int parent_id = findParent(parent, i); //System.out.println(parent_id); int val = affine.get(parent_id); res[i] = val; } System.out.println("YES"); for(int i=0;i<n;i++){ System.out.print(res[i]+" "); } System.out.println(); for(int i=0;i<m;i++){ System.out.print(res[n+i]+" "); } System.out.println(); } public static int findParent(int[] parent, int index){ while(index!=parent[index]){ parent[index] = parent[parent[index]]; index = parent[index]; } return index; } public static void solveCycle(){ Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int[] array = new int[n]; for(int i=0;i<n;i++){ array[i] = scan.nextInt(); } Arrays.sort(array); List<Integer> list = new ArrayList<>(); for(int i=0;i<array.length;i+=2){ list.add(array[i]); } int i=(array.length%2==0)?array.length-1:array.length-2; for(;i>=1;i-=2){ list.add(array[i]); } for(int ele: list){ System.out.print(ele+" "); } } public static void solveDraw(){ Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int[] arrayA = new int[n+1]; int[] arrayB = new int[n+1]; for(int i=0;i<n;i++){ arrayA[i+1] = scan.nextInt(); arrayB[i+1] = scan.nextInt(); } int count = 0; for(int i=0;i<arrayA.length-1;i++){ int min = Math.max(arrayA[i], arrayB[i]); int max = Math.min(arrayA[i+1], arrayB[i+1]); if(max<min){ continue; } int len = max-min+1; if(arrayA[i]==arrayB[i]){ len--; } count += len; } System.out.println(count+1); } }
JAVA
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n × m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≤ n, m ≤ 1000) — the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers — evaluations of dishes from the first set, and on the third line print m integers — evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> using namespace std; const long long inf = (long long)1e18; const long long md = (long long)1e9 + 21; long long n, m, par[2010], cnt[2010], col[2010], indeg[2010], pos[2010]; bool fo = 0; char s[1005][1005]; vector<long long> adj[2010]; queue<long long> ts; long long root(long long x) { while (x != par[x]) x = par[x]; return x; } void dsu(long long x, long long y) { if (root(x) == root(y)) return; if (cnt[root(x)] >= cnt[root(y)]) { cnt[root(x)] += cnt[root(y)]; par[root(y)] = root(x); } else { cnt[root(y)] += cnt[root(x)]; par[root(x)] = root(y); } } void topsort(long long x) { col[x] = 1; for (auto &y : adj[x]) { if (col[y] == 2) continue; if (col[y] == 1) { fo = 1; break; } topsort(y); } if (fo) return; col[x] = 2; ts.push(x); } signed main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); ; cin >> n >> m; for (long long i = 1; i < n + m + 1; ++i) par[i] = i, cnt[i] = 1; for (long long i = 1; i < n + 1; ++i) { for (long long j = 1; j < m + 1; ++j) { cin >> s[i][j]; if (s[i][j] == '=') dsu(root(i), root(n + j)); } } for (long long i = 1; i < n + 1; ++i) { for (long long j = 1; j < m + 1; ++j) { if (s[i][j] == '>') { adj[root(i)].push_back(root(n + j)); indeg[root(n + j)]++; ; } else if (s[i][j] == '<') { adj[root(n + j)].push_back(root(i)); indeg[root(i)]++; } } } long long st = -1; for (long long i = 1; i < n + m + 1; ++i) { if (indeg[root(i)] == 0) st = root(i); } if (st == -1) { cout << "No\n"; return 0; } for (long long i = 1; i < n + m + 1; ++i) { if (col[i] == 0 && indeg[root(i)] == 0) topsort(root(i)); } if (fo) { cout << "No\n"; return 0; } while (!ts.empty()) { long long x = ts.front(); ts.pop(); long long ma = 0; for (auto &y : adj[x]) { ma = max(ma, pos[y]); } pos[x] = ma + 1; } cout << "Yes\n"; for (long long i = 1; i < n + 1; ++i) cout << pos[root(i)] << " "; cout << "\n"; for (long long i = n + 1; i < n + m + 1; ++i) cout << pos[root(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.*; 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) { boolean[] curMask = new boolean[sz]; for (int v = 0; v < sz; v++) { if (!was.contains(v) && nodes[v].gr == 0) { curMask[v] = true; } } Queue<Integer> queue = new ArrayDeque<>(); boolean[] visited = new boolean[sz]; for (int v = 0; v < sz; v++) { if (!curMask[v]) { queue.add(v); visited[v] = true; } } while (!queue.isEmpty()) { int v = queue.poll(); curMask[v] = false; for (int u: nodes[v].eq) { if (!visited[u]) { visited[u] = true; queue.add(u); } } } List<Integer> cur = new ArrayList<>(); for (int v = 0; v < sz; v++) { if (curMask[v]) { cur.add(v); } } 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
#include <bits/stdc++.h> using namespace std; const int MAXN = 2010; char thoughts[1010][1010]; vector<int> G[MAXN]; vector<int> r[MAXN]; int deg[MAXN]; int fs[MAXN], fa[MAXN]; int n, m, rnd; int find(int n) { if (fa[n] == 0) return n; else return fa[n] = find(fa[n]); } void merge(int a, int b) { int A = find(a), B = find(b); if (A != B) fa[A] = B; } bool topology_sort() { int cnt, lastcnt = 0; for (int i = 1; i <= n + m; i++) if (fa[i]) deg[i] = -1; while (lastcnt < n + m) { cnt = lastcnt; for (int i = 1; i <= n + m; i++) { if (deg[i] == 0) { r[rnd].push_back(i); deg[i] = -1; } } if (r[rnd].size() == 0) return false; for (auto u : r[rnd]) { for (int i = 1; i <= n + m; i++) if (find(i) == u) fs[i] = rnd, cnt++; for (auto v : G[u]) deg[v]--; } rnd++; lastcnt = cnt; } return true; } int main() { scanf("%d %d", &n, &m); for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { scanf(" %c", &thoughts[i][j]); if (thoughts[i][j] == '=') { merge(i, j + n); } } } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (thoughts[i][j] == '>') { G[find(i)].push_back(find(j + n)); deg[find(j + n)]++; } else if (thoughts[i][j] == '<') { G[find(j + n)].push_back(find(i)); deg[find(i)]++; } } } if (topology_sort()) { printf("Yes\n"); for (int i = 1; i <= n; i++) printf("%d ", rnd - fs[i]); printf("\n"); for (int i = n + 1; i <= n + m; i++) printf("%d ", rnd - fs[i]); printf("\n"); } else { printf("No\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; vector<int> adj[2001]; int n, m, pa[2001]; char str[1010][1010]; int vis[2001], in[2001]; int find(int cur) { return cur == pa[cur] ? cur : pa[cur] = find(pa[cur]); } void merge(int u, int v) { u = find(u), v = find(v); if (u != v) pa[v] = u; } int main() { scanf("%d%d", &n, &m); for (int i = 0; i < n; i++) scanf("%s", str[i]); for (int i = 0; i < n + m; i++) pa[i] = i; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) if (str[i][j] == '=') { merge(i, n + j); } for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { if (str[i][j] == '>') adj[find(j + n)].push_back(find(i)), in[find(i)]++; else if (str[i][j] == '<') adj[find(i)].push_back(find(j + n)), in[find(j + n)]++; } queue<int> que; for (int i = 0; i < n + m; i++) if (find(i) == i && !in[i]) { vis[i] = 1; que.push(i); } while (!que.empty()) { int cur = que.front(); que.pop(); for (auto &it : adj[cur]) { in[it]--; vis[it] = max(vis[it], vis[cur] + 1); if (!in[it]) { que.push(it); } } } for (int i = 0; i < n + m; i++) if (find(i) == i && in[i]) { puts("No"); return 0; } puts("Yes"); for (int i = 0; i < n; i++) printf("%d ", vis[find(i)]); puts(""); for (int i = n; i < n + m; i++) printf("%d ", vis[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 maxn = 1e5 + 10; const long long mod = 1e9 + 7; const int inf = 0x3f3f3f3f; const long long INF = 0x3f3f3f3f3f3f3f3f; const double eps = 1e-7; int T; int n, m, q; int f[maxn]; char str[2000][2000]; vector<int> vec[maxn]; queue<int> que; int cnt[maxn]; int ans[maxn]; int find(int x) { return x == f[x] ? x : f[x] = find(f[x]); } void bset(int x, int y) { int fx = find(x), fy = find(y); f[fx] = fy; } int main() { scanf("%d %d", &n, &m); for (int i = 0; i < n; ++i) { scanf("%s", str[i]); } for (int i = 1; i <= n + m; ++i) f[i] = i; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (str[i][j] == '=') { bset(i + 1, j + 1 + n); } } } for (int i = 1; i <= n + m; ++i) { f[i] = find(i); } for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (str[i][j] == '<') { vec[f[i + 1]].push_back(f[j + 1 + n]); cnt[f[j + 1 + n]]++; } if (str[i][j] == '>') { vec[f[j + 1 + n]].push_back(f[i + 1]); cnt[f[i + 1]]++; } } } for (int i = 1; i <= n + m; ++i) { if (cnt[f[i]] == 0 && i == f[i]) { que.push(f[i]); ans[f[i]] = 1; } } while (que.size()) { int tmp = que.front(); que.pop(); for (int i = 0; i < vec[tmp].size(); ++i) { cnt[vec[tmp][i]]--; if (cnt[vec[tmp][i]] == 0) { que.push(vec[tmp][i]); ans[vec[tmp][i]] = ans[tmp] + 1; } } } for (int i = 1; i <= n + m; ++i) { if (cnt[i] != 0) { printf("NO\n"); return 0; } } for (int i = 1; i <= n + m; ++i) { ans[i] = ans[f[i]]; } printf("YES\n"); for (int i = 1; i <= n + m; ++i) { printf("%d", ans[i]); if (i == n || i == n + m) printf("\n"); else printf(" "); } 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.*; import java.util.stream.IntStream; public class Main { public static void main(String[] args) { try (PrintWriter out = new PrintWriter(System.out)) { Solution solution = new Solution(); solution.in = new InputReader(getInput()); solution.out = out; solution.solve(); } } static InputStream getInput() { String inputFile = getInputFileName(); if (inputFile == null) { return System.in; } try { return new FileInputStream(Main.class.getClassLoader().getResource(inputFile).getFile()); } catch (FileNotFoundException e) { throw new RuntimeException(e); } } static String getInputFileName() { try { return System.getProperty("compet.input"); } catch (Exception ex) { return null; } } } class Solution { InputReader in; PrintWriter out; int n; int m; class Node { List<Integer> ls = new ArrayList<>(); int gr = 0; List<Integer> eq = new ArrayList<>(); } void solve() { n = in.nextInt(); m = in.nextInt(); String[] a = new String[n]; for (int i = 0; i < n; i++) { a[i] = in.next(); } int sz = n+m; Node[] nodes = IntStream.range(0, sz).mapToObj(i -> new Node()).toArray(Node[]::new); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int v = i; int u = n + j; switch (a[i].charAt(j)) { case '>': nodes[v].gr++; nodes[u].ls.add(v); break; case '<': nodes[u].gr++; nodes[v].ls.add(u); break; case '=': nodes[u].eq.add(v); nodes[v].eq.add(u); break; } } } boolean[] was = new boolean[sz]; int wasCnt = 0; boolean bad = false; int num = 1; int[] ans = new int[sz]; while (wasCnt < sz && !bad) { boolean[] curMask = new boolean[sz]; for (int v = 0; v < sz; v++) { if (!was[v] && nodes[v].gr == 0) { curMask[v] = true; } } Queue<Integer> queue = new ArrayDeque<>(); boolean[] visited = new boolean[sz]; for (int v = 0; v < sz; v++) { if (!curMask[v]) { queue.add(v); visited[v] = true; } } while (!queue.isEmpty()) { int v = queue.poll(); curMask[v] = false; for (int u: nodes[v].eq) { if (!visited[u]) { visited[u] = true; queue.add(u); } } } List<Integer> cur = new ArrayList<>(); for (int v = 0; v < sz; v++) { if (curMask[v]) { cur.add(v); } } if (cur.size() == 0) { bad = true; break; } for (int v: cur) { wasCnt++; was[v] = true; ans[v] = num; for (int u: nodes[v].ls) { nodes[u].gr--; } } num++; } out.println(bad ? "No" : "Yes"); if (!bad) { for (int i = 0; i < sz; i++) { if (i == n) { out.println(); } out.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
#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; } char s[1005][1005]; int main() { scanf("%d %d", &n, &m); for (int i = 1; i <= n; i++) scanf("%s", s[i] + 1); for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (s[i][j] == '>') { vec[j + n].push_back(make_pair(i, 1)); } else if (s[i][j] == '<') { 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> using namespace std; template <class T> ostream& operator<<(ostream& os, vector<T> V) { os << "[ "; for (auto v : V) os << v << " "; return os << "]"; } template <class L, class R> ostream& operator<<(ostream& os, pair<L, R> P) { return os << "(" << P.first << "," << P.second << ")"; } const long long Mod = 1e9 + 7; int n, m; char A[1005][1005]; int dsu[2005], parent[2005], depth[2005]; vector<int> G[2005]; bool vis[2005], grey[2005], ultimate = true; void dfs(int u) { depth[u] = 1; vis[u] = true; grey[u] = true; for (auto it : G[u]) { if (!vis[it]) { dfs(it); } else if (grey[it]) ultimate = false; depth[u] = max(depth[u], depth[it] + 1); } grey[u] = false; } int find_parent(int i) { while (parent[i] != i) i = parent[i]; return i; } void merge(int a, int b) { int p_a = find_parent(a), p_b = find_parent(b); if (p_a == p_b) return; else parent[p_b] = p_a; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n >> m; for (int i = 0; i < n + m; i++) { dsu[i] = i; parent[i] = i; } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> A[i][j]; if (A[i][j] == '=') { merge(i, n + j); } } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (A[i][j] == '=') continue; int a = find_parent(i), b = find_parent(n + j); if (A[i][j] == '<') swap(a, b); G[a].push_back(b); } } for (int i = 0; i < n + m; i++) { if (find_parent(i) == i && !vis[i]) dfs(i); } if (ultimate) { cout << "Yes" << endl; for (int i = 0; i < n; i++) cout << depth[find_parent(i)] << " "; cout << endl; for (int i = 0; i < m; i++) cout << depth[find_parent(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
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; int sz; class Node { List<Integer> ls = new ArrayList<>(sz); int gr = 0; List<Integer> eq = new ArrayList<>(sz); } void solve() { n = in.nextInt(); m = in.nextInt(); String[] a = new String[n]; for (int i = 0; i < n; i++) { a[i] = in.next(); } sz = n+m; Node[] nodes = IntStream.range(0, sz).mapToObj(i -> new Node()).toArray(Node[]::new); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int v = i; int u = n + j; switch (a[i].charAt(j)) { case '>': nodes[v].gr++; nodes[u].ls.add(v); break; case '<': nodes[u].gr++; nodes[v].ls.add(u); break; case '=': nodes[u].eq.add(v); nodes[v].eq.add(u); break; } } } boolean[] was = new boolean[sz]; int wasCnt = 0; boolean bad = false; int num = 1; int[] ans = new int[sz]; while (wasCnt < sz && !bad) { boolean[] curMask = new boolean[sz]; for (int v = 0; v < sz; v++) { if (!was[v] && nodes[v].gr == 0) { curMask[v] = true; } } Queue<Integer> queue = new ArrayDeque<>(sz); boolean[] visited = new boolean[sz]; for (int v = 0; v < sz; v++) { if (!curMask[v]) { queue.add(v); visited[v] = true; } } while (!queue.isEmpty()) { int v = queue.poll(); curMask[v] = false; for (int u: nodes[v].eq) { if (!visited[u]) { visited[u] = true; queue.add(u); } } } List<Integer> cur = new ArrayList<>(sz); for (int v = 0; v < sz; v++) { if (curMask[v]) { cur.add(v); } } if (cur.size() == 0) { bad = true; break; } for (int v: cur) { wasCnt++; was[v] = true; ans[v] = num; for (int u: nodes[v].ls) { nodes[u].gr--; } } num++; } out.println(bad ? "No" : "Yes"); if (!bad) { for (int i = 0; i < sz; i++) { if (i == n) { out.println(); } out.print(ans[i] + " "); } } } } class InputReader { BufferedReader reader; StringTokenizer tokenizer; InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } }
JAVA
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n × m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≤ n, m ≤ 1000) — the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers — evaluations of dishes from the first set, and on the third line print m integers — evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.
2
10
import java.util.*; import java.io.*; public class D { public static void main(String[] args) { FastScanner scanner = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int N = scanner.nextInt(); int M = scanner.nextInt(); char[][] rels = new char[N][M]; DSU dsu = new DSU(N+M); for(int i= 0; i < N; i++) { char[] line = scanner.next().toCharArray(); for(int j = 0; j < M; j++) { rels[i][j] = line[j]; if (rels[i][j] == '=') dsu.union(i, j+N); } } int nextNode = 0; HashMap<Integer, Integer> mapping = new HashMap<>(); for(int i= 0; i < N+M; i++) { if (!mapping.containsKey(dsu.find(i))) mapping.put(dsu.find(i), nextNode++); } ArrayList<Integer>[] graph = new ArrayList[nextNode]; for(int i = 0; i <nextNode; i++) graph[i] = new ArrayList<>(); int[] indeg = new int[nextNode]; for(int i = 0; i < N; i++) { for(int j = 0; j < M; j++) { if (rels[i][j] == '=')continue; else if (rels[i][j] == '<') { graph[mapping.get(dsu.find(i))].add(mapping.get(dsu.find(j + N))); indeg[mapping.get(dsu.find(j+N))]++; } else { graph[mapping.get(dsu.find(j+N))].add(mapping.get(dsu.find(i))); indeg[mapping.get(dsu.find(i))]++; } } } int tot = 0; int[] ansList= new int[nextNode]; ArrayDeque<Integer> queue = new ArrayDeque<>(); for(int i = 0; i < nextNode; i++) if (indeg[i] == 0) { ansList[i] = 1; queue.offer(i); } while(!queue.isEmpty()) { int cur = queue.poll(); tot++; for(int edge: graph[cur]) { indeg[edge]--; ansList[edge] = Math.max(ansList[cur] + 1, ansList[edge]); if (indeg[edge] == 0) queue.offer(edge); } } if (tot < nextNode) { out.println("No"); out.flush(); return; } out.println("Yes"); for(int i = 0; i < N; i++) { out.print(ansList[mapping.get(dsu.find(i))] + " "); } out.println(); for(int i = N; i < N+M; i++) { out.print(ansList[mapping.get(dsu.find(i))] + " "); } out.println(); out.flush(); } // public static class Pair { // int x, y; // public Pair(int xx, int yy) { // x = xx; // y = yy; // } // } public static class DSU { int[] parent, rank; int nSets; public DSU (int ss) { nSets = ss; parent = new int[ss]; rank = new int[ss]; for(int i = 0; i < ss; i++) { rank[i] = 1; parent[i] = i; } } public int find(int t) { int prev = t; while(parent[t] != t) { t = parent[t]; } compress(prev, t); return t; } public void compress(int s, int t) { while(parent[s]!=t) { int temp = parent[s]; parent[s] = t; s = temp; } } public boolean union (int a, int b) { int pa = find(a); int pb = find(b); if (pa == pb) return false; nSets--; if(rank[pa]<=rank[pb]) { rank[pb]++; parent[pa] = pb; } else { rank[pa]++; parent[pb] = pa; } return true; } } public 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 readNextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] readIntArray(int n) { int[] a = new int[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextInt(); } return a; } } }
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> bool debug = 0; const long long MOD = 1000000007; const double PI = acos(-1.0); const double eps = 1e-9; using namespace std; set<int> adj[3000]; int father[3000], indeg[3000], res[3000], m, n; char grid[3000][3000]; int find(int x) { return father[x] == x ? x : father[x] = find(father[x]); } void join(int a, int b) { a = find(a); b = find(b); if (a != b) father[b] = a; } void connect(int a, int b) { a = find(a); b = find(b); if (adj[a].find(b) == adj[a].end()) indeg[b]++; adj[a].insert(b); } int main() { scanf("%d %d", &n, &m); for (int i = 0; i < n + m + 100; i++) father[i] = i; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { scanf(" %c", &grid[i][j]); if (grid[i][j] == '=') join(i, n + j); } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (grid[i][j] == '<') connect(i, j + n); if (grid[i][j] == '>') connect(j + n, i); } } set<int> fila; for (int i = 0; i < m + n; i++) { if (indeg[find(i)] == 0) { fila.insert(find(i)); res[find(i)] = 1; } } int now; while (!fila.empty()) { now = *fila.begin(); fila.erase(fila.begin()); now = find(now); if (debug) cout << "now" << " = " << (now) << endl; for (int v : adj[now]) { if (debug) cout << "find(v)" << " = " << (find(v)) << endl; indeg[find(v)]--; if (debug) cout << "indeg[find(v)]" << " = " << (indeg[find(v)]) << endl; res[find(v)] = max(res[find(v)], 1 + res[now]); if (indeg[find(v)] == 0) fila.insert(find(v)); } if (debug) cout << endl; } for (int i = 0; i < n + m; i++) { if (indeg[find(i)] != 0) { printf("No\n"); return 0; } } printf("Yes\n"); for (int i = 0; i < n; i++) { printf("%d ", res[find(i)]); } printf("\n"); for (int i = 0; i < m; i++) { printf("%d ", res[find(i + n)]); } 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
//package round541; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.Comparator; import java.util.InputMismatchException; public class D { InputStream is; PrintWriter out; String INPUT = ""; static class Row { int[] a; int oid; public Row(int[] a, int oid) { this.a = a; this.oid = oid; } } void solve() { int n = ni(), m = ni(); char[][] map = nm(n,m); Row[] rows = new Row[n]; for(int i = 0;i < n;i++){ int[] a = new int[m]; for(int j = 0;j < m;j++){ a[j] = "<=>".indexOf(map[i][j])-1; } rows[i] = new Row(a, i); } Arrays.sort(rows, new Comparator<Row>() { public int compare(Row a, Row b) { for(int i = 0;i < a.a.length;i++){ if(a.a[i] != b.a[i]){ return a.a[i] - b.a[i]; } } return 0; } }); Row[] cols = new Row[m]; for(int j = 0;j < m;j++){ int[] b = new int[n]; for(int i = 0;i < n;i++){ b[i] = rows[i].a[j]; } cols[j] = new Row(b, j); } Arrays.sort(cols, new Comparator<Row>() { public int compare(Row a, Row b) { for(int i = 0;i < a.a.length;i++){ if(a.a[i] != b.a[i]){ return -(a.a[i] - b.a[i]); } } return 0; } }); int[] cnums = new int[m]; int[] rnums = new int[n]; int gen = 0; int p = 0; for(int i = 0;i < n;){ int j = i; while(j < n && Arrays.equals(rows[i].a, rows[j].a))j++; int oop = p; while(p < m && map[rows[i].oid][cols[p].oid] == '>'){ if(oop < p && Arrays.equals(cols[p].a, cols[p-1].a)){ }else{ gen++; } cnums[cols[p].oid] = gen; p++; } gen++; int op = p; while(p < m && map[rows[i].oid][cols[p].oid] == '=')p++; for(int k = i;k < j;k++){ rnums[rows[k].oid] = gen; } for(int k = op;k < p;k++){ cnums[cols[k].oid] = gen; } i = j; } gen++; while(p < m){ cnums[cols[p].oid] = gen; p++; } for(int i = 0;i < n;i++){ for(int j = 0;j < m;j++){ if(map[i][j] == '<'){ if(rnums[i] < cnums[j]){ }else{ out.println("No"); return; } }else if(map[i][j] == '>'){ if(rnums[i] > cnums[j]){ }else{ out.println("No"); return; } }else{ if(rnums[i] == cnums[j]){ }else{ out.println("No"); return; } } } } out.println("Yes"); for(int w : rnums){ out.print(w + " "); } out.println(); for(int w : cnums){ out.print(w + " "); } out.println(); } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new D().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
JAVA
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n × m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≤ n, m ≤ 1000) — the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers — evaluations of dishes from the first set, and on the third line print m integers — evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.
2
10
import java.io.*; import java.util.*; public class D_541 { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader inp = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Solver solver = new Solver(); solver.solve(inp, out); out.close(); } static class Solver { private void solve(InputReader inp, PrintWriter out) { int n = inp.nextInt(), m = inp.nextInt(); char[][] s = new char[n][m]; for (int i = 0; i < n; i++) s[i] = inp.next().toCharArray(); DSU dsu = new DSU(n+m); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (s[i][j] == '=') { if (!dsu.sameSet(i, n + j)) dsu.union(i, n + j); } } } int compI = 0; int[] comp = new int[n+m]; for (int i = 0; i < n+m; i++) comp[i] = -1; for (int i = 0; i < n + m; i++) { if (comp[i] != -1) continue; comp[i] = compI; for (int j = i + 1; j < n + m; j++) { if (dsu.sameSet(i, j)) { comp[j] = compI; } } compI++; } ArrayList<Integer>[] g = new ArrayList[compI]; for (int i = 0; i < compI; i++) g[i] = new ArrayList<>(); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (s[i][j] == '<') {//second set from m better g[comp[i]].add(comp[n+j]); } else if (s[i][j] == '>') {//first set from n better g[comp[n+j]].add(comp[i]); } } } int[] in_degree = new int[compI]; for (int i = 0; i < compI; i++) { for (int j: g[i]) in_degree[j]++; } int[] val = new int[compI]; Queue<Pair> queue = new LinkedList<>(); for (int i = 0; i < compI; i++) { if (in_degree[i] == 0) queue.add(new Pair(i, 1)); } while (!queue.isEmpty()) { Pair p = queue.poll(); if (val[p.v] > 0) continue; val[p.v] = p.depth; for (int nei: g[p.v]) { if (--in_degree[nei] == 0 && val[nei] == 0) { queue.add(new Pair(nei, p.depth + 1)); } } } int[] res = new int[n+m]; for (int i = 0; i < n + m; i++) { res[i] = val[comp[i]]; if (res[i] == 0) { System.out.println("No"); System.exit(0); } } out.println("Yes"); for (int i = 0; i < n + m; i++) { out.print(res[i] + " "); if (i == n - 1) out.print("\n"); } //Topological order (each layer has 1 value higher) //If it doesn't terminate => No //Store values for each dish to check answer } public class Pair { int v, depth; public Pair(int v, int depth) { this.v = v; this.depth = depth; } } public class DSU { private int[] parents, rank; public DSU(int n) { parents = new int[n]; rank = new int[n]; for (int i = 0; i < n; i++) parents[i] = -1; } int findParent(int node) { if (parents[node] == -1) return node; //recursively search int parent = findParent(parents[node]); parents[node] = parent; //don't search another time for parent return parent; } void union(int x, int y) { int xParent = findParent(x), yParent = findParent(y); if (rank[x] < rank[y]) parents[xParent] = yParent; else if (rank[x] > rank[y]) parents[yParent] = xParent; else { parents[yParent] = xParent; rank[xParent]++; } } boolean sameSet(int x, int y) { return findParent(x) == findParent(y); } } } static 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(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
JAVA
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n × m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≤ n, m ≤ 1000) — the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers — evaluations of dishes from the first set, and on the third line print m integers — evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> using namespace std; char c[1010][1010]; vector<int> v[2010]; int n, m, p[2010], val[2010], deg[2010]; bool vis[2010], flag; int find_set(int x) { if (p[x] == x) return x; return p[x] = find_set(p[x]); } signed main() { ios::sync_with_stdio(false); cin >> n >> m; for (int i = 1; i <= n + m; i++) p[i] = i; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { int x = i, y = j + n; cin >> c[i][j]; if (c[i][j] == '=') { int rootx = find_set(x), rooty = find_set(y); p[rootx] = rooty; } } } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { int x = i, y = j + n; if (c[i][j] == '<') { flag = true; int rootx = find_set(x), rooty = find_set(y); v[rootx].push_back(rooty); deg[rooty]++; } else if (c[i][j] == '>') { flag = true; int rootx = find_set(x), rooty = find_set(y); v[rooty].push_back(rootx); deg[rootx]++; } } } if (!flag) { cout << "Yes\n"; for (int i = 1; i <= n; i++) cout << 1 << " "; cout << endl; for (int j = 1; j <= m; j++) cout << 1 << " "; cout << endl; return 0; } queue<int> q; for (int i = 1; i <= n + m; i++) if (p[i] == i && deg[i] == 0) { q.push(i); vis[i] = 1; val[i] = 1; } while (!q.empty()) { int t = q.front(); q.pop(); for (int i = 0; i < v[t].size(); i++) { if (v[t][i] == t) { cout << "No" << endl; exit(0); } deg[v[t][i]]--; if (deg[v[t][i]] == 0) { val[v[t][i]] = val[t] + 1; vis[v[t][i]] = 1; q.push(v[t][i]); } } } for (int i = 1; i <= n + m; i++) if (p[i] == i && !vis[i]) { cout << "No" << endl; exit(0); } cout << "Yes" << endl; for (int i = 1; i <= n; i++) { cout << val[find_set(i)] << " "; } cout << endl; for (int j = 1; j <= m; j++) { cout << val[find_set(j + 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; template <class T> inline T lowbit(T x) { return x & (-x); } template <class T> T gcd(T a, T b) { return b ? gcd(b, a % b) : a; } template <class T> inline T Pow(T a, T b, T p) { T ret = 1; a %= p; for (; b; b >>= 1, a = a * a % p) if (b & 1) (ret *= a) %= p; return ret; } template <class T> inline void read(T &ret) { T x = 0, f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = x * 10 + ch - '0'; ch = getchar(); } ret = x * f; } const int N = 2010, M = 1e6 + 10; struct dsu { int par[N]; void init(int n) { for (int i = (1); i <= (n); i++) par[i] = i; } int find(int u) { return par[u] == u ? u : par[u] = find(par[u]); } void join(int u, int v) { u = find(u); v = find(v); if (u == v) return; par[u] = v; } } s; struct edge { int v, nxt; } g[M]; int head[N], sz = 0; void add(int u, int v) { g[++sz] = {v, head[u]}; head[u] = sz; } int n, m, deg[N]; char mat[N][N]; bool flg[N], edg[N][N]; int d[N], q[N]; bool bfs() { int h = 0, t = 0; for (int i = (1); i <= (n + m); i++) if (flg[i]) q[t++] = i, d[i] = 1; for (; h != t; h++) { int u = q[h]; for (int i = head[u], v; i; i = g[i].nxt) { deg[v = g[i].v]--; if (!deg[v]) { q[t++] = v; d[v] = d[u] + 1; } } } for (int i = (1); i <= (n + m); i++) if (deg[i]) return false; return true; } int main() { read(n); read(m); s.init(n + m); for (int i = (1); i <= (n); i++) { scanf("%s", mat[i]); for (int j = (0); j <= (m - 1); j++) if (mat[i][j] == '=') s.join(i, j + n + 1); } for (int i = (1); i <= (n); i++) for (int j = (0); j <= (m - 1); j++) if (mat[i][j] == '<') { int u = s.find(i), v = s.find(j + n + 1); if (!edg[u][v]) add(u, v), deg[v]++; edg[u][v] = 1; } else if (mat[i][j] == '>') { int u = s.find(j + 1 + n), v = s.find(i); if (!edg[u][v]) add(u, v), deg[v]++; edg[u][v] = 1; } for (int i = (1); i <= (n + m); i++) if (!deg[s.find(i)]) flg[s.find(i)] = 1; if (bfs()) { printf("YES\n"); for (int i = (1); i <= (n); i++) printf("%d ", d[s.find(i)]); printf("\n"); for (int i = (1); i <= (m); i++) printf("%d ", d[s.find(i + n)]); } 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
#include <bits/stdc++.h> #pragma GCC optimize("O3") using namespace std; void init_ios() { ios_base::sync_with_stdio(0); cin.tie(0); } const int N = 1005; int n, m, res[2 * N], wyn[2 * N], p[2 * N], bla[2 * N]; char a[N][N]; vector<int> topo, child[2 * N], kto[2 * N]; bool vis[2 * N]; int Find(int x) { if (x == p[x]) return x; return p[x] = Find(p[x]); } void Union(int x, int y) { x = Find(x); y = Find(y); if (x == y) return; if (child[x].size() < child[y].size()) swap(x, y); for (int c : child[y]) child[x].push_back(c); for (int c : kto[y]) kto[x].push_back(c); kto[y].clear(); child[y].clear(); p[y] = x; } void dfs(int v) { vis[v] = true; for (int x : child[v]) if (!vis[Find(x)]) dfs(Find(x)); topo.push_back(v); } void dfs2(int v) { bla[v] = 1; for (int x : child[v]) { if (bla[Find(x)] == 0) dfs2(Find(x)); else if (bla[Find(x)] == 1) { cout << "No\n"; exit(0); } } bla[v] = 2; } int main() { init_ios(); cin >> n >> m; for (int i = 1; i <= n + m; ++i) { p[i] = i; kto[i].push_back(i); wyn[i] = 1; } for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) { cin >> a[i][j]; if (a[i][j] == '<') child[Find(i)].push_back(Find(n + j)); else if (a[i][j] == '>') child[Find(n + j)].push_back(Find(i)); else Union(i, n + j); } for (int i = 1; i <= n + m; ++i) if (bla[Find(i)] == 0) dfs2(Find(i)); for (int i = 1; i <= n + m; ++i) if (!vis[Find(i)]) dfs(Find(i)); reverse(topo.begin(), topo.end()); for (int i = 0; i + 1 < topo.size(); ++i) { for (int el : child[topo[i]]) wyn[Find(el)] = max(wyn[Find(el)], 1 + wyn[topo[i]]); } for (int i = 1; i <= n + m; ++i) for (int x : kto[Find(i)]) res[x] = wyn[Find(i)]; cout << "Yes\n"; for (int i = 1; i <= n; ++i) cout << res[i] << " "; cout << "\n"; for (int i = n + 1; i <= n + m; ++i) cout << res[i] << " "; cout << "\n"; }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n × m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≤ n, m ≤ 1000) — the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers — evaluations of dishes from the first set, and on the third line print m integers — evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> using namespace std; const int N = 2000010, mod = 1e9 + 7; inline int read() { int x = 0, f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = (x << 1) + (x << 3) + (ch ^ 48); ch = getchar(); } return x * f; } int n, m, fa[N]; char g[1010][1010]; int Find(int x) { return fa[x] == x ? x : fa[x] = Find(fa[x]); } int h[N], ne[N], e[N], idx, d[N], ans[N], q[N], vis[N]; void add(int a, int b) { d[b]++, e[idx] = b, ne[idx] = h[a], h[a] = idx++; } int main() { memset(h, -1, sizeof h); n = read(), m = read(); for (int i = 1; i <= n; ++i) scanf("%s", g[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) { int x = Find(i), y = Find(n + j); if (g[i][j] == '=' && x != y) fa[x] = y; } } for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { int x = Find(i), y = Find(n + j); if (x == y && g[i][j] != '=') { puts("No"); return 0; } else if (g[i][j] == '>') add(y, x); else if (g[i][j] == '<') add(x, y); } } int hh = 0, tt = 0; for (int i = 1; i <= n + m; ++i) { if (d[Find(i)] == 0 && vis[Find(i)] == 0) q[tt++] = Find(i), ans[Find(i)] = 1, vis[Find(i)] = 1; } while (hh != tt) { int u = q[hh++]; for (int i = h[u]; ~i; i = ne[i]) { int t = Find(e[i]); ans[t] = max(ans[t], ans[u] + 1); if (--d[t] == 0) q[tt++] = t, vis[t] = 1; } } for (int i = 1; i <= n; ++i) { if (!vis[Find(i)]) { puts("No"); return 0; } } puts("Yes"); for (int i = 1; i <= n; ++i) { cout << ans[Find(i)] << ' '; } puts(""); for (int i = 1; i <= m; ++i) { cout << 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; inline int read() { int ans = 0, fh = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') fh = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') ans = (ans << 1) + (ans << 3) + ch - '0', ch = getchar(); return ans * fh; } const int maxn = 2e3 + 100, maxm = 2e6 + 100; int n, m, head[maxn], nex[maxm], v[maxm], num = 1; int bj[maxn], vis[maxn], fa[maxn], cz[maxn], du[maxn]; queue<int> q; inline void add(int x, int y) { v[++num] = y; nex[num] = head[x]; head[x] = num; du[y]++; } char s[maxn][maxn]; int getfa(int x) { return x == fa[x] ? x : fa[x] = getfa(fa[x]); } inline void merge(int x, int y) { x = getfa(x), y = getfa(y); if (x == y) return; fa[x] = y; } int dfs(int x) { if (vis[x]) return 1; if (cz[x]) return 0; vis[x] = 1, cz[x] = 1; for (int i = head[x]; i; i = nex[i]) if (dfs(v[i])) return 1; vis[x] = 0; return 0; } inline void tarjan() { for (int i = 1; i <= n + m; i++) if (!du[i]) q.push(i), bj[i] = 1; while (!q.empty()) { int x = q.front(); q.pop(); for (int i = head[x]; i; i = nex[i]) { int y = v[i]; du[y]--; bj[y] = max(bj[y], bj[x] + 1); if (!du[y]) q.push(y); } } } int main() { n = read(), m = read(); 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 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] == '>') { int x = getfa(i); int y = getfa(n + j); if (x == y) { printf("No\n"); return 0; } add(y, x); } if (s[i][j] == '<') { int x = getfa(i); int y = getfa(n + j); if (x == y) { printf("No\n"); return 0; } add(x, y); } } for (int i = 1; i <= n + m; i++) if (!cz[i] && dfs(i)) { printf("No\n"); return 0; } tarjan(); printf("Yes\n"); for (int i = 1; i <= n; i++) printf("%d ", bj[getfa(i)]); printf("\n"); for (int i = n + 1; i <= n + m; i++) printf("%d ", bj[getfa(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 maxn = 4000 + 10; const int MAXN = 2000000 + 10; const int inf = 0x3f3f3f3f; struct Edge { int from; int to; int next; } edge[MAXN]; int n, m, e, cnt, head[maxn], in[maxn], val[maxn], vis[maxn][maxn]; int pre[maxn], rnk[maxn]; char mp[maxn][maxn]; void add_edge(int u, int v) { edge[e].from = u; edge[e].to = v; edge[e].next = head[u]; head[u] = e++; } int find(int x) { return x == pre[x] ? x : pre[x] = find(pre[x]); } void join(int x, int y) { x = find(x); y = find(y); if (x == y) return; if (rnk[x] > rnk[y]) pre[y] = x; else { if (rnk[x] == rnk[y]) rnk[x]++; pre[x] = y; } } bool solve() { queue<int> q; for (int i = 1; i <= n + m; i++) if (i == pre[i] && in[i] == 0) { q.push(i); val[i] = 1; } while (!q.empty()) { int u = q.front(); q.pop(); for (int i = head[u]; i != -1; i = edge[i].next) { int v = edge[i].to; val[v] = max(val[v], val[u] + 1); if (--in[v] == 0) q.push(v); } } for (int i = 1; i <= n + m; i++) if (i == pre[i] && in[i] > 0) return false; return true; } void init() { for (int i = 0; i < maxn; i++) { pre[i] = i; head[i] = -1; } for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) if (mp[i][j] == '=') join(i, n + j); for (int i = 1; i <= n + m; i++) if (i == find(i)) cnt++; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { if (mp[i][j] == '<' && !vis[pre[i]][pre[n + j]]) { add_edge(pre[i], pre[n + j]); in[pre[n + j]]++; vis[pre[i]][pre[n + j]] = 1; } else if (mp[i][j] == '>' && !vis[pre[n + j]][pre[i]]) { add_edge(pre[n + j], pre[i]); in[pre[i]]++; vis[pre[n + j]][pre[i]] = 1; } } } int main() { scanf("%d%d", &n, &m); getchar(); for (int i = 1; i <= n; i++) gets(mp[i] + 1); init(); if (solve() == false) { printf("No\n"); return 0; } printf("Yes\n"); for (int i = 1; i <= n; i++) printf("%d ", val[pre[i]]); putchar('\n'); for (int i = 1; i <= m; i++) printf("%d ", val[pre[n + i]]); putchar('\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 N = 2005; int n, m, fa[N], inDeg[N], val[N]; string s[1005]; vector<int> g[N]; int fi(int x) { return fa[x] == x ? x : fi(fa[x]); } void unite(int x, int y) { fa[fi(y)] = fi(x); } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cin >> n >> m; for (int i = 0; i < n + m; i++) fa[i] = i; for (int i = 0; i < n; i++) { cin >> s[i]; for (int j = 0; j < m; j++) { if (s[i][j] == '=') unite(i, j + n); } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (s[i][j] == '<') { g[fi(i)].emplace_back(fi(j + n)); inDeg[fi(j + n)]++; } if (s[i][j] == '>') { g[fi(j + n)].emplace_back(fi(i)); inDeg[fi(i)]++; } } } queue<int> q; for (int i = 0; i < n + m; i++) { if (fi(i) == i && !inDeg[i]) { q.push(i); val[i] = 1; } } while (!q.empty()) { int u = q.front(); q.pop(); for (int i = 0; i < g[u].size(); i++) { inDeg[g[u][i]]--; val[g[u][i]] = val[u] + 1; if (!inDeg[g[u][i]]) q.push(g[u][i]); } } for (int i = 0; i < n + m; i++) { if (inDeg[i]) { cout << "NO" << endl; return 0; } } cout << "YES" << endl; for (int i = 0; i < n; i++) cout << val[fi(i)] << " "; cout << endl; for (int i = n; i < n + m; i++) cout << val[fi(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
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream st) { this.stream = st; } public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { 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 { res *= 10; res += c - '0'; c = read(); } 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 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 String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } public static class DSU { int[] parent,rank; public DSU(int n) { parent = new int[n]; rank = new int[n]; for(int i=0;i<n;i++) parent[i] = -1; } public int find(int node) { if(parent[node] == -1) return node; parent[node] = find(parent[node]); return parent[node]; } public void union(int x,int y) { int xroot = find(x); int yroot = find(y); if(rank[x] > rank[y]) parent[yroot] = xroot; else if(rank[x] < parent[y]) parent[xroot] = yroot; else { parent[yroot] = xroot; rank[xroot]++; } } public boolean sameset(int x,int y) { return find(x) == find(y); } } public static class Pair { int v,depth; public Pair(int v,int depth) { this.v = v; this.depth = depth; } } public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] str = (br.readLine()).trim().split(" "); int n = Integer.parseInt(str[0]); int m = Integer.parseInt(str[1]); str = new String[n]; DSU dsu = new DSU(n + m); for(int i=0;i<n;i++) { str[i] = (br.readLine()).trim(); for(int j=0;j<m;j++) { if(str[i].charAt(j) == '=') { if(!dsu.sameset(i,j+n)) dsu.union(i, j+n); } } } int Icomp = 0; int[] comp = new int[n+m]; Arrays.fill(comp,-1); for(int i=0;i<n+m;i++) { if(comp[i] != -1) continue; comp[i] = Icomp; for(int j=i+1;j<m+n;j++) { if(dsu.sameset(i, j)) comp[j] = Icomp; } Icomp++; } //System.out.println(Icomp); ArrayList<Integer>[] g = new ArrayList[Icomp]; for(int i=0;i<Icomp;i++) g[i] = new ArrayList<>(); for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(str[i].charAt(j) == '<') { g[comp[i]].add(comp[n+j]); } else if(str[i].charAt(j) == '>') { //System.out.println(i + " " + (n + j)); g[comp[n+j]].add(comp[i]); } } } int[] in_degree = new int[Icomp]; for(int i=0;i<Icomp;i++) { for(int j : g[i]) in_degree[j]++; } int[] val = new int[Icomp]; Queue<Pair> queue = new LinkedList<>(); for(int i=0;i<Icomp;i++) { if(in_degree[i] == 0) queue.add(new Pair(i,1)); } while(!queue.isEmpty()) { Pair s = queue.poll(); if(val[s.v] > 0) continue; val[s.v] = s.depth; for(int it : g[s.v]) { if(--in_degree[it] == 0 && val[it] == 0) { queue.add(new Pair(it,s.depth + 1)); } } } //for(int i=0;i<Icomp;i++) // System.out.print(val[i] + " "); //System.out.println(); int[] ans = new int[n+m]; for(int i=0;i<n+m;i++) { ans[i] = val[comp[i]]; if(ans[i] == 0) { System.out.println("No"); return; } } System.out.println("Yes"); for(int i=0;i<n;i++) System.out.print(ans[i] + " "); System.out.println(); for(int j=n;j<n+m;j++) System.out.print(ans[j] + " "); System.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
#include <bits/stdc++.h> int DEBUG = 1; using namespace std; const int N = 1000 + 5; int parent[N + N], sz[N + N]; int find_set(int v) { if (parent[v] == v) return v; return parent[v] = find_set(parent[v]); } void make_set(int v) { parent[v] = v; sz[v] = 1; } void merge(int a, int b) { a = find_set(a); b = find_set(b); if (a == b) return; if (sz[a] < sz[b]) swap(a, b); parent[b] = a; sz[a] += sz[b]; } int n, m; vector<int> g[N + N]; vector<int> gt[N + N]; int odeg[N + N]; char s[N][N]; int color[N + N]; int was_cycle = 0; void dfs(int v) { if (color[v] == 1) { was_cycle = 1; return; } color[v] = 1; for (int to : gt[v]) { if (color[to] != 2) { dfs(to); } } color[v] = 2; } int main() { scanf("%d%d", &n, &m); for (int i = 0; i < n + m; i++) make_set(i); bool bad = false; for (int i = 0; i < n; i++) { scanf("%s", s[i]); for (int j = 0; j < m; j++) { if (s[i][j] == '=') { merge(i, j + n); } } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (s[i][j] != '=') { if (find_set(i) == find_set(j + n)) bad = true; } } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (s[i][j] == '=') continue; int u = i; int v = j + n; if (s[i][j] == '<') swap(u, v); u = find_set(u); v = find_set(v); g[u].push_back(v); gt[v].push_back(u); odeg[u]++; } } for (int v = 0; v < n + m; v++) { if (color[v] == 0) { dfs(v); } } if (was_cycle || bad) { printf("No\n"); return 0; } set<pair<int, int> > st; for (int v = 0; v < n + m; v++) { st.insert(make_pair(odeg[v], v)); } map<int, int> mp; int GI = 1; while (!st.empty()) { vector<int> cur; while (!st.empty() && st.begin()->first == 0) { cur.push_back(st.begin()->second); st.erase(st.begin()); } for (int v : cur) { mp[v] = GI; } for (int v : cur) { for (int nei : gt[v]) { st.erase({odeg[nei], nei}); odeg[nei]--; st.insert({odeg[nei], nei}); } } GI++; } printf("Yes\n"); for (int i = 0; i < n; i++) { int val = mp[find_set(i)]; printf("%d ", val); } printf("\n"); for (int i = n; i < n + m; i++) { int val = mp[find_set(i)]; printf("%d ", val); } 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
#!/usr/bin/env pypy import collections #import random import heapq import bisect import math import time class Solution2: def solve(self, A1, A2): pass def gcd(a, b): if not b: return a return gcd(b, a%b) def lcm(a, b): return b*a//gcd(b,a) class Solution: def solve(self, grid): def union(i,j): leader_i, leader_j = find(i), find(j) sets[leader_j] = sets[i] = sets[j] = leader_i def find(i): while i != sets[i]: i = sets[i] return i N = len(grid) + len(grid[0]) sets = list(range(N)) for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == '=': union(i,j+len(grid)) graph = collections.defaultdict(set) inc = collections.defaultdict(set) for i in range(len(grid)): for j in range(len(grid[0])): leader_i, leader_j = find(i), find(j+len(grid)) if grid[i][j] == '>': if leader_i == leader_j: print("No") return graph[leader_j].add(leader_i) inc[leader_i].add(leader_j) elif grid[i][j] == '<': if leader_i == leader_j: print("No") return graph[leader_i].add(leader_j) inc[leader_j].add(leader_i) self.levels = [0]*N def dfs(node, level): self.levels[node] = max(self.levels[node],level) if not inc[node]: seen.add(node) for next_node in graph[node]: inc[next_node].discard(node) dfs(next_node,self.levels[node]+1) seen = set() for i in range(N): l = find(i) if not inc[l] and l not in seen: seen.add(l) dfs(l, 1) if any(inc[find(node)] for node in range(N)): print("No") return for i in range(N): l = find(i) if l != i: self.levels[i] = self.levels[l] print("Yes") print(' '.join(str(o) for o in self.levels[:len(grid)])) print(' '.join(str(o) for o in self.levels[len(grid):])) sol = Solution() sol2 = Solution2() #TT = int(input()) for test_case in range(1): N, M = input().split() a = [] for _ in range(int(N)): a.append(input()) #b = [int(c) for c in input().split()] out = sol.solve(a) #print(' '.join([str(o) for o in out])) #print(str(out)) # out2 = sol2.solve(s) # for _ in range(100000): # rand = [random.randrange(60) for _ in range(10)] # out1 = sol.solve(rand) # out2 = sol2.solve(rand) # if out1 != out2: # print(rand, out1, out2) # break
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 static java.lang.Math.*; import static java.util.Arrays.*; // 4:14.620 + 17:04.436 public class cf1131d { static int par[], indeg[]; static int find(int i) { return i == par[i] ? i : (par[i] = find(par[i])); } static void union(int i, int j) { int a = find(i), b = find(j); if (a != b) { par[b] = a; indeg[a] += indeg[b]; } } public static void main(String[] args) throws IOException { int n = rni(), m = ni(); char[][] a = new char[n][]; for (int i = 0; i < n; ++i) { a[i] = rcha(); } Graph g = graph(n + m); par = new int[n + m]; indeg = new int[n + m]; int ecnt = 0; for (int i = 0; i < n + m; ++i) { par[i] = i; } for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (a[i][j] == '=') { union(i, n + j); } } } for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (a[i][j] == '=') { continue; } if (find(i) == find(n + j)) { prn(); close(); return; } if (a[i][j] == '<') { g.cto(find(i), find(n + j)); ++indeg[find(n + j)]; ++ecnt; } else if (a[i][j] == '>') { g.cto(find(n + j), find(i)); ++indeg[find(i)]; ++ecnt; } } } int ans[] = new int[n + m]; fill(ans, 1); Queue<Integer> q = new LinkedList<>(); for (int i = 0; i < n + m; ++i) { if (find(i) == i && indeg[i] == 0) { q.offer(i); } } while (!q.isEmpty()) { int i = q.poll(); for (int j : g.get(i)) { --ecnt; ans[j] = max(ans[j], ans[i] + 1); if (--indeg[j] == 0) { q.offer(j); } } } if (ecnt == 0) { pry(); for (int i = 0; i < n; ++i) { if (i > 0) { pr(' '); } pr(ans[find(i)]); } prln(); for (int i = 0; i < m; ++i) { if (i > 0) { pr(' '); } pr(ans[find(n + i)]); } prln(); } else { prn(); } close(); } static Graph graph(int n) { Graph g = new Graph(); for (int i = 0; i < n; ++i) { g.add(new ArrayList<>()); } return g; } static Graph graph(int n, int m) throws IOException { Graph g = graph(n); for (int i = 0; i < m; ++i) { g.c(rni() - 1, ni() - 1); } return g; } static Graph tree(int n) throws IOException { return graph(n, n - 1); } static class Graph extends ArrayList<List<Integer>> { void cto(int u, int v) { get(u).add(v); } void c(int u, int v) { cto(u, v); cto(v, u); } boolean is_leaf(int i) { return get(i).size() == 1; } } static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out)); static StringTokenizer input; static Random __rand = new Random(); // references // IBIG = 1e9 + 7 // IMAX ~= 2e9 // LMAX ~= 9e18 // constants static final int IBIG = 1000000007; static final int IMAX = 2147483647; static final int IMIN = -2147483648; static final long LMAX = 9223372036854775807L; static final long LMIN = -9223372036854775808L; // math util static int minof(int a, int b, int c) {return min(a, min(b, c));} static int minof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;} static long minof(long a, long b, long c) {return min(a, min(b, c));} static long minof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;} static int maxof(int a, int b, int c) {return max(a, max(b, c));} static int maxof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;} static long maxof(long a, long b, long c) {return max(a, max(b, c));} static long maxof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;} static int powi(int a, int b) {if (a == 0) return 0; int ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static long powl(long a, int b) {if (a == 0) return 0; long ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static int fli(double d) {return (int) d;} static int cei(double d) {return (int) ceil(d);} static long fll(double d) {return (long) d;} static long cel(double d) {return (long) ceil(d);} static int gcf(int a, int b) {return b == 0 ? a : gcf(b, a % b);} static long gcf(long a, long b) {return b == 0 ? a : gcf(b, a % b);} static int lcm(int a, int b) {return a * b / gcf(a, b);} static long lcm(long a, long b) {return a * b / gcf(a, b);} static int randInt(int min, int max) {return __rand.nextInt(max - min + 1) + min;} static long mix(long x) {x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31);} // array util static void reverse(int[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(long[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(double[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(char[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void shuffle(int[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(long[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(double[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void rsort(int[] a) {shuffle(a); sort(a);} static void rsort(long[] a) {shuffle(a); sort(a);} static void rsort(double[] a) {shuffle(a); sort(a);} static int[] copy(int[] a) {int[] ans = new int[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static long[] copy(long[] a) {long[] ans = new long[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static double[] copy(double[] a) {double[] ans = new double[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static char[] copy(char[] a) {char[] ans = new char[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} // input static void r() throws IOException {input = new StringTokenizer(rline());} static int ri() throws IOException {return Integer.parseInt(rline());} static long rl() throws IOException {return Long.parseLong(rline());} static double rd() throws IOException {return Double.parseDouble(rline());} static int[] ria(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni(); return a;} static int[] riam1(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni() - 1; return a;} static long[] rla(int n) throws IOException {long[] a = new long[n]; r(); for (int i = 0; i < n; ++i) a[i] = nl(); return a;} static double[] rda(int n) throws IOException {double[] a = new double[n]; r(); for (int i = 0; i < n; ++i) a[i] = nd(); return a;} static char[] rcha() throws IOException {return rline().toCharArray();} static String rline() throws IOException {return __in.readLine();} static String n() {return input.nextToken();} static int rni() throws IOException {r(); return ni();} static int ni() {return Integer.parseInt(n());} static long rnl() throws IOException {r(); return nl();} static long nl() {return Long.parseLong(n());} static double rnd() throws IOException {r(); return nd();} static double nd() {return Double.parseDouble(n());} // output static void pr(int i) {__out.print(i);} static void prln(int i) {__out.println(i);} static void pr(long l) {__out.print(l);} static void prln(long l) {__out.println(l);} static void pr(double d) {__out.print(d);} static void prln(double d) {__out.println(d);} static void pr(char c) {__out.print(c);} static void prln(char c) {__out.println(c);} static void pr(char[] s) {__out.print(new String(s));} static void prln(char[] s) {__out.println(new String(s));} static void pr(String s) {__out.print(s);} static void prln(String s) {__out.println(s);} static void pr(Object o) {__out.print(o);} static void prln(Object o) {__out.println(o);} static void prln() {__out.println();} static void pryes() {prln("yes");} static void pry() {prln("Yes");} static void prY() {prln("YES");} static void prno() {prln("no");} static void prn() {prln("No");} static void prN() {prln("NO");} static boolean pryesno(boolean b) {prln(b ? "yes" : "no"); return b;}; static boolean pryn(boolean b) {prln(b ? "Yes" : "No"); return b;} static boolean prYN(boolean b) {prln(b ? "YES" : "NO"); return b;} static void prln(int... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static void prln(long... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static void prln(double... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for (int i = 0; i < n; pr(iter.next()), pr(' '), ++i); if (n >= 0) prln(iter.next()); else prln();} static void h() {prln("hlfd"); flush();} static void flush() {__out.flush();} static void 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; int n, m; char mp[1005][1005]; int pre[2 * 1005]; bool vis[2 * 1005]; int in[2 * 1005]; int ans[2 * 1005]; vector<int> g[2 * 1005]; struct no { int a, c; }; int found(int x) { int re = x; while (re != pre[re]) { re = pre[re]; } while (x != pre[x]) { int t = pre[x]; pre[x] = re; x = t; } return re; } void join(int x, int y) { int fx = found(x), fy = found(y); if (fx != fy) { pre[fx] = pre[fy]; vis[fx] = 1; } } void addarc(int from, int to) { g[from].push_back(to); in[to]++; } void topo(int st) { queue<no> q; q.push((no){st, 1}); while (!q.empty()) { no now = q.front(); q.pop(); ans[now.a] = now.c; for (int i = 0; i < (int)g[now.a].size(); i++) { int to = g[now.a][i]; in[to]--; if (in[to] == 0 && vis[to] == 0) q.push((no){to, now.c + 1}); } g[now.a].clear(); } } int main() { ios::sync_with_stdio(false); cin >> n >> m; for (int i = 0; i < n; i++) cin >> mp[i]; int kk = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (mp[i][j] != '=') { kk = 1; } } } if (kk == 0) { cout << "Yes" << endl; for (int i = 0; i < m + n; i++) { cout << 1 << ' '; if (i == n - 1) cout << endl; } return 0; } for (int i = 0; i < m + n; i++) pre[i] = i; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (mp[i][j] == '=') { join(i, j + n); } } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (found(i) == found(j + n) && mp[i][j] != '=') { cout << "No"; return 0; } int fx = found(i), fy = found(j + n); if (mp[i][j] == '>') { addarc(fy, fx); } if (mp[i][j] == '<') { addarc(fx, fy); } } } int i; for (i = 0; i < m + n; i++) { if (in[i] == 0 && g[i].size()) { topo(i); } } for (int i = 0; i < m + n; i++) { if (in[i] != 0 && vis[i] == 0) { cout << "No"; return 0; } } cout << "Yes" << endl; for (int i = 0; i < m + n; i++) { if (ans[i] == 0) { ans[i] = ans[found(i)]; } cout << ans[i] << ' '; if (i == n - 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; using namespace std; char a[1005][1005]; vector<int> e[2005]; int cont[2005]; int ans[2005]; int fa[2005]; int n, m; int f(int x) { if (fa[x] == x) return x; return fa[x] = f(fa[x]); } void unite(int u, int v) { int _u, _v; _u = f(u); _v = f(v); if (_u != _v) fa[_v] = _u; } int main() { scanf("%d%d", &n, &m); for (int i = 1; i <= n + m; i++) fa[i] = i; for (int i = 1; i <= n; i++) scanf("%s", a[i] + 1); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) if (a[i][j] == '=') unite(i, n + j); for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (a[i][j] == '=') continue; int fi = f(i); int fj = f(n + j); if (fi == fj) { printf("No\n"); return 0; } if (a[i][j] == '<') { cont[fj]++; e[fi].push_back(fj); } else { cont[fi]++; e[fj].push_back(fi); } } } int sum = 0; int x; int l; for (int i = 1; i <= n + m; i++) if (f(i) == i) sum++; queue<int> qu; for (int i = 1; i <= n + m; i++) if (cont[i] == 0 && (f(i) == i)) { qu.push(i); ans[i] = 1; sum--; } while (!qu.empty()) { x = qu.front(); qu.pop(); l = e[x].size(); for (int i = 0; i < l; i++) { ans[e[x][i]] = max(ans[x] + 1, ans[e[x][i]]); if (--cont[e[x][i]] == 0) { sum--; qu.push(e[x][i]); } } } if (sum != 0) { printf("No\n"); return 0; } printf("Yes\n"); for (int i = 1; i <= n; i++) printf("%d ", ans[f(i)]); printf("\n"); for (int i = n + 1; i <= n + m; i++) printf("%d ", ans[f(i)]); printf("\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; struct enode { int y, nxt; } e[1005 * 1005]; int n, m; int tot = 0; char s[1005][1005]; int q[1005 * 3]; int fa[1005 * 3], first[1005 * 3], dp[1005 * 3], goin[1005 * 3]; int get(int x) { if (fa[x] == x) return x; else return fa[x] = get(fa[x]); } void adde(int x, int y) { e[tot].nxt = first[x]; e[tot].y = y; first[x] = tot++; goin[y]++; } int tupu() { int head = 1, tail = 0; for (int i = 1; i <= n + m; i++) if (goin[i] == 0) q[++tail] = i; while (head <= tail) { int x = q[head]; for (int i = first[x]; i >= 0; i = e[i].nxt) { int y = e[i].y; goin[y]--; dp[y] = ((dp[y]) > (dp[x] + 1) ? (dp[y]) : (dp[x] + 1)); if (goin[y] == 0) q[++tail] = y; } head++; } if (tail == n + m) return 1; else return 0; } int main() { scanf("%d%d", &n, &m); for (int i = 1; i <= n + m; i++) fa[i] = i, first[i] = -1, dp[i] = 1; for (int i = 1; i <= n; i++) { scanf("%s", s[i] + 1); for (int j = 1; j <= m; j++) { int x = get(i), y = get(n + j); if (s[i][j] == '=') { if (x != y) fa[x] = y; } } } for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { int x = get(i), y = get(n + j); if (x == y && s[i][j] != '=') return printf("No"), 0; if (x == y) continue; if (s[i][j] == '>') adde(y, x); else adde(x, y); } if (tupu()) { printf("Yes\n"); for (int i = 1; i <= n; i++) printf("%d ", dp[get(i)]); printf("\n"); for (int i = 1; i <= m; i++) printf("%d ", dp[get(n + i)]); printf("\n"); } else return printf("No"), 0; 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, a[1001], b[1001], sa[1001], sb[1001], s, ok, val = 1, ln, lm, Ok, v[1001][1001], eg1[1001], eg2[1001], mn; char c; int main() { cin >> n >> m; ln = m; lm = n; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { cin >> c; switch (c) { case '<': sa[i]++; s++; v[i][j] = -1; break; case '=': sa[i]++; sb[j]++; v[i][j] = 0; eg1[i]++; eg2[j]++; break; case '>': sb[j]++; s++; v[i][j] = 1; break; } } } while (ln > 0 && lm > 0) { ok = 0; mn = m + 1; ; for (int i = 1; i <= n; i++) if (eg1[i] < mn && sa[i] >= ln) mn = eg1[i]; for (int i = 1; i <= n; i++) { if (sa[i] >= ln && eg1[i] == mn) { lm--; a[i] = val; sa[i] = -1; ok = 1; } } Ok = ok; mn = n + 1; for (int i = 1; i <= m; i++) if (eg2[i] < mn && sb[i] >= lm + Ok) mn = eg2[i]; for (int i = 1; i <= m; i++) { if (sb[i] >= lm + Ok && eg2[i] == mn) { ln--; b[i] = val; sb[i] = -1; ok = 1; } } if (ok == 0) { cout << "NO"; return 0; } val++; } for (int i = 1; i <= n; i++) { if (a[i] == 0) a[i] = val; for (int j = 1; j <= m; j++) { if (b[j] == 0) b[j] = val; if ((v[i][j] == 0 && a[i] != b[j]) || (v[i][j] && a[i] * v[i][j] <= b[j] * v[i][j])) { cout << "NO"; return 0; } } } cout << "YES\n"; for (int i = 1; i <= n; i++) { cout << a[i] << ' '; } cout << '\n'; for (int i = 1; i <= m; i++) { cout << b[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 = (int)3e3; int p[N], n, m, deg[N], d[N]; char a[N][N]; vector<int> adj[N]; queue<int> q; bool visited[N]; int findSet(int u) { return p[u] == u ? p[u] : p[u] = findSet(p[u]); } void unionSet(int u, int v) { int x = findSet(u), y = findSet(v); p[x] = y; } int main() { scanf("%d %d\n", &n, &m); for (int i = 1; i <= n; ++i) { scanf("%s\n", a[i] + 1); p[i] = i; } for (int i = 1; i <= m; ++i) p[n + i] = n + i; for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) if (a[i][j] == '=') unionSet(i, n + j); for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) { if (a[i][j] == '>') adj[findSet(n + j)].push_back(findSet(i)), deg[findSet(i)]++; else if (a[i][j] == '<') adj[findSet(i)].push_back(findSet(n + j)), deg[findSet(n + j)]++; } bool ans = 1; for (int i = 1; i <= n + m; ++i) if (deg[findSet(i)] == 0 && !visited[findSet(i)]) { d[findSet(i)] = 1; visited[findSet(i)] = 1; q.push(findSet(i)); } while (!q.empty()) { int u = q.front(); q.pop(); for (int v : adj[u]) if (!visited[v]) { d[v] = max(d[v], d[u] + 1); deg[v]--; if (deg[v] == 0) { q.push(v); visited[v] = 1; } } } for (int i = 1; i <= n + m; ++i) if (!visited[findSet(i)]) { ans = 0; break; } if (ans) { printf("Yes\n"); for (int i = 1; i <= n; ++i) printf("%d ", d[findSet(i)]); printf("\n"); for (int i = 1; i <= m; ++i) printf("%d ", d[findSet(n + i)]); printf("\n"); } else printf("No\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
class UnionFind: def __init__(self, n): self.follow = [-1]*(n+1) self.num_follower = [1]*(n+1) def root_index_of(self, a): r = a while self.follow[r] > -1: r = self.follow[r] return r def connected(self, a, b): return self.root_index_of(a) == self.root_index_of(b) def connect(self, a, b): ra = self.root_index_of(a) rb = self.root_index_of(b) if ra == rb: return if self.num_follower[ra] < self.num_follower[rb]: self.follow[ra] = rb self.follow[a] = rb self.num_follower[rb] += self.num_follower[ra] else: self.follow[rb] = ra self.follow[b] = ra self.num_follower[ra] += self.num_follower[rb] import sys from collections import deque input = sys.stdin.readline n, m = map(int, input().split()) s = [input() for _ in range(n)] uf = UnionFind(n+m) v = [[] for _ in range(n+m)] c = [0]*(n+m) for i in range(n): for j in range(m): if s[i][j] == "=": uf.connect(i, j+n) for i in range(n): for j in range(m): if s[i][j] == "<": v[uf.root_index_of(i)].append(uf.root_index_of(n+j)) c[uf.root_index_of(n+j)] += 1 elif s[i][j] == ">": v[uf.root_index_of(n+j)].append(uf.root_index_of(i)) c[uf.root_index_of(i)] += 1 ans = [0]*(n+m) used = [0]*(n+m) que = deque([]) for i in range(n+m): if c[i] == 0: ans[i] = 1 used[i] = 1 que.append(i) while que: x = que.popleft() for i in v[x]: if used[i]: continue ans[i] = max(ans[x]+1, ans[i]) c[i] -= 1 if c[i] == 0: used[i] = 1 que.append(i) for i in range(n+m): if used[i] == 0: print("No") exit() for i in range(n): for j in range(m): if s[i][j] == "=": if ans[uf.root_index_of(i)] != ans[uf.root_index_of(n+j)]: print("No") exit() for i in range(n): for j in range(m): if s[i][j] == "<": if ans[uf.root_index_of(i)] >= ans[uf.root_index_of(n+j)]: print("No") exit() for i in range(n): for j in range(m): if s[i][j] == ">": if ans[uf.root_index_of(i)] <= ans[uf.root_index_of(n+j)]: print("No") exit() print("Yes") for i in range(n): print(ans[uf.root_index_of(i)], end=" ") print() for j in range(m): print(ans[uf.root_index_of(j+n)], end=" ") print()
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; class Graph { public: vector<vector<int> > adjList; vector<int> indegree; Graph(int v) { adjList.resize(v); indegree.resize(v, 0); } void add(int u, int v) { adjList[u].push_back(v); indegree[v]++; } }; struct subset { int rank; int parent; }; int find(subset subsets[], int i) { if (subsets[i].parent != i) subsets[i].parent = find(subsets, subsets[i].parent); return subsets[i].parent; } void Union(subset subsets[], int x, int y) { int xroot = find(subsets, x); int yroot = find(subsets, y); if (subsets[xroot].rank > subsets[yroot].rank) { subsets[yroot].parent = xroot; } else if (subsets[xroot].rank < subsets[yroot].rank) { subsets[xroot].parent = yroot; } else { subsets[yroot].parent = xroot; subsets[xroot].rank++; } } bool TopologicalSort(Graph const &graph, vector<int> &ans, int v, subset subsets[]) { vector<int> indegree = graph.indegree; queue<int> S; for (int i = 0; i < v; i++) { if (!indegree[i]) { S.push(i); ans[find(subsets, i)] = 1; } } while (!S.empty()) { int n = S.front(); S.pop(); for (int m : graph.adjList[n]) { indegree[m] -= 1; ans[find(subsets, m)] = ans[find(subsets, n)] + 1; if (!indegree[m]) { S.push(m); } } } for (int i = 0; i < v; i++) { if (indegree[i]) { return false; } } return true; } int main() { int n, m; cin >> n >> m; subset *subsets = new subset[n + m]; for (int v = 0; v < n + m; v++) { subsets[v].parent = v; subsets[v].rank = 0; } Graph graph(n + m); char input[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> input[i][j]; if (input[i][j] == '=') { Union(subsets, i, j + n); } } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int x = find(subsets, i); int y = find(subsets, j + n); if (input[i][j] == '<') { graph.add(x, y); } else if (input[i][j] == '>') { graph.add(y, x); } } } vector<int> ans(n + m); if (TopologicalSort(graph, ans, n + m, subsets)) { cout << "YES" << endl; for (int i = 0; i < n; i++) { cout << ans[find(subsets, i)] << " "; } cout << endl; for (int i = n; i < m + n; i++) { cout << ans[find(subsets, i)] << " "; } cout << endl; } 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; struct READ { int d1, d2, d3; READ(int d1 = -1, int d2 = -1, int d3 = -1) : d1(d1), d2(d2), d3(d3) {} template <class T> operator T() { T tmp; this->read(tmp); return tmp; } template <class T> void read(T& t) { cin >> t; } template <class T> void read(vector<T>& cont) { assert(d1 != -1); cont.resize(d1); READ r(d2, d3); for (int i = 0; i < d1; ++i) r.read(cont[i]); } template <class T1, class T2> void read(pair<T1, T2>& x) { read(x.first); read(x.second); } }; int main(int argc, char* argv[]) { int n = READ(), m = READ(); vector<string> matrix = READ(n); vector<pair<int, int>> dishes; for (int i = 0; i < n; ++i) dishes.emplace_back(0, i); for (int i = 0; i < m; ++i) dishes.emplace_back(1, i); auto d1Greatness = [&](int i) { int result = 0; for (char ch : matrix[i]) if (ch == '>') result += 1; else if (ch == '<') result -= 1; return result; }; auto d2Greatness = [&](int i) { int result = 0; for (auto& row : matrix) if (row[i] == '<') result += 1; else if (row[i] == '>') result -= 1; return result; }; auto compare = [&](pair<int, int>& x, pair<int, int>& y) { if (x.first == 0) { if (y.first == 0) { return d1Greatness(x.second) < d1Greatness(y.second); } else { return matrix[x.second][y.second] == '<'; } } else { if (y.first == 0) { return matrix[y.second][x.second] == '>'; } else { return d2Greatness(x.second) < d2Greatness(y.second); } } }; std::sort(dishes.begin(), dishes.end(), compare); vector<int> d1(n), d2(m); int cur = 1; for (int i = 0; i < dishes.size(); ++i) { if (i > 0 && compare(dishes[i - 1], dishes[i])) cur += 1; if (dishes[i].first == 0) d1[dishes[i].second] = cur; else d2[dishes[i].second] = cur; } bool goodSolution = true; for (int i = 0; i < d1.size(); ++i) { for (int j = 0; j < d2.size(); ++j) { char ch = '='; if (d1[i] > d2[j]) ch = '>'; else if (d1[i] < d2[j]) ch = '<'; if (ch != matrix[i][j]) { goodSolution = false; break; } } } if (goodSolution) { cout << "Yes" << endl; for (int x : d1) cout << x << " "; cout << endl; for (int x : d2) cout << x << " "; 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
#include <bits/stdc++.h> using namespace std; using INT = long long; char s[2100][2100]; vector<int> adj[2100], rev[2100]; int arr[2100]; vector<int> vec[2100]; int root[2100]; int find_root(int u) { if (root[u] == u) return u; return root[u] = find_root(root[u]); } void merge(int u, int v) { if (find_root(u) == find_root(v)) return; u = root[u]; vector<int> tmp = vec[root[v]]; vec[root[v]].clear(); v = root[v], root[v] = u; for (int p : tmp) vec[u].push_back(p); } int id[2100], flag[2100]; int dfs(int u) { flag[u] = 1; for (int v : adj[u]) { if (flag[v] == 1) return 1; if (flag[v]) continue; if (dfs(v)) return 1; } flag[u] = -1; return 0; } int val[2100], vst[2100], dig[2100]; int a[2100], b[2100]; int main() { int n, m; cin >> n >> m; for (int i = 1; i <= n; i++) { scanf("%s", s[i] + 1); } for (int i = 1; i <= n; i++) { root[i] = i; vec[i].push_back(i); } for (int i = 1; i <= m; i++) { root[i + n] = i + n; vec[i + n].push_back(i + n); } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (s[i][j] == '=') merge(i, j + n); } } int nn = 0; for (int i = 1; i <= n + m; i++) if (find_root(i) == i) arr[++nn] = i, id[i] = nn; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { int u = id[root[i]]; int v = id[root[j + n]]; if (s[i][j] == '>') { adj[v].push_back(u); rev[u].push_back(v); } if (s[i][j] == '<') { adj[u].push_back(v); rev[v].push_back(u); } } } for (int i = 1; i <= nn; i++) { if (flag[i]) continue; int ok = dfs(i); if (ok) { puts("No"); return 0; } } puts("Yes"); int tot = nn + 10; queue<int> q; for (int i = 1; i <= nn; i++) { dig[i] = adj[i].size(); if (dig[i] == 0) { q.push(i); val[i] = tot; vst[i] = 1; } } while (!q.empty()) { int u = q.front(); q.pop(); for (int v : rev[u]) { dig[v]--; if (dig[v] == 0) { val[v] = val[u] - 1; q.push(v); } } } int mn = 1e6; for (int i = 1; i <= nn; i++) { int u = arr[i]; mn = min(mn, val[i]); for (int v : vec[u]) { if (v <= n) a[v] = val[i]; else { b[v - n] = val[i]; } } } for (int i = 1; i <= n; i++) printf("%d ", a[i] - mn + 1); printf("\n"); for (int i = 1; i <= m; i++) mn = min(mn, b[i]); for (int i = 1; i <= m; i++) printf("%d ", b[i] - mn + 1); return 0; }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n × m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≤ n, m ≤ 1000) — the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers — evaluations of dishes from the first set, and on the third line print m integers — evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> using namespace std; int root(vector<int> &p, int i) { while (p[i] != i) { p[i] = p[p[i]]; i = p[i]; } return i; } void init(vector<int> &p, vector<int> &s) { for (int i = 0; i < p.size(); i++) { p[i] = i; } for (auto &i : s) { i = 1; } } void merge(int i, int j, vector<int> &p, vector<int> &s) { int root_i = root(p, i); int root_j = root(p, j); if (root_i != root_j) { if (s[root_i] > s[root_j]) { p[root_j] = p[root_i]; s[root_i] += s[root_j]; } else { p[root_i] = p[root_j]; s[root_j] += s[root_i]; } } } void nodeMerge(const vector<string> &r, vector<int> &p, vector<int> &s) { for (int i = 0; i < r.size(); i++) { for (int j = 0; j < r[0].size(); j++) { if (r[i][j] == '=') { merge(i, r.size() + j, p, s); } } } } vector<vector<int>> construct(const vector<string> &r, vector<int> &p, vector<int> &s) { vector<vector<int>> res(p.size()); int base = r.size(); for (int i = 0; i < r.size(); i++) { for (int j = 0; j < r[0].size(); j++) { if (r[i][j] == '<') { res[root(p, i)].push_back(root(p, base + j)); } else if (r[i][j] == '>') { res[root(p, base + j)].push_back(root(p, i)); } } } return res; } bool DFS(vector<int> &state, const vector<vector<int>> &g, int i, stack<int> &order) { if (state[i] == 2) { return false; } else if (state[i] == 1) { return true; } else { state[i] = 1; for (auto n : g[i]) { if (DFS(state, g, n, order)) { return true; } } state[i] = 2; order.push(i); } return false; } bool findLoop(const vector<vector<int>> &g, stack<int> &order) { vector<int> state(g.size(), 0); for (int i = 0; i < state.size(); i++) { if (DFS(state, g, i, order)) { return true; } } return false; } int findRoot(vector<int> &p, stack<int> &order) { while (!order.empty()) { int topNode = order.top(); if (root(p, topNode) == topNode) { return topNode; } order.pop(); } cout << "no root"; } vector<int> calGrade(const vector<vector<int>> &g, vector<int> &p, stack<int> &order) { vector<vector<int>> rev(g.size()); vector<int> grade(g.size(), 87); for (int i = 0; i < g.size(); i++) { for (auto n : g[i]) { rev[n].push_back(i); } } while (!order.empty()) { int maxVal = 0; int topNode = order.top(); for (auto i : rev[topNode]) { maxVal = max(maxVal, grade[i]); } grade[topNode] = maxVal + 1; order.pop(); } for (int i = 0; i < grade.size(); i++) { if (root(p, i) != i) { grade[i] = grade[root(p, i)]; } } return grade; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); int n, m; cin >> n >> m; vector<string> r; vector<int> p(n + m); vector<int> s(n + m); stack<int> order; init(p, s); string input; for (int i = 0; i < n; i++) { cin >> input; r.push_back(input); } nodeMerge(r, p, s); auto g = construct(r, p, s); if (findLoop(g, order)) { cout << "No"; } else { cout << "Yes" << endl; int point = 1; vector<int> grade = calGrade(g, p, order); for (int i = 0; i < n; i++) { cout << grade[i] << ' '; } cout << endl; for (int i = 0; i < m; i++) { cout << grade[n + i] << ' '; } } }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n × m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≤ n, m ≤ 1000) — the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers — evaluations of dishes from the first set, and on the third line print m integers — evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.
2
10
import java.util.Scanner; public class Main { public static int[] dsu; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int m = scanner.nextInt(); scanner.nextLine(); int[] a = new int[n * m + 1]; int[] b = new int[n * m + 1]; int[] c = new int[n + m + 1]; dsu = new int[n + m + 1]; int[] state = new int[n + m + 1]; int[] inDegree = new int[n + m + 1]; for (int i = 1, total = n + m; i <= total; i++) dsu[i] = i; char[][] chars = new char[n][]; for (int i = 0; i < n; i++) { chars[i] = scanner.nextLine().toCharArray(); for (int j = 0; j < m; j++) { if (chars[i][j] == '=') { join(i + 1, n + j + 1); } } } int t = 0; int temp; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (chars[i][j] == '<') { t++; temp = find(i + 1); a[t] = find(temp); inDegree[temp]++; temp = find(n + j + 1); b[t] = c[temp]; c[temp] = t; } else if (chars[i][j] == '>') { t++; temp = find(n + j + 1); a[t] = find(temp); inDegree[temp]++; temp = find(i + 1); b[t] = c[temp]; c[temp] = t; } } } boolean findable = true; int count = 0; boolean[] used = new boolean[n + m + 1]; while (findable) { findable = false; count++; for (int i = 1, total = n + m; i <= total; i++) { if (state[i] == 0 && inDegree[find(i)] == 0) { findable = true; state[i] = count; } } for (int i = 1, total = n + m; i <= total; i++) { if (state[i] == count && !used[temp = find(i)]) { used[temp] = true; t = c[temp]; while (t != 0) { inDegree[find(a[t])]--; t = b[t]; } } } } for (int i = 1; i <= n + m; i++) if (state[i] == 0) { System.out.println("No"); System.exit(0); } System.out.println("Yes"); for (int i = 1; i < n; i++) System.out.print(count - state[i] + " "); System.out.println(count - state[n]); for (int i = n + 1; i <= n + m; i++) System.out.print(count - state[i] + " "); } public static int find(int x) { int r = x; while (dsu[r] != r) r = dsu[r]; int temp; while (dsu[x] != x) { temp = dsu[x]; dsu[x] = r; x = temp; } return r; } public static void join(int x, int y) { int rx = find(x); int ry = find(y); if (rx != ry){ dsu[ry] = rx; } } }
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.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Random; import java.util.StringTokenizer; import java.util.stream.IntStream; public class Solution{ static final int N = 1005; static boolean[] visited, cur; static ArrayList<Integer>[] g; static int[] val; static boolean cycle = false; public static void main(String[] args) throws IOException { FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int tt = 1; while(tt-->0) { int n = fs.nextInt(), m = fs.nextInt(); DSU dsu = new DSU(n+m); visited = new boolean[n+m]; cur = new boolean[n+m]; val = new int[n+m]; g = new ArrayList[n+m]; for(int i=0;i<n+m;i++) g[i] = new ArrayList<Integer>(); char[][] a = new char[n][]; for(int i=0;i<n;i++) { a[i] = fs.next().toCharArray(); for(int j=0;j<m;j++) { if(a[i][j]=='=') { dsu.union(i, n+j); } } } for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(a[i][j]!='=' && dsu.find(i)==dsu.find(n+j)) { out.println("No"); out.flush(); return; } if(a[i][j]=='>') { g[dsu.find(i)].add(dsu.find(n+j)); } else if(a[i][j]=='<') { g[dsu.find(n+j)].add(dsu.find(i)); } } } ArrayList[] G = g; for(int i=0;i<n+m;i++) { if(!visited[dsu.find(i)]) { dfs(dsu.find(i)); } } if(cycle) { out.println("No"); out.flush(); return; } out.println("Yes"); for(int i=0;i<n;i++) { out.print(val[dsu.find(i)]+" "); } out.println(); for(int i=n;i<n+m;i++) { out.print(val[dsu.find(i)]+" "); } out.println(); } out.close(); } static int dfs(int v) { cur[v] = true; if(visited[v]) { cur[v] = false; return val[v]; } visited[v] = true; val[v] = 1; for(int u: g[v]) { if(cur[u]) { cycle = true; return 0; } val[v] = Math.max(val[v], 1 + dfs(u)); } cur[v] = false; return val[v]; } static class DSU{ int[] parent; int[] size; DSU(int n){ parent = new int[n]; for(int i=0;i<n;i++) parent[i] = i; size = new int[n]; Arrays.fill(size, 1); } int find(int v) { if(parent[v]==v) return v; return parent[v] = find(parent[v]); } void union(int a, int b) { a = find(a); b = find(b); if(a==b) return; if(size[a]>size[b]) { int temp = a; a = b; b = temp; } parent[a] = b; size[b] += size[a]; } } static final Random random=new Random(); static <T> void shuffle(T[] arr) { int n = arr.length; for(int i=0;i<n;i++ ) { int k = random.nextInt(n); T temp = arr[k]; arr[k] = arr[i]; arr[i] = temp; } } static void ruffleSort(int[] a) { int n=a.length;//shuffle, then sort for (int i=0; i<n; i++) { int oi=random.nextInt(n); int temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static void ruffleSort(long[] a) { int n=a.length;//shuffle, then sort for (int i=0; i<n; i++) { int oi=random.nextInt(n); long temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static void reverse(int[] arr, int l, int r) { for(int i=l;i<l+(r-l)/2;i++){ int temp = arr[i]; arr[i] = arr[r-i+l-1]; arr[r-i+l-1] = temp; } } static void reverse(long[] arr, int l, int r) { for(int i=l;i<l+(r-l)/2;i++){ long temp = arr[i]; arr[i] = arr[r-i+l-1]; arr[r-i+l-1] = temp; } } static <T> void reverse(T[] arr, int l, int r) { for(int i=l;i<l+(r-l)/2;i++) { T temp = arr[i]; arr[i] = arr[r-i+l-1]; arr[r-i+l-1] = temp; } } static class FastScanner{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); public String next(){ while(!st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); } catch(IOException e){ e.printStackTrace(); } } return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt(){ return Integer.parseInt(next()); } public int[] readArray(int n){ int[] a = new int[n]; for(int i=0;i<n;i++) a[i] = nextInt(); return a; } public long nextLong() { return Long.parseLong(next()); } public char nextChar() { return next().toCharArray()[0]; } } }
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<long long> adj[2005]; long long vis[2005]; long long ans[2005]; struct DSU { long long size; vector<long long> id; vector<long long> si; DSU(long long x) { size = x; id.resize(x + 1); si.resize(x + 1); for (long long i = 0; i < x; i++) { id[i] = i, si[i] = 1; } } long long getRoot(long long a) { while (a != id[a]) a = id[a]; return a; } void merge(long long a, long long b) { if (si[a] < si[b]) { swap(a, b); } si[a] += si[b]; id[b] = id[a]; } void fun(long long a, long long b) { long long x = getRoot(a); long long y = getRoot(b); if (x == y) return; merge(x, y); } }; bool loop(long long x, long long p) { vis[x] = 1; bool fl = false; for (auto it : adj[x]) { if (vis[it] == 1) fl = fl | (true); else if (vis[it] == 0) fl = fl | loop(it, x); } vis[x] = 2; return fl; } void dfs(long long x, long long p) { vis[x] = 1; for (auto it : adj[x]) { if (!vis[it]) dfs(it, x); } long long temp = 1; for (auto it : adj[x]) { temp = max(temp, ans[it] + 1); } ans[x] = temp; } signed main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); long long n, m; cin >> n >> m; struct DSU temp = DSU(n + m); vector<string> str(n); for (long long i = 0; i < n; i++) cin >> str[i]; for (long long i = 0; i < n; i++) { for (long long j = 0; j < m; j++) { if (str[i][j] == '=') temp.fun(i, j + n); } } for (long long i = 0; i < n; i++) { for (long long j = 0; j < m; j++) { long long x = temp.getRoot(j + n); long long y = temp.getRoot(i); if (str[i][j] == '=') continue; if (x == y) { cout << "No\n"; return 0; } if (str[i][j] == '<') adj[x].push_back(y); else if (str[i][j] == '>') adj[y].push_back(x); } } bool fl = false; for (long long i = 0; i < n + m; i++) { if (vis[i] == 0) { bool fl = loop(i, -1); if (fl == true) { cout << "No\n"; return 0; } } } for (long long i = 0; i < n + m; i++) vis[i] = 0; for (long long i = 0; i < n + m; i++) { if (vis[i] == 0) { dfs(i, -1); } } cout << "Yes\n"; for (long long i = 0; i < n; i++) cout << ans[temp.getRoot(i)] << " \n"[i == n - 1]; for (long long j = 0; j < m; j++) cout << ans[temp.getRoot(j + n)] << " \n"[j == m - 1]; return 0; }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n × m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≤ n, m ≤ 1000) — the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers — evaluations of dishes from the first set, and on the third line print m integers — evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.
2
10
import java.io.*; import java.util.*; public class TaskD { public static void main(String[] args){ InputStream inputstream; OutputStream outputstream; inputstream = System.in; outputstream = System.out; InputReader in = new InputReader(inputstream); PrintWriter out = new PrintWriter(outputstream); Task solver = new Task(); solver.solve(in,out); out.close(); } static class Task{ private ArrayList <Vertices> gr = new ArrayList <Vertices> (); private ArrayList <Integer> topo = new ArrayList <Integer> (); private ArrayList <Integer> p = new ArrayList<Integer>(); private String[] s; private int[] ord; private int[] h; private int[] col; private boolean[] vis; private int n,m; public void solve(InputReader in,PrintWriter out){ n = in.nextInt(); m = in.nextInt(); ord = new int[n + m]; h = new int[n + m]; vis = new boolean[n + m]; col = new int[n + m]; s = new String[n]; Arrays.fill(col,1); Arrays.fill(h,0); Arrays.fill(vis,false); Dsu dsu = new Dsu(n + m); for(int i = 0;i < n;++i){ s[i] = in.nextLine(); for(int j = 0;j < m;++j){ if(s[i].charAt(j) == '='){ dsu.join(i,n + j); } } } for(int i = 0;i < n + m;++i){ gr.add(new Vertices()); } for(int i = 0;i < n + m;++i){ if(i == dsu.findp(i)){ ord[i] = p.size(); p.add(i); } } for(int i = 0;i < n;++i){ for(int j = 0;j < m;++j){ int u = ord[dsu.findp(i)]; int v = ord[dsu.findp(n + j)]; if(u == v && s[i].charAt(j) != '='){ out.print("No");//contradict return; } if(s[i].charAt(j) == '>'){ gr.get(u).adj.add(v); } else if(s[i].charAt(j) == '<'){ gr.get(v).adj.add(u); } } } for(int u : p){ if(!vis[ord[u]]){ dfs(ord[u]); } } for(int u : p){ for(int v : gr.get(ord[u]).adj){ if(h[ord[u]] < h[v]){ //cycle out.print("No"); return; } } } for(int u : topo){ for(int v : gr.get(u).adj){ col[u] = Math.max(col[u],col[v] + 1); } } out.println("Yes"); for(int i = 0;i < n;++i){ out.print(col[ord[dsu.findp(i)]] + " "); } out.println(); for(int i = 0;i < m;++i){ out.print(col[ord[dsu.findp(i + n)]] + " "); } } private void dfs(int u){ vis[u] = true; for(int v : gr.get(u).adj){ if(!vis[v]){ dfs(v); } } h[u] = topo.size(); topo.add(u); } private class Vertices{ private ArrayList <Integer> adj; public Vertices(){ adj = new ArrayList <Integer>(); } } private class Dsu{ private int[] par; public Dsu(int sizeArray){ par = new int[sizeArray]; for(int i = 0;i < sizeArray;++i){ par[i] = i; } } public int findp(int u){ if(u == par[u]){ return u; } else { return par[u] = findp(par[u]); } } public void join(int u,int v){ par[findp(u)] = findp(v); } } } static class InputReader{ public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream){ reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next(){ while(tokenizer == null || !tokenizer.hasMoreTokens()){ try{ tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e){ throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt(){ return Integer.parseInt(next()); } public long nextLong(){ return Long.parseLong(next()); } public double nextDouble(){ return Double.parseDouble(next()); } public String nextLine(){ String ret_str = ""; try { ret_str = reader.readLine(); } catch (IOException e){ e.printStackTrace(); } return ret_str; } } }
JAVA
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n × m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≤ n, m ≤ 1000) — the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers — evaluations of dishes from the first set, and on the third line print m integers — evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> #pragma GCC optimize(2) using namespace std; inline int read() { int x = 0; bool op = false; char c = getchar(); while (!isdigit(c)) op |= (c == '-'), c = getchar(); while (isdigit(c)) x = (x << 1) + (x << 3) + (c ^ 48), c = getchar(); return op ? -x : x; } const int N = 3010; const int M = N * N + N; int n, m, tot; int head[N * 2], to[M * 2], nxt[M * 2], edge[M * 2], vis[N * 2], dis[N * 2], cnt[N * 2]; char s[N]; struct Node { int to, w; Node() {} Node(int to, int w) : to(to), w(w) {} }; vector<Node> nbr[N]; void addedge(int u, int v, int w) { to[++tot] = v; edge[tot] = w; nxt[tot] = head[u]; head[u] = tot; } bool spfa() { queue<int> q; vis[0] = 1; q.push(0); memset(dis, -0x3f, sizeof(dis)); dis[0] = 0; while (q.empty() == false) { int u = q.front(); q.pop(); vis[u] = 0; for (int i = 0, vs = nbr[u].size(); i < vs; i++) { int to = nbr[u][i].to, w = nbr[u][i].w; if (dis[to] < dis[u] + w) { dis[to] = dis[u] + w; if (vis[to] == 0) { vis[to] = 1, q.push(to); cnt[to]++; if (cnt[to] > n + m) return false; } } } } return true; } int main() { n = read(); m = read(); for (int i = 1; i <= n; i++) { scanf("%s", s + 1); for (int j = 1; j <= m; j++) { if (s[j] == '>') nbr[j + n].push_back(Node(i, 1)); else if (s[j] == '<') nbr[i].push_back(Node(j + n, 1)); else nbr[i].push_back(Node(j + n, 0)), nbr[j + n].push_back(Node(i, 0)); } } for (int i = 1; i <= n + m; i++) nbr[0].push_back(Node(i, 0)); if (spfa() == 0) printf("No"); else { puts("Yes"); int mini = 1e9; for (int i = 1; i <= n + m; i++) mini = min(mini, dis[i]); for (int i = 1; i <= n; i++) printf("%d ", dis[i] - mini + 1); puts(""); for (int i = n + 1; i <= n + m; i++) printf("%d ", dis[i] - mini + 1); } return 0; }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n × m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≤ n, m ≤ 1000) — the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers — evaluations of dishes from the first set, and on the third line print m integers — evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.
2
10
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.IOException; import java.io.Reader; import java.io.InputStreamReader; import java.util.List; import java.util.StringTokenizer; import java.io.BufferedReader; import java.util.LinkedList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); D solver = new D(); solver.solve(1, in, out); out.close(); } static class D { List<Edge>[] g; boolean[] used; boolean[] processed; int[] val; private boolean dfs(int v) { used[v] = true; int min = 10000; for (Edge e : g[v]) { if (!used[e.to]) { if (!dfs(e.to)) return false; } else if (!processed[e.to]) { return false; } min = Math.min(min, val[e.to]); } val[v] = min - 1; processed[v] = true; return true; } public void solve(int testNumber, FastScanner in, PrintWriter out) { int n = in.ni(), m = in.ni(); char[][] map = in.nm(n, m); DSU dsu = new DSU(n + m); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (map[i][j] == '=') { dsu.union(i, n + j); } } } g = new List[n + m]; for (int i = 0; i < n + m; i++) { g[i] = new LinkedList<>(); } int[] dIn = new int[n + m]; int[] dOut = new int[n + m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (map[i][j] == '<') { int from = dsu.find(i); int to = dsu.find(n + j); g[from].add(new Edge(from, to)); dOut[from]++; dIn[to]++; } else if (map[i][j] == '>') { int from = dsu.find(n + j); int to = dsu.find(i); g[from].add(new Edge(from, to)); dOut[from]++; dIn[to]++; } } } used = new boolean[n + m]; processed = new boolean[n + m]; val = new int[n + m]; while (true) { int start = -1; for (int i = 0; i < n + m; i++) { if (!processed[i] && dIn[i] == 0 && dOut[i] > 0) { start = i; break; } } if (start == -1) { break; } if (!dfs(start)) { out.println("No"); return; } } for (int i = 0; i < n + m; i++) { if (!processed[i] && dOut[i] > 0) { out.println("No"); return; } } int min = 10000; for (int i = 0; i < n + m; i++) { if (val[i] != 0) { min = Math.min(val[i], min); } } if (min == 10000) min = 0; min--; out.println("Yes"); for (int i = 0; i < n; i++) { out.printf("%d ", val[dsu.find(i)] - min); } out.println(); for (int i = 0; i < m; i++) { out.printf("%d ", val[dsu.find(n + i)] - min); } } class Edge { int from; int to; public Edge(int from, int to) { this.from = from; this.to = to; } } } static class FastScanner { private BufferedReader in; private StringTokenizer st; public FastScanner(InputStream stream) { in = new BufferedReader(new InputStreamReader(stream)); } public String ns() { while (st == null || !st.hasMoreTokens()) { try { String rl = in.readLine(); if (rl == null) { return null; } st = new StringTokenizer(rl); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int ni() { return Integer.parseInt(ns()); } public char[] ns(int n) { char[] buf = new char[n]; try { in.read(buf); } catch (IOException e) { throw new RuntimeException(); } return buf; } public char[][] nm(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) { map[i] = ns(m); readLine(); } return map; } public String readLine() { try { return in.readLine(); } catch (IOException e) { throw new RuntimeException(); } } } static class DSU { int[] rank; int[] parent; int n; int sets; public DSU(int n) { rank = new int[n]; parent = new int[n]; this.n = n; sets = n; makeSet(); } void makeSet() { for (int i = 0; i < n; i++) { parent[i] = i; } } public int find(int x) { if (parent[x] != x) { parent[x] = find(parent[x]); } return parent[x]; } public void union(int x, int y) { int xRoot = find(x), yRoot = find(y); if (xRoot == yRoot) return; sets--; if (rank[xRoot] < rank[yRoot]) parent[xRoot] = yRoot; else if (rank[yRoot] < rank[xRoot]) parent[yRoot] = xRoot; else { parent[yRoot] = xRoot; rank[xRoot] = rank[xRoot] + 1; } } } }
JAVA
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n × m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≤ n, m ≤ 1000) — the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers — evaluations of dishes from the first set, and on the third line print m integers — evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> using namespace std; set<long long> graph[2000]; char matrix[1000][1000]; bool crash = false; void dfs(long long v, vector<long long> &used, vector<long long> &dp) { used[v] = 1; long long maxu = 0; for (long long u : graph[v]) { if (!used[u]) { dfs(u, used, dp); maxu = max(maxu, dp[u]); } else if (used[u] == 2) maxu = max(maxu, dp[u]); else crash = true; } dp[v] = maxu + 1; used[v] = 2; } long long find(long long v, vector<long long> &parent) { if (v == parent[v]) return v; parent[v] = find(parent[v], parent); return parent[v]; } void unite(long long a, long long b, vector<long long> &parent) { a = find(a, parent); b = find(b, parent); if (a != b) parent[b] = a; } int main() { long long n, m; cin >> n >> m; vector<long long> parent(n + m); for (long long i = 0; i < n + m; i++) parent[i] = i; for (long long i = 0; i < n; i++) for (long long j = 0; j < m; j++) { cin >> matrix[i][j]; if (matrix[i][j] == '=') unite(i, j + n, parent); } for (long long i = 0; i < n; i++) for (long long j = 0; j < m; j++) { if (matrix[i][j] == '>') graph[find(i, parent)].insert(find(n + j, parent)); if (matrix[i][j] == '<') graph[find(n + j, parent)].insert(find(i, parent)); } vector<long long> used(n + m); vector<long long> dp(n + m); for (long long i = 0; i < n + m; i++) if (!used[i]) dfs(i, used, dp); if (crash) cout << "No"; else { cout << "Yes\n"; for (long long i = 0; i < n; i++) cout << dp[find(i, parent)] << ' '; cout << '\n'; for (long long i = n; i < n + m; i++) cout << dp[find(i, parent)] << ' '; } 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 cc, to[1000010], net[1000010], fr[3000], ind[3000], fa[3000]; int q[3000], ans[3000], n, m; char ch[1010][1010]; void addedge(int u, int v) { cc++; to[cc] = v; net[cc] = fr[u]; fr[u] = cc; ind[v]++; } int fafa(int x) { if (fa[x] == x) return x; return fa[x] = fafa(fa[x]); } void hebing(int x, int y) { x = fafa(x); y = fafa(y); fa[x] = y; } bool topsort() { int h = 1, t = 0; for (int i = 1; i <= n + m; i++) if (!ind[i]) q[++t] = i, ans[i] = 1; while (h <= t) { for (int i = fr[q[h]]; i; i = net[i]) { ind[to[i]]--; if (ind[to[i]] == 0) { q[++t] = to[i]; ans[to[i]] = ans[q[h]] + 1; } } h++; } for (int i = 1; i <= n + m; i++) if (ind[fafa(i)]) return false; return true; } int main() { cin >> n >> m; for (int i = 1; i <= n + m; i++) { fa[i] = i; } for (int i = 1; i <= n; i++) { cin >> ch[i]; for (int j = 1; j <= m; j++) { if (ch[i][j - 1] == '=') hebing(i, j + n); } } for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { if (ch[i][j - 1] == '<') addedge(fafa(i), fafa(j + n)); if (ch[i][j - 1] == '>') addedge(fafa(j + n), fafa(i)); } if (topsort()) { cout << "Yes\n"; for (int i = 1; i <= n; i++) { cout << ans[fafa(i)] << " "; } cout << endl; for (int i = 1 + n; i <= m + n; i++) { cout << ans[fafa(i)] << " "; } } else cout << "No\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 os from io import BytesIO #input = BytesIO(os.read(0, os.fstat(0).st_size)).readline from itertools import product class CYCLE(Exception): ... debug_print = lambda *args: None def solve(n, m, gs): def union(u, v): p, q = find(u), find(v) if p == q: return if rank[p] < rank[q]: p, q = q, p if rank[p] == rank[q]: rank[p] += 1 parent[q] = p def find(u): if parent[u] == u: return u else: p = find(parent[u]) parent[u] = p return p rank = [0] * (n + m) parent = list(range(n + m)) for i, j in product(range(n), range(m)): if gs[i][j] == "=": union(i, n + j) vertices = set(parent) v_sz = len(vertices) g = [set() for _ in range(n + m)] for i, j in product(range(n), range(m)): c = gs[i][j] i, j = parent[i], parent[n + j] if c == "<": g[i].add(j) elif c == ">": g[j].add(i) debug_print(vertices, g) NIL, VISITED, FINAL = 0, 1, 2 state = [NIL] * (n + m) toposort_stack = [] def visit(v): debug_print(v) if state[v] == VISITED: raise CYCLE state[v] = VISITED for u in g[v]: if state[u] != FINAL: visit(u) state[v] = FINAL toposort_stack.append(v) try: for v in vertices: if state[v] == FINAL: continue visit(v) except CYCLE: print('No') return debug_print(toposort_stack) layer = [1] * (n + m) while toposort_stack: v = toposort_stack.pop() for u in g[v]: layer[u] = max(layer[u], layer[v]+1) print('Yes') out = [] for i in range(n): out.append(str(layer[parent[i]])) print(' '.join(out)) out = [] for j in range(m): out.append(str(layer[parent[n + j]])) print(' '.join(out)) def solve_from_stdin(): n, m = map(int, input().split()) gs = [] for _ in range(n): gs.append(input()) solve(n, m, gs) solve_from_stdin()
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; 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; 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) globok = false; } } color[v] = 2; } void usedclear() { for (int i = 0; i < used.size(); i++) used[i] = false; } void dfs2(int v) { for (int i = 0; i < more[v].size(); i++) { int to = more[v][i]; if (w[to] < w[v] + 1) { w[to] = w[v] + 1; dfs2(to); } } } 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 < lessy.size(); i++) { if (color[i] == 0) dfs(i); } if (!globok) { cout << "No"; return 0; } cout << "Yes" << endl; vector<int> starts; for (int i = 0; i < n + m; i++) { if (more[i].size() > 0 && lessy[i].size() == 0) { w[i] = 0; dfs2(i); } } long long mini = LONG_LONG_MAX; for (int i = 0; i < w.size(); i++) { int ico = find_set(i); mini = min(mini, w[ico]); } long long add = -mini; bool enter = false; for (int i = 0; i < w.size(); i++) { int ico = find_set(i); if (!enter && i >= n) { cout << endl; enter = true; } cout << w[ico] + add + 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; void fun() {} int md = 1e9 + 7; int __gcd(int a, int b) { if (b == 0) return a; return __gcd(b, a % b); } int poww(int a, int b, int md) { if (b < 0) return 0; if (a == 0) return 0; int res = 1; while (b) { if (b & 1) { res = (1ll * res * a) % md; } a = (1ll * a * a) % md; b >>= 1; } return res; } int poww(int a, int b) { if (b < 0) return 0; if (a == 0) return 0; int res = 1; while (b) { if (b & 1) { res = (1ll * res * a); } a = (1ll * a * a); b >>= 1; } return res; } void ainp(int arr[], int n) { for (int i = 1; i <= n; i++) cin >> arr[i]; } void disp(int arr[], int n) { for (int i = 1; i <= n; i++) cout << arr[i] << " "; cout << "\n"; } void dispv(vector<int> &v) { for (int i = 0; i < v.size(); i++) cout << v[i] << " "; cout << "\n"; } int divide(int a, int b, int md) { int rr = a * (poww(b, md - 2, md)); rr %= md; return rr; } const int size = 2004; char arr[size][size]; int ans[size]; vector<int> g[size]; int vis[size]; int parent[size]; int n, m; void pre() { for (int i = 1; i < size; i++) parent[i] = i; } int findp(int node) { if (parent[node] == node) return node; return parent[node] = findp(parent[node]); } void unite(int par, int child) { par = findp(par), child = findp(child); if (par == child) return; parent[child] = par; } bool check(int par) { if (vis[par] == 2) return 0; if (vis[par] == 1) return 1; vis[par] = 1; for (int child : g[par]) if (check(child)) return 1; vis[par] = 2; return 0; } bool checkloop() { for (int i = 1; i <= n + m; i++) if (!vis[findp(i)] && check(findp(i))) return 1; return 0; } void dfs(int par) { if (vis[par]) return; ans[par] = 1; vis[par] = 1; for (int child : g[par]) { dfs(child); ans[par] = max(ans[child] + 1, ans[par]); } } signed main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); fun(); pre(); cin >> n >> m; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { cin >> arr[i][j]; if (arr[i][j] == '=') unite(i, j + n); } } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (arr[i][j] == '>') g[findp(i)].push_back(findp(j + n)); else if (arr[i][j] == '<') g[findp(j + n)].push_back(findp(i)); } } if (checkloop()) return cout << "NO\n", 0; memset(vis, 0, sizeof(vis)); for (int i = 1; i <= n + m; i++) dfs(findp(i)); cout << "YES\n"; for (int i = 1; i <= n + m; i++) { cout << ans[findp(i)] << " "; if (i == n) cout << "\n"; } cout << "\n"; return 0; }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n × m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≤ n, m ≤ 1000) — the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers — evaluations of dishes from the first set, and on the third line print m integers — evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> using namespace std; const int MAX_N = 1e3 + 5; const int MAX_M = 4e5 + 5; const int INF = 0x3f3f3f3f; struct Edge { int v, next; } es[MAX_N * MAX_N]; int n, m, fa[MAX_N << 1], cnt1, tot, head[MAX_N << 1], ind[MAX_N << 1], eval[MAX_N << 1], cnt2; char g[MAX_N][MAX_N]; queue<int> Q; inline void addEdge(int u, int v) { es[++tot].v = v, es[tot].next = head[u], head[u] = tot; } int findFa(int x) { return fa[x] == x ? x : fa[x] = findFa(fa[x]); } void topoSort() { while (Q.size()) { int u = Q.front(); Q.pop(); for (int i = head[u]; i; i = es[i].next) { int v = es[i].v; if (--ind[v] == 0) Q.push(v), cnt2++; eval[v] = max(eval[v], eval[u] + 1); } } } void solve() { scanf("%d%d", &n, &m); for (int i = 1; i <= n + m; i++) fa[i] = i; for (int i = 1; i <= n; i++) { scanf("%s", g[i] + 1); for (int j = 1; j <= m; j++) { if (g[i][j] == '=') { fa[findFa(i)] = findFa(j + n); } } } for (int i = 1; i <= n + m; i++) if (findFa(i) == i) cnt1++; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (g[i][j] == '>') { addEdge(fa[j + n], fa[i]); ind[fa[i]]++; } else if (g[i][j] == '<') { addEdge(fa[i], fa[j + n]); ind[fa[j + n]]++; } } } for (int i = 1; i <= n + m; i++) { if (fa[i] == i && !ind[i]) { Q.push(i); cnt2++; eval[i] = 1; } } topoSort(); if (cnt1 == cnt2) { puts("Yes"); for (int i = 1; i <= n; i++) { if (i != 1) printf(" "); printf("%d", eval[fa[i]]); } puts(""); for (int i = 1 + n; i <= m + n; i++) { if (i != 1 + n) printf(" "); printf("%d", eval[fa[i]]); } puts(""); } else { puts("No"); } } 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
import java.util.*; import java.io.*; public class Main { static FastScanner sc = new FastScanner(System.in); static PrintWriter pw = new PrintWriter(System.out); static StringBuilder sb = new StringBuilder(); static ArrayList<ArrayList<Integer>> G; static int[] indegree; static int V,E; static int[] ans; static boolean flg = true; static DSU dsu; public static void main(String[] args) throws Exception { int n = sc.nextInt(); int m = sc.nextInt(); dsu = new DSU(n+m); char[][] map = new char[n][m]; for(int i = 0; i < n; i++) map[i] = sc.next().toCharArray(); V = n+m; E = n*m; G = new ArrayList<>(); for(int i = 0; i < V; i++){ G.add(new ArrayList<>()); } indegree = new int[V]; for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ if(map[i][j] == '='){ dsu.merge(i,n+j); } } } for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ if(map[i][j] == '<'){ int u = dsu.leader(i); int v = dsu.leader(n+j); G.get(u).add(v); indegree[v]++; }else if(map[i][j] == '>'){ int u = dsu.leader(n+j); int v = dsu.leader(i); G.get(u).add(v); indegree[v]++; } } } ans = new int[n+m]; Arrays.fill(ans,Integer.MAX_VALUE); ArrayList<Integer> sortedV = topologicalSort(); if(sortedV.size() != n+m){ pw.println("No"); }else{ pw.println("Yes"); for(int i = 0; i < n; i++){ sb.append(ans[dsu.leader(i)]).append(" "); } pw.println(sb.toString().trim()); sb.setLength(0); for(int i = n; i < n+m; i++){ sb.append(ans[dsu.leader(i)]).append(" "); } pw.println(sb.toString().trim()); } pw.flush(); } public static ArrayList<Integer> topologicalSort(){ ArrayList<Integer> sorted_vertices = new ArrayList<>(); Deque<Item> q = new ArrayDeque<>(); for(int i = 0; i < V; i++){ if(indegree[i] == 0){ q.push(new Item(i,1)); } } while (q.size() > 0) { Item item = q.pop(); int v = item.i; int w = item.w; ans[v] = Math.min(ans[v],w); for(int u : G.get(v)){ indegree[u]--; if(indegree[u] == 0){ q.push(new Item(u,w+1)); } } sorted_vertices.add(v); } return sorted_vertices; } static class Item{ int i,w; public Item(int i, int w){ this.i = i; this.w = w; } } static class GeekInteger { public static void save_sort(int[] array) { shuffle(array); Arrays.sort(array); } public static int[] shuffle(int[] array) { int n = array.length; Random random = new Random(); for (int i = 0, j; i < n; i++) { j = i + random.nextInt(n - i); int randomElement = array[j]; array[j] = array[i]; array[i] = randomElement; } return array; } public static void save_sort(long[] array) { shuffle(array); Arrays.sort(array); } public static long[] shuffle(long[] array) { int n = array.length; Random random = new Random(); for (int i = 0, j; i < n; i++) { j = i + random.nextInt(n - i); long randomElement = array[j]; array[j] = array[i]; array[i] = randomElement; } return array; } } static class DSU { private int n; private int[] parentOrSize; private java.util.ArrayList<java.util.ArrayList<Integer>> map; public DSU(int n) { this.n = n; this.map = new java.util.ArrayList<java.util.ArrayList<Integer>>(); for (int i = 0; i < n; i++) { this.map.add(new java.util.ArrayList<Integer>()); this.map.get(i).add(i); } this.parentOrSize = new int[n]; java.util.Arrays.fill(parentOrSize, -1); } int merge(int a, int b) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("a=" + a); if (!(0 <= b && b < n)) throw new IndexOutOfBoundsException("b=" + b); int x = leader(a); int y = leader(b); if (x == y) return x; if (-parentOrSize[x] < -parentOrSize[y]) { int tmp = x; x = y; y = tmp; } parentOrSize[x] += parentOrSize[y]; parentOrSize[y] = x; this.map.get(x).addAll(this.map.get(y)); return x; } boolean same(int a, int b) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("a=" + a); if (!(0 <= b && b < n)) throw new IndexOutOfBoundsException("b=" + b); return leader(a) == leader(b); } int leader(int a) { if (parentOrSize[a] < 0) { return a; } else { parentOrSize[a] = leader(parentOrSize[a]); return parentOrSize[a]; } } int size(int a) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("" + a); return -parentOrSize[leader(a)]; } java.util.ArrayList<java.util.ArrayList<Integer>> groups() { int[] leaderBuf = new int[n]; int[] groupSize = new int[n]; for (int i = 0; i < n; i++) { leaderBuf[i] = leader(i); groupSize[leaderBuf[i]]++; } java.util.ArrayList<java.util.ArrayList<Integer>> result = new java.util.ArrayList<>(n); for (int i = 0; i < n; i++) { result.add(new java.util.ArrayList<>(groupSize[i])); } for (int i = 0; i < n; i++) { result.get(leaderBuf[i]).add(i); } result.removeIf(java.util.ArrayList::isEmpty); return result; } void getAdd(int n) { for(int t : map.get(n)){ indegree[t]++; } } } } class FastScanner { private BufferedReader reader = null; private StringTokenizer tokenizer = null; public FastScanner(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); tokenizer = null; } public String next() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public String nextLine() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken("\n"); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String[] nextArray(int n) { String[] a = new String[n]; for (int i = 0; i < n; i++) a[i] = next(); return a; } 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; } }
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 std::max; int head[2001], nxt[2000001], b[2000001], k, f[2001], comp[1001][1001], n, m, nodes, d[2001], q[2001], t, h, ans[2001], orig; int get() { char ch = getchar(); while (ch != '<' && ch != '=' && ch != '>') ch = getchar(); return (ch == '<') ? (-1) : ((ch == '=') ? 0 : 1); } int find(int x) { if (!f[x]) return x; return f[x] = find(f[x]); } void unionn(int x, int y) { x = find(x); y = find(y); if (x == y) return; f[x] = y; } void push(int s, int t) { nxt[++k] = head[s]; head[s] = k; b[k] = t; ++d[t]; } bool vis[2001]; int main() { scanf("%d%d", &n, &m); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { comp[i][j] = get(); if (comp[i][j] == 0) unionn(i, j + n); } for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) if (comp[i][j]) { if (find(i) == find(j + n)) { puts("No"); return 0; } if (comp[i][j] == -1) push(find(i), find(j + n)); else push(find(j + n), find(i)); } for (int i = 1; i <= n + m; i++) if (!f[i] && !d[i]) q[++t] = i, ans[i] = 1; while (h < t) { ++h; vis[q[h]] = 1; for (int i = head[q[h]]; i; i = nxt[i]) { if (vis[b[i]]) { puts("No"); return 0; } ans[b[i]] = max(ans[b[i]], ans[q[h]] + 1); if (!(--d[b[i]])) q[++t] = b[i]; } } for (int i = 1; i <= n + m; i++) { if (!f[i] && !vis[i]) { puts("No"); return 0; } } puts("Yes"); for (int i = 1; i <= n; i++) printf("%d ", ans[find(i)]); putchar('\n'); for (int i = 1; i <= m; i++) printf("%d ", ans[find(i + n)]); putchar('\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.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.lang.invoke.MethodHandles; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.PriorityQueue; import java.util.Random; import java.util.TreeSet; public final class CF_541_D2_De { static boolean verb=true; static void log(Object X){if (verb) System.err.println(X);} static void log(Object[] X){if (verb) {for (Object U:X) System.err.print(U+" ");System.err.println("");}} static void log(int[] X){if (verb) {for (int U:X) System.err.print(U+" ");System.err.println("");}} static void log(int[] X,int L){if (verb) {for (int i=0;i<L;i++) System.err.print(X[i]+" ");System.err.println("");}} static void log(long[] X){if (verb) {for (long U:X) System.err.print(U+" ");System.err.println("");}} static void logWln(Object X){if (verb) System.err.print(X);} static void info(Object o){ System.out.println(o);} static void output(Object o){outputWln(""+o+"\n"); } static void outputWln(Object o){try {out.write(""+ o);} catch (Exception e) {}} static long mod=1000000007; // Global vars static BufferedWriter out; static InputReader reader; static void test() { log("testing"); log("done"); } static int[] anc,rank,max,list; static void initSet(int x){ anc[x]=x; rank[x]=0; max[x]=x; } static int union(int x,int y){ //log("unioning x:"+x+" y:"+y); int xr=find(x); int yr=find(y); if (xr!=yr){ if (rank[xr]<rank[yr]){ anc[xr]=yr; max[yr]=Math.max(max[xr],max[yr]); return yr; // max[xr]=max[yr]; } else if (rank[xr]>rank[yr]) { anc[yr]=xr; max[xr]=Math.max(max[xr],max[yr]); // max[xr]=max[yr]; return xr; } else { anc[yr]=xr; rank[xr]++; max[xr]=Math.max(max[xr],max[yr]); //max[xr]=max[yr]; return xr; } } return -1; } static int find(int x){ if (anc[x]!=x){ anc[x]=find(anc[x]); } return anc[x]; } static void process() throws Exception { out = new BufferedWriter(new OutputStreamWriter(System.out)); reader = new InputReader(System.in); int n=reader.readInt(); int m=reader.readInt(); int nm=n+m; HashSet<Integer>[] upper=new HashSet[nm]; HashSet<Integer>[] lower=new HashSet[nm]; for (int i=0;i<nm;i++) { upper[i]=new HashSet<Integer>(); lower[i]=new HashSet<Integer>(); } anc=new int[nm]; rank=new int[nm]; max=new int[nm]; for (int i=0;i<nm;i++) initSet(i); String[] s=new String[n]; // first pass, merge for (int i=0;i<n;i++) { s[i]=reader.readString(); int u=i; for (int j=0;j<m;j++) { int v=j+n; char c=s[i].charAt(j); if (c=='=') { union(u,v); } } } for (int i=0;i<n;i++) { int u=find(i); for (int j=0;j<m;j++) { int v=find(j+n); char c=s[i].charAt(j); if (c=='>') { upper[v].add(u); lower[u].add(v); } if (c=='<') { upper[u].add(v); lower[v].add(u); } } } ArrayList<Integer>[] friends=new ArrayList[nm]; for (int u=0;u<nm;u++) { if (u==find(u)) { friends[u]=new ArrayList<Integer>(); friends[u].addAll(lower[u]); } } int[] it=new int[nm]; int tot=0; int processed=0; int[] stack=new int[nm]; int st=0; // now dfs starting from the lowest int time=0; int[] onstack=new int[nm]; boolean[] visited=new boolean[nm]; boolean error=false; int[] score=new int[nm]; Arrays.fill(score, -1); loop:for (int u=0;u<nm;u++) { if (u==anc[u]) { tot++; if (!visited[u]) { if (upper[u].size()==0) { //log("processing u:"+u); time++; st=0; stack[st++]=u; onstack[u]=time; it[u]=0; score[u]=1; visited[u]=true; while (st>0) { int v=stack[st-1]; if (it[v]==friends[v].size()) { onstack[v]=-1; it[v]=0; score[v]=1; for (int w:friends[v]) { if (score[v]<=score[w]) score[v]=score[w]+1; } st--; } else { int w=friends[v].get(it[v]++); if (onstack[w]==time) { error=true; //log("found loop"); break loop; } else { if (!visited[w]) { it[w]=0; onstack[w]=time; stack[st++]=w; visited[w]=true; } } } } } } } } if (!error) { // check for error for (int i=0;i<nm;i++) { int u=find(i); if (score[u]==-1) { //log("non allocated u:"+u); error=true; break; } } } if (error) { output("No"); } else { output("Yes"); for (int i=0;i<n;i++) { int u=find(i); output(score[u]); } output(""); for (int i=n;i<nm;i++) { int u=find(i); output(score[u]); } output(""); } try { out.close(); } catch (Exception e) { } } public static void main(String[] args) throws Exception { process(); } static final class InputReader { private final InputStream stream; private final byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } private int read() throws IOException { if (curChar >= numChars) { curChar = 0; numChars = stream.read(buf); if (numChars <= 0) { return -1; } } return buf[curChar++]; } public final String readString() throws IOException { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.append((char) c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public final int readInt() throws IOException { int c = read(); boolean neg = false; while (isSpaceChar(c)) { c = read(); } char d = (char) c; // log("d:"+d); if (d == '-') { neg = true; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); // log("res:"+res); if (neg) return -res; return res; } public final long readLong() throws IOException { int c = read(); boolean neg = false; while (isSpaceChar(c)) { c = read(); } char d = (char) c; // log("d:"+d); if (d == '-') { neg = true; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); // log("res:"+res); if (neg) return -res; return res; } private boolean isSpaceChar(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> using namespace std; const int INF = 1e9 + 7; const int MOD = 1e9 + 7; const int MAXN = 1e6 + 3; long long gcd(long long a, long long b) { if (b == 0) return a; else return gcd(b, a % b); } long long power(long long x, long long y) { long long res = 1; while (y > 0) { if (y & 1) res = res * x; y = y >> 1; x = x * x; } return res; } long long n, m; const int maxn = 1005; vector<long long> parent(2 * maxn); vector<long long> sz(2 * maxn); string s[maxn]; vector<long long> adj[2 * maxn]; vector<long long> clr(2 * maxn); vector<long long> depth(2 * maxn, 0); void makeset(long long v) { parent[v] = v; sz[v] = 1; return; } long long getset(long long v) { while (parent[v] != v) v = parent[v]; return v; } void uset(long long x, long long y) { x = getset(x); y = getset(y); if (x != y) { if (sz[x] < sz[y]) { x = x + y; y = x - y; x = x - y; }; sz[x] += sz[y]; parent[y] = x; } return; } bool dfs(long long u) { if (clr[u] == 2) return false; clr[u] = 1; long long mx = 0; for (auto v : adj[u]) { if (clr[v] == 0) { if (dfs(v)) return true; mx = max(depth[v], mx); } else if (clr[v] == 1) { return true; } else if (clr[v] == 2) { mx = max(depth[v], mx); continue; } } clr[u] = 2; depth[u] = max(depth[u], mx + 1); return false; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cin >> n >> m; for (long long i = 0; i < (n + m); ++i) { makeset(i); } for (long long i = 0; i < (n); ++i) cin >> s[i]; for (long long i = 0; i < (n); ++i) { for (long long j = 0; j < (m); ++j) { if (s[i][j] == '=') uset(getset(i), getset(n + j)); } } for (long long i = 0; i < (n); ++i) { for (long long j = 0; j < (m); ++j) { if (s[i][j] == '>') { adj[getset(i)].push_back(getset(n + j)); } else if (s[i][j] == '<') { adj[getset(n + j)].push_back(getset(i)); } } } for (long long i = 0; i < (n + m); ++i) { if (dfs(getset(i))) { cout << "No\n"; return 0; } } cout << "Yes\n"; for (long long i = 0; i < (n); ++i) { cout << depth[getset(i)] << " "; } cout << '\n'; for (long long i = 0; i < (m); ++i) { cout << depth[getset(i + n)] << " "; } cout << '\n'; return 0; }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n × m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≤ n, m ≤ 1000) — the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers — evaluations of dishes from the first set, and on the third line print m integers — evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> using namespace std; int main() { int n, m; vector<string> data; cin >> n >> m; for (int i = 0; i < n; ++i) { string row; cin >> row; data.push_back(row); } vector<vector<int> > set; set.resize(2); set[0].resize(n, 0); set[1].resize(m, 0); vector<vector<int> > setJcan; setJcan.resize(n); for (auto& v : setJcan) v.resize(m); for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (data[i][j] == '>') setJcan[i][j] = -1; if (data[i][j] == '<') setJcan[i][j] = 1; if (data[i][j] == '=') setJcan[i][j] = 0; } int min = 0; for (int j = 0; j < m; ++j) if (min > setJcan[i][j]) min = setJcan[i][j]; set[0][i] = set[0][i] + (1 - min); for (int j = 0; j < m; ++j) { setJcan[i][j] = setJcan[i][j] + (1 - min); } } map<int, bool> done; vector<int> minJ(m); for (int j = 0; j < m; ++j) { minJ[j] = -1; for (int i = 0; i < n; ++i) { if (minJ[j] == -1 || minJ[j] > setJcan[i][j]) minJ[j] = setJcan[i][j]; } } int consecutive_update_count = 0; while (done.size() < (unsigned int)m && consecutive_update_count <= 2 * m) { int min = -1; int j_min; for (int j = 0; j < m; ++j) { if (minJ[j] == -1) continue; if (min == -1 || min > minJ[j]) { min = minJ[j]; j_min = j; } } int max = 0; for (int i = 0; i < n; ++i) { if (max < setJcan[i][j_min]) { max = setJcan[i][j_min]; } } minJ[j_min] = max; bool updated = false; for (int i = 0; i < n; ++i) { int diff = max - setJcan[i][j_min]; if (diff == 0) continue; if (set[0][i] >= setJcan[i][j_min] && set[0][i] <= max) { int newSetI; if (set[0][i] == setJcan[i][j_min]) newSetI = max; else newSetI = max + 1; for (int j = 0; j < m; ++j) { if (j == j_min) continue; if (setJcan[i][j] >= set[0][i] && setJcan[i][j] <= newSetI) { if (setJcan[i][j] == set[0][i]) setJcan[i][j] = newSetI; else setJcan[i][j] = newSetI + 1; } } set[0][i] = newSetI; } setJcan[i][j_min] += diff; updated = true; } if (updated) { consecutive_update_count++; } else { done[j_min] = true; minJ[j_min] = -1; consecutive_update_count = 0; } } for (int j = 0; j < m; ++j) { set[1][j] = setJcan[0][j]; } bool yes = true; for (int i = 0; i < n && yes; ++i) { for (int j = 0; j < m && yes; ++j) { if (data[i][j] == '>' && set[0][i] <= set[1][j]) yes = false; if (data[i][j] == '=' && set[0][i] != set[1][j]) yes = false; if (data[i][j] == '<' && set[0][i] >= set[1][j]) yes = false; } } if (yes) { cout << "Yes" << endl; int min = set[0][0]; for (auto num : set[0]) if (min > num) min = num; for (auto num : set[1]) if (min > num) min = num; int offset = 1 - min; for (int i = 0; i < n; ++i) cout << (set[0][i] + offset) << ' '; cout << endl; for (int j = 0; j < m; ++j) cout << (set[1][j] + offset) << ' '; 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
import java.io.*; import java.util.*; public class CFD { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; private static long MOD = 1000L * 1000L * 1000L + 7; private static final int[] dx = {0, -1, 0, 1}; private static final int[] dy = {1, 0, -1, 0}; private static final String yes = "Yes"; private static final String no = "No"; int n; int m; char[][] mat; List<List<Integer>> graph = new ArrayList<>(); int[] res; // union find int[] id; int[] sz; int parent(int v) { while (v != id[v]) { v = id[v]; } return v; } boolean merge(int u, int v) { int p1 = parent(u); int p2 = parent(v); if (p1 == p2) { return false; } if (sz[p1] < sz[p2]) { sz[p2] += sz[p1]; id[p1] = p2; } else { sz[p1] += sz[p2]; id[p2] = p1; } return true; } void solve() throws IOException { n = nextInt(); m = nextInt(); mat = new char[n][m]; for (int i = 0; i < n; i++) { mat[i] = nextString().toCharArray(); } for (int i = 0; i < n + m; i++) { graph.add(new ArrayList<>()); } sz = new int[n + m]; id = new int[n + m]; for (int i = 0; i < n + m; i++) { sz[i] = 1; id[i] = i; } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (mat[i][j] == '=') { merge(i, n + j); } } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { char cur = mat[i][j]; // i -> (n + j) int p1 = parent(i); int p2 = parent(n + j); if (cur == '>') { graph.get(p1).add(p2); } else if (cur == '<') { graph.get(p2).add(p1); } } } int size = n + m; int[] degree = new int[size]; for (int i = 0; i < size; i++) { for (int v : graph.get(i)) { degree[v]++; } } Deque<Integer> deck = new LinkedList<>(); for (int i = 0; i < size; i++) { if (degree[i] == 0) { deck.add(i); } } List<Integer> topo = new ArrayList<>(); while (!deck.isEmpty()) { int cur = deck.removeFirst(); topo.add(cur); for (int nxt : graph.get(cur)) { degree[nxt]--; if (degree[nxt] == 0) { deck.addLast(nxt); } } } if (topo.size() != size) { outln(no); return; } res = new int[size]; Arrays.fill(res, -1); for (int i = topo.size() - 1; i >= 0; i--) { int cur = topo.get(i); int min = 0; for (int v : graph.get(cur)) { int p = parent(v); if (res[p] != -1) { min = Math.max(min, res[p] + 1); } } res[cur] = min; } outln(yes); for (int i = 0; i < n; i++) { out((1 + res[parent(i)]) + " "); } outln(""); for (int i = n; i < size; i++) { out((1 + res[parent(i)]) + " "); } } void shuffle(int[] a) { int n = a.length; for(int i = 0; i < n; i++) { int r = i + (int) (Math.random() * (n - i)); int tmp = a[i]; a[i] = a[r]; a[r] = tmp; } } long gcd(long a, long b) { while(a != 0 && b != 0) { long c = b; b = a % b; a = c; } return a + b; } private void outln(Object o) { out.println(o); } private void out(Object o) { out.print(o); } private void formatPrint(double val) { outln(String.format("%.9f%n", val)); } public CFD() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } public static void main(String[] args) throws IOException { new CFD(); } public long[] nextLongArr(int n) throws IOException{ long[] res = new long[n]; for(int i = 0; i < n; i++) res[i] = nextLong(); return res; } public int[] nextIntArr(int n) throws IOException { int[] res = new int[n]; for(int i = 0; i < n; i++) res[i] = nextInt(); return res; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return null; } } return st.nextToken(); } public String nextString() { try { return br.readLine(); } catch (IOException e) { eof = true; return null; } } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(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
import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.Scanner; import java.util.Set; public class Main { private static int findSet(int x) { if (x == set[x]) { return x; } else { return set[x] = findSet(set[x]); } } private static String[] input = new String[1010]; private static int[] set = new int[2010]; private static Set<Integer>[] graph = new HashSet[2010]; private static int[] inDegree = new int[2010]; private static int[] values = new int[2010]; static { for (int i = 0;i < 2010;i ++) { graph[i] = new HashSet<>(); } } public static void main(String[] args) { Scanner scan = new Scanner(System.in); int i , j , n , m; n = scan.nextInt(); m = scan.nextInt(); for (i = 0;i < n;i ++) { input[i] = scan.next(); } for (i = 0;i < n + m;i ++) { set[i] = i; } Arrays.fill(values , - 1); for (i = 0;i < n;i ++) { for (j = 0;j < m;j ++) { int index1 = i , index2 = n + j; int f1 = findSet(index1) , f2 = findSet(index2); if (input[i].charAt(j) == '=') { if (f1 != f2) { set[f1] = f2; } } else { if (f1 == f2) { System.out.println("No"); return; } } } } for (i = 0;i < n;i ++) { for (j = 0;j < m;j ++) { if (input[i].charAt(j) != '=') { int index1 = i , index2 = n + j; int f1 = findSet(index1) , f2 = findSet(index2); if (input[i].charAt(j) == '<') { if (graph[f1].add(f2)) { inDegree[f2] ++; } } else { if (graph[f2].add(f1)) { inDegree[f1] ++; } } } } } // topo sort Set<Integer> fSet = new HashSet<>(); for (i = 0;i < n + m;i ++) { fSet.add(findSet(i)); } Queue<Integer> queue = new LinkedList<>(); for (int value : fSet) { if (inDegree[value] == 0) { queue.add(value); } } int next = 1; while (!queue.isEmpty()) { List<Integer> nextList = new ArrayList<>(); while (!queue.isEmpty()) { int current = queue.poll(); values[current] = next; for (int child : graph[current]) { inDegree[child] --; if (inDegree[child] == 0) { nextList.add(child); } } } next ++; queue.addAll(nextList); } for (i = 0;i < n + m;i ++) { int f = findSet(i); if (values[f] < 0) { System.out.println("No"); return; } } System.out.println("Yes"); StringBuilder builder = new StringBuilder(); for (i = 0;i < n;i ++) { if (i > 0) { builder.append(" "); } int f = findSet(i); builder.append(values[f]); } System.out.println(builder.toString()); builder.setLength(0); for (i = n;i < n + m;i ++) { if (i > n) { builder.append(" "); } int f = findSet(i); builder.append(values[f]); } System.out.println(builder.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
import java.io.*; import java.util.*; import java.util.stream.IntStream; public class Main { public static void main(String[] args) { try (PrintWriter out = new PrintWriter(System.out)) { Solution solution = new Solution(); solution.in = new InputReader(getInput()); solution.out = out; solution.solve(); } } static InputStream getInput() { String inputFile = getInputFileName(); if (inputFile == null) { return System.in; } try { return new FileInputStream(Main.class.getClassLoader().getResource(inputFile).getFile()); } catch (FileNotFoundException e) { throw new RuntimeException(e); } } static String getInputFileName() { try { return System.getProperty("compet.input"); } catch (Exception ex) { return null; } } } class Solution { InputReader in; PrintWriter out; int n; int m; class Node { List<Integer> ls = new ArrayList<>(); int gr = 0; List<Integer> eq = new ArrayList<>(); } void solve() { n = in.nextInt(); m = in.nextInt(); String[] a = new String[n]; for (int i = 0; i < n; i++) { a[i] = in.next(); } int sz = n+m; Node[] nodes = IntStream.range(0, sz).mapToObj(i -> new Node()).toArray(Node[]::new); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int v = i; int u = n + j; switch (a[i].charAt(j)) { case '>': nodes[v].gr++; nodes[u].ls.add(v); break; case '<': nodes[u].gr++; nodes[v].ls.add(u); break; case '=': nodes[u].eq.add(v); nodes[v].eq.add(u); break; } } } boolean[] was = new boolean[sz]; int wasCnt = 0; boolean bad = false; int num = 1; int[] ans = new int[sz]; while (wasCnt < sz && !bad) { boolean[] curMask = new boolean[sz]; for (int v = 0; v < sz; v++) { if (!was[v] && nodes[v].gr == 0) { curMask[v] = true; } } Queue<Integer> queue = new ArrayDeque<>(sz); boolean[] visited = new boolean[sz]; for (int v = 0; v < sz; v++) { if (!curMask[v]) { queue.add(v); visited[v] = true; } } while (!queue.isEmpty()) { int v = queue.poll(); curMask[v] = false; for (int u: nodes[v].eq) { if (!visited[u]) { visited[u] = true; queue.add(u); } } } List<Integer> cur = new ArrayList<>(sz); for (int v = 0; v < sz; v++) { if (curMask[v]) { cur.add(v); } } if (cur.size() == 0) { bad = true; break; } for (int v: cur) { wasCnt++; was[v] = true; ans[v] = num; for (int u: nodes[v].ls) { nodes[u].gr--; } } num++; } out.println(bad ? "No" : "Yes"); if (!bad) { for (int i = 0; i < sz; i++) { if (i == n) { out.println(); } out.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
#include <bits/stdc++.h> using namespace std; vector<long long int> v[2005]; long long int vis[2005] = {0}; long long int in_stack[2005] = {0}; long long int value[2005]; bool dfs(long long int node) { long long int i; vis[node] = 1; if (v[node].size() == 0) { value[node] = 1; return true; } in_stack[node] = 1; long long int si = v[node].size(); long long int ma = INT_MIN; for (i = 0; i < si; i++) { if (in_stack[v[node][i]] == 1) { return false; } if (vis[v[node][i]] == 0) { if (!dfs(v[node][i])) return false; } ma = max(ma, value[v[node][i]] + 1); } value[node] = ma; in_stack[node] = 0; return true; } int main() { long long int n, m, i, j; cin >> n >> m; char c[n + 1][m + 1]; for (i = 1; i <= n; i++) for (j = 1; j <= m; j++) cin >> c[i][j]; long long int par[2005]; for (i = 1; i <= 2000; i++) par[i] = i; for (i = 1; i <= n; i++) { for (j = 1; j <= m; j++) { if (c[i][j] == '=') { long long int idx1 = i; long long int idx2 = n + j; while (idx1 != par[idx1]) { par[idx1] = par[par[idx1]]; idx1 = par[idx1]; } while (idx2 != par[idx2]) { par[idx2] = par[par[idx2]]; idx2 = par[idx2]; } par[idx2] = par[idx1]; } } } for (i = 1; i <= n; i++) { for (j = 1; j <= m; j++) { if (c[i][j] == '>') { long long int idx1 = i; long long int idx2 = n + j; while (idx1 != par[idx1]) { par[idx1] = par[par[idx1]]; idx1 = par[idx1]; } while (idx2 != par[idx2]) { par[idx2] = par[par[idx2]]; idx2 = par[idx2]; } v[idx1].push_back(idx2); } if (c[i][j] == '<') { long long int idx1 = i; long long int idx2 = n + j; while (idx1 != par[idx1]) { par[idx1] = par[par[idx1]]; idx1 = par[idx1]; } while (idx2 != par[idx2]) { par[idx2] = par[par[idx2]]; idx2 = par[idx2]; } v[idx2].push_back(idx1); } } } for (i = 1; i <= n + m; i++) { long long int idx2 = i; while (idx2 != par[idx2]) { par[idx2] = par[par[idx2]]; idx2 = par[idx2]; } if (vis[idx2] == 0) if (!dfs(idx2)) { cout << "No"; return 0; } } cout << "Yes\n"; for (i = 1; i <= n; i++) { long long int idx2 = i; while (idx2 != par[idx2]) { par[idx2] = par[par[idx2]]; idx2 = par[idx2]; } cout << value[idx2] << " "; } cout << "\n"; for (i = n + 1; i <= n + m; i++) { long long int idx2 = i; while (idx2 != par[idx2]) { par[idx2] = par[par[idx2]]; idx2 = par[idx2]; } cout << value[idx2] << " "; } }
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 HashSet<>()); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (a[i][j] == '>') g.get(find(i)).add(find(n + j)); else if (a[i][j] == '<') g.get(find(n + j)).add(find(i)); } } vis = new int[n + m]; ans = new int[n + m]; for (int i = 0; i < n + m; i++) { if (vis[find(i)] == 0 && !dfs(find(i))) { out.println("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
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, M = 1005; int n, m, fa[N], To[M * M], Ne[M * M], St[N], en, ind[N], wg[N]; char mp[M][M]; queue<int> q; int Find(int u) { return fa[u] == 0 ? u : fa[u] = Find(fa[u]); } void addedge(int u, int v) { To[++en] = v, Ne[en] = St[u], St[u] = en; ++ind[v]; } int main() { scanf("%d%d", &n, &m); for (int i = 1; i <= n; ++i) { scanf("%s", mp[i] + 1); for (int j = 1; j <= m; ++j) if (mp[i][j] == '=' && Find(i) != Find(n + j)) fa[Find(i)] = Find(n + j); } for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { if (mp[i][j] == '<') addedge(Find(i), Find(n + j)); else if (mp[i][j] == '>') addedge(Find(n + j), Find(i)); } } for (int i = 1; i <= n + m; ++i) if (ind[i] == 0) q.push(i), wg[i] = 1; while (!q.empty()) { int u = q.front(); q.pop(); for (int i = St[u]; i; i = Ne[i]) { wg[To[i]] = max(wg[To[i]], wg[u] + 1); if ((--ind[To[i]]) == 0) q.push(To[i]); } } for (int i = 1; i <= n + m; ++i) if (ind[i] != 0) { puts("No"); return 0; } puts("Yes"); for (int i = 1; i <= n; ++i) printf("%d ", wg[Find(i)]); puts(""); for (int i = n + 1; i <= n + m; ++i) printf("%d ", wg[Find(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; inline bool EQ(double a, double b) { return fabs(a - b) < 1e-9; } const int INF = (((1 << 30) - 1) << 1) + 1; const int nINF = 1 << 31; void bad() { cout << "No" << endl; exit(0); } const int N = 2010; int parent[N]; int sz[N]; int find(int x) { return parent[x] = (x == parent[x] ? x : find(parent[x])); } bool disjoint(int x, int y) { return find(x) != find(y); } void join(int x, int y) { if (!disjoint(x, y)) return; int newPar = find(x), newChild = find(y); parent[newChild] = newPar; } int dsuSize(int x) { return sz[find(x)]; } int n, m, s, ch[N][N], ans[N], onpath[N], vis[N]; vector<int> g[N]; void dfs(int s) { onpath[s] = vis[s] = 1; for (int v : g[s]) { if (onpath[v]) bad(); if (!vis[v]) dfs(v); } int lo = 0; for (int v : g[s]) { lo = max(lo, ans[find(v)]); } ans[find(s)] = lo + 1; onpath[s] = 0; } signed main() { ios::sync_with_stdio(false); cin >> n >> m; s = n + m; std::iota(parent, parent + s + 1, 0), std::fill(sz, sz + s + 1, 1); for (int i = 0; i < (n); i++) { for (int j = 0; j < (m); j++) { char c; cin >> c; if (c == '=') { ch[i][j] = 0; join(i, n + j); } if (c == '>') ch[i][j] = 1; if (c == '<') ch[i][j] = -1; } } for (int i = 0; i < (n); i++) { for (int j = 0; j < (m); j++) { if (ch[i][j] == 1) { g[find(i)].push_back(find(n + j)); } else if (ch[i][j] == -1) { g[find(n + j)].push_back(find(i)); } } } for (int i = 0; i < (n + m); i++) if (!vis[i]) dfs(find(i)); cout << "Yes" << endl; for (int i = 0; i < (n); i++) cout << ans[find(i)] << ' '; cout << endl; for (int j = 0; j < (m); j++) cout << ans[find(n + j)] << ' '; cout << endl; return 0; }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n × m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≤ n, m ≤ 1000) — the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers — evaluations of dishes from the first set, and on the third line print m integers — evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.
2
10
"""Codeforces 1131D """ from sys import * from typing import * from collections import * r, c = [int(i) for i in stdin.readline().strip().split(' ')] a = [stdin.readline().strip() for i in range(r)] def L(i: int) -> int: return i def R(i: int) -> int: return r + i parent = [0] * (r + c) for i in range(r): parent[L(i)] = L(i) for i in range(c): parent[R(i)] = R(i) def find(i: int) -> int: parent[i] = i if parent[i] == i else find(parent[i]) return parent[i] def union(i: int, j: int): parent[find(i)] = find(j) for i in range(r): for j in range(c): if a[i][j] == '=': union(L(i), R(j)) less_than = [[] for i in range(r + c)] for i in range(r): for j in range(c): if a[i][j] == '<': less_than[find(R(j))].append(find(L(i))) elif a[i][j] == '>': less_than[find(L(i))].append(find(R(j))) score = {} color = {} no_solution = set() def f(i: int) -> int: if i not in color: color[i] = 'gray' elif color[i] == 'gray': no_solution.add(True) else: return score[i] if no_solution: return 0 score[i] = 1 + max([f(j) for j in less_than[i]], default=0) color[i] = 'black' return score[i] ans1 = [f(find(L(i))) for i in range(r)] ans2 = [f(find(R(i))) for i in range(c)] if no_solution: print('No') else: print('Yes') print(*ans1) print(*ans2)
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") using namespace std; void init_ios() { ios_base::sync_with_stdio(0); cin.tie(0); } const int N = 1005; int n, m, res[2 * N], wyn[2 * N], p[2 * N], bla[2 * N]; char a[N][N]; vector<int> topo, child[2 * N], kto[2 * N]; bool vis[2 * N]; int Find(int x) { if (x == p[x]) return x; return p[x] = Find(p[x]); } void Union(int x, int y) { x = Find(x); y = Find(y); if (x == y) return; for (int c : child[x]) child[y].push_back(c); for (int c : kto[x]) kto[y].push_back(c); kto[x].clear(); child[x].clear(); p[x] = y; } void dfs(int v) { vis[v] = true; for (int x : child[v]) if (!vis[Find(x)]) dfs(Find(x)); topo.push_back(v); } void dfs2(int v) { bla[v] = 1; for (int x : child[v]) { if (bla[Find(x)] == 0) dfs2(Find(x)); else if (bla[Find(x)] == 1) { cout << "No\n"; exit(0); } } bla[v] = 2; } int main() { init_ios(); cin >> n >> m; for (int i = 1; i <= n + m; ++i) { p[i] = i; kto[i].push_back(i); wyn[i] = 1; } for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) { cin >> a[i][j]; if (a[i][j] == '<') child[Find(i)].push_back(Find(n + j)); else if (a[i][j] == '>') child[Find(n + j)].push_back(Find(i)); else Union(i, n + j); } for (int i = 1; i <= n + m; ++i) if (bla[Find(i)] == 0) dfs2(Find(i)); for (int i = 1; i <= n + m; ++i) if (!vis[Find(i)]) dfs(Find(i)); reverse(topo.begin(), topo.end()); for (int i = 0; i + 1 < topo.size(); ++i) { for (int el : child[topo[i]]) wyn[Find(el)] = max(wyn[Find(el)], 1 + wyn[topo[i]]); } for (int i = 1; i <= n + m; ++i) for (int x : kto[Find(i)]) res[x] = wyn[Find(i)]; cout << "Yes\n"; for (int i = 1; i <= n; ++i) cout << res[i] << " "; cout << "\n"; for (int i = n + 1; i <= n + m; ++i) cout << res[i] << " "; cout << "\n"; }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n × m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≤ n, m ≤ 1000) — the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers — evaluations of dishes from the first set, and on the third line print m integers — evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> using namespace std; const int MAX = 1002; int n, m; char table[MAX][MAX]; struct UnionFind { int n, p[2 * MAX], w[2 * MAX]; UnionFind(int _n) { n = _n; for (int i = 0; i < n; i++) w[i] = 1; for (int i = 0; i < n; i++) p[i] = i; } void uni(int i, int j) { int u = root(i), v = root(j); if (u == v) return; if (w[u] > w[v]) { p[v] = u; w[u] += w[v]; } else { p[u] = v; w[v] += w[u]; } } bool connected(int i, int j) { int u = root(i), v = root(j); if (u == v) return true; else return false; } int root(int k) { while (p[k] != k) k = p[k]; return k; } } uf(2 * MAX); vector<int> adj[2 * MAX]; int val[2 * MAX], outdeg[2 * MAX]; bool comp[2 * MAX], cycle; void dfs(int v, int k) { val[v] = k; comp[v] = false; for (int w : adj[v]) { if (val[w] <= val[v] && comp[w]) dfs(w, k + 1); else if (!comp[w]) { cycle = true; return; } } comp[v] = true; } int main() { cin >> n >> m; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) cin >> table[i][j]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) if (table[i][j] == '=') uf.uni(i, j + n); memset(outdeg, 0, sizeof(outdeg)); for (int i = 0; i < m + n; i++) comp[i] = true; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { int u = uf.root(i), v = uf.root(j + n); if (table[i][j] == '<') { adj[u].push_back(v); outdeg[v]++; } if (table[i][j] == '>') { adj[v].push_back(u); outdeg[u]++; } } for (int i = 0; i < m + n; i++) val[i] = 1; vector<int> s; for (int i = 0; i < m + n; i++) if (outdeg[i] == 0 && adj[i].size() > 0) s.push_back(i); if (s.size() == 0) { s.push_back(uf.root(0)); } for (int i : s) dfs(i, 1); if (cycle) { cout << "No"; return 0; } cout << "YES\n"; for (int i = 0; i < n; i++) cout << val[uf.root(i)] << " "; cout << "\n"; for (int i = 0; i < m; i++) cout << val[uf.root(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; const long long MAXN = 2e3 + 5; const long long MOD = 1e9 + 7; int n, m, a[MAXN], vis[MAXN], pre[MAXN]; vector<int> v[MAXN]; char mp[MAXN][MAXN]; struct node { int x, val; } p; queue<node> q; int Find(int x) { return pre[x] == x ? x : pre[x] = Find(pre[x]); } int main() { while (~scanf("%d%d", &n, &m)) { int flag = 0; memset(vis, 0, sizeof(vis)); memset(a, 0, sizeof(a)); for (long long i = 1; i <= n + m; i++) pre[i] = i; for (long long i = 1; i <= n; i++) { scanf("%s", mp[i] + 1); } for (long long i = 1; i <= n; i++) { for (long long j = 1; j <= m; j++) { if (mp[i][j] == '=') { int xx = Find(i), yy = Find(n + j); pre[xx] = yy; } } } for (long long i = 1; i <= n; i++) { for (long long j = 1; j <= m; j++) { if (mp[i][j] == '=') continue; int xx = Find(i), yy = Find(n + j); if (xx == yy) { flag = 1; break; } if (mp[i][j] == '<') { v[xx].push_back(yy); vis[yy]++; } if (mp[i][j] == '>') { v[yy].push_back(xx); vis[xx]++; } } if (flag) break; } if (flag) { puts("No"); continue; } for (long long i = 1; i <= n; i++) { if (vis[i] == 0) { p.x = i, p.val = 1; q.push(p); } } for (long long i = 1; i <= m; i++) { if (vis[n + i] == 0) { p.x = n + i, p.val = 1; q.push(p); } } int tot = 0; while (!q.empty()) { tot++; p = q.front(); q.pop(); a[p.x] = p.val; int len = v[p.x].size(); for (long long i = 0; i <= len - 1; i++) { int to = v[p.x][i]; vis[to]--; if (!vis[to]) { node temp; temp.x = to, temp.val = p.val + 1; q.push(temp); } } } for (long long i = 1; i <= n + m; i++) { a[i] = a[Find(i)]; } for (long long i = 1; i <= n; i++) { for (long long j = 1; j <= m; j++) { if ((mp[i][j] == '=' && a[i] == a[n + j]) || (mp[i][j] == '>' && a[i] > a[n + j]) || (mp[i][j] == '<' && a[i] < a[n + j])) flag = 0; else { flag = 1; break; } } if (flag) break; } if (flag) printf("No\n"); else { printf("Yes\n"); for (long long i = 1; i <= n + m; i++) { printf("%d", a[i]); if (i == n || i == n + m) cout << endl; else 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
import sys,os,io range = xrange # INPUT input_data = os.read(0,os.fstat(0).st_size) input = io.BytesIO(input_data).readline n,m = [int(x) for x in input().split()] data = [input() for _ in range(n)] rep = [-1]*(n+m) for root in range(n+m): if rep[root]>=0:continue rep[root] = root Q = [root] while Q: node = Q.pop() if node<n: i = node for j in range(m): if rep[j+n]==-1 and data[i][j]=='=': rep[j+n] = root Q.append(j+n) else: j = node-n for i in range(n): if rep[i]==-1 and data[i][j]=='=': rep[i] = root Q.append(i) assert(not any(r<0 for r in rep)) better = [[] for _ in range(n+m)] for i in range(n): for j in range(m): if data[i][j]=='>': better[rep[j+n]].append(rep[i]) elif data[i][j]=='<': better[rep[i]].append(rep[j+n]) counter = [0]*(n+m) for ind in range(n+m): if rep[ind]==ind: for ind2 in better[ind]: counter[ind2] += 1 val = [-1]*(n+m) found = sum(1 for ind in range(n+m) if rep[ind]==ind) leaves = [ind for ind in range(n+m) if rep[ind]==ind and counter[ind]==0] for ind in leaves: val[ind] = 1 while leaves: ind = leaves.pop() found -= 1 v = val[ind] for ind2 in better[ind]: if ind2==ind: print 'No' sys.exit() val[ind2] = max(val[ind2],v+1) counter[ind2] -= 1 if counter[ind2]==0: leaves.append(ind2) val = [val[rep[i]] for i in range(n+m)] if found>0 or any(v<0 for v in val): print 'No' else: print 'Yes' print ' '.join(str(x) for x in val[:n]) print ' '.join(str(x) for x in val[n:n+m])
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; class DisjointedSetMergingStructure { vector<size_t> parent; public: explicit DisjointedSetMergingStructure(const size_t size) { parent = vector<size_t>(size); iota(parent.begin(), parent.end(), size_t()); } void join(const size_t A, const size_t B) { parent.at(get_root(B)) = get_root(A); } size_t get_root(const size_t A) { if (parent.at(A) == A) { return A; } return (parent.at(A) = get_root(parent.at(A))); } bool is_root(const size_t A) { return A == get_root(A); } bool is_same_set(const size_t A, const size_t B) { return get_root(A) == get_root(B); } }; void AnswerExit() { cout << "No" << endl; exit(0); } int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); int N, M; cin >> N >> M; DisjointedSetMergingStructure equal_group(N + M); vector<string> table(N); for (auto n = 0; n < N; ++n) { cin >> table[n]; for (auto m = 0; m < M; ++m) { if (table[n][m] == '=') { equal_group.join(n, N + m); } } } vector<int> degree_in(N + M); vector<vector<int>> graph(N + M); for (auto n = 0; n < N; ++n) { for (auto m = 0; m < M; ++m) { auto group_n = equal_group.get_root(n); auto group_m = equal_group.get_root(N + m); switch (table[n][m]) { case '<': if (group_n == group_m) { AnswerExit(); } graph[group_m].push_back(group_n); degree_in[group_n]++; break; case '>': if (group_n == group_m) { AnswerExit(); } graph[group_n].push_back(group_m); degree_in[group_m]++; break; default: break; } } } int max_answers = 0; vector<int> answers(N + M, 0); queue<int> searching; for (auto i = 0; i < N + M; ++i) { if (equal_group.is_root(i) and degree_in[i] == 0) { searching.push(i); } } if (searching.empty()) { AnswerExit(); } while (not searching.empty()) { auto top = searching.front(); searching.pop(); for (const auto &dst : graph[top]) { answers[dst] = answers[top] + 1; max_answers = max(max_answers, answers[dst]); if (--degree_in[dst] == 0) { searching.push(dst); } } } for (auto i = 0; i < N + M; ++i) { if (equal_group.is_root(i) and degree_in[i] > 0) { AnswerExit(); } } max_answers++; cout << "YES\n"; for (auto n = 0; n < N; ++n) { cout << max_answers - answers[equal_group.get_root(n)] << ' '; } cout << '\n'; for (auto m = 0; m < M; ++m) { cout << max_answers - answers[equal_group.get_root(N + m)] << ' '; } 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.lang.reflect.Array; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; public class D541 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(), m = scanner.nextInt(); List<List<Integer>> lt = new ArrayList<>(); List<List<Integer>> eq = new ArrayList<>(); List<List<Integer>> gt = new ArrayList<>(); for (int i = 0; i < m; i++){ lt.add(new ArrayList<>()); gt.add(new ArrayList<>()); eq.add(new ArrayList<>()); } scanner.nextLine(); for (int i = 0; i < n;i++){ String s = scanner.nextLine(); for (int j = 0; j < m; j++){ char c = s.charAt(j); if ( c == '<'){ lt.get(j).add(i); }else if (c == '>'){ gt.get(j).add(i); }else eq.get(j).add(i); } } PriorityQueue<Pair> pairs = new PriorityQueue<>( (o1, o2) -> o1.size == o2.size ? o1.eq - o2.eq : o1.size - o2.size); for (int i = 0; i < lt.size(); i++) { pairs.add(new Pair(lt.get(i).size(), eq.get(i).size(), i)); } Integer[] first = new Integer[n]; Integer[] second = new Integer[m]; int value = 0; int prevIdx = -1; while (pairs.size() > 0){ Pair poll = pairs.poll(); if (prevIdx != -1 && poll.size == lt.get(prevIdx).size()){ boolean flag = true; for (Integer integer : lt.get(poll.idx)) { if (!lt.get(prevIdx).contains(integer)) flag =false; } if (eq.get(prevIdx).size() > 0){ if (eq.get(poll.idx).size() != eq.get(prevIdx).size()){ System.out.println("No"); return; } for (Integer integer : eq.get(poll.idx)) { if (!eq.get(prevIdx).contains(integer)) flag =false; } } if (flag){ if (eq.get(prevIdx).size() == 0 && eq.get(poll.idx).size() > 0){ value += 1; for (Integer integer : eq.get(poll.idx)) { first[integer] = value; } } second[poll.idx] = value; prevIdx = poll.idx; continue; } System.out.println("No"); return; } value +=1; boolean flag = false; for (Integer integer : lt.get(poll.idx)) { if (first[integer] == null) { first[integer] = value; flag = true; } } if (flag) value +=1; second[poll.idx] = value; for (Integer integer : eq.get(poll.idx)) { if (first[integer] != null){ System.out.println("No"); return; } first[integer] = value; } for (Integer integer : gt.get(poll.idx)) { if (first[integer] != null){ System.out.println("No"); return; } } prevIdx = poll.idx; } value += 1; for (int i = 0; i < n; i++){ if (first[i] == null) first[i] = value; } System.out.println("Yes"); String firsrAns = Stream.of(first) .map(Objects::toString) .collect(Collectors.joining(" ")); String secondAns = Stream.of(second) .map(Objects::toString) .collect(Collectors.joining(" ")); System.out.println(firsrAns); System.out.println(secondAns); } } class Pair{ int size; int idx; int eq; public Pair(int size, int eq, int idx) { this.size = size; this.idx = idx; this.eq = eq; } }
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 main() { int n, m; cin >> n >> m; vector<vector<int> > equals_n_m(n + m, vector<int>()); vector<vector<int> > major_n_m(n + m, vector<int>()); vector<int> minor_n_m(n + m, 0); vector<vector<char> > input_matrix(n, vector<char>(m)); vector<int> result(n + m, 0); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> input_matrix[i][j]; } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (input_matrix[i][j] == '=') { equals_n_m[i].push_back(j + n); equals_n_m[j + n].push_back(i); } else if (input_matrix[i][j] == '<') { major_n_m[i].push_back(j + n); minor_n_m[j + n]++; } else if (input_matrix[i][j] == '>') { major_n_m[j + n].push_back(i); minor_n_m[i]++; } } } vector<bool> marked(n + m, false); int counter_marked = 0; int explored = 0; int counter_of_turns = 1; bool error_found = false; while (explored < n + m && !error_found) { vector<bool> neighbours(n + m, false); queue<int> q; for (int i = 0; i < n + m; i++) { if (minor_n_m[i] > 0) { neighbours[i] = false; } else { neighbours[i] = true; } } for (int i = 0; i < n + m; i++) { if (!marked[i]) { bool found = true; for (int n = 0; n < equals_n_m[i].size(); n++) { if (!neighbours[equals_n_m[i][n]]) { found = false; } } if (found && minor_n_m[i] == 0) { q.push(i); } } } if (q.empty()) { break; } while (!q.empty()) { int node = q.front(); q.pop(); for (int i = 0; i < major_n_m[node].size(); i++) { minor_n_m[major_n_m[node][i]]--; } for (int i = 0; i < equals_n_m[node].size(); i++) { if (result[equals_n_m[node][i]] != 0 && result[equals_n_m[node][i]] != counter_of_turns) { error_found = true; break; } } result[node] = counter_of_turns; explored++; marked[node] = true; counter_marked++; } counter_of_turns++; } if (error_found || counter_marked != n + m) { cout << "NO" << endl; } else { cout << "YES" << endl; for (int i = 0; i < n; i++) { cout << result[i] << " "; } cout << endl; for (int j = n; j < n + m; j++) { cout << result[j] << " "; } cout << endl; } return 0; }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n × m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≤ n, m ≤ 1000) — the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers — evaluations of dishes from the first set, and on the third line print m integers — evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> using namespace std; template <typename _tp> inline void read(_tp& x) { char c11 = getchar(), ob = 0; x = 0; while (c11 != '-' && !isdigit(c11)) c11 = getchar(); if (c11 == '-') ob = 1, c11 = getchar(); while (isdigit(c11)) x = x * 10 + c11 - '0', c11 = getchar(); if (ob) x = -x; } const int N = 2013, M = 1001000; struct Edge { int v, nxt; } a[M]; char s[1003][1003]; int head[N], num[N], deg[N]; int n, m, _; inline void add(int u, int v) { a[++_].v = v, a[_].nxt = head[u], head[u] = _; ++deg[v]; } namespace UNF { int d[N]; inline int get(int x) { return d[x] ? d[x] = get(d[x]) : x; } inline void merge(int x, int y) { x = get(x); y = get(y); if (x != y) d[x] = y; } } // namespace UNF int q[N], he, ta; void topo() { he = 1, ta = 0; for (int i = 1; i <= n + m; ++i) if (!deg[i]) num[q[++ta] = i] = 1; while (he <= ta) { int x = q[he++]; for (int i = head[x]; i; i = a[i].nxt) { num[a[i].v] = max(num[a[i].v], num[x] + 1); --deg[a[i].v]; if (!deg[a[i].v]) q[++ta] = a[i].v; } } } int main() { read(n), read(m); for (int i = 1; i <= n; ++i) scanf("%s", s[i] + 1); for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) if (s[i][j] == '=') UNF::merge(i, j + n); for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) if (s[i][j] != '=') { int x = UNF::get(i); int y = UNF::get(j + n); if (x == y) { puts("No"); return 0; } if (s[i][j] == '<') add(x, y); else add(y, x); } topo(); for (int i = 1; i <= n + m; ++i) if (num[i] and deg[i]) { puts("No"); return 0; } puts("Yes"); for (int i = 1; i <= n; ++i) printf("%d ", num[UNF::get(i)]); putchar(10); for (int i = 1; i <= m; ++i) printf("%d ", num[UNF::get(i + n)]); putchar(10); 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 = 1e3 + 5; int n, m, father[maxn << 1], ru[maxn << 1], vis[maxn << 1], ans[maxn << 1]; vector<int> g[maxn << 1]; char s[maxn][maxn]; int findfather(int x) { if (x == father[x]) return x; int i = findfather(father[x]); father[x] = i; return i; } void unit(int a, int b) { int fa = findfather(a), fb = findfather(b); if (fa != fb) father[fa] = fb; } int main() { queue<int> q; scanf("%d%d", &n, &m); for (int i = 0; i <= n + m; ++i) father[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] == '=') unit(i, j + n); for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) if (s[i][j] == '<') g[findfather(i)].push_back(findfather(j + n)), ru[findfather(j + n)]++; else if (s[i][j] == '>') g[findfather(j + n)].push_back(findfather(i)), ru[findfather(i)]++; for (int i = 1; i <= n + m; ++i) if (ru[i] == 0) q.push(i), vis[i] = 1, ans[i] = 1; while (!q.empty()) { int t = q.front(); q.pop(); for (int to : g[t]) { if (vis[to]) continue; ru[to]--; if (ru[to] == 0) q.push(to), ans[to] = ans[t] + 1, vis[to] = 1; } } for (int i = 1; i <= n + m; ++i) if (i == findfather(i) && !vis[i]) { puts("No"); return 0; } puts("Yes"); for (int i = 1; i <= n; ++i) printf("%d%s", ans[findfather(i)], (i == n) ? "\n" : " "); for (int i = 1; i <= m; ++i) printf("%d%s", ans[findfather(i + n)], (i == 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
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class GourmetChoice { static int[] values = new int[2000]; static color[] state = new color[2000]; static DisjointSet dsu; public static void main(String[] args) throws IOException { BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(f.readLine()); int N = Integer.parseInt(st.nextToken()); int M = Integer.parseInt(st.nextToken()); dsu = new DisjointSet(N+M); String[][] input = new String[N][M]; for (int i = 0; i < N; i++) { st = new StringTokenizer(f.readLine()); String[] next = st.nextToken().split(""); for (int j = 0; j < M; j++) { if (next[j].equals("=")) { dsu.union(j + N, i); } } input[i] = next; } for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { if (input[i][j].equals(">")) { dsu.addEdge(dsu.find(i), dsu.find(j+N)); } else if (input[i][j].equals("<")) { dsu.addEdge(dsu.find(j+N), dsu.find(i)); } } } for (int i = 0; i <2000; i++) { state[i] = color.blank; } for (int i = 0; i < N + M; i++) { int temp = dsu.find(i); if (state[temp] == color.blank) { dfs(temp); } } PrintWriter out = new PrintWriter(System.out); if (!ok) { System.out.println("NO"); System.exit(0); } out.println("YES"); for (int i = 0; i < N; i++) { out.print(values[dsu.find(i)] + " "); } out.println(); for (int i = 0; i < M; i++) { out.print(values[dsu.find(N+i)] + " "); } out.println(); out.close(); } static boolean ok = true; public static void dfs(int i) { if (dsu.adjList[i].size() == 0) { state[i] = color.okay; values[i] = 1; return; } int mx = 0; state[i] = color.progress; for (int x = 0; x < dsu.adjList[i].size(); x++) { if (!ok) return; int j = dsu.adjList[i].get(x); if (state[j]==color.progress)ok=false; if (state[j] != color.okay) dfs(j); mx = Math.max(mx, values[j]+1); } state[i] = color.okay; values[i] = mx; } static class DisjointSet { int[] parent; ArrayList<Integer>[] adjList; int size; DisjointSet(int N) { size = N; parent = new int[size]; adjList = new ArrayList[size]; for (int i = 0; i < size; i++) { parent[i] = i; adjList[i] = new ArrayList<>(); } } public int find(int x) { return (parent[x] == x ? x : (parent[x] = find(parent[x]))); } public void addEdge(int x, int e) { adjList[x].add(e); } public void union(int x, int y) { int parX = find(x); int parY = find(y); if (parX != parY) { parent[parY] = parX; } } public ArrayList<Integer> getadjLists(int x) { return adjList[x]; } } enum color { progress, okay, blank; }; }
JAVA
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n × m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≤ n, m ≤ 1000) — the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers — evaluations of dishes from the first set, and on the third line print m integers — evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> using namespace std; void test() { cerr << "\n"; } template <typename T, typename... Args> void test(T x, Args... args) { cerr << x << " "; test(args...); } const int MAXN = (int)1e5 + 5; const int MOD = (int)1e9 + 7; char g[1005][1005]; int a[1005], b[1005]; int main() { int n, m; scanf("%d%d", &n, &m); vector<pair<int, int> > v1(n); for (int i = 0; i < n; i++) { scanf("%s", g[i]); v1[i] = {0, i}; for (int j = 0; j < m; j++) { if (g[i][j] == '>') v1[i].first++; else if (g[i][j] == '<') v1[i].first--; } } sort(v1.begin(), v1.end()); bool flag = 1; a[v1[0].second] = 1; for (int i = 1; i < n; i++) { int u = v1[i].second, v = v1[i - 1].second; if (v1[i].first == v1[i - 1].first) a[u] = a[v]; else a[u] = a[v] + 2; } for (int j = 0; j < m; j++) { int f = 0; for (int i = 0; i < n; i++) { if (g[i][j] == '=') { b[j] = a[i]; f = 1; break; } } if (!f) { for (int i = 0; i < n; i++) { if (g[i][j] == '<') { b[j] = max(b[j], a[i] + 1); } } } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { char tmp; if (a[i] > b[j]) tmp = '>'; else if (a[i] == b[j]) tmp = '='; else tmp = '<'; if (tmp != g[i][j]) flag = 0; } } if (flag == 0) printf("No\n"); else { printf("Yes\n"); vector<int> ve; for (int i = 0; i < n; i++) { ve.push_back(a[i]); } for (int i = 0; i < m; i++) { ve.push_back(b[i]); } sort(ve.begin(), ve.end()); ve.erase(unique(ve.begin(), ve.end()), ve.end()); for (int i = 0; i < n; i++) { a[i] = lower_bound(ve.begin(), ve.end(), a[i]) - ve.begin() + 1; printf("%d ", a[i]); } printf("\n"); for (int i = 0; i < m; i++) { b[i] = lower_bound(ve.begin(), ve.end(), b[i]) - ve.begin() + 1; printf("%d ", b[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 MAXN = 2005; template <size_t N> struct DSU { int parent[N]; void init(int n) { iota(parent + 1, parent + n + 1, 1); } int find(int x) { return x == parent[x] ? x : parent[x] = find(parent[x]); } void merge(int x, int y) { parent[find(x)] = find(y); } }; int n, m; char g[MAXN][MAXN]; DSU<MAXN> dsu; vector<int> edges[MAXN]; int vis[MAXN], deg[MAXN], value[MAXN]; bool dfs(int x) { if (vis[x] == 2) return true; if (vis[x] == 1) return false; vis[x] = 1; for (auto i : edges[x]) if (!dfs(i)) return false; vis[x] = 2; return true; } bool check() { for (int i = 1; i <= n + m; i++) if (!vis[i] && !dfs(i)) return false; return true; } void bfs() { memset(vis, 0, sizeof vis); queue<int> q; for (int i = 1; i <= n + m; i++) if (i == dsu.find(i) && deg[i] == 0) { value[i] = 1; q.push(i); } while (!q.empty()) { int x = q.front(); for (auto i : edges[x]) { value[i] = max(value[i], value[x] + 1); if (--deg[i] == 0) q.push(i); } q.pop(); } } int main() { scanf("%d%d", &n, &m); for (int i = 1; i <= n; i++) scanf("%s", g[i] + 1); dsu.init(n + m); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) if (g[i][j] == '=') dsu.merge(i, n + j); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { if (g[i][j] == '<') { edges[dsu.find(i)].push_back(dsu.find(n + j)); deg[dsu.find(n + j)]++; } else if (g[i][j] == '>') { edges[dsu.find(n + j)].push_back(dsu.find(i)); deg[dsu.find(i)]++; } } if (!check()) { printf("No\n"); return 0; } bfs(); printf("Yes\n"); for (int i = 1; i <= n; i++) printf("%d ", value[dsu.find(i)]); printf("\n"); for (int i = 1; i <= m; i++) printf("%d ", value[dsu.find(n + 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; const long long N = 2007; long long n, m; char a[N][N]; vector<long long> g[N], g1[N]; bool used[N]; long long c[N]; void dfs(long long u, long long cc) { used[u] = 1; c[u] = cc; for (long long v : g[u]) { if (!used[v]) dfs(v, cc); } } long long ans[N]; void dfs1(long long u) { used[u] = 1; ans[u] = 1; for (long long v : g1[u]) { if (!used[v]) dfs1(v); ans[u] = max(ans[u], ans[v] + 1); } } void solve() { for (long long i = 0; i < n; ++i) { for (long long j = 0; j < m; ++j) { if (a[i][j] == '=') { g[i].push_back(n + j); g[n + j].push_back(i); } } } long long cc = 0; for (long long i = 0; i < n + m; ++i) { if (!used[i]) { dfs(i, cc); ++cc; } } for (long long i = 0; i < n; ++i) { for (long long j = 0; j < m; ++j) { if (a[i][j] == '>') { g1[c[i]].push_back(c[n + j]); } else if (a[i][j] == '<') { g1[c[n + j]].push_back(c[i]); } } } memset(used, 0, sizeof used); for (long long i = 0; i < cc; ++i) { if (!used[i]) { dfs1(i); } } } long long x[N], y[N]; void check() { for (long long i = 0; i < n; ++i) { x[i] = ans[c[i]]; } for (long long i = 0; i < m; ++i) { y[i] = ans[c[i + n]]; } for (long long i = 0; i < n; ++i) { for (long long j = 0; j < m; ++j) { if (a[i][j] == '=') { if (x[i] != y[j]) { cout << "No\n"; exit(0); } } else if (a[i][j] == '<') { if (!(x[i] < y[j])) { cout << "No\n"; exit(0); } } else { if (!(x[i] > y[j])) { cout << "No\n"; exit(0); } } } } } signed main() { ios_base::sync_with_stdio(0); cin.tie(0); cin >> n >> m; for (long long i = 0; i < n; ++i) { for (long long j = 0; j < m; ++j) { cin >> a[i][j]; } } solve(); check(); cout << "Yes\n"; for (long long i = 0; i < n; ++i) { cout << x[i] << ' '; } cout << '\n'; for (long long i = 0; i < m; ++i) { cout << y[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> int n, m, fa[2005]; char s[2005][2005], G[2005][2005]; int in[2005], dis[2005]; int find(int x) { return fa[x] ? fa[x] = find(fa[x]) : x; } inline void join(int a, int b) { int x = find(a), y = find(b); if (x != y) fa[x] = y; } bool bfs() { std::queue<int> q; int i, u, cnt = 0; for (i = 1; i <= n + m; ++i) { if (!fa[i]) { ++cnt; if (!in[i]) { dis[i] = 1; q.push(i); } } } while (!q.empty()) { u = q.front(); q.pop(); --cnt; for (i = 1; i <= n + m; ++i) { if (G[u][i]) { if (!--in[i]) { dis[i] = dis[u] + 1; in[i] = 1 << 30; q.push(i); } } } } return !cnt; } int main() { int i, j, a, b; scanf("%d%d", &n, &m); for (i = 1; i <= n; ++i) { scanf("%s", s[i] + 1); for (j = 1; j <= m; ++j) { if (s[i][j] == '=') join(i, n + j); } } for (i = 1; i <= n; ++i) { for (j = 1; j <= m; ++j) { if (s[i][j] != '=') { a = find(i); b = find(n + j); if (a == b) { puts("No"); return 0; } if (s[i][j] == '<') { if (!G[a][b]) { G[a][b] = 1; ++in[b]; } } else { if (!G[b][a]) { G[b][a] = 1; ++in[a]; } } } } } if (bfs()) { puts("Yes"); for (int i = 1; i <= n; ++i) printf("%d ", dis[find(i)]); puts(""); for (int i = 1; i <= m; ++i) printf("%d ", dis[find(n + i)]); puts(""); } 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> using namespace std; int N, M; string grid[1000]; vector<vector<pair<int, char>>> startAdj; vector<bool> visited; vector<int> merged; vector<vector<pair<int, char>>> adj; vector<int> value; vector<int> greaterCount; void flood(int start, int pos) { if (visited[pos]) return; visited[pos] = true; merged[pos] = start; for (int i = 0; i < startAdj[pos].size(); i++) { if (startAdj[pos][i].second != '=') { adj[start].push_back(startAdj[pos][i]); } } for (int i = 0; i < startAdj[pos].size(); i++) { if (startAdj[pos][i].second == '=') { flood(start, startAdj[pos][i].first); } } } int main() { ios_base::sync_with_stdio(false); cin >> N >> M; for (int i = 0; i < N; i++) cin >> grid[i]; startAdj.assign(N + M + 1, vector<pair<int, char>>()); for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) startAdj[i + 1].push_back({j + 1 + N, grid[i][j]}); for (int j = 0; j < M; j++) { for (int i = 0; i < N; i++) { char c = grid[i][j]; if (c == '>') c = '<'; else if (c == '<') c = '>'; startAdj[j + 1 + N].push_back({i + 1, c}); } } visited.assign(N + M + 1, false); merged.assign(N + M + 1, 0); adj.assign(N + M + 1, vector<pair<int, char>>()); value.assign(N + M + 1, 0); greaterCount.assign(N + M + 1, 0); for (int i = 1; i <= N + M; i++) { if (!visited[i]) { flood(i, i); } } bool works = true; for (int i = 1; i <= N + M; i++) { for (int j = 0; j < adj[i].size(); j++) { if (adj[i][j].second == '>') greaterCount[i]++; if (merged[adj[i][j].first] == i) works = false; } } if (works) { vector<int> curr; for (int i = 1; i <= N + M; i++) if (merged[i] == i && greaterCount[i] == 0) curr.push_back(i); vector<int> next; int v = 1; while (curr.size() != 0) { for (int i = 0; i < curr.size(); i++) { value[curr[i]] = v; for (int j = 0; j < adj[curr[i]].size(); j++) { if (adj[curr[i]][j].second == '<') { greaterCount[merged[adj[curr[i]][j].first]]--; if (greaterCount[merged[adj[curr[i]][j].first]] == 0) { next.push_back(merged[adj[curr[i]][j].first]); } } } } curr = next; next.clear(); v++; } for (int i = 1; i <= N + M; i++) { if (!value[i] && merged[i] == i) works = false; } } if (works) { cout << "Yes\n"; for (int i = 0; i < N; i++) { if (i) cout << " "; cout << value[merged[i + 1]]; } cout << "\n"; for (int i = 0; i < M; i++) { if (i) cout << " "; cout << value[merged[i + 1 + N]]; } cout << "\n"; } else { cout << "No\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; vector<int> V[4444]; string s[4444]; int fa[4444], D[4444], ans[4444]; int fd(int x) { if (x == fa[x]) return x; return fa[x] = fd(fa[x]); } int main() { ios_base::sync_with_stdio(false); cout.tie(0); cin.tie(0); for (int i = 0; i < 4444; i++) fa[i] = i; int n, m; cin >> n >> m; for (int i = 0; i < n; i++) cin >> s[i]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) if (s[i][j] == '=') fa[fd(i)] = fa[fd(j + 1000)]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (s[i][j] == '<') { V[fd(j + 1000)].push_back(fd(i)); D[fd(i)]++; } else if (s[i][j] == '>') { V[fd(i)].push_back(fd(j + 1000)); D[fd(j + 1000)]++; } } } queue<int> Q; for (int i = 0; i < n; i++) if (fd(i) == i && D[fd(i)] == 0) { Q.push(fd(i)); } for (int i = 0; i < m; i++) if (fd(i + 1000) == i + 1000 && D[fd(i + 1000)] == 0) Q.push(i + 1000); int inf = 4444; while (!Q.empty()) { int sz = Q.size(); for (int i = 0; i < sz; i++) { int t = Q.front(); Q.pop(); ans[t] = inf; for (int v : V[t]) { D[v]--; if (!D[v]) Q.push(v); } } inf--; } vector<int> a(n), b(m); for (int i = 0; i < n; i++) { a[i] = ans[fd(i)]; if (a[i] == 0) { cout << "No"; return 0; } } for (int i = 0; i < m; i++) { b[i] = ans[fd(i + 1000)]; if (b[i] == 0) { cout << "No"; return 0; } } cout << "Yes" << "\n"; for (int i = 0; i < n; i++) cout << a[i] - inf << " "; cout << "\n"; for (int i = 0; i < m; i++) cout << b[i] - inf << " "; }
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 mod = 1e9 + 7; const int p_mod = 998244353; using namespace std; long long fast_pow(long long a, long long b) { long long res = 1; while (b) { if (b & 1) res = (res * a) % mod; b >>= 1; a = (a * a) % mod; } return res % mod; } const int N = 2000 + 10; char g[N][N]; int n, m, root[N], ans[N], in[N]; int find(int x) { return (x != root[x]) ? root[x] = find(root[x]) : root[x]; } vector<int> e[N]; bool check() { for (int i = 1; i <= n + m; i++) root[i] = i; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) if (g[i][j] == '=') root[find(i)] = find(n + j); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { if (g[i][j] == '=') continue; if (find(i) == find(n + j)) return false; if (g[i][j] == '>') e[find(j + n)].push_back(find(i)); if (g[i][j] == '<') e[find(i)].push_back(find(j + n)); } for (int i = 1; i <= n + m; i++) { sort(e[i].begin(), e[i].end()); } for (int i = 1; i <= n + m; i++) e[i].erase(unique(e[i].begin(), e[i].end()), e[i].end()); for (int i = 1; i <= n + m; i++) for (int j = 0; j < e[i].size(); j++) in[e[i][j]]++; queue<int> q; for (int i = 1; i <= n + m; i++) if (in[i] == 0) { q.push(i); ans[i] = 1; } while (!q.empty()) { int now = q.front(); q.pop(); for (int i = 0; i < e[now].size(); i++) { int upper = e[now][i]; in[upper]--; ans[upper] = max(ans[upper], ans[now] + 1); if (in[upper] == 0) q.push(upper); } } if (*max_element(in + 1, in + m + n + 1) > 0) return false; return true; } int main() { std::ios::sync_with_stdio(false); std::cin.tie(0); cin >> n >> m; for (int i = 1; i <= n; i++) cin >> (g[i] + 1); if (check()) { cout << "Yes" << endl; for (int i = 1; i <= n; i++) cout << ans[find(i)] << " "; cout << endl; for (int i = 1; i <= m; i++) cout << ans[find(i + n)] << " "; } else 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
#include <bits/stdc++.h> using namespace std; const int MAXN = 100000; const int MAXM = 200000; inline void dfs(int); struct edge { int v, w; }; int Error; int dis[MAXN + 1]; bitset<MAXN + 1> vis, chk; int sz[MAXN + 1]; vector<edge> to[MAXN + 1]; void dfs(int x) { vis[x] = 1; int si = sz[x]; for (int i = 0; i < si; i++) { int u = to[x][i].v, w = to[x][i].w; if (dis[u] < dis[x] + w) { if (vis[u]) { Error = 1; return; } dis[u] = dis[x] + w; dfs(u); if (Error) return; } } vis[x] = 0; } int main() { int n, m; cin >> n >> m; 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 == '>') to[j + n].push_back((edge){i, 1}), sz[j + n]++; if (ch == '<') to[i].push_back((edge){j + n, 1}), sz[i]++; if (ch == '=') { to[i].push_back((edge){j + n, 0}), sz[i]++; to[j + n].push_back((edge){i, 0}), sz[j + n]++; } } } for (int i = 1; i <= n + m; i++) to[0].push_back((edge){i, 1}), sz[0]++; dfs(0); if (!Error) { puts("Yes"); for (int i = 1; i <= n; i++) printf("%d%c", dis[i], " \n"[i == n]); for (int i = 1; i <= m; i++) printf("%d%c", dis[i + n], " \n"[i == m]); } 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
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; import java.io.BufferedWriter; import java.util.Collection; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.io.UncheckedIOException; import java.util.List; import java.nio.charset.Charset; import java.util.StringTokenizer; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.Queue; import java.io.BufferedReader; import java.util.ArrayDeque; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author mikit */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; LightScanner in = new LightScanner(inputStream); LightWriter out = new LightWriter(outputStream); DGourmetChoice solver = new DGourmetChoice(); solver.solve(1, in, out); out.close(); } static class DGourmetChoice { public void solve(int testNumber, LightScanner in, LightWriter out) { // out.setBoolLabel(LightWriter.BoolLabel.YES_NO_FIRST_UP); int n = in.ints(), m = in.ints(); DGourmetChoice.Node[] nodes = new DGourmetChoice.Node[n + m]; for (int i = 0; i < n + m; i++) nodes[i] = new DGourmetChoice.Node(i); char[][] tbl = new char[n][]; for (int i = 0; i < n; i++) tbl[i] = in.string().toCharArray(); IntUnionFind uf = new IntUnionFind(n + m); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (tbl[i][j] == '=') uf.union(i, n + j); } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (tbl[i][j] == '=') continue; nodes[uf.find(i)].valid = nodes[uf.find(n + j)].valid = true; if (uf.find(i) == uf.find(n + j)) { //System.out.println("DIFF EQUAL"); out.noln(); return; } else if (tbl[i][j] == '<') { nodes[uf.find(i)].adj.add(nodes[uf.find(n + j)]); nodes[uf.find(n + j)].incoming++; } else { nodes[uf.find(n + j)].adj.add(nodes[uf.find(i)]); nodes[uf.find(i)].incoming++; } } } Queue<DGourmetChoice.Node> q = new ArrayDeque<>(); for (int i = 0; i < n + m; i++) if (nodes[i].incoming == 0) q.offer(nodes[i]); int cur = 1; while (!q.isEmpty()) { Queue<DGourmetChoice.Node> nq = new ArrayDeque<>(); while (!q.isEmpty()) { DGourmetChoice.Node node = q.poll(); node.order = cur; for (DGourmetChoice.Node next : node.adj) { if (next.valid && --next.incoming == 0) { nq.offer(next); } } } cur++; q = nq; } for (int i = 0; i < n + m; i++) { if (nodes[i].valid && nodes[i].incoming != 0) { //System.out.println("INCOMING 0 NODE " + i); out.noln(); return; } } int[] ansA = new int[n], ansB = new int[m]; int[] order = new int[n + m + 1]; out.yesln(); for (int i = 0; i < n; i++) { out.ans(nodes[uf.find(i)].order); } out.ln(); for (int i = 0; i < m; i++) { out.ans(nodes[uf.find(n + i)].order); } out.ln(); } private static class Node { int index; int incoming; boolean valid; int order = 0; List<DGourmetChoice.Node> adj = new ArrayList<>(); Node(int index) { this.index = index; } } } static class LightScanner { private BufferedReader reader = null; private StringTokenizer tokenizer = null; public LightScanner(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); } public String string() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new UncheckedIOException(e); } } return tokenizer.nextToken(); } public int ints() { return Integer.parseInt(string()); } } static final class IntUnionFind { private int groups; private final int[] nodes; private final int[] rank; public IntUnionFind(int n) { groups = n; nodes = new int[n]; Arrays.fill(nodes, -1); rank = new int[n]; } public int find(int i) { int ans = nodes[i]; if (ans < 0) { return i; } else { return nodes[i] = find(ans); } } public boolean union(int x, int y) { x = find(x); y = find(y); if (x == y) { return false; } else if (rank[x] < rank[y]) { nodes[y] += nodes[x]; nodes[x] = y; } else if (rank[x] == rank[y]) { rank[x]++; nodes[x] += nodes[y]; nodes[y] = x; } else { nodes[x] += nodes[y]; nodes[y] = x; } groups--; return true; } } static class LightWriter implements AutoCloseable { private final Writer out; private boolean autoflush = false; private boolean breaked = true; private LightWriter.BoolLabel boolLabel = LightWriter.BoolLabel.YES_NO_FIRST_UP; public LightWriter(Writer out) { this.out = out; } public LightWriter(OutputStream out) { this(new BufferedWriter(new OutputStreamWriter(out, Charset.defaultCharset()))); } public LightWriter print(char c) { try { out.write(c); breaked = false; } catch (IOException ex) { throw new UncheckedIOException(ex); } return this; } public LightWriter print(String s) { try { out.write(s, 0, s.length()); breaked = false; } catch (IOException ex) { throw new UncheckedIOException(ex); } return this; } public LightWriter ans(String s) { if (!breaked) { print(' '); } return print(s); } public LightWriter ans(int i) { return ans(Integer.toString(i)); } public LightWriter ans(boolean b) { return ans(boolLabel.transfer(b)); } public LightWriter yesln() { return ans(true).ln(); } public LightWriter noln() { return ans(false).ln(); } public LightWriter ln() { print(System.lineSeparator()); breaked = true; if (autoflush) { try { out.flush(); } catch (IOException ex) { throw new UncheckedIOException(ex); } } return this; } public void close() { try { out.close(); } catch (IOException ex) { throw new UncheckedIOException(ex); } } public enum BoolLabel { YES_NO_FIRST_UP("Yes", "No"), YES_NO_ALL_UP("YES", "NO"), YES_NO_ALL_DOWN("yes", "no"), Y_N_ALL_UP("Y", "N"), POSSIBLE_IMPOSSIBLE_FIRST_UP("Possible", "Impossible"), POSSIBLE_IMPOSSIBLE_ALL_UP("POSSIBLE", "IMPOSSIBLE"), POSSIBLE_IMPOSSIBLE_ALL_DOWN("possible", "impossible"), FIRST_SECOND_FIRST_UP("First", "Second"), FIRST_SECOND_ALL_UP("FIRST", "SECOND"), FIRST_SECOND_ALL_DOWN("first", "second"), ALICE_BOB_FIRST_UP("Alice", "Bob"), ALICE_BOB_ALL_UP("ALICE", "BOB"), ALICE_BOB_ALL_DOWN("alice", "bob"), ; private final String positive; private final String negative; BoolLabel(String positive, String negative) { this.positive = positive; this.negative = negative; } private String transfer(boolean f) { return f ? positive : negative; } } } }
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 = 2005; int id[MAXN]; int cnt[MAXN]; vector<int> graph[MAXN]; int outDegree[MAXN]; int n, m; char str[MAXN][MAXN]; bool vis[MAXN]; int value[MAXN]; int findRoot(int a) { if (id[a] == a) { return a; } return id[a] = findRoot(id[a]); } void unite(int a, int b) { int ra = findRoot(a), rb = findRoot(b); id[rb] = ra; if (ra != rb) cnt[ra] += cnt[rb]; } int main() { scanf("%d%d", &n, &m); for (int i = 1; i <= m; i++) { id[i] = i; cnt[i] = 1; } for (int i = 1; i <= n; i++) { id[i + m] = i + m; cnt[i + m] = 1; } for (int i = 1; i <= n; i++) { scanf("%s", str[i] + 1); for (int j = 1; j <= m; j++) { if (str[i][j] == '=') { unite(i + m, j); } } } bool yes = true; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { int ri = findRoot(i + m), rj = findRoot(j); if (str[i][j] != '=' && ri == rj) { yes = false; } if (str[i][j] == '>') { graph[rj].push_back(ri); outDegree[ri]++; } else if (str[i][j] == '<') { graph[ri].push_back(rj); outDegree[rj]++; } } } int sum = 0; queue<int> que; for (int i = 1; i <= n + m; i++) { int rt = findRoot(i); if (!vis[rt] && outDegree[rt] == 0) { vis[rt] = true; que.push(rt); sum += cnt[rt]; value[rt] = 1; } } while (!que.empty()) { int u = que.front(); que.pop(); for (int i = 0; i < graph[u].size(); i++) { int v = graph[u][i]; value[v] = max(value[v], value[u] + 1); outDegree[v]--; if (outDegree[v] == 0) { que.push(v); sum += cnt[v]; } } } if (n + m != sum) { yes = false; } if (!yes) { puts("No"); } else { puts("Yes"); for (int i = 1; i <= n; i++) { printf("%d ", value[findRoot(i + m)]); } putchar('\n'); for (int i = 1; i <= m; i++) { printf("%d ", value[findRoot(i)]); } putchar('\n'); } return 0; }
CPP
1131_D. Gourmet choice
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer. Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes. The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n × m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=". Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same. Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible. Input The first line contains integers n and m (1 ≤ n, m ≤ 1000) — the number of dishes in both days. Each of the next n lines contains a string of m symbols. The j-th symbol on i-th line is a_{ij}. All strings consist only of "<", ">" and "=". Output The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print n integers — evaluations of dishes from the first set, and on the third line print m integers — evaluations of dishes from the second set. Examples Input 3 4 &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; Output Yes 2 2 2 1 1 1 1 Input 3 3 &gt;&gt;&gt; &lt;&lt;&lt; &gt;&gt;&gt; Output Yes 3 1 3 2 2 2 Input 3 2 == =&lt; == Output No Note In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be 2, for all dishes of the first day. In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.
2
10
#include <bits/stdc++.h> using namespace std; const int maxn = 1111; struct Edge { int to, next, val; }; Edge edge[maxn * maxn]; int head[maxn << 1], vis[maxn << 1], dis[maxn << 1], cnt; int fin[maxn << 1]; int n, m; int f[maxn << 1]; int find(int x) { return x == f[x] ? x : f[x] = find(f[x]); } void merge(int x, int y) { x = find(x); y = find(y); f[y] = x; } void init() { memset(head, -1, sizeof(head)); memset(vis, 0, sizeof(vis)); memset(fin, 0, sizeof(fin)); for (int i = 1; i <= n + m; i++) f[i] = i, dis[i] = 1; cnt = 0; } void addedge(int u, int v, int val) { edge[cnt].to = v; edge[cnt].val = val; edge[cnt].next = head[u]; head[u] = cnt++; } char s[maxn][maxn]; int main() { while (scanf("%d%d", &n, &m) == 2) { init(); bool judge = 1; 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] == '=') merge(i, j + n); for (int i = 1; judge && i <= n; i++) for (int j = 1; judge && j <= m; j++) { int fi = find(i); int fj = find(j + n); if (s[i][j] == '<') { if (fi == fj) { judge = 0; break; } else { addedge(fi, fj, 1); fin[fj]++; } } else if (s[i][j] == '>') { if (fi == fj) { judge = 0; break; } else { addedge(fj, fi, 1); fin[fi]++; } } } if (!judge) { printf("No\n"); continue; } queue<int> q; for (int i = 1; i <= n + m; i++) { int v = find(i); if (vis[v]) { vis[i] = 1; continue; } if (!fin[v]) q.push(v); vis[i] = vis[v] = 1; } while (!q.empty()) { int v = q.front(); q.pop(); for (int i = head[v]; i + 1; i = edge[i].next) { int to = edge[i].to; fin[to]--; if (!fin[to]) { q.push(to); dis[to] = dis[v] + 1; } } } for (int i = 1; i <= m + n; i++) if (fin[i]) { judge = 0; break; } if (!judge) printf("No\n"); else { for (int i = 1; i <= n + m; i++) dis[i] = dis[find(i)]; printf("Yes\n"); printf("%d", dis[1]); for (int i = 2; i <= n; i++) printf(" %d", dis[i]); printf("\n%d", dis[n + 1]); for (int i = n + 2; i <= n + m; i++) printf(" %d", dis[i]); printf("\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 const N = 3e5 + 2, oo = 1e9; long long const OO = 2e18; double const eps = 1e-8, PI = acos(-1); int mod = oo + 7; string aa[1001]; int lar[2][1001], eq[2][1001], er[2][1001], val[2][1001]; int main() { ios::sync_with_stdio(0); cin.tie(0); int now = 1; int n, m; cin >> n >> m; for (int i = 0; i < n; i++) { cin >> aa[i]; for (int j = 0; j < m; j++) { lar[0][i] += aa[i][j] == '<'; eq[0][i] += aa[i][j] == '='; lar[1][j] += aa[i][j] == '>'; eq[1][j] += aa[i][j] == '='; } } int rn = n, rm = m; while (rn || rm) { vector<pair<int, int> > ssm[2]; int cnt = 0; for (int i = 0; i < n; i++) if (!er[0][i] && lar[0][i] + eq[0][i] == rm) ssm[0].push_back({lar[0][i], i}); for (int i = 0; i < m; i++) if (!er[1][i] && lar[1][i] + eq[1][i] == rn) ssm[1].push_back({lar[1][i], i}); sort(ssm[0].begin(), ssm[0].end(), greater<pair<int, int> >()); sort(ssm[1].begin(), ssm[1].end(), greater<pair<int, int> >()); for (int i = 0; i < ssm[0].size(); i++) { if (i && ssm[0][i].first != ssm[0][i - 1].first) break; int v = ssm[0][i].second; er[0][v] = 1; val[0][v] = now; cnt++; rn--; } for (int i = 0; i < ssm[1].size(); i++) { if (i && ssm[1][i].first != ssm[1][i - 1].first) break; int v = ssm[1][i].second; er[1][v] = 1; val[1][v] = now; cnt++; rm--; } now++; if (!cnt) break; } if (rn || rm) { cout << "No\n"; return 0; } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (aa[i][j] == '>') { if (val[0][i] > val[1][j]) continue; cout << "No\n"; return 0; } else if (aa[i][j] == '<') { if (val[0][i] < val[1][j]) continue; cout << "No\n"; return 0; } else { if (val[0][i] == val[1][j]) continue; cout << "No\n"; return 0; } assert(val[1][j] > 0); } assert(val[0][i] > 0); } cout << "Yes\n"; for (int i = 0; i < n; i++) cout << val[0][i] << ' '; cout << '\n'; for (int i = 0; i < m; i++) cout << val[1][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
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