text
stringlengths
424
69.5k
### Prompt Please formulate a CPP solution to the following problem: After finishing eating her bun, Alyona came up with two integers n and m. She decided to write down two columns of integers — the first column containing integers from 1 to n and the second containing integers from 1 to m. Now the girl wants to count how many pairs of integers she can choose, one from the first column and the other from the second column, such that their sum is divisible by 5. Formally, Alyona wants to count the number of pairs of integers (x, y) such that 1 ≤ x ≤ n, 1 ≤ y ≤ m and <image> equals 0. As usual, Alyona has some troubles and asks you to help. Input The only line of the input contains two integers n and m (1 ≤ n, m ≤ 1 000 000). Output Print the only integer — the number of pairs of integers (x, y) such that 1 ≤ x ≤ n, 1 ≤ y ≤ m and (x + y) is divisible by 5. Examples Input 6 12 Output 14 Input 11 14 Output 31 Input 1 5 Output 1 Input 3 8 Output 5 Input 5 7 Output 7 Input 21 21 Output 88 Note Following pairs are suitable in the first sample case: * for x = 1 fits y equal to 4 or 9; * for x = 2 fits y equal to 3 or 8; * for x = 3 fits y equal to 2, 7 or 12; * for x = 4 fits y equal to 1, 6 or 11; * for x = 5 fits y equal to 5 or 10; * for x = 6 fits y equal to 4 or 9. Only the pair (1, 4) is suitable in the third sample case. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { long long n, m, a = 0, b = 0, c = 0, d = 0, e = 0; cin >> n >> m; long long kalo1 = 0; if (m >= 4 && n >= 1) { kalo1 = 1 + (m - 4) / 5; } long long kalo2 = 0; if (m >= 3 && n >= 2) { kalo2 = 1 + (m - 3) / 5; } long long kalo3 = 0; if (m >= 2 && n >= 3) { kalo3 = 1 + (m - 2) / 5; } long long kalo4 = 0; if (m >= 1 && n >= 4) { kalo4 = 1 + (m - 1) / 5; } long long kalo5 = 0; if (m >= 5 && n >= 5) { kalo5 = 1 + (m - 5) / 5; } for (long long i = 1; i <= n; i++) { if (i % 5 == 1) { a++; } else if (i % 5 == 2) { b++; } else if (i % 5 == 3) { c++; } else if (i % 5 == 4) { d++; } else if (i % 5 == 0) { e++; } } cout << a * kalo1 + b * kalo2 + c * kalo3 + d * kalo4 + e * kalo5; return 0; } ```
### Prompt Please create a solution in Cpp to the following problem: In this problem you will meet the simplified model of game Pudding Monsters. An important process in developing any game is creating levels. A game field in Pudding Monsters is an n × n rectangular grid, n of its cells contain monsters and some other cells contain game objects. The gameplay is about moving the monsters around the field. When two monsters are touching each other, they glue together into a single big one (as they are from pudding, remember?). <image> Statistics showed that the most interesting maps appear if initially each row and each column contains exactly one monster and the rest of map specifics is set up by the correct positioning of the other game objects. A technique that's widely used to make the development process more efficient is reusing the available resources. For example, if there is a large n × n map, you can choose in it a smaller k × k square part, containing exactly k monsters and suggest it as a simplified version of the original map. You wonder how many ways there are to choose in the initial map a k × k (1 ≤ k ≤ n) square fragment, containing exactly k pudding monsters. Calculate this number. Input The first line contains a single integer n (1 ≤ n ≤ 3 × 105) — the size of the initial field. Next n lines contain the coordinates of the cells initially containing monsters. The i-th of the next lines contains two numbers ri, ci (1 ≤ ri, ci ≤ n) — the row number and the column number of the cell that initially contains the i-th monster. It is guaranteed that all ri are distinct numbers and all ci are distinct numbers. Output Print the number of distinct square fragments of the original field that can form a new map. Examples Input 5 1 1 4 3 3 2 2 4 5 5 Output 10 ### Response ```cpp #include <bits/stdc++.h> long long ans = 0; int n, a[300005]; int mx[300005], mi[300005]; std::map<int, int> mp; inline void cdq(int l, int r) { if (l == r) return ++ans, void(); int mid = l + r >> 1; cdq(l, mid), cdq(mid + 1, r); mx[mid] = mi[mid] = a[mid]; mx[mid + 1] = mi[mid + 1] = a[mid + 1]; for (int i = mid - 1, iend = l; i >= iend; --i) { mx[i] = std::max(a[i], mx[i + 1]); mi[i] = std::min(a[i], mi[i + 1]); } for (int i = mid + 2, iend = r; i <= iend; ++i) { mx[i] = std::max(a[i], mx[i - 1]); mi[i] = std::min(a[i], mi[i - 1]); } for (int i = mid, iend = l; i >= iend; --i) { int pos = mx[i] - mi[i] + i; if (!(pos > mid && pos <= r)) continue; if (mx[pos] < mx[i] && mi[pos] > mi[i]) ++ans; } for (int i = mid + 1, iend = r; i <= iend; ++i) { int pos = i - mx[i] + mi[i]; if (!(pos <= mid && pos >= l)) continue; if (mx[pos] < mx[i] && mi[pos] > mi[i]) ++ans; } int x, y; x = mid + 1, y = mid + 1; mp.clear(); for (int i = mid, iend = l; i >= iend; --i) { while (y <= r && mi[y] > mi[i]) { ++mp[mx[y] - y]; ++y; } while (x < y && mx[x] < mx[i]) { --mp[mx[x] - x]; ++x; } ans += mp[mi[i] - i]; } x = mid, y = mid; mp.clear(); for (int i = mid + 1, iend = r; i <= iend; ++i) { while (y >= l && mi[y] > mi[i]) { ++mp[mx[y] + y]; --y; } while (x > y && mx[x] < mx[i]) { --mp[mx[x] + x]; --x; } ans += mp[mi[i] + i]; } } int main() { std::ios::sync_with_stdio(0), std::cin.tie(0), std::cout.tie(0); std::cin >> n; for (int i = 1, iend = n; i <= iend; ++i) { int x, y; std::cin >> x >> y; a[x] = y; } cdq(1, n); std::cout << ans << '\n'; return 0; } ```
### Prompt Please provide a cpp coded solution to the problem described below: Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order. After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical! She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order. Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: si ≠ ti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet. Input The first line contains an integer n (1 ≤ n ≤ 100): number of names. Each of the following n lines contain one string namei (1 ≤ |namei| ≤ 100), the i-th name. Each name contains only lowercase Latin letters. All names are different. Output If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'–'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on). Otherwise output a single word "Impossible" (without quotes). Examples Input 3 rivest shamir adleman Output bcdefghijklmnopqrsatuvwxyz Input 10 tourist petr wjmzbmr yeputons vepifanov scottwu oooooooooooooooo subscriber rowdark tankengineer Output Impossible Input 10 petr egor endagorion feferivan ilovetanyaromanova kostka dmitriyh maratsnowbear bredorjaguarturnik cgyforever Output aghjlnopefikdmbcqrstuvwxyz Input 7 car care careful carefully becarefuldontforgetsomething otherwiseyouwillbehacked goodluck Output acbdefhijklmnogpqrstuvwxyz ### Response ```cpp #include <bits/stdc++.h> using namespace std; long long mod = 10e9 + 7; long long gcd(long long a, long long b) { if (b == 0) return a; else return gcd(b, a % b); } long long modularExp(long long x, long long n, long long mod) { long long result = 1; while (n > 0) { if (n % 2 == 1) result = (result * x) % mod; x = ((x % mod) * (x % mod)) % mod; n = n / 2; } return (result) % mod; } bool isPrime(long long n) { for (long long i = 2; i * i <= n; i++) if (n % i == 0) return false; return true; } vector<long long> v[26], visited(26, 0), indeg(26, 0), recstack(26, 0); bool dfs(long long x) { visited[x] = 1; recstack[x] = 1; long long i; for (i = 0; i < v[x].size(); i++) { if (!visited[v[x][i]] && dfs(v[x][i])) return true; else if (recstack[v[x][i]]) return true; } recstack[x] = 0; return false; } int main() { long long n; cin >> n; long long i, j, k; vector<string> list(n + 1); for (i = 1; i <= n; i++) cin >> list[i]; for (i = 1; i <= n - 1; i++) { string s = list[i]; string t = list[i + 1]; j = 0, k = 0; long long flag = 0; while (j < s.length() && k < t.length()) { if (s[j] != t[k]) { long long c1 = s[j] - 'a'; long long c2 = t[k] - 'a'; indeg[c2] += 1; v[c1].push_back(c2); flag = 1; break; } j++; k++; } if (flag == 0 && s.length() > t.length()) { cout << "Impossible"; return 0; } } for (i = 0; i < 26; i++) { if (!visited[i]) { if (dfs(i)) { cout << "Impossible\n"; return 0; } } } for (i = 0; i < 26; i++) visited[i] = 0; queue<long long> q; for (i = 0; i < 26; i++) if (indeg[i] == 0) { q.push(i); visited[i] = 1; } vector<long long> ans; while (!q.empty()) { long long top = q.front(); q.pop(); ans.push_back(top); for (i = 0; i < v[top].size(); i++) { indeg[v[top][i]] -= 1; if (indeg[v[top][i]] == 0) { q.push(v[top][i]); visited[v[top][i]] = 1; } } } for (i = 0; i < ans.size(); i++) { char c = ans[i] + 'a'; cout << c; } } ```
### Prompt Your task is to create a cpp solution to the following problem: You have unweighted tree of n vertices. You have to assign a positive weight to each edge so that the following condition would hold: * For every two different leaves v_{1} and v_{2} of this tree, [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of weights of all edges on the simple path between v_{1} and v_{2} has to be equal to 0. Note that you can put very large positive integers (like 10^{(10^{10})}). It's guaranteed that such assignment always exists under given constraints. Now let's define f as the number of distinct weights in assignment. <image> In this example, assignment is valid, because bitwise XOR of all edge weights between every pair of leaves is 0. f value is 2 here, because there are 2 distinct edge weights(4 and 5). <image> In this example, assignment is invalid, because bitwise XOR of all edge weights between vertex 1 and vertex 6 (3, 4, 5, 4) is not 0. What are the minimum and the maximum possible values of f for the given tree? Find and print both. Input The first line contains integer n (3 ≤ n ≤ 10^{5}) — the number of vertices in given tree. The i-th of the next n-1 lines contains two integers a_{i} and b_{i} (1 ≤ a_{i} < b_{i} ≤ n) — it means there is an edge between a_{i} and b_{i}. It is guaranteed that given graph forms tree of n vertices. Output Print two integers — the minimum and maximum possible value of f can be made from valid assignment of given tree. Note that it's always possible to make an assignment under given constraints. Examples Input 6 1 3 2 3 3 4 4 5 5 6 Output 1 4 Input 6 1 3 2 3 3 4 4 5 4 6 Output 3 3 Input 7 1 2 2 7 3 4 4 7 5 6 6 7 Output 1 6 Note In the first example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum. <image> In the second example, possible assignments for each minimum and maximum are described in picture below. The f value of valid assignment of this tree is always 3. <image> In the third example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum. <image> ### Response ```cpp #include <bits/stdc++.h> using namespace std; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); int N; vector<int> adj[100001]; bool odd = false; bool e[100001], o[100001]; void dfs(int node, int par) { for (int x : adj[node]) { if (x != par) { dfs(x, node); if (o[x]) e[node] = true; if (e[x]) o[node] = true; } } if (adj[node].size() == 1) e[node] = true; if (e[node] && o[node]) odd = true; } int main() { cin >> N; for (int i = 1; i < N; i++) { int a, b; cin >> a >> b; adj[a].push_back(b); adj[b].push_back(a); } dfs(1, 1); int sub = 0; for (int i = 1; i <= N; i++) { int cnt = 0; for (int x : adj[i]) if (adj[x].size() == 1) cnt++; if (cnt >= 2) sub += cnt - 1; } if (odd) cout << 3 << ' ' << N - 1 - sub << endl; else cout << 1 << ' ' << N - 1 - sub << endl; return 0; } ```
### Prompt Generate a Cpp solution to the following problem: Given is a string S consisting of `0` and `1`. Find the number of strings, modulo 998244353, that can result from applying the following operation on S zero or more times: * Remove the two characters at the beginning of S, erase one of them, and reinsert the other somewhere in S. This operation can be applied only when S has two or more characters. Constraints * 1 \leq |S| \leq 300 * S consists of `0` and `1`. Input Input is given from Standard Input in the following format: S Output Print the number of strings, modulo 998244353, that can result from applying the operation on S zero or more times. Examples Input 0001 Output 8 Input 110001 Output 24 Input 11101111011111000000000110000001111100011111000000001111111110000000111111111 Output 697354558 ### Response ```cpp #include<bits/stdc++.h> using namespace std; const int mod=998244353; char s[333]; int n,suf0[333],suf1[333],arr[333],mx[333][333],num[333][333][333],ans; bool dp[333][333][333]; void upd(int &x,int y) { if (x<y) x=y; } void add(int &x,int y) { x+=y; if (x>=mod) x-=mod; } int main() { scanf("%s",s);n=strlen(s); for (int i=1;i<=n;i++) arr[i]=s[i-1]-'0'; for (int i=n;i>=1;i--) { suf0[i]=suf0[i+1]+(arr[i]==0); suf1[i]=suf1[i+1]+(arr[i]==1); } dp[0][0][1]=1; for (int k=1;k<=n+1;k++) { for (int i=n;i>=0;i--) { for (int j=n;j>=0;j--) { if (!dp[i][j][k]) continue; if (arr[k]==1 || arr[k+1]==1) dp[i][j+1][k+2]=1; if (arr[k]==0 || arr[k+1]==0) dp[i+1][j][k+2]=1; dp[i][j][k+1]=1; if (arr[k]==1 && i) dp[i-1][j+1][k+1]=1; if (arr[k]==0 && j) dp[i+1][j-1][k+1]=1; if (i) dp[i-1][j][k]=1; if (j) dp[i][j-1][k]=1; } } } memset(mx,-1,sizeof(mx)); for (int i=0;i<=n;i++) { for (int j=0;j<=n;j++) { for (int k=1;k<=n+1;k++) { if (dp[i][j][k]) { upd(mx[i+suf0[k]][j+suf1[k]],k); } } } } num[0][0][n]=1; for (int i=0;i<=n;i++) { for (int j=0;j<=n;j++) { add(num[i+1][j][0],num[i][j][0]); add(num[i][j+1][0],num[i][j][0]); for (int k=1;k<=n;k++) { if (arr[k]) { add(num[i+1][j][k],num[i][j][k]); add(num[i][j+1][k-1],num[i][j][k]); } else { add(num[i+1][j][k-1],num[i][j][k]); add(num[i][j+1][k],num[i][j][k]); } } } } for (int i=0;i<=n;i++) { for (int j=0;j<=n;j++) { if (!i && !j) continue; for (int k=0;k<=n;k++) { if (k<mx[i][j]) { if (num[i][j][k]) { add(ans,num[i][j][k]); } } } } } printf("%d\n",ans); return 0; } ```
### Prompt Please create a solution in CPP to the following problem: A median in an array with the length of n is an element which occupies position number <image> after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17. We define an expression <image> as the integer part of dividing number a by number b. One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x. Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need. Input The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different. Output Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x. Examples Input 3 10 10 20 30 Output 1 Input 3 4 1 2 3 Output 4 Note In the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position <image>, that is, 10. In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4. ### Response ```cpp #include <bits/stdc++.h> using namespace std; void init() { freopen("input.txt", "r", stdin); } int main() { int n, x; cin >> n >> x; vector<int> arr(n); for (int i = 0; i < n; ++i) { cin >> arr[i]; } sort(arr.begin(), arr.end()); int ans = 0; while (arr[(n - 1) / 2] != x) { arr.push_back(x); sort(arr.begin(), arr.end()); ++ans; ++n; } cout << ans; return 0; } ```
### Prompt Your challenge is to write a cpp solution to the following problem: Andrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players. Given a group of n non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns. On his step player must add a single letter in the end of the word, the resulting word must be prefix of at least one string from the group. A player loses if he cannot move. Andrew and Alex decided to play this game k times. The player who is the loser of the i-th game makes the first move in the (i + 1)-th game. Guys decided that the winner of all games is the player who wins the last (k-th) game. Andrew and Alex already started the game. Fedor wants to know who wins the game if both players will play optimally. Help him. Input The first line contains two integers, n and k (1 ≤ n ≤ 105; 1 ≤ k ≤ 109). Each of the next n lines contains a single non-empty string from the given group. The total length of all strings from the group doesn't exceed 105. Each string of the group consists only of lowercase English letters. Output If the player who moves first wins, print "First", otherwise print "Second" (without the quotes). Examples Input 2 3 a b Output First Input 3 1 a b c Output First Input 1 2 ab Output Second ### Response ```cpp #include <bits/stdc++.h> using namespace std; std::vector<std::string> alph; class IAlphabet { public: virtual int encode(char symbol) = 0; virtual char decode(int code) = 0; virtual int size() = 0; }; class alphabet_eng : public IAlphabet { public: virtual int encode(char symbol); virtual char decode(int code); virtual int size() { return 26; }; }; int alphabet_eng::encode(char symbol) { if ((symbol < 97) || (symbol >= 123)) return -1; else return (symbol - 97); } char alphabet_eng::decode(int code) { if ((code < 0) || (code >= 26)) return 0; else return (code + 97); } class VocabularyTrie { public: VocabularyTrie(IAlphabet& alphabet); VocabularyTrie(VocabularyTrie& parent); void Fill(); int GetSize(); bool m_end_of_word; IAlphabet& m_alphabet; int winner; int loser; std::vector<std::unique_ptr<VocabularyTrie>> m_children; VocabularyTrie* m_parent; }; std::set<std::pair<int, VocabularyTrie*>> proce; VocabularyTrie::VocabularyTrie(IAlphabet& alphabet) : m_end_of_word(false), m_children(alphabet.size()), m_parent(nullptr), m_alphabet(alphabet) { winner = 2; } VocabularyTrie::VocabularyTrie(VocabularyTrie& parent) : m_end_of_word(false), m_children(parent.GetSize()), m_parent(&parent), m_alphabet(parent.m_alphabet) {} int VocabularyTrie::GetSize() { return m_alphabet.size(); } void VocabularyTrie::Fill() { for (int i = 0; i < alph.size(); i++) { std::string word; word = alph[i]; VocabularyTrie* trie_ptr = this; for (int letter = 0; letter < word.length(); letter++) { int curr_letter_code = m_alphabet.encode(word[letter]); if (trie_ptr->m_children[curr_letter_code] == nullptr) { trie_ptr->m_children[curr_letter_code].reset( new VocabularyTrie(*trie_ptr)); } trie_ptr = trie_ptr->m_children[curr_letter_code].get(); } trie_ptr->m_end_of_word = true; proce.insert(std::make_pair(word.length(), trie_ptr)); } } int main() { int m, n, k; cin >> n >> k; for (int i = 0; i < n; i++) { std::string x; cin >> x; alph.push_back(x); } alphabet_eng alphabet; VocabularyTrie nn(alphabet); nn.Fill(); while (proce.size() >= 1) { auto h = proce.end(); h--; int x = h->first; VocabularyTrie* y = h->second; proce.erase(std::make_pair(x, y)); int winner = 2; int loser = 1; for (int i = 0; i < 26; i++) { if (y->m_children[i] != nullptr) loser = 2; } if (y == nullptr) continue; for (int i = 0; i < 26; i++) { if ((y->m_children[i] != nullptr) && (y->m_children[i]->winner == 2)) winner = 1; if ((y->m_children[i] != nullptr) && (y->m_children[i]->loser == 2)) loser = 1; } y->winner = winner; y->loser = loser; if (x > 0) proce.insert(std::make_pair(x - 1, y->m_parent)); } int whowins = 1; int u = nn.winner; int v = nn.loser; if (u == 2) whowins = 2; else { if (v == 1) whowins = 1; else whowins = 2 - (k % 2); } if (whowins == 2) cout << "Second"; else cout << "First"; return 0; } ```
### Prompt Develop a solution in cpp to the problem described below: A great king of a certain country suddenly decided to visit the land of a friendly country. The country is famous for trains, and the king visits various stations. There are 52 train stations, each with a single uppercase or lowercase alphabetic name (no overlapping names). The line of this train is circular, with station a next to station b, station b next to station c, then station z next to station A, then station B, and so on. Proceed in order, and after Z station, it becomes a station and returns to the original. It is a single track, and there are no trains running in the opposite direction. One day, a newspaper reporter got a list of the stations the King would visit. "DcdkIlkP ..." It is said that they will visit d station first, then c station, then d station, and so on. With this, when I thought that I could follow up on the king of a great country, I discovered something unexpected. The list was encrypted for counter-terrorism! A fellow reporter reportedly obtained the key to break the code. The reporter immediately gave him the key and started to modify the list. The key consists of a sequence of numbers. "3 1 4 5 3" This number means that the first station you visit is the one three stations before the one on the list. The station you visit second is the station in front of the second station on the list, which indicates how many stations you actually visit are in front of the stations on the list. The reporter started to fix it, but when I asked my friends what to do because the number of keys was smaller than the number of stations to visit, if you use the last key, use the first key again. It seems to be good. And the reporter was finally able to revise the list. "AbZfFijL ..." With this, there would be nothing scary anymore, and as soon as I thought so, an unexpected situation was discovered. The Great King stayed for days, and there was a list and keys for each date. The reporter was instructed by his boss to decrypt the entire list, but the amount was not enough for him alone. Your job is to help him and create a program that will automatically decrypt this list. Input The input consists of multiple datasets. The format of each data set is as follows. n k1 k2 ... kn s n is an integer representing the number of keys and can be assumed to be between 1 and 100. The following line contains a list of keys. ki indicates the i-th key. It can be assumed that it is 1 or more and 52 or less. s is a character string consisting of uppercase and lowercase letters, and indicates a list of stations to visit. It may be assumed that it is 1 or more and 100 or less. n = 0 indicates the end of input. This is not included in the dataset. Output Print the decrypted list for each dataset on one line each. Sample Input 2 1 2 bdd 3 3 2 1 DDDA Five 3 1 4 5 3 dcdkIlkP 0 Output for Sample Input abc ABCx abZfFijL Example Input 2 1 2 bdd 3 3 2 1 DDDA 5 3 1 4 5 3 dcdkIlkP 0 Output abc ABCx abZfFijL ### Response ```cpp #include<iostream> #include<cmath> #include<cstdio> #include<algorithm> #include<vector> #include<cstring> using namespace std; #define INF 999999999 int char_int(char c){ if(c >= 'a' && c <= 'z') return c - 'a'; if(c >= 'A' && c <= 'Z') return c - 'A' + 26; } char int_char(int i){ if(i < 0) i += 52; if(i > 51) i -= 52; if(i >= 0 && i <= 25) return i + 'a'; if(i >= 26 && i <= 51) return i + 'A' - 26; } int main(){ int i, j, n, k[100]; string s; while(1){ cin >> n; if(!n)break; for(i=0;i<n;i++) cin >> k[i]; for(i=n;i<100;i++) k[i] = k[i-n]; cin >> s; for(i=0;i<s.size();i++){ cout << int_char(char_int(s[i]) - k[i]); } cout << endl; } return 0; } ```
### Prompt Create a solution in cpp for the following problem: Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits. Input The first line contains integer n (2 ≤ n ≤ 100) — amount of digits in the phone number. The second line contains n digits — the phone number to divide into groups. Output Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any. Examples Input 6 549871 Output 54-98-71 Input 7 1198733 Output 11-987-33 ### Response ```cpp #include <bits/stdc++.h> using namespace std; void __print(int x) { cerr << x; } void __print(long x) { cerr << x; } void __print(long long x) { cerr << x; } void __print(unsigned x) { cerr << x; } void __print(unsigned long x) { cerr << x; } void __print(unsigned long long x) { cerr << x; } void __print(float x) { cerr << x; } void __print(double x) { cerr << x; } void __print(long double x) { cerr << x; } void __print(char x) { cerr << '\'' << x << '\''; } void __print(const char *x) { cerr << '\"' << x << '\"'; } void __print(const string &x) { cerr << '\"' << x << '\"'; } void __print(bool x) { cerr << (x ? "true" : "false"); } template <typename T, typename V> void __print(const pair<T, V> &x) { cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}'; } template <typename T> void __print(const T &x) { int f = 0; cerr << '{'; for (auto &i : x) cerr << (f++ ? "," : ""), __print(i); cerr << "}"; } void _print() { cerr << "]\n"; } template <typename T, typename... V> void _print(T t, V... v) { __print(t); if (sizeof...(v)) cerr << ", "; _print(v...); } mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); const long long INF = 1e18L; const double eps = 1e-9; const long long mod = 1e9 + 7; const double pi = 2.0 * acos(0.0); int32_t main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); ; long long n; cin >> n; string s; cin >> s; if (n == 3) { cout << s << "\n"; return 0; } if (n % 3 == 1) { for (long long i = 0; i < n - 4; i += 3) { cout << s.substr(i, 3) << "-"; } cout << s.substr(n - 4, 2) << "-"; cout << s.substr(n - 2, 2) << "\n"; return 0; } if (n % 3 == 0) { long long i; for (i = 0; i < (n / 3 - 1) * 3; i += 3) { cout << s.substr(i, 3) << "-"; } cout << s.substr(i, 3) << "\n"; return 0; } long long i; for (i = 0; i < n / 3 * 3; i += 3) { cout << s.substr(i, 3) << "-"; } cout << s.substr(i, 3) << "\n"; return 0; } ```
### Prompt Generate a cpp solution to the following problem: There is a new attraction in Singapore Zoo: The Infinite Zoo. The Infinite Zoo can be represented by a graph with an infinite number of vertices labeled 1,2,3,…. There is a directed edge from vertex u to vertex u+v if and only if u\&v=v, where \& denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). There are no other edges in the graph. Zookeeper has q queries. In the i-th query she will ask you if she can travel from vertex u_i to vertex v_i by going through directed edges. Input The first line contains an integer q (1 ≤ q ≤ 10^5) — the number of queries. The i-th of the next q lines will contain two integers u_i, v_i (1 ≤ u_i, v_i < 2^{30}) — a query made by Zookeeper. Output For the i-th of the q queries, output "YES" in a single line if Zookeeper can travel from vertex u_i to vertex v_i. Otherwise, output "NO". You can print your answer in any case. For example, if the answer is "YES", then the output "Yes" or "yeS" will also be considered as correct answer. Example Input 5 1 4 3 6 1 6 6 2 5 5 Output YES YES NO NO YES Note The subgraph on vertices 1,2,3,4,5,6 is shown below. <image> ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { int T; scanf("%d", &T); while(T--) { int u, v; scanf("%d%d", &u, &v); if(u > v) { puts("NO"); continue; } vector<int> bits[2]; auto Gao = [&](int x) { vector<int> res; for(int i = 0; i < 30; i++) if(x & (1 << i)) res.push_back(i); return res; }; bits[0] = Gao(u), bits[1] = Gao(v); if(bits[0].size() < bits[1].size()) { puts("NO"); continue; } bool flag = 1; for(int i = 0; i < bits[1].size(); i++) { if(bits[1][i] < bits[0][i]) { flag = 0; continue; } } puts(flag ? "YES" : "NO"); } return 0; } ```
### Prompt Develop a solution in CPP to the problem described below: There are N balls in the xy-plane. The coordinates of the i-th of them is (x_i, i). Thus, we have one ball on each of the N lines y = 1, y = 2, ..., y = N. In order to collect these balls, Snuke prepared 2N robots, N of type A and N of type B. Then, he placed the i-th type-A robot at coordinates (0, i), and the i-th type-B robot at coordinates (K, i). Thus, now we have one type-A robot and one type-B robot on each of the N lines y = 1, y = 2, ..., y = N. When activated, each type of robot will operate as follows. * When a type-A robot is activated at coordinates (0, a), it will move to the position of the ball on the line y = a, collect the ball, move back to its original position (0, a) and deactivate itself. If there is no such ball, it will just deactivate itself without doing anything. * When a type-B robot is activated at coordinates (K, b), it will move to the position of the ball on the line y = b, collect the ball, move back to its original position (K, b) and deactivate itself. If there is no such ball, it will just deactivate itself without doing anything. Snuke will activate some of the 2N robots to collect all of the balls. Find the minimum possible total distance covered by robots. Constraints * 1 \leq N \leq 100 * 1 \leq K \leq 100 * 0 < x_i < K * All input values are integers. Inputs Input is given from Standard Input in the following format: N K x_1 x_2 ... x_N Outputs Print the minimum possible total distance covered by robots. Examples Input 1 10 2 Output 4 Input 2 9 3 6 Output 12 Input 5 20 11 12 9 17 12 Output 74 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { int n,x,k,cnt; cin>>n>>k; for(int i=1;i<=n;i++){cin>>x;cnt+=2*min(x,k-x);} cout<<cnt<<endl; } ```
### Prompt Please create a solution in Cpp to the following problem: You have a cross-section paper with W x H squares, and each of them is painted either in white or black. You want to re-arrange the squares into a neat checkered pattern, in which black and white squares are arranged alternately both in horizontal and vertical directions (the figure shown below is a checkered patter with W = 5 and H = 5). To achieve this goal, you can perform the following two operations as many times you like in an arbitrary sequence: swapping of two arbitrarily chosen columns, and swapping of two arbitrarily chosen rows. <image> Create a program to determine, starting from the given cross-section paper, if you can re-arrange them into a checkered pattern. Input The input is given in the following format. W H c1,1 c1,2 ... c1,W c2,1 c2,2 ... c2,W : cH,1 cH,2 ... cH,W The first line provides the number of squares in horizontal direction W (2≤W≤1000) and those in vertical direction H(2≤H≤1000). Each of subsequent H lines provides an array of W integers ci,j corresponding to a square of i-th row and j-th column. The color of the square is white if ci,j is 0, and black if it is 1. Output Output "yes" if the goal is achievable and "no" otherwise. Examples Input 3 2 1 1 0 0 0 1 Output yes Input 2 2 0 0 1 1 Output no ### Response ```cpp #include "bits/stdc++.h" using namespace std; using ll = long long; template<typename T> using vec = vector<T>; template<typename T> using mat = vector<vec<T>>; template<typename T> using val = valarray<T>; using pi = pair<int,int>; #define rep(a,b) for(int a=0; a<b; ++a) #define Rep(a,b,c) for(int a=b; a<c; ++a) #define ran(a,b) for(auto &a:b) #define all(v) v.begin(),v.end() int main(){ int W, H; cin >> W >> H; vector<vector<int>> c(H, vector<int>(W)), d(W, vector<int>(H)); for(int i=0; i<H; ++i) for(int j=0; j<W; ++j) cin >> c[i][j], d[j][i] = c[i][j]; map<vector<int>,int> S; for(int i=0; i<H; ++i) { S[c[i]]++; if(S.size() > 2) { cout << "no" << endl; return 0; } } if(S.size() != 2) { cout << "no" << endl; return 0; } auto itr = S.begin(); if(itr->second == H / 2 || (++itr)->second == H / 2) { } else { cout << "no" << endl; return 0; } S.clear(); for(int i=0; i<W; ++i) { S[d[i]]++; if(S.size() > 2) { cout << "no" << endl; return 0; } } if(S.size() != 2) { cout << "no" << endl; return 0; } itr = S.begin(); if(itr->second == W / 2 || (++itr)->second == W / 2) { } else { cout << "no" << endl; return 0; } cout << "yes" << endl; } ```
### Prompt Your challenge is to write a CPP solution to the following problem: An extension of a complex number is called a quaternion. It is a convenient number that can be used to control the arm of a robot because it is convenient for expressing the rotation of an object. Quaternions are $ using four real numbers $ x $, $ y $, $ z $, $ w $ and special numbers (extended imaginary numbers) $ i $, $ j $, $ k $. It is expressed as x + yi + zj + wk $. The sum of such quaternions is defined as: $ (x_1 + y_1 i + z_1 j + w_1 k) + (x_2 + y_2 i + z_2 j + w_2 k) = (x_1 + x_2) + (y_1 + y_2) i + (z_1 + z_2) j + (w_1 + w_2) k $ On the other hand, the product between 1, $ i $, $ j $, and $ k $ is given as follows. <image> This table represents the product $ AB $ of two special numbers $ A $ and $ B $. For example, the product $ ij $ of $ i $ and $ j $ is $ k $, and the product $ ji $ of $ j $ and $ i $ is $ -k $. The product of common quaternions is calculated to satisfy this relationship. For example, the product of two quaternions, $ 1 + 2i + 3j + 4k $ and $ 7 + 6i + 7j + 8k $, is calculated as follows: $ (1 + 2i + 3j + 4k) \ times (7 + 6i + 7j + 8k) = $ $ 7 + 6i + 7j + 8k $ $ + 14i + 12i ^ 2 + 14ij + 16ik $ $ + 21j + 18ji + 21j ^ 2 + 24jk $ $ + 28k + 24ki + 28kj + 32k ^ 2 $ By applying the table above $ = -58 + 16i + 36j + 32k $ It will be. Two quaternions ($ x_1 + y_1 i + z_1 j + w_1 k $) and ($) where the four coefficients $ x $, $ y $, $ z $, $ w $ are integers and not all zeros x_2 + y_2 i + z_2 j + w_2 k $), and the product is ($ x_3 + y_3 i + z_3 j + w_3 k $), $ x_3 $, $ y_3 $, $ z_3 $, $ Create a program that outputs w_3 $. input Given multiple datasets. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format: $ n $ $ data_1 $ $ data_2 $ :: $ data_n $ The first line gives the number of pairs of quaternions to process $ n $ ($ n \ leq 10 $). The following $ n $ line is given the $ i $ th quaternion pair of information $ data_i $ in the following format: $ x_1 $ $ y_1 $ $ z_1 $ $ w_1 $ $ x_2 $ $ y_2 $ $ z_2 $ $ w_2 $ All coefficients given should be -1000 or more and 1000 or less. The number of datasets does not exceed 50. output Prints the product of a given set of quaternions for each dataset. Example Input 2 1 2 3 4 7 6 7 8 5 6 7 8 3 2 3 4 0 Output -58 16 36 32 -50 32 28 48 ### Response ```cpp #include<iostream> #define loop(i,a,b) for(int i=a;i<b;i++) #define rep(i,a) loop(i,0,a) using namespace std; int main(){ int n,a,b,c,d,e,f,g,h; while(cin>>n,n){ rep(i,n){ cin>>a>>b>>c>>d>>e>>f>>g>>h; cout<<(a*e-b*f-c*g-d*h)<<" "<<(a*f+b*e+c*h-d*g)<<" "<<(a*g-b*h+c*e+d*f)<<" "<<(a*h+b*g-c*f+d*e)<<endl; } } return 0; } ```
### Prompt In CPP, your task is to solve the following problem: Polycarpus is sure that his life fits the description: "first there is a white stripe, then a black one, then a white one again". So, Polycarpus is sure that this rule is going to fulfill during the next n days. Polycarpus knows that he is in for w good events and b not-so-good events. At least one event is going to take place during each day. As each day is unequivocally characterizes as a part of a white or a black stripe, then each day is going to have events of the same type only (ether good or not-so-good). What is the number of distinct ways this scenario can develop over the next n days if Polycarpus is in for a white stripe (a stripe that has good events only, the stripe's length is at least 1 day), the a black stripe (a stripe that has not-so-good events only, the stripe's length is at least 1 day) and a white stripe again (a stripe that has good events only, the stripe's length is at least 1 day). Each of n days will belong to one of the three stripes only. Note that even the events of the same type are distinct from each other. Even if some events occur on the same day, they go in some order (there are no simultaneous events). Write a code that prints the number of possible configurations to sort the events into days. See the samples for clarifications on which scenarios should be considered distinct. Print the answer modulo 1000000009 (109 + 9). Input The single line of the input contains integers n, w and b (3 ≤ n ≤ 4000, 2 ≤ w ≤ 4000, 1 ≤ b ≤ 4000) — the number of days, the number of good events and the number of not-so-good events. It is guaranteed that w + b ≥ n. Output Print the required number of ways modulo 1000000009 (109 + 9). Examples Input 3 2 1 Output 2 Input 4 2 2 Output 4 Input 3 2 2 Output 4 Note We'll represent the good events by numbers starting from 1 and the not-so-good events — by letters starting from 'a'. Vertical lines separate days. In the first sample the possible ways are: "1|a|2" and "2|a|1". In the second sample the possible ways are: "1|a|b|2", "2|a|b|1", "1|b|a|2" and "2|b|a|1". In the third sample the possible ways are: "1|ab|2", "2|ab|1", "1|ba|2" and "2|ba|1". ### Response ```cpp #include <bits/stdc++.h> using namespace std; long long modulo(long long base, long long exponent, long long modulus); long long choose(long long n, long long k); long long inverse(long long a, long long m); void build(); void fileio(); long long ncr(long long n, long long r); const int nax = 1e6 + 10; const int LG = log2(nax) + 1; vector<long long> fact(nax); int32_t main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); build(); long long n, w, b; cin >> n >> w >> b; long long ans = 0; for (long long i = 1; i < w; i++) { long long temp = (ncr(w, i) * fact[i]) % 1000000009; temp = (temp * fact[w - i]) % 1000000009; temp = (temp * fact[b]) % 1000000009; temp = (temp * ncr(i - 1 + w - i - 1 + b - 1, n - 3)) % 1000000009; ans = (ans + temp) % 1000000009; } cout << ans << '\n'; return 0; } long long ncr(long long n, long long r) { if (r > n || r < 0 || n < 0) return 0; long long ans = fact[n]; long long temp = (fact[n - r] * fact[r]) % 1000000009; ans = (ans * inverse(temp, 1000000009)) % 1000000009; return ans; } void fileio() { freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); } void build() { fact[0] = 1; for (long long i = 1; i < nax; i++) fact[i] = (fact[i - 1] * i) % 1000000009; } long long modulo(long long base, long long exponent, long long modulus) { if (modulus == 1) return 0; long long result = 1; base = base % modulus; while (exponent > 0) { if (exponent % 2 == 1) { result = (result * base) % modulus; } exponent = exponent >> 1; base = (base * base) % modulus; } return result; } long long choose(long long n, long long k) { if (k == 0) return 1; return (n * choose(n - 1, k - 1)) / k; } void EE(long long a, long long b, long long &co1, long long &co2) { if (a % b == 0) { co1 = 0; co2 = 1; return; } EE(b, a % b, co1, co2); long long temp = co1; co1 = co2; co2 = temp - co2 * (a / b); } long long inverse(long long a, long long m) { long long x, y; EE(a, m, x, y); if (x < 0) x += m; return x; } ```
### Prompt Your task is to create a cpp solution to the following problem: This is an easier version of the problem. In this version n ≤ 1000 The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought n plots along the highway and is preparing to build n skyscrapers, one skyscraper per plot. Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it. Formally, let's number the plots from 1 to n. Then if the skyscraper on the i-th plot has a_i floors, it must hold that a_i is at most m_i (1 ≤ a_i ≤ m_i). Also there mustn't be integers j and k such that j < i < k and a_j > a_i < a_k. Plots j and k are not required to be adjacent to i. The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors. Input The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of plots. The second line contains the integers m_1, m_2, …, m_n (1 ≤ m_i ≤ 10^9) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot. Output Print n integers a_i — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible. If there are multiple answers possible, print any of them. Examples Input 5 1 2 3 2 1 Output 1 2 3 2 1 Input 3 10 6 8 Output 10 6 6 Note In the first example, you can build all skyscrapers with the highest possible height. In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10, 6, 6] is optimal. Note that the answer of [6, 6, 8] also satisfies all restrictions, but is not optimal. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 1e5 + 144, mod = 1e9 + 7, inf = 1e9 + 7, LOG = 18; long long a[N], b[N]; long long bp(long long x, long long y) { x %= mod; if (y == 0) return 1; if (y & 1) return (x * bp(x, y - 1)) % mod; long long z = bp(x, y / 2); return (z * z) % mod; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n; cin >> n; for (int i = 1; i <= n; i++) { cin >> a[i]; } long long mx = 0, mi; for (int i = 1; i <= n; i++) { long long res = a[i]; b[i] = a[i]; for (int j = i - 1; j >= 1; j--) { b[j] = min(b[j + 1], a[j]); res += b[j]; } for (int j = i + 1; j <= n; j++) { b[j] = min(b[j - 1], a[j]); res += b[j]; } if (res > mx) { mx = res; mi = i; } } b[mi] = a[mi]; for (int j = mi - 1; j >= 1; j--) b[j] = min(b[j + 1], a[j]); for (int j = mi + 1; j <= n; j++) b[j] = min(b[j - 1], a[j]); for (int i = 1; i <= n; i++) cout << b[i] << " "; return 0; } ```
### Prompt Please formulate a Cpp solution to the following problem: Vasya is interested in arranging dominoes. He is fed up with common dominoes and he uses the dominoes of different heights. He put n dominoes on the table along one axis, going from left to right. Every domino stands perpendicular to that axis so that the axis passes through the center of its base. The i-th domino has the coordinate xi and the height hi. Now Vasya wants to learn for every domino, how many dominoes will fall if he pushes it to the right. Help him do that. Consider that a domino falls if it is touched strictly above the base. In other words, the fall of the domino with the initial coordinate x and height h leads to the fall of all dominoes on the segment [x + 1, x + h - 1]. <image> Input The first line contains integer n (1 ≤ n ≤ 105) which is the number of dominoes. Then follow n lines containing two integers xi and hi ( - 108 ≤ xi ≤ 108, 2 ≤ hi ≤ 108) each, which are the coordinate and height of every domino. No two dominoes stand on one point. Output Print n space-separated numbers zi — the number of dominoes that will fall if Vasya pushes the i-th domino to the right (including the domino itself). Examples Input 4 16 5 20 5 10 10 18 2 Output 3 1 4 1 Input 4 0 10 1 5 9 10 15 10 Output 4 1 2 1 ### Response ```cpp #include <bits/stdc++.h> using namespace std; struct Domino { int coordinate, height, input_index; }; template <size_t Size> class Segment_Tree { protected: array<int, 4 * Size> segment_tree; int ceil_log(const int &number) { int result = 0; for (int power_of_two = 1; power_of_two < number; power_of_two <<= 1, ++result) ; return result; } int leaf_to_index(const int &leaf) { return (1 << (height - 1)) - 1 + leaf; } int parent(const int &index) { return index / 2; } int left_child(const int &index) { return index * 2; } int right_child(const int &index) { return index * 2 + 1; } public: int height = ceil_log(Size) + 1; Segment_Tree() { for (int depth = 1; depth <= height; ++depth) for (int index = 1 << (depth - 1); index < 1 << depth; ++index) segment_tree[index] = 0; } void set(const int &leaf, const int &value) { segment_tree[leaf_to_index(leaf)] = value; for (int index = parent(leaf_to_index(leaf)); index >= 1; index = parent(index)) segment_tree[index] = max(segment_tree[left_child(index)], segment_tree[right_child(index)]); } int get(const int &start_leaf, const int &end_leaf) { int result = -1; int start_index, end_index; for (start_index = leaf_to_index(start_leaf), end_index = leaf_to_index(end_leaf); start_index < end_index; start_index = parent(start_index), end_index = parent(end_index)) { if (left_child(parent(start_index)) != start_index) { result = max(result, segment_tree[start_index]); ++start_index; } if (right_child(parent(end_index)) != end_index) { result = max(result, segment_tree[end_index]); --end_index; } } if (start_index == end_index) result = max(result, segment_tree[start_index]); return result; } }; const int MAX_N = 1e5; int n; array<Domino, MAX_N + 1> dominos; Segment_Tree<MAX_N> segment_tree; bool has_next(const int &index) { return index < n; } bool makes_next_to_fall(const int &index) { return dominos[index].coordinate + dominos[index].height - 1 >= dominos[index + 1].coordinate; } int farest_fallen_domino(const int &range_start, const int &range_end) { return segment_tree.get(range_start, range_end); } struct proxy { const int index; proxy(const int &index) : index(index) {} void operator=(const int &value) { segment_tree.set(index, value); } operator int() { return segment_tree.get(index, index); } }; proxy farest_fallen_domino(const int &index) { return proxy(index); } void optimize_IO() { ios_base::sync_with_stdio(false); cin.tie(nullptr); } int main() { array<int, MAX_N + 1> z; optimize_IO(); cin >> n; for (int input_index = 1; input_index <= n; ++input_index) { int x, h; cin >> x >> h; dominos[input_index] = {x, h, input_index}; } sort(dominos.begin() + 1, dominos.begin() + n + 1, [](const Domino &comparand, const Domino &comparator) { return comparand.coordinate < comparator.coordinate; }); for (int index = n; index >= 1; --index) { if (has_next(index) and makes_next_to_fall(index)) farest_fallen_domino(index) = farest_fallen_domino( index + 1, distance(dominos.begin() + 1, upper_bound( dominos.begin() + 1, dominos.begin() + n + 1, dominos[index].coordinate + dominos[index].height - 1, [](const int &fallen_coordinate, const Domino &domino) { return fallen_coordinate < domino.coordinate; }))); else farest_fallen_domino(index) = index; } for (int index = 1; index <= n; ++index) z[dominos[index].input_index] = farest_fallen_domino(index) - index + 1; for (int input_index = 1; input_index <= n; ++input_index) cout << z[input_index] << ' '; cout << '\n'; } ```
### Prompt Construct a CPP code solution to the problem outlined: Student Valera is an undergraduate student at the University. His end of term exams are approaching and he is to pass exactly n exams. Valera is a smart guy, so he will be able to pass any exam he takes on his first try. Besides, he can take several exams on one day, and in any order. According to the schedule, a student can take the exam for the i-th subject on the day number ai. However, Valera has made an arrangement with each teacher and the teacher of the i-th subject allowed him to take an exam before the schedule time on day bi (bi < ai). Thus, Valera can take an exam for the i-th subject either on day ai, or on day bi. All the teachers put the record of the exam in the student's record book on the day of the actual exam and write down the date of the mark as number ai. Valera believes that it would be rather strange if the entries in the record book did not go in the order of non-decreasing date. Therefore Valera asks you to help him. Find the minimum possible value of the day when Valera can take the final exam if he takes exams so that all the records in his record book go in the order of non-decreasing date. Input The first line contains a single positive integer n (1 ≤ n ≤ 5000) — the number of exams Valera will take. Each of the next n lines contains two positive space-separated integers ai and bi (1 ≤ bi < ai ≤ 109) — the date of the exam in the schedule and the early date of passing the i-th exam, correspondingly. Output Print a single integer — the minimum possible number of the day when Valera can take the last exam if he takes all the exams so that all the records in his record book go in the order of non-decreasing date. Examples Input 3 5 2 3 1 4 2 Output 2 Input 3 6 1 5 2 4 3 Output 6 Note In the first sample Valera first takes an exam in the second subject on the first day (the teacher writes down the schedule date that is 3). On the next day he takes an exam in the third subject (the teacher writes down the schedule date, 4), then he takes an exam in the first subject (the teacher writes down the mark with date 5). Thus, Valera takes the last exam on the second day and the dates will go in the non-decreasing order: 3, 4, 5. In the second sample Valera first takes an exam in the third subject on the fourth day. Then he takes an exam in the second subject on the fifth day. After that on the sixth day Valera takes an exam in the first subject. ### Response ```cpp #include <bits/stdc++.h> using namespace std; pair<int, int> c[5010]; int main() { int n; cin >> n; for (int i = 1; i <= n; i++) cin >> c[i].first >> c[i].second; sort(c + 1, c + n + 1); long long kq = 0; for (int i = 1; i <= n; i++) { if (c[i].second >= kq) kq = c[i].second; else kq = c[i].first; } cout << kq; } ```
### Prompt Generate a Cpp solution to the following problem: It is known that there are k fish species in the polar ocean, numbered from 1 to k. They are sorted by non-decreasing order of their weight, which is a positive number. Let the weight of the i-th type of fish be wi, then 0 < w1 ≤ w2 ≤ ... ≤ wk holds. Polar bears Alice and Bob each have caught some fish, and they are guessing who has the larger sum of weight of the fish he/she's caught. Given the type of the fish they've caught, determine whether it is possible that the fish caught by Alice has a strictly larger total weight than Bob's. In other words, does there exist a sequence of weights wi (not necessary integers), such that the fish caught by Alice has a strictly larger total weight? Input The first line contains three integers n, m, k (1 ≤ n, m ≤ 105, 1 ≤ k ≤ 109) — the number of fish caught by Alice and Bob respectively, and the number of fish species. The second line contains n integers each from 1 to k, the list of fish type caught by Alice. The third line contains m integers each from 1 to k, the list of fish type caught by Bob. Note that one may have caught more than one fish for a same species. Output Output "YES" (without quotes) if it is possible, and "NO" (without quotes) otherwise. Examples Input 3 3 3 2 2 2 1 1 3 Output YES Input 4 7 9 5 2 7 3 3 5 2 7 3 8 7 Output NO Note In the first sample, if w1 = 1, w2 = 2, w3 = 2.5, then Alice has a total of 2 + 2 + 2 = 6 weight units, while Bob only has 1 + 1 + 2.5 = 4.5. In the second sample, the fish that Alice caught is a subset of Bob's. Therefore, the total weight of Bob’s fish is always not less than the total weight of Alice’s fish. ### Response ```cpp #include <bits/stdc++.h> using namespace std; map<int, int> ma; map<int, int>::iterator it; int main() { int n, m, k, x, num; while (~scanf("%d%d%d", &n, &m, &k)) { ma.clear(); for (int i = 1; i <= n; i++) { scanf("%d", &x); ma[x]++; } for (int i = 1; i <= m; i++) { scanf("%d", &x); ma[x]--; } num = 0; for (it = ma.begin(); it != ma.end(); it++) { num += it->second; if (num < 0) num = 0; } if (num > 0) printf("YES\n"); else printf("NO\n"); } return 0; } ```
### Prompt Your challenge is to write a CPP solution to the following problem: There is a directed graph with N vertices and M edges. The i-th edge (1≤i≤M) points from vertex a_i to vertex b_i, and has a weight c_i. We will play the following single-player game using this graph and a piece. Initially, the piece is placed at vertex 1, and the score of the player is set to 0. The player can move the piece as follows: * When the piece is placed at vertex a_i, move the piece along the i-th edge to vertex b_i. After this move, the score of the player is increased by c_i. The player can end the game only when the piece is placed at vertex N. The given graph guarantees that it is possible to traverse from vertex 1 to vertex N. When the player acts optimally to maximize the score at the end of the game, what will the score be? If it is possible to increase the score indefinitely, print `inf`. Constraints * 2≤N≤1000 * 1≤M≤min(N(N-1),2000) * 1≤a_i,b_i≤N (1≤i≤M) * a_i≠b_i (1≤i≤M) * a_i≠a_j or b_i≠b_j (1≤i<j≤M) * -10^9≤c_i≤10^9 (1≤i≤M) * c_i is an integer. * In the given graph, there exists a path from vertex 1 to vertex N. Input Input is given from Standard Input in the following format: N M a_1 b_1 c_1 a_2 b_2 c_2 : a_M b_M c_M Output Print the maximum possible score at the end of the game, if it is finite. If it is possible to increase the score indefinitely, print `inf`. Examples Input 3 3 1 2 4 2 3 3 1 3 5 Output 7 Input 2 2 1 2 1 2 1 1 Output inf Input 6 5 1 2 -1000000000 2 3 -1000000000 3 4 -1000000000 4 5 -1000000000 5 6 -1000000000 Output -5000000000 ### Response ```cpp #include <iostream> #include <cstdio> #define N 1005 #define M 2005 using namespace std; typedef long long ll; ll n, m, a[M], b[M], c[M], d[N]; bool v = 1; int main() { ll i, j, t; cin >> n >> m; for (i = 0; i < m; i++) scanf("%lld %lld %lld", &a[i], &b[i], &c[i]); for (i = 2; i <= n; i++) d[i] = -1e18; for (i = 0; i < n - 1 && v; i++) { v = 0; for (j = 0; j < m; j++) { if (d[b[j]] < d[a[j]] + c[j]) v = 1, d[b[j]] = d[a[j]] + c[j]; } } if (v) { t = d[n]; for (i = 0; i < m; i++) { if (d[b[i]] < d[a[i]] + c[i]) d[b[i]] = d[a[i]] + c[i]; } if (t != d[n]) {cout << "inf"; return 0;} } cout << d[n]; return 0; } ```
### Prompt Your task is to create a Cpp solution to the following problem: Innopolis University scientists continue to investigate the periodic table. There are n·m known elements and they form a periodic table: a rectangle with n rows and m columns. Each element can be described by its coordinates (r, c) (1 ≤ r ≤ n, 1 ≤ c ≤ m) in the table. Recently scientists discovered that for every four different elements in this table that form a rectangle with sides parallel to the sides of the table, if they have samples of three of the four elements, they can produce a sample of the fourth element using nuclear fusion. So if we have elements in positions (r1, c1), (r1, c2), (r2, c1), where r1 ≠ r2 and c1 ≠ c2, then we can produce element (r2, c2). <image> Samples used in fusion are not wasted and can be used again in future fusions. Newly crafted elements also can be used in future fusions. Innopolis University scientists already have samples of q elements. They want to obtain samples of all n·m elements. To achieve that, they will purchase some samples from other laboratories and then produce all remaining elements using an arbitrary number of nuclear fusions in some order. Help them to find the minimal number of elements they need to purchase. Input The first line contains three integers n, m, q (1 ≤ n, m ≤ 200 000; 0 ≤ q ≤ min(n·m, 200 000)), the chemical table dimensions and the number of elements scientists already have. The following q lines contain two integers ri, ci (1 ≤ ri ≤ n, 1 ≤ ci ≤ m), each describes an element that scientists already have. All elements in the input are different. Output Print the minimal number of elements to be purchased. Examples Input 2 2 3 1 2 2 2 2 1 Output 0 Input 1 5 3 1 3 1 1 1 5 Output 2 Input 4 3 6 1 2 1 3 2 2 2 3 3 1 3 3 Output 1 Note For each example you have a picture which illustrates it. The first picture for each example describes the initial set of element samples available. Black crosses represent elements available in the lab initially. The second picture describes how remaining samples can be obtained. Red dashed circles denote elements that should be purchased from other labs (the optimal solution should minimize the number of red circles). Blue dashed circles are elements that can be produced with nuclear fusion. They are numbered in order in which they can be produced. Test 1 We can use nuclear fusion and get the element from three other samples, so we don't need to purchase anything. <image> Test 2 We cannot use any nuclear fusion at all as there is only one row, so we have to purchase all missing elements. <image> Test 3 There are several possible solutions. One of them is illustrated below. Note that after purchasing one element marked as red it's still not possible to immidiately produce the middle element in the bottom row (marked as 4). So we produce the element in the left-top corner first (marked as 1), and then use it in future fusions. <image> ### Response ```cpp #include <bits/stdc++.h> using namespace std; inline int read() { int x = 0, f = 1; char c = getchar(); for (; !isdigit(c); c = getchar()) if (c == '-') f = -1; for (; isdigit(c); c = getchar()) x = x * 10 + c - '0'; return x * f; } const int MAXN = 600010; const int INF = 2147483600; int fa[MAXN + 1]; int N, M, Q; inline int find(int x) { return x == fa[x] ? x : (fa[x] = find(fa[x])); } inline void merge(int u, int v) { int x = find(u), y = find(v); if (x == y) return; fa[y] = x; } int main() { N = read(), M = read(), Q = read(); int cnt = 0; for (int i = 1; i <= N + M; i++) fa[i] = i; for (int i = 1; i <= Q; i++) { int u = read(), v = read(); merge(u, v + N); } for (int i = 1; i <= N + M; i++) if (fa[i] == i) ++cnt; printf("%d\n", cnt - 1); return 0; } ```
### Prompt Generate a Cpp solution to the following problem: Don't put up with what you're sick of! The Smart Beaver decided to escape from the campus of Beaver Science Academy (BSA). BSA is a b × b square on a plane. Each point x, y (0 ≤ x, y ≤ b) belongs to BSA. To make the path quick and funny, the Beaver constructed a Beaveractor, an effective and comfortable types of transport. The campus obeys traffic rules: there are n arrows, parallel to the coordinate axes. The arrows do not intersect and do not touch each other. When the Beaveractor reaches some arrow, it turns in the arrow's direction and moves on until it either reaches the next arrow or gets outside the campus. The Beaveractor covers exactly one unit of space per one unit of time. You can assume that there are no obstacles to the Beaveractor. The BSA scientists want to transport the brand new Beaveractor to the "Academic Tractor" research institute and send the Smart Beaver to do his postgraduate studies and sharpen pencils. They have q plans, representing the Beaveractor's initial position (xi, yi), the initial motion vector wi and the time ti that have passed after the escape started. Your task is for each of the q plans to determine the Smart Beaver's position after the given time. Input The first line contains two integers: the number of traffic rules n and the size of the campus b, 0 ≤ n, 1 ≤ b. Next n lines contain the rules. Each line of the rules contains four space-separated integers x0, y0, x1, y1 — the beginning and the end of the arrow. It is guaranteed that all arrows are parallel to the coordinate axes and have no common points. All arrows are located inside the campus, that is, 0 ≤ x0, y0, x1, y1 ≤ b holds. Next line contains integer q — the number of plans the scientists have, 1 ≤ q ≤ 105. The i-th plan is represented by two integers, xi, yi are the Beaveractor's coordinates at the initial time, 0 ≤ xi, yi ≤ b, character wi, that takes value U, D, L, R and sets the initial direction up, down, to the left or to the right correspondingly (the Y axis is directed upwards), and ti — the time passed after the escape started, 0 ≤ ti ≤ 1015. * to get 30 points you need to solve the problem with constraints n, b ≤ 30 (subproblem D1); * to get 60 points you need to solve the problem with constraints n, b ≤ 1000 (subproblems D1+D2); * to get 100 points you need to solve the problem with constraints n, b ≤ 105 (subproblems D1+D2+D3). Output Print q lines. Each line should contain two integers — the Beaveractor's coordinates at the final moment of time for each plan. If the Smart Beaver manages to leave the campus in time ti, print the coordinates of the last point in the campus he visited. Examples Input 3 3 0 0 0 1 0 2 2 2 3 3 2 3 12 0 0 L 0 0 0 L 1 0 0 L 2 0 0 L 3 0 0 L 4 0 0 L 5 0 0 L 6 2 0 U 2 2 0 U 3 3 0 U 5 1 3 D 2 1 3 R 2 Output 0 0 0 1 0 2 1 2 2 2 3 2 3 2 2 2 3 2 1 3 2 2 1 3 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 1005; int dx[5] = {0, 1, 0, -1, 0}; int dy[5] = {0, 0, 1, 0, -1}; int n, b, q; int a[N + 5][N + 5]; int nx[N * N * 5 + 55][2]; int ans[111111]; long long t[111111]; int hash1(int x, int y, int d) { if (a[x][y]) d = a[x][y]; return d * N * N + x * N + y; } int main() { int i, j, k, x1, y1, x2, y2, d, h; char ch[5]; scanf("%d%d", &n, &b); for (i = 1; i <= n; i = i + 1) { scanf("%d%d%d%d", &x1, &y1, &x2, &y2); if (x1 == x2) { if (y1 > y2) d = 4; else d = 2; } else { if (x1 > x2) d = 3; else d = 1; } while (x1 != x2 || y1 != y2) { a[x1][y1] = d; x1 += dx[d]; y1 += dy[d]; } a[x2][y2] = d; } for (i = 0; i <= b; i = i + 1) for (j = 0; j <= b; j = j + 1) for (k = 1; k <= 4; k = k + 1) { if (a[i][j] && a[i][j] != k) continue; h = hash1(i, j, k); x1 = i + dx[k]; y1 = j + dy[k]; if (x1 < 0 || x1 > b || y1 < 0 || y1 > b) nx[h][0] = h; else nx[h][0] = hash1(x1, y1, k); } scanf("%d", &q); for (i = 1; i <= q; i = i + 1) { scanf("%d%d%s%lld", &x1, &x2, &ch, t + i); if (ch[0] == 'R') d = 1; if (ch[0] == 'U') d = 2; if (ch[0] == 'L') d = 3; if (ch[0] == 'D') d = 4; ans[i] = hash1(x1, x2, d); } for (i = 0; i <= 60; i = i + 1) { h = i & 1; for (j = 1; j <= q; j = j + 1) if (t[j] & ((long long)1 << i)) ans[j] = nx[ans[j]][h]; for (j = 1; j < N * N * 5; j = j + 1) nx[j][h ^ 1] = nx[nx[j][h]][h]; } for (i = 1; i <= q; i = i + 1) { y1 = ans[i] % N; ans[i] /= N; x1 = ans[i] % N; cout << x1 << ' ' << y1 << endl; } return 0; } ```
### Prompt Develop a solution in cpp to the problem described below: You are given N points (x_i,y_i) located on a two-dimensional plane. Consider a subset S of the N points that forms a convex polygon. Here, we say a set of points S forms a convex polygon when there exists a convex polygon with a positive area that has the same set of vertices as S. All the interior angles of the polygon must be strictly less than 180°. cddb0c267926c2add885ca153c47ad8a.png For example, in the figure above, {A,C,E} and {B,D,E} form convex polygons; {A,C,D,E}, {A,B,C,E}, {A,B,C}, {D,E} and {} do not. For a given set S, let n be the number of the points among the N points that are inside the convex hull of S (including the boundary and vertices). Then, we will define the score of S as 2^{n-|S|}. Compute the scores of all possible sets S that form convex polygons, and find the sum of all those scores. However, since the sum can be extremely large, print the sum modulo 998244353. Constraints * 1≤N≤200 * 0≤x_i,y_i<10^4 (1≤i≤N) * If i≠j, x_i≠x_j or y_i≠y_j. * x_i and y_i are integers. Input The input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_N y_N Output Print the sum of all the scores modulo 998244353. Examples Input 4 0 0 0 1 1 0 1 1 Output 5 Input 5 0 0 0 1 0 2 0 3 1 1 Output 11 Input 1 3141 2718 Output 0 ### Response ```cpp #include<bits/stdc++.h> #define Mo 998244353 #define N 500 typedef long long LL; using namespace std; int x[N], y[N], b[N], num[N], n; void prepare() { b[0] = 1; for(int i = 1; i <= n; i++) b[i] = ((LL)b[i - 1] * 2) % Mo; for(int i = 1; i <= n; i++) b[i] = (b[i] - 1 - i - i * (i - 1) / 2) % Mo; } int main() { cin >> n; for(int i = 1; i <= n; i++) cin >> x[i] >> y[i]; prepare(); for(int i = 1; i <= n; i++) for(int j = 1; j <= n; j++) { if (i == j) continue; int cnt = 2; for(int k = 1; k <= n; k++) { if (k == i || k == j) continue; if ((LL)(x[k] - x[i]) * (y[k] - y[j]) == (LL)(x[k] - x[j]) * (y[k] - y[i])) cnt++; } num[cnt]++; } for(int i = 3; i <= n; i++) num[i] = num[i] / i / (i - 1); LL ans = b[n]; for(int i = 3; i <= n; i++) ans = (ans - (LL)num[i] * b[i] % Mo) % Mo; cout << (ans % Mo + Mo) % Mo << endl; } ```
### Prompt Develop a solution in CPP to the problem described below: Fedya studies in a gymnasium. Fedya's maths hometask is to calculate the following expression: (1n + 2n + 3n + 4n) mod 5 for given value of n. Fedya managed to complete the task. Can you? Note that given number n can be extremely large (e.g. it can exceed any integer type of your programming language). Input The single line contains a single integer n (0 ≤ n ≤ 10105). The number doesn't contain any leading zeroes. Output Print the value of the expression without leading zeros. Examples Input 4 Output 4 Input 124356983594583453458888889 Output 0 Note Operation x mod y means taking remainder after division x by y. Note to the first sample: <image> ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { string s; cin >> s; int n = (int)s.length(); int m4 = 0; for (int i = 0; i < n; i++) { m4 = m4 * 10 + (s[i] - '0'); m4 %= 4; } if (m4 == 0) { cout << 4 << endl; } else { cout << 0 << endl; } return 0; } ```
### Prompt In CPP, your task is to solve the following problem: When Valera was playing football on a stadium, it suddenly began to rain. Valera hid in the corridor under the grandstand not to get wet. However, the desire to play was so great that he decided to train his hitting the ball right in this corridor. Valera went back far enough, put the ball and hit it. The ball bounced off the walls, the ceiling and the floor corridor and finally hit the exit door. As the ball was wet, it left a spot on the door. Now Valera wants to know the coordinates for this spot. Let's describe the event more formally. The ball will be considered a point in space. The door of the corridor will be considered a rectangle located on plane xOz, such that the lower left corner of the door is located at point (0, 0, 0), and the upper right corner is located at point (a, 0, b) . The corridor will be considered as a rectangular parallelepiped, infinite in the direction of increasing coordinates of y. In this corridor the floor will be considered as plane xOy, and the ceiling as plane, parallel to xOy and passing through point (a, 0, b). We will also assume that one of the walls is plane yOz, and the other wall is plane, parallel to yOz and passing through point (a, 0, b). We'll say that the ball hit the door when its coordinate y was equal to 0. Thus the coordinates of the spot are point (x0, 0, z0), where 0 ≤ x0 ≤ a, 0 ≤ z0 ≤ b. To hit the ball, Valera steps away from the door at distance m and puts the ball in the center of the corridor at point <image>. After the hit the ball flies at speed (vx, vy, vz). This means that if the ball has coordinates (x, y, z), then after one second it will have coordinates (x + vx, y + vy, z + vz). See image in notes for clarification. When the ball collides with the ceiling, the floor or a wall of the corridor, it bounces off in accordance with the laws of reflection (the angle of incidence equals the angle of reflection). In the problem we consider the ideal physical model, so we can assume that there is no air resistance, friction force, or any loss of energy. Input The first line contains three space-separated integers a, b, m (1 ≤ a, b, m ≤ 100). The first two integers specify point (a, 0, b), through which the ceiling and one of the corridor walls pass. The third integer is the distance at which Valera went away from the door. The second line has three space-separated integers vx, vy, vz (|vx|, |vy|, |vz| ≤ 100, vy < 0, vz ≥ 0) — the speed of the ball after the hit. It is guaranteed that the ball hits the door. Output Print two real numbers x0, z0 — the x and z coordinates of point (x0, 0, z0), at which the ball hits the exit door. The answer will be considered correct, if its absolute or relative error does not exceed 10 - 6. Examples Input 7 2 11 3 -11 2 Output 6.5000000000 2.0000000000 Input 7 2 11 4 -3 3 Output 4.1666666667 1.0000000000 Note <image> ### Response ```cpp #include <bits/stdc++.h> const int maxi = 2000000000; const int maxq = 1000000000; const double eps = 1e-10; const double pi = 3.1415926535897932; const double inf = 1e+18; const int mo = 1000000007; using namespace std; double a, b, m, vx, vy, vz; int main() { cin >> a >> b >> m; cin >> vx >> vy >> vz; double xs = a / 2.; double ys = m; double zs = 0; double tx = ys / fabs(vy); double tz = tx; bool flag = false; if (fabs(vx * tx) > a / 2.) { if (vx < 0) xs = 0; else xs = a; tx = tx - ((a / 2.) / fabs(vx)); flag = true; } else xs = xs + vx * tx, tx = 0; vx = fabs(vx); int tiz = int((vz * tz) / b); int tix = int((vx * tx) / a); if (vx > eps) tx = tx - (tix * a) / vx; if (vz > eps) tz = tz - (tiz * b) / vz; if (((tiz)&1)) zs = b - tz * vz; else zs = tz * vz; if (flag) { if (fabs(xs) < eps) { if (((tix)&1)) xs = a - tx * vx; else xs = tx * vx; } else { if (((tix)&1) == 0) xs = a - tx * vx; else xs = tx * vx; } } printf("%.9lf %.9lf\n", xs, zs); return 0; } ```
### Prompt Please provide a CPP coded solution to the problem described below: There are n stone quarries in Petrograd. Each quarry owns mi dumpers (1 ≤ i ≤ n). It is known that the first dumper of the i-th quarry has xi stones in it, the second dumper has xi + 1 stones in it, the third has xi + 2, and the mi-th dumper (the last for the i-th quarry) has xi + mi - 1 stones in it. Two oligarchs play a well-known game Nim. Players take turns removing stones from dumpers. On each turn, a player can select any dumper and remove any non-zero amount of stones from it. The player who cannot take a stone loses. Your task is to find out which oligarch will win, provided that both of them play optimally. The oligarchs asked you not to reveal their names. So, let's call the one who takes the first stone «tolik» and the other one «bolik». Input The first line of the input contains one integer number n (1 ≤ n ≤ 105) — the amount of quarries. Then there follow n lines, each of them contains two space-separated integers xi and mi (1 ≤ xi, mi ≤ 1016) — the amount of stones in the first dumper of the i-th quarry and the number of dumpers at the i-th quarry. Output Output «tolik» if the oligarch who takes a stone first wins, and «bolik» otherwise. Examples Input 2 2 1 3 2 Output tolik Input 4 1 1 1 1 1 1 1 1 Output bolik ### Response ```cpp #include <bits/stdc++.h> using namespace std; long long range(long long L) { switch (L & 3) { case 0: return L; case 1: return 1; case 2: return L + 1; case 3: return 0; } } int main() { for (int N; cin >> N;) { long long sum = 0; for (int i = 0; i < (int)(N); ++i) { long long m, x; cin >> x >> m; long long b = range(x - 1); long long a = range(x + m - 1); sum ^= b; sum ^= a; } if (sum == 0) cout << "bolik" << endl; else cout << "tolik" << endl; } return 0; } ```
### Prompt Create a solution in Cpp for the following problem: You're given an array a of n integers, such that a_1 + a_2 + ⋅⋅⋅ + a_n = 0. In one operation, you can choose two different indices i and j (1 ≤ i, j ≤ n), decrement a_i by one and increment a_j by one. If i < j this operation is free, otherwise it costs one coin. How many coins do you have to spend in order to make all elements equal to 0? Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 5000). Description of the test cases follows. The first line of each test case contains an integer n (1 ≤ n ≤ 10^5) — the number of elements. The next line contains n integers a_1, …, a_n (-10^9 ≤ a_i ≤ 10^9). It is given that ∑_{i=1}^n a_i = 0. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case, print the minimum number of coins we have to spend in order to make all elements equal to 0. Example Input 7 4 -3 5 -3 1 2 1 -1 4 -3 2 -3 4 4 -1 1 1 -1 7 -5 7 -6 -4 17 -13 4 6 -1000000000 -1000000000 -1000000000 1000000000 1000000000 1000000000 1 0 Output 3 0 4 1 8 3000000000 0 Note Possible strategy for the first test case: * Do (i=2, j=3) three times (free), a = [-3, 2, 0, 1]. * Do (i=2, j=1) two times (pay two coins), a = [-1, 0, 0, 1]. * Do (i=4, j=1) one time (pay one coin), a = [0, 0, 0, 0]. ### Response ```cpp #include <bits/stdc++.h> const long long M = 1e9 + 7; const long long N = 2e5 + 5; using namespace std; void solve() { long long n; cin >> n; long long a[n]; for (int i = 0; i < n; i++) cin >> a[i]; long long z = 0, ans = 0; for (int i = 0; i < n; i++) { if (a[i] > 0) { z += a[i]; } else { long long p = min(z, -1 * a[i]); a[i] += p; z -= p; ans -= a[i]; } } cout << ans << endl; } int main() { ios_base ::sync_with_stdio(false); cin.tie(NULL); long long t; cin >> t; while (t--) solve(); } ```
### Prompt In Cpp, your task is to solve the following problem: You are recording a result of a secret experiment, which consists of a large set of N-dimensional vectors. Since the result may become very large, you are thinking of compressing it. Fortunately you already have a good compression method for vectors with small absolute values, all you have to do is to preprocess the vectors and make them small. You can record the set of vectors in any order you like. Let's assume you process them in the order v_1, v_2,..., v_M. Each vector v_i is recorded either as is, or as a difference vector. When it is recorded as a difference, you can arbitrarily pick up an already chosen vector v_j (j<i) and a real value r. Then the actual vector value recorded is (v_i - r v_j). The values of r and j do not affect the compression ratio so much, so you don't have to care about them. Given a set of vectors, your task is to write a program that calculates the minimum sum of the squared length of the recorded vectors. Input The input is like the following style. N M v_{1,1} v_{1,2} ... v_{1,N} ... v_{M,1} v_{M,2} ... v_{M,N} The first line contains two integers N and M (1 \leq N, M \leq 100), where N is the dimension of each vector, and M is the number of the vectors. Each of the following M lines contains N floating point values v_{i,j} (-1.0 \leq v_{i,j} \leq 1.0) which represents the j-th element value of the i-th vector. Output Output the minimum sum of the squared length of the recorded vectors. The output should not contain an absolute error greater than 10^{-6}. Examples Input 2 3 1.0 1.0 -1.0 0.0 0.5 0.5 Output 1.0 Input 1 1 1.0 Output 1.0 Input 4 3 1.0 1.0 0.0 0.0 -1.0 0.0 -1.0 0.0 0.5 0.5 0.5 0.5 Output 3.0 ### Response ```cpp #include<bits/stdc++.h> using namespace std; typedef double ldouble; typedef vector<ldouble> Point; ldouble INF=1e9; struct UnionFind{ vector<int> par,rank; void init(int n){ par.clear(); rank.clear(); par.resize(n); rank.resize(n); for(int i=0;i<n;i++){ par[i]=i; rank[i]=1; } } int find(int x){ if(x==par[x])return x; return par[x]=find(par[x]); } bool same(int x,int y){ return ( find(x)==find(y) ); } void unite(int x,int y){ x=find(x); y=find(y); if(x==y)return; if(rank[x]<rank[y])swap(x,y); par[y]=x; rank[x]+=rank[y]; } }; struct edge{ int from; int to; ldouble cost; int id; edge(int from,int to,ldouble cost,int id) :from(from), to(to),cost(cost),id(id) {} bool operator < (const edge e)const{ return cost > e.cost; } }; typedef priority_queue< edge > prque; typedef prque* Prque; typedef vector<edge> Node; typedef vector<Node> Graph; Prque Merge(vector< Prque > &Q, vector<edge> &ev,int A,int C){ if( Q[C]->size() < Q[A]->size() ){ while( !Q[C]->empty() ){ edge e=Q[C]->top(); e.cost-=ev[C].cost; e.cost+=ev[A].cost; // cout<<e.from<<' '<<e.to<<' '<<e.cost<<' '<<ev[A].cost<<' '<<ev[C].cost<<endl; Q[A]->push(e); Q[C]->pop(); } ev[C].cost=ev[A].cost; return Q[A]; }else{ while( !Q[A]->empty() ){ edge e=Q[A]->top(); e.cost-=ev[A].cost; e.cost+=ev[C].cost; // cout<<e.from<<' '<<e.to<<' '<<e.cost<<endl; Q[C]->push(e); Q[A]->pop(); } return Q[C]; } } ldouble solve(Graph &G,vector<edge> &edges,int root){ int n=G.size(); ldouble res=0; vector<int> used(n,0); vector< edge > ev(n, (edge){0,0,0,-1} ); vector< prque > pool(n); vector< Prque > Q(n); for(int i=0;i<n;i++)Q[i]=&pool[i]; UnionFind uf; uf.init(n); for(int i=0;i<(int)edges.size();i++){ edge e=edges[i]; Q[ e.to ]->push( e ); } used[root]=2; for(int Pos=0;Pos<n;Pos++){ if(used[Pos]==2)continue; int pos=Pos; vector<int> path; while( used[pos] != 2 ){ pos=uf.find(pos); used[pos]=1; path.push_back(pos); if( Q[pos]->empty() ){ return INF; } edge e=Q[pos]->top(); Q[pos]->pop(); e.cost-=ev[pos].cost; if( uf.same(e.from,pos) ) continue; ldouble tmpcost=ev[pos].cost; /* cout<<" pos="<<pos; cout<<" e.from="<<e.from; cout<<" e.to="<<e.to; cout<<" e.cost="<<e.cost; cout<<" tmpcost="<<tmpcost<<endl; cout<<endl; */ res+=e.cost; e.cost+=tmpcost; ev[pos]=e; if( used[ uf.find(e.from) ] == 2 )break; if( used[ uf.find(e.from) ] == 0 ){ pos=e.from; continue; } int pre=uf.find(e.from); for(int i=0;i<100;i++){ if(!uf.same(pre,pos)){ int A=uf.find(pre), B=uf.find(pos); uf.unite(A,B); int C=uf.find(A); /* cout<<" !!A="<<A; cout<<" !!B="<<B; cout<<" !!C="<<C<<endl; */ Prque tmp=NULL; if(B==C)tmp=Merge(Q,ev,A,C); else if(A==C)tmp=Merge(Q,ev,B,C); else assert(0); Q[C]=tmp; } pre=uf.find(ev[pre].from); } }// while_pos for(int i=0;i<(int)path.size();i++)used[ path[i] ]=2; }// Pos return res; } Point add(Point a,Point b){ Point res(a.size()); for(int i=0;i<(int)a.size();i++) res[i]=a[i]+b[i]; return res; } Point sub(Point a,Point b){ Point res(a.size()); for(int i=0;i<(int)a.size();i++) res[i]=a[i]-b[i]; return res; } ldouble dot(Point a,Point b){ ldouble res=0; for(int i=0;i<(int)a.size();i++) res+=a[i]*b[i]; return res; } ldouble norm(Point p){ return dot(p,p); } ldouble abs(Point p){ return sqrt( norm(p) ); } double Sqrt(double x){ if(x<0)return 0; return sqrt(x); } double project(Point a,Point b){ ldouble t=dot(a,b); // cout<<a[0]<<' '<<a[1]<<endl; // cout<<b[0]<<' '<<b[1]<<endl; // cout<< dot(a,b) <<endl; return abs( norm(b) - (t*t/norm(a)) ); } int main(){ int n,m; vector< Point > t; cin>>m>>n; for(int i=0;i<n;i++){ Point a(m); for(int j=0;j<m;j++){ cin>>a[j]; } if(norm(a) < 0.00000001){ continue; } t.push_back(a); } n=t.size(); Graph G; G.resize(n+1); int cc=0; for(int i=0;i<n;i++){ G[n].push_back( edge(n,i,norm(t[i]) , cc++) ); for(int j=0;j<n;j++){ if(i==j)continue; ldouble cost=project(t[i],t[j]); G[i].push_back( edge(i,j,cost,cc++) ); } } vector<edge> edges; for(int i=0;i<=n;i++) for(int j=0;j<(int)G[i].size();j++) edges.push_back(G[i][j]); printf("%.10f\n",(double) solve(G,edges,n) ); return 0; } ```
### Prompt Create a solution in cpp for the following problem: User ainta has a permutation p1, p2, ..., pn. As the New Year is coming, he wants to make his permutation as pretty as possible. Permutation a1, a2, ..., an is prettier than permutation b1, b2, ..., bn, if and only if there exists an integer k (1 ≤ k ≤ n) where a1 = b1, a2 = b2, ..., ak - 1 = bk - 1 and ak < bk all holds. As known, permutation p is so sensitive that it could be only modified by swapping two distinct elements. But swapping two elements is harder than you think. Given an n × n binary matrix A, user ainta can swap the values of pi and pj (1 ≤ i, j ≤ n, i ≠ j) if and only if Ai, j = 1. Given the permutation p and the matrix A, user ainta wants to know the prettiest permutation that he can obtain. Input The first line contains an integer n (1 ≤ n ≤ 300) — the size of the permutation p. The second line contains n space-separated integers p1, p2, ..., pn — the permutation p that user ainta has. Each integer between 1 and n occurs exactly once in the given permutation. Next n lines describe the matrix A. The i-th line contains n characters '0' or '1' and describes the i-th row of A. The j-th character of the i-th line Ai, j is the element on the intersection of the i-th row and the j-th column of A. It is guaranteed that, for all integers i, j where 1 ≤ i < j ≤ n, Ai, j = Aj, i holds. Also, for all integers i where 1 ≤ i ≤ n, Ai, i = 0 holds. Output In the first and only line, print n space-separated integers, describing the prettiest permutation that can be obtained. Examples Input 7 5 2 4 3 6 7 1 0001001 0000000 0000010 1000001 0000000 0010000 1001000 Output 1 2 4 3 6 7 5 Input 5 4 2 1 5 3 00100 00011 10010 01101 01010 Output 1 2 3 4 5 Note In the first sample, the swap needed to obtain the prettiest permutation is: (p1, p7). In the second sample, the swaps needed to obtain the prettiest permutation is (p1, p3), (p4, p5), (p3, p4). <image> A permutation p is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. The i-th element of the permutation p is denoted as pi. The size of the permutation p is denoted as n. ### Response ```cpp #include <bits/stdc++.h> using namespace std; template <typename T> inline T gcd(T a, T b) { if (b == 0) return a; else return gcd(b, a % b); } template <typename T> inline T lcm(T a, T b) { return (a * b) / gcd(a, b); } using namespace std; int n, vec[305], visited[305]; char ar[305][305]; vector<set<int> > ans(305); void dfs(int node, int color) { visited[node] = color; ans[color].insert(vec[node]); for (int i = 1; i <= n; i++) { if (ar[node][i] == '1' && !visited[i]) { dfs(i, color); } } } int main() { cin >> n; for (int i = 1; i <= n; i++) cin >> vec[i]; for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) cin >> ar[i][j]; int c = 0; for (int i = 1; i <= n; i++) { if (!visited[i]) { dfs(i, ++c); } } for (int i = 1; i <= n; i++) { cout << *ans[visited[i]].begin() << " "; ans[visited[i]].erase(ans[visited[i]].begin()); } return 0; } ```
### Prompt Construct a Cpp code solution to the problem outlined: Hands that shed innocent blood! There are n guilty people in a line, the i-th of them holds a claw with length Li. The bell rings and every person kills some of people in front of him. All people kill others at the same time. Namely, the i-th person kills the j-th person if and only if j < i and j ≥ i - Li. You are given lengths of the claws. You need to find the total number of alive people after the bell rings. Input The first line contains one integer n (1 ≤ n ≤ 106) — the number of guilty people. Second line contains n space-separated integers L1, L2, ..., Ln (0 ≤ Li ≤ 109), where Li is the length of the i-th person's claw. Output Print one integer — the total number of alive people after the bell rings. Examples Input 4 0 1 0 10 Output 1 Input 2 0 0 Output 2 Input 10 1 1 3 0 0 0 2 1 0 3 Output 3 Note In first sample the last person kills everyone in front of him. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int mod = 1e9 + 7; const int INF = 1e9; int f[1000005]; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n; cin >> n; vector<int> l(n, 0); for (int i = 1; i <= n; i++) { cin >> l[i]; } for (int i = 1; i <= n; i++) { f[max(0, i - l[i])]++; f[i]--; } int cur = f[0], res = 0; for (int i = 1; i <= n; i++) { cur += f[i]; if (cur == 0) res++; } cout << min(n, res) << endl; } ```
### Prompt Your task is to create a CPP solution to the following problem: You have a bag of size n. Also you have m boxes. The size of i-th box is a_i, where each a_i is an integer non-negative power of two. You can divide boxes into two parts of equal size. Your goal is to fill the bag completely. For example, if n = 10 and a = [1, 1, 32] then you have to divide the box of size 32 into two parts of size 16, and then divide the box of size 16. So you can fill the bag with boxes of size 1, 1 and 8. Calculate the minimum number of divisions required to fill the bag of size n. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains two integers n and m (1 ≤ n ≤ 10^{18}, 1 ≤ m ≤ 10^5) — the size of bag and the number of boxes, respectively. The second line of each test case contains m integers a_1, a_2, ... , a_m (1 ≤ a_i ≤ 10^9) — the sizes of boxes. It is guaranteed that each a_i is a power of two. It is also guaranteed that sum of all m over all test cases does not exceed 10^5. Output For each test case print one integer — the minimum number of divisions required to fill the bag of size n (or -1, if it is impossible). Example Input 3 10 3 1 32 1 23 4 16 1 4 1 20 5 2 1 16 1 8 Output 2 -1 0 ### Response ```cpp #include <bits/stdc++.h> using namespace std; long long int T, n, m, a, buc[63], con, sum, e; bool z; void pot(long int p) { if (p > 60) { z = true; return; } if (buc[p] == 0) { con++; pot(p + 1); buc[p]++; return; } buc[p]--; return; } int main() { cin >> T; for (int t = 0; t < T; t++) { cin >> n >> m; con = 0; z = false; for (int i = 0; i < m; i++) { cin >> a; e = -1; while (a != 0) { a /= 2; e++; } buc[e]++; } for (int i = 0; i <= 60; i++) { if ((n & (1ULL << i)) != 0) { n -= (1ULL << i); pot(i); } buc[i + 1] += buc[i] / 2; buc[i] = 0; } if (!z) cout << con << "\n"; else cout << "-1" << "\n"; } } ```
### Prompt Please create a solution in cpp to the following problem: There are N towns in the State of Atcoder, connected by M bidirectional roads. The i-th road connects Town A_i and B_i and has a length of C_i. Joisino is visiting R towns in the state, r_1,r_2,..,r_R (not necessarily in this order). She will fly to the first town she visits, and fly back from the last town she visits, but for the rest of the trip she will have to travel by road. If she visits the towns in the order that minimizes the distance traveled by road, what will that distance be? Constraints * 2≤N≤200 * 1≤M≤N×(N-1)/2 * 2≤R≤min(8,N) (min(8,N) is the smaller of 8 and N.) * r_i≠r_j (i≠j) * 1≤A_i,B_i≤N, A_i≠B_i * (A_i,B_i)≠(A_j,B_j),(A_i,B_i)≠(B_j,A_j) (i≠j) * 1≤C_i≤100000 * Every town can be reached from every town by road. * All input values are integers. Input Input is given from Standard Input in the following format: N M R r_1 ... r_R A_1 B_1 C_1 : A_M B_M C_M Output Print the distance traveled by road if Joisino visits the towns in the order that minimizes it. Examples Input 3 3 3 1 2 3 1 2 1 2 3 1 3 1 4 Output 2 Input 3 3 2 1 3 2 3 2 1 3 6 1 2 2 Output 4 Input 4 6 3 2 3 4 1 2 4 2 3 3 4 3 1 1 4 1 4 2 2 3 1 6 Output 3 ### Response ```cpp #include <bits/stdc++.h> #define rep(i,n) for (long long i = 0; i < (n); ++i) using namespace std; using ll = long long; using P = pair<ll,ll>; const ll MOD = 1000000007; #define all(v) v.begin(), v.end() int main(){ ll N,M,R,ans=1000000000; cin >> N >> M >> R; vector<ll> r(R); rep(i,R){ cin >> r.at(i); r.at(i)--; } sort(all(r)); vector<vector<ll>> d(N,vector<ll>(N,100000000)); rep(i,N) d.at(i).at(i)=0; rep(i,M){ ll a,b,c; cin >> a >> b >> c; d.at(a-1).at(b-1)=c; d.at(b-1).at(a-1)=c; } rep(k,N)rep(i,N)rep(j,N){ d.at(i).at(j)=min(d.at(i).at(j),d.at(i).at(k)+d.at(k).at(j)); } do{ ll t=0; rep(i,R-1){ t+=d.at(r.at(i)).at(r.at(i+1)); } ans=min(ans,t); } while (next_permutation(all(r))); cout << ans << endl; } ```
### Prompt Your task is to create a Cpp solution to the following problem: Cucumber boy is fan of Kyubeat, a famous music game. Kyubeat has 16 panels for playing arranged in 4 × 4 table. When a panel lights up, he has to press that panel. Each panel has a timing to press (the preffered time when a player should press it), and Cucumber boy is able to press at most k panels in a time with his one hand. Cucumber boy is trying to press all panels in perfect timing, that is he wants to press each panel exactly in its preffered time. If he cannot press the panels with his two hands in perfect timing, his challenge to press all the panels in perfect timing will fail. You are given one scene of Kyubeat's panel from the music Cucumber boy is trying. Tell him is he able to press all the panels in perfect timing. Input The first line contains a single integer k (1 ≤ k ≤ 5) — the number of panels Cucumber boy can press with his one hand. Next 4 lines contain 4 characters each (digits from 1 to 9, or period) — table of panels. If a digit i was written on the panel, it means the boy has to press that panel in time i. If period was written on the panel, he doesn't have to press that panel. Output Output "YES" (without quotes), if he is able to press all the panels in perfect timing. If not, output "NO" (without quotes). Examples Input 1 .135 1247 3468 5789 Output YES Input 5 ..1. 1111 ..1. ..1. Output YES Input 1 .... 12.1 .2.. .2.. Output NO Note In the third sample boy cannot press all panels in perfect timing. He can press all the panels in timing in time 1, but he cannot press the panels in time 2 in timing with his two hands. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { int arr[10] = {0}; int k; cin >> k; k *= 2; char s; for (int i = 0; i < 16 && cin >> s; i++) if (s != '.') arr[s - '0']++; for (int i = 0; i < 10; i++) if (arr[i] > k) { cout << "NO"; return 0; } cout << "YES"; return 0; } ```
### Prompt Please formulate a Cpp solution to the following problem: Tokitsukaze and CSL are playing a little game of stones. In the beginning, there are n piles of stones, the i-th pile of which has a_i stones. The two players take turns making moves. Tokitsukaze moves first. On each turn the player chooses a nonempty pile and removes exactly one stone from the pile. A player loses if all of the piles are empty before his turn, or if after removing the stone, two piles (possibly empty) contain the same number of stones. Supposing that both players play optimally, who will win the game? Consider an example: n=3 and sizes of piles are a_1=2, a_2=3, a_3=0. It is impossible to choose the empty pile, so Tokitsukaze has two choices: the first and the second piles. If she chooses the first pile then the state will be [1, 3, 0] and it is a good move. But if she chooses the second pile then the state will be [2, 2, 0] and she immediately loses. So the only good move for her is to choose the first pile. Supposing that both players always take their best moves and never make mistakes, who will win the game? Note that even if there are two piles with the same number of stones at the beginning, Tokitsukaze may still be able to make a valid first move. It is only necessary that there are no two piles with the same number of stones after she moves. Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of piles. The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_1, a_2, …, a_n ≤ 10^9), which mean the i-th pile has a_i stones. Output Print "sjfnb" (without quotes) if Tokitsukaze will win, or "cslnb" (without quotes) if CSL will win. Note the output characters are case-sensitive. Examples Input 1 0 Output cslnb Input 2 1 0 Output cslnb Input 2 2 2 Output sjfnb Input 3 2 3 1 Output sjfnb Note In the first example, Tokitsukaze cannot take any stone, so CSL will win. In the second example, Tokitsukaze can only take a stone from the first pile, and then, even though they have no stone, these two piles will have the same number of stones, which implies CSL will win. In the third example, Tokitsukaze will win. Here is one of the optimal ways: * Firstly, Tokitsukaze can choose the first pile and take a stone from that pile. * Then, CSL can only choose the first pile, because if he chooses the second pile, he will lose immediately. * Finally, Tokitsukaze can choose the second pile, and then CSL will have no choice but to lose. In the fourth example, they only have one good choice at any time, so Tokitsukaze can make the game lasting as long as possible and finally win. ### Response ```cpp #include <bits/stdc++.h> using namespace std; char buf[(1 << 22)], *p1 = buf, *p2 = buf; inline int read() { char c = (p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 1 << 22, stdin), p1 == p2) ? EOF : *p1++); int x = 0, f = 1; while (c<'0' | c> '9') { if (c == '-') f = -1; c = (p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 1 << 22, stdin), p1 == p2) ? EOF : *p1++); } while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = (p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 1 << 22, stdin), p1 == p2) ? EOF : *p1++); return x * f; } const int maxn = 1e5 + 10; int a[maxn], n; map<int, int> mp; map<int, bool> vis; int main() { long long sum = 0; scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &a[i]); mp[a[i]]++; } sort(a, a + n); int tot = 0; for (int i = 0; i < n; i++) { sum += (a[i] - i); if (!vis[a[i]] && mp[a[i]] > 1) { vis[a[i]] = true; tot++; } if (mp[a[i]] > 2) { sum = 0; break; } if (mp[a[i] + 1] > 1) { sum = 0; break; } } if (tot > 1 || mp[0] > 1) sum = 0; printf(sum % 2 == 0 ? "cslnb\n" : "sjfnb\n"); return 0; } ```
### Prompt Generate a CPP solution to the following problem: The Cybermen solved that first test much quicker than the Daleks. Luckily for us, the Daleks were angry (shocking!) and they destroyed some of the Cybermen. After the fighting stopped, Heidi gave them another task to waste their time on. There are n points on a plane. Given a radius r, find the maximum number of points that can be covered by an L^1-ball with radius r. An L^1-ball with radius r and center (x_0, y_0) in a 2D-plane is defined as the set of points (x, y) such that the Manhattan distance between (x_0, y_0) and (x, y) is at most r. Manhattan distance between (x_0, y_0) and (x, y) is defined as |x - x_0| + |y - y_0|. Input The first line contains two integers n, r (1 ≤ n ≤ 300 000, 1 ≤ r ≤ 10^6), the number of points and the radius of the ball, respectively. Each of the next n lines contains integers x_i, y_i (-10^6 ≤ x_i, y_i ≤ 10^6), describing the coordinates of the i-th point. It is guaranteed, that all points are distinct. Output Print one integer — the maximum number points that an L^1-ball with radius r can cover. Examples Input 5 1 1 1 1 -1 -1 1 -1 -1 2 0 Output 3 Input 5 2 1 1 1 -1 -1 1 -1 -1 2 0 Output 5 Note In the first example, a ball centered at (1, 0) covers the points (1, 1), (1, -1), (2, 0). In the second example, a ball centered at (0, 0) covers all the points. Note that x_0 and y_0 need not be integer. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = (int)3e5 + 25; const long long inf = (long long)1e12; const int MOD = (int)1e9 + 7; struct Point { int x, y; bool operator<(const Point& b) const { return x != b.x ? x < b.x : y < b.y; } }; Point pt[N]; int mp[N]; int seg[N << 2], lzy[N << 2]; inline void init(int n) { memset(seg, 0, 4 * n * sizeof(int)); memset(lzy, 0, 4 * n * sizeof(int)); } inline void pushDown(int rt) { if (lzy[rt]) { seg[rt << 1] += lzy[rt]; seg[rt << 1 | 1] += lzy[rt]; lzy[rt << 1] += lzy[rt]; lzy[rt << 1 | 1] += lzy[rt]; lzy[rt] = 0; } } inline void pushUp(int rt) { seg[rt] = max(seg[rt << 1], seg[rt << 1 | 1]); } inline void update(int ql, int qr, int val, int l, int r, int rt) { if (ql <= l && r <= qr) { seg[rt] += val; lzy[rt] += val; return; } pushDown(rt); int m = (l + r) >> 1; if (ql <= m) { update(ql, qr, val, l, m, rt << 1); } if (m < qr) { update(ql, qr, val, m + 1, r, rt << 1 | 1); } pushUp(rt); } int main() { int n, r; while (~scanf("%d%d", &n, &r)) { init(n + 5); for (int i = 1; i <= n; i++) { int x, y; scanf("%d%d", &x, &y); pt[i].x = x + y; mp[i] = pt[i].y = x - y; } int ans = 0; sort(pt + 1, pt + 1 + n); sort(mp + 1, mp + 1 + n); int tot = unique(mp + 1, mp + n + 1) - mp - 1; int l = 1; for (int i = 1; i <= n; i++) { while (pt[i].x - pt[l].x > 2 * r) { int rp = upper_bound(mp + 1, mp + 1 + tot, pt[l].y + 2 * r) - mp - 1; int lp = lower_bound(mp + 1, mp + 1 + tot, pt[l].y) - mp; update(lp, rp, -1, 1, tot, 1); l++; } int rp = upper_bound(mp + 1, mp + 1 + tot, pt[i].y + 2 * r) - mp - 1; int lp = lower_bound(mp + 1, mp + 1 + tot, pt[i].y) - mp; update(lp, rp, 1, 1, tot, 1); ans = max(ans, seg[1]); } printf("%d\n", ans); } } ```
### Prompt Create a solution in CPP for the following problem: We have N+1 integers: 10^{100}, 10^{100}+1, ..., 10^{100}+N. We will choose K or more of these integers. Find the number of possible values of the sum of the chosen numbers, modulo (10^9+7). Constraints * 1 \leq N \leq 2\times 10^5 * 1 \leq K \leq N+1 * All values in input are integers. Input Input is given from Standard Input in the following format: N K Output Print the number of possible values of the sum, modulo (10^9+7). Examples Input 3 2 Output 10 Input 200000 200001 Output 1 Input 141421 35623 Output 220280457 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main(){ long long n,k; cin >> n >> k; long long ans=0; while(k<=n+1){ ans=(ans+(k*(n-k+1)+1))%1000000007; k++; } cout << ans << endl; return 0; } ```
### Prompt Construct a cpp code solution to the problem outlined: Little Vasya loves orange juice very much. That's why any food and drink in his kitchen necessarily contains orange juice. There are n drinks in his fridge, the volume fraction of orange juice in the i-th drink equals pi percent. One day Vasya decided to make himself an orange cocktail. He took equal proportions of each of the n drinks and mixed them. Then he wondered, how much orange juice the cocktail has. Find the volume fraction of orange juice in the final drink. Input The first input line contains a single integer n (1 ≤ n ≤ 100) — the number of orange-containing drinks in Vasya's fridge. The second line contains n integers pi (0 ≤ pi ≤ 100) — the volume fraction of orange juice in the i-th drink, in percent. The numbers are separated by a space. Output Print the volume fraction in percent of orange juice in Vasya's cocktail. The answer will be considered correct if the absolute or relative error does not exceed 10 - 4. Examples Input 3 50 50 100 Output 66.666666666667 Input 4 0 25 50 75 Output 37.500000000000 Note Note to the first sample: let's assume that Vasya takes x milliliters of each drink from the fridge. Then the volume of pure juice in the cocktail will equal <image> milliliters. The total cocktail's volume equals 3·x milliliters, so the volume fraction of the juice in the cocktail equals <image>, that is, 66.(6) percent. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { int n, k; cin >> n; double sum = 0; for (int i = 0; i < n; i++) { cin >> k; sum += k / 100.0; } printf("%.12f\n", sum / n * 100); return 0; } ```
### Prompt In cpp, your task is to solve the following problem: Suppose you are given two strings a and b. You can apply the following operation any number of times: choose any contiguous substring of a or b, and sort the characters in it in non-descending order. Let f(a, b) the minimum number of operations you have to apply in order to make them equal (or f(a, b) = 1337 if it is impossible to make a and b equal using these operations). For example: * f(ab, ab) = 0; * f(ba, ab) = 1 (in one operation, we can sort the whole first string); * f(ebcda, ecdba) = 1 (in one operation, we can sort the substring of the second string starting from the 2-nd character and ending with the 4-th character); * f(a, b) = 1337. You are given n strings s_1, s_2, ..., s_k having equal length. Calculate ∑ _{i = 1}^{n} ∑_{j = i + 1}^{n} f(s_i, s_j). Input The first line contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of strings. Then n lines follow, each line contains one of the strings s_i, consisting of lowercase Latin letters. |s_1| = |s_2| = … = |s_n|, and n ⋅ |s_1| ≤ 2 ⋅ 10^5. All these strings are pairwise distinct. Output Print one integer: ∑ _{i = 1}^{n} ∑_{j = i + 1}^{n} f(s_i, s_j). Examples Input 4 zzz bac abc acb Output 4015 Input 2 a b Output 1337 ### Response ```cpp #include <bits/stdc++.h> #define int long long #define double long double //#define endl '\n' #define st first #define nd second #define pb push_back #define sz(x) (int)(x).size() using namespace std; double PI=3.14159265359; int inf=1000000000000000007; int mod=1000000007; int mod1=998244353; const bool multi=0; string s[200007]; string s1[200007]; int it=1,n,m; int fen[400007]; int trie[200007][27]; int pre[200007],post[200007],c=0; int last[27]; void dfs(int v) { pre[v]=++c; for(int j=0;j<26;j++) if(trie[v][j]>0) dfs(trie[v][j]); post[v]=c; } inline void ins(int x,int val) {while(x<=it) { fen[x]+=val; x+=(x&-x); } } inline int que(int x) {int res=0; while(x>0) { res+=fen[x]; x-=(x&-x); } return res; } vector<int> gdzie[200007]; vector<int> mx[200007]; int pairs; void solve(vector<int> id,int j) { if(sz(id)<=1||j>=m) return ; for(auto x:id) ins(pre[gdzie[x][0]],1); vector<int>vec[26]; for(auto x:id) vec[s[x][j]-'a'].pb(x); for(int i=0;i<26;i++) { for(auto x:vec[i]) ins(pre[gdzie[x][0]],-1); for(auto x:vec[i]) pairs+=que(post[gdzie[x][mx[x][j]]])-que(pre[gdzie[x][mx[x][j]]]-1); for(auto x:vec[i]) ins(pre[gdzie[x][0]],1); } for(auto x:id) ins(pre[gdzie[x][0]],-1); for(int i=0;i<26;i++) solve(vec[i],j+1); } map<string,int>mapa; signed main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int tt; if(multi) cin>>tt; else tt=1; while(tt--) { cin>>n; for(int i=1;i<=n;i++) cin>>s[i]; m=sz(s[1]); for(int i=1;i<=n;i++) { for(int j=0;j<=m+1;j++) { gdzie[i].pb(0); mx[i].pb(0); } int p=1; gdzie[i][m]=1; for(int j=m-1;j>=0;j--) { if(trie[p][s[i][j]-'a']==0) trie[p][s[i][j]-'a']=++it; p=trie[p][s[i][j]-'a']; gdzie[i][j]=p; } } dfs(1); for(int i=1;i<=n;i++) { for(int j=0;j<26;j++) last[j]=m; mx[i][m]=m; for(int j=m-1;j>=0;j--) { int xd=mod; last[s[i][j]-'a']=j; for(int l=s[i][j]-'a'-1;l>=0;l--) xd=min(xd,last[l]); mx[i][j]=min(xd,mx[i][j+1]); } } vector<int>act; for(int i=1;i<=n;i++) { s1[i]=s[i]; sort(s1[i].begin(),s1[i].end()); } vector<pair<string,int>>vec; for(int i=1;i<=n;i++) vec.pb({s1[i],i}); sort(vec.begin(),vec.end()); act.pb(vec[0].nd); int ans=0,bad=0,good=0; for(int i=1;i<=n;i++) { good+=mapa[s[i]]; mapa[s[i]]++; } for(int i=1;i<n;i++) { if(vec[i].st!=vec[i-1].st) { pairs=0; solve(act,0); ans+=pairs; ans+=2*(sz(act)*(sz(act)-1)/2-pairs); bad+=sz(act)*(n-sz(act)); act.clear(); } act.pb(vec[i].nd); } pairs=0; solve(act,0); ans+=pairs; ans+=2*(sz(act)*(sz(act)-1)/2-pairs); bad+=sz(act)*(n-sz(act)); ans+=bad/2*1337; ans-=good*2; cout<<ans<<endl; } return 0; } ```
### Prompt Please formulate a cpp solution to the following problem: Bear Limak prepares problems for a programming competition. Of course, it would be unprofessional to mention the sponsor name in the statement. Limak takes it seriously and he is going to change some words. To make it still possible to read, he will try to modify each word as little as possible. Limak has a string s that consists of uppercase English letters. In one move he can swap two adjacent letters of the string. For example, he can transform a string "ABBC" into "BABC" or "ABCB" in one move. Limak wants to obtain a string without a substring "VK" (i.e. there should be no letter 'V' immediately followed by letter 'K'). It can be easily proved that it's possible for any initial string s. What is the minimum possible number of moves Limak can do? Input The first line of the input contains an integer n (1 ≤ n ≤ 75) — the length of the string. The second line contains a string s, consisting of uppercase English letters. The length of the string is equal to n. Output Print one integer, denoting the minimum possible number of moves Limak can do, in order to obtain a string without a substring "VK". Examples Input 4 VKVK Output 3 Input 5 BVVKV Output 2 Input 7 VVKEVKK Output 3 Input 20 VKVKVVVKVOVKVQKKKVVK Output 8 Input 5 LIMAK Output 0 Note In the first sample, the initial string is "VKVK". The minimum possible number of moves is 3. One optimal sequence of moves is: 1. Swap two last letters. The string becomes "VKKV". 2. Swap first two letters. The string becomes "KVKV". 3. Swap the second and the third letter. The string becomes "KKVV". Indeed, this string doesn't have a substring "VK". In the second sample, there are two optimal sequences of moves. One is "BVVKV" → "VBVKV" → "VVBKV". The other is "BVVKV" → "BVKVV" → "BKVVV". In the fifth sample, no swaps are necessary. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int MAXN = 80, INF = 0x3f3f3f3f; char str[MAXN]; vector<int> vs, ks, xs; int dp[MAXN][MAXN][MAXN][2]; int remain(vector<int> &vec, int start, int lim) { int res = 0; for (unsigned i = start; i < vec.size() && vec[i] < lim; i++) res++; return res; } void update(int &dst, int v, int k, int x, int canK, int val) { int d = remain(vs, v, val) + remain(ks, k, val) + remain(xs, x, val); dst = min(dst, dp[v][k][x][canK] + d); } int main() { std::cin.tie(0); std::ios_base::sync_with_stdio(0); int n; cin >> n >> str; for (int i = 0; i < n; i++) { if (str[i] == 'V') vs.push_back(i); else if (str[i] == 'K') ks.push_back(i); else xs.push_back(i); } memset(dp, INF, sizeof(dp)); dp[0][0][0][1] = 0; for (unsigned v = 0; v <= vs.size(); v++) { for (unsigned k = 0; k <= ks.size(); k++) { for (unsigned x = 0; x <= xs.size(); x++) { for (unsigned canK = 0; canK <= 1; canK++) { if (v < vs.size()) update(dp[v + 1][k][x][0], v, k, x, canK, vs[v]); if (canK && k < ks.size()) { update(dp[v][k + 1][x][1], v, k, x, canK, ks[k]); } if (x < xs.size()) update(dp[v][k][x + 1][1], v, k, x, canK, xs[x]); } } } } int *ans = dp[vs.size()][ks.size()][xs.size()]; cout << min(ans[0], ans[1]) << '\n'; } ```
### Prompt In Cpp, your task is to solve the following problem: Vasiliy lives at point (a, b) of the coordinate plane. He is hurrying up to work so he wants to get out of his house as soon as possible. New app suggested n available Beru-taxi nearby. The i-th taxi is located at point (xi, yi) and moves with a speed vi. Consider that each of n drivers will move directly to Vasiliy and with a maximum possible speed. Compute the minimum time when Vasiliy will get in any of Beru-taxi cars. Input The first line of the input contains two integers a and b ( - 100 ≤ a, b ≤ 100) — coordinates of Vasiliy's home. The second line contains a single integer n (1 ≤ n ≤ 1000) — the number of available Beru-taxi cars nearby. The i-th of the following n lines contains three integers xi, yi and vi ( - 100 ≤ xi, yi ≤ 100, 1 ≤ vi ≤ 100) — the coordinates of the i-th car and its speed. It's allowed that several cars are located at the same point. Also, cars may be located at exactly the same point where Vasiliy lives. Output Print a single real value — the minimum time Vasiliy needs to get in any of the Beru-taxi cars. You answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 0 0 2 2 0 1 0 2 2 Output 1.00000000000000000000 Input 1 3 3 3 3 2 -2 3 6 -2 7 10 Output 0.50000000000000000000 Note In the first sample, first taxi will get to Vasiliy in time 2, and second will do this in time 1, therefore 1 is the answer. In the second sample, cars 2 and 3 will arrive simultaneously. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { long long int n; long double q[100000][3]; long double a, b, t, d, min, di; cin >> a >> b; cin >> n; for (int i = 0; i < n; i++) { for (int j = 0; j < 3; j++) { cin >> q[i][j]; } } di = sqrt((q[0][0] - a) * (q[0][0] - a) + (q[0][1] - b) * (q[0][1] - b)); min = di / q[0][2]; for (int i = 0; i < n; i++) { d = sqrt((q[i][0] - a) * (q[i][0] - a) + (q[i][1] - b) * (q[i][1] - b)); t = d / q[i][2]; if (t < min || i == 0) min = t; } cout << std::setprecision(14) << min; } ```
### Prompt Please provide a Cpp coded solution to the problem described below: Blackjack is a type of card game played in casinos, where the game is played using cards with numbers from 1 to 13. The score of each card is decided as follows. * 1 is 1 point or 11 points * From 2 to 9, the score is as written. * 10 points from 10 to 13 There are several participants in this game, including parents, each with several sets of cards. This set of cards is called a hand. The hand score is the total of the card scores. The calculation shall be performed as follows. * If the total score of the cards is greater than 21, the score of the hand is set to 0. * As the score of the card, 1 may be calculated as 1 point or 11 points, but the one with the maximum hand score shall be selected. Create a program that uses the information of the cards dealt as input and outputs the score of the hand. Input A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format: c1 c2 ... cn The integer ci (1 ≤ ci ≤ 13) written on the i-th card is given to each line, separated by blanks. The number of cards n does not exceed 100. The number of datasets does not exceed 200. Output The score of the hand is output to one line for each data set. Example Input 1 7 7 7 7 7 8 12 1 10 1 1 0 Output 11 21 0 21 12 ### Response ```cpp #include<bits/stdc++.h> using namespace std; int ans,f,num; string s; int getNum(int x){ int res=0; for(int i=x;s[i]!=' '&&i!=s.size();i++){ res=res*10+s[i]-'0'; } return res; } int main(){ int d[14]={0,1,2,3,4,5,6,7,8,9,10,10,10,10}; while(1){ getline(cin,s); if(s=="0")break; ans=0,f=0; for(int i=0;i<s.size();i++){ num=getNum(i); while(s[i]!=' '&&i!=s.size())i++; ans+=d[num]; if(num==1)f=1; } if(f&&ans+10<=21)cout<<ans+10<<endl; else if(ans<=21)cout<<ans<<endl; else cout<<0<<endl; } return 0; } ```
### Prompt Create a solution in CPP for the following problem: You are a given a list of integers a_1, a_2, …, a_n and s of its segments [l_j; r_j] (where 1 ≤ l_j ≤ r_j ≤ n). You need to select exactly m segments in such a way that the k-th order statistic of the multiset of a_i, where i is contained in at least one segment, is the smallest possible. If it's impossible to select a set of m segments in such a way that the multiset contains at least k elements, print -1. The k-th order statistic of a multiset is the value of the k-th element after sorting the multiset in non-descending order. Input The first line contains four integers n, s, m and k (1 ≤ m ≤ s ≤ 1500, 1 ≤ k ≤ n ≤ 1500) — the size of the list, the number of segments, the number of segments to choose and the statistic number. The second line contains n integers a_i (1 ≤ a_i ≤ 10^9) — the values of the numbers in the list. Each of the next s lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the endpoints of the segments. It is possible that some segments coincide. Output Print exactly one integer — the smallest possible k-th order statistic, or -1 if it's impossible to choose segments in a way that the multiset contains at least k elements. Examples Input 4 3 2 2 3 1 3 2 1 2 2 3 4 4 Output 2 Input 5 2 1 1 1 2 3 4 5 2 4 1 5 Output 1 Input 5 3 3 5 5 5 2 1 1 1 2 2 3 3 4 Output -1 Note In the first example, one possible solution is to choose the first and the third segment. Together they will cover three elements of the list (all, except for the third one). This way the 2-nd order statistic for the covered elements is 2. <image> ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 1500 + 10; const int INF = 0x3f3f3f3f; int n, s, m, k; int a[N], b[N], f[N][N], mn[N]; struct dat { int l, r; bool operator<(const dat& rhs) const { return l < rhs.l; } } q[N]; bool flag[N]; int mx[N]; void update(int x, int v) { for (; x <= n; x += x & -x) mx[x] = max(mx[x], v); } int query(int x) { int res = 0; for (; x; x -= x & -x) res = max(res, mx[x]); return res; } bool check(int mid) { for (int i = 1; i <= n; i++) if (a[i] <= mid) b[i] = 1; else b[i] = 0; int Max = 0; for (int i = 1; i <= n; i++) b[i] += b[i - 1]; memset(f, 0, sizeof(f)); for (int i = 1; i <= m; i++) { memset(mx, 0, sizeof(mx)); for (int j = 1; j <= s; j++) { f[i][j] = f[i - 1][j]; int t = mn[q[j].l]; f[i][j] = max(f[i][j], f[i - 1][t] + b[q[j].r] - b[q[t].r]); f[i][j] = max(f[i][j], query(q[j].l - 1) + b[q[j].r] - b[q[j].l - 1]); update(q[j].r, f[i - 1][j]); Max = max(Max, f[i][j]); } } return Max >= k; } int main() { cin >> n >> s >> m >> k; for (int i = 1; i <= n; i++) scanf("%d", &a[i]); for (int i = 1; i <= s; i++) scanf("%d%d", &q[i].l, &q[i].r); for (int i = 1; i <= s; i++) for (int j = 1; j <= s; j++) if (i != j && !flag[j] && q[j].l <= q[i].l && q[i].r <= q[j].r) { flag[i] = 1; break; } int tp = 0; for (int i = 1; i <= s; i++) if (!flag[i]) q[++tp].l = q[i].l, q[tp].r = q[i].r; s = tp; sort(q + 1, q + s + 1); for (int i = 1; i <= s; i++) for (int j = q[i].l; j <= q[i].r; j++) if (!mn[j] || q[mn[j]].l > q[i].l) mn[j] = i; int L = -INF, R = INF; while (L < R) { int mid = L + R >> 1; if (check(mid)) R = mid; else L = mid + 1; } if (check(L)) cout << L; else cout << -1; return 0; } ```
### Prompt Develop a solution in CPP to the problem described below: C: AA グラフ (AA Graph) Problem Given a graph as an ASCII Art (AA), please print the length of shortest paths from the vertex s to the vertex t. The AA of the graph satisfies the following constraints. A vertex is represented by an uppercase alphabet and symbols `o` in 8 neighbors as follows. ooo oAo ooo Horizontal edges and vertical edges are represented by symbols `-` and `|`, respectively. Lengths of all edges are 1, that is, it do not depends on the number of continuous symbols `-` or `|`. All edges do not cross each other, and all vertices do not overlap and touch each other. For each vertex, outgoing edges are at most 1 for each directions top, bottom, left, and right. Each edge is connected to a symbol `o` that is adjacent to an uppercase alphabet in 4 neighbors as follows. ..|.. .ooo. -oAo- .ooo. ..|.. Therefore, for example, following inputs are not given. .......... .ooo..ooo. .oAo..oBo. .ooo--ooo. .......... (Edges do not satisfies the constraint about their position.) oooooo oAooBo oooooo (Two vertices are adjacent each other.) Input Format H W s t a_1 $\vdots$ a_H * In line 1, two integers H and W, and two characters s and t are given. H and W is the width and height of the AA, respectively. s and t is the start and end vertices, respectively. They are given in separating by en spaces. * In line 1 + i where 1 \leq i \leq H, the string representing line i of the AA is given. Constraints * 3 \leq H, W \leq 50 * s and t are selected by uppercase alphabets from `A` to `Z`, and s \neq t. * a_i (1 \leq i \leq H) consists of uppercase alphabets and symbols `o`, `-`, `|`, and `.`. * Each uppercase alphabet occurs at most once in the AA. * It is guaranteed that there are two vertices representing s and t. * The AA represents a connected graph. Output Format Print the length of the shortest paths from s to t in one line. Example 1 14 16 A L ooo.....ooo..... oAo-----oHo..... ooo.....ooo..ooo .|.......|...oLo ooo..ooo.|...ooo oKo--oYo.|....|. ooo..ooo.|....|. .|....|.ooo...|. .|....|.oGo...|. .|....|.ooo...|. .|....|.......|. ooo..ooo.....ooo oFo--oXo-----oEo ooo..ooo.....ooo Output 1 5 Exapmple 2 21 17 F L ................. .....ooo.....ooo. .....oAo-----oBo. .....ooo.....ooo. ......|.......|.. .ooo..|..ooo..|.. .oCo..|..oDo.ooo. .ooo.ooo.ooo.oEo. ..|..oFo..|..ooo. ..|..ooo..|...|.. ..|...|...|...|.. ..|...|...|...|.. ..|...|...|...|.. .ooo.ooo.ooo..|.. .oGo-oHo-oIo..|.. .ooo.ooo.ooo..|.. ..|...........|.. .ooo...ooo...ooo. .oJo---oKo---oLo. .ooo...ooo...ooo. ................. Output 2 4 Example Input Output ### Response ```cpp #include <iostream> #include <string> #include <vector> #include <algorithm> #define rep(i, n) for(i = 0; i < n; i++) using namespace std; typedef pair<int, int> P; int h, w; char s, t; string art[50]; vector<int> et[26]; P toPos(char a) { int i, j; rep(i, h) rep(j, w) if (art[i][j] == a) return P(i, j); return P(-1, -1); } bool isConnect(char a, char b) { P posA = toPos(a); int yA = posA.first; int xA = posA.second; P posB = toPos(b); int yB = posB.first; int xB = posB.second; int i; if (yA == -1 || yB == -1) return false; if (yA == yB) { int y = yA; if (xA > xB) swap(xA, xB); if (art[y][xA + 1] != 'o') return false; if (art[y][xB - 1] != 'o') return false; for (i = xA + 2; i <= xB - 2; i++) { if (art[y][i] != '-') return false; } return true; } if (xA == xB) { int x = xA; if (yA > yB) swap(yA, yB); if (art[yA + 1][x] != 'o') return false; if (art[yB - 1][x] != 'o') return false; for (i = yA + 2; i <= yB - 2; i++) { if (art[i][x] != '|') return false; } return true; } return false; } int main() { int i, j, k; cin >> h >> w >> s >> t; for (i = 0; i < h; i++) cin >> art[i]; for (i = 0; i < 26; i++) { for (j = i + 1; j < 26; j++) { if (isConnect('A' + i, 'A' + j)) { et[i].push_back(j); et[j].push_back(i); } } } int dist[26][26], INF = 114514; rep(i, 26) rep(j, 26) dist[i][j] = INF; rep(i, 26) dist[i][i] = 0; rep(i, 26) rep(j, et[i].size()) dist[i][et[i][j]] = 1; rep(k, 26) rep(i, 26) rep(j, 26) dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]); cout << dist[s - 'A'][t - 'A'] << endl; return 0; } ```
### Prompt Create a solution in cpp for the following problem: You have a plate and you want to add some gilding to it. The plate is a rectangle that we split into w× h cells. There should be k gilded rings, the first one should go along the edge of the plate, the second one — 2 cells away from the edge and so on. Each ring has a width of 1 cell. Formally, the i-th of these rings should consist of all bordering cells on the inner rectangle of size (w - 4(i - 1))×(h - 4(i - 1)). <image> The picture corresponds to the third example. Your task is to compute the number of cells to be gilded. Input The only line contains three integers w, h and k (3 ≤ w, h ≤ 100, 1 ≤ k ≤ \left⌊ (min(n, m) + 1)/(4)\right⌋, where ⌊ x ⌋ denotes the number x rounded down) — the number of rows, columns and the number of rings, respectively. Output Print a single positive integer — the number of cells to be gilded. Examples Input 3 3 1 Output 8 Input 7 9 1 Output 28 Input 7 9 2 Output 40 Note The first example is shown on the picture below. <image> The second example is shown on the picture below. <image> The third example is shown in the problem description. ### Response ```cpp #include <bits/stdc++.h> int gold(int m, int n, int k) { int f, i = 1, tot, total = 0; f = (((m + n) * 2) - 4); total = f; if (k > 1) { while (i <= (k - 1)) { m = m - 4; n = n - 4; tot = (((m + n) * 2) - 4); total = tot + total; i++; } } return total; } int main(int argc, char **argv) { int g, h, t, k; scanf("%d", &g); scanf("%d", &h); scanf("%d", &k); t = gold(g, h, k); printf("%d", t); return 0; } ```
### Prompt Construct a cpp code solution to the problem outlined: One day Petya got a birthday present from his mom: a book called "The Legends and Myths of Graph Theory". From this book Petya learned about a hydra graph. A non-oriented graph is a hydra, if it has a structure, shown on the figure below. Namely, there are two nodes u and v connected by an edge, they are the hydra's chest and stomach, correspondingly. The chest is connected with h nodes, which are the hydra's heads. The stomach is connected with t nodes, which are the hydra's tails. Note that the hydra is a tree, consisting of h + t + 2 nodes. <image> Also, Petya's got a non-directed graph G, consisting of n nodes and m edges. Petya got this graph as a last year birthday present from his mom. Graph G contains no self-loops or multiple edges. Now Petya wants to find a hydra in graph G. Or else, to make sure that the graph doesn't have a hydra. Input The first line contains four integers n, m, h, t (1 ≤ n, m ≤ 105, 1 ≤ h, t ≤ 100) — the number of nodes and edges in graph G, and the number of a hydra's heads and tails. Next m lines contain the description of the edges of graph G. The i-th of these lines contains two integers ai and bi (1 ≤ ai, bi ≤ n, a ≠ b) — the numbers of the nodes, connected by the i-th edge. It is guaranteed that graph G contains no self-loops and multiple edges. Consider the nodes of graph G numbered with integers from 1 to n. Output If graph G has no hydra, print "NO" (without the quotes). Otherwise, in the first line print "YES" (without the quotes). In the second line print two integers — the numbers of nodes u and v. In the third line print h numbers — the numbers of the nodes that are the heads. In the fourth line print t numbers — the numbers of the nodes that are the tails. All printed numbers should be distinct. If there are multiple possible answers, you are allowed to print any of them. Examples Input 9 12 2 3 1 2 2 3 1 3 1 4 2 5 4 5 4 6 6 5 6 7 7 5 8 7 9 1 Output YES 4 1 5 6 9 3 2 Input 7 10 3 3 1 2 2 3 1 3 1 4 2 5 4 5 4 6 6 5 6 7 7 5 Output NO Note The first sample is depicted on the picture below: <image> ### Response ```cpp #include <bits/stdc++.h> using namespace std; vector<vector<int> > vv; int n, m, h, t; vector<pair<int, int> > edges; vector<int> add; int count(int v1, int v2) { int ans = 0; vector<int> all; int id1 = 0, id2 = 0; while (id1 < vv[v1].size() || id2 < vv[v2].size()) { if (id1 == vv[v1].size()) { all.push_back(vv[v2][id2]); id2++; continue; } if (id2 == vv[v2].size()) { all.push_back(vv[v1][id1]); id1++; continue; } if (vv[v1][id1] < vv[v2][id2]) { all.push_back(vv[v1][id1]); id1++; } else { all.push_back(vv[v2][id2]); id2++; } } add.clear(); for (int i = 1; i < all.size(); i++) { if (all[i] == all[i - 1]) { ans++; add.push_back(all[i]); } } return ans; } bool used[100002]; int main() { cin >> n >> m >> h >> t; vv.resize(n + 1); for (int i = 0; i < m; i++) { int from, to; cin >> from >> to; vv[from].push_back(to); vv[to].push_back(from); edges.push_back(make_pair(from, to)); edges.push_back(make_pair(to, from)); } for (int i = 0; i <= n; i++) { sort(vv[i].begin(), vv[i].end()); } for (int i = 0; i < edges.size(); i++) { int u = edges[i].first; int v = edges[i].second; if ((int)vv[u].size() - 1 < h || (int)vv[v].size() - 1 < t) continue; int cnt_all = count(u, v); int cnt1 = vv[u].size() - 1 - cnt_all; int cnt2 = vv[v].size() - 1 - cnt_all; int need = max(0, h - cnt1); cnt_all -= need; cnt1 += need; need = max(0, t - cnt2); cnt_all -= need; cnt2 += need; if (cnt_all >= 0 && cnt1 >= h && cnt2 >= t) { cout << "YES\n"; cout << u << ' ' << v << '\n'; int cnt = 0; used[u] = true; used[v] = true; for (int j = 0; j < add.size(); j++) used[add[j]] = true; for (int j = 0; j < vv[u].size() && cnt < h; j++) { if (!used[vv[u][j]]) { cout << vv[u][j] << ' '; cnt++; used[vv[u][j]] = true; } } int from = 0; while (cnt < h) { cout << add[from] << ' '; cnt++; from++; } cout << '\n'; cnt = 0; for (int j = 0; j < vv[v].size() && cnt < t; j++) { if (!used[vv[v][j]]) { cout << vv[v][j] << ' '; cnt++; } } while (cnt < t) { cout << add[from] << ' '; cnt++; from++; } cout << '\n'; return 0; } } cout << "NO\n"; return 0; } ```
### Prompt Generate a cpp solution to the following problem: You are given an integer N. Consider an infinite N-ary tree as shown below: <image> Figure: an infinite N-ary tree for the case N = 3 As shown in the figure, each vertex is indexed with a unique positive integer, and for every positive integer there is a vertex indexed with it. The root of the tree has the index 1. For the remaining vertices, vertices in the upper row have smaller indices than those in the lower row. Among the vertices in the same row, a vertex that is more to the left has a smaller index. Regarding this tree, process Q queries. The i-th query is as follows: * Find the index of the lowest common ancestor (see Notes) of Vertex v_i and w_i. Constraints * 1 ≤ N ≤ 10^9 * 1 ≤ Q ≤ 10^5 * 1 ≤ v_i < w_i ≤ 10^9 Input Input is given from Standard Input in the following format: N Q v_1 w_1 : v_Q w_Q Output Print Q lines. The i-th line (1 ≤ i ≤ Q) must contain the index of the lowest common ancestor of Vertex v_i and w_i. Examples Input 3 3 5 7 8 11 3 9 Output 2 1 3 Input 100000 2 1 2 3 4 Output 1 1 ### Response ```cpp #include <iostream> #include <algorithm> #include <set> using namespace std; typedef long long ll; int main(void){ int n,q,i,v,w; cin >> n >> q; if (n==1){ for (i=0;i<q;i++){ cin >> v >> w; cout << v << endl; } return 0; } for (i=0;i<q;i++){ cin >> v >> w; set<int> s; while (v>0){ s.insert(v); v=(v+n-2)/n; } while (1){ if (s.find(w)!=s.end()) break; w=(w+n-2)/n; } cout << w << endl; } return 0; } ```
### Prompt Please formulate a Cpp solution to the following problem: You are given a tree with N vertices. Here, a tree is a kind of graph, and more specifically, a connected undirected graph with N-1 edges, where N is the number of its vertices. The i-th edge (1≤i≤N-1) connects Vertices a_i and b_i, and has a length of c_i. You are also given Q queries and an integer K. In the j-th query (1≤j≤Q): * find the length of the shortest path from Vertex x_j and Vertex y_j via Vertex K. Constraints * 3≤N≤10^5 * 1≤a_i,b_i≤N (1≤i≤N-1) * 1≤c_i≤10^9 (1≤i≤N-1) * The given graph is a tree. * 1≤Q≤10^5 * 1≤K≤N * 1≤x_j,y_j≤N (1≤j≤Q) * x_j≠y_j (1≤j≤Q) * x_j≠K,y_j≠K (1≤j≤Q) Input Input is given from Standard Input in the following format: N a_1 b_1 c_1 : a_{N-1} b_{N-1} c_{N-1} Q K x_1 y_1 : x_{Q} y_{Q} Output Print the responses to the queries in Q lines. In the j-th line j(1≤j≤Q), print the response to the j-th query. Examples Input 5 1 2 1 1 3 1 2 4 1 3 5 1 3 1 2 4 2 3 4 5 Output 3 2 4 Input 7 1 2 1 1 3 3 1 4 5 1 5 7 1 6 9 1 7 11 3 2 1 3 4 5 6 7 Output 5 14 22 Input 10 1 2 1000000000 2 3 1000000000 3 4 1000000000 4 5 1000000000 5 6 1000000000 6 7 1000000000 7 8 1000000000 8 9 1000000000 9 10 1000000000 1 1 9 10 Output 17000000000 ### Response ```cpp #include<iostream> #include<cstdio> #include<algorithm> #define N 100001 using namespace std; int a[N*2][3],g[N]; long long dis[N]; int n,m,k; void ins(int x,int y,int z){ static int sum=1; a[++sum][0]=y,a[sum][1]=z,a[sum][2]=g[x],g[x]=sum; } void dfs(int x,int fa){ for (int i=g[x];i;i=a[i][2]) if (fa!=a[i][0]){ dis[a[i][0]]=dis[x]+a[i][1]; dfs(a[i][0],x); } } int main(){ scanf("%d",&n); for (int i=1;i<n;i++){ int x,y,z; scanf("%d %d %d",&x,&y,&z); ins(x,y,z),ins(y,x,z); } scanf("%d %d",&m,&k); dfs(k,0); while (m--){ int x,y; scanf("%d %d",&x,&y); cout<<dis[x]+dis[y]<<endl; } return 0; } ```
### Prompt Please provide a CPP coded solution to the problem described below: Snuke has decided to play a game using cards. He has a deck consisting of N cards. On the i-th card from the top, an integer A_i is written. He will perform the operation described below zero or more times, so that the values written on the remaining cards will be pairwise distinct. Find the maximum possible number of remaining cards. Here, N is odd, which guarantees that at least one card can be kept. Operation: Take out three arbitrary cards from the deck. Among those three cards, eat two: one with the largest value, and another with the smallest value. Then, return the remaining one card to the deck. Constraints * 3 ≦ N ≦ 10^{5} * N is odd. * 1 ≦ A_i ≦ 10^{5} * A_i is an integer. Input The input is given from Standard Input in the following format: N A_1 A_2 A_3 ... A_{N} Output Print the answer. Examples Input 5 1 2 1 3 7 Output 3 Input 15 1 3 5 2 1 3 2 8 8 6 2 6 11 1 1 Output 7 ### Response ```cpp #include <bits/stdc++.h> using namespace std; #define rep(i, n) for(int i = 0; i < (n); i++) int main() { int N; cin >>N; unordered_set<int> s; rep(i, N) { int A; cin >> A; s.insert(A); } int uniq = s.size(); int dup = N-uniq; cout << uniq-(dup%2) << endl; } ```
### Prompt Your task is to create a Cpp solution to the following problem: Valera is a coder. Recently he wrote a funny program. The pseudo code for this program is given below: //input: integers x, k, p a = x; for(step = 1; step <= k; step = step + 1){ rnd = [random integer from 1 to 100]; if(rnd <= p) a = a * 2; else a = a + 1; } s = 0; while(remainder after dividing a by 2 equals 0){ a = a / 2; s = s + 1; } Now Valera wonders: given the values x, k and p, what is the expected value of the resulting number s? Input The first line of the input contains three integers x, k, p (1 ≤ x ≤ 109; 1 ≤ k ≤ 200; 0 ≤ p ≤ 100). Output Print the required expected value. Your answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6. Examples Input 1 1 50 Output 1.0000000000000 Input 5 3 0 Output 3.0000000000000 Input 5 3 25 Output 1.9218750000000 Note If the concept of expected value is new to you, you can read about it by the link: http://en.wikipedia.org/wiki/Expected_value ### Response ```cpp #include <bits/stdc++.h> using namespace std; int X, K, P; double dp[203][260][2][260]; int main() { scanf("%d%d%d", &X, &K, &P); double prob = 0.01 * P; int bm = X & 255; int last = (X >> 8) & 1; int tmp = X >> 8; int cnt = 0; while (tmp && (tmp & 1) == last) { ++cnt; tmp >>= 1; } dp[0][bm][last][cnt] = 1.0; for (int k = 0; k < K; ++k) { for (int i = 0; i < 256; ++i) { for (int j = 0; j < 2; ++j) { for (int cnt = 0; cnt < 240; ++cnt) { int new_bm = i << 1; int new_cnt, new_last; if (new_bm & 256) { new_last = 1; if (j == 1) { new_cnt = cnt + 1; } else { new_cnt = 1; } } else { new_last = 0; if (j == 1) { new_cnt = 1; } else { new_cnt = (cnt == 0 ? 0 : cnt + 1); } } new_bm &= 255; dp[k + 1][new_bm][new_last][new_cnt] += prob * dp[k][i][j][cnt]; new_bm = i + 1; if (new_bm & 256) { if (j == 1) { new_last = 0; new_cnt = cnt; } else { new_last = 1; new_cnt = 1; } } else { new_last = j; new_cnt = cnt; } new_bm &= 255; dp[k + 1][new_bm][new_last][new_cnt] += (1.0 - prob) * dp[k][i][j][cnt]; } } } } double ans = 0; for (int i = 0; i < 256; ++i) { for (int j = 0; j < 2; ++j) { for (int cnt = 0; cnt < 240; ++cnt) { int val = 0; if (j == 1 || i & 255) { if (i & 255) { int lsb = i & ((~i) + 1); while (lsb > 1) { ++val; lsb >>= 1; } } else val = 8; } else { val = (cnt > 0 ? cnt + 8 : 0); } ans += dp[K][i][j][cnt] * val; } } } printf("%.12lf\n", ans); return 0; } ```
### Prompt Your task is to create a cpp solution to the following problem: Lunar New Year is approaching, and Bob is going to receive some red envelopes with countless money! But collecting money from red envelopes is a time-consuming process itself. Let's describe this problem in a mathematical way. Consider a timeline from time 1 to n. The i-th red envelope will be available from time s_i to t_i, inclusive, and contain w_i coins. If Bob chooses to collect the coins in the i-th red envelope, he can do it only in an integer point of time between s_i and t_i, inclusive, and he can't collect any more envelopes until time d_i (inclusive) after that. Here s_i ≤ t_i ≤ d_i holds. Bob is a greedy man, he collects coins greedily — whenever he can collect coins at some integer time x, he collects the available red envelope with the maximum number of coins. If there are multiple envelopes with the same maximum number of coins, Bob would choose the one whose parameter d is the largest. If there are still multiple choices, Bob will choose one from them randomly. However, Alice — his daughter — doesn't want her father to get too many coins. She could disturb Bob at no more than m integer time moments. If Alice decides to disturb Bob at time x, he could not do anything at time x and resumes his usual strategy at the time x + 1 (inclusive), which may lead to missing some red envelopes. Calculate the minimum number of coins Bob would get if Alice disturbs him optimally. Input The first line contains three non-negative integers n, m and k (1 ≤ n ≤ 10^5, 0 ≤ m ≤ 200, 1 ≤ k ≤ 10^5), denoting the length of the timeline, the number of times Alice can disturb Bob and the total number of red envelopes, respectively. The following k lines describe those k red envelopes. The i-th line contains four positive integers s_i, t_i, d_i and w_i (1 ≤ s_i ≤ t_i ≤ d_i ≤ n, 1 ≤ w_i ≤ 10^9) — the time segment when the i-th envelope is available, the time moment Bob can continue collecting after collecting the i-th envelope, and the number of coins in this envelope, respectively. Output Output one integer — the minimum number of coins Bob would get if Alice disturbs him optimally. Examples Input 5 0 2 1 3 4 5 2 5 5 8 Output 13 Input 10 1 6 1 1 2 4 2 2 6 2 3 3 3 3 4 4 4 5 5 5 5 7 6 6 6 9 Output 2 Input 12 2 6 1 5 5 4 4 6 6 2 3 8 8 3 2 9 9 5 6 10 10 7 8 12 12 9 Output 11 Note In the first sample, Alice has no chance to disturb Bob. Therefore Bob will collect the coins in the red envelopes at time 1 and 5, collecting 13 coins in total. In the second sample, Alice should disturb Bob at time 1. Therefore Bob skips the first envelope, collects the second one and can not do anything after that. So the answer is 2. ### Response ```cpp #include <bits/stdc++.h> using namespace std; multiset<pair<long long, long long> > s; vector<vector<pair<long long, long long> > > st, en; vector<pair<long long, long long> > gud; long long n, m, k; long long dp[100009][210]; long long f(long long pos, long long baki) { if (pos > n) return 0; long long &res = dp[pos][baki]; if (res != -1) return dp[pos][baki]; long long nxt = gud[pos].second; if (nxt == 0) nxt = pos; res = gud[pos].first + f(nxt + 1, baki); if (baki > 0) res = min(res, f(pos + 1, baki - 1)); return res; } int main() { cin >> n >> m >> k; gud.assign(n + 4, pair<long long, long long>(0, 0)); st.assign(n + 4, vector<pair<long long, long long> >()); en.assign(n + 4, vector<pair<long long, long long> >()); memset(dp, -1, sizeof dp); for (long long i = 0; i < k; i++) { long long si, ti, di, wi; cin >> si >> ti >> di >> wi; st[si].push_back(pair<long long, long long>(wi, di)); en[ti].push_back(pair<long long, long long>(wi, di)); } for (long long i = 1; i <= n; i++) { for (auto pr : st[i]) s.insert(pr); if (s.size() > 0) gud[i] = *(s.rbegin()); for (auto pr : en[i]) s.erase(s.find(pr)); } cout << f(1, m); return 0; } ```
### Prompt Generate a CPP solution to the following problem: You are given a rooted tree on n vertices, its root is the vertex number 1. The i-th vertex contains a number w_i. Split it into the minimum possible number of vertical paths in such a way that each path contains no more than L vertices and the sum of integers w_i on each path does not exceed S. Each vertex should belong to exactly one path. A vertical path is a sequence of vertices v_1, v_2, …, v_k where v_i (i ≥ 2) is the parent of v_{i - 1}. Input The first line contains three integers n, L, S (1 ≤ n ≤ 10^5, 1 ≤ L ≤ 10^5, 1 ≤ S ≤ 10^{18}) — the number of vertices, the maximum number of vertices in one path and the maximum sum in one path. The second line contains n integers w_1, w_2, …, w_n (1 ≤ w_i ≤ 10^9) — the numbers in the vertices of the tree. The third line contains n - 1 integers p_2, …, p_n (1 ≤ p_i < i), where p_i is the parent of the i-th vertex in the tree. Output Output one number — the minimum number of vertical paths. If it is impossible to split the tree, output -1. Examples Input 3 1 3 1 2 3 1 1 Output 3 Input 3 3 6 1 2 3 1 1 Output 2 Input 1 1 10000 10001 Output -1 Note In the first sample the tree is split into \{1\},\ \{2\},\ \{3\}. In the second sample the tree is split into \{1,\ 2\},\ \{3\} or \{1,\ 3\},\ \{2\}. In the third sample it is impossible to split the tree. ### Response ```cpp #include <bits/stdc++.h> using namespace std; long long n, L, S; int w[100001]; int p[100001]; int d[100001]; bool vis[100001]; vector<int> at[100001]; int ret = 0; void solve(int cur) { if (vis[cur]) return; ret++; long long weight = S; int cnt = L; while (weight - w[cur] >= 0 && cnt - 1 >= 0 && cur) { weight -= w[cur]; cnt--; vis[cur] = 1; cur = p[cur]; } } int main() { cout << setprecision(10); ios::sync_with_stdio(0); cin.tie(0); cin >> n >> L >> S; for (int i = 1; i <= n; i++) { cin >> w[i]; if (w[i] > S) { cout << -1 << '\n'; return 0; } } for (int i = 2; i <= n; i++) { cin >> p[i]; d[i] = d[p[i]] + 1; at[d[i]].push_back(i); } at[0].push_back(1); for (int dep = n; dep >= 0; dep--) for (auto e : at[dep]) solve(e); cout << ret << '\n'; return 0; } ```
### Prompt Construct a Cpp code solution to the problem outlined: The Third Doctor Who once correctly said that travel between parallel universes is "like travelling sideways". However, he incorrectly thought that there were infinite parallel universes, whereas in fact, as we now all know, there will never be more than 250. Heidi recently got her hands on a multiverse observation tool. She was able to see all n universes lined up in a row, with non-existent links between them. She also noticed that the Doctor was in the k-th universe. The tool also points out that due to restrictions originating from the space-time discontinuum, the number of universes will never exceed m. Obviously, the multiverse is unstable because of free will. Each time a decision is made, one of two events will randomly happen: a new parallel universe is created, or a non-existent link is broken. More specifically, * When a universe is created, it will manifest itself between any two adjacent universes or at one of the ends. * When a link is broken, it could be cut between any two adjacent universes. After separating the multiverse into two segments, the segment NOT containing the Doctor will cease to exist. Heidi wants to perform a simulation of t decisions. Each time a decision is made, Heidi wants to know the length of the multiverse (i.e. the number of universes), and the position of the Doctor. Input The first line contains four integers n, k, m and t (2 ≤ k ≤ n ≤ m ≤ 250, 1 ≤ t ≤ 1000). Each of the following t lines is in one of the following formats: * "1 i" — meaning that a universe is inserted at the position i (1 ≤ i ≤ l + 1), where l denotes the current length of the multiverse. * "0 i" — meaning that the i-th link is broken (1 ≤ i ≤ l - 1), where l denotes the current length of the multiverse. Output Output t lines. Each line should contain l, the current length of the multiverse and k, the current position of the Doctor. It is guaranteed that the sequence of the steps will be valid, i.e. the multiverse will have length at most m and when the link breaking is performed, there will be at least one universe in the multiverse. Example Input 5 2 10 4 0 1 1 1 0 4 1 2 Output 4 1 5 2 4 2 5 3 Note The multiverse initially consisted of 5 universes, with the Doctor being in the second. First, link 1 was broken, leaving the multiverse with 4 universes, and the Doctor in the first. Then, a universe was added to the leftmost end of the multiverse, increasing the multiverse length to 5, and the Doctor was then in the second universe. Then, the rightmost link was broken. Finally, a universe was added between the first and the second universe. ### Response ```cpp #include <bits/stdc++.h> using namespace std; void err(istream_iterator<string> it) { cout << endl; } template <typename T, typename... Args> void err(istream_iterator<string> it, T a, Args... args) { cerr << *it << " = " << a << ' '; err(++it, args...); } int dx[8] = {1, 0, -1, 0, -1, -1, 1, 1}; int dy[8] = {0, 1, 0, -1, -1, 1, -1, 1}; int ini() { int x; scanf("%d", &x); return x; } long long inl() { long long x; scanf("%lld", &x); return x; } int set_1(int n, int pos) { return n = (n | (1 << pos)); } int reset_0(int n, int pos) { return n = n & ~(1 << pos); } bool check_bit(int n, int pos) { return n = n & (1 << pos); } const int N = (int)1e6 + 5; const int M = (int)1e9 + 7; const double pi = 2 * acos(0.0); int main() { int n, k, m, t; cin >> n >> k >> m >> t; int pos = k, sz = n; while (t--) { int op, x; cin >> op >> x; if (op == 0) { if (x < pos) { pos = pos - x; sz = sz - x; } else if (x > pos) { sz = x; } else { sz = pos; } } else { sz++; if (x <= pos) { pos += 1; } } cout << sz << " " << pos << endl; } return 0; } ```
### Prompt Please create a solution in CPP to the following problem: Consider a tree T (that is, a connected graph without cycles) with n vertices labelled 1 through n. We start the following process with T: while T has more than one vertex, do the following: * choose a random edge of T equiprobably; * shrink the chosen edge: if the edge was connecting vertices v and u, erase both v and u and create a new vertex adjacent to all vertices previously adjacent to either v or u. The new vertex is labelled either v or u equiprobably. At the end of the process, T consists of a single vertex labelled with one of the numbers 1, …, n. For each of the numbers, what is the probability of this number becoming the label of the final vertex? Input The first line contains a single integer n (1 ≤ n ≤ 50). The following n - 1 lines describe the tree edges. Each of these lines contains two integers u_i, v_i — labels of vertices connected by the respective edge (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i). It is guaranteed that the given graph is a tree. Output Print n floating numbers — the desired probabilities for labels 1, …, n respectively. All numbers should be correct up to 10^{-6} relative or absolute precision. Examples Input 4 1 2 1 3 1 4 Output 0.1250000000 0.2916666667 0.2916666667 0.2916666667 Input 7 1 2 1 3 2 4 2 5 3 6 3 7 Output 0.0850694444 0.0664062500 0.0664062500 0.1955295139 0.1955295139 0.1955295139 0.1955295139 Note In the first sample, the resulting vertex has label 1 if and only if for all three edges the label 1 survives, hence the probability is 1/2^3 = 1/8. All other labels have equal probability due to symmetry, hence each of them has probability (1 - 1/8) / 3 = 7/24. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 55; vector<int> g[N]; double f[N][N], F[N], tmp[N], C[N][N]; int n, siz[N]; void Solve(int x, int fa) { f[x][0] = 1; siz[x] = 1; for (int v : g[x]) { if (v == fa) continue; Solve(v, x); double pob = 1. / siz[v]; for (int i = 0; i <= siz[v]; i++) F[i] = 0; for (int i = 0; i <= siz[v]; i++) for (int j = 0; j < siz[v]; j++) if (j < i) F[i] += pob * f[v][i - 1]; else F[i] += 0.5 * pob * f[v][j]; for (int i = 0; i < siz[x]; i++) tmp[i] = f[x][i], f[x][i] = 0; for (int i = 0; i < siz[x]; i++) for (int j = 0; j <= siz[v]; j++) { f[x][i + j] += F[j] * tmp[i] * C[siz[x] - 1][i] * C[siz[v]][j] / C[siz[x] - 1 + siz[v]][i + j]; } siz[x] += siz[v]; } } int main(void) { scanf("%d", &n); C[0][0] = 1; for (int i = 1; i < n; i++) { C[i][0] = 1; for (int j = 1; j <= i; j++) C[i][j] = C[i - 1][j] + C[i - 1][j - 1]; } for (int i = 1; i < n; i++) { int u, v; scanf("%d%d", &u, &v); g[u].push_back(v); g[v].push_back(u); } for (int i = 1; i <= n; i++) { memset(f, 0, sizeof f); Solve(i, 0); printf("%.10f\n", f[i][0]); } return 0; } ```
### Prompt In CPP, your task is to solve the following problem: Dr. Fukuoka has placed a simple robot in a two-dimensional maze. It moves within the maze and never goes out of the maze as there is no exit. The maze is made up of H × W grid cells as depicted below. The upper side of the maze faces north. Consequently, the right, lower and left sides face east, south and west respectively. Each cell is either empty or wall and has the coordinates of (i, j) where the north-west corner has (1, 1). The row i goes up toward the south and the column j toward the east. <image> The robot moves on empty cells and faces north, east, south or west. It goes forward when there is an empty cell in front, and rotates 90 degrees to the right when it comes in front of a wall cell or on the edge of the maze. It cannot enter the wall cells. It stops right after moving forward by L cells. Your mission is, given the initial position and direction of the robot and the number of steps, to write a program to calculate the final position and direction of the robot. Input The input is a sequence of datasets. Each dataset is formatted as follows. H W L c1,1c1,2...c1,W . . . cH,1cH,2...cH,W The first line of a dataset contains three integers H, W and L (1 ≤ H, W ≤ 100, 1 ≤ L ≤ 1018). Each of the following H lines contains exactly W characters. In the i-th line, the j-th character ci,j represents a cell at (i, j) of the maze. "." denotes an empty cell. "#" denotes a wall cell. "N", "E", "S", "W" denote a robot on an empty cell facing north, east, south and west respectively; it indicates the initial position and direction of the robot. You can assume that there is at least one empty cell adjacent to the initial position of the robot. The end of input is indicated by a line with three zeros. This line is not part of any dataset. Output For each dataset, output in a line the final row, column and direction of the robot, separated by a single space. The direction should be one of the following: "N" (north), "E" (east), "S" (south) and "W" (west). No extra spaces or characters are allowed. Examples Input 3 3 10 E.. .#. ... 5 5 19 ####. ..... .#S#. ...#. #.##. 5 5 6 #.#.. #.... ##.#. #..S. #.... 5 4 35 ..## .... .##. .#S. ...# 0 0 0 Output 1 3 E 4 5 S 4 4 E 1 1 N Input 3 3 10 E.. .#. ... 5 5 19 . ..... .#S#. ...#. .##. 5 5 6 .#.. .... .#. ..S. .... 5 4 35 ..## .... .##. .#S. ...# 0 0 0 Output 1 3 E 4 5 S 4 4 E 1 1 N ### Response ```cpp #include <bits/stdc++.h> #define rep(i, a, n) for(int i = a; i < n; i++) #define REP(i, n) rep(i, 0, n) #define repb(i, a, b) for(int i = a; i >= b; i--) #define all(a) a.begin(), a.end() #define int long long #define chmax(x, y) x = max(x, y) #define chmin(x, y) x = min(x, y) using namespace std; typedef pair<int, int> P; typedef pair<P, int> PP; const int mod = 1000000007; const int INF = 1e12; char c[110][110]; int d[110][110][4]; int h, w, l; string str = "NESW"; int dy[4] = {-1, 0, 1, 0}; int dx[4] = { 0, 1, 0,-1}; bool contain(int y, int x){ return (0 <= y && y < h && 0 <= x && x < w); } signed main(){ ios::sync_with_stdio(false); cin.tie(0); while(1){ cin >> h >> w >> l; if(h + w + l == 0) break; int dr = 0, y = 0, x = 0; rep(i, 0, 110) rep(j, 0, 110) rep(k, 0, 4) d[i][j][k] = -1; rep(i, 0, h){ rep(j, 0, w){ cin >> c[i][j]; if(str.find(c[i][j]) != string::npos){ dr = str.find(c[i][j]); y = i; x = j; } } } d[y][x][dr] = 0; vector<PP> sv; sv.push_back(PP(P(y, x), dr)); for(int i = 1;; i++){ int ny = 0, nx = 0; while(1){ ny = y + dy[dr]; nx = x + dx[dr]; if(contain(ny, nx) && c[ny][nx] != '#'){ break; } dr = (dr + 1) % 4; } y = ny; x = nx; if(i == l){ cout << y + 1 << ' ' << x + 1 << ' ' << str[dr] << endl; break; } if(d[y][x][dr] != -1){ int loop = i - d[y][x][dr]; int step = d[y][x][dr] + (l - d[y][x][dr]) % loop; //cerr << loop << ' ' << step << endl; cout << sv[step].first.first + 1 << ' ' << sv[step].first.second + 1 << ' ' << str[sv[step].second] << endl; break; } d[y][x][dr] = i; sv.push_back(PP(P(y, x), dr)); } } } ```
### Prompt Create a solution in cpp for the following problem: a is an array of n positive integers, all of which are not greater than n. You have to process q queries to this array. Each query is represented by two numbers p and k. Several operations are performed in each query; each operation changes p to p + ap + k. There operations are applied until p becomes greater than n. The answer to the query is the number of performed operations. Input The first line contains one integer n (1 ≤ n ≤ 100000). The second line contains n integers — elements of a (1 ≤ ai ≤ n for each i from 1 to n). The third line containts one integer q (1 ≤ q ≤ 100000). Then q lines follow. Each line contains the values of p and k for corresponding query (1 ≤ p, k ≤ n). Output Print q integers, ith integer must be equal to the answer to ith query. Example Input 3 1 1 1 3 1 1 2 1 3 1 Output 2 1 1 Note Consider first example: In first query after first operation p = 3, after second operation p = 5. In next two queries p is greater than n after the first operation. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int a, b, c, d, e, dp[100009][320], f[100009], q, sq; int main() { ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0); cin >> a; for (b = 1; b <= a; b++) cin >> f[b]; sq = sqrt(a); for (c = 1; c <= sq; c++) { for (d = a; d >= 1; d--) dp[d][c] = 1; for (d = a; d >= 1; d--) { if (d + f[d] + c > a) continue; dp[d][c] = dp[d + f[d] + c][c] + 1; } } cin >> q; for (b = 1; b <= q; b++) { cin >> c >> d; if (d <= sq) { cout << dp[c][d] << endl; } else { e = c; int h = 1; while (e <= a) { if (f[e] + e + d > a) break; h++; e = f[e] + e + d; } cout << h << endl; } } return 0; } ```
### Prompt Please provide a Cpp coded solution to the problem described below: Vasya goes to visit his classmate Petya. Vasya knows that Petya's apartment number is n. There is only one entrance in Petya's house and the distribution of apartments is the following: the first floor contains 2 apartments, every other floor contains x apartments each. Apartments are numbered starting from one, from the first floor. I.e. apartments on the first floor have numbers 1 and 2, apartments on the second floor have numbers from 3 to (x + 2), apartments on the third floor have numbers from (x + 3) to (2 ⋅ x + 2), and so on. Your task is to find the number of floor on which Petya lives. Assume that the house is always high enough to fit at least n apartments. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. Then t test cases follow. The only line of the test case contains two integers n and x (1 ≤ n, x ≤ 1000) — the number of Petya's apartment and the number of apartments on each floor of the house except the first one (there are two apartments on the first floor). Output For each test case, print the answer: the number of floor on which Petya lives. Example Input 4 7 3 1 5 22 5 987 13 Output 3 1 5 77 Note Consider the first test case of the example: the first floor contains apartments with numbers 1 and 2, the second one contains apartments with numbers 3, 4 and 5, the third one contains apartments with numbers 6, 7 and 8. Therefore, Petya lives on the third floor. In the second test case of the example, Petya lives in the apartment 1 which is on the first floor. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n, x; float ans; cin >> n; cin >> x; n = n - 2; if (n < 1) ans = 1; else { ans = ceil((float)n / x); ans++; } cout << ans << endl; } return 0; } ```
### Prompt Construct a CPP code solution to the problem outlined: This night wasn't easy on Vasya. His favorite team lost, and he didn't find himself victorious either — although he played perfectly, his teammates let him down every time. He had to win at least one more time, but the losestreak only grew longer and longer... It's no wonder he didn't get any sleep this night at all. In the morning, Vasya was waiting the bus to the university on the bus stop. Vasya's thoughts were hazy and so he couldn't remember the right bus' number quite right and got onto the bus with the number n. In the bus, Vasya thought that he could get the order of the digits in the number of the bus wrong. Futhermore, he could "see" some digits several times, but the digits he saw were definitely in the real number of the bus. For example, if Vasya saw the number 2028, it could mean that the real bus number could be 2028, 8022, 2820 or just 820. However, numbers 80, 22208, 52 definitely couldn't be the number of the bus. Also, real bus number couldn't start with the digit 0, this meaning that, for example, number 082 couldn't be the real bus number too. Given n, determine the total number of possible bus number variants. Input The first line contains one integer n (1 ≤ n ≤ 10^{18}) — the number of the bus that was seen by Vasya. It is guaranteed that this number does not start with 0. Output Output a single integer — the amount of possible variants of the real bus number. Examples Input 97 Output 2 Input 2028 Output 13 Note In the first sample, only variants 97 and 79 are possible. In the second sample, the variants (in the increasing order) are the following: 208, 280, 802, 820, 2028, 2082, 2208, 2280, 2802, 2820, 8022, 8202, 8220. ### Response ```cpp #include <bits/stdc++.h> using namespace std; #pragma comment(linker, "/stack:200000000") #pragma GCC optimize("Ofast") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") long long fact[20]; string str; int n; long long getAns() { map<vector<int>, bool> taken; long long ans = 0LL; int minCnt = 0; bool exists[10] = {}; for (long long i = 0; i < (n); ++i) if (!exists[str[i] - 48]) { exists[str[i] - 48] = true; ++minCnt; } for (long long i = 0; i < ((1 << n)); ++i) { vector<int> cnt(10); int curCnt = 0; int tempN = 0; for (long long j = 0; j < (n); ++j) if (i & (1 << j)) ++cnt[str[j] - 48]; for (long long i = 0; i < (10); ++i) if (cnt[i]) { tempN += cnt[i]; ++curCnt; } if (curCnt != minCnt) continue; if (!taken[cnt]) { taken[cnt] = true; long long temp = fact[tempN]; for (long long i = 0; i < (10); ++i) temp /= fact[cnt[i]]; if (cnt[0]) { long long diff = fact[tempN - 1]; --cnt[0]; for (long long i = 0; i < (10); ++i) diff /= fact[cnt[i]]; temp -= diff; } ans += temp; } } return ans; } int main() { ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); cin >> str; n = str.length(); fact[0] = 1LL; for (long long i = (1); i < (20); ++i) fact[i] = fact[i - 1] * i; cout << getAns() << '\n'; return 0; } ```
### Prompt Develop a solution in Cpp to the problem described below: Game field is represented by a line of n square cells. In some cells there are packmen, in some cells there are asterisks and the rest of the cells are empty. Packmen eat asterisks. Before the game starts you can choose a movement direction, left or right, for each packman. Once the game begins all the packmen simultaneously start moving according their directions. A packman can't change the given direction. Once a packman enters a cell containing an asterisk, packman immediately eats the asterisk. Once the packman leaves the cell it becomes empty. Each packman moves at speed 1 cell per second. If a packman enters a border cell, the packman stops. Packmen do not interfere with the movement of other packmen; in one cell there can be any number of packmen moving in any directions. Your task is to assign a direction to each packman so that they eat the maximal number of asterisks. If there are multiple ways to assign directions to eat the maximal number of asterisks, you should choose the way which minimizes the time to do that. Input The first line contains integer number n (2 ≤ n ≤ 1 000 000) — the number of cells in the game field. The second line contains n characters. If the i-th character is '.', the i-th cell is empty. If the i-th character is '*', the i-th cell contains an asterisk. If the i-th character is 'P', the i-th cell contains a packman. The field contains at least one asterisk and at least one packman. Output Print two integer numbers — the maximal number of asterisks packmen can eat and the minimal time to do it. Examples Input 6 *.P*P* Output 3 4 Input 8 *...P..* Output 1 3 Note In the first example the leftmost packman should move to the right, the rightmost packman should move to the left. All the asterisks will be eaten, the last asterisk will be eaten after 4 seconds. ### Response ```cpp #include <bits/stdc++.h> using namespace std; inline int in() { int x, y; y = scanf("%d", &x); return x; } const int MAXN = 2e6 + 10; int n, p[MAXN], sec[MAXN], pt[MAXN]; string s; int nxt[MAXN], prv[MAXN]; int d[MAXN][2]; bool ok(int mid, int sz) { memset(d, 0, sizeof(d)); d[0][0] = d[0][1] = 1; for (int i = 1; i <= n; i++) { if (s[i - 1] == '.') d[i][0] = d[i - 1][0]; else if (s[i - 1] == 'P') d[i][0] = d[i - 1][1]; else { int xx = prv[i - 1]; if (~xx && xx + mid >= i - 1) { d[i][0] |= d[xx][0]; int temp = prv[xx]; if (~temp && temp + mid >= i - 1) { int t = max(0, xx - mid); int temp2 = 0; if (t && nxt[t - 1] < temp) temp2 = 1; d[i][0] |= d[t][temp2]; } } } int xx = nxt[i - 1]; if (xx < n) { int temp = max(0, xx - mid); temp = min(temp, i); int temp2 = 0; if (temp && nxt[temp - 1] < xx) temp2 = 1; d[i][1] |= d[temp][temp2]; } } return d[n][0]; } int main() { ios::sync_with_stdio(false); cin.tie(0); cin >> n >> s; int sz = 0, c = 0; for (int i = 0; i < n; i++) if (s[i] == 'P') sec[sz++] = i; else if (s[i] == '*') c++; int mn = 1e9, mx = -1; for (int i = 0; i < n; i++) { p[i + 1] = p[i]; if (s[i] == '*') { p[i + 1]++; mn = min(mn, i); mx = max(mx, i); } } int last = n; for (int i = n - 1; ~i; i--) { nxt[i] = last; if (s[i] == 'P') last = i; } last = -1; for (int i = 0; i < n; i++) { prv[i] = last; if (s[i] == 'P') last = i; } memcpy(pt, p, sizeof(p)); if (sz == 1) { if (mn > sec[0]) cout << c << " " << mx - sec[0] << "\n"; else if (mx < sec[0]) cout << c << " " << sec[0] - mn << "\n"; else { if (p[sec[0]] > c - p[sec[0]]) cout << p[sec[0]] << " " << sec[0] - mn << "\n"; else if (p[sec[0]] < c - p[sec[0]]) cout << c - p[sec[0]] << " " << mx - sec[0] << "\n"; else cout << p[sec[0]] << " " << min(sec[0] - mn, mx - sec[0]) << "\n"; } } else { int lo = 0, hi = n - 1; while (hi - lo > 1) { int mid = hi + lo >> 1; if (ok(mid, sz)) hi = mid; else lo = mid; } cout << c << " " << hi << "\n"; } return 0; } ```
### Prompt Generate a cpp solution to the following problem: An African crossword is a rectangular table n × m in size. Each cell of the table contains exactly one letter. This table (it is also referred to as grid) contains some encrypted word that needs to be decoded. To solve the crossword you should cross out all repeated letters in rows and columns. In other words, a letter should only be crossed out if and only if the corresponding column or row contains at least one more letter that is exactly the same. Besides, all such letters are crossed out simultaneously. When all repeated letters have been crossed out, we should write the remaining letters in a string. The letters that occupy a higher position follow before the letters that occupy a lower position. If the letters are located in one row, then the letter to the left goes first. The resulting word is the answer to the problem. You are suggested to solve an African crossword and print the word encrypted there. Input The first line contains two integers n and m (1 ≤ n, m ≤ 100). Next n lines contain m lowercase Latin letters each. That is the crossword grid. Output Print the encrypted word on a single line. It is guaranteed that the answer consists of at least one letter. Examples Input 3 3 cba bcd cbc Output abcd Input 5 5 fcofd ooedo afaoa rdcdf eofsf Output codeforces ### Response ```cpp #include <bits/stdc++.h> using namespace std; const long long N = 1e6 + 1; map<pair<long long, long long>, long long> mp, pm; deque<long long> v, vc, ve; deque<char> p, pe; deque<string> ts, ss; deque<double> sd; long long a, b, c, d, e, f, cnt, ans, r, n, l; long double q, t, cnt1; string g, h, w, o, z, m, s; char y, u; bool re, rt; set<long long> st; vector<pair<long long, long long> > pr, rp; int main() { cin.tie(NULL); cout.tie(NULL); ios_base::sync_with_stdio(0); cin >> a >> b; char arr[a][b]; for (long long i = 0; i < a; i++) { cin >> g; for (long long j = 0; j < g.size(); j++) arr[i][j] = g[j]; } for (long long i = 0; i < a; i++) { for (long long j = 0; j < b; j++) { for (long long k = 0; k < b; k++) { if (j != k and (arr[i][j] == arr[i][k])) { mp[{i, j}]++; mp[{i, k}]++; if (mp[{i, j}] == 1) pr.push_back({i, j}); if (mp[{i, k}] == 1) pr.push_back({i, k}); } } } } for (long long i = 0; i < b; i++) { for (long long j = 0; j < a; j++) { for (long long k = 0; k < a; k++) { if (j != k and (arr[j][i] == arr[k][i])) { mp[{j, i}]++; mp[{k, i}]++; if (mp[{j, i}] == 1) pr.push_back({j, i}); if (mp[{k, i}] == 1) pr.push_back({k, i}); } } } } for (long long i = 0; i < a; i++) { for (long long j = 0; j < b; j++) { cnt = 0; for (long long k = 0; k < pr.size(); k++) { if (i == pr[k].first and j == pr[k].second) { cnt++; break; } } if (cnt == 0) cout << arr[i][j]; } } } ```
### Prompt Your task is to create a Cpp solution to the following problem: Again, there are hard times in Berland! Many towns have such tensions that even civil war is possible. There are n towns in Reberland, some pairs of which connected by two-way roads. It is not guaranteed that it is possible to reach one town from any other town using these roads. Towns s and t announce the final break of any relationship and intend to rule out the possibility of moving between them by the roads. Now possibly it is needed to close several roads so that moving from s to t using roads becomes impossible. Each town agrees to spend money on closing no more than one road, therefore, the total number of closed roads will be no more than two. Help them find set of no more than two roads such that there will be no way between s and t after closing these roads. For each road the budget required for its closure was estimated. Among all sets find such that the total budget for the closure of a set of roads is minimum. Input The first line of the input contains two integers n and m (2 ≤ n ≤ 1000, 0 ≤ m ≤ 30 000) — the number of towns in Berland and the number of roads. The second line contains integers s and t (1 ≤ s, t ≤ n, s ≠ t) — indices of towns which break up the relationships. Then follow m lines, each of them contains three integers xi, yi and wi (1 ≤ xi, yi ≤ n, 1 ≤ wi ≤ 109) — indices of towns connected by the i-th road, and the budget on its closure. All roads are bidirectional. It is allowed that the pair of towns is connected by more than one road. Roads that connect the city to itself are allowed. Output In the first line print the minimum budget required to break up the relations between s and t, if it is allowed to close no more than two roads. In the second line print the value c (0 ≤ c ≤ 2) — the number of roads to be closed in the found solution. In the third line print in any order c diverse integers from 1 to m — indices of closed roads. Consider that the roads are numbered from 1 to m in the order they appear in the input. If it is impossible to make towns s and t disconnected by removing no more than 2 roads, the output should contain a single line -1. If there are several possible answers, you may print any of them. Examples Input 6 7 1 6 2 1 6 2 3 5 3 4 9 4 6 4 4 6 5 4 5 1 3 1 3 Output 8 2 2 7 Input 6 7 1 6 2 3 1 1 2 2 1 3 3 4 5 4 3 6 5 4 6 6 1 5 7 Output 9 2 4 5 Input 5 4 1 5 2 1 3 3 2 1 3 4 4 4 5 2 Output 1 1 2 Input 2 3 1 2 1 2 734458840 1 2 817380027 1 2 304764803 Output -1 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int N = 1e3 + 2, M = 3e4 + 5; int a[M], b[M], w[M], dontgo, d[N], pos = 0, can[N], par[N]; vector<int> path, adj[N]; void dfs(int x, int prev) { int i, u, v; d[x] = can[x] = ++pos; for (i = 0; i < adj[x].size(); ++i) { u = adj[x][i]; if (prev != u && u != dontgo) { v = a[u] ^ b[u] ^ x; if (d[v]) can[x] = min(can[x], d[v]); else { dfs(v, u); par[v] = u; can[x] = min(can[x], can[v]); } } } } long long W = 2e9 + 5, R1 = -1, R2 = -1; void sol(long long w, int x, int y) { if (W > w) W = w, R1 = x, R2 = y; } int main() { int s, t, n, m, i, j; cin >> n >> m >> s >> t; for (i = 1; i <= m; ++i) scanf("%d%d%d", &a[i], &b[i], &w[i]), adj[a[i]].push_back(i), adj[b[i]].push_back(i); dfs(s, -1); if (d[t] == 0) { printf("0\n0\n"); return 0; } int u, v, node = t, pp; while (node != s) { pp = node ^ a[par[node]] ^ b[par[node]]; if (d[pp] < can[node]) sol(w[par[node]], par[node], -1); else path.push_back(par[node]); node = pp; } for (i = 0; i < path.size(); ++i) { u = path[i]; memset(can, 0, sizeof(can)); memset(d, 0, sizeof(d)); dontgo = u; dfs(s, -1); node = t; while (node != s) { pp = node ^ a[par[node]] ^ b[par[node]]; if (d[pp] < can[node]) sol(w[par[node]] + w[u], par[node], u); node = pp; } } if (W == 2e9 + 5) { printf("-1\n"); } else { cout << W << endl; cout << (R1 != -1) + (R2 != -1) << endl; if (R1 != -1) cout << R1 << " "; if (R2 != -1) cout << R2; cout << endl; } } ```
### Prompt In CPP, your task is to solve the following problem: You are given a picture consisting of n rows and m columns. Rows are numbered from 1 to n from the top to the bottom, columns are numbered from 1 to m from the left to the right. Each cell is painted either black or white. You think that this picture is not interesting enough. You consider a picture to be interesting if there is at least one cross in it. A cross is represented by a pair of numbers x and y, where 1 ≤ x ≤ n and 1 ≤ y ≤ m, such that all cells in row x and all cells in column y are painted black. For examples, each of these pictures contain crosses: <image> The fourth picture contains 4 crosses: at (1, 3), (1, 5), (3, 3) and (3, 5). Following images don't contain crosses: <image> You have a brush and a can of black paint, so you can make this picture interesting. Each minute you may choose a white cell and paint it black. What is the minimum number of minutes you have to spend so the resulting picture contains at least one cross? You are also asked to answer multiple independent queries. Input The first line contains an integer q (1 ≤ q ≤ 5 ⋅ 10^4) — the number of queries. The first line of each query contains two integers n and m (1 ≤ n, m ≤ 5 ⋅ 10^4, n ⋅ m ≤ 4 ⋅ 10^5) — the number of rows and the number of columns in the picture. Each of the next n lines contains m characters — '.' if the cell is painted white and '*' if the cell is painted black. It is guaranteed that ∑ n ≤ 5 ⋅ 10^4 and ∑ n ⋅ m ≤ 4 ⋅ 10^5. Output Print q lines, the i-th line should contain a single integer — the answer to the i-th query, which is the minimum number of minutes you have to spend so the resulting picture contains at least one cross. Example Input 9 5 5 ..*.. ..*.. ***** ..*.. ..*.. 3 4 **** .*.. .*.. 4 3 *** *.. *.. *.. 5 5 ***** *.*.* ***** ..*.* ..*** 1 4 **** 5 5 ..... ..*.. .***. ..*.. ..... 5 3 ... .*. .*. *** .*. 3 3 .*. *.* .*. 4 4 *.** .... *.** *.** Output 0 0 0 0 0 4 1 1 2 Note The example contains all the pictures from above in the same order. The first 5 pictures already contain a cross, thus you don't have to paint anything. You can paint (1, 3), (3, 1), (5, 3) and (3, 5) on the 6-th picture to get a cross in (3, 3). That'll take you 4 minutes. You can paint (1, 2) on the 7-th picture to get a cross in (4, 2). You can paint (2, 2) on the 8-th picture to get a cross in (2, 2). You can, for example, paint (1, 3), (3, 1) and (3, 3) to get a cross in (3, 3) but that will take you 3 minutes instead of 1. There are 9 possible crosses you can get in minimum time on the 9-th picture. One of them is in (1, 1): paint (1, 2) and (2, 1). ### Response ```cpp #include <bits/stdc++.h> using namespace std; const double pi = acos(-1.0); template <class T> inline T read() { 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(); } if (ch == '.') { ch = getchar(); while (ch >= '0' && ch <= '9') { x = x * 10 + ch - '0'; f *= 0.1; ch = getchar(); } } return x * f; } inline void readstr(char* s) { char ch = getchar(); int cnt = 0; while (ch == '\n' || ch == ' ') ch = getchar(); while (!(ch == '\n' || ch == ' ')) s[cnt++] = ch, ch = getchar(); s[cnt] = 0; } void debug(int f) { if (f) freopen("input.txt", "r", stdin); if (f == 2) freopen("output.txt", "w", stdout); } const int MOD = 1e9 + 7, INF = 0XFFFFFFF; const double eps = 1e-8; const int maxn = 5e4 + 5, maxm = 200005; int n, m; vector<char> c[maxn]; int x[maxn], y[maxn]; int main() { debug(0); int T = read<int>(); while (T--) { n = read<int>(), m = read<int>(); char str[maxn]; memset(x, 0, sizeof(x)); memset(y, 0, sizeof(y)); for (int i = 0; i < n; i++) { readstr(str); for (int j = 0; j < m; j++) c[i].push_back(str[j]); } for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { if (c[i][j] == '.') x[i]++, y[j]++; } int ans = n + m + 1; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { if (c[i][j] == '.') ans = min(ans, x[i] + y[j] - 1); else ans = min(ans, x[i] + y[j]); } printf("%d\n", ans); for (int i = 0; i < n; i++) c[i].clear(); } return 0; } ```
### Prompt Please provide a CPP coded solution to the problem described below: We are committed to the well being of all participants. Therefore, instead of the problem, we suggest you enjoy a piece of cake. Uh oh. Somebody cut the cake. We told them to wait for you, but they did it anyway. There is still some left, though, if you hurry back. Of course, before you taste the cake, you thought about how the cake was cut. It is known that the cake was originally a regular n-sided polygon, each vertex of which had a unique number from 1 to n. The vertices were numbered in random order. Each piece of the cake is a triangle. The cake was cut into n - 2 pieces as follows: each time one cut was made with a knife (from one vertex to another) such that exactly one triangular piece was separated from the current cake, and the rest continued to be a convex polygon. In other words, each time three consecutive vertices of the polygon were selected and the corresponding triangle was cut off. A possible process of cutting the cake is presented in the picture below. <image> Example of 6-sided cake slicing. You are given a set of n-2 triangular pieces in random order. The vertices of each piece are given in random order — clockwise or counterclockwise. Each piece is defined by three numbers — the numbers of the corresponding n-sided cake vertices. For example, for the situation in the picture above, you could be given a set of pieces: [3, 6, 5], [5, 2, 4], [5, 4, 6], [6, 3, 1]. You are interested in two questions. * What was the enumeration of the n-sided cake vertices? * In what order were the pieces cut? Formally, you have to find two permutations p_1, p_2, ..., p_n (1 ≤ p_i ≤ n) and q_1, q_2, ..., q_{n - 2} (1 ≤ q_i ≤ n - 2) such that if the cake vertices are numbered with the numbers p_1, p_2, ..., p_n in order clockwise or counterclockwise, then when cutting pieces of the cake in the order q_1, q_2, ..., q_{n - 2} always cuts off a triangular piece so that the remaining part forms one convex polygon. For example, in the picture above the answer permutations could be: p=[2, 4, 6, 1, 3, 5] (or any of its cyclic shifts, or its reversal and after that any cyclic shift) and q=[2, 4, 1, 3]. Write a program that, based on the given triangular pieces, finds any suitable permutations p and q. Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. Then there are t independent sets of input data. The first line of each set consists of a single integer n (3 ≤ n ≤ 10^5) — the number of vertices in the cake. The following n - 2 lines describe the numbers of the pieces vertices: each line consists of three different integers a, b, c (1 ≤ a, b, c ≤ n) — the numbers of the pieces vertices of cake given in random order. The pieces are given in random order. It is guaranteed that the answer to each of the tests exists. It is also guaranteed that the sum of n for all test cases does not exceed 10^5. Output Print 2t lines — answers to given t test cases in the order in which they are written in the input. Each answer should consist of 2 lines. In the first line of an answer on a test case print n distinct numbers p_1, p_2, ..., p_n(1 ≤ p_i ≤ n) — the numbers of the cake vertices in clockwise or counterclockwise order. In the second line of an answer on a test case print n - 2 distinct numbers q_1, q_2, ..., q_{n - 2}(1 ≤ q_i ≤ n - 2) — the order of cutting pieces of the cake. The number of a piece of the cake corresponds to its number in the input. If there are several answers, print any. It is guaranteed that the answer to each of the tests exists. Example Input 3 6 3 6 5 5 2 4 5 4 6 6 3 1 6 2 5 6 2 5 1 4 1 2 1 3 5 3 1 2 3 Output 1 6 4 2 5 3 4 2 3 1 1 4 2 6 5 3 3 4 2 1 1 3 2 1 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int MOD = 1000000007; const long long INF = 1e18; const long double PI = acos((long double)-1); const int xd[4] = {1, 0, -1, 0}, yd[4] = {0, 1, 0, -1}; const int MN = 1e5 + 5; int T, N, cnt[MN], lft[MN], rht[MN], deg[MN]; bool vis[MN], done[MN]; map<vector<int>, int> rev; vector<vector<int>> v; map<pair<int, int>, vector<int>> m; vector<int> g[MN]; inline void reset() { rev.clear(); v.clear(); m.clear(); } inline int not_common(vector<int> &a, vector<int> &b) { for (int i = 0; i < 3; i++) { if (find(begin(a), end(a), b[i]) != a.end()) continue; return b[i]; } assert(false); } inline void add(int a, int b, int n) { if (rht[a] != b) swap(a, b); lft[n] = a, rht[n] = b; rht[a] = n, lft[b] = n; } void dfs(int u, int p) { for (int ch : g[u]) { if (ch == p) continue; int n = not_common(v[u], v[ch]); vector<int> other; for (int ck : v[ch]) if (ck != n) other.push_back(ck); add(other[0], other[1], n); dfs(ch, u); } } int main() { ios::sync_with_stdio(0); cin.tie(0); cin >> T; while (T--) { cin >> N; reset(); for (int i = 0; i <= N; i++) { g[i].clear(), cnt[i] = 0; lft[i] = rht[i] = deg[i] = 0; vis[i] = done[i] = false; } for (int i = 3; i <= N; i++) { vector<int> t; for (int k = 0; k < 3; k++) { int a; cin >> a; t.push_back(a); cnt[a]++; } sort(begin(t), end(t)); v.push_back(t); m[{t[0], t[1]}].push_back(i - 3); m[{t[1], t[2]}].push_back(i - 3); m[{t[0], t[2]}].push_back(i - 3); } for (int i = 0; i < v.size(); i++) rev[v[i]] = i; int rt = -1, al = -1; vector<int> tmp; for (int i = 0; i < v.size(); i++) { for (int a = 0; a < 3; a++) { for (int b = a + 1; b < 3; b++) { vector<int> &v2 = m[{v[i][a], v[i][b]}]; for (int ck : v2) { if (ck == i) continue; g[i].push_back(ck); deg[i]++; } } if (cnt[v[i][a]] == 1) { rt = i, al = v[i][a]; if (a == 0) tmp = {v[i][1], v[i][2]}; else if (a == 1) tmp = {v[i][0], v[i][2]}; else tmp = {v[i][0], v[i][1]}; } } } rht[tmp[0]] = al, lft[tmp[0]] = tmp[1]; lft[tmp[1]] = al, rht[tmp[1]] = tmp[0]; lft[al] = tmp[0], rht[al] = tmp[1]; dfs(rt, -1); int curr = al; while (!vis[curr]) { vis[curr] = true; cout << curr << " "; curr = rht[curr]; } cout << "\n"; vector<int> t; for (int i = 0; i < v.size(); i++) if (deg[i] <= 1) done[i] = true, t.push_back(i); while (t.size()) { int n = t.back(); t.pop_back(); cout << n + 1 << " "; for (int ck : g[n]) { if (done[ck]) continue; deg[ck]--; if (deg[ck] <= 1) { done[ck] = true; t.push_back(ck); } } } cout << "\n"; } } ```
### Prompt Your challenge is to write a CPP solution to the following problem: You are given two segments [l_1; r_1] and [l_2; r_2] on the x-axis. It is guaranteed that l_1 < r_1 and l_2 < r_2. Segments may intersect, overlap or even coincide with each other. <image> The example of two segments on the x-axis. Your problem is to find two integers a and b such that l_1 ≤ a ≤ r_1, l_2 ≤ b ≤ r_2 and a ≠ b. In other words, you have to choose two distinct integer points in such a way that the first point belongs to the segment [l_1; r_1] and the second one belongs to the segment [l_2; r_2]. It is guaranteed that the answer exists. If there are multiple answers, you can print any of them. You have to answer q independent queries. Input The first line of the input contains one integer q (1 ≤ q ≤ 500) — the number of queries. Each of the next q lines contains four integers l_{1_i}, r_{1_i}, l_{2_i} and r_{2_i} (1 ≤ l_{1_i}, r_{1_i}, l_{2_i}, r_{2_i} ≤ 10^9, l_{1_i} < r_{1_i}, l_{2_i} < r_{2_i}) — the ends of the segments in the i-th query. Output Print 2q integers. For the i-th query print two integers a_i and b_i — such numbers that l_{1_i} ≤ a_i ≤ r_{1_i}, l_{2_i} ≤ b_i ≤ r_{2_i} and a_i ≠ b_i. Queries are numbered in order of the input. It is guaranteed that the answer exists. If there are multiple answers, you can print any. Example Input 5 1 2 1 2 2 6 3 4 2 4 1 3 1 2 1 3 1 4 5 8 Output 2 1 3 4 3 2 1 2 3 7 ### Response ```cpp #include <bits/stdc++.h> #pragma GCC optimize("Ofast,unroll-loops,no-stack-protector,fast-math") #pragma GCC target( \ "sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,tune=native") #pragma comment(linker, "/STACK:16777216") using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); long long q; cin >> q; while (q--) { long long a, b, c, d; cin >> a >> b >> c >> d; cout << a << " "; if (a == c) { cout << d << '\n'; } else { cout << c << '\n'; } } return 0; } ```
### Prompt Generate a cpp solution to the following problem: Polycarp has a lot of work to do. Recently he has learned a new time management rule: "if a task takes five minutes or less, do it immediately". Polycarp likes the new rule, however he is not sure that five minutes is the optimal value. He supposes that this value d should be chosen based on existing task list. Polycarp has a list of n tasks to complete. The i-th task has difficulty p_i, i.e. it requires exactly p_i minutes to be done. Polycarp reads the tasks one by one from the first to the n-th. If a task difficulty is d or less, Polycarp starts the work on the task immediately. If a task difficulty is strictly greater than d, he will not do the task at all. It is not allowed to rearrange tasks in the list. Polycarp doesn't spend any time for reading a task or skipping it. Polycarp has t minutes in total to complete maximum number of tasks. But he does not want to work all the time. He decides to make a break after each group of m consecutive tasks he was working on. The break should take the same amount of time as it was spent in total on completion of these m tasks. For example, if n=7, p=[3, 1, 4, 1, 5, 9, 2], d=3 and m=2 Polycarp works by the following schedule: * Polycarp reads the first task, its difficulty is not greater than d (p_1=3 ≤ d=3) and works for 3 minutes (i.e. the minutes 1, 2, 3); * Polycarp reads the second task, its difficulty is not greater than d (p_2=1 ≤ d=3) and works for 1 minute (i.e. the minute 4); * Polycarp notices that he has finished m=2 tasks and takes a break for 3+1=4 minutes (i.e. on the minutes 5, 6, 7, 8); * Polycarp reads the third task, its difficulty is greater than d (p_3=4 > d=3) and skips it without spending any time; * Polycarp reads the fourth task, its difficulty is not greater than d (p_4=1 ≤ d=3) and works for 1 minute (i.e. the minute 9); * Polycarp reads the tasks 5 and 6, skips both of them (p_5>d and p_6>d); * Polycarp reads the 7-th task, its difficulty is not greater than d (p_7=2 ≤ d=3) and works for 2 minutes (i.e. the minutes 10, 11); * Polycarp notices that he has finished m=2 tasks and takes a break for 1+2=3 minutes (i.e. on the minutes 12, 13, 14). Polycarp stops exactly after t minutes. If Polycarp started a task but has not finished it by that time, the task is not considered as completed. It is allowed to complete less than m tasks in the last group. Also Polycarp considers acceptable to have shorter break than needed after the last group of tasks or even not to have this break at all — his working day is over and he will have enough time to rest anyway. Please help Polycarp to find such value d, which would allow him to complete maximum possible number of tasks in t minutes. Input The first line of the input contains single integer c (1 ≤ c ≤ 5 ⋅ 10^4) — number of test cases. Then description of c test cases follows. Solve test cases separately, test cases are completely independent and do not affect each other. Each test case is described by two lines. The first of these lines contains three space-separated integers n, m and t (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ 2 ⋅ 10^5, 1 ≤ t ≤ 4 ⋅ 10^{10}) — the number of tasks in Polycarp's list, the number of tasks he can do without a break and the total amount of time Polycarp can work on tasks. The second line of the test case contains n space separated integers p_1, p_2, ..., p_n (1 ≤ p_i ≤ 2 ⋅ 10^5) — difficulties of the tasks. The sum of values n for all test cases in the input does not exceed 2 ⋅ 10^5. Output Print c lines, each line should contain answer for the corresponding test case — the maximum possible number of tasks Polycarp can complete and the integer value d (1 ≤ d ≤ t) Polycarp should use in time management rule, separated by space. If there are several possible values d for a test case, output any of them. Examples Input 4 5 2 16 5 6 1 4 7 5 3 30 5 6 1 4 7 6 4 15 12 5 15 7 20 17 1 1 50 100 Output 3 5 4 7 2 10 0 25 Input 3 11 1 29 6 4 3 7 5 3 4 7 3 5 3 7 1 5 1 1 1 1 1 1 1 5 2 18 2 3 3 7 5 Output 4 3 3 1 4 5 Note In the first test case of the first example n=5, m=2 and t=16. The sequence of difficulties is [5, 6, 1, 4, 7]. If Polycarp chooses d=5 then he will complete 3 tasks. Polycarp will work by the following schedule: * Polycarp reads the first task, its difficulty is not greater than d (p_1=5 ≤ d=5) and works for 5 minutes (i.e. the minutes 1, 2, ..., 5); * Polycarp reads the second task, its difficulty is greater than d (p_2=6 > d=5) and skips it without spending any time; * Polycarp reads the third task, its difficulty is not greater than d (p_3=1 ≤ d=5) and works for 1 minute (i.e. the minute 6); * Polycarp notices that he has finished m=2 tasks and takes a break for 5+1=6 minutes (i.e. on the minutes 7, 8, ..., 12); * Polycarp reads the fourth task, its difficulty is not greater than d (p_4=4 ≤ d=5) and works for 4 minutes (i.e. the minutes 13, 14, 15, 16); * Polycarp stops work because of t=16. In total in the first test case Polycarp will complete 3 tasks for d=5. He can't choose other value for d to increase the number of completed tasks. ### Response ```cpp #include <bits/stdc++.h> using namespace std; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); const int N = 200200; int n, m; long long t; long long a[N]; long long b[N]; bool solve(int k) { int kk = k - k % m; if (kk == k) kk -= m; int pos = 0; long long T = t; for (int i = 0; pos < k; i++) { if (a[i] > b[k - 1]) continue; T -= a[i]; if (pos < kk) T -= a[i]; if (T < 0) return false; pos++; } return true; } void solve() { scanf("%d%d%lld", &n, &m, &t); for (int i = 0; i < n; i++) { scanf("%lld", &a[i]); b[i] = a[i]; } sort(b, b + n); int l = 0, r = n + 1; while (r - l > 1) { int x = (l + r) / 2; if (solve(x)) l = x; else r = x; } printf("%d %lld\n", l, (l == 0 ? 1 : b[l - 1])); } int main() { int T; scanf("%d", &T); while (T--) solve(); return 0; } ```
### Prompt Develop a solution in Cpp to the problem described below: Snuke has a blackboard and a set S consisting of N integers. The i-th element in S is S_i. He wrote an integer X on the blackboard, then performed the following operation N times: * Choose one element from S and remove it. * Let x be the number written on the blackboard now, and y be the integer removed from S. Replace the number on the blackboard with x \bmod {y}. There are N! possible orders in which the elements are removed from S. For each of them, find the number that would be written on the blackboard after the N operations, and compute the sum of all those N! numbers modulo 10^{9}+7. Constraints * All values in input are integers. * 1 \leq N \leq 200 * 1 \leq S_i, X \leq 10^{5} * S_i are pairwise distinct. Input Input is given from Standard Input in the following format: N X S_1 S_2 \ldots S_{N} Output Print the answer. Examples Input 2 19 3 7 Output 3 Input 5 82 22 11 6 5 13 Output 288 Input 10 100000 50000 50001 50002 50003 50004 50005 50006 50007 50008 50009 Output 279669259 ### Response ```cpp #include<bits/stdc++.h> #define ll long long #define fornum(A,B,C) for(A=B;A<C;A++) #define mp make_pair #define pii pair<int,int> #define pll pair<ll,ll> using namespace std; ///////////////////////////////////////////////////// #define MOD (ll)(1e9+7) ll N,X; ll dp[202][101010]; ll S[222]; ll i,j,k; int main(){ scanf("%lld%lld", &N ,& X); fornum(i,0,N){ scanf("%lld", &S[i]); } sort(S, S + N, greater<ll>()); dp[0][X] = 1; fornum(i,0,N){ fornum(j,0,X+1){ dp[i+1][j % S[i]] =(dp[i+1][j % S[i]] + dp[i][j])%MOD; } fornum(j,0,X+1){ dp[i + 1][j] = (dp[i+1][j]+dp[i][j] * (N-1-i)) % MOD; } } ll ans = 0; fornum(i,0,S[N-1]){ ans = (ans+dp[N][i] * i)%MOD; } printf("%lld", ans); return 0; } ```
### Prompt Your task is to create a cpp solution to the following problem: Polycarp is very careful. He even types numeric sequences carefully, unlike his classmates. If he sees a sequence without a space after the comma, with two spaces in a row, or when something else does not look neat, he rushes to correct it. For example, number sequence written like "1,2 ,3,..., 10" will be corrected to "1, 2, 3, ..., 10". In this task you are given a string s, which is composed by a concatination of terms, each of which may be: * a positive integer of an arbitrary length (leading zeroes are not allowed), * a "comma" symbol (","), * a "space" symbol (" "), * "three dots" ("...", that is, exactly three points written one after another, also known as suspension points). Polycarp wants to add and remove spaces in the string s to ensure the following: * each comma is followed by exactly one space (if the comma is the last character in the string, this rule does not apply to it), * each "three dots" term is preceded by exactly one space (if the dots are at the beginning of the string, this rule does not apply to the term), * if two consecutive numbers were separated by spaces only (one or more), then exactly one of them should be left, * there should not be other spaces. Automate Polycarp's work and write a program that will process the given string s. Input The input data contains a single string s. Its length is from 1 to 255 characters. The string s does not begin and end with a space. Its content matches the description given above. Output Print the string s after it is processed. Your program's output should be exactly the same as the expected answer. It is permissible to end output line with a line-break character, and without it. Examples Input 1,2 ,3,..., 10 Output 1, 2, 3, ..., 10 Input 1,,,4...5......6 Output 1, , , 4 ...5 ... ...6 Input ...,1,2,3,... Output ..., 1, 2, 3, ... ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { string str; getline(cin, str); string ans; int cnt = 0; bool check = false; for (int i = 0; i < str.size(); i++) { char ch = str[i]; if (!isdigit(ch)) { if (ch == ',') { ans.push_back(','); ans.push_back(' '); } if (ch == '.') cnt++; if (cnt == 3) { ans.push_back(' '); ans.push_back('.'); ans.push_back('.'); ans.push_back('.'); cnt = 0; } if (ch == ' ') { if (isdigit(str[i - 1])) { check = true; } if (check) { if (isdigit(str[i + 1])) { ans.push_back(' '); check = false; } } if (str[i + 1] != ch) check = false; } } else ans.push_back(ch); } int low = 0, high = ans.size() - 1; while (ans[low] == ' ') { ans[low] = '-'; low++; } while (ans[high] == ' ') { ans[high] = '-'; high--; } for (int i = 0; i < ans.size() - 1; i++) { if ((ans[i] == ' ') && (ans[i + 1] == ' ')) ans[i] = '-'; } for (int i = 0; i < ans.size(); i++) { if (ans[i] != '-') cout << ans[i]; } return 0; } ```
### Prompt Please create a solution in Cpp to the following problem: You are given the following concurrent program. There are N processes and the i-th process has the following pseudocode: repeat ni times yi := y y := yi + 1 end repeat Here y is a shared variable. Everything else is local for the process. All actions on a given row are atomic, i.e. when the process starts executing a row it is never interrupted. Beyond that all interleavings are possible, i.e. every process that has yet work to do can be granted the rights to execute its next row. In the beginning y = 0. You will be given an integer W and ni, for i = 1, ... , N. Determine if it is possible that after all processes terminate, y = W, and if it is possible output an arbitrary schedule that will produce this final value. Input In the first line of the input you will be given two space separated integers N (1 ≤ N ≤ 100) and W ( - 109 ≤ W ≤ 109). In the second line there are N space separated integers ni (1 ≤ ni ≤ 1000). Output On the first line of the output write Yes if it is possible that at the end y = W, or No otherwise. If the answer is No then there is no second line, but if the answer is Yes, then on the second line output a space separated list of integers representing some schedule that leads to the desired result. For more information see note. Examples Input 1 10 11 Output No Input 2 3 4 4 Output Yes 1 1 2 1 2 2 2 2 2 1 2 1 1 1 1 2 Input 3 6 1 2 3 Output Yes 1 1 2 2 2 2 3 3 3 3 3 3 Note For simplicity, assume that there is no repeat statement in the code of the processes, but the code from the loop is written the correct amount of times. The processes are numbered starting from 1. The list of integers represent which process works on its next instruction at a given step. For example, consider the schedule 1 2 2 1 3. First process 1 executes its first instruction, then process 2 executes its first two instructions, after that process 1 executes its second instruction, and finally process 3 executes its first instruction. The list must consists of exactly 2·Σ i = 1...N ni numbers. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int n; long long sum, W, w; struct A { int id, val; } a[102]; bool comp(A x, A y) { return (x.val < y.val); } int main() { int i, j; cin >> n >> W; sum = 0LL; for (i = 1; i <= n; i++) { a[i].id = i; cin >> a[i].val; sum += (long long)a[i].val; } sort(&a[1], &a[n + 1], comp); if (W <= 0LL || W > sum || (n == 1 && sum != W) || (a[1].val > 1 && W == 1LL)) cout << "No"; else if (W == sum) { cout << "Yes" << endl; printf("%d %d", a[1].id, a[1].id); a[1].val--; for (i = 1; i <= n; i++) for (; a[i].val > 0; a[i].val--) printf(" %d %d", a[i].id, a[i].id); } else if (W >= a[1].val) { cout << "Yes" << endl; w = sum - W; printf("%d", a[1].id); a[1].val--; for (i = 2; i <= n && w > 0; i++) for (; a[i].val > 0 && w > 0; a[i].val--) w--, printf(" %d %d", a[i].id, a[i].id); printf(" %d", a[1].id); for (i = 1; i <= n; i++) for (; a[i].val > 0; a[i].val--) printf(" %d %d", a[i].id, a[i].id); } else { cout << "Yes" << endl; printf("%d", a[1].id); a[1].val--; for (; a[2].val > 1; a[2].val--) printf(" %d %d", a[2].id, a[2].id); printf(" %d", a[1].id); printf(" %d", a[2].id); w = W - 2; for (; a[1].val > w; a[1].val--) printf(" %d %d", a[1].id, a[1].id); for (i = 3; i <= n; i++) for (; a[i].val > 0; a[i].val--) printf(" %d %d", a[i].id, a[i].id); printf(" %d", a[2].id); for (; a[1].val > 0; a[1].val--) printf(" %d %d", a[1].id, a[1].id); } return 0; } ```
### Prompt In Cpp, your task is to solve the following problem: In this problem, we only consider strings consisting of lowercase English letters. Strings s and t are said to be isomorphic when the following conditions are satisfied: * |s| = |t| holds. * For every pair i, j, one of the following holds: * s_i = s_j and t_i = t_j. * s_i \neq s_j and t_i \neq t_j. For example, `abcac` and `zyxzx` are isomorphic, while `abcac` and `ppppp` are not. A string s is said to be in normal form when the following condition is satisfied: * For every string t that is isomorphic to s, s \leq t holds. Here \leq denotes lexicographic comparison. For example, `abcac` is in normal form, but `zyxzx` is not since it is isomorphic to `abcac`, which is lexicographically smaller than `zyxzx`. You are given an integer N. Print all strings of length N that are in normal form, in lexicographically ascending order. Constraints * 1 \leq N \leq 10 * All values in input are integers. Input Input is given from Standard Input in the following format: N Output Assume that there are K strings of length N that are in normal form: w_1, \ldots, w_K in lexicographical order. Output should be in the following format: w_1 : w_K Output Assume that there are K strings of length N that are in normal form: w_1, \ldots, w_K in lexicographical order. Output should be in the following format: w_1 : w_K Examples Input 1 Output a Input 2 Output aa ab ### Response ```cpp #include <bits/stdc++.h> using namespace std; int N; void dfs(string s, char c) { if (s.size() == N) { cout << s << endl; } else { for (char i = 'a'; i <= c; i++) { if (i != c) dfs(s + i, c); else dfs(s + i, c + 1); } } } int main() { cin >> N; dfs("", 'a'); } ```
### Prompt Create a solution in Cpp for the following problem: Suppose you have two polynomials <image> and <image>. Then polynomial <image> can be uniquely represented in the following way: <image> This can be done using [long division](https://en.wikipedia.org/wiki/Polynomial_long_division). Here, <image> denotes the degree of polynomial P(x). <image> is called the remainder of division of polynomial <image> by polynomial <image>, it is also denoted as <image>. Since there is a way to divide polynomials with remainder, we can define Euclid's algorithm of finding the greatest common divisor of two polynomials. The algorithm takes two polynomials <image>. If the polynomial <image> is zero, the result is <image>, otherwise the result is the value the algorithm returns for pair <image>. On each step the degree of the second argument decreases, so the algorithm works in finite number of steps. But how large that number could be? You are to answer this question. You are given an integer n. You have to build two polynomials with degrees not greater than n, such that their coefficients are integers not exceeding 1 by their absolute value, the leading coefficients (ones with the greatest power of x) are equal to one, and the described Euclid's algorithm performs exactly n steps finding their greatest common divisor. Moreover, the degree of the first polynomial should be greater than the degree of the second. By a step of the algorithm we mean the transition from pair <image> to pair <image>. Input You are given a single integer n (1 ≤ n ≤ 150) — the number of steps of the algorithm you need to reach. Output Print two polynomials in the following format. In the first line print a single integer m (0 ≤ m ≤ n) — the degree of the polynomial. In the second line print m + 1 integers between - 1 and 1 — the coefficients of the polynomial, from constant to leading. The degree of the first polynomial should be greater than the degree of the second polynomial, the leading coefficients should be equal to 1. Euclid's algorithm should perform exactly n steps when called using these polynomials. If there is no answer for the given n, print -1. If there are multiple answer, print any of them. Examples Input 1 Output 1 0 1 0 1 Input 2 Output 2 -1 0 1 1 0 1 Note In the second example you can print polynomials x2 - 1 and x. The sequence of transitions is (x2 - 1, x) → (x, - 1) → ( - 1, 0). There are two steps in it. ### Response ```cpp #include <bits/stdc++.h> using namespace std; long long min(long long a, long long b) { if (a < b) return a; else return b; } static long long gcd(long long a, long long b) { long long r; while (b != 0) { r = a % b; a = b; b = r; } return a; } long long lcm(long long a, long long b) { long long temp = gcd(a, b); return temp ? (a / temp * b) : 0; } unsigned long long PowMod(unsigned long long x, unsigned long long e, unsigned long long mod) { unsigned long long res; if (e == 0) { res = 1; } else if (e == 1) { res = x; } else { res = PowMod(x, e / 2, mod); res = res * res % mod; if (e % 2) res = res * x % mod; } return res; } int a[152][152]; int r[152][152]; bool check(int x, int y) { a[x + 1][0] = 0; for (int i = 0; i <= x; i++) { a[x + 1][i + 1] = a[x][i]; r[x + 1][i] = a[x][i]; } for (int i = 0; i <= x; i++) { a[x + 1][i] += (y * r[x][i]); } for (int i = 0; i <= x + 1; i++) { if (a[x + 1][i] > 1 || a[x + 1][i] < (-1)) { return false; } } return true; } int solve() { int n; cin >> n; memset(a, 0, sizeof(a)); memset(r, 0, sizeof(r)); a[1][0] = 0; a[1][1] = 1; r[1][0] = 1; a[2][0] = -1; a[2][1] = 0; a[2][2] = 1; r[2][0] = 0; r[2][1] = 1; for (int i = 3; i <= n; i++) { if (check(i - 1, 1) == true) { } else { check(i - 1, -1); } } cout << n << endl; for (int i = 0; i <= n; i++) { cout << a[n][i] << " "; } cout << endl << n - 1 << endl; for (int i = 0; i < n; i++) { cout << r[n][i] << " "; } cout << endl; return 0; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int t = 1; for (int i = 1; i <= t; i++) { solve(); } return 0; } ```
### Prompt Generate a CPP solution to the following problem: Every year a race takes place on the motorway between cities A and B. This year Vanya decided to take part in the race and drive his own car that has been around and bears its own noble name — The Huff-puffer. So, Vasya leaves city A on the Huff-puffer, besides, at the very beginning he fills the petrol tank with α liters of petrol (α ≥ 10 is Vanya's favorite number, it is not necessarily integer). Petrol stations are located on the motorway at an interval of 100 kilometers, i.e. the first station is located 100 kilometers away from the city A, the second one is 200 kilometers away from the city A, the third one is 300 kilometers away from the city A and so on. The Huff-puffer spends 10 liters of petrol every 100 kilometers. Vanya checks the petrol tank every time he passes by a petrol station. If the petrol left in the tank is not enough to get to the next station, Vanya fills the tank with α liters of petrol. Otherwise, he doesn't stop at the station and drives on. For example, if α = 43.21, then the car will be fuelled up for the first time at the station number 4, when there'll be 3.21 petrol liters left. After the fuelling up the car will have 46.42 liters. Then Vanya stops at the station number 8 and ends up with 6.42 + 43.21 = 49.63 liters. The next stop is at the station number 12, 9.63 + 43.21 = 52.84. The next stop is at the station number 17 and so on. You won't believe this but the Huff-puffer has been leading in the race! Perhaps it is due to unexpected snow. Perhaps it is due to video cameras that have been installed along the motorway which register speed limit breaking. Perhaps it is due to the fact that Vanya threatened to junk the Huff-puffer unless the car wins. Whatever the reason is, the Huff-puffer is leading, and jealous people together with other contestants wrack their brains trying to think of a way to stop that outrage. One way to do this is to mine the next petrol station where Vanya will stop. Your task is to calculate at which station this will happen and warn Vanya. You don't know the α number, however, you are given the succession of the numbers of the stations where Vanya has stopped. Find the number of the station where the next stop will be. Input The first line contains an integer n (1 ≤ n ≤ 1000) which represents the number of petrol stations where Vanya has stopped. The next line has n space-separated integers which represent the numbers of the stations. The numbers are positive and do not exceed 106, they are given in the increasing order. No two numbers in the succession match. It is guaranteed that there exists at least one number α ≥ 10, to which such a succession of stops corresponds. Output Print in the first line "unique" (without quotes) if the answer can be determined uniquely. In the second line print the number of the station where the next stop will take place. If the answer is not unique, print in the first line "not unique". Examples Input 3 1 2 4 Output unique 5 Input 2 1 2 Output not unique Note In the second example the answer is not unique. For example, if α = 10, we'll have such a sequence as 1, 2, 3, and if α = 14, the sequence will be 1, 2, 4. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; int i; int s; double A = -1; double B = -1; for (i = 1; i <= n; ++i) { cin >> s; if (A < 0 || A <= (s * 10 + 0.0) / (i + 0.0)) A = (s * 10 + 0.0) / (i + 0.0); if (B < 0 || B > (10.0 + s * 10) / (i + 0.0)) B = (10.0 + s * 10) / (i + 0.0); } double L = A * (n + 1) / 10; double R = B * (n + 1) / 10; if (int(L) != (int)(R - (1e-8))) cout << "not unique" << endl; else cout << "unique" << endl << int(L) << endl; return 0; } ```
### Prompt Your task is to create a cpp solution to the following problem: You are running through a rectangular field. This field can be represented as a matrix with 3 rows and m columns. (i, j) denotes a cell belonging to i-th row and j-th column. You start in (2, 1) and have to end your path in (2, m). From the cell (i, j) you may advance to: * (i - 1, j + 1) — only if i > 1, * (i, j + 1), or * (i + 1, j + 1) — only if i < 3. However, there are n obstacles blocking your path. k-th obstacle is denoted by three integers ak, lk and rk, and it forbids entering any cell (ak, j) such that lk ≤ j ≤ rk. You have to calculate the number of different paths from (2, 1) to (2, m), and print it modulo 109 + 7. Input The first line contains two integers n and m (1 ≤ n ≤ 104, 3 ≤ m ≤ 1018) — the number of obstacles and the number of columns in the matrix, respectively. Then n lines follow, each containing three integers ak, lk and rk (1 ≤ ak ≤ 3, 2 ≤ lk ≤ rk ≤ m - 1) denoting an obstacle blocking every cell (ak, j) such that lk ≤ j ≤ rk. Some cells may be blocked by multiple obstacles. Output Print the number of different paths from (2, 1) to (2, m), taken modulo 109 + 7. If it is impossible to get from (2, 1) to (2, m), then the number of paths is 0. Example Input 2 5 1 3 4 2 2 3 Output 2 ### Response ```cpp #include <bits/stdc++.h> using namespace std; vector<vector<long long> > operator*(vector<vector<long long> > a, vector<vector<long long> > b) { int n = (int)a.size(); int m = (int)b.size(); int p = (int)b[0].size(); vector<vector<long long> > c; c.resize(n); for (int i = 0; i < n; i++) { c[i].assign(p, 0); for (int j = 0; j < p; j++) { for (int k = 0; k < m; k++) { c[i][j] = (c[i][j] + a[i][k] * b[k][j]) % 1000000007; } } } return c; } vector<vector<long long> > id(int size) { vector<vector<long long> > a(size, vector<long long>(size, 0)); for (int i = 0; i < size; i++) a[i][i] = 1; return a; } vector<vector<long long> > matrixExp(vector<vector<long long> > a, long long n) { if (n == 0) return id(a.size()); vector<vector<long long> > c = matrixExp(a, n / 2); c = c * c; if (n % 2 != 0) c = c * a; return c; } vector<vector<long long> > blocked(int *b) { vector<vector<long long> > a(3, vector<long long>(3, 0)); a[0][0] = a[0][1] = 1; a[1][0] = a[1][1] = a[1][2] = 1; a[2][1] = a[2][2] = 1; if (b[1] > 0) a[0][0] = a[0][1] = a[1][0] = 0; if (b[2] > 0) a[0][1] = a[1][0] = a[1][1] = a[1][2] = a[2][1] = 0; if (b[3] > 0) a[1][2] = a[2][1] = a[2][2] = 0; return a; } int main() { int n; long long m; cin >> n >> m; vector<pair<long long, int> > block; for (int i = 0; i < n; i++) { int b; long long l, r; cin >> b >> l >> r; block.push_back(pair<long long, int>(l, b)); block.push_back(pair<long long, int>(r, -b)); } sort(block.begin(), block.end()); vector<vector<long long> > ans = id(3); long long pos = 1; int b[4] = {0, 0, 0, 0}; for (auto it : block) { long long nextPos = it.first; ans = ans * matrixExp(blocked(b), nextPos - pos); b[abs(it.second)] += it.second; pos = nextPos; } ans = ans * matrixExp(blocked(b), m - pos); cout << ans[1][1] << endl; } ```
### Prompt In CPP, your task is to solve the following problem: You have a knapsack with the capacity of W. There are also n items, the i-th one has weight w_i. You want to put some of these items into the knapsack in such a way that their total weight C is at least half of its size, but (obviously) does not exceed it. Formally, C should satisfy: ⌈ W/2⌉ ≤ C ≤ W. Output the list of items you will put into the knapsack or determine that fulfilling the conditions is impossible. If there are several possible lists of items satisfying the conditions, you can output any. Note that you don't have to maximize the sum of weights of items in the knapsack. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows. The first line of each test case contains integers n and W (1 ≤ n ≤ 200 000, 1≤ W ≤ 10^{18}). The second line of each test case contains n integers w_1, w_2, ..., w_n (1 ≤ w_i ≤ 10^9) — weights of the items. The sum of n over all test cases does not exceed 200 000. Output For each test case, if there is no solution, print a single integer -1. If there exists a solution consisting of m items, print m in the first line of the output and m integers j_1, j_2, ..., j_m (1 ≤ j_i ≤ n, all j_i are distinct) in the second line of the output — indices of the items you would like to pack into the knapsack. If there are several possible lists of items satisfying the conditions, you can output any. Note that you don't have to maximize the sum of weights items in the knapsack. Example Input 3 1 3 3 6 2 19 8 19 69 9 4 7 12 1 1 1 17 1 1 1 Output 1 1 -1 6 1 2 3 5 6 7 Note In the first test case, you can take the item of weight 3 and fill the knapsack just right. In the second test case, all the items are larger than the knapsack's capacity. Therefore, the answer is -1. In the third test case, you fill the knapsack exactly in half. ### Response ```cpp #include <bits/stdc++.h> using namespace std; using lli = long long int; using ld = long double; const int N = 1e5 + 1; const lli MOD = 1e9 + 7; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int t; cin >> t; while (t--) { lli n, w; cin >> n >> w; vector<pair<lli, lli> > v; lli sum = 0; for (int i = 0; i < n; i++) { lli c; cin >> c; if (c > w) { continue; } v.emplace_back(c, i + 1); sum += c; } if (2 * sum < w) { cout << "-1\n"; continue; } sort(v.rbegin(), v.rend()); lli val = 0, i = 0; while (2 * val < w) { val += v[i].first; i++; } cout << i << '\n'; for (int j = 0; j < i; j++) { cout << v[j].second << " \n"[j == i - 1]; } } } ```
### Prompt Generate a cpp solution to the following problem: Vasya has n burles. One bottle of Ber-Cola costs a burles and one Bars bar costs b burles. He can buy any non-negative integer number of bottles of Ber-Cola and any non-negative integer number of Bars bars. Find out if it's possible to buy some amount of bottles of Ber-Cola and Bars bars and spend exactly n burles. In other words, you should find two non-negative integers x and y such that Vasya can buy x bottles of Ber-Cola and y Bars bars and x·a + y·b = n or tell that it's impossible. Input First line contains single integer n (1 ≤ n ≤ 10 000 000) — amount of money, that Vasya has. Second line contains single integer a (1 ≤ a ≤ 10 000 000) — cost of one bottle of Ber-Cola. Third line contains single integer b (1 ≤ b ≤ 10 000 000) — cost of one Bars bar. Output If Vasya can't buy Bars and Ber-Cola in such a way to spend exactly n burles print «NO» (without quotes). Otherwise in first line print «YES» (without quotes). In second line print two non-negative integers x and y — number of bottles of Ber-Cola and number of Bars bars Vasya should buy in order to spend exactly n burles, i.e. x·a + y·b = n. If there are multiple answers print any of them. Any of numbers x and y can be equal 0. Examples Input 7 2 3 Output YES 2 1 Input 100 25 10 Output YES 0 10 Input 15 4 8 Output NO Input 9960594 2551 2557 Output YES 1951 1949 Note In first example Vasya can buy two bottles of Ber-Cola and one Bars bar. He will spend exactly 2·2 + 1·3 = 7 burles. In second example Vasya can spend exactly n burles multiple ways: * buy two bottles of Ber-Cola and five Bars bars; * buy four bottles of Ber-Cola and don't buy Bars bars; * don't buy Ber-Cola and buy 10 Bars bars. In third example it's impossible to but Ber-Cola and Bars bars in order to spend exactly n burles. ### Response ```cpp #include <bits/stdc++.h> int dx[] = {-1, -1, -1, 0, 1, 1, 1, 0}; int dy[] = {-1, 0, 1, 1, 1, 0, -1, -1}; using namespace std; long long power(long long a, long long p, long long M) { long long r = 1; a = a % M; while (p > 0) { if (p % 2) r = (r * a) % M; a = (a * a) % M; p /= 2; } return r; } long long gcd(long long a, long long b) { if (b == 0) return a; return gcd(b, a % b); } void solve() { long long n, a, b; cin >> n >> a >> b; long long x = 0; while (x * a <= n) { long long y = (n - x * a) / b; if (x * a + y * b == n) { cout << "YES\n"; cout << x << " " << y << endl; return; } x++; } cout << "NO\n"; } int main() { solve(); return 0; } ```
### Prompt Construct a CPP code solution to the problem outlined: Taro, a junior high school student, is working on his homework. Today's homework is to read Chinese classic texts. As you know, Japanese language shares the (mostly) same Chinese characters but the order of words is a bit different. Therefore the notation called "returning marks" was invented in order to read Chinese classic texts in the order similar to Japanese language. There are two major types of returning marks: 'Re' mark and jump marks. Also there are a couple of jump marks such as one-two-three marks, top-middle-bottom marks. The marks are attached to letters to describe the reading order of each letter in the Chinese classic text. Figure 1 is an example of a Chinese classic text annotated with returning marks, which are the small letters at the bottom-left of the big Chinese letters. <image> Figure 1: a Chinese classic text Taro generalized the concept of jump marks, and summarized the rules to read Chinese classic texts with returning marks as below. Your task is to help Taro by writing a program that interprets Chinese classic texts with returning marks following his rules, and outputs the order of reading of each letter. When two (or more) rules are applicable in each step, the latter in the list below is applied first, then the former. 1. Basically letters are read downwards from top to bottom, i.e. the first letter should be read (or skipped) first, and after the i-th letter is read or skipped, (i + 1)-th letter is read next. 2. Each jump mark has a type (represented with a string consisting of lower-case letters) and a number (represented with a positive integer). A letter with a jump mark whose number is 2 or larger must be skipped. 3. When the i-th letter with a jump mark of type t, number n is read, and when there exists an unread letter L at position less than i that has a jump mark of type t, number n + 1, then L must be read next. If there is no such letter L, the (k + 1)-th letter is read, where k is the index of the most recently read letter with a jump mark of type t, number 1. 4. A letter with a 'Re' mark must be skipped. 5. When the i-th letter is read and (i - 1)-th letter has a 'Re' mark, then (i - 1)-th letter must be read next. 6. No letter may be read twice or more. Once a letter is read, the letter must be skipped in the subsequent steps. 7. If no letter can be read next, finish reading. Let's see the first case of the sample input. We begin reading with the first letter because of the rule 1. However, since the first letter has a jump mark 'onetwo2', we must follow the rule 2 and skip the letter. Therefore the second letter, which has no returning mark, will be read first. Then the third letter will be read. The third letter has a jump mark 'onetwo1', so we must follow rule 3 and read a letter with a jump mark `onetwo2' next, if exists. The first letter has the exact jump mark, so it will be read third. Similarly, the fifth letter is read fourth, and then the sixth letter is read. Although we have two letters which have the same jump mark 'onetwo2', we must not take into account the first letter, which has already been read, and must read the fourth letter. Now we have read all six letters and no letter can be read next, so we finish reading. We have read the second, third, first, fifth, sixth, and fourth letter in this order, so the output is 2 3 1 5 6 4. Input The input contains multiple datasets. Each dataset is given in the following format: N mark1 ... markN N, a positive integer (1 ≤ N ≤ 10,000), means the number of letters in a Chinese classic text. marki denotes returning marks attached to the i-th letter. A 'Re' mark is represented by a single letter, namely, 'v' (quotes for clarity). The description of a jump mark is the simple concatenation of its type, specified by one or more lowercase letter, and a positive integer. Note that each letter has at most one jump mark and at most one 'Re' mark. When the same letter has both types of returning marks, the description of the jump mark comes first, followed by 'v' for the 'Re' mark. You can assume this happens only on the jump marks with the number 1. If the i-th letter has no returning mark, marki is '-' (quotes for clarity). The length of marki never exceeds 20. You may assume that input is well-formed, that is, there is exactly one reading order that follows the rules above. And in the ordering, every letter is read exactly once. You may also assume that the N-th letter does not have 'Re' mark. The input ends when N = 0. Your program must not output anything for this case. Output For each dataset, you should output N lines. The first line should contain the index of the letter which is to be read first, the second line for the letter which is to be read second, and so on. All the indices are 1-based. Example Input 6 onetwo2 - onetwo1 onetwo2 - onetwo1 7 v topbottom2 onetwo2 - onetwo1 topbottom1 - 6 baz2 foo2 baz1v bar2 foo1 bar1 0 Output 2 3 1 5 6 4 4 5 3 6 2 1 7 5 2 6 4 3 1 ### Response ```cpp #include <bits/stdc++.h> using namespace std; #define dump(n) cout<<"# "<<#n<<'='<<(n)<<endl #define repi(i,a,b) for(int i=int(a);i<int(b);i++) #define peri(i,a,b) for(int i=int(b);i-->int(a);) #define rep(i,n) repi(i,0,n) #define per(i,n) peri(i,0,n) #define all(c) begin(c),end(c) #define mp make_pair #define mt make_tuple typedef unsigned int uint; typedef long long ll; typedef unsigned long long ull; typedef pair<int,int> pii; typedef vector<int> vi; typedef vector<vi> vvi; typedef vector<ll> vl; typedef vector<vl> vvl; typedef vector<double> vd; typedef vector<vd> vvd; typedef vector<string> vs; const int INF=1e9; const int MOD=1e9+7; const double EPS=1e-9; template<typename T1,typename T2> ostream& operator<<(ostream& os,const pair<T1,T2>& p){ return os<<'('<<p.first<<','<<p.second<<')'; } template<typename T> ostream& operator<<(ostream& os,const vector<T>& a){ os<<'['; rep(i,a.size()) os<<(i?" ":"")<<a[i]; return os<<']'; } int main() { for(int n;cin>>n && n;){ vs lines(n); rep(i,n) cin>>lines[i]; vi prev(n,-1); rep(i,n) if(lines[i].back()=='v'){ prev[i]=i+1; //lines[i].pop_back(); lines[i].erase(end(lines[i])-1); } map<string,int> f; per(i,n) if(lines[i].size() && isdigit(lines[i].back())) rep(j,lines[i].size()) if(isdigit(lines[i][j])){ string tag=lines[i].substr(0,j); int x=stoi(lines[i].substr(j)); if(x>1) prev[i]=f[tag]; f[tag]=i; } vvi pathes; vi vis(n); rep(i,n) if(!vis[i]){ vi path; for(int v=i;v!=-1;v=prev[v]){ path.push_back(v); vis[v]=1; } reverse(all(path)); pathes.push_back(path); } sort(all(pathes)); rep(i,pathes.size()) rep(j,pathes[i].size()) cout<<pathes[i][j]+1<<endl; } } ```
### Prompt Generate a Cpp solution to the following problem: During the last 24 hours Hamed and Malek spent all their time playing "Sharti". Now they are too exhausted to finish the last round. So they asked you for help to determine the winner of this round. "Sharti" is played on a n × n board with some of cells colored white and others colored black. The rows of the board are numbered from top to bottom using number 1 to n. Also the columns of the board are numbered from left to right using numbers 1 to n. The cell located at the intersection of i-th row and j-th column is denoted by (i, j). The players alternatively take turns. In each turn the player must choose a square with side-length at most k with its lower-right cell painted white. Then the colors of all the cells in this square are inversed (white cells become black and vice-versa). The player who cannot perform a move in his turn loses. You know Hamed and Malek are very clever and they would have played their best moves at each turn. Knowing this and the fact that Hamed takes the first turn, given the initial board as described in the input, you must determine which one of them will be the winner. Input In this problem the initial board is specified as a set of m rectangles. All cells that lie inside at least one of these rectangles are colored white and the rest are colored black. In the first line of input three space-spereated integers n, m, k (1 ≤ k ≤ n ≤ 109, 1 ≤ m ≤ 5·104) follow, denoting size of the board, number of rectangles and maximum size of the turn square during the game, respectively. In i-th line of the next m lines four space-seperated integers ai, bi, ci, di (1 ≤ ai ≤ ci ≤ n, 1 ≤ bi ≤ di ≤ n) are given meaning that i-th rectangle determining the initial board is a rectangle with upper-left cell at (ai, bi) and lower-right cell at (ci, di). Output If Hamed wins, print "Hamed", otherwise print "Malek" (without the quotes). Examples Input 5 2 1 1 1 3 3 2 2 4 4 Output Malek Input 12 5 7 3 4 5 6 1 2 1 2 4 5 9 9 8 6 12 10 12 4 12 4 Output Hamed ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int maxn = 50010; int n, m, K; struct rect { int a, b, c, d; } a[maxn], b[maxn]; namespace SEG { int tot; struct node { int l, r, cnt, ans; } t[maxn * 50]; void init() { for (int i = 1; i <= tot; i++) t[i].l = t[i].r = 0; tot = 0; } void maintain(int k, int l, int r) { if (t[k].cnt) t[k].ans = r - l + 1; else t[k].ans = t[t[k].l].ans + t[t[k].r].ans; } void add(int &k, int l, int r, int ql, int qr, int v) { if (!k) k = ++tot; if (l >= ql && r <= qr) { t[k].cnt += v, maintain(k, l, r); return; } if ((l + r >> 1) >= ql) add(t[k].l, l, (l + r >> 1), ql, qr, v); if ((l + r >> 1) < qr) add(t[k].r, (l + r >> 1) + 1, r, ql, qr, v); maintain(k, l, r); } } // namespace SEG int main() { scanf("%d %d %d", &n, &m, &K); for (int i = 1; i <= m; i++) { scanf("%d %d %d %d", &a[i].a, &a[i].b, &a[i].c, &a[i].d); } auto chk = [&]() { vector<tuple<int, int, int, int>> V; int ans = 0, rt = 0, n = 0; for (int i = 1; i <= m; i++) if (b[i].a <= b[i].c && b[i].b <= b[i].d) { n = max(n, b[i].d), V.emplace_back(b[i].a, b[i].b, b[i].d, 1); V.emplace_back(b[i].c + 1, b[i].b, b[i].d, -1); } sort(V.begin(), V.end()), SEG::init(); for (int i = 0, j; i < V.size(); i = j) { for (j = i; j < V.size() && get<0>(V[i]) == get<0>(V[j]); j++) { SEG::add(rt, 1, n, get<1>(V[j]), get<2>(V[j]), get<3>(V[j])); } if (j == V.size() || !((get<0>(V[j]) - get<0>(V[i])) & 1)) continue; ans ^= SEG::t[1].ans & 1; } return ans; }; for (int i = 0; 1 << i <= K; i++) { copy(a + 1, a + m + 1, b + 1); for (int j = 1; j <= m; j++) { b[j].a = ((b[j].a - 1) >> i) + 1, b[j].c >>= i; b[j].b = ((b[j].b - 1) >> i) + 1, b[j].d >>= i; } if (chk()) puts("Hamed"), exit(0); } puts("Malek"); return 0; } ```
### Prompt Please provide a CPP coded solution to the problem described below: Andrewid the Android is a galaxy-famous detective. Now he is busy with a top secret case, the details of which are not subject to disclosure. However, he needs help conducting one of the investigative experiment. There are n pegs put on a plane, they are numbered from 1 to n, the coordinates of the i-th of them are (xi, 0). Then, we tie to the bottom of one of the pegs a weight on a tight rope of length l (thus, its coordinates will be equal to (xi, - l), where i is the number of the used peg). Then the weight is pushed to the right, so that it starts to rotate counterclockwise. At the same time, if the weight during rotation touches some of the other pegs, it then begins to rotate around that peg. Suppose that each peg itself is very thin and does not affect the rope length while weight is rotating around it. <image> More formally, if at some moment the segment of the rope contains one or more pegs in addition to the peg around which the weight is rotating, the weight will then rotate around the farthermost one of them on a shorter segment of a rope. In particular, if the segment of the rope touches some peg by its endpoint, it is considered that the weight starts to rotate around that peg on a segment of the rope of length 0. At some moment the weight will begin to rotate around some peg, without affecting the rest of the pegs. Andrewid interested in determining the number of this peg. Andrewid prepared m queries containing initial conditions for pushing the weight, help him to determine for each of them, around what peg the weight will eventually rotate. Input The first line contains integers n and m (1 ≤ n, m ≤ 2·105) — the number of pegs and queries. The next line contains n integers x1, x2, ..., xn ( - 109 ≤ xi ≤ 109) — the coordinates of the pegs. It is guaranteed that the coordinates of all the pegs are distinct integers. Next m lines contain the descriptions of the queries of pushing the weight, each consists of two integers ai (1 ≤ ai ≤ n) and li (1 ≤ li ≤ 109) — the number of the starting peg and the length of the rope. Output Print m lines, the i-th line should contain the number of the peg around which the weight will eventually rotate after the i-th push. Examples Input 3 2 0 3 5 2 3 1 8 Output 3 2 Input 4 4 1 5 7 15 1 4 2 15 3 16 1 28 Output 2 4 3 1 Note Picture to the first sample test: <image> Picture to the second sample test: <image> Note that in the last query weight starts to rotate around the peg 1 attached to a rope segment of length 0. ### Response ```cpp #include <bits/stdc++.h> using namespace std; pair<int, int> p[200010]; int pos[200010], idx[200010], mp[200010]; int main() { int n, m; scanf("%d%d", &n, &m); for (int i = 1; i <= n; i++) scanf("%d", &p[i].first), p[i].second = i; sort(p + 1, p + n + 1); for (int i = 1; i <= n; i++) pos[i] = p[i].first, idx[i] = p[i].second, mp[p[i].second] = i; while (m--) { bool type = true; int x, len; scanf("%d%d", &x, &len); if (n == 1) { printf("1\n"); continue; } x = mp[x]; int id = upper_bound(pos + 1, pos + n + 1, pos[x] + len) - pos - 1; len -= pos[id] - pos[x]; x = id; type = false; if (len >= pos[n] - pos[1]) { int q = len / (pos[n] - pos[1]); if (q % 2) x = 1, type = true; else x = n, type = false; len -= q * (pos[n] - pos[1]); } while (len) { if (type) { id = upper_bound(pos + 1, pos + n + 1, pos[x] + len) - pos - 1; if (id == x || pos[id] == pos[x] + len) { x = id; break; } if (pos[id] - pos[x] >= len / 2) { len -= (pos[id] - pos[x]); x = id; type = !type; continue; } int tmp = pos[id] - pos[x], q = len / tmp; if (q % 2) x = id, type = false, len -= q * tmp; else len -= q * tmp; } else { id = lower_bound(pos + 1, pos + n + 1, pos[x] - len) - pos; if (id == x || pos[id] == pos[x] - len) { x = id; break; } if (pos[x] - pos[id] >= len / 2) { len -= (pos[x] - pos[id]); x = id; type = !type; continue; } int tmp = (pos[x] - pos[id]), q = len / tmp; if (q % 2) x = id, type = true, len -= q * tmp; else len -= q * tmp; } } printf("%d\n", idx[x]); } } ```
### Prompt Develop a solution in Cpp to the problem described below: Fafa owns a company that works on huge projects. There are n employees in Fafa's company. Whenever the company has a new project to start working on, Fafa has to divide the tasks of this project among all the employees. Fafa finds doing this every time is very tiring for him. So, he decided to choose the best l employees in his company as team leaders. Whenever there is a new project, Fafa will divide the tasks among only the team leaders and each team leader will be responsible of some positive number of employees to give them the tasks. To make this process fair for the team leaders, each one of them should be responsible for the same number of employees. Moreover, every employee, who is not a team leader, has to be under the responsibility of exactly one team leader, and no team leader is responsible for another team leader. Given the number of employees n, find in how many ways Fafa could choose the number of team leaders l in such a way that it is possible to divide employees between them evenly. Input The input consists of a single line containing a positive integer n (2 ≤ n ≤ 105) — the number of employees in Fafa's company. Output Print a single integer representing the answer to the problem. Examples Input 2 Output 1 Input 10 Output 3 Note In the second sample Fafa has 3 ways: * choose only 1 employee as a team leader with 9 employees under his responsibility. * choose 2 employees as team leaders with 4 employees under the responsibility of each of them. * choose 5 employees as team leaders with 1 employee under the responsibility of each of them. ### Response ```cpp #include <bits/stdc++.h> int main() { long i, n, d = 0; scanf("%ld", &n); for (i = 1; i <= n / 2; i++) { if (n % i == 0) d++; } printf("%d", d); return 0; } ```
### Prompt Generate a CPP solution to the following problem: You're given a tree consisting of n nodes. Every node u has a weight a_u. You want to choose an integer k (1 ≤ k ≤ n) and then choose k connected components of nodes that don't overlap (i.e every node is in at most 1 component). Let the set of nodes you chose be s. You want to maximize: $$$\frac{∑_{u ∈ s} a_u}{k}$$$ In other words, you want to maximize the sum of weights of nodes in s divided by the number of connected components you chose. Also, if there are several solutions, you want to maximize k. Note that adjacent nodes can belong to different components. Refer to the third sample. Input The first line contains the integer n (1 ≤ n ≤ 3 ⋅ 10^5), the number of nodes in the tree. The second line contains n space-separated integers a_1, a_2, ..., a_n (|a_i| ≤ 10^9), the weights of the nodes. The next n-1 lines, each contains 2 space-separated integers u and v (1 ≤ u,v ≤ n) which means there's an edge between u and v. Output Print the answer as a non-reduced fraction represented by 2 space-separated integers. The fraction itself should be maximized and if there are several possible ways, you should maximize the denominator. See the samples for a better understanding. Examples Input 3 1 2 3 1 2 1 3 Output 6 1 Input 1 -2 Output -2 1 Input 3 -1 -1 -1 1 2 2 3 Output -3 3 Input 3 -1 -2 -1 1 2 1 3 Output -2 2 Note A connected component is a set of nodes such that for any node in the set, you can reach all other nodes in the set passing only nodes in the set. In the first sample, it's optimal to choose the whole tree. In the second sample, you only have one choice (to choose node 1) because you can't choose 0 components. In the third sample, notice that we could've, for example, chosen only node 1, or node 1 and node 3, or even the whole tree, and the fraction would've had the same value (-1), but we want to maximize k. In the fourth sample, we'll just choose nodes 1 and 3. ### Response ```cpp #include <bits/stdc++.h> using namespace std; long long int power(long long int x, long long int y) { long long int res = 1; while (y) { if (y & 1) res = (res * x) % 1000000007; y = y / 2, x = (x * x) % 1000000007; } return res % 1000000007; } long long int child[1000000]; long long int val[1000000]; vector<vector<long long int> > arr(1000000); long long int cnt = 0; long long int ma = -1e18; void dfs(long long int u, long long int par) { child[u] = val[u]; long long int i; for (i = 0; i < arr[u].size(); i++) { long long int v = arr[u][i]; if (v != par) { dfs(v, u); if (child[v] > 0) child[u] += child[v]; } } } void dfs1(long long int u, long long int par) { long long int i; child[u] = val[u]; for (i = 0; i < arr[u].size(); i++) { long long int v = arr[u][i]; if (v != par) { dfs1(v, u); if (child[v] > 0) child[u] += child[v]; } } if (child[u] == ma) { child[u] = 0; cnt++; } } signed main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); long long int n; cin >> n; long long int i; for (i = 1; i <= n; i++) cin >> val[i]; for (i = 0; i < n - 1; i++) { long long int u, v; cin >> u >> v; arr[u].push_back(v); arr[v].push_back(u); } dfs(1, 0); for (i = 1; i <= n; i++) { ma = max(ma, child[i]); } dfs1(1, 0); cout << ma * cnt << " " << cnt; } ```
### Prompt Please provide a Cpp coded solution to the problem described below: You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it [here](http://tiny.cc/636xmz). The picture showing the correct sudoku solution: <image> Blocks are bordered with bold black color. Your task is to change at most 9 elements of this field (i.e. choose some 1 ≤ i, j ≤ 9 and change the number at the position (i, j) to any other number in range [1; 9]) to make it anti-sudoku. The anti-sudoku is the 9 × 9 field, in which: * Any number in this field is in range [1; 9]; * each row contains at least two equal elements; * each column contains at least two equal elements; * each 3 × 3 block (you can read what is the block in the link above) contains at least two equal elements. It is guaranteed that the answer exists. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow. Each test case consists of 9 lines, each line consists of 9 characters from 1 to 9 without any whitespaces — the correct solution of the sudoku puzzle. Output For each test case, print the answer — the initial field with at most 9 changed elements so that the obtained field is anti-sudoku. If there are several solutions, you can print any. It is guaranteed that the answer exists. Example Input 1 154873296 386592714 729641835 863725149 975314628 412968357 631457982 598236471 247189563 Output 154873396 336592714 729645835 863725145 979314628 412958357 631457992 998236471 247789563 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const long long MOD = (1 ? 100000000000000007 : 233333333333333333); const int mod = (1 ? 1000000007 : 998244353); const long long INF = 0x7fffffffffffffff; const int inf = 0x7fffffff; const double eps = 1e-9; const int N = 1e6 + 5; clock_t start, finish; void time_in() { start = clock(); } void time_out() { finish = clock(); double tim = (double)(finish - start) / CLOCKS_PER_SEC; printf("Running time is %lf\n", tim); } inline long long mul(long long a, long long b) { long long s = 0; while (b) { if (b & 1) s = (s + a) % mod; a = (a << 1) % mod; b >>= 1; } return s % mod; } inline long long pow_mul(long long a, long long b) { long long s = 1; while (b) { if (b & 1) s = mul(s, a); a = mul(a, a); b >>= 1; } return s; } inline long long poww(long long a, long long b) { long long s = 1; while (b) { if (b & 1) s = (s * a) % mod; a = (a * a) % mod; b >>= 1; } return s % mod; } inline int read() { char c = getchar(); int sgn = 1, ret = 0; while (c != '-' && (c < '0' || c > '9')) c = getchar(); if (c == '-') sgn = -1, c = getchar(); while (c >= '0' && c <= '9') ret = ret * 10 + c - 48, c = getchar(); return ret * sgn; } void write(int x) { if (x > 9) write(x / 10); putchar(x % 10 + '0'); } inline long long phi(long long x) { long long ans = x; for (long long i = 2; i * i <= x; i++) if (x % i == 0) { ans -= ans / i; while (x % i == 0) x /= i; } if (x > 1) ans -= ans / x; return ans; } int st[5][3] = {-1, 0, 0, 1, 0, 0, 0, -1, 0, 0, 1, 0, 0, 0, 1}; int t, cas; int m, n; string s[11]; int a[11][11]; int b[9][2] = {2, 2, 3, 6, 1, 7, 5, 3, 6, 5, 4, 9, 8, 1, 9, 4, 7, 8}; int main() { scanf("%d", &t); while (t--) { for (int i = 0; i < 9; i++) { cin >> s[i]; } for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { a[i + 1][j + 1] = s[i][j] - '0'; } } int cnt = 0; for (int i = 0; i < 9; i++) { int x = b[i][0], y = b[i][1]; for (int i = 1; i <= 9; i++) { if (a[x][y] != i) { a[x][y] = i; cnt++; break; } } } for (int i = 1; i <= 9; i++) { for (int j = 1; j <= 9; j++) { printf("%d", a[i][j]); } printf("\n"); } } } ```
### Prompt In Cpp, your task is to solve the following problem: You are given an array a[0 … n-1] of length n which consists of non-negative integers. Note that array indices start from zero. An array is called good if the parity of each index matches the parity of the element at that index. More formally, an array is good if for all i (0 ≤ i ≤ n - 1) the equality i mod 2 = a[i] mod 2 holds, where x mod 2 is the remainder of dividing x by 2. For example, the arrays [0, 5, 2, 1] and [0, 17, 0, 3] are good, and the array [2, 4, 6, 7] is bad, because for i=1, the parities of i and a[i] are different: i mod 2 = 1 mod 2 = 1, but a[i] mod 2 = 4 mod 2 = 0. In one move, you can take any two elements of the array and swap them (these elements are not necessarily adjacent). Find the minimum number of moves in which you can make the array a good, or say that this is not possible. Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases in the test. Then t test cases follow. Each test case starts with a line containing an integer n (1 ≤ n ≤ 40) — the length of the array a. The next line contains n integers a_0, a_1, …, a_{n-1} (0 ≤ a_i ≤ 1000) — the initial array. Output For each test case, output a single integer — the minimum number of moves to make the given array a good, or -1 if this is not possible. Example Input 4 4 3 2 7 6 3 3 2 6 1 7 7 4 9 2 1 18 3 0 Output 2 1 -1 0 Note In the first test case, in the first move, you can swap the elements with indices 0 and 1, and in the second move, you can swap the elements with indices 2 and 3. In the second test case, in the first move, you need to swap the elements with indices 0 and 1. In the third test case, you cannot make the array good. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; int a[n]; int wantodd = 0; int wanteven = 0; for (int i = 0; i < n; i++) { cin >> a[i]; if (a[i] % 2 == 0 && i % 2 == 1) { wanteven++; } else if (a[i] % 2 == 1 && i % 2 == 0) { wantodd++; } } if (wantodd == wanteven) { cout << wanteven << endl; } else if (wantodd != wanteven) { cout << -1 << endl; } } return 0; } ```
### Prompt Your task is to create a Cpp solution to the following problem: You are asked to watch your nephew who likes to play with toy blocks in a strange way. He has n boxes and the i-th box has a_i blocks. His game consists of two steps: 1. he chooses an arbitrary box i; 2. he tries to move all blocks from the i-th box to other boxes. If he can make the same number of blocks in each of n - 1 other boxes then he will be happy, otherwise, will be sad. Note that your nephew can only move the blocks from the chosen box to the other boxes; he cannot move blocks from the other boxes. You don't want to make your nephew sad, so you decided to put several extra blocks into some boxes in such a way that no matter which box i he chooses he won't be sad. What is the minimum number of extra blocks you need to put? Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains the integer n (2 ≤ n ≤ 10^5) — the number of boxes. The second line of each test case contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9) — the number of blocks in each box. It's guaranteed that the sum of n over test cases doesn't exceed 10^5. Output For each test case, print a single integer — the minimum number of blocks you need to put. It can be proved that the answer always exists, i. e. the number of blocks is finite. Example Input 3 3 3 2 2 4 2 2 3 2 3 0 3 0 Output 1 0 3 Note In the first test case, you can, for example, put one extra block into the first box and make a = [4, 2, 2]. If your nephew chooses the box with 4 blocks, then we will move two blocks to the second box and two blocks to the third box. If he chooses the box with 2 blocks then he will move these two blocks to the other box with 2 blocks. In the second test case, you don't need to put any extra blocks, since no matter which box your nephew chooses, he can always make other boxes equal. In the third test case, you should put 3 extra blocks. For example, you can put 2 blocks in the first box and 1 block in the third box. You'll get array a = [2, 3, 1]. ### Response ```cpp //#define LOCAL #include <bits/stdc++.h> using namespace std; #define ll long long #define mem(a, b) memset(a,b,sizeof(a)) #define sz(a) (int)a.size() #define INF 0x3f3f3f3f #define DNF 0x7f #define DBG printf("this is a input\n") #define fi first #define se second #define pii pair<int,int> #define mk(a, b) make_pair(a,b) #define pb push_back #define LF putchar('\n') #define SP putchar(' ') #define p_queue priority_queue #define CLOSE ios::sync_with_stdio(0); cin.tie(0) template<typename T> void read(T &x) {x = 0;char ch = getchar();ll f = 1;while(!isdigit(ch)){if(ch == '-')f *= -1;ch = getchar();}while(isdigit(ch)){x = x * 10 + ch - 48; ch = getchar();}x *= f;} template<typename T, typename... Args> void read(T &first, Args& ... args) {read(first);read(args...);} template<typename T> void write(T arg) {T x = arg;if(x < 0) {putchar('-'); x =- x;}if(x > 9) {write(x / 10);}putchar(x % 10 + '0');} template<typename T, typename ... Ts> void write(T arg, Ts ... args) {write(arg);if(sizeof...(args) != 0) {putchar(' ');write(args ...);}} using namespace std; ll gcd(ll a, ll b) { return b == 0 ? a : gcd(b, a % b); } ll lcm(ll a, ll b) { return a / gcd(a, b) * b; } const int N = 4e5 + 5; int T, n, m; ll a[N], sum; int main (void) { CLOSE; cin >> T; while (T --) { sum = 0; cin >> n; for (int i = 1 ; i <= n ; i ++) cin >> a[i]; sort (a + 1, a + 1 + n); for (int i = 1 ; i <= n ; i ++) sum += a[n]-a[i]; ll ans = 1e18; for (int i = 1 ; i <= n ; i ++) { ll x = sum - (a[n]-a[i]); if (a[i] <= x) ans = min (ans , x-a[i]); else { ll add = (a[i]-x)%(n-1); if (add) ans = min (ans, n-1-add); else ans = 0; } } cout << ans << endl; } } /* 2 2 3 3 3 3 1 2 3 6 5 4 3 0 */ ```
### Prompt In CPP, your task is to solve the following problem: Snuke can change a string t of length N into a string t' of length N - 1 under the following rule: * For each i (1 ≤ i ≤ N - 1), the i-th character of t' must be either the i-th or (i + 1)-th character of t. There is a string s consisting of lowercase English letters. Snuke's objective is to apply the above operation to s repeatedly so that all the characters in s are the same. Find the minimum necessary number of operations. Constraints * 1 ≤ |s| ≤ 100 * s consists of lowercase English letters. Input Input is given from Standard Input in the following format: s Output Print the minimum necessary number of operations to achieve the objective. Examples Input serval Output 3 Input jackal Output 2 Input zzz Output 0 Input whbrjpjyhsrywlqjxdbrbaomnw Output 8 ### Response ```cpp #include<iostream> #include<cstdio> #include<cstring> using namespace std; int main(){ char ca[105]; char cb,cc; int i,j,k; int a,b,c; int s=105; cin>>ca; for(cb='a';cb<='z';cb++){ for(a=0,b=0,i=0;i<strlen(ca);i++,b++){ if(ca[i]==cb){ if(a<b)a=b; b=-1; } } if(a<b)a=b; if(a<s)s=a; } cout<<s<<endl; return 0; } ```
### Prompt Please provide a CPP coded solution to the problem described below: After years of hard work scientists invented an absolutely new e-reader display. The new display has a larger resolution, consumes less energy and its production is cheaper. And besides, one can bend it. The only inconvenience is highly unusual management. For that very reason the developers decided to leave the e-readers' software to programmers. The display is represented by n × n square of pixels, each of which can be either black or white. The display rows are numbered with integers from 1 to n upside down, the columns are numbered with integers from 1 to n from the left to the right. The display can perform commands like "x, y". When a traditional display fulfills such command, it simply inverts a color of (x, y), where x is the row number and y is the column number. But in our new display every pixel that belongs to at least one of the segments (x, x) - (x, y) and (y, y) - (x, y) (both ends of both segments are included) inverts a color. For example, if initially a display 5 × 5 in size is absolutely white, then the sequence of commands (1, 4), (3, 5), (5, 1), (3, 3) leads to the following changes: <image> You are an e-reader software programmer and you should calculate minimal number of commands needed to display the picture. You can regard all display pixels as initially white. Input The first line contains number n (1 ≤ n ≤ 2000). Next n lines contain n characters each: the description of the picture that needs to be shown. "0" represents the white color and "1" represents the black color. Output Print one integer z — the least number of commands needed to display the picture. Examples Input 5 01110 10010 10001 10011 11110 Output 4 ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int MAXN = 2222; char a[MAXN][MAXN]; int r[MAXN], c[MAXN], d[MAXN]; int main() { int n; scanf("%d", &n); for (int i = 0; i < n; ++i) scanf("%s", a[i]); int ans = 0; for (int i = 0; i < n; ++i) c[i] = 0; for (int i = 0; i < n; ++i) { int val = 0; for (int j = n - 1; j > i; --j) if (a[i][j] - '0' != (val ^ c[j])) { ++ans; c[j] ^= 1; val ^= 1; } d[i] = val; } for (int i = 0; i < n; ++i) r[i] = 0; for (int j = 0; j < n; ++j) { int val = 0; for (int i = n - 1; i > j; --i) if (a[i][j] - '0' != (val ^ r[i])) { ++ans; r[i] ^= 1; val ^= 1; } d[j] ^= val; } for (int i = 0; i < n; ++i) if (a[i][i] - '0' != (r[i] ^ c[i] ^ d[i])) ++ans; printf("%d\n", ans); } ```
### Prompt Please formulate a CPP solution to the following problem: Blake is a CEO of a large company called "Blake Technologies". He loves his company very much and he thinks that his company should be the best. That is why every candidate needs to pass through the interview that consists of the following problem. We define function f(x, l, r) as a bitwise OR of integers xl, xl + 1, ..., xr, where xi is the i-th element of the array x. You are given two arrays a and b of length n. You need to determine the maximum value of sum f(a, l, r) + f(b, l, r) among all possible 1 ≤ l ≤ r ≤ n. <image> Input The first line of the input contains a single integer n (1 ≤ n ≤ 1000) — the length of the arrays. The second line contains n integers ai (0 ≤ ai ≤ 109). The third line contains n integers bi (0 ≤ bi ≤ 109). Output Print a single integer — the maximum value of sum f(a, l, r) + f(b, l, r) among all possible 1 ≤ l ≤ r ≤ n. Examples Input 5 1 2 4 3 2 2 3 3 12 1 Output 22 Input 10 13 2 7 11 8 4 9 8 5 1 5 7 18 9 2 3 0 11 8 6 Output 46 Note Bitwise OR of two non-negative integers a and b is the number c = a OR b, such that each of its digits in binary notation is 1 if and only if at least one of a or b have 1 in the corresponding position in binary notation. In the first sample, one of the optimal answers is l = 2 and r = 4, because f(a, 2, 4) + f(b, 2, 4) = (2 OR 4 OR 3) + (3 OR 3 OR 12) = 7 + 15 = 22. Other ways to get maximum value is to choose l = 1 and r = 4, l = 1 and r = 5, l = 2 and r = 4, l = 2 and r = 5, l = 3 and r = 4, or l = 3 and r = 5. In the second sample, the maximum value is obtained for l = 1 and r = 9. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { long long int tam; vector<int> v1, v2; scanf("%lld", &tam); for (int i = 0, x; i < tam; i++) { scanf("%d", &x); v1.push_back(x); } for (int i = 0, x; i < tam; i++) { scanf("%d", &x); v2.push_back(x); } int s1 = 0, s2 = 0, maxi = 0; for (int i = 0; i < tam; i++) { for (int j = i; j <= i; j++) { s1 |= v1[j]; s2 |= v2[j]; maxi = max(s1 + s2, maxi); } } printf("%d\n", maxi); return 0; } ```
### Prompt Generate a cpp solution to the following problem: Danil decided to earn some money, so he had found a part-time job. The interview have went well, so now he is a light switcher. Danil works in a rooted tree (undirected connected acyclic graph) with n vertices, vertex 1 is the root of the tree. There is a room in each vertex, light can be switched on or off in each room. Danil's duties include switching light in all rooms of the subtree of the vertex. It means that if light is switched on in some room of the subtree, he should switch it off. Otherwise, he should switch it on. Unfortunately (or fortunately), Danil is very lazy. He knows that his boss is not going to personally check the work. Instead, he will send Danil tasks using Workforces personal messages. There are two types of tasks: 1. pow v describes a task to switch lights in the subtree of vertex v. 2. get v describes a task to count the number of rooms in the subtree of v, in which the light is turned on. Danil should send the answer to his boss using Workforces messages. A subtree of vertex v is a set of vertices for which the shortest path from them to the root passes through v. In particular, the vertex v is in the subtree of v. Danil is not going to perform his duties. He asks you to write a program, which answers the boss instead of him. Input The first line contains a single integer n (1 ≤ n ≤ 200 000) — the number of vertices in the tree. The second line contains n - 1 space-separated integers p2, p3, ..., pn (1 ≤ pi < i), where pi is the ancestor of vertex i. The third line contains n space-separated integers t1, t2, ..., tn (0 ≤ ti ≤ 1), where ti is 1, if the light is turned on in vertex i and 0 otherwise. The fourth line contains a single integer q (1 ≤ q ≤ 200 000) — the number of tasks. The next q lines are get v or pow v (1 ≤ v ≤ n) — the tasks described above. Output For each task get v print the number of rooms in the subtree of v, in which the light is turned on. Example Input 4 1 1 1 1 0 0 1 9 get 1 get 2 get 3 get 4 pow 1 get 1 get 2 get 3 get 4 Output 2 0 0 1 2 1 1 0 Note <image> The tree before the task pow 1. <image> The tree after the task pow 1. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int const N = int(2e5) + 7; int const mod = int(1e9) + 7; int p[N]; vector<int> ent, out; int t[N]; int rt[N]; bool switchS[4 * N]; vector<int> gr[N]; vector<int> seg; int endS; int n; void build(int v = 1, int l = 0, int r = endS) { if (l == r) { seg[v] = t[rt[l]]; return; } int mid = (l + r) >> 1; build(v << 1, l, mid); build((v << 1) + 1, mid + 1, r); seg[v] = seg[v << 1] + seg[(v << 1) + 1]; } void push(int v, int l, int r) { if (switchS[v]) { seg[v] = min(n - 1, r) - l + 1 - seg[v]; if (l < r) { switchS[v << 1] ^= true; switchS[v << 1 | 1] ^= true; } switchS[v] = false; } } void update(int ls, int rs, int v = 1, int l = 0, int r = endS) { push(v, l, r); if (r < ls || rs < l) { return; } if (ls <= l && r <= rs) { switchS[v] = true; push(v, l, r); return; } int mid = (l + r) >> 1; update(ls, rs, v << 1, l, mid); update(ls, rs, (v << 1) + 1, mid + 1, r); seg[v] = seg[v << 1] + seg[(v << 1) + 1]; } int query(int ls, int rs, int v = 1, int l = 0, int r = endS) { push(v, l, r); if (r < ls || rs < l) { return 0; } if (ls <= l && r <= rs) { return seg[v]; } int mid = (l + r) >> 1; return query(ls, rs, v << 1, l, mid) + query(ls, rs, (v << 1) + 1, mid + 1, r); } void dfs(int v, int &tt) { ent[v] = tt; for (int i = 0; i < gr[v].size(); ++i) { ++tt; dfs(gr[v][i], tt); } out[v] = tt; } int main() { ios_base::sync_with_stdio(false); ifstream in("input.txt"); cin >> n; endS = n - 1; for (int i = 1; i < n; ++i) { cin >> p[i]; --p[i]; gr[p[i]].push_back(i); } int tt = 0; seg.resize(4 * n, 0); ent.resize(n); out.resize(n); dfs(0, tt); for (int i = 0; i < n; ++i) { rt[ent[i]] = i; } for (int i = 0; i < n; ++i) { cin >> t[i]; } build(); int q; cin >> q; while (q--) { string typeQuery; cin >> typeQuery; int v; cin >> v; --v; if (typeQuery == "pow") { update(ent[v], out[v]); } else { cout << query(ent[v], out[v]) << endl; } } return 0; } ```
### Prompt Generate a cpp solution to the following problem: T students applied into the ZPP class of Summer Irrelevant School. The organizing committee of the school may enroll any number of them, but at least t students must be enrolled. The enrolled students should be divided into two groups in any manner (it is possible that one of the groups will be empty!) During a shift the students from the ZPP grade are tutored by n teachers. Due to the nature of the educational process, each of the teachers should be assigned to exactly one of two groups (it is possible that no teacher will be assigned to some of the groups!). The i-th teacher is willing to work in a group as long as the group will have at least li and at most ri students (otherwise it would be either too boring or too hard). Besides, some pairs of the teachers don't like each other other and therefore can not work in the same group; in total there are m pairs of conflicting teachers. You, as the head teacher of Summer Irrelevant School, have got a difficult task: to determine how many students to enroll in each of the groups and in which group each teacher will teach. Input The first line contains two space-separated integers, t and T (1 ≤ t ≤ T ≤ 109). The second line contains two space-separated integers n and m (1 ≤ n ≤ 105, 0 ≤ m ≤ 105). The i-th of the next n lines contain integers li and ri (0 ≤ li ≤ ri ≤ 109). The next m lines describe the pairs of conflicting teachers. Each of these lines contain two space-separated integers — the indices of teachers in the pair. The teachers are indexed starting from one. It is guaranteed that no teacher has a conflict with himself and no pair of conflicting teachers occurs in the list more than once. Output If the distribution is possible, print in the first line a single word 'POSSIBLE' (without the quotes). In the second line print two space-separated integers n1 and n2 — the number of students in the first and second group, correspondingly, the contstraint t ≤ n1 + n2 ≤ T should be met. In the third line print n characters, the i-th of which should be 1 or 2, if the i-th teacher should be assigned to the first or second group, correspondingly. If there are multiple possible distributions of students and teachers in groups, you can print any of them. If the sought distribution doesn't exist, print a single word 'IMPOSSIBLE' (without the quotes). Examples Input 10 20 3 0 3 6 4 9 16 25 Output POSSIBLE 4 16 112 Input 1 10 3 3 0 10 0 10 0 10 1 2 1 3 2 3 Output IMPOSSIBLE ### Response ```cpp #include <bits/stdc++.h> using namespace std; template <class free> inline void Min(free&, free); template <class free> inline void Max(free&, free); struct inter { int l, r, id, id1; inline void operator^=(const inter x) { Max(l, x.l), Min(r, x.r); } inline inter operator^(const inter x) { return {max(l, x.l), min(r, x.r)}; } inline bool operator<(const inter& x) const { return l < x.l; } } I[200050], I1[200050][2], I2[200050]; struct point { int next, to; } ar[200050]; multiset<int> S; bool ans[200050], is[200050]; int head[200050], art, a[200050], at, b1, b2, b3, b4, I2t, t, T, n, m; inline bool dfs(int, int); inline void read(int&), link(int, int), deal(inter, inter), deal1(inter, inter), deal2(inter, inter), deal3(int, int); int main() { read(t), read(T), read(n), read(m); for (int i(1); i <= n; ++i) read(I[i].l), read(I[i].r), I1[i][0] = {0, 0x3f3f3f3f, i, 0}, I1[i][1] = {0, 0x3f3f3f3f, i, 1}; for (int i(1), u, v; i <= m; ++i) read(u), read(v), link(u, v); memset(a, -1, sizeof(a)); for (int i(1); i <= n; ++i) if (!~a[i] && dfs((++at, i), 0)) return puts("IMPOSSIBLE"), 0; for (int i(1), j; i <= at; ++i) for (j = 0; j < 2; ++j) { if (!b1 || I1[i][j].l > I1[b1][b2].l) b1 = i, b2 = j; if (!b3 || I1[i][j].r < I1[b3][b4].r) b3 = i, b4 = j; } if (b1 ^ b3) { ans[b1] = b2, ans[b3] = b4; deal(I1[b1][b2] ^ I1[b3][b4], I1[b1][b2 ^ 1] ^ I1[b3][b4 ^ 1]); ans[b3] ^= 1; deal2(I1[b1][b2] ^ I1[b3][b4 ^ 1], I1[b1][b2 ^ 1] ^ I1[b3][b4]); } else { if (b2 ^ b4) ans[b1] = b2, deal2(I1[b1][b2], I1[b3][b4]); else ans[b1] = b2, deal(I1[b1][b2], I1[b1][b2 ^ 1]); } return puts("IMPOSSIBLE"), 0; } inline void deal3(int x, int y) { printf("POSSIBLE\n%d %d\n", x, y); for (int i(1); i <= n; ++i) putchar(ans[I[i].id] ^ a[i] ? 50 : 49); exit(0); } inline void deal2(inter a, inter b) { I2t = 0, S.clear(), memset(is, 0, sizeof(is)), S.insert({0x3f3f3f3f}); for (int i(1), j; i <= at; ++i) if (i ^ b1 && i ^ b3) { for (j = 0; j < 2; ++j) I2[++I2t] = I1[i][j]; if (I1[i][0].r > I1[i][1].r) ans[i] = 0, S.insert(I1[i][0].r); else ans[i] = 1, S.insert({I1[i][1].r}); } if (!I2t) deal1(a, b); sort(I2 + 1, I2 + I2t + 1); for (int i(I2t), j, k; i; i = j) { for (j = i; j && I2[j].l == I2[i].l; --j) ; bool pd(false); for (k = i; k > j; --k) if (is[I2[k].id]) pd = 1, deal1(a, b); else { inter b1(I1[I2[k].id][I2[k].id1 ^ 1]); bool temp(ans[b1.id]); pd |= I2[k].l == b1.l; S.erase(S.find(max(I2[k].r, b1.r))), ans[b1.id] = b1.id1; deal1(a ^ (inter){0, *S.begin()} ^ b1, b ^ I2[k]); S.insert(max(I2[k].r, b1.r)), ans[b1.id] = temp; } if (pd) return; for (k = i; k > j; --k) if (!is[I2[k].id]) { inter b1(I1[I2[k].id][I2[k].id1 ^ 1]); S.erase(S.find(max(I2[k].r, b1.r))); ans[b1.id] = I2[k].id1, a ^= I2[k], b ^= b1; is[b1.id] = 1; } } } inline void deal1(inter a, inter b) { if (a.l > a.r || b.l > b.r) return; if (t - a.l <= b.l && b.l <= T - a.l) deal3(a.l, b.l); if (t - a.l <= b.r && b.r <= T - a.l) deal3(a.l, b.r); if (t - a.r <= b.l && b.l <= T - a.r) deal3(a.r, b.l); if (t - a.r <= b.r && b.r <= T - a.r) deal3(a.r, b.r); int x(a.l), y(t - x); if (b.l <= y && y <= b.r) deal3(x, y); x = a.r, y = t - x; if (b.l <= y && y <= b.r) deal3(x, y); y = b.l, x = t - y; if (a.l <= x && x <= a.r) deal3(x, y); y = b.r, x = t - y; if (a.l <= x && x <= a.r) deal3(x, y); } inline void deal(inter a, inter b) { I2t = 0, S.clear(), memset(is, 0, sizeof(is)), S.insert(0x3f3f3f3f); for (int i(1), j; i <= at; ++i) if (i ^ b1 && i ^ b3) { for (j = 0; j < 2; ++j) I2[++I2t] = I1[i][j]; if (I1[i][0].r > I1[i][1].r) S.insert(I1[i][0].r), ans[i] = 1; else S.insert(I1[i][1].r), ans[i] = 0; } if (!I2t) deal1(a, b); sort(I2 + 1, I2 + I2t + 1); for (int i(I2t), j, k; i; i = j) { for (j = i; j && I2[j].l == I2[i].l; --j) ; bool pd(false); for (k = i; k > j; --k) if (is[I2[k].id]) pd = 1, deal1(a, b ^ (inter){0, *S.begin()}); else { bool temp(ans[I2[k].id]); inter& b1(I1[I2[k].id][I2[k].id1 ^ 1]); pd |= b1.r == I2[k].r; ans[I2[k].id] = b1.id1, S.erase(S.find(max(I2[k].r, b1.r))); deal1(a, b ^ (inter){0, *S.begin()} ^ I2[k]); ans[I2[k].id] = temp, S.insert(max(I2[k].r, b1.r)); } if (pd) return; for (k = i; k > j; --k) if (!is[I2[k].id]) { inter& b1(I1[I2[k].id][I2[k].id1 ^ 1]); b ^= b1; is[I2[k].id] = 1, S.erase(S.find(max(I2[k].r, b1.r))); } } } template <class free> inline void Min(free& x, free y) { x = x < y ? x : y; } template <class free> inline void Max(free& x, free y) { x = x > y ? x : y; } inline bool dfs(int x, int c) { I1[I[x].id = at][a[x] = c] ^= I[x]; for (int i(head[x]), i1; i; i = ar[i].next) if (!~a[i1 = ar[i].to] && dfs(i1, c ^ 1)) return true; else if (a[i1] == c) return true; return false; } inline void link(int u, int v) { ar[++art] = {head[u], v}, head[u] = art; ar[++art] = {head[v], u}, head[v] = art; } inline void read(int& x) { x ^= x; register char c; while (c = getchar(), c < '0' || c > '9') ; while (c >= '0' && c <= '9') x = (x << 1) + (x << 3) + (c ^ 48), c = getchar(); } ```
### Prompt Your challenge is to write a CPP solution to the following problem: Limak and Radewoosh are going to compete against each other in the upcoming algorithmic contest. They are equally skilled but they won't solve problems in the same order. There will be n problems. The i-th problem has initial score pi and it takes exactly ti minutes to solve it. Problems are sorted by difficulty — it's guaranteed that pi < pi + 1 and ti < ti + 1. A constant c is given too, representing the speed of loosing points. Then, submitting the i-th problem at time x (x minutes after the start of the contest) gives max(0, pi - c·x) points. Limak is going to solve problems in order 1, 2, ..., n (sorted increasingly by pi). Radewoosh is going to solve them in order n, n - 1, ..., 1 (sorted decreasingly by pi). Your task is to predict the outcome — print the name of the winner (person who gets more points at the end) or a word "Tie" in case of a tie. You may assume that the duration of the competition is greater or equal than the sum of all ti. That means both Limak and Radewoosh will accept all n problems. Input The first line contains two integers n and c (1 ≤ n ≤ 50, 1 ≤ c ≤ 1000) — the number of problems and the constant representing the speed of loosing points. The second line contains n integers p1, p2, ..., pn (1 ≤ pi ≤ 1000, pi < pi + 1) — initial scores. The third line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ 1000, ti < ti + 1) where ti denotes the number of minutes one needs to solve the i-th problem. Output Print "Limak" (without quotes) if Limak will get more points in total. Print "Radewoosh" (without quotes) if Radewoosh will get more points in total. Print "Tie" (without quotes) if Limak and Radewoosh will get the same total number of points. Examples Input 3 2 50 85 250 10 15 25 Output Limak Input 3 6 50 85 250 10 15 25 Output Radewoosh Input 8 1 10 20 30 40 50 60 70 80 8 10 58 63 71 72 75 76 Output Tie Note In the first sample, there are 3 problems. Limak solves them as follows: 1. Limak spends 10 minutes on the 1-st problem and he gets 50 - c·10 = 50 - 2·10 = 30 points. 2. Limak spends 15 minutes on the 2-nd problem so he submits it 10 + 15 = 25 minutes after the start of the contest. For the 2-nd problem he gets 85 - 2·25 = 35 points. 3. He spends 25 minutes on the 3-rd problem so he submits it 10 + 15 + 25 = 50 minutes after the start. For this problem he gets 250 - 2·50 = 150 points. So, Limak got 30 + 35 + 150 = 215 points. Radewoosh solves problem in the reversed order: 1. Radewoosh solves 3-rd problem after 25 minutes so he gets 250 - 2·25 = 200 points. 2. He spends 15 minutes on the 2-nd problem so he submits it 25 + 15 = 40 minutes after the start. He gets 85 - 2·40 = 5 points for this problem. 3. He spends 10 minutes on the 1-st problem so he submits it 25 + 15 + 10 = 50 minutes after the start. He gets max(0, 50 - 2·50) = max(0, - 50) = 0 points. Radewoosh got 200 + 5 + 0 = 205 points in total. Limak has 215 points so Limak wins. In the second sample, Limak will get 0 points for each problem and Radewoosh will first solve the hardest problem and he will get 250 - 6·25 = 100 points for that. Radewoosh will get 0 points for other two problems but he is the winner anyway. In the third sample, Limak will get 2 points for the 1-st problem and 2 points for the 2-nd problem. Radewoosh will get 4 points for the 8-th problem. They won't get points for other problems and thus there is a tie because 2 + 2 = 4. ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main() { int n, c, p[55], t[55], x = 0, L = 0, R = 0; cin >> n >> c; for (int i = 0; i < n; i++) { cin >> p[i]; } for (int i = 0; i < n; i++) { cin >> t[i]; } for (int i = 0; i < n; i++) { x += t[i]; L += max(0, p[i] - c * x); } x = 0; for (int i = n - 1; i > -1; i--) { x += t[i]; R += max(0, p[i] - c * x); } if (L > R) { cout << "Limak" << endl; } else if (L < R) { cout << "Radewoosh" << endl; } else cout << "Tie" << endl; return 0; } ```
### Prompt Please formulate a Cpp solution to the following problem: Koa the Koala and her best friend want to play a game. The game starts with an array a of length n consisting of non-negative integers. Koa and her best friend move in turns and each have initially a score equal to 0. Koa starts. Let's describe a move in the game: * During his move, a player chooses any element of the array and removes it from this array, xor-ing it with the current score of the player. More formally: if the current score of the player is x and the chosen element is y, his new score will be x ⊕ y. Here ⊕ denotes [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR). Note that after a move element y is removed from a. * The game ends when the array is empty. At the end of the game the winner is the player with the maximum score. If both players have the same score then it's a draw. If both players play optimally find out whether Koa will win, lose or draw the game. Input Each test contains multiple test cases. The first line contains t (1 ≤ t ≤ 10^4) — the number of test cases. Description of the test cases follows. The first line of each test case contains the integer n (1 ≤ n ≤ 10^5) — the length of a. The second line of each test case contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9) — elements of a. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case print: * WIN if Koa will win the game. * LOSE if Koa will lose the game. * DRAW if the game ends in a draw. Examples Input 3 3 1 2 2 3 2 2 3 5 0 0 0 2 2 Output WIN LOSE DRAW Input 4 5 4 1 5 1 3 4 1 0 1 6 1 0 2 5 4 Output WIN WIN DRAW WIN Note In testcase 1 of the first sample we have: a = [1, 2, 2]. Here Koa chooses 1, other player has to choose 2, Koa chooses another 2. Score for Koa is 1 ⊕ 2 = 3 and score for other player is 2 so Koa wins. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int MAXN = 5001; int T, N; void solve() { cin >> N; vector<int> a(N); vector<int> c(30, 0), c2(30, 0); for (int i = 0; i < N; i++) { cin >> a[i]; int ind = 0; for (int j = 0; j < 30; j++) { if (a[i] & (1 << j)) c[j]++; else c2[j]++; } } for (int j = 29; j >= 0; j--) { if (c[j] % 2 == 1) { if (c[j] % 4 == 1 || c2[j] % 2 == 1) { cout << "WIN\n"; return; } else { cout << "LOSE\n"; return; } } } cout << "DRAW\n"; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> T; while (T--) { solve(); } } ```
### Prompt Please create a solution in Cpp to the following problem: You are given an integer N. Among the divisors of N! (= 1 \times 2 \times ... \times N), how many Shichi-Go numbers (literally "Seven-Five numbers") are there? Here, a Shichi-Go number is a positive integer that has exactly 75 divisors. Constraints * 1 \leq N \leq 100 * N is an integer. Input Input is given from Standard Input in the following format: N Output Print the number of the Shichi-Go numbers that are divisors of N!. Examples Input 9 Output 0 Input 10 Output 1 Input 100 Output 543 ### Response ```cpp #include <iostream> using namespace std; int n, p = 0; int dp[120][100]; bool is_prime(int n){ for(int i = 2; i * i <= n; i++)if(n % i == 0)return false; return true; } int main(){ cin >> n; dp[0][1] = 1; for (int i = 2; i <= n; i++){ if (is_prime(i) == false)continue; int cnt = 0; for (int j = 1; j <= n; j++){ int a = j; while (a % i == 0)cnt++, a /= i; } for (int j = 0; j <= cnt; j++){ for (int k = 1; k * (j + 1) <= 75; k++){ dp[i][k * (j + 1)] += dp[p][k]; } } p = i; } cout << dp[p][75] << endl; } ```
### Prompt Generate a cpp solution to the following problem: Berland crossword is a puzzle that is solved on a square grid with n rows and n columns. Initially all the cells are white. To solve the puzzle one has to color some cells on the border of the grid black in such a way that: * exactly U cells in the top row are black; * exactly R cells in the rightmost column are black; * exactly D cells in the bottom row are black; * exactly L cells in the leftmost column are black. Note that you can color zero cells black and leave every cell white. Your task is to check if there exists a solution to the given puzzle. Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of testcases. Then the descriptions of t testcases follow. The only line of each testcase contains 5 integers n, U, R, D, L (2 ≤ n ≤ 100; 0 ≤ U, R, D, L ≤ n). Output For each testcase print "YES" if the solution exists and "NO" otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer). Example Input 4 5 2 5 3 1 3 0 0 0 0 4 4 1 4 0 2 1 1 1 1 Output YES YES NO YES Note Here are possible solutions to testcases 1, 2 and 4: <image> ### Response ```cpp #include <bits/stdc++.h> using namespace std; inline bool active (int etat, int i) { return ((etat & (1 << i))!= 0); } inline bool est_ok (int nbDeja, int cote, int obj) { if (nbDeja > obj) return false; int nbBlancsMin = (2-nbDeja); int nbBlancsObj = cote-obj; if (nbBlancsMin > nbBlancsObj) return false; return true; } int main() { ios:: sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int nbTests; cin >> nbTests; for (int iTest = 0; iTest < nbTests; iTest++) { int cote, haut, droite, bas, gauche; cin >> cote >> haut >> droite >> bas >> gauche; bool okToutEtat = false; for (int etat = 0; etat < pow(2, 4); etat++) { int nbHaut = 0, nbBas = 0, nbGauche = 0, nbDroite = 0; if (active(etat, 0)) { nbGauche++; nbHaut++; } if (active(etat, 1)) { nbHaut++; nbDroite++; } if (active(etat, 2)) { nbDroite++; nbBas++; } if (active(etat, 3)) { nbBas++; nbGauche++; } bool ok = true; if (!est_ok(nbHaut, cote, haut)) ok = false; if (!est_ok(nbBas, cote, bas)) ok = false; if (!est_ok(nbDroite, cote, droite)) ok = false; if (!est_ok(nbGauche, cote, gauche)) ok = false; if (ok) okToutEtat = true; } if (okToutEtat) cout << "YES\n"; else cout << "NO\n"; } } ```
### Prompt Please formulate a CPP solution to the following problem: Evi has N integers a_1,a_2,..,a_N. His objective is to have N equal integers by transforming some of them. He may transform each integer at most once. Transforming an integer x into another integer y costs him (x-y)^2 dollars. Even if a_i=a_j (i≠j), he has to pay the cost separately for transforming each of them (See Sample 2). Find the minimum total cost to achieve his objective. Constraints * 1≦N≦100 * -100≦a_i≦100 Input The input is given from Standard Input in the following format: N a_1 a_2 ... a_N Output Print the minimum total cost to achieve Evi's objective. Examples Input 2 4 8 Output 8 Input 3 1 1 3 Output 3 Input 3 4 2 5 Output 5 Input 4 -100 -100 -100 -100 Output 0 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int main(){ int n, i, ave = 0, sum = 0; cin >> n; int a[n]; for(i=0; i<n; i++){ cin >> a[i]; ave += a[i]; } ave = round((float)ave/n); for(i=0; i<n; i++){ sum += (ave - a[i])*(ave -a[i]); } cout << sum; return 0; } ```
### Prompt Your task is to create a CPP solution to the following problem: C: Skewering problem One day, when Homura was playing with blocks, Tempura came. Homura decided to play with blocks with Tempura. There is a rectangular parallelepiped of A \ times B \ times C, which is made by stacking A \ times B \ times C blocks of cubic blocks with a side length of 1 without any gaps. Each side of all cubes and rectangular parallelepipeds is parallel to the x-axis, y-axis, or z-axis. Homura-chan and Tempura-kun alternately repeat the following operations. * Select a row of blocks of building blocks lined up in a row from a rectangular parallelepiped in any of the vertical, horizontal, and depth directions, and paint all the blocks included in the row in red. However, you cannot select columns that contain blocks that are already painted red. More precisely * Select one of the blocks contained in the rectangular parallelepiped and one of the three directions x, y, and z. * When the selected block is moved in the selected direction by an integer distance, all the blocks that completely overlap are painted in red (think of moving the distance of 0 or a negative integer). However, this operation cannot be performed if there is at least one block that meets the conditions and has already been painted. Homura-chan is the first player to lose the game if he can't operate it first. Also, initially all cubes are uncolored. Determine which one wins when the two act optimally. Input format A B C Constraint * 1 \ leq A, B, C \ leq 100 * All inputs are integers. Output format When the two act optimally, if Homura wins, `Hom` is output, and if Tempura wins,` Tem` is output on one line. Input example 1 1 1 10 Output example 1 Hom * The first time Homura can paint all the blocks red. Input example 2 4 3 5 Output example 2 Hom Input example 3 6 4 10 Output example 3 Tem Example Input 1 1 10 Output Hom ### Response ```cpp #include<iostream> #include<string> #include<cstdio> #include<vector> #include<cmath> #include<algorithm> #include<functional> #include<iomanip> #include<queue> #include<ciso646> #include<random> #include<map> #include<set> #include<bitset> #include<stack> #include<unordered_map> #include<utility> #include<cassert> using namespace std; typedef long long ll; typedef unsigned long long ul; typedef unsigned int ui; const ll mod = 998244353; const ll INF = mod * mod; typedef pair<int, int> P; #define stop char nyaa;cin>>nyaa; #define rep(i,n) for(int i=0;i<n;i++) #define per(i,n) for(int i=n-1;i>=0;i--) #define Rep(i,sta,n) for(int i=sta;i<n;i++) #define rep1(i,n) for(int i=1;i<=n;i++) #define per1(i,n) for(int i=n;i>=1;i--) #define Rep1(i,sta,n) for(int i=sta;i<=n;i++) typedef pair<ll, ll> LP; typedef vector<LP> vec; typedef vector<string> svec; typedef long double ld; typedef pair<ld, ld> LDP; const ld eps = 1e-8; void solve() { int a, b, c; cin >> a >> b >> c; int num = 0; if (a % 2)num++; if (b % 2)num++; if (c % 2)num++; if (num<=1) { cout << "Tem" << endl; } else { cout << "Hom" << endl; } } signed main() { ios::sync_with_stdio(false); cin.tie(0); //cout << fixed << setprecision(10); //init(); solve(); //stop return 0; } ```
### Prompt Create a solution in CPP for the following problem: Prime numbers are widely applied for cryptographic and communication technology. A twin prime is a prime number that differs from another prime number by 2. For example, (5, 7) and (11, 13) are twin prime pairs. In this problem, we call the greater number of a twin prime "size of the twin prime." Your task is to create a program which reads an integer n and prints a twin prime which has the maximum size among twin primes less than or equals to n You may assume that 5 ≤ n ≤ 10000. Input The input is a sequence of datasets. The end of the input is indicated by a line containing one zero. Each dataset is formatted as follows: n (integer) Output For each dataset, print the twin prime p and q (p < q). p and q should be separated by a single space. Example Input 12 100 200 300 0 Output 5 7 71 73 197 199 281 283 ### Response ```cpp #include<stdio.h> int main(){ const int MAX_V = 10000; int prime[MAX_V+1]; int i, k, v, ans, dif; for(i = 2; i <= MAX_V; i++){ prime[i] = 1; } for(i = 2; i*i <= MAX_V; i++){ if(prime[i]){ for(k = 2 * i; k <= MAX_V; k += i){ prime[k] = 0; } } } while(scanf("%d", &v) != EOF){ if(v == 0) break; for(k = v; k >= 2; k--){ ans = prime[k]; if(ans == 1){ dif = prime[k - 2]; if(dif == 1){ printf("%d %d\n", k - 2, k); break; } } } } return 0; } ```
### Prompt Create a solution in Cpp for the following problem: Simon has an array a1, a2, ..., an, consisting of n positive integers. Today Simon asked you to find a pair of integers l, r (1 ≤ l ≤ r ≤ n), such that the following conditions hold: 1. there is integer j (l ≤ j ≤ r), such that all integers al, al + 1, ..., ar are divisible by aj; 2. value r - l takes the maximum value among all pairs for which condition 1 is true; Help Simon, find the required pair of numbers (l, r). If there are multiple required pairs find all of them. Input The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 106). Output Print two integers in the first line — the number of required pairs and the maximum value of r - l. On the following line print all l values from optimal pairs in increasing order. Examples Input 5 4 6 9 3 6 Output 1 3 2 Input 5 1 3 5 7 9 Output 1 4 1 Input 5 2 3 5 7 11 Output 5 0 1 2 3 4 5 Note In the first sample the pair of numbers is right, as numbers 6, 9, 3 are divisible by 3. In the second sample all numbers are divisible by number 1. In the third sample all numbers are prime, so conditions 1 and 2 are true only for pairs of numbers (1, 1), (2, 2), (3, 3), (4, 4), (5, 5). ### Response ```cpp #include <bits/stdc++.h> using namespace std; long long int st_min[300001][20], st_gcd[300001][20]; long long int gcd(long long int a, long long int b) { if (a == 0) return b; return gcd(b % a, a); } bool f(long long int n, long long int M, long long int log_2[]) { for (auto i = 0; i < n - M; i++) { long long int j = log_2[M + 1]; if (min(st_min[i][j], st_min[i + M - (1 << j) + 1][j]) == gcd(st_gcd[i][j], st_gcd[i + M - (1 << j) + 1][j])) return true; } return false; } signed main() { ios_base::sync_with_stdio(0); cin.tie(NULL); long long int n; cin >> n; long long int a[n]; for (auto i = 0; i < n; i++) cin >> a[i]; for (auto i = 0; i < n; i++) { st_min[i][0] = a[i]; st_gcd[i][0] = a[i]; } for (auto j = 1; j < 20; j++) for (auto i = 0; i < n; i++) { st_min[i][j] = st_min[i][j - 1]; st_gcd[i][j] = st_gcd[i][j - 1]; if (i + (1 << (j - 1)) < n) { st_min[i][j] = min(st_min[i][j], st_min[i + (1 << (j - 1))][j - 1]); st_gcd[i][j] = gcd(st_gcd[i][j], st_gcd[i + (1 << (j - 1))][j - 1]); } } long long int log_2[n + 1]; log_2[1] = 0; for (auto i = 2; i < n + 1; i++) log_2[i] = log_2[i / 2] + 1; long long int L = 0, R = n - 1, M, chk = -1; while (L <= R) { M = (L + R) >> 1; if (f(n, M, log_2)) { chk = M; L = M + 1; } else R = M - 1; } vector<long long int> v; for (auto i = 0; i < n - chk; i++) { long long int j = log_2[chk + 1]; if (min(st_min[i][j], st_min[i + chk - (1 << j) + 1][j]) == gcd(st_gcd[i][j], st_gcd[i + chk - (1 << j) + 1][j])) v.push_back(i + 1); } cout << (long long int)(v).size() << " " << chk << "\n"; for (auto i = 0; i < (long long int)(v).size(); i++) cout << v[i] << " "; cout << "\n"; return 0; } ```
### Prompt Your challenge is to write a Cpp solution to the following problem: The name of one small but proud corporation consists of n lowercase English letters. The Corporation has decided to try rebranding — an active marketing strategy, that includes a set of measures to change either the brand (both for the company and the goods it produces) or its components: the name, the logo, the slogan. They decided to start with the name. For this purpose the corporation has consecutively hired m designers. Once a company hires the i-th designer, he immediately contributes to the creation of a new corporation name as follows: he takes the newest version of the name and replaces all the letters xi by yi, and all the letters yi by xi. This results in the new version. It is possible that some of these letters do no occur in the string. It may also happen that xi coincides with yi. The version of the name received after the work of the last designer becomes the new name of the corporation. Manager Arkady has recently got a job in this company, but is already soaked in the spirit of teamwork and is very worried about the success of the rebranding. Naturally, he can't wait to find out what is the new name the Corporation will receive. Satisfy Arkady's curiosity and tell him the final version of the name. Input The first line of the input contains two integers n and m (1 ≤ n, m ≤ 200 000) — the length of the initial name and the number of designers hired, respectively. The second line consists of n lowercase English letters and represents the original name of the corporation. Next m lines contain the descriptions of the designers' actions: the i-th of them contains two space-separated lowercase English letters xi and yi. Output Print the new name of the corporation. Examples Input 6 1 police p m Output molice Input 11 6 abacabadaba a b b c a d e g f a b b Output cdcbcdcfcdc Note In the second sample the name of the corporation consecutively changes as follows: <image> <image> <image> <image> <image> <image> ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int MAXN = 200020; int cnt; char str[MAXN]; int a[30], b[30]; int main() { int n, m; scanf("%d%d", &m, &n); scanf("%s", &str); getchar(); char ch1, ch2; for (int i = 0; i < 26; i++) { a[i] = i; b[i] = i; } for (int i = 1; i <= n; i++) { scanf("%c %c", &ch1, &ch2); getchar(); int x = b[ch1 - 'a']; int y = b[ch2 - 'a']; int tmp = a[x]; a[x] = a[y]; a[y] = tmp; b[a[x]] = x; b[a[y]] = y; } for (int i = 0; i < m; i++) { printf("%c", a[str[i] - 'a'] + 'a'); } printf("\n"); return 0; } ```
### Prompt Create a solution in cpp for the following problem: One day Vasya came up to the blackboard and wrote out n distinct integers from 1 to n in some order in a circle. Then he drew arcs to join the pairs of integers (a, b) (a ≠ b), that are either each other's immediate neighbors in the circle, or there is number c, such that a and с are immediate neighbors, and b and c are immediate neighbors. As you can easily deduce, in the end Vasya drew 2·n arcs. For example, if the numbers are written in the circle in the order 1, 2, 3, 4, 5 (in the clockwise direction), then the arcs will join pairs of integers (1, 2), (2, 3), (3, 4), (4, 5), (5, 1), (1, 3), (2, 4), (3, 5), (4, 1) and (5, 2). Much time has passed ever since, the numbers we wiped off the blackboard long ago, but recently Vasya has found a piece of paper with 2·n written pairs of integers that were joined with the arcs on the board. Vasya asks you to find the order of numbers in the circle by these pairs. Input The first line of the input contains a single integer n (5 ≤ n ≤ 105) that shows, how many numbers were written on the board. Next 2·n lines contain pairs of integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — the numbers that were connected by the arcs. It is guaranteed that no pair of integers, connected by a arc, occurs in the input more than once. The pairs of numbers and the numbers in the pairs are given in the arbitrary order. Output If Vasya made a mistake somewhere and there isn't any way to place numbers from 1 to n on the circle according to the statement, then print a single number "-1" (without the quotes). Otherwise, print any suitable sequence of n distinct integers from 1 to n. If there are multiple solutions, you are allowed to print any of them. Specifically, it doesn't matter which number you write first to describe the sequence of the order. It also doesn't matter whether you write out the numbers in the clockwise or counter-clockwise direction. Examples Input 5 1 2 2 3 3 4 4 5 5 1 1 3 2 4 3 5 4 1 5 2 Output 1 2 3 4 5 Input 6 5 6 4 3 5 3 2 4 6 1 3 1 6 2 2 5 1 4 3 6 1 2 4 5 Output 1 2 4 5 3 6 ### Response ```cpp #include <bits/stdc++.h> using namespace std; vector<vector<int> > E; vector<int> nodes; bitset<100001> bs; int n; bool connected(int a, int b) { bool ans = false; for (int i = 0; i < 4; ++i) { if (E[a][i] == b) { ans = true; break; } } return ans; } bool dfs(int a, int b, int k, int lim) { if (k == lim) { return b == 1; } nodes[k - 1] = a, nodes[k] = b; bs[b] = true; for (int i = 0; i < 4; ++i) { int m = E[b][i]; if (bs[m]) continue; if (connected(a, m) && dfs(b, m, k + 1, lim)) return true; } bs[b] = false; return false; } int main() { ios_base::sync_with_stdio(0); int n, a, b; cin >> n; E.resize(n + 1); nodes.resize(n + 1); for (int i = 0; i < (2 * n); ++i) { cin >> a >> b; E[a].push_back(b); E[b].push_back(a); } for (int i = 1; i <= n; ++i) { if (E[i].size() != 4) { cout << -1 << '\n'; return 0; } } for (int i = 0; i < 4; ++i) { if (dfs(1, E[1][i], 1, n)) { for (int j = 0; j < n; ++j) cout << nodes[j] << " "; cout << '\n'; return 0; } } cout << -1 << '\n'; } ```
### Prompt Generate a Cpp solution to the following problem: Little X has n distinct integers: p1, p2, ..., pn. He wants to divide all of them into two sets A and B. The following two conditions must be satisfied: * If number x belongs to set A, then number a - x must also belong to set A. * If number x belongs to set B, then number b - x must also belong to set B. Help Little X divide the numbers into two sets or determine that it's impossible. Input The first line contains three space-separated integers n, a, b (1 ≤ n ≤ 105; 1 ≤ a, b ≤ 109). The next line contains n space-separated distinct integers p1, p2, ..., pn (1 ≤ pi ≤ 109). Output If there is a way to divide the numbers into two sets, then print "YES" in the first line. Then print n integers: b1, b2, ..., bn (bi equals either 0, or 1), describing the division. If bi equals to 0, then pi belongs to set A, otherwise it belongs to set B. If it's impossible, print "NO" (without the quotes). Examples Input 4 5 9 2 3 4 5 Output YES 0 0 1 1 Input 3 3 4 1 2 4 Output NO Note It's OK if all the numbers are in the same set, and the other one is empty. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int maxn = (int)1e5 + 10; ; map<int, int> m; int num[maxn], n, a, b, pr[maxn], rank[maxn]; bool ans[maxn]; int find(int a) { return (a == pr[a] ? a : pr[a] = find(pr[a])); } void uni(int a, int b) { a = find(a); b = find(b); pr[a] = b; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); for (int i = 0; i < maxn; i++) { pr[i] = i; } cin >> n >> a >> b; for (int i = 2; i < n + 2; i++) { cin >> num[i]; m[num[i]] = i; } for (int i = 2; i < n + 2; i++) { if (m[a - num[i]]) uni(m[num[i]], m[a - num[i]]); if (m[b - num[i]]) uni(m[num[i]], m[b - num[i]]); } if (a == b) { for (int i = 2; i < n + 2; i++) { if (!m[a - num[i]]) { cout << "NO"; return 0; } } cout << "YES\n"; for (int i = 0; i < n; i++) cout << "0 "; return 0; } for (int i = 2; i < n + 2; i++) { if ((find(i) == 0 && !m[a - num[i]]) || (find(i) == 1 && !m[b - num[i]]) || (!m[a - num[i]] && !m[b - num[i]])) { cout << "NO"; return 0; } bool f = m[a - num[i]], f2 = m[b - num[i]]; if (f && f2) continue; if (f) { pr[find(i)] = 0; } else { pr[find(i)] = 1; } } cout << "YES\n"; for (int i = 2; i < n + 2; i++) cout << find(i) << " "; } ```
### Prompt In CPP, your task is to solve the following problem: You are given sequence a1, a2, ..., an and m queries lj, rj (1 ≤ lj ≤ rj ≤ n). For each query you need to print the minimum distance between such pair of elements ax and ay (x ≠ y), that: * both indexes of the elements lie within range [lj, rj], that is, lj ≤ x, y ≤ rj; * the values of the elements are equal, that is ax = ay. The text above understands distance as |x - y|. Input The first line of the input contains a pair of integers n, m (1 ≤ n, m ≤ 5·105) — the length of the sequence and the number of queries, correspondingly. The second line contains the sequence of integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). Next m lines contain the queries, one per line. Each query is given by a pair of numbers lj, rj (1 ≤ lj ≤ rj ≤ n) — the indexes of the query range limits. Output Print m integers — the answers to each query. If there is no valid match for some query, please print -1 as an answer to this query. Examples Input 5 3 1 1 2 3 2 1 5 2 4 3 5 Output 1 -1 2 Input 6 5 1 2 1 3 2 3 4 6 1 3 2 5 2 4 1 6 Output 2 2 3 -1 2 ### Response ```cpp #include <bits/stdc++.h> using namespace std; int Num; char CH[20]; const int inf = 0x3f3f3f3f; inline long long 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 * 10 + ch - '0'; ch = getchar(); } return x * f; } inline void P(int x) { Num = 0; if (!x) { putchar('0'); puts(""); return; } while (x > 0) CH[++Num] = x % 10, x /= 10; while (Num) putchar(CH[Num--] + 48); puts(""); } struct node { int l, r, v; } a[500001 * 4]; struct ques { int l, r, an, v; } qu[500001]; void build(int x, int l, int r) { a[x].l = l, a[x].r = r; a[x].v = 500001; if (l == r) return; int mid = (l + r) >> 1; build(x << 1, l, mid); build(x << 1 | 1, mid + 1, r); } void pushup(int x) { a[x].v = min(a[x << 1].v, a[x << 1 | 1].v); } void update(int x, int pos, int val) { if (a[x].l == a[x].r) { a[x].v = val; return; } int mid = (a[x].l + a[x].r) >> 1; if (pos <= mid) update(x << 1, pos, val); else update(x << 1 | 1, pos, val); pushup(x); } int mi; void query(int x, int l, int r) { if (l <= a[x].r && r >= a[x].r) { mi = min(mi, a[x].v); return; } int mid = (a[x].l + a[x].r) >> 1; if (l <= mid) query(x << 1, l, r); if (r > mid) query(x << 1 | 1, l, r); } map<int, int> mp; int d[500001]; bool cmp(ques a, ques b) { return a.l > b.l; } int ans[500001]; int main() { int n = read(), m = read(); build(1, 1, n); for (int i = 1; i <= n; i++) d[i] = read(); for (int i = 1; i <= m; i++) { qu[i].l = read(), qu[i].r = read(); qu[i].v = i; } sort(qu + 1, qu + 1 + m, cmp); int t = 1; for (int i = n; i; i--) { if (mp[d[i]]) { update(1, mp[d[i]], mp[d[i]] - i); } mp[d[i]] = i; while (qu[t].l == i) { mi = 500001; query(1, qu[t].l, qu[t].r); if (mi == 500001) mi = -1; ans[qu[t].v] = mi; t++; } } for (int i = 1; i <= m; i++) printf("%d\n", ans[i]); } ```
### Prompt Create a solution in cpp for the following problem: A substring of some string is called the most frequent, if the number of its occurrences is not less than number of occurrences of any other substring. You are given a set of strings. A string (not necessarily from this set) is called good if all elements of the set are the most frequent substrings of this string. Restore the non-empty good string with minimum length. If several such strings exist, restore lexicographically minimum string. If there are no good strings, print "NO" (without quotes). A substring of a string is a contiguous subsequence of letters in the string. For example, "ab", "c", "abc" are substrings of string "abc", while "ac" is not a substring of that string. The number of occurrences of a substring in a string is the number of starting positions in the string where the substring occurs. These occurrences could overlap. String a is lexicographically smaller than string b, if a is a prefix of b, or a has a smaller letter at the first position where a and b differ. Input The first line contains integer n (1 ≤ n ≤ 105) — the number of strings in the set. Each of the next n lines contains a non-empty string consisting of lowercase English letters. It is guaranteed that the strings are distinct. The total length of the strings doesn't exceed 105. Output Print the non-empty good string with minimum length. If several good strings exist, print lexicographically minimum among them. Print "NO" (without quotes) if there are no good strings. Examples Input 4 mail ai lru cf Output cfmailru Input 3 kek preceq cheburek Output NO Note One can show that in the first sample only two good strings with minimum length exist: "cfmailru" and "mailrucf". The first string is lexicographically minimum. ### Response ```cpp #include <bits/stdc++.h> using namespace std; const int maxn = 100100; char *s[maxn], *p, buf[maxn * 2]; char t[maxn]; int alp[30][30], d[30], is[30], vis[30]; int ct; bool dfs(int u) { t[ct++] = u + 'a'; vis[u] = 1; int cnt = 0, p = -1; for (int i = 0; i < 26; i++) { if (alp[u][i]) cnt++, p = i; } if (cnt > 1) return false; if (cnt == 0) { t[ct] = 0; return true; } if (vis[p]) return 0; return dfs(p); } int main(void) { int n; scanf("%d", &n); p = buf; for (int i = 1; i <= n; i++) { scanf("%s", p); s[i] = p; p += strlen(p) + 1; } for (int i = 1; i <= n; i++) { is[s[i][0] - 'a'] = 1; for (int j = 1; s[i][j]; j++) { alp[s[i][j - 1] - 'a'][s[i][j] - 'a'] = 1; d[s[i][j] - 'a']++; is[s[i][0] - 'a'] = 1; } } int flag = 0, yes = 0; for (int i = 0; i < 26; i++) if (is[i] == 1) { if (d[i] == 0) { yes = 1; if (dfs(i) == false) { flag = 1; break; } } } for (int i = 0; i < 26; i++) if (is[i] && vis[i] == 0) { flag = 1; } if (flag || yes == 0) { printf("NO\n"); return 0; } printf("%s\n", t); return 0; } ```
### Prompt Your task is to create a CPP solution to the following problem: You are now examining a unique method to sort a sequence of numbers in increasing order. The method only allows swapping of two numbers that have a common prime factor. For example, a sequence [6, 4, 2, 3, 7] can be sorted using the following steps. Step 0: 6 4 2 3 7 (given sequence) Step 1: 2 4 6 3 7 (elements 6 and 2 swapped) Step 2: 2 6 4 3 7 (elements 4 and 6 swapped) Step 3: 2 3 4 6 7 (elements 6 and 3 swapped) Depending on the nature of the sequence, however, this approach may fail to complete the sorting. You have given a name "Coprime sort" to this approach and are now examining if a given sequence is coprime-sortable. Make a program to determine if a given sequence can be sorted in increasing order by iterating an arbitrary number of swapping operations of two elements that have a common prime number. Input The input is given in the following format. $N$ $a_1$ $a_2$ $...$ $a_N$ The first line provides the number of elements included in the sequence $N$ ($2 \leq N \leq 10^5$). The second line provides an array of integers $a_i$ ($2 \leq a_i \leq 10^5$) that constitute the sequence. Output Output "1" if the sequence is coprime-sortable in increasing order, or "0" otherwise. Examples Input 5 6 4 2 3 7 Output 1 Input 7 2 9 6 5 6 7 3 Output 0 ### Response ```cpp #include <iostream> #include <fstream> #include <stdio.h> #include <math.h> #include <time.h> #include <string> #include <tuple> #include <vector> #include <map> #include <unordered_map> #include <list> #include <set> #include <stack> #include <queue> #include <cstdlib> #include <algorithm> #include <random> #include <cassert> using namespace std; #define MP(a, b) make_pair(a, b) //Union-Find木 struct UnionFind{ private: vector<int> parent; public: UnionFind(int N) : parent(N){ //初期化する O(N) for(int i=0; i<N; i++) parent[i] = i; } int root(int a){ //親を返す O(log N) if(parent[a] == a) return a; return parent[a] = root(parent[a]); } void unite(int a, int b){ //木を併合する O(log N) int rootA = root(a); int rootB = root(b); if(rootA != rootB) parent[rootA] = rootB; } bool same(int a, int b){ //属する木が同じかを返す O(log N) return root(a) == root(b); } }; int main(){ iostream::sync_with_stdio(false); int N; cin >> N; int a[100000]; vector<pair<int,int> > b; for(int i=0; i<N; i++){ cin >> a[i]; b.push_back(MP(a[i], i)); } sort(b.begin(), b.end()); UnionFind uf(N); //素因数分解 map<int,int> so; for(int i=0; i<N; i++){ for(int j=2; j<=sqrt(a[i])+1; j++){ if(a[i] % j == 0){ a[i] /= j; auto itr = so.find(j); if(itr == so.end()) so[j] = i; else uf.unite(i,itr->second); j--; } } if(a[i] != 1){ auto itr = so.find(a[i]); if(itr == so.end()) so[a[i]] = i; else uf.unite(i,itr->second); } } //判定 for(int i=0; i<N; i++){ if(!uf.same(i, b[i].second)){ cout << 0 << endl; return 0; } } cout << 1 << endl; return 0; } ```
### Prompt Your task is to create a Cpp solution to the following problem: Bessie and the cows are playing with sequences and need your help. They start with a sequence, initially containing just the number 0, and perform n operations. Each operation is one of the following: 1. Add the integer xi to the first ai elements of the sequence. 2. Append an integer ki to the end of the sequence. (And hence the size of the sequence increases by 1) 3. Remove the last element of the sequence. So, the size of the sequence decreases by one. Note, that this operation can only be done if there are at least two elements in the sequence. After each operation, the cows would like to know the average of all the numbers in the sequence. Help them! Input The first line contains a single integer n (1 ≤ n ≤ 2·105) — the number of operations. The next n lines describe the operations. Each line will start with an integer ti (1 ≤ ti ≤ 3), denoting the type of the operation (see above). If ti = 1, it will be followed by two integers ai, xi (|xi| ≤ 103; 1 ≤ ai). If ti = 2, it will be followed by a single integer ki (|ki| ≤ 103). If ti = 3, it will not be followed by anything. It is guaranteed that all operations are correct (don't touch nonexistent elements) and that there will always be at least one element in the sequence. Output Output n lines each containing the average of the numbers in the sequence after the corresponding operation. The answer will be considered correct if its absolute or relative error doesn't exceed 10 - 6. Examples Input 5 2 1 3 2 3 2 1 3 Output 0.500000 0.000000 1.500000 1.333333 1.500000 Input 6 2 1 1 2 20 2 2 1 2 -3 3 3 Output 0.500000 20.500000 14.333333 12.333333 17.500000 17.000000 Note In the second sample, the sequence becomes <image> ### Response ```cpp #include <bits/stdc++.h> const int inf = 0xfffffff; const long long INF = 1ll << 61; using namespace std; int add[200000 + 5]; int now[200000 + 5]; int len; double sum; void init() { len = 1; sum = 0.00; memset(add, 0, sizeof(add)); memset(now, 0, sizeof(now)); } void input(int &n) { scanf("%d", &n); } void cal(int &n) { int t; while (n--) { scanf("%d", &t); if (t == 1) { int x, a; scanf("%d %d", &a, &x); sum += a * x; add[a] += x; double ans = sum * 1.0 / len * 1.0; printf("%lf\n", ans); } else if (t == 2) { int x; scanf("%d", &x); now[++len] = x; sum += x; double ans = sum * 1.0 / len * 1.0; printf("%lf\n", ans); } else { if (len < 2) continue; sum -= now[len]; sum -= add[len]; if (add[len]) add[len - 1] += add[len]; add[len] = 0; now[len] = 0; --len; double ans = sum * 1.0 / len * 1.0; printf("%lf\n", ans); } } } void output() {} int main() { int n; init(); input(n); cal(n); output(); return 0; } ```