Search is not available for this dataset
name
stringlengths
2
112
description
stringlengths
29
13k
source
int64
1
7
difficulty
int64
0
25
solution
stringlengths
7
983k
language
stringclasses
4 values
139_C. Literature Lesson
Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes. Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels. Two lines rhyme if their suffixes that start from the k-th vowels (counting from the end) match. If a line has less than k vowels, then such line can't rhyme with any other line. For example, if k = 1, lines commit and hermit rhyme (the corresponding suffixes equal it), and if k = 2, they do not rhyme (ommit β‰  ermit). Today on a literature lesson Vera learned that quatrains can contain four different schemes of rhymes, namely the following ones (the same letters stand for rhyming lines): * Clerihew (aabb); * Alternating (abab); * Enclosed (abba). If all lines of a quatrain pairwise rhyme, then the quatrain can belong to any rhyme scheme (this situation is represented by aaaa). If all quatrains of a poem belong to the same rhyme scheme, then we can assume that the whole poem belongs to this rhyme scheme. If in each quatrain all lines pairwise rhyme, then the rhyme scheme of the poem is aaaa. Let us note that it doesn't matter whether lines from different quatrains rhyme with each other or not. In other words, it is possible that different quatrains aren't connected by a rhyme. Vera got a long poem as a home task. The girl has to analyse it and find the poem rhyme scheme. Help Vera cope with the task. Input The first line contains two integers n and k (1 ≀ n ≀ 2500, 1 ≀ k ≀ 5) β€” the number of quatrains in the poem and the vowel's number, correspondingly. Next 4n lines contain the poem. Each line is not empty and only consists of small Latin letters. The total length of the lines does not exceed 104. If we assume that the lines are numbered starting from 1, then the first quatrain contains lines number 1, 2, 3, 4; the second one contains lines number 5, 6, 7, 8; and so on. Output Print the rhyme scheme of the poem as "aabb", "abab", "abba", "aaaa"; or "NO" if the poem does not belong to any of the above mentioned schemes. Examples Input 1 1 day may sun fun Output aabb Input 1 1 day may gray way Output aaaa Input 2 1 a a a a a a e e Output aabb Input 2 1 day may sun fun test hill fest thrill Output NO Note In the last sample both quatrains have rhymes but finding the common scheme is impossible, so the answer is "NO".
2
9
#include <bits/stdc++.h> using namespace std; const int N = 1000005; long long modd = 998244353; vector<bool> isprime(N); vector<int> primes; void seive() { isprime[0] = false; isprime[1] = false; for (int i = 2; i <= 1e6; i++) { isprime[i] = true; } for (int i = 2; i * i <= 1e6; i++) { if (isprime[i]) { for (int j = i * i; j <= 1e6; j += i) { isprime[j] = false; } } } for (int i = 2; i < 1e6; i++) { if (isprime[i]) { primes.push_back(i); } } } void Reverse_Matrix() { int n, k; cin >> n >> k; set<char> s; s.insert('a'); s.insert('e'); s.insert('i'); s.insert('o'); s.insert('u'); int dp[3] = {0}; for (int i = 0; i < n; i++) { string s1, s2, s3, s4; cin >> s1 >> s2 >> s3 >> s4; int l1 = s1.length(); int l2 = s2.length(); int l3 = s3.length(); int l4 = s4.length(); int cnt1 = 0; for (int i = l1 - 1; i >= 0; i--) { if (s.find(s1[i]) != s.end()) cnt1++; if (cnt1 == k) { s1 = s1.substr(i); break; } } int cnt2 = 0; for (int i = l2 - 1; i >= 0; i--) { if (s.find(s2[i]) != s.end()) cnt2++; if (cnt2 == k) { s2 = s2.substr(i); break; } } int cnt3 = 0; for (int i = l3 - 1; i >= 0; i--) { if (s.find(s3[i]) != s.end()) cnt3++; if (cnt3 == k) { s3 = s3.substr(i); break; } } int cnt4 = 0; for (int i = l4 - 1; i >= 0; i--) { if (s.find(s4[i]) != s.end()) cnt4++; if (cnt4 == k) { s4 = s4.substr(i); break; } } if (cnt1 != k || cnt2 != k || cnt3 != k || cnt4 != k) { cout << "NO" << endl; return; } if (s1 == s2 && s2 == s3 && s3 == s4) { dp[0]++; dp[1]++; dp[2]++; } else if (s1 == s2 && s3 == s4) { dp[0]++; } else if (s1 == s3 && s2 == s4) { dp[1]++; } else if (s1 == s4 && s2 == s3) { dp[2]++; } else { cout << "NO" << endl; return; } } if (dp[0] < n && dp[1] < n && dp[2] < n) { cout << "NO"; } else if (dp[0] == n && dp[1] == n && dp[2] == n) { cout << "aaaa" << endl; } else if (dp[0] == n) { cout << "aabb" << endl; } else if (dp[1] == n) { cout << "abab" << endl; } else { cout << "abba" << endl; } } int main() { ios_base::sync_with_stdio(false); int TEST = 1; while (TEST--) { Reverse_Matrix(); } }
CPP
139_C. Literature Lesson
Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes. Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels. Two lines rhyme if their suffixes that start from the k-th vowels (counting from the end) match. If a line has less than k vowels, then such line can't rhyme with any other line. For example, if k = 1, lines commit and hermit rhyme (the corresponding suffixes equal it), and if k = 2, they do not rhyme (ommit β‰  ermit). Today on a literature lesson Vera learned that quatrains can contain four different schemes of rhymes, namely the following ones (the same letters stand for rhyming lines): * Clerihew (aabb); * Alternating (abab); * Enclosed (abba). If all lines of a quatrain pairwise rhyme, then the quatrain can belong to any rhyme scheme (this situation is represented by aaaa). If all quatrains of a poem belong to the same rhyme scheme, then we can assume that the whole poem belongs to this rhyme scheme. If in each quatrain all lines pairwise rhyme, then the rhyme scheme of the poem is aaaa. Let us note that it doesn't matter whether lines from different quatrains rhyme with each other or not. In other words, it is possible that different quatrains aren't connected by a rhyme. Vera got a long poem as a home task. The girl has to analyse it and find the poem rhyme scheme. Help Vera cope with the task. Input The first line contains two integers n and k (1 ≀ n ≀ 2500, 1 ≀ k ≀ 5) β€” the number of quatrains in the poem and the vowel's number, correspondingly. Next 4n lines contain the poem. Each line is not empty and only consists of small Latin letters. The total length of the lines does not exceed 104. If we assume that the lines are numbered starting from 1, then the first quatrain contains lines number 1, 2, 3, 4; the second one contains lines number 5, 6, 7, 8; and so on. Output Print the rhyme scheme of the poem as "aabb", "abab", "abba", "aaaa"; or "NO" if the poem does not belong to any of the above mentioned schemes. Examples Input 1 1 day may sun fun Output aabb Input 1 1 day may gray way Output aaaa Input 2 1 a a a a a a e e Output aabb Input 2 1 day may sun fun test hill fest thrill Output NO Note In the last sample both quatrains have rhymes but finding the common scheme is impossible, so the answer is "NO".
2
9
n, k = [int(x) for x in raw_input().split()] def get(s): global k s1 = s[::-1] previ = 0 for p in xrange(k - 1): for i in xrange(previ, len(s1)): if s1[i] in ['a', 'e', 'i', 'o', 'u']: s1 = s1[:i] + chr(ord(s1[i])-ord('a')+ord('A')) + s1[i+1:] previ = i + 1 break for i in xrange(len(s1)): if s1[i] in ['a', 'e', 'i', 'o', 'u']: s1 = s1[:i+1] break return s1 def isbad(s): global k for i in xrange(4): p = 0 for j in s[i]: if j in ['a', 'e', 'i', 'o', 'u']: p += 1 if p < k: return True return False t = ["aabb", "abab", "abba", "aaaa"] for i in range(n): s = [raw_input() for x in range(4)] t1 = [] if get(s[0]) == get(s[1]) and get(s[2]) == get(s[3]): t1.append("aabb") if get(s[0]) == get(s[2]) and get(s[1]) == get(s[3]): t1.append("abab") if get(s[0]) == get(s[3]) and get(s[1]) == get(s[2]): t1.append("abba") if get(s[0]) == get(s[1]) and get(s[1]) == get(s[2]) and get(s[2]) == get(s[3]): t1.append("aaaa") if isbad(s): t1 = [] t2 = [] for i in t1: if i in t: t2.append(i) t = [x for x in t2] if t: print t[-1] else: print "NO"
PYTHON
139_C. Literature Lesson
Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes. Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels. Two lines rhyme if their suffixes that start from the k-th vowels (counting from the end) match. If a line has less than k vowels, then such line can't rhyme with any other line. For example, if k = 1, lines commit and hermit rhyme (the corresponding suffixes equal it), and if k = 2, they do not rhyme (ommit β‰  ermit). Today on a literature lesson Vera learned that quatrains can contain four different schemes of rhymes, namely the following ones (the same letters stand for rhyming lines): * Clerihew (aabb); * Alternating (abab); * Enclosed (abba). If all lines of a quatrain pairwise rhyme, then the quatrain can belong to any rhyme scheme (this situation is represented by aaaa). If all quatrains of a poem belong to the same rhyme scheme, then we can assume that the whole poem belongs to this rhyme scheme. If in each quatrain all lines pairwise rhyme, then the rhyme scheme of the poem is aaaa. Let us note that it doesn't matter whether lines from different quatrains rhyme with each other or not. In other words, it is possible that different quatrains aren't connected by a rhyme. Vera got a long poem as a home task. The girl has to analyse it and find the poem rhyme scheme. Help Vera cope with the task. Input The first line contains two integers n and k (1 ≀ n ≀ 2500, 1 ≀ k ≀ 5) β€” the number of quatrains in the poem and the vowel's number, correspondingly. Next 4n lines contain the poem. Each line is not empty and only consists of small Latin letters. The total length of the lines does not exceed 104. If we assume that the lines are numbered starting from 1, then the first quatrain contains lines number 1, 2, 3, 4; the second one contains lines number 5, 6, 7, 8; and so on. Output Print the rhyme scheme of the poem as "aabb", "abab", "abba", "aaaa"; or "NO" if the poem does not belong to any of the above mentioned schemes. Examples Input 1 1 day may sun fun Output aabb Input 1 1 day may gray way Output aaaa Input 2 1 a a a a a a e e Output aabb Input 2 1 day may sun fun test hill fest thrill Output NO Note In the last sample both quatrains have rhymes but finding the common scheme is impossible, so the answer is "NO".
2
9
def isRhyme(x, y, k): lx, ly = len(x), len(y) cnt = 0 for i, j in zip(xrange(lx - 1, -1, -1), xrange(ly - 1, -1, -1)): if x[i] != y[j]: return False if x[i] in 'aeiou': cnt += 1 if cnt == k: return True return False n, k = map(int, raw_input().split()) ans = 'aaaa' for i in xrange(n): line = [] for j in xrange(4): line.append(raw_input()) if ans == 'NO': continue r01 = isRhyme(line[0], line[1], k) r23 = isRhyme(line[2], line[3], k) r02 = isRhyme(line[0], line[2], k) r13 = isRhyme(line[1], line[3], k) r12 = isRhyme(line[1], line[2], k) r03 = isRhyme(line[0], line[3], k) if r01 and r23: tmp = 'aabb' if r12: tmp = 'aaaa' elif r02 and r13: tmp = 'abab' if r01: tmp = 'aaaa' elif r03 and r12: tmp = 'abba' if r01: tmp = 'aaaa' else: tmp = 'NO' if ans == 'aaaa': ans = tmp elif ans == tmp or tmp == 'aaaa': pass else: ans = 'NO' print ans
PYTHON
139_C. Literature Lesson
Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes. Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels. Two lines rhyme if their suffixes that start from the k-th vowels (counting from the end) match. If a line has less than k vowels, then such line can't rhyme with any other line. For example, if k = 1, lines commit and hermit rhyme (the corresponding suffixes equal it), and if k = 2, they do not rhyme (ommit β‰  ermit). Today on a literature lesson Vera learned that quatrains can contain four different schemes of rhymes, namely the following ones (the same letters stand for rhyming lines): * Clerihew (aabb); * Alternating (abab); * Enclosed (abba). If all lines of a quatrain pairwise rhyme, then the quatrain can belong to any rhyme scheme (this situation is represented by aaaa). If all quatrains of a poem belong to the same rhyme scheme, then we can assume that the whole poem belongs to this rhyme scheme. If in each quatrain all lines pairwise rhyme, then the rhyme scheme of the poem is aaaa. Let us note that it doesn't matter whether lines from different quatrains rhyme with each other or not. In other words, it is possible that different quatrains aren't connected by a rhyme. Vera got a long poem as a home task. The girl has to analyse it and find the poem rhyme scheme. Help Vera cope with the task. Input The first line contains two integers n and k (1 ≀ n ≀ 2500, 1 ≀ k ≀ 5) β€” the number of quatrains in the poem and the vowel's number, correspondingly. Next 4n lines contain the poem. Each line is not empty and only consists of small Latin letters. The total length of the lines does not exceed 104. If we assume that the lines are numbered starting from 1, then the first quatrain contains lines number 1, 2, 3, 4; the second one contains lines number 5, 6, 7, 8; and so on. Output Print the rhyme scheme of the poem as "aabb", "abab", "abba", "aaaa"; or "NO" if the poem does not belong to any of the above mentioned schemes. Examples Input 1 1 day may sun fun Output aabb Input 1 1 day may gray way Output aaaa Input 2 1 a a a a a a e e Output aabb Input 2 1 day may sun fun test hill fest thrill Output NO Note In the last sample both quatrains have rhymes but finding the common scheme is impossible, so the answer is "NO".
2
9
#include <bits/stdc++.h> #pragma comment(linker, "/STACK:268435456") using namespace std; const string IN_NAME = "input.txt"; const string OUT_NAME = "output.txt"; template <class T> T abs(T &x) { return ((x) >= 0) ? (x) : (-(x)); } template <class T> T sqr(T &x) { return (x) * (x); } template <class T> T min(T &a, T &b) { return ((a) < (b)) ? (a) : (b); } template <class T> T max(T &a, T &b) { return ((a) > (b)) ? (a) : (b); } int n, k; string s[4]; string sub[4]; const int aabb = 0, abab = 1, abba = 2, aaaa = 3; bool answer[4]; bool isVowel(char c) { return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'; } bool getVowels(int index) { int i = ((int)((s[index]).size())) - 1; int j = 0; while (i >= 0) { if (isVowel(s[index][i])) j++; if (j == k) { sub[index] = s[index].substr(i, ((int)((s[index]).size())) - i + 1); return true; } i--; } return false; } bool equal(int ind1, int ind2) { return sub[ind1] == sub[ind2]; } void getAns() { for (int i = 0; i < 4; i++) if (!getVowels(i)) { for (int j = 0; j < 4; j++) answer[j] = false; return; } if (equal(0, 1) && equal(1, 2) && equal(2, 3) && equal(3, 0)) ; else answer[aaaa] = false; if (equal(0, 1) && equal(2, 3)) ; else answer[aabb] = false; if (equal(0, 2) && equal(1, 3)) ; else answer[abab] = false; if (equal(0, 3) && equal(1, 2)) ; else answer[abba] = false; } int main() { for (int i = 0; i < 4; i++) answer[i] = true; cin >> n >> k; for (int i = 0; i < n; i++) { for (int j = 0; j < 4; j++) { cin >> s[j]; } getAns(); } if (answer[aaaa]) { cout << "aaaa"; return 0; } int cnt = 0; for (int i = 0; i <= 2; i++) if (answer[i]) cnt++; if (cnt != 1) { cout << "NO"; return 0; } if (answer[aabb]) { cout << "aabb"; return 0; } if (answer[abba]) { cout << "abba"; return 0; } if (answer[abab]) { cout << "abab"; return 0; } }
CPP
139_C. Literature Lesson
Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes. Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels. Two lines rhyme if their suffixes that start from the k-th vowels (counting from the end) match. If a line has less than k vowels, then such line can't rhyme with any other line. For example, if k = 1, lines commit and hermit rhyme (the corresponding suffixes equal it), and if k = 2, they do not rhyme (ommit β‰  ermit). Today on a literature lesson Vera learned that quatrains can contain four different schemes of rhymes, namely the following ones (the same letters stand for rhyming lines): * Clerihew (aabb); * Alternating (abab); * Enclosed (abba). If all lines of a quatrain pairwise rhyme, then the quatrain can belong to any rhyme scheme (this situation is represented by aaaa). If all quatrains of a poem belong to the same rhyme scheme, then we can assume that the whole poem belongs to this rhyme scheme. If in each quatrain all lines pairwise rhyme, then the rhyme scheme of the poem is aaaa. Let us note that it doesn't matter whether lines from different quatrains rhyme with each other or not. In other words, it is possible that different quatrains aren't connected by a rhyme. Vera got a long poem as a home task. The girl has to analyse it and find the poem rhyme scheme. Help Vera cope with the task. Input The first line contains two integers n and k (1 ≀ n ≀ 2500, 1 ≀ k ≀ 5) β€” the number of quatrains in the poem and the vowel's number, correspondingly. Next 4n lines contain the poem. Each line is not empty and only consists of small Latin letters. The total length of the lines does not exceed 104. If we assume that the lines are numbered starting from 1, then the first quatrain contains lines number 1, 2, 3, 4; the second one contains lines number 5, 6, 7, 8; and so on. Output Print the rhyme scheme of the poem as "aabb", "abab", "abba", "aaaa"; or "NO" if the poem does not belong to any of the above mentioned schemes. Examples Input 1 1 day may sun fun Output aabb Input 1 1 day may gray way Output aaaa Input 2 1 a a a a a a e e Output aabb Input 2 1 day may sun fun test hill fest thrill Output NO Note In the last sample both quatrains have rhymes but finding the common scheme is impossible, so the answer is "NO".
2
9
import java.io.BufferedReader; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Literature implements Runnable { private String solve() throws IOException { int n = in.nextInt(), k = in.nextInt(); Pattern XXX = Pattern.compile("(([aeiou][^aeiou]*){" + k + "})$"); String prev = "aaaa"; String[] lines = new String[4]; for (int i = 0; i < n; ++i) { for (int j = 0; j < 4; ++j) { Matcher m = XXX.matcher(in.nextToken()); if (!m.find()) { return "NO"; } lines[j] = m.group(1); } String cur; if (lines[0].equals(lines[1]) && lines[2].equals(lines[3])) { cur = lines[0].equals(lines[2]) ? "aaaa" : "aabb"; } else if (lines[0].equals(lines[2]) && lines[1].equals(lines[3])) { cur = "abab"; } else if (lines[0].equals(lines[3]) && lines[1].equals(lines[2])) { cur = "abba"; } else { return "NO"; } if (!cur.equals("aaaa") && !prev.equals("aaaa") && !cur.equals(prev)) { return "NO"; } if (cur != "aaaa") { prev = cur; } } return prev; } public static void main(String[] args) { new Literature().run(); } FastReader in; PrintWriter out; public void run() { try { in = new FastReader(System.in); out = new PrintWriter(System.out); out.println(solve()); out.close(); in.close(); } catch (Throwable e) { e.printStackTrace(); System.exit(1); } } private static class FastReader implements Closeable { BufferedReader reader; StringTokenizer tokenizer; private FastReader(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } @Override public void close() throws IOException { reader.close(); } } }
JAVA
139_C. Literature Lesson
Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes. Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels. Two lines rhyme if their suffixes that start from the k-th vowels (counting from the end) match. If a line has less than k vowels, then such line can't rhyme with any other line. For example, if k = 1, lines commit and hermit rhyme (the corresponding suffixes equal it), and if k = 2, they do not rhyme (ommit β‰  ermit). Today on a literature lesson Vera learned that quatrains can contain four different schemes of rhymes, namely the following ones (the same letters stand for rhyming lines): * Clerihew (aabb); * Alternating (abab); * Enclosed (abba). If all lines of a quatrain pairwise rhyme, then the quatrain can belong to any rhyme scheme (this situation is represented by aaaa). If all quatrains of a poem belong to the same rhyme scheme, then we can assume that the whole poem belongs to this rhyme scheme. If in each quatrain all lines pairwise rhyme, then the rhyme scheme of the poem is aaaa. Let us note that it doesn't matter whether lines from different quatrains rhyme with each other or not. In other words, it is possible that different quatrains aren't connected by a rhyme. Vera got a long poem as a home task. The girl has to analyse it and find the poem rhyme scheme. Help Vera cope with the task. Input The first line contains two integers n and k (1 ≀ n ≀ 2500, 1 ≀ k ≀ 5) β€” the number of quatrains in the poem and the vowel's number, correspondingly. Next 4n lines contain the poem. Each line is not empty and only consists of small Latin letters. The total length of the lines does not exceed 104. If we assume that the lines are numbered starting from 1, then the first quatrain contains lines number 1, 2, 3, 4; the second one contains lines number 5, 6, 7, 8; and so on. Output Print the rhyme scheme of the poem as "aabb", "abab", "abba", "aaaa"; or "NO" if the poem does not belong to any of the above mentioned schemes. Examples Input 1 1 day may sun fun Output aabb Input 1 1 day may gray way Output aaaa Input 2 1 a a a a a a e e Output aabb Input 2 1 day may sun fun test hill fest thrill Output NO Note In the last sample both quatrains have rhymes but finding the common scheme is impossible, so the answer is "NO".
2
9
n,k=map(int,raw_input().split()) def f(s): s=s[::-1] o=0 for i in range(len(s)): if s[i] in 'aeiou': o+=1 if o==k: return s[:i+1][::-1] print 'NO' exit() A=[] E=[] for i in range(n): B=[ raw_input() for i in range(4) ] A.append(B) for x in A: D=[] for y in x: D.append(f(y)) if D[0]==D[1]==D[2]==D[3]: E.append('aaaa') elif D[0]==D[1] and D[2]==D[3]: E.append('aabb') elif D[0]==D[2] and D[1]==D[3]: E.append('abab') elif D[0]==D[3] and D[1]==D[2]: E.append('abba') else: print 'NO' exit() r=E[0] for x in E: if x == r: continue if x=='aaaa' : continue if r=='aaaa': r=x continue print 'NO' exit() print r
PYTHON
139_C. Literature Lesson
Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes. Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels. Two lines rhyme if their suffixes that start from the k-th vowels (counting from the end) match. If a line has less than k vowels, then such line can't rhyme with any other line. For example, if k = 1, lines commit and hermit rhyme (the corresponding suffixes equal it), and if k = 2, they do not rhyme (ommit β‰  ermit). Today on a literature lesson Vera learned that quatrains can contain four different schemes of rhymes, namely the following ones (the same letters stand for rhyming lines): * Clerihew (aabb); * Alternating (abab); * Enclosed (abba). If all lines of a quatrain pairwise rhyme, then the quatrain can belong to any rhyme scheme (this situation is represented by aaaa). If all quatrains of a poem belong to the same rhyme scheme, then we can assume that the whole poem belongs to this rhyme scheme. If in each quatrain all lines pairwise rhyme, then the rhyme scheme of the poem is aaaa. Let us note that it doesn't matter whether lines from different quatrains rhyme with each other or not. In other words, it is possible that different quatrains aren't connected by a rhyme. Vera got a long poem as a home task. The girl has to analyse it and find the poem rhyme scheme. Help Vera cope with the task. Input The first line contains two integers n and k (1 ≀ n ≀ 2500, 1 ≀ k ≀ 5) β€” the number of quatrains in the poem and the vowel's number, correspondingly. Next 4n lines contain the poem. Each line is not empty and only consists of small Latin letters. The total length of the lines does not exceed 104. If we assume that the lines are numbered starting from 1, then the first quatrain contains lines number 1, 2, 3, 4; the second one contains lines number 5, 6, 7, 8; and so on. Output Print the rhyme scheme of the poem as "aabb", "abab", "abba", "aaaa"; or "NO" if the poem does not belong to any of the above mentioned schemes. Examples Input 1 1 day may sun fun Output aabb Input 1 1 day may gray way Output aaaa Input 2 1 a a a a a a e e Output aabb Input 2 1 day may sun fun test hill fest thrill Output NO Note In the last sample both quatrains have rhymes but finding the common scheme is impossible, so the answer is "NO".
2
9
n, k = map(int, raw_input().split()) t = 0 s = 'aeiou' for i in range(n): a = [] for j in range(4): a.append(raw_input()) cnt = 0 for g in range(len(a[j]) - 1, -1, -1): if a[j][g] in s: cnt += 1 if cnt == k: a[j] = a[j][g:] break if cnt < k: t = -1 tt = 0 if t == -1: break if a[0] == a[1] == a[2] == a[3]: tt = 4 elif a[0] == a[1] and a[2] == a[3]: tt = 1 elif a[0] == a[2] and a[1] == a[3]: tt = 2 elif a[0] == a[3] and a[1] == a[2]: tt = 3 else: t = -1 if t == -1: break if t == 0 or t == 4: t = tt elif tt != t and tt != 4: t = -1 if t == -1: print 'NO' if t == 1: print 'aabb' if t == 2: print 'abab' if t == 3: print 'abba' if t == 4: print 'aaaa'
PYTHON
139_C. Literature Lesson
Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes. Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels. Two lines rhyme if their suffixes that start from the k-th vowels (counting from the end) match. If a line has less than k vowels, then such line can't rhyme with any other line. For example, if k = 1, lines commit and hermit rhyme (the corresponding suffixes equal it), and if k = 2, they do not rhyme (ommit β‰  ermit). Today on a literature lesson Vera learned that quatrains can contain four different schemes of rhymes, namely the following ones (the same letters stand for rhyming lines): * Clerihew (aabb); * Alternating (abab); * Enclosed (abba). If all lines of a quatrain pairwise rhyme, then the quatrain can belong to any rhyme scheme (this situation is represented by aaaa). If all quatrains of a poem belong to the same rhyme scheme, then we can assume that the whole poem belongs to this rhyme scheme. If in each quatrain all lines pairwise rhyme, then the rhyme scheme of the poem is aaaa. Let us note that it doesn't matter whether lines from different quatrains rhyme with each other or not. In other words, it is possible that different quatrains aren't connected by a rhyme. Vera got a long poem as a home task. The girl has to analyse it and find the poem rhyme scheme. Help Vera cope with the task. Input The first line contains two integers n and k (1 ≀ n ≀ 2500, 1 ≀ k ≀ 5) β€” the number of quatrains in the poem and the vowel's number, correspondingly. Next 4n lines contain the poem. Each line is not empty and only consists of small Latin letters. The total length of the lines does not exceed 104. If we assume that the lines are numbered starting from 1, then the first quatrain contains lines number 1, 2, 3, 4; the second one contains lines number 5, 6, 7, 8; and so on. Output Print the rhyme scheme of the poem as "aabb", "abab", "abba", "aaaa"; or "NO" if the poem does not belong to any of the above mentioned schemes. Examples Input 1 1 day may sun fun Output aabb Input 1 1 day may gray way Output aaaa Input 2 1 a a a a a a e e Output aabb Input 2 1 day may sun fun test hill fest thrill Output NO Note In the last sample both quatrains have rhymes but finding the common scheme is impossible, so the answer is "NO".
2
9
import java.util.Scanner; import java.io.OutputStream; import java.io.IOException; import java.util.Arrays; import java.io.PrintWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author codeKNIGHT */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { public void solve(int testNumber, Scanner in, PrintWriter out) { int n=in.nextInt(),k=in.nextInt(),i,j,c=0; String s,s1,s2,s3,res,a[]=new String[n]; boolean status=true; for(i=0;i<n;i++) { s=in.next(); s1=in.next(); s2=in.next(); s3=in.next(); c=0; for(j=s.length()-1;j>=0;j--) { if(s.charAt(j)=='a'||s.charAt(j)=='e'||s.charAt(j)=='i'||s.charAt(j)=='o'||s.charAt(j)=='u') c++; if(c==k) break; } if(c<k) { status=false; break; } s=s.substring(j,s.length()); c=0; for(j=s1.length()-1;j>=0;j--) { if(s1.charAt(j)=='a'||s1.charAt(j)=='e'||s1.charAt(j)=='i'||s1.charAt(j)=='o'||s1.charAt(j)=='u') c++; if(c==k) break; } if(c<k) { status=false; break; } s1=s1.substring(j,s1.length()); c=0; for(j=s2.length()-1;j>=0;j--) { if(s2.charAt(j)=='a'||s2.charAt(j)=='e'||s2.charAt(j)=='i'||s2.charAt(j)=='o'||s2.charAt(j)=='u') c++; if(c==k) break; } if(c<k) { status=false; break; } s2=s2.substring(j,s2.length()); c=0; for(j=s3.length()-1;j>=0;j--) { if(s3.charAt(j)=='a'||s3.charAt(j)=='e'||s3.charAt(j)=='i'||s3.charAt(j)=='o'||s3.charAt(j)=='u') c++; if(c==k) break; } if(c<k) { status=false; break; } s3=s3.substring(j,s3.length()); //System.out.println(s+" "+s1+" "+s2+" "+s3); if(s.equals(s1)&&s.equals(s2)&&s.equals(s3)) res="aaaa"; else if(s.equals(s1)&&s2.equals(s3)) res="aabb"; else if(s.equals(s2)&&s1.equals(s3)) res="abab"; else if(s.equals(s3)&&s1.equals(s2)) res="abba"; else { status=false; break; } a[i]=res; } if(!status) out.println("NO"); else { Arrays.sort(a); res=a[n-1]; for(i=0;i<n-1;i++) { if(a[i].equals(res)||a[i].equals("aaaa")) continue; else { status=false; break; } } if(!status) out.println("NO"); else out.println(res); } } }
JAVA
139_C. Literature Lesson
Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes. Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels. Two lines rhyme if their suffixes that start from the k-th vowels (counting from the end) match. If a line has less than k vowels, then such line can't rhyme with any other line. For example, if k = 1, lines commit and hermit rhyme (the corresponding suffixes equal it), and if k = 2, they do not rhyme (ommit β‰  ermit). Today on a literature lesson Vera learned that quatrains can contain four different schemes of rhymes, namely the following ones (the same letters stand for rhyming lines): * Clerihew (aabb); * Alternating (abab); * Enclosed (abba). If all lines of a quatrain pairwise rhyme, then the quatrain can belong to any rhyme scheme (this situation is represented by aaaa). If all quatrains of a poem belong to the same rhyme scheme, then we can assume that the whole poem belongs to this rhyme scheme. If in each quatrain all lines pairwise rhyme, then the rhyme scheme of the poem is aaaa. Let us note that it doesn't matter whether lines from different quatrains rhyme with each other or not. In other words, it is possible that different quatrains aren't connected by a rhyme. Vera got a long poem as a home task. The girl has to analyse it and find the poem rhyme scheme. Help Vera cope with the task. Input The first line contains two integers n and k (1 ≀ n ≀ 2500, 1 ≀ k ≀ 5) β€” the number of quatrains in the poem and the vowel's number, correspondingly. Next 4n lines contain the poem. Each line is not empty and only consists of small Latin letters. The total length of the lines does not exceed 104. If we assume that the lines are numbered starting from 1, then the first quatrain contains lines number 1, 2, 3, 4; the second one contains lines number 5, 6, 7, 8; and so on. Output Print the rhyme scheme of the poem as "aabb", "abab", "abba", "aaaa"; or "NO" if the poem does not belong to any of the above mentioned schemes. Examples Input 1 1 day may sun fun Output aabb Input 1 1 day may gray way Output aaaa Input 2 1 a a a a a a e e Output aabb Input 2 1 day may sun fun test hill fest thrill Output NO Note In the last sample both quatrains have rhymes but finding the common scheme is impossible, so the answer is "NO".
2
9
#include <bits/stdc++.h> using namespace std; const double eps = 1e-8; const double Pi = acos(-1.0); const int INF = 0x3f3f3f3f; int num[3000]; int n, k; struct st { char str[4][10010]; } poem[2510]; bool is(char ch) { if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') return true; else return false; } void rev(int a, int b) { char tmp[10010]; memset(tmp, 0, sizeof(tmp)); strcpy(tmp, poem[a].str[b]); int len = strlen(tmp); for (int i = 0; i < len; i++) poem[a].str[b][i] = tmp[len - 1 - i]; } bool isaaaa(int num) { int cc; for (int i = 0; i < 4; i++) for (int j = i + 1; j < 4; j++) { bool flag = false; cc = 0; for (int p = 0;; p++) { if (poem[num].str[i][p] != poem[num].str[j][p]) return false; if (is(poem[num].str[i][p])) cc++; if (cc == k) { flag = true; break; } } if (flag == false) return false; } return true; } bool isaabb(int num) { bool flag = false; int cc = 0; for (int p = 0;; p++) { if (poem[num].str[0][p] != poem[num].str[1][p]) return false; if (is(poem[num].str[0][p])) cc++; if (cc == k) { flag = true; break; } } if (flag == false) return false; flag = false; cc = 0; for (int p = 0;; p++) { if (poem[num].str[2][p] != poem[num].str[3][p]) return false; if (is(poem[num].str[2][p])) cc++; if (cc == k) { flag = true; break; } } return flag; } bool isabab(int num) { bool flag = false; int cc = 0; for (int p = 0;; p++) { if (poem[num].str[0][p] != poem[num].str[2][p]) return false; if (is(poem[num].str[0][p])) cc++; if (cc == k) { flag = true; break; } } if (flag == false) return false; flag = false; cc = 0; for (int p = 0;; p++) { if (poem[num].str[1][p] != poem[num].str[3][p]) return false; if (is(poem[num].str[1][p])) cc++; if (cc == k) { flag = true; break; } } return flag; } bool isabba(int num) { bool flag = false; int cc = 0; for (int p = 0;; p++) { if (poem[num].str[0][p] != poem[num].str[3][p]) return false; if (is(poem[num].str[0][p])) cc++; if (cc == k) { flag = true; break; } } if (flag == false) return false; flag = false; cc = 0; for (int p = 0;; p++) { if (poem[num].str[2][p] != poem[num].str[1][p]) return false; if (is(poem[num].str[2][p])) cc++; if (cc == k) { flag = true; break; } } return flag; } int judge(int num) { if (isaaaa(num)) return 1; if (isaabb(num)) return 2; if (isabab(num)) return 3; if (isabba(num)) return 4; return -1; } int main() { while (cin >> n >> k) { memset(poem, 0, sizeof(poem)); memset(num, -1, sizeof(num)); bool flag = true; int type = 0; for (int i = 1; i <= n; i++) for (int j = 0; j < 4; j++) { scanf("%s", poem[i].str[j]); rev(i, j); } for (int i = 1; i <= n; i++) { num[i] = judge(i); if (num[i] == -1) { flag = false; break; } } int loc = -1; sort(num + 1, num + 1 + n); for (int i = 1; i <= n; i++) { if (num[i] == -1) { flag = false; goto next; } if (num[i] == 1) continue; else { loc = i; type = num[i]; break; } } if (loc == -1) { type = 1; goto next; } for (int i = loc + 1; i <= n; i++) if (type != num[i]) { flag = false; break; } next: if (!flag) printf("NO\n"); else { if (type == 1) printf("aaaa\n"); if (type == 2) printf("aabb\n"); if (type == 3) printf("abab\n"); if (type == 4) printf("abba\n"); } } return 0; }
CPP
139_C. Literature Lesson
Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes. Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels. Two lines rhyme if their suffixes that start from the k-th vowels (counting from the end) match. If a line has less than k vowels, then such line can't rhyme with any other line. For example, if k = 1, lines commit and hermit rhyme (the corresponding suffixes equal it), and if k = 2, they do not rhyme (ommit β‰  ermit). Today on a literature lesson Vera learned that quatrains can contain four different schemes of rhymes, namely the following ones (the same letters stand for rhyming lines): * Clerihew (aabb); * Alternating (abab); * Enclosed (abba). If all lines of a quatrain pairwise rhyme, then the quatrain can belong to any rhyme scheme (this situation is represented by aaaa). If all quatrains of a poem belong to the same rhyme scheme, then we can assume that the whole poem belongs to this rhyme scheme. If in each quatrain all lines pairwise rhyme, then the rhyme scheme of the poem is aaaa. Let us note that it doesn't matter whether lines from different quatrains rhyme with each other or not. In other words, it is possible that different quatrains aren't connected by a rhyme. Vera got a long poem as a home task. The girl has to analyse it and find the poem rhyme scheme. Help Vera cope with the task. Input The first line contains two integers n and k (1 ≀ n ≀ 2500, 1 ≀ k ≀ 5) β€” the number of quatrains in the poem and the vowel's number, correspondingly. Next 4n lines contain the poem. Each line is not empty and only consists of small Latin letters. The total length of the lines does not exceed 104. If we assume that the lines are numbered starting from 1, then the first quatrain contains lines number 1, 2, 3, 4; the second one contains lines number 5, 6, 7, 8; and so on. Output Print the rhyme scheme of the poem as "aabb", "abab", "abba", "aaaa"; or "NO" if the poem does not belong to any of the above mentioned schemes. Examples Input 1 1 day may sun fun Output aabb Input 1 1 day may gray way Output aaaa Input 2 1 a a a a a a e e Output aabb Input 2 1 day may sun fun test hill fest thrill Output NO Note In the last sample both quatrains have rhymes but finding the common scheme is impossible, so the answer is "NO".
2
9
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; public class ProblemC { public static boolean[] vowel = new boolean[512]; public static String Kth(String line, int k) { int len = line.length(); for (int i = len-1 ; i >= 0 ; i--) { if (vowel[line.charAt(i)]) { k--; if (k == 0) { return line.substring(i); } } } return ""; } public static void main(String[] args) throws IOException { vowel['a'] = true; vowel['i'] = true; vowel['u'] = true; vowel['e'] = true; vowel['o'] = true; BufferedReader s = new BufferedReader(new InputStreamReader(System.in)); String[] data = s.readLine().split(" "); int n = Integer.valueOf(data[0]); int K = Integer.valueOf(data[1]); boolean[] scheme = new boolean[3]; for (int i = 0 ; i < 3 ; i++) { scheme[i] = true; } for (int i = 0 ; i < n ; i++) { String[] kthv = new String[4]; for (int j = 0 ; j < 4 ; j++) { kthv[j] = Kth(s.readLine(), K); if (kthv[j].length() == 0) { kthv[j] += (char)('0' + j); } } if (kthv[0].equals(kthv[1]) && kthv[2].equals(kthv[3])) { } else { scheme[0] = false; } if (kthv[0].equals(kthv[2]) && kthv[1].equals(kthv[3])) { } else { scheme[1] = false; } if (kthv[0].equals(kthv[3]) && kthv[1].equals(kthv[2])) { } else { scheme[2] = false; } } if (scheme[0] && scheme[1] && scheme[2]) { System.out.println("aaaa"); return; } if (scheme[0]) { System.out.println("aabb"); return; } if (scheme[1]) { System.out.println("abab"); return; } if (scheme[2]) { System.out.println("abba"); return; } System.out.println("NO"); } }
JAVA
139_C. Literature Lesson
Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes. Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels. Two lines rhyme if their suffixes that start from the k-th vowels (counting from the end) match. If a line has less than k vowels, then such line can't rhyme with any other line. For example, if k = 1, lines commit and hermit rhyme (the corresponding suffixes equal it), and if k = 2, they do not rhyme (ommit β‰  ermit). Today on a literature lesson Vera learned that quatrains can contain four different schemes of rhymes, namely the following ones (the same letters stand for rhyming lines): * Clerihew (aabb); * Alternating (abab); * Enclosed (abba). If all lines of a quatrain pairwise rhyme, then the quatrain can belong to any rhyme scheme (this situation is represented by aaaa). If all quatrains of a poem belong to the same rhyme scheme, then we can assume that the whole poem belongs to this rhyme scheme. If in each quatrain all lines pairwise rhyme, then the rhyme scheme of the poem is aaaa. Let us note that it doesn't matter whether lines from different quatrains rhyme with each other or not. In other words, it is possible that different quatrains aren't connected by a rhyme. Vera got a long poem as a home task. The girl has to analyse it and find the poem rhyme scheme. Help Vera cope with the task. Input The first line contains two integers n and k (1 ≀ n ≀ 2500, 1 ≀ k ≀ 5) β€” the number of quatrains in the poem and the vowel's number, correspondingly. Next 4n lines contain the poem. Each line is not empty and only consists of small Latin letters. The total length of the lines does not exceed 104. If we assume that the lines are numbered starting from 1, then the first quatrain contains lines number 1, 2, 3, 4; the second one contains lines number 5, 6, 7, 8; and so on. Output Print the rhyme scheme of the poem as "aabb", "abab", "abba", "aaaa"; or "NO" if the poem does not belong to any of the above mentioned schemes. Examples Input 1 1 day may sun fun Output aabb Input 1 1 day may gray way Output aaaa Input 2 1 a a a a a a e e Output aabb Input 2 1 day may sun fun test hill fest thrill Output NO Note In the last sample both quatrains have rhymes but finding the common scheme is impossible, so the answer is "NO".
2
9
#include <bits/stdc++.h> int IntMaxVal = (int)1e20; int IntMinVal = (int)-1e20; long long LongMaxVal = (long long)1e20; long long LongMinVal = (long long)-1e20; using namespace std; template <typename T> struct argument_type; template <typename T, typename U> struct argument_type<T(U)> {}; template <typename T1, typename T2> istream& operator>>(istream& is, pair<T1, T2>& s) { is >> s.first >> s.second; return is; } int main() { srand(time(NULL)); ios_base::sync_with_stdio(false); cin.tie(NULL); int n; cin >> n; ; int k; cin >> k; ; vector<string> strs; for (int i = 0; i < 4 * n; ++i) { string s; cin >> s; ; int met = 0; for (int i = s.length() - 1; i >= 0; --i) if (s[i] == 'a' || s[i] == 'e' || s[i] == 'o' || s[i] == 'i' || s[i] == 'u') { met++; if (met == k) { strs.push_back(s.substr(i)); break; } } if (met < k) { cout << "NO"; return 0; } } vector<int> rhymes; for (int i = 0; i < n; ++i) { string s1 = strs[4 * i + 0]; string s2 = strs[4 * i + 1]; string s3 = strs[4 * i + 2]; string s4 = strs[4 * i + 3]; int rt = 0; if (s1 == s2 && s2 == s3 && s3 == s4) rt = 7; else if (s1 == s2 && s3 == s4) rt = 1; else if (s1 == s3 && s2 == s4) rt = 2; else if (s1 == s4 && s2 == s3) rt = 4; rhymes.push_back(rt); } int res = rhymes.front(); for (auto x : rhymes) res = res & x; if (res == 0) cout << "NO"; else if (res == 7) cout << "aaaa"; else if (res == 1) cout << "aabb"; else if (res == 2) cout << "abab"; else cout << "abba"; }
CPP
139_C. Literature Lesson
Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes. Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels. Two lines rhyme if their suffixes that start from the k-th vowels (counting from the end) match. If a line has less than k vowels, then such line can't rhyme with any other line. For example, if k = 1, lines commit and hermit rhyme (the corresponding suffixes equal it), and if k = 2, they do not rhyme (ommit β‰  ermit). Today on a literature lesson Vera learned that quatrains can contain four different schemes of rhymes, namely the following ones (the same letters stand for rhyming lines): * Clerihew (aabb); * Alternating (abab); * Enclosed (abba). If all lines of a quatrain pairwise rhyme, then the quatrain can belong to any rhyme scheme (this situation is represented by aaaa). If all quatrains of a poem belong to the same rhyme scheme, then we can assume that the whole poem belongs to this rhyme scheme. If in each quatrain all lines pairwise rhyme, then the rhyme scheme of the poem is aaaa. Let us note that it doesn't matter whether lines from different quatrains rhyme with each other or not. In other words, it is possible that different quatrains aren't connected by a rhyme. Vera got a long poem as a home task. The girl has to analyse it and find the poem rhyme scheme. Help Vera cope with the task. Input The first line contains two integers n and k (1 ≀ n ≀ 2500, 1 ≀ k ≀ 5) β€” the number of quatrains in the poem and the vowel's number, correspondingly. Next 4n lines contain the poem. Each line is not empty and only consists of small Latin letters. The total length of the lines does not exceed 104. If we assume that the lines are numbered starting from 1, then the first quatrain contains lines number 1, 2, 3, 4; the second one contains lines number 5, 6, 7, 8; and so on. Output Print the rhyme scheme of the poem as "aabb", "abab", "abba", "aaaa"; or "NO" if the poem does not belong to any of the above mentioned schemes. Examples Input 1 1 day may sun fun Output aabb Input 1 1 day may gray way Output aaaa Input 2 1 a a a a a a e e Output aabb Input 2 1 day may sun fun test hill fest thrill Output NO Note In the last sample both quatrains have rhymes but finding the common scheme is impossible, so the answer is "NO".
2
9
#include <bits/stdc++.h> using namespace std; const char letters[] = {'a', 'e', 'i', 'o', 'u'}; const char res[][5] = {"aabb", "abab", "abba", "aaaa"}; const int MAXN = 2510; const int MAXM = 10010; int n, k; char s[4][MAXM]; inline int ISV(char c) { for (int i = 0; i < 5; ++i) if (c == letters[i]) return 1; return 0; } int checkSame(char sa[], char sb[]) { int la = strlen(sa) - 1, lb = strlen(sb) - 1; int ra = k, rb = k; while (0 <= la && 0 <= lb && ra && rb) { if (sa[la] != sb[lb]) return 0; if (ISV(sa[la])) --ra; if (ISV(sb[lb])) --rb; --la; --lb; } if (ra == 0 && rb == 0) return 1; return 0; } int checkType() { int same[4][4]; for (int i = 0; i < 4; ++i) for (int j = i + 1; j < 4; ++j) same[i][j] = checkSame(s[i], s[j]); if (same[0][1] && same[0][2] && same[0][3]) return 3; if (same[0][1] && same[2][3]) return 0; if (same[0][2] && same[1][3]) return 1; if (same[0][3] && same[1][2]) return 2; return -1; } void solve() { int type = 3, cur_type; for (int i = 0; i < n; ++i) { for (int j = 0; j < 4; ++j) scanf("%s", s[j]); cur_type = checkType(); if (cur_type == -1 || (cur_type != 3 && type != 3 && type != cur_type)) { puts("NO"); return; } if (cur_type != 3) type = cur_type; } puts(res[type]); } int main() { scanf("%d%d", &n, &k); solve(); return 0; }
CPP
139_C. Literature Lesson
Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes. Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels. Two lines rhyme if their suffixes that start from the k-th vowels (counting from the end) match. If a line has less than k vowels, then such line can't rhyme with any other line. For example, if k = 1, lines commit and hermit rhyme (the corresponding suffixes equal it), and if k = 2, they do not rhyme (ommit β‰  ermit). Today on a literature lesson Vera learned that quatrains can contain four different schemes of rhymes, namely the following ones (the same letters stand for rhyming lines): * Clerihew (aabb); * Alternating (abab); * Enclosed (abba). If all lines of a quatrain pairwise rhyme, then the quatrain can belong to any rhyme scheme (this situation is represented by aaaa). If all quatrains of a poem belong to the same rhyme scheme, then we can assume that the whole poem belongs to this rhyme scheme. If in each quatrain all lines pairwise rhyme, then the rhyme scheme of the poem is aaaa. Let us note that it doesn't matter whether lines from different quatrains rhyme with each other or not. In other words, it is possible that different quatrains aren't connected by a rhyme. Vera got a long poem as a home task. The girl has to analyse it and find the poem rhyme scheme. Help Vera cope with the task. Input The first line contains two integers n and k (1 ≀ n ≀ 2500, 1 ≀ k ≀ 5) β€” the number of quatrains in the poem and the vowel's number, correspondingly. Next 4n lines contain the poem. Each line is not empty and only consists of small Latin letters. The total length of the lines does not exceed 104. If we assume that the lines are numbered starting from 1, then the first quatrain contains lines number 1, 2, 3, 4; the second one contains lines number 5, 6, 7, 8; and so on. Output Print the rhyme scheme of the poem as "aabb", "abab", "abba", "aaaa"; or "NO" if the poem does not belong to any of the above mentioned schemes. Examples Input 1 1 day may sun fun Output aabb Input 1 1 day may gray way Output aaaa Input 2 1 a a a a a a e e Output aabb Input 2 1 day may sun fun test hill fest thrill Output NO Note In the last sample both quatrains have rhymes but finding the common scheme is impossible, so the answer is "NO".
2
9
#!/usr/bin/env python """(c) gorlum0 [at] gmail.com""" import itertools as it from sys import stdin vowels = 'aeiou' types_rhymes = 'NO abba abab # aabb # # aaaa'.split() def suffix(k, w): for i in xrange(len(w)-1, -1, -1): if w[i] in vowels: k -= 1 if not k: break return w[i:] if not k else '' def rhyme(k, w1, w2, w3, w4): s1 = suffix(k, w1) s2 = suffix(k, w2) s3 = suffix(k, w3) s4 = suffix(k, w4) ## print s1, s2, s3, s4 if not (s1 and s2 and s3 and s4): return 0 if s1 == s2 == s3 == s4: return 7 # 111, aaaa elif s1 == s2 and s3 == s4: return 4 # 100, aabb elif s1 == s3 and s2 == s4: return 2 # 010, abab elif s1 == s4 and s2 == s3: return 1 # 001, abba else: return 0 def solve(n, k, ws): res = rhyme(k, *ws[:4]) for i in xrange(4, n*4, 4): res &= rhyme(k, *ws[i:i+4]) return types_rhymes[res] def main(): for l in stdin: n, k = map(int, l.split()) ws = [next(stdin).strip() for _ in xrange(n*4)] ## print ws print solve(n, k, ws) if __name__ == '__main__': main()
PYTHON
139_C. Literature Lesson
Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes. Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels. Two lines rhyme if their suffixes that start from the k-th vowels (counting from the end) match. If a line has less than k vowels, then such line can't rhyme with any other line. For example, if k = 1, lines commit and hermit rhyme (the corresponding suffixes equal it), and if k = 2, they do not rhyme (ommit β‰  ermit). Today on a literature lesson Vera learned that quatrains can contain four different schemes of rhymes, namely the following ones (the same letters stand for rhyming lines): * Clerihew (aabb); * Alternating (abab); * Enclosed (abba). If all lines of a quatrain pairwise rhyme, then the quatrain can belong to any rhyme scheme (this situation is represented by aaaa). If all quatrains of a poem belong to the same rhyme scheme, then we can assume that the whole poem belongs to this rhyme scheme. If in each quatrain all lines pairwise rhyme, then the rhyme scheme of the poem is aaaa. Let us note that it doesn't matter whether lines from different quatrains rhyme with each other or not. In other words, it is possible that different quatrains aren't connected by a rhyme. Vera got a long poem as a home task. The girl has to analyse it and find the poem rhyme scheme. Help Vera cope with the task. Input The first line contains two integers n and k (1 ≀ n ≀ 2500, 1 ≀ k ≀ 5) β€” the number of quatrains in the poem and the vowel's number, correspondingly. Next 4n lines contain the poem. Each line is not empty and only consists of small Latin letters. The total length of the lines does not exceed 104. If we assume that the lines are numbered starting from 1, then the first quatrain contains lines number 1, 2, 3, 4; the second one contains lines number 5, 6, 7, 8; and so on. Output Print the rhyme scheme of the poem as "aabb", "abab", "abba", "aaaa"; or "NO" if the poem does not belong to any of the above mentioned schemes. Examples Input 1 1 day may sun fun Output aabb Input 1 1 day may gray way Output aaaa Input 2 1 a a a a a a e e Output aabb Input 2 1 day may sun fun test hill fest thrill Output NO Note In the last sample both quatrains have rhymes but finding the common scheme is impossible, so the answer is "NO".
2
9
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.*; public class C { BufferedReader in; PrintStream out; StringTokenizer tok; public C() throws NumberFormatException, IOException { in = new BufferedReader(new InputStreamReader(System.in)); //in = new BufferedReader(new FileReader("in.txt")); out = System.out; run(); } boolean isVowel(char c) { return (c=='a'||c=='e'||c=='i'||c=='o'||c=='u'); } String rim(String s, int k) { int c = 0; int i; for(i = s.length()-1; i>=0 && c<k; i--) { if(isVowel(s.charAt(i))) c++; if(c==k)break; } if(c<k) return ""; return s.substring(i,s.length()); } int type(String[] s) { for(int i = 0; i < 4;i++) if(s[i].length()==0)return-1; if(s[0].compareTo(s[1])==0&& s[1].compareTo(s[2])==0&& s[2].compareTo(s[3])==0)return 0; if(s[0].compareTo(s[1])==0&& s[2].compareTo(s[3])==0)return 2; if(s[0].compareTo(s[2])==0&&s[1].compareTo(s[3])==0)return 1; if(s[0].compareTo(s[3])==0&&s[1].compareTo(s[2])==0)return 3; return -1; } String st(int i) { if(i==0) return "aaaa"; if(i==1) return "abab"; if(i==2) return "aabb"; if(i==3) return "abba"; return ""; } void run() throws NumberFormatException, IOException { int n = nextInt(); int k = nextInt(); int[] r = new int[4]; //0->aaaa //1->abab //2->aabb //3->abba for(int i = 0; i < n; i++) { String[] rimas = new String[4]; for(int j = 0; j < 4; j++) rimas[j] =rim(nextToken(),k); int t = type(rimas); if(t!= -1)r[t]++; if(t==0)for(int j = 1; j < 4; j++) r[j]++; } for(int i = 0; i < 4; i++) if(r[i]==n) { out.println(st(i)); return; } out.println("NO"); } public static void main(String[] args) throws NumberFormatException, IOException { new C(); } String nextToken() throws IOException { if(tok ==null || !tok.hasMoreTokens()) tok = new StringTokenizer(in.readLine()); return tok.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextToken()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(nextToken()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextToken()); } }
JAVA
139_C. Literature Lesson
Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes. Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels. Two lines rhyme if their suffixes that start from the k-th vowels (counting from the end) match. If a line has less than k vowels, then such line can't rhyme with any other line. For example, if k = 1, lines commit and hermit rhyme (the corresponding suffixes equal it), and if k = 2, they do not rhyme (ommit β‰  ermit). Today on a literature lesson Vera learned that quatrains can contain four different schemes of rhymes, namely the following ones (the same letters stand for rhyming lines): * Clerihew (aabb); * Alternating (abab); * Enclosed (abba). If all lines of a quatrain pairwise rhyme, then the quatrain can belong to any rhyme scheme (this situation is represented by aaaa). If all quatrains of a poem belong to the same rhyme scheme, then we can assume that the whole poem belongs to this rhyme scheme. If in each quatrain all lines pairwise rhyme, then the rhyme scheme of the poem is aaaa. Let us note that it doesn't matter whether lines from different quatrains rhyme with each other or not. In other words, it is possible that different quatrains aren't connected by a rhyme. Vera got a long poem as a home task. The girl has to analyse it and find the poem rhyme scheme. Help Vera cope with the task. Input The first line contains two integers n and k (1 ≀ n ≀ 2500, 1 ≀ k ≀ 5) β€” the number of quatrains in the poem and the vowel's number, correspondingly. Next 4n lines contain the poem. Each line is not empty and only consists of small Latin letters. The total length of the lines does not exceed 104. If we assume that the lines are numbered starting from 1, then the first quatrain contains lines number 1, 2, 3, 4; the second one contains lines number 5, 6, 7, 8; and so on. Output Print the rhyme scheme of the poem as "aabb", "abab", "abba", "aaaa"; or "NO" if the poem does not belong to any of the above mentioned schemes. Examples Input 1 1 day may sun fun Output aabb Input 1 1 day may gray way Output aaaa Input 2 1 a a a a a a e e Output aabb Input 2 1 day may sun fun test hill fest thrill Output NO Note In the last sample both quatrains have rhymes but finding the common scheme is impossible, so the answer is "NO".
2
9
#!/usr/bin/python line = raw_input().strip().split() num_quar = int(line[0]) k = int(line[1]) poem = [] scheme = "aaaa" vowels = "aeiou" for i in range(num_quar): end = [] for j in range(4): line = raw_input().strip() poem = line[::-1] temp = 0 id = 0 for char in poem: id+=1 if char in vowels: temp += 1 if(temp == k): break; if(temp<k): print "NO" exit(0) poem = poem[:id] end.append(poem[::-1]) if((end[0] == end[1]) and (end[2] == end[3])): current_scheme = "aabb" elif((end[0] == end[2]) and (end[1] == end[3])): current_scheme = "abab" elif((end[0] == end[3]) and (end[1] == end[2])): current_scheme = "abba" else: print "NO"; exit(0) end = list(set(end)) if(len(end) > 2): print "NO" exit(0) if (len(end) == 1) or (scheme == current_scheme): #scheme remains as it is pass elif(scheme == "aaaa"): scheme = current_scheme else: print "NO" exit(0) print scheme
PYTHON
139_C. Literature Lesson
Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes. Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels. Two lines rhyme if their suffixes that start from the k-th vowels (counting from the end) match. If a line has less than k vowels, then such line can't rhyme with any other line. For example, if k = 1, lines commit and hermit rhyme (the corresponding suffixes equal it), and if k = 2, they do not rhyme (ommit β‰  ermit). Today on a literature lesson Vera learned that quatrains can contain four different schemes of rhymes, namely the following ones (the same letters stand for rhyming lines): * Clerihew (aabb); * Alternating (abab); * Enclosed (abba). If all lines of a quatrain pairwise rhyme, then the quatrain can belong to any rhyme scheme (this situation is represented by aaaa). If all quatrains of a poem belong to the same rhyme scheme, then we can assume that the whole poem belongs to this rhyme scheme. If in each quatrain all lines pairwise rhyme, then the rhyme scheme of the poem is aaaa. Let us note that it doesn't matter whether lines from different quatrains rhyme with each other or not. In other words, it is possible that different quatrains aren't connected by a rhyme. Vera got a long poem as a home task. The girl has to analyse it and find the poem rhyme scheme. Help Vera cope with the task. Input The first line contains two integers n and k (1 ≀ n ≀ 2500, 1 ≀ k ≀ 5) β€” the number of quatrains in the poem and the vowel's number, correspondingly. Next 4n lines contain the poem. Each line is not empty and only consists of small Latin letters. The total length of the lines does not exceed 104. If we assume that the lines are numbered starting from 1, then the first quatrain contains lines number 1, 2, 3, 4; the second one contains lines number 5, 6, 7, 8; and so on. Output Print the rhyme scheme of the poem as "aabb", "abab", "abba", "aaaa"; or "NO" if the poem does not belong to any of the above mentioned schemes. Examples Input 1 1 day may sun fun Output aabb Input 1 1 day may gray way Output aaaa Input 2 1 a a a a a a e e Output aabb Input 2 1 day may sun fun test hill fest thrill Output NO Note In the last sample both quatrains have rhymes but finding the common scheme is impossible, so the answer is "NO".
2
9
#include <bits/stdc++.h> using namespace std; long long vow(char c) { if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') { return 1; } else return 0; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); long long n, k, j, i; set<string> s; string def1 = "!#1", def2 = "!#2", def3 = "!#3", def4 = "!#4"; cin >> n >> k; while (n--) { vector<string> arr(4); vector<string> fin(4); for (i = 0; i < 4; i++) { cin >> arr[i]; long long cnt = 0, flag = 0, ind; for (j = (long long)arr[i].size() - 1; j >= 0; j--) { if (vow(arr[i][j])) { cnt++; } if (cnt == k) { flag = 1; ind = j; break; } } if (flag) { for (j = ind; j < arr[i].size(); j++) fin[i].push_back(arr[i][j]); } else { if (i == 0) fin[i] = def1; else if (i == 1) fin[i] = def2; else if (i == 2) fin[i] = def3; else fin[i] = def4; } } if (fin[0] == fin[1] && fin[1] == fin[2] && fin[0] == fin[3]) s.insert("aaaa"); else if (fin[0] == fin[1] && fin[3] == fin[2]) s.insert("aabb"); else if (fin[0] == fin[3] && fin[1] == fin[2]) s.insert("abba"); else if (fin[0] == fin[2] && fin[1] == fin[3]) s.insert("abab"); else s.insert("NO"); } set<string>::iterator it; map<string, long long> mp; for (it = s.begin(); it != s.end(); it++) { mp[*it] = 1; } string ans; if (mp["NO"]) ans = "NO"; else if (mp["aaaa"] && !mp["aabb"] && !mp["abab"] && !mp["abba"]) ans = "aaaa"; else if (mp["aabb"] && !mp["abab"] && !mp["abba"]) ans = "aabb"; else if (!mp["aabb"] && mp["abab"] && !mp["abba"]) ans = "abab"; else if (!mp["aabb"] && !mp["abab"] && mp["abba"]) ans = "abba"; else ans = "NO"; cout << ans << "\n"; return 0; }
CPP
139_C. Literature Lesson
Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes. Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels. Two lines rhyme if their suffixes that start from the k-th vowels (counting from the end) match. If a line has less than k vowels, then such line can't rhyme with any other line. For example, if k = 1, lines commit and hermit rhyme (the corresponding suffixes equal it), and if k = 2, they do not rhyme (ommit β‰  ermit). Today on a literature lesson Vera learned that quatrains can contain four different schemes of rhymes, namely the following ones (the same letters stand for rhyming lines): * Clerihew (aabb); * Alternating (abab); * Enclosed (abba). If all lines of a quatrain pairwise rhyme, then the quatrain can belong to any rhyme scheme (this situation is represented by aaaa). If all quatrains of a poem belong to the same rhyme scheme, then we can assume that the whole poem belongs to this rhyme scheme. If in each quatrain all lines pairwise rhyme, then the rhyme scheme of the poem is aaaa. Let us note that it doesn't matter whether lines from different quatrains rhyme with each other or not. In other words, it is possible that different quatrains aren't connected by a rhyme. Vera got a long poem as a home task. The girl has to analyse it and find the poem rhyme scheme. Help Vera cope with the task. Input The first line contains two integers n and k (1 ≀ n ≀ 2500, 1 ≀ k ≀ 5) β€” the number of quatrains in the poem and the vowel's number, correspondingly. Next 4n lines contain the poem. Each line is not empty and only consists of small Latin letters. The total length of the lines does not exceed 104. If we assume that the lines are numbered starting from 1, then the first quatrain contains lines number 1, 2, 3, 4; the second one contains lines number 5, 6, 7, 8; and so on. Output Print the rhyme scheme of the poem as "aabb", "abab", "abba", "aaaa"; or "NO" if the poem does not belong to any of the above mentioned schemes. Examples Input 1 1 day may sun fun Output aabb Input 1 1 day may gray way Output aaaa Input 2 1 a a a a a a e e Output aabb Input 2 1 day may sun fun test hill fest thrill Output NO Note In the last sample both quatrains have rhymes but finding the common scheme is impossible, so the answer is "NO".
2
9
#include <bits/stdc++.h> using namespace std; const string none = "george.ioanisyan.1996"; int n, k; string first, second, third, fourth; bool vowel(char ch) { return (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u'); } string getKstring(string str) { int i, qi = 0; for (i = str.size() - 1; i >= 0; --i) { qi += vowel(str[i]); if (qi == k) break; } if (qi != k) return none; else return str.substr(i); } string l1, l2, l3, l4; int check() { l1 = getKstring(first); l2 = getKstring(second); l3 = getKstring(third); l4 = getKstring(fourth); if (l1 == none || l2 == none || l3 == none || l4 == none) return -1; else { if (l1 == l2 && l2 == l3 && l3 == l4) return 4; if (l1 == l2 && l3 == l4) return 1; if (l1 == l3 && l2 == l4) return 2; if (l1 == l4 && l2 == l3) return 3; return -1; } } int main() { int i, j, a4 = 0; cin >> n >> k; int myMas[10]; for (i = 0; i < 10; ++i) myMas[i] = 0; for (i = 1; i <= n; ++i) { cin >> first >> second >> third >> fourth; j = check(); if (j == -1) { cout << "NO" << endl; return 0; } else { myMas[j] = 1; } } if (myMas[1] + myMas[2] + myMas[3] == 0) { if (myMas[4] == 1) cout << "aaaa" << endl; else cout << "NO" << endl; return 0; } if (myMas[1] + myMas[2] + myMas[3] == 1) { if (myMas[1] == 1) cout << "aabb" << endl; if (myMas[2] == 1) cout << "abab" << endl; if (myMas[3] == 1) cout << "abba" << endl; return 0; } if (myMas[1] + myMas[2] + myMas[3] > 1) { cout << "NO" << endl; return 0; } return 0; }
CPP
139_C. Literature Lesson
Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes. Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels. Two lines rhyme if their suffixes that start from the k-th vowels (counting from the end) match. If a line has less than k vowels, then such line can't rhyme with any other line. For example, if k = 1, lines commit and hermit rhyme (the corresponding suffixes equal it), and if k = 2, they do not rhyme (ommit β‰  ermit). Today on a literature lesson Vera learned that quatrains can contain four different schemes of rhymes, namely the following ones (the same letters stand for rhyming lines): * Clerihew (aabb); * Alternating (abab); * Enclosed (abba). If all lines of a quatrain pairwise rhyme, then the quatrain can belong to any rhyme scheme (this situation is represented by aaaa). If all quatrains of a poem belong to the same rhyme scheme, then we can assume that the whole poem belongs to this rhyme scheme. If in each quatrain all lines pairwise rhyme, then the rhyme scheme of the poem is aaaa. Let us note that it doesn't matter whether lines from different quatrains rhyme with each other or not. In other words, it is possible that different quatrains aren't connected by a rhyme. Vera got a long poem as a home task. The girl has to analyse it and find the poem rhyme scheme. Help Vera cope with the task. Input The first line contains two integers n and k (1 ≀ n ≀ 2500, 1 ≀ k ≀ 5) β€” the number of quatrains in the poem and the vowel's number, correspondingly. Next 4n lines contain the poem. Each line is not empty and only consists of small Latin letters. The total length of the lines does not exceed 104. If we assume that the lines are numbered starting from 1, then the first quatrain contains lines number 1, 2, 3, 4; the second one contains lines number 5, 6, 7, 8; and so on. Output Print the rhyme scheme of the poem as "aabb", "abab", "abba", "aaaa"; or "NO" if the poem does not belong to any of the above mentioned schemes. Examples Input 1 1 day may sun fun Output aabb Input 1 1 day may gray way Output aaaa Input 2 1 a a a a a a e e Output aabb Input 2 1 day may sun fun test hill fest thrill Output NO Note In the last sample both quatrains have rhymes but finding the common scheme is impossible, so the answer is "NO".
2
9
#include <bits/stdc++.h> int diru[] = {-1, -1, -1, 0, 0, 1, 1, 1}; int dirv[] = {-1, 0, 1, -1, 1, -1, 0, 1}; using namespace std; template <class T> T sq(T n) { return n * n; } template <class T> T gcd(T a, T b) { return (b != 0 ? gcd<T>(b, a % b) : a); } template <class T> T lcm(T a, T b) { return (a / gcd<T>(a, b) * b); } template <class T> bool inside(T a, T b, T c) { return a <= b && b <= c; } template <class T> void setmax(T &a, T b) { if (a < b) a = b; } template <class T> void setmin(T &a, T b) { if (b < a) a = b; } template <class T> T power(T N, T P) { return (P == 0) ? 1 : N * power(N, P - 1); } int k, l; string in[4 * 2510]; bool rime[4 * 2510][10]; bool isrime(int i, int j) { int la = ((int)in[i].size()), cnt = k; while (1) { la--; if (la < 0) return 0; if (in[i][la] == 'a' || in[i][la] == 'e' || in[i][la] == 'i' || in[i][la] == 'o' || in[i][la] == 'u') cnt--; if (cnt == 0) break; } int lb = ((int)in[j].size()); cnt = k; while (1) { lb--; if (lb < 0) return 0; if (in[j][lb] == 'a' || in[j][lb] == 'e' || in[j][lb] == 'i' || in[j][lb] == 'o' || in[j][lb] == 'u') cnt--; if (cnt == 0) break; } for (; la < ((int)in[i].size()) && lb < ((int)in[j].size()); la++, lb++) { if (in[i][la] != in[j][lb]) return 0; } if (la == ((int)in[i].size()) && lb == ((int)in[j].size())) return 1; return 0; } bool chkk(int r) { int i; for (i = 0; i < l; i++) { if (rime[i][r] == 0) return 0; } return 1; } char tmp[100010]; int main() { int n, T, t = 1, m, i, j; while (scanf("%d", &n) == 1) { scanf("%d", &k); n *= 4; for (i = 0; i < n; i++) { scanf("%s", tmp); in[i] = tmp; } memset(rime, 0, sizeof(rime)); l = 0; for (i = 0; i < n; i++) { if (isrime(i, i + 1) && isrime(i + 2, i + 3)) rime[l][0] = 1; if (isrime(i, i + 2) && isrime(i + 1, i + 3)) rime[l][1] = 1; if (isrime(i, i + 3) && isrime(i + 1, i + 2)) rime[l][2] = 1; if (rime[l][0] && rime[l][1] && rime[l][2]) rime[l][3] = 1; i += 3; l++; } if (chkk(3)) puts("aaaa"); else if (chkk(0)) puts("aabb"); else if (chkk(1)) puts("abab"); else if (chkk(2)) puts("abba"); else puts("NO"); } return 0; }
CPP
139_C. Literature Lesson
Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes. Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels. Two lines rhyme if their suffixes that start from the k-th vowels (counting from the end) match. If a line has less than k vowels, then such line can't rhyme with any other line. For example, if k = 1, lines commit and hermit rhyme (the corresponding suffixes equal it), and if k = 2, they do not rhyme (ommit β‰  ermit). Today on a literature lesson Vera learned that quatrains can contain four different schemes of rhymes, namely the following ones (the same letters stand for rhyming lines): * Clerihew (aabb); * Alternating (abab); * Enclosed (abba). If all lines of a quatrain pairwise rhyme, then the quatrain can belong to any rhyme scheme (this situation is represented by aaaa). If all quatrains of a poem belong to the same rhyme scheme, then we can assume that the whole poem belongs to this rhyme scheme. If in each quatrain all lines pairwise rhyme, then the rhyme scheme of the poem is aaaa. Let us note that it doesn't matter whether lines from different quatrains rhyme with each other or not. In other words, it is possible that different quatrains aren't connected by a rhyme. Vera got a long poem as a home task. The girl has to analyse it and find the poem rhyme scheme. Help Vera cope with the task. Input The first line contains two integers n and k (1 ≀ n ≀ 2500, 1 ≀ k ≀ 5) β€” the number of quatrains in the poem and the vowel's number, correspondingly. Next 4n lines contain the poem. Each line is not empty and only consists of small Latin letters. The total length of the lines does not exceed 104. If we assume that the lines are numbered starting from 1, then the first quatrain contains lines number 1, 2, 3, 4; the second one contains lines number 5, 6, 7, 8; and so on. Output Print the rhyme scheme of the poem as "aabb", "abab", "abba", "aaaa"; or "NO" if the poem does not belong to any of the above mentioned schemes. Examples Input 1 1 day may sun fun Output aabb Input 1 1 day may gray way Output aaaa Input 2 1 a a a a a a e e Output aabb Input 2 1 day may sun fun test hill fest thrill Output NO Note In the last sample both quatrains have rhymes but finding the common scheme is impossible, so the answer is "NO".
2
9
// Main Code at the Bottom import java.util.*; import java.io.*; public class Main{ //Fast IO class static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { boolean env=System.getProperty("ONLINE_JUDGE") != null; if(!env) { try { br=new BufferedReader(new FileReader("src\\input.txt")); } catch (FileNotFoundException e) { e.printStackTrace(); } } else br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static long MOD=1000000000+7; //debug static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } // Pair static class pair{ long x,y; pair(long a,long b){ this.x=a; this.y=b; } public boolean equals(Object obj) { if(obj == null || obj.getClass()!= this.getClass()) return false; pair p = (pair) obj; return (this.x==p.x && this.y==p.y); } public int hashCode() { return Objects.hash(x,y); } } static FastReader sc=new FastReader(); static PrintWriter out=new PrintWriter(System.out); //Global variables and functions static boolean isVowel(char s) { if(s=='a' || s=='e' || s=='i' || s=='o' || s=='u') return true; return false; } static boolean check(String a,String b,int k) { int n=a.length(),m=b.length(),x=0,y=0; for(int i=n-1;i>=0;i--) { if(isVowel(a.charAt(i))) x++; if(x==k) { for(int j=m-1;j>=0;j--) { if(isVowel(b.charAt(j))) y++; if(y==k) { if(n-i!=m-j) return false; for(;i<n;i++,j++) if(a.charAt(i)!=b.charAt(j)) return false; return true; } } break; } } return false; } //Main function(The main code starts from here) public static void main (String[] args) throws java.lang.Exception { int test=1; //test=sc.nextInt(); while(test-->0){ int n=sc.nextInt(),k=sc.nextInt(); String a[]=new String[4*n]; int rhyme=0; for(int i=0;i<4*n;i++) a[i]=sc.nextLine(); for(int i=0;i<4*n;i+=4) { int tmp=-1; boolean p=check(a[i],a[i+1],k),q=check(a[i],a[i+2],k),r=check(a[i],a[i+3],k); if(p && q && r) tmp=Math.max(rhyme, 0); else if(p && check(a[i+2],a[i+3],k)) tmp=1; else if(check(a[i],a[i+2],k) && check(a[i+1],a[i+3],k)) tmp=2; else if(r && check(a[i+1],a[i+2],k)) tmp=3; if(tmp!=-1 && (rhyme==0 || tmp==rhyme)) rhyme=tmp; else { rhyme=-1; break; } } String ans="aaaa"; if(rhyme==1) ans="aabb"; else if(rhyme==2) ans="abab"; else if(rhyme==3) ans="abba"; else if(rhyme==-1) ans="NO"; out.println(ans); } out.flush(); out.close(); } }
JAVA
139_C. Literature Lesson
Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes. Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels. Two lines rhyme if their suffixes that start from the k-th vowels (counting from the end) match. If a line has less than k vowels, then such line can't rhyme with any other line. For example, if k = 1, lines commit and hermit rhyme (the corresponding suffixes equal it), and if k = 2, they do not rhyme (ommit β‰  ermit). Today on a literature lesson Vera learned that quatrains can contain four different schemes of rhymes, namely the following ones (the same letters stand for rhyming lines): * Clerihew (aabb); * Alternating (abab); * Enclosed (abba). If all lines of a quatrain pairwise rhyme, then the quatrain can belong to any rhyme scheme (this situation is represented by aaaa). If all quatrains of a poem belong to the same rhyme scheme, then we can assume that the whole poem belongs to this rhyme scheme. If in each quatrain all lines pairwise rhyme, then the rhyme scheme of the poem is aaaa. Let us note that it doesn't matter whether lines from different quatrains rhyme with each other or not. In other words, it is possible that different quatrains aren't connected by a rhyme. Vera got a long poem as a home task. The girl has to analyse it and find the poem rhyme scheme. Help Vera cope with the task. Input The first line contains two integers n and k (1 ≀ n ≀ 2500, 1 ≀ k ≀ 5) β€” the number of quatrains in the poem and the vowel's number, correspondingly. Next 4n lines contain the poem. Each line is not empty and only consists of small Latin letters. The total length of the lines does not exceed 104. If we assume that the lines are numbered starting from 1, then the first quatrain contains lines number 1, 2, 3, 4; the second one contains lines number 5, 6, 7, 8; and so on. Output Print the rhyme scheme of the poem as "aabb", "abab", "abba", "aaaa"; or "NO" if the poem does not belong to any of the above mentioned schemes. Examples Input 1 1 day may sun fun Output aabb Input 1 1 day may gray way Output aaaa Input 2 1 a a a a a a e e Output aabb Input 2 1 day may sun fun test hill fest thrill Output NO Note In the last sample both quatrains have rhymes but finding the common scheme is impossible, so the answer is "NO".
2
9
#include <bits/stdc++.h> using namespace std; int n, nk; char s[4][10005]; int f[4][4]; int sce[4]; void cal(int i) { if (i == 0) puts("aaaa"); if (i == 1) puts("aabb"); if (i == 2) puts("abab"); if (i == 3) puts("abba"); } int main() { scanf("%d%d", &n, &nk); sce[0] = sce[1] = sce[2] = sce[3] = 1; for (int i = 0; i < n; i++) { for (int j = 0; j < 4; j++) scanf("%s", s[j]); memset(f, 0, sizeof(f)); for (int j = 0; j < 4; j++) for (int k = j + 1; k < 4; k++) { int l1 = strlen(s[j]); int l2 = strlen(s[k]); int cnt = 0; for (int l = 1; l <= min(l1, l2); l++) { if (s[j][l1 - l] != s[k][l2 - l]) break; else if (s[j][l1 - l] == 'a' || s[j][l1 - l] == 'e' || s[j][l1 - l] == 'i' || s[j][l1 - l] == 'o' || s[j][l1 - l] == 'u') cnt++; } if (cnt >= nk) f[j][k] = f[k][j] = 1; } bool flag; flag = (f[0][1] && f[0][2] && f[0][3] && f[0][4]); sce[0] &= flag; flag = (f[0][1] && f[2][3]); sce[1] &= flag; flag = (f[0][2] && f[1][3]); sce[2] &= flag; flag = (f[0][3] && f[1][2]); sce[3] &= flag; } for (int i = 0; i < 4; i++) { if (sce[i]) { cal(i); return 0; } } puts("NO"); }
CPP
139_C. Literature Lesson
Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes. Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels. Two lines rhyme if their suffixes that start from the k-th vowels (counting from the end) match. If a line has less than k vowels, then such line can't rhyme with any other line. For example, if k = 1, lines commit and hermit rhyme (the corresponding suffixes equal it), and if k = 2, they do not rhyme (ommit β‰  ermit). Today on a literature lesson Vera learned that quatrains can contain four different schemes of rhymes, namely the following ones (the same letters stand for rhyming lines): * Clerihew (aabb); * Alternating (abab); * Enclosed (abba). If all lines of a quatrain pairwise rhyme, then the quatrain can belong to any rhyme scheme (this situation is represented by aaaa). If all quatrains of a poem belong to the same rhyme scheme, then we can assume that the whole poem belongs to this rhyme scheme. If in each quatrain all lines pairwise rhyme, then the rhyme scheme of the poem is aaaa. Let us note that it doesn't matter whether lines from different quatrains rhyme with each other or not. In other words, it is possible that different quatrains aren't connected by a rhyme. Vera got a long poem as a home task. The girl has to analyse it and find the poem rhyme scheme. Help Vera cope with the task. Input The first line contains two integers n and k (1 ≀ n ≀ 2500, 1 ≀ k ≀ 5) β€” the number of quatrains in the poem and the vowel's number, correspondingly. Next 4n lines contain the poem. Each line is not empty and only consists of small Latin letters. The total length of the lines does not exceed 104. If we assume that the lines are numbered starting from 1, then the first quatrain contains lines number 1, 2, 3, 4; the second one contains lines number 5, 6, 7, 8; and so on. Output Print the rhyme scheme of the poem as "aabb", "abab", "abba", "aaaa"; or "NO" if the poem does not belong to any of the above mentioned schemes. Examples Input 1 1 day may sun fun Output aabb Input 1 1 day may gray way Output aaaa Input 2 1 a a a a a a e e Output aabb Input 2 1 day may sun fun test hill fest thrill Output NO Note In the last sample both quatrains have rhymes but finding the common scheme is impossible, so the answer is "NO".
2
9
#include <bits/stdc++.h> using namespace std; int n, K; string res[] = {"aabb", "abab", "abba", "aaaa"}; bool rhymes(string a, string b) { string ta = "!!!", tb = "###"; int k = K; for (int i = a.length() - 1; i >= 0; i--) { if (a[i] == 'a' || a[i] == 'e' || a[i] == 'i' || a[i] == 'o' || a[i] == 'u') k--; if (k == 0) { ta = a.substr(i); break; } } k = K; for (int i = b.length() - 1; i >= 0; i--) { if (b[i] == 'a' || b[i] == 'e' || b[i] == 'i' || b[i] == 'o' || b[i] == 'u') k--; if (k == 0) { tb = b.substr(i); break; } } return ta == tb; } int main() { while (cin >> n >> K) { bool cannot[4]; memset(cannot, 0, sizeof(cannot)); for (int(i) = 0; (i) < (n); (i)++) { vector<string> q; for (int(j) = 0; (j) < (4); (j)++) { string s; cin >> s; q.push_back(s); } bool rhyme[4][4]; memset(rhyme, 0, sizeof(rhyme)); for (int(j) = 0; (j) < (4); (j)++) { for (int k = j + 1; k < 4; k++) { if (rhymes(q[j], q[k])) { rhyme[j][k] = 1; rhyme[k][j] = 1; } } } if (!(rhyme[0][1] && rhyme[2][3])) cannot[0] = 1; if (!(rhyme[0][2] && rhyme[1][3])) cannot[1] = 1; if (!(rhyme[0][3] && rhyme[1][2])) cannot[2] = 1; if (!(rhyme[0][1] && rhyme[1][2] && rhyme[2][3] && rhyme[3][1])) cannot[3] = 1; } if (!cannot[3]) cout << res[3] << endl; else { bool can = 0; for (int i = 0; i < 3; i++) { if (!cannot[i]) { cout << res[i] << endl; can = 1; break; } } if (!can) cout << "NO" << endl; } } }
CPP
139_C. Literature Lesson
Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes. Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels. Two lines rhyme if their suffixes that start from the k-th vowels (counting from the end) match. If a line has less than k vowels, then such line can't rhyme with any other line. For example, if k = 1, lines commit and hermit rhyme (the corresponding suffixes equal it), and if k = 2, they do not rhyme (ommit β‰  ermit). Today on a literature lesson Vera learned that quatrains can contain four different schemes of rhymes, namely the following ones (the same letters stand for rhyming lines): * Clerihew (aabb); * Alternating (abab); * Enclosed (abba). If all lines of a quatrain pairwise rhyme, then the quatrain can belong to any rhyme scheme (this situation is represented by aaaa). If all quatrains of a poem belong to the same rhyme scheme, then we can assume that the whole poem belongs to this rhyme scheme. If in each quatrain all lines pairwise rhyme, then the rhyme scheme of the poem is aaaa. Let us note that it doesn't matter whether lines from different quatrains rhyme with each other or not. In other words, it is possible that different quatrains aren't connected by a rhyme. Vera got a long poem as a home task. The girl has to analyse it and find the poem rhyme scheme. Help Vera cope with the task. Input The first line contains two integers n and k (1 ≀ n ≀ 2500, 1 ≀ k ≀ 5) β€” the number of quatrains in the poem and the vowel's number, correspondingly. Next 4n lines contain the poem. Each line is not empty and only consists of small Latin letters. The total length of the lines does not exceed 104. If we assume that the lines are numbered starting from 1, then the first quatrain contains lines number 1, 2, 3, 4; the second one contains lines number 5, 6, 7, 8; and so on. Output Print the rhyme scheme of the poem as "aabb", "abab", "abba", "aaaa"; or "NO" if the poem does not belong to any of the above mentioned schemes. Examples Input 1 1 day may sun fun Output aabb Input 1 1 day may gray way Output aaaa Input 2 1 a a a a a a e e Output aabb Input 2 1 day may sun fun test hill fest thrill Output NO Note In the last sample both quatrains have rhymes but finding the common scheme is impossible, so the answer is "NO".
2
9
#from bisect import bisect_left as bl #c++ lowerbound bl(array,element) #from bisect import bisect_right as br #c++ upperbound br(array,element) #from __future__ import print_function, division #while using python2 # from itertools import accumulate # from collections import defaultdict, Counter def modinv(n,p): return pow(n,p-2,p) def get_suffix(s, k): vovels = "aeiou" for i in range(len(s)-1, -1, -1): if s[i] in vovels: k -= 1 if k == 0: return s[i:] return -1 # aaaa = 1 # aabb = 2 # abab = 3 # abba = 4 # none = -1 def get_scheme(s1, s2, s3, s4): if s1 == s2 == s3 == s4: return 1 if s1 == s2 and s3 == s4: return 2 if s1 == s3 and s2 == s4: return 3 if s1 == s4 and s2 == s3: return 4 return -1 def get_scheme2(x): if x == 1: return "aaaa" if x == 2: return "aabb" if x == 3: return "abab" if x == 4: return "abba" def main(): #sys.stdin = open('input.txt', 'r') #sys.stdout = open('output.txt', 'w') # print(get_suffix("commit", 3)) n, k = [int(x) for x in input().split()] rhymes = [] no_scheme = False for i in range(n): s1 = get_suffix(input(), k) s2 = get_suffix(input(), k) s3 = get_suffix(input(), k) s4 = get_suffix(input(), k) if s1 == -1 or s2 == -1 or s3 == -1 or s4 == -1: rhymes.append(-1) else: rhymes.append(get_scheme(s1, s2, s3, s4)) # print(*rhymes) rhymes = set(rhymes) scheme = "" if -1 in rhymes: scheme = "NO" elif len(rhymes) == 1: scheme = get_scheme2(rhymes.pop()) elif len(rhymes) == 2 and 1 in rhymes: rhymes.remove(1) scheme = get_scheme2(rhymes.pop()) else: scheme = "NO" print(scheme) #------------------ Python 2 and 3 footer by Pajenegod and c1729----------------------------------------- py2 = round(0.5) if py2: from future_builtins import ascii, filter, hex, map, oct, zip range = xrange import os, sys from io import IOBase, BytesIO BUFSIZE = 8192 class FastIO(BytesIO): newlines = 0 def __init__(self, file): self._file = file self._fd = file.fileno() self.writable = "x" in file.mode or "w" in file.mode self.write = super(FastIO, self).write if self.writable else None def _fill(self): s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.seek((self.tell(), self.seek(0,2), super(FastIO, self).write(s))[0]) return s def read(self): while self._fill(): pass return super(FastIO,self).read() def readline(self): while self.newlines == 0: s = self._fill(); self.newlines = s.count(b"\n") + (not s) self.newlines -= 1 return super(FastIO, self).readline() def flush(self): if self.writable: os.write(self._fd, self.getvalue()) self.truncate(0), self.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable if py2: self.write = self.buffer.write self.read = self.buffer.read self.readline = self.buffer.readline else: self.write = lambda s:self.buffer.write(s.encode('ascii')) self.read = lambda:self.buffer.read().decode('ascii') self.readline = lambda:self.buffer.readline().decode('ascii') sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip('\r\n') if __name__ == '__main__': main()
PYTHON3
139_C. Literature Lesson
Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes. Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels. Two lines rhyme if their suffixes that start from the k-th vowels (counting from the end) match. If a line has less than k vowels, then such line can't rhyme with any other line. For example, if k = 1, lines commit and hermit rhyme (the corresponding suffixes equal it), and if k = 2, they do not rhyme (ommit β‰  ermit). Today on a literature lesson Vera learned that quatrains can contain four different schemes of rhymes, namely the following ones (the same letters stand for rhyming lines): * Clerihew (aabb); * Alternating (abab); * Enclosed (abba). If all lines of a quatrain pairwise rhyme, then the quatrain can belong to any rhyme scheme (this situation is represented by aaaa). If all quatrains of a poem belong to the same rhyme scheme, then we can assume that the whole poem belongs to this rhyme scheme. If in each quatrain all lines pairwise rhyme, then the rhyme scheme of the poem is aaaa. Let us note that it doesn't matter whether lines from different quatrains rhyme with each other or not. In other words, it is possible that different quatrains aren't connected by a rhyme. Vera got a long poem as a home task. The girl has to analyse it and find the poem rhyme scheme. Help Vera cope with the task. Input The first line contains two integers n and k (1 ≀ n ≀ 2500, 1 ≀ k ≀ 5) β€” the number of quatrains in the poem and the vowel's number, correspondingly. Next 4n lines contain the poem. Each line is not empty and only consists of small Latin letters. The total length of the lines does not exceed 104. If we assume that the lines are numbered starting from 1, then the first quatrain contains lines number 1, 2, 3, 4; the second one contains lines number 5, 6, 7, 8; and so on. Output Print the rhyme scheme of the poem as "aabb", "abab", "abba", "aaaa"; or "NO" if the poem does not belong to any of the above mentioned schemes. Examples Input 1 1 day may sun fun Output aabb Input 1 1 day may gray way Output aaaa Input 2 1 a a a a a a e e Output aabb Input 2 1 day may sun fun test hill fest thrill Output NO Note In the last sample both quatrains have rhymes but finding the common scheme is impossible, so the answer is "NO".
2
9
#include <bits/stdc++.h> using namespace std; int a[5000]; int k; int no = 0; string last(string s) { int w = 0; int i = (int)s.size() - 1; while (i >= 0 && w != k) { if (s[i] == 'a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'o' || s[i] == 'u') { w++; } i--; } string res; if (w == k) { i++; } else { no = 1; } for (i; i < (int)s.size(); i++) { res += s[i]; } return res; } int main() { int n; cin >> n >> k; string s1, s2, s3, s4; string p1, p2, p3, p4; for (int i = 0; i < n; i++) { cin >> s1 >> s2 >> s3 >> s4; p1 = last(s1); p2 = last(s2); p3 = last(s3); p4 = last(s4); if (p1 == p2 && p2 == p3 && p3 == p4 && no == 0) { a[i] = 0; } else if (p1 == p2 && p3 == p4 && no == 0) { a[i] = 2; } else if (p1 == p3 && p2 == p4 && no == 0) { a[i] = 3; } else if (p1 == p4 && p2 == p3 && no == 0) { a[i] = 5; } else { a[i] = 7; } } int r = 0; for (int i = 0; i < n; i++) { if (a[i] != 0) { r = 1; } } if (r == 0) { cout << "aaaa" << endl; return 0; } r = 0; for (int i = 0; i < n; i++) { if (!(a[i] == 2 || a[i] == 0)) { r = 1; } } if (r == 0) { cout << "aabb" << endl; return 0; } r = 0; for (int i = 0; i < n; i++) { if (!(a[i] == 3 || a[i] == 0)) { r = 1; } } if (r == 0) { cout << "abab" << endl; return 0; } r = 0; for (int i = 0; i < n; i++) { if (!(a[i] == 5 || a[i] == 0)) { r = 1; } } if (r == 0) { cout << "abba" << endl; return 0; } cout << "NO" << endl; return 0; }
CPP
139_C. Literature Lesson
Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes. Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels. Two lines rhyme if their suffixes that start from the k-th vowels (counting from the end) match. If a line has less than k vowels, then such line can't rhyme with any other line. For example, if k = 1, lines commit and hermit rhyme (the corresponding suffixes equal it), and if k = 2, they do not rhyme (ommit β‰  ermit). Today on a literature lesson Vera learned that quatrains can contain four different schemes of rhymes, namely the following ones (the same letters stand for rhyming lines): * Clerihew (aabb); * Alternating (abab); * Enclosed (abba). If all lines of a quatrain pairwise rhyme, then the quatrain can belong to any rhyme scheme (this situation is represented by aaaa). If all quatrains of a poem belong to the same rhyme scheme, then we can assume that the whole poem belongs to this rhyme scheme. If in each quatrain all lines pairwise rhyme, then the rhyme scheme of the poem is aaaa. Let us note that it doesn't matter whether lines from different quatrains rhyme with each other or not. In other words, it is possible that different quatrains aren't connected by a rhyme. Vera got a long poem as a home task. The girl has to analyse it and find the poem rhyme scheme. Help Vera cope with the task. Input The first line contains two integers n and k (1 ≀ n ≀ 2500, 1 ≀ k ≀ 5) β€” the number of quatrains in the poem and the vowel's number, correspondingly. Next 4n lines contain the poem. Each line is not empty and only consists of small Latin letters. The total length of the lines does not exceed 104. If we assume that the lines are numbered starting from 1, then the first quatrain contains lines number 1, 2, 3, 4; the second one contains lines number 5, 6, 7, 8; and so on. Output Print the rhyme scheme of the poem as "aabb", "abab", "abba", "aaaa"; or "NO" if the poem does not belong to any of the above mentioned schemes. Examples Input 1 1 day may sun fun Output aabb Input 1 1 day may gray way Output aaaa Input 2 1 a a a a a a e e Output aabb Input 2 1 day may sun fun test hill fest thrill Output NO Note In the last sample both quatrains have rhymes but finding the common scheme is impossible, so the answer is "NO".
2
9
n, k = map(int, input().split()) def get_suffix(line): position = 0 for _ in range(k): position -= 1 while -position <= len(line) and line[position] not in 'aeiou': position -= 1 if -position > len(line): return '' return line[position:] common_rhyme_type = 'aaaa' for _ in range(n): s1, s2, s3, s4 = [get_suffix(input()) for _ in range(4)] if '' in (s1, s2, s3, s4): print('NO') break if s1 == s2 == s3 == s4: rhyme_type = 'aaaa' elif s1 == s2 and s3 == s4: rhyme_type = 'aabb' elif s1 == s3 and s2 == s4: rhyme_type = 'abab' elif s1 == s4 and s2 == s3: rhyme_type = 'abba' else: print('NO') break if rhyme_type != 'aaaa': if common_rhyme_type != 'aaaa' and rhyme_type != common_rhyme_type: print('NO') break else: common_rhyme_type = rhyme_type else: print(common_rhyme_type)
PYTHON3
139_C. Literature Lesson
Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes. Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels. Two lines rhyme if their suffixes that start from the k-th vowels (counting from the end) match. If a line has less than k vowels, then such line can't rhyme with any other line. For example, if k = 1, lines commit and hermit rhyme (the corresponding suffixes equal it), and if k = 2, they do not rhyme (ommit β‰  ermit). Today on a literature lesson Vera learned that quatrains can contain four different schemes of rhymes, namely the following ones (the same letters stand for rhyming lines): * Clerihew (aabb); * Alternating (abab); * Enclosed (abba). If all lines of a quatrain pairwise rhyme, then the quatrain can belong to any rhyme scheme (this situation is represented by aaaa). If all quatrains of a poem belong to the same rhyme scheme, then we can assume that the whole poem belongs to this rhyme scheme. If in each quatrain all lines pairwise rhyme, then the rhyme scheme of the poem is aaaa. Let us note that it doesn't matter whether lines from different quatrains rhyme with each other or not. In other words, it is possible that different quatrains aren't connected by a rhyme. Vera got a long poem as a home task. The girl has to analyse it and find the poem rhyme scheme. Help Vera cope with the task. Input The first line contains two integers n and k (1 ≀ n ≀ 2500, 1 ≀ k ≀ 5) β€” the number of quatrains in the poem and the vowel's number, correspondingly. Next 4n lines contain the poem. Each line is not empty and only consists of small Latin letters. The total length of the lines does not exceed 104. If we assume that the lines are numbered starting from 1, then the first quatrain contains lines number 1, 2, 3, 4; the second one contains lines number 5, 6, 7, 8; and so on. Output Print the rhyme scheme of the poem as "aabb", "abab", "abba", "aaaa"; or "NO" if the poem does not belong to any of the above mentioned schemes. Examples Input 1 1 day may sun fun Output aabb Input 1 1 day may gray way Output aaaa Input 2 1 a a a a a a e e Output aabb Input 2 1 day may sun fun test hill fest thrill Output NO Note In the last sample both quatrains have rhymes but finding the common scheme is impossible, so the answer is "NO".
2
9
import static java.lang.Math.*; import java.util.*; import java.io.*; public class C { public void solve() throws Exception { int n = nextInt(), kk = nextInt(); boolean aabb=true, abab=true, abba=true; for (int i=0; i<n; ++i) { String[] q = new String[4]; int[] start = new int[4]; Arrays.fill(start,-1); for (int j=0; j<4; ++j) { q[j] = nextLine(); int wcnt = 0; for (int k=q[j].length()-1; k>=0; --k) { if (q[j].charAt(k)=='a' || q[j].charAt(k)=='e' || q[j].charAt(k)=='i' || q[j].charAt(k)=='o' || q[j].charAt(k)=='u') wcnt++; if (wcnt==kk) { start[j] = k; break; } } if (start[j]==-1) halt("NO"); } //aabb if (q[0].length()-start[0]!=q[1].length()-start[1] || q[2].length()-start[2]!=q[3].length()-start[3]) aabb=false; else { int a = q[0].length()-start[0]; for (int k=0; k<a; ++k) { if (q[0].charAt(q[0].length()-k-1) != q[1].charAt(q[1].length()-k-1)) { aabb = false; break; } } int b = q[2].length()-start[2]; for (int k=0; k<b; ++k) { if (q[2].charAt(q[2].length()-k-1) != q[3].charAt(q[3].length()-k-1)) { aabb = false; break; } } } //abab if (q[0].length()-start[0]!=q[2].length()-start[2] || q[1].length()-start[1]!=q[3].length()-start[3]) abab=false; else { int a = q[0].length()-start[0]; for (int k=0; k<a; ++k) { if (q[0].charAt(q[0].length()-k-1) != q[2].charAt(q[2].length()-k-1)) { abab = false; break; } } int b = q[1].length()-start[1]; for (int k=0; k<b; ++k) { if (q[1].charAt(q[1].length()-k-1) != q[3].charAt(q[3].length()-k-1)) { abab = false; break; } } } //abba if (q[0].length()-start[0]!=q[3].length()-start[3] || q[2].length()-start[2]!=q[1].length()-start[1]) abba=false; else { int a = q[0].length()-start[0]; for (int k=0; k<a; ++k) { if (q[0].charAt(q[0].length()-k-1) != q[3].charAt(q[3].length()-k-1)) { abba = false; break; } } int b = q[2].length()-start[2]; for (int k=0; k<b; ++k) { if (q[2].charAt(q[2].length()-k-1) != q[1].charAt(q[1].length()-k-1)) { abba = false; break; } } } } int cnt = 0; cnt = (abab ? 1:0) + (abba ? 1:0) + (aabb ? 1:0); if (cnt>1) halt("aaaa"); if (cnt==0) halt("NO"); if (abab) halt("abab"); if (abba) halt("abba"); halt("aabb"); } //////////////////////////////////////////////////////////////////////////// boolean showDebug = true; static boolean useFiles = false; static String inFile = "input.txt"; static String outFile = "output.txt"; double EPS = 1e-7; int INF = Integer.MAX_VALUE; long INFL = Long.MAX_VALUE; double INFD = Double.MAX_VALUE; int absPos(int num) { return num<0 ? 0:num; } long absPos(long num) { return num<0 ? 0:num; } double absPos(double num) { return num<0 ? 0:num; } int min(int... nums) { int r = INF; for (int i: nums) if (i<r) r=i; return r; } int max(int... nums) { int r = -INF; for (int i: nums) if (i>r) r=i; return r; } long minL(long... nums) { long r = INFL; for (long i: nums) if (i<r) r=i; return r; } long maxL(long... nums) { long r = -INFL; for (long i: nums) if (i>r) r=i; return r; } double minD(double... nums) { double r = INFD; for (double i: nums) if (i<r) r=i; return r; } double maxD(double... nums) { double r = -INFD; for (double i: nums) if (i>r) r=i; return r; } long sumArr(int[] arr) { long res = 0; for (int i: arr) res+=i; return res; } long sumArr(long[] arr) { long res = 0; for (long i: arr) res+=i; return res; } double sumArr(double[] arr) { double res = 0; for (double i: arr) res+=i; return res; } long partsFitCnt(long partSize, long wholeSize) { return (partSize+wholeSize-1)/partSize; } boolean odd(long num) { return (num&1)==1; } boolean hasBit(int num, int pos) { return (num&(1<<pos))>0; } long binpow(long a, int n) { long r = 1; while (n>0) { if ((n&1)!=0) r*=a; a*=a; n>>=1; } return r; } boolean isLetter(char c) { return (c>='a' && c<='z') || (c>='A' && c<='Z'); } boolean isLowercase(char c) { return (c>='a' && c<='z'); } boolean isUppercase(char c) { return (c>='A' && c<='Z'); } boolean isDigit(char c) { return (c>='0' && c<='9'); } String stringn(String s, int n) { if (n<1) return ""; StringBuilder sb = new StringBuilder(s.length()*n); for (int i=0; i<n; ++i) sb.append(s); return sb.toString(); } String str(Object o) { return o.toString(); } long timer = System.currentTimeMillis(); void startTimer() { timer = System.currentTimeMillis(); } void stopTimer() { System.err.println("time: "+(System.currentTimeMillis()-timer)/1000.0); } static class InputReader { private byte[] buf; private int bufPos = 0, bufLim = -1; private InputStream stream; public InputReader(InputStream stream, int size) { buf = new byte[size]; this.stream = stream; } private void fillBuf() throws IOException { bufLim = stream.read(buf); bufPos = 0; } char read() throws IOException { if (bufPos>=bufLim) fillBuf(); return (char)buf[bufPos++]; } boolean hasInput() throws IOException { if (bufPos>=bufLim) fillBuf(); return bufPos<bufLim; } } static InputReader inputReader; static BufferedWriter outputWriter; char nextChar() throws IOException { return inputReader.read(); } char nextNonWhitespaceChar() throws IOException { char c = inputReader.read(); while (c<=' ') c=inputReader.read(); return c; } String nextWord() throws IOException { StringBuilder sb = new StringBuilder(); char c = inputReader.read(); while (c<=' ') c=inputReader.read(); while (c>' ') { sb.append(c); c = inputReader.read(); } return new String(sb); } String nextLine() throws IOException { StringBuilder sb = new StringBuilder(); char c = inputReader.read(); while (c<=' ') c=inputReader.read(); while (c!='\n' && c!='\r') { sb.append(c); c = inputReader.read(); } return new String(sb); } int nextInt() throws IOException { int r = 0; char c = nextNonWhitespaceChar(); boolean neg = false; if (c=='-') neg=true; else r=c-48; c = nextChar(); while (c>='0' && c<='9') { r*=10; r+=c-48; c=nextChar(); } return neg ? -r:r; } long nextLong() throws IOException { long r = 0; char c = nextNonWhitespaceChar(); boolean neg = false; if (c=='-') neg=true; else r = c-48; c = nextChar(); while (c>='0' && c<='9') { r*=10L; r+=c-48L; c=nextChar(); } return neg ? -r:r; } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextWord()); } int[] nextArr(int size) throws NumberFormatException, IOException { int[] arr = new int[size]; for (int i=0; i<size; ++i) arr[i] = nextInt(); return arr; } long[] nextArrL(int size) throws NumberFormatException, IOException { long[] arr = new long[size]; for (int i=0; i<size; ++i) arr[i] = nextLong(); return arr; } double[] nextArrD(int size) throws NumberFormatException, IOException { double[] arr = new double[size]; for (int i=0; i<size; ++i) arr[i] = nextDouble(); return arr; } String[] nextArrS(int size) throws NumberFormatException, IOException { String[] arr = new String[size]; for (int i=0; i<size; ++i) arr[i] = nextWord(); return arr; } char[] nextArrCh(int size) throws IOException { char[] arr = new char[size]; for (int i=0; i<size; ++i) arr[i] = nextNonWhitespaceChar(); return arr; } char[][] nextArrCh(int rows, int columns) throws IOException { char[][] arr = new char[rows][columns]; for (int i=0; i<rows; ++i) for (int j=0; j<columns; ++j) arr[i][j] = nextNonWhitespaceChar(); return arr; } char[][] nextArrChBorders(int rows, int columns, char border) throws IOException { char[][] arr = new char[rows+2][columns+2]; for (int i=1; i<=rows; ++i) for (int j=1; j<=columns; ++j) arr[i][j] = nextNonWhitespaceChar(); for (int i=0; i<columns+2; ++i) { arr[0][i] = border; arr[rows+1][i] = border; } for (int i=0; i<rows+2; ++i) { arr[i][0] = border; arr[i][columns+1] = border; } return arr; } void printf(String format, Object... args) throws IOException { outputWriter.write(String.format(format, args)); } void print(Object o) throws IOException { outputWriter.write(o.toString()); } void println(Object o) throws IOException { outputWriter.write(o.toString()); outputWriter.newLine(); } void print(Object... o) throws IOException { for (int i=0; i<o.length; ++i) { if (i!=0) outputWriter.write(' '); outputWriter.write(o[i].toString()); } } void println(Object... o) throws IOException { print(o); outputWriter.newLine(); } void printn(Object o, int n) throws IOException { String s = o.toString(); for (int i=0; i<n; ++i) { outputWriter.write(s); if (i!=n-1) outputWriter.write(' '); } } void printnln(Object o, int n) throws IOException { printn(o, n); outputWriter.newLine(); } void printArr(int[] arr) throws IOException { for (int i=0; i<arr.length; ++i) { if (i!=0) outputWriter.write(' '); outputWriter.write(Integer.toString(arr[i])); } } void printArr(long[] arr) throws IOException { for (int i=0; i<arr.length; ++i) { if (i!=0) outputWriter.write(' '); outputWriter.write(Long.toString(arr[i])); } } void printArr(double[] arr) throws IOException { for (int i=0; i<arr.length; ++i) { if (i!=0) outputWriter.write(' '); outputWriter.write(Double.toString(arr[i])); } } void printArr(String[] arr) throws IOException { for (int i=0; i<arr.length; ++i) { if (i!=0) outputWriter.write(' '); outputWriter.write(arr[i]); } } void printArr(char[] arr) throws IOException { for (char c: arr) outputWriter.write(c); } void printlnArr(int[] arr) throws IOException { printArr(arr); outputWriter.newLine(); } void printlnArr(long[] arr) throws IOException { printArr(arr); outputWriter.newLine(); } void printlnArr(double[] arr) throws IOException { printArr(arr); outputWriter.newLine(); } void printlnArr(String[] arr) throws IOException { printArr(arr); outputWriter.newLine(); } void printlnArr(char[] arr) throws IOException { printArr(arr); outputWriter.newLine(); } void halt(Object... o) throws IOException { if (o.length!=0) println(o); outputWriter.flush(); outputWriter.close(); System.exit(0); } void debug(Object... o) { if (showDebug) System.err.println(Arrays.deepToString(o)); } public static void main(String[] args) throws Exception { Locale.setDefault(Locale.US); if (!useFiles) { inputReader = new InputReader(System.in, 1<<16); outputWriter = new BufferedWriter(new OutputStreamWriter(System.out), 1<<16); } else { inputReader = new InputReader(new FileInputStream(new File(inFile)), 1<<16); outputWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(outFile))), 1<<16); } new C().solve(); outputWriter.flush(); outputWriter.close(); } }
JAVA
139_C. Literature Lesson
Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes. Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels. Two lines rhyme if their suffixes that start from the k-th vowels (counting from the end) match. If a line has less than k vowels, then such line can't rhyme with any other line. For example, if k = 1, lines commit and hermit rhyme (the corresponding suffixes equal it), and if k = 2, they do not rhyme (ommit β‰  ermit). Today on a literature lesson Vera learned that quatrains can contain four different schemes of rhymes, namely the following ones (the same letters stand for rhyming lines): * Clerihew (aabb); * Alternating (abab); * Enclosed (abba). If all lines of a quatrain pairwise rhyme, then the quatrain can belong to any rhyme scheme (this situation is represented by aaaa). If all quatrains of a poem belong to the same rhyme scheme, then we can assume that the whole poem belongs to this rhyme scheme. If in each quatrain all lines pairwise rhyme, then the rhyme scheme of the poem is aaaa. Let us note that it doesn't matter whether lines from different quatrains rhyme with each other or not. In other words, it is possible that different quatrains aren't connected by a rhyme. Vera got a long poem as a home task. The girl has to analyse it and find the poem rhyme scheme. Help Vera cope with the task. Input The first line contains two integers n and k (1 ≀ n ≀ 2500, 1 ≀ k ≀ 5) β€” the number of quatrains in the poem and the vowel's number, correspondingly. Next 4n lines contain the poem. Each line is not empty and only consists of small Latin letters. The total length of the lines does not exceed 104. If we assume that the lines are numbered starting from 1, then the first quatrain contains lines number 1, 2, 3, 4; the second one contains lines number 5, 6, 7, 8; and so on. Output Print the rhyme scheme of the poem as "aabb", "abab", "abba", "aaaa"; or "NO" if the poem does not belong to any of the above mentioned schemes. Examples Input 1 1 day may sun fun Output aabb Input 1 1 day may gray way Output aaaa Input 2 1 a a a a a a e e Output aabb Input 2 1 day may sun fun test hill fest thrill Output NO Note In the last sample both quatrains have rhymes but finding the common scheme is impossible, so the answer is "NO".
2
9
#include <bits/stdc++.h> using namespace std; int n, k, i, j, x, l; bool b[4] = {true, true, true, true}; string s[4], a[4], ans[4] = {"aabb", "abab", "abba", "aaaa"}; int main() { cin >> n >> k; for (j = 0; j < n; j++) { for (i = 0; i < 4; i++) { cin >> s[i]; a[i] = ""; } for (l = 0; l < 4; l++) { x = k; for (i = s[l].size() - 1; i >= 0 && x > 0; i--) { a[l] += s[l][i]; if (s[l][i] == 'a' || s[l][i] == 'e' || s[l][i] == 'i' || s[l][i] == 'o' || s[l][i] == 'u') x--; } if (x > 0) { cout << "NO"; return 0; } } if (!(a[0] == a[1] && a[2] == a[3])) b[0] = false; if (!(a[0] == a[2] && a[1] == a[3])) b[1] = false; if (!(a[0] == a[3] && a[1] == a[2])) b[2] = false; if (!(a[0] == a[1] && a[1] == a[2] && a[2] == a[3])) b[3] = false; } for (i = 3; i >= 0; i--) if (b[i]) { cout << ans[i]; return 0; } cout << "NO"; return 0; }
CPP
1423_G. Growing flowers
Sarah has always been a lover of nature, and a couple of years ago she saved up enough money to travel the world and explore all the things built by nature over its lifetime on earth. During this time she visited some truly special places which were left untouched for centuries, from watching icebergs in freezing weather to scuba-diving in oceans and admiring the sea life, residing unseen. These experiences were enhanced with breathtaking views built by mountains over time and left there for visitors to see for years on end. Over time, all these expeditions took a toll on Sarah and culminated in her decision to settle down in the suburbs and live a quiet life. However, as Sarah's love for nature never faded, she started growing flowers in her garden in an attempt to stay connected with nature. At the beginning she planted only blue orchids, but over time she started using different flower types to add variety to her collection of flowers. This collection of flowers can be represented as an array of N flowers and the i-th of them has a type associated with it, denoted as A_i. Each resident, passing by her collection and limited by the width of his view, can only see K contiguous flowers at each moment in time. To see the whole collection, the resident will look at the first K contiguous flowers A_1, A_2, ..., A_K, then shift his view by one flower and look at the next section of K contiguous flowers A_2, A_3, ..., A_{K+1} and so on until they scan the whole collection, ending with section A_{N-K+1}, ..., A_{N-1}, A_N. Each resident determines the beautiness of a section of K flowers as the number of distinct flower types in that section. Furthermore, the beautiness of the whole collection is calculated by summing the beautiness values of each contiguous section. Formally, beautiness B_i of a section starting at the i-th position is calculated as B_i = distinct(A_i, A_{i+1}, ..., A_{i+K-1}), and beautiness of the collection B is calculated as B=B_1 + B_2 + ... + B_{N-K+1}. In addition, as Sarah wants to keep her collection of flowers have a fresh feel, she can also pick two points L and R, dispose flowers between those two points and plant new flowers, all of them being the same type. You will be given Q queries and each of those queries will be of the following two types: 1. You will be given three integers L, R, X describing that Sarah has planted flowers of type X between positions L and R inclusive. Formally collection is changed such that A[i]=X for all i in range [L.. R]. 2. You will be given integer K, width of the resident's view and you have to determine the beautiness value B resident has associated with the collection For each query of second type print the result – beautiness B of the collection. Input First line contains two integers N and Q \;(1 ≀ N, Q ≀ 10^5) β€” number of flowers and the number of queries, respectively. The second line contains N integers A_1, A_2, ..., A_N\;(1 ≀ A_i ≀ 10^9) β€” where A_i represents type of the i-th flower. Each of the next Q lines describe queries and start with integer T∈\{1, 2\}. * If T = 1, there will be three more integers in the line L, R, X\;(1 ≀ L, R ≀ N;\; 1 ≀ X ≀ 10^9) β€” L and R describing boundaries and X describing the flower type * If T = 2, there will be one more integer in the line K\;(1 ≀ K ≀ N) β€” resident's width of view Output For each query of the second type print the beautiness B of the collection. Example Input 5 5 1 2 3 4 5 2 3 1 1 2 5 2 4 1 2 4 5 2 2 Output 9 6 4 Note Let's look at the example. Initially the collection is [1, 2, 3, 4, 5]. In the first query K = 3, we consider sections of three flowers with the first being [1, 2, 3]. Since beautiness of the section is the number of distinct flower types in that section, B_1 = 3. Second section is [2, 3, 4] and B_2 = 3. Third section is [3, 4, 5] and B_3 = 3, since the flower types are all distinct. The beautiness value resident has associated with the collection is B = B_1 + B_2 + B_3 = 3 + 3 + 3 = 9. After the second query, the collection becomes [5, 5, 3, 4, 5]. For the third query K = 4, so we consider sections of four flowers with the first being [5, 5, 3, 4]. There are three distinct flower types [5, 3, 4] in this section, so B_1 = 3. Second section [5, 3, 4, 5] also has 3 distinct flower types, so B_2 = 3. The beautiness value resident has associated with the collection is B = B_1 + B_2 = 3 + 3 = 6 After the fourth query, the collection becomes [5, 5, 5, 5, 5]. For the fifth query K = 2 and in this case all the four sections are same with each of them being [5, 5]. Beautiness of [5, 5] is 1 since there is only one distinct element in this section [5]. Beautiness of the whole collection is B = B_1 + B_2 + B_3 + B_4 = 1 + 1 + 1 + 1 = 4
2
13
#include <bits/stdc++.h> int n, m, cnt; long long tr[400010], tags[400010], tage[400010]; void addtag(long long s, long long e, int x, int l, int r) { tr[x] += s * (r - l + 1) + 1ll * (r - l) * (r - l + 1) / 2 * e; tags[x] += s, tage[x] += e; } void pushdown(int x, int ls, int rs, int l, int mid, int r) { if (tage[x] || tags[x]) { addtag(tags[x], tage[x], ls, l, mid); addtag(tags[x] + tage[x] * (mid - l + 1), tage[x], rs, mid + 1, r); tags[x] = tage[x] = 0; } } void update(int pl, int pr, long long ps, long long pe, int x = 1, int l = 1, int r = n) { if (l == pl && r == pr) return addtag(ps, pe, x, l, r); int mid = (l + r) >> 1, ls = x << 1, rs = x << 1 | 1; pushdown(x, ls, rs, l, mid, r); if (pr <= mid) update(pl, pr, ps, pe, ls, l, mid); else if (pl > mid) update(pl, pr, ps, pe, rs, mid + 1, r); else update(pl, mid, ps, pe, ls, l, mid), update(mid + 1, pr, ps + (mid - pl + 1) * pe, pe, rs, mid + 1, r); tr[x] = tr[ls] + tr[rs]; } void dfs(int x = 1, int l = 1, int r = n) { printf("%d %d %lld %lld %lld\n", l, r, tr[x], tags[x], tage[x]); if (l == r) return; int mid = (l + r) >> 1, ls = x << 1, rs = x << 1 | 1; pushdown(x, ls, rs, l, mid, r); dfs(ls, l, mid), dfs(rs, mid + 1, r); } long long query(int p, int x = 1, int l = 1, int r = n) { if (l == r) return tr[x]; int mid = (l + r) >> 1, ls = x << 1, rs = x << 1 | 1; pushdown(x, ls, rs, l, mid, r); if (p <= mid) return query(p, ls, l, mid); else return query(p, rs, mid + 1, r); } std::set<std::pair<int, int>> st[200010]; struct node { int l, r, x; node() : l(), r(), x() {} node(int _l, int _r, int _c) : l(_l), r(_r), x(_c) {} bool operator<(node const &x) const { return l < x.l; } }; std::set<node> s; std::map<int, int> mp; void insert(int l, int r, int x) { s.emplace(l, r, x); std::set<std::pair<int, int>>::iterator it = st[x].emplace(l, r).first; int pre = (--it)->second; ++it; int nxt = (++it)->first; int k = std::min(l - pre, nxt - r), f = std::max(l - pre, nxt - r); update(1, k, r - l + 1, 1); if (k != f) { update(k + 1, f, k + r - l, 0); } if (f + 1 <= nxt - pre - 1) update(f + 1, nxt - pre - 1, k + r - l - 1, -1); } std::set<node>::iterator split(int pos) { std::set<node>::iterator it = s.lower_bound(node(pos, 0, 0)); if (it->l == pos) return it; --it; int l = it->l, r = it->r, x = it->x; s.erase(it); st[x].erase(std::make_pair(l, r)); st[x].emplace(l, pos - 1), st[x].emplace(pos, r); s.emplace(l, pos - 1, x); return s.emplace(pos, r, x).first; } void erase(int l, int r) { std::set<node>::iterator itr = split(r + 1), itl = split(l); for (std::set<node>::iterator it = itl; it != itr; ++it) { int l = it->l, r = it->r, x = it->x; std::set<std::pair<int, int>>::iterator i = st[x].find(std::make_pair(l, r)); int pre = (--i)->second; ++i; int nxt = (++i)->first; st[x].erase(--i); int k = std::min(l - pre, nxt - r), f = std::max(l - pre, nxt - r); update(1, k, -(r - l + 1), -1); if (k != f) { update(k + 1, f, -(k + r - l), 0); } if (f + 1 <= nxt - pre - 1) update(f + 1, nxt - pre - 1, -(k + r - l - 1), 1); } s.erase(itl, itr); } int main() { scanf("%d%d", &n, &m); s.emplace(0, 0, 0), s.emplace(n + 1, n + 1, 0); for (int i = 1; i <= n + m; i++) st[i].emplace(0, 0), st[i].emplace(n + 1, n + 1); for (int i = 1, x; i <= n; i++) { scanf("%d", &x); if (!mp[x]) mp[x] = ++cnt; x = mp[x]; insert(i, i, x); } for (int i = 1; i <= m; i++) { int op, l, r, x; scanf("%d", &op); if (op == 1) { scanf("%d%d%d", &l, &r, &x); erase(l, r); if (!mp[x]) mp[x] = ++cnt; x = mp[x]; insert(l, r, x); } else { scanf("%d", &x); printf("%lld\n", query(x)); } } return 0; }
CPP
1423_G. Growing flowers
Sarah has always been a lover of nature, and a couple of years ago she saved up enough money to travel the world and explore all the things built by nature over its lifetime on earth. During this time she visited some truly special places which were left untouched for centuries, from watching icebergs in freezing weather to scuba-diving in oceans and admiring the sea life, residing unseen. These experiences were enhanced with breathtaking views built by mountains over time and left there for visitors to see for years on end. Over time, all these expeditions took a toll on Sarah and culminated in her decision to settle down in the suburbs and live a quiet life. However, as Sarah's love for nature never faded, she started growing flowers in her garden in an attempt to stay connected with nature. At the beginning she planted only blue orchids, but over time she started using different flower types to add variety to her collection of flowers. This collection of flowers can be represented as an array of N flowers and the i-th of them has a type associated with it, denoted as A_i. Each resident, passing by her collection and limited by the width of his view, can only see K contiguous flowers at each moment in time. To see the whole collection, the resident will look at the first K contiguous flowers A_1, A_2, ..., A_K, then shift his view by one flower and look at the next section of K contiguous flowers A_2, A_3, ..., A_{K+1} and so on until they scan the whole collection, ending with section A_{N-K+1}, ..., A_{N-1}, A_N. Each resident determines the beautiness of a section of K flowers as the number of distinct flower types in that section. Furthermore, the beautiness of the whole collection is calculated by summing the beautiness values of each contiguous section. Formally, beautiness B_i of a section starting at the i-th position is calculated as B_i = distinct(A_i, A_{i+1}, ..., A_{i+K-1}), and beautiness of the collection B is calculated as B=B_1 + B_2 + ... + B_{N-K+1}. In addition, as Sarah wants to keep her collection of flowers have a fresh feel, she can also pick two points L and R, dispose flowers between those two points and plant new flowers, all of them being the same type. You will be given Q queries and each of those queries will be of the following two types: 1. You will be given three integers L, R, X describing that Sarah has planted flowers of type X between positions L and R inclusive. Formally collection is changed such that A[i]=X for all i in range [L.. R]. 2. You will be given integer K, width of the resident's view and you have to determine the beautiness value B resident has associated with the collection For each query of second type print the result – beautiness B of the collection. Input First line contains two integers N and Q \;(1 ≀ N, Q ≀ 10^5) β€” number of flowers and the number of queries, respectively. The second line contains N integers A_1, A_2, ..., A_N\;(1 ≀ A_i ≀ 10^9) β€” where A_i represents type of the i-th flower. Each of the next Q lines describe queries and start with integer T∈\{1, 2\}. * If T = 1, there will be three more integers in the line L, R, X\;(1 ≀ L, R ≀ N;\; 1 ≀ X ≀ 10^9) β€” L and R describing boundaries and X describing the flower type * If T = 2, there will be one more integer in the line K\;(1 ≀ K ≀ N) β€” resident's width of view Output For each query of the second type print the beautiness B of the collection. Example Input 5 5 1 2 3 4 5 2 3 1 1 2 5 2 4 1 2 4 5 2 2 Output 9 6 4 Note Let's look at the example. Initially the collection is [1, 2, 3, 4, 5]. In the first query K = 3, we consider sections of three flowers with the first being [1, 2, 3]. Since beautiness of the section is the number of distinct flower types in that section, B_1 = 3. Second section is [2, 3, 4] and B_2 = 3. Third section is [3, 4, 5] and B_3 = 3, since the flower types are all distinct. The beautiness value resident has associated with the collection is B = B_1 + B_2 + B_3 = 3 + 3 + 3 = 9. After the second query, the collection becomes [5, 5, 3, 4, 5]. For the third query K = 4, so we consider sections of four flowers with the first being [5, 5, 3, 4]. There are three distinct flower types [5, 3, 4] in this section, so B_1 = 3. Second section [5, 3, 4, 5] also has 3 distinct flower types, so B_2 = 3. The beautiness value resident has associated with the collection is B = B_1 + B_2 = 3 + 3 = 6 After the fourth query, the collection becomes [5, 5, 5, 5, 5]. For the fifth query K = 2 and in this case all the four sections are same with each of them being [5, 5]. Beautiness of [5, 5] is 1 since there is only one distinct element in this section [5]. Beautiness of the whole collection is B = B_1 + B_2 + B_3 + B_4 = 1 + 1 + 1 + 1 = 4
2
13
#include <bits/stdc++.h> using namespace std; using ll = long long; inline ll read() { ll x = 0, f = 1; char ch = getchar(); while (!isdigit(ch)) { if (ch == '-') f = -1; ch = getchar(); } while (isdigit(ch)) { x = (x << 1) + (x << 3) + ch - '0'; ch = getchar(); } return x * f; } const ll N = 2e5 + 10; ll n, q; struct BIT { ll t[N]; inline ll lowbit(ll x) { return x & -x; } inline void update(ll x, ll k) { for (ll i = x; i <= n; i += lowbit(i)) t[i] += k; } inline ll query(ll x) { ll ans = 0; for (ll i = x; i; i -= lowbit(i)) ans += t[i]; return ans; } } t1, t2; inline ll query(ll x) { return t1.query(x) + t2.query(x) * x; } inline void modify(ll x, ll d) { t1.update(x, -x * d); t2.update(x, d); } struct Node { ll l, r, w; friend bool operator<(const Node& a, const Node& b) { return a.l < b.l; } }; set<Node> S, a[N]; inline void erase(Node x) { auto it = a[x.w].find(x); if (it != a[x.w].begin()) { it--; modify(x.l - it->r, 1); it++; } it++; if (it != a[x.w].end()) modify(it->l - x.r, 1); it--; if (it != a[x.w].begin()) { auto it2 = it, it3 = it; it2++; it3--; if (it2 != a[x.w].end()) modify(it2->l - it3->r, -1); } if (x.l != x.r) modify(1, x.r - x.l); modify(a[x.w].begin()->l, 1); modify(n - a[x.w].rbegin()->r + 1, 1); a[x.w].erase(x); if (!a[x.w].empty()) { modify(a[x.w].begin()->l, -1); modify(n - a[x.w].rbegin()->r + 1, -1); } } inline void insert(Node x) { if (!a[x.w].empty()) { modify(a[x.w].begin()->l, 1); modify(n - a[x.w].rbegin()->r + 1, 1); } a[x.w].insert(x); modify(a[x.w].begin()->l, -1); modify(n - a[x.w].rbegin()->r + 1, -1); auto it = a[x.w].find(x); if (it != a[x.w].begin()) { it--; modify(x.l - it->r, -1); it++; } it++; if (it != a[x.w].end()) modify(it->l - x.r, -1); it--; if (it != a[x.w].begin()) { auto it2 = it, it3 = it; it2++; it3--; if (it2 != a[x.w].end()) modify(it2->l - it3->r, 1); } if (x.l != x.r) modify(1, x.l - x.r); } inline set<Node>::iterator split(ll p) { auto x = S.upper_bound((Node){p, -1, -1}); x--; if (x->l == p) return x; else if (p > x->r) return S.end(); else { Node t = (*x); erase(t); S.erase(x); S.insert((Node){t.l, p - 1, t.w}); S.insert((Node){p, t.r, t.w}); insert((Node){t.l, p - 1, t.w}); insert((Node){p, t.r, t.w}); return S.find((Node){p, t.r, t.w}); } } inline void assign(ll l, ll r, ll w) { auto R = split(r + 1), L = split(l); auto p = L; do { erase(*p); p++; } while (p != R); S.erase(L, R); S.insert((Node){l, r, w}); insert((Node){l, r, w}); } map<ll, ll> mp; ll idcnt; inline ll get_id(ll x) { return mp.count(x) ? mp[x] : mp[x] = (++idcnt); } int main() { n = read(); q = read(); for (ll i = 1; i <= n; ++i) { ll x = read(); S.insert((Node){i, i, get_id(x)}); insert((Node){i, i, get_id(x)}); } while (q--) { ll opt = read(), l, r, x; switch (opt) { case 1: l = read(); r = read(); x = read(); assign(l, r, get_id(x)); break; case 2: x = read(); printf("%lld\n", x * n + query(x)); break; } } return 0; }
CPP
1423_G. Growing flowers
Sarah has always been a lover of nature, and a couple of years ago she saved up enough money to travel the world and explore all the things built by nature over its lifetime on earth. During this time she visited some truly special places which were left untouched for centuries, from watching icebergs in freezing weather to scuba-diving in oceans and admiring the sea life, residing unseen. These experiences were enhanced with breathtaking views built by mountains over time and left there for visitors to see for years on end. Over time, all these expeditions took a toll on Sarah and culminated in her decision to settle down in the suburbs and live a quiet life. However, as Sarah's love for nature never faded, she started growing flowers in her garden in an attempt to stay connected with nature. At the beginning she planted only blue orchids, but over time she started using different flower types to add variety to her collection of flowers. This collection of flowers can be represented as an array of N flowers and the i-th of them has a type associated with it, denoted as A_i. Each resident, passing by her collection and limited by the width of his view, can only see K contiguous flowers at each moment in time. To see the whole collection, the resident will look at the first K contiguous flowers A_1, A_2, ..., A_K, then shift his view by one flower and look at the next section of K contiguous flowers A_2, A_3, ..., A_{K+1} and so on until they scan the whole collection, ending with section A_{N-K+1}, ..., A_{N-1}, A_N. Each resident determines the beautiness of a section of K flowers as the number of distinct flower types in that section. Furthermore, the beautiness of the whole collection is calculated by summing the beautiness values of each contiguous section. Formally, beautiness B_i of a section starting at the i-th position is calculated as B_i = distinct(A_i, A_{i+1}, ..., A_{i+K-1}), and beautiness of the collection B is calculated as B=B_1 + B_2 + ... + B_{N-K+1}. In addition, as Sarah wants to keep her collection of flowers have a fresh feel, she can also pick two points L and R, dispose flowers between those two points and plant new flowers, all of them being the same type. You will be given Q queries and each of those queries will be of the following two types: 1. You will be given three integers L, R, X describing that Sarah has planted flowers of type X between positions L and R inclusive. Formally collection is changed such that A[i]=X for all i in range [L.. R]. 2. You will be given integer K, width of the resident's view and you have to determine the beautiness value B resident has associated with the collection For each query of second type print the result – beautiness B of the collection. Input First line contains two integers N and Q \;(1 ≀ N, Q ≀ 10^5) β€” number of flowers and the number of queries, respectively. The second line contains N integers A_1, A_2, ..., A_N\;(1 ≀ A_i ≀ 10^9) β€” where A_i represents type of the i-th flower. Each of the next Q lines describe queries and start with integer T∈\{1, 2\}. * If T = 1, there will be three more integers in the line L, R, X\;(1 ≀ L, R ≀ N;\; 1 ≀ X ≀ 10^9) β€” L and R describing boundaries and X describing the flower type * If T = 2, there will be one more integer in the line K\;(1 ≀ K ≀ N) β€” resident's width of view Output For each query of the second type print the beautiness B of the collection. Example Input 5 5 1 2 3 4 5 2 3 1 1 2 5 2 4 1 2 4 5 2 2 Output 9 6 4 Note Let's look at the example. Initially the collection is [1, 2, 3, 4, 5]. In the first query K = 3, we consider sections of three flowers with the first being [1, 2, 3]. Since beautiness of the section is the number of distinct flower types in that section, B_1 = 3. Second section is [2, 3, 4] and B_2 = 3. Third section is [3, 4, 5] and B_3 = 3, since the flower types are all distinct. The beautiness value resident has associated with the collection is B = B_1 + B_2 + B_3 = 3 + 3 + 3 = 9. After the second query, the collection becomes [5, 5, 3, 4, 5]. For the third query K = 4, so we consider sections of four flowers with the first being [5, 5, 3, 4]. There are three distinct flower types [5, 3, 4] in this section, so B_1 = 3. Second section [5, 3, 4, 5] also has 3 distinct flower types, so B_2 = 3. The beautiness value resident has associated with the collection is B = B_1 + B_2 = 3 + 3 = 6 After the fourth query, the collection becomes [5, 5, 5, 5, 5]. For the fifth query K = 2 and in this case all the four sections are same with each of them being [5, 5]. Beautiness of [5, 5] is 1 since there is only one distinct element in this section [5]. Beautiness of the whole collection is B = B_1 + B_2 + B_3 + B_4 = 1 + 1 + 1 + 1 = 4
2
13
#include <bits/stdc++.h> using namespace std; constexpr int Maxn = 2e5 + 5; int n, m; int a[Maxn]; namespace range_tree { using value_t = int; struct range { int l, r; mutable value_t c; range() : l(0), r(0), c(value_t()) {} range(int l, int r, const value_t &c) : l(l), r(r), c(c) {} range(const range &x) : l(x.l), r(x.r), c(x.c) {} friend bool operator<(const range &x, const range &y) { return x.l < y.l; } }; using rtree = set<range>; void insert(rtree &, const range &); void erase(const range &); rtree::iterator split(rtree &S, int p) { auto x = prev(S.upper_bound(range(p, -1, value_t()))); if (x->l == p) return x; else if (p > x->r) return S.end(); else { range t = *x; erase(t); S.erase(t); insert(S, range(t.l, p - 1, t.c)); insert(S, range(p, t.r, t.c)); return S.find(range(p, t.r, t.c)); } } void assign(rtree &S, int l, int r, value_t c) { auto itr = split(S, r + 1), itl = split(S, l); for (auto p = itl; p != itr; ++p) erase(*p); S.erase(itl, itr); insert(S, range(l, r, c)); } } // namespace range_tree using range_tree::assign; using range_tree::insert; using range_tree::range; using range_tree::rtree; using range_tree::value_t; namespace range_tree_helper { void insert(const range &); void erase(const range &); } // namespace range_tree_helper void range_tree::insert(rtree &S, const range &r) { S.insert(r); range_tree_helper::insert(r); } void range_tree::erase(const range &r) { range_tree_helper::erase(r); } namespace ds { struct fenwick_tree { int64_t b[Maxn]; fenwick_tree() {} void add(int x, int64_t y) { while (x < Maxn) { b[x] += y; x += (x & -x); } } int64_t qry(int x) { int64_t res = 0; while (x) { res += b[x]; x -= (x & -x); } return res; } } fen1, fen2; void modify(int pos, int64_t x) { fen1.add(pos, -x * pos); fen2.add(pos, x); } int64_t query(int k) { return fen1.qry(k) + fen2.qry(k) * k; } } // namespace ds using namespace ds; rtree st[Maxn]; void range_tree_helper::insert(const range &x) { int col = x.c; if (!st[col].empty()) { modify(st[col].begin()->l, -1); modify(n - st[col].rbegin()->r + 1, -1); } st[col].insert(x); modify(st[col].begin()->l, 1); modify(n - st[col].rbegin()->r + 1, 1); if (x.l != x.r) modify(1, x.r - x.l); auto it = st[col].find(x); if (it != st[col].begin()) { modify(x.l - prev(it)->r, 1); } if (next(it) != st[col].end()) { modify(next(it)->l - x.r, 1); } if (it != st[col].begin() && next(it) != st[col].end()) { modify(next(it)->l - prev(it)->r, -1); } } void range_tree_helper::erase(const range &x) { int col = x.c; if (x.l != x.r) modify(1, -(x.r - x.l)); auto it = st[col].find(x); if (it != st[col].begin()) { modify(x.l - prev(it)->r, -1); } if (next(it) != st[col].end()) { modify(next(it)->l - x.r, -1); } if (it != st[col].begin() && next(it) != st[col].end()) { modify(next(it)->l - prev(it)->r, 1); } modify(n - st[col].rbegin()->r + 1, -1); modify(st[col].begin()->l, -1); st[col].erase(x); if (!st[col].empty()) { modify(st[col].begin()->l, 1); modify(n - st[col].rbegin()->r + 1, 1); } } int64_t calc(int k) { int64_t ans = 1LL * k * n; ans -= query(k); return ans; } int main() { auto get_id = [](int x) -> int { static unordered_map<int, int> mp; static int ids = 0; if (mp.find(x) == mp.end()) mp[x] = ++ids; return mp[x]; }; scanf("%d %d", &n, &m); rtree chtholly; for (int i = 1; i <= n; ++i) { scanf("%d", a + i); a[i] = get_id(a[i]); insert(chtholly, range(i, i, a[i])); } while (m--) { int op; scanf("%d", &op); if (op == 1) { int l, r, x; scanf("%d %d %d", &l, &r, &x); x = get_id(x); assign(chtholly, l, r, x); } else { int x; scanf("%d", &x); printf("%lld\n", calc(x)); } } return 0; }
CPP
1423_G. Growing flowers
Sarah has always been a lover of nature, and a couple of years ago she saved up enough money to travel the world and explore all the things built by nature over its lifetime on earth. During this time she visited some truly special places which were left untouched for centuries, from watching icebergs in freezing weather to scuba-diving in oceans and admiring the sea life, residing unseen. These experiences were enhanced with breathtaking views built by mountains over time and left there for visitors to see for years on end. Over time, all these expeditions took a toll on Sarah and culminated in her decision to settle down in the suburbs and live a quiet life. However, as Sarah's love for nature never faded, she started growing flowers in her garden in an attempt to stay connected with nature. At the beginning she planted only blue orchids, but over time she started using different flower types to add variety to her collection of flowers. This collection of flowers can be represented as an array of N flowers and the i-th of them has a type associated with it, denoted as A_i. Each resident, passing by her collection and limited by the width of his view, can only see K contiguous flowers at each moment in time. To see the whole collection, the resident will look at the first K contiguous flowers A_1, A_2, ..., A_K, then shift his view by one flower and look at the next section of K contiguous flowers A_2, A_3, ..., A_{K+1} and so on until they scan the whole collection, ending with section A_{N-K+1}, ..., A_{N-1}, A_N. Each resident determines the beautiness of a section of K flowers as the number of distinct flower types in that section. Furthermore, the beautiness of the whole collection is calculated by summing the beautiness values of each contiguous section. Formally, beautiness B_i of a section starting at the i-th position is calculated as B_i = distinct(A_i, A_{i+1}, ..., A_{i+K-1}), and beautiness of the collection B is calculated as B=B_1 + B_2 + ... + B_{N-K+1}. In addition, as Sarah wants to keep her collection of flowers have a fresh feel, she can also pick two points L and R, dispose flowers between those two points and plant new flowers, all of them being the same type. You will be given Q queries and each of those queries will be of the following two types: 1. You will be given three integers L, R, X describing that Sarah has planted flowers of type X between positions L and R inclusive. Formally collection is changed such that A[i]=X for all i in range [L.. R]. 2. You will be given integer K, width of the resident's view and you have to determine the beautiness value B resident has associated with the collection For each query of second type print the result – beautiness B of the collection. Input First line contains two integers N and Q \;(1 ≀ N, Q ≀ 10^5) β€” number of flowers and the number of queries, respectively. The second line contains N integers A_1, A_2, ..., A_N\;(1 ≀ A_i ≀ 10^9) β€” where A_i represents type of the i-th flower. Each of the next Q lines describe queries and start with integer T∈\{1, 2\}. * If T = 1, there will be three more integers in the line L, R, X\;(1 ≀ L, R ≀ N;\; 1 ≀ X ≀ 10^9) β€” L and R describing boundaries and X describing the flower type * If T = 2, there will be one more integer in the line K\;(1 ≀ K ≀ N) β€” resident's width of view Output For each query of the second type print the beautiness B of the collection. Example Input 5 5 1 2 3 4 5 2 3 1 1 2 5 2 4 1 2 4 5 2 2 Output 9 6 4 Note Let's look at the example. Initially the collection is [1, 2, 3, 4, 5]. In the first query K = 3, we consider sections of three flowers with the first being [1, 2, 3]. Since beautiness of the section is the number of distinct flower types in that section, B_1 = 3. Second section is [2, 3, 4] and B_2 = 3. Third section is [3, 4, 5] and B_3 = 3, since the flower types are all distinct. The beautiness value resident has associated with the collection is B = B_1 + B_2 + B_3 = 3 + 3 + 3 = 9. After the second query, the collection becomes [5, 5, 3, 4, 5]. For the third query K = 4, so we consider sections of four flowers with the first being [5, 5, 3, 4]. There are three distinct flower types [5, 3, 4] in this section, so B_1 = 3. Second section [5, 3, 4, 5] also has 3 distinct flower types, so B_2 = 3. The beautiness value resident has associated with the collection is B = B_1 + B_2 = 3 + 3 = 6 After the fourth query, the collection becomes [5, 5, 5, 5, 5]. For the fifth query K = 2 and in this case all the four sections are same with each of them being [5, 5]. Beautiness of [5, 5] is 1 since there is only one distinct element in this section [5]. Beautiness of the whole collection is B = B_1 + B_2 + B_3 + B_4 = 1 + 1 + 1 + 1 = 4
2
13
#include <bits/stdc++.h> using namespace std; const int Maxn = 200005; int n, m, ct, a[Maxn], b[Maxn], x[Maxn], y[Maxn], opt[Maxn], val[Maxn]; set<pair<int, int> > Se[Maxn]; struct ele { int lt, rt, val; bool operator<(const ele &A) const { return lt < A.lt; } }; set<ele> S; struct Tree { int lt, rt; pair<int, long long> tag; } tree[4 * Maxn]; void build(int root, int lt, int rt) { tree[root] = (Tree){lt, rt, make_pair(0, 0)}; if (lt + 1 != rt) { int mid = (lt + rt) >> 1; build(root << 1, lt, mid); build(root << 1 | 1, mid, rt); } } pair<int, long long> operator+(const pair<int, long long> &A, const pair<int, long long> &B) { return make_pair(A.first + B.first, A.second + B.second); } void pushdown(int root) { tree[root << 1].tag = tree[root << 1].tag + tree[root].tag; tree[root << 1 | 1].tag = tree[root << 1 | 1].tag + tree[root].tag; tree[root].tag = make_pair(0, 0); } void modify(int root, int lt, int rt, pair<int, long long> val) { lt = max(lt, 1); if (lt >= rt) return; if (tree[root].lt == lt && tree[root].rt == rt) tree[root].tag = tree[root].tag + val; else { pushdown(root); int mid = (tree[root].lt + tree[root].rt) >> 1; if (lt >= mid) modify(root << 1 | 1, lt, rt, val); else if (rt <= mid) modify(root << 1, lt, rt, val); else modify(root << 1, lt, mid, val), modify(root << 1 | 1, mid, rt, val); } } long long ask(int root, int pos) { if (tree[root].lt + 1 == tree[root].rt) return tree[root].tag.first * (long long)tree[root].lt + tree[root].tag.second; else { pushdown(root); int mid = (tree[root].lt + tree[root].rt) >> 1; if (pos >= mid) return ask(root << 1 | 1, pos); else return ask(root << 1, pos); } } void work(int u, int lt, int rt, int val) { int las = (--Se[u].lower_bound(make_pair(lt, 0)))->second + 1, nxt = Se[u].upper_bound(make_pair(rt, 0x3f3f3f3f))->first - 1; modify(1, 1, min(lt - las + 1, nxt - rt + 1) + 1, make_pair(val, (rt - lt) * val)); modify(1, nxt - rt + 2, lt - las + 2, make_pair(0, (nxt - lt + 1) * val)); modify(1, lt - las + 2, nxt - rt + 2, make_pair(0, (rt - las + 1) * val)); modify(1, max(lt - las + 2, nxt - rt + 2), nxt - las + 2, make_pair(-val, (nxt - las + 2) * val)); } set<pair<int, int> >::iterator spilt(int u, int x) { set<pair<int, int> >::iterator it = --Se[u].lower_bound(make_pair(x, 0x3f3f3f3f)); pair<int, int> now = *it; if (it->first == x) return it; if (it->second < x) return ++it; Se[u].erase(it); Se[u].insert(make_pair(now.first, x - 1)); return Se[u].insert(make_pair(x, now.second)).first; } void erase(int lt, int rt, int u) { set<pair<int, int> >::iterator it_r = spilt(u, rt + 1), it_l = spilt(u, lt); for (auto it = it_l; it != it_r;) { work(u, it->first, it->second, -1); it = Se[u].erase(it); } } set<ele>::iterator spilt(int x) { if (x > n) return S.end(); set<ele>::iterator it = --S.upper_bound((ele){x, 0, 0}); if (it->lt == x) return it; ele now = *it; S.erase(it); S.insert((ele){now.lt, x - 1, now.val}); return S.insert((ele){x, now.rt, now.val}).first; } void erase(int lt, int rt) { set<ele>::iterator it_r = spilt(rt + 1), it_l = spilt(lt); for (auto it = it_l; it != it_r; it++) erase(it->lt, it->rt, it->val); S.erase(it_l, it_r); } int main() { scanf("%d%d", &n, &m); for (int i = 1; i <= n; i++) scanf("%d", &a[i]), b[++ct] = a[i]; for (int i = 1; i <= m; i++) { scanf("%d", &opt[i]); if (opt[i] == 1) scanf("%d%d%d", &x[i], &y[i], &val[i]), b[++ct] = val[i]; else scanf("%d", &val[i]); } sort(b + 1, b + 1 + ct); ct = unique(b + 1, b + 1 + ct) - b - 1; for (int i = 1; i <= ct; i++) Se[i].insert(make_pair(0, 0)), Se[i].insert(make_pair(n + 1, n + 1)); build(1, 1, n + 1); for (int i = 1; i <= n; i++) { a[i] = lower_bound(b + 1, b + 1 + ct, a[i]) - b; work(a[i], i, i, 1); Se[a[i]].insert(make_pair(i, i)); S.insert((ele){i, i, a[i]}); } for (int i = 1; i <= m; i++) if (opt[i] == 1) { val[i] = lower_bound(b + 1, b + 1 + ct, val[i]) - b; erase(x[i], y[i]); S.insert((ele){x[i], y[i], val[i]}); work(val[i], x[i], y[i], 1); Se[val[i]].insert(make_pair(x[i], y[i])); } else printf("%lld\n", ask(1, val[i])); return 0; }
CPP
1423_G. Growing flowers
Sarah has always been a lover of nature, and a couple of years ago she saved up enough money to travel the world and explore all the things built by nature over its lifetime on earth. During this time she visited some truly special places which were left untouched for centuries, from watching icebergs in freezing weather to scuba-diving in oceans and admiring the sea life, residing unseen. These experiences were enhanced with breathtaking views built by mountains over time and left there for visitors to see for years on end. Over time, all these expeditions took a toll on Sarah and culminated in her decision to settle down in the suburbs and live a quiet life. However, as Sarah's love for nature never faded, she started growing flowers in her garden in an attempt to stay connected with nature. At the beginning she planted only blue orchids, but over time she started using different flower types to add variety to her collection of flowers. This collection of flowers can be represented as an array of N flowers and the i-th of them has a type associated with it, denoted as A_i. Each resident, passing by her collection and limited by the width of his view, can only see K contiguous flowers at each moment in time. To see the whole collection, the resident will look at the first K contiguous flowers A_1, A_2, ..., A_K, then shift his view by one flower and look at the next section of K contiguous flowers A_2, A_3, ..., A_{K+1} and so on until they scan the whole collection, ending with section A_{N-K+1}, ..., A_{N-1}, A_N. Each resident determines the beautiness of a section of K flowers as the number of distinct flower types in that section. Furthermore, the beautiness of the whole collection is calculated by summing the beautiness values of each contiguous section. Formally, beautiness B_i of a section starting at the i-th position is calculated as B_i = distinct(A_i, A_{i+1}, ..., A_{i+K-1}), and beautiness of the collection B is calculated as B=B_1 + B_2 + ... + B_{N-K+1}. In addition, as Sarah wants to keep her collection of flowers have a fresh feel, she can also pick two points L and R, dispose flowers between those two points and plant new flowers, all of them being the same type. You will be given Q queries and each of those queries will be of the following two types: 1. You will be given three integers L, R, X describing that Sarah has planted flowers of type X between positions L and R inclusive. Formally collection is changed such that A[i]=X for all i in range [L.. R]. 2. You will be given integer K, width of the resident's view and you have to determine the beautiness value B resident has associated with the collection For each query of second type print the result – beautiness B of the collection. Input First line contains two integers N and Q \;(1 ≀ N, Q ≀ 10^5) β€” number of flowers and the number of queries, respectively. The second line contains N integers A_1, A_2, ..., A_N\;(1 ≀ A_i ≀ 10^9) β€” where A_i represents type of the i-th flower. Each of the next Q lines describe queries and start with integer T∈\{1, 2\}. * If T = 1, there will be three more integers in the line L, R, X\;(1 ≀ L, R ≀ N;\; 1 ≀ X ≀ 10^9) β€” L and R describing boundaries and X describing the flower type * If T = 2, there will be one more integer in the line K\;(1 ≀ K ≀ N) β€” resident's width of view Output For each query of the second type print the beautiness B of the collection. Example Input 5 5 1 2 3 4 5 2 3 1 1 2 5 2 4 1 2 4 5 2 2 Output 9 6 4 Note Let's look at the example. Initially the collection is [1, 2, 3, 4, 5]. In the first query K = 3, we consider sections of three flowers with the first being [1, 2, 3]. Since beautiness of the section is the number of distinct flower types in that section, B_1 = 3. Second section is [2, 3, 4] and B_2 = 3. Third section is [3, 4, 5] and B_3 = 3, since the flower types are all distinct. The beautiness value resident has associated with the collection is B = B_1 + B_2 + B_3 = 3 + 3 + 3 = 9. After the second query, the collection becomes [5, 5, 3, 4, 5]. For the third query K = 4, so we consider sections of four flowers with the first being [5, 5, 3, 4]. There are three distinct flower types [5, 3, 4] in this section, so B_1 = 3. Second section [5, 3, 4, 5] also has 3 distinct flower types, so B_2 = 3. The beautiness value resident has associated with the collection is B = B_1 + B_2 = 3 + 3 = 6 After the fourth query, the collection becomes [5, 5, 5, 5, 5]. For the fifth query K = 2 and in this case all the four sections are same with each of them being [5, 5]. Beautiness of [5, 5] is 1 since there is only one distinct element in this section [5]. Beautiness of the whole collection is B = B_1 + B_2 + B_3 + B_4 = 1 + 1 + 1 + 1 = 4
2
13
#include <bits/stdc++.h> using namespace std; constexpr int Maxn = 2e5 + 5; int n, q; int a[Maxn]; template <typename _Tp> class range { public: public: range() : l(0), r(0), v(_Tp()) {} range(int l, int r, const _Tp &v) : l(l), r(r), v(v) {} range(const range &x) : l(x.l), r(x.r), v(x.v) {} friend bool operator<(const range &x, const range &y) { return x.l < y.l; } inline int left(void) const { return l; } inline int right(void) const { return r; } inline _Tp value(void) const { return v; } private: int l, r; mutable _Tp v; }; template <typename _Tp> class range_tree { public: typedef typename set<range<_Tp>>::const_reverse_iterator const_reverse_iterator; private: void insert_to(const range<_Tp> &_r); void erase_from(const range<_Tp> &_r); public: range_tree() : T() {} range_tree(const range_tree &x) : T(x.T) {} void insert(const range<_Tp> &_r) { T.insert(_r); insert_to(_r); } void erase(const range<_Tp> &_r) { T.erase(_r); erase_from(_r); } typename set<range<_Tp>>::iterator split(int p) { auto x = prev(T.upper_bound(range<_Tp>(p, -1, _Tp()))); if (x->left() == p) return x; else if (p > x->right()) return T.end(); else { range<_Tp> t = *x; erase(t); insert(range<_Tp>(t.left(), p - 1, t.value())); insert(range<_Tp>(p, t.right(), t.value())); return T.find(range<_Tp>(p, t.right(), t.value())); } } std::pair<typename set<range<_Tp>>::iterator, typename set<range<_Tp>>::iterator> split_range(int l, int r) { auto itr = split(r + 1), itl = split(l); return {itl, itr}; } void assign(int l, int r, _Tp v) { typename set<range<_Tp>>::iterator itl, itr; tie(itl, itr) = split_range(l, r); for (typename set<range<_Tp>>::iterator p = itl; p != itr; ++p) erase_from(*p); T.erase(itl, itr); insert(range<_Tp>(l, r, v)); } private: std::set<range<_Tp>> T; }; template <typename _Tp> class fenwick_tree { public: private: int N; std::vector<_Tp> X, Y; inline void _M_check(int idx) { if (__builtin_expect(idx >= N || idx < 0, false)) { throw std::out_of_range("<Fenwick-tree::add> range error"); } } inline void _M_check(int l, int r) { if (__builtin_expect(l > r || r >= N || l < 0, false)) { throw std::out_of_range("<Fenwick-tree::add> range error"); } } void _M_add(std::vector<_Tp> &b, int idx, _Tp delta) { for (; idx < N; idx = idx | (idx + 1)) b[idx] = b[idx] + delta; } _Tp _M_sum(std::vector<_Tp> &b, int idx) { _Tp ret = 0; for (; idx >= 0; idx = (idx & (idx + 1)) - 1) ret = ret + b[idx]; return ret; } public: fenwick_tree() { clear(); } fenwick_tree(int N) { resize(N, 0); } fenwick_tree(const fenwick_tree &arr) : N(arr.N), X(arr.X), Y(arr.Y) {} fenwick_tree(fenwick_tree &&arr) { N = arr.N, arr.N = 0; X.swap(arr.X), arr.X.clear(); Y.swap(arr.Y), arr.Y.clear(); } fenwick_tree(const std::vector<_Tp> &arr) { resize(arr); } inline void clear() { resize(0); } void resize(int len, _Tp val = _Tp(0)) { N = len; X.resize(N, _Tp(0)); Y.resize(N, _Tp(0)); if (val != _Tp(0)) add(0, N - 1, val); } void resize(const std::vector<_Tp> &arr) { N = (int)arr.size(); X.resize(N, _Tp(0)); Y.resize(N, _Tp(0)); for (int i = 0; i < (int)arr.size(); ++i) add(i, i, arr[i]); } void add(int l, int r, _Tp val) { _M_check(l, r); _M_add(X, l, val); _M_add(Y, l, val * static_cast<_Tp>(l)); if (r != N - 1) { _M_add(X, r + 1, -val); _M_add(Y, r + 1, -val * static_cast<_Tp>(r + 1)); } } inline _Tp prefix_sum(int idx) { _M_check(idx); return _M_sum(X, idx) * static_cast<_Tp>(idx + 1) - _M_sum(Y, idx); } inline _Tp sum(int l, int r) { _M_check(l, r); _Tp _ans = prefix_sum(r); if (l != 0) _ans = _ans - prefix_sum(l - 1); return _ans; } }; fenwick_tree<int64_t> f1(Maxn), f2(Maxn); inline void modify(int k, int64_t v) { f1.add(k, n, -k * v); f2.add(k, n, v); } inline int64_t query(int k) { return f1.sum(k, k) + f2.sum(k, k) * k; } set<range<int>> st[Maxn]; template <> void range_tree<int>::insert_to(const range<int> &x) { int l = x.left(), r = x.right(), c = x.value(); if (!st[c].empty()) { modify(st[c].begin()->left(), -1); modify(n - st[c].rbegin()->right() + 1, -1); } st[c].insert(x); modify(st[c].begin()->left(), 1); modify(n - st[c].rbegin()->right() + 1, 1); if (l != r) modify(1, r - l); auto it = st[c].find(x); if (it != st[c].begin()) modify(l - prev(it)->right(), 1); if (next(it) != st[c].end()) modify(next(it)->left() - r, 1); if (it != st[c].begin() && next(it) != st[c].end()) modify(next(it)->left() - prev(it)->right(), -1); } template <> void range_tree<int>::erase_from(const range<int> &x) { int l = x.left(), r = x.right(), c = x.value(); if (l != r) modify(1, -(r - l)); auto it = st[c].find(x); if (it != st[c].begin()) modify(l - prev(it)->right(), -1); if (next(it) != st[c].end()) modify(next(it)->left() - r, -1); if (it != st[c].begin() && next(it) != st[c].end()) modify(next(it)->left() - prev(it)->right(), 1); modify(n - st[c].rbegin()->right() + 1, -1); modify(st[c].begin()->left(), -1); st[c].erase(x); if (!st[c].empty()) { modify(st[c].begin()->left(), 1); modify(n - st[c].rbegin()->right() + 1, 1); } } int64_t calc(int k) { int64_t ans = 1LL * k * n; ans -= query(k); return ans; } std::int32_t main(int argc, const char *argv[]) { std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr); std::cout << std::fixed << std::setprecision(12); std::cerr << std::boolalpha; auto get_id = [&](int x) -> int { static std::unordered_map<int, int> mp; if (mp.find(x) == mp.end()) mp[x] = (int)mp.size() + 1; return mp[x]; }; cin >> n >> q; range_tree<int> T; for (int i = 1; i <= n; ++i) { cin >> a[i]; a[i] = get_id(a[i]); T.insert(range<int>(i, i, a[i])); } while (q--) { int op; cin >> op; if (op == 1) { int l, r, x; cin >> l >> r >> x; x = get_id(x); T.assign(l, r, x); } else { int x; cin >> x; cout << calc(x) << endl; } } std::exit(EXIT_SUCCESS); }
CPP
1423_G. Growing flowers
Sarah has always been a lover of nature, and a couple of years ago she saved up enough money to travel the world and explore all the things built by nature over its lifetime on earth. During this time she visited some truly special places which were left untouched for centuries, from watching icebergs in freezing weather to scuba-diving in oceans and admiring the sea life, residing unseen. These experiences were enhanced with breathtaking views built by mountains over time and left there for visitors to see for years on end. Over time, all these expeditions took a toll on Sarah and culminated in her decision to settle down in the suburbs and live a quiet life. However, as Sarah's love for nature never faded, she started growing flowers in her garden in an attempt to stay connected with nature. At the beginning she planted only blue orchids, but over time she started using different flower types to add variety to her collection of flowers. This collection of flowers can be represented as an array of N flowers and the i-th of them has a type associated with it, denoted as A_i. Each resident, passing by her collection and limited by the width of his view, can only see K contiguous flowers at each moment in time. To see the whole collection, the resident will look at the first K contiguous flowers A_1, A_2, ..., A_K, then shift his view by one flower and look at the next section of K contiguous flowers A_2, A_3, ..., A_{K+1} and so on until they scan the whole collection, ending with section A_{N-K+1}, ..., A_{N-1}, A_N. Each resident determines the beautiness of a section of K flowers as the number of distinct flower types in that section. Furthermore, the beautiness of the whole collection is calculated by summing the beautiness values of each contiguous section. Formally, beautiness B_i of a section starting at the i-th position is calculated as B_i = distinct(A_i, A_{i+1}, ..., A_{i+K-1}), and beautiness of the collection B is calculated as B=B_1 + B_2 + ... + B_{N-K+1}. In addition, as Sarah wants to keep her collection of flowers have a fresh feel, she can also pick two points L and R, dispose flowers between those two points and plant new flowers, all of them being the same type. You will be given Q queries and each of those queries will be of the following two types: 1. You will be given three integers L, R, X describing that Sarah has planted flowers of type X between positions L and R inclusive. Formally collection is changed such that A[i]=X for all i in range [L.. R]. 2. You will be given integer K, width of the resident's view and you have to determine the beautiness value B resident has associated with the collection For each query of second type print the result – beautiness B of the collection. Input First line contains two integers N and Q \;(1 ≀ N, Q ≀ 10^5) β€” number of flowers and the number of queries, respectively. The second line contains N integers A_1, A_2, ..., A_N\;(1 ≀ A_i ≀ 10^9) β€” where A_i represents type of the i-th flower. Each of the next Q lines describe queries and start with integer T∈\{1, 2\}. * If T = 1, there will be three more integers in the line L, R, X\;(1 ≀ L, R ≀ N;\; 1 ≀ X ≀ 10^9) β€” L and R describing boundaries and X describing the flower type * If T = 2, there will be one more integer in the line K\;(1 ≀ K ≀ N) β€” resident's width of view Output For each query of the second type print the beautiness B of the collection. Example Input 5 5 1 2 3 4 5 2 3 1 1 2 5 2 4 1 2 4 5 2 2 Output 9 6 4 Note Let's look at the example. Initially the collection is [1, 2, 3, 4, 5]. In the first query K = 3, we consider sections of three flowers with the first being [1, 2, 3]. Since beautiness of the section is the number of distinct flower types in that section, B_1 = 3. Second section is [2, 3, 4] and B_2 = 3. Third section is [3, 4, 5] and B_3 = 3, since the flower types are all distinct. The beautiness value resident has associated with the collection is B = B_1 + B_2 + B_3 = 3 + 3 + 3 = 9. After the second query, the collection becomes [5, 5, 3, 4, 5]. For the third query K = 4, so we consider sections of four flowers with the first being [5, 5, 3, 4]. There are three distinct flower types [5, 3, 4] in this section, so B_1 = 3. Second section [5, 3, 4, 5] also has 3 distinct flower types, so B_2 = 3. The beautiness value resident has associated with the collection is B = B_1 + B_2 = 3 + 3 = 6 After the fourth query, the collection becomes [5, 5, 5, 5, 5]. For the fifth query K = 2 and in this case all the four sections are same with each of them being [5, 5]. Beautiness of [5, 5] is 1 since there is only one distinct element in this section [5]. Beautiness of the whole collection is B = B_1 + B_2 + B_3 + B_4 = 1 + 1 + 1 + 1 = 4
2
13
#include <bits/stdc++.h> using namespace std; namespace FGF { int n, m; const int N = 2e5 + 5; int a[N]; struct Node { int l, r, x; Node() {} Node(int _l, int _r, int _c) : l(_l), r(_r), x(_c) {} bool operator<(const Node &a) const { return l < a.l; } }; int id(int x) { static unordered_map<int, int> mp; static int tot = 0; if (!mp[x]) mp[x] = ++tot; return mp[x]; } set<pair<int, int> > st[N]; set<Node> s; long long tas[N << 2], tak[N << 2], sum[N << 2]; void add(int ro, int l, int r, long long s, long long k) { sum[ro] += s * (r - l + 1) + k * (r - l) * (r - l + 1) / 2; tas[ro] += s, tak[ro] += k; } void pushdown(int ro, int l, int r) { if (tas[ro] || tak[ro]) { int mid = (l + r) >> 1; add(ro << 1, l, mid, tas[ro], tak[ro]), add(ro << 1 | 1, mid + 1, r, tas[ro] + tak[ro] * (mid - l + 1), tak[ro]); tas[ro] = tak[ro] = 0; } } void updat(int ro, int l, int r, int L, int R, long long s, long long k) { if (L == l && r == R) return add(ro, l, r, s, k); pushdown(ro, l, r); int mid = (l + r) >> 1; if (R <= mid) updat(ro << 1, l, mid, L, R, s, k); else if (L > mid) updat(ro << 1 | 1, mid + 1, r, L, R, s, k); else updat(ro << 1, l, mid, L, mid, s, k), updat(ro << 1 | 1, mid + 1, r, mid + 1, R, s + k * (mid - L + 1), k); } long long query(int ro, int l, int r, int x) { if (l == r) return sum[ro]; pushdown(ro, l, r); int mid = (l + r) >> 1; return x <= mid ? query(ro << 1, l, mid, x) : query(ro << 1 | 1, mid + 1, r, x); } void inser(int l, int r, int x) { x = id(x); s.insert(Node(l, r, x)); set<pair<int, int> >::iterator it = st[x].insert(make_pair(l, r)).first; int pre = (--it)->second; it++, it++; int nxt = it->first; int mi = min(l - pre, nxt - r), mx = max(l - pre, nxt - r); if (mi) updat(1, 1, n, 1, mi, r - l + 1, 1); if (mi < mx) updat(1, 1, n, mi + 1, mx, r - l + mi, 0); if (mx + 1 <= nxt - pre - 1) updat(1, 1, n, mx + 1, nxt - pre - 1, r - l + mi - 1, -1); } set<Node>::iterator split(int p) { set<Node>::iterator jt = s.lower_bound(Node(p, 0, 0)); if (jt->l == p) return jt; jt--; int l = jt->l, r = jt->r, x = jt->x; s.erase(jt), st[x].erase(make_pair(l, r)); s.insert(Node(l, p - 1, x)), st[x].insert(make_pair(l, p - 1)), st[x].insert(make_pair(p, r)); return s.insert(Node(p, r, x)).first; } void del(int l, int r) { set<Node>::iterator rt = split(r + 1), lt = split(l), jt; for (jt = lt; jt != rt; jt++) { int l = jt->l, r = jt->r, x = jt->x; set<pair<int, int> >::iterator it = st[x].insert(make_pair(l, r)).first; int pre = (--it)->second; it++, it++; int nxt = it->first; int mi = min(l - pre, nxt - r), mx = max(l - pre, nxt - r); if (mi) updat(1, 1, n, 1, mi, -(r - l + 1), -1); if (mi < mx) updat(1, 1, n, mi + 1, mx, -(r - l + mi), 0); if (mx + 1 <= nxt - pre - 1) updat(1, 1, n, mx + 1, nxt - pre - 1, -(r - l + mi - 1), 1); st[x].erase(--it); } s.erase(lt, rt); } void work() { scanf("%d%d", &n, &m); s.insert(Node(0, 0, 0)), s.insert(Node(n + 1, n + 1, 0)); for (int i = 1; i <= n + m; i++) st[i].insert(make_pair(0, 0)), st[i].insert(make_pair(n + 1, n + 1)); for (int i = 1; i <= n; i++) scanf("%d", &a[i]), inser(i, i, a[i]); while (m--) { int op, l, r, x; scanf("%d", &op); if (op == 1) scanf("%d%d%d", &l, &r, &x), del(l, r), inser(l, r, x); else scanf("%d", &x), printf("%lld\n", query(1, 1, n, x)); } } } // namespace FGF int main() { FGF::work(); return 0; }
CPP
1423_G. Growing flowers
Sarah has always been a lover of nature, and a couple of years ago she saved up enough money to travel the world and explore all the things built by nature over its lifetime on earth. During this time she visited some truly special places which were left untouched for centuries, from watching icebergs in freezing weather to scuba-diving in oceans and admiring the sea life, residing unseen. These experiences were enhanced with breathtaking views built by mountains over time and left there for visitors to see for years on end. Over time, all these expeditions took a toll on Sarah and culminated in her decision to settle down in the suburbs and live a quiet life. However, as Sarah's love for nature never faded, she started growing flowers in her garden in an attempt to stay connected with nature. At the beginning she planted only blue orchids, but over time she started using different flower types to add variety to her collection of flowers. This collection of flowers can be represented as an array of N flowers and the i-th of them has a type associated with it, denoted as A_i. Each resident, passing by her collection and limited by the width of his view, can only see K contiguous flowers at each moment in time. To see the whole collection, the resident will look at the first K contiguous flowers A_1, A_2, ..., A_K, then shift his view by one flower and look at the next section of K contiguous flowers A_2, A_3, ..., A_{K+1} and so on until they scan the whole collection, ending with section A_{N-K+1}, ..., A_{N-1}, A_N. Each resident determines the beautiness of a section of K flowers as the number of distinct flower types in that section. Furthermore, the beautiness of the whole collection is calculated by summing the beautiness values of each contiguous section. Formally, beautiness B_i of a section starting at the i-th position is calculated as B_i = distinct(A_i, A_{i+1}, ..., A_{i+K-1}), and beautiness of the collection B is calculated as B=B_1 + B_2 + ... + B_{N-K+1}. In addition, as Sarah wants to keep her collection of flowers have a fresh feel, she can also pick two points L and R, dispose flowers between those two points and plant new flowers, all of them being the same type. You will be given Q queries and each of those queries will be of the following two types: 1. You will be given three integers L, R, X describing that Sarah has planted flowers of type X between positions L and R inclusive. Formally collection is changed such that A[i]=X for all i in range [L.. R]. 2. You will be given integer K, width of the resident's view and you have to determine the beautiness value B resident has associated with the collection For each query of second type print the result – beautiness B of the collection. Input First line contains two integers N and Q \;(1 ≀ N, Q ≀ 10^5) β€” number of flowers and the number of queries, respectively. The second line contains N integers A_1, A_2, ..., A_N\;(1 ≀ A_i ≀ 10^9) β€” where A_i represents type of the i-th flower. Each of the next Q lines describe queries and start with integer T∈\{1, 2\}. * If T = 1, there will be three more integers in the line L, R, X\;(1 ≀ L, R ≀ N;\; 1 ≀ X ≀ 10^9) β€” L and R describing boundaries and X describing the flower type * If T = 2, there will be one more integer in the line K\;(1 ≀ K ≀ N) β€” resident's width of view Output For each query of the second type print the beautiness B of the collection. Example Input 5 5 1 2 3 4 5 2 3 1 1 2 5 2 4 1 2 4 5 2 2 Output 9 6 4 Note Let's look at the example. Initially the collection is [1, 2, 3, 4, 5]. In the first query K = 3, we consider sections of three flowers with the first being [1, 2, 3]. Since beautiness of the section is the number of distinct flower types in that section, B_1 = 3. Second section is [2, 3, 4] and B_2 = 3. Third section is [3, 4, 5] and B_3 = 3, since the flower types are all distinct. The beautiness value resident has associated with the collection is B = B_1 + B_2 + B_3 = 3 + 3 + 3 = 9. After the second query, the collection becomes [5, 5, 3, 4, 5]. For the third query K = 4, so we consider sections of four flowers with the first being [5, 5, 3, 4]. There are three distinct flower types [5, 3, 4] in this section, so B_1 = 3. Second section [5, 3, 4, 5] also has 3 distinct flower types, so B_2 = 3. The beautiness value resident has associated with the collection is B = B_1 + B_2 = 3 + 3 = 6 After the fourth query, the collection becomes [5, 5, 5, 5, 5]. For the fifth query K = 2 and in this case all the four sections are same with each of them being [5, 5]. Beautiness of [5, 5] is 1 since there is only one distinct element in this section [5]. Beautiness of the whole collection is B = B_1 + B_2 + B_3 + B_4 = 1 + 1 + 1 + 1 = 4
2
13
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 3; using ll = long long; struct P { int l, r, a; bool operator<(P a) const { return l < a.l; } }; using it = set<P>::iterator; int n, id; set<P> st; set<int> ps[N]; unordered_map<int, int> mp; struct FW { ll t[N]; void add(int x, int y) { for (; x <= n; x += x & -x) t[x] += y; } void add(int l, int r, int y) { add(l, y), add(r + 1, -y); } ll sum(int x) { ll r = 0; for (; x; x -= x & -x) r += t[x]; return r; } } A, B; void add(int l, int r, int a, int w) { if (!mp[a]) mp[a] = ++id, ps[id].insert(0), ps[id].insert(n + 1); if (a = mp[a], w == -1) ps[a].erase(l), ps[a].erase(r); int x = *(--ps[a].lower_bound(l)), y = *ps[a].lower_bound(r), u = min(l - x, y - r), v = max(l - x, y - r), p = min(r - l + u + v, n); A.add(1, u, (r - l) * w), B.add(1, u, w); A.add(u + 1, v, (r - l + u) * w); A.add(v + 1, p, (r - l + u + v) * w), B.add(v + 1, p, -w); if (w == 1) ps[a].insert(l), ps[a].insert(r); } it sp(int x) { it p = st.lower_bound({x, 0, 0}); if (p != st.end() && p->l == x) return p; --p; int l = p->l, r = p->r, a = p->a, b = mp[a]; return ps[b].insert(x - 1), ps[b].insert(x), st.erase(p), st.insert({l, x - 1, a}), st.insert({x, r, a}).first; } int main() { int m, i, j, k; it p, q, o; scanf("%d%d", &n, &m); for (i = 1; i <= n; ++i) scanf("%d", &j), add(i, i, j, 1), st.insert({i, i, j}); while (m--) { scanf("%d%d", &i, &j); if (i == 1) { scanf("%d%d", &k, &i), q = sp(k + 1), p = sp(j); for (o = p; o != q; ++o) add(o->l, o->r, o->a, -1); st.erase(p, q), st.insert({j, k, i}), add(j, k, i, 1); } else printf("%lld\n", A.sum(j) + B.sum(j) * j); } return 0; }
CPP
1423_G. Growing flowers
Sarah has always been a lover of nature, and a couple of years ago she saved up enough money to travel the world and explore all the things built by nature over its lifetime on earth. During this time she visited some truly special places which were left untouched for centuries, from watching icebergs in freezing weather to scuba-diving in oceans and admiring the sea life, residing unseen. These experiences were enhanced with breathtaking views built by mountains over time and left there for visitors to see for years on end. Over time, all these expeditions took a toll on Sarah and culminated in her decision to settle down in the suburbs and live a quiet life. However, as Sarah's love for nature never faded, she started growing flowers in her garden in an attempt to stay connected with nature. At the beginning she planted only blue orchids, but over time she started using different flower types to add variety to her collection of flowers. This collection of flowers can be represented as an array of N flowers and the i-th of them has a type associated with it, denoted as A_i. Each resident, passing by her collection and limited by the width of his view, can only see K contiguous flowers at each moment in time. To see the whole collection, the resident will look at the first K contiguous flowers A_1, A_2, ..., A_K, then shift his view by one flower and look at the next section of K contiguous flowers A_2, A_3, ..., A_{K+1} and so on until they scan the whole collection, ending with section A_{N-K+1}, ..., A_{N-1}, A_N. Each resident determines the beautiness of a section of K flowers as the number of distinct flower types in that section. Furthermore, the beautiness of the whole collection is calculated by summing the beautiness values of each contiguous section. Formally, beautiness B_i of a section starting at the i-th position is calculated as B_i = distinct(A_i, A_{i+1}, ..., A_{i+K-1}), and beautiness of the collection B is calculated as B=B_1 + B_2 + ... + B_{N-K+1}. In addition, as Sarah wants to keep her collection of flowers have a fresh feel, she can also pick two points L and R, dispose flowers between those two points and plant new flowers, all of them being the same type. You will be given Q queries and each of those queries will be of the following two types: 1. You will be given three integers L, R, X describing that Sarah has planted flowers of type X between positions L and R inclusive. Formally collection is changed such that A[i]=X for all i in range [L.. R]. 2. You will be given integer K, width of the resident's view and you have to determine the beautiness value B resident has associated with the collection For each query of second type print the result – beautiness B of the collection. Input First line contains two integers N and Q \;(1 ≀ N, Q ≀ 10^5) β€” number of flowers and the number of queries, respectively. The second line contains N integers A_1, A_2, ..., A_N\;(1 ≀ A_i ≀ 10^9) β€” where A_i represents type of the i-th flower. Each of the next Q lines describe queries and start with integer T∈\{1, 2\}. * If T = 1, there will be three more integers in the line L, R, X\;(1 ≀ L, R ≀ N;\; 1 ≀ X ≀ 10^9) β€” L and R describing boundaries and X describing the flower type * If T = 2, there will be one more integer in the line K\;(1 ≀ K ≀ N) β€” resident's width of view Output For each query of the second type print the beautiness B of the collection. Example Input 5 5 1 2 3 4 5 2 3 1 1 2 5 2 4 1 2 4 5 2 2 Output 9 6 4 Note Let's look at the example. Initially the collection is [1, 2, 3, 4, 5]. In the first query K = 3, we consider sections of three flowers with the first being [1, 2, 3]. Since beautiness of the section is the number of distinct flower types in that section, B_1 = 3. Second section is [2, 3, 4] and B_2 = 3. Third section is [3, 4, 5] and B_3 = 3, since the flower types are all distinct. The beautiness value resident has associated with the collection is B = B_1 + B_2 + B_3 = 3 + 3 + 3 = 9. After the second query, the collection becomes [5, 5, 3, 4, 5]. For the third query K = 4, so we consider sections of four flowers with the first being [5, 5, 3, 4]. There are three distinct flower types [5, 3, 4] in this section, so B_1 = 3. Second section [5, 3, 4, 5] also has 3 distinct flower types, so B_2 = 3. The beautiness value resident has associated with the collection is B = B_1 + B_2 = 3 + 3 = 6 After the fourth query, the collection becomes [5, 5, 5, 5, 5]. For the fifth query K = 2 and in this case all the four sections are same with each of them being [5, 5]. Beautiness of [5, 5] is 1 since there is only one distinct element in this section [5]. Beautiness of the whole collection is B = B_1 + B_2 + B_3 + B_4 = 1 + 1 + 1 + 1 = 4
2
13
#include <bits/stdc++.h> using namespace std; inline long long read() { long long x = 0, f = 1; char c = getchar(); while (c < '0' || c > '9') { if (c == '-') f = -1; c = getchar(); } while (c >= '0' && c <= '9') { x = (x << 1) + (x << 3) + c - '0'; c = getchar(); } return x * f; } int a[101010], n, Q; struct Seg_ment { struct node { int l, r; long long sum, add; inline void Add(long long d) { sum += (r - l + 1) * d, add += d; } } tree[101010 << 2]; inline void update(int i) { tree[i].sum = tree[i << 1].sum + tree[i << 1 | 1].sum; } inline void pushdown(int i) { if (tree[i].add) { tree[i << 1].Add(tree[i].add); tree[i << 1 | 1].Add(tree[i].add); tree[i].add = 0; } } void build(int i, int l, int r) { tree[i].l = l; tree[i].r = r; tree[i].add = tree[i].sum = 0; if (l == r) return; int mid = (l + r) >> 1; build(i << 1, l, mid); build(i << 1 | 1, mid + 1, r); } void Plus(int i, int l, int r, int d) { if (tree[i].l >= l && tree[i].r <= r) { tree[i].Add(d); return; } pushdown(i); int mid = (tree[i].l + tree[i].r) >> 1; if (l <= mid) Plus(i << 1, l, r, d); if (r > mid) Plus(i << 1 | 1, l, r, d); update(i); } long long Query(int i, int l, int r) { if (tree[i].l >= l && tree[i].r <= r) { return tree[i].sum; } pushdown(i); int mid = (tree[i].l + tree[i].r) >> 1; long long tot = 0; if (l <= mid) tot += Query(i << 1, l, r); if (r > mid) tot += Query(i << 1 | 1, l, r); return tot; } } T; int tot; map<int, int> id; set<pair<int, int> > s[101010]; set<pair<pair<int, int>, int> > all; void Change(int A, int B, int w) { if (A > B) swap(A, B); T.Plus(1, 1, A, w); if (B < n) T.Plus(1, B + 1, min(n, A + B), -w); } inline void Erase(int l, int r, int u) { all.erase(make_pair(make_pair(l, r), u)); auto it = s[u].lower_bound(make_pair(l, r)); int R = n + 1; if ((++it) != s[u].end()) { R = it->first; } --it, --it; int L = it->second; if (R <= n) { Change(R - r, n - R + 1, -1); Change(R - L, n - R + 1, 1); } ++it; s[u].erase(it); Change(l - L, n - l + 1, -1); if (l < r) { T.Plus(1, 1, 1, -(r - l)); T.Plus(1, n - r + 2, min(n, n - l + 1), 1); } } inline void Insert(int l, int r, int u) { all.insert(make_pair(make_pair(l, r), u)); auto it = s[u].lower_bound(make_pair(l, r)); int R = n + 1; if (it != s[u].end()) { R = it->first; } --it; int L = it->second; if (R <= n) { Change(R - r, n - R + 1, 1); Change(R - L, n - R + 1, -1); } s[u].insert(make_pair(l, r)); Change(l - L, n - l + 1, 1); if (l < r) { T.Plus(1, 1, 1, r - l); T.Plus(1, n - r + 2, min(n, n - l + 1), -1); } } int main() { n = read(), Q = read(); T.build(1, 1, n); for (int i = 1; i <= n; ++i) { a[i] = read(); if (!id.count(a[i])) id[a[i]] = ++tot, s[tot].insert(make_pair(0, 0)); Insert(i, i, id[a[i]]); } while (Q--) { int opt = read(); if (opt == 1) { int l = read(), r = read(), x = read(); if (!id.count(x)) id[x] = ++tot, s[tot].insert(make_pair(0, 0)); x = id[x]; auto it = --all.lower_bound(make_pair(make_pair(l, n + 1), 233)); int itl = it->first.first, itr = it->first.second, itu = it->second; Erase(itl, itr, itu); if (itl < l) { Insert(itl, l - 1, itu); } if (itr > r) { Insert(r + 1, itr, itu); } else { while (true) { it = all.lower_bound(make_pair(make_pair(l, 0), 0)); if (it == all.end() || it->first.second > r) break; Erase(it->first.first, it->first.second, it->second); } if (it != all.end() && it->first.first <= r) { itl = it->first.first, itr = it->first.second, itu = it->second; Erase(itl, itr, itu); Insert(r + 1, itr, itu); } } Insert(l, r, x); } else { int k = read(); printf("%lld\n", T.Query(1, 1, k)); } } return 0; }
CPP
1423_G. Growing flowers
Sarah has always been a lover of nature, and a couple of years ago she saved up enough money to travel the world and explore all the things built by nature over its lifetime on earth. During this time she visited some truly special places which were left untouched for centuries, from watching icebergs in freezing weather to scuba-diving in oceans and admiring the sea life, residing unseen. These experiences were enhanced with breathtaking views built by mountains over time and left there for visitors to see for years on end. Over time, all these expeditions took a toll on Sarah and culminated in her decision to settle down in the suburbs and live a quiet life. However, as Sarah's love for nature never faded, she started growing flowers in her garden in an attempt to stay connected with nature. At the beginning she planted only blue orchids, but over time she started using different flower types to add variety to her collection of flowers. This collection of flowers can be represented as an array of N flowers and the i-th of them has a type associated with it, denoted as A_i. Each resident, passing by her collection and limited by the width of his view, can only see K contiguous flowers at each moment in time. To see the whole collection, the resident will look at the first K contiguous flowers A_1, A_2, ..., A_K, then shift his view by one flower and look at the next section of K contiguous flowers A_2, A_3, ..., A_{K+1} and so on until they scan the whole collection, ending with section A_{N-K+1}, ..., A_{N-1}, A_N. Each resident determines the beautiness of a section of K flowers as the number of distinct flower types in that section. Furthermore, the beautiness of the whole collection is calculated by summing the beautiness values of each contiguous section. Formally, beautiness B_i of a section starting at the i-th position is calculated as B_i = distinct(A_i, A_{i+1}, ..., A_{i+K-1}), and beautiness of the collection B is calculated as B=B_1 + B_2 + ... + B_{N-K+1}. In addition, as Sarah wants to keep her collection of flowers have a fresh feel, she can also pick two points L and R, dispose flowers between those two points and plant new flowers, all of them being the same type. You will be given Q queries and each of those queries will be of the following two types: 1. You will be given three integers L, R, X describing that Sarah has planted flowers of type X between positions L and R inclusive. Formally collection is changed such that A[i]=X for all i in range [L.. R]. 2. You will be given integer K, width of the resident's view and you have to determine the beautiness value B resident has associated with the collection For each query of second type print the result – beautiness B of the collection. Input First line contains two integers N and Q \;(1 ≀ N, Q ≀ 10^5) β€” number of flowers and the number of queries, respectively. The second line contains N integers A_1, A_2, ..., A_N\;(1 ≀ A_i ≀ 10^9) β€” where A_i represents type of the i-th flower. Each of the next Q lines describe queries and start with integer T∈\{1, 2\}. * If T = 1, there will be three more integers in the line L, R, X\;(1 ≀ L, R ≀ N;\; 1 ≀ X ≀ 10^9) β€” L and R describing boundaries and X describing the flower type * If T = 2, there will be one more integer in the line K\;(1 ≀ K ≀ N) β€” resident's width of view Output For each query of the second type print the beautiness B of the collection. Example Input 5 5 1 2 3 4 5 2 3 1 1 2 5 2 4 1 2 4 5 2 2 Output 9 6 4 Note Let's look at the example. Initially the collection is [1, 2, 3, 4, 5]. In the first query K = 3, we consider sections of three flowers with the first being [1, 2, 3]. Since beautiness of the section is the number of distinct flower types in that section, B_1 = 3. Second section is [2, 3, 4] and B_2 = 3. Third section is [3, 4, 5] and B_3 = 3, since the flower types are all distinct. The beautiness value resident has associated with the collection is B = B_1 + B_2 + B_3 = 3 + 3 + 3 = 9. After the second query, the collection becomes [5, 5, 3, 4, 5]. For the third query K = 4, so we consider sections of four flowers with the first being [5, 5, 3, 4]. There are three distinct flower types [5, 3, 4] in this section, so B_1 = 3. Second section [5, 3, 4, 5] also has 3 distinct flower types, so B_2 = 3. The beautiness value resident has associated with the collection is B = B_1 + B_2 = 3 + 3 = 6 After the fourth query, the collection becomes [5, 5, 5, 5, 5]. For the fifth query K = 2 and in this case all the four sections are same with each of them being [5, 5]. Beautiness of [5, 5] is 1 since there is only one distinct element in this section [5]. Beautiness of the whole collection is B = B_1 + B_2 + B_3 + B_4 = 1 + 1 + 1 + 1 = 4
2
13
#include <bits/stdc++.h> const int N = 1e5 + 10; int n, m, a[N], b[N << 1], pre[N], las[N << 1], ql[N], qr[N], qx[N]; long long tk[N << 2], tb[N << 2]; inline void adt(int rt, long long k, long long b) { tk[rt] += k; tb[rt] += b; } inline void pushdown(int rt) { adt(rt << 1, tk[rt], tb[rt]), adt(rt << 1 | 1, tk[rt], tb[rt]), tk[rt] = tb[rt] = 0; } void update(int rt, int l, int r, int ql, int qr, int k, int b) { if (ql <= l && r <= qr) return adt(rt, k, b); int m = (l + r) >> 1; pushdown(rt); if (ql <= m) update(rt << 1, l, m, ql, qr, k, b); if (qr > m) update(rt << 1 | 1, m + 1, r, ql, qr, k, b); } long long query(int rt, int l, int r, int p) { if (l == r) return tk[rt] * p + tb[rt]; int m = (l + r) >> 1; pushdown(rt); return p <= m ? query(rt << 1, l, m, p) : query(rt << 1 | 1, m + 1, r, p); } inline void update(int l, int r, int x) { if (r < 1 || l > n) return; int a = l - pre[l], b = n - r + 1, c = a < b ? a : b, d = a > b ? a : b; update(1, 1, n, 1, c, x, (r - l) * x); if (a < b) update(1, 1, n, a + 1, b, 0, (r - pre[l]) * x); else if (a > b) update(1, 1, n, b + 1, a, 0, (n - l + 1) * x); if (d < n - pre[l]) update(1, 1, n, d + 1, n - pre[l], -x, (n + 1 - pre[l]) * x); } struct node { int l, r, x; node() {} node(int p) : r(p) {} node(int l, int r, int x) : l(l), r(r), x(x) {} bool operator<(const node &x) const { return r < x.r; } }; std::set<node> st[N]; inline void split(std::set<node>::iterator it, int i) { int l = it->l, r = it->r, x = it->x; if (i < l || i >= r) return; st[x].erase(*it); st[x].insert(node(l, i, x)); st[x].insert(node(i + 1, r, x)); st[0].erase(*it); st[0].insert(node(l, i, x)); st[0].insert(node(i + 1, r, x)); } inline void change(int x, int y) { pre[x] = y; } inline void del(node a) { int l = a.l, r = a.r, x = a.x; st[x].erase(a); node ls = *--st[x].lower_bound(node(l)), rs = *st[x].lower_bound(node(r)); update(l, r, -1); change(l, l - 1); update(rs.l, rs.r, -1); change(rs.l, ls.r); update(rs.l, rs.r, 1); st[0].erase(a); } inline void add(node a) { int l = a.l, r = a.r, x = a.x; st[0].insert(a); node ls = *--st[x].lower_bound(node(l)), rs = *st[x].lower_bound(node(r)); change(l, ls.r); update(l, r, 1); update(rs.l, rs.r, -1); change(rs.l, r); update(rs.l, rs.r, 1); st[x].insert(a); } inline void modify(int l, int r, int x) { split(st[0].lower_bound(node(l - 1)), l - 1); split(st[0].lower_bound(node(r)), r); for (std::set<node>::iterator i = st[0].lower_bound(node(l)), ed = st[0].lower_bound(node(r + 1)); i != ed;) del(*i++); add(node(l, r, x)); } int main() { int i, op; scanf("%d%d", &n, &m); for (i = 1; i <= n; i++) scanf("%d", &a[i]), b[++b[0]] = a[i]; for (i = 1; i <= m; i++) scanf("%d", &op), op == 1 ? scanf("%d%d%d", &ql[i], &qr[i], &qx[i]), b[++b[0]] = qx[i] : scanf("%d", &qx[i]); std::sort(b + 1, b + 1 + b[0]); b[0] = std::unique(b + 1, b + 1 + b[0]) - b - 1; for (i = 0; i <= b[0]; i++) st[i].insert(node(0, 0, i)), st[i].insert(node(n + 1, n + 1, i)); for (i = 1; i <= n; i++) a[i] = std::lower_bound(b + 1, b + 1 + b[0], a[i]) - b, pre[i] = las[a[i]], las[a[i]] = i, st[0].insert(node(i, i, a[i])), st[a[i]].insert(node(i, i, a[i])), update(i, i, 1); for (i = 1; i <= m; i++) if (qr[i]) modify(ql[i], qr[i], std::lower_bound(b + 1, b + 1 + b[0], qx[i]) - b); else printf("%lld\n", query(1, 1, n, qx[i])); return 0; }
CPP
1423_G. Growing flowers
Sarah has always been a lover of nature, and a couple of years ago she saved up enough money to travel the world and explore all the things built by nature over its lifetime on earth. During this time she visited some truly special places which were left untouched for centuries, from watching icebergs in freezing weather to scuba-diving in oceans and admiring the sea life, residing unseen. These experiences were enhanced with breathtaking views built by mountains over time and left there for visitors to see for years on end. Over time, all these expeditions took a toll on Sarah and culminated in her decision to settle down in the suburbs and live a quiet life. However, as Sarah's love for nature never faded, she started growing flowers in her garden in an attempt to stay connected with nature. At the beginning she planted only blue orchids, but over time she started using different flower types to add variety to her collection of flowers. This collection of flowers can be represented as an array of N flowers and the i-th of them has a type associated with it, denoted as A_i. Each resident, passing by her collection and limited by the width of his view, can only see K contiguous flowers at each moment in time. To see the whole collection, the resident will look at the first K contiguous flowers A_1, A_2, ..., A_K, then shift his view by one flower and look at the next section of K contiguous flowers A_2, A_3, ..., A_{K+1} and so on until they scan the whole collection, ending with section A_{N-K+1}, ..., A_{N-1}, A_N. Each resident determines the beautiness of a section of K flowers as the number of distinct flower types in that section. Furthermore, the beautiness of the whole collection is calculated by summing the beautiness values of each contiguous section. Formally, beautiness B_i of a section starting at the i-th position is calculated as B_i = distinct(A_i, A_{i+1}, ..., A_{i+K-1}), and beautiness of the collection B is calculated as B=B_1 + B_2 + ... + B_{N-K+1}. In addition, as Sarah wants to keep her collection of flowers have a fresh feel, she can also pick two points L and R, dispose flowers between those two points and plant new flowers, all of them being the same type. You will be given Q queries and each of those queries will be of the following two types: 1. You will be given three integers L, R, X describing that Sarah has planted flowers of type X between positions L and R inclusive. Formally collection is changed such that A[i]=X for all i in range [L.. R]. 2. You will be given integer K, width of the resident's view and you have to determine the beautiness value B resident has associated with the collection For each query of second type print the result – beautiness B of the collection. Input First line contains two integers N and Q \;(1 ≀ N, Q ≀ 10^5) β€” number of flowers and the number of queries, respectively. The second line contains N integers A_1, A_2, ..., A_N\;(1 ≀ A_i ≀ 10^9) β€” where A_i represents type of the i-th flower. Each of the next Q lines describe queries and start with integer T∈\{1, 2\}. * If T = 1, there will be three more integers in the line L, R, X\;(1 ≀ L, R ≀ N;\; 1 ≀ X ≀ 10^9) β€” L and R describing boundaries and X describing the flower type * If T = 2, there will be one more integer in the line K\;(1 ≀ K ≀ N) β€” resident's width of view Output For each query of the second type print the beautiness B of the collection. Example Input 5 5 1 2 3 4 5 2 3 1 1 2 5 2 4 1 2 4 5 2 2 Output 9 6 4 Note Let's look at the example. Initially the collection is [1, 2, 3, 4, 5]. In the first query K = 3, we consider sections of three flowers with the first being [1, 2, 3]. Since beautiness of the section is the number of distinct flower types in that section, B_1 = 3. Second section is [2, 3, 4] and B_2 = 3. Third section is [3, 4, 5] and B_3 = 3, since the flower types are all distinct. The beautiness value resident has associated with the collection is B = B_1 + B_2 + B_3 = 3 + 3 + 3 = 9. After the second query, the collection becomes [5, 5, 3, 4, 5]. For the third query K = 4, so we consider sections of four flowers with the first being [5, 5, 3, 4]. There are three distinct flower types [5, 3, 4] in this section, so B_1 = 3. Second section [5, 3, 4, 5] also has 3 distinct flower types, so B_2 = 3. The beautiness value resident has associated with the collection is B = B_1 + B_2 = 3 + 3 = 6 After the fourth query, the collection becomes [5, 5, 5, 5, 5]. For the fifth query K = 2 and in this case all the four sections are same with each of them being [5, 5]. Beautiness of [5, 5] is 1 since there is only one distinct element in this section [5]. Beautiness of the whole collection is B = B_1 + B_2 + B_3 + B_4 = 1 + 1 + 1 + 1 = 4
2
13
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 5, M = 1e3 + 5; const long long INF = 1e18 + 5; inline long long read() { long long sum = 0, fh = 1; char c = getchar(); while (c < '0' || c > '9') { if (c == '-') fh = -1; c = getchar(); } while (c >= '0' && c <= '9') { sum = sum * 10 + c - '0'; c = getchar(); } return sum * fh; } inline int read2() { char c = getchar(); while (c != 'a' && c != 'b' && c != 'c' && c != '?') c = getchar(); return c == '?' ? 0 : c - 'a' + 1; } inline int read3() { char c = getchar(); while (c < 'a' || c > 'z') { c = getchar(); } return c - 'a'; } inline void write(long long x) { if (x < 0) putchar('-'), x = -x; if (x > 9) write(x / 10); putchar(x % 10 + '0'); } inline int gcd(int x, int y) { return y == 0 ? x : gcd(y, x % y); } inline long long ab(long long x) { return x < 0 ? -x : x; } inline long long fpow(long long qwe, long long asd, long long zxc) { if (asd < 0) return 0; long long a = qwe, b = 1, c = asd; while (c) { if (c & 1) b = b * a % zxc; a = a * a % zxc; c >>= 1; } return b; } struct miaow { int l, r; long long sz, sum; } t[N * 4 + 5]; inline void csh(int l, int r, int o) { t[o].l = l, t[o].r = r; t[o].sz = t[o].sum = 0; if (l == r) { return; } int mid = (l + r) >> 1; csh(l, mid, (o * 2)), csh(mid + 1, r, (o * 2 + 1)); } inline void xg(int k, int o, int x) { if (t[o].l == t[o].r) { t[o].sz += x; t[o].sum = t[o].l * t[o].sz; return; } int mid = (t[o].l + t[o].r) >> 1; if (k <= mid) xg(k, (o * 2), x); else xg(k, (o * 2 + 1), x); t[o].sz = t[(o * 2)].sz + t[(o * 2 + 1)].sz; t[o].sum = t[(o * 2)].sum + t[(o * 2 + 1)].sum; } inline pair<long long, long long> cx(int l, int r, int o) { if (l <= t[o].l && r >= t[o].r) return pair<long long, long long>(t[o].sz, t[o].sum); pair<long long, long long> qwe(0, 0), asd(0, 0); int mid = (t[o].l + t[o].r) >> 1; if (l <= mid) qwe = cx(l, min(mid, r), (o * 2)); if (r > mid) asd = cx(max(mid + 1, l), r, (o * 2 + 1)); return pair<long long, long long>(qwe.first + asd.first, qwe.second + asd.second); } struct meow { int l, r; int sz; meow(int l1 = 0, int r1 = 0, int sz1 = 0) { l = l1, r = r1, sz = sz1; } inline bool operator<(const meow& qwe) const { return l < qwe.l; } }; set<meow> wz[N], odt; inline void del(int l, int r, int x) { set<meow>::iterator qwe, asd, zxc; qwe = asd = zxc = wz[x].lower_bound(meow(l, r, x)); --qwe, ++zxc; int l1 = qwe->l, r1 = qwe->r, l2 = asd->l, r2 = asd->r, l3 = zxc->l, r3 = zxc->r; xg(l2 - r1, 1, -1), xg(l3 - r2, 1, -1); xg(l3 - r1, 1, 1); wz[x].erase(asd); } inline void ins(int l, int r, int x) { set<meow>::iterator qwe, asd, zxc; qwe = asd = zxc = wz[x].insert(meow(l, r, x)).first; --qwe, ++zxc; int r1 = qwe->r, l3 = zxc->l; xg(l3 - r1, 1, -1); xg(l - r1, 1, 1), xg(l3 - r, 1, 1); } inline void cr(int l, int r, int x) { set<meow>::iterator qwe = odt.upper_bound(meow(l)), asd = odt.upper_bound(meow(r)); --qwe, --asd; if (qwe == asd) { int l1 = qwe->l, r1 = qwe->r, sz1 = qwe->sz; del(l1, r1, sz1); odt.erase(qwe); if (l1 == l) { if (r1 == r) { odt.insert(meow(l, r, x)); ins(l, r, x); } else { odt.insert(meow(l, r, x)); ins(l, r, x); odt.insert(meow(r + 1, r1, sz1)); ins(r + 1, r1, sz1); } } else { if (r1 == r) { odt.insert(meow(l, r, x)); ins(l, r, x); odt.insert(meow(l1, l - 1, sz1)); ins(l1, l - 1, sz1); } else { odt.insert(meow(l, r, x)); ins(l, r, x); odt.insert(meow(l1, l - 1, sz1)); ins(l1, l - 1, sz1); odt.insert(meow(r + 1, r1, sz1)); ins(r + 1, r1, sz1); } } } else { int l1 = qwe->l, r1 = qwe->r, sz1 = qwe->sz, l2 = asd->l, r2 = asd->r, sz2 = asd->sz; del(l1, r1, sz1), del(l2, r2, sz2); set<meow>::iterator i = qwe; ++i; for (; i != asd; ++i) { int l3 = i->l, r3 = i->r, sz3 = i->sz; del(l3, r3, sz3); } ++asd; odt.erase(qwe, asd); odt.insert(meow(l, r, x)); ins(l, r, x); if (l1 != l) { odt.insert(meow(l1, l - 1, sz1)); ins(l1, l - 1, sz1); } if (r2 != r) { odt.insert(meow(r + 1, r2, sz2)); ins(r + 1, r2, sz2); } } } map<int, int> ls; struct nya { int o, l, r, x; nya(int o1 = 0, int l1 = 0, int r1 = 0, int x1 = 0) { o = o1, l = l1, r = r1, x = x1; } } q[N]; int lxsz[N], lxcou = 0, lxjs = 0; int a[N], n, m; inline void lxh() { sort(lxsz + 1, lxsz + lxcou + 1); int sz = 0; for (int i = 1; i <= lxcou; ++i) { if (lxsz[i] != sz) { sz = lxsz[i]; ++lxjs; ls[sz] = lxjs; } } } int main() { n = read(), m = read(); for (int i = 1; i <= n; ++i) { a[i] = read(); lxsz[++lxcou] = a[i]; } for (int i = 1; i <= m; ++i) { int o = read(), l, r, x; if (o == 1) { l = read(), r = read(), x = read(); lxsz[++lxcou] = x; q[i] = nya(o, l, r, x); } else { x = read(); q[i] = nya(o, 0, 0, x); } } lxh(); csh(1, n + 1, 1); for (int i = 1; i <= lxjs; ++i) { wz[i].insert(meow(0, 0, i)); wz[i].insert(meow(n + 1, n + 1, i)); xg(n + 1, 1, 1); } for (int i = 1; i <= n; ++i) { a[i] = ls[a[i]]; odt.insert(meow(i, i, a[i])); ins(i, i, a[i]); } for (int i = 1; i <= m; ++i) { int o = q[i].o, l = q[i].l, r = q[i].r; long long x = q[i].x; if (o == 1) { x = ls[x]; cr(l, r, x); } else { long long ans = 1ll * lxjs * (n - x + 1); pair<long long, long long> qwe = cx(x, n + 1, 1); ans -= qwe.second - qwe.first * x; write(ans), putchar('\n'); } } }
CPP
1423_G. Growing flowers
Sarah has always been a lover of nature, and a couple of years ago she saved up enough money to travel the world and explore all the things built by nature over its lifetime on earth. During this time she visited some truly special places which were left untouched for centuries, from watching icebergs in freezing weather to scuba-diving in oceans and admiring the sea life, residing unseen. These experiences were enhanced with breathtaking views built by mountains over time and left there for visitors to see for years on end. Over time, all these expeditions took a toll on Sarah and culminated in her decision to settle down in the suburbs and live a quiet life. However, as Sarah's love for nature never faded, she started growing flowers in her garden in an attempt to stay connected with nature. At the beginning she planted only blue orchids, but over time she started using different flower types to add variety to her collection of flowers. This collection of flowers can be represented as an array of N flowers and the i-th of them has a type associated with it, denoted as A_i. Each resident, passing by her collection and limited by the width of his view, can only see K contiguous flowers at each moment in time. To see the whole collection, the resident will look at the first K contiguous flowers A_1, A_2, ..., A_K, then shift his view by one flower and look at the next section of K contiguous flowers A_2, A_3, ..., A_{K+1} and so on until they scan the whole collection, ending with section A_{N-K+1}, ..., A_{N-1}, A_N. Each resident determines the beautiness of a section of K flowers as the number of distinct flower types in that section. Furthermore, the beautiness of the whole collection is calculated by summing the beautiness values of each contiguous section. Formally, beautiness B_i of a section starting at the i-th position is calculated as B_i = distinct(A_i, A_{i+1}, ..., A_{i+K-1}), and beautiness of the collection B is calculated as B=B_1 + B_2 + ... + B_{N-K+1}. In addition, as Sarah wants to keep her collection of flowers have a fresh feel, she can also pick two points L and R, dispose flowers between those two points and plant new flowers, all of them being the same type. You will be given Q queries and each of those queries will be of the following two types: 1. You will be given three integers L, R, X describing that Sarah has planted flowers of type X between positions L and R inclusive. Formally collection is changed such that A[i]=X for all i in range [L.. R]. 2. You will be given integer K, width of the resident's view and you have to determine the beautiness value B resident has associated with the collection For each query of second type print the result – beautiness B of the collection. Input First line contains two integers N and Q \;(1 ≀ N, Q ≀ 10^5) β€” number of flowers and the number of queries, respectively. The second line contains N integers A_1, A_2, ..., A_N\;(1 ≀ A_i ≀ 10^9) β€” where A_i represents type of the i-th flower. Each of the next Q lines describe queries and start with integer T∈\{1, 2\}. * If T = 1, there will be three more integers in the line L, R, X\;(1 ≀ L, R ≀ N;\; 1 ≀ X ≀ 10^9) β€” L and R describing boundaries and X describing the flower type * If T = 2, there will be one more integer in the line K\;(1 ≀ K ≀ N) β€” resident's width of view Output For each query of the second type print the beautiness B of the collection. Example Input 5 5 1 2 3 4 5 2 3 1 1 2 5 2 4 1 2 4 5 2 2 Output 9 6 4 Note Let's look at the example. Initially the collection is [1, 2, 3, 4, 5]. In the first query K = 3, we consider sections of three flowers with the first being [1, 2, 3]. Since beautiness of the section is the number of distinct flower types in that section, B_1 = 3. Second section is [2, 3, 4] and B_2 = 3. Third section is [3, 4, 5] and B_3 = 3, since the flower types are all distinct. The beautiness value resident has associated with the collection is B = B_1 + B_2 + B_3 = 3 + 3 + 3 = 9. After the second query, the collection becomes [5, 5, 3, 4, 5]. For the third query K = 4, so we consider sections of four flowers with the first being [5, 5, 3, 4]. There are three distinct flower types [5, 3, 4] in this section, so B_1 = 3. Second section [5, 3, 4, 5] also has 3 distinct flower types, so B_2 = 3. The beautiness value resident has associated with the collection is B = B_1 + B_2 = 3 + 3 = 6 After the fourth query, the collection becomes [5, 5, 5, 5, 5]. For the fifth query K = 2 and in this case all the four sections are same with each of them being [5, 5]. Beautiness of [5, 5] is 1 since there is only one distinct element in this section [5]. Beautiness of the whole collection is B = B_1 + B_2 + B_3 + B_4 = 1 + 1 + 1 + 1 = 4
2
13
#include <bits/stdc++.h> using namespace std; const long long N = 2e5 + 5; long long read() { long long s = 0; char c = getchar(), lc = '+'; while (c < '0' || '9' < c) lc = c, c = getchar(); while ('0' <= c && c <= '9') s = s * 10 + c - '0', c = getchar(); return lc == '-' ? -s : s; } void write(long long x) { if (x < 0) putchar('-'), x = -x; if (x < 10) putchar(x + '0'); else write(x / 10), putchar(x % 10 + '0'); } void print(long long x, char c = '\n') { write(x); putchar(c); } struct segment_tree { long long tot[N * 4], sum[N * 4], tag[N * 4]; void update(long long w, long long l, long long r, long long y) { tag[w] += y; tot[w] += y * (r - l + 1); sum[w] += (l + r) * (r - l + 1) / 2 * y; } void push_up(long long w) { tot[w] = tot[(w * 2)] + tot[(w * 2 + 1)]; sum[w] = sum[(w * 2)] + sum[(w * 2 + 1)]; } void push_down(long long w, long long l, long long r) { if (!tag[w]) return; update((w * 2), l, ((l + r) / 2), tag[w]); update((w * 2 + 1), ((l + r) / 2) + 1, r, tag[w]); tag[w] = 0; } void add(long long w, long long l, long long r, long long ql, long long qr, long long y) { if (qr < l || r < ql) return; if (ql <= l && r <= qr) return update(w, l, r, y); push_down(w, l, r); if (ql <= ((l + r) / 2)) add((w * 2), l, ((l + r) / 2), ql, qr, y); if (qr > ((l + r) / 2)) add((w * 2 + 1), ((l + r) / 2) + 1, r, ql, qr, y); push_up(w); } void add(long long w, long long l, long long r, long long x, long long y) { add(w, l, r, x, x, y); } long long querytot(long long w, long long l, long long r, long long ql, long long qr) { if (qr < l || r < ql) return 0; if (ql <= l && r <= qr) return tot[w]; push_down(w, l, r); return querytot((w * 2), l, ((l + r) / 2), ql, qr) + querytot((w * 2 + 1), ((l + r) / 2) + 1, r, ql, qr); } long long querysum(long long w, long long l, long long r, long long ql, long long qr) { if (qr < l || r < ql) return 0; if (ql <= l && r <= qr) return sum[w]; push_down(w, l, r); return querysum((w * 2), l, ((l + r) / 2), ql, qr) + querysum((w * 2 + 1), ((l + r) / 2) + 1, r, ql, qr); } } t, tl, tr; struct Query { long long opt, l, r, x; } q[N]; struct node { long long l, r, x; bool operator<(const node &a) const { return l == a.l ? r < a.r : l < a.l; } }; set<node> s, c[N]; long long a[N], b[N], last[N]; signed main() { long long n = read(), m = read(), cnt = n; for (long long i = 1; i <= n; i++) b[i] = a[i] = read(); for (long long i = 1; i <= m; i++) { q[i].opt = read(); if (q[i].opt == 1) q[i].l = read(), q[i].r = read(), b[++cnt] = q[i].x = read(); else q[i].x = read(); } sort(b + 1, b + 1 + cnt); cnt = unique(b + 1, b + 1 + cnt) - b - 1; for (long long i = 1; i <= n; i++) a[i] = lower_bound(b + 1, b + 1 + cnt, a[i]) - b; for (long long i = 1; i <= m; i++) if (q[i].opt == 1) q[i].x = lower_bound(b + 1, b + 1 + cnt, q[i].x) - b; for (long long i = 1; i <= n; i++) s.insert((node){i, i, a[i]}); for (long long i = 1; i <= n; i++) c[a[i]].insert((node){i, i, a[i]}); for (long long i = 1; i <= n; i++) { t.add(1, 1, n, i - last[a[i]], 1); tl.add(1, 1, n, last[a[i]], 1); tr.add(1, 1, n, i, 1); last[a[i]] = i; } for (long long i = 1; i <= cnt; i++) c[i].insert((node){0, 0, i}); for (long long i = 1; i <= m; i++) if (q[i].opt == 1) { long long l = q[i].l, r = q[i].r, x = q[i].x; auto tmp = s.upper_bound((node){l, n, 0}); tmp--; if ((tmp->l) != l) { c[tmp->x].insert((node){tmp->l, l - 1, tmp->x}); c[tmp->x].insert((node){l, tmp->r, tmp->x}); c[tmp->x].erase(*tmp); s.insert((node){tmp->l, l - 1, tmp->x}); s.insert((node){l, tmp->r, tmp->x}); s.erase(tmp); } tmp = s.upper_bound((node){r, n, 0}); tmp--; if ((tmp->r) != r) { c[tmp->x].insert((node){tmp->l, r, tmp->x}); c[tmp->x].insert((node){r + 1, tmp->r, tmp->x}); c[tmp->x].erase(*tmp); s.insert((node){tmp->l, r, tmp->x}); s.insert((node){r + 1, tmp->r, tmp->x}); s.erase(tmp); } auto now = s.lower_bound((node){l, 0, 0}); while (now != s.end() && (now->r) <= r) { auto nxt = now; nxt++; auto M = c[now->x].lower_bound(*now), L = M, R = M; L--, R++; t.add(1, 1, n, 1, (M->l) - (M->r)); tl.add(1, 1, n, (M->l), (M->r) - 1, -1); tr.add(1, 1, n, (M->l) + 1, M->r, -1); t.add(1, 1, n, (M->l) - (L->r), -1); tl.add(1, 1, n, L->r, -1); tr.add(1, 1, n, M->l, -1); if (R != c[now->x].end()) { t.add(1, 1, n, (R->l) - (M->r), -1); tl.add(1, 1, n, M->r, -1); tr.add(1, 1, n, R->l, -1); t.add(1, 1, n, (R->l) - (L->r), 1); tl.add(1, 1, n, L->r, 1); tr.add(1, 1, n, R->l, 1); } c[now->x].erase(M); s.erase(now); now = nxt; } c[x].insert((node){l, r, x}); s.insert((node){l, r, x}); auto M = c[x].lower_bound((node){l, r, x}), L = M, R = M; L--, R++; t.add(1, 1, n, 1, (M->r) - (M->l)); tl.add(1, 1, n, (M->l), (M->r) - 1, 1); tr.add(1, 1, n, (M->l) + 1, M->r, 1); t.add(1, 1, n, (M->l) - (L->r), 1); tl.add(1, 1, n, L->r, 1); tr.add(1, 1, n, M->l, 1); if (R != c[x].end()) { t.add(1, 1, n, (R->l) - (M->r), 1); tl.add(1, 1, n, M->r, 1); tr.add(1, 1, n, R->l, 1); t.add(1, 1, n, (R->l) - (L->r), -1); tl.add(1, 1, n, L->r, -1); tr.add(1, 1, n, R->l, -1); } } else print(t.querysum(1, 1, n, 1, q[i].x) + t.querytot(1, 1, n, q[i].x + 1, n) * q[i].x - (tr.querysum(1, 1, n, n - q[i].x + 1, n) - tr.querytot(1, 1, n, n - q[i].x + 1, n) * (n - q[i].x + 1)) + (tl.querysum(1, 1, n, n - q[i].x + 1, n) - tl.querytot(1, 1, n, n - q[i].x + 1, n) * (n - q[i].x + 1))); return 0; }
CPP
1423_G. Growing flowers
Sarah has always been a lover of nature, and a couple of years ago she saved up enough money to travel the world and explore all the things built by nature over its lifetime on earth. During this time she visited some truly special places which were left untouched for centuries, from watching icebergs in freezing weather to scuba-diving in oceans and admiring the sea life, residing unseen. These experiences were enhanced with breathtaking views built by mountains over time and left there for visitors to see for years on end. Over time, all these expeditions took a toll on Sarah and culminated in her decision to settle down in the suburbs and live a quiet life. However, as Sarah's love for nature never faded, she started growing flowers in her garden in an attempt to stay connected with nature. At the beginning she planted only blue orchids, but over time she started using different flower types to add variety to her collection of flowers. This collection of flowers can be represented as an array of N flowers and the i-th of them has a type associated with it, denoted as A_i. Each resident, passing by her collection and limited by the width of his view, can only see K contiguous flowers at each moment in time. To see the whole collection, the resident will look at the first K contiguous flowers A_1, A_2, ..., A_K, then shift his view by one flower and look at the next section of K contiguous flowers A_2, A_3, ..., A_{K+1} and so on until they scan the whole collection, ending with section A_{N-K+1}, ..., A_{N-1}, A_N. Each resident determines the beautiness of a section of K flowers as the number of distinct flower types in that section. Furthermore, the beautiness of the whole collection is calculated by summing the beautiness values of each contiguous section. Formally, beautiness B_i of a section starting at the i-th position is calculated as B_i = distinct(A_i, A_{i+1}, ..., A_{i+K-1}), and beautiness of the collection B is calculated as B=B_1 + B_2 + ... + B_{N-K+1}. In addition, as Sarah wants to keep her collection of flowers have a fresh feel, she can also pick two points L and R, dispose flowers between those two points and plant new flowers, all of them being the same type. You will be given Q queries and each of those queries will be of the following two types: 1. You will be given three integers L, R, X describing that Sarah has planted flowers of type X between positions L and R inclusive. Formally collection is changed such that A[i]=X for all i in range [L.. R]. 2. You will be given integer K, width of the resident's view and you have to determine the beautiness value B resident has associated with the collection For each query of second type print the result – beautiness B of the collection. Input First line contains two integers N and Q \;(1 ≀ N, Q ≀ 10^5) β€” number of flowers and the number of queries, respectively. The second line contains N integers A_1, A_2, ..., A_N\;(1 ≀ A_i ≀ 10^9) β€” where A_i represents type of the i-th flower. Each of the next Q lines describe queries and start with integer T∈\{1, 2\}. * If T = 1, there will be three more integers in the line L, R, X\;(1 ≀ L, R ≀ N;\; 1 ≀ X ≀ 10^9) β€” L and R describing boundaries and X describing the flower type * If T = 2, there will be one more integer in the line K\;(1 ≀ K ≀ N) β€” resident's width of view Output For each query of the second type print the beautiness B of the collection. Example Input 5 5 1 2 3 4 5 2 3 1 1 2 5 2 4 1 2 4 5 2 2 Output 9 6 4 Note Let's look at the example. Initially the collection is [1, 2, 3, 4, 5]. In the first query K = 3, we consider sections of three flowers with the first being [1, 2, 3]. Since beautiness of the section is the number of distinct flower types in that section, B_1 = 3. Second section is [2, 3, 4] and B_2 = 3. Third section is [3, 4, 5] and B_3 = 3, since the flower types are all distinct. The beautiness value resident has associated with the collection is B = B_1 + B_2 + B_3 = 3 + 3 + 3 = 9. After the second query, the collection becomes [5, 5, 3, 4, 5]. For the third query K = 4, so we consider sections of four flowers with the first being [5, 5, 3, 4]. There are three distinct flower types [5, 3, 4] in this section, so B_1 = 3. Second section [5, 3, 4, 5] also has 3 distinct flower types, so B_2 = 3. The beautiness value resident has associated with the collection is B = B_1 + B_2 = 3 + 3 = 6 After the fourth query, the collection becomes [5, 5, 5, 5, 5]. For the fifth query K = 2 and in this case all the four sections are same with each of them being [5, 5]. Beautiness of [5, 5] is 1 since there is only one distinct element in this section [5]. Beautiness of the whole collection is B = B_1 + B_2 + B_3 + B_4 = 1 + 1 + 1 + 1 = 4
2
13
#include <bits/stdc++.h> using namespace std; template <typename T> void read(T &x) { x = 0; int f = 1; char ch = getchar(); while (!isdigit(ch)) { if (ch == '-') f = -1; ch = getchar(); } while (isdigit(ch)) { x = x * 10 + ch - '0'; ch = getchar(); } x *= f; } inline void write(long long x) { if (x > 9) write(x / 10); putchar(x % 10 + '0'); } const int N = 100005, Q = 100005; int n; struct BIT { long long d[N]; inline void add(int x, long long v) { while (x <= n) d[x] += v, x += x & -x; } inline long long ask(int x) { static long long r; r = 0; while (x) r += d[x], x -= x & -x; return r; } inline void modify(int l, int r, long long v) { if (l > r) return; add(l, v), add(r + 1, -v); } }; struct DataStructure { BIT T1, T2; inline void add(int l) { T1.modify(1, l, -1), T2.modify(1, l, l + 1); } inline void del(int l) { T1.modify(1, l, 1), T2.modify(1, l, -(l + 1)); } inline long long ask(int x) { long long r = x * T1.ask(x) + T2.ask(x); return r; } } DS; struct Line { int l, r; Line(int ll = -1, int rr = -1) { l = ll, r = rr; } bool operator<(Line w) const { return l < w.l; } }; set<Line> T[N + Q]; inline void addval(int l, int r, int v) { if (v <= 0 || r < 0) return; static int L, R, l1, l2, l3; static set<Line>::iterator it2, it; it = T[v].find(Line(l, r)); if (it->l != l || it->r != r) assert(0); if (it == T[v].begin()) L = 0; else { it2 = it, --it2, L = it2->r; } it2 = it, ++it2; if (it2 == T[v].end()) R = n + 1; else R = it2->l; R = n + 1; l2 = r - l + 1, l1 = l - L - 1, l3 = R - r - 1, DS.del(l1), DS.del(l3), DS.add(l1 + l2 + l3); } inline void devval(int l, int r, int v) { if (v <= 0 || r < 0) return; static int L, R, l1, l2, l3; static set<Line>::iterator it2, it; it = T[v].find(Line(l, r)); if (it->l != l || it->r != r) assert(0); if (it == T[v].begin()) L = 0; else { it2 = it, --it2, L = it2->r; } it2 = it, ++it2; if (it2 == T[v].end()) R = n + 1; else R = it2->l; R = n + 1; l2 = r - l + 1, l1 = l - L - 1, l3 = R - r - 1, DS.add(l1), DS.add(l3), DS.del(l1 + l2 + l3); } inline void addc(int l, int r, int v) { if (v <= 0) return; static int l1, r1, l2, r2; l1 = r1 = l2 = r2 = -1; static set<Line>::iterator it; it = T[v].insert(Line(l, r)).first; if (it != T[v].begin()) { --it; l1 = it->l, r1 = it->r; ++it; } if ((++it) != T[v].end()) { l2 = it->l, r2 = it->r; } --it; T[v].erase(it); devval(l1, r1, v), devval(l2, r2, v); T[v].insert(Line(l, r)); addval(l1, r1, v), addval(l2, r2, v); addval(l, r, v); } inline void devc(int l, int r, int v) { if (v <= 0) return; static int l1, r1, l2, r2; l1 = r1 = l2 = r2 = -1; static set<Line>::iterator it; it = T[v].find(Line(l, r)); if (it->l != l || it->r != r) assert(0); if (it != T[v].begin()) { --it; l1 = it->l, r1 = it->r; ++it; } if ((++it) != T[v].end()) { l2 = it->l, r2 = it->r; } --it; devval(l1, r1, v), devval(l2, r2, v), devval(l, r, v); T[v].erase(T[v].find(Line(l, r))); addval(l1, r1, v), addval(l2, r2, v); } struct Node { int l, r, v; Node(int ll = -1, int rr = -1, int vv = -1) { l = ll, r = rr, v = vv; } bool operator<(Node w) const { return l < w.l; } }; set<Node> S; int v[N << 1], lv; int q, a[N], qt[Q], ql[Q], qr[Q], qx[Q]; inline set<Node>::iterator spilt(int p) { static set<Node>::iterator it; it = S.upper_bound(Node(p)); --it; if (it->l == p) return it; static int L, R, V; L = it->l, R = it->r, V = it->v; devc(L, R, V), S.erase(it); S.insert(Node(L, p - 1, V)); addc(L, p - 1, V); addc(p, R, V); return S.insert(Node(p, R, V)).first; } inline void merge(int l, int r, int v) { if (v <= 0) return; static set<Node>::iterator it, it2; static bool fl, fr; static int L, R; fl = fr = 0, it = S.find(Node(l, r)); if (it != S.begin()) { it2 = it, --it2; if (it2->v == v) fl = 1; } it2 = it, ++it2; if (it2 != S.end() && it2->v == v) fr = 1; if (!fl && !fr) return; while (fl || fr) { if (fl) { it2 = it, --it2; L = it2->l, R = r; devc(it->l, it->r, it->v), devc(it2->l, it2->r, it2->v); S.erase(it), S.erase(it2), fl = fr = 0, it = S.insert(Node(L, R, v)).first; l = L, r = R, addc(it->l, it->r, it->v); if (it != S.begin()) { it2 = it, --it2; if (it2->v == v) fl = 1; } it2 = it, ++it2; if (it2 != S.end() && it2->v == v) fr = 1; continue; } if (fr) { it2 = it, ++it2; L = l, R = it2->r; devc(it->l, it->r, it->v), devc(it2->l, it2->r, it2->v); S.erase(it), S.erase(it2), fl = fr = 0, it = S.insert(Node(L, R, v)).first; l = L, r = R, addc(it->l, it->r, it->v); if (it != S.begin()) { it2 = it, --it2; if (it2->v == v) fl = 1; } it2 = it, ++it2; if (it2 != S.end() && it2->v == v) fr = 1; continue; } } } inline void change(int l, int r, int v) { static set<Node>::iterator itl, itr, it; itr = spilt(r + 1), itl = spilt(l); for (it = itl; it != itr; ++it) devc(it->l, it->r, it->v); S.erase(itl, itr); S.insert(Node(l, r, v)), addc(l, r, v); if (v) merge(l, r, v); } int main() { int i; read(n), read(q); for (i = 1; i <= n; ++i) read(a[i]), v[i] = a[i]; lv = n; for (i = 1; i <= q; ++i) { read(qt[i]); if (qt[i] == 1) { read(ql[i]), read(qr[i]), read(qx[i]); v[++lv] = qx[i]; } else read(qx[i]); } sort(v + 1, v + lv + 1), lv = unique(v + 1, v + lv + 1) - (v + 1); for (i = 1; i <= n; ++i) a[i] = lower_bound(v + 1, v + lv + 1, a[i]) - v; for (i = 1; i <= q; ++i) if (qt[i] == 1) qx[i] = lower_bound(v + 1, v + lv + 1, qx[i]) - v; S.insert(Node(0, 0, 0)); S.insert(Node(n + 1, n + 1, 0)); for (i = 1; i <= n; ++i) S.insert(Node(i, i, 0)); for (i = 1; i <= n; ++i) change(i, i, a[i]); for (i = 1; i <= q; ++i) { if (qt[i] == 2) { write(DS.ask(qx[i])), putchar('\n'); continue; } change(ql[i], qr[i], qx[i]); } return 0; }
CPP
1423_G. Growing flowers
Sarah has always been a lover of nature, and a couple of years ago she saved up enough money to travel the world and explore all the things built by nature over its lifetime on earth. During this time she visited some truly special places which were left untouched for centuries, from watching icebergs in freezing weather to scuba-diving in oceans and admiring the sea life, residing unseen. These experiences were enhanced with breathtaking views built by mountains over time and left there for visitors to see for years on end. Over time, all these expeditions took a toll on Sarah and culminated in her decision to settle down in the suburbs and live a quiet life. However, as Sarah's love for nature never faded, she started growing flowers in her garden in an attempt to stay connected with nature. At the beginning she planted only blue orchids, but over time she started using different flower types to add variety to her collection of flowers. This collection of flowers can be represented as an array of N flowers and the i-th of them has a type associated with it, denoted as A_i. Each resident, passing by her collection and limited by the width of his view, can only see K contiguous flowers at each moment in time. To see the whole collection, the resident will look at the first K contiguous flowers A_1, A_2, ..., A_K, then shift his view by one flower and look at the next section of K contiguous flowers A_2, A_3, ..., A_{K+1} and so on until they scan the whole collection, ending with section A_{N-K+1}, ..., A_{N-1}, A_N. Each resident determines the beautiness of a section of K flowers as the number of distinct flower types in that section. Furthermore, the beautiness of the whole collection is calculated by summing the beautiness values of each contiguous section. Formally, beautiness B_i of a section starting at the i-th position is calculated as B_i = distinct(A_i, A_{i+1}, ..., A_{i+K-1}), and beautiness of the collection B is calculated as B=B_1 + B_2 + ... + B_{N-K+1}. In addition, as Sarah wants to keep her collection of flowers have a fresh feel, she can also pick two points L and R, dispose flowers between those two points and plant new flowers, all of them being the same type. You will be given Q queries and each of those queries will be of the following two types: 1. You will be given three integers L, R, X describing that Sarah has planted flowers of type X between positions L and R inclusive. Formally collection is changed such that A[i]=X for all i in range [L.. R]. 2. You will be given integer K, width of the resident's view and you have to determine the beautiness value B resident has associated with the collection For each query of second type print the result – beautiness B of the collection. Input First line contains two integers N and Q \;(1 ≀ N, Q ≀ 10^5) β€” number of flowers and the number of queries, respectively. The second line contains N integers A_1, A_2, ..., A_N\;(1 ≀ A_i ≀ 10^9) β€” where A_i represents type of the i-th flower. Each of the next Q lines describe queries and start with integer T∈\{1, 2\}. * If T = 1, there will be three more integers in the line L, R, X\;(1 ≀ L, R ≀ N;\; 1 ≀ X ≀ 10^9) β€” L and R describing boundaries and X describing the flower type * If T = 2, there will be one more integer in the line K\;(1 ≀ K ≀ N) β€” resident's width of view Output For each query of the second type print the beautiness B of the collection. Example Input 5 5 1 2 3 4 5 2 3 1 1 2 5 2 4 1 2 4 5 2 2 Output 9 6 4 Note Let's look at the example. Initially the collection is [1, 2, 3, 4, 5]. In the first query K = 3, we consider sections of three flowers with the first being [1, 2, 3]. Since beautiness of the section is the number of distinct flower types in that section, B_1 = 3. Second section is [2, 3, 4] and B_2 = 3. Third section is [3, 4, 5] and B_3 = 3, since the flower types are all distinct. The beautiness value resident has associated with the collection is B = B_1 + B_2 + B_3 = 3 + 3 + 3 = 9. After the second query, the collection becomes [5, 5, 3, 4, 5]. For the third query K = 4, so we consider sections of four flowers with the first being [5, 5, 3, 4]. There are three distinct flower types [5, 3, 4] in this section, so B_1 = 3. Second section [5, 3, 4, 5] also has 3 distinct flower types, so B_2 = 3. The beautiness value resident has associated with the collection is B = B_1 + B_2 = 3 + 3 = 6 After the fourth query, the collection becomes [5, 5, 5, 5, 5]. For the fifth query K = 2 and in this case all the four sections are same with each of them being [5, 5]. Beautiness of [5, 5] is 1 since there is only one distinct element in this section [5]. Beautiness of the whole collection is B = B_1 + B_2 + B_3 + B_4 = 1 + 1 + 1 + 1 = 4
2
13
#include <bits/stdc++.h> using namespace std; inline long long read() { long long x = 0, f = 1; char c = getchar(); while (c < '0' || c > '9') { if (c == '-') f = -1; c = getchar(); } while (c >= '0' && c <= '9') { x = (x << 1) + (x << 3) + c - '0'; c = getchar(); } return x * f; } int a[100010], n, Q; struct Seg_ment { struct node { int l, r; long long sum, add; inline void Add(long long d) { sum += (r - l + 1) * d, add += d; } } tree[100010 << 2]; inline void update(int i) { tree[i].sum = tree[i << 1].sum + tree[i << 1 | 1].sum; } inline void pushdown(int i) { if (tree[i].add) { tree[i << 1].Add(tree[i].add); tree[i << 1 | 1].Add(tree[i].add); tree[i].add = 0; } } void build(int i, int l, int r) { tree[i].l = l; tree[i].r = r; tree[i].add = tree[i].sum = 0; if (l == r) return; int mid = (l + r) >> 1; build(i << 1, l, mid); build(i << 1 | 1, mid + 1, r); } void Plus(int i, int l, int r, int d) { if (tree[i].l >= l && tree[i].r <= r) { tree[i].Add(d); return; } pushdown(i); int mid = (tree[i].l + tree[i].r) >> 1; if (l <= mid) Plus(i << 1, l, r, d); if (r > mid) Plus(i << 1 | 1, l, r, d); update(i); } long long Query(int i, int l, int r) { if (tree[i].l >= l && tree[i].r <= r) { return tree[i].sum; } pushdown(i); int mid = (tree[i].l + tree[i].r) >> 1; long long tot = 0; if (l <= mid) tot += Query(i << 1, l, r); if (r > mid) tot += Query(i << 1 | 1, l, r); return tot; } } T; int tot; map<int, int> id; set<pair<int, int> > s[100010]; set<pair<pair<int, int>, int> > all; void Change(int A, int B, int w) { if (A > B) swap(A, B); T.Plus(1, 1, A, w); if (B < n) T.Plus(1, B + 1, min(n, A + B), -w); } inline void Erase(int l, int r, int u) { all.erase(make_pair(make_pair(l, r), u)); auto it = s[u].lower_bound(make_pair(l, r)); int R = n + 1; if ((++it) != s[u].end()) { R = it->first; } --it, --it; int L = it->second; if (R <= n) { Change(R - r, n - R + 1, -1); Change(R - L, n - R + 1, 1); } ++it; s[u].erase(it); Change(l - L, n - l + 1, -1); if (l < r) { T.Plus(1, 1, 1, -(r - l)); T.Plus(1, n - r + 2, min(n, n - l + 1), 1); } } inline void Insert(int l, int r, int u) { all.insert(make_pair(make_pair(l, r), u)); auto it = s[u].lower_bound(make_pair(l, r)); int R = n + 1; if (it != s[u].end()) { R = it->first; } --it; int L = it->second; if (R <= n) { Change(R - r, n - R + 1, 1); Change(R - L, n - R + 1, -1); } s[u].insert(make_pair(l, r)); Change(l - L, n - l + 1, 1); if (l < r) { T.Plus(1, 1, 1, r - l); T.Plus(1, n - r + 2, min(n, n - l + 1), -1); } } int main() { n = read(), Q = read(); T.build(1, 1, n); for (int i = 1; i <= n; ++i) { a[i] = read(); if (!id.count(a[i])) id[a[i]] = ++tot, s[tot].insert(make_pair(0, 0)); Insert(i, i, id[a[i]]); } while (Q--) { int opt = read(); if (opt == 1) { int l = read(), r = read(), x = read(); if (!id.count(x)) id[x] = ++tot, s[tot].insert(make_pair(0, 0)); x = id[x]; auto it = --all.lower_bound(make_pair(make_pair(l, n + 1), 233)); int itl = it->first.first, itr = it->first.second, itu = it->second; Erase(itl, itr, itu); if (itl < l) { Insert(itl, l - 1, itu); } if (itr > r) { Insert(r + 1, itr, itu); } else { while (true) { it = all.lower_bound(make_pair(make_pair(l, 0), 0)); if (it == all.end() || it->first.second > r) break; Erase(it->first.first, it->first.second, it->second); } if (it != all.end() && it->first.first <= r) { itl = it->first.first, itr = it->first.second, itu = it->second; Erase(itl, itr, itu); Insert(r + 1, itr, itu); } } Insert(l, r, x); } else { int k = read(); printf("%lld\n", T.Query(1, 1, k)); } } return 0; }
CPP
1423_G. Growing flowers
Sarah has always been a lover of nature, and a couple of years ago she saved up enough money to travel the world and explore all the things built by nature over its lifetime on earth. During this time she visited some truly special places which were left untouched for centuries, from watching icebergs in freezing weather to scuba-diving in oceans and admiring the sea life, residing unseen. These experiences were enhanced with breathtaking views built by mountains over time and left there for visitors to see for years on end. Over time, all these expeditions took a toll on Sarah and culminated in her decision to settle down in the suburbs and live a quiet life. However, as Sarah's love for nature never faded, she started growing flowers in her garden in an attempt to stay connected with nature. At the beginning she planted only blue orchids, but over time she started using different flower types to add variety to her collection of flowers. This collection of flowers can be represented as an array of N flowers and the i-th of them has a type associated with it, denoted as A_i. Each resident, passing by her collection and limited by the width of his view, can only see K contiguous flowers at each moment in time. To see the whole collection, the resident will look at the first K contiguous flowers A_1, A_2, ..., A_K, then shift his view by one flower and look at the next section of K contiguous flowers A_2, A_3, ..., A_{K+1} and so on until they scan the whole collection, ending with section A_{N-K+1}, ..., A_{N-1}, A_N. Each resident determines the beautiness of a section of K flowers as the number of distinct flower types in that section. Furthermore, the beautiness of the whole collection is calculated by summing the beautiness values of each contiguous section. Formally, beautiness B_i of a section starting at the i-th position is calculated as B_i = distinct(A_i, A_{i+1}, ..., A_{i+K-1}), and beautiness of the collection B is calculated as B=B_1 + B_2 + ... + B_{N-K+1}. In addition, as Sarah wants to keep her collection of flowers have a fresh feel, she can also pick two points L and R, dispose flowers between those two points and plant new flowers, all of them being the same type. You will be given Q queries and each of those queries will be of the following two types: 1. You will be given three integers L, R, X describing that Sarah has planted flowers of type X between positions L and R inclusive. Formally collection is changed such that A[i]=X for all i in range [L.. R]. 2. You will be given integer K, width of the resident's view and you have to determine the beautiness value B resident has associated with the collection For each query of second type print the result – beautiness B of the collection. Input First line contains two integers N and Q \;(1 ≀ N, Q ≀ 10^5) β€” number of flowers and the number of queries, respectively. The second line contains N integers A_1, A_2, ..., A_N\;(1 ≀ A_i ≀ 10^9) β€” where A_i represents type of the i-th flower. Each of the next Q lines describe queries and start with integer T∈\{1, 2\}. * If T = 1, there will be three more integers in the line L, R, X\;(1 ≀ L, R ≀ N;\; 1 ≀ X ≀ 10^9) β€” L and R describing boundaries and X describing the flower type * If T = 2, there will be one more integer in the line K\;(1 ≀ K ≀ N) β€” resident's width of view Output For each query of the second type print the beautiness B of the collection. Example Input 5 5 1 2 3 4 5 2 3 1 1 2 5 2 4 1 2 4 5 2 2 Output 9 6 4 Note Let's look at the example. Initially the collection is [1, 2, 3, 4, 5]. In the first query K = 3, we consider sections of three flowers with the first being [1, 2, 3]. Since beautiness of the section is the number of distinct flower types in that section, B_1 = 3. Second section is [2, 3, 4] and B_2 = 3. Third section is [3, 4, 5] and B_3 = 3, since the flower types are all distinct. The beautiness value resident has associated with the collection is B = B_1 + B_2 + B_3 = 3 + 3 + 3 = 9. After the second query, the collection becomes [5, 5, 3, 4, 5]. For the third query K = 4, so we consider sections of four flowers with the first being [5, 5, 3, 4]. There are three distinct flower types [5, 3, 4] in this section, so B_1 = 3. Second section [5, 3, 4, 5] also has 3 distinct flower types, so B_2 = 3. The beautiness value resident has associated with the collection is B = B_1 + B_2 = 3 + 3 = 6 After the fourth query, the collection becomes [5, 5, 5, 5, 5]. For the fifth query K = 2 and in this case all the four sections are same with each of them being [5, 5]. Beautiness of [5, 5] is 1 since there is only one distinct element in this section [5]. Beautiness of the whole collection is B = B_1 + B_2 + B_3 + B_4 = 1 + 1 + 1 + 1 = 4
2
13
#include <bits/stdc++.h> #pragma GCC target("avx,avx2") using namespace std; template <typename T> void chmin(T &x, const T &y) { if (x > y) x = y; } template <typename T> void chmax(T &x, const T &y) { if (x < y) x = y; } int read() { char c; while ((c = getchar()) < '-') ; if (c == '-') { int x = (c = getchar()) - '0'; while ((c = getchar()) >= '0') x = x * 10 + c - '0'; return -x; } int x = c - '0'; while ((c = getchar()) >= '0') x = x * 10 + c - '0'; return x; } const int N = 1e5 + 5; int n; map<int, int> Map_A; map<int, map<int, int>> Map_V; namespace BIT { int64_t s0[N], s1[N]; void A(int i, int k, int b) { for (; i <= n; i += i & -i) { s1[i] += k; s0[i] += b; } } void add(int l, int r, int k, int b) { if (l > r) return; A(l, k, b); A(r + 1, -k, -b); } int64_t query(int x) { int64_t k = 0, b = 0; for (int i = x; i; i -= i & -i) { k += s1[i]; b += s0[i]; } return k * x + b; } }; // namespace BIT void add_ij(int i, int j, int w) { assert(j < i); int mn = n - i + 1, mx = i - j; if (mx < mn) swap(mn, mx); BIT::add(mx, n - j, -1 * w, (n - j + 1) * w); BIT::add(mn, mx - 1, 0, mn * w); BIT::add(1, mn - 1, 1 * w, 0); } void add_lr(int l, int r, int w) { ++l; if (l > r) return; BIT::add(1, n - r + 1, 0, (r - l + 1) * w); BIT::add(n - r + 2, n - l + 1, -1 * w, (n - l + 1 + 1) * w); } void ins(map<int, int> &Map, int l, int r) { auto it = Map.lower_bound(l); int r1 = 0, l1 = 0; if (it != Map.end()) add_ij(r1 = it->first, r, 1); if (it != Map.begin()) l1 = (--it)->second; add_ij(l, l1, 1); if (r1) add_ij(r1, l1, -1); add_lr(l, r, 1); Map[l] = r; } void del(map<int, int> &Map, int l, int r) { auto split = [&](int p) { auto it = Map.lower_bound(p); if (it == Map.begin()) return; --it; if (it->second >= p) { Map[p] = it->second; it->second = p - 1; } }; split(l); split(r + 1); auto it = Map.lower_bound(l); if (it == Map.end()) { cerr << "it==Map.end() " << l << " " << r << endl; for (auto p : Map) cerr << p.first << " " << p.second << endl; assert(0); } if (it->second != r) { cerr << "it->second!=r " << l << " " << it->second << " " << r << endl; assert(0); } Map.erase(it); int l1 = 0, r1 = 0; it = Map.lower_bound(r + 1); if (it != Map.end()) add_ij(r1 = it->first, r, -1); if (it != Map.begin()) l1 = (--it)->second; add_ij(l, l1, -1); if (r1) add_ij(r1, l1, 1); add_lr(l, r, -1); } void split(int p) { auto it = Map_A.lower_bound(p); if (it->first == p) return; --it; Map_A[p] = it->second; } int main() { n = read(); int m = read(); for (int i = 1; i <= n; ++i) { int x = read(); ins(Map_V[x], i, i); Map_A[i] = x; } Map_A[n + 1] = 0; while (m--) if (read() == 1) { int l = read(), r = read(), x = read(); split(l); split(r + 1); auto it = Map_A.lower_bound(l); while (it->first <= r) { auto it1 = it; ++it1; del(Map_V[it->second], it->first, it1->first - 1); Map_A.erase(it); it = it1; } Map_A[l] = x; ins(Map_V[x], l, r); } else { printf("%lld\n", BIT::query(read())); } }
CPP
1423_G. Growing flowers
Sarah has always been a lover of nature, and a couple of years ago she saved up enough money to travel the world and explore all the things built by nature over its lifetime on earth. During this time she visited some truly special places which were left untouched for centuries, from watching icebergs in freezing weather to scuba-diving in oceans and admiring the sea life, residing unseen. These experiences were enhanced with breathtaking views built by mountains over time and left there for visitors to see for years on end. Over time, all these expeditions took a toll on Sarah and culminated in her decision to settle down in the suburbs and live a quiet life. However, as Sarah's love for nature never faded, she started growing flowers in her garden in an attempt to stay connected with nature. At the beginning she planted only blue orchids, but over time she started using different flower types to add variety to her collection of flowers. This collection of flowers can be represented as an array of N flowers and the i-th of them has a type associated with it, denoted as A_i. Each resident, passing by her collection and limited by the width of his view, can only see K contiguous flowers at each moment in time. To see the whole collection, the resident will look at the first K contiguous flowers A_1, A_2, ..., A_K, then shift his view by one flower and look at the next section of K contiguous flowers A_2, A_3, ..., A_{K+1} and so on until they scan the whole collection, ending with section A_{N-K+1}, ..., A_{N-1}, A_N. Each resident determines the beautiness of a section of K flowers as the number of distinct flower types in that section. Furthermore, the beautiness of the whole collection is calculated by summing the beautiness values of each contiguous section. Formally, beautiness B_i of a section starting at the i-th position is calculated as B_i = distinct(A_i, A_{i+1}, ..., A_{i+K-1}), and beautiness of the collection B is calculated as B=B_1 + B_2 + ... + B_{N-K+1}. In addition, as Sarah wants to keep her collection of flowers have a fresh feel, she can also pick two points L and R, dispose flowers between those two points and plant new flowers, all of them being the same type. You will be given Q queries and each of those queries will be of the following two types: 1. You will be given three integers L, R, X describing that Sarah has planted flowers of type X between positions L and R inclusive. Formally collection is changed such that A[i]=X for all i in range [L.. R]. 2. You will be given integer K, width of the resident's view and you have to determine the beautiness value B resident has associated with the collection For each query of second type print the result – beautiness B of the collection. Input First line contains two integers N and Q \;(1 ≀ N, Q ≀ 10^5) β€” number of flowers and the number of queries, respectively. The second line contains N integers A_1, A_2, ..., A_N\;(1 ≀ A_i ≀ 10^9) β€” where A_i represents type of the i-th flower. Each of the next Q lines describe queries and start with integer T∈\{1, 2\}. * If T = 1, there will be three more integers in the line L, R, X\;(1 ≀ L, R ≀ N;\; 1 ≀ X ≀ 10^9) β€” L and R describing boundaries and X describing the flower type * If T = 2, there will be one more integer in the line K\;(1 ≀ K ≀ N) β€” resident's width of view Output For each query of the second type print the beautiness B of the collection. Example Input 5 5 1 2 3 4 5 2 3 1 1 2 5 2 4 1 2 4 5 2 2 Output 9 6 4 Note Let's look at the example. Initially the collection is [1, 2, 3, 4, 5]. In the first query K = 3, we consider sections of three flowers with the first being [1, 2, 3]. Since beautiness of the section is the number of distinct flower types in that section, B_1 = 3. Second section is [2, 3, 4] and B_2 = 3. Third section is [3, 4, 5] and B_3 = 3, since the flower types are all distinct. The beautiness value resident has associated with the collection is B = B_1 + B_2 + B_3 = 3 + 3 + 3 = 9. After the second query, the collection becomes [5, 5, 3, 4, 5]. For the third query K = 4, so we consider sections of four flowers with the first being [5, 5, 3, 4]. There are three distinct flower types [5, 3, 4] in this section, so B_1 = 3. Second section [5, 3, 4, 5] also has 3 distinct flower types, so B_2 = 3. The beautiness value resident has associated with the collection is B = B_1 + B_2 = 3 + 3 = 6 After the fourth query, the collection becomes [5, 5, 5, 5, 5]. For the fifth query K = 2 and in this case all the four sections are same with each of them being [5, 5]. Beautiness of [5, 5] is 1 since there is only one distinct element in this section [5]. Beautiness of the whole collection is B = B_1 + B_2 + B_3 + B_4 = 1 + 1 + 1 + 1 = 4
2
13
#include <bits/stdc++.h> using namespace std; using ll = long long; const int N = 200005; int n, q; struct TNode { int l, r; ll a, b; } t[N << 2]; inline int lc(int pos) { return pos << 1; } inline int rc(int pos) { return pos << 1 | 1; } void build(int pos, int l, int r) { t[pos].l = l; t[pos].r = r; if (l == r) return; int mid = (l + r) >> 1; build(lc(pos), l, mid); build(rc(pos), mid + 1, r); } void modify(int pos, int l, int r, ll a, ll b) { if (t[pos].l == l && t[pos].r == r) { t[pos].a += a; t[pos].b += b; return; } int mid = (t[pos].l + t[pos].r) >> 1; if (r <= mid) modify(lc(pos), l, r, a, b); else if (l > mid) modify(rc(pos), l, r, a, b); else modify(lc(pos), l, mid, a, b), modify(rc(pos), mid + 1, r, a, b); } ll query(int pos, int p) { ll ret = t[pos].a * p + t[pos].b; if (t[pos].l == t[pos].r) return ret; int mid = (t[pos].l + t[pos].r) >> 1; return p <= mid ? ret + query(lc(pos), p) : ret + query(rc(pos), p); } map<int, int> id; int idx; int gid(int x) { auto it = id.find(x); if (it != id.end()) return it->second; return id[x] = ++idx; } struct Node { int l, r, c; }; inline bool operator<(const Node &a, const Node &b) { return a.l < b.l; } set<Node> s[N], tt; using Iter = set<Node>::iterator; void get_ans(Iter it, int d) { int l = it->l, r = it->r, c = it->c; int pre = 0; if (it != s[c].begin()) pre = prev(it)->r; int lim = n - pre, lim1 = l - pre, lim2 = n - r + 1; if (lim1 > 1) modify(1, 1, lim1 - 1, d, -d * l); modify(1, lim1, lim, 0, -d * pre); if (lim2 > 1) modify(1, 1, lim2 - 1, 0, d * r); modify(1, lim2, lim, -d, d * (n + 1)); } void ins(Node x) { int c = x.c; tt.insert(x); Iter suf = s[c].lower_bound(x); if (suf != s[c].end()) get_ans(suf, -1); Iter it = s[c].insert(x).first; get_ans(it, 1); if (suf != s[c].end()) get_ans(suf, 1); } void del(Node x) { int c = x.c; Iter suf = s[c].find(x), it = suf; ++suf; get_ans(it, -1); if (suf != s[c].end()) get_ans(suf, -1); s[c].erase(it); if (suf != s[c].end()) get_ans(suf, 1); } void cut(int pos) { Iter it = prev(tt.upper_bound({pos, 0, 0})); if (it->r == pos) return; Node tmp = *it; int l = it->l, r = it->r, c = it->c; Node x = {l, pos, c}, y = {pos + 1, r, c}; tt.erase(it); tt.insert(x); tt.insert(y); s[c].erase(tmp); s[c].insert(x); s[c].insert(y); } int main() { ios::sync_with_stdio(false); cin >> n >> q; build(1, 1, n); for (int i = 1; i <= n; i++) { int t1; cin >> t1; int x = gid(t1); ins({i, i, x}); } while (q--) { int op; cin >> op; if (op & 1) { int l, r, c; cin >> l >> r >> c; c = gid(c); cut(r); if (l > 1) cut(l - 1); Iter pre = tt.lower_bound({l, 0, 0}), suf = tt.upper_bound({r, 0, 0}); for (auto it = pre; it != suf; it++) del(*it); tt.erase(pre, suf); ins({l, r, c}); continue; } int x; cin >> x; cout << query(1, x) << endl; } return 0; }
CPP
1423_G. Growing flowers
Sarah has always been a lover of nature, and a couple of years ago she saved up enough money to travel the world and explore all the things built by nature over its lifetime on earth. During this time she visited some truly special places which were left untouched for centuries, from watching icebergs in freezing weather to scuba-diving in oceans and admiring the sea life, residing unseen. These experiences were enhanced with breathtaking views built by mountains over time and left there for visitors to see for years on end. Over time, all these expeditions took a toll on Sarah and culminated in her decision to settle down in the suburbs and live a quiet life. However, as Sarah's love for nature never faded, she started growing flowers in her garden in an attempt to stay connected with nature. At the beginning she planted only blue orchids, but over time she started using different flower types to add variety to her collection of flowers. This collection of flowers can be represented as an array of N flowers and the i-th of them has a type associated with it, denoted as A_i. Each resident, passing by her collection and limited by the width of his view, can only see K contiguous flowers at each moment in time. To see the whole collection, the resident will look at the first K contiguous flowers A_1, A_2, ..., A_K, then shift his view by one flower and look at the next section of K contiguous flowers A_2, A_3, ..., A_{K+1} and so on until they scan the whole collection, ending with section A_{N-K+1}, ..., A_{N-1}, A_N. Each resident determines the beautiness of a section of K flowers as the number of distinct flower types in that section. Furthermore, the beautiness of the whole collection is calculated by summing the beautiness values of each contiguous section. Formally, beautiness B_i of a section starting at the i-th position is calculated as B_i = distinct(A_i, A_{i+1}, ..., A_{i+K-1}), and beautiness of the collection B is calculated as B=B_1 + B_2 + ... + B_{N-K+1}. In addition, as Sarah wants to keep her collection of flowers have a fresh feel, she can also pick two points L and R, dispose flowers between those two points and plant new flowers, all of them being the same type. You will be given Q queries and each of those queries will be of the following two types: 1. You will be given three integers L, R, X describing that Sarah has planted flowers of type X between positions L and R inclusive. Formally collection is changed such that A[i]=X for all i in range [L.. R]. 2. You will be given integer K, width of the resident's view and you have to determine the beautiness value B resident has associated with the collection For each query of second type print the result – beautiness B of the collection. Input First line contains two integers N and Q \;(1 ≀ N, Q ≀ 10^5) β€” number of flowers and the number of queries, respectively. The second line contains N integers A_1, A_2, ..., A_N\;(1 ≀ A_i ≀ 10^9) β€” where A_i represents type of the i-th flower. Each of the next Q lines describe queries and start with integer T∈\{1, 2\}. * If T = 1, there will be three more integers in the line L, R, X\;(1 ≀ L, R ≀ N;\; 1 ≀ X ≀ 10^9) β€” L and R describing boundaries and X describing the flower type * If T = 2, there will be one more integer in the line K\;(1 ≀ K ≀ N) β€” resident's width of view Output For each query of the second type print the beautiness B of the collection. Example Input 5 5 1 2 3 4 5 2 3 1 1 2 5 2 4 1 2 4 5 2 2 Output 9 6 4 Note Let's look at the example. Initially the collection is [1, 2, 3, 4, 5]. In the first query K = 3, we consider sections of three flowers with the first being [1, 2, 3]. Since beautiness of the section is the number of distinct flower types in that section, B_1 = 3. Second section is [2, 3, 4] and B_2 = 3. Third section is [3, 4, 5] and B_3 = 3, since the flower types are all distinct. The beautiness value resident has associated with the collection is B = B_1 + B_2 + B_3 = 3 + 3 + 3 = 9. After the second query, the collection becomes [5, 5, 3, 4, 5]. For the third query K = 4, so we consider sections of four flowers with the first being [5, 5, 3, 4]. There are three distinct flower types [5, 3, 4] in this section, so B_1 = 3. Second section [5, 3, 4, 5] also has 3 distinct flower types, so B_2 = 3. The beautiness value resident has associated with the collection is B = B_1 + B_2 = 3 + 3 = 6 After the fourth query, the collection becomes [5, 5, 5, 5, 5]. For the fifth query K = 2 and in this case all the four sections are same with each of them being [5, 5]. Beautiness of [5, 5] is 1 since there is only one distinct element in this section [5]. Beautiness of the whole collection is B = B_1 + B_2 + B_3 + B_4 = 1 + 1 + 1 + 1 = 4
2
13
#include <bits/stdc++.h> using namespace std; const int N = 100000; int n, cq, a[N + 9]; void into() { scanf("%d%d", &n, &cq); for (int i = 1; i <= n; ++i) scanf("%d", &a[i]); } struct answer { struct tree { long long sum, add; } tr[N * 4 + 9]; void Pushup(int k) { tr[k].sum = tr[k << 1].sum + tr[k << 1 | 1].sum; } void Update_add(int k, int l, int r, long long v) { tr[k].sum += v * (r - l + 1); tr[k].add += v; } void Pushdown(int k, int l, int r) { if (!tr[k].add) return; int mid = l + r >> 1; Update_add(k << 1, l, mid, tr[k].add); Update_add(k << 1 | 1, mid + 1, r, tr[k].add); tr[k].add = 0; } void Change_add(int L, int R, long long v, int l, int r, int k) { if (L > R) return; if (R < l) return; if (L > r) return; if (L <= l && R >= r) { Update_add(k, l, r, v); return; } int mid = l + r >> 1; Pushdown(k, l, r); if (L <= mid) Change_add(L, R, v, l, mid, k << 1); if (R > mid) Change_add(L, R, v, mid + 1, r, k << 1 | 1); Pushup(k); } long long Query_sum(int L, int R, int l, int r, int k) { if (L <= l && R >= r) return tr[k].sum; int mid = l + r >> 1; long long res = 0; Pushdown(k, l, r); if (L <= mid) res += Query_sum(L, R, l, mid, k << 1); if (R > mid) res += Query_sum(L, R, mid + 1, r, k << 1 | 1); return res; } void Add(int l, int r, int v) { int len = r - l + 1; int x = n - l + 1, y = r, p = min(x, y), q = max(x, y); Change_add(len, len, v * (l - r + len - 1), 0, n, 1); Change_add(p + 1, p + 1, -v * (l - r + len - 1), 0, n, 1); Change_add(len, p, v, 0, n, 1); Change_add(p + 1, p + 1, -v * (p - len + 1), 0, n, 1); if (p == x) { Change_add(p + 1, p + 1, v * (n - r + 1), 0, n, 1); Change_add(q + 1, q + 1, -v * (n - r + 1), 0, n, 1); } else { Change_add(p + 1, p + 1, v * l, 0, n, 1); Change_add(q + 1, q + 1, -v * l, 0, n, 1); } Change_add(q + 1, q + 1, v * (n + 1 - q), 0, n, 1); Change_add(q + 1, n, -v, 0, n, 1); } long long Query(int p) { return Query_sum(0, p, 0, n, 1); } } ans; struct seg { int l, r, x; seg(int L = 0, int R = 0, int X = 0) { l = L; r = R; x = X; } bool operator<(const seg &p) const { return l < p.l; } }; map<int, set<seg> > mp; set<seg> s; void Get_ans() { map<int, int> last; for (int i = 1; i <= n; ++i) { mp[a[i]].insert(seg(i, i, a[i])); s.insert(seg(i, i, a[i])); int p = last[a[i]]; if (p) ans.Add(p, i, 1); last[a[i]] = i; } } void work() { Get_ans(); } void Change(int l, int r, int c) { seg p = *--s.upper_bound(seg(l)); if (p.l < l) { s.erase(p); mp[p.x].erase(p); s.insert(seg(p.l, l - 1, p.x)); mp[p.x].insert(seg(p.l, l - 1, p.x)); s.insert(seg(l, p.r, p.x)); mp[p.x].insert(seg(l, p.r, p.x)); } p = *--s.upper_bound(seg(r)); if (r < p.r) { s.erase(p); mp[p.x].erase(p); s.insert(seg(p.l, r, p.x)); mp[p.x].insert(seg(p.l, r, p.x)); s.insert(seg(r + 1, p.r, p.x)); mp[p.x].insert(seg(r + 1, p.r, p.x)); } vector<seg> tmp; set<int> col; for (set<seg>::iterator it = s.find(seg(l)); it != s.end() && it->r <= r; ++it) { tmp.push_back(*it); col.insert(it->x); set<seg> &ss = mp[it->x]; if (ss.find(*it) != ss.begin()) ans.Add((--ss.find(*it))->r, it->l, -1); if (ss.find(*it) != --ss.end() && (++ss.find(*it))->l > r) ans.Add(it->r, (++ss.find(*it))->l, -1); } for (int vs = tmp.size(), i = 0; i < vs; ++i) { s.erase(tmp[i]); mp[tmp[i].x].erase(tmp[i]); if (i) ans.Add(tmp[i - 1].r, tmp[i].l, 1); } if (col.find(c) != col.end()) col.erase(c); else { set<seg> &ss = mp[c]; set<seg>::iterator t = ss.lower_bound(l); if (t == ss.begin() || t == ss.end()) ; else { int v = t->l, u = (--t)->r; ans.Add(u, v, -1); } } for (set<int>::iterator it = col.begin(); it != col.end(); ++it) { int x = *it; set<seg> &ss = mp[x]; set<seg>::iterator t = ss.lower_bound(l); if (t == ss.begin() || t == ss.end()) continue; int v = t->l, u = (--t)->r; ans.Add(u, v, 1); } s.insert(seg(l, r, c)); set<seg>::iterator it = (mp[c].insert(seg(l, r, c))).first; set<seg> &ss = mp[c]; if (it != ss.begin()) { set<seg>::iterator p = it; --p; ans.Add(p->r, it->l, 1); } if (it != --ss.end()) { set<seg>::iterator p = it; ++p; ans.Add(it->r, p->l, 1); } } void outo() { for (; cq--;) { int opt; scanf("%d", &opt); if (opt == 1) { int l, r, x; scanf("%d%d%d", &l, &r, &x); Change(l, r, x); } else { int x; scanf("%d", &x); printf("%lld\n", 1LL * x * (n - x + 1) - ans.Query(x)); } } } int main() { into(); work(); outo(); return 0; }
CPP
1423_G. Growing flowers
Sarah has always been a lover of nature, and a couple of years ago she saved up enough money to travel the world and explore all the things built by nature over its lifetime on earth. During this time she visited some truly special places which were left untouched for centuries, from watching icebergs in freezing weather to scuba-diving in oceans and admiring the sea life, residing unseen. These experiences were enhanced with breathtaking views built by mountains over time and left there for visitors to see for years on end. Over time, all these expeditions took a toll on Sarah and culminated in her decision to settle down in the suburbs and live a quiet life. However, as Sarah's love for nature never faded, she started growing flowers in her garden in an attempt to stay connected with nature. At the beginning she planted only blue orchids, but over time she started using different flower types to add variety to her collection of flowers. This collection of flowers can be represented as an array of N flowers and the i-th of them has a type associated with it, denoted as A_i. Each resident, passing by her collection and limited by the width of his view, can only see K contiguous flowers at each moment in time. To see the whole collection, the resident will look at the first K contiguous flowers A_1, A_2, ..., A_K, then shift his view by one flower and look at the next section of K contiguous flowers A_2, A_3, ..., A_{K+1} and so on until they scan the whole collection, ending with section A_{N-K+1}, ..., A_{N-1}, A_N. Each resident determines the beautiness of a section of K flowers as the number of distinct flower types in that section. Furthermore, the beautiness of the whole collection is calculated by summing the beautiness values of each contiguous section. Formally, beautiness B_i of a section starting at the i-th position is calculated as B_i = distinct(A_i, A_{i+1}, ..., A_{i+K-1}), and beautiness of the collection B is calculated as B=B_1 + B_2 + ... + B_{N-K+1}. In addition, as Sarah wants to keep her collection of flowers have a fresh feel, she can also pick two points L and R, dispose flowers between those two points and plant new flowers, all of them being the same type. You will be given Q queries and each of those queries will be of the following two types: 1. You will be given three integers L, R, X describing that Sarah has planted flowers of type X between positions L and R inclusive. Formally collection is changed such that A[i]=X for all i in range [L.. R]. 2. You will be given integer K, width of the resident's view and you have to determine the beautiness value B resident has associated with the collection For each query of second type print the result – beautiness B of the collection. Input First line contains two integers N and Q \;(1 ≀ N, Q ≀ 10^5) β€” number of flowers and the number of queries, respectively. The second line contains N integers A_1, A_2, ..., A_N\;(1 ≀ A_i ≀ 10^9) β€” where A_i represents type of the i-th flower. Each of the next Q lines describe queries and start with integer T∈\{1, 2\}. * If T = 1, there will be three more integers in the line L, R, X\;(1 ≀ L, R ≀ N;\; 1 ≀ X ≀ 10^9) β€” L and R describing boundaries and X describing the flower type * If T = 2, there will be one more integer in the line K\;(1 ≀ K ≀ N) β€” resident's width of view Output For each query of the second type print the beautiness B of the collection. Example Input 5 5 1 2 3 4 5 2 3 1 1 2 5 2 4 1 2 4 5 2 2 Output 9 6 4 Note Let's look at the example. Initially the collection is [1, 2, 3, 4, 5]. In the first query K = 3, we consider sections of three flowers with the first being [1, 2, 3]. Since beautiness of the section is the number of distinct flower types in that section, B_1 = 3. Second section is [2, 3, 4] and B_2 = 3. Third section is [3, 4, 5] and B_3 = 3, since the flower types are all distinct. The beautiness value resident has associated with the collection is B = B_1 + B_2 + B_3 = 3 + 3 + 3 = 9. After the second query, the collection becomes [5, 5, 3, 4, 5]. For the third query K = 4, so we consider sections of four flowers with the first being [5, 5, 3, 4]. There are three distinct flower types [5, 3, 4] in this section, so B_1 = 3. Second section [5, 3, 4, 5] also has 3 distinct flower types, so B_2 = 3. The beautiness value resident has associated with the collection is B = B_1 + B_2 = 3 + 3 = 6 After the fourth query, the collection becomes [5, 5, 5, 5, 5]. For the fifth query K = 2 and in this case all the four sections are same with each of them being [5, 5]. Beautiness of [5, 5] is 1 since there is only one distinct element in this section [5]. Beautiness of the whole collection is B = B_1 + B_2 + B_3 + B_4 = 1 + 1 + 1 + 1 = 4
2
13
#include <bits/stdc++.h> int enlarge(int n) { int res = 1; while (res < n) { res <<= 1; } return res; } struct node { int c; long long s; node() : c(0), s(0) {} node(int _c, long long _s) : c(_c), s(_s) {} node operator+(const node &rhs) const { return node(c + rhs.c, s + rhs.s); } }; class segment_tree { int n; std::vector<node> a; void modify(int u, int l, int r, int x, int v) { if (l + 1 == r) { a[u].c += v; a[u].s += 1ll * v * x; return; } int mid = (l + r + 1) >> 1; if (x < mid) { modify(u << 1, l, mid, x, v); } else { modify(u << 1 | 1, mid, r, x, v); } a[u] = a[u << 1] + a[u << 1 | 1]; } node query(int u, int l, int r, int L, int R) { if (L <= l && r <= R) { return a[u]; } int mid = (l + r + 1) >> 1; if (R <= mid) { return query(u << 1, l, mid, L, R); } else if (L >= mid) { return query(u << 1 | 1, mid, r, L, R); } else { return query(u << 1, l, mid, L, R) + query(u << 1 | 1, mid, r, L, R); } } public: segment_tree(int _n) : n(_n), a(enlarge(n) << 1) {} void add(int x, int v) { modify(1, 0, n, x, v); } node query(int l, int r) { return query(1, 0, n, l, r); } }; int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(0); int n, q; std::cin >> n >> q; std::map<int, int> a; std::map<int, std::set<std::pair<int, int>>> S; a[-1] = a[n] = -1; for (int i = 0; i < n; ++i) { std::cin >> a[i]; } segment_tree Tl(n + 2), Tr(n + 2), Tn(n + 2); long long ans = 0; int cnt = 0; auto add = [&](int i, int j, int p, int v) { Tl.add(i - p, v); Tr.add(n - j, v); Tn.add(n - p, v); ans += 1ll * (j - p) * v; }; auto insert = [&](std::set<std::pair<int, int>> &S, int l, int r) { auto it = S.lower_bound(std::make_pair(r + 1, 0)); int lst = it == S.begin() ? -1 : std::prev(it)->second; if (it != S.end()) { add(it->first, it->second, lst, -1); add(it->first, it->second, r, 1); } add(l, r, lst, 1); S.emplace(l, r); }; auto erase = [&](std::set<std::pair<int, int>> &S, int l, int r) { auto it = S.find(std::make_pair(l, r)), nx = std::next(it); int lst = it == S.begin() ? -1 : std::prev(it)->second; if (nx != S.end()) { add(nx->first, nx->second, r, -1); add(nx->first, nx->second, lst, 1); } add(l, r, lst, -1); S.erase(it); }; for (int i = 0; i < n; ++i) { insert(S[a[i]], i, i); } while (q--) { int op; std::cin >> op; if (op == 1) { int l, r, x; std::cin >> l >> r >> x; --l, --r; auto it = a.lower_bound(l); int lst = std::prev(it)->first; int pl = lst, cl = it->second; while (it->first <= r) { erase(S[it->second], lst + 1, it->first); lst = it->first; it = a.erase(it); } int pr = it->first, cr = it->second; if (pr < n) { erase(S[cr], lst + 1, pr); } if (pl < l - 1) { insert(S[cl], pl + 1, l - 1); a[l - 1] = cl; } insert(S[x], l, r); a[r] = x; if (pr < n) { insert(S[cr], r + 1, pr); } } else { int k; std::cin >> k; node pl = Tl.query(0, k), sl = Tl.query(k, n + 2); node pr = Tr.query(0, k), sr = Tr.query(k, n + 2); node pn = Tn.query(0, k); std::cout << ans - 1ll * pl.c * k - sl.s + pr.s + 1ll * sr.c * k + 1ll * pn.c * k - pn.s << "\n"; } } }
CPP
1423_G. Growing flowers
Sarah has always been a lover of nature, and a couple of years ago she saved up enough money to travel the world and explore all the things built by nature over its lifetime on earth. During this time she visited some truly special places which were left untouched for centuries, from watching icebergs in freezing weather to scuba-diving in oceans and admiring the sea life, residing unseen. These experiences were enhanced with breathtaking views built by mountains over time and left there for visitors to see for years on end. Over time, all these expeditions took a toll on Sarah and culminated in her decision to settle down in the suburbs and live a quiet life. However, as Sarah's love for nature never faded, she started growing flowers in her garden in an attempt to stay connected with nature. At the beginning she planted only blue orchids, but over time she started using different flower types to add variety to her collection of flowers. This collection of flowers can be represented as an array of N flowers and the i-th of them has a type associated with it, denoted as A_i. Each resident, passing by her collection and limited by the width of his view, can only see K contiguous flowers at each moment in time. To see the whole collection, the resident will look at the first K contiguous flowers A_1, A_2, ..., A_K, then shift his view by one flower and look at the next section of K contiguous flowers A_2, A_3, ..., A_{K+1} and so on until they scan the whole collection, ending with section A_{N-K+1}, ..., A_{N-1}, A_N. Each resident determines the beautiness of a section of K flowers as the number of distinct flower types in that section. Furthermore, the beautiness of the whole collection is calculated by summing the beautiness values of each contiguous section. Formally, beautiness B_i of a section starting at the i-th position is calculated as B_i = distinct(A_i, A_{i+1}, ..., A_{i+K-1}), and beautiness of the collection B is calculated as B=B_1 + B_2 + ... + B_{N-K+1}. In addition, as Sarah wants to keep her collection of flowers have a fresh feel, she can also pick two points L and R, dispose flowers between those two points and plant new flowers, all of them being the same type. You will be given Q queries and each of those queries will be of the following two types: 1. You will be given three integers L, R, X describing that Sarah has planted flowers of type X between positions L and R inclusive. Formally collection is changed such that A[i]=X for all i in range [L.. R]. 2. You will be given integer K, width of the resident's view and you have to determine the beautiness value B resident has associated with the collection For each query of second type print the result – beautiness B of the collection. Input First line contains two integers N and Q \;(1 ≀ N, Q ≀ 10^5) β€” number of flowers and the number of queries, respectively. The second line contains N integers A_1, A_2, ..., A_N\;(1 ≀ A_i ≀ 10^9) β€” where A_i represents type of the i-th flower. Each of the next Q lines describe queries and start with integer T∈\{1, 2\}. * If T = 1, there will be three more integers in the line L, R, X\;(1 ≀ L, R ≀ N;\; 1 ≀ X ≀ 10^9) β€” L and R describing boundaries and X describing the flower type * If T = 2, there will be one more integer in the line K\;(1 ≀ K ≀ N) β€” resident's width of view Output For each query of the second type print the beautiness B of the collection. Example Input 5 5 1 2 3 4 5 2 3 1 1 2 5 2 4 1 2 4 5 2 2 Output 9 6 4 Note Let's look at the example. Initially the collection is [1, 2, 3, 4, 5]. In the first query K = 3, we consider sections of three flowers with the first being [1, 2, 3]. Since beautiness of the section is the number of distinct flower types in that section, B_1 = 3. Second section is [2, 3, 4] and B_2 = 3. Third section is [3, 4, 5] and B_3 = 3, since the flower types are all distinct. The beautiness value resident has associated with the collection is B = B_1 + B_2 + B_3 = 3 + 3 + 3 = 9. After the second query, the collection becomes [5, 5, 3, 4, 5]. For the third query K = 4, so we consider sections of four flowers with the first being [5, 5, 3, 4]. There are three distinct flower types [5, 3, 4] in this section, so B_1 = 3. Second section [5, 3, 4, 5] also has 3 distinct flower types, so B_2 = 3. The beautiness value resident has associated with the collection is B = B_1 + B_2 = 3 + 3 = 6 After the fourth query, the collection becomes [5, 5, 5, 5, 5]. For the fifth query K = 2 and in this case all the four sections are same with each of them being [5, 5]. Beautiness of [5, 5] is 1 since there is only one distinct element in this section [5]. Beautiness of the whole collection is B = B_1 + B_2 + B_3 + B_4 = 1 + 1 + 1 + 1 = 4
2
13
#include <bits/stdc++.h> const int N = 200000; int n, q; struct BIT { long long tree[N + 5]; int lowbit(int x) { return x & -x; } void update(int x, int k) { for (int i = x; i <= n; i += lowbit(i)) tree[i] += k; } long long sum(int x) { long long ans = 0; for (int i = x; i; i -= lowbit(i)) ans += tree[i]; return ans; } } t1, t2; long long sum(int x) { return t1.sum(x) + t2.sum(x) * x; } void modify(int x, int d) { t1.update(x, -x * d), t2.update(x, d); } struct node { int l, r, c; friend bool operator<(const node &a, const node &b) { return a.l < b.l; } }; std::set<node> st, a[N + 5]; void erase(node x) { auto it = a[x.c].find(x); if (it != a[x.c].begin()) it--, modify(x.l - it->r, 1), it++; it++; if (it != a[x.c].end()) modify(it->l - x.r, 1); it--; if (it != a[x.c].begin()) { auto it2 = it, it3 = it; it2++, it3--; if (it2 != a[x.c].end()) modify(it2->l - it3->r, -1); } if (x.l != x.r) modify(1, x.r - x.l); modify(a[x.c].begin()->l, 1), modify(n - a[x.c].rbegin()->r + 1, 1), a[x.c].erase(x); if (!a[x.c].empty()) modify(a[x.c].begin()->l, -1), modify(n - a[x.c].rbegin()->r + 1, -1); } void insert(node x) { if (!a[x.c].empty()) modify(a[x.c].begin()->l, 1), modify(n - a[x.c].rbegin()->r + 1, 1); a[x.c].insert(x), modify(a[x.c].begin()->l, -1), modify(n - a[x.c].rbegin()->r + 1, -1); auto it = a[x.c].find(x); if (it != a[x.c].begin()) it--, modify(x.l - it->r, -1), it++; it++; if (it != a[x.c].end()) modify(it->l - x.r, -1); it--; if (it != a[x.c].begin()) { auto it2 = it, it3 = it; it2++, it3--; if (it2 != a[x.c].end()) modify(it2->l - it3->r, 1); } if (x.l != x.r) modify(1, x.l - x.r); } std::set<node>::iterator split(int p) { auto x = st.upper_bound((node){p, -1, -1}); x--; if (x->l == p) return x; else if (p > x->r) return st.end(); else { node t = (*x); erase(t), st.erase(x); st.insert((node){t.l, p - 1, t.c}), st.insert((node){p, t.r, t.c}); insert((node){t.l, p - 1, t.c}), insert((node){p, t.r, t.c}); return st.find((node){p, t.r, t.c}); } } void assign(int l, int r, int c) { auto rx = split(r + 1), lx = split(l); auto p = lx; do { erase(*p), p++; } while (p != rx); st.erase(lx, rx), st.insert((node){l, r, c}); insert((node){l, r, c}); } void debug() { for (int i = 1; i <= 5; i++) { printf("%d : ", i); for (auto x : a[i]) printf("(%d %d %d)\t", x.l, x.r, x.c); puts(""); } for (auto x : st) printf("(%d %d %d)\t", x.l, x.r, x.c); puts("\n"); } std::map<int, int> mp; int idcnt; int id(int x) { return mp.count(x) ? mp[x] : mp[x] = (++idcnt); } int main() { scanf("%d%d", &n, &q); for (int i = 1, x; i <= n; i++) scanf("%d", &x), st.insert((node){i, i, id(x)}), insert((node){i, i, id(x)}); for (int i = 1, opt, x, l, r; i <= q; i++) { scanf("%d", &opt); if (opt == 2) { scanf("%d", &x); long long ans = 1ll * x * (n - x + 1) + 1ll * x * (x - 1); printf("%lld\n", ans + sum(x)); } else scanf("%d%d%d", &l, &r, &x), assign(l, r, id(x)); } }
CPP
1423_G. Growing flowers
Sarah has always been a lover of nature, and a couple of years ago she saved up enough money to travel the world and explore all the things built by nature over its lifetime on earth. During this time she visited some truly special places which were left untouched for centuries, from watching icebergs in freezing weather to scuba-diving in oceans and admiring the sea life, residing unseen. These experiences were enhanced with breathtaking views built by mountains over time and left there for visitors to see for years on end. Over time, all these expeditions took a toll on Sarah and culminated in her decision to settle down in the suburbs and live a quiet life. However, as Sarah's love for nature never faded, she started growing flowers in her garden in an attempt to stay connected with nature. At the beginning she planted only blue orchids, but over time she started using different flower types to add variety to her collection of flowers. This collection of flowers can be represented as an array of N flowers and the i-th of them has a type associated with it, denoted as A_i. Each resident, passing by her collection and limited by the width of his view, can only see K contiguous flowers at each moment in time. To see the whole collection, the resident will look at the first K contiguous flowers A_1, A_2, ..., A_K, then shift his view by one flower and look at the next section of K contiguous flowers A_2, A_3, ..., A_{K+1} and so on until they scan the whole collection, ending with section A_{N-K+1}, ..., A_{N-1}, A_N. Each resident determines the beautiness of a section of K flowers as the number of distinct flower types in that section. Furthermore, the beautiness of the whole collection is calculated by summing the beautiness values of each contiguous section. Formally, beautiness B_i of a section starting at the i-th position is calculated as B_i = distinct(A_i, A_{i+1}, ..., A_{i+K-1}), and beautiness of the collection B is calculated as B=B_1 + B_2 + ... + B_{N-K+1}. In addition, as Sarah wants to keep her collection of flowers have a fresh feel, she can also pick two points L and R, dispose flowers between those two points and plant new flowers, all of them being the same type. You will be given Q queries and each of those queries will be of the following two types: 1. You will be given three integers L, R, X describing that Sarah has planted flowers of type X between positions L and R inclusive. Formally collection is changed such that A[i]=X for all i in range [L.. R]. 2. You will be given integer K, width of the resident's view and you have to determine the beautiness value B resident has associated with the collection For each query of second type print the result – beautiness B of the collection. Input First line contains two integers N and Q \;(1 ≀ N, Q ≀ 10^5) β€” number of flowers and the number of queries, respectively. The second line contains N integers A_1, A_2, ..., A_N\;(1 ≀ A_i ≀ 10^9) β€” where A_i represents type of the i-th flower. Each of the next Q lines describe queries and start with integer T∈\{1, 2\}. * If T = 1, there will be three more integers in the line L, R, X\;(1 ≀ L, R ≀ N;\; 1 ≀ X ≀ 10^9) β€” L and R describing boundaries and X describing the flower type * If T = 2, there will be one more integer in the line K\;(1 ≀ K ≀ N) β€” resident's width of view Output For each query of the second type print the beautiness B of the collection. Example Input 5 5 1 2 3 4 5 2 3 1 1 2 5 2 4 1 2 4 5 2 2 Output 9 6 4 Note Let's look at the example. Initially the collection is [1, 2, 3, 4, 5]. In the first query K = 3, we consider sections of three flowers with the first being [1, 2, 3]. Since beautiness of the section is the number of distinct flower types in that section, B_1 = 3. Second section is [2, 3, 4] and B_2 = 3. Third section is [3, 4, 5] and B_3 = 3, since the flower types are all distinct. The beautiness value resident has associated with the collection is B = B_1 + B_2 + B_3 = 3 + 3 + 3 = 9. After the second query, the collection becomes [5, 5, 3, 4, 5]. For the third query K = 4, so we consider sections of four flowers with the first being [5, 5, 3, 4]. There are three distinct flower types [5, 3, 4] in this section, so B_1 = 3. Second section [5, 3, 4, 5] also has 3 distinct flower types, so B_2 = 3. The beautiness value resident has associated with the collection is B = B_1 + B_2 = 3 + 3 = 6 After the fourth query, the collection becomes [5, 5, 5, 5, 5]. For the fifth query K = 2 and in this case all the four sections are same with each of them being [5, 5]. Beautiness of [5, 5] is 1 since there is only one distinct element in this section [5]. Beautiness of the whole collection is B = B_1 + B_2 + B_3 + B_4 = 1 + 1 + 1 + 1 = 4
2
13
#include <bits/stdc++.h> using namespace std; inline int read() { int w = 0, x = 0; char c = getchar(); while (!isdigit(c)) w |= c == '-', c = getchar(); while (isdigit(c)) x = x * 10 + (c ^ 48), c = getchar(); return w ? -x : x; } namespace star { const int maxn = 1e5 + 10; int n, m; struct sec { int l, r, w; sec(int l = 0, int r = 0, int w = 0) : l(l), r(r), w(w) {} inline bool operator<(const sec &b) const { return r < b.r; } }; pair<long long, long long> e[maxn << 2]; void update(int x, int y, pair<int, int> k, int ro = 1, int l = 1, int r = n) { if (x > y) return; if (x == l and y == r) return e[ro].first += k.first, e[ro].second += k.second, void(); e[(ro << 1)] = make_pair(e[(ro << 1)].first + e[ro].first, e[(ro << 1)].second + e[ro].second), e[(ro << 1 | 1)] = make_pair(e[(ro << 1 | 1)].first + e[ro].first + (((l + r) >> 1) + 1ll - l) * e[ro].second, e[(ro << 1 | 1)].second + e[ro].second), e[ro] = make_pair(0, 0); if (y <= ((l + r) >> 1)) update(x, y, k, (ro << 1), l, ((l + r) >> 1)); else if (x > ((l + r) >> 1)) update(x, y, k, (ro << 1 | 1), ((l + r) >> 1) + 1, r); else update(x, ((l + r) >> 1), k, (ro << 1), l, ((l + r) >> 1)), update(((l + r) >> 1) + 1, y, make_pair((((l + r) >> 1) + 1ll - x) * k.second + k.first, k.second), (ro << 1 | 1), ((l + r) >> 1) + 1, r); } long long query(int x, int ro = 1, int l = 1, int r = n) { if (l == r) return e[ro].first; e[(ro << 1)] = make_pair(e[(ro << 1)].first + e[ro].first, e[(ro << 1)].second + e[ro].second), e[(ro << 1 | 1)] = make_pair(e[(ro << 1 | 1)].first + e[ro].first + (((l + r) >> 1) + 1ll - l) * e[ro].second, e[(ro << 1 | 1)].second + e[ro].second), e[ro] = make_pair(0, 0); return x <= ((l + r) >> 1) ? query(x, (ro << 1), l, ((l + r) >> 1)) : query(x, (ro << 1 | 1), ((l + r) >> 1) + 1, r); } set<sec> st[maxn << 1]; inline void split(int x) { sec res = *st[0].lower_bound(sec(0, x, 0)); if (res.r == x) return; st[0].erase(res), st[0].insert(sec(res.l, x, res.w)), st[0].insert(sec(x + 1, res.r, res.w)); st[res.w].erase(res), st[res.w].insert(sec(res.l, x, res.w)), st[res.w].insert(sec(x + 1, res.r, res.w)); } inline void del(sec x) { int l = x.l, r = x.r, w = x.w; auto it = st[w].find(x); int pre = it == st[w].begin() ? 0 : (--it)->r, a1 = l - pre, a2 = n - l + 1; if (a1 > a2) swap(a1, a2); if (l < r) update(1, n - r + 1, make_pair(-(r - l), 0)), update(n - r + 2, n - l, make_pair(-(r - 1 - l), 1)); update(1, a1, make_pair(-1, -1)), update(a1 + 1, a2, make_pair(-a1, 0)), update(a2 + 1, a2 + a1 - 1, make_pair(-(a1 - 1), 1)); st[0].erase(x), st[w].erase(x); } inline void insert(sec x) { int l = x.l, r = x.r, w = x.w; st[0].insert(x); auto it = st[w].insert(x).first; int pre = it == st[w].begin() ? 0 : (--it)->r, a1 = l - pre, a2 = n - l + 1; if (a1 > a2) swap(a1, a2); if (l < r) update(1, n - r + 1, make_pair(r - l, 0)), update(n - r + 2, n - l, make_pair(r - 1 - l, -1)); update(1, a1, make_pair(1, 1)), update(a1 + 1, a2, make_pair(a1, 0)), update(a2 + 1, a2 + a1 - 1, make_pair(a1 - 1, -1)); } inline int id(int x) { static unordered_map<int, int> mp; static int tot; if (!mp[x]) mp[x] = ++tot; return mp[x]; } inline void work() { n = read(), m = read(); for (int i = 1; i <= n; i++) insert(sec(i, i, id(read()))); while (m--) if (read() == 1) { int l = read(), r = read(), w = id(read()); split(l - 1), split(r); sec i, j; set<sec>::iterator it; while ((it = st[0].lower_bound(sec(0, l, 0))) != st[0].end() and it->l <= r) { int x = it->w; it = st[x].lower_bound(sec(0, l, 0)); i = *it++; if (it != st[x].end()) j = *it, del(j); else j = sec(0, 0, 0); del(i); if (j.w) insert(j); } it = st[w].lower_bound(sec(0, l, 0)); if (it != st[w].end()) j = *it, del(j); else j = sec(0, 0, 0); insert(sec(l, r, w)); if (j.w) insert(j); } else printf("%lld\n", query(read())); } } // namespace star signed main() { star::work(); return 0; }
CPP
1423_G. Growing flowers
Sarah has always been a lover of nature, and a couple of years ago she saved up enough money to travel the world and explore all the things built by nature over its lifetime on earth. During this time she visited some truly special places which were left untouched for centuries, from watching icebergs in freezing weather to scuba-diving in oceans and admiring the sea life, residing unseen. These experiences were enhanced with breathtaking views built by mountains over time and left there for visitors to see for years on end. Over time, all these expeditions took a toll on Sarah and culminated in her decision to settle down in the suburbs and live a quiet life. However, as Sarah's love for nature never faded, she started growing flowers in her garden in an attempt to stay connected with nature. At the beginning she planted only blue orchids, but over time she started using different flower types to add variety to her collection of flowers. This collection of flowers can be represented as an array of N flowers and the i-th of them has a type associated with it, denoted as A_i. Each resident, passing by her collection and limited by the width of his view, can only see K contiguous flowers at each moment in time. To see the whole collection, the resident will look at the first K contiguous flowers A_1, A_2, ..., A_K, then shift his view by one flower and look at the next section of K contiguous flowers A_2, A_3, ..., A_{K+1} and so on until they scan the whole collection, ending with section A_{N-K+1}, ..., A_{N-1}, A_N. Each resident determines the beautiness of a section of K flowers as the number of distinct flower types in that section. Furthermore, the beautiness of the whole collection is calculated by summing the beautiness values of each contiguous section. Formally, beautiness B_i of a section starting at the i-th position is calculated as B_i = distinct(A_i, A_{i+1}, ..., A_{i+K-1}), and beautiness of the collection B is calculated as B=B_1 + B_2 + ... + B_{N-K+1}. In addition, as Sarah wants to keep her collection of flowers have a fresh feel, she can also pick two points L and R, dispose flowers between those two points and plant new flowers, all of them being the same type. You will be given Q queries and each of those queries will be of the following two types: 1. You will be given three integers L, R, X describing that Sarah has planted flowers of type X between positions L and R inclusive. Formally collection is changed such that A[i]=X for all i in range [L.. R]. 2. You will be given integer K, width of the resident's view and you have to determine the beautiness value B resident has associated with the collection For each query of second type print the result – beautiness B of the collection. Input First line contains two integers N and Q \;(1 ≀ N, Q ≀ 10^5) β€” number of flowers and the number of queries, respectively. The second line contains N integers A_1, A_2, ..., A_N\;(1 ≀ A_i ≀ 10^9) β€” where A_i represents type of the i-th flower. Each of the next Q lines describe queries and start with integer T∈\{1, 2\}. * If T = 1, there will be three more integers in the line L, R, X\;(1 ≀ L, R ≀ N;\; 1 ≀ X ≀ 10^9) β€” L and R describing boundaries and X describing the flower type * If T = 2, there will be one more integer in the line K\;(1 ≀ K ≀ N) β€” resident's width of view Output For each query of the second type print the beautiness B of the collection. Example Input 5 5 1 2 3 4 5 2 3 1 1 2 5 2 4 1 2 4 5 2 2 Output 9 6 4 Note Let's look at the example. Initially the collection is [1, 2, 3, 4, 5]. In the first query K = 3, we consider sections of three flowers with the first being [1, 2, 3]. Since beautiness of the section is the number of distinct flower types in that section, B_1 = 3. Second section is [2, 3, 4] and B_2 = 3. Third section is [3, 4, 5] and B_3 = 3, since the flower types are all distinct. The beautiness value resident has associated with the collection is B = B_1 + B_2 + B_3 = 3 + 3 + 3 = 9. After the second query, the collection becomes [5, 5, 3, 4, 5]. For the third query K = 4, so we consider sections of four flowers with the first being [5, 5, 3, 4]. There are three distinct flower types [5, 3, 4] in this section, so B_1 = 3. Second section [5, 3, 4, 5] also has 3 distinct flower types, so B_2 = 3. The beautiness value resident has associated with the collection is B = B_1 + B_2 = 3 + 3 = 6 After the fourth query, the collection becomes [5, 5, 5, 5, 5]. For the fifth query K = 2 and in this case all the four sections are same with each of them being [5, 5]. Beautiness of [5, 5] is 1 since there is only one distinct element in this section [5]. Beautiness of the whole collection is B = B_1 + B_2 + B_3 + B_4 = 1 + 1 + 1 + 1 = 4
2
13
#include <bits/stdc++.h> using namespace std; constexpr int Maxn = 2e5 + 5; int n, m; int a[Maxn]; namespace range_tree { using value_t = int; struct range { int l, r; mutable value_t c; range() : l(0), r(0), c(value_t()) {} range(int l, int r, const value_t &c) : l(l), r(r), c(c) {} range(const range &x) : l(x.l), r(x.r), c(x.c) {} friend bool operator<(const range &x, const range &y) { return x.l < y.l; } }; using rtree = set<range>; void insert(rtree &, const range &); void erase(const range &); rtree::iterator split(rtree &S, int p) { auto x = prev(S.upper_bound(range(p, -1, value_t()))); if (x->l == p) return x; else if (p > x->r) return S.end(); else { range t = *x; erase(t); S.erase(t); insert(S, range(t.l, p - 1, t.c)); insert(S, range(p, t.r, t.c)); return S.find(range(p, t.r, t.c)); } } void assign(rtree &S, int l, int r, value_t c) { auto itr = split(S, r + 1), itl = split(S, l); for (auto p = itl; p != itr; ++p) erase(*p); S.erase(itl, itr); insert(S, range(l, r, c)); } } // namespace range_tree using range_tree::assign; using range_tree::insert; using range_tree::range; using range_tree::rtree; using range_tree::value_t; namespace range_tree_helper { void insert(const range &); void erase(const range &); } // namespace range_tree_helper void range_tree::insert(rtree &S, const range &r) { S.insert(r); range_tree_helper::insert(r); } void range_tree::erase(const range &r) { range_tree_helper::erase(r); } namespace ds { struct fenwick_tree { int64_t b[Maxn]; fenwick_tree() {} void add(int x, int64_t y) { while (x < Maxn) { b[x] += y; x += (x & -x); } } int64_t qry(int x) { int64_t res = 0; while (x) { res += b[x]; x -= (x & -x); } return res; } } fen1, fen2; void modify(int pos, int64_t x) { fen1.add(pos, -x * pos); fen2.add(pos, x); } int64_t query(int k) { return fen1.qry(k) + fen2.qry(k) * k; } } // namespace ds using namespace ds; rtree st[Maxn]; void range_tree_helper::insert(const range &x) { int col = x.c; if (!st[col].empty()) { modify(st[col].begin()->l, -1); modify(n - st[col].rbegin()->r + 1, -1); } st[col].insert(x); modify(st[col].begin()->l, 1); modify(n - st[col].rbegin()->r + 1, 1); if (x.l != x.r) modify(1, x.r - x.l); auto it = st[col].find(x); if (it != st[col].begin()) { modify(x.l - prev(it)->r, 1); } if (next(it) != st[col].end()) { modify(next(it)->l - x.r, 1); } if (it != st[col].begin() && next(it) != st[col].end()) { modify(next(it)->l - prev(it)->r, -1); } } void range_tree_helper::erase(const range &x) { int col = x.c; if (x.l != x.r) modify(1, -(x.r - x.l)); auto it = st[col].find(x); if (it != st[col].begin()) { modify(x.l - prev(it)->r, -1); } if (next(it) != st[col].end()) { modify(next(it)->l - x.r, -1); } if (it != st[col].begin() && next(it) != st[col].end()) { modify(next(it)->l - prev(it)->r, 1); } modify(n - st[col].rbegin()->r + 1, -1); modify(st[col].begin()->l, -1); st[col].erase(x); if (!st[col].empty()) { modify(st[col].begin()->l, 1); modify(n - st[col].rbegin()->r + 1, 1); } } int64_t calc(int k) { int64_t ans = 1LL * k * n; ans -= query(k); return ans; } int main() { auto get_id = [](int x) -> int { static unordered_map<int, int> mp; static int ids = 0; if (mp.find(x) == mp.end()) mp[x] = ++ids; return mp[x]; }; scanf("%d %d", &n, &m); rtree chtholly; for (int i = 1; i <= n; ++i) { scanf("%d", a + i); a[i] = get_id(a[i]); insert(chtholly, range(i, i, a[i])); } while (m--) { int op; scanf("%d", &op); if (op == 1) { int l, r, x; scanf("%d %d %d", &l, &r, &x); x = get_id(x); assign(chtholly, l, r, x); } else { int x; scanf("%d", &x); printf("%lld\n", calc(x)); } } return 0; }
CPP
1423_G. Growing flowers
Sarah has always been a lover of nature, and a couple of years ago she saved up enough money to travel the world and explore all the things built by nature over its lifetime on earth. During this time she visited some truly special places which were left untouched for centuries, from watching icebergs in freezing weather to scuba-diving in oceans and admiring the sea life, residing unseen. These experiences were enhanced with breathtaking views built by mountains over time and left there for visitors to see for years on end. Over time, all these expeditions took a toll on Sarah and culminated in her decision to settle down in the suburbs and live a quiet life. However, as Sarah's love for nature never faded, she started growing flowers in her garden in an attempt to stay connected with nature. At the beginning she planted only blue orchids, but over time she started using different flower types to add variety to her collection of flowers. This collection of flowers can be represented as an array of N flowers and the i-th of them has a type associated with it, denoted as A_i. Each resident, passing by her collection and limited by the width of his view, can only see K contiguous flowers at each moment in time. To see the whole collection, the resident will look at the first K contiguous flowers A_1, A_2, ..., A_K, then shift his view by one flower and look at the next section of K contiguous flowers A_2, A_3, ..., A_{K+1} and so on until they scan the whole collection, ending with section A_{N-K+1}, ..., A_{N-1}, A_N. Each resident determines the beautiness of a section of K flowers as the number of distinct flower types in that section. Furthermore, the beautiness of the whole collection is calculated by summing the beautiness values of each contiguous section. Formally, beautiness B_i of a section starting at the i-th position is calculated as B_i = distinct(A_i, A_{i+1}, ..., A_{i+K-1}), and beautiness of the collection B is calculated as B=B_1 + B_2 + ... + B_{N-K+1}. In addition, as Sarah wants to keep her collection of flowers have a fresh feel, she can also pick two points L and R, dispose flowers between those two points and plant new flowers, all of them being the same type. You will be given Q queries and each of those queries will be of the following two types: 1. You will be given three integers L, R, X describing that Sarah has planted flowers of type X between positions L and R inclusive. Formally collection is changed such that A[i]=X for all i in range [L.. R]. 2. You will be given integer K, width of the resident's view and you have to determine the beautiness value B resident has associated with the collection For each query of second type print the result – beautiness B of the collection. Input First line contains two integers N and Q \;(1 ≀ N, Q ≀ 10^5) β€” number of flowers and the number of queries, respectively. The second line contains N integers A_1, A_2, ..., A_N\;(1 ≀ A_i ≀ 10^9) β€” where A_i represents type of the i-th flower. Each of the next Q lines describe queries and start with integer T∈\{1, 2\}. * If T = 1, there will be three more integers in the line L, R, X\;(1 ≀ L, R ≀ N;\; 1 ≀ X ≀ 10^9) β€” L and R describing boundaries and X describing the flower type * If T = 2, there will be one more integer in the line K\;(1 ≀ K ≀ N) β€” resident's width of view Output For each query of the second type print the beautiness B of the collection. Example Input 5 5 1 2 3 4 5 2 3 1 1 2 5 2 4 1 2 4 5 2 2 Output 9 6 4 Note Let's look at the example. Initially the collection is [1, 2, 3, 4, 5]. In the first query K = 3, we consider sections of three flowers with the first being [1, 2, 3]. Since beautiness of the section is the number of distinct flower types in that section, B_1 = 3. Second section is [2, 3, 4] and B_2 = 3. Third section is [3, 4, 5] and B_3 = 3, since the flower types are all distinct. The beautiness value resident has associated with the collection is B = B_1 + B_2 + B_3 = 3 + 3 + 3 = 9. After the second query, the collection becomes [5, 5, 3, 4, 5]. For the third query K = 4, so we consider sections of four flowers with the first being [5, 5, 3, 4]. There are three distinct flower types [5, 3, 4] in this section, so B_1 = 3. Second section [5, 3, 4, 5] also has 3 distinct flower types, so B_2 = 3. The beautiness value resident has associated with the collection is B = B_1 + B_2 = 3 + 3 = 6 After the fourth query, the collection becomes [5, 5, 5, 5, 5]. For the fifth query K = 2 and in this case all the four sections are same with each of them being [5, 5]. Beautiness of [5, 5] is 1 since there is only one distinct element in this section [5]. Beautiness of the whole collection is B = B_1 + B_2 + B_3 + B_4 = 1 + 1 + 1 + 1 = 4
2
13
#include <bits/stdc++.h> const int N = 200000; int n, q; struct BIT { long long tree[N + 5]; int lowbit(int x) { return x & -x; } void update(int x, int k) { for (int i = x; i <= n; i += lowbit(i)) tree[i] += k; } long long sum(int x) { long long ans = 0; for (int i = x; i; i -= lowbit(i)) ans += tree[i]; return ans; } } t1, t2; long long sum(int x) { return t1.sum(x) + t2.sum(x) * x; } void modify(int x, int d) { t1.update(x, -x * d), t2.update(x, d); } struct node { int l, r, c; friend bool operator<(const node &a, const node &b) { return a.l < b.l; } }; std::set<node> st, a[N + 5]; void erase(node x) { auto it = a[x.c].find(x); if (it != a[x.c].begin()) it--, modify(x.l - it->r, 1), it++; it++; if (it != a[x.c].end()) modify(it->l - x.r, 1); it--; if (it != a[x.c].begin()) { auto it2 = it, it3 = it; it2++, it3--; if (it2 != a[x.c].end()) modify(it2->l - it3->r, -1); } if (x.l != x.r) modify(1, x.r - x.l); modify(a[x.c].begin()->l, 1), modify(n - a[x.c].rbegin()->r + 1, 1), a[x.c].erase(x); if (!a[x.c].empty()) modify(a[x.c].begin()->l, -1), modify(n - a[x.c].rbegin()->r + 1, -1); } void insert(node x) { if (!a[x.c].empty()) modify(a[x.c].begin()->l, 1), modify(n - a[x.c].rbegin()->r + 1, 1); a[x.c].insert(x), modify(a[x.c].begin()->l, -1), modify(n - a[x.c].rbegin()->r + 1, -1); auto it = a[x.c].find(x); if (it != a[x.c].begin()) it--, modify(x.l - it->r, -1), it++; it++; if (it != a[x.c].end()) modify(it->l - x.r, -1); it--; if (it != a[x.c].begin()) { auto it2 = it, it3 = it; it2++, it3--; if (it2 != a[x.c].end()) modify(it2->l - it3->r, 1); } if (x.l != x.r) modify(1, x.l - x.r); } std::set<node>::iterator split(int p) { auto x = st.upper_bound((node){p, -1, -1}); x--; if (x->l == p) return x; else if (p > x->r) return st.end(); else { node t = (*x); erase(t), st.erase(x); st.insert((node){t.l, p - 1, t.c}), st.insert((node){p, t.r, t.c}); insert((node){t.l, p - 1, t.c}), insert((node){p, t.r, t.c}); return st.find((node){p, t.r, t.c}); } } void assign(int l, int r, int c) { auto rx = split(r + 1), lx = split(l); auto p = lx; do { erase(*p), p++; } while (p != rx); st.erase(lx, rx), st.insert((node){l, r, c}); insert((node){l, r, c}); } void debug() { for (int i = 1; i <= 5; i++) { printf("%d : ", i); for (auto x : a[i]) printf("(%d %d %d)\t", x.l, x.r, x.c); puts(""); } for (auto x : st) printf("(%d %d %d)\t", x.l, x.r, x.c); puts("\n"); } std::map<int, int> mp; int idcnt; int id(int x) { return mp.count(x) ? mp[x] : mp[x] = (++idcnt); } int main() { scanf("%d%d", &n, &q); for (int i = 1, x; i <= n; i++) scanf("%d", &x), st.insert((node){i, i, id(x)}), insert((node){i, i, id(x)}); for (int i = 1, opt, x, l, r; i <= q; i++) { scanf("%d", &opt); if (opt == 2) { scanf("%d", &x); long long ans = 1ll * x * (n - x + 1) + 1ll * x * (x - 1); printf("%lld\n", ans + sum(x)); } else scanf("%d%d%d", &l, &r, &x), assign(l, r, id(x)); } }
CPP
1423_G. Growing flowers
Sarah has always been a lover of nature, and a couple of years ago she saved up enough money to travel the world and explore all the things built by nature over its lifetime on earth. During this time she visited some truly special places which were left untouched for centuries, from watching icebergs in freezing weather to scuba-diving in oceans and admiring the sea life, residing unseen. These experiences were enhanced with breathtaking views built by mountains over time and left there for visitors to see for years on end. Over time, all these expeditions took a toll on Sarah and culminated in her decision to settle down in the suburbs and live a quiet life. However, as Sarah's love for nature never faded, she started growing flowers in her garden in an attempt to stay connected with nature. At the beginning she planted only blue orchids, but over time she started using different flower types to add variety to her collection of flowers. This collection of flowers can be represented as an array of N flowers and the i-th of them has a type associated with it, denoted as A_i. Each resident, passing by her collection and limited by the width of his view, can only see K contiguous flowers at each moment in time. To see the whole collection, the resident will look at the first K contiguous flowers A_1, A_2, ..., A_K, then shift his view by one flower and look at the next section of K contiguous flowers A_2, A_3, ..., A_{K+1} and so on until they scan the whole collection, ending with section A_{N-K+1}, ..., A_{N-1}, A_N. Each resident determines the beautiness of a section of K flowers as the number of distinct flower types in that section. Furthermore, the beautiness of the whole collection is calculated by summing the beautiness values of each contiguous section. Formally, beautiness B_i of a section starting at the i-th position is calculated as B_i = distinct(A_i, A_{i+1}, ..., A_{i+K-1}), and beautiness of the collection B is calculated as B=B_1 + B_2 + ... + B_{N-K+1}. In addition, as Sarah wants to keep her collection of flowers have a fresh feel, she can also pick two points L and R, dispose flowers between those two points and plant new flowers, all of them being the same type. You will be given Q queries and each of those queries will be of the following two types: 1. You will be given three integers L, R, X describing that Sarah has planted flowers of type X between positions L and R inclusive. Formally collection is changed such that A[i]=X for all i in range [L.. R]. 2. You will be given integer K, width of the resident's view and you have to determine the beautiness value B resident has associated with the collection For each query of second type print the result – beautiness B of the collection. Input First line contains two integers N and Q \;(1 ≀ N, Q ≀ 10^5) β€” number of flowers and the number of queries, respectively. The second line contains N integers A_1, A_2, ..., A_N\;(1 ≀ A_i ≀ 10^9) β€” where A_i represents type of the i-th flower. Each of the next Q lines describe queries and start with integer T∈\{1, 2\}. * If T = 1, there will be three more integers in the line L, R, X\;(1 ≀ L, R ≀ N;\; 1 ≀ X ≀ 10^9) β€” L and R describing boundaries and X describing the flower type * If T = 2, there will be one more integer in the line K\;(1 ≀ K ≀ N) β€” resident's width of view Output For each query of the second type print the beautiness B of the collection. Example Input 5 5 1 2 3 4 5 2 3 1 1 2 5 2 4 1 2 4 5 2 2 Output 9 6 4 Note Let's look at the example. Initially the collection is [1, 2, 3, 4, 5]. In the first query K = 3, we consider sections of three flowers with the first being [1, 2, 3]. Since beautiness of the section is the number of distinct flower types in that section, B_1 = 3. Second section is [2, 3, 4] and B_2 = 3. Third section is [3, 4, 5] and B_3 = 3, since the flower types are all distinct. The beautiness value resident has associated with the collection is B = B_1 + B_2 + B_3 = 3 + 3 + 3 = 9. After the second query, the collection becomes [5, 5, 3, 4, 5]. For the third query K = 4, so we consider sections of four flowers with the first being [5, 5, 3, 4]. There are three distinct flower types [5, 3, 4] in this section, so B_1 = 3. Second section [5, 3, 4, 5] also has 3 distinct flower types, so B_2 = 3. The beautiness value resident has associated with the collection is B = B_1 + B_2 = 3 + 3 = 6 After the fourth query, the collection becomes [5, 5, 5, 5, 5]. For the fifth query K = 2 and in this case all the four sections are same with each of them being [5, 5]. Beautiness of [5, 5] is 1 since there is only one distinct element in this section [5]. Beautiness of the whole collection is B = B_1 + B_2 + B_3 + B_4 = 1 + 1 + 1 + 1 = 4
2
13
#include <bits/stdc++.h> using namespace std; namespace FGF { int n, m; const int N = 2e5 + 5; int a[N]; struct Node { int l, r, x; Node() {} Node(int _l, int _r, int _c) : l(_l), r(_r), x(_c) {} bool operator<(const Node &a) const { return l < a.l; } }; int id(int x) { static unordered_map<int, int> mp; static int tot = 0; if (!mp[x]) mp[x] = ++tot; return mp[x]; } set<pair<int, int> > st[N]; set<Node> s; long long tas[N << 2], tak[N << 2], sum[N << 2]; void add(int ro, int l, int r, long long s, long long k) { sum[ro] += s * (r - l + 1) + k * (r - l) * (r - l + 1) / 2; tas[ro] += s, tak[ro] += k; } void pushdown(int ro, int l, int r) { if (tas[ro] || tak[ro]) { add(ro << 1, l, ((l + r) >> 1), tas[ro], tak[ro]), add(ro << 1 | 1, ((l + r) >> 1) + 1, r, tas[ro] + tak[ro] * (((l + r) >> 1) - l + 1), tak[ro]); tas[ro] = tak[ro] = 0; } } void updat(int ro, int l, int r, int L, int R, long long s, long long k) { if (L == l && r == R) return add(ro, l, r, s, k); pushdown(ro, l, r); if (R <= ((l + r) >> 1)) return updat(ro << 1, l, ((l + r) >> 1), L, R, s, k); if (L > ((l + r) >> 1)) return updat(ro << 1 | 1, ((l + r) >> 1) + 1, r, L, R, s, k); updat(ro << 1, l, ((l + r) >> 1), L, ((l + r) >> 1), s, k), updat(ro << 1 | 1, ((l + r) >> 1) + 1, r, ((l + r) >> 1) + 1, R, s + k * (((l + r) >> 1) - L + 1), k); } long long query(int ro, int l, int r, int x) { if (l == r) return sum[ro]; pushdown(ro, l, r); return x <= ((l + r) >> 1) ? query(ro << 1, l, ((l + r) >> 1), x) : query(ro << 1 | 1, ((l + r) >> 1) + 1, r, x); } void inser(int l, int r, int x) { x = id(x); s.insert(Node(l, r, x)); set<pair<int, int> >::iterator it = st[x].insert(make_pair(l, r)).first; int pre = (--it)->second; it++, it++; int nxt = it->first; int mi = min(l - pre, nxt - r), mx = max(l - pre, nxt - r); if (mi) updat(1, 1, n, 1, mi, r - l + 1, 1); if (mi < mx) updat(1, 1, n, mi + 1, mx, r - l + mi, 0); if (mx + 1 <= nxt - pre - 1) updat(1, 1, n, mx + 1, nxt - pre - 1, r - l + mi - 1, -1); } set<Node>::iterator split(int p) { set<Node>::iterator jt = s.lower_bound(Node(p, 0, 0)); if (jt->l == p) return jt; jt--; int l = jt->l, r = jt->r, x = jt->x; s.erase(jt), st[x].erase(make_pair(l, r)); s.insert(Node(l, p - 1, x)), st[x].insert(make_pair(l, p - 1)), st[x].insert(make_pair(p, r)); return s.insert(Node(p, r, x)).first; } void del(int l, int r) { set<Node>::iterator rt = split(r + 1), lt = split(l), jt; for (jt = lt; jt != rt; jt++) { int l = jt->l, r = jt->r, x = jt->x; set<pair<int, int> >::iterator it = st[x].insert(make_pair(l, r)).first; int pre = (--it)->second; it++, it++; int nxt = it->first; int mi = min(l - pre, nxt - r), mx = max(l - pre, nxt - r); if (mi) updat(1, 1, n, 1, mi, -(r - l + 1), -1); if (mi < mx) updat(1, 1, n, mi + 1, mx, -(r - l + mi), 0); if (mx + 1 <= nxt - pre - 1) updat(1, 1, n, mx + 1, nxt - pre - 1, -(r - l + mi - 1), 1); st[x].erase(--it); } s.erase(lt, rt); } void work() { scanf("%d%d", &n, &m); s.insert(Node(0, 0, 0)), s.insert(Node(n + 1, n + 1, 0)); for (int i = 1; i <= n + m; i++) st[i].insert(make_pair(0, 0)), st[i].insert(make_pair(n + 1, n + 1)); for (int i = 1; i <= n; i++) scanf("%d", &a[i]), inser(i, i, a[i]); while (m--) { int op, l, r, x; scanf("%d", &op); if (op == 1) scanf("%d%d%d", &l, &r, &x), del(l, r), inser(l, r, x); else scanf("%d", &x), printf("%lld\n", query(1, 1, n, x)); } } } // namespace FGF int main() { FGF::work(); return 0; }
CPP
1442_F. Differentiating Games
This is an interactive problem Ginny is taking an exam on game theory. The professor is tired of hearing the same answers over and over again, so he offered Ginny to play a game instead of a standard exam. As known from the course, a combinatorial game on a graph with multiple starting positions is a game with a directed graph and multiple starting vertices holding a token each. Two players take turns moving one of the tokens along the graph edges on each turn. The player who can't make a move loses the game. If both players can play an infinitely long game without losing, a draw is called. For the exam, the professor drew an acyclic directed graph and chose one of its vertices. Ginny needs to guess the vertex the professor chose. To do so, Ginny can choose a multiset of vertices S several times and ask the professor: "If I put one token in each vertex of the given graph for each occurrence of the vertex in the multiset S, and then one more in the selected vertex, what would be the result of the combinatorial game?". Having given the task, the professor left the room to give Ginny some time to prepare for the game. Ginny thinks that she's being tricked because the problem is impossible to solve. Therefore, while the professor is away, she wants to add or remove several edges from the graph. Even though the original graph was acyclic, edges could be added to the graph to make cycles appear. Interaction In this task, interaction consists of several phases. In the first phase, the interactor gives as an input to your program three integers N (1 ≀ N ≀ 1000), M (0 ≀ M ≀ 100 000), T (1 ≀ T ≀ 2000): the number of vertices and edges in the initial graph, and the number of times Ginny has to guess the chosen vertex. The next M lines contain pairs of vertices a_i b_i (1 ≀ a_i, b_i ≀ N): beginning and end of corresponding graph edges. The graph is guaranteed to be acyclic and all of its edges to be distinct. The solution should print an integer K (0 ≀ K ≀ 4242): the number of edges to change in the graph. The next K lines should contain either "+ a_i b_i" or "- a_i b_i": the beginning and the end of an edge that Ginny has to add or remove accordingly. You are allowed to add preexisting edges to the graph. Operations are performed in the order of appearance, so Ginny is allowed to remove an edge added by the solution. You can only remove an existing edge. The operations can create cycles in the graph. The next T phases are dedicated to guessing the chosen vertices. In each phase, the solution can make at most 20 queries and then print the answer. To query a multiset S, the solution should print "? |S|~S_1~S_2~...~S_{|S|}". The total size of all multisets in a single phase should not exceed 20. The interactor will reply with one of the following words: * "Win", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the first player. * "Lose", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the second player. * "Draw", if a combinatorial game with tokens in multiset S and selected vertex ends in a draw. * "Slow", if the solution made a 21-st request, or the total size of all multisets in a single phase exceeded 20. In this case, the solution should terminate and receive Wrong Answer verdict. As soon as the selected vertex is guessed, that solution should print "! v". If the chosen vertex is guessed correctly, the interactor will print Correct and the solution should either move on to the next phase of guessing or finish its execution if it's the last phase. Otherwise, the interactor will print Wrong, which means that the solution should terminate and will receive the Wrong Answer verdict. The interactor can change the chosen vertex based on graph changes and solution actions, but at every given moment of time, at least one vertex that corresponds to all given interactor answers will exist. Hack format Hacks have the following extra limitations: * T = 1 * you need to specify a single vertex, chosen by the interactor. Hack test format. The first line of input contains three integers N~M~1. The next M lines on input contain edge description in the same format as in the input. The next line contains a single integer v: the number of the chosen vertex. The hack will be successful even if the solution guesses the vertex right, but the vertex will not be the single one to match all performed queries. Example Input 3 2 3 1 2 2 3 Lose Correct Win Correct Draw Correct Output 6 + 2 2 - 1 2 + 2 3 - 2 2 + 3 1 + 2 2 ? 0 ! 1 ? 1 2 ! 3 ? 5 1 3 1 3 1 ! 2 Note In the sample test, the empty lines represent waiting for the input by the other side of the interaction. The real interactor will not print empty lines, and the solution should not print them either. <image> The image above illustrates the sample test. Added edges are coloured in red, and the removed edges are drawn with a dotted line. Three guessing phases denote different ways of getting the answer. * If the solution will query just the chosen vertex, the interactor will return the result of the game in that vertex. The first player loses only if the chosen vertex has the number 1. * If we add a single vertex 2 to the chosen vertex, then if the chosen vertex is either 1 or 2, the game should end in a draw. If vertex number 3 is chosen, then the first player wins. * If we place three tokens in vertex 1 and two tokens in vertex 3, then the game will end in a draw only if vertex 2 is chosen. If the professor chose vertex 3, the first player will win, if the professor chose vertex 1, then the second player will win. In the first test, the interactor will behave as if the chosen vertices are the same as those in the example above. However, if you will try to guess the answer before it limits the options to one single vertex, the solution will get "Wrong Answer", even if you print the same answers. That's because the interactor is allowed to change the chosen vertex if it's consistent with the previous query answers.
2
12
#include <bits/stdc++.h> using namespace std; const int N = 1e3 + 10; const long long mod = 998244353; const long long Inf = 1e18; int inv[1 << 20], cnt, f[N], val[N], mini, id[N]; vector<int> g[N]; bool vis[N]; void dfs(int u) { vis[u] = 1; for (auto v : g[u]) { if (!vis[v]) dfs(v); val[u] += val[v] * f[v]; } if (cnt < mini) { val[u] = 1 << cnt; f[u] = 1; } id[cnt] = u; ++cnt; } void add(int u, int v, int c) { if (c) printf("+ %d %d\n", u, v); else printf("- %d %d\n", u, v); } void check(int u, int i) { if (val[u] & (1 << i)) printf("- %d %d\n", u, id[i]); else printf("+ %d %d\n", u, id[i]); } int main() { int n, m, T; scanf("%d%d%d", &n, &m, &T); while (m--) { int u, v; scanf("%d%d", &u, &v); g[u].push_back(v); } mini = min(n, 20); for (int i = (1); i < (n + 1); ++i) { if (!vis[i]) dfs(i); } printf("%d\n", (mini - 1) * mini / 2 + 4 * (n - mini)); for (int i = (0); i < (n); ++i) { if (i < mini) { for (int j = (0); j < (i); ++j) add(id[i], id[j], 1); } else { add(id[i], id[i], 1); int u = id[i]; int ok = 0; for (int j = (0); j < (mini); ++j) { for (int k = (j + 1); k < (mini); ++k) { for (int l = (k + 1); l < (mini); ++l) { int mask = val[u] ^ (1 << j) ^ (1 << k) ^ (1 << l); if (!ok && !inv[mask]) { ok = 1; inv[mask] = u; check(u, j); check(u, k); check(u, l); } } } } } } char s[10]; while (T--) { int ans = 0, ok = 0; for (int i = (0); i < (mini); ++i) { printf("? 1 %d\n", id[i]); fflush(stdout); scanf("%s", s); if (s[0] == 'W') ans |= 1 << i; if (s[0] == 'L') ok = id[i]; } ans = inv[ans]; if (ok) ans = ok; printf("! %d\n", ans); fflush(stdout); scanf("%s", s); } }
CPP
1442_F. Differentiating Games
This is an interactive problem Ginny is taking an exam on game theory. The professor is tired of hearing the same answers over and over again, so he offered Ginny to play a game instead of a standard exam. As known from the course, a combinatorial game on a graph with multiple starting positions is a game with a directed graph and multiple starting vertices holding a token each. Two players take turns moving one of the tokens along the graph edges on each turn. The player who can't make a move loses the game. If both players can play an infinitely long game without losing, a draw is called. For the exam, the professor drew an acyclic directed graph and chose one of its vertices. Ginny needs to guess the vertex the professor chose. To do so, Ginny can choose a multiset of vertices S several times and ask the professor: "If I put one token in each vertex of the given graph for each occurrence of the vertex in the multiset S, and then one more in the selected vertex, what would be the result of the combinatorial game?". Having given the task, the professor left the room to give Ginny some time to prepare for the game. Ginny thinks that she's being tricked because the problem is impossible to solve. Therefore, while the professor is away, she wants to add or remove several edges from the graph. Even though the original graph was acyclic, edges could be added to the graph to make cycles appear. Interaction In this task, interaction consists of several phases. In the first phase, the interactor gives as an input to your program three integers N (1 ≀ N ≀ 1000), M (0 ≀ M ≀ 100 000), T (1 ≀ T ≀ 2000): the number of vertices and edges in the initial graph, and the number of times Ginny has to guess the chosen vertex. The next M lines contain pairs of vertices a_i b_i (1 ≀ a_i, b_i ≀ N): beginning and end of corresponding graph edges. The graph is guaranteed to be acyclic and all of its edges to be distinct. The solution should print an integer K (0 ≀ K ≀ 4242): the number of edges to change in the graph. The next K lines should contain either "+ a_i b_i" or "- a_i b_i": the beginning and the end of an edge that Ginny has to add or remove accordingly. You are allowed to add preexisting edges to the graph. Operations are performed in the order of appearance, so Ginny is allowed to remove an edge added by the solution. You can only remove an existing edge. The operations can create cycles in the graph. The next T phases are dedicated to guessing the chosen vertices. In each phase, the solution can make at most 20 queries and then print the answer. To query a multiset S, the solution should print "? |S|~S_1~S_2~...~S_{|S|}". The total size of all multisets in a single phase should not exceed 20. The interactor will reply with one of the following words: * "Win", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the first player. * "Lose", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the second player. * "Draw", if a combinatorial game with tokens in multiset S and selected vertex ends in a draw. * "Slow", if the solution made a 21-st request, or the total size of all multisets in a single phase exceeded 20. In this case, the solution should terminate and receive Wrong Answer verdict. As soon as the selected vertex is guessed, that solution should print "! v". If the chosen vertex is guessed correctly, the interactor will print Correct and the solution should either move on to the next phase of guessing or finish its execution if it's the last phase. Otherwise, the interactor will print Wrong, which means that the solution should terminate and will receive the Wrong Answer verdict. The interactor can change the chosen vertex based on graph changes and solution actions, but at every given moment of time, at least one vertex that corresponds to all given interactor answers will exist. Hack format Hacks have the following extra limitations: * T = 1 * you need to specify a single vertex, chosen by the interactor. Hack test format. The first line of input contains three integers N~M~1. The next M lines on input contain edge description in the same format as in the input. The next line contains a single integer v: the number of the chosen vertex. The hack will be successful even if the solution guesses the vertex right, but the vertex will not be the single one to match all performed queries. Example Input 3 2 3 1 2 2 3 Lose Correct Win Correct Draw Correct Output 6 + 2 2 - 1 2 + 2 3 - 2 2 + 3 1 + 2 2 ? 0 ! 1 ? 1 2 ! 3 ? 5 1 3 1 3 1 ! 2 Note In the sample test, the empty lines represent waiting for the input by the other side of the interaction. The real interactor will not print empty lines, and the solution should not print them either. <image> The image above illustrates the sample test. Added edges are coloured in red, and the removed edges are drawn with a dotted line. Three guessing phases denote different ways of getting the answer. * If the solution will query just the chosen vertex, the interactor will return the result of the game in that vertex. The first player loses only if the chosen vertex has the number 1. * If we add a single vertex 2 to the chosen vertex, then if the chosen vertex is either 1 or 2, the game should end in a draw. If vertex number 3 is chosen, then the first player wins. * If we place three tokens in vertex 1 and two tokens in vertex 3, then the game will end in a draw only if vertex 2 is chosen. If the professor chose vertex 3, the first player will win, if the professor chose vertex 1, then the second player will win. In the first test, the interactor will behave as if the chosen vertices are the same as those in the example above. However, if you will try to guess the answer before it limits the options to one single vertex, the solution will get "Wrong Answer", even if you print the same answers. That's because the interactor is allowed to change the chosen vertex if it's consistent with the previous query answers.
2
12
#include <bits/stdc++.h> using namespace std; const int c = 1002, k = 1 << 20; int n, m, q, ert[c], mini, inv[k], ts[c], cnt; vector<int> sz[c]; bool v[c], sp[c]; string s; void add(int a, int b, int c) { if (c) cout << "+ "; else cout << "- "; cout << a << " " << b << "\n"; } void valt(int a, int b) { if (ert[a] & (1 << b)) add(a, ts[b], 0); else add(a, ts[b], 1); } void dfs(int a) { v[a] = true; for (int x : sz[a]) { if (!v[x]) dfs(x); ert[a] += ert[x] * sp[x]; } ts[cnt] = a; if (cnt < mini) { sp[a] = 1; ert[a] = (1 << cnt); } cnt++; } int main() { ios_base::sync_with_stdio(false); cin >> n >> m >> q; mini = min(n, 20); cout << mini * (mini - 1) / 2 + 4 * (n - mini) << "\n"; for (int i = 1; i <= m; i++) { int a, b; cin >> a >> b; sz[a].push_back(b); } for (int i = 1; i <= n; i++) { if (!v[i]) dfs(i); } for (int id = 1; id <= n; id++) { if (sp[id]) { for (int i = 1; i <= n; i++) { if (sp[i] && ert[id] > ert[i]) add(id, i, 1); } } else { bool jo = 0; add(id, id, 1); for (int i = 0; i < mini; i++) { for (int j = i + 1; j < mini; j++) { for (int k = j + 1; k < mini; k++) { int cel = ert[id] ^ (1 << i) ^ (1 << j) ^ (1 << k); if (!jo && !inv[cel]) { jo = 1; inv[cel] = id; valt(id, i), valt(id, j), valt(id, k); } } } } } } while (q--) { int ans = 0, kul = 0; for (int i = 0; i < mini; i++) { cout.flush() << "? " << 1 << " " << ts[i] << "\n"; string s; cin >> s; if (s == "Lose") kul = ts[i]; if (s == "Win") ans += (1 << i); } ans = inv[ans]; if (kul) ans = kul; cout.flush() << "! " << ans << "\n"; cin >> s; } return 0; }
CPP
1442_F. Differentiating Games
This is an interactive problem Ginny is taking an exam on game theory. The professor is tired of hearing the same answers over and over again, so he offered Ginny to play a game instead of a standard exam. As known from the course, a combinatorial game on a graph with multiple starting positions is a game with a directed graph and multiple starting vertices holding a token each. Two players take turns moving one of the tokens along the graph edges on each turn. The player who can't make a move loses the game. If both players can play an infinitely long game without losing, a draw is called. For the exam, the professor drew an acyclic directed graph and chose one of its vertices. Ginny needs to guess the vertex the professor chose. To do so, Ginny can choose a multiset of vertices S several times and ask the professor: "If I put one token in each vertex of the given graph for each occurrence of the vertex in the multiset S, and then one more in the selected vertex, what would be the result of the combinatorial game?". Having given the task, the professor left the room to give Ginny some time to prepare for the game. Ginny thinks that she's being tricked because the problem is impossible to solve. Therefore, while the professor is away, she wants to add or remove several edges from the graph. Even though the original graph was acyclic, edges could be added to the graph to make cycles appear. Interaction In this task, interaction consists of several phases. In the first phase, the interactor gives as an input to your program three integers N (1 ≀ N ≀ 1000), M (0 ≀ M ≀ 100 000), T (1 ≀ T ≀ 2000): the number of vertices and edges in the initial graph, and the number of times Ginny has to guess the chosen vertex. The next M lines contain pairs of vertices a_i b_i (1 ≀ a_i, b_i ≀ N): beginning and end of corresponding graph edges. The graph is guaranteed to be acyclic and all of its edges to be distinct. The solution should print an integer K (0 ≀ K ≀ 4242): the number of edges to change in the graph. The next K lines should contain either "+ a_i b_i" or "- a_i b_i": the beginning and the end of an edge that Ginny has to add or remove accordingly. You are allowed to add preexisting edges to the graph. Operations are performed in the order of appearance, so Ginny is allowed to remove an edge added by the solution. You can only remove an existing edge. The operations can create cycles in the graph. The next T phases are dedicated to guessing the chosen vertices. In each phase, the solution can make at most 20 queries and then print the answer. To query a multiset S, the solution should print "? |S|~S_1~S_2~...~S_{|S|}". The total size of all multisets in a single phase should not exceed 20. The interactor will reply with one of the following words: * "Win", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the first player. * "Lose", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the second player. * "Draw", if a combinatorial game with tokens in multiset S and selected vertex ends in a draw. * "Slow", if the solution made a 21-st request, or the total size of all multisets in a single phase exceeded 20. In this case, the solution should terminate and receive Wrong Answer verdict. As soon as the selected vertex is guessed, that solution should print "! v". If the chosen vertex is guessed correctly, the interactor will print Correct and the solution should either move on to the next phase of guessing or finish its execution if it's the last phase. Otherwise, the interactor will print Wrong, which means that the solution should terminate and will receive the Wrong Answer verdict. The interactor can change the chosen vertex based on graph changes and solution actions, but at every given moment of time, at least one vertex that corresponds to all given interactor answers will exist. Hack format Hacks have the following extra limitations: * T = 1 * you need to specify a single vertex, chosen by the interactor. Hack test format. The first line of input contains three integers N~M~1. The next M lines on input contain edge description in the same format as in the input. The next line contains a single integer v: the number of the chosen vertex. The hack will be successful even if the solution guesses the vertex right, but the vertex will not be the single one to match all performed queries. Example Input 3 2 3 1 2 2 3 Lose Correct Win Correct Draw Correct Output 6 + 2 2 - 1 2 + 2 3 - 2 2 + 3 1 + 2 2 ? 0 ! 1 ? 1 2 ! 3 ? 5 1 3 1 3 1 ! 2 Note In the sample test, the empty lines represent waiting for the input by the other side of the interaction. The real interactor will not print empty lines, and the solution should not print them either. <image> The image above illustrates the sample test. Added edges are coloured in red, and the removed edges are drawn with a dotted line. Three guessing phases denote different ways of getting the answer. * If the solution will query just the chosen vertex, the interactor will return the result of the game in that vertex. The first player loses only if the chosen vertex has the number 1. * If we add a single vertex 2 to the chosen vertex, then if the chosen vertex is either 1 or 2, the game should end in a draw. If vertex number 3 is chosen, then the first player wins. * If we place three tokens in vertex 1 and two tokens in vertex 3, then the game will end in a draw only if vertex 2 is chosen. If the professor chose vertex 3, the first player will win, if the professor chose vertex 1, then the second player will win. In the first test, the interactor will behave as if the chosen vertices are the same as those in the example above. However, if you will try to guess the answer before it limits the options to one single vertex, the solution will get "Wrong Answer", even if you print the same answers. That's because the interactor is allowed to change the chosen vertex if it's consistent with the previous query answers.
2
12
#include <bits/stdc++.h> using namespace std; void dfs(int v, vector<int> &col, vector<int> &ts, vector<vector<int> > &g) { col[v] = 1; for (auto u : g[v]) if (col[u] == 0) { dfs(u, col, ts, g); } ts.push_back(v); } int main() { ios_base::sync_with_stdio(false); cin.tie(0); int n, m, t; cin >> n >> m >> t; vector<vector<int> > g(n); vector<int> in(n); vector<vector<int> > con(n, vector<int>(n)); for (int(i) = 0; (i) != (m); (i)++) { int a, b; cin >> a >> b; a--, b--; g[a].push_back(b); con[a][b] = 1; in[b]++; } vector<int> ts, col(n); for (int(i) = 0; (i) != (n); (i)++) { if (in[i] == 0 && !col[i]) { dfs(i, col, ts, g); } } struct edit { char c; int fr, to; }; vector<edit> edits; int b = min(n, 19); for (int i = 0; i < b; i++) { for (int j = i + 1; j < b; j++) { int fr = ts[j], to = ts[i]; if (!con[fr][to]) { con[fr][to] = 1; edits.push_back({'+', fr + 1, to + 1}); } } } for (int i = b; i < n; i++) { int v = ts[i]; edits.push_back({'+', v + 1, v + 1}); } vector<int> have(1 << b, -1); for (int i = b; i < n; i++) { int v = ts[i]; int mask = 0; for (int j = 0; j < b; j++) { if (con[v][ts[j]]) mask += (1 << j); } int t = 0; for (int edit = 0; !t && edit <= b; edit++) { vector<int> e(b); for (int j = b - 1; j >= b - edit; j--) e[j] = 1; while (!t) { int mask2 = mask; for (int j = 0; j < b; j++) { if (e[j]) mask2 ^= (1 << j); } if (have[mask2] == -1) { t = 1; have[mask2] = v; for (int j = 0; j < b; j++) { if (e[j] && (mask & (1 << j))) { edits.push_back({'-', v + 1, ts[j] + 1}); con[v][ts[j]] = 0; } if (e[j] && !(mask & (1 << j))) { edits.push_back({'+', v + 1, ts[j] + 1}); con[v][ts[j]] = 1; } } } if (!next_permutation(e.begin(), e.end())) break; } } } cout << edits.size() << "\n"; for (auto e : edits) { cout << e.c << " " << e.fr << " " << e.to << "\n"; } cout << endl; while (t--) { vector<string> res(b); for (int j = 0; j < b; j++) { cout << "? 1 " << ts[j] + 1 << "\n"; } cout << endl; int mask = 0, fail = -1; for (int j = 0; j < b; j++) { cin >> res[j]; if (res[j] == "Lose") { assert(fail == -1); fail = ts[j]; } else { if (res[j] == "Win") { mask += (1 << j); } } } if (fail != -1) { cout << "! " << fail + 1 << endl; string s; cin >> s; continue; } cout << "! " << have[mask] + 1 << endl; string s; cin >> s; } }
CPP
1442_F. Differentiating Games
This is an interactive problem Ginny is taking an exam on game theory. The professor is tired of hearing the same answers over and over again, so he offered Ginny to play a game instead of a standard exam. As known from the course, a combinatorial game on a graph with multiple starting positions is a game with a directed graph and multiple starting vertices holding a token each. Two players take turns moving one of the tokens along the graph edges on each turn. The player who can't make a move loses the game. If both players can play an infinitely long game without losing, a draw is called. For the exam, the professor drew an acyclic directed graph and chose one of its vertices. Ginny needs to guess the vertex the professor chose. To do so, Ginny can choose a multiset of vertices S several times and ask the professor: "If I put one token in each vertex of the given graph for each occurrence of the vertex in the multiset S, and then one more in the selected vertex, what would be the result of the combinatorial game?". Having given the task, the professor left the room to give Ginny some time to prepare for the game. Ginny thinks that she's being tricked because the problem is impossible to solve. Therefore, while the professor is away, she wants to add or remove several edges from the graph. Even though the original graph was acyclic, edges could be added to the graph to make cycles appear. Interaction In this task, interaction consists of several phases. In the first phase, the interactor gives as an input to your program three integers N (1 ≀ N ≀ 1000), M (0 ≀ M ≀ 100 000), T (1 ≀ T ≀ 2000): the number of vertices and edges in the initial graph, and the number of times Ginny has to guess the chosen vertex. The next M lines contain pairs of vertices a_i b_i (1 ≀ a_i, b_i ≀ N): beginning and end of corresponding graph edges. The graph is guaranteed to be acyclic and all of its edges to be distinct. The solution should print an integer K (0 ≀ K ≀ 4242): the number of edges to change in the graph. The next K lines should contain either "+ a_i b_i" or "- a_i b_i": the beginning and the end of an edge that Ginny has to add or remove accordingly. You are allowed to add preexisting edges to the graph. Operations are performed in the order of appearance, so Ginny is allowed to remove an edge added by the solution. You can only remove an existing edge. The operations can create cycles in the graph. The next T phases are dedicated to guessing the chosen vertices. In each phase, the solution can make at most 20 queries and then print the answer. To query a multiset S, the solution should print "? |S|~S_1~S_2~...~S_{|S|}". The total size of all multisets in a single phase should not exceed 20. The interactor will reply with one of the following words: * "Win", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the first player. * "Lose", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the second player. * "Draw", if a combinatorial game with tokens in multiset S and selected vertex ends in a draw. * "Slow", if the solution made a 21-st request, or the total size of all multisets in a single phase exceeded 20. In this case, the solution should terminate and receive Wrong Answer verdict. As soon as the selected vertex is guessed, that solution should print "! v". If the chosen vertex is guessed correctly, the interactor will print Correct and the solution should either move on to the next phase of guessing or finish its execution if it's the last phase. Otherwise, the interactor will print Wrong, which means that the solution should terminate and will receive the Wrong Answer verdict. The interactor can change the chosen vertex based on graph changes and solution actions, but at every given moment of time, at least one vertex that corresponds to all given interactor answers will exist. Hack format Hacks have the following extra limitations: * T = 1 * you need to specify a single vertex, chosen by the interactor. Hack test format. The first line of input contains three integers N~M~1. The next M lines on input contain edge description in the same format as in the input. The next line contains a single integer v: the number of the chosen vertex. The hack will be successful even if the solution guesses the vertex right, but the vertex will not be the single one to match all performed queries. Example Input 3 2 3 1 2 2 3 Lose Correct Win Correct Draw Correct Output 6 + 2 2 - 1 2 + 2 3 - 2 2 + 3 1 + 2 2 ? 0 ! 1 ? 1 2 ! 3 ? 5 1 3 1 3 1 ! 2 Note In the sample test, the empty lines represent waiting for the input by the other side of the interaction. The real interactor will not print empty lines, and the solution should not print them either. <image> The image above illustrates the sample test. Added edges are coloured in red, and the removed edges are drawn with a dotted line. Three guessing phases denote different ways of getting the answer. * If the solution will query just the chosen vertex, the interactor will return the result of the game in that vertex. The first player loses only if the chosen vertex has the number 1. * If we add a single vertex 2 to the chosen vertex, then if the chosen vertex is either 1 or 2, the game should end in a draw. If vertex number 3 is chosen, then the first player wins. * If we place three tokens in vertex 1 and two tokens in vertex 3, then the game will end in a draw only if vertex 2 is chosen. If the professor chose vertex 3, the first player will win, if the professor chose vertex 1, then the second player will win. In the first test, the interactor will behave as if the chosen vertices are the same as those in the example above. However, if you will try to guess the answer before it limits the options to one single vertex, the solution will get "Wrong Answer", even if you print the same answers. That's because the interactor is allowed to change the chosen vertex if it's consistent with the previous query answers.
2
12
import java.io.*; import java.math.*; import java.util.*; import java.util.stream.*; public class E {boolean[] vis;ArrayList<Integer> order;int[][] g; void dfs(int v) {vis[v] = true;for (int u : g[v]) {if (!vis[u]) {dfs(u);}}order.add(v);} static final int K = 20; void submit() { int n = nextInt();int m = nextInt();int t = nextInt();int[] es = new int[2 * m]; for (int i = 0; i < 2 * m; i++) {es[i] = nextInt() - 1;} g = buildDGraph(es, n, m);vis = new boolean[n];order = new ArrayList<>();for (int i = 0; i < n; i++) {if (!vis[i]) {dfs(i);}} ArrayList<Integer> head = new ArrayList<>();ArrayList<Integer> ans = new ArrayList<>(); int[] who = new int[n]; Arrays.fill(who, -1); for (int i = 0; i < n && i < K; i++) { int v = order.get(i); head.add(v); who[v] = i; ArrayList<Integer> after = new ArrayList<>(); for (int j = 0; j < i; j++) { after.add(order.get(j)); } for (int u : g[v]) { after.remove(Integer.valueOf(u)); } for (int u : after) { ans.add(v); ans.add(u); } } ArrayList<Integer> rest = new ArrayList<>(); for (int i = K; i < n; i++) { rest.add(order.get(i)); } Collections.shuffle(rest); int[] memo = new int[1 << K]; Arrays.fill(memo, -1); ArrayList<Integer> randHead = new ArrayList<>(head); for (int v : rest) { ans.add(v); ans.add(v); int curMask = 0; for (int u : g[v]) { if (who[u] != -1) { curMask |= 1 << who[u]; } } Collections.shuffle(randHead); for (int u : randHead) { if (memo[curMask] == -1) { break; } ans.add(v); ans.add(test(curMask, who[u]) ? ~u : u); curMask ^= 1 << who[u]; } if (memo[curMask] != -1) { throw new AssertionError("couldn't make all nodes different"); } memo[curMask] = v; } if (ans.size() > 2 * 4242) { throw new AssertionError("too many edges added"); } out.println(ans.size() / 2); for (int i = 0; i < ans.size(); i += 2) { int v = ans.get(i); int u = ans.get(i + 1); if (u >= 0) { out.println("+ " + (v + 1) + " " + (u + 1)); } else { out.println("- " + (v + 1) + " " + ((~u) + 1)); } } out.flush(); while (t-- > 0) { int[] resp = new int[Math.min(n, K)]; for (int i = 0; i < resp.length; i++) { out.println("? 1 " + (head.get(i) + 1)); out.flush(); resp[i] = decode(nextToken()); } int winMask = 0; boolean fuck = false; for (int i = 0; i < resp.length; i++) { if (resp[i] == -1) { out.println("! " + (head.get(i) + 1)); out.flush(); fuck = true; break; } if (resp[i] == 1) { winMask |= 1 << i; } } if (!fuck) { if (memo[winMask] == -1) { throw new AssertionError("no answer for winMask"); } out.println("! " + (memo[winMask] + 1)); out.flush(); } nextToken(); } } static boolean test(int mask, int i) {return ((mask >> i) & 1) == 1;} int decode(String response) {switch (response) {case "Lose":return -1;case "Draw":return 0;case "Win":return 1;default:throw new AssertionError("unknown response");}} int[][] buildDGraph(int[] a, int n, int m) { if (m == 0) { if (a.length == 0) { return new int[n][0]; } else { throw new AssertionError(); } } if (a.length % m != 0 || a.length < 2 * m) { throw new AssertionError("Bad array length"); } int[] deg = new int[n]; int s = a.length / m; for (int i = 0; i < a.length; i += s) { deg[a[i]]++; } int[][] g = new int[n][]; for (int i = 0; i < n; i++) { g[i] = new int[deg[i] * (s - 1)]; } for (int i = s * (m - 1); i >= 0; i -= s) { int v = a[i]; int u = a[i + 1]; int pv = (--deg[v]) * (s - 1); g[v][pv] = u; System.arraycopy(a, i + 2, g[v], pv + 1, s - 2); } return g; } void test() {} void stress() {for (int tst = 0;; tst++) {submit();System.err.println(tst);}} E() throws IOException {is = System.in;out = new PrintWriter(System.out);submit();out.close();} static final Random rng = new Random();static final int C = 5; static int rand(int l, int r) {return l + rng.nextInt(r - l + 1);} public static void main(String[] args) throws IOException {new E();} private InputStream is; PrintWriter out;private byte[] buf = new byte[1 << 14];private int bufSz = 0, bufPtr = 0; private int readByte() { if (bufSz == -1) throw new RuntimeException("Reading past EOF"); if (bufPtr >= bufSz) { bufPtr = 0; try { bufSz = is.read(buf); } catch (IOException e) { throw new RuntimeException(e); } if (bufSz <= 0) return -1; } return buf[bufPtr++]; } private boolean isTrash(int c) {return c < 33 || c > 126;} private int skip() {int b;while ((b = readByte()) != -1 && isTrash(b));return b;} String nextToken() {int b = skip();StringBuilder sb = new StringBuilder();while (!isTrash(b)) {sb.appendCodePoint(b);b = readByte();}return sb.toString();} String nextString() {int b = readByte();StringBuilder sb = new StringBuilder();while (!isTrash(b) || b == ' ') {sb.appendCodePoint(b);b = readByte();}return sb.toString();} double nextDouble() {return Double.parseDouble(nextToken());} char nextChar() {return (char) skip();} int nextInt() { int ret = 0; int b = skip(); if (b != '-' && (b < '0' || b > '9')) { throw new InputMismatchException(); } boolean neg = false; if (b == '-') { neg = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { ret = ret * 10 + (b - '0'); } else { if (b != -1 && !isTrash(b)) { throw new InputMismatchException(); } return neg ? -ret : ret; } b = readByte(); } } long nextLong() {long ret = 0;int b = skip(); if (b != '-' && (b < '0' || b > '9')) {throw new InputMismatchException();}boolean neg = false; if (b == '-') {neg = true;b = readByte();} while (true) { if (b >= '0' && b <= '9') {ret = ret * 10 + (b - '0'); } else { if (b != -1 && !isTrash(b)) { throw new InputMismatchException(); }return neg ? -ret : ret;}b = readByte(); }}}
JAVA
1442_F. Differentiating Games
This is an interactive problem Ginny is taking an exam on game theory. The professor is tired of hearing the same answers over and over again, so he offered Ginny to play a game instead of a standard exam. As known from the course, a combinatorial game on a graph with multiple starting positions is a game with a directed graph and multiple starting vertices holding a token each. Two players take turns moving one of the tokens along the graph edges on each turn. The player who can't make a move loses the game. If both players can play an infinitely long game without losing, a draw is called. For the exam, the professor drew an acyclic directed graph and chose one of its vertices. Ginny needs to guess the vertex the professor chose. To do so, Ginny can choose a multiset of vertices S several times and ask the professor: "If I put one token in each vertex of the given graph for each occurrence of the vertex in the multiset S, and then one more in the selected vertex, what would be the result of the combinatorial game?". Having given the task, the professor left the room to give Ginny some time to prepare for the game. Ginny thinks that she's being tricked because the problem is impossible to solve. Therefore, while the professor is away, she wants to add or remove several edges from the graph. Even though the original graph was acyclic, edges could be added to the graph to make cycles appear. Interaction In this task, interaction consists of several phases. In the first phase, the interactor gives as an input to your program three integers N (1 ≀ N ≀ 1000), M (0 ≀ M ≀ 100 000), T (1 ≀ T ≀ 2000): the number of vertices and edges in the initial graph, and the number of times Ginny has to guess the chosen vertex. The next M lines contain pairs of vertices a_i b_i (1 ≀ a_i, b_i ≀ N): beginning and end of corresponding graph edges. The graph is guaranteed to be acyclic and all of its edges to be distinct. The solution should print an integer K (0 ≀ K ≀ 4242): the number of edges to change in the graph. The next K lines should contain either "+ a_i b_i" or "- a_i b_i": the beginning and the end of an edge that Ginny has to add or remove accordingly. You are allowed to add preexisting edges to the graph. Operations are performed in the order of appearance, so Ginny is allowed to remove an edge added by the solution. You can only remove an existing edge. The operations can create cycles in the graph. The next T phases are dedicated to guessing the chosen vertices. In each phase, the solution can make at most 20 queries and then print the answer. To query a multiset S, the solution should print "? |S|~S_1~S_2~...~S_{|S|}". The total size of all multisets in a single phase should not exceed 20. The interactor will reply with one of the following words: * "Win", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the first player. * "Lose", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the second player. * "Draw", if a combinatorial game with tokens in multiset S and selected vertex ends in a draw. * "Slow", if the solution made a 21-st request, or the total size of all multisets in a single phase exceeded 20. In this case, the solution should terminate and receive Wrong Answer verdict. As soon as the selected vertex is guessed, that solution should print "! v". If the chosen vertex is guessed correctly, the interactor will print Correct and the solution should either move on to the next phase of guessing or finish its execution if it's the last phase. Otherwise, the interactor will print Wrong, which means that the solution should terminate and will receive the Wrong Answer verdict. The interactor can change the chosen vertex based on graph changes and solution actions, but at every given moment of time, at least one vertex that corresponds to all given interactor answers will exist. Hack format Hacks have the following extra limitations: * T = 1 * you need to specify a single vertex, chosen by the interactor. Hack test format. The first line of input contains three integers N~M~1. The next M lines on input contain edge description in the same format as in the input. The next line contains a single integer v: the number of the chosen vertex. The hack will be successful even if the solution guesses the vertex right, but the vertex will not be the single one to match all performed queries. Example Input 3 2 3 1 2 2 3 Lose Correct Win Correct Draw Correct Output 6 + 2 2 - 1 2 + 2 3 - 2 2 + 3 1 + 2 2 ? 0 ! 1 ? 1 2 ! 3 ? 5 1 3 1 3 1 ! 2 Note In the sample test, the empty lines represent waiting for the input by the other side of the interaction. The real interactor will not print empty lines, and the solution should not print them either. <image> The image above illustrates the sample test. Added edges are coloured in red, and the removed edges are drawn with a dotted line. Three guessing phases denote different ways of getting the answer. * If the solution will query just the chosen vertex, the interactor will return the result of the game in that vertex. The first player loses only if the chosen vertex has the number 1. * If we add a single vertex 2 to the chosen vertex, then if the chosen vertex is either 1 or 2, the game should end in a draw. If vertex number 3 is chosen, then the first player wins. * If we place three tokens in vertex 1 and two tokens in vertex 3, then the game will end in a draw only if vertex 2 is chosen. If the professor chose vertex 3, the first player will win, if the professor chose vertex 1, then the second player will win. In the first test, the interactor will behave as if the chosen vertices are the same as those in the example above. However, if you will try to guess the answer before it limits the options to one single vertex, the solution will get "Wrong Answer", even if you print the same answers. That's because the interactor is allowed to change the chosen vertex if it's consistent with the previous query answers.
2
12
#include <bits/stdc++.h> const int MN = 1e3 + 10; const int K = 20; int N, M, T, id[MN], t[MN], ctr, m[1 << K]; bool conn[MN][MN]; char s[10]; std::vector<int> a[MN], on[K + 1]; struct Mod { public: char c; int a, b; void out() const { printf("%c %d %d\n", c, a, b); } }; std::vector<Mod> f; void flip(int a, int b) { f.push_back({conn[a][b] ? '-' : '+', a, b}); conn[a][b] ^= 1; } void dfs(int n) { for (int x : a[n]) if (!~id[x]) dfs(x); id[n] = ctr; t[ctr] = n; ++ctr; } int main() { memset(id, -1, sizeof id); scanf("%d%d%d", &N, &M, &T); for (int i = 0, u, v; i < M; ++i) scanf("%d%d", &u, &v), a[u].push_back(v), conn[u][v] = 1; ctr = 0; for (int i = 1; i <= N; ++i) if (!~id[i]) dfs(i); for (int i = std::min(N, K) - 1; i; --i) for (int j = i - 1; j >= 0; --j) if (!conn[t[i]][t[j]]) { a[t[i]].push_back(t[j]); conn[t[i]][t[j]] = 1; f.push_back({'+', t[i], t[j]}); } for (int i = 0; i < 1 << K; ++i) if (__builtin_popcount(i) <= 3) on[__builtin_popcount(i)].push_back(i); memset(m, -1, sizeof m); for (int i = K; i < N; ++i) { f.push_back({'+', t[i], t[i]}); int n = t[i], v = 0; for (int x : a[n]) if (id[x] < K) v |= 1 << id[x]; bool ok = 0; for (int j = 0; !ok; ++j) { assert(j <= 3); for (int k : on[j]) if (!~m[v ^ k]) { m[v ^ k] = n; for (int b = 0; b < K; ++b) if (k >> b & 1) flip(n, t[b]); ok = 1; break; } } } printf("%u\n", f.size()); for (int i = 0; i < f.size(); ++i) f[i].out(); fflush(stdout); for (int i = 0; i < T; ++i) { int v = 0; bool lose = 0; for (int j = 0; j < std::min(N, K); ++j) { printf("? 1 %d\n", t[j]); fflush(stdout); scanf(" %s", s); if (s[0] == 'S') return 0; if (s[0] == 'W') v |= 1 << j; if (s[0] == 'L') { lose = 1, v = j; break; } } if (lose) printf("! %d\n", t[v]); else printf("! %d\n", m[v]); fflush(stdout); scanf(" %s", s); if (s[0] == 'W') return 0; } return 0; }
CPP
1442_F. Differentiating Games
This is an interactive problem Ginny is taking an exam on game theory. The professor is tired of hearing the same answers over and over again, so he offered Ginny to play a game instead of a standard exam. As known from the course, a combinatorial game on a graph with multiple starting positions is a game with a directed graph and multiple starting vertices holding a token each. Two players take turns moving one of the tokens along the graph edges on each turn. The player who can't make a move loses the game. If both players can play an infinitely long game without losing, a draw is called. For the exam, the professor drew an acyclic directed graph and chose one of its vertices. Ginny needs to guess the vertex the professor chose. To do so, Ginny can choose a multiset of vertices S several times and ask the professor: "If I put one token in each vertex of the given graph for each occurrence of the vertex in the multiset S, and then one more in the selected vertex, what would be the result of the combinatorial game?". Having given the task, the professor left the room to give Ginny some time to prepare for the game. Ginny thinks that she's being tricked because the problem is impossible to solve. Therefore, while the professor is away, she wants to add or remove several edges from the graph. Even though the original graph was acyclic, edges could be added to the graph to make cycles appear. Interaction In this task, interaction consists of several phases. In the first phase, the interactor gives as an input to your program three integers N (1 ≀ N ≀ 1000), M (0 ≀ M ≀ 100 000), T (1 ≀ T ≀ 2000): the number of vertices and edges in the initial graph, and the number of times Ginny has to guess the chosen vertex. The next M lines contain pairs of vertices a_i b_i (1 ≀ a_i, b_i ≀ N): beginning and end of corresponding graph edges. The graph is guaranteed to be acyclic and all of its edges to be distinct. The solution should print an integer K (0 ≀ K ≀ 4242): the number of edges to change in the graph. The next K lines should contain either "+ a_i b_i" or "- a_i b_i": the beginning and the end of an edge that Ginny has to add or remove accordingly. You are allowed to add preexisting edges to the graph. Operations are performed in the order of appearance, so Ginny is allowed to remove an edge added by the solution. You can only remove an existing edge. The operations can create cycles in the graph. The next T phases are dedicated to guessing the chosen vertices. In each phase, the solution can make at most 20 queries and then print the answer. To query a multiset S, the solution should print "? |S|~S_1~S_2~...~S_{|S|}". The total size of all multisets in a single phase should not exceed 20. The interactor will reply with one of the following words: * "Win", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the first player. * "Lose", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the second player. * "Draw", if a combinatorial game with tokens in multiset S and selected vertex ends in a draw. * "Slow", if the solution made a 21-st request, or the total size of all multisets in a single phase exceeded 20. In this case, the solution should terminate and receive Wrong Answer verdict. As soon as the selected vertex is guessed, that solution should print "! v". If the chosen vertex is guessed correctly, the interactor will print Correct and the solution should either move on to the next phase of guessing or finish its execution if it's the last phase. Otherwise, the interactor will print Wrong, which means that the solution should terminate and will receive the Wrong Answer verdict. The interactor can change the chosen vertex based on graph changes and solution actions, but at every given moment of time, at least one vertex that corresponds to all given interactor answers will exist. Hack format Hacks have the following extra limitations: * T = 1 * you need to specify a single vertex, chosen by the interactor. Hack test format. The first line of input contains three integers N~M~1. The next M lines on input contain edge description in the same format as in the input. The next line contains a single integer v: the number of the chosen vertex. The hack will be successful even if the solution guesses the vertex right, but the vertex will not be the single one to match all performed queries. Example Input 3 2 3 1 2 2 3 Lose Correct Win Correct Draw Correct Output 6 + 2 2 - 1 2 + 2 3 - 2 2 + 3 1 + 2 2 ? 0 ! 1 ? 1 2 ! 3 ? 5 1 3 1 3 1 ! 2 Note In the sample test, the empty lines represent waiting for the input by the other side of the interaction. The real interactor will not print empty lines, and the solution should not print them either. <image> The image above illustrates the sample test. Added edges are coloured in red, and the removed edges are drawn with a dotted line. Three guessing phases denote different ways of getting the answer. * If the solution will query just the chosen vertex, the interactor will return the result of the game in that vertex. The first player loses only if the chosen vertex has the number 1. * If we add a single vertex 2 to the chosen vertex, then if the chosen vertex is either 1 or 2, the game should end in a draw. If vertex number 3 is chosen, then the first player wins. * If we place three tokens in vertex 1 and two tokens in vertex 3, then the game will end in a draw only if vertex 2 is chosen. If the professor chose vertex 3, the first player will win, if the professor chose vertex 1, then the second player will win. In the first test, the interactor will behave as if the chosen vertices are the same as those in the example above. However, if you will try to guess the answer before it limits the options to one single vertex, the solution will get "Wrong Answer", even if you print the same answers. That's because the interactor is allowed to change the chosen vertex if it's consistent with the previous query answers.
2
12
#include <bits/stdc++.h> using namespace std; void dfs(int v, vector<int> &col, vector<int> &ts, vector<vector<int> > &g) { col[v] = 1; for (auto u : g[v]) if (col[u] == 0) { dfs(u, col, ts, g); } ts.push_back(v); } int main() { ios_base::sync_with_stdio(false); cin.tie(0); int n, m, t; cin >> n >> m >> t; vector<vector<int> > g(n); vector<int> in(n); vector<vector<int> > con(n, vector<int>(n)); for (int(i) = 0; (i) != (m); (i)++) { int a, b; cin >> a >> b; a--, b--; g[a].push_back(b); con[a][b] = 1; in[b]++; } vector<int> ts, col(n); for (int(i) = 0; (i) != (n); (i)++) { if (in[i] == 0 && !col[i]) { dfs(i, col, ts, g); } } struct edit { char c; int fr, to; }; vector<edit> edits; int b = min(n, 17); for (int i = 0; i < b; i++) { for (int j = i + 1; j < b; j++) { int fr = ts[j], to = ts[i]; if (!con[fr][to]) { con[fr][to] = 1; edits.push_back({'+', fr + 1, to + 1}); } } } for (int i = b; i < n; i++) { int v = ts[i]; edits.push_back({'+', v + 1, v + 1}); } vector<int> have(1 << b, -1); for (int i = b; i < n; i++) { int v = ts[i]; int mask = 0; for (int j = 0; j < b; j++) { if (con[v][ts[j]]) mask += (1 << j); } int t = 0; for (int edit = 0; !t && edit <= b; edit++) { vector<int> e(b); for (int j = b - 1; j >= b - edit; j--) e[j] = 1; while (!t) { int mask2 = mask; for (int j = 0; j < b; j++) { if (e[j]) mask2 ^= (1 << j); } if (have[mask2] == -1) { t = 1; have[mask2] = v; for (int j = 0; j < b; j++) { if (e[j] && (mask & (1 << j))) { edits.push_back({'-', v + 1, ts[j] + 1}); con[v][ts[j]] = 0; } if (e[j] && !(mask & (1 << j))) { edits.push_back({'+', v + 1, ts[j] + 1}); con[v][ts[j]] = 1; } } } if (!next_permutation(e.begin(), e.end())) break; } } } cout << edits.size() << "\n"; for (auto e : edits) { cout << e.c << " " << e.fr << " " << e.to << "\n"; } cout << endl; while (t--) { vector<string> res(b); for (int j = 0; j < b; j++) { cout << "? 1 " << ts[j] + 1 << "\n"; } cout << endl; int mask = 0, fail = -1; for (int j = 0; j < b; j++) { cin >> res[j]; if (res[j] == "Lose") { assert(fail == -1); fail = ts[j]; } else { if (res[j] == "Win") { mask += (1 << j); } } } if (fail != -1) { cout << "! " << fail + 1 << endl; string s; cin >> s; continue; } cout << "! " << have[mask] + 1 << endl; string s; cin >> s; } }
CPP
1442_F. Differentiating Games
This is an interactive problem Ginny is taking an exam on game theory. The professor is tired of hearing the same answers over and over again, so he offered Ginny to play a game instead of a standard exam. As known from the course, a combinatorial game on a graph with multiple starting positions is a game with a directed graph and multiple starting vertices holding a token each. Two players take turns moving one of the tokens along the graph edges on each turn. The player who can't make a move loses the game. If both players can play an infinitely long game without losing, a draw is called. For the exam, the professor drew an acyclic directed graph and chose one of its vertices. Ginny needs to guess the vertex the professor chose. To do so, Ginny can choose a multiset of vertices S several times and ask the professor: "If I put one token in each vertex of the given graph for each occurrence of the vertex in the multiset S, and then one more in the selected vertex, what would be the result of the combinatorial game?". Having given the task, the professor left the room to give Ginny some time to prepare for the game. Ginny thinks that she's being tricked because the problem is impossible to solve. Therefore, while the professor is away, she wants to add or remove several edges from the graph. Even though the original graph was acyclic, edges could be added to the graph to make cycles appear. Interaction In this task, interaction consists of several phases. In the first phase, the interactor gives as an input to your program three integers N (1 ≀ N ≀ 1000), M (0 ≀ M ≀ 100 000), T (1 ≀ T ≀ 2000): the number of vertices and edges in the initial graph, and the number of times Ginny has to guess the chosen vertex. The next M lines contain pairs of vertices a_i b_i (1 ≀ a_i, b_i ≀ N): beginning and end of corresponding graph edges. The graph is guaranteed to be acyclic and all of its edges to be distinct. The solution should print an integer K (0 ≀ K ≀ 4242): the number of edges to change in the graph. The next K lines should contain either "+ a_i b_i" or "- a_i b_i": the beginning and the end of an edge that Ginny has to add or remove accordingly. You are allowed to add preexisting edges to the graph. Operations are performed in the order of appearance, so Ginny is allowed to remove an edge added by the solution. You can only remove an existing edge. The operations can create cycles in the graph. The next T phases are dedicated to guessing the chosen vertices. In each phase, the solution can make at most 20 queries and then print the answer. To query a multiset S, the solution should print "? |S|~S_1~S_2~...~S_{|S|}". The total size of all multisets in a single phase should not exceed 20. The interactor will reply with one of the following words: * "Win", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the first player. * "Lose", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the second player. * "Draw", if a combinatorial game with tokens in multiset S and selected vertex ends in a draw. * "Slow", if the solution made a 21-st request, or the total size of all multisets in a single phase exceeded 20. In this case, the solution should terminate and receive Wrong Answer verdict. As soon as the selected vertex is guessed, that solution should print "! v". If the chosen vertex is guessed correctly, the interactor will print Correct and the solution should either move on to the next phase of guessing or finish its execution if it's the last phase. Otherwise, the interactor will print Wrong, which means that the solution should terminate and will receive the Wrong Answer verdict. The interactor can change the chosen vertex based on graph changes and solution actions, but at every given moment of time, at least one vertex that corresponds to all given interactor answers will exist. Hack format Hacks have the following extra limitations: * T = 1 * you need to specify a single vertex, chosen by the interactor. Hack test format. The first line of input contains three integers N~M~1. The next M lines on input contain edge description in the same format as in the input. The next line contains a single integer v: the number of the chosen vertex. The hack will be successful even if the solution guesses the vertex right, but the vertex will not be the single one to match all performed queries. Example Input 3 2 3 1 2 2 3 Lose Correct Win Correct Draw Correct Output 6 + 2 2 - 1 2 + 2 3 - 2 2 + 3 1 + 2 2 ? 0 ! 1 ? 1 2 ! 3 ? 5 1 3 1 3 1 ! 2 Note In the sample test, the empty lines represent waiting for the input by the other side of the interaction. The real interactor will not print empty lines, and the solution should not print them either. <image> The image above illustrates the sample test. Added edges are coloured in red, and the removed edges are drawn with a dotted line. Three guessing phases denote different ways of getting the answer. * If the solution will query just the chosen vertex, the interactor will return the result of the game in that vertex. The first player loses only if the chosen vertex has the number 1. * If we add a single vertex 2 to the chosen vertex, then if the chosen vertex is either 1 or 2, the game should end in a draw. If vertex number 3 is chosen, then the first player wins. * If we place three tokens in vertex 1 and two tokens in vertex 3, then the game will end in a draw only if vertex 2 is chosen. If the professor chose vertex 3, the first player will win, if the professor chose vertex 1, then the second player will win. In the first test, the interactor will behave as if the chosen vertices are the same as those in the example above. However, if you will try to guess the answer before it limits the options to one single vertex, the solution will get "Wrong Answer", even if you print the same answers. That's because the interactor is allowed to change the chosen vertex if it's consistent with the previous query answers.
2
12
#include <bits/stdc++.h> const long long MOD = 1e9 + 7; const long long INF = 1e9; const long long INFLL = 1e18; using namespace std; int cx[4] = {0, 0, 1, -1}; int cy[4] = {-1, 1, 0, 0}; string Yes[2] = {"No\n", "Yes\n"}; string YES[2] = {"NO\n", "YES\n"}; string Possible[2] = {"Impossible\n", "Possible\n"}; string POSSIBLE[2] = {"IMPOSSIBLE\n", "POSSIBLE\n"}; void dfs(int v, vector<int> &col, vector<int> &ts, vector<vector<int> > &g) { col[v] = 1; for (auto u : g[v]) if (col[u] == 0) { dfs(u, col, ts, g); } ts.push_back(v); } int main() { ios_base::sync_with_stdio(false); cin.tie(0); int n, m, t; cin >> n >> m >> t; vector<vector<int> > g(n); vector<int> in(n); vector<vector<int> > con(n, vector<int>(n)); for (int(i) = 0; (i) != (m); (i)++) { int a, b; cin >> a >> b; a--, b--; g[a].push_back(b); con[a][b] = 1; in[b]++; } vector<int> ts, col(n); for (int(i) = 0; (i) != (n); (i)++) { if (in[i] == 0 && !col[i]) { dfs(i, col, ts, g); } } struct edit { char c; int fr, to; }; vector<edit> edits; int b = min(n, 20); for (int i = 0; i < b; i++) { for (int j = i + 1; j < b; j++) { int fr = ts[j], to = ts[i]; if (!con[fr][to]) { con[fr][to] = 1; edits.push_back({'+', fr + 1, to + 1}); } } } for (int i = b; i < n; i++) { int v = ts[i]; edits.push_back({'+', v + 1, v + 1}); } vector<int> have(1 << b, -1); for (int i = b; i < n; i++) { int v = ts[i]; int mask = 0; for (int j = 0; j < b; j++) { if (con[v][ts[j]]) mask += (1 << j); } int t = 0; for (int edit = 0; !t && edit <= b; edit++) { vector<int> e(b); for (int j = b - 1; j >= b - edit; j--) e[j] = 1; while (!t) { int mask2 = mask; for (int j = 0; j < b; j++) { if (e[j]) mask2 ^= (1 << j); } if (have[mask2] == -1) { t = 1; have[mask2] = v; for (int j = 0; j < b; j++) { if (e[j] && (mask & (1 << j))) { edits.push_back({'-', v + 1, ts[j] + 1}); con[v][ts[j]] = 0; } if (e[j] && !(mask & (1 << j))) { edits.push_back({'+', v + 1, ts[j] + 1}); con[v][ts[j]] = 1; } } } if (!next_permutation((e).begin(), (e).end())) break; } } } cout << edits.size() << endl; for (auto e : edits) { cout << e.c << " " << e.fr << " " << e.to << endl; } cout << endl; while (t--) { vector<string> res(b); for (int j = 0; j < b; j++) { cout << "? 1 " << ts[j] + 1 << endl; cin >> res[j]; } int mask = 0, fail = -1; for (int j = 0; j < b; j++) { if (res[j] == "Lose") { assert(fail == -1); fail = ts[j]; } else { if (res[j] == "Win") { mask += (1 << j); } } } if (fail != -1) { cout << "! " << fail + 1 << endl; string s; cin >> s; continue; } cout << "! " << have[mask] + 1 << endl; string s; cin >> s; } }
CPP
1442_F. Differentiating Games
This is an interactive problem Ginny is taking an exam on game theory. The professor is tired of hearing the same answers over and over again, so he offered Ginny to play a game instead of a standard exam. As known from the course, a combinatorial game on a graph with multiple starting positions is a game with a directed graph and multiple starting vertices holding a token each. Two players take turns moving one of the tokens along the graph edges on each turn. The player who can't make a move loses the game. If both players can play an infinitely long game without losing, a draw is called. For the exam, the professor drew an acyclic directed graph and chose one of its vertices. Ginny needs to guess the vertex the professor chose. To do so, Ginny can choose a multiset of vertices S several times and ask the professor: "If I put one token in each vertex of the given graph for each occurrence of the vertex in the multiset S, and then one more in the selected vertex, what would be the result of the combinatorial game?". Having given the task, the professor left the room to give Ginny some time to prepare for the game. Ginny thinks that she's being tricked because the problem is impossible to solve. Therefore, while the professor is away, she wants to add or remove several edges from the graph. Even though the original graph was acyclic, edges could be added to the graph to make cycles appear. Interaction In this task, interaction consists of several phases. In the first phase, the interactor gives as an input to your program three integers N (1 ≀ N ≀ 1000), M (0 ≀ M ≀ 100 000), T (1 ≀ T ≀ 2000): the number of vertices and edges in the initial graph, and the number of times Ginny has to guess the chosen vertex. The next M lines contain pairs of vertices a_i b_i (1 ≀ a_i, b_i ≀ N): beginning and end of corresponding graph edges. The graph is guaranteed to be acyclic and all of its edges to be distinct. The solution should print an integer K (0 ≀ K ≀ 4242): the number of edges to change in the graph. The next K lines should contain either "+ a_i b_i" or "- a_i b_i": the beginning and the end of an edge that Ginny has to add or remove accordingly. You are allowed to add preexisting edges to the graph. Operations are performed in the order of appearance, so Ginny is allowed to remove an edge added by the solution. You can only remove an existing edge. The operations can create cycles in the graph. The next T phases are dedicated to guessing the chosen vertices. In each phase, the solution can make at most 20 queries and then print the answer. To query a multiset S, the solution should print "? |S|~S_1~S_2~...~S_{|S|}". The total size of all multisets in a single phase should not exceed 20. The interactor will reply with one of the following words: * "Win", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the first player. * "Lose", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the second player. * "Draw", if a combinatorial game with tokens in multiset S and selected vertex ends in a draw. * "Slow", if the solution made a 21-st request, or the total size of all multisets in a single phase exceeded 20. In this case, the solution should terminate and receive Wrong Answer verdict. As soon as the selected vertex is guessed, that solution should print "! v". If the chosen vertex is guessed correctly, the interactor will print Correct and the solution should either move on to the next phase of guessing or finish its execution if it's the last phase. Otherwise, the interactor will print Wrong, which means that the solution should terminate and will receive the Wrong Answer verdict. The interactor can change the chosen vertex based on graph changes and solution actions, but at every given moment of time, at least one vertex that corresponds to all given interactor answers will exist. Hack format Hacks have the following extra limitations: * T = 1 * you need to specify a single vertex, chosen by the interactor. Hack test format. The first line of input contains three integers N~M~1. The next M lines on input contain edge description in the same format as in the input. The next line contains a single integer v: the number of the chosen vertex. The hack will be successful even if the solution guesses the vertex right, but the vertex will not be the single one to match all performed queries. Example Input 3 2 3 1 2 2 3 Lose Correct Win Correct Draw Correct Output 6 + 2 2 - 1 2 + 2 3 - 2 2 + 3 1 + 2 2 ? 0 ! 1 ? 1 2 ! 3 ? 5 1 3 1 3 1 ! 2 Note In the sample test, the empty lines represent waiting for the input by the other side of the interaction. The real interactor will not print empty lines, and the solution should not print them either. <image> The image above illustrates the sample test. Added edges are coloured in red, and the removed edges are drawn with a dotted line. Three guessing phases denote different ways of getting the answer. * If the solution will query just the chosen vertex, the interactor will return the result of the game in that vertex. The first player loses only if the chosen vertex has the number 1. * If we add a single vertex 2 to the chosen vertex, then if the chosen vertex is either 1 or 2, the game should end in a draw. If vertex number 3 is chosen, then the first player wins. * If we place three tokens in vertex 1 and two tokens in vertex 3, then the game will end in a draw only if vertex 2 is chosen. If the professor chose vertex 3, the first player will win, if the professor chose vertex 1, then the second player will win. In the first test, the interactor will behave as if the chosen vertices are the same as those in the example above. However, if you will try to guess the answer before it limits the options to one single vertex, the solution will get "Wrong Answer", even if you print the same answers. That's because the interactor is allowed to change the chosen vertex if it's consistent with the previous query answers.
2
12
#include <bits/stdc++.h> using namespace std; const int N = 1003, M = 100003; template <typename T> void read(T &x) { int ch = getchar(); x = 0; for (; ch < '0' || ch > '9'; ch = getchar()) ; for (; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - '0'; } int n, m, K, T, cnt, head[N], to[M], nxt[M], deg[N], pr[N], fr, re, ans[3][5000], acnt; void add(int a, int b) { to[++cnt] = b; nxt[cnt] = head[a]; head[a] = cnt; } void work(bool op, int x, int y) { ans[0][acnt] = op; ans[1][acnt] = x; ans[2][acnt++] = y; } int pre[N], vis[1 << 20]; char opt[10]; int findMask(int val) { vector<int> tmp; tmp.emplace_back(val); for (int i = 0; i < tmp.size(); ++i) { int u = tmp[i]; if (!vis[u]) return u; for (int i = 0; i < K; ++i) tmp.emplace_back(u ^ (1 << i)); } return 0; } int main() { read(n); read(m); read(T); for (int i = 1, u, v; i <= m; ++i) { read(u); read(v); add(u, v); ++deg[v]; } for (int i = 1; i <= n; ++i) if (!deg[i]) pr[re++] = i; while (fr < re) { int u = pr[fr++]; for (int i = head[u]; i; i = nxt[i]) if (!--deg[to[i]]) pr[re++] = to[i]; } reverse(pr, pr + n); K = min(n, 20); memset(pre, -1, sizeof pre); for (int i = 0; i < K; ++i) { pre[pr[i]] = i; for (int j = 0; j < i; ++j) work(1, pr[i], pr[j]); } for (int i = K; i < n; ++i) { work(1, pr[i], pr[i]); int mask = 0; for (int j = head[pr[i]]; j; j = nxt[j]) if (~pre[to[j]]) mask |= 1 << pre[to[j]]; int nxt = findMask(mask); vis[nxt] = pr[i]; for (int j = 0; j < K; ++j) if ((mask ^ nxt) >> j & 1) work((nxt >> j) & 1, pr[i], pr[j]); } printf("%d\n", acnt); for (int i = 0; i < acnt; ++i) printf("%c %d %d\n", ans[0][i] ? '+' : '-', ans[1][i], ans[2][i]); fflush(stdout); while (T--) { int mask = 0, ans = -1; for (int i = 0; i < K; ++i) { printf("? 1 %d\n", pr[i]); fflush(stdout); scanf("%s", opt); if (opt[0] == 'L') { ans = pr[i]; break; } else if (opt[0] == 'W') mask |= 1 << i; } printf("! %d\n", ans == -1 ? vis[mask] : ans); fflush(stdout); scanf("%s", opt); assert(opt[0] == 'C'); } }
CPP
1442_F. Differentiating Games
This is an interactive problem Ginny is taking an exam on game theory. The professor is tired of hearing the same answers over and over again, so he offered Ginny to play a game instead of a standard exam. As known from the course, a combinatorial game on a graph with multiple starting positions is a game with a directed graph and multiple starting vertices holding a token each. Two players take turns moving one of the tokens along the graph edges on each turn. The player who can't make a move loses the game. If both players can play an infinitely long game without losing, a draw is called. For the exam, the professor drew an acyclic directed graph and chose one of its vertices. Ginny needs to guess the vertex the professor chose. To do so, Ginny can choose a multiset of vertices S several times and ask the professor: "If I put one token in each vertex of the given graph for each occurrence of the vertex in the multiset S, and then one more in the selected vertex, what would be the result of the combinatorial game?". Having given the task, the professor left the room to give Ginny some time to prepare for the game. Ginny thinks that she's being tricked because the problem is impossible to solve. Therefore, while the professor is away, she wants to add or remove several edges from the graph. Even though the original graph was acyclic, edges could be added to the graph to make cycles appear. Interaction In this task, interaction consists of several phases. In the first phase, the interactor gives as an input to your program three integers N (1 ≀ N ≀ 1000), M (0 ≀ M ≀ 100 000), T (1 ≀ T ≀ 2000): the number of vertices and edges in the initial graph, and the number of times Ginny has to guess the chosen vertex. The next M lines contain pairs of vertices a_i b_i (1 ≀ a_i, b_i ≀ N): beginning and end of corresponding graph edges. The graph is guaranteed to be acyclic and all of its edges to be distinct. The solution should print an integer K (0 ≀ K ≀ 4242): the number of edges to change in the graph. The next K lines should contain either "+ a_i b_i" or "- a_i b_i": the beginning and the end of an edge that Ginny has to add or remove accordingly. You are allowed to add preexisting edges to the graph. Operations are performed in the order of appearance, so Ginny is allowed to remove an edge added by the solution. You can only remove an existing edge. The operations can create cycles in the graph. The next T phases are dedicated to guessing the chosen vertices. In each phase, the solution can make at most 20 queries and then print the answer. To query a multiset S, the solution should print "? |S|~S_1~S_2~...~S_{|S|}". The total size of all multisets in a single phase should not exceed 20. The interactor will reply with one of the following words: * "Win", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the first player. * "Lose", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the second player. * "Draw", if a combinatorial game with tokens in multiset S and selected vertex ends in a draw. * "Slow", if the solution made a 21-st request, or the total size of all multisets in a single phase exceeded 20. In this case, the solution should terminate and receive Wrong Answer verdict. As soon as the selected vertex is guessed, that solution should print "! v". If the chosen vertex is guessed correctly, the interactor will print Correct and the solution should either move on to the next phase of guessing or finish its execution if it's the last phase. Otherwise, the interactor will print Wrong, which means that the solution should terminate and will receive the Wrong Answer verdict. The interactor can change the chosen vertex based on graph changes and solution actions, but at every given moment of time, at least one vertex that corresponds to all given interactor answers will exist. Hack format Hacks have the following extra limitations: * T = 1 * you need to specify a single vertex, chosen by the interactor. Hack test format. The first line of input contains three integers N~M~1. The next M lines on input contain edge description in the same format as in the input. The next line contains a single integer v: the number of the chosen vertex. The hack will be successful even if the solution guesses the vertex right, but the vertex will not be the single one to match all performed queries. Example Input 3 2 3 1 2 2 3 Lose Correct Win Correct Draw Correct Output 6 + 2 2 - 1 2 + 2 3 - 2 2 + 3 1 + 2 2 ? 0 ! 1 ? 1 2 ! 3 ? 5 1 3 1 3 1 ! 2 Note In the sample test, the empty lines represent waiting for the input by the other side of the interaction. The real interactor will not print empty lines, and the solution should not print them either. <image> The image above illustrates the sample test. Added edges are coloured in red, and the removed edges are drawn with a dotted line. Three guessing phases denote different ways of getting the answer. * If the solution will query just the chosen vertex, the interactor will return the result of the game in that vertex. The first player loses only if the chosen vertex has the number 1. * If we add a single vertex 2 to the chosen vertex, then if the chosen vertex is either 1 or 2, the game should end in a draw. If vertex number 3 is chosen, then the first player wins. * If we place three tokens in vertex 1 and two tokens in vertex 3, then the game will end in a draw only if vertex 2 is chosen. If the professor chose vertex 3, the first player will win, if the professor chose vertex 1, then the second player will win. In the first test, the interactor will behave as if the chosen vertices are the same as those in the example above. However, if you will try to guess the answer before it limits the options to one single vertex, the solution will get "Wrong Answer", even if you print the same answers. That's because the interactor is allowed to change the chosen vertex if it's consistent with the previous query answers.
2
12
#include <bits/stdc++.h> using namespace std; int D = 20; int n, m, q, cnt = -1; int fir[1000], in[1000]; int nxt[200000], to[200000]; int tp[1000], pos[1000]; int have[1 << 20]; int K = 0, A[10000], B[10000]; bool C[10000]; inline void addedge(int a, int b, bool c) { A[K] = a; B[K] = b; C[K++] = c; return; } inline void add(int a, int b) { to[++cnt] = b; in[b]++; nxt[cnt] = fir[a]; fir[a] = cnt; return; } queue<int> que; void topo(void) { for (int i = 0; i < n; i++) if (in[i] == 0) { tp[cnt++] = i; que.push(i); } while (que.size() > 0) { int i = que.front(); que.pop(); for (int j = fir[i]; j != -1; j = nxt[j]) { in[to[j]]--; if (in[to[j]] == 0) { tp[cnt++] = to[j]; que.push(to[j]); } } } return; } void changeS(int p, int S) { for (int p1 = D; p1 >= 0; p1--) for (int p2 = (p1 == D ? D : p1 - 1); p2 >= 0; p2--) for (int p3 = (p2 == D ? D : p2 - 1); p3 >= 0; p3--) { int S2 = (S ^ (1 << p1) ^ (1 << p2) ^ (1 << p3)) & ((1 << D) - 1); if (have[S2] == -1) { have[S2] = p; if (p1 < D) addedge(p, tp[n - D + p1], !(S >> p1 & 1)); if (p2 < D) addedge(p, tp[n - D + p2], !(S >> p2 & 1)); if (p3 < D) addedge(p, tp[n - D + p3], !(S >> p3 & 1)); return; } } return; } void edge(void) { for (int i = 0; i < n; i++) pos[tp[i]] = i; for (int i = n - D; i < n; i++) for (int j = i + 1; j < n; j++) addedge(tp[i], tp[j], 1); for (int i = 0; i < n; i++) { if (pos[i] >= n - D) continue; addedge(i, i, 1); int S = 0; for (int p = fir[i]; p != -1; p = nxt[p]) { int j = to[p]; if (pos[j] >= n - D) S |= (1 << (pos[j] - n + D)); } changeS(i, S); } return; } int main(void) { scanf("%d%d%d", &n, &m, &q); if (D > n) D = n; for (int i = 0; i < n; i++) fir[i] = -1; for (int i = 0; i < (1 << D); i++) have[i] = -1; while (m--) { int a, b; scanf("%d%d", &a, &b); add(a - 1, b - 1); } cnt = 0; topo(); edge(); printf("%d\n", K); for (int i = 0; i < K; i++) if (C[i] == 1) printf("+ %d %d\n", A[i] + 1, B[i] + 1); else printf("- %d %d\n", A[i] + 1, B[i] + 1); fflush(stdout); while (q--) { char s[20]; int S = 0; for (int i = 0; i < D; i++) { printf("? 1 %d\n", tp[i + n - D] + 1); fflush(stdout); scanf(" %s", s); if (s[0] == 'L') { printf("! %d\n", tp[i + n - D] + 1); fflush(stdout); break; } if (s[0] == 'W') S |= (1 << i); } if (s[0] != 'L') { printf("! %d\n", have[S] + 1); fflush(stdout); } scanf(" %s", s); if (s[0] == 'W') return 0; } return 0; }
CPP
1442_F. Differentiating Games
This is an interactive problem Ginny is taking an exam on game theory. The professor is tired of hearing the same answers over and over again, so he offered Ginny to play a game instead of a standard exam. As known from the course, a combinatorial game on a graph with multiple starting positions is a game with a directed graph and multiple starting vertices holding a token each. Two players take turns moving one of the tokens along the graph edges on each turn. The player who can't make a move loses the game. If both players can play an infinitely long game without losing, a draw is called. For the exam, the professor drew an acyclic directed graph and chose one of its vertices. Ginny needs to guess the vertex the professor chose. To do so, Ginny can choose a multiset of vertices S several times and ask the professor: "If I put one token in each vertex of the given graph for each occurrence of the vertex in the multiset S, and then one more in the selected vertex, what would be the result of the combinatorial game?". Having given the task, the professor left the room to give Ginny some time to prepare for the game. Ginny thinks that she's being tricked because the problem is impossible to solve. Therefore, while the professor is away, she wants to add or remove several edges from the graph. Even though the original graph was acyclic, edges could be added to the graph to make cycles appear. Interaction In this task, interaction consists of several phases. In the first phase, the interactor gives as an input to your program three integers N (1 ≀ N ≀ 1000), M (0 ≀ M ≀ 100 000), T (1 ≀ T ≀ 2000): the number of vertices and edges in the initial graph, and the number of times Ginny has to guess the chosen vertex. The next M lines contain pairs of vertices a_i b_i (1 ≀ a_i, b_i ≀ N): beginning and end of corresponding graph edges. The graph is guaranteed to be acyclic and all of its edges to be distinct. The solution should print an integer K (0 ≀ K ≀ 4242): the number of edges to change in the graph. The next K lines should contain either "+ a_i b_i" or "- a_i b_i": the beginning and the end of an edge that Ginny has to add or remove accordingly. You are allowed to add preexisting edges to the graph. Operations are performed in the order of appearance, so Ginny is allowed to remove an edge added by the solution. You can only remove an existing edge. The operations can create cycles in the graph. The next T phases are dedicated to guessing the chosen vertices. In each phase, the solution can make at most 20 queries and then print the answer. To query a multiset S, the solution should print "? |S|~S_1~S_2~...~S_{|S|}". The total size of all multisets in a single phase should not exceed 20. The interactor will reply with one of the following words: * "Win", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the first player. * "Lose", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the second player. * "Draw", if a combinatorial game with tokens in multiset S and selected vertex ends in a draw. * "Slow", if the solution made a 21-st request, or the total size of all multisets in a single phase exceeded 20. In this case, the solution should terminate and receive Wrong Answer verdict. As soon as the selected vertex is guessed, that solution should print "! v". If the chosen vertex is guessed correctly, the interactor will print Correct and the solution should either move on to the next phase of guessing or finish its execution if it's the last phase. Otherwise, the interactor will print Wrong, which means that the solution should terminate and will receive the Wrong Answer verdict. The interactor can change the chosen vertex based on graph changes and solution actions, but at every given moment of time, at least one vertex that corresponds to all given interactor answers will exist. Hack format Hacks have the following extra limitations: * T = 1 * you need to specify a single vertex, chosen by the interactor. Hack test format. The first line of input contains three integers N~M~1. The next M lines on input contain edge description in the same format as in the input. The next line contains a single integer v: the number of the chosen vertex. The hack will be successful even if the solution guesses the vertex right, but the vertex will not be the single one to match all performed queries. Example Input 3 2 3 1 2 2 3 Lose Correct Win Correct Draw Correct Output 6 + 2 2 - 1 2 + 2 3 - 2 2 + 3 1 + 2 2 ? 0 ! 1 ? 1 2 ! 3 ? 5 1 3 1 3 1 ! 2 Note In the sample test, the empty lines represent waiting for the input by the other side of the interaction. The real interactor will not print empty lines, and the solution should not print them either. <image> The image above illustrates the sample test. Added edges are coloured in red, and the removed edges are drawn with a dotted line. Three guessing phases denote different ways of getting the answer. * If the solution will query just the chosen vertex, the interactor will return the result of the game in that vertex. The first player loses only if the chosen vertex has the number 1. * If we add a single vertex 2 to the chosen vertex, then if the chosen vertex is either 1 or 2, the game should end in a draw. If vertex number 3 is chosen, then the first player wins. * If we place three tokens in vertex 1 and two tokens in vertex 3, then the game will end in a draw only if vertex 2 is chosen. If the professor chose vertex 3, the first player will win, if the professor chose vertex 1, then the second player will win. In the first test, the interactor will behave as if the chosen vertices are the same as those in the example above. However, if you will try to guess the answer before it limits the options to one single vertex, the solution will get "Wrong Answer", even if you print the same answers. That's because the interactor is allowed to change the chosen vertex if it's consistent with the previous query answers.
2
12
#include <bits/stdc++.h> const long long MOD = 1e9 + 7; const long long INF = 1e9; const long long INFLL = 1e18; using namespace std; int cx[4] = {0, 0, 1, -1}; int cy[4] = {-1, 1, 0, 0}; string Yes[2] = {"No\n", "Yes\n"}; string YES[2] = {"NO\n", "YES\n"}; string Possible[2] = {"Impossible\n", "Possible\n"}; string POSSIBLE[2] = {"IMPOSSIBLE\n", "POSSIBLE\n"}; void dfs(int v, vector<int> &col, vector<int> &ts, vector<vector<int> > &g) { col[v] = 1; for (auto u : g[v]) if (col[u] == 0) { dfs(u, col, ts, g); } ts.push_back(v); } int main() { ios_base::sync_with_stdio(false); cin.tie(0); int n, m, t; cin >> n >> m >> t; vector<vector<int> > g(n); vector<int> in(n); vector<vector<int> > con(n, vector<int>(n)); for (int(i) = 0; (i) != (m); (i)++) { int a, b; cin >> a >> b; a--, b--; g[a].push_back(b); con[a][b] = 1; in[b]++; } vector<int> ts, col(n); for (int(i) = 0; (i) != (n); (i)++) { if (in[i] == 0 && !col[i]) { dfs(i, col, ts, g); } } struct edit { char c; int fr, to; }; vector<edit> edits; int b = min(n, 20); for (int i = 0; i < b; i++) { for (int j = i + 1; j < b; j++) { int fr = ts[j], to = ts[i]; if (!con[fr][to]) { con[fr][to] = 1; edits.push_back({'+', fr + 1, to + 1}); } } } for (int i = b; i < n; i++) { int v = ts[i]; edits.push_back({'+', v + 1, v + 1}); } vector<int> have(1 << b, -1); for (int i = b; i < n; i++) { int v = ts[i]; int mask = 0; for (int j = 0; j < b; j++) { if (con[v][ts[j]]) mask += (1 << j); } int t = 0; for (int edit = 0; !t && edit <= b; edit++) { vector<int> e(b); for (int j = b - 1; j >= b - edit; j--) e[j] = 1; while (!t) { int mask2 = mask; for (int j = 0; j < b; j++) { if (e[j]) mask2 ^= (1 << j); } if (have[mask2] == -1) { t = 1; have[mask2] = v; for (int j = 0; j < b; j++) { if (e[j] && (mask & (1 << j))) { edits.push_back({'-', v + 1, ts[j] + 1}); con[v][ts[j]] = 0; } if (e[j] && !(mask & (1 << j))) { edits.push_back({'+', v + 1, ts[j] + 1}); con[v][ts[j]] = 1; } } } if (!next_permutation((e).begin(), (e).end())) break; } } } cout << edits.size() << endl; for (auto e : edits) { cout << e.c << " " << e.fr << " " << e.to << endl; } cout << endl; while (t--) { vector<string> res(b); for (int j = 0; j < b; j++) { cout << "? 1 " << ts[j] + 1 << "\n"; } cout << endl; int mask = 0, fail = -1; for (int j = 0; j < b; j++) { cin >> res[j]; if (res[j] == "Lose") { assert(fail == -1); fail = ts[j]; } else { if (res[j] == "Win") { mask += (1 << j); } } } if (fail != -1) { cout << "! " << fail + 1 << endl; string s; cin >> s; continue; } cout << "! " << have[mask] + 1 << endl; string s; cin >> s; } }
CPP
1442_F. Differentiating Games
This is an interactive problem Ginny is taking an exam on game theory. The professor is tired of hearing the same answers over and over again, so he offered Ginny to play a game instead of a standard exam. As known from the course, a combinatorial game on a graph with multiple starting positions is a game with a directed graph and multiple starting vertices holding a token each. Two players take turns moving one of the tokens along the graph edges on each turn. The player who can't make a move loses the game. If both players can play an infinitely long game without losing, a draw is called. For the exam, the professor drew an acyclic directed graph and chose one of its vertices. Ginny needs to guess the vertex the professor chose. To do so, Ginny can choose a multiset of vertices S several times and ask the professor: "If I put one token in each vertex of the given graph for each occurrence of the vertex in the multiset S, and then one more in the selected vertex, what would be the result of the combinatorial game?". Having given the task, the professor left the room to give Ginny some time to prepare for the game. Ginny thinks that she's being tricked because the problem is impossible to solve. Therefore, while the professor is away, she wants to add or remove several edges from the graph. Even though the original graph was acyclic, edges could be added to the graph to make cycles appear. Interaction In this task, interaction consists of several phases. In the first phase, the interactor gives as an input to your program three integers N (1 ≀ N ≀ 1000), M (0 ≀ M ≀ 100 000), T (1 ≀ T ≀ 2000): the number of vertices and edges in the initial graph, and the number of times Ginny has to guess the chosen vertex. The next M lines contain pairs of vertices a_i b_i (1 ≀ a_i, b_i ≀ N): beginning and end of corresponding graph edges. The graph is guaranteed to be acyclic and all of its edges to be distinct. The solution should print an integer K (0 ≀ K ≀ 4242): the number of edges to change in the graph. The next K lines should contain either "+ a_i b_i" or "- a_i b_i": the beginning and the end of an edge that Ginny has to add or remove accordingly. You are allowed to add preexisting edges to the graph. Operations are performed in the order of appearance, so Ginny is allowed to remove an edge added by the solution. You can only remove an existing edge. The operations can create cycles in the graph. The next T phases are dedicated to guessing the chosen vertices. In each phase, the solution can make at most 20 queries and then print the answer. To query a multiset S, the solution should print "? |S|~S_1~S_2~...~S_{|S|}". The total size of all multisets in a single phase should not exceed 20. The interactor will reply with one of the following words: * "Win", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the first player. * "Lose", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the second player. * "Draw", if a combinatorial game with tokens in multiset S and selected vertex ends in a draw. * "Slow", if the solution made a 21-st request, or the total size of all multisets in a single phase exceeded 20. In this case, the solution should terminate and receive Wrong Answer verdict. As soon as the selected vertex is guessed, that solution should print "! v". If the chosen vertex is guessed correctly, the interactor will print Correct and the solution should either move on to the next phase of guessing or finish its execution if it's the last phase. Otherwise, the interactor will print Wrong, which means that the solution should terminate and will receive the Wrong Answer verdict. The interactor can change the chosen vertex based on graph changes and solution actions, but at every given moment of time, at least one vertex that corresponds to all given interactor answers will exist. Hack format Hacks have the following extra limitations: * T = 1 * you need to specify a single vertex, chosen by the interactor. Hack test format. The first line of input contains three integers N~M~1. The next M lines on input contain edge description in the same format as in the input. The next line contains a single integer v: the number of the chosen vertex. The hack will be successful even if the solution guesses the vertex right, but the vertex will not be the single one to match all performed queries. Example Input 3 2 3 1 2 2 3 Lose Correct Win Correct Draw Correct Output 6 + 2 2 - 1 2 + 2 3 - 2 2 + 3 1 + 2 2 ? 0 ! 1 ? 1 2 ! 3 ? 5 1 3 1 3 1 ! 2 Note In the sample test, the empty lines represent waiting for the input by the other side of the interaction. The real interactor will not print empty lines, and the solution should not print them either. <image> The image above illustrates the sample test. Added edges are coloured in red, and the removed edges are drawn with a dotted line. Three guessing phases denote different ways of getting the answer. * If the solution will query just the chosen vertex, the interactor will return the result of the game in that vertex. The first player loses only if the chosen vertex has the number 1. * If we add a single vertex 2 to the chosen vertex, then if the chosen vertex is either 1 or 2, the game should end in a draw. If vertex number 3 is chosen, then the first player wins. * If we place three tokens in vertex 1 and two tokens in vertex 3, then the game will end in a draw only if vertex 2 is chosen. If the professor chose vertex 3, the first player will win, if the professor chose vertex 1, then the second player will win. In the first test, the interactor will behave as if the chosen vertices are the same as those in the example above. However, if you will try to guess the answer before it limits the options to one single vertex, the solution will get "Wrong Answer", even if you print the same answers. That's because the interactor is allowed to change the chosen vertex if it's consistent with the previous query answers.
2
12
#include <bits/stdc++.h> using namespace std; const int c = 1002, k = 1 << 20; int n, m, q, ert[c], mini, inv[k], ts[c], cnt; vector<int> sz[c]; bool v[c], sp[c]; string s; void add(int a, int b, int c) { if (c) cout << "+ "; else cout << "- "; cout << a << " " << b << "\n"; } void valt(int a, int b) { if (ert[a] & (1 << b)) add(a, ts[b], 0); else add(a, ts[b], 1); } void dfs(int a) { v[a] = true; for (int x : sz[a]) { if (!v[x]) dfs(x); ert[a] += ert[x] * sp[x]; } ts[cnt] = a; if (cnt < mini) { sp[a] = 1; ert[a] = (1 << cnt); } cnt++; } int main() { ios_base::sync_with_stdio(false); cin >> n >> m >> q; mini = min(n, 20); cout << mini * (mini - 1) / 2 + 4 * (n - mini) << "\n"; for (int i = 1; i <= m; i++) { int a, b; cin >> a >> b; sz[a].push_back(b); } for (int i = 1; i <= n; i++) { if (!v[i]) dfs(i); } for (int id = 1; id <= n; id++) { if (sp[id]) { for (int i = 1; i <= n; i++) { if (sp[i] && ert[id] > ert[i]) add(id, i, 1); } } else { bool jo = 0; add(id, id, 1); for (int i = 0; i < mini; i++) { for (int j = i + 1; j < mini; j++) { for (int k = j + 1; k < mini; k++) { int cel = ert[id] ^ (1 << i) ^ (1 << j) ^ (1 << k); if (!jo && !inv[cel]) { jo = 1; inv[cel] = id; valt(id, i), valt(id, j), valt(id, k); } } } } } } while (q--) { int ans = 0, kul = 0; for (int i = 0; i < mini; i++) { cout.flush() << "? " << 1 << " " << ts[i] << "\n"; string s; cin >> s; if (s == "Lose") kul = ts[i]; if (s == "Win") ans += (1 << i); } ans = inv[ans]; if (kul) ans = kul; cout.flush() << "! " << ans << "\n"; cin >> s; } return 0; }
CPP
1442_F. Differentiating Games
This is an interactive problem Ginny is taking an exam on game theory. The professor is tired of hearing the same answers over and over again, so he offered Ginny to play a game instead of a standard exam. As known from the course, a combinatorial game on a graph with multiple starting positions is a game with a directed graph and multiple starting vertices holding a token each. Two players take turns moving one of the tokens along the graph edges on each turn. The player who can't make a move loses the game. If both players can play an infinitely long game without losing, a draw is called. For the exam, the professor drew an acyclic directed graph and chose one of its vertices. Ginny needs to guess the vertex the professor chose. To do so, Ginny can choose a multiset of vertices S several times and ask the professor: "If I put one token in each vertex of the given graph for each occurrence of the vertex in the multiset S, and then one more in the selected vertex, what would be the result of the combinatorial game?". Having given the task, the professor left the room to give Ginny some time to prepare for the game. Ginny thinks that she's being tricked because the problem is impossible to solve. Therefore, while the professor is away, she wants to add or remove several edges from the graph. Even though the original graph was acyclic, edges could be added to the graph to make cycles appear. Interaction In this task, interaction consists of several phases. In the first phase, the interactor gives as an input to your program three integers N (1 ≀ N ≀ 1000), M (0 ≀ M ≀ 100 000), T (1 ≀ T ≀ 2000): the number of vertices and edges in the initial graph, and the number of times Ginny has to guess the chosen vertex. The next M lines contain pairs of vertices a_i b_i (1 ≀ a_i, b_i ≀ N): beginning and end of corresponding graph edges. The graph is guaranteed to be acyclic and all of its edges to be distinct. The solution should print an integer K (0 ≀ K ≀ 4242): the number of edges to change in the graph. The next K lines should contain either "+ a_i b_i" or "- a_i b_i": the beginning and the end of an edge that Ginny has to add or remove accordingly. You are allowed to add preexisting edges to the graph. Operations are performed in the order of appearance, so Ginny is allowed to remove an edge added by the solution. You can only remove an existing edge. The operations can create cycles in the graph. The next T phases are dedicated to guessing the chosen vertices. In each phase, the solution can make at most 20 queries and then print the answer. To query a multiset S, the solution should print "? |S|~S_1~S_2~...~S_{|S|}". The total size of all multisets in a single phase should not exceed 20. The interactor will reply with one of the following words: * "Win", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the first player. * "Lose", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the second player. * "Draw", if a combinatorial game with tokens in multiset S and selected vertex ends in a draw. * "Slow", if the solution made a 21-st request, or the total size of all multisets in a single phase exceeded 20. In this case, the solution should terminate and receive Wrong Answer verdict. As soon as the selected vertex is guessed, that solution should print "! v". If the chosen vertex is guessed correctly, the interactor will print Correct and the solution should either move on to the next phase of guessing or finish its execution if it's the last phase. Otherwise, the interactor will print Wrong, which means that the solution should terminate and will receive the Wrong Answer verdict. The interactor can change the chosen vertex based on graph changes and solution actions, but at every given moment of time, at least one vertex that corresponds to all given interactor answers will exist. Hack format Hacks have the following extra limitations: * T = 1 * you need to specify a single vertex, chosen by the interactor. Hack test format. The first line of input contains three integers N~M~1. The next M lines on input contain edge description in the same format as in the input. The next line contains a single integer v: the number of the chosen vertex. The hack will be successful even if the solution guesses the vertex right, but the vertex will not be the single one to match all performed queries. Example Input 3 2 3 1 2 2 3 Lose Correct Win Correct Draw Correct Output 6 + 2 2 - 1 2 + 2 3 - 2 2 + 3 1 + 2 2 ? 0 ! 1 ? 1 2 ! 3 ? 5 1 3 1 3 1 ! 2 Note In the sample test, the empty lines represent waiting for the input by the other side of the interaction. The real interactor will not print empty lines, and the solution should not print them either. <image> The image above illustrates the sample test. Added edges are coloured in red, and the removed edges are drawn with a dotted line. Three guessing phases denote different ways of getting the answer. * If the solution will query just the chosen vertex, the interactor will return the result of the game in that vertex. The first player loses only if the chosen vertex has the number 1. * If we add a single vertex 2 to the chosen vertex, then if the chosen vertex is either 1 or 2, the game should end in a draw. If vertex number 3 is chosen, then the first player wins. * If we place three tokens in vertex 1 and two tokens in vertex 3, then the game will end in a draw only if vertex 2 is chosen. If the professor chose vertex 3, the first player will win, if the professor chose vertex 1, then the second player will win. In the first test, the interactor will behave as if the chosen vertices are the same as those in the example above. However, if you will try to guess the answer before it limits the options to one single vertex, the solution will get "Wrong Answer", even if you print the same answers. That's because the interactor is allowed to change the chosen vertex if it's consistent with the previous query answers.
2
12
#include <bits/stdc++.h> using namespace std; inline void read(int &x) { int v = 0, f = 1; char c = getchar(); while (!isdigit(c) && c != '-') c = getchar(); if (c == '-') f = -1; else v = (c & 15); while (isdigit(c = getchar())) v = (v << 1) + (v << 3) + (c & 15); x = v * f; } inline void read(long long &x) { long long v = 0ll, f = 1ll; char c = getchar(); while (!isdigit(c) && c != '-') c = getchar(); if (c == '-') f = -1; else v = (c & 15); while (isdigit(c = getchar())) v = (v << 1) + (v << 3) + (c & 15); x = v * f; } inline void readc(char &x) { char c; while (((c = getchar()) == ' ') || c == '\n') ; x = c; } int n, m, q, i, j, g[1005][1005], deg[1005], id[10005], nd[25], mp[1 << 19], t; vector<int> v; vector<pair<char, pair<int, int> > > res; char s[15]; void dfs(int x) { deg[x] = -1; v.push_back(x); int i; for (((i)) = (1); ((i)) <= ((n)); ((i))++) if (g[x][i]) { if (!--deg[i]) dfs(i); } } void init(int x) { res.push_back(make_pair('+', make_pair(x, x))); int cur = 0, i, j, k; for (j = v.size() - t; j < v.size() - 1; j++) { if (g[x][v[j]]) cur ^= (1 << (j - (v.size() - t))); } if (!mp[cur]) { mp[cur] = x; return; } for (((i)) = (0); ((i)) <= (((int)(t - 1)) - 1); ((i))++) { if (!mp[cur ^ (1 << i)]) { if (g[x][nd[i]]) res.push_back(make_pair('-', make_pair(x, nd[i]))); else res.push_back(make_pair('+', make_pair(x, nd[i]))); g[x][nd[i]] ^= 1; cur ^= (1 << i); mp[cur] = x; return; } } for (((i)) = (0); ((i)) <= (((int)(t - 1)) - 1); ((i))++) for (((j)) = (0); ((j)) <= (((int)(t - 1)) - 1); ((j))++) { if (!mp[cur ^ (1 << i) ^ (1 << j)]) { if (g[x][nd[i]]) res.push_back(make_pair('-', make_pair(x, nd[i]))); else res.push_back(make_pair('+', make_pair(x, nd[i]))); g[x][nd[i]] ^= 1; cur ^= (1 << i); if (g[x][nd[j]]) res.push_back(make_pair('-', make_pair(x, nd[j]))); else res.push_back(make_pair('+', make_pair(x, nd[j]))); g[x][nd[j]] ^= 1; cur ^= (1 << j); mp[cur] = x; return; } } for (((i)) = (0); ((i)) <= (((int)(t - 1)) - 1); ((i))++) for (((j)) = (0); ((j)) <= (((int)(t - 1)) - 1); ((j))++) for (((k)) = (0); ((k)) <= (((int)(t - 1)) - 1); ((k))++) { if (!mp[cur ^ (1 << i) ^ (1 << j) ^ (1 << k)]) { if (g[x][nd[i]]) res.push_back(make_pair('-', make_pair(x, nd[i]))); else res.push_back(make_pair('+', make_pair(x, nd[i]))); g[x][nd[i]] ^= 1; cur ^= (1 << i); if (g[x][nd[j]]) res.push_back(make_pair('-', make_pair(x, nd[j]))); else res.push_back(make_pair('+', make_pair(x, nd[j]))); g[x][nd[j]] ^= 1; cur ^= (1 << j); if (g[x][nd[k]]) res.push_back(make_pair('-', make_pair(x, nd[k]))); else res.push_back(make_pair('+', make_pair(x, nd[k]))); g[x][nd[k]] ^= 1; cur ^= (1 << k); mp[cur] = x; return; } } } void solve() { puts("? 0"); fflush(stdout); scanf("%s", s); if (s[0] == 'L') { printf("! %d\n", v.back()); fflush(stdout); scanf("%s", s); return; } int cur = 0; for (((i)) = (0); ((i)) <= (((int)(t - 1)) - 1); ((i))++) { printf("? 1 %d\n", nd[i]); fflush(stdout); scanf("%s", s); if (s[0] == 'L') { printf("! %d\n", nd[i]); fflush(stdout); scanf("%s", s); return; } if (s[0] == 'W') { cur |= (1 << i); } } printf("! %d\n", mp[cur]); fflush(stdout); scanf("%s", s); } int main() { scanf("%d%d%d", &n, &m, &q); for (((i)) = (1); ((i)) <= ((m)); ((i))++) { int x, y; scanf("%d%d", &x, &y); g[x][y] = 1; deg[y]++; } for (((i)) = (1); ((i)) <= ((n)); ((i))++) if (!deg[i]) dfs(i); t = min(n, 20); memset(id, -1, sizeof(id)); for (i = v.size() - t; i < v.size(); i++) { nd[id[v[i]] = i - (v.size() - t)] = v[i]; for (j = i + 1; j < v.size(); j++) { if (!g[v[i]][v[j]]) { res.push_back(make_pair('+', make_pair(v[i], v[j]))); g[v[i]][v[j]] = 1; } } } for (((i)) = (1); ((i)) <= ((n)); ((i))++) if (id[i] == -1) { init(i); } printf("%d\n", res.size()); for (__typeof((res).begin()) it = (res).begin(); it != (res).end(); it++) { printf("%c %d %d\n", it->first, it->second.first, it->second.second); } fflush(stdout); while (q--) { solve(); } return 0; }
CPP
1442_F. Differentiating Games
This is an interactive problem Ginny is taking an exam on game theory. The professor is tired of hearing the same answers over and over again, so he offered Ginny to play a game instead of a standard exam. As known from the course, a combinatorial game on a graph with multiple starting positions is a game with a directed graph and multiple starting vertices holding a token each. Two players take turns moving one of the tokens along the graph edges on each turn. The player who can't make a move loses the game. If both players can play an infinitely long game without losing, a draw is called. For the exam, the professor drew an acyclic directed graph and chose one of its vertices. Ginny needs to guess the vertex the professor chose. To do so, Ginny can choose a multiset of vertices S several times and ask the professor: "If I put one token in each vertex of the given graph for each occurrence of the vertex in the multiset S, and then one more in the selected vertex, what would be the result of the combinatorial game?". Having given the task, the professor left the room to give Ginny some time to prepare for the game. Ginny thinks that she's being tricked because the problem is impossible to solve. Therefore, while the professor is away, she wants to add or remove several edges from the graph. Even though the original graph was acyclic, edges could be added to the graph to make cycles appear. Interaction In this task, interaction consists of several phases. In the first phase, the interactor gives as an input to your program three integers N (1 ≀ N ≀ 1000), M (0 ≀ M ≀ 100 000), T (1 ≀ T ≀ 2000): the number of vertices and edges in the initial graph, and the number of times Ginny has to guess the chosen vertex. The next M lines contain pairs of vertices a_i b_i (1 ≀ a_i, b_i ≀ N): beginning and end of corresponding graph edges. The graph is guaranteed to be acyclic and all of its edges to be distinct. The solution should print an integer K (0 ≀ K ≀ 4242): the number of edges to change in the graph. The next K lines should contain either "+ a_i b_i" or "- a_i b_i": the beginning and the end of an edge that Ginny has to add or remove accordingly. You are allowed to add preexisting edges to the graph. Operations are performed in the order of appearance, so Ginny is allowed to remove an edge added by the solution. You can only remove an existing edge. The operations can create cycles in the graph. The next T phases are dedicated to guessing the chosen vertices. In each phase, the solution can make at most 20 queries and then print the answer. To query a multiset S, the solution should print "? |S|~S_1~S_2~...~S_{|S|}". The total size of all multisets in a single phase should not exceed 20. The interactor will reply with one of the following words: * "Win", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the first player. * "Lose", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the second player. * "Draw", if a combinatorial game with tokens in multiset S and selected vertex ends in a draw. * "Slow", if the solution made a 21-st request, or the total size of all multisets in a single phase exceeded 20. In this case, the solution should terminate and receive Wrong Answer verdict. As soon as the selected vertex is guessed, that solution should print "! v". If the chosen vertex is guessed correctly, the interactor will print Correct and the solution should either move on to the next phase of guessing or finish its execution if it's the last phase. Otherwise, the interactor will print Wrong, which means that the solution should terminate and will receive the Wrong Answer verdict. The interactor can change the chosen vertex based on graph changes and solution actions, but at every given moment of time, at least one vertex that corresponds to all given interactor answers will exist. Hack format Hacks have the following extra limitations: * T = 1 * you need to specify a single vertex, chosen by the interactor. Hack test format. The first line of input contains three integers N~M~1. The next M lines on input contain edge description in the same format as in the input. The next line contains a single integer v: the number of the chosen vertex. The hack will be successful even if the solution guesses the vertex right, but the vertex will not be the single one to match all performed queries. Example Input 3 2 3 1 2 2 3 Lose Correct Win Correct Draw Correct Output 6 + 2 2 - 1 2 + 2 3 - 2 2 + 3 1 + 2 2 ? 0 ! 1 ? 1 2 ! 3 ? 5 1 3 1 3 1 ! 2 Note In the sample test, the empty lines represent waiting for the input by the other side of the interaction. The real interactor will not print empty lines, and the solution should not print them either. <image> The image above illustrates the sample test. Added edges are coloured in red, and the removed edges are drawn with a dotted line. Three guessing phases denote different ways of getting the answer. * If the solution will query just the chosen vertex, the interactor will return the result of the game in that vertex. The first player loses only if the chosen vertex has the number 1. * If we add a single vertex 2 to the chosen vertex, then if the chosen vertex is either 1 or 2, the game should end in a draw. If vertex number 3 is chosen, then the first player wins. * If we place three tokens in vertex 1 and two tokens in vertex 3, then the game will end in a draw only if vertex 2 is chosen. If the professor chose vertex 3, the first player will win, if the professor chose vertex 1, then the second player will win. In the first test, the interactor will behave as if the chosen vertices are the same as those in the example above. However, if you will try to guess the answer before it limits the options to one single vertex, the solution will get "Wrong Answer", even if you print the same answers. That's because the interactor is allowed to change the chosen vertex if it's consistent with the previous query answers.
2
12
import java.io.*; import java.math.*; import java.util.*; import java.util.stream.*; public class E {boolean[] vis;ArrayList<Integer> order;int[][] g; void dfs(int v) {vis[v] = true;for (int u : g[v]) {if (!vis[u]) {dfs(u);}}order.add(v);} static final int K = 20; void submit() { int n = nextInt();int m = nextInt();int t = nextInt();int[] es = new int[2 * m]; for (int i = 0; i < 2 * m; i++) {es[i] = nextInt() - 1;} g = buildDGraph(es, n, m);vis = new boolean[n];order = new ArrayList<>();for (int i = 0; i < n; i++) {if (!vis[i]) {dfs(i);}} ArrayList<Integer> head = new ArrayList<>();ArrayList<Integer> ans = new ArrayList<>(); int[] who = new int[n]; Arrays.fill(who, -1); for (int i = 0; i < n && i < K; i++) { int v = order.get(i); head.add(v); who[v] = i; ArrayList<Integer> after = new ArrayList<>(); for (int j = 0; j < i; j++) { after.add(order.get(j)); } for (int u : g[v]) { after.remove(Integer.valueOf(u)); } for (int u : after) { ans.add(v); ans.add(u); } } ArrayList<Integer> rest = new ArrayList<>(); for (int i = K; i < n; i++) { rest.add(order.get(i)); } Collections.shuffle(rest); int[] memo = new int[1 << K]; Arrays.fill(memo, -1); ArrayList<Integer> randHead = new ArrayList<>(head); for (int v : rest) { ans.add(v); ans.add(v); int curMask = 0; for (int u : g[v]) { if (who[u] != -1) { curMask |= 1 << who[u]; } } Collections.shuffle(randHead); for (int u : randHead) { if (memo[curMask] == -1) { break; } // if (m == 100000 && v == 0) { // out.print(test(curMask, who[u]) ? ~u : u + ";"); // } ans.add(v); ans.add(test(curMask, who[u]) ? ~u : u); curMask ^= 1 << who[u]; } if (memo[curMask] != -1) { throw new AssertionError("couldn't make all nodes different"); } memo[curMask] = v; } // if (m == 100000) { // out.println("!" + Arrays.toString(g[0]).replaceAll(" ", "")); // out.println("!"); // out.flush(); // } // System.err.println(ans.size() / 2); if (ans.size() > 2 * 4242) { throw new AssertionError("too many edges added"); } out.println(ans.size() / 2); for (int i = 0; i < ans.size(); i += 2) { int v = ans.get(i); int u = ans.get(i + 1); if (u >= 0) { out.println("+ " + (v + 1) + " " + (u + 1)); } else { out.println("- " + (v + 1) + " " + ((~u) + 1)); } } out.flush(); while (t-- > 0) { int[] resp = new int[Math.min(n, K)]; for (int i = 0; i < resp.length; i++) { out.println("? 1 " + (head.get(i) + 1)); out.flush(); resp[i] = decode(nextToken()); } int winMask = 0; boolean fuck = false; for (int i = 0; i < resp.length; i++) { if (resp[i] == -1) { out.println("! " + (head.get(i) + 1)); out.flush(); fuck = true; break; } if (resp[i] == 1) { winMask |= 1 << i; } } if (!fuck) { if (memo[winMask] == -1) { throw new AssertionError("no answer for winMask"); } out.println("! " + (memo[winMask] + 1)); out.flush(); } nextToken(); } } static boolean test(int mask, int i) { return ((mask >> i) & 1) == 1; } int decode(String response) { switch (response) { case "Lose": return -1; case "Draw": return 0; case "Win": return 1; default: throw new AssertionError("unknown response"); } } int[][] buildDGraph(int[] a, int n, int m) { if (m == 0) { if (a.length == 0) { return new int[n][0]; } else { throw new AssertionError(); } } if (a.length % m != 0 || a.length < 2 * m) { throw new AssertionError("Bad array length"); } int[] deg = new int[n]; int s = a.length / m; for (int i = 0; i < a.length; i += s) { deg[a[i]]++; } int[][] g = new int[n][]; for (int i = 0; i < n; i++) { g[i] = new int[deg[i] * (s - 1)]; } for (int i = s * (m - 1); i >= 0; i -= s) { int v = a[i]; int u = a[i + 1]; int pv = (--deg[v]) * (s - 1); g[v][pv] = u; System.arraycopy(a, i + 2, g[v], pv + 1, s - 2); } return g; } void test() { } void stress() { for (int tst = 0;; tst++) { submit(); System.err.println(tst); } } E() throws IOException { is = System.in; out = new PrintWriter(System.out); submit(); // stress(); // test(); out.close(); } static final Random rng = new Random(); static final int C = 5; static int rand(int l, int r) { return l + rng.nextInt(r - l + 1); } public static void main(String[] args) throws IOException { new E(); } private InputStream is; PrintWriter out; private byte[] buf = new byte[1 << 14]; private int bufSz = 0, bufPtr = 0; private int readByte() { if (bufSz == -1) throw new RuntimeException("Reading past EOF"); if (bufPtr >= bufSz) { bufPtr = 0; try { bufSz = is.read(buf); } catch (IOException e) { throw new RuntimeException(e); } if (bufSz <= 0) return -1; } return buf[bufPtr++]; } private boolean isTrash(int c) { return c < 33 || c > 126; } private int skip() { int b; while ((b = readByte()) != -1 && isTrash(b)) ; return b; } String nextToken() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!isTrash(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } String nextString() { int b = readByte(); StringBuilder sb = new StringBuilder(); while (!isTrash(b) || b == ' ') { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } double nextDouble() { return Double.parseDouble(nextToken()); } char nextChar() { return (char) skip(); } int nextInt() { int ret = 0; int b = skip(); if (b != '-' && (b < '0' || b > '9')) { throw new InputMismatchException(); } boolean neg = false; if (b == '-') { neg = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { ret = ret * 10 + (b - '0'); } else { if (b != -1 && !isTrash(b)) { throw new InputMismatchException(); } return neg ? -ret : ret; } b = readByte(); } } long nextLong() {long ret = 0;int b = skip(); if (b != '-' && (b < '0' || b > '9')) {throw new InputMismatchException();}boolean neg = false; if (b == '-') {neg = true;b = readByte();} while (true) { if (b >= '0' && b <= '9') {ret = ret * 10 + (b - '0'); } else { if (b != -1 && !isTrash(b)) { throw new InputMismatchException(); }return neg ? -ret : ret;}b = readByte(); }}}
JAVA
1442_F. Differentiating Games
This is an interactive problem Ginny is taking an exam on game theory. The professor is tired of hearing the same answers over and over again, so he offered Ginny to play a game instead of a standard exam. As known from the course, a combinatorial game on a graph with multiple starting positions is a game with a directed graph and multiple starting vertices holding a token each. Two players take turns moving one of the tokens along the graph edges on each turn. The player who can't make a move loses the game. If both players can play an infinitely long game without losing, a draw is called. For the exam, the professor drew an acyclic directed graph and chose one of its vertices. Ginny needs to guess the vertex the professor chose. To do so, Ginny can choose a multiset of vertices S several times and ask the professor: "If I put one token in each vertex of the given graph for each occurrence of the vertex in the multiset S, and then one more in the selected vertex, what would be the result of the combinatorial game?". Having given the task, the professor left the room to give Ginny some time to prepare for the game. Ginny thinks that she's being tricked because the problem is impossible to solve. Therefore, while the professor is away, she wants to add or remove several edges from the graph. Even though the original graph was acyclic, edges could be added to the graph to make cycles appear. Interaction In this task, interaction consists of several phases. In the first phase, the interactor gives as an input to your program three integers N (1 ≀ N ≀ 1000), M (0 ≀ M ≀ 100 000), T (1 ≀ T ≀ 2000): the number of vertices and edges in the initial graph, and the number of times Ginny has to guess the chosen vertex. The next M lines contain pairs of vertices a_i b_i (1 ≀ a_i, b_i ≀ N): beginning and end of corresponding graph edges. The graph is guaranteed to be acyclic and all of its edges to be distinct. The solution should print an integer K (0 ≀ K ≀ 4242): the number of edges to change in the graph. The next K lines should contain either "+ a_i b_i" or "- a_i b_i": the beginning and the end of an edge that Ginny has to add or remove accordingly. You are allowed to add preexisting edges to the graph. Operations are performed in the order of appearance, so Ginny is allowed to remove an edge added by the solution. You can only remove an existing edge. The operations can create cycles in the graph. The next T phases are dedicated to guessing the chosen vertices. In each phase, the solution can make at most 20 queries and then print the answer. To query a multiset S, the solution should print "? |S|~S_1~S_2~...~S_{|S|}". The total size of all multisets in a single phase should not exceed 20. The interactor will reply with one of the following words: * "Win", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the first player. * "Lose", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the second player. * "Draw", if a combinatorial game with tokens in multiset S and selected vertex ends in a draw. * "Slow", if the solution made a 21-st request, or the total size of all multisets in a single phase exceeded 20. In this case, the solution should terminate and receive Wrong Answer verdict. As soon as the selected vertex is guessed, that solution should print "! v". If the chosen vertex is guessed correctly, the interactor will print Correct and the solution should either move on to the next phase of guessing or finish its execution if it's the last phase. Otherwise, the interactor will print Wrong, which means that the solution should terminate and will receive the Wrong Answer verdict. The interactor can change the chosen vertex based on graph changes and solution actions, but at every given moment of time, at least one vertex that corresponds to all given interactor answers will exist. Hack format Hacks have the following extra limitations: * T = 1 * you need to specify a single vertex, chosen by the interactor. Hack test format. The first line of input contains three integers N~M~1. The next M lines on input contain edge description in the same format as in the input. The next line contains a single integer v: the number of the chosen vertex. The hack will be successful even if the solution guesses the vertex right, but the vertex will not be the single one to match all performed queries. Example Input 3 2 3 1 2 2 3 Lose Correct Win Correct Draw Correct Output 6 + 2 2 - 1 2 + 2 3 - 2 2 + 3 1 + 2 2 ? 0 ! 1 ? 1 2 ! 3 ? 5 1 3 1 3 1 ! 2 Note In the sample test, the empty lines represent waiting for the input by the other side of the interaction. The real interactor will not print empty lines, and the solution should not print them either. <image> The image above illustrates the sample test. Added edges are coloured in red, and the removed edges are drawn with a dotted line. Three guessing phases denote different ways of getting the answer. * If the solution will query just the chosen vertex, the interactor will return the result of the game in that vertex. The first player loses only if the chosen vertex has the number 1. * If we add a single vertex 2 to the chosen vertex, then if the chosen vertex is either 1 or 2, the game should end in a draw. If vertex number 3 is chosen, then the first player wins. * If we place three tokens in vertex 1 and two tokens in vertex 3, then the game will end in a draw only if vertex 2 is chosen. If the professor chose vertex 3, the first player will win, if the professor chose vertex 1, then the second player will win. In the first test, the interactor will behave as if the chosen vertices are the same as those in the example above. However, if you will try to guess the answer before it limits the options to one single vertex, the solution will get "Wrong Answer", even if you print the same answers. That's because the interactor is allowed to change the chosen vertex if it's consistent with the previous query answers.
2
12
#include <bits/stdc++.h> using namespace std; void dfs(int v, vector<int> &col, vector<int> &ts, vector<vector<int> > &g) { col[v] = 1; for (auto u : g[v]) if (col[u] == 0) { dfs(u, col, ts, g); } ts.push_back(v); } int main() { ios_base::sync_with_stdio(false); cin.tie(0); int n, m, t; cin >> n >> m >> t; vector<vector<int> > g(n); vector<int> in(n); vector<vector<int> > con(n, vector<int>(n)); for (int(i) = 0; (i) != (m); (i)++) { int a, b; cin >> a >> b; a--, b--; g[a].push_back(b); con[a][b] = 1; in[b]++; } vector<int> ts, col(n); for (int(i) = 0; (i) != (n); (i)++) { if (in[i] == 0 && !col[i]) { dfs(i, col, ts, g); } } struct edit { char c; int fr, to; }; vector<edit> edits; int b = min(n, 18); for (int i = 0; i < b; i++) { for (int j = i + 1; j < b; j++) { int fr = ts[j], to = ts[i]; if (!con[fr][to]) { con[fr][to] = 1; edits.push_back({'+', fr + 1, to + 1}); } } } for (int i = b; i < n; i++) { int v = ts[i]; edits.push_back({'+', v + 1, v + 1}); } vector<int> have(1 << b, -1); for (int i = b; i < n; i++) { int v = ts[i]; int mask = 0; for (int j = 0; j < b; j++) { if (con[v][ts[j]]) mask += (1 << j); } int t = 0; for (int edit = 0; !t && edit <= b; edit++) { vector<int> e(b); for (int j = b - 1; j >= b - edit; j--) e[j] = 1; while (!t) { int mask2 = mask; for (int j = 0; j < b; j++) { if (e[j]) mask2 ^= (1 << j); } if (have[mask2] == -1) { t = 1; have[mask2] = v; for (int j = 0; j < b; j++) { if (e[j] && (mask & (1 << j))) { edits.push_back({'-', v + 1, ts[j] + 1}); con[v][ts[j]] = 0; } if (e[j] && !(mask & (1 << j))) { edits.push_back({'+', v + 1, ts[j] + 1}); con[v][ts[j]] = 1; } } } if (!next_permutation(e.begin(), e.end())) break; } } } cout << edits.size() << "\n"; for (auto e : edits) { cout << e.c << " " << e.fr << " " << e.to << "\n"; } cout << endl; while (t--) { vector<string> res(b); for (int j = 0; j < b; j++) { cout << "? 1 " << ts[j] + 1 << "\n"; } cout << endl; int mask = 0, fail = -1; for (int j = 0; j < b; j++) { cin >> res[j]; if (res[j] == "Lose") { assert(fail == -1); fail = ts[j]; } else { if (res[j] == "Win") { mask += (1 << j); } } } if (fail != -1) { cout << "! " << fail + 1 << endl; string s; cin >> s; continue; } cout << "! " << have[mask] + 1 << endl; string s; cin >> s; } }
CPP
1442_F. Differentiating Games
This is an interactive problem Ginny is taking an exam on game theory. The professor is tired of hearing the same answers over and over again, so he offered Ginny to play a game instead of a standard exam. As known from the course, a combinatorial game on a graph with multiple starting positions is a game with a directed graph and multiple starting vertices holding a token each. Two players take turns moving one of the tokens along the graph edges on each turn. The player who can't make a move loses the game. If both players can play an infinitely long game without losing, a draw is called. For the exam, the professor drew an acyclic directed graph and chose one of its vertices. Ginny needs to guess the vertex the professor chose. To do so, Ginny can choose a multiset of vertices S several times and ask the professor: "If I put one token in each vertex of the given graph for each occurrence of the vertex in the multiset S, and then one more in the selected vertex, what would be the result of the combinatorial game?". Having given the task, the professor left the room to give Ginny some time to prepare for the game. Ginny thinks that she's being tricked because the problem is impossible to solve. Therefore, while the professor is away, she wants to add or remove several edges from the graph. Even though the original graph was acyclic, edges could be added to the graph to make cycles appear. Interaction In this task, interaction consists of several phases. In the first phase, the interactor gives as an input to your program three integers N (1 ≀ N ≀ 1000), M (0 ≀ M ≀ 100 000), T (1 ≀ T ≀ 2000): the number of vertices and edges in the initial graph, and the number of times Ginny has to guess the chosen vertex. The next M lines contain pairs of vertices a_i b_i (1 ≀ a_i, b_i ≀ N): beginning and end of corresponding graph edges. The graph is guaranteed to be acyclic and all of its edges to be distinct. The solution should print an integer K (0 ≀ K ≀ 4242): the number of edges to change in the graph. The next K lines should contain either "+ a_i b_i" or "- a_i b_i": the beginning and the end of an edge that Ginny has to add or remove accordingly. You are allowed to add preexisting edges to the graph. Operations are performed in the order of appearance, so Ginny is allowed to remove an edge added by the solution. You can only remove an existing edge. The operations can create cycles in the graph. The next T phases are dedicated to guessing the chosen vertices. In each phase, the solution can make at most 20 queries and then print the answer. To query a multiset S, the solution should print "? |S|~S_1~S_2~...~S_{|S|}". The total size of all multisets in a single phase should not exceed 20. The interactor will reply with one of the following words: * "Win", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the first player. * "Lose", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the second player. * "Draw", if a combinatorial game with tokens in multiset S and selected vertex ends in a draw. * "Slow", if the solution made a 21-st request, or the total size of all multisets in a single phase exceeded 20. In this case, the solution should terminate and receive Wrong Answer verdict. As soon as the selected vertex is guessed, that solution should print "! v". If the chosen vertex is guessed correctly, the interactor will print Correct and the solution should either move on to the next phase of guessing or finish its execution if it's the last phase. Otherwise, the interactor will print Wrong, which means that the solution should terminate and will receive the Wrong Answer verdict. The interactor can change the chosen vertex based on graph changes and solution actions, but at every given moment of time, at least one vertex that corresponds to all given interactor answers will exist. Hack format Hacks have the following extra limitations: * T = 1 * you need to specify a single vertex, chosen by the interactor. Hack test format. The first line of input contains three integers N~M~1. The next M lines on input contain edge description in the same format as in the input. The next line contains a single integer v: the number of the chosen vertex. The hack will be successful even if the solution guesses the vertex right, but the vertex will not be the single one to match all performed queries. Example Input 3 2 3 1 2 2 3 Lose Correct Win Correct Draw Correct Output 6 + 2 2 - 1 2 + 2 3 - 2 2 + 3 1 + 2 2 ? 0 ! 1 ? 1 2 ! 3 ? 5 1 3 1 3 1 ! 2 Note In the sample test, the empty lines represent waiting for the input by the other side of the interaction. The real interactor will not print empty lines, and the solution should not print them either. <image> The image above illustrates the sample test. Added edges are coloured in red, and the removed edges are drawn with a dotted line. Three guessing phases denote different ways of getting the answer. * If the solution will query just the chosen vertex, the interactor will return the result of the game in that vertex. The first player loses only if the chosen vertex has the number 1. * If we add a single vertex 2 to the chosen vertex, then if the chosen vertex is either 1 or 2, the game should end in a draw. If vertex number 3 is chosen, then the first player wins. * If we place three tokens in vertex 1 and two tokens in vertex 3, then the game will end in a draw only if vertex 2 is chosen. If the professor chose vertex 3, the first player will win, if the professor chose vertex 1, then the second player will win. In the first test, the interactor will behave as if the chosen vertices are the same as those in the example above. However, if you will try to guess the answer before it limits the options to one single vertex, the solution will get "Wrong Answer", even if you print the same answers. That's because the interactor is allowed to change the chosen vertex if it's consistent with the previous query answers.
2
12
#include <bits/stdc++.h> using namespace std; int n, m, k, T, head[1010], o = 0, deg[1010], id[1010]; int tpn[1010], l = 1, r = 0, cnt = 0; int vis[1050000], st[4300][3]; char s[100]; struct edge { int to, link; } e[100010]; void add_edge(int u, int v) { e[++o].to = v, e[o].link = head[u], head[u] = o, deg[v]++; } queue<int> q; int find(int S) { while (!q.empty()) q.pop(); q.push(S); while (!q.empty()) { int now = q.front(); q.pop(); if (!vis[now]) return now; for (int i = 0; i < k; i++) q.push(now ^ (1 << i)); } } void opt(int op, int x, int y) { st[++cnt][0] = op, st[cnt][1] = x, st[cnt][2] = y; } int main() { scanf("%d%d%d", &n, &m, &T), k = min(n, 20); for (int i = 1, u, v; i <= m; i++) scanf("%d%d", &u, &v), add_edge(u, v); for (int i = 1; i <= n; i++) if (!deg[i]) tpn[++r] = i; while (l <= r) { int u = tpn[l]; l++; for (int i = head[u]; i; i = e[i].link) { if (!--deg[e[i].to]) tpn[++r] = e[i].to; } } reverse(tpn + 1, tpn + n + 1); for (int i = 1; i <= k; i++) { id[tpn[i]] = i; for (int j = 1; j < i; j++) opt(1, tpn[i], tpn[j]); } for (int j = k + 1; j <= n; j++) { int u = tpn[j]; opt(1, u, u); int S = 0, tmp; for (int i = head[u]; i; i = e[i].link) if (id[e[i].to]) S |= 1 << (id[e[i].to] - 1); tmp = find(S), vis[tmp] = u; for (int i = 0; i < k; i++) if (((tmp ^ S) >> i) & 1) opt((tmp >> i) & 1, u, tpn[i + 1]); } printf("%d\n", cnt); for (int i = 1; i <= cnt; i++) printf("%c %d %d\n", st[i][0] ? '+' : '-', st[i][1], st[i][2]); while (T--) { int S = 0, ans = 0; for (int i = 1; i <= k; i++) { printf("? 1 %d\n", tpn[i]); fflush(stdout); scanf("%s", s + 1); if (s[1] == 'L') { ans = tpn[i]; break; } else if (s[1] == 'W') S |= 1 << (i - 1); } printf("! %d\n", ans ? ans : vis[S]); fflush(stdout); scanf("%s", s + 1); } }
CPP
1442_F. Differentiating Games
This is an interactive problem Ginny is taking an exam on game theory. The professor is tired of hearing the same answers over and over again, so he offered Ginny to play a game instead of a standard exam. As known from the course, a combinatorial game on a graph with multiple starting positions is a game with a directed graph and multiple starting vertices holding a token each. Two players take turns moving one of the tokens along the graph edges on each turn. The player who can't make a move loses the game. If both players can play an infinitely long game without losing, a draw is called. For the exam, the professor drew an acyclic directed graph and chose one of its vertices. Ginny needs to guess the vertex the professor chose. To do so, Ginny can choose a multiset of vertices S several times and ask the professor: "If I put one token in each vertex of the given graph for each occurrence of the vertex in the multiset S, and then one more in the selected vertex, what would be the result of the combinatorial game?". Having given the task, the professor left the room to give Ginny some time to prepare for the game. Ginny thinks that she's being tricked because the problem is impossible to solve. Therefore, while the professor is away, she wants to add or remove several edges from the graph. Even though the original graph was acyclic, edges could be added to the graph to make cycles appear. Interaction In this task, interaction consists of several phases. In the first phase, the interactor gives as an input to your program three integers N (1 ≀ N ≀ 1000), M (0 ≀ M ≀ 100 000), T (1 ≀ T ≀ 2000): the number of vertices and edges in the initial graph, and the number of times Ginny has to guess the chosen vertex. The next M lines contain pairs of vertices a_i b_i (1 ≀ a_i, b_i ≀ N): beginning and end of corresponding graph edges. The graph is guaranteed to be acyclic and all of its edges to be distinct. The solution should print an integer K (0 ≀ K ≀ 4242): the number of edges to change in the graph. The next K lines should contain either "+ a_i b_i" or "- a_i b_i": the beginning and the end of an edge that Ginny has to add or remove accordingly. You are allowed to add preexisting edges to the graph. Operations are performed in the order of appearance, so Ginny is allowed to remove an edge added by the solution. You can only remove an existing edge. The operations can create cycles in the graph. The next T phases are dedicated to guessing the chosen vertices. In each phase, the solution can make at most 20 queries and then print the answer. To query a multiset S, the solution should print "? |S|~S_1~S_2~...~S_{|S|}". The total size of all multisets in a single phase should not exceed 20. The interactor will reply with one of the following words: * "Win", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the first player. * "Lose", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the second player. * "Draw", if a combinatorial game with tokens in multiset S and selected vertex ends in a draw. * "Slow", if the solution made a 21-st request, or the total size of all multisets in a single phase exceeded 20. In this case, the solution should terminate and receive Wrong Answer verdict. As soon as the selected vertex is guessed, that solution should print "! v". If the chosen vertex is guessed correctly, the interactor will print Correct and the solution should either move on to the next phase of guessing or finish its execution if it's the last phase. Otherwise, the interactor will print Wrong, which means that the solution should terminate and will receive the Wrong Answer verdict. The interactor can change the chosen vertex based on graph changes and solution actions, but at every given moment of time, at least one vertex that corresponds to all given interactor answers will exist. Hack format Hacks have the following extra limitations: * T = 1 * you need to specify a single vertex, chosen by the interactor. Hack test format. The first line of input contains three integers N~M~1. The next M lines on input contain edge description in the same format as in the input. The next line contains a single integer v: the number of the chosen vertex. The hack will be successful even if the solution guesses the vertex right, but the vertex will not be the single one to match all performed queries. Example Input 3 2 3 1 2 2 3 Lose Correct Win Correct Draw Correct Output 6 + 2 2 - 1 2 + 2 3 - 2 2 + 3 1 + 2 2 ? 0 ! 1 ? 1 2 ! 3 ? 5 1 3 1 3 1 ! 2 Note In the sample test, the empty lines represent waiting for the input by the other side of the interaction. The real interactor will not print empty lines, and the solution should not print them either. <image> The image above illustrates the sample test. Added edges are coloured in red, and the removed edges are drawn with a dotted line. Three guessing phases denote different ways of getting the answer. * If the solution will query just the chosen vertex, the interactor will return the result of the game in that vertex. The first player loses only if the chosen vertex has the number 1. * If we add a single vertex 2 to the chosen vertex, then if the chosen vertex is either 1 or 2, the game should end in a draw. If vertex number 3 is chosen, then the first player wins. * If we place three tokens in vertex 1 and two tokens in vertex 3, then the game will end in a draw only if vertex 2 is chosen. If the professor chose vertex 3, the first player will win, if the professor chose vertex 1, then the second player will win. In the first test, the interactor will behave as if the chosen vertices are the same as those in the example above. However, if you will try to guess the answer before it limits the options to one single vertex, the solution will get "Wrong Answer", even if you print the same answers. That's because the interactor is allowed to change the chosen vertex if it's consistent with the previous query answers.
2
12
#include <bits/stdc++.h> using namespace std; const int N = 1005; int n, m, kk, deg[N], id[N], l = 1, r, idx, tp[N]; vector<int> v[N]; int vis[1 << 20]; struct Mov { int x, y, z; } mov[N * 5]; char s[N]; int find(int st) { queue<int> q; q.push(st); while (!q.empty()) { int nd = q.front(); q.pop(); if (!vis[nd]) return nd; for (int i = 0; i < kk; i++) q.push(nd ^ (1 << i)); } return -1; } inline void add(int x, int y, int z) { mov[++idx] = {x, y, z}; } int main() { ios::sync_with_stdio(false); cin >> n >> m; int T; cin >> T; kk = min(n, 20); int t1, t2; for (int i = 1; i <= m; i++) cin >> t1 >> t2, v[t1].push_back(t2), ++deg[t2]; for (int i = 1; i <= n; i++) if (!deg[i]) tp[++r] = i; while (l <= r) { int p = tp[l++]; for (auto &i : v[p]) if (!--deg[i]) tp[++r] = i; } reverse(tp + 1, tp + n + 1); for (int i = 1; i <= kk; i++) { id[tp[i]] = i; for (int j = 1; j < i; j++) add(1, tp[i], tp[j]); } for (int j = kk + 1; j <= n; j++) { int nd = tp[j]; add(1, nd, nd); int st = 0; for (auto &i : v[nd]) if (id[i]) st |= 1 << (id[i] - 1); int tmp = find(st); vis[tmp] = nd; for (int i = 0; i < kk; i++) if (((tmp ^ st) >> i) & 1) add((tmp >> i) & 1, nd, tp[i + 1]); } cout << idx << endl; for (int i = 1; i <= idx; i++) cout << (mov[i].x ? "+ " : "- ") << mov[i].y << ' ' << mov[i].z << endl; while (T--) { int st = 0, ans = 0; for (int i = 1; i <= kk; i++) { cout << "? 1 " << tp[i] << endl; cin >> (s + 1); if (s[1] == 'L') { ans = tp[i]; break; } else if (s[1] == 'W') st |= 1 << (i - 1); } cout << "! " << (ans ? ans : vis[st]) << endl; cin >> (s + 1); } return 0; }
CPP
1442_F. Differentiating Games
This is an interactive problem Ginny is taking an exam on game theory. The professor is tired of hearing the same answers over and over again, so he offered Ginny to play a game instead of a standard exam. As known from the course, a combinatorial game on a graph with multiple starting positions is a game with a directed graph and multiple starting vertices holding a token each. Two players take turns moving one of the tokens along the graph edges on each turn. The player who can't make a move loses the game. If both players can play an infinitely long game without losing, a draw is called. For the exam, the professor drew an acyclic directed graph and chose one of its vertices. Ginny needs to guess the vertex the professor chose. To do so, Ginny can choose a multiset of vertices S several times and ask the professor: "If I put one token in each vertex of the given graph for each occurrence of the vertex in the multiset S, and then one more in the selected vertex, what would be the result of the combinatorial game?". Having given the task, the professor left the room to give Ginny some time to prepare for the game. Ginny thinks that she's being tricked because the problem is impossible to solve. Therefore, while the professor is away, she wants to add or remove several edges from the graph. Even though the original graph was acyclic, edges could be added to the graph to make cycles appear. Interaction In this task, interaction consists of several phases. In the first phase, the interactor gives as an input to your program three integers N (1 ≀ N ≀ 1000), M (0 ≀ M ≀ 100 000), T (1 ≀ T ≀ 2000): the number of vertices and edges in the initial graph, and the number of times Ginny has to guess the chosen vertex. The next M lines contain pairs of vertices a_i b_i (1 ≀ a_i, b_i ≀ N): beginning and end of corresponding graph edges. The graph is guaranteed to be acyclic and all of its edges to be distinct. The solution should print an integer K (0 ≀ K ≀ 4242): the number of edges to change in the graph. The next K lines should contain either "+ a_i b_i" or "- a_i b_i": the beginning and the end of an edge that Ginny has to add or remove accordingly. You are allowed to add preexisting edges to the graph. Operations are performed in the order of appearance, so Ginny is allowed to remove an edge added by the solution. You can only remove an existing edge. The operations can create cycles in the graph. The next T phases are dedicated to guessing the chosen vertices. In each phase, the solution can make at most 20 queries and then print the answer. To query a multiset S, the solution should print "? |S|~S_1~S_2~...~S_{|S|}". The total size of all multisets in a single phase should not exceed 20. The interactor will reply with one of the following words: * "Win", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the first player. * "Lose", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the second player. * "Draw", if a combinatorial game with tokens in multiset S and selected vertex ends in a draw. * "Slow", if the solution made a 21-st request, or the total size of all multisets in a single phase exceeded 20. In this case, the solution should terminate and receive Wrong Answer verdict. As soon as the selected vertex is guessed, that solution should print "! v". If the chosen vertex is guessed correctly, the interactor will print Correct and the solution should either move on to the next phase of guessing or finish its execution if it's the last phase. Otherwise, the interactor will print Wrong, which means that the solution should terminate and will receive the Wrong Answer verdict. The interactor can change the chosen vertex based on graph changes and solution actions, but at every given moment of time, at least one vertex that corresponds to all given interactor answers will exist. Hack format Hacks have the following extra limitations: * T = 1 * you need to specify a single vertex, chosen by the interactor. Hack test format. The first line of input contains three integers N~M~1. The next M lines on input contain edge description in the same format as in the input. The next line contains a single integer v: the number of the chosen vertex. The hack will be successful even if the solution guesses the vertex right, but the vertex will not be the single one to match all performed queries. Example Input 3 2 3 1 2 2 3 Lose Correct Win Correct Draw Correct Output 6 + 2 2 - 1 2 + 2 3 - 2 2 + 3 1 + 2 2 ? 0 ! 1 ? 1 2 ! 3 ? 5 1 3 1 3 1 ! 2 Note In the sample test, the empty lines represent waiting for the input by the other side of the interaction. The real interactor will not print empty lines, and the solution should not print them either. <image> The image above illustrates the sample test. Added edges are coloured in red, and the removed edges are drawn with a dotted line. Three guessing phases denote different ways of getting the answer. * If the solution will query just the chosen vertex, the interactor will return the result of the game in that vertex. The first player loses only if the chosen vertex has the number 1. * If we add a single vertex 2 to the chosen vertex, then if the chosen vertex is either 1 or 2, the game should end in a draw. If vertex number 3 is chosen, then the first player wins. * If we place three tokens in vertex 1 and two tokens in vertex 3, then the game will end in a draw only if vertex 2 is chosen. If the professor chose vertex 3, the first player will win, if the professor chose vertex 1, then the second player will win. In the first test, the interactor will behave as if the chosen vertices are the same as those in the example above. However, if you will try to guess the answer before it limits the options to one single vertex, the solution will get "Wrong Answer", even if you print the same answers. That's because the interactor is allowed to change the chosen vertex if it's consistent with the previous query answers.
2
12
#include <bits/stdc++.h> using namespace std; const int maxn = 1111, maxm = 111111, maxs = 1111111, mod = 998244353; inline long long read() { char ch = getchar(); long long x = 0, f = 0; while (ch < '0' || ch > '9') f |= ch == '-', ch = getchar(); while (ch >= '0' && ch <= '9') x = x * 10 + ch - '0', ch = getchar(); return f ? -x : x; } inline int qpow(int a, int b) { int ans = 1; for (; b; b >>= 1, a = 1ll * a * a % mod) if (b & 1) ans = 1ll * ans * a % mod; return ans; } int n, m, T, el, head[maxn], to[maxm], nxt[maxm], deg[maxn], q[maxn], h = 1, r = 0, id[maxn], tl, x[4444], y[4444], S[maxn], at[22]; char op[4444], ver[10]; bool vis[maxs]; inline void add(int u, int v) { to[++el] = v; nxt[el] = head[u]; head[u] = el; } inline void add(char c, int xx, int yy) { tl++; op[tl] = c; x[tl] = xx; y[tl] = yy; } int main() { n = read(); m = read(); T = read(); for (int i = (1); i <= (m); i++) { int u = read(), v = read(); add(u, v); deg[v]++; } for (int i = (1); i <= (n); i++) if (!deg[i]) q[++r] = i; while (h <= r) { int u = q[h++]; for (int i = head[u]; i; i = nxt[i]) { int v = to[i]; if (!--deg[v]) q[++r] = v; } } for (int i = (1); i <= (n); i++) id[i] = -1; for (int i = (r); i >= (max(1, r - 19)); i--) id[q[i]] = r - i, at[r - i] = q[i]; for (int i = (max(1, r - 19)); i <= (r); i++) for (int j = (i + 1); j <= (r); j++) add('+', q[i], q[j]); if (r - 20 >= 1) { for (int i = (1); i <= (r - 20); i++) { add('+', q[i], q[i]); for (int j = head[q[i]]; j; j = nxt[j]) if (~id[to[j]]) S[q[i]] |= 1 << id[to[j]]; bool flag = false; for (int x = (20); x >= (0); x--) { for (int y = (20); y >= (x + 1); y--) { for (int z = (20); z >= (y + 1); z--) { int tmp = S[q[i]]; if (x <= 19) tmp ^= 1 << x; if (y <= 19) tmp ^= 1 << y; if (z <= 19) tmp ^= 1 << z; if (!vis[tmp]) { for (int w = (0); w <= (19); w++) { int a = (S[q[i]] >> w) & 1, b = (tmp >> w) & 1; if (!a && b) add('+', q[i], at[w]); if (a && !b) add('-', q[i], at[w]); } S[q[i]] = tmp; vis[tmp] = true; flag = true; break; } } if (flag) break; } if (flag) break; } if (!flag) return puts("/kk"), 1; } } printf("%d\n", tl); for (int i = (1); i <= (tl); i++) printf("%c %d %d\n", op[i], x[i], y[i]); fflush(stdout); while (T--) { int s = 0, flag = 0; for (int i = (0); i <= (min(r - 1, 19)); i++) { printf("? 1 %d\n", at[i]); fflush(stdout); scanf("%s", ver); switch (ver[0]) { case 'W': s |= 1 << i; break; case 'L': flag = at[i]; break; case 'D': break; } } if (flag) printf("! %d\n", flag); else { for (int i = (1); i <= (r - 20); i++) if (S[q[i]] == s) { printf("! %d\n", q[i]); break; } } fflush(stdout); scanf("%s", ver); if (ver[0] == 'W') return puts("/kk"), 2; } }
CPP
1442_F. Differentiating Games
This is an interactive problem Ginny is taking an exam on game theory. The professor is tired of hearing the same answers over and over again, so he offered Ginny to play a game instead of a standard exam. As known from the course, a combinatorial game on a graph with multiple starting positions is a game with a directed graph and multiple starting vertices holding a token each. Two players take turns moving one of the tokens along the graph edges on each turn. The player who can't make a move loses the game. If both players can play an infinitely long game without losing, a draw is called. For the exam, the professor drew an acyclic directed graph and chose one of its vertices. Ginny needs to guess the vertex the professor chose. To do so, Ginny can choose a multiset of vertices S several times and ask the professor: "If I put one token in each vertex of the given graph for each occurrence of the vertex in the multiset S, and then one more in the selected vertex, what would be the result of the combinatorial game?". Having given the task, the professor left the room to give Ginny some time to prepare for the game. Ginny thinks that she's being tricked because the problem is impossible to solve. Therefore, while the professor is away, she wants to add or remove several edges from the graph. Even though the original graph was acyclic, edges could be added to the graph to make cycles appear. Interaction In this task, interaction consists of several phases. In the first phase, the interactor gives as an input to your program three integers N (1 ≀ N ≀ 1000), M (0 ≀ M ≀ 100 000), T (1 ≀ T ≀ 2000): the number of vertices and edges in the initial graph, and the number of times Ginny has to guess the chosen vertex. The next M lines contain pairs of vertices a_i b_i (1 ≀ a_i, b_i ≀ N): beginning and end of corresponding graph edges. The graph is guaranteed to be acyclic and all of its edges to be distinct. The solution should print an integer K (0 ≀ K ≀ 4242): the number of edges to change in the graph. The next K lines should contain either "+ a_i b_i" or "- a_i b_i": the beginning and the end of an edge that Ginny has to add or remove accordingly. You are allowed to add preexisting edges to the graph. Operations are performed in the order of appearance, so Ginny is allowed to remove an edge added by the solution. You can only remove an existing edge. The operations can create cycles in the graph. The next T phases are dedicated to guessing the chosen vertices. In each phase, the solution can make at most 20 queries and then print the answer. To query a multiset S, the solution should print "? |S|~S_1~S_2~...~S_{|S|}". The total size of all multisets in a single phase should not exceed 20. The interactor will reply with one of the following words: * "Win", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the first player. * "Lose", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the second player. * "Draw", if a combinatorial game with tokens in multiset S and selected vertex ends in a draw. * "Slow", if the solution made a 21-st request, or the total size of all multisets in a single phase exceeded 20. In this case, the solution should terminate and receive Wrong Answer verdict. As soon as the selected vertex is guessed, that solution should print "! v". If the chosen vertex is guessed correctly, the interactor will print Correct and the solution should either move on to the next phase of guessing or finish its execution if it's the last phase. Otherwise, the interactor will print Wrong, which means that the solution should terminate and will receive the Wrong Answer verdict. The interactor can change the chosen vertex based on graph changes and solution actions, but at every given moment of time, at least one vertex that corresponds to all given interactor answers will exist. Hack format Hacks have the following extra limitations: * T = 1 * you need to specify a single vertex, chosen by the interactor. Hack test format. The first line of input contains three integers N~M~1. The next M lines on input contain edge description in the same format as in the input. The next line contains a single integer v: the number of the chosen vertex. The hack will be successful even if the solution guesses the vertex right, but the vertex will not be the single one to match all performed queries. Example Input 3 2 3 1 2 2 3 Lose Correct Win Correct Draw Correct Output 6 + 2 2 - 1 2 + 2 3 - 2 2 + 3 1 + 2 2 ? 0 ! 1 ? 1 2 ! 3 ? 5 1 3 1 3 1 ! 2 Note In the sample test, the empty lines represent waiting for the input by the other side of the interaction. The real interactor will not print empty lines, and the solution should not print them either. <image> The image above illustrates the sample test. Added edges are coloured in red, and the removed edges are drawn with a dotted line. Three guessing phases denote different ways of getting the answer. * If the solution will query just the chosen vertex, the interactor will return the result of the game in that vertex. The first player loses only if the chosen vertex has the number 1. * If we add a single vertex 2 to the chosen vertex, then if the chosen vertex is either 1 or 2, the game should end in a draw. If vertex number 3 is chosen, then the first player wins. * If we place three tokens in vertex 1 and two tokens in vertex 3, then the game will end in a draw only if vertex 2 is chosen. If the professor chose vertex 3, the first player will win, if the professor chose vertex 1, then the second player will win. In the first test, the interactor will behave as if the chosen vertices are the same as those in the example above. However, if you will try to guess the answer before it limits the options to one single vertex, the solution will get "Wrong Answer", even if you print the same answers. That's because the interactor is allowed to change the chosen vertex if it's consistent with the previous query answers.
2
12
#include <bits/stdc++.h> using namespace std; const int N = 1005; int n, m, T; int e[N][N], q[N], deg[N]; int id[N], adj[N]; void topo() { for (int i = (int)(1); i <= (int)(n); i++) for (int j = (int)(1); j <= (int)(n); j++) if (e[i][j]) ++deg[j]; int h = 0, t = 0; for (int i = (int)(1); i <= (int)(n); i++) if (!deg[i]) q[++t] = i; while (h != t) { int x = q[++h]; for (int i = (int)(1); i <= (int)(n); i++) if (e[x][i]) if (!--deg[i]) q[++t] = i; } } int q2[5005]; int vi[1 << 20 | 5]; void build() { *q = 0; vector<pair<int, int> > opt; int p1 = max(1, n - 19), m = n - p1 + 1; q2[++*q2] = 0; for (int i = (int)(0); i <= (int)(m - 1); i++) q2[++*q2] = 1 << i; for (int i = (int)(0); i <= (int)(m - 1); i++) for (int j = (int)(i + 1); j <= (int)(m - 1); j++) q2[++*q2] = (1 << i) | (1 << j); for (int i = (int)(0); i <= (int)(m - 1); i++) for (int j = (int)(i + 1); j <= (int)(m - 1); j++) for (int k = (int)(j + 1); k <= (int)(m - 1); k++) q2[++*q2] = (1 << i) | (1 << j) | (1 << k); for (int i = (int)(p1); i <= (int)(n); i++) for (int j = (int)(i + 1); j <= (int)(n); j++) if (!e[q[i]][q[j]]) opt.push_back(pair<int, int>(q[i], q[j])); for (int i = (int)(p1); i <= (int)(n); i++) { id[q[i]] = adj[q[i]] = 1 << (n - i); vi[id[q[i]]] = 1; } for (int i = (int)(1); i <= (int)(p1 - 1); i++) { int x = q[i]; opt.push_back(pair<int, int>(x, x)); for (int j = (int)(1); j <= (int)(n); j++) if (e[x][j] && id[j]) adj[x] |= id[j]; for (int j = (int)(1); j <= (int)(*q2); j++) if (!vi[adj[x] ^ q2[j]]) { adj[x] ^= q2[j]; vi[adj[x]] = 1; for (int p = (int)(p1); p <= (int)(n); p++) if (q2[j] & id[q[p]]) opt.push_back(pair<int, int>(x, q[p])); break; } } printf("%d\n", opt.size()); for (auto i : opt) if (e[i.first][i.second]) printf("- %d %d\n", i.first, i.second); else printf("+ %d %d\n", i.first, i.second); fflush(stdout); } void solve() { int p1 = max(1, n - 19), m = n - p1 + 1, vadj = 0; for (int i = (int)(p1); i <= (int)(n); i++) { printf("? 1 %d\n", q[i]); fflush(stdout); char s[10]; scanf("%s", s + 1); if (s[1] == 'L') { printf("! %d\n", q[i]); fflush(stdout); scanf("%s", s + 1); return; } if (s[1] == 'W') vadj |= id[q[i]]; } for (int i = (int)(1); i <= (int)(n); i++) if (adj[i] == vadj) printf("! %d\n", i); fflush(stdout); char s[10]; scanf("%s", s + 1); } int main() { scanf("%d%d%d", &n, &m, &T); for (int i = (int)(1); i <= (int)(m); i++) { int x, y; scanf("%d%d", &x, &y); e[x][y] = 1; } topo(); build(); while (T--) solve(); }
CPP
1442_F. Differentiating Games
This is an interactive problem Ginny is taking an exam on game theory. The professor is tired of hearing the same answers over and over again, so he offered Ginny to play a game instead of a standard exam. As known from the course, a combinatorial game on a graph with multiple starting positions is a game with a directed graph and multiple starting vertices holding a token each. Two players take turns moving one of the tokens along the graph edges on each turn. The player who can't make a move loses the game. If both players can play an infinitely long game without losing, a draw is called. For the exam, the professor drew an acyclic directed graph and chose one of its vertices. Ginny needs to guess the vertex the professor chose. To do so, Ginny can choose a multiset of vertices S several times and ask the professor: "If I put one token in each vertex of the given graph for each occurrence of the vertex in the multiset S, and then one more in the selected vertex, what would be the result of the combinatorial game?". Having given the task, the professor left the room to give Ginny some time to prepare for the game. Ginny thinks that she's being tricked because the problem is impossible to solve. Therefore, while the professor is away, she wants to add or remove several edges from the graph. Even though the original graph was acyclic, edges could be added to the graph to make cycles appear. Interaction In this task, interaction consists of several phases. In the first phase, the interactor gives as an input to your program three integers N (1 ≀ N ≀ 1000), M (0 ≀ M ≀ 100 000), T (1 ≀ T ≀ 2000): the number of vertices and edges in the initial graph, and the number of times Ginny has to guess the chosen vertex. The next M lines contain pairs of vertices a_i b_i (1 ≀ a_i, b_i ≀ N): beginning and end of corresponding graph edges. The graph is guaranteed to be acyclic and all of its edges to be distinct. The solution should print an integer K (0 ≀ K ≀ 4242): the number of edges to change in the graph. The next K lines should contain either "+ a_i b_i" or "- a_i b_i": the beginning and the end of an edge that Ginny has to add or remove accordingly. You are allowed to add preexisting edges to the graph. Operations are performed in the order of appearance, so Ginny is allowed to remove an edge added by the solution. You can only remove an existing edge. The operations can create cycles in the graph. The next T phases are dedicated to guessing the chosen vertices. In each phase, the solution can make at most 20 queries and then print the answer. To query a multiset S, the solution should print "? |S|~S_1~S_2~...~S_{|S|}". The total size of all multisets in a single phase should not exceed 20. The interactor will reply with one of the following words: * "Win", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the first player. * "Lose", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the second player. * "Draw", if a combinatorial game with tokens in multiset S and selected vertex ends in a draw. * "Slow", if the solution made a 21-st request, or the total size of all multisets in a single phase exceeded 20. In this case, the solution should terminate and receive Wrong Answer verdict. As soon as the selected vertex is guessed, that solution should print "! v". If the chosen vertex is guessed correctly, the interactor will print Correct and the solution should either move on to the next phase of guessing or finish its execution if it's the last phase. Otherwise, the interactor will print Wrong, which means that the solution should terminate and will receive the Wrong Answer verdict. The interactor can change the chosen vertex based on graph changes and solution actions, but at every given moment of time, at least one vertex that corresponds to all given interactor answers will exist. Hack format Hacks have the following extra limitations: * T = 1 * you need to specify a single vertex, chosen by the interactor. Hack test format. The first line of input contains three integers N~M~1. The next M lines on input contain edge description in the same format as in the input. The next line contains a single integer v: the number of the chosen vertex. The hack will be successful even if the solution guesses the vertex right, but the vertex will not be the single one to match all performed queries. Example Input 3 2 3 1 2 2 3 Lose Correct Win Correct Draw Correct Output 6 + 2 2 - 1 2 + 2 3 - 2 2 + 3 1 + 2 2 ? 0 ! 1 ? 1 2 ! 3 ? 5 1 3 1 3 1 ! 2 Note In the sample test, the empty lines represent waiting for the input by the other side of the interaction. The real interactor will not print empty lines, and the solution should not print them either. <image> The image above illustrates the sample test. Added edges are coloured in red, and the removed edges are drawn with a dotted line. Three guessing phases denote different ways of getting the answer. * If the solution will query just the chosen vertex, the interactor will return the result of the game in that vertex. The first player loses only if the chosen vertex has the number 1. * If we add a single vertex 2 to the chosen vertex, then if the chosen vertex is either 1 or 2, the game should end in a draw. If vertex number 3 is chosen, then the first player wins. * If we place three tokens in vertex 1 and two tokens in vertex 3, then the game will end in a draw only if vertex 2 is chosen. If the professor chose vertex 3, the first player will win, if the professor chose vertex 1, then the second player will win. In the first test, the interactor will behave as if the chosen vertices are the same as those in the example above. However, if you will try to guess the answer before it limits the options to one single vertex, the solution will get "Wrong Answer", even if you print the same answers. That's because the interactor is allowed to change the chosen vertex if it's consistent with the previous query answers.
2
12
#include <bits/stdc++.h> const long long MOD = 1e9 + 7; const long long INF = 1e9; const long long INFLL = 1e18; using namespace std; int cx[4] = {0, 0, 1, -1}; int cy[4] = {-1, 1, 0, 0}; string Yes[2] = {"No\n", "Yes\n"}; string YES[2] = {"NO\n", "YES\n"}; string Possible[2] = {"Impossible\n", "Possible\n"}; string POSSIBLE[2] = {"IMPOSSIBLE\n", "POSSIBLE\n"}; void dfs(int v, vector<int> &col, vector<int> &ts, vector<vector<int> > &g) { col[v] = 1; for (auto u : g[v]) if (col[u] == 0) { dfs(u, col, ts, g); } ts.push_back(v); } int main() { ios_base::sync_with_stdio(false); cin.tie(0); int n, m, t; cin >> n >> m >> t; vector<vector<int> > g(n); vector<int> in(n); vector<vector<int> > con(n, vector<int>(n)); for (int(i) = 0; (i) != (m); (i)++) { int a, b; cin >> a >> b; a--, b--; g[a].push_back(b); con[a][b] = 1; in[b]++; } vector<int> ts, col(n); for (int(i) = 0; (i) != (n); (i)++) { if (in[i] == 0 && !col[i]) { dfs(i, col, ts, g); } } struct edit { char c; int fr, to; }; vector<edit> edits; int b = min(n, 19); for (int i = 0; i < b; i++) { for (int j = i + 1; j < b; j++) { int fr = ts[j], to = ts[i]; if (!con[fr][to]) { con[fr][to] = 1; edits.push_back({'+', fr + 1, to + 1}); } } } for (int i = b; i < n; i++) { int v = ts[i]; edits.push_back({'+', v + 1, v + 1}); } vector<int> have(1 << b, -1); for (int i = b; i < n; i++) { int v = ts[i]; int mask = 0; for (int j = 0; j < b; j++) { if (con[v][ts[j]]) mask += (1 << j); } int t = 0; for (int edit = 0; !t && edit <= b; edit++) { vector<int> e(b); for (int j = b - 1; j >= b - edit; j--) e[j] = 1; while (!t) { int mask2 = mask; for (int j = 0; j < b; j++) { if (e[j]) mask2 ^= (1 << j); } if (have[mask2] == -1) { t = 1; have[mask2] = v; for (int j = 0; j < b; j++) { if (e[j] && (mask & (1 << j))) { edits.push_back({'-', v + 1, ts[j] + 1}); con[v][ts[j]] = 0; } if (e[j] && !(mask & (1 << j))) { edits.push_back({'+', v + 1, ts[j] + 1}); con[v][ts[j]] = 1; } } } if (!next_permutation((e).begin(), (e).end())) break; } } } cout << edits.size() << endl; for (auto e : edits) { cout << e.c << " " << e.fr << " " << e.to << endl; } cout << endl; while (t--) { vector<string> res(b); for (int j = 0; j < b; j++) { cout << "? 1 " << ts[j] + 1 << endl; cin >> res[j]; } int mask = 0, fail = -1; for (int j = 0; j < b; j++) { if (res[j] == "Lose") { assert(fail == -1); fail = ts[j]; } else { if (res[j] == "Win") { mask += (1 << j); } } } if (fail != -1) { cout << "! " << fail + 1 << endl; string s; cin >> s; continue; } cout << "! " << have[mask] + 1 << endl; string s; cin >> s; } }
CPP
1442_F. Differentiating Games
This is an interactive problem Ginny is taking an exam on game theory. The professor is tired of hearing the same answers over and over again, so he offered Ginny to play a game instead of a standard exam. As known from the course, a combinatorial game on a graph with multiple starting positions is a game with a directed graph and multiple starting vertices holding a token each. Two players take turns moving one of the tokens along the graph edges on each turn. The player who can't make a move loses the game. If both players can play an infinitely long game without losing, a draw is called. For the exam, the professor drew an acyclic directed graph and chose one of its vertices. Ginny needs to guess the vertex the professor chose. To do so, Ginny can choose a multiset of vertices S several times and ask the professor: "If I put one token in each vertex of the given graph for each occurrence of the vertex in the multiset S, and then one more in the selected vertex, what would be the result of the combinatorial game?". Having given the task, the professor left the room to give Ginny some time to prepare for the game. Ginny thinks that she's being tricked because the problem is impossible to solve. Therefore, while the professor is away, she wants to add or remove several edges from the graph. Even though the original graph was acyclic, edges could be added to the graph to make cycles appear. Interaction In this task, interaction consists of several phases. In the first phase, the interactor gives as an input to your program three integers N (1 ≀ N ≀ 1000), M (0 ≀ M ≀ 100 000), T (1 ≀ T ≀ 2000): the number of vertices and edges in the initial graph, and the number of times Ginny has to guess the chosen vertex. The next M lines contain pairs of vertices a_i b_i (1 ≀ a_i, b_i ≀ N): beginning and end of corresponding graph edges. The graph is guaranteed to be acyclic and all of its edges to be distinct. The solution should print an integer K (0 ≀ K ≀ 4242): the number of edges to change in the graph. The next K lines should contain either "+ a_i b_i" or "- a_i b_i": the beginning and the end of an edge that Ginny has to add or remove accordingly. You are allowed to add preexisting edges to the graph. Operations are performed in the order of appearance, so Ginny is allowed to remove an edge added by the solution. You can only remove an existing edge. The operations can create cycles in the graph. The next T phases are dedicated to guessing the chosen vertices. In each phase, the solution can make at most 20 queries and then print the answer. To query a multiset S, the solution should print "? |S|~S_1~S_2~...~S_{|S|}". The total size of all multisets in a single phase should not exceed 20. The interactor will reply with one of the following words: * "Win", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the first player. * "Lose", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the second player. * "Draw", if a combinatorial game with tokens in multiset S and selected vertex ends in a draw. * "Slow", if the solution made a 21-st request, or the total size of all multisets in a single phase exceeded 20. In this case, the solution should terminate and receive Wrong Answer verdict. As soon as the selected vertex is guessed, that solution should print "! v". If the chosen vertex is guessed correctly, the interactor will print Correct and the solution should either move on to the next phase of guessing or finish its execution if it's the last phase. Otherwise, the interactor will print Wrong, which means that the solution should terminate and will receive the Wrong Answer verdict. The interactor can change the chosen vertex based on graph changes and solution actions, but at every given moment of time, at least one vertex that corresponds to all given interactor answers will exist. Hack format Hacks have the following extra limitations: * T = 1 * you need to specify a single vertex, chosen by the interactor. Hack test format. The first line of input contains three integers N~M~1. The next M lines on input contain edge description in the same format as in the input. The next line contains a single integer v: the number of the chosen vertex. The hack will be successful even if the solution guesses the vertex right, but the vertex will not be the single one to match all performed queries. Example Input 3 2 3 1 2 2 3 Lose Correct Win Correct Draw Correct Output 6 + 2 2 - 1 2 + 2 3 - 2 2 + 3 1 + 2 2 ? 0 ! 1 ? 1 2 ! 3 ? 5 1 3 1 3 1 ! 2 Note In the sample test, the empty lines represent waiting for the input by the other side of the interaction. The real interactor will not print empty lines, and the solution should not print them either. <image> The image above illustrates the sample test. Added edges are coloured in red, and the removed edges are drawn with a dotted line. Three guessing phases denote different ways of getting the answer. * If the solution will query just the chosen vertex, the interactor will return the result of the game in that vertex. The first player loses only if the chosen vertex has the number 1. * If we add a single vertex 2 to the chosen vertex, then if the chosen vertex is either 1 or 2, the game should end in a draw. If vertex number 3 is chosen, then the first player wins. * If we place three tokens in vertex 1 and two tokens in vertex 3, then the game will end in a draw only if vertex 2 is chosen. If the professor chose vertex 3, the first player will win, if the professor chose vertex 1, then the second player will win. In the first test, the interactor will behave as if the chosen vertices are the same as those in the example above. However, if you will try to guess the answer before it limits the options to one single vertex, the solution will get "Wrong Answer", even if you print the same answers. That's because the interactor is allowed to change the chosen vertex if it's consistent with the previous query answers.
2
12
#include <bits/stdc++.h> #pragma GCC optimize("Ofast", "unroll-loops", "omit-frame-pointer", "inline") #pragma GCC option("arch=native", "tune=native", "no-zero-upper") #pragma GCC target("avx2") using namespace std; template <typename T> void maxtt(T& t1, T t2) { t1 = max(t1, t2); } template <typename T> void mintt(T& t1, T t2) { t1 = min(t1, t2); } bool debug = 0; int n, m, k; int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0}; string direc = "RDLU"; const long long MOD2 = (long long)998244353 * (long long)998244353; long long ln, lk, lm; void etp(bool f = 0) { puts(f ? "YES" : "NO"); exit(0); } void addmod(int& x, int y, int mod = 998244353) { x += y; if (x >= mod) x -= mod; if (x < 0) x += mod; assert(x >= 0 && x < mod); } void et(int x = -1) { printf("%d\n", x); exit(0); } long long fastPow(long long x, long long y, int mod = 998244353) { long long ans = 1; while (y > 0) { if (y & 1) ans = (x * ans) % mod; x = x * x % mod; y >>= 1; } return ans; } long long gcd1(long long x, long long y) { return y ? gcd1(y, x % y) : x; } int T, B = 20, in[(1135)], id[(1135)], nid[(1135)]; int val[(1 << 20) + 5], valToX[(1 << 20) + 5]; vector<int> mp[(1135)]; void init() { vector<tuple<char, int, int>> es; vector<int> vp; queue<int> q; for (int(i) = 1; (i) <= (int)(n); (i)++) if (in[i] == 0) q.push(i); while (!q.empty()) { int x = q.front(); q.pop(); vp.push_back(x); for (int c : mp[x]) { in[c]--; if (in[c] == 0) q.push(c); } } for (int(i) = 1; (i) <= (int)(n); (i)++) nid[i] = -1; for (int(j) = 0; (j) < (int)(B); (j)++) { nid[vp[n - 1 - j]] = j; id[j] = vp[n - 1 - j]; } vector<vector<bool>> vis(B + 1, vector<bool>(B + 1, 0)); for (int(i) = 1; (i) <= (int)(B - 1); (i)++) { int x = id[i]; for (int c : mp[x]) if (nid[c] != -1 && nid[c] < i) { vis[i][nid[c]] = 1; } for (int j = 0; j < i; j++) if (!vis[i][j]) { es.push_back({'+', x, id[j]}); } } for (int(i) = 1; (i) <= (int)(n); (i)++) if (nid[i] == -1) { es.push_back({'+', i, i}); } vector<int> msk[4]; for (int(i) = 0; (i) < (int)(1 << B); (i)++) { int cc = __builtin_popcount(i); if (cc <= 3) msk[cc].push_back(i); } for (int(i) = 1; (i) <= (int)(n); (i)++) if (nid[i] == -1) { for (int c : mp[i]) if (nid[c] != -1) { val[i] |= 1 << nid[c]; } if (valToX[val[i]] == 0) { valToX[val[i]] = i; } } auto cg = [&](int i) { for (int(z) = 1; (z) <= (int)(3); (z)++) for (int M : msk[z]) { int nm = val[i] ^ M; if (valToX[nm] == 0) { valToX[nm] = i; for (int(j) = 0; (j) < (int)(B); (j)++) if (M & (1 << j)) { int pre = (val[i] >> j) & 1; if (pre == 0) { es.push_back({'+', i, id[j]}); } else es.push_back({'-', i, id[j]}); } val[i] ^= M; return; } } }; for (int(i) = 1; (i) <= (int)(n); (i)++) if (nid[i] == -1 && valToX[val[i]] != i) { cg(i); } printf("%d\n", (int)es.size()); for (auto [x, y, z] : es) printf("%c %d %d\n", x, y, z); fflush(stdout); } char rd(int x) { printf("? 1 %d\n", x); fflush(stdout); char ope[10]; scanf("%s", ope); return ope[0]; } void fmain(int tid) { scanf("%d%d%d", &n, &m, &T); mintt(B, n); for (int(i) = 1; (i) <= (int)(m); (i)++) { int u, v; scanf("%d%d", &u, &v); mp[u].push_back(v); in[v]++; } init(); for (int(i) = 1; (i) <= (int)(T); (i)++) { int ans = -1; int M = 0; for (int(j) = 0; (j) < (int)(B); (j)++) { char X = rd(id[j]); if (X == 'L') { ans = id[j]; break; } else if (X == 'W') M |= 1 << j; } if (ans == -1) ans = valToX[M]; printf("! %d\n", ans); fflush(stdout); char ope[20]; scanf("%s", ope); if (ope[0] == 'W') exit(0); } } int main() { int t = 1; for (int(i) = 1; (i) <= (int)(t); (i)++) { fmain(i); } return 0; }
CPP
1442_F. Differentiating Games
This is an interactive problem Ginny is taking an exam on game theory. The professor is tired of hearing the same answers over and over again, so he offered Ginny to play a game instead of a standard exam. As known from the course, a combinatorial game on a graph with multiple starting positions is a game with a directed graph and multiple starting vertices holding a token each. Two players take turns moving one of the tokens along the graph edges on each turn. The player who can't make a move loses the game. If both players can play an infinitely long game without losing, a draw is called. For the exam, the professor drew an acyclic directed graph and chose one of its vertices. Ginny needs to guess the vertex the professor chose. To do so, Ginny can choose a multiset of vertices S several times and ask the professor: "If I put one token in each vertex of the given graph for each occurrence of the vertex in the multiset S, and then one more in the selected vertex, what would be the result of the combinatorial game?". Having given the task, the professor left the room to give Ginny some time to prepare for the game. Ginny thinks that she's being tricked because the problem is impossible to solve. Therefore, while the professor is away, she wants to add or remove several edges from the graph. Even though the original graph was acyclic, edges could be added to the graph to make cycles appear. Interaction In this task, interaction consists of several phases. In the first phase, the interactor gives as an input to your program three integers N (1 ≀ N ≀ 1000), M (0 ≀ M ≀ 100 000), T (1 ≀ T ≀ 2000): the number of vertices and edges in the initial graph, and the number of times Ginny has to guess the chosen vertex. The next M lines contain pairs of vertices a_i b_i (1 ≀ a_i, b_i ≀ N): beginning and end of corresponding graph edges. The graph is guaranteed to be acyclic and all of its edges to be distinct. The solution should print an integer K (0 ≀ K ≀ 4242): the number of edges to change in the graph. The next K lines should contain either "+ a_i b_i" or "- a_i b_i": the beginning and the end of an edge that Ginny has to add or remove accordingly. You are allowed to add preexisting edges to the graph. Operations are performed in the order of appearance, so Ginny is allowed to remove an edge added by the solution. You can only remove an existing edge. The operations can create cycles in the graph. The next T phases are dedicated to guessing the chosen vertices. In each phase, the solution can make at most 20 queries and then print the answer. To query a multiset S, the solution should print "? |S|~S_1~S_2~...~S_{|S|}". The total size of all multisets in a single phase should not exceed 20. The interactor will reply with one of the following words: * "Win", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the first player. * "Lose", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the second player. * "Draw", if a combinatorial game with tokens in multiset S and selected vertex ends in a draw. * "Slow", if the solution made a 21-st request, or the total size of all multisets in a single phase exceeded 20. In this case, the solution should terminate and receive Wrong Answer verdict. As soon as the selected vertex is guessed, that solution should print "! v". If the chosen vertex is guessed correctly, the interactor will print Correct and the solution should either move on to the next phase of guessing or finish its execution if it's the last phase. Otherwise, the interactor will print Wrong, which means that the solution should terminate and will receive the Wrong Answer verdict. The interactor can change the chosen vertex based on graph changes and solution actions, but at every given moment of time, at least one vertex that corresponds to all given interactor answers will exist. Hack format Hacks have the following extra limitations: * T = 1 * you need to specify a single vertex, chosen by the interactor. Hack test format. The first line of input contains three integers N~M~1. The next M lines on input contain edge description in the same format as in the input. The next line contains a single integer v: the number of the chosen vertex. The hack will be successful even if the solution guesses the vertex right, but the vertex will not be the single one to match all performed queries. Example Input 3 2 3 1 2 2 3 Lose Correct Win Correct Draw Correct Output 6 + 2 2 - 1 2 + 2 3 - 2 2 + 3 1 + 2 2 ? 0 ! 1 ? 1 2 ! 3 ? 5 1 3 1 3 1 ! 2 Note In the sample test, the empty lines represent waiting for the input by the other side of the interaction. The real interactor will not print empty lines, and the solution should not print them either. <image> The image above illustrates the sample test. Added edges are coloured in red, and the removed edges are drawn with a dotted line. Three guessing phases denote different ways of getting the answer. * If the solution will query just the chosen vertex, the interactor will return the result of the game in that vertex. The first player loses only if the chosen vertex has the number 1. * If we add a single vertex 2 to the chosen vertex, then if the chosen vertex is either 1 or 2, the game should end in a draw. If vertex number 3 is chosen, then the first player wins. * If we place three tokens in vertex 1 and two tokens in vertex 3, then the game will end in a draw only if vertex 2 is chosen. If the professor chose vertex 3, the first player will win, if the professor chose vertex 1, then the second player will win. In the first test, the interactor will behave as if the chosen vertices are the same as those in the example above. However, if you will try to guess the answer before it limits the options to one single vertex, the solution will get "Wrong Answer", even if you print the same answers. That's because the interactor is allowed to change the chosen vertex if it's consistent with the previous query answers.
2
12
import java.io.*; import java.math.*; import java.util.*; import java.util.stream.*; public class E { boolean[] vis; ArrayList<Integer> order; int[][] g; void dfs(int v) { vis[v] = true; for (int u : g[v]) { if (!vis[u]) { dfs(u); } } order.add(v); } static final int K = 20; void submit() { int n = nextInt(); int m = nextInt(); int t = nextInt(); // int n = 1000; // int m = 0; // int t = 0; int[] es = new int[2 * m]; for (int i = 0; i < 2 * m; i++) { es[i] = nextInt() - 1; } g = buildDGraph(es, n, m); vis = new boolean[n]; order = new ArrayList<>(); for (int i = 0; i < n; i++) { if (!vis[i]) { dfs(i); } } ArrayList<Integer> head = new ArrayList<>(); ArrayList<Integer> ans = new ArrayList<>(); int[] who = new int[n]; Arrays.fill(who, -1); for (int i = 0; i < n && i < K; i++) { int v = order.get(i); // if (m == 100000) { // out.print(";" + v); // } head.add(v); who[v] = i; ArrayList<Integer> after = new ArrayList<>(); for (int j = 0; j < i; j++) { after.add(order.get(j)); } for (int u : g[v]) { after.remove(Integer.valueOf(u)); } for (int u : after) { ans.add(v); ans.add(u); } } // if (m == 100000) { // out.println(); // out.flush(); // } ArrayList<Integer> rest = new ArrayList<>(); for (int i = K; i < n; i++) { rest.add(order.get(i)); } Collections.shuffle(rest); int[] memo = new int[1 << K]; Arrays.fill(memo, -1); ArrayList<Integer> randHead = new ArrayList<>(head); for (int v : rest) { ans.add(v); ans.add(v); int curMask = 0; for (int u : g[v]) { if (who[u] != -1) { curMask |= 1 << who[u]; } } Collections.shuffle(randHead); for (int u : randHead) { if (memo[curMask] == -1) { break; } // if (m == 100000 && v == 0) { // out.print(test(curMask, who[u]) ? ~u : u + ";"); // } ans.add(v); ans.add(test(curMask, who[u]) ? ~u : u); curMask ^= 1 << who[u]; } if (memo[curMask] != -1) { throw new AssertionError("couldn't make all nodes different"); } memo[curMask] = v; } // if (m == 100000) { // out.println("!" + Arrays.toString(g[0]).replaceAll(" ", "")); // out.println("!"); // out.flush(); // } // System.err.println(ans.size() / 2); if (ans.size() > 2 * 4242) { throw new AssertionError("too many edges added"); } out.println(ans.size() / 2); for (int i = 0; i < ans.size(); i += 2) { int v = ans.get(i); int u = ans.get(i + 1); if (u >= 0) { out.println("+ " + (v + 1) + " " + (u + 1)); } else { out.println("- " + (v + 1) + " " + ((~u) + 1)); } } out.flush(); while (t-- > 0) { int[] resp = new int[Math.min(n, K)]; for (int i = 0; i < resp.length; i++) { out.println("? 1 " + (head.get(i) + 1)); out.flush(); resp[i] = decode(nextToken()); } int winMask = 0; boolean fuck = false; for (int i = 0; i < resp.length; i++) { if (resp[i] == -1) { out.println("! " + (head.get(i) + 1)); out.flush(); fuck = true; break; } if (resp[i] == 1) { winMask |= 1 << i; } } if (!fuck) { if (memo[winMask] == -1) { throw new AssertionError("no answer for winMask"); } out.println("! " + (memo[winMask] + 1)); out.flush(); } nextToken(); } } static boolean test(int mask, int i) { return ((mask >> i) & 1) == 1; } int decode(String response) { switch (response) { case "Lose": return -1; case "Draw": return 0; case "Win": return 1; default: throw new AssertionError("unknown response"); } } int[][] buildDGraph(int[] a, int n, int m) { if (m == 0) { if (a.length == 0) { return new int[n][0]; } else { throw new AssertionError(); } } if (a.length % m != 0 || a.length < 2 * m) { throw new AssertionError("Bad array length"); } int[] deg = new int[n]; int s = a.length / m; for (int i = 0; i < a.length; i += s) { deg[a[i]]++; } int[][] g = new int[n][]; for (int i = 0; i < n; i++) { g[i] = new int[deg[i] * (s - 1)]; } for (int i = s * (m - 1); i >= 0; i -= s) { int v = a[i]; int u = a[i + 1]; int pv = (--deg[v]) * (s - 1); g[v][pv] = u; System.arraycopy(a, i + 2, g[v], pv + 1, s - 2); } return g; } void test() { } void stress() { for (int tst = 0;; tst++) { submit(); System.err.println(tst); } } E() throws IOException { is = System.in; out = new PrintWriter(System.out); submit(); // stress(); // test(); out.close(); } static final Random rng = new Random(); static final int C = 5; static int rand(int l, int r) { return l + rng.nextInt(r - l + 1); } public static void main(String[] args) throws IOException { new E(); } private InputStream is; PrintWriter out; private byte[] buf = new byte[1 << 14]; private int bufSz = 0, bufPtr = 0; private int readByte() { if (bufSz == -1) throw new RuntimeException("Reading past EOF"); if (bufPtr >= bufSz) { bufPtr = 0; try { bufSz = is.read(buf); } catch (IOException e) { throw new RuntimeException(e); } if (bufSz <= 0) return -1; } return buf[bufPtr++]; } private boolean isTrash(int c) { return c < 33 || c > 126; } private int skip() { int b; while ((b = readByte()) != -1 && isTrash(b)) ; return b; } String nextToken() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!isTrash(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } String nextString() { int b = readByte(); StringBuilder sb = new StringBuilder(); while (!isTrash(b) || b == ' ') { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } double nextDouble() { return Double.parseDouble(nextToken()); } char nextChar() { return (char) skip(); } int nextInt() { int ret = 0; int b = skip(); if (b != '-' && (b < '0' || b > '9')) { throw new InputMismatchException(); } boolean neg = false; if (b == '-') { neg = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { ret = ret * 10 + (b - '0'); } else { if (b != -1 && !isTrash(b)) { throw new InputMismatchException(); } return neg ? -ret : ret; } b = readByte(); } } long nextLong() { long ret = 0; int b = skip(); if (b != '-' && (b < '0' || b > '9')) { throw new InputMismatchException(); } boolean neg = false; if (b == '-') { neg = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { ret = ret * 10 + (b - '0'); } else { if (b != -1 && !isTrash(b)) { throw new InputMismatchException(); } return neg ? -ret : ret; } b = readByte(); } } }
JAVA
1442_F. Differentiating Games
This is an interactive problem Ginny is taking an exam on game theory. The professor is tired of hearing the same answers over and over again, so he offered Ginny to play a game instead of a standard exam. As known from the course, a combinatorial game on a graph with multiple starting positions is a game with a directed graph and multiple starting vertices holding a token each. Two players take turns moving one of the tokens along the graph edges on each turn. The player who can't make a move loses the game. If both players can play an infinitely long game without losing, a draw is called. For the exam, the professor drew an acyclic directed graph and chose one of its vertices. Ginny needs to guess the vertex the professor chose. To do so, Ginny can choose a multiset of vertices S several times and ask the professor: "If I put one token in each vertex of the given graph for each occurrence of the vertex in the multiset S, and then one more in the selected vertex, what would be the result of the combinatorial game?". Having given the task, the professor left the room to give Ginny some time to prepare for the game. Ginny thinks that she's being tricked because the problem is impossible to solve. Therefore, while the professor is away, she wants to add or remove several edges from the graph. Even though the original graph was acyclic, edges could be added to the graph to make cycles appear. Interaction In this task, interaction consists of several phases. In the first phase, the interactor gives as an input to your program three integers N (1 ≀ N ≀ 1000), M (0 ≀ M ≀ 100 000), T (1 ≀ T ≀ 2000): the number of vertices and edges in the initial graph, and the number of times Ginny has to guess the chosen vertex. The next M lines contain pairs of vertices a_i b_i (1 ≀ a_i, b_i ≀ N): beginning and end of corresponding graph edges. The graph is guaranteed to be acyclic and all of its edges to be distinct. The solution should print an integer K (0 ≀ K ≀ 4242): the number of edges to change in the graph. The next K lines should contain either "+ a_i b_i" or "- a_i b_i": the beginning and the end of an edge that Ginny has to add or remove accordingly. You are allowed to add preexisting edges to the graph. Operations are performed in the order of appearance, so Ginny is allowed to remove an edge added by the solution. You can only remove an existing edge. The operations can create cycles in the graph. The next T phases are dedicated to guessing the chosen vertices. In each phase, the solution can make at most 20 queries and then print the answer. To query a multiset S, the solution should print "? |S|~S_1~S_2~...~S_{|S|}". The total size of all multisets in a single phase should not exceed 20. The interactor will reply with one of the following words: * "Win", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the first player. * "Lose", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the second player. * "Draw", if a combinatorial game with tokens in multiset S and selected vertex ends in a draw. * "Slow", if the solution made a 21-st request, or the total size of all multisets in a single phase exceeded 20. In this case, the solution should terminate and receive Wrong Answer verdict. As soon as the selected vertex is guessed, that solution should print "! v". If the chosen vertex is guessed correctly, the interactor will print Correct and the solution should either move on to the next phase of guessing or finish its execution if it's the last phase. Otherwise, the interactor will print Wrong, which means that the solution should terminate and will receive the Wrong Answer verdict. The interactor can change the chosen vertex based on graph changes and solution actions, but at every given moment of time, at least one vertex that corresponds to all given interactor answers will exist. Hack format Hacks have the following extra limitations: * T = 1 * you need to specify a single vertex, chosen by the interactor. Hack test format. The first line of input contains three integers N~M~1. The next M lines on input contain edge description in the same format as in the input. The next line contains a single integer v: the number of the chosen vertex. The hack will be successful even if the solution guesses the vertex right, but the vertex will not be the single one to match all performed queries. Example Input 3 2 3 1 2 2 3 Lose Correct Win Correct Draw Correct Output 6 + 2 2 - 1 2 + 2 3 - 2 2 + 3 1 + 2 2 ? 0 ! 1 ? 1 2 ! 3 ? 5 1 3 1 3 1 ! 2 Note In the sample test, the empty lines represent waiting for the input by the other side of the interaction. The real interactor will not print empty lines, and the solution should not print them either. <image> The image above illustrates the sample test. Added edges are coloured in red, and the removed edges are drawn with a dotted line. Three guessing phases denote different ways of getting the answer. * If the solution will query just the chosen vertex, the interactor will return the result of the game in that vertex. The first player loses only if the chosen vertex has the number 1. * If we add a single vertex 2 to the chosen vertex, then if the chosen vertex is either 1 or 2, the game should end in a draw. If vertex number 3 is chosen, then the first player wins. * If we place three tokens in vertex 1 and two tokens in vertex 3, then the game will end in a draw only if vertex 2 is chosen. If the professor chose vertex 3, the first player will win, if the professor chose vertex 1, then the second player will win. In the first test, the interactor will behave as if the chosen vertices are the same as those in the example above. However, if you will try to guess the answer before it limits the options to one single vertex, the solution will get "Wrong Answer", even if you print the same answers. That's because the interactor is allowed to change the chosen vertex if it's consistent with the previous query answers.
2
12
#include <bits/stdc++.h> using namespace std; void dfs(int v, vector<int> &col, vector<int> &ts, vector<vector<int> > &g) { col[v] = 1; for (auto u : g[v]) if (col[u] == 0) { dfs(u, col, ts, g); } ts.push_back(v); } int main() { ios_base::sync_with_stdio(false); cin.tie(0); int n, m, t; cin >> n >> m >> t; vector<vector<int> > g(n); vector<int> in(n); vector<vector<int> > con(n, vector<int>(n)); for (int(i) = 0; (i) != (m); (i)++) { int a, b; cin >> a >> b; a--, b--; g[a].push_back(b); con[a][b] = 1; in[b]++; } vector<int> ts, col(n); for (int(i) = 0; (i) != (n); (i)++) { if (in[i] == 0 && !col[i]) { dfs(i, col, ts, g); } } struct edit { char c; int fr, to; }; vector<edit> edits; int b = min(n, 20); for (int i = 0; i < b; i++) { for (int j = i + 1; j < b; j++) { int fr = ts[j], to = ts[i]; if (!con[fr][to]) { con[fr][to] = 1; edits.push_back({'+', fr + 1, to + 1}); } } } for (int i = b; i < n; i++) { int v = ts[i]; edits.push_back({'+', v + 1, v + 1}); } vector<int> have(1 << b, -1); for (int i = b; i < n; i++) { int v = ts[i]; int mask = 0; for (int j = 0; j < b; j++) { if (con[v][ts[j]]) mask += (1 << j); } int t = 0; for (int edit = 0; !t && edit <= b; edit++) { vector<int> e(b); for (int j = b - 1; j >= b - edit; j--) e[j] = 1; while (!t) { int mask2 = mask; for (int j = 0; j < b; j++) { if (e[j]) mask2 ^= (1 << j); } if (have[mask2] == -1) { t = 1; have[mask2] = v; for (int j = 0; j < b; j++) { if (e[j] && (mask & (1 << j))) { edits.push_back({'-', v + 1, ts[j] + 1}); con[v][ts[j]] = 0; } if (e[j] && !(mask & (1 << j))) { edits.push_back({'+', v + 1, ts[j] + 1}); con[v][ts[j]] = 1; } } } if (!next_permutation(e.begin(), e.end())) break; } } } cout << edits.size() << "\n"; for (auto e : edits) { cout << e.c << " " << e.fr << " " << e.to << "\n"; } cout << endl; while (t--) { vector<string> res(b); for (int j = 0; j < b; j++) { cout << "? 1 " << ts[j] + 1 << "\n"; } cout << endl; int mask = 0, fail = -1; for (int j = 0; j < b; j++) { cin >> res[j]; if (res[j] == "Lose") { assert(fail == -1); fail = ts[j]; } else { if (res[j] == "Win") { mask += (1 << j); } } } if (fail != -1) { cout << "! " << fail + 1 << endl; string s; cin >> s; continue; } cout << "! " << have[mask] + 1 << endl; string s; cin >> s; } }
CPP
1442_F. Differentiating Games
This is an interactive problem Ginny is taking an exam on game theory. The professor is tired of hearing the same answers over and over again, so he offered Ginny to play a game instead of a standard exam. As known from the course, a combinatorial game on a graph with multiple starting positions is a game with a directed graph and multiple starting vertices holding a token each. Two players take turns moving one of the tokens along the graph edges on each turn. The player who can't make a move loses the game. If both players can play an infinitely long game without losing, a draw is called. For the exam, the professor drew an acyclic directed graph and chose one of its vertices. Ginny needs to guess the vertex the professor chose. To do so, Ginny can choose a multiset of vertices S several times and ask the professor: "If I put one token in each vertex of the given graph for each occurrence of the vertex in the multiset S, and then one more in the selected vertex, what would be the result of the combinatorial game?". Having given the task, the professor left the room to give Ginny some time to prepare for the game. Ginny thinks that she's being tricked because the problem is impossible to solve. Therefore, while the professor is away, she wants to add or remove several edges from the graph. Even though the original graph was acyclic, edges could be added to the graph to make cycles appear. Interaction In this task, interaction consists of several phases. In the first phase, the interactor gives as an input to your program three integers N (1 ≀ N ≀ 1000), M (0 ≀ M ≀ 100 000), T (1 ≀ T ≀ 2000): the number of vertices and edges in the initial graph, and the number of times Ginny has to guess the chosen vertex. The next M lines contain pairs of vertices a_i b_i (1 ≀ a_i, b_i ≀ N): beginning and end of corresponding graph edges. The graph is guaranteed to be acyclic and all of its edges to be distinct. The solution should print an integer K (0 ≀ K ≀ 4242): the number of edges to change in the graph. The next K lines should contain either "+ a_i b_i" or "- a_i b_i": the beginning and the end of an edge that Ginny has to add or remove accordingly. You are allowed to add preexisting edges to the graph. Operations are performed in the order of appearance, so Ginny is allowed to remove an edge added by the solution. You can only remove an existing edge. The operations can create cycles in the graph. The next T phases are dedicated to guessing the chosen vertices. In each phase, the solution can make at most 20 queries and then print the answer. To query a multiset S, the solution should print "? |S|~S_1~S_2~...~S_{|S|}". The total size of all multisets in a single phase should not exceed 20. The interactor will reply with one of the following words: * "Win", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the first player. * "Lose", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the second player. * "Draw", if a combinatorial game with tokens in multiset S and selected vertex ends in a draw. * "Slow", if the solution made a 21-st request, or the total size of all multisets in a single phase exceeded 20. In this case, the solution should terminate and receive Wrong Answer verdict. As soon as the selected vertex is guessed, that solution should print "! v". If the chosen vertex is guessed correctly, the interactor will print Correct and the solution should either move on to the next phase of guessing or finish its execution if it's the last phase. Otherwise, the interactor will print Wrong, which means that the solution should terminate and will receive the Wrong Answer verdict. The interactor can change the chosen vertex based on graph changes and solution actions, but at every given moment of time, at least one vertex that corresponds to all given interactor answers will exist. Hack format Hacks have the following extra limitations: * T = 1 * you need to specify a single vertex, chosen by the interactor. Hack test format. The first line of input contains three integers N~M~1. The next M lines on input contain edge description in the same format as in the input. The next line contains a single integer v: the number of the chosen vertex. The hack will be successful even if the solution guesses the vertex right, but the vertex will not be the single one to match all performed queries. Example Input 3 2 3 1 2 2 3 Lose Correct Win Correct Draw Correct Output 6 + 2 2 - 1 2 + 2 3 - 2 2 + 3 1 + 2 2 ? 0 ! 1 ? 1 2 ! 3 ? 5 1 3 1 3 1 ! 2 Note In the sample test, the empty lines represent waiting for the input by the other side of the interaction. The real interactor will not print empty lines, and the solution should not print them either. <image> The image above illustrates the sample test. Added edges are coloured in red, and the removed edges are drawn with a dotted line. Three guessing phases denote different ways of getting the answer. * If the solution will query just the chosen vertex, the interactor will return the result of the game in that vertex. The first player loses only if the chosen vertex has the number 1. * If we add a single vertex 2 to the chosen vertex, then if the chosen vertex is either 1 or 2, the game should end in a draw. If vertex number 3 is chosen, then the first player wins. * If we place three tokens in vertex 1 and two tokens in vertex 3, then the game will end in a draw only if vertex 2 is chosen. If the professor chose vertex 3, the first player will win, if the professor chose vertex 1, then the second player will win. In the first test, the interactor will behave as if the chosen vertices are the same as those in the example above. However, if you will try to guess the answer before it limits the options to one single vertex, the solution will get "Wrong Answer", even if you print the same answers. That's because the interactor is allowed to change the chosen vertex if it's consistent with the previous query answers.
2
12
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.*; public class E { static final int K = 20; static final Random rng = new Random(); static final int C = 5; boolean[] vis; ArrayList<Integer> order; int[][] g; PrintWriter out; private InputStream is; private final byte[] buf = new byte[1 << 14]; private int bufSz = 0, bufPtr = 0; E() throws IOException { is = System.in; out = new PrintWriter(System.out); submit(); out.close(); } static boolean test(int mask, int i) { return ((mask >> i) & 1) == 1; } static int rand(int l, int r) { return l + rng.nextInt(r - l + 1); } public static void main(String[] args) throws IOException { new E(); } void dfs(int v) { vis[v] = true; for (int u : g[v]) { if (!vis[u]) { dfs(u); } } order.add(v); } void submit() { int n = nextInt(); int m = nextInt(); int t = nextInt(); int[] es = new int[2 * m]; for (int i = 0; i < 2 * m; i++) { es[i] = nextInt() - 1; } g = buildDGraph(es, n, m); vis = new boolean[n]; order = new ArrayList<>(); for (int i = 0; i < n; i++) { if (!vis[i]) { dfs(i); } } ArrayList<Integer> head = new ArrayList<>(); ArrayList<Integer> ans = new ArrayList<>(); int[] who = new int[n]; Arrays.fill(who, -1); for (int i = 0; i < n && i < K; i++) { int v = order.get(i); head.add(v); who[v] = i; ArrayList<Integer> after = new ArrayList<>(); for (int j = 0; j < i; j++) { after.add(order.get(j)); } for (int u : g[v]) { after.remove(Integer.valueOf(u)); } for (int u : after) { ans.add(v); ans.add(u); } } ArrayList<Integer> rest = new ArrayList<>(); for (int i = K; i < n; i++) { rest.add(order.get(i)); } Collections.shuffle(rest); int[] memo = new int[1 << K]; Arrays.fill(memo, -1); ArrayList<Integer> randHead = new ArrayList<>(head); for (int v : rest) { ans.add(v); ans.add(v); int curMask = 0; for (int u : g[v]) { if (who[u] != -1) { curMask |= 1 << who[u]; } } Collections.shuffle(randHead); for (int u : randHead) { if (memo[curMask] == -1) { break; } ans.add(v); ans.add(test(curMask, who[u]) ? ~u : u); curMask ^= 1 << who[u]; } if (memo[curMask] != -1) { throw new AssertionError("couldn't make all nodes different"); } memo[curMask] = v; } if (ans.size() > 2 * 4242) { throw new AssertionError("too many edges added"); } out.println(ans.size() / 2); for (int i = 0; i < ans.size(); i += 2) { int v = ans.get(i); int u = ans.get(i + 1); if (u >= 0) { out.println("+ " + (v + 1) + " " + (u + 1)); } else { out.println("- " + (v + 1) + " " + ((~u) + 1)); } } out.flush(); while (t-- > 0) { int[] resp = new int[Math.min(n, K)]; for (int i = 0; i < resp.length; i++) { out.println("? 1 " + (head.get(i) + 1)); out.flush(); resp[i] = decode(nextToken()); } int winMask = 0; boolean fuck = false; for (int i = 0; i < resp.length; i++) { if (resp[i] == -1) { out.println("! " + (head.get(i) + 1)); out.flush(); fuck = true; break; } if (resp[i] == 1) { winMask |= 1 << i; } } if (!fuck) { if (memo[winMask] == -1) { throw new AssertionError("no answer for winMask"); } out.println("! " + (memo[winMask] + 1)); out.flush(); } nextToken(); } } int decode(String response) { switch (response) { case "Lose": return -1; case "Draw": return 0; case "Win": return 1; default: throw new AssertionError("unknown response"); } } int[][] buildDGraph(int[] a, int n, int m) { if (m == 0) { if (a.length == 0) { return new int[n][0]; } else { throw new AssertionError(); } } if (a.length % m != 0 || a.length < 2 * m) { throw new AssertionError("Bad array length"); } int[] deg = new int[n]; int s = a.length / m; for (int i = 0; i < a.length; i += s) { deg[a[i]]++; } int[][] g = new int[n][]; for (int i = 0; i < n; i++) { g[i] = new int[deg[i] * (s - 1)]; } for (int i = s * (m - 1); i >= 0; i -= s) { int v = a[i]; int u = a[i + 1]; int pv = (--deg[v]) * (s - 1); g[v][pv] = u; System.arraycopy(a, i + 2, g[v], pv + 1, s - 2); } return g; } void test() { } void stress() { for (int tst = 0; ; tst++) { submit(); System.err.println(tst); } } private int readByte() { if (bufSz == -1) throw new RuntimeException("Reading past EOF"); if (bufPtr >= bufSz) { bufPtr = 0; try { bufSz = is.read(buf); } catch (IOException e) { throw new RuntimeException(e); } if (bufSz <= 0) return -1; } return buf[bufPtr++]; } private boolean isTrash(int c) { return c < 33 || c > 126; } private int skip() { int b; while ((b = readByte()) != -1 && isTrash(b)) ; return b; } String nextToken() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!isTrash(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } String nextString() { int b = readByte(); StringBuilder sb = new StringBuilder(); while (!isTrash(b) || b == ' ') { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } double nextDouble() { return Double.parseDouble(nextToken()); } char nextChar() { return (char) skip(); } int nextInt() { int ret = 0; int b = skip(); if (b != '-' && (b < '0' || b > '9')) { throw new InputMismatchException(); } boolean neg = false; if (b == '-') { neg = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { ret = ret * 10 + (b - '0'); } else { if (b != -1 && !isTrash(b)) { throw new InputMismatchException(); } return neg ? -ret : ret; } b = readByte(); } } long nextLong() { long ret = 0; int b = skip(); if (b != '-' && (b < '0' || b > '9')) { throw new InputMismatchException(); } boolean neg = false; if (b == '-') { neg = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { ret = ret * 10 + (b - '0'); } else { if (b != -1 && !isTrash(b)) { throw new InputMismatchException(); } return neg ? -ret : ret; } b = readByte(); } } }
JAVA
1442_F. Differentiating Games
This is an interactive problem Ginny is taking an exam on game theory. The professor is tired of hearing the same answers over and over again, so he offered Ginny to play a game instead of a standard exam. As known from the course, a combinatorial game on a graph with multiple starting positions is a game with a directed graph and multiple starting vertices holding a token each. Two players take turns moving one of the tokens along the graph edges on each turn. The player who can't make a move loses the game. If both players can play an infinitely long game without losing, a draw is called. For the exam, the professor drew an acyclic directed graph and chose one of its vertices. Ginny needs to guess the vertex the professor chose. To do so, Ginny can choose a multiset of vertices S several times and ask the professor: "If I put one token in each vertex of the given graph for each occurrence of the vertex in the multiset S, and then one more in the selected vertex, what would be the result of the combinatorial game?". Having given the task, the professor left the room to give Ginny some time to prepare for the game. Ginny thinks that she's being tricked because the problem is impossible to solve. Therefore, while the professor is away, she wants to add or remove several edges from the graph. Even though the original graph was acyclic, edges could be added to the graph to make cycles appear. Interaction In this task, interaction consists of several phases. In the first phase, the interactor gives as an input to your program three integers N (1 ≀ N ≀ 1000), M (0 ≀ M ≀ 100 000), T (1 ≀ T ≀ 2000): the number of vertices and edges in the initial graph, and the number of times Ginny has to guess the chosen vertex. The next M lines contain pairs of vertices a_i b_i (1 ≀ a_i, b_i ≀ N): beginning and end of corresponding graph edges. The graph is guaranteed to be acyclic and all of its edges to be distinct. The solution should print an integer K (0 ≀ K ≀ 4242): the number of edges to change in the graph. The next K lines should contain either "+ a_i b_i" or "- a_i b_i": the beginning and the end of an edge that Ginny has to add or remove accordingly. You are allowed to add preexisting edges to the graph. Operations are performed in the order of appearance, so Ginny is allowed to remove an edge added by the solution. You can only remove an existing edge. The operations can create cycles in the graph. The next T phases are dedicated to guessing the chosen vertices. In each phase, the solution can make at most 20 queries and then print the answer. To query a multiset S, the solution should print "? |S|~S_1~S_2~...~S_{|S|}". The total size of all multisets in a single phase should not exceed 20. The interactor will reply with one of the following words: * "Win", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the first player. * "Lose", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the second player. * "Draw", if a combinatorial game with tokens in multiset S and selected vertex ends in a draw. * "Slow", if the solution made a 21-st request, or the total size of all multisets in a single phase exceeded 20. In this case, the solution should terminate and receive Wrong Answer verdict. As soon as the selected vertex is guessed, that solution should print "! v". If the chosen vertex is guessed correctly, the interactor will print Correct and the solution should either move on to the next phase of guessing or finish its execution if it's the last phase. Otherwise, the interactor will print Wrong, which means that the solution should terminate and will receive the Wrong Answer verdict. The interactor can change the chosen vertex based on graph changes and solution actions, but at every given moment of time, at least one vertex that corresponds to all given interactor answers will exist. Hack format Hacks have the following extra limitations: * T = 1 * you need to specify a single vertex, chosen by the interactor. Hack test format. The first line of input contains three integers N~M~1. The next M lines on input contain edge description in the same format as in the input. The next line contains a single integer v: the number of the chosen vertex. The hack will be successful even if the solution guesses the vertex right, but the vertex will not be the single one to match all performed queries. Example Input 3 2 3 1 2 2 3 Lose Correct Win Correct Draw Correct Output 6 + 2 2 - 1 2 + 2 3 - 2 2 + 3 1 + 2 2 ? 0 ! 1 ? 1 2 ! 3 ? 5 1 3 1 3 1 ! 2 Note In the sample test, the empty lines represent waiting for the input by the other side of the interaction. The real interactor will not print empty lines, and the solution should not print them either. <image> The image above illustrates the sample test. Added edges are coloured in red, and the removed edges are drawn with a dotted line. Three guessing phases denote different ways of getting the answer. * If the solution will query just the chosen vertex, the interactor will return the result of the game in that vertex. The first player loses only if the chosen vertex has the number 1. * If we add a single vertex 2 to the chosen vertex, then if the chosen vertex is either 1 or 2, the game should end in a draw. If vertex number 3 is chosen, then the first player wins. * If we place three tokens in vertex 1 and two tokens in vertex 3, then the game will end in a draw only if vertex 2 is chosen. If the professor chose vertex 3, the first player will win, if the professor chose vertex 1, then the second player will win. In the first test, the interactor will behave as if the chosen vertices are the same as those in the example above. However, if you will try to guess the answer before it limits the options to one single vertex, the solution will get "Wrong Answer", even if you print the same answers. That's because the interactor is allowed to change the chosen vertex if it's consistent with the previous query answers.
2
12
#include <bits/stdc++.h> using namespace std; const int MAXN = 1010; struct Modify { bool add; int a, b; }; int n, m, t; vector<int> x[MAXN]; map<int, int> h; vector<int> s; vector<Modify> ans; int losestate[1 << 20]; int winstate[1 << 20]; void BuildBase() { int out[MAXN]; vector<int> y[MAXN]; for (int i = 1; i <= n; ++i) { out[i] = x[i].size(); y[i].clear(); } for (int i = 1; i <= n; ++i) { for (int b : x[i]) y[b].push_back(i); } queue<int> q; for (int i = 1; i <= n; ++i) { if (out[i] == 0) { q.push(i); } } while (!q.empty() && s.size() < 20) { int a = q.front(); q.pop(); s.push_back(a); h[a] = s.size() - 1; for (int b : y[a]) { --out[b]; if (out[b] == 0) q.push(b); } } int z[20][20]; memset(z, 0, sizeof(z)); for (int i = 0; i < s.size(); ++i) { for (int b : x[s[i]]) z[i][h[b]] = true; } for (int i = 0; i < s.size(); ++i) { for (int j = 0; j < s.size(); ++j) { if (z[i][j] && i <= j) { ans.push_back({false, s[i], s[j]}); } if (!z[i][j] && i > j) { ans.push_back({true, s[i], s[j]}); } } } for (int i = 0; i < s.size(); ++i) { losestate[1 << i] = s[i]; } } void ModifyGraph() { bool sz[1 << 20]; memset(sz, 0, sizeof(sz)); sz[0] = true; for (int i = 1; i <= n; ++i) { if (h.find(i) != h.end()) continue; ans.push_back({true, i, i}); int state = 0; for (int b : x[i]) { if (h.find(b) == h.end()) continue; state |= (1 << h[b]); } if (!sz[state]) { sz[state] = true; winstate[state] = i; continue; } bool finished = false; for (int p = 0; p < 20; ++p) { int newst = state ^ (1 << p); if (sz[newst]) continue; finished = true; sz[newst] = true; winstate[newst] = i; if (state & (1 << p)) { ans.push_back({false, i, s[p]}); } else { ans.push_back({true, i, s[p]}); } if (finished) break; } if (finished) continue; for (int p = 0; p < 20; ++p) { for (int q = p + 1; q < 20; ++q) { int newst = state ^ (1 << p) ^ (1 << q); if (sz[newst]) continue; finished = true; sz[newst] = true; winstate[newst] = i; for (int o : {p, q}) { if (state & (1 << o)) { ans.push_back({false, i, s[o]}); } else { ans.push_back({true, i, s[o]}); } } if (finished) break; } if (finished) break; } if (finished) continue; for (int p = 0; p < 20; ++p) { for (int q = p + 1; q < 20; ++q) { for (int r = q + 1; r < 20; ++r) { int newst = state ^ (1 << p) ^ (1 << q) ^ (1 << r); if (sz[newst]) continue; finished = true; sz[newst] = true; winstate[newst] = i; for (int o : {p, q, r}) { if (state & (1 << o)) { ans.push_back({false, i, s[o]}); } else { ans.push_back({true, i, s[o]}); } } if (finished) break; } if (finished) break; } if (finished) break; } } } int main() { ios::sync_with_stdio(false); cin >> n >> m >> t; for (int i = 0; i < m; ++i) { int a, b; cin >> a >> b; x[a].push_back(b); } BuildBase(); ModifyGraph(); cout << ans.size() << endl; for (int i = 0; i < ans.size(); ++i) { if (ans[i].add) cout << "+ "; else cout << "- "; cout << ans[i].a << " " << ans[i].b << endl; } cout << flush; while (t--) { int win = 0, lose = 0, draw = 0; for (int i = 0; i < s.size(); ++i) { cout << "? 1 " << s[i] << endl << flush; string st; cin >> st; if (st == "Win") { win |= (1 << i); } else if (st == "Lose") { lose |= (1 << i); } else { draw |= (1 << i); } } int ans = 0; if (lose > 0) { ans = losestate[lose]; } else { ans = winstate[win]; } cout << "! " << ans << endl << flush; string st; cin >> st; if (st != "Correct") return 0; } return 0; }
CPP
1442_F. Differentiating Games
This is an interactive problem Ginny is taking an exam on game theory. The professor is tired of hearing the same answers over and over again, so he offered Ginny to play a game instead of a standard exam. As known from the course, a combinatorial game on a graph with multiple starting positions is a game with a directed graph and multiple starting vertices holding a token each. Two players take turns moving one of the tokens along the graph edges on each turn. The player who can't make a move loses the game. If both players can play an infinitely long game without losing, a draw is called. For the exam, the professor drew an acyclic directed graph and chose one of its vertices. Ginny needs to guess the vertex the professor chose. To do so, Ginny can choose a multiset of vertices S several times and ask the professor: "If I put one token in each vertex of the given graph for each occurrence of the vertex in the multiset S, and then one more in the selected vertex, what would be the result of the combinatorial game?". Having given the task, the professor left the room to give Ginny some time to prepare for the game. Ginny thinks that she's being tricked because the problem is impossible to solve. Therefore, while the professor is away, she wants to add or remove several edges from the graph. Even though the original graph was acyclic, edges could be added to the graph to make cycles appear. Interaction In this task, interaction consists of several phases. In the first phase, the interactor gives as an input to your program three integers N (1 ≀ N ≀ 1000), M (0 ≀ M ≀ 100 000), T (1 ≀ T ≀ 2000): the number of vertices and edges in the initial graph, and the number of times Ginny has to guess the chosen vertex. The next M lines contain pairs of vertices a_i b_i (1 ≀ a_i, b_i ≀ N): beginning and end of corresponding graph edges. The graph is guaranteed to be acyclic and all of its edges to be distinct. The solution should print an integer K (0 ≀ K ≀ 4242): the number of edges to change in the graph. The next K lines should contain either "+ a_i b_i" or "- a_i b_i": the beginning and the end of an edge that Ginny has to add or remove accordingly. You are allowed to add preexisting edges to the graph. Operations are performed in the order of appearance, so Ginny is allowed to remove an edge added by the solution. You can only remove an existing edge. The operations can create cycles in the graph. The next T phases are dedicated to guessing the chosen vertices. In each phase, the solution can make at most 20 queries and then print the answer. To query a multiset S, the solution should print "? |S|~S_1~S_2~...~S_{|S|}". The total size of all multisets in a single phase should not exceed 20. The interactor will reply with one of the following words: * "Win", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the first player. * "Lose", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the second player. * "Draw", if a combinatorial game with tokens in multiset S and selected vertex ends in a draw. * "Slow", if the solution made a 21-st request, or the total size of all multisets in a single phase exceeded 20. In this case, the solution should terminate and receive Wrong Answer verdict. As soon as the selected vertex is guessed, that solution should print "! v". If the chosen vertex is guessed correctly, the interactor will print Correct and the solution should either move on to the next phase of guessing or finish its execution if it's the last phase. Otherwise, the interactor will print Wrong, which means that the solution should terminate and will receive the Wrong Answer verdict. The interactor can change the chosen vertex based on graph changes and solution actions, but at every given moment of time, at least one vertex that corresponds to all given interactor answers will exist. Hack format Hacks have the following extra limitations: * T = 1 * you need to specify a single vertex, chosen by the interactor. Hack test format. The first line of input contains three integers N~M~1. The next M lines on input contain edge description in the same format as in the input. The next line contains a single integer v: the number of the chosen vertex. The hack will be successful even if the solution guesses the vertex right, but the vertex will not be the single one to match all performed queries. Example Input 3 2 3 1 2 2 3 Lose Correct Win Correct Draw Correct Output 6 + 2 2 - 1 2 + 2 3 - 2 2 + 3 1 + 2 2 ? 0 ! 1 ? 1 2 ! 3 ? 5 1 3 1 3 1 ! 2 Note In the sample test, the empty lines represent waiting for the input by the other side of the interaction. The real interactor will not print empty lines, and the solution should not print them either. <image> The image above illustrates the sample test. Added edges are coloured in red, and the removed edges are drawn with a dotted line. Three guessing phases denote different ways of getting the answer. * If the solution will query just the chosen vertex, the interactor will return the result of the game in that vertex. The first player loses only if the chosen vertex has the number 1. * If we add a single vertex 2 to the chosen vertex, then if the chosen vertex is either 1 or 2, the game should end in a draw. If vertex number 3 is chosen, then the first player wins. * If we place three tokens in vertex 1 and two tokens in vertex 3, then the game will end in a draw only if vertex 2 is chosen. If the professor chose vertex 3, the first player will win, if the professor chose vertex 1, then the second player will win. In the first test, the interactor will behave as if the chosen vertices are the same as those in the example above. However, if you will try to guess the answer before it limits the options to one single vertex, the solution will get "Wrong Answer", even if you print the same answers. That's because the interactor is allowed to change the chosen vertex if it's consistent with the previous query answers.
2
12
#include <bits/stdc++.h> using namespace std; void dfs(int v, vector<int> &col, vector<int> &ts, vector<vector<int> > &g) { col[v] = 1; for (auto u : g[v]) if (col[u] == 0) { dfs(u, col, ts, g); } ts.push_back(v); } int main() { ios_base::sync_with_stdio(false); cin.tie(0); int n, m, t; cin >> n >> m >> t; vector<vector<int> > g(n); vector<int> in(n); vector<vector<int> > con(n, vector<int>(n)); for (int(i) = 0; (i) != (m); (i)++) { int a, b; cin >> a >> b; a--, b--; g[a].push_back(b); con[a][b] = 1; in[b]++; } vector<int> ts, col(n); for (int(i) = 0; (i) != (n); (i)++) { if (in[i] == 0 && !col[i]) { dfs(i, col, ts, g); } } struct edit { char c; int fr, to; }; vector<edit> edits; int b = min(n, 16); for (int i = 0; i < b; i++) { for (int j = i + 1; j < b; j++) { int fr = ts[j], to = ts[i]; if (!con[fr][to]) { con[fr][to] = 1; edits.push_back({'+', fr + 1, to + 1}); } } } for (int i = b; i < n; i++) { int v = ts[i]; edits.push_back({'+', v + 1, v + 1}); } vector<int> have(1 << b, -1); for (int i = b; i < n; i++) { int v = ts[i]; int mask = 0; for (int j = 0; j < b; j++) { if (con[v][ts[j]]) mask += (1 << j); } int t = 0; for (int edit = 0; !t && edit <= b; edit++) { vector<int> e(b); for (int j = b - 1; j >= b - edit; j--) e[j] = 1; while (!t) { int mask2 = mask; for (int j = 0; j < b; j++) { if (e[j]) mask2 ^= (1 << j); } if (have[mask2] == -1) { t = 1; have[mask2] = v; for (int j = 0; j < b; j++) { if (e[j] && (mask & (1 << j))) { edits.push_back({'-', v + 1, ts[j] + 1}); con[v][ts[j]] = 0; } if (e[j] && !(mask & (1 << j))) { edits.push_back({'+', v + 1, ts[j] + 1}); con[v][ts[j]] = 1; } } } if (!next_permutation(e.begin(), e.end())) break; } } } cout << edits.size() << "\n"; for (auto e : edits) { cout << e.c << " " << e.fr << " " << e.to << "\n"; } cout << endl; while (t--) { vector<string> res(b); for (int j = 0; j < b; j++) { cout << "? 1 " << ts[j] + 1 << "\n"; } cout << endl; int mask = 0, fail = -1; for (int j = 0; j < b; j++) { cin >> res[j]; if (res[j] == "Lose") { assert(fail == -1); fail = ts[j]; } else { if (res[j] == "Win") { mask += (1 << j); } } } if (fail != -1) { cout << "! " << fail + 1 << endl; string s; cin >> s; continue; } cout << "! " << have[mask] + 1 << endl; string s; cin >> s; } }
CPP
1468_H. K and Medians
Let's denote the median of a sequence s with odd length as the value in the middle of s if we sort s in non-decreasing order. For example, let s = [1, 2, 5, 7, 2, 3, 12]. After sorting, we get sequence [1, 2, 2, \underline{3}, 5, 7, 12], and the median is equal to 3. You have a sequence of n integers [1, 2, ..., n] and an odd integer k. In one step, you choose any k elements from the sequence and erase all chosen elements except their median. These elements do not have to go continuously (gaps are allowed between them). For example, if you have a sequence [1, 2, 3, 4, 5, 6, 7] (i.e. n=7) and k = 3, then the following options for the first step are possible: * choose [1, \underline{2}, 3]; 2 is their median, so it is not erased, and the resulting sequence is [2, 4, 5, 6, 7]; * choose [2, \underline{4}, 6]; 4 is their median, so it is not erased, and the resulting sequence is [1, 3, 4, 5, 7]; * choose [1, \underline{6}, 7]; 6 is their median, so it is not erased, and the resulting sequence is [2, 3, 4, 5, 6]; * and several others. You can do zero or more steps. Can you get a sequence b_1, b_2, ..., b_m after several steps? You'll be given t test cases. Solve each test case independently. 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 three integers n, k, and m (3 ≀ n ≀ 2 β‹… 10^5; 3 ≀ k ≀ n; k is odd; 1 ≀ m < n) β€” the length of the sequence you have, the number of elements you choose in each step and the length of the sequence you'd like to get. The second line of each test case contains m integers b_1, b_2, ..., b_m (1 ≀ b_1 < b_2 < ... < b_m ≀ n) β€” the sequence you'd like to get, given in the ascending order. It's guaranteed that the total sum of n over all test cases doesn't exceed 2 β‹… 10^5. Output For each test case, print YES if you can obtain the sequence b or NO otherwise. You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer). Example Input 4 3 3 1 1 7 3 3 1 5 7 10 5 3 4 5 6 13 7 7 1 3 5 7 9 11 12 Output NO YES NO YES Note In the first test case, you have sequence [1, 2, 3]. Since k = 3 you have only one way to choose k elements β€” it's to choose all elements [1, \underline{2}, 3] with median 2. That's why after erasing all chosen elements except its median you'll get sequence [2]. In other words, there is no way to get sequence b = [1] as the result. In the second test case, you have sequence [1, 2, 3, 4, 5, 6, 7] and one of the optimal strategies is following: 1. choose k = 3 elements [2, \underline{3}, 4] and erase them except its median; you'll get sequence [1, 3, 5, 6, 7]; 2. choose 3 elements [3, \underline{5}, 6] and erase them except its median; you'll get desired sequence [1, 5, 7]; In the fourth test case, you have sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]. You can choose k=7 elements [2, 4, 6, \underline{7}, 8, 10, 13] and erase them except its median to get sequence b.
2
14
import java.io.*; import java.util.*; public final class h{ static int T, N, K, M, b[], pfx[]; public static void main(String args[]) throws IOException{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); T = Integer.parseInt(in.readLine()); while(T-- > 0){ StringTokenizer st = new StringTokenizer(in.readLine()); N = Integer.parseInt(st.nextToken()); K = Integer.parseInt(st.nextToken()) / 2; M = Integer.parseInt(st.nextToken()); b = new int[M]; pfx = new int[N+1]; st = new StringTokenizer(in.readLine()); for(int i = 0; i < M; i++){ b[i] = Integer.parseInt(st.nextToken()); } int pv = 1; for(int i = 0; i < M; i++){ for(int j = pv; j < b[i]; j++){ pfx[j] = pfx[j-1] + 1; } pfx[b[i]] = pfx[b[i]-1]; pv = b[i]+1; } for(int i = b[M-1]+1; i <= N; i++){ pfx[i] = pfx[i-1] + 1; } if(N % (2*K) != M % (2*K)){ out.printf("nO\n"); continue; } boolean good = false; for(int i = 0; i < M; i++){ int lo = pfx[b[i]]; int hi = pfx[N] - pfx[b[i]]; if(lo >= K && hi >= K){ good = true; break; } } out.printf(good ? "yEs\n" : "no\n"); } in.close(); out.close(); } }
JAVA
1468_H. K and Medians
Let's denote the median of a sequence s with odd length as the value in the middle of s if we sort s in non-decreasing order. For example, let s = [1, 2, 5, 7, 2, 3, 12]. After sorting, we get sequence [1, 2, 2, \underline{3}, 5, 7, 12], and the median is equal to 3. You have a sequence of n integers [1, 2, ..., n] and an odd integer k. In one step, you choose any k elements from the sequence and erase all chosen elements except their median. These elements do not have to go continuously (gaps are allowed between them). For example, if you have a sequence [1, 2, 3, 4, 5, 6, 7] (i.e. n=7) and k = 3, then the following options for the first step are possible: * choose [1, \underline{2}, 3]; 2 is their median, so it is not erased, and the resulting sequence is [2, 4, 5, 6, 7]; * choose [2, \underline{4}, 6]; 4 is their median, so it is not erased, and the resulting sequence is [1, 3, 4, 5, 7]; * choose [1, \underline{6}, 7]; 6 is their median, so it is not erased, and the resulting sequence is [2, 3, 4, 5, 6]; * and several others. You can do zero or more steps. Can you get a sequence b_1, b_2, ..., b_m after several steps? You'll be given t test cases. Solve each test case independently. 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 three integers n, k, and m (3 ≀ n ≀ 2 β‹… 10^5; 3 ≀ k ≀ n; k is odd; 1 ≀ m < n) β€” the length of the sequence you have, the number of elements you choose in each step and the length of the sequence you'd like to get. The second line of each test case contains m integers b_1, b_2, ..., b_m (1 ≀ b_1 < b_2 < ... < b_m ≀ n) β€” the sequence you'd like to get, given in the ascending order. It's guaranteed that the total sum of n over all test cases doesn't exceed 2 β‹… 10^5. Output For each test case, print YES if you can obtain the sequence b or NO otherwise. You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer). Example Input 4 3 3 1 1 7 3 3 1 5 7 10 5 3 4 5 6 13 7 7 1 3 5 7 9 11 12 Output NO YES NO YES Note In the first test case, you have sequence [1, 2, 3]. Since k = 3 you have only one way to choose k elements β€” it's to choose all elements [1, \underline{2}, 3] with median 2. That's why after erasing all chosen elements except its median you'll get sequence [2]. In other words, there is no way to get sequence b = [1] as the result. In the second test case, you have sequence [1, 2, 3, 4, 5, 6, 7] and one of the optimal strategies is following: 1. choose k = 3 elements [2, \underline{3}, 4] and erase them except its median; you'll get sequence [1, 3, 5, 6, 7]; 2. choose 3 elements [3, \underline{5}, 6] and erase them except its median; you'll get desired sequence [1, 5, 7]; In the fourth test case, you have sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]. You can choose k=7 elements [2, 4, 6, \underline{7}, 8, 10, 13] and erase them except its median to get sequence b.
2
14
T = int(input()) for _ in range(T): n, k, m = map(int, input().split()) b = [int(i) for i in input().split()] f = False ff = False for p, i in enumerate(b): if i - p - 1 == n - i - len(b) + p + 1: f = True break if i - p - 1 >= k>>1 and n - i - len(b) + p + 1 >= k>>1: ff = True if b==[int(i)+1 for i in range(n)]: print('YES') elif k>1 and (n-m)%(k-1)==0: if f: print('YES') else: border = b[0]-1 >=k>>1 or n - b[-1]>=k>>1 mid = b[-1] - b[0] + 1 - len(b) if ff: print('YES') else: print('NO') else: print('NO')
PYTHON3
1468_H. K and Medians
Let's denote the median of a sequence s with odd length as the value in the middle of s if we sort s in non-decreasing order. For example, let s = [1, 2, 5, 7, 2, 3, 12]. After sorting, we get sequence [1, 2, 2, \underline{3}, 5, 7, 12], and the median is equal to 3. You have a sequence of n integers [1, 2, ..., n] and an odd integer k. In one step, you choose any k elements from the sequence and erase all chosen elements except their median. These elements do not have to go continuously (gaps are allowed between them). For example, if you have a sequence [1, 2, 3, 4, 5, 6, 7] (i.e. n=7) and k = 3, then the following options for the first step are possible: * choose [1, \underline{2}, 3]; 2 is their median, so it is not erased, and the resulting sequence is [2, 4, 5, 6, 7]; * choose [2, \underline{4}, 6]; 4 is their median, so it is not erased, and the resulting sequence is [1, 3, 4, 5, 7]; * choose [1, \underline{6}, 7]; 6 is their median, so it is not erased, and the resulting sequence is [2, 3, 4, 5, 6]; * and several others. You can do zero or more steps. Can you get a sequence b_1, b_2, ..., b_m after several steps? You'll be given t test cases. Solve each test case independently. 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 three integers n, k, and m (3 ≀ n ≀ 2 β‹… 10^5; 3 ≀ k ≀ n; k is odd; 1 ≀ m < n) β€” the length of the sequence you have, the number of elements you choose in each step and the length of the sequence you'd like to get. The second line of each test case contains m integers b_1, b_2, ..., b_m (1 ≀ b_1 < b_2 < ... < b_m ≀ n) β€” the sequence you'd like to get, given in the ascending order. It's guaranteed that the total sum of n over all test cases doesn't exceed 2 β‹… 10^5. Output For each test case, print YES if you can obtain the sequence b or NO otherwise. You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer). Example Input 4 3 3 1 1 7 3 3 1 5 7 10 5 3 4 5 6 13 7 7 1 3 5 7 9 11 12 Output NO YES NO YES Note In the first test case, you have sequence [1, 2, 3]. Since k = 3 you have only one way to choose k elements β€” it's to choose all elements [1, \underline{2}, 3] with median 2. That's why after erasing all chosen elements except its median you'll get sequence [2]. In other words, there is no way to get sequence b = [1] as the result. In the second test case, you have sequence [1, 2, 3, 4, 5, 6, 7] and one of the optimal strategies is following: 1. choose k = 3 elements [2, \underline{3}, 4] and erase them except its median; you'll get sequence [1, 3, 5, 6, 7]; 2. choose 3 elements [3, \underline{5}, 6] and erase them except its median; you'll get desired sequence [1, 5, 7]; In the fourth test case, you have sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]. You can choose k=7 elements [2, 4, 6, \underline{7}, 8, 10, 13] and erase them except its median to get sequence b.
2
14
#include<bits/stdc++.h> #define ll long long using namespace std; const int maxn=200010; inline int read(){ int f=1,x=0;char ch=getchar(); while (ch<'0'||ch>'9'){if (ch=='-') f=-1;ch=getchar();} while (ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+ch-'0';ch=getchar();} return f*x; } int T,n,k,m; int vis[maxn],a[maxn]; int main(){ T=read(); while (T--){ memset(vis,0,sizeof(vis)); n=read();k=read();m=read(); int x; for (int i=1;i<=m;++i){ x=read(); vis[x]=1; } int pos=0; for (int i=1;i<=n;++i) if (!vis[i]) a[++pos]=i; bool fl=0; for (int i=k/2+1;i<=pos;++i){ if (pos%(k-1)==0&&pos-i+1>=k/2&&a[i]!=a[i-1]+1){ puts("YES"); fl=1;break; } } if (fl)continue; puts("NO"); } }
CPP
1468_H. K and Medians
Let's denote the median of a sequence s with odd length as the value in the middle of s if we sort s in non-decreasing order. For example, let s = [1, 2, 5, 7, 2, 3, 12]. After sorting, we get sequence [1, 2, 2, \underline{3}, 5, 7, 12], and the median is equal to 3. You have a sequence of n integers [1, 2, ..., n] and an odd integer k. In one step, you choose any k elements from the sequence and erase all chosen elements except their median. These elements do not have to go continuously (gaps are allowed between them). For example, if you have a sequence [1, 2, 3, 4, 5, 6, 7] (i.e. n=7) and k = 3, then the following options for the first step are possible: * choose [1, \underline{2}, 3]; 2 is their median, so it is not erased, and the resulting sequence is [2, 4, 5, 6, 7]; * choose [2, \underline{4}, 6]; 4 is their median, so it is not erased, and the resulting sequence is [1, 3, 4, 5, 7]; * choose [1, \underline{6}, 7]; 6 is their median, so it is not erased, and the resulting sequence is [2, 3, 4, 5, 6]; * and several others. You can do zero or more steps. Can you get a sequence b_1, b_2, ..., b_m after several steps? You'll be given t test cases. Solve each test case independently. 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 three integers n, k, and m (3 ≀ n ≀ 2 β‹… 10^5; 3 ≀ k ≀ n; k is odd; 1 ≀ m < n) β€” the length of the sequence you have, the number of elements you choose in each step and the length of the sequence you'd like to get. The second line of each test case contains m integers b_1, b_2, ..., b_m (1 ≀ b_1 < b_2 < ... < b_m ≀ n) β€” the sequence you'd like to get, given in the ascending order. It's guaranteed that the total sum of n over all test cases doesn't exceed 2 β‹… 10^5. Output For each test case, print YES if you can obtain the sequence b or NO otherwise. You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer). Example Input 4 3 3 1 1 7 3 3 1 5 7 10 5 3 4 5 6 13 7 7 1 3 5 7 9 11 12 Output NO YES NO YES Note In the first test case, you have sequence [1, 2, 3]. Since k = 3 you have only one way to choose k elements β€” it's to choose all elements [1, \underline{2}, 3] with median 2. That's why after erasing all chosen elements except its median you'll get sequence [2]. In other words, there is no way to get sequence b = [1] as the result. In the second test case, you have sequence [1, 2, 3, 4, 5, 6, 7] and one of the optimal strategies is following: 1. choose k = 3 elements [2, \underline{3}, 4] and erase them except its median; you'll get sequence [1, 3, 5, 6, 7]; 2. choose 3 elements [3, \underline{5}, 6] and erase them except its median; you'll get desired sequence [1, 5, 7]; In the fourth test case, you have sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]. You can choose k=7 elements [2, 4, 6, \underline{7}, 8, 10, 13] and erase them except its median to get sequence b.
2
14
/** * Prof.Nicola **/ #include <bits/stdc++.h> using namespace std; template<class T>void re(T&x){cin>>x;} template<class T1,class T2> void re(pair<T1,T2>&x){re(x.first);re(x.second);} template<class T>void re(vector<T>&x){for(long i=0;i<x.size();i++){re(x[i]);}} template<class T>void re(deque<T>&x){for(long i=0;i<x.size();i++){re(x[i]);}} template<class T1,class T2> pair<T1,T2> mp(T1&x,T2&z){return make_pair(x,z);} long k; long solve(long x) { if(x<k){ return x; } return solve((x/k)+(x%k)); } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); long long t,n,m,x,z; cin>>t; for(long i=0;i<t;i++){ cin>>n>>k>>m; deque<long>v(m); re(v); if((n-m)%(k-1)!=0){ cout<<"NO"<<endl; continue; } v.push_front(0); v.push_back(n+1); vector<long>pre(m),suf(m); x=0; for(long j=1;j<=m;j++){ x+=v[j]-v[j-1]-1; pre[j-1]=x; } x=0; for(long j=m+1;j>1;j--){ x+=v[j]-v[j-1]-1; suf[j-2]=x; } bool ok=false; for(long j=0;j<m;j++){ x=solve(pre[j]); z=solve(suf[j]); if((x%(k/2)==0&&z==x)||(min(pre[j],suf[j])>=k/2)){ ok=true; break; } } if(ok){ cout<<"YES"<<endl; } else{ cout<<"NO"<<endl; } } return 0; }
CPP
1468_H. K and Medians
Let's denote the median of a sequence s with odd length as the value in the middle of s if we sort s in non-decreasing order. For example, let s = [1, 2, 5, 7, 2, 3, 12]. After sorting, we get sequence [1, 2, 2, \underline{3}, 5, 7, 12], and the median is equal to 3. You have a sequence of n integers [1, 2, ..., n] and an odd integer k. In one step, you choose any k elements from the sequence and erase all chosen elements except their median. These elements do not have to go continuously (gaps are allowed between them). For example, if you have a sequence [1, 2, 3, 4, 5, 6, 7] (i.e. n=7) and k = 3, then the following options for the first step are possible: * choose [1, \underline{2}, 3]; 2 is their median, so it is not erased, and the resulting sequence is [2, 4, 5, 6, 7]; * choose [2, \underline{4}, 6]; 4 is their median, so it is not erased, and the resulting sequence is [1, 3, 4, 5, 7]; * choose [1, \underline{6}, 7]; 6 is their median, so it is not erased, and the resulting sequence is [2, 3, 4, 5, 6]; * and several others. You can do zero or more steps. Can you get a sequence b_1, b_2, ..., b_m after several steps? You'll be given t test cases. Solve each test case independently. 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 three integers n, k, and m (3 ≀ n ≀ 2 β‹… 10^5; 3 ≀ k ≀ n; k is odd; 1 ≀ m < n) β€” the length of the sequence you have, the number of elements you choose in each step and the length of the sequence you'd like to get. The second line of each test case contains m integers b_1, b_2, ..., b_m (1 ≀ b_1 < b_2 < ... < b_m ≀ n) β€” the sequence you'd like to get, given in the ascending order. It's guaranteed that the total sum of n over all test cases doesn't exceed 2 β‹… 10^5. Output For each test case, print YES if you can obtain the sequence b or NO otherwise. You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer). Example Input 4 3 3 1 1 7 3 3 1 5 7 10 5 3 4 5 6 13 7 7 1 3 5 7 9 11 12 Output NO YES NO YES Note In the first test case, you have sequence [1, 2, 3]. Since k = 3 you have only one way to choose k elements β€” it's to choose all elements [1, \underline{2}, 3] with median 2. That's why after erasing all chosen elements except its median you'll get sequence [2]. In other words, there is no way to get sequence b = [1] as the result. In the second test case, you have sequence [1, 2, 3, 4, 5, 6, 7] and one of the optimal strategies is following: 1. choose k = 3 elements [2, \underline{3}, 4] and erase them except its median; you'll get sequence [1, 3, 5, 6, 7]; 2. choose 3 elements [3, \underline{5}, 6] and erase them except its median; you'll get desired sequence [1, 5, 7]; In the fourth test case, you have sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]. You can choose k=7 elements [2, 4, 6, \underline{7}, 8, 10, 13] and erase them except its median to get sequence b.
2
14
#pragma GCC diagnostic ignored "-Wunused-parameter" #define _USE_MATH_DEFINES #include <bits/stdc++.h> using namespace std; #define INP "solve" #define OUT "solve" const long long INF_LL = 8e18; const int INF = 1e9 + 100; const int MOD = 1e9 + 7; //const int Base = 311;9 const long double EPS = 1e-10; const int BLOCK = 1000; const int dx[4] = {0, 0, 1, -1}; const int dy[4] = {1, -1, 0, 0}; mt19937 rnd(chrono::system_clock::now().time_since_epoch().count()); void open_file() { #ifdef THEMIS freopen(INP ".inp","r",stdin); freopen(OUT ".out","w",stdout); #endif // THEMIS } const int maxN = 3e5 + 100; void sol(){ int n, k, m; cin >> n >> k >> m; vector<bool> used(n, false); for (int i = 0; i < m; i++) { int b; cin >> b; b--; used[b] = true; } if ((n - m) % (k - 1)) { cout << "NO" << '\n'; return; } bool ok = false; int num = 0; for (int i = 0; i < n; i++) { if (used[i] == false) num++; else { ok |= (num >= k / 2) && ((n - m) - num >= k / 2); } } if (ok) cout << "YES" << '\n'; else cout << "NO" << '\n'; } void solve() { clock_t begin = clock(); int T; cin >> T; //T = 1; int TestCase = 0; while (T--) { TestCase += 1; //cout << "Case #" << TestCase << ":" << ' '; //cout << "Test " << TestCase << ": "; sol(); } clock_t end = clock(); cerr << "Time: " << fixed << setprecision(10) << (double)(end - begin) / (double)CLOCKS_PER_SEC << '\n'; } int main(int argc,char *argv[]) { ///srand(time(nullptr)); ios_base::sync_with_stdio(0); cin.tie(nullptr); cout.tie(nullptr); open_file(); solve(); }
CPP
1468_H. K and Medians
Let's denote the median of a sequence s with odd length as the value in the middle of s if we sort s in non-decreasing order. For example, let s = [1, 2, 5, 7, 2, 3, 12]. After sorting, we get sequence [1, 2, 2, \underline{3}, 5, 7, 12], and the median is equal to 3. You have a sequence of n integers [1, 2, ..., n] and an odd integer k. In one step, you choose any k elements from the sequence and erase all chosen elements except their median. These elements do not have to go continuously (gaps are allowed between them). For example, if you have a sequence [1, 2, 3, 4, 5, 6, 7] (i.e. n=7) and k = 3, then the following options for the first step are possible: * choose [1, \underline{2}, 3]; 2 is their median, so it is not erased, and the resulting sequence is [2, 4, 5, 6, 7]; * choose [2, \underline{4}, 6]; 4 is their median, so it is not erased, and the resulting sequence is [1, 3, 4, 5, 7]; * choose [1, \underline{6}, 7]; 6 is their median, so it is not erased, and the resulting sequence is [2, 3, 4, 5, 6]; * and several others. You can do zero or more steps. Can you get a sequence b_1, b_2, ..., b_m after several steps? You'll be given t test cases. Solve each test case independently. 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 three integers n, k, and m (3 ≀ n ≀ 2 β‹… 10^5; 3 ≀ k ≀ n; k is odd; 1 ≀ m < n) β€” the length of the sequence you have, the number of elements you choose in each step and the length of the sequence you'd like to get. The second line of each test case contains m integers b_1, b_2, ..., b_m (1 ≀ b_1 < b_2 < ... < b_m ≀ n) β€” the sequence you'd like to get, given in the ascending order. It's guaranteed that the total sum of n over all test cases doesn't exceed 2 β‹… 10^5. Output For each test case, print YES if you can obtain the sequence b or NO otherwise. You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer). Example Input 4 3 3 1 1 7 3 3 1 5 7 10 5 3 4 5 6 13 7 7 1 3 5 7 9 11 12 Output NO YES NO YES Note In the first test case, you have sequence [1, 2, 3]. Since k = 3 you have only one way to choose k elements β€” it's to choose all elements [1, \underline{2}, 3] with median 2. That's why after erasing all chosen elements except its median you'll get sequence [2]. In other words, there is no way to get sequence b = [1] as the result. In the second test case, you have sequence [1, 2, 3, 4, 5, 6, 7] and one of the optimal strategies is following: 1. choose k = 3 elements [2, \underline{3}, 4] and erase them except its median; you'll get sequence [1, 3, 5, 6, 7]; 2. choose 3 elements [3, \underline{5}, 6] and erase them except its median; you'll get desired sequence [1, 5, 7]; In the fourth test case, you have sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]. You can choose k=7 elements [2, 4, 6, \underline{7}, 8, 10, 13] and erase them except its median to get sequence b.
2
14
#include <bits/stdc++.h> using namespace std; typedef long long ll; int a[200005]; int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t; cin >> t; while(t--) { int n, k, m; cin >> n >> k >> m; for(int i=1;i<=n;++i) a[i] = 1; for(int i=1;i<=m;++i) { int x; cin >> x; a[x] = 0; } if((n - m) % (k - 1)) { cout << "NO" << endl; continue; } int ok = 0; int l = 0, r = n - m; for(int i=1;i<=n;++i) { if(a[i]) --r; if(a[i] == 0 && r >= (k-1)/2 && l >= (k-1)/2) ok = 1; if(a[i]) ++l; } if(ok) cout << "YES\n"; else cout << "NO\n"; } }
CPP
1468_H. K and Medians
Let's denote the median of a sequence s with odd length as the value in the middle of s if we sort s in non-decreasing order. For example, let s = [1, 2, 5, 7, 2, 3, 12]. After sorting, we get sequence [1, 2, 2, \underline{3}, 5, 7, 12], and the median is equal to 3. You have a sequence of n integers [1, 2, ..., n] and an odd integer k. In one step, you choose any k elements from the sequence and erase all chosen elements except their median. These elements do not have to go continuously (gaps are allowed between them). For example, if you have a sequence [1, 2, 3, 4, 5, 6, 7] (i.e. n=7) and k = 3, then the following options for the first step are possible: * choose [1, \underline{2}, 3]; 2 is their median, so it is not erased, and the resulting sequence is [2, 4, 5, 6, 7]; * choose [2, \underline{4}, 6]; 4 is their median, so it is not erased, and the resulting sequence is [1, 3, 4, 5, 7]; * choose [1, \underline{6}, 7]; 6 is their median, so it is not erased, and the resulting sequence is [2, 3, 4, 5, 6]; * and several others. You can do zero or more steps. Can you get a sequence b_1, b_2, ..., b_m after several steps? You'll be given t test cases. Solve each test case independently. 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 three integers n, k, and m (3 ≀ n ≀ 2 β‹… 10^5; 3 ≀ k ≀ n; k is odd; 1 ≀ m < n) β€” the length of the sequence you have, the number of elements you choose in each step and the length of the sequence you'd like to get. The second line of each test case contains m integers b_1, b_2, ..., b_m (1 ≀ b_1 < b_2 < ... < b_m ≀ n) β€” the sequence you'd like to get, given in the ascending order. It's guaranteed that the total sum of n over all test cases doesn't exceed 2 β‹… 10^5. Output For each test case, print YES if you can obtain the sequence b or NO otherwise. You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer). Example Input 4 3 3 1 1 7 3 3 1 5 7 10 5 3 4 5 6 13 7 7 1 3 5 7 9 11 12 Output NO YES NO YES Note In the first test case, you have sequence [1, 2, 3]. Since k = 3 you have only one way to choose k elements β€” it's to choose all elements [1, \underline{2}, 3] with median 2. That's why after erasing all chosen elements except its median you'll get sequence [2]. In other words, there is no way to get sequence b = [1] as the result. In the second test case, you have sequence [1, 2, 3, 4, 5, 6, 7] and one of the optimal strategies is following: 1. choose k = 3 elements [2, \underline{3}, 4] and erase them except its median; you'll get sequence [1, 3, 5, 6, 7]; 2. choose 3 elements [3, \underline{5}, 6] and erase them except its median; you'll get desired sequence [1, 5, 7]; In the fourth test case, you have sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]. You can choose k=7 elements [2, 4, 6, \underline{7}, 8, 10, 13] and erase them except its median to get sequence b.
2
14
#include<cstdio> #include<cstring> #include<algorithm> #include<cmath> #define maxn 200005 using namespace std; int T,n,m,K,i,j,k,bz[maxn],cnt[maxn]; int main(){ scanf("%d",&T); while (T--){ scanf("%d%d%d",&n,&k,&m); for(i=1;i<=n;i++) bz[i]=0; for(i=1;i<=m;i++){ int x; scanf("%d",&x); bz[x]=1; } if ((n-m)%(k-1)!=0) { printf("NO\n"); continue; } for(i=1;i<=n;i++) cnt[i]=cnt[i-1]+(bz[i]^1); int tp=0; for(i=1;i<=n;i++) if (bz[i]){ if (cnt[i]>=k/2&&cnt[n]-cnt[i]>=k/2){ tp=1; printf("YES\n"); break; } } if (!tp) printf("NO\n"); } }
CPP
1468_H. K and Medians
Let's denote the median of a sequence s with odd length as the value in the middle of s if we sort s in non-decreasing order. For example, let s = [1, 2, 5, 7, 2, 3, 12]. After sorting, we get sequence [1, 2, 2, \underline{3}, 5, 7, 12], and the median is equal to 3. You have a sequence of n integers [1, 2, ..., n] and an odd integer k. In one step, you choose any k elements from the sequence and erase all chosen elements except their median. These elements do not have to go continuously (gaps are allowed between them). For example, if you have a sequence [1, 2, 3, 4, 5, 6, 7] (i.e. n=7) and k = 3, then the following options for the first step are possible: * choose [1, \underline{2}, 3]; 2 is their median, so it is not erased, and the resulting sequence is [2, 4, 5, 6, 7]; * choose [2, \underline{4}, 6]; 4 is their median, so it is not erased, and the resulting sequence is [1, 3, 4, 5, 7]; * choose [1, \underline{6}, 7]; 6 is their median, so it is not erased, and the resulting sequence is [2, 3, 4, 5, 6]; * and several others. You can do zero or more steps. Can you get a sequence b_1, b_2, ..., b_m after several steps? You'll be given t test cases. Solve each test case independently. 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 three integers n, k, and m (3 ≀ n ≀ 2 β‹… 10^5; 3 ≀ k ≀ n; k is odd; 1 ≀ m < n) β€” the length of the sequence you have, the number of elements you choose in each step and the length of the sequence you'd like to get. The second line of each test case contains m integers b_1, b_2, ..., b_m (1 ≀ b_1 < b_2 < ... < b_m ≀ n) β€” the sequence you'd like to get, given in the ascending order. It's guaranteed that the total sum of n over all test cases doesn't exceed 2 β‹… 10^5. Output For each test case, print YES if you can obtain the sequence b or NO otherwise. You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer). Example Input 4 3 3 1 1 7 3 3 1 5 7 10 5 3 4 5 6 13 7 7 1 3 5 7 9 11 12 Output NO YES NO YES Note In the first test case, you have sequence [1, 2, 3]. Since k = 3 you have only one way to choose k elements β€” it's to choose all elements [1, \underline{2}, 3] with median 2. That's why after erasing all chosen elements except its median you'll get sequence [2]. In other words, there is no way to get sequence b = [1] as the result. In the second test case, you have sequence [1, 2, 3, 4, 5, 6, 7] and one of the optimal strategies is following: 1. choose k = 3 elements [2, \underline{3}, 4] and erase them except its median; you'll get sequence [1, 3, 5, 6, 7]; 2. choose 3 elements [3, \underline{5}, 6] and erase them except its median; you'll get desired sequence [1, 5, 7]; In the fourth test case, you have sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]. You can choose k=7 elements [2, 4, 6, \underline{7}, 8, 10, 13] and erase them except its median to get sequence b.
2
14
#include<bits/stdc++.h> using namespace std; #define int long long #define double long double #define endl '\n' #define pb push_back #define pob pop_back #define pii pair<int,int> #define mod 1000000007 // #define mod 1000000009 // #define mod 163577857 // #define mod 998244353 #define rep(i,n) for (int i = 0; i < n; i++) #define repp(i,a,b) for(int i = a ; i<b ; i++) #define reppr(i,a,b) for(int i = a-1 ; i>=b ; i--) #define repr(i,n) for (int i = n - 1; i >= 0; i--) #define ff first #define ss second #define inf 9223372036854775807 #define infn -9223372036854775807 #define pi 3.14159265358979323846 #define eps 0.0000000001 #define setprec(x) cout << fixed << setprecision(x); #define REVERSE(a) reverse(all(a)); #define SORT(a) sort(all(a)); #define all(n) n.begin(),n.end() //GCD and LCM int gcd (int a, int b) { return b ? gcd (b, a % b) : a; } int lcm (int a, int b) { return a / gcd(a, b) * b; } //Modular Exponentiation int powmod(int x,int y) { if (y == 0) return 1; int p = powmod(x, y/2) % mod; p = (p * p) % mod; return (y%2 == 0)? p : (x * p) % mod; } //Modular Inverse int inverse(int a) { return powmod(a,mod-2); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////NO TEXT ABOVE IT////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool codejam = 0, testcases = 1; void solve() { int n , k , m ; cin >> n >> k >> m; vector<int> v(m); rep(i,m) cin >> v[i]; rep(i,m) { int left = v[i]-i-1 , right = (n-m) - left; if(left>=k/2) left -= k/2; else continue; if(right>=k/2) right -= k/2; else continue; left%=(k-1); right%=(k-1); if((left+right)%(k-1)==0) { cout << "YES\n"; return; } } cout << "NO\n"; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////NO TEXT BELOW IT////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////// signed main() { ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); int t = 1; if(testcases) cin >> t; rep(i,t) { if(codejam) cout << "Case #" << i+ 1<< ": "; solve(); } }
CPP
1468_H. K and Medians
Let's denote the median of a sequence s with odd length as the value in the middle of s if we sort s in non-decreasing order. For example, let s = [1, 2, 5, 7, 2, 3, 12]. After sorting, we get sequence [1, 2, 2, \underline{3}, 5, 7, 12], and the median is equal to 3. You have a sequence of n integers [1, 2, ..., n] and an odd integer k. In one step, you choose any k elements from the sequence and erase all chosen elements except their median. These elements do not have to go continuously (gaps are allowed between them). For example, if you have a sequence [1, 2, 3, 4, 5, 6, 7] (i.e. n=7) and k = 3, then the following options for the first step are possible: * choose [1, \underline{2}, 3]; 2 is their median, so it is not erased, and the resulting sequence is [2, 4, 5, 6, 7]; * choose [2, \underline{4}, 6]; 4 is their median, so it is not erased, and the resulting sequence is [1, 3, 4, 5, 7]; * choose [1, \underline{6}, 7]; 6 is their median, so it is not erased, and the resulting sequence is [2, 3, 4, 5, 6]; * and several others. You can do zero or more steps. Can you get a sequence b_1, b_2, ..., b_m after several steps? You'll be given t test cases. Solve each test case independently. 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 three integers n, k, and m (3 ≀ n ≀ 2 β‹… 10^5; 3 ≀ k ≀ n; k is odd; 1 ≀ m < n) β€” the length of the sequence you have, the number of elements you choose in each step and the length of the sequence you'd like to get. The second line of each test case contains m integers b_1, b_2, ..., b_m (1 ≀ b_1 < b_2 < ... < b_m ≀ n) β€” the sequence you'd like to get, given in the ascending order. It's guaranteed that the total sum of n over all test cases doesn't exceed 2 β‹… 10^5. Output For each test case, print YES if you can obtain the sequence b or NO otherwise. You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer). Example Input 4 3 3 1 1 7 3 3 1 5 7 10 5 3 4 5 6 13 7 7 1 3 5 7 9 11 12 Output NO YES NO YES Note In the first test case, you have sequence [1, 2, 3]. Since k = 3 you have only one way to choose k elements β€” it's to choose all elements [1, \underline{2}, 3] with median 2. That's why after erasing all chosen elements except its median you'll get sequence [2]. In other words, there is no way to get sequence b = [1] as the result. In the second test case, you have sequence [1, 2, 3, 4, 5, 6, 7] and one of the optimal strategies is following: 1. choose k = 3 elements [2, \underline{3}, 4] and erase them except its median; you'll get sequence [1, 3, 5, 6, 7]; 2. choose 3 elements [3, \underline{5}, 6] and erase them except its median; you'll get desired sequence [1, 5, 7]; In the fourth test case, you have sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]. You can choose k=7 elements [2, 4, 6, \underline{7}, 8, 10, 13] and erase them except its median to get sequence b.
2
14
#pragma GCC optimize("Ofast") #pragma GCC optimize("unroll-loops") #pragma GCC target("sse,sse2,sse3,ssse3,abm,mmx,tune=native") #pragma comment(linker, "/STACK:2769095000") #define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<cstdlib> //#include<cstdint> #include<sstream> #include<cmath> #include<ctime> #include<algorithm> #include<iostream> #include<fstream> #include<vector> #include<string> #include<cstring> #include<map> #include<set> #include<queue> #include<deque> #include<bitset> #include<sstream> #include<numeric> #include<random> //#include<functional> #include<unordered_set> #include<unordered_map> #include<stack> #include<complex> #include <numeric> using namespace std; typedef unsigned long long ull; typedef long long ll; typedef int itn; typedef long double ld; typedef pair<ll, ll> pii; typedef pair<ld, ld> pdd; typedef pair<ll, ld> pid; typedef pair<int, char> pic; typedef pair<int, pii> piii; #define xx first #define yy second //#define int ll //#define F first //#define S second #define zz second #define mp make_pair #define y1 oshfkfsldhs #define union jfghjdghdjhgjhdjgh #define all(x) (x).begin(), (x).end() #define out(x) return void(cout << (x) << endl) #define OUT(x) ((cout << (x)), exit(0)) const ll MOD = 1e9 + 7; //(ll)998244353; const ll MOR = (ll)1e9 + 33; const int dy[] = { 0, 0, 1, 1 }; const int dx[] = { 0, 1, 0, 1 }; const char dc[] = { 'D', 'U', 'R', 'L' }; const ll INF = 1e18 + 100; const ld EPS = 1e-10; const double PI = 3.14159265358979323846; const int SZ = 400; const ll MAXN = 8e5 + 10; #ifdef _DEBUG ll __builtin_popcount(ll x) { return x ? (__builtin_popcount(x >> 1) + (x & 1)) : 0; } #endif inline void getint(int& x) { int c = getc(stdin); x = 0; while (c <= 32) c = getc(stdin); while ('0' <= c && c <= '9') x = x * 10 + c - '0', c = getc(stdin); return; } inline void writeint(int& x) { char s[10]; int n = 0; while (x || !n) s[n++] = '0' + x % 10, x /= 10; while (n--) putc(s[n], stdout); putc('\n', stdout); } int b[MAXN]; int cnt[MAXN]; void solve() { int n, k, m; cin >> n >> k >> m; for (int i = 0; i < m; i++) cin >> b[i], b[i]--; if ((n - m) % (k - 1) != 0) { cout << "NO\n"; return; } int j = 0; for (int i = 0; i < n; i++) { cnt[i] = 0; while (j < m && b[j] < i) j++; if (i != b[j]) cnt[i] = 1; } for (int i = 1; i < n; i++) cnt[i] = cnt[i] + cnt[i - 1]; for (int i = 0; i < m; i++) { if ((k - 1) / 2 <= cnt[b[i]] && (n - m - cnt[b[i]]) >= (k - 1) / 2) { cout << "YES\n"; return; } } cout << "NO\n"; } int32_t main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cout.precision(10); #ifdef _DEBUG auto _ = freopen("input.txt", "r", stdin); _ = freopen("output.txt", "w", stdout); #else //auto _ = freopen("improvements.in", "r", stdin); //_ = freopen("improvements.out", "w", stdout); #endif int t; cin >> t; while (t--) solve(); }
CPP
1468_H. K and Medians
Let's denote the median of a sequence s with odd length as the value in the middle of s if we sort s in non-decreasing order. For example, let s = [1, 2, 5, 7, 2, 3, 12]. After sorting, we get sequence [1, 2, 2, \underline{3}, 5, 7, 12], and the median is equal to 3. You have a sequence of n integers [1, 2, ..., n] and an odd integer k. In one step, you choose any k elements from the sequence and erase all chosen elements except their median. These elements do not have to go continuously (gaps are allowed between them). For example, if you have a sequence [1, 2, 3, 4, 5, 6, 7] (i.e. n=7) and k = 3, then the following options for the first step are possible: * choose [1, \underline{2}, 3]; 2 is their median, so it is not erased, and the resulting sequence is [2, 4, 5, 6, 7]; * choose [2, \underline{4}, 6]; 4 is their median, so it is not erased, and the resulting sequence is [1, 3, 4, 5, 7]; * choose [1, \underline{6}, 7]; 6 is their median, so it is not erased, and the resulting sequence is [2, 3, 4, 5, 6]; * and several others. You can do zero or more steps. Can you get a sequence b_1, b_2, ..., b_m after several steps? You'll be given t test cases. Solve each test case independently. 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 three integers n, k, and m (3 ≀ n ≀ 2 β‹… 10^5; 3 ≀ k ≀ n; k is odd; 1 ≀ m < n) β€” the length of the sequence you have, the number of elements you choose in each step and the length of the sequence you'd like to get. The second line of each test case contains m integers b_1, b_2, ..., b_m (1 ≀ b_1 < b_2 < ... < b_m ≀ n) β€” the sequence you'd like to get, given in the ascending order. It's guaranteed that the total sum of n over all test cases doesn't exceed 2 β‹… 10^5. Output For each test case, print YES if you can obtain the sequence b or NO otherwise. You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer). Example Input 4 3 3 1 1 7 3 3 1 5 7 10 5 3 4 5 6 13 7 7 1 3 5 7 9 11 12 Output NO YES NO YES Note In the first test case, you have sequence [1, 2, 3]. Since k = 3 you have only one way to choose k elements β€” it's to choose all elements [1, \underline{2}, 3] with median 2. That's why after erasing all chosen elements except its median you'll get sequence [2]. In other words, there is no way to get sequence b = [1] as the result. In the second test case, you have sequence [1, 2, 3, 4, 5, 6, 7] and one of the optimal strategies is following: 1. choose k = 3 elements [2, \underline{3}, 4] and erase them except its median; you'll get sequence [1, 3, 5, 6, 7]; 2. choose 3 elements [3, \underline{5}, 6] and erase them except its median; you'll get desired sequence [1, 5, 7]; In the fourth test case, you have sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]. You can choose k=7 elements [2, 4, 6, \underline{7}, 8, 10, 13] and erase them except its median to get sequence b.
2
14
from sys import stdin, stdout from collections import defaultdict import math def main(): t = int(stdin.readline()) for _ in range(t): n,k,m = list(map(int, stdin.readline().split())) arr = list(map(int, stdin.readline().split())) if (n - m) % (k - 1) != 0: stdout.write("NO\n") continue is_can = False for i, a in enumerate(arr): left = a - (i + 1) right = n - m - left if left < int(k / 2) or right < int(k / 2): continue is_can = True break if is_can: stdout.write("YES\n") else: stdout.write("NO\n") main()
PYTHON3
1468_H. K and Medians
Let's denote the median of a sequence s with odd length as the value in the middle of s if we sort s in non-decreasing order. For example, let s = [1, 2, 5, 7, 2, 3, 12]. After sorting, we get sequence [1, 2, 2, \underline{3}, 5, 7, 12], and the median is equal to 3. You have a sequence of n integers [1, 2, ..., n] and an odd integer k. In one step, you choose any k elements from the sequence and erase all chosen elements except their median. These elements do not have to go continuously (gaps are allowed between them). For example, if you have a sequence [1, 2, 3, 4, 5, 6, 7] (i.e. n=7) and k = 3, then the following options for the first step are possible: * choose [1, \underline{2}, 3]; 2 is their median, so it is not erased, and the resulting sequence is [2, 4, 5, 6, 7]; * choose [2, \underline{4}, 6]; 4 is their median, so it is not erased, and the resulting sequence is [1, 3, 4, 5, 7]; * choose [1, \underline{6}, 7]; 6 is their median, so it is not erased, and the resulting sequence is [2, 3, 4, 5, 6]; * and several others. You can do zero or more steps. Can you get a sequence b_1, b_2, ..., b_m after several steps? You'll be given t test cases. Solve each test case independently. 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 three integers n, k, and m (3 ≀ n ≀ 2 β‹… 10^5; 3 ≀ k ≀ n; k is odd; 1 ≀ m < n) β€” the length of the sequence you have, the number of elements you choose in each step and the length of the sequence you'd like to get. The second line of each test case contains m integers b_1, b_2, ..., b_m (1 ≀ b_1 < b_2 < ... < b_m ≀ n) β€” the sequence you'd like to get, given in the ascending order. It's guaranteed that the total sum of n over all test cases doesn't exceed 2 β‹… 10^5. Output For each test case, print YES if you can obtain the sequence b or NO otherwise. You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer). Example Input 4 3 3 1 1 7 3 3 1 5 7 10 5 3 4 5 6 13 7 7 1 3 5 7 9 11 12 Output NO YES NO YES Note In the first test case, you have sequence [1, 2, 3]. Since k = 3 you have only one way to choose k elements β€” it's to choose all elements [1, \underline{2}, 3] with median 2. That's why after erasing all chosen elements except its median you'll get sequence [2]. In other words, there is no way to get sequence b = [1] as the result. In the second test case, you have sequence [1, 2, 3, 4, 5, 6, 7] and one of the optimal strategies is following: 1. choose k = 3 elements [2, \underline{3}, 4] and erase them except its median; you'll get sequence [1, 3, 5, 6, 7]; 2. choose 3 elements [3, \underline{5}, 6] and erase them except its median; you'll get desired sequence [1, 5, 7]; In the fourth test case, you have sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]. You can choose k=7 elements [2, 4, 6, \underline{7}, 8, 10, 13] and erase them except its median to get sequence b.
2
14
T = int(input()) for _ in range(T): n, k, m = map(int, input().split()) b = [int(i) for i in input().split()] ff = False for p, i in enumerate(b): if i - p - 1 >= k>>1 and n - i - len(b) + p + 1 >= k>>1: ff = True if b==[int(i)+1 for i in range(n)]: print('YES') elif k>1 and (n-m)%(k-1)==0: if ff: print('YES') else: print('NO') else: print('NO')
PYTHON3
1468_H. K and Medians
Let's denote the median of a sequence s with odd length as the value in the middle of s if we sort s in non-decreasing order. For example, let s = [1, 2, 5, 7, 2, 3, 12]. After sorting, we get sequence [1, 2, 2, \underline{3}, 5, 7, 12], and the median is equal to 3. You have a sequence of n integers [1, 2, ..., n] and an odd integer k. In one step, you choose any k elements from the sequence and erase all chosen elements except their median. These elements do not have to go continuously (gaps are allowed between them). For example, if you have a sequence [1, 2, 3, 4, 5, 6, 7] (i.e. n=7) and k = 3, then the following options for the first step are possible: * choose [1, \underline{2}, 3]; 2 is their median, so it is not erased, and the resulting sequence is [2, 4, 5, 6, 7]; * choose [2, \underline{4}, 6]; 4 is their median, so it is not erased, and the resulting sequence is [1, 3, 4, 5, 7]; * choose [1, \underline{6}, 7]; 6 is their median, so it is not erased, and the resulting sequence is [2, 3, 4, 5, 6]; * and several others. You can do zero or more steps. Can you get a sequence b_1, b_2, ..., b_m after several steps? You'll be given t test cases. Solve each test case independently. 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 three integers n, k, and m (3 ≀ n ≀ 2 β‹… 10^5; 3 ≀ k ≀ n; k is odd; 1 ≀ m < n) β€” the length of the sequence you have, the number of elements you choose in each step and the length of the sequence you'd like to get. The second line of each test case contains m integers b_1, b_2, ..., b_m (1 ≀ b_1 < b_2 < ... < b_m ≀ n) β€” the sequence you'd like to get, given in the ascending order. It's guaranteed that the total sum of n over all test cases doesn't exceed 2 β‹… 10^5. Output For each test case, print YES if you can obtain the sequence b or NO otherwise. You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer). Example Input 4 3 3 1 1 7 3 3 1 5 7 10 5 3 4 5 6 13 7 7 1 3 5 7 9 11 12 Output NO YES NO YES Note In the first test case, you have sequence [1, 2, 3]. Since k = 3 you have only one way to choose k elements β€” it's to choose all elements [1, \underline{2}, 3] with median 2. That's why after erasing all chosen elements except its median you'll get sequence [2]. In other words, there is no way to get sequence b = [1] as the result. In the second test case, you have sequence [1, 2, 3, 4, 5, 6, 7] and one of the optimal strategies is following: 1. choose k = 3 elements [2, \underline{3}, 4] and erase them except its median; you'll get sequence [1, 3, 5, 6, 7]; 2. choose 3 elements [3, \underline{5}, 6] and erase them except its median; you'll get desired sequence [1, 5, 7]; In the fourth test case, you have sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]. You can choose k=7 elements [2, 4, 6, \underline{7}, 8, 10, 13] and erase them except its median to get sequence b.
2
14
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<algorithm> #include<queue> #include<set> #include<map> #define mp make_pair #define fi first #define se second #define pb push_back #define ls (x<<1) #define rs (x<<1|1) #define db double #define inf 2147483647 #define llinf 9223372036854775807 #define ll long long #define ull unsigned long long using namespace std; typedef pair<int,int> PII; int inline read(){ int num=0,neg=1;char c=getchar(); while(!isdigit(c)){if(c=='-')neg=-1;c=getchar();} while(isdigit(c)){num=(num<<3)+(num<<1)+c-'0';c=getchar();} return num*neg; } const int maxn=200010,mod=998244353; int T,n,m,k,a[maxn],sum[maxn],is[maxn],sum1[maxn]; int main(){ T=read(); while(T--){ for(int i=1;i<=m;i++)is[a[i]]=0; n=read();k=read();m=read(); for(int i=1;i<=m;i++)a[i]=read(),is[a[i]]=1; if((n-m)%(k-1)!=0)printf("NO\n"); else{ int flg=0; for(int i=1;i<=n;i++) sum[i]=sum[i-1]+1-is[i]; for(int i=n;i>=1;i--) sum1[i]=sum1[i+1]+1-is[i]; for(int i=1;i<=m;i++) if(sum[a[i]-1]>=k/2&&sum1[a[i]+1]>=k/2)flg=1; if(flg)printf("YES\n");else printf("NO\n"); } }return 0; } /* 7 4 3 2 2 3 4 3 2 1 4 4 3 2 1 2 3 3 1 1 7 3 3 1 5 7 10 5 3 4 5 6 13 7 7 1 3 5 7 9 11 12 YES NO NO NO YES NO YES */
CPP
1468_H. K and Medians
Let's denote the median of a sequence s with odd length as the value in the middle of s if we sort s in non-decreasing order. For example, let s = [1, 2, 5, 7, 2, 3, 12]. After sorting, we get sequence [1, 2, 2, \underline{3}, 5, 7, 12], and the median is equal to 3. You have a sequence of n integers [1, 2, ..., n] and an odd integer k. In one step, you choose any k elements from the sequence and erase all chosen elements except their median. These elements do not have to go continuously (gaps are allowed between them). For example, if you have a sequence [1, 2, 3, 4, 5, 6, 7] (i.e. n=7) and k = 3, then the following options for the first step are possible: * choose [1, \underline{2}, 3]; 2 is their median, so it is not erased, and the resulting sequence is [2, 4, 5, 6, 7]; * choose [2, \underline{4}, 6]; 4 is their median, so it is not erased, and the resulting sequence is [1, 3, 4, 5, 7]; * choose [1, \underline{6}, 7]; 6 is their median, so it is not erased, and the resulting sequence is [2, 3, 4, 5, 6]; * and several others. You can do zero or more steps. Can you get a sequence b_1, b_2, ..., b_m after several steps? You'll be given t test cases. Solve each test case independently. 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 three integers n, k, and m (3 ≀ n ≀ 2 β‹… 10^5; 3 ≀ k ≀ n; k is odd; 1 ≀ m < n) β€” the length of the sequence you have, the number of elements you choose in each step and the length of the sequence you'd like to get. The second line of each test case contains m integers b_1, b_2, ..., b_m (1 ≀ b_1 < b_2 < ... < b_m ≀ n) β€” the sequence you'd like to get, given in the ascending order. It's guaranteed that the total sum of n over all test cases doesn't exceed 2 β‹… 10^5. Output For each test case, print YES if you can obtain the sequence b or NO otherwise. You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer). Example Input 4 3 3 1 1 7 3 3 1 5 7 10 5 3 4 5 6 13 7 7 1 3 5 7 9 11 12 Output NO YES NO YES Note In the first test case, you have sequence [1, 2, 3]. Since k = 3 you have only one way to choose k elements β€” it's to choose all elements [1, \underline{2}, 3] with median 2. That's why after erasing all chosen elements except its median you'll get sequence [2]. In other words, there is no way to get sequence b = [1] as the result. In the second test case, you have sequence [1, 2, 3, 4, 5, 6, 7] and one of the optimal strategies is following: 1. choose k = 3 elements [2, \underline{3}, 4] and erase them except its median; you'll get sequence [1, 3, 5, 6, 7]; 2. choose 3 elements [3, \underline{5}, 6] and erase them except its median; you'll get desired sequence [1, 5, 7]; In the fourth test case, you have sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]. You can choose k=7 elements [2, 4, 6, \underline{7}, 8, 10, 13] and erase them except its median to get sequence b.
2
14
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); HKAndMedians solver = new HKAndMedians(); solver.solve(1, in, out); out.close(); } static class HKAndMedians { public void solve(int testNumber, Scanner sc, PrintWriter pw) { int q = sc.nextInt(); while (q-- > 0) { int n = sc.nextInt(), k = sc.nextInt(), m = sc.nextInt(); boolean f = true; if ((n - m) % (k - 1) != 0) { f = false; } int[] prefix = new int[n]; for (int i = 0; i < n; i++) { prefix[i] = 1; } int[] arr = new int[m]; for (int i = 0; i < m; i++) { arr[i] = sc.nextInt() - 1; prefix[arr[i]] = 0; } for (int i = 1; i < n; i++) prefix[i] += prefix[i - 1]; boolean f2 = false; for (int i = 0; i < m; i++) { int before = prefix[arr[i]]; int after = n - m - before; if (before >= k / 2 && after >= k / 2) f2 = true; } if (f2 & f) { pw.println("YES"); } else pw.println("NO"); } } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() { try { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } catch (Exception e) { throw new RuntimeException(e); } } public int nextInt() { return Integer.parseInt(next()); } } }
JAVA
1468_H. K and Medians
Let's denote the median of a sequence s with odd length as the value in the middle of s if we sort s in non-decreasing order. For example, let s = [1, 2, 5, 7, 2, 3, 12]. After sorting, we get sequence [1, 2, 2, \underline{3}, 5, 7, 12], and the median is equal to 3. You have a sequence of n integers [1, 2, ..., n] and an odd integer k. In one step, you choose any k elements from the sequence and erase all chosen elements except their median. These elements do not have to go continuously (gaps are allowed between them). For example, if you have a sequence [1, 2, 3, 4, 5, 6, 7] (i.e. n=7) and k = 3, then the following options for the first step are possible: * choose [1, \underline{2}, 3]; 2 is their median, so it is not erased, and the resulting sequence is [2, 4, 5, 6, 7]; * choose [2, \underline{4}, 6]; 4 is their median, so it is not erased, and the resulting sequence is [1, 3, 4, 5, 7]; * choose [1, \underline{6}, 7]; 6 is their median, so it is not erased, and the resulting sequence is [2, 3, 4, 5, 6]; * and several others. You can do zero or more steps. Can you get a sequence b_1, b_2, ..., b_m after several steps? You'll be given t test cases. Solve each test case independently. 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 three integers n, k, and m (3 ≀ n ≀ 2 β‹… 10^5; 3 ≀ k ≀ n; k is odd; 1 ≀ m < n) β€” the length of the sequence you have, the number of elements you choose in each step and the length of the sequence you'd like to get. The second line of each test case contains m integers b_1, b_2, ..., b_m (1 ≀ b_1 < b_2 < ... < b_m ≀ n) β€” the sequence you'd like to get, given in the ascending order. It's guaranteed that the total sum of n over all test cases doesn't exceed 2 β‹… 10^5. Output For each test case, print YES if you can obtain the sequence b or NO otherwise. You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer). Example Input 4 3 3 1 1 7 3 3 1 5 7 10 5 3 4 5 6 13 7 7 1 3 5 7 9 11 12 Output NO YES NO YES Note In the first test case, you have sequence [1, 2, 3]. Since k = 3 you have only one way to choose k elements β€” it's to choose all elements [1, \underline{2}, 3] with median 2. That's why after erasing all chosen elements except its median you'll get sequence [2]. In other words, there is no way to get sequence b = [1] as the result. In the second test case, you have sequence [1, 2, 3, 4, 5, 6, 7] and one of the optimal strategies is following: 1. choose k = 3 elements [2, \underline{3}, 4] and erase them except its median; you'll get sequence [1, 3, 5, 6, 7]; 2. choose 3 elements [3, \underline{5}, 6] and erase them except its median; you'll get desired sequence [1, 5, 7]; In the fourth test case, you have sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]. You can choose k=7 elements [2, 4, 6, \underline{7}, 8, 10, 13] and erase them except its median to get sequence b.
2
14
#include <bits/stdc++.h> using namespace std; typedef long long ll; int n, k, m; bool check(ll suml, int x, int y, ll sumr) { if (x == 0 || y == 0) return true; int p = (k - 1) >> 1; int c = (y + p - 1) / p * p; if (y + sumr >= c && suml + x - 1 >= c) return true; return false; } signed main() { int T; scanf("%d", &T); while (T--) { scanf("%d %d %d", &n, &k, &m); vector<int> a(m + 2, 0); a[m + 1] = n + 1; for (int i = 1; i <= m; i++) scanf("%d", &a[i]); ll sum = 0; vector<int> b; for (int i = 1; i <= m + 1; i++) { b.push_back(a[i] - a[i - 1] - 1); sum += b.back(); } bool ans = false; if (sum % (k - 1) == 0) { ll suml = 0, sumr = 0; int x, y; for (int i = 0; i < (int)b.size(); i++) { if (suml + b[i] >= (sum >> 1)) { sumr = sum - suml - b[i]; x = (sum >> 1) - suml; y = b[i] - x; break; } suml += b[i]; } if (check(suml, x, y, sumr) || check(sumr, y, x, suml)) ans = true; } puts(ans ? "YES" : "NO"); } }
CPP
1468_H. K and Medians
Let's denote the median of a sequence s with odd length as the value in the middle of s if we sort s in non-decreasing order. For example, let s = [1, 2, 5, 7, 2, 3, 12]. After sorting, we get sequence [1, 2, 2, \underline{3}, 5, 7, 12], and the median is equal to 3. You have a sequence of n integers [1, 2, ..., n] and an odd integer k. In one step, you choose any k elements from the sequence and erase all chosen elements except their median. These elements do not have to go continuously (gaps are allowed between them). For example, if you have a sequence [1, 2, 3, 4, 5, 6, 7] (i.e. n=7) and k = 3, then the following options for the first step are possible: * choose [1, \underline{2}, 3]; 2 is their median, so it is not erased, and the resulting sequence is [2, 4, 5, 6, 7]; * choose [2, \underline{4}, 6]; 4 is their median, so it is not erased, and the resulting sequence is [1, 3, 4, 5, 7]; * choose [1, \underline{6}, 7]; 6 is their median, so it is not erased, and the resulting sequence is [2, 3, 4, 5, 6]; * and several others. You can do zero or more steps. Can you get a sequence b_1, b_2, ..., b_m after several steps? You'll be given t test cases. Solve each test case independently. 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 three integers n, k, and m (3 ≀ n ≀ 2 β‹… 10^5; 3 ≀ k ≀ n; k is odd; 1 ≀ m < n) β€” the length of the sequence you have, the number of elements you choose in each step and the length of the sequence you'd like to get. The second line of each test case contains m integers b_1, b_2, ..., b_m (1 ≀ b_1 < b_2 < ... < b_m ≀ n) β€” the sequence you'd like to get, given in the ascending order. It's guaranteed that the total sum of n over all test cases doesn't exceed 2 β‹… 10^5. Output For each test case, print YES if you can obtain the sequence b or NO otherwise. You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer). Example Input 4 3 3 1 1 7 3 3 1 5 7 10 5 3 4 5 6 13 7 7 1 3 5 7 9 11 12 Output NO YES NO YES Note In the first test case, you have sequence [1, 2, 3]. Since k = 3 you have only one way to choose k elements β€” it's to choose all elements [1, \underline{2}, 3] with median 2. That's why after erasing all chosen elements except its median you'll get sequence [2]. In other words, there is no way to get sequence b = [1] as the result. In the second test case, you have sequence [1, 2, 3, 4, 5, 6, 7] and one of the optimal strategies is following: 1. choose k = 3 elements [2, \underline{3}, 4] and erase them except its median; you'll get sequence [1, 3, 5, 6, 7]; 2. choose 3 elements [3, \underline{5}, 6] and erase them except its median; you'll get desired sequence [1, 5, 7]; In the fourth test case, you have sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]. You can choose k=7 elements [2, 4, 6, \underline{7}, 8, 10, 13] and erase them except its median to get sequence b.
2
14
#include <bits/stdc++.h> using namespace std; const int maxn = 2e5 + 5; int b[maxn]; bool vis[maxn]; void work() { int n, k, m; scanf("%d%d%d", &n, &k, &m); for (int i = 1; i <= n; i++) vis[i] = 0; for (int i = 0; i < m; i++) scanf("%d", b + i), vis[b[i]] = 1; if ((n - m) % (k - 1)) { puts("NO"); return; } int cnt = (k - 1) / 2; int sum = 0; for (int i = 1; i <= n; i++) { if (vis[i] == 0) sum++; else { if (sum >= cnt && (n - m) - sum >= cnt) { puts("YES"); return; } } } puts("NO"); } int main() { int T; scanf("%d", &T); while (T--) work(); }
CPP
1468_H. K and Medians
Let's denote the median of a sequence s with odd length as the value in the middle of s if we sort s in non-decreasing order. For example, let s = [1, 2, 5, 7, 2, 3, 12]. After sorting, we get sequence [1, 2, 2, \underline{3}, 5, 7, 12], and the median is equal to 3. You have a sequence of n integers [1, 2, ..., n] and an odd integer k. In one step, you choose any k elements from the sequence and erase all chosen elements except their median. These elements do not have to go continuously (gaps are allowed between them). For example, if you have a sequence [1, 2, 3, 4, 5, 6, 7] (i.e. n=7) and k = 3, then the following options for the first step are possible: * choose [1, \underline{2}, 3]; 2 is their median, so it is not erased, and the resulting sequence is [2, 4, 5, 6, 7]; * choose [2, \underline{4}, 6]; 4 is their median, so it is not erased, and the resulting sequence is [1, 3, 4, 5, 7]; * choose [1, \underline{6}, 7]; 6 is their median, so it is not erased, and the resulting sequence is [2, 3, 4, 5, 6]; * and several others. You can do zero or more steps. Can you get a sequence b_1, b_2, ..., b_m after several steps? You'll be given t test cases. Solve each test case independently. 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 three integers n, k, and m (3 ≀ n ≀ 2 β‹… 10^5; 3 ≀ k ≀ n; k is odd; 1 ≀ m < n) β€” the length of the sequence you have, the number of elements you choose in each step and the length of the sequence you'd like to get. The second line of each test case contains m integers b_1, b_2, ..., b_m (1 ≀ b_1 < b_2 < ... < b_m ≀ n) β€” the sequence you'd like to get, given in the ascending order. It's guaranteed that the total sum of n over all test cases doesn't exceed 2 β‹… 10^5. Output For each test case, print YES if you can obtain the sequence b or NO otherwise. You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer). Example Input 4 3 3 1 1 7 3 3 1 5 7 10 5 3 4 5 6 13 7 7 1 3 5 7 9 11 12 Output NO YES NO YES Note In the first test case, you have sequence [1, 2, 3]. Since k = 3 you have only one way to choose k elements β€” it's to choose all elements [1, \underline{2}, 3] with median 2. That's why after erasing all chosen elements except its median you'll get sequence [2]. In other words, there is no way to get sequence b = [1] as the result. In the second test case, you have sequence [1, 2, 3, 4, 5, 6, 7] and one of the optimal strategies is following: 1. choose k = 3 elements [2, \underline{3}, 4] and erase them except its median; you'll get sequence [1, 3, 5, 6, 7]; 2. choose 3 elements [3, \underline{5}, 6] and erase them except its median; you'll get desired sequence [1, 5, 7]; In the fourth test case, you have sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]. You can choose k=7 elements [2, 4, 6, \underline{7}, 8, 10, 13] and erase them except its median to get sequence b.
2
14
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskH solver = new TaskH(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class TaskH { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(), k = in.nextInt(), m = in.nextInt(); int[] b = in.readIntArray(m); k /= 2; int pref = 0, old = 1; if ((n - m) % (2 * k) != 0) { out.println("NO"); return; } for (int i = 0; i < m; i++) { pref += b[i] - old; if (pref >= k && pref <= (n - m) - k) { out.println("YES"); return; } old = b[i] + 1; } out.println("NO"); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void println(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } writer.print('\n'); } public void close() { writer.close(); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int[] readIntArray(int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = readInt(); } return array; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String next() { int c; while (isSpaceChar(c = this.read())) { ; } StringBuilder result = new StringBuilder(); result.appendCodePoint(c); while (!isSpaceChar(c = this.read())) { result.appendCodePoint(c); } return result.toString(); } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
JAVA
1468_H. K and Medians
Let's denote the median of a sequence s with odd length as the value in the middle of s if we sort s in non-decreasing order. For example, let s = [1, 2, 5, 7, 2, 3, 12]. After sorting, we get sequence [1, 2, 2, \underline{3}, 5, 7, 12], and the median is equal to 3. You have a sequence of n integers [1, 2, ..., n] and an odd integer k. In one step, you choose any k elements from the sequence and erase all chosen elements except their median. These elements do not have to go continuously (gaps are allowed between them). For example, if you have a sequence [1, 2, 3, 4, 5, 6, 7] (i.e. n=7) and k = 3, then the following options for the first step are possible: * choose [1, \underline{2}, 3]; 2 is their median, so it is not erased, and the resulting sequence is [2, 4, 5, 6, 7]; * choose [2, \underline{4}, 6]; 4 is their median, so it is not erased, and the resulting sequence is [1, 3, 4, 5, 7]; * choose [1, \underline{6}, 7]; 6 is their median, so it is not erased, and the resulting sequence is [2, 3, 4, 5, 6]; * and several others. You can do zero or more steps. Can you get a sequence b_1, b_2, ..., b_m after several steps? You'll be given t test cases. Solve each test case independently. 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 three integers n, k, and m (3 ≀ n ≀ 2 β‹… 10^5; 3 ≀ k ≀ n; k is odd; 1 ≀ m < n) β€” the length of the sequence you have, the number of elements you choose in each step and the length of the sequence you'd like to get. The second line of each test case contains m integers b_1, b_2, ..., b_m (1 ≀ b_1 < b_2 < ... < b_m ≀ n) β€” the sequence you'd like to get, given in the ascending order. It's guaranteed that the total sum of n over all test cases doesn't exceed 2 β‹… 10^5. Output For each test case, print YES if you can obtain the sequence b or NO otherwise. You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer). Example Input 4 3 3 1 1 7 3 3 1 5 7 10 5 3 4 5 6 13 7 7 1 3 5 7 9 11 12 Output NO YES NO YES Note In the first test case, you have sequence [1, 2, 3]. Since k = 3 you have only one way to choose k elements β€” it's to choose all elements [1, \underline{2}, 3] with median 2. That's why after erasing all chosen elements except its median you'll get sequence [2]. In other words, there is no way to get sequence b = [1] as the result. In the second test case, you have sequence [1, 2, 3, 4, 5, 6, 7] and one of the optimal strategies is following: 1. choose k = 3 elements [2, \underline{3}, 4] and erase them except its median; you'll get sequence [1, 3, 5, 6, 7]; 2. choose 3 elements [3, \underline{5}, 6] and erase them except its median; you'll get desired sequence [1, 5, 7]; In the fourth test case, you have sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]. You can choose k=7 elements [2, 4, 6, \underline{7}, 8, 10, 13] and erase them except its median to get sequence b.
2
14
#include <bits/stdc++.h> using namespace std; const int NR = 5e5 + 5; int n, m, c[NR], k, t; signed main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int i; cin >> t; while (t--) { cin >> n >> k >> m; for (i = 1; i <= m; ++i) { cin >> c[i]; } if ( (n-m)%(k-1) ) { cout << "NO\n" ; continue; } int sw =0; for ( i = 1; i <= m ; ++ i ) { if ( c[i]-1-i+1 >= k /2 && n - c [ i ] - (m-i) >= k /2 ) { sw = 1; } } if ( sw ) cout << "YES\n" ; else cout << "NO\n" ; } return 0; }
CPP
1468_H. K and Medians
Let's denote the median of a sequence s with odd length as the value in the middle of s if we sort s in non-decreasing order. For example, let s = [1, 2, 5, 7, 2, 3, 12]. After sorting, we get sequence [1, 2, 2, \underline{3}, 5, 7, 12], and the median is equal to 3. You have a sequence of n integers [1, 2, ..., n] and an odd integer k. In one step, you choose any k elements from the sequence and erase all chosen elements except their median. These elements do not have to go continuously (gaps are allowed between them). For example, if you have a sequence [1, 2, 3, 4, 5, 6, 7] (i.e. n=7) and k = 3, then the following options for the first step are possible: * choose [1, \underline{2}, 3]; 2 is their median, so it is not erased, and the resulting sequence is [2, 4, 5, 6, 7]; * choose [2, \underline{4}, 6]; 4 is their median, so it is not erased, and the resulting sequence is [1, 3, 4, 5, 7]; * choose [1, \underline{6}, 7]; 6 is their median, so it is not erased, and the resulting sequence is [2, 3, 4, 5, 6]; * and several others. You can do zero or more steps. Can you get a sequence b_1, b_2, ..., b_m after several steps? You'll be given t test cases. Solve each test case independently. 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 three integers n, k, and m (3 ≀ n ≀ 2 β‹… 10^5; 3 ≀ k ≀ n; k is odd; 1 ≀ m < n) β€” the length of the sequence you have, the number of elements you choose in each step and the length of the sequence you'd like to get. The second line of each test case contains m integers b_1, b_2, ..., b_m (1 ≀ b_1 < b_2 < ... < b_m ≀ n) β€” the sequence you'd like to get, given in the ascending order. It's guaranteed that the total sum of n over all test cases doesn't exceed 2 β‹… 10^5. Output For each test case, print YES if you can obtain the sequence b or NO otherwise. You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer). Example Input 4 3 3 1 1 7 3 3 1 5 7 10 5 3 4 5 6 13 7 7 1 3 5 7 9 11 12 Output NO YES NO YES Note In the first test case, you have sequence [1, 2, 3]. Since k = 3 you have only one way to choose k elements β€” it's to choose all elements [1, \underline{2}, 3] with median 2. That's why after erasing all chosen elements except its median you'll get sequence [2]. In other words, there is no way to get sequence b = [1] as the result. In the second test case, you have sequence [1, 2, 3, 4, 5, 6, 7] and one of the optimal strategies is following: 1. choose k = 3 elements [2, \underline{3}, 4] and erase them except its median; you'll get sequence [1, 3, 5, 6, 7]; 2. choose 3 elements [3, \underline{5}, 6] and erase them except its median; you'll get desired sequence [1, 5, 7]; In the fourth test case, you have sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]. You can choose k=7 elements [2, 4, 6, \underline{7}, 8, 10, 13] and erase them except its median to get sequence b.
2
14
#include<bits/stdc++.h> #ifdef miaojie #define dbg(args...) do {cout << #args << " : "; err(args);} while (0) void err() {std::cout << std::endl;} template<typename T, typename...Args> void err(T a, Args...args){std::cout << a << ' '; err(args...);} #else #define dbg(...) #endif using namespace std; using ll = long long; const int maxn = 2e5 + 20; int T, n, k, m; int b[maxn], vis[maxn]; vector<int>ve; int main() { scanf("%d", &T); while(T--) { scanf("%d%d%d", &n, &k, &m); ve.clear(); for (int i = 1; i <= n; i++) { vis[i] = 0; } for (int i = 1; i <= m; i++) { scanf("%d", b + i); vis[b[i]] = 1; } for (int i = 1; i <= n; i++) { if(!vis[i]) { ve.push_back(i); } } int siz = ve.size(); if(siz % (k - 1) != 0) puts("NO"); else { bool flag = 0; for (int i = (k - 2) / 2; i <= siz - (k - 2) / 2 - 2; i++) { // dbg(i); if(ve[i] != ve[i + 1] - 1) flag = 1; } if(flag) puts("YES"); else puts("NO"); } } return 0; }
CPP
1468_H. K and Medians
Let's denote the median of a sequence s with odd length as the value in the middle of s if we sort s in non-decreasing order. For example, let s = [1, 2, 5, 7, 2, 3, 12]. After sorting, we get sequence [1, 2, 2, \underline{3}, 5, 7, 12], and the median is equal to 3. You have a sequence of n integers [1, 2, ..., n] and an odd integer k. In one step, you choose any k elements from the sequence and erase all chosen elements except their median. These elements do not have to go continuously (gaps are allowed between them). For example, if you have a sequence [1, 2, 3, 4, 5, 6, 7] (i.e. n=7) and k = 3, then the following options for the first step are possible: * choose [1, \underline{2}, 3]; 2 is their median, so it is not erased, and the resulting sequence is [2, 4, 5, 6, 7]; * choose [2, \underline{4}, 6]; 4 is their median, so it is not erased, and the resulting sequence is [1, 3, 4, 5, 7]; * choose [1, \underline{6}, 7]; 6 is their median, so it is not erased, and the resulting sequence is [2, 3, 4, 5, 6]; * and several others. You can do zero or more steps. Can you get a sequence b_1, b_2, ..., b_m after several steps? You'll be given t test cases. Solve each test case independently. 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 three integers n, k, and m (3 ≀ n ≀ 2 β‹… 10^5; 3 ≀ k ≀ n; k is odd; 1 ≀ m < n) β€” the length of the sequence you have, the number of elements you choose in each step and the length of the sequence you'd like to get. The second line of each test case contains m integers b_1, b_2, ..., b_m (1 ≀ b_1 < b_2 < ... < b_m ≀ n) β€” the sequence you'd like to get, given in the ascending order. It's guaranteed that the total sum of n over all test cases doesn't exceed 2 β‹… 10^5. Output For each test case, print YES if you can obtain the sequence b or NO otherwise. You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer). Example Input 4 3 3 1 1 7 3 3 1 5 7 10 5 3 4 5 6 13 7 7 1 3 5 7 9 11 12 Output NO YES NO YES Note In the first test case, you have sequence [1, 2, 3]. Since k = 3 you have only one way to choose k elements β€” it's to choose all elements [1, \underline{2}, 3] with median 2. That's why after erasing all chosen elements except its median you'll get sequence [2]. In other words, there is no way to get sequence b = [1] as the result. In the second test case, you have sequence [1, 2, 3, 4, 5, 6, 7] and one of the optimal strategies is following: 1. choose k = 3 elements [2, \underline{3}, 4] and erase them except its median; you'll get sequence [1, 3, 5, 6, 7]; 2. choose 3 elements [3, \underline{5}, 6] and erase them except its median; you'll get desired sequence [1, 5, 7]; In the fourth test case, you have sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]. You can choose k=7 elements [2, 4, 6, \underline{7}, 8, 10, 13] and erase them except its median to get sequence b.
2
14
#include <bits/stdc++.h> using namespace std; #define ll long long #define pii pair<int, int> #define pll pair<long long, long long> #define pb push_back #define ff first #define ss second #define YES printf("YES\n") #define NO printf("NO\n") #define nn "\n" #define sci(x) scanf("%d", &x) #define LL_INF (1LL << 62) #define INF (1 << 30) #define SetBit(x, k) (x |= (1LL << k)) #define ClearBit(x, k) (x &= ~(1LL << k)) #define CheckBit(x, k) (x & (1LL << k)) #define mod 1000000007 #define N 200005 int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int t; cin >> t; while(t--){ vector<int> v; ll sum = 0; int n, k, m; cin >> n >> k >> m; int prev = 0; for(int i = 0; i < m; i++){ int x; cin >> x; int z = (x-prev)-1; prev = x; if(z){ v.pb(z); sum += z; } } int z = n-prev; if(z){ v.pb(z); sum += z; } // for(int i = 0; i < v.size(); i++){ // cout << v[i] << "*"; // } // cout << nn; int l = 0; int s = k/2; for(int i = 0; i < v.size(); i++){ if(v[i]>=s){ l = i; break; } else s -= v[i]; } int r = 0; s = k/2; for(int i = v.size()-1; i >= 0; i--){ if(v[i]>=s){ r = i; break; } else s -= v[i]; } if(sum%(k-1)!=0) cout << "NO\n"; else if(sum==0 || r>l) cout << "YES\n"; else cout << "NO\n"; } return 0; }
CPP
1468_H. K and Medians
Let's denote the median of a sequence s with odd length as the value in the middle of s if we sort s in non-decreasing order. For example, let s = [1, 2, 5, 7, 2, 3, 12]. After sorting, we get sequence [1, 2, 2, \underline{3}, 5, 7, 12], and the median is equal to 3. You have a sequence of n integers [1, 2, ..., n] and an odd integer k. In one step, you choose any k elements from the sequence and erase all chosen elements except their median. These elements do not have to go continuously (gaps are allowed between them). For example, if you have a sequence [1, 2, 3, 4, 5, 6, 7] (i.e. n=7) and k = 3, then the following options for the first step are possible: * choose [1, \underline{2}, 3]; 2 is their median, so it is not erased, and the resulting sequence is [2, 4, 5, 6, 7]; * choose [2, \underline{4}, 6]; 4 is their median, so it is not erased, and the resulting sequence is [1, 3, 4, 5, 7]; * choose [1, \underline{6}, 7]; 6 is their median, so it is not erased, and the resulting sequence is [2, 3, 4, 5, 6]; * and several others. You can do zero or more steps. Can you get a sequence b_1, b_2, ..., b_m after several steps? You'll be given t test cases. Solve each test case independently. 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 three integers n, k, and m (3 ≀ n ≀ 2 β‹… 10^5; 3 ≀ k ≀ n; k is odd; 1 ≀ m < n) β€” the length of the sequence you have, the number of elements you choose in each step and the length of the sequence you'd like to get. The second line of each test case contains m integers b_1, b_2, ..., b_m (1 ≀ b_1 < b_2 < ... < b_m ≀ n) β€” the sequence you'd like to get, given in the ascending order. It's guaranteed that the total sum of n over all test cases doesn't exceed 2 β‹… 10^5. Output For each test case, print YES if you can obtain the sequence b or NO otherwise. You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer). Example Input 4 3 3 1 1 7 3 3 1 5 7 10 5 3 4 5 6 13 7 7 1 3 5 7 9 11 12 Output NO YES NO YES Note In the first test case, you have sequence [1, 2, 3]. Since k = 3 you have only one way to choose k elements β€” it's to choose all elements [1, \underline{2}, 3] with median 2. That's why after erasing all chosen elements except its median you'll get sequence [2]. In other words, there is no way to get sequence b = [1] as the result. In the second test case, you have sequence [1, 2, 3, 4, 5, 6, 7] and one of the optimal strategies is following: 1. choose k = 3 elements [2, \underline{3}, 4] and erase them except its median; you'll get sequence [1, 3, 5, 6, 7]; 2. choose 3 elements [3, \underline{5}, 6] and erase them except its median; you'll get desired sequence [1, 5, 7]; In the fourth test case, you have sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]. You can choose k=7 elements [2, 4, 6, \underline{7}, 8, 10, 13] and erase them except its median to get sequence b.
2
14
//package com.company; import java.io.*; import java.math.*; import java.util.*; public class Main { public static class Task { public void solve(Scanner sc, PrintWriter pw) throws IOException { int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int k = sc.nextInt(); int m = sc.nextInt(); int[] bx = new int[n + 1]; Arrays.fill(bx, 1); for (int i = 0; i < m; i++) { bx[sc.nextInt()] = 0; } if ((n - m) % (k - 1) != 0) { pw.println("NO"); } else { int totalBlocks = (n - m) / ((k - 1) / 2); int c = 0; int nB = 0; boolean good = false; for (int i = 1; i <= n; i++) { if (bx[i] == 1) { c++; if (c == k / 2) { c = 0; nB++; } } else { if (nB == 0) continue; if (nB == totalBlocks - 1 && c > 0) continue; if (nB == totalBlocks) continue; good = true; } } pw.println(good ? "YES": "NO"); } } } } static long TIME_START, TIME_END; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); // Scanner sc = new Scanner(new FileInputStream("in.txt")); PrintWriter pw = new PrintWriter(new BufferedOutputStream(System.out)); //output // PrintWriter pw = new PrintWriter(new FileOutputStream("out.txt")); Runtime runtime = Runtime.getRuntime(); long usedMemoryBefore = runtime.totalMemory() - runtime.freeMemory(); TIME_START = System.currentTimeMillis(); Task t = new Task(); t.solve(sc, pw); TIME_END = System.currentTimeMillis(); long usedMemoryAfter = runtime.totalMemory() - runtime.freeMemory(); pw.close(); System.err.println("Memory increased: " + (usedMemoryAfter - usedMemoryBefore) / 1000000); System.err.println("Time used: " + (TIME_END - TIME_START) + "."); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader s) throws FileNotFoundException { br = new BufferedReader(s); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException { return br.ready(); } } }
JAVA
1468_H. K and Medians
Let's denote the median of a sequence s with odd length as the value in the middle of s if we sort s in non-decreasing order. For example, let s = [1, 2, 5, 7, 2, 3, 12]. After sorting, we get sequence [1, 2, 2, \underline{3}, 5, 7, 12], and the median is equal to 3. You have a sequence of n integers [1, 2, ..., n] and an odd integer k. In one step, you choose any k elements from the sequence and erase all chosen elements except their median. These elements do not have to go continuously (gaps are allowed between them). For example, if you have a sequence [1, 2, 3, 4, 5, 6, 7] (i.e. n=7) and k = 3, then the following options for the first step are possible: * choose [1, \underline{2}, 3]; 2 is their median, so it is not erased, and the resulting sequence is [2, 4, 5, 6, 7]; * choose [2, \underline{4}, 6]; 4 is their median, so it is not erased, and the resulting sequence is [1, 3, 4, 5, 7]; * choose [1, \underline{6}, 7]; 6 is their median, so it is not erased, and the resulting sequence is [2, 3, 4, 5, 6]; * and several others. You can do zero or more steps. Can you get a sequence b_1, b_2, ..., b_m after several steps? You'll be given t test cases. Solve each test case independently. 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 three integers n, k, and m (3 ≀ n ≀ 2 β‹… 10^5; 3 ≀ k ≀ n; k is odd; 1 ≀ m < n) β€” the length of the sequence you have, the number of elements you choose in each step and the length of the sequence you'd like to get. The second line of each test case contains m integers b_1, b_2, ..., b_m (1 ≀ b_1 < b_2 < ... < b_m ≀ n) β€” the sequence you'd like to get, given in the ascending order. It's guaranteed that the total sum of n over all test cases doesn't exceed 2 β‹… 10^5. Output For each test case, print YES if you can obtain the sequence b or NO otherwise. You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer). Example Input 4 3 3 1 1 7 3 3 1 5 7 10 5 3 4 5 6 13 7 7 1 3 5 7 9 11 12 Output NO YES NO YES Note In the first test case, you have sequence [1, 2, 3]. Since k = 3 you have only one way to choose k elements β€” it's to choose all elements [1, \underline{2}, 3] with median 2. That's why after erasing all chosen elements except its median you'll get sequence [2]. In other words, there is no way to get sequence b = [1] as the result. In the second test case, you have sequence [1, 2, 3, 4, 5, 6, 7] and one of the optimal strategies is following: 1. choose k = 3 elements [2, \underline{3}, 4] and erase them except its median; you'll get sequence [1, 3, 5, 6, 7]; 2. choose 3 elements [3, \underline{5}, 6] and erase them except its median; you'll get desired sequence [1, 5, 7]; In the fourth test case, you have sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]. You can choose k=7 elements [2, 4, 6, \underline{7}, 8, 10, 13] and erase them except its median to get sequence b.
2
14
// main.cpp // ervb // // Created by Kanak Gautam on 21/04/20. // Copyright Β© 2020 Kanak Gautam. All rights reserved. // #include <iostream> #include <cstdio> #include <stdio.h> #include <cstdlib> #include <algorithm> #include <cmath> #include <vector> #include <set> #include <stack> #include <map> #include <unordered_set> #include <unordered_map> #include <queue> #include <ctime> #include <cassert> #include <complex> #include <string> #include <cstring> #include <utility> #define pb push_back #define mk make_pair #define endl "\n" #define mod 1000000009 #define mod1 13141702292180207 #define hashingmul 207 #define PI 3.14159265358979323846264 using namespace std; typedef long long int lli; typedef long double ld; typedef pair<lli,lli> ii; //priority_queue <lli, vector<lli>, greater<lli> > ti; //priority_queue<pair<lli,pair<lli,lli>>>e; vector <lli> p[300005],g(200005),f(2000005),lazy(2000005,0),a(500005,1); //vector<vector<lli>> d(300005,vector<lli>(18,0)); //vector<pair<lli,ii>>p[300005]; map<pair<lli,lli>,lli>mp; //vector<pair<pair<lli, lli>,lli> > st; //map<lli,lli> np; //queue<lli> qy; lli gcd(lli a, lli b) { if (b == 0) return a; return gcd(b, a % b); } lli bpow(lli a, lli b) { lli res = 1; while (b > 0) { if (b & 1) res = (res * a)%mod; a = (a * a)%mod; b >>= 1; } return res%mod; } void fact(lli i) { f[0]=1; for(lli k=1;k<=i;k++) { (f[k]=f[k-1]*k)%=mod; } } lli isprime(lli n) { if(n==1) return 0; for(lli i=2;i<=sqrt(n);i++) if(n%i==0) return 0; return 1; } lli find(lli x) { if(f[x]==x) return x; else return f[x]=find(f[x]); } bool cmp(lli x,lli y) { return x<y; } lli comb(lli i,lli j) { if(j>i)return 0; lli k=f[i]; lli g=(f[j]*(f[i-j]))%mod; lli h=bpow(g,mod-2); return (k*h)%mod; } /*void sieve() { for(lli i=2;i<=sqrt(10000000);i++) { if(b[i]==0) { k.pb(i); for(lli j=2;i*j<=sqrt(10000000);j++) { b[i*j]=1; } } } }*/ int main () { ios_base::sync_with_stdio(false); cin.tie(NULL);cout.tie(NULL); lli t;cin>>t; while(t--) { lli n,k,m; cin>>n>>k>>m; vector<lli> a(n+1,0); lli x; set<lli>s; vector<lli> v,g; for(lli i=0;i<m;i++) { cin>>x; a[x]=1; } if((n-m)%(k-1)) { cout<<"NO"<<endl;continue; } lli sum=0,f=0; for(lli i=1;i<=n;i++) { if(!a[i])sum++; else { if(sum>=(k-1)/2 && (n-m-sum)>=(k-1)/2) { cout<<"YES"<<endl; f=1;break; } } } if(!f)cout<<"NO"<<endl; } }
CPP
1468_H. K and Medians
Let's denote the median of a sequence s with odd length as the value in the middle of s if we sort s in non-decreasing order. For example, let s = [1, 2, 5, 7, 2, 3, 12]. After sorting, we get sequence [1, 2, 2, \underline{3}, 5, 7, 12], and the median is equal to 3. You have a sequence of n integers [1, 2, ..., n] and an odd integer k. In one step, you choose any k elements from the sequence and erase all chosen elements except their median. These elements do not have to go continuously (gaps are allowed between them). For example, if you have a sequence [1, 2, 3, 4, 5, 6, 7] (i.e. n=7) and k = 3, then the following options for the first step are possible: * choose [1, \underline{2}, 3]; 2 is their median, so it is not erased, and the resulting sequence is [2, 4, 5, 6, 7]; * choose [2, \underline{4}, 6]; 4 is their median, so it is not erased, and the resulting sequence is [1, 3, 4, 5, 7]; * choose [1, \underline{6}, 7]; 6 is their median, so it is not erased, and the resulting sequence is [2, 3, 4, 5, 6]; * and several others. You can do zero or more steps. Can you get a sequence b_1, b_2, ..., b_m after several steps? You'll be given t test cases. Solve each test case independently. 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 three integers n, k, and m (3 ≀ n ≀ 2 β‹… 10^5; 3 ≀ k ≀ n; k is odd; 1 ≀ m < n) β€” the length of the sequence you have, the number of elements you choose in each step and the length of the sequence you'd like to get. The second line of each test case contains m integers b_1, b_2, ..., b_m (1 ≀ b_1 < b_2 < ... < b_m ≀ n) β€” the sequence you'd like to get, given in the ascending order. It's guaranteed that the total sum of n over all test cases doesn't exceed 2 β‹… 10^5. Output For each test case, print YES if you can obtain the sequence b or NO otherwise. You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer). Example Input 4 3 3 1 1 7 3 3 1 5 7 10 5 3 4 5 6 13 7 7 1 3 5 7 9 11 12 Output NO YES NO YES Note In the first test case, you have sequence [1, 2, 3]. Since k = 3 you have only one way to choose k elements β€” it's to choose all elements [1, \underline{2}, 3] with median 2. That's why after erasing all chosen elements except its median you'll get sequence [2]. In other words, there is no way to get sequence b = [1] as the result. In the second test case, you have sequence [1, 2, 3, 4, 5, 6, 7] and one of the optimal strategies is following: 1. choose k = 3 elements [2, \underline{3}, 4] and erase them except its median; you'll get sequence [1, 3, 5, 6, 7]; 2. choose 3 elements [3, \underline{5}, 6] and erase them except its median; you'll get desired sequence [1, 5, 7]; In the fourth test case, you have sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]. You can choose k=7 elements [2, 4, 6, \underline{7}, 8, 10, 13] and erase them except its median to get sequence b.
2
14
import java.io.*; import java.util.*; import java.util.Map.Entry; public class D { FastScanner in; PrintWriter out; boolean systemIO = true; public class Pair implements Comparable<Pair> { int x; int y; public Pair(int x, int y) { this.x = x; this.y = y; } public Pair clone() { return new Pair(x, y); } @Override public int compareTo(Pair o) { if (x > o.x) { return 1; } if (x < o.x) { return -1; } if (y > o.y) { return 1; } if (y < o.y) { return -1; } return 0; } } public class Fenvik { int[] sum; public Fenvik(int n) { sum = new int[n]; } public void add(int x, int d) { for (int i = x; i < sum.length; i = (i | (i + 1))) { sum[i] += d; } } public int sum(int r) { int ans = 0; for (int i = r; i >= 0; i = (i & (i + 1)) - 1) { ans += sum[i]; } return ans; } public int sum(int l, int r) { if (l > r) { return 0; } return sum(r) - sum(l - 1); } } public class FenvikMax { int[] max; public FenvikMax(int n) { max = new int[n]; } public void add(int x, int d) { for (int i = x; i < max.length; i = (i | (i + 1))) { if (d > max[i]) { max[i] = d; } } } public int max(int r) { int ans = -1; for (int i = r; i >= 0; i = (i & (i + 1)) - 1) { if (max[i] > ans) { ans = max[i]; } } return ans; } } public class SegmentTree { int pow; long[] min; public SegmentTree(long[] a) { pow = 1; while (pow < a.length) { pow *= 2; } min = new long[2 * pow]; for (int i = 0; i < a.length; i++) { min[pow + i] = a[i]; } for (int i = a.length; i < pow; i++) { min[pow + i] = Long.MAX_VALUE / 2; } for (int i = pow - 1; i > 0; i--) { min[i] = f(min[2 * i + 1], min[2 * i + 1]); } } public long get(int l, int r) { return get(1, 0, pow, l, r); } private long get(int v, int tl, int tr, int l, int r) { if (l >= tr || r <= tl) { return Long.MAX_VALUE / 2; } if (l <= tl && r >= tr) { return min[v]; } int tm = (tl + tr) / 2; return f(get(2 * v, tl, tm, l, r), get(2 * v + 1, tm, tr, l, r)); } public void set(int x, long value) { set(1, 0, pow, x, value); } private void set(int v, int tl, int tr, int x, long value) { if (x >= tr || x < tl) { return; } if (v >= pow) { min[v] = value; return; } int tm = (tl + tr) / 2; set(2 * v, tl, tm, x, value); set(2 * v + 1, tm, tr, x, value); min[v] = f(min[2 * v], min[2 * v + 1]); } public long f(long a, long b) { return Math.min(a, b); } } public long gcd(long x, long y) { if (y == 0) { return x; } if (x == 0) { return y; } return gcd(y, x % y); } public long[][] pow(long[][] x, long p) { if (p == 0) { long[][] ans = new long[x.length][x.length]; for (int i = 0; i < ans.length; i++) { ans[i][i] = 1; } return ans; } long[][] t = pow(x, p / 2); t = multiply(t, t); if (p % 2 == 1) { t = multiply(t, x); } return t; } public long[][] multiply(long[][] a, long[][] b) { long[][] ans = new long[a.length][b[0].length]; for (int i = 0; i < ans.length; i++) { for (int j = 0; j < ans[0].length; j++) { for (int k = 0; k < b.length; k++) { ans[i][j] += a[i][k] * b[k][j]; ans[i][j] %= mod; } } } return ans; } public long pow(long x, long p) { if (p == 0) { return 1; } long t = pow(x, p / 2); t *= t; t %= mod; if (p % 2 == 1) { t *= x; t %= mod; } return t; } public long modInv(long x) { return pow(x, mod - 2); } long mod = 1000000007; public class VectorInt { long x; long y; public VectorInt(long x, long y) { this.x = x; this.y = y; } public VectorInt subtract(VectorInt v) { return new VectorInt(x - v.x, y - v.y); } public double norm() { return Math.sqrt(x * x + y * y); } } public class VectorDouble { double x; double y; public VectorDouble(double x, double y) { this.x = x; this.y = y; } public VectorDouble(VectorInt v) { x = v.x; y = v.y; } public String toString() { return x + " " + y; } public VectorDouble add(VectorDouble v) { return new VectorDouble(x + v.x, y + v.y); } public VectorDouble subtract(VectorDouble v) { return new VectorDouble(x - v.x, y - v.y); } public VectorDouble mult(double c) { return new VectorDouble(x * c, y * c); } public double norm() { return Math.sqrt(x * x + y * y); } public double norm2() { return x * x + y * y; } public void normalize() { double n = norm(); x /= n; y /= n; } } public long dp(VectorInt a, VectorInt b) { return a.x * b.x + a.y * b.y; } public long cp(VectorInt a, VectorInt b) { return a.x * b.y - a.y * b.x; } public double dp(VectorDouble a, VectorDouble b) { return a.x * b.x + a.y * b.y; } public double cp(VectorDouble a, VectorDouble b) { return a.x * b.y - a.y * b.x; } Random random = new Random(566); public class Fret implements Comparable<Fret> { int value; int index; public Fret(int value, int index) { this.value = value; this.index = index; } @Override public int compareTo(Fret o) { if (value != o.value) { return value - o.value; } return index - o.index; } } public int[][] readGraph(int n, int m) { int[][] to = new int[n][]; int[] sz = new int[n]; int[] x = new int[m]; int[] y = new int[m]; for (int i = 0; i < m; i++) { x[i] = in.nextInt() - 1; y[i] = in.nextInt() - 1; sz[x[i]]++; sz[y[i]]++; } for (int i = 0; i < to.length; i++) { to[i] = new int[sz[i]]; sz[i] = 0; } for (int i = 0; i < x.length; i++) { to[x[i]][sz[x[i]]++] = y[i]; to[y[i]][sz[y[i]]++] = x[i]; } return to; } public double volume(double x0, double y0, double dxdz, double dydz, double dz) { return x0 * y0 * dz - (dxdz * y0 + dydz * x0) * dz * dz / 2 + dxdz * dydz * dz * dz * dz / 3; } public class Vector { double x; double y; double z; public Vector(double x, double y, double z) { this.x = x; this.y = y; this.z = z; } public double norm() { return Math.sqrt(x * x + y * y + z * z); } public double norm2() { return x * x + y * y + z * z; } public Vector subtract(Vector v) { return new Vector(x - v.x, y - v.y, z - v.z); } } public Vector cp(Vector a, Vector b) { return new Vector(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x); } public double sin(Vector a, Vector b) { return cp(a, b).norm() / a.norm() / b.norm(); } public double dp(Vector a, Vector b) { return a.x * b.x + a.y * b.y + a.z * b.z; } public double cos(Vector a, Vector b) { return dp(a, b) / a.norm() / b.norm(); } double eps = 1e-9; int[] mult(int[] a, int[] b) { int[] res = new int[a.length]; for (int i = 0; i < a.length; ++i) { res[i] = b[a[i]]; } return res; } int[] rev(int[] a) { int[] res = new int[a.length]; for (int i = 0; i < a.length; ++i) { res[a[i]] = i; } return res; } int[] conj(int[] pi, int[] f) { return mult(mult(rev(pi), f), pi); } void print(int[] p) { for (int i : p) { System.out.print(i + 1 + " "); } System.out.println(); } public class Triangle implements Comparable<Triangle> { Pair p1; Pair p2; public Triangle(Pair p1, Pair p2) { this.p1 = p1.clone(); this.p2 = p2.clone(); if (p1.compareTo(p2) > 0) { Pair p = p1; this.p1 = p2; this.p2 = p; } } @Override public int compareTo(Triangle o) { if (p1.compareTo(o.p1) != 0) { return p1.compareTo(o.p1); } return p2.compareTo(o.p2); } } public class Color implements Comparable<Color> { int a; int b; public Color(int a, int b) { this.a = a; this.b = b; } public int day() { return a - b + 1; } @Override public int compareTo(Color o) { if (b == 0 && o.b == 0) { return 0; } if (b == 0) { return 1; } if (o.b == 0) { return -1; } return day() - o.day(); } } public void solve() { f : for (int qwerty = in.nextInt(); qwerty > 0; qwerty--) { int n = in.nextInt(); int k = in.nextInt(); int m = in.nextInt(); boolean[] alive = new boolean[n]; for (int i = 0; i < m; i++) { alive[in.nextInt() - 1] = true; } if ((n - m) % (k - 1) != 0) { out.println("NO"); continue; } int cur = 0; int l = 0; for (int i = 0; i < alive.length; i++) { if (!alive[i]) { cur++; if (cur == k / 2) { l = i; break; } } } cur = 0; int r = n; for (int i = n - 1; i >= 0; i--) { if (!alive[i]) { cur++; if (cur == k / 2) { r = i; break; } } } for (int i = l + 1; i < r; i++) { if (alive[i]) { out.println("YES"); continue f; } } out.println("NO"); } } public void run() { try { if (systemIO) { in = new FastScanner(System.in); out = new PrintWriter(System.out); } else { in = new FastScanner(new File("input.txt")); out = new PrintWriter(new File("output.txt")); } solve(); out.close(); } catch (IOException e) { e.printStackTrace(); } } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } String nextLine() { try { return br.readLine(); } catch (IOException e) { return null; } } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA public static void main(String[] arg) { long time = System.currentTimeMillis(); new D().run(); // System.err.println(System.currentTimeMillis() - time); } }
JAVA
1468_H. K and Medians
Let's denote the median of a sequence s with odd length as the value in the middle of s if we sort s in non-decreasing order. For example, let s = [1, 2, 5, 7, 2, 3, 12]. After sorting, we get sequence [1, 2, 2, \underline{3}, 5, 7, 12], and the median is equal to 3. You have a sequence of n integers [1, 2, ..., n] and an odd integer k. In one step, you choose any k elements from the sequence and erase all chosen elements except their median. These elements do not have to go continuously (gaps are allowed between them). For example, if you have a sequence [1, 2, 3, 4, 5, 6, 7] (i.e. n=7) and k = 3, then the following options for the first step are possible: * choose [1, \underline{2}, 3]; 2 is their median, so it is not erased, and the resulting sequence is [2, 4, 5, 6, 7]; * choose [2, \underline{4}, 6]; 4 is their median, so it is not erased, and the resulting sequence is [1, 3, 4, 5, 7]; * choose [1, \underline{6}, 7]; 6 is their median, so it is not erased, and the resulting sequence is [2, 3, 4, 5, 6]; * and several others. You can do zero or more steps. Can you get a sequence b_1, b_2, ..., b_m after several steps? You'll be given t test cases. Solve each test case independently. 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 three integers n, k, and m (3 ≀ n ≀ 2 β‹… 10^5; 3 ≀ k ≀ n; k is odd; 1 ≀ m < n) β€” the length of the sequence you have, the number of elements you choose in each step and the length of the sequence you'd like to get. The second line of each test case contains m integers b_1, b_2, ..., b_m (1 ≀ b_1 < b_2 < ... < b_m ≀ n) β€” the sequence you'd like to get, given in the ascending order. It's guaranteed that the total sum of n over all test cases doesn't exceed 2 β‹… 10^5. Output For each test case, print YES if you can obtain the sequence b or NO otherwise. You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer). Example Input 4 3 3 1 1 7 3 3 1 5 7 10 5 3 4 5 6 13 7 7 1 3 5 7 9 11 12 Output NO YES NO YES Note In the first test case, you have sequence [1, 2, 3]. Since k = 3 you have only one way to choose k elements β€” it's to choose all elements [1, \underline{2}, 3] with median 2. That's why after erasing all chosen elements except its median you'll get sequence [2]. In other words, there is no way to get sequence b = [1] as the result. In the second test case, you have sequence [1, 2, 3, 4, 5, 6, 7] and one of the optimal strategies is following: 1. choose k = 3 elements [2, \underline{3}, 4] and erase them except its median; you'll get sequence [1, 3, 5, 6, 7]; 2. choose 3 elements [3, \underline{5}, 6] and erase them except its median; you'll get desired sequence [1, 5, 7]; In the fourth test case, you have sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]. You can choose k=7 elements [2, 4, 6, \underline{7}, 8, 10, 13] and erase them except its median to get sequence b.
2
14
import sys for _ in range(int(sys.stdin.readline().strip())): n,k,m=tuple(map(int,sys.stdin.readline().strip().split(" "))) ml=set(map(int,sys.stdin.readline().strip().split(" "))) havitada=[] for i in range(1,n+1): if i not in ml: havitada.append(i) saab=False if len(havitada)%(k-1)!=0: print("no") continue for i in range(k//2-1,len(havitada)-k//2): if havitada[i+1]-havitada[i]!=1: print("yes") break else: print("no")
PYTHON3
1468_H. K and Medians
Let's denote the median of a sequence s with odd length as the value in the middle of s if we sort s in non-decreasing order. For example, let s = [1, 2, 5, 7, 2, 3, 12]. After sorting, we get sequence [1, 2, 2, \underline{3}, 5, 7, 12], and the median is equal to 3. You have a sequence of n integers [1, 2, ..., n] and an odd integer k. In one step, you choose any k elements from the sequence and erase all chosen elements except their median. These elements do not have to go continuously (gaps are allowed between them). For example, if you have a sequence [1, 2, 3, 4, 5, 6, 7] (i.e. n=7) and k = 3, then the following options for the first step are possible: * choose [1, \underline{2}, 3]; 2 is their median, so it is not erased, and the resulting sequence is [2, 4, 5, 6, 7]; * choose [2, \underline{4}, 6]; 4 is their median, so it is not erased, and the resulting sequence is [1, 3, 4, 5, 7]; * choose [1, \underline{6}, 7]; 6 is their median, so it is not erased, and the resulting sequence is [2, 3, 4, 5, 6]; * and several others. You can do zero or more steps. Can you get a sequence b_1, b_2, ..., b_m after several steps? You'll be given t test cases. Solve each test case independently. 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 three integers n, k, and m (3 ≀ n ≀ 2 β‹… 10^5; 3 ≀ k ≀ n; k is odd; 1 ≀ m < n) β€” the length of the sequence you have, the number of elements you choose in each step and the length of the sequence you'd like to get. The second line of each test case contains m integers b_1, b_2, ..., b_m (1 ≀ b_1 < b_2 < ... < b_m ≀ n) β€” the sequence you'd like to get, given in the ascending order. It's guaranteed that the total sum of n over all test cases doesn't exceed 2 β‹… 10^5. Output For each test case, print YES if you can obtain the sequence b or NO otherwise. You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer). Example Input 4 3 3 1 1 7 3 3 1 5 7 10 5 3 4 5 6 13 7 7 1 3 5 7 9 11 12 Output NO YES NO YES Note In the first test case, you have sequence [1, 2, 3]. Since k = 3 you have only one way to choose k elements β€” it's to choose all elements [1, \underline{2}, 3] with median 2. That's why after erasing all chosen elements except its median you'll get sequence [2]. In other words, there is no way to get sequence b = [1] as the result. In the second test case, you have sequence [1, 2, 3, 4, 5, 6, 7] and one of the optimal strategies is following: 1. choose k = 3 elements [2, \underline{3}, 4] and erase them except its median; you'll get sequence [1, 3, 5, 6, 7]; 2. choose 3 elements [3, \underline{5}, 6] and erase them except its median; you'll get desired sequence [1, 5, 7]; In the fourth test case, you have sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]. You can choose k=7 elements [2, 4, 6, \underline{7}, 8, 10, 13] and erase them except its median to get sequence b.
2
14
import sys input = sys.stdin.readline for _ in range(int(input())): n, k, m = map(int, input().split()) B = list(map(int, input().split())) if (n - m) % (k - 1): print("NO") else: p = (k - 1) // 2 left, right = [0] * m, [0] * m for i, b in enumerate(B, 1): left[i - 1] = b - i for i, b in enumerate(B[::-1], 1): right[m - i] = n - i + 1 - b for i in range(m): if left[i] >= p and right[i] >= p: print("YES") break else: print("NO")
PYTHON3
1468_H. K and Medians
Let's denote the median of a sequence s with odd length as the value in the middle of s if we sort s in non-decreasing order. For example, let s = [1, 2, 5, 7, 2, 3, 12]. After sorting, we get sequence [1, 2, 2, \underline{3}, 5, 7, 12], and the median is equal to 3. You have a sequence of n integers [1, 2, ..., n] and an odd integer k. In one step, you choose any k elements from the sequence and erase all chosen elements except their median. These elements do not have to go continuously (gaps are allowed between them). For example, if you have a sequence [1, 2, 3, 4, 5, 6, 7] (i.e. n=7) and k = 3, then the following options for the first step are possible: * choose [1, \underline{2}, 3]; 2 is their median, so it is not erased, and the resulting sequence is [2, 4, 5, 6, 7]; * choose [2, \underline{4}, 6]; 4 is their median, so it is not erased, and the resulting sequence is [1, 3, 4, 5, 7]; * choose [1, \underline{6}, 7]; 6 is their median, so it is not erased, and the resulting sequence is [2, 3, 4, 5, 6]; * and several others. You can do zero or more steps. Can you get a sequence b_1, b_2, ..., b_m after several steps? You'll be given t test cases. Solve each test case independently. 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 three integers n, k, and m (3 ≀ n ≀ 2 β‹… 10^5; 3 ≀ k ≀ n; k is odd; 1 ≀ m < n) β€” the length of the sequence you have, the number of elements you choose in each step and the length of the sequence you'd like to get. The second line of each test case contains m integers b_1, b_2, ..., b_m (1 ≀ b_1 < b_2 < ... < b_m ≀ n) β€” the sequence you'd like to get, given in the ascending order. It's guaranteed that the total sum of n over all test cases doesn't exceed 2 β‹… 10^5. Output For each test case, print YES if you can obtain the sequence b or NO otherwise. You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer). Example Input 4 3 3 1 1 7 3 3 1 5 7 10 5 3 4 5 6 13 7 7 1 3 5 7 9 11 12 Output NO YES NO YES Note In the first test case, you have sequence [1, 2, 3]. Since k = 3 you have only one way to choose k elements β€” it's to choose all elements [1, \underline{2}, 3] with median 2. That's why after erasing all chosen elements except its median you'll get sequence [2]. In other words, there is no way to get sequence b = [1] as the result. In the second test case, you have sequence [1, 2, 3, 4, 5, 6, 7] and one of the optimal strategies is following: 1. choose k = 3 elements [2, \underline{3}, 4] and erase them except its median; you'll get sequence [1, 3, 5, 6, 7]; 2. choose 3 elements [3, \underline{5}, 6] and erase them except its median; you'll get desired sequence [1, 5, 7]; In the fourth test case, you have sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]. You can choose k=7 elements [2, 4, 6, \underline{7}, 8, 10, 13] and erase them except its median to get sequence b.
2
14
# by the authority of GOD author: manhar singh sachdev # import os,sys from io import BytesIO, IOBase def solve(n,k,m,b): if (n-m)%(k-1): return 'NO' val,val1,x = 0,0,k//2 for i in range(1,n+1): if i == b[val]: val += 1 if val1 >= x and n-m-val1 >= x: return 'YES' else: val1 += 1 if val == m: break return 'NO' def main(): for _ in range(int(input())): n,k,m = map(int,input().split()) b = list(map(int,input().split())) print(solve(n,k,m,b)) #Fast IO Region BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") if __name__ == '__main__': main()
PYTHON3
1468_H. K and Medians
Let's denote the median of a sequence s with odd length as the value in the middle of s if we sort s in non-decreasing order. For example, let s = [1, 2, 5, 7, 2, 3, 12]. After sorting, we get sequence [1, 2, 2, \underline{3}, 5, 7, 12], and the median is equal to 3. You have a sequence of n integers [1, 2, ..., n] and an odd integer k. In one step, you choose any k elements from the sequence and erase all chosen elements except their median. These elements do not have to go continuously (gaps are allowed between them). For example, if you have a sequence [1, 2, 3, 4, 5, 6, 7] (i.e. n=7) and k = 3, then the following options for the first step are possible: * choose [1, \underline{2}, 3]; 2 is their median, so it is not erased, and the resulting sequence is [2, 4, 5, 6, 7]; * choose [2, \underline{4}, 6]; 4 is their median, so it is not erased, and the resulting sequence is [1, 3, 4, 5, 7]; * choose [1, \underline{6}, 7]; 6 is their median, so it is not erased, and the resulting sequence is [2, 3, 4, 5, 6]; * and several others. You can do zero or more steps. Can you get a sequence b_1, b_2, ..., b_m after several steps? You'll be given t test cases. Solve each test case independently. 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 three integers n, k, and m (3 ≀ n ≀ 2 β‹… 10^5; 3 ≀ k ≀ n; k is odd; 1 ≀ m < n) β€” the length of the sequence you have, the number of elements you choose in each step and the length of the sequence you'd like to get. The second line of each test case contains m integers b_1, b_2, ..., b_m (1 ≀ b_1 < b_2 < ... < b_m ≀ n) β€” the sequence you'd like to get, given in the ascending order. It's guaranteed that the total sum of n over all test cases doesn't exceed 2 β‹… 10^5. Output For each test case, print YES if you can obtain the sequence b or NO otherwise. You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer). Example Input 4 3 3 1 1 7 3 3 1 5 7 10 5 3 4 5 6 13 7 7 1 3 5 7 9 11 12 Output NO YES NO YES Note In the first test case, you have sequence [1, 2, 3]. Since k = 3 you have only one way to choose k elements β€” it's to choose all elements [1, \underline{2}, 3] with median 2. That's why after erasing all chosen elements except its median you'll get sequence [2]. In other words, there is no way to get sequence b = [1] as the result. In the second test case, you have sequence [1, 2, 3, 4, 5, 6, 7] and one of the optimal strategies is following: 1. choose k = 3 elements [2, \underline{3}, 4] and erase them except its median; you'll get sequence [1, 3, 5, 6, 7]; 2. choose 3 elements [3, \underline{5}, 6] and erase them except its median; you'll get desired sequence [1, 5, 7]; In the fourth test case, you have sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]. You can choose k=7 elements [2, 4, 6, \underline{7}, 8, 10, 13] and erase them except its median to get sequence b.
2
14
#include<bits/stdc++.h> using namespace std; #define int long long #define ull unsigned long long #define ll long long #define M 1000000007 #define pb push_back #define p_q priority_queue #define pii pair<ll,ll> #define vi vector<ll> #define vii vector<pii> #define mi map<ll,ll> #define mii map<pii,ll> #define all(a) (a).begin(),(a).end() #define sz(x) (ll)x.size() #define endl '\n' #define gcd(a,b) __gcd((a),(b)) #define lcm(a,b) ((a)*(b)) / gcd((a),(b)) #define ios ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0); #define mp make_pair #define lb lower_bound #define ub upper_bound #define F first #define S second #define rep(i, begin, end) for (int i=begin;i<end;i++) #define repd(i, begin, end) for (int i=end-1;i>=begin;i--) #define ini(a,n,b) for(ll int i=0;i<n;i++) a[i]=0; #define cset(a) __builtin_popcountll(a) #define hell 1000000007 #define re resize const int INF=1e18; const int N=3e5+5; int powm(int a,int b) { int res=1; while(b) { if(b&1) res=(res*a)%M; a=(a*a)%M; b>>=1; } return res; } int pow(int a,int b) { int res=1; while(b) { if(b&1) res=(res*a); a=(a*a); b>>=1; } return res; } signed main(void) {ios #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin);freopen("answer.txt", "w", stdout); #endif int q; cin>>q; while(q--) { int n,k,m; cin>>n>>k>>m; vi vis(N,0); vi a(m); rep(i,0,m) { cin>>a[i]; vis[a[i]]=1; } int f=1,f2=0,d=n-m; if((n-m)%(k-1)!=0) f=0; k--; int cnt=0,x=0; for(int i=1;i<=n;i++) { if(!vis[i]) cnt++; else { int rem=d-cnt; if(cnt>=(k/2)&&rem>=(k/2)) f2=1; } } if(!f||!f2) cout<<"NO"<<endl; else cout<<"YES"<<endl; } }
CPP
1468_H. K and Medians
Let's denote the median of a sequence s with odd length as the value in the middle of s if we sort s in non-decreasing order. For example, let s = [1, 2, 5, 7, 2, 3, 12]. After sorting, we get sequence [1, 2, 2, \underline{3}, 5, 7, 12], and the median is equal to 3. You have a sequence of n integers [1, 2, ..., n] and an odd integer k. In one step, you choose any k elements from the sequence and erase all chosen elements except their median. These elements do not have to go continuously (gaps are allowed between them). For example, if you have a sequence [1, 2, 3, 4, 5, 6, 7] (i.e. n=7) and k = 3, then the following options for the first step are possible: * choose [1, \underline{2}, 3]; 2 is their median, so it is not erased, and the resulting sequence is [2, 4, 5, 6, 7]; * choose [2, \underline{4}, 6]; 4 is their median, so it is not erased, and the resulting sequence is [1, 3, 4, 5, 7]; * choose [1, \underline{6}, 7]; 6 is their median, so it is not erased, and the resulting sequence is [2, 3, 4, 5, 6]; * and several others. You can do zero or more steps. Can you get a sequence b_1, b_2, ..., b_m after several steps? You'll be given t test cases. Solve each test case independently. 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 three integers n, k, and m (3 ≀ n ≀ 2 β‹… 10^5; 3 ≀ k ≀ n; k is odd; 1 ≀ m < n) β€” the length of the sequence you have, the number of elements you choose in each step and the length of the sequence you'd like to get. The second line of each test case contains m integers b_1, b_2, ..., b_m (1 ≀ b_1 < b_2 < ... < b_m ≀ n) β€” the sequence you'd like to get, given in the ascending order. It's guaranteed that the total sum of n over all test cases doesn't exceed 2 β‹… 10^5. Output For each test case, print YES if you can obtain the sequence b or NO otherwise. You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer). Example Input 4 3 3 1 1 7 3 3 1 5 7 10 5 3 4 5 6 13 7 7 1 3 5 7 9 11 12 Output NO YES NO YES Note In the first test case, you have sequence [1, 2, 3]. Since k = 3 you have only one way to choose k elements β€” it's to choose all elements [1, \underline{2}, 3] with median 2. That's why after erasing all chosen elements except its median you'll get sequence [2]. In other words, there is no way to get sequence b = [1] as the result. In the second test case, you have sequence [1, 2, 3, 4, 5, 6, 7] and one of the optimal strategies is following: 1. choose k = 3 elements [2, \underline{3}, 4] and erase them except its median; you'll get sequence [1, 3, 5, 6, 7]; 2. choose 3 elements [3, \underline{5}, 6] and erase them except its median; you'll get desired sequence [1, 5, 7]; In the fourth test case, you have sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]. You can choose k=7 elements [2, 4, 6, \underline{7}, 8, 10, 13] and erase them except its median to get sequence b.
2
14
#pragma GCC optimize("O3") #pragma GCC target("sse4") // #pragma GCC optimize("Ofast") // #pragma GCC target("avx,avx2,fma") #include<bits/stdc++.h> using namespace std; typedef long long ll; const double PI=acos(-1.0); #define t1(x) cerr<<#x<<"="<<x<<endl #define t2(x, y) cerr<<#x<<"="<<x<<" "<<#y<<"="<<y<<endl #define t3(x, y, z) cerr<<#x<<"=" <<x<<" "<<#y<<"="<<y<<" "<<#z<<"="<<z<<endl #define t4(a,b,c,d) cerr<<#a<<"="<<a<<" "<<#b<<"="<<b<<" "<<#c<<"="<<c<<" "<<#d<<"="<<d<<endl #define t5(a,b,c,d,e) cerr<<#a<<"="<<a<<" "<<#b<<"="<<b<<" "<<#c<<"="<<c<<" "<<#d<<"="<<d<<" "<<#e<<"="<<e<<endl #define t6(a,b,c,d,e,f) cerr<<#a<<"="<<a<<" "<<#b<<"="<<b<<" "<<#c<<"="<<c<<" "<<#d<<"="<<d<<" "<<#e<<"="<<e<<" "<<#f<<"="<<f<<endl #define GET_MACRO(_1,_2,_3,_4,_5,_6,NAME,...) NAME #define tr(...) GET_MACRO(__VA_ARGS__,t6,t5, t4, t3, t2, t1)(__VA_ARGS__) #define __ freopen("input.txt","r",stdin);freopen("output.txt","w",stdout); #define fastio() ios::sync_with_stdio(0);cin.tie(0) #define MEMS(x,t) memset(x,t,sizeof(x)); mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); /*-------------------------------------------------------------------------------------------------------------------------------------*/ //#define MOD 1000000007 #define endl "\n" #define int long long #define inf 1e18 #define ld long double /*-------------------------------------------------------------------------------------------------------------------------------------*/ signed main() { fastio(); int t; cin>>t; while(t--) { int n,k,m; cin>>n>>k>>m; vector<int> cnt(n+1,1); for(int i=1;i<=m;i++) { int x; cin>>x; cnt[x]=0; } if((n-m)%(k-1)!=0) { cout<<"no\n"; continue; } bool flag=0; int sum=0; for(int i=1;i<=n;i++) { if(sum>=k/2 && (n-m)-(sum+cnt[i])>=k/2 && cnt[i]==0) { flag=1; break; } sum+=cnt[i]; } if(flag) { cout<<"yes\n"; } else { cout<<"no\n"; } } }
CPP