exec_outcome
stringclasses 1
value | code_uid
stringlengths 32
32
| file_name
stringclasses 111
values | prob_desc_created_at
stringlengths 10
10
| prob_desc_description
stringlengths 63
3.8k
| prob_desc_memory_limit
stringclasses 18
values | source_code
stringlengths 117
65.5k
| lang_cluster
stringclasses 1
value | prob_desc_sample_inputs
stringlengths 2
802
| prob_desc_time_limit
stringclasses 27
values | prob_desc_sample_outputs
stringlengths 2
796
| prob_desc_notes
stringlengths 4
3k
⌀ | lang
stringclasses 5
values | prob_desc_input_from
stringclasses 3
values | tags
sequencelengths 0
11
| src_uid
stringlengths 32
32
| prob_desc_input_spec
stringlengths 28
2.37k
⌀ | difficulty
int64 -1
3.5k
⌀ | prob_desc_output_spec
stringlengths 17
1.47k
⌀ | prob_desc_output_to
stringclasses 3
values | hidden_unit_tests
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PASSED | f12e5c183cf84f96db3a5e91e9c1ea09 | train_000.jsonl | 1576386300 | Your friend Jeff Zebos has been trying to run his new online company, but it's not going very well. He's not getting a lot of sales on his website which he decided to call Azamon. His big problem, you think, is that he's not ranking high enough on the search engines. If only he could rename his products to have better names than his competitors, then he'll be at the top of the search results and will be a millionaire.After doing some research, you find out that search engines only sort their results lexicographically. If your friend could rename his products to lexicographically smaller strings than his competitor's, then he'll be at the top of the rankings!To make your strategy less obvious to his competitors, you decide to swap no more than two letters of the product names.Please help Jeff to find improved names for his products that are lexicographically smaller than his competitor's!Given the string $$$s$$$ representing Jeff's product name and the string $$$c$$$ representing his competitor's product name, find a way to swap at most one pair of characters in $$$s$$$ (that is, find two distinct indices $$$i$$$ and $$$j$$$ and swap $$$s_i$$$ and $$$s_j$$$) such that the resulting new name becomes strictly lexicographically smaller than $$$c$$$, or determine that it is impossible.Note: String $$$a$$$ is strictly lexicographically smaller than string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a proper prefix of $$$b$$$, that is, $$$a$$$ is a prefix of $$$b$$$ such that $$$a \neq b$$$; There exists an integer $$$1 \le i \le \min{(|a|, |b|)}$$$ such that $$$a_i < b_i$$$ and $$$a_j = b_j$$$ for $$$1 \le j < i$$$. | 256 megabytes | import java.util.Scanner;
public class Azamon_Web_Services {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int tests = in.nextInt();
for (int i = 0; i< tests; i++) {
String yours = in.next();
String competitor = in.next();
int k;
int current; //index of firstest letter
boolean swapped = false;
outer:
//AMAZON
for(int j = 0; j < yours.length(); j++) {
current = j;
for (k = j; k <yours.length(); k++ ) {
if (yours.charAt(k) < yours.charAt(current)
|| (yours.charAt(k) <= yours.charAt(current) && current != j)) {
current = k;
swapped = true;
}
}
if(yours.compareTo(competitor) < 0) {
System.out.println(yours);
break outer;
}
//if you swapped once...
if(swapped) {
//this is swapping characters
char[] c = yours.toCharArray();
char temp = c[j];
c[j] = c[current];
c[current] = temp;
yours= new String(c);
if(yours.compareTo(competitor) < 0) {
System.out.println(yours);
break outer;
}
else {
//System.out.println("Stopped here");
System.out.println("---");
break outer;
}
}
//if you reach the end of the word and no swaps
if (j == yours.length() - 1) {
//System.out.println("End of word");
System.out.println("---");
break outer;
}
}
}
}
}
| Java | ["3\nAZAMON APPLE\nAZAMON AAAAAAAAAAALIBABA\nAPPLE BANANA"] | 2 seconds | ["AMAZON\n---\nAPPLE"] | NoteIn the first test case, it is possible to swap the second and the fourth letters of the string and the resulting string "AMAZON" is lexicographically smaller than "APPLE".It is impossible to improve the product's name in the second test case and satisfy all conditions.In the third test case, it is possible not to swap a pair of characters. The name "APPLE" is lexicographically smaller than "BANANA". Note that there are other valid answers, e.g., "APPEL". | Java 11 | standard input | [
"greedy"
] | 88743b7acb4a95dc0d5bb2e073714c49 | The first line of input contains a single integer $$$t$$$ ($$$1 \le t \le 1500$$$) denoting the number of test cases. The next lines contain descriptions of the test cases. Each test case consists of a single line containing two space-separated strings $$$s$$$ and $$$c$$$ ($$$2 \le |s| \le 5000, 1 \le |c| \le 5000$$$). The strings $$$s$$$ and $$$c$$$ consists of uppercase English letters. It is guaranteed that the sum of $$$|s|$$$ in the input is at most $$$5000$$$ and the sum of the $$$|c|$$$ in the input is at most $$$5000$$$. | 1,600 | For each test case, output a single line containing a single string, which is either the new name which is obtained after swapping no more than one pair of characters that is strictly lexicographically smaller than $$$c$$$. In case there are many possible such strings, you can output any of them; three dashes (the string "---" without quotes) if it is impossible. | standard output | |
PASSED | 45e2500c21d0c477aa7d32f72ebec4e4 | train_000.jsonl | 1600094100 | You are playing a very popular game called Cubecraft. Initially, you have one stick and want to craft $$$k$$$ torches. One torch can be crafted using one stick and one coal.Hopefully, you've met a very handsome wandering trader who has two trade offers: exchange $$$1$$$ stick for $$$x$$$ sticks (you lose $$$1$$$ stick and gain $$$x$$$ sticks). exchange $$$y$$$ sticks for $$$1$$$ coal (you lose $$$y$$$ sticks and gain $$$1$$$ coal). During one trade, you can use only one of these two trade offers. You can use each trade offer any number of times you want to, in any order.Your task is to find the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
static class Scan {
private byte[] buf=new byte[1024];
private int index;
private InputStream in;
private int total;
public Scan()
{
in=System.in;
}
public int scan()throws IOException
{
if(total<0)
throw new InputMismatchException();
if(index>=total)
{
index=0;
total=in.read(buf);
if(total<=0)
return -1;
}
return buf[index++];
}
public int scanInt()throws IOException
{
int integer=0;
int n=scan();
while(isWhiteSpace(n))
n=scan();
int neg=1;
if(n=='-')
{
neg=-1;
n=scan();
}
while(!isWhiteSpace(n))
{
if(n>='0'&&n<='9')
{
integer*=10;
integer+=n-'0';
n=scan();
}
else throw new InputMismatchException();
}
return neg*integer;
}
public double scanDouble()throws IOException
{
double doub=0;
int n=scan();
while(isWhiteSpace(n))
n=scan();
int neg=1;
if(n=='-')
{
neg=-1;
n=scan();
}
while(!isWhiteSpace(n)&&n!='.')
{
if(n>='0'&&n<='9')
{
doub*=10;
doub+=n-'0';
n=scan();
}
else throw new InputMismatchException();
}
if(n=='.')
{
n=scan();
double temp=1;
while(!isWhiteSpace(n))
{
if(n>='0'&&n<='9')
{
temp/=10;
doub+=(n-'0')*temp;
n=scan();
}
else throw new InputMismatchException();
}
}
return doub*neg;
}
public String scanString()throws IOException
{
StringBuilder sb=new StringBuilder();
int n=scan();
while(isWhiteSpace(n))
n=scan();
while(!isWhiteSpace(n))
{
sb.append((char)n);
n=scan();
}
return sb.toString();
}
private boolean isWhiteSpace(int n)
{
if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1)
return true;
return false;
}
}
public static void main(String args[]) throws IOException {
Scan input=new Scan();
StringBuilder ans=new StringBuilder("");
int test=input.scanInt();
for(int tt=1;tt<=test;tt++) {
long x=input.scanInt();
long y=input.scanInt();
long k=input.scanInt();
long tmp=(k+k*y)/(x-1);
if(tmp*(x-1)+1<(k+k*y)) {
tmp++;
}
if((tmp-1)*(x-1)+1>=(k+k*y)) {
tmp--;
}
ans.append(tmp+k);
ans.append("\n");
}
System.out.println(ans);
}
}
| Java | ["5\n2 1 5\n42 13 24\n12 11 12\n1000000000 1000000000 1000000000\n2 1000000000 1000000000"] | 1 second | ["14\n33\n25\n2000000003\n1000000001999999999"] | null | Java 11 | standard input | [
"math"
] | 28610d192329c78580db354f8dfc4094 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains three integers $$$x$$$, $$$y$$$ and $$$k$$$ ($$$2 \le x \le 10^9$$$; $$$1 \le y, k \le 10^9$$$) — the number of sticks you can buy with one stick, the number of sticks required to buy one coal and the number of torches you need, respectively. | 1,000 | For each test case, print the answer: the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints. | standard output | |
PASSED | 3a7adb1541f39a5b927e9b75bbb146fb | train_000.jsonl | 1600094100 | You are playing a very popular game called Cubecraft. Initially, you have one stick and want to craft $$$k$$$ torches. One torch can be crafted using one stick and one coal.Hopefully, you've met a very handsome wandering trader who has two trade offers: exchange $$$1$$$ stick for $$$x$$$ sticks (you lose $$$1$$$ stick and gain $$$x$$$ sticks). exchange $$$y$$$ sticks for $$$1$$$ coal (you lose $$$y$$$ sticks and gain $$$1$$$ coal). During one trade, you can use only one of these two trade offers. You can use each trade offer any number of times you want to, in any order.Your task is to find the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main{
static long ceil(long a, long b) {
return (a+b-1)/b;
}
public static void main(String[] args) throws IOException{
int t = sc.nextInt();
while (t-->0){
long x = sc.nextInt()-1;
long y = sc.nextInt();
long torch = sc.nextLong();
long needed = (torch)* (y+1)-1;
out.println(ceil(needed, x) + torch);
}
out.close();
}
static long powMod(long base, long exp, long mod) {
if (base == 0 || base == 1) return base;
if (exp == 0) return 1;
if (exp == 1) return base % mod;
long R = powMod(base, exp/2, mod) % mod;
R *= R;
R %= mod;
if ((exp & 1) == 1) {
return base * R % mod;
}
else return R % mod;
}
static long pow(long base, long exp) {
if (base == 0 || base == 1) return base;
if (exp == 0) return 1;
if (exp == 1) return base;
long R = pow(base, exp/2);
if ((exp & 1) == 1) {
return R * R * base;
}
else return R * R;
}
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out));
public static Reader sc = new Reader();
}
| Java | ["5\n2 1 5\n42 13 24\n12 11 12\n1000000000 1000000000 1000000000\n2 1000000000 1000000000"] | 1 second | ["14\n33\n25\n2000000003\n1000000001999999999"] | null | Java 11 | standard input | [
"math"
] | 28610d192329c78580db354f8dfc4094 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains three integers $$$x$$$, $$$y$$$ and $$$k$$$ ($$$2 \le x \le 10^9$$$; $$$1 \le y, k \le 10^9$$$) — the number of sticks you can buy with one stick, the number of sticks required to buy one coal and the number of torches you need, respectively. | 1,000 | For each test case, print the answer: the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints. | standard output | |
PASSED | 41e7091907cf183ae20d4d5ee8f82749 | train_000.jsonl | 1600094100 | You are playing a very popular game called Cubecraft. Initially, you have one stick and want to craft $$$k$$$ torches. One torch can be crafted using one stick and one coal.Hopefully, you've met a very handsome wandering trader who has two trade offers: exchange $$$1$$$ stick for $$$x$$$ sticks (you lose $$$1$$$ stick and gain $$$x$$$ sticks). exchange $$$y$$$ sticks for $$$1$$$ coal (you lose $$$y$$$ sticks and gain $$$1$$$ coal). During one trade, you can use only one of these two trade offers. You can use each trade offer any number of times you want to, in any order.Your task is to find the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.Scanner;
public class App {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long t = sc.nextInt();
for (long c = 1; c <= t; c++) {
long count = 0;
long x = sc.nextInt();
long y = sc.nextInt();
long k = sc.nextInt();
count += k;
if (((((y + 1) * k) - 1) % (x - 1)) == 0) {
count += ((((y + 1) * k) - 1) / (x - 1));
} else {
count += ((((y + 1) * k) - 1) / (x - 1)) + 1;
}
System.out.println(count);
}
sc.close();
}
} | Java | ["5\n2 1 5\n42 13 24\n12 11 12\n1000000000 1000000000 1000000000\n2 1000000000 1000000000"] | 1 second | ["14\n33\n25\n2000000003\n1000000001999999999"] | null | Java 11 | standard input | [
"math"
] | 28610d192329c78580db354f8dfc4094 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains three integers $$$x$$$, $$$y$$$ and $$$k$$$ ($$$2 \le x \le 10^9$$$; $$$1 \le y, k \le 10^9$$$) — the number of sticks you can buy with one stick, the number of sticks required to buy one coal and the number of torches you need, respectively. | 1,000 | For each test case, print the answer: the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints. | standard output | |
PASSED | f06063ad3cdf6915f1f868f248fabbae | train_000.jsonl | 1600094100 | You are playing a very popular game called Cubecraft. Initially, you have one stick and want to craft $$$k$$$ torches. One torch can be crafted using one stick and one coal.Hopefully, you've met a very handsome wandering trader who has two trade offers: exchange $$$1$$$ stick for $$$x$$$ sticks (you lose $$$1$$$ stick and gain $$$x$$$ sticks). exchange $$$y$$$ sticks for $$$1$$$ coal (you lose $$$y$$$ sticks and gain $$$1$$$ coal). During one trade, you can use only one of these two trade offers. You can use each trade offer any number of times you want to, in any order.Your task is to find the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.net.Inet4Address;
import java.nio.channels.InterruptedByTimeoutException;
import java.util.*;
import java.io.*;
import java.text.*;
import java.math.*;
public class Main {
public static FastIO file = new FastIO();
private static void solve() {
int amount = nextInt();
long coalTrade, torches;
long stickTrade;
while (amount-- > 0) {
stickTrade = nextInt();
coalTrade = nextInt();
torches = nextInt();
stickTrade = (coalTrade*torches-1+torches)%(stickTrade-1) == 0 ? (coalTrade*torches-1+torches)/(stickTrade-1) : (coalTrade*torches-1+torches)/(stickTrade-1)+1;
System.out.println((long)(stickTrade+torches));
}
}
private static long gcd(int a, int b) {
int t;
while (b != 0) {
t = b;
b = a % b;
a = t;
}
return a;
}
private static long lcm(int a, int b) {
return a / gcd(a, b) * b;
}
private static int[] nextArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
public static int[][] nextArray2D(int n, int m) {
int[][] result = new int[n][];
for (int i = 0; i < n; i++) {
result[i] = nextArray(m);
}
return result;
}
public static long pow(long n, long p) {
long ret = 1L;
while (p > 0) {
if (p % 2 != 0L)
ret *= n;
n *= n;
p >>= 1L;
}
return ret;
}
public static String next() {
return file.next();
}
public static int nextInt() {
return file.nextInt();
}
public static long nextLong() {
return file.nextLong();
}
public static double nextDouble() {
return file.nextDouble();
}
public static String nextLine() {
return file.nextLine();
}
public static class FastIO {
BufferedReader br;
StringTokenizer st;
PrintWriter out;
public FastIO() {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
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;
}
}
public static void main(String[] args) throws IOException {
solve();
}
} | Java | ["5\n2 1 5\n42 13 24\n12 11 12\n1000000000 1000000000 1000000000\n2 1000000000 1000000000"] | 1 second | ["14\n33\n25\n2000000003\n1000000001999999999"] | null | Java 11 | standard input | [
"math"
] | 28610d192329c78580db354f8dfc4094 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains three integers $$$x$$$, $$$y$$$ and $$$k$$$ ($$$2 \le x \le 10^9$$$; $$$1 \le y, k \le 10^9$$$) — the number of sticks you can buy with one stick, the number of sticks required to buy one coal and the number of torches you need, respectively. | 1,000 | For each test case, print the answer: the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints. | standard output | |
PASSED | c5e10a5d6b37b9a685a3a51187b43a80 | train_000.jsonl | 1600094100 | You are playing a very popular game called Cubecraft. Initially, you have one stick and want to craft $$$k$$$ torches. One torch can be crafted using one stick and one coal.Hopefully, you've met a very handsome wandering trader who has two trade offers: exchange $$$1$$$ stick for $$$x$$$ sticks (you lose $$$1$$$ stick and gain $$$x$$$ sticks). exchange $$$y$$$ sticks for $$$1$$$ coal (you lose $$$y$$$ sticks and gain $$$1$$$ coal). During one trade, you can use only one of these two trade offers. You can use each trade offer any number of times you want to, in any order.Your task is to find the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
public class solution {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
for(int i=0;i<t;i++) {
long x=sc.nextLong();
long y=sc.nextLong();
long k=sc.nextLong();
long s=k*(y+1);
long a;
s=s-1;
if(s%(x-1)==0) {
a=s/(x-1);
System.out.println(a+k);
}
else {
a=s/(x-1);
System.out.println(a+1+k);
}
}
sc.close();
}
} | Java | ["5\n2 1 5\n42 13 24\n12 11 12\n1000000000 1000000000 1000000000\n2 1000000000 1000000000"] | 1 second | ["14\n33\n25\n2000000003\n1000000001999999999"] | null | Java 11 | standard input | [
"math"
] | 28610d192329c78580db354f8dfc4094 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains three integers $$$x$$$, $$$y$$$ and $$$k$$$ ($$$2 \le x \le 10^9$$$; $$$1 \le y, k \le 10^9$$$) — the number of sticks you can buy with one stick, the number of sticks required to buy one coal and the number of torches you need, respectively. | 1,000 | For each test case, print the answer: the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints. | standard output | |
PASSED | 09b227a9c667d6b074716091b2647ef9 | train_000.jsonl | 1600094100 | You are playing a very popular game called Cubecraft. Initially, you have one stick and want to craft $$$k$$$ torches. One torch can be crafted using one stick and one coal.Hopefully, you've met a very handsome wandering trader who has two trade offers: exchange $$$1$$$ stick for $$$x$$$ sticks (you lose $$$1$$$ stick and gain $$$x$$$ sticks). exchange $$$y$$$ sticks for $$$1$$$ coal (you lose $$$y$$$ sticks and gain $$$1$$$ coal). During one trade, you can use only one of these two trade offers. You can use each trade offer any number of times you want to, in any order.Your task is to find the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
public class CodeForces {
private final static Scanner input = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
private static long solve(int x, int y, int k) {
//get k coals
long sticksNeededForCoal = (long) y * (long) k;
long tradesForCoal = (long)((sticksNeededForCoal * 1.0 / (x-1)) + 0.5) + k;
long left = (x-1) * (tradesForCoal - k);
while(left < sticksNeededForCoal){
tradesForCoal++;
left += (x-1);
}
left -= sticksNeededForCoal;
//get sticksLeft sticks
long sticksNeeded = k - 1 - left;
long tradesForSticks = (long)((sticksNeeded * 1.0 / (x-1)) + 0.5);
long result = (x-1) * tradesForSticks;
while(result < sticksNeeded){
tradesForSticks++;
result += (x-1);
}
return tradesForCoal + tradesForSticks;
}
public static void main(String[] args) {
int t = input.nextInt();
for(int i=0; i<t; i++){
int x = input.nextInt();
int y = input.nextInt();
int k = input.nextInt();
System.out.println(solve(x, y, k));
}
}
}
| Java | ["5\n2 1 5\n42 13 24\n12 11 12\n1000000000 1000000000 1000000000\n2 1000000000 1000000000"] | 1 second | ["14\n33\n25\n2000000003\n1000000001999999999"] | null | Java 11 | standard input | [
"math"
] | 28610d192329c78580db354f8dfc4094 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains three integers $$$x$$$, $$$y$$$ and $$$k$$$ ($$$2 \le x \le 10^9$$$; $$$1 \le y, k \le 10^9$$$) — the number of sticks you can buy with one stick, the number of sticks required to buy one coal and the number of torches you need, respectively. | 1,000 | For each test case, print the answer: the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints. | standard output | |
PASSED | 4ff6b4b2ee1d798a87d60d17f72a4b43 | train_000.jsonl | 1600094100 | You are playing a very popular game called Cubecraft. Initially, you have one stick and want to craft $$$k$$$ torches. One torch can be crafted using one stick and one coal.Hopefully, you've met a very handsome wandering trader who has two trade offers: exchange $$$1$$$ stick for $$$x$$$ sticks (you lose $$$1$$$ stick and gain $$$x$$$ sticks). exchange $$$y$$$ sticks for $$$1$$$ coal (you lose $$$y$$$ sticks and gain $$$1$$$ coal). During one trade, you can use only one of these two trade offers. You can use each trade offer any number of times you want to, in any order.Your task is to find the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints.You have to answer $$$t$$$ independent test cases. | 256 megabytes | //package hiougyf;
import java.io.*;
import java.util.*;
import java.util.Map.Entry;
public class Solution {
public static void main(String[] args){
Scanner sc =new Scanner(System.in);
int t=sc.nextInt();
while(t-->0) {
long x=sc.nextLong(),y=sc.nextLong(),k=sc.nextLong();
long v= (k*y+k-1);
long p=x-1;
long ans=(v+p-1)/p;
//if(v%p!=0) ans+=1;
System.out.println(ans+k);
}
}
public static int floorSqrt(int x)
{
// Base Cases
if (x == 0 || x == 1)
return x;
// Do Binary Search for floor(sqrt(x))
int start = 1, end = x, ans=0;
while (start <= end)
{
int mid = (start + end) / 2;
// If x is a perfect square
if (mid*mid == x)
return mid;
// Since we need floor, we update answer when mid*mid is
// smaller than x, and move closer to sqrt(x)
if (mid*mid < x)
{
start = mid + 1;
ans = mid;
}
else // If mid*mid is greater than x
end = mid-1;
}
return ans;
}
static int div(int n,int b) {
int g=-1;
for(int i=2;i<=Math.sqrt(n);i++) {
if(n%i==0&&i!=b) {
g=i;
break;
}
}
return g;
}
public static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
public static int lcm(int a, int b)
{
return (a*b)/gcd(a, b);
}
public static boolean isPrime1(int n) {
if (n <= 1) {
return false;
}
if (n == 2) {
return true;
}
for (int i = 2; i <= Math.sqrt(n) + 1; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static boolean isPrime(int n) {
if (n <= 1) {
return false;
}
if (n == 2) {
return true;
}
if (n % 2 == 0) {
return false;
}
for (int i = 3; i <= Math.sqrt(n) + 1; i = i + 2) {
if (n % i == 0) {
return false;
}
}
return true;
}
} | Java | ["5\n2 1 5\n42 13 24\n12 11 12\n1000000000 1000000000 1000000000\n2 1000000000 1000000000"] | 1 second | ["14\n33\n25\n2000000003\n1000000001999999999"] | null | Java 11 | standard input | [
"math"
] | 28610d192329c78580db354f8dfc4094 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains three integers $$$x$$$, $$$y$$$ and $$$k$$$ ($$$2 \le x \le 10^9$$$; $$$1 \le y, k \le 10^9$$$) — the number of sticks you can buy with one stick, the number of sticks required to buy one coal and the number of torches you need, respectively. | 1,000 | For each test case, print the answer: the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints. | standard output | |
PASSED | c94ee48c4b27c2e716b10b2bc5acc6a9 | train_000.jsonl | 1600094100 | You are playing a very popular game called Cubecraft. Initially, you have one stick and want to craft $$$k$$$ torches. One torch can be crafted using one stick and one coal.Hopefully, you've met a very handsome wandering trader who has two trade offers: exchange $$$1$$$ stick for $$$x$$$ sticks (you lose $$$1$$$ stick and gain $$$x$$$ sticks). exchange $$$y$$$ sticks for $$$1$$$ coal (you lose $$$y$$$ sticks and gain $$$1$$$ coal). During one trade, you can use only one of these two trade offers. You can use each trade offer any number of times you want to, in any order.Your task is to find the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints.You have to answer $$$t$$$ independent test cases. | 256 megabytes | //package hiougyf;
import java.io.*;
import java.util.*;
import java.util.Map.Entry;
public class Solution {
public static void main(String[] args){
Scanner sc =new Scanner(System.in);
int t=sc.nextInt();
while(t-->0) {
long x=sc.nextLong(),y=sc.nextLong(),k=sc.nextLong();
long v= (k*y+k-1);
long ans=v/(x-1);
if(v%(x-1)!=0) ans+=1;
System.out.println(ans+k);
}
}
public static int floorSqrt(int x)
{
// Base Cases
if (x == 0 || x == 1)
return x;
// Do Binary Search for floor(sqrt(x))
int start = 1, end = x, ans=0;
while (start <= end)
{
int mid = (start + end) / 2;
// If x is a perfect square
if (mid*mid == x)
return mid;
// Since we need floor, we update answer when mid*mid is
// smaller than x, and move closer to sqrt(x)
if (mid*mid < x)
{
start = mid + 1;
ans = mid;
}
else // If mid*mid is greater than x
end = mid-1;
}
return ans;
}
static int div(int n,int b) {
int g=-1;
for(int i=2;i<=Math.sqrt(n);i++) {
if(n%i==0&&i!=b) {
g=i;
break;
}
}
return g;
}
public static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
public static int lcm(int a, int b)
{
return (a*b)/gcd(a, b);
}
public static boolean isPrime1(int n) {
if (n <= 1) {
return false;
}
if (n == 2) {
return true;
}
for (int i = 2; i <= Math.sqrt(n) + 1; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static boolean isPrime(int n) {
if (n <= 1) {
return false;
}
if (n == 2) {
return true;
}
if (n % 2 == 0) {
return false;
}
for (int i = 3; i <= Math.sqrt(n) + 1; i = i + 2) {
if (n % i == 0) {
return false;
}
}
return true;
}
} | Java | ["5\n2 1 5\n42 13 24\n12 11 12\n1000000000 1000000000 1000000000\n2 1000000000 1000000000"] | 1 second | ["14\n33\n25\n2000000003\n1000000001999999999"] | null | Java 11 | standard input | [
"math"
] | 28610d192329c78580db354f8dfc4094 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains three integers $$$x$$$, $$$y$$$ and $$$k$$$ ($$$2 \le x \le 10^9$$$; $$$1 \le y, k \le 10^9$$$) — the number of sticks you can buy with one stick, the number of sticks required to buy one coal and the number of torches you need, respectively. | 1,000 | For each test case, print the answer: the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints. | standard output | |
PASSED | 668e8ce1add4529ab8d3767de66537b2 | train_000.jsonl | 1600094100 | You are playing a very popular game called Cubecraft. Initially, you have one stick and want to craft $$$k$$$ torches. One torch can be crafted using one stick and one coal.Hopefully, you've met a very handsome wandering trader who has two trade offers: exchange $$$1$$$ stick for $$$x$$$ sticks (you lose $$$1$$$ stick and gain $$$x$$$ sticks). exchange $$$y$$$ sticks for $$$1$$$ coal (you lose $$$y$$$ sticks and gain $$$1$$$ coal). During one trade, you can use only one of these two trade offers. You can use each trade offer any number of times you want to, in any order.Your task is to find the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints.You have to answer $$$t$$$ independent test cases. | 256 megabytes |
import java.util.*;
import java.io.*;
public class A {
private static final int mod =(int)1e9+7;
public static void main(String[] args) throws Exception {
Scanner sc=new Scanner(System.in);
PrintWriter out=new PrintWriter(System.out);
int t=sc.nextInt();
while(t-->0) {
long x=sc.nextLong();
long y=sc.nextLong();
long k=sc.nextLong();
long req=y*k+x;
long st=1;
long s=(y+1)*k+-1;x--; long ans=(s+x-1)/x;
System.out.println((s+x-1)/x+k);
}
}
static boolean vis[]=new boolean[10001];
static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static long nCr(int n,int r) {
int dp[][]=new int[2001][2001];
for(int i=0;i<2001;i++) {
dp[0][i]=0;
}
for(int i=0;i<2001;i++) {
dp[i][0]=1;
}
for(int i=1;i<2001;i++) {
for(int j=1;j<2001;j++) {
if(i==j) {
dp[i][j]=1;
}else {
dp[i][j]=dp[i-1][j-1]+dp[i][j-1];
}
}
}
return dp[n][r];
}
}
class pair{
int wt,val;
pair(int wt,int val){
this.wt=wt;
this.val=val;
}
} | Java | ["5\n2 1 5\n42 13 24\n12 11 12\n1000000000 1000000000 1000000000\n2 1000000000 1000000000"] | 1 second | ["14\n33\n25\n2000000003\n1000000001999999999"] | null | Java 11 | standard input | [
"math"
] | 28610d192329c78580db354f8dfc4094 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains three integers $$$x$$$, $$$y$$$ and $$$k$$$ ($$$2 \le x \le 10^9$$$; $$$1 \le y, k \le 10^9$$$) — the number of sticks you can buy with one stick, the number of sticks required to buy one coal and the number of torches you need, respectively. | 1,000 | For each test case, print the answer: the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints. | standard output | |
PASSED | 4d9cea19db5d1f2db22c39acedc31891 | train_000.jsonl | 1600094100 | You are playing a very popular game called Cubecraft. Initially, you have one stick and want to craft $$$k$$$ torches. One torch can be crafted using one stick and one coal.Hopefully, you've met a very handsome wandering trader who has two trade offers: exchange $$$1$$$ stick for $$$x$$$ sticks (you lose $$$1$$$ stick and gain $$$x$$$ sticks). exchange $$$y$$$ sticks for $$$1$$$ coal (you lose $$$y$$$ sticks and gain $$$1$$$ coal). During one trade, you can use only one of these two trade offers. You can use each trade offer any number of times you want to, in any order.Your task is to find the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints.You have to answer $$$t$$$ independent test cases. | 256 megabytes |
import java.util.*;
import java.lang.*;
import java.io.*;
public class Test
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner s=new Scanner(System.in);
int test=s.nextInt();
for(int i=0;i<test;i++)
{
long x=s.nextInt();
long y=s.nextInt();
long k=s.nextInt();
long res=k;
long ans= k+k*y-1;
long inc= ans/(x-1);
if(ans%(x-1)!=0) inc++;
res+=inc;
System.out.println(res);
}
}
}
| Java | ["5\n2 1 5\n42 13 24\n12 11 12\n1000000000 1000000000 1000000000\n2 1000000000 1000000000"] | 1 second | ["14\n33\n25\n2000000003\n1000000001999999999"] | null | Java 11 | standard input | [
"math"
] | 28610d192329c78580db354f8dfc4094 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains three integers $$$x$$$, $$$y$$$ and $$$k$$$ ($$$2 \le x \le 10^9$$$; $$$1 \le y, k \le 10^9$$$) — the number of sticks you can buy with one stick, the number of sticks required to buy one coal and the number of torches you need, respectively. | 1,000 | For each test case, print the answer: the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints. | standard output | |
PASSED | 5e2bdd0538cd36ea5af7e57a39526d12 | train_000.jsonl | 1600094100 | You are playing a very popular game called Cubecraft. Initially, you have one stick and want to craft $$$k$$$ torches. One torch can be crafted using one stick and one coal.Hopefully, you've met a very handsome wandering trader who has two trade offers: exchange $$$1$$$ stick for $$$x$$$ sticks (you lose $$$1$$$ stick and gain $$$x$$$ sticks). exchange $$$y$$$ sticks for $$$1$$$ coal (you lose $$$y$$$ sticks and gain $$$1$$$ coal). During one trade, you can use only one of these two trade offers. You can use each trade offer any number of times you want to, in any order.Your task is to find the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.io.*;
import java.util.*;
public class Codeforces
{
public static void main(String args[])throws Exception
{
BufferedReader bu=new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb=new StringBuilder();
int t=Integer.parseInt(bu.readLine());
while(t-->0)
{
String s[]=bu.readLine().split(" ");
int x=Integer.parseInt(s[0]),y=Integer.parseInt(s[1]),k=Integer.parseInt(s[2]);
long c=1l*k*y;
long tot=c+k;
long ans=(tot-1)/(x-1)+((tot-1)%(x-1)==0?0:1)+k;
sb.append(ans+"\n");
}
System.out.print(sb);
}
} | Java | ["5\n2 1 5\n42 13 24\n12 11 12\n1000000000 1000000000 1000000000\n2 1000000000 1000000000"] | 1 second | ["14\n33\n25\n2000000003\n1000000001999999999"] | null | Java 11 | standard input | [
"math"
] | 28610d192329c78580db354f8dfc4094 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains three integers $$$x$$$, $$$y$$$ and $$$k$$$ ($$$2 \le x \le 10^9$$$; $$$1 \le y, k \le 10^9$$$) — the number of sticks you can buy with one stick, the number of sticks required to buy one coal and the number of torches you need, respectively. | 1,000 | For each test case, print the answer: the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints. | standard output | |
PASSED | 6b78e374d6416c0ca951e027a3a86d52 | train_000.jsonl | 1600094100 | You are playing a very popular game called Cubecraft. Initially, you have one stick and want to craft $$$k$$$ torches. One torch can be crafted using one stick and one coal.Hopefully, you've met a very handsome wandering trader who has two trade offers: exchange $$$1$$$ stick for $$$x$$$ sticks (you lose $$$1$$$ stick and gain $$$x$$$ sticks). exchange $$$y$$$ sticks for $$$1$$$ coal (you lose $$$y$$$ sticks and gain $$$1$$$ coal). During one trade, you can use only one of these two trade offers. You can use each trade offer any number of times you want to, in any order.Your task is to find the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
while (T-- > 0) {
int n = sc.nextInt();
int y = sc.nextInt();
int k = sc.nextInt();
long tS = (long)k*(1+y);
long count = (tS-1)/(n-1);
if (((n-1)*count)+1 < tS) count++;
System.out.println(count + k);
}
}
}
| Java | ["5\n2 1 5\n42 13 24\n12 11 12\n1000000000 1000000000 1000000000\n2 1000000000 1000000000"] | 1 second | ["14\n33\n25\n2000000003\n1000000001999999999"] | null | Java 11 | standard input | [
"math"
] | 28610d192329c78580db354f8dfc4094 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains three integers $$$x$$$, $$$y$$$ and $$$k$$$ ($$$2 \le x \le 10^9$$$; $$$1 \le y, k \le 10^9$$$) — the number of sticks you can buy with one stick, the number of sticks required to buy one coal and the number of torches you need, respectively. | 1,000 | For each test case, print the answer: the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints. | standard output | |
PASSED | 6be297619c577305b6730bdfdf27a51d | train_000.jsonl | 1600094100 | You are playing a very popular game called Cubecraft. Initially, you have one stick and want to craft $$$k$$$ torches. One torch can be crafted using one stick and one coal.Hopefully, you've met a very handsome wandering trader who has two trade offers: exchange $$$1$$$ stick for $$$x$$$ sticks (you lose $$$1$$$ stick and gain $$$x$$$ sticks). exchange $$$y$$$ sticks for $$$1$$$ coal (you lose $$$y$$$ sticks and gain $$$1$$$ coal). During one trade, you can use only one of these two trade offers. You can use each trade offer any number of times you want to, in any order.Your task is to find the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints.You have to answer $$$t$$$ independent test cases. | 256 megabytes | /******************************************************************************
Online Java Compiler.
Code, Compile, Run and Debug java program online.
Write your code in this editor and press "Run" button to execute it.
*******************************************************************************/
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t=sc.nextInt();
while(t-->0)
{
long x=sc.nextLong();
long y=sc.nextLong();
long k=sc.nextLong();
long ans=0;
long sticks_n=0;
sticks_n+=k+y*k;
sticks_n--;
ans+=k;
long sticks_o=1;
// while(sticks_o<sticks_n)
// {
// ans++;
// sticks_o+=x;
// sticks_o--;
// }
if(sticks_n%(x-1)==0)
{
ans+=(sticks_n/(x-1));
}
else
{
ans+=(sticks_n/(x-1))+1;
}
System.out.println(ans);
}
}
}
| Java | ["5\n2 1 5\n42 13 24\n12 11 12\n1000000000 1000000000 1000000000\n2 1000000000 1000000000"] | 1 second | ["14\n33\n25\n2000000003\n1000000001999999999"] | null | Java 11 | standard input | [
"math"
] | 28610d192329c78580db354f8dfc4094 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains three integers $$$x$$$, $$$y$$$ and $$$k$$$ ($$$2 \le x \le 10^9$$$; $$$1 \le y, k \le 10^9$$$) — the number of sticks you can buy with one stick, the number of sticks required to buy one coal and the number of torches you need, respectively. | 1,000 | For each test case, print the answer: the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints. | standard output | |
PASSED | 9ebcc52ac8dee103364624309a8564b1 | train_000.jsonl | 1600094100 | You are playing a very popular game called Cubecraft. Initially, you have one stick and want to craft $$$k$$$ torches. One torch can be crafted using one stick and one coal.Hopefully, you've met a very handsome wandering trader who has two trade offers: exchange $$$1$$$ stick for $$$x$$$ sticks (you lose $$$1$$$ stick and gain $$$x$$$ sticks). exchange $$$y$$$ sticks for $$$1$$$ coal (you lose $$$y$$$ sticks and gain $$$1$$$ coal). During one trade, you can use only one of these two trade offers. You can use each trade offer any number of times you want to, in any order.Your task is to find the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.io.*;
import java.util.*;
public class noob {
InputReader in;
final long mod=1000000007;
StringBuilder sb;
public static void main(String[] args) throws java.lang.Exception {
new noob().run();
}
void run() throws Exception {
in=new InputReader(System.in);
sb = new StringBuilder();
int t=i();
for(int i=1;i<=t;i++)
solve();
System.out.print(sb);
}
void solve() {
int i,j;
long x=l(), y=l(), k=l();
long req=k*y + k - 1;
long ans=req/(x-1);
if(req % (x-1) > 0)
ans++;
ans+=k;
sb.append(ans+"\n");
}
long power(long x, long y, long p) {
long res = 1;
x = x % p;
if (x == 0) return 0;
while (y > 0) {
if((y & 1)==1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res%p;
}
int gcd(int a, int b) {
return (b==0)?a:gcd(b,a%b);
}
String s(){return in.next();}
int i(){return in.nextInt();}
long l(){return in.nextLong();}
double d(){return in.nextDouble();}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new UnknownError();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new UnknownError();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int peek() {
if (numChars == -1)
return -1;
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
if (numChars <= 0)
return -1;
}
return buf[curChar];
}
public void skip(int x) {
while (x-->0)
read();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public String nextString() {
return next();
}
public String next() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuffer res = new StringBuffer();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
StringBuffer buf = new StringBuffer();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r')
buf.appendCodePoint(c);
c = read();
}
return buf.toString();
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public boolean hasNext() {
int value;
while (isSpaceChar(value = peek()) && value != -1)
read();
return value != -1;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
} | Java | ["5\n2 1 5\n42 13 24\n12 11 12\n1000000000 1000000000 1000000000\n2 1000000000 1000000000"] | 1 second | ["14\n33\n25\n2000000003\n1000000001999999999"] | null | Java 11 | standard input | [
"math"
] | 28610d192329c78580db354f8dfc4094 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains three integers $$$x$$$, $$$y$$$ and $$$k$$$ ($$$2 \le x \le 10^9$$$; $$$1 \le y, k \le 10^9$$$) — the number of sticks you can buy with one stick, the number of sticks required to buy one coal and the number of torches you need, respectively. | 1,000 | For each test case, print the answer: the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints. | standard output | |
PASSED | 030b065149f2725f4f4dc9d4cb8be14b | train_000.jsonl | 1600094100 | You are playing a very popular game called Cubecraft. Initially, you have one stick and want to craft $$$k$$$ torches. One torch can be crafted using one stick and one coal.Hopefully, you've met a very handsome wandering trader who has two trade offers: exchange $$$1$$$ stick for $$$x$$$ sticks (you lose $$$1$$$ stick and gain $$$x$$$ sticks). exchange $$$y$$$ sticks for $$$1$$$ coal (you lose $$$y$$$ sticks and gain $$$1$$$ coal). During one trade, you can use only one of these two trade offers. You can use each trade offer any number of times you want to, in any order.Your task is to find the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.Scanner;
public class BuyingTorches {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- != 0) {
//Helloworld
long n = sc.nextLong();
long c = sc.nextLong();
long k = sc.nextLong();
long trades;
long sticks = (c+1)*k;
if((sticks-1)%(n-1)==0){
trades=(sticks-1)/(n-1)+k;
}
else {
trades=(sticks-1)/(n-1)+k+1;
}
System.out.println(trades);
}
}
}
| Java | ["5\n2 1 5\n42 13 24\n12 11 12\n1000000000 1000000000 1000000000\n2 1000000000 1000000000"] | 1 second | ["14\n33\n25\n2000000003\n1000000001999999999"] | null | Java 11 | standard input | [
"math"
] | 28610d192329c78580db354f8dfc4094 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains three integers $$$x$$$, $$$y$$$ and $$$k$$$ ($$$2 \le x \le 10^9$$$; $$$1 \le y, k \le 10^9$$$) — the number of sticks you can buy with one stick, the number of sticks required to buy one coal and the number of torches you need, respectively. | 1,000 | For each test case, print the answer: the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints. | standard output | |
PASSED | 883441bf490bf4ad561dfae2b3ca3476 | train_000.jsonl | 1600094100 | You are playing a very popular game called Cubecraft. Initially, you have one stick and want to craft $$$k$$$ torches. One torch can be crafted using one stick and one coal.Hopefully, you've met a very handsome wandering trader who has two trade offers: exchange $$$1$$$ stick for $$$x$$$ sticks (you lose $$$1$$$ stick and gain $$$x$$$ sticks). exchange $$$y$$$ sticks for $$$1$$$ coal (you lose $$$y$$$ sticks and gain $$$1$$$ coal). During one trade, you can use only one of these two trade offers. You can use each trade offer any number of times you want to, in any order.Your task is to find the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
import java.awt.geom.*;
import static java.lang.Math.*;
public class Solution implements Runnable {
long mod1 = (long) 1e9 + 7;
int mod2 = 998244353;
public void solve() throws Exception {
int t = sc.nextInt();
while (t-- > 0) {
long x=sc.nextLong();
long y=sc.nextLong();
long k=sc.nextLong();
long ans=0;
ans+=(k*y+k-1)/(x-1)+((k*y+k-1)%(x-1)!=0?1:0);
out.println(ans+k);
}
}
static long gcd(long a, long b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
static long ncr(int n, int r, long p) {
if (r > n)
return 0l;
if (r > n - r)
r = n - r;
long C[] = new long[r + 1];
C[0] = 1;
for (int i = 1; i <= n; i++) {
for (int j = Math.min(i, r); j > 0; j--)
C[j] = (C[j] + C[j - 1]) % p;
}
return C[r] % p;
}
public long power(long x, long y, long p) {
long res = 1;
// out.println(x+" "+y);
x = x % p;
if (x == 0)
return 0;
while (y > 0) {
if ((y & 1) == 1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
static Throwable uncaught;
BufferedReader in;
FastScanner sc;
PrintWriter out;
@Override
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
sc = new FastScanner(in);
solve();
} catch (Throwable uncaught) {
Solution.uncaught = uncaught;
} finally {
out.close();
}
}
public static void main(String[] args) throws Throwable {
Thread thread = new Thread(null, new Solution(), "", (1 << 26));
thread.start();
thread.join();
if (Solution.uncaught != null) {
throw Solution.uncaught;
}
}
}
class FastScanner {
BufferedReader in;
StringTokenizer st;
public FastScanner(BufferedReader in) {
this.in = in;
}
public String nextToken() throws Exception {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
public int nextInt() throws Exception {
return Integer.parseInt(nextToken());
}
public int[] readArray(int n) throws Exception {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public long nextLong() throws Exception {
return Long.parseLong(nextToken());
}
public double nextDouble() throws Exception {
return Double.parseDouble(nextToken());
}
} | Java | ["5\n2 1 5\n42 13 24\n12 11 12\n1000000000 1000000000 1000000000\n2 1000000000 1000000000"] | 1 second | ["14\n33\n25\n2000000003\n1000000001999999999"] | null | Java 11 | standard input | [
"math"
] | 28610d192329c78580db354f8dfc4094 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains three integers $$$x$$$, $$$y$$$ and $$$k$$$ ($$$2 \le x \le 10^9$$$; $$$1 \le y, k \le 10^9$$$) — the number of sticks you can buy with one stick, the number of sticks required to buy one coal and the number of torches you need, respectively. | 1,000 | For each test case, print the answer: the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints. | standard output | |
PASSED | 7e0c049ba06f81e545a65b3e0acc04a3 | train_000.jsonl | 1600094100 | You are playing a very popular game called Cubecraft. Initially, you have one stick and want to craft $$$k$$$ torches. One torch can be crafted using one stick and one coal.Hopefully, you've met a very handsome wandering trader who has two trade offers: exchange $$$1$$$ stick for $$$x$$$ sticks (you lose $$$1$$$ stick and gain $$$x$$$ sticks). exchange $$$y$$$ sticks for $$$1$$$ coal (you lose $$$y$$$ sticks and gain $$$1$$$ coal). During one trade, you can use only one of these two trade offers. You can use each trade offer any number of times you want to, in any order.Your task is to find the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.ParseException;
import java.util.*;
public class Main {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st;
static StringBuilder sb = new StringBuilder("");
static int[] inputArray(int n) throws IOException {
int[] a = new int[n];
st = new StringTokenizer(br.readLine());
for(int i = 0 ; i < n ; i++) {
a[i] = Integer.parseInt(st.nextToken());
}
return a;
}
public static void main(String[] args) throws IOException {
int t = Integer.parseInt(br.readLine());
while(t-- != 0) {
st = new StringTokenizer(br.readLine());
long x = Long.parseLong(st.nextToken());
long y = Long.parseLong(st.nextToken());
long k = Long.parseLong(st.nextToken());
long u = (k + y * k - 1);
if(u % (x-1) == 0) {
System.out.println(u/(x-1) + k);
}
else {
System.out.println((u/(x-1) + 1) + k);
}
}
}
private static int Code(int a[][] , int b[][] , int n) {
Arrays.sort(a, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return o1[0] - o2[0];
}
});
Arrays.sort(b, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return o1[0] - o2[0];
}
});
HashMap<Integer , Integer> freq = new HashMap<>();
int cnt = 0;
int i = 0 , j = 0;
while(i < n && j < n) {
if(a[i][0] == b[i][0]) {
if(a[i][1] < b[i][1]) {
int k = b[i][1] - a[i][1];
if(freq.containsKey(k)) {
freq.replace(k , freq.get(k) + 1);
}
else {
freq.put(k , 1);
}
if(freq.containsKey(k - n)) {
freq.replace(k - n , freq.get(k - n) + 1);
}
else {
freq.put(k - n , 1);
}
}
else {
int k = b[i][1] - a[i][1];
if(freq.containsKey(k)) {
freq.replace(k , freq.get(k) + 1);
}
else {
freq.put(k , 1);
}
if(freq.containsKey(k + n)) {
freq.replace(k + n , freq.get(k + n) + 1);
}
else {
freq.put(k + n , 1);
}
}
i++;
j++;
}
else if(a[i][0] < b[i][0]) {
i++;
}
else {
j++;
}
}
for(Map.Entry<Integer , Integer> map : freq.entrySet()) {
cnt = Math.max(cnt , map.getValue());
}
return cnt;
}
} | Java | ["5\n2 1 5\n42 13 24\n12 11 12\n1000000000 1000000000 1000000000\n2 1000000000 1000000000"] | 1 second | ["14\n33\n25\n2000000003\n1000000001999999999"] | null | Java 11 | standard input | [
"math"
] | 28610d192329c78580db354f8dfc4094 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains three integers $$$x$$$, $$$y$$$ and $$$k$$$ ($$$2 \le x \le 10^9$$$; $$$1 \le y, k \le 10^9$$$) — the number of sticks you can buy with one stick, the number of sticks required to buy one coal and the number of torches you need, respectively. | 1,000 | For each test case, print the answer: the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints. | standard output | |
PASSED | 3f83ddafea908a92bf14826f0a14df9c | train_000.jsonl | 1600094100 | You are playing a very popular game called Cubecraft. Initially, you have one stick and want to craft $$$k$$$ torches. One torch can be crafted using one stick and one coal.Hopefully, you've met a very handsome wandering trader who has two trade offers: exchange $$$1$$$ stick for $$$x$$$ sticks (you lose $$$1$$$ stick and gain $$$x$$$ sticks). exchange $$$y$$$ sticks for $$$1$$$ coal (you lose $$$y$$$ sticks and gain $$$1$$$ coal). During one trade, you can use only one of these two trade offers. You can use each trade offer any number of times you want to, in any order.Your task is to find the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints.You have to answer $$$t$$$ independent test cases. | 256 megabytes |
import java.io.BufferedReader;
import java.util.Scanner;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
import java.math.BigInteger;
public class A
{
static Scanner sc=new Scanner(System.in);
static PrintWriter out=new PrintWriter(System.out);
static void pn(Object o)
{
out.println(o);
out.flush();
}
static void p(Object o)
{
out.print(o);
out.flush();
}
static void pni(Object o)
{
out.println(o);System.out.flush();
}
static int I() throws IOException
{
return sc.nextInt();
}
static long L()throws IOException
{
return sc.nextLong();
}
static double D()throws IOException
{
return sc.nextDouble();
}
static String S()throws IOException
{
return sc.next();
}
static char C() throws IOException
{
return sc.next().charAt(0);
}
public static void process() throws IOException
{
long x=L();
long y=L();
y=y*1;
long k=L();
long p=(((k+(y*k))-1)/(x-1));
if(((k+(y*k)-1)%(x-1)==0))
{
p=p*1;
}
else
{
p=p+1;
}
pn(p+k);
}
public static void main(String[] args) throws IOException {
int t = I();
while (t-- > 0)
process();
}
} | Java | ["5\n2 1 5\n42 13 24\n12 11 12\n1000000000 1000000000 1000000000\n2 1000000000 1000000000"] | 1 second | ["14\n33\n25\n2000000003\n1000000001999999999"] | null | Java 11 | standard input | [
"math"
] | 28610d192329c78580db354f8dfc4094 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains three integers $$$x$$$, $$$y$$$ and $$$k$$$ ($$$2 \le x \le 10^9$$$; $$$1 \le y, k \le 10^9$$$) — the number of sticks you can buy with one stick, the number of sticks required to buy one coal and the number of torches you need, respectively. | 1,000 | For each test case, print the answer: the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints. | standard output | |
PASSED | bc027ee22622c7bcb6d325fef64ea40e | train_000.jsonl | 1600094100 | You are playing a very popular game called Cubecraft. Initially, you have one stick and want to craft $$$k$$$ torches. One torch can be crafted using one stick and one coal.Hopefully, you've met a very handsome wandering trader who has two trade offers: exchange $$$1$$$ stick for $$$x$$$ sticks (you lose $$$1$$$ stick and gain $$$x$$$ sticks). exchange $$$y$$$ sticks for $$$1$$$ coal (you lose $$$y$$$ sticks and gain $$$1$$$ coal). During one trade, you can use only one of these two trade offers. You can use each trade offer any number of times you want to, in any order.Your task is to find the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.Scanner;
public class BuyingTorches {
//1418A: 购买火炬
private long exSticks; //在一次交易中1单位木棍能够兑换的木棍数量
private long exCoals; //在一次交易中兑换1单位煤需要的木棍数量
private long torchesNumber; //需要合成的火炬数量
private long tradeNumber; //交易发生的次数
private BuyingTorches() {
}
public BuyingTorches(long exSticks,long exCoals,long torchesNumber) {
this.exSticks = exSticks;
this.exCoals = exCoals;
this.torchesNumber = torchesNumber;
}
public long getTradeNumber() {
long getSticks = exSticks-1;
long getCoals = exCoals;
tradeNumber = 0;
//获得目标数量煤所需要的交换次数
tradeNumber += (getCoals*torchesNumber)/getSticks+((getCoals*torchesNumber)%getSticks!=0?1:0); //获取交换煤所需的木棍
long remainSticks = tradeNumber*getSticks-torchesNumber*getCoals+1; //除去交换煤所需木棍外的剩余木棍,初始1木棍
//System.out.println("test0:"+remainSticks);
tradeNumber += torchesNumber; //把木棍交换成煤
//System.out.println("test1:"+tradeNumber);
//交换目标数量木棍所需要的交换次数
if(torchesNumber>remainSticks)
tradeNumber += (torchesNumber-remainSticks)/getSticks+((torchesNumber-remainSticks)%getSticks!=0?1:0);
//System.out.println("test2:"+(torchesNumber-remainSticks));
return tradeNumber;
}
public static void main(String args[]) {
int T;
long exSticks,exCoals,torchesNumber;
BuyingTorches buyingTorches;
Scanner scanner = new Scanner(System.in);
T = scanner.nextInt();
while(T-->0) {
exSticks = scanner.nextLong();
exCoals = scanner.nextLong();
torchesNumber = scanner.nextLong();
buyingTorches = new BuyingTorches(exSticks,exCoals,torchesNumber);
System.out.println(buyingTorches.getTradeNumber());
}
}
}
| Java | ["5\n2 1 5\n42 13 24\n12 11 12\n1000000000 1000000000 1000000000\n2 1000000000 1000000000"] | 1 second | ["14\n33\n25\n2000000003\n1000000001999999999"] | null | Java 11 | standard input | [
"math"
] | 28610d192329c78580db354f8dfc4094 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains three integers $$$x$$$, $$$y$$$ and $$$k$$$ ($$$2 \le x \le 10^9$$$; $$$1 \le y, k \le 10^9$$$) — the number of sticks you can buy with one stick, the number of sticks required to buy one coal and the number of torches you need, respectively. | 1,000 | For each test case, print the answer: the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints. | standard output | |
PASSED | 3fe8aa1e0631b8e4e45ecf8fc4448204 | train_000.jsonl | 1600094100 | You are playing a very popular game called Cubecraft. Initially, you have one stick and want to craft $$$k$$$ torches. One torch can be crafted using one stick and one coal.Hopefully, you've met a very handsome wandering trader who has two trade offers: exchange $$$1$$$ stick for $$$x$$$ sticks (you lose $$$1$$$ stick and gain $$$x$$$ sticks). exchange $$$y$$$ sticks for $$$1$$$ coal (you lose $$$y$$$ sticks and gain $$$1$$$ coal). During one trade, you can use only one of these two trade offers. You can use each trade offer any number of times you want to, in any order.Your task is to find the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.Scanner;
public class q1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long t=sc.nextInt();
for(long c=1;c<=t;c++){
long count=0;
long x= sc.nextInt();
long y=sc.nextInt();
long k=sc.nextInt();
count+=k;
// total sticks=(y+1)*k
if(((((y+1)*k)-1)%(x-1))==0)count+=((((y+1)*k)-1)/(x-1));
else{
count+=((((y+1)*k)-1)/(x-1))+1;
}
System.out.println(count);
}
sc.close();
}
} | Java | ["5\n2 1 5\n42 13 24\n12 11 12\n1000000000 1000000000 1000000000\n2 1000000000 1000000000"] | 1 second | ["14\n33\n25\n2000000003\n1000000001999999999"] | null | Java 11 | standard input | [
"math"
] | 28610d192329c78580db354f8dfc4094 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains three integers $$$x$$$, $$$y$$$ and $$$k$$$ ($$$2 \le x \le 10^9$$$; $$$1 \le y, k \le 10^9$$$) — the number of sticks you can buy with one stick, the number of sticks required to buy one coal and the number of torches you need, respectively. | 1,000 | For each test case, print the answer: the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints. | standard output | |
PASSED | 59c8b65b5fac9d50a7834dea9aad34db | train_000.jsonl | 1600094100 | You are playing a very popular game called Cubecraft. Initially, you have one stick and want to craft $$$k$$$ torches. One torch can be crafted using one stick and one coal.Hopefully, you've met a very handsome wandering trader who has two trade offers: exchange $$$1$$$ stick for $$$x$$$ sticks (you lose $$$1$$$ stick and gain $$$x$$$ sticks). exchange $$$y$$$ sticks for $$$1$$$ coal (you lose $$$y$$$ sticks and gain $$$1$$$ coal). During one trade, you can use only one of these two trade offers. You can use each trade offer any number of times you want to, in any order.Your task is to find the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints.You have to answer $$$t$$$ independent test cases. | 256 megabytes | /* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0)
{
long x=sc.nextLong();
long y=sc.nextLong();
long k=sc.nextLong();
System.out.println(find(x,y,k));
}
}
private static long find(long x, long y, long k) {
// TODO Auto-generated method stub
long count=0;
long init=1;
count=k;
k=(k*y)+k;
// System.out.println(k);
long div=(k-1)/(x-1);
// Syste/m.out.println(div);
k=k-(x-1)*div;
// System.out.println(k);
// System.out.println(div);
if(k%x!=0&&k%x!=1)
div++;
return div+count;
}
}
| Java | ["5\n2 1 5\n42 13 24\n12 11 12\n1000000000 1000000000 1000000000\n2 1000000000 1000000000"] | 1 second | ["14\n33\n25\n2000000003\n1000000001999999999"] | null | Java 11 | standard input | [
"math"
] | 28610d192329c78580db354f8dfc4094 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains three integers $$$x$$$, $$$y$$$ and $$$k$$$ ($$$2 \le x \le 10^9$$$; $$$1 \le y, k \le 10^9$$$) — the number of sticks you can buy with one stick, the number of sticks required to buy one coal and the number of torches you need, respectively. | 1,000 | For each test case, print the answer: the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints. | standard output | |
PASSED | 8461de33be8e402ad15908f6e1eaf943 | train_000.jsonl | 1600094100 | You are playing a very popular game called Cubecraft. Initially, you have one stick and want to craft $$$k$$$ torches. One torch can be crafted using one stick and one coal.Hopefully, you've met a very handsome wandering trader who has two trade offers: exchange $$$1$$$ stick for $$$x$$$ sticks (you lose $$$1$$$ stick and gain $$$x$$$ sticks). exchange $$$y$$$ sticks for $$$1$$$ coal (you lose $$$y$$$ sticks and gain $$$1$$$ coal). During one trade, you can use only one of these two trade offers. You can use each trade offer any number of times you want to, in any order.Your task is to find the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int t = scn.nextInt();
for (int i =0; i<t; i++){
long n1 = scn.nextLong();
long n2 = scn.nextLong();
long n3 = scn.nextLong();
if((n3*n2+n3-1)%(n1-1)==0){
System.out.println((n3*n2+n3-1)/(n1-1)+n3);
} else {
System.out.println((n3*n2+n3-1)/(n1-1)+n3+1);
}
}
}
}
| Java | ["5\n2 1 5\n42 13 24\n12 11 12\n1000000000 1000000000 1000000000\n2 1000000000 1000000000"] | 1 second | ["14\n33\n25\n2000000003\n1000000001999999999"] | null | Java 11 | standard input | [
"math"
] | 28610d192329c78580db354f8dfc4094 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains three integers $$$x$$$, $$$y$$$ and $$$k$$$ ($$$2 \le x \le 10^9$$$; $$$1 \le y, k \le 10^9$$$) — the number of sticks you can buy with one stick, the number of sticks required to buy one coal and the number of torches you need, respectively. | 1,000 | For each test case, print the answer: the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints. | standard output | |
PASSED | 86a0d522330a000d3b8771d58810ceaa | train_000.jsonl | 1600094100 | You are playing a very popular game called Cubecraft. Initially, you have one stick and want to craft $$$k$$$ torches. One torch can be crafted using one stick and one coal.Hopefully, you've met a very handsome wandering trader who has two trade offers: exchange $$$1$$$ stick for $$$x$$$ sticks (you lose $$$1$$$ stick and gain $$$x$$$ sticks). exchange $$$y$$$ sticks for $$$1$$$ coal (you lose $$$y$$$ sticks and gain $$$1$$$ coal). During one trade, you can use only one of these two trade offers. You can use each trade offer any number of times you want to, in any order.Your task is to find the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
public class C1418A {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t =sc.nextInt();
for(int i = 0 ; i < t ; i++) {
long x = sc.nextLong();
long y = sc.nextLong();
long k = sc.nextLong();
long gain = x-1;
long neededSticks = k*y-1;
long answer = 0;
if((neededSticks+k) % gain == 0) {
answer = (neededSticks+k)/gain ;
}
else {
answer = (neededSticks+k)/gain + 1;
}
System.out.println(answer+k);
}
}
}
/*
5
2 1 5
42 13 24
12 11 12
1000000000 1000000000 1000000000
2 1000000000 1000000000
14
32 ? add one more
25
2000000002 ? add one more
1000000001999999999
*/ | Java | ["5\n2 1 5\n42 13 24\n12 11 12\n1000000000 1000000000 1000000000\n2 1000000000 1000000000"] | 1 second | ["14\n33\n25\n2000000003\n1000000001999999999"] | null | Java 11 | standard input | [
"math"
] | 28610d192329c78580db354f8dfc4094 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains three integers $$$x$$$, $$$y$$$ and $$$k$$$ ($$$2 \le x \le 10^9$$$; $$$1 \le y, k \le 10^9$$$) — the number of sticks you can buy with one stick, the number of sticks required to buy one coal and the number of torches you need, respectively. | 1,000 | For each test case, print the answer: the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints. | standard output | |
PASSED | c70cad23c447cf4f212a105c79cc9d27 | train_000.jsonl | 1600094100 | You are playing a very popular game called Cubecraft. Initially, you have one stick and want to craft $$$k$$$ torches. One torch can be crafted using one stick and one coal.Hopefully, you've met a very handsome wandering trader who has two trade offers: exchange $$$1$$$ stick for $$$x$$$ sticks (you lose $$$1$$$ stick and gain $$$x$$$ sticks). exchange $$$y$$$ sticks for $$$1$$$ coal (you lose $$$y$$$ sticks and gain $$$1$$$ coal). During one trade, you can use only one of these two trade offers. You can use each trade offer any number of times you want to, in any order.Your task is to find the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
public class C1418A {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t =sc.nextInt();
for(int i = 0 ; i < t ; i++) {
long x = sc.nextLong();
long y = sc.nextLong();
long k = sc.nextLong();
long gain = x-1;
long neededSticks = k*y-1;
long answer = 0;
if((neededSticks+k) % gain == 0) {
answer = (neededSticks+k)/gain ;
}
else {
answer = (neededSticks+k)/gain + 1;
}
System.out.println(answer+k);
}
}
}
/* c
5
2 1 5
42 13 24
12 11 12
1000000000 1000000000 1000000000
2 1000000000 1000000000
14
32 ? add one more
25
2000000002 ? add one more
1000000001999999999
*/ | Java | ["5\n2 1 5\n42 13 24\n12 11 12\n1000000000 1000000000 1000000000\n2 1000000000 1000000000"] | 1 second | ["14\n33\n25\n2000000003\n1000000001999999999"] | null | Java 11 | standard input | [
"math"
] | 28610d192329c78580db354f8dfc4094 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains three integers $$$x$$$, $$$y$$$ and $$$k$$$ ($$$2 \le x \le 10^9$$$; $$$1 \le y, k \le 10^9$$$) — the number of sticks you can buy with one stick, the number of sticks required to buy one coal and the number of torches you need, respectively. | 1,000 | For each test case, print the answer: the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints. | standard output | |
PASSED | 2f3a39bf9dc7e52c4a4ccc3a85b137ff | train_000.jsonl | 1600094100 | You are playing a very popular game called Cubecraft. Initially, you have one stick and want to craft $$$k$$$ torches. One torch can be crafted using one stick and one coal.Hopefully, you've met a very handsome wandering trader who has two trade offers: exchange $$$1$$$ stick for $$$x$$$ sticks (you lose $$$1$$$ stick and gain $$$x$$$ sticks). exchange $$$y$$$ sticks for $$$1$$$ coal (you lose $$$y$$$ sticks and gain $$$1$$$ coal). During one trade, you can use only one of these two trade offers. You can use each trade offer any number of times you want to, in any order.Your task is to find the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
public class Solve8 {
public static void main(String[] args) throws IOException {
PrintWriter pw = new PrintWriter(System.out);
new Solve8().solve(pw);
pw.flush();
pw.close();
}
public void solve(PrintWriter pw) throws IOException {
FastReader sc = new FastReader();
int t = sc.nextInt();
while (t-- > 0) {
long x = sc.nextLong(), y = sc.nextLong(), k = sc.nextLong();
long z = (k + k * y - 1) / (x - 1) + (((k + k * y - 1) % (x - 1)) == 0 ? 0 : 1) + k;
pw.println(z);
}
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) {
try {
br = new BufferedReader(new FileReader(s));
} catch (FileNotFoundException e) {
}
}
public String next() {
if (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
try {
return br.readLine();
} catch (Exception e) {
}
return null;
}
public boolean hasNext() throws IOException {
if (st != null && st.hasMoreTokens()) {
return true;
}
String s = br.readLine();
if (s == null || s.isEmpty()) {
return false;
}
st = new StringTokenizer(s);
return true;
}
}
}
| Java | ["5\n2 1 5\n42 13 24\n12 11 12\n1000000000 1000000000 1000000000\n2 1000000000 1000000000"] | 1 second | ["14\n33\n25\n2000000003\n1000000001999999999"] | null | Java 11 | standard input | [
"math"
] | 28610d192329c78580db354f8dfc4094 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains three integers $$$x$$$, $$$y$$$ and $$$k$$$ ($$$2 \le x \le 10^9$$$; $$$1 \le y, k \le 10^9$$$) — the number of sticks you can buy with one stick, the number of sticks required to buy one coal and the number of torches you need, respectively. | 1,000 | For each test case, print the answer: the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints. | standard output | |
PASSED | c9fb89a55ec8041c27d6ee035cfaa3e6 | train_000.jsonl | 1600094100 | You are playing a very popular game called Cubecraft. Initially, you have one stick and want to craft $$$k$$$ torches. One torch can be crafted using one stick and one coal.Hopefully, you've met a very handsome wandering trader who has two trade offers: exchange $$$1$$$ stick for $$$x$$$ sticks (you lose $$$1$$$ stick and gain $$$x$$$ sticks). exchange $$$y$$$ sticks for $$$1$$$ coal (you lose $$$y$$$ sticks and gain $$$1$$$ coal). During one trade, you can use only one of these two trade offers. You can use each trade offer any number of times you want to, in any order.Your task is to find the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.math.BigInteger;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();
Case[] cases=new Case[n];
for(int i=0;i<n;i++){
Case c=new Case();
cases[i]=c;
cases[i].x=scan.nextLong();
cases[i].y=scan.nextLong();
cases[i].k=scan.nextLong();
}
for(int i=0;i<n;i++){
long coalReq=cases[i].k;
long sticksReq=cases[i].k-1;
long ans=0;
sticksReq+=coalReq*cases[i].y;
ans+=cases[i].k;
if(sticksReq%(cases[i].x-1)>0){
ans+=1;
}
sticksReq/=(cases[i].x-1);
ans+=sticksReq;
System.out.println(ans);
}
}
}
class Case{
public long x;
public long y;
public long k;
}
| Java | ["5\n2 1 5\n42 13 24\n12 11 12\n1000000000 1000000000 1000000000\n2 1000000000 1000000000"] | 1 second | ["14\n33\n25\n2000000003\n1000000001999999999"] | null | Java 11 | standard input | [
"math"
] | 28610d192329c78580db354f8dfc4094 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains three integers $$$x$$$, $$$y$$$ and $$$k$$$ ($$$2 \le x \le 10^9$$$; $$$1 \le y, k \le 10^9$$$) — the number of sticks you can buy with one stick, the number of sticks required to buy one coal and the number of torches you need, respectively. | 1,000 | For each test case, print the answer: the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints. | standard output | |
PASSED | 7dc8e6db88e87ac93e90c6d7a13e1a25 | train_000.jsonl | 1435676400 | Pasha decided to invite his friends to a tea party. For that occasion, he has a large teapot with the capacity of w milliliters and 2n tea cups, each cup is for one of Pasha's friends. The i-th cup can hold at most ai milliliters of water.It turned out that among Pasha's friends there are exactly n boys and exactly n girls and all of them are going to come to the tea party. To please everyone, Pasha decided to pour the water for the tea as follows: Pasha can boil the teapot exactly once by pouring there at most w milliliters of water; Pasha pours the same amount of water to each girl; Pasha pours the same amount of water to each boy; if each girl gets x milliliters of water, then each boy gets 2x milliliters of water. In the other words, each boy should get two times more water than each girl does.Pasha is very kind and polite, so he wants to maximize the total amount of the water that he pours to his friends. Your task is to help him and determine the optimum distribution of cups between Pasha's friends. | 256 megabytes | import java.io.*;
import java.util.*;
public class Solution{
public static void main(String arg[])throws IOException
{
BufferedReader io =new BufferedReader(new InputStreamReader(System.in));
String[] input1 = io.readLine().trim().split(" ");
int n = Integer.parseInt(input1[0]);
int w = Integer.parseInt(input1[1]);
int[] cups= Arrays.stream(io.readLine().split("\\s+")
).mapToInt(Integer::parseInt).toArray();
double ans=0.0;
Arrays.sort(cups);
if(2*cups[0]>cups[n])
{
ans = cups[n]/2.0;
}
else{
ans = cups[0];
}
double answer=ans*3.0*n;
if(answer>w)
answer=w;
System.out.println(answer);
}
} | Java | ["2 4\n1 1 1 1", "3 18\n4 4 4 2 2 2", "1 5\n2 3"] | 1 second | ["3", "18", "4.5"] | NotePasha also has candies that he is going to give to girls but that is another task... | Java 11 | standard input | [
"constructive algorithms",
"implementation",
"sortings",
"math"
] | b2031a328d72b464f965b4789fd35b93 | The first line of the input contains two integers, n and w (1 ≤ n ≤ 105, 1 ≤ w ≤ 109) — the number of Pasha's friends that are boys (equal to the number of Pasha's friends that are girls) and the capacity of Pasha's teapot in milliliters. The second line of the input contains the sequence of integers ai (1 ≤ ai ≤ 109, 1 ≤ i ≤ 2n) — the capacities of Pasha's tea cups in milliliters. | 1,500 | Print a single real number — the maximum total amount of water in milliliters that Pasha can pour to his friends without violating the given conditions. Your answer will be considered correct if its absolute or relative error doesn't exceed 10 - 6. | standard output | |
PASSED | d3fde4d3d4bb4798b3a880ed786f97ed | train_000.jsonl | 1435676400 | Pasha decided to invite his friends to a tea party. For that occasion, he has a large teapot with the capacity of w milliliters and 2n tea cups, each cup is for one of Pasha's friends. The i-th cup can hold at most ai milliliters of water.It turned out that among Pasha's friends there are exactly n boys and exactly n girls and all of them are going to come to the tea party. To please everyone, Pasha decided to pour the water for the tea as follows: Pasha can boil the teapot exactly once by pouring there at most w milliliters of water; Pasha pours the same amount of water to each girl; Pasha pours the same amount of water to each boy; if each girl gets x milliliters of water, then each boy gets 2x milliliters of water. In the other words, each boy should get two times more water than each girl does.Pasha is very kind and polite, so he wants to maximize the total amount of the water that he pours to his friends. Your task is to help him and determine the optimum distribution of cups between Pasha's friends. | 256 megabytes | import java.util.*;
public class Solution {
private static boolean isSorted(int[] arr) {
for (int i = 0; i< arr.length - 1; i++) {
if (arr[i] > arr[i+1]) return false;
}
return true;
}
private static void reverse(int[] arr, int from, int to) {
int i, t;
int d = (to-from+1)/2;
for (i = 0; i < d; i++) {
t = arr[from + i];
arr[from + i] = arr[to - i];
arr[to - i] = t;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int w = sc.nextInt();
int[] caps = new int[2*n];
for (int i = 0; i< 2*n; i++) {
caps[i] = sc.nextInt();
}
Arrays.sort(caps);
int[] boysCap = new int[n];
int[] girlsCap = new int[n];
for (int i = 0; i < n; i++)
girlsCap[i] = caps[i];
for (int i = n; i < 2*n; i++)
boysCap[i - n] = caps[i];
double[] boysTea = new double[n];
double[] girlsTea = new double[n];
double girlTea =((double) w / 3) / n;
if (girlTea < girlsCap[0] ) {
for (int i = 0; i < n; i++) {
girlsTea[i] = girlTea;
}
}
else {
for (int i = 0; i< n; i++) {
girlsTea[i] = girlsCap[0];
}
}
double boyTea = girlsTea[0] * 2;
if (boyTea < boysCap[0]) {
for (int i = 0; i < n; i++) {
boysTea[i] = boyTea;
}
}
else {
for (int i = 0; i < n; i++) {
boyTea = boysCap[0];
boysTea[i] = boyTea;
girlsTea[i] = boyTea / 2;
}
}
double total = 0;
for (int i = 0; i< n; i++) {
total += boysTea[i];
total += girlsTea[i];
}
System.out.println(total);
}
}
| Java | ["2 4\n1 1 1 1", "3 18\n4 4 4 2 2 2", "1 5\n2 3"] | 1 second | ["3", "18", "4.5"] | NotePasha also has candies that he is going to give to girls but that is another task... | Java 11 | standard input | [
"constructive algorithms",
"implementation",
"sortings",
"math"
] | b2031a328d72b464f965b4789fd35b93 | The first line of the input contains two integers, n and w (1 ≤ n ≤ 105, 1 ≤ w ≤ 109) — the number of Pasha's friends that are boys (equal to the number of Pasha's friends that are girls) and the capacity of Pasha's teapot in milliliters. The second line of the input contains the sequence of integers ai (1 ≤ ai ≤ 109, 1 ≤ i ≤ 2n) — the capacities of Pasha's tea cups in milliliters. | 1,500 | Print a single real number — the maximum total amount of water in milliliters that Pasha can pour to his friends without violating the given conditions. Your answer will be considered correct if its absolute or relative error doesn't exceed 10 - 6. | standard output | |
PASSED | 41e455be1d92aa1cccfeb9339f0c0930 | train_000.jsonl | 1435676400 | Pasha decided to invite his friends to a tea party. For that occasion, he has a large teapot with the capacity of w milliliters and 2n tea cups, each cup is for one of Pasha's friends. The i-th cup can hold at most ai milliliters of water.It turned out that among Pasha's friends there are exactly n boys and exactly n girls and all of them are going to come to the tea party. To please everyone, Pasha decided to pour the water for the tea as follows: Pasha can boil the teapot exactly once by pouring there at most w milliliters of water; Pasha pours the same amount of water to each girl; Pasha pours the same amount of water to each boy; if each girl gets x milliliters of water, then each boy gets 2x milliliters of water. In the other words, each boy should get two times more water than each girl does.Pasha is very kind and polite, so he wants to maximize the total amount of the water that he pours to his friends. Your task is to help him and determine the optimum distribution of cups between Pasha's friends. | 256 megabytes | import java.util.*;
public class cf311div2B {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int w=sc.nextInt();
int arr[]=new int[2*n];
for(int i=0;i<2*n;i++)
arr[i]=sc.nextInt();
Arrays.sort(arr);
int min1=arr[2*n-1];
int min2=arr[2*n-1];
for(int i=0;i<=n-1;i++)
{if(arr[i]<min1)
min1=arr[i];}
for(int i=n;i<2*n;i++)
{if(arr[i]<min2)
min2=arr[i];}
double Min2=(double)min2;
Min2=Min2/2;
double min=Math.min(min1,Min2);
if(3*n*min>w)
{min=(double)w/(double)(3*n);}
System.out.println(3*n*min);
sc.close();
}
} | Java | ["2 4\n1 1 1 1", "3 18\n4 4 4 2 2 2", "1 5\n2 3"] | 1 second | ["3", "18", "4.5"] | NotePasha also has candies that he is going to give to girls but that is another task... | Java 11 | standard input | [
"constructive algorithms",
"implementation",
"sortings",
"math"
] | b2031a328d72b464f965b4789fd35b93 | The first line of the input contains two integers, n and w (1 ≤ n ≤ 105, 1 ≤ w ≤ 109) — the number of Pasha's friends that are boys (equal to the number of Pasha's friends that are girls) and the capacity of Pasha's teapot in milliliters. The second line of the input contains the sequence of integers ai (1 ≤ ai ≤ 109, 1 ≤ i ≤ 2n) — the capacities of Pasha's tea cups in milliliters. | 1,500 | Print a single real number — the maximum total amount of water in milliliters that Pasha can pour to his friends without violating the given conditions. Your answer will be considered correct if its absolute or relative error doesn't exceed 10 - 6. | standard output | |
PASSED | 5b7529e867c47f4adb4966e01d75d681 | train_000.jsonl | 1435676400 | Pasha decided to invite his friends to a tea party. For that occasion, he has a large teapot with the capacity of w milliliters and 2n tea cups, each cup is for one of Pasha's friends. The i-th cup can hold at most ai milliliters of water.It turned out that among Pasha's friends there are exactly n boys and exactly n girls and all of them are going to come to the tea party. To please everyone, Pasha decided to pour the water for the tea as follows: Pasha can boil the teapot exactly once by pouring there at most w milliliters of water; Pasha pours the same amount of water to each girl; Pasha pours the same amount of water to each boy; if each girl gets x milliliters of water, then each boy gets 2x milliliters of water. In the other words, each boy should get two times more water than each girl does.Pasha is very kind and polite, so he wants to maximize the total amount of the water that he pours to his friends. Your task is to help him and determine the optimum distribution of cups between Pasha's friends. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
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);
BPashaAndTea solver = new BPashaAndTea();
solver.solve(1, in, out);
out.close();
}
static class BPashaAndTea {
public void solve(int testNumber, Scanner sc, PrintWriter pw) {
int n = sc.nextInt(), w = sc.nextInt();
PriorityQueue<Integer> pq = new PriorityQueue<>();
for (int i = 0; i < 2 * n; i++) {
pq.add(sc.nextInt());
}
int min = pq.poll();
for (int i = 0; i < n - 1; i++)
pq.poll();
int max = pq.poll();
double temp = Math.min(min, max / 2.0);
pw.println(Math.min(w, temp * 3 * n));
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["2 4\n1 1 1 1", "3 18\n4 4 4 2 2 2", "1 5\n2 3"] | 1 second | ["3", "18", "4.5"] | NotePasha also has candies that he is going to give to girls but that is another task... | Java 11 | standard input | [
"constructive algorithms",
"implementation",
"sortings",
"math"
] | b2031a328d72b464f965b4789fd35b93 | The first line of the input contains two integers, n and w (1 ≤ n ≤ 105, 1 ≤ w ≤ 109) — the number of Pasha's friends that are boys (equal to the number of Pasha's friends that are girls) and the capacity of Pasha's teapot in milliliters. The second line of the input contains the sequence of integers ai (1 ≤ ai ≤ 109, 1 ≤ i ≤ 2n) — the capacities of Pasha's tea cups in milliliters. | 1,500 | Print a single real number — the maximum total amount of water in milliliters that Pasha can pour to his friends without violating the given conditions. Your answer will be considered correct if its absolute or relative error doesn't exceed 10 - 6. | standard output | |
PASSED | 8743bab11426d38a0a336c75e4593b37 | train_000.jsonl | 1435676400 | Pasha decided to invite his friends to a tea party. For that occasion, he has a large teapot with the capacity of w milliliters and 2n tea cups, each cup is for one of Pasha's friends. The i-th cup can hold at most ai milliliters of water.It turned out that among Pasha's friends there are exactly n boys and exactly n girls and all of them are going to come to the tea party. To please everyone, Pasha decided to pour the water for the tea as follows: Pasha can boil the teapot exactly once by pouring there at most w milliliters of water; Pasha pours the same amount of water to each girl; Pasha pours the same amount of water to each boy; if each girl gets x milliliters of water, then each boy gets 2x milliliters of water. In the other words, each boy should get two times more water than each girl does.Pasha is very kind and polite, so he wants to maximize the total amount of the water that he pours to his friends. Your task is to help him and determine the optimum distribution of cups between Pasha's friends. | 256 megabytes | import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int n, w;
List<Integer> as = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
n = scanner.nextInt();
w = scanner.nextInt();
for (int i = 0; i < 2 * n; i++) {
as.add(scanner.nextInt());
}
double x = w / (3.0 * n);
double threshold = x;
if (n > 1) {
Collections.sort(as);
int minGirls = Collections.min(as.subList(0, n - 1));
int minBoys = Collections.min(as.subList(n, 2 * n - 1));
if (minGirls < threshold) {
threshold = minGirls;
}
if (minBoys < 2 * threshold) {
threshold = minBoys / 2.0;
}
} else {
int min = Collections.min(as);
int max = Collections.max(as);
if (min < threshold) {
threshold = min;
}
if (max < 2 * threshold) {
threshold = max / 2.0;
}
}
System.out.println(3 * threshold * n);
}
} | Java | ["2 4\n1 1 1 1", "3 18\n4 4 4 2 2 2", "1 5\n2 3"] | 1 second | ["3", "18", "4.5"] | NotePasha also has candies that he is going to give to girls but that is another task... | Java 11 | standard input | [
"constructive algorithms",
"implementation",
"sortings",
"math"
] | b2031a328d72b464f965b4789fd35b93 | The first line of the input contains two integers, n and w (1 ≤ n ≤ 105, 1 ≤ w ≤ 109) — the number of Pasha's friends that are boys (equal to the number of Pasha's friends that are girls) and the capacity of Pasha's teapot in milliliters. The second line of the input contains the sequence of integers ai (1 ≤ ai ≤ 109, 1 ≤ i ≤ 2n) — the capacities of Pasha's tea cups in milliliters. | 1,500 | Print a single real number — the maximum total amount of water in milliliters that Pasha can pour to his friends without violating the given conditions. Your answer will be considered correct if its absolute or relative error doesn't exceed 10 - 6. | standard output | |
PASSED | 1d8bced5feb17a53afc93b5a7ef83308 | train_000.jsonl | 1435676400 | Pasha decided to invite his friends to a tea party. For that occasion, he has a large teapot with the capacity of w milliliters and 2n tea cups, each cup is for one of Pasha's friends. The i-th cup can hold at most ai milliliters of water.It turned out that among Pasha's friends there are exactly n boys and exactly n girls and all of them are going to come to the tea party. To please everyone, Pasha decided to pour the water for the tea as follows: Pasha can boil the teapot exactly once by pouring there at most w milliliters of water; Pasha pours the same amount of water to each girl; Pasha pours the same amount of water to each boy; if each girl gets x milliliters of water, then each boy gets 2x milliliters of water. In the other words, each boy should get two times more water than each girl does.Pasha is very kind and polite, so he wants to maximize the total amount of the water that he pours to his friends. Your task is to help him and determine the optimum distribution of cups between Pasha's friends. | 256 megabytes | /*
ID: davidzh8
PROG: subset
LANG: JAVA
*/
import java.io.*;
import java.util.*;
import java.lang.*;
public class pashatea {
//Start Stub
static long startTime = System.nanoTime();
//Globals Go Here
//Globals End
public static void main(String[] args) throws IOException {
boolean debug = (true);
FastScanner sc = new FastScanner("pashatea.in", debug);
FastWriter pw = new FastWriter("pashatea.out", debug);
int N= sc.ni();
int w= sc.ni();
int[] arr= new int[N*2];
for (int i = 0; i < N*2; i++) {
arr[i]= sc.ni();
}
Arrays.sort(arr);
int maxboy= arr[N];
int maxgirl= arr[0];
double min= N*1.5*(double) Math.min(maxboy, maxgirl*2);
System.out.println(Math.min(min,w));
/* End Stub */
long endTime = System.nanoTime();
// System.out.println("Execution Time: " + (endTime - startTime) / 1e9 + " s");
pw.close();
}
static class Edge implements Comparable<Edge> {
int w;
int a;
int b;
public Edge(int w, int a, int b) {
this.w = w;
this.a = a;
this.b = b;
}
public int compareTo(Edge obj) {
if (obj.w == w) {
if (obj.a == a) {
return b - obj.b;
}
return a - obj.a;
} else return w - obj.w;
}
}
static class Pair implements Comparable<Pair> {
int a;
int b;
public Pair(int a, int b) {
this.a = a;
this.b = b;
}
public int compareTo(Pair obj) {
if (obj.a == a) {
return b - obj.b;
} else return a - obj.a;
}
}
static class SegmentTree {
public long[] arr;
public long[] tree;
public int N;
//Zero initialization
public SegmentTree(int n) {
N = n;
arr = new long[N];
tree = new long[4 * N + 1];
}
public long query(int treeIndex, int lo, int hi, int i, int j) {
// query for arr[i..j]
if (lo > j || hi < i)
return 0;
if (i <= lo && j >= hi)
return tree[treeIndex];
int mid = lo + (hi - lo) / 2;
if (i > mid)
return query(2 * treeIndex + 2, mid + 1, hi, i, j);
else if (j <= mid)
return query(2 * treeIndex + 1, lo, mid, i, j);
long leftQuery = query(2 * treeIndex + 1, lo, mid, i, mid);
long rightQuery = query(2 * treeIndex + 2, mid + 1, hi, mid + 1, j);
// merge query results
return merge(leftQuery, rightQuery);
}
public void update(int treeIndex, int lo, int hi, int arrIndex, long val) {
if (lo == hi) {
tree[treeIndex] = val;
arr[arrIndex] = val;
return;
}
int mid = lo + (hi - lo) / 2;
if (arrIndex > mid)
update(2 * treeIndex + 2, mid + 1, hi, arrIndex, val);
else if (arrIndex <= mid)
update(2 * treeIndex + 1, lo, mid, arrIndex, val);
// merge updates
tree[treeIndex] = merge(tree[2 * treeIndex + 1], tree[2 * treeIndex + 2]);
}
public long merge(long a, long b) {
return (a + b);
}
}
static class djset {
int N;
int[] parent;
// Creates a disjoint set of size n (0, 1, ..., n-1)
public djset(int n) {
parent = new int[n];
N = n;
for (int i = 0; i < n; i++)
parent[i] = i;
}
public int find(int v) {
// I am the club president!!! (root of the tree)
if (parent[v] == v) return v;
// Find my parent's root.
int res = find(parent[v]);
// Attach me directly to the root of my tree.
parent[v] = res;
return res;
}
public boolean union(int v1, int v2) {
// Find respective roots.
int rootv1 = find(v1);
int rootv2 = find(v2);
// No union done, v1, v2 already together.
if (rootv1 == rootv2) return false;
// Attach tree of v2 to tree of v1.
parent[rootv2] = rootv1;
return true;
}
}
static class FastScanner {
public BufferedReader br;
public StringTokenizer st;
public InputStream is;
public FastScanner(String name, boolean debug) throws IOException {
if (debug) {
is = System.in;
} else {
is = new FileInputStream(name);
}
br = new BufferedReader(new InputStreamReader(is), 32768);
st = null;
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int ni() {
return Integer.parseInt(next());
}
public long nl() {
return Long.parseLong(next());
}
public double nd() {
return Double.parseDouble(next());
}
public String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return str;
}
}
static class FastWriter {
public PrintWriter pw;
public FastWriter(String name, boolean debug) throws IOException {
if (debug) {
pw = new PrintWriter(System.out);
} else {
pw = new PrintWriter(new BufferedWriter(new FileWriter(new File(name))));
}
}
public void println(Object text) {
pw.println(text);
}
public void print(Object text) {
pw.print(text);
}
public void close() {
pw.close();
}
public void flush() {
pw.flush();
}
}
} | Java | ["2 4\n1 1 1 1", "3 18\n4 4 4 2 2 2", "1 5\n2 3"] | 1 second | ["3", "18", "4.5"] | NotePasha also has candies that he is going to give to girls but that is another task... | Java 11 | standard input | [
"constructive algorithms",
"implementation",
"sortings",
"math"
] | b2031a328d72b464f965b4789fd35b93 | The first line of the input contains two integers, n and w (1 ≤ n ≤ 105, 1 ≤ w ≤ 109) — the number of Pasha's friends that are boys (equal to the number of Pasha's friends that are girls) and the capacity of Pasha's teapot in milliliters. The second line of the input contains the sequence of integers ai (1 ≤ ai ≤ 109, 1 ≤ i ≤ 2n) — the capacities of Pasha's tea cups in milliliters. | 1,500 | Print a single real number — the maximum total amount of water in milliliters that Pasha can pour to his friends without violating the given conditions. Your answer will be considered correct if its absolute or relative error doesn't exceed 10 - 6. | standard output | |
PASSED | c03849b8d0a9cbc45360c4c73acfbba2 | train_000.jsonl | 1435676400 | Pasha decided to invite his friends to a tea party. For that occasion, he has a large teapot with the capacity of w milliliters and 2n tea cups, each cup is for one of Pasha's friends. The i-th cup can hold at most ai milliliters of water.It turned out that among Pasha's friends there are exactly n boys and exactly n girls and all of them are going to come to the tea party. To please everyone, Pasha decided to pour the water for the tea as follows: Pasha can boil the teapot exactly once by pouring there at most w milliliters of water; Pasha pours the same amount of water to each girl; Pasha pours the same amount of water to each boy; if each girl gets x milliliters of water, then each boy gets 2x milliliters of water. In the other words, each boy should get two times more water than each girl does.Pasha is very kind and polite, so he wants to maximize the total amount of the water that he pours to his friends. Your task is to help him and determine the optimum distribution of cups between Pasha's friends. | 256 megabytes | import java.util.*;
public class HelloWorld {
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
String[] data = scanner.nextLine().split(" ");
String[] arr = scanner.nextLine().split(" ");
int n = Integer.parseInt(data[0]);
int w = Integer.parseInt(data[1]);
double[] friends = new double[2*n];
for(int i = 0; i < 2*n; i++) {
friends[i] = Double.parseDouble(arr[i]);
}
Arrays.sort(friends);
double output = Math.min(friends[0], friends[n] / 2);
output = Math.min(3 * output * n, w);
System.out.print(output);
scanner.close();
}
}
| Java | ["2 4\n1 1 1 1", "3 18\n4 4 4 2 2 2", "1 5\n2 3"] | 1 second | ["3", "18", "4.5"] | NotePasha also has candies that he is going to give to girls but that is another task... | Java 11 | standard input | [
"constructive algorithms",
"implementation",
"sortings",
"math"
] | b2031a328d72b464f965b4789fd35b93 | The first line of the input contains two integers, n and w (1 ≤ n ≤ 105, 1 ≤ w ≤ 109) — the number of Pasha's friends that are boys (equal to the number of Pasha's friends that are girls) and the capacity of Pasha's teapot in milliliters. The second line of the input contains the sequence of integers ai (1 ≤ ai ≤ 109, 1 ≤ i ≤ 2n) — the capacities of Pasha's tea cups in milliliters. | 1,500 | Print a single real number — the maximum total amount of water in milliliters that Pasha can pour to his friends without violating the given conditions. Your answer will be considered correct if its absolute or relative error doesn't exceed 10 - 6. | standard output | |
PASSED | ccaf010057a011820531e6a79206f313 | train_000.jsonl | 1435676400 | Pasha decided to invite his friends to a tea party. For that occasion, he has a large teapot with the capacity of w milliliters and 2n tea cups, each cup is for one of Pasha's friends. The i-th cup can hold at most ai milliliters of water.It turned out that among Pasha's friends there are exactly n boys and exactly n girls and all of them are going to come to the tea party. To please everyone, Pasha decided to pour the water for the tea as follows: Pasha can boil the teapot exactly once by pouring there at most w milliliters of water; Pasha pours the same amount of water to each girl; Pasha pours the same amount of water to each boy; if each girl gets x milliliters of water, then each boy gets 2x milliliters of water. In the other words, each boy should get two times more water than each girl does.Pasha is very kind and polite, so he wants to maximize the total amount of the water that he pours to his friends. Your task is to help him and determine the optimum distribution of cups between Pasha's friends. | 256 megabytes | import java.util.*;
public class Lecture3_Pasha_and_Tea {
private static int[] A;
private static int n;
private static double chk(double lim) {
if (Double.compare(lim, A[0]) > 0 || Double.compare(lim * 2, A[n]) > 0)
return 0;
return (lim * n * 3);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
n = in.nextInt();
int w = in.nextInt();
A = new int[2*n];
for(int i = 0; i < 2*n; i++)
A[i] = in.nextInt();
in.close();
Arrays.sort(A);
double res = Math.max(chk(A[0]), chk(A[n] / 2.0));
System.out.print(Math.min(res, w));
}
} | Java | ["2 4\n1 1 1 1", "3 18\n4 4 4 2 2 2", "1 5\n2 3"] | 1 second | ["3", "18", "4.5"] | NotePasha also has candies that he is going to give to girls but that is another task... | Java 11 | standard input | [
"constructive algorithms",
"implementation",
"sortings",
"math"
] | b2031a328d72b464f965b4789fd35b93 | The first line of the input contains two integers, n and w (1 ≤ n ≤ 105, 1 ≤ w ≤ 109) — the number of Pasha's friends that are boys (equal to the number of Pasha's friends that are girls) and the capacity of Pasha's teapot in milliliters. The second line of the input contains the sequence of integers ai (1 ≤ ai ≤ 109, 1 ≤ i ≤ 2n) — the capacities of Pasha's tea cups in milliliters. | 1,500 | Print a single real number — the maximum total amount of water in milliliters that Pasha can pour to his friends without violating the given conditions. Your answer will be considered correct if its absolute or relative error doesn't exceed 10 - 6. | standard output | |
PASSED | c67ef8b7b127b2a6df2514ec378fc627 | train_000.jsonl | 1435676400 | Pasha decided to invite his friends to a tea party. For that occasion, he has a large teapot with the capacity of w milliliters and 2n tea cups, each cup is for one of Pasha's friends. The i-th cup can hold at most ai milliliters of water.It turned out that among Pasha's friends there are exactly n boys and exactly n girls and all of them are going to come to the tea party. To please everyone, Pasha decided to pour the water for the tea as follows: Pasha can boil the teapot exactly once by pouring there at most w milliliters of water; Pasha pours the same amount of water to each girl; Pasha pours the same amount of water to each boy; if each girl gets x milliliters of water, then each boy gets 2x milliliters of water. In the other words, each boy should get two times more water than each girl does.Pasha is very kind and polite, so he wants to maximize the total amount of the water that he pours to his friends. Your task is to help him and determine the optimum distribution of cups between Pasha's friends. | 256 megabytes | import java.util.*;
public class Lecture03_Pasha_and_Tea {
private static int[] A;
private static int n;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
n = in.nextInt();
int w = in.nextInt();
A = new int[2*n];
for(int i = 0; i < 2*n; i++)
A[i] = in.nextInt();
in.close();
Arrays.sort(A);
double res;
if (2 * A[0] <= A[n])
res = 3.0 * A[0] * n;
else
res = 3.0 / 2 * A[n] * n;
System.out.print(Math.min(res, w));
}
} | Java | ["2 4\n1 1 1 1", "3 18\n4 4 4 2 2 2", "1 5\n2 3"] | 1 second | ["3", "18", "4.5"] | NotePasha also has candies that he is going to give to girls but that is another task... | Java 11 | standard input | [
"constructive algorithms",
"implementation",
"sortings",
"math"
] | b2031a328d72b464f965b4789fd35b93 | The first line of the input contains two integers, n and w (1 ≤ n ≤ 105, 1 ≤ w ≤ 109) — the number of Pasha's friends that are boys (equal to the number of Pasha's friends that are girls) and the capacity of Pasha's teapot in milliliters. The second line of the input contains the sequence of integers ai (1 ≤ ai ≤ 109, 1 ≤ i ≤ 2n) — the capacities of Pasha's tea cups in milliliters. | 1,500 | Print a single real number — the maximum total amount of water in milliliters that Pasha can pour to his friends without violating the given conditions. Your answer will be considered correct if its absolute or relative error doesn't exceed 10 - 6. | standard output | |
PASSED | af1bf04af650440aa13806e6a1aeeaeb | train_000.jsonl | 1435676400 | Pasha decided to invite his friends to a tea party. For that occasion, he has a large teapot with the capacity of w milliliters and 2n tea cups, each cup is for one of Pasha's friends. The i-th cup can hold at most ai milliliters of water.It turned out that among Pasha's friends there are exactly n boys and exactly n girls and all of them are going to come to the tea party. To please everyone, Pasha decided to pour the water for the tea as follows: Pasha can boil the teapot exactly once by pouring there at most w milliliters of water; Pasha pours the same amount of water to each girl; Pasha pours the same amount of water to each boy; if each girl gets x milliliters of water, then each boy gets 2x milliliters of water. In the other words, each boy should get two times more water than each girl does.Pasha is very kind and polite, so he wants to maximize the total amount of the water that he pours to his friends. Your task is to help him and determine the optimum distribution of cups between Pasha's friends. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
static class PairComparator implements Comparator<Pair> {
@Override
public int compare(Pair x, Pair y) {
if (x.val < y.val)
return -1;
if (x.val > y.val)
return 1;
if (x.val == y.val) {
if (x.ind < y.ind)
return -1;
if (x.ind > y.ind)
return 1;
}
return 0;
}
}
static class Pair {
int ind, val;
Pair(int i, int v) {
ind = i;
val = v;
}
}
static int[] vis;
static void func() throws Exception {
int n = sc.nextInt();
int w = sc.nextInt();
List<Integer > arr= new ArrayList<>();
for (int i=0;i<2*n;i++){
arr.add(sc.nextInt());
}
Collections.sort(arr);
double x=arr.get(0);
for (int i=1;i<n;i++){
x = Math.min(x, arr.get(i));
}
for (int i=n;i<2*n;i++){
x = Math.min(x, arr.get(i)/2.0);
}
pw.println(Math.min(x*3*n, w));
}
/*
* */
static PrintWriter pw;
static MScanner sc;
public static void main(String[] args) throws Exception {
pw = new PrintWriter(System.out);
sc = new MScanner(System.in);
int tests = 1;
// tests =sc.nextInt(); //comment this line
while (tests-- > 0) {
func();
pw.flush();
}
}
static class MScanner {
StringTokenizer st;
BufferedReader br;
public MScanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public MScanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int[] intArr(int n) throws IOException {
int[] in = new int[n];
for (int i = 0; i < n; i++)
in[i] = nextInt();
return in;
}
public long[] longArr(int n) throws IOException {
long[] in = new long[n];
for (int i = 0; i < n; i++)
in[i] = nextLong();
return in;
}
public int[] intSortedArr(int n) throws IOException {
int[] in = new int[n];
for (int i = 0; i < n; i++)
in[i] = nextInt();
shuffle(in);
Arrays.sort(in);
return in;
}
public long[] longSortedArr(int n) throws IOException {
long[] in = new long[n];
for (int i = 0; i < n; i++)
in[i] = nextLong();
shuffle(in);
Arrays.sort(in);
return in;
}
public Integer[] IntegerArr(int n) throws IOException {
Integer[] in = new Integer[n];
for (int i = 0; i < n; i++)
in[i] = nextInt();
return in;
}
public Long[] LongArr(int n) throws IOException {
Long[] in = new Long[n];
for (int i = 0; i < n; i++)
in[i] = nextLong();
return in;
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
static void shuffle(int[] in) {
for (int i = 0; i < in.length; i++) {
int idx = (int) (Math.random() * (i + 1));
int tmp = in[i];
in[i] = in[idx];
in[idx] = tmp;
}
}
static void shuffle(long[] in) {
for (int i = 0; i < in.length; i++) {
int idx = (int) (Math.random() * (i + 1));
long tmp = in[i];
in[i] = in[idx];
in[idx] = tmp;
}
}
}
| Java | ["2 4\n1 1 1 1", "3 18\n4 4 4 2 2 2", "1 5\n2 3"] | 1 second | ["3", "18", "4.5"] | NotePasha also has candies that he is going to give to girls but that is another task... | Java 11 | standard input | [
"constructive algorithms",
"implementation",
"sortings",
"math"
] | b2031a328d72b464f965b4789fd35b93 | The first line of the input contains two integers, n and w (1 ≤ n ≤ 105, 1 ≤ w ≤ 109) — the number of Pasha's friends that are boys (equal to the number of Pasha's friends that are girls) and the capacity of Pasha's teapot in milliliters. The second line of the input contains the sequence of integers ai (1 ≤ ai ≤ 109, 1 ≤ i ≤ 2n) — the capacities of Pasha's tea cups in milliliters. | 1,500 | Print a single real number — the maximum total amount of water in milliliters that Pasha can pour to his friends without violating the given conditions. Your answer will be considered correct if its absolute or relative error doesn't exceed 10 - 6. | standard output | |
PASSED | 17edbe8109ce43a5cbc0b1bba2d0c694 | train_000.jsonl | 1400167800 | You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | import java.io.*;
import java.util.*;
// press Ctrl+Shift+L for all shortcut key (Eclipse only !)
public class Solution
{
static MyScanner sc;
static PrintWriter pw;
public static void main(String[] args)
{
sc=new MyScanner(); pw=new PrintWriter(System.out);
int i;
String inp=sc.nextLine();
int lps[]=new int[inp.length()];
computeLPSArray(inp, lps);
//for(char c:inp.toCharArray()) pw.print(c+" ");
//pw.println();
//printArr(lps);
int c[]=new int[1000*100];
for(i=1;i<lps.length;i++) c[lps[i]]++;
//for(i=0;i<c.length;i++) if(c[i]!=0) {c[i]=c[i]+1; }
//pw.println("C2"+c[2]);
for(i=c.length-1;i>=1;i--)
{
if(c[i]!=0)
{
c[lps[i-1]]+=c[i];
}
}
int len=lps[lps.length-1];
ArrayList<String> ans=new ArrayList<>(); ans.add(lps.length+" "+1);
while(len!=0)
{
ans.add(len+" "+(c[len]+1));
len=lps[len-1];
}
pw.println(ans.size());
for(i=ans.size()-1;i>=0;i--)
pw.println(ans.get(i));
pw.close();
}
static void printArr(int arr[])
{
for(int i=0;i<arr.length;i++)
{
System.out.print(arr[i]+" ");
}
System.out.println();
}
static void computeLPSArray(String pat, int lps[])
{
// length of the previous longest prefix suffix
int len = 0;
int i = 1;
lps[0] = 0; // lps[0] is always 0
// the loop calculates lps[i] for i = 1 to M-1
while (i < lps.length)
{
if (pat.charAt(i) == pat.charAt(len))
{
len++;
lps[i] = len;
i++;
}
else // (pat[i] != pat[len])
{
// This is tricky. Consider the example.
// AAACAAAA and i = 7. The idea is similar
// to search step.
if (len != 0)
{
len = lps[len-1];
// Also, note that we do not increment
// i here
}
else // if (len == 0)
{
lps[i] = len;
i++;
}
}
}
}
static int [] z(String str) {
char s[] = str.toCharArray();
int n = s.length;
int z[] = new int[n];
for(int i = 1, L = 0, R = 0; i < n; ++i) {
if(R < i) {
L = R = i;
while(R < n && s[R - L] == s[R]) R++;
z[i] = R - L;
R--;
}
else {
int k = i - L;
if(i + z[k] <= R) z[i] = z[k];
else {
L = i;
while(R < n && s[R] == s[R - L]) R++;
z[i] = R - L; R--;
}
}
}
return z;
}
static class MyScanner
{
BufferedReader br;
StringTokenizer st;
public MyScanner()
{
br = new BufferedReader(new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
} catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
} | Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1 ≤ |s| ≤ 105) — string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | 49dd7896f326803ea724c6cacbaca1f5 | train_000.jsonl | 1400167800 | You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | ////package CodeForce;
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Z1 {
static int[] A;
static int[] S;
static long[] sum;
public static int mod=1000000007;
static int[][] dp;
static boolean[][] isPalin;
static int max1=5000+10;
static int[][] g;
static int ver;
static int n;
static boolean[] visit;
static LinkedList<Pair> l[];
static int ans=0;
static int[] color;
public static void main(String[] args) throws Exception
{
InputReader in = new InputReader(System.in);
PrintWriter pw=new PrintWriter(System.out);
String s=in.is();
int[] z=new int[s.length()];
int[] count=new int[s.length()+1];
++count[s.length()];
int l=0;
int r=0;
z[0]=s.length();
int n=s.length();
for(int i=1;i<s.length();i++)
{
if(i<=r)
z[i]=Math.min(z[i-l],r-i+1);
while(i+z[i]<s.length()&&s.charAt(z[i])==s.charAt(i+z[i]))
++z[i];
if(i+z[i]-1>r)
{
l=i;
r=i+z[i]-1;
}
++count[z[i]];
}
//pw.println(Arrays.toString(z));
//pw.println(Arrays.toString(count));
for(int i=s.length();i>0;i--)
count[i-1]+=count[i];
// pw.println(Arrays.toString(count));
int size=0;
int[] a=new int[n];
int[] b=new int[n];
for(int i=0;i<n;i++)
{
if(z[n-i-1]==i+1)
{
a[size]=i+1;
b[size++]=count[i+1];
}
}
pw.println(size);
for(int i=0;i<size;i++)
pw.println(a[i]+" "+b[i]);
pw.close();
}
///// according to https://e-maxx-eng.appspot.com/string/z-function.html algorithm
static int[] ZALGORITHM(String s1)
{
char[] s=s1.toCharArray();
int n=s.length;
int[] z=new int[n];
int l=0;
int r=0;
for(int i=1;i<n;i++)
{
if(i<=r)
z[i]=Math.min(r-i+1, z[i-l]); /// z[i-l] means that l...i...r =how much character matched in left i-l
//from start and we have already found z[i-l] and in right how much char
//will match is r-i+1 and we have to take min of these values
/* if we know for 0--(r-l) the value is z[r-l] then for 0---- (i-l) is z[i-l] */
while(i+z[i]<n&&s[z[i]]==s[i+z[i]]) /* this is for i>r || or above computed z[i] tells us from where we have to compare character*/
z[i]++;
if(i+z[i]-1>r) // update the interval or segment
{
l=i;
r=i+z[i]-1;
}
}
return z;
}
static void dfs(int i)
{
if(visit[i])return ;
visit[i]=true;
for(int o:g[i])
if(!visit[o])
dfs(o);
}
private static class DSU{
int[] parent;
int[] rank;
int cnt;
public DSU(int n){
parent=new int[n];
rank=new int[n];
for(int i=0;i<n;i++){
parent[i]=i;
rank[i]=1;
}
cnt=n;
}
int find(int i){
while(parent[i] !=i){
parent[i]=parent[parent[i]];
i=parent[i];
}
return i;
}
int Union(int x, int y){
int xset = find(x);
int yset = find(y);
if(xset!=yset)
cnt--;
if(rank[xset]<rank[yset]){
parent[xset] = yset;
rank[yset]+=rank[xset];
rank[xset]=0;
return yset;
}else{
parent[yset]=xset;
rank[xset]+=rank[yset];
rank[yset]=0;
return xset;
}
}
}
public static int[][] packU(int n, int[] from, int[] to, int max) {
int[][] g = new int[n][];
int[] p = new int[n];
for (int i = 0; i < max; i++) p[from[i]]++;
for (int i = 0; i < max; i++) p[to[i]]++;
for (int i = 0; i < n; i++) g[i] = new int[p[i]];
for (int i = 0; i < max; i++) {
g[from[i]][--p[from[i]]] = to[i];
g[to[i]][--p[to[i]]] = from[i];
}
return g;
}
public static int[][] parents3(int[][] g, int root) {
int n = g.length;
int[] par = new int[n];
Arrays.fill(par, -1);
int[] depth = new int[n];
depth[0] = 0;
int[] q = new int[n];
q[0] = root;
for (int p = 0, r = 1; p < r; p++) {
int cur = q[p];
for (int nex : g[cur]) {
if (par[cur] != nex) {
q[r++] = nex;
par[nex] = cur;
depth[nex] = depth[cur] + 1;
}
}
}
return new int[][]{par, q, depth};
}
public static int lower_bound(int[] nums, int target) {
int low = 0, high = nums.length - 1;
while (low < high) {
int mid = low + (high - low) / 2;
if (nums[mid] < target)
low = mid + 1;
else
high = mid;
}
return nums[low] == target ? low : -1;
}
public static int upper_bound(int[] nums, int target) {
int low = 0, high = nums.length - 1;
while (low < high) {
int mid = low + (high + 1 - low) / 2;
if (nums[mid] > target)
high = mid - 1;
else
low = mid;
}
return nums[low] == target ? low : -1;
}
public static boolean palin(String s)
{
int i=0;
int j=s.length()-1;
while(i<j)
{
if(s.charAt(i)==s.charAt(j))
{
i++;
j--;
}
else return false;
}
return true;
}
static boolean CountPs(String s,int n)
{
boolean b=false;
char[] S=s.toCharArray();
int[][] dp=new int[n][n];
boolean[][] p=new boolean[n][n];
for(int i=0;i<n;i++)p[i][i]=true;
for(int i=0;i<n-1;i++)
{
if(S[i]==S[i+1])
{
p[i][i+1]=true;
dp[i][i+1]=1;
b=true;
}
}
for(int gap=2;gap<n;gap++)
{
for(int i=0;i<n-gap;i++)
{
int j=gap+i;
if(S[i]==S[j]&&p[i+1][j-1]){p[i][j]=true;}
if(p[i][j])
dp[i][j]=dp[i][j-1]+dp[i+1][j]+1-dp[i+1][j-1];
else dp[i][j]=dp[i][j-1]+dp[i+1][j]-dp[i+1][j-1];
if(dp[i][j]>=1){b=true;}
}
}
return b;
// return dp[0][n-1];
}
public static int gcd(int a,int b)
{
int res=1;
while(a>0)
{
res=a;
a=b%a;
b=res;
}
return res;
}
public static long pow(long n,long p,long m)
{
long result = 1;
if(p==0)
return 1;
if (p==1)
return n;
while(p!=0)
{
if(p%2==1)
result *= n;
if(result>=m)
result%=m;
p >>=1;
n*=n;
if(n>=m)
n%=m;
}
return result;
}
public static long pow(long n,long p)
{
long result = 1;
if(p==0)
return 1;
if (p==1)
return n;
while(p!=0)
{
if(p%2==1)
result *= n;
p >>=1;
n*=n;
}
return result;
}
static class Edge implements Comparator<Edge> {
private int u;
private int v;
private int w;
public Edge() {
}
public Edge(int u, int v, int w) {
this.u=u;
this.v=v;
this.w=w;
}
public int getU() {
return u;
}
public void setU(int u) {
this.u = u;
}
public int getV() {
return v;
}
public void setV(int v) {
this.v = v;
}
public int getW() {
return w;
}
public void setW(int w) {
this.w = w;
}
public int compareTo(Edge e)
{
return this.getW() - e.getW();
}
@Override
public String toString() {
return "Edge [u=" + u + ", v=" + v + ", w=" + w + "]";
}
@Override
public int compare(Edge arg0, Edge arg1) {
// TODO Auto-generated method stub
return 0;
}
}
static class Pair implements Comparable<Pair>
{
int a,b;
Pair (int a,int b)
{
this.a=a;
this.b=b;
}
public int compareTo(Pair o) {
// TODO Auto-generated method stub
if(this.a!=o.a)
return -Integer.compare(this.a,o.a);
else
return -Integer.compare(this.b, o.b);
//return 0;
}
public boolean equals(Object o) {
if (o instanceof Pair) {
Pair p = (Pair)o;
return p.a == a && p.b == b;
}
return false;
}
public int hashCode() {
return new Integer(a).hashCode() * 31 + new Integer(b).hashCode();
}
}
static class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private SpaceCharFilter filter;
byte inbuffer[] = new byte[1024];
int lenbuffer = 0, ptrbuffer = 0;
final int M = (int) 1e9 + 7;
int md=(int)(1e7+1);
int[] SMP=new int[md];
final double eps = 1e-6;
final double pi = Math.PI;
PrintWriter out;
String check = "";
InputStream obj = check.isEmpty() ? System.in : new ByteArrayInputStream(check.getBytes());
public InputReader(InputStream stream)
{
this.stream = stream;
}
int readByte() {
if (lenbuffer == -1) throw new InputMismatchException();
if (ptrbuffer >= lenbuffer) {
ptrbuffer = 0;
try {
lenbuffer = obj.read(inbuffer);
} catch (IOException e) {
throw new InputMismatchException();
}
}
if (lenbuffer <= 0) return -1;
return inbuffer[ptrbuffer++];
}
public int read()
{
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;
}
String is() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) // when nextLine, (isSpaceChar(b) && b!=' ')
{
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public int ii() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
public long il() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
boolean isSpaceChar(int c) {
return (!(c >= 33 && c <= 126));
}
int skip()
{
int b;
while ((b = readByte()) != -1 && isSpaceChar(b)) ;
return b;
}
float nf() {
return Float.parseFloat(is());
}
double id() {
return Double.parseDouble(is());
}
char ic() {
return (char) skip();
}
int[] iia(int n) {
int a[] = new int[n];
for (int i = 0; i<n; i++) a[i] = ii();
return a;
}
long[] ila(int n) {
long a[] = new long[n];
for (int i = 0; i <n; i++) a[i] = il();
return a;
}
String[] isa(int n) {
String a[] = new String[n];
for (int i = 0; i < n; i++) a[i] = is();
return a;
}
long mul(long a, long b) { return a * b % M; }
long div(long a, long b)
{
return mul(a, pow(b, M - 2));
}
double[][] idm(int n, int m) {
double a[][] = new double[n][m];
for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) a[i][j] = id();
return a;
}
int[][] iim(int n, int m) {
int a[][] = new int[n][m];
for (int i = 0; i < n; i++) for (int j = 0; j <m; j++) a[i][j] = ii();
return a;
}
public String readLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
public boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
}
| Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1 ≤ |s| ≤ 105) — string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | 883718802577b1896b2c82eb49865847 | train_000.jsonl | 1400167800 | You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
public class Solution
{
public static void main (String[] args) throws java.lang.Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
String s = br.readLine();
int[] z = calculateZAlgorithm(s);
TreeSet<Integer> set = new TreeSet();
int[] nums = new int[s.length()+1];
z[0] = s.length();
for(int i=0;i<z.length;i++){
nums[z[i]]++;
if(i+z[i] == z.length)
set.add(z[i]);
}
nums[z.length] = 1;
for(int i =z.length-1;i>=0;i--)
nums[i]+=nums[i+1];
out.println(set.size());
for(int i:set)
out.println(i+" "+nums[i]);
out.close();
}
public static int[] calculateZAlgorithm(String s){
int[] z = new int[s.length()];
int l=0,r=0;
for(int i=1;i<s.length();i++){
if(i <= r){
z[i] = Math.min(r-i+1,z[i-l]);
}
while(i+z[i]<s.length() &&s.charAt(z[i]) == s.charAt(i+z[i]))
z[i]++;
if(r < i+z[i]){
l = i;
r = i+z[i]-1;
}
}
return z;
}
}
| Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1 ≤ |s| ≤ 105) — string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | 5002c28174f3f8907402857e21c9c51d | train_000.jsonl | 1400167800 | You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes |
import java.io.*;
import java.math.*;
import java.util.*;
import static java.util.Arrays.fill;
import static java.lang.Math.*;
import static java.util.Arrays.sort;
import static java.util.Collections.sort;
public class D432
{
public static int mod = 1000000007;
public static long INF = (1L << 60);
static FastScanner2 in = new FastScanner2();
static OutputWriter out = new OutputWriter(System.out);
public static void main(String[] args)
{
String str=in.nextLine();
char[] s=str.toCharArray();
int l=0,r=0;
int[] z=new int[s.length];
for(int i=1;i<s.length;i++)
{
if(i>r)
{
l=r=i;
while(r<s.length && s[r-l]==s[r])
r++;
z[i]=r-l;
r--;
}
else
{
int k=i-l;
if(z[k]<r-i+1)
z[i]=z[k];
else
{
l=i;
while(r<s.length && s[r-l]==s[r])
r++;
z[i]=r-l;
r--;
}
}
}
int[] cx=Arrays.copyOf(z, z.length);
TreeMap<Integer, Integer> map=new TreeMap<>();
Arrays.sort(cx);
//tr(z);
for(int i=1;i<s.length;i++)
{
if(z[i]==0)
continue;
int len=z[i];
if(z[s.length-len]==len)
{
//prefix matches suffix
//add all numbers whose z function is greater than or equal to len +1
int low=0;
int high=s.length-1;
int ans=0;
while(low<=high)
{
int mid=(low+high)/2;
if(cx[mid]<len)
{
ans=mid;
low=mid+1;
}
else
{
high=mid-1;
}
}
//tr("len is "+len+" ans is "+ans);
if(!map.containsKey(len))
map.put(len, s.length-ans);
}
}
map.put(s.length, 1);
out.println(map.size());
while(!map.isEmpty())
{
int len=map.firstKey();
out.println(len+" "+map.get(len));
map.remove(len);
}
out.close();
}
static class FastScanner2
{
private byte[] buf = new byte[1024];
private int curChar;
private int snumChars;
public int read()
{
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars)
{
curChar = 0;
try
{
snumChars = System.in.read(buf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isEndOfLine(c));
return res.toString();
}
public String nextString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public 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 int[] nextIntArray(int n)
{
int[] arr = new int[n];
for (int i = 0; i < n; i++)
{
arr[i] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n)
{
long[] arr = new long[n];
for (int i = 0; i < n; i++)
{
arr[i] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c)
{
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c)
{
return c == '\n' || c == '\r' || c == -1;
}
}
static class OutputWriter
{
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream)
{
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer)
{
this.writer = new PrintWriter(writer);
}
public void print(Object... objects)
{
for (int i = 0; i < objects.length; i++)
{
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void println(Object... objects)
{
print(objects);
writer.println();
}
public void close()
{
writer.close();
}
public void flush()
{
writer.flush();
}
}
private static boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private static void debug(Object... o)
{
if (!oj)
System.out.println(Arrays.deepToString(o));
}
private static void tr(Object... o)
{
if (!oj)
System.out.println(Arrays.deepToString(o));
}
} | Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1 ≤ |s| ≤ 105) — string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | a67eaceb83528f7a7156b59b25393f96 | train_000.jsonl | 1400167800 | You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.sql.Array;
import java.util.*;
import java.util.stream.Stream;
public class AtCoder implements Runnable {
static final int MOD = (int) 1e9 + 7;
static final Reader in = new Reader();
static final PrintWriter out = new PrintWriter(System.out);
StringBuilder answer = new StringBuilder();
public static void main(String[] args) {
new Thread(null, new AtCoder(), "persefone", 1 << 28).start();
}
@Override
public void run() {
solve();
printf();
flush();
}
void solve() {
char[] s = in.next().toCharArray();
int n = s.length;
int[] z = StringUtils.z_function(s);
int[][] cnt = new int[n][];
for (int i = 1; i < n; i++) {
int k = z[i];
if (k == 0) continue;
if (cnt[k] == null) cnt[k] = new int[2];
cnt[k][0] = i;
cnt[k][1]++;
}
int sum = 0;
Stack<String> ans = new Stack<>();
ans.push(n + " " + 1);
for (int i = n - 1; i > 0; i--) {
if (cnt[i] == null) continue;
if (cnt[i][0] + i == n) {
ans.push(i + " " + (sum + cnt[i][1] + 1));
}
sum += cnt[i][1];
}
printf(ans.size());
while (!ans.isEmpty()) add(ans.pop(), '\n');
}
static class StringUtils {
static int[] z_function(char[] s) {
int n = s.length;
int[] z = new int[n];
int l = 0, r = 0;
for (int i = 1; i < n; i++) {
if (i > r) {
l = r = i;
while (r < n && s[r-l] == s[r]) r++;
z[i] = r - l; r--;
} else {
int k = i - l;
if (z[k] < r - i + 1) z[i] = z[k];
else {
l = i;
while (r < n && s[r-l] == s[r]) r++;
z[i] = r - l; r--;
}
}
}
return z;
}
static int[] z_function(CharSequence s) {
return z_function(s.toString().toCharArray());
}
}
void printf() {
out.print(answer);
}
void close() {
out.close();
}
void flush() {
out.flush();
}
void printf(Stream<?> str) {
str.forEach(o -> add(o, " "));
add("\n");
}
void printf(Object... obj) {
printf(false, obj);
}
void printfWithDescription(Object... obj) {
printf(true, obj);
}
private void printf(boolean b, Object... obj) {
if (obj.length > 1) {
for (int i = 0; i < obj.length; i++) {
if (b) add(obj[i].getClass().getSimpleName(), " - ");
if (obj[i] instanceof Collection<?>) {
printf((Collection<?>) obj[i]);
} else if (obj[i] instanceof int[][]) {
printf((int[][]) obj[i]);
} else if (obj[i] instanceof long[][]) {
printf((long[][]) obj[i]);
} else if (obj[i] instanceof double[][]) {
printf((double[][]) obj[i]);
} else printf(obj[i]);
}
return;
}
if (b) add(obj[0].getClass().getSimpleName(), " - ");
printf(obj[0]);
}
void printf(Object o) {
if (o instanceof int[])
printf(Arrays.stream((int[]) o).boxed());
else if (o instanceof char[])
printf(new String((char[]) o));
else if (o instanceof long[])
printf(Arrays.stream((long[]) o).boxed());
else if (o instanceof double[])
printf(Arrays.stream((double[]) o).boxed());
else if (o instanceof boolean[]) {
for (boolean b : (boolean[]) o) add(b, " ");
add("\n");
} else
add(o, "\n");
}
void printf(int[]... obj) {
for (int i = 0; i < obj.length; i++) printf(obj[i]);
}
void printf(long[]... obj) {
for (int i = 0; i < obj.length; i++) printf(obj[i]);
}
void printf(double[]... obj) {
for (int i = 0; i < obj.length; i++) printf(obj[i]);
}
void printf(boolean[]... obj) {
for (int i = 0; i < obj.length; i++) printf(obj[i]);
}
void printf(Collection<?> col) {
printf(col.stream());
}
<T, K> void add(T t, K k) {
if (t instanceof Collection<?>) {
((Collection<?>) t).forEach(i -> add(i, " "));
} else if (t instanceof Object[]) {
Arrays.stream((Object[]) t).forEach(i -> add(i, " "));
} else
add(t);
add(k);
}
<T> void add(T t) {
answer.append(t);
}
@SuppressWarnings("unchecked")
<T extends Comparable<? super T>> T min(T... t) {
if (t.length == 0)
return null;
T m = t[0];
for (int i = 1; i < t.length; i++)
if (t[i].compareTo(m) < 0)
m = t[i];
return m;
}
@SuppressWarnings("unchecked")
<T extends Comparable<? super T>> T max(T... t) {
if (t.length == 0)
return null;
T m = t[0];
for (int i = 1; i < t.length; i++)
if (t[i].compareTo(m) > 0)
m = t[i];
return m;
}
static class Pair<K extends Comparable<? super K>, V extends Comparable<? super V>>
implements Comparable<Pair<K, V>> {
private K k;
private V v;
Pair(K k, V v) {
this.k = k;
this.v = v;
}
@SuppressWarnings("unchecked")
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || !(o instanceof Pair)) return false;
Pair<K, V> p = (Pair<K, V>) o;
return k.compareTo(p.k) == 0 && v.compareTo(p.v) == 0;
}
@Override
public int hashCode() {
int hash = 31;
hash = hash * 89 + k.hashCode();
hash = hash * 89 + v.hashCode();
return hash;
}
@Override
public int compareTo(Pair<K, V> pair) {
return k.compareTo(pair.k) == 0 ? v.compareTo(pair.v) : k.compareTo(pair.k);
}
@Override
public Pair<K, V> clone() {
return new Pair<K, V>(this.k, this.v);
}
@Override
public String toString() {
return String.valueOf(k).concat(" ").concat(String.valueOf(v)).concat("\n");
}
}
static class Reader {
private BufferedReader br;
private StringTokenizer st;
Reader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
try {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = nextInt();
return arr;
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String s = "";
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return s;
}
}
} | Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1 ≤ |s| ≤ 105) — string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | a7bea952ff49b1607fd6c7349df503ed | train_000.jsonl | 1400167800 | You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.sql.Array;
import java.util.*;
import java.util.stream.Stream;
public class AtCoder implements Runnable {
static final int MOD = (int) 1e9 + 7;
static final Reader in = new Reader();
static final PrintWriter out = new PrintWriter(System.out);
StringBuilder answer = new StringBuilder();
public static void main(String[] args) {
new Thread(null, new AtCoder(), "persefone", 1 << 28).start();
}
@Override
public void run() {
solve();
printf();
flush();
}
void solve() {
char[] s = in.next().toCharArray();
int n = s.length;
int[] z = StringUtils.z_function(s);
int[][] cnt = new int[n][];
for (int i = 1; i < n; i++) {
int k = z[i];
if (k == 0) continue;
if (cnt[k] == null) cnt[k] = new int[2];
cnt[k][0] = i;
cnt[k][1]++;
}
int sum = 0;
Stack<String> ans = new Stack<>();
ans.push(n + " " + 1);
for (int i = n - 1; i > 0; i--) {
if (cnt[i] == null) continue;
if (cnt[i][0] + i == n) {
ans.push(i + " " + (sum + cnt[i][1] + 1));
}
sum += cnt[i][1];
}
printf(ans.size());
while (!ans.isEmpty()) add(ans.pop(), '\n');
}
static class StringUtils {
static int[] z_function(char[] s) {
int n = s.length;
int[] z = new int[n];
// z[0...r - l] = z[l...r] - [l, r] the rightmost segments match.
for (int i = 1, left = 0, right = 0; i < n; i++) {
/* i <= r: according to the fomula above: z[i] = z[i - left]
if i + z[i - left] < r -> ok
if not : z[i] = r - i + 1;
*/
if (i <= right) z[i] = Math.min(z[i - left], right - i + 1);
// run trivial algorithm
while (i + z[i] < n && s[z[i]] == s[i + z[i]]) z[i]++;
// update l & r
if (i + z[i] - 1 > right) {
left = i;
right = i + z[i] - 1;
}
}
return z;
}
static int[] z_function(CharSequence s) {
return z_function(s.toString().toCharArray());
}
}
void printf() {
out.print(answer);
}
void close() {
out.close();
}
void flush() {
out.flush();
}
void printf(Stream<?> str) {
str.forEach(o -> add(o, " "));
add("\n");
}
void printf(Object... obj) {
printf(false, obj);
}
void printfWithDescription(Object... obj) {
printf(true, obj);
}
private void printf(boolean b, Object... obj) {
if (obj.length > 1) {
for (int i = 0; i < obj.length; i++) {
if (b) add(obj[i].getClass().getSimpleName(), " - ");
if (obj[i] instanceof Collection<?>) {
printf((Collection<?>) obj[i]);
} else if (obj[i] instanceof int[][]) {
printf((int[][]) obj[i]);
} else if (obj[i] instanceof long[][]) {
printf((long[][]) obj[i]);
} else if (obj[i] instanceof double[][]) {
printf((double[][]) obj[i]);
} else printf(obj[i]);
}
return;
}
if (b) add(obj[0].getClass().getSimpleName(), " - ");
printf(obj[0]);
}
void printf(Object o) {
if (o instanceof int[])
printf(Arrays.stream((int[]) o).boxed());
else if (o instanceof char[])
printf(new String((char[]) o));
else if (o instanceof long[])
printf(Arrays.stream((long[]) o).boxed());
else if (o instanceof double[])
printf(Arrays.stream((double[]) o).boxed());
else if (o instanceof boolean[]) {
for (boolean b : (boolean[]) o) add(b, " ");
add("\n");
} else
add(o, "\n");
}
void printf(int[]... obj) {
for (int i = 0; i < obj.length; i++) printf(obj[i]);
}
void printf(long[]... obj) {
for (int i = 0; i < obj.length; i++) printf(obj[i]);
}
void printf(double[]... obj) {
for (int i = 0; i < obj.length; i++) printf(obj[i]);
}
void printf(boolean[]... obj) {
for (int i = 0; i < obj.length; i++) printf(obj[i]);
}
void printf(Collection<?> col) {
printf(col.stream());
}
<T, K> void add(T t, K k) {
if (t instanceof Collection<?>) {
((Collection<?>) t).forEach(i -> add(i, " "));
} else if (t instanceof Object[]) {
Arrays.stream((Object[]) t).forEach(i -> add(i, " "));
} else
add(t);
add(k);
}
<T> void add(T t) {
answer.append(t);
}
@SuppressWarnings("unchecked")
<T extends Comparable<? super T>> T min(T... t) {
if (t.length == 0)
return null;
T m = t[0];
for (int i = 1; i < t.length; i++)
if (t[i].compareTo(m) < 0)
m = t[i];
return m;
}
@SuppressWarnings("unchecked")
<T extends Comparable<? super T>> T max(T... t) {
if (t.length == 0)
return null;
T m = t[0];
for (int i = 1; i < t.length; i++)
if (t[i].compareTo(m) > 0)
m = t[i];
return m;
}
static class Pair<K extends Comparable<? super K>, V extends Comparable<? super V>>
implements Comparable<Pair<K, V>> {
private K k;
private V v;
Pair(K k, V v) {
this.k = k;
this.v = v;
}
@SuppressWarnings("unchecked")
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || !(o instanceof Pair)) return false;
Pair<K, V> p = (Pair<K, V>) o;
return k.compareTo(p.k) == 0 && v.compareTo(p.v) == 0;
}
@Override
public int hashCode() {
int hash = 31;
hash = hash * 89 + k.hashCode();
hash = hash * 89 + v.hashCode();
return hash;
}
@Override
public int compareTo(Pair<K, V> pair) {
return k.compareTo(pair.k) == 0 ? v.compareTo(pair.v) : k.compareTo(pair.k);
}
@Override
public Pair<K, V> clone() {
return new Pair<K, V>(this.k, this.v);
}
@Override
public String toString() {
return String.valueOf(k).concat(" ").concat(String.valueOf(v)).concat("\n");
}
}
static class Reader {
private BufferedReader br;
private StringTokenizer st;
Reader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
try {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = nextInt();
return arr;
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String s = "";
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return s;
}
}
} | Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1 ≤ |s| ≤ 105) — string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | 6e2332a0f77ebbb6e699ed09d09cd3e1 | train_000.jsonl | 1400167800 | You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | import static java.lang.Math.* ;
import static java.util.Arrays.* ;
import java.util.*;
import java.io.*;
public class Main
{
TreeMap<Character , Integer> [] next ;
int [] link , len , cnt ;
int idx , last ;
void addLetter(char c) {
int curr = ++idx, p = last;
len[curr] = len[p] + 1;
cnt[curr] = 1 ;
while (!next[p].containsKey(c)) {
next[p].put(c, curr);
p = link[p];
}
int q = next[p].get(c) ;
if(q != curr)
{
if(len[q] == len[p] + 1 )
link[curr] = q ;
else {
int clone = ++idx ;
len[clone] = len[p] + 1 ;
link[clone] = link[q] ;
link[q] = link[curr] = clone ;
next[clone] = (TreeMap<Character, Integer>) next[q].clone();
while (next[p].get(c) == q)
{
next[p].put(c , clone) ;
p = link[p] ;
}
}
}
next[last = curr] = new TreeMap<>() ;
}
void main() throws Exception
{
Scanner sc = new Scanner(System.in) ;
PrintWriter out = new PrintWriter(System.out) ;
char [] s = sc.next().toCharArray() ;
int n = s.length ;
next = new TreeMap[n << 1] ;
next[0] = new TreeMap<>();
link = new int [n << 1] ;
len = new int [n << 1] ;
cnt = new int [n << 1] ;
Hashing hashing = new Hashing((s)) ;
for(int i = 0 ; i < n ; i++)
addLetter(s[i]);
Integer [] id = new Integer[n << 1] ;
for(int i = 0 ; i < n << 1 ; i++)
id[i] = i ;
sort(id , (x , y) -> len[y] - len[x]);
for(int v : id)
cnt[link[v]] += cnt[v];
int ans = 0 ;
StringBuilder sb = new StringBuilder() ;
int state = 0 ;
for(int l = 1 ;l <= n ; l++)
{
state = next[state].get(s[l - 1]) ;
if(hashing.getHash(1 , l) == hashing.getHash(n - l + 1 , n))
{
ans ++ ;
sb.append(l).append(' ').append(cnt[state]).append('\n') ;
}
}
out.println(ans);
out.println(sb);
out.flush();
out.close();
}
int pow(int a , int e , int MOD)
{
int res = 1 ;
while(e > 0)
{
if((e & 1) == 1)
res = (int)(1L * res * a % MOD) ;
a = (int)(1L * a * a % MOD) ;
e /= 2 ;
}
return res ;
}
class Hashing
{
final int P_L = 31, MOD_L = (int)1e9 + 9 , MOD_INV_L = pow(P_L, MOD_L - 2, MOD_L);
final int P_H = 43, MOD_H = (int)1e9 + 7 , MOD_INV_H = pow(P_H, MOD_H - 2, MOD_H);
long [] hash_LOW , hash_HIGH;
long [] inv_LOW , inv_HIGH;
int n ;
Hashing(char [] s)
{
n = s.length;
hash_LOW = new long [n + 1];
hash_HIGH = new long [n + 1] ;
inv_LOW = new long [n + 1] ;
inv_HIGH = new long [n + 1] ;
inv_LOW[0] = inv_HIGH[0] = 1;
long pow_L = 1 ;
long pow_H = 1 ;
for(int i = 1 ; i <= n ; i++)
{
int c = s[i - 1] - 'a' + 1 ;
hash_LOW[i] = (hash_LOW[i - 1] + (c * pow_L)) % MOD_L;
inv_LOW[i] = inv_LOW[i - 1] * MOD_INV_L % MOD_L;
pow_L = pow_L * P_L % MOD_L;
hash_HIGH[i] = (hash_HIGH[i - 1] + (c * pow_H)) % MOD_H;
inv_HIGH[i] = inv_HIGH[i - 1] * MOD_INV_H % MOD_H;
pow_H = pow_H * P_H % MOD_H;
}
}
long getHash(int i , int j)
{
long get_HIGH = ((hash_HIGH[j] - hash_HIGH[i - 1] + MOD_H) * inv_HIGH[i - 1] )% MOD_H ;
long get_LOW = ((hash_LOW[j] - hash_LOW[i - 1] + MOD_L) * inv_LOW[i - 1] )% MOD_L ;
return (get_HIGH << 32) | get_LOW ;
}
}
class Scanner
{
BufferedReader br;
StringTokenizer st;
Scanner(InputStream in)
{
br = new BufferedReader(new InputStreamReader(System.in));
}
Scanner(String path) throws Exception
{
br = new BufferedReader(new FileReader(path)) ;
}
String next() throws Exception
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
int nextInt() throws Exception { return Integer.parseInt(next()); }
long nextLong() throws Exception { return Long.parseLong(next()); }
double nextDouble() throws Exception { return Double.parseDouble(next());}
}
public static void main (String [] args) throws Exception {(new Main()).main();}
} | Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1 ≤ |s| ≤ 105) — string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | 2af47f1a9ea64ebf8acb626377942b9b | train_000.jsonl | 1400167800 | You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | import static java.lang.Math.*;
import static java.util.Arrays.* ;
import java.util.*;
import java.io.*;
public class B
{
int [] ans ;
void KMP (char [] s)
{
int n = s.length;
int [] pi = new int [n + 1] ;
ans = new int [n + 1] ;
for(int i = 1 , j = 0 ; i < n ; i++)
{
while(j > 0 && s[i] != s[j]) j = pi[j - 1] ;
if(s[i] == s[j])
pi[i] = ++ j ;
else
pi[i] = j ;
}
for (int i = 0; i < n; i++)
ans[pi[i]]++;
for (int i = n-1; i > 0; i--)
ans[pi[i-1]] += ans[i];
for (int i = 0; i <= n; i++)
ans[i]++;
}
void main() throws Exception
{
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
String s = sc.next() ;
Hashing str = new Hashing(s.toCharArray()) ;
KMP(s.toCharArray());
int n = s.length() ;
StringBuilder sb = new StringBuilder() ;
int cnt = 0 ;
for(int l = 1 ; l <= n ; l ++)
{
if(str.getHash(1 , l) == str.getHash(n - l + 1 ,n))
{
cnt ++ ;
sb.append(l).append(' ').append(ans[l]).append('\n') ;
}
}
out.println(cnt);
out.print(sb);
out.flush();
out.close();
}
int pow(int a , int e , int MOD)
{
int res = 1 ;
while(e > 0)
{
if((e & 1) == 1)
res = (int)(1L * res * a % MOD) ;
a = (int)(1L * a * a % MOD) ;
e /= 2 ;
}
return res ;
}
class Hashing
{
final int P_L = 31, MOD_L = (int)1e9 + 9 , MOD_INV_L = pow(P_L, MOD_L - 2, MOD_L);
final int P_H = 43, MOD_H = (int)1e9 + 7 , MOD_INV_H = pow(P_H, MOD_H - 2, MOD_H);
long [] hash_LOW , hash_HIGH;
long [] inv_LOW , inv_HIGH;
int n ;
Hashing(char [] s)
{
n = s.length;
hash_LOW = new long [n + 1];
hash_HIGH = new long [n + 1] ;
inv_LOW = new long [n + 1] ;
inv_HIGH = new long [n + 1] ;
inv_LOW[0] = inv_HIGH[0] = 1;
long pow_L = 1 ;
long pow_H = 1 ;
for(int i = 1 ; i <= n ; i++)
{
int c = s[i - 1] - 'a' + 1 ;
hash_LOW[i] = (hash_LOW[i - 1] + (c * pow_L)) % MOD_L;
inv_LOW[i] = inv_LOW[i - 1] * MOD_INV_L % MOD_L;
pow_L = pow_L * P_L % MOD_L;
hash_HIGH[i] = (hash_HIGH[i - 1] + (c * pow_H)) % MOD_H;
inv_HIGH[i] = inv_HIGH[i - 1] * MOD_INV_H % MOD_H;
pow_H = pow_H * P_H % MOD_H;
}
}
long getHash(int i , int j)
{
long get_HIGH = ((hash_HIGH[j] - hash_HIGH[i - 1] + MOD_H) * inv_HIGH[i - 1] )% MOD_H ;
long get_LOW = ((hash_LOW[j] - hash_LOW[i - 1] + MOD_L) * inv_LOW[i - 1] )% MOD_L ;
return (get_HIGH << 32) | get_LOW ;
}
}
class Scanner
{
BufferedReader br;
StringTokenizer st;
Scanner(InputStream in)
{
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() throws Exception
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
int nextInt() throws Exception { return Integer.parseInt(next()); }
long nextLong() throws Exception { return Long.parseLong(next()); }
double nextDouble() throws Exception { return Double.parseDouble(next());}
boolean ready() throws Exception{
return br.ready() ;
}
}
public static void main (String [] args) throws Exception {(new B()).main();}
} | Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1 ≤ |s| ≤ 105) — string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | e64ee4748454b9f4230569caa679244a | train_000.jsonl | 1400167800 | You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | import java.io.*;
import java.io.IOException;
import java.lang.Thread.State;
import java.util.*;
//import javafx.util.Pair;
//import java.util.concurrent.LinkedBlockingDeque;
public class Codeforces {
public static long mod = (long)Math.pow(10,9)+7 ;
public static double epsilon=0.00000000008854;//value of epsilon
public static InputReader sc = new InputReader(System.in);
public static PrintWriter pw = new PrintWriter(System.out);
public static ArrayList<ArrayList <Pair>> GetGraph(int n,int m){
ArrayList<ArrayList <Pair>> g=new ArrayList<>();
for(int i=0;i<n;i++){
g.add(new ArrayList<>());
}
for(int i=0;i<m;i++){
//int t=sc.nextInt();
int u=sc.nextInt()-1;
int v=sc.nextInt()-1;
int w=sc.nextInt();
g.get(u).add(new Pair(v, w));
//if(t==0)
g.get(v).add(new Pair(u,w));
}
return g;
}
public static int find(int a,int p[]){
if(a!=p[a]){
p[a]=find(p[a], p);
}
return p[a];
}
public static void Union(int a,int b,int p[]){
p[find(b, p)]=find(a, p);
}
public static long gcd(long a,long b){
while(b>0){
long t=b;
b=a%b;
a=t;
}
return a;
}
public static int dfs(ArrayList<ArrayList <Pair>> g,int u,int p,long pathSum,long maxS){
//vis[u]=1;
int Inf=100000000;
int cost=0;
for(int i=0;i<g.get(u).size();i++){
int v=g.get(u).get(i).no;
int c=Inf;
if(v!=p){
int w=g.get(u).get(i).we;
int t=0;
while(w>0){
c=Math.min(dfs(g, v, u, pathSum+w, maxS)+t, c);
t++;
w/=2;
}
//if(c!=Integer.MAX_VALUE)
if(c!=Inf)
cost+=c;
else{
cost=Inf;
}
}
}
if(g.get(u).size()==1&&pathSum>maxS){
cost=Inf;
}
return cost;
}
public static long[][] multiply(long a[][], long b[][])
{
long mul[][] = new long[a.length][b[0].length];
for (int i = 0; i < a.length; i++)
{
for (int j = 0; j < b[0].length; j++)
{
mul[i][j] = Long.MAX_VALUE;
for (int k = 0; k < a[0].length; k++)
//mul[i][j] += (a[i][k] * b[k][j])%mod;
//mul[i][j] %= mod;
if(a[i][k]!=Long.MAX_VALUE&&b[k][j]!=Long.MAX_VALUE)
mul[i][j]=Math.max(a[i][k] + b[k][j],mul[i][j]);
}
}
return mul;
}
public static long[][] power(long F[][], long n)
{
long[][] result = new long[F.length][F.length];
for(int i=0; i<F.length; i++)
result[i][i] = 1;
while (n > 0) {
if (n % 2 == 1)
result = multiply(result, F);
F = multiply(F, F);
n = n / 2;
//System.out.println("==");
}
return result;
}
public static long pow(long x,long y,long mod){
long ans=1;
//If u know that mod=prime than don't do phi just write (mod-1) instead
x%=mod;
while(y>0){
if((y&1)==1){
ans=(ans*x)%mod;
}
y=y>>1;
x=(x*x)%mod;
}
return ans;
}
public static long nCr(long n,long r)
{
long ans=1;
for(long i=0;i<r;i++)
{
ans=(ans*(n-i))/(i+1);
}
return ans;
}
public static int fun(int i,int j,int x,int y,int dp[][],String s[]){
int n=s.length;
int m=s[0].length();
if(x<0||y<0||x>=n||y>=m){
return 0;
}
if(s[i].charAt(j)==s[x].charAt(y)){
return dp[x][y];
}
else return 0;
}
public static char getchar(int n,String s[]){
if(s[2].charAt(n+2)=='.'){
return 'A';
}
if(s[1].charAt(n)=='.'){
return 'I';
}
if(s[0].charAt(n+2)=='.'){
return 'U';
}
if(s[1].charAt(n+2)=='.'){
return 'O';
}
return 'E';
}
public static int[] lps(String s){
int n=s.length();
int a[]=new int[n];
int j=0;
for(int i=1;i<n;i++){
while(j>0&&s.charAt(j)!=s.charAt(i)){
j=a[--j];
}
if(s.charAt(i)==s.charAt(j)){
j++;
a[i]=j;
}
}
return a;
}
public static void main(String[] args) {
// code starts..
String s=sc.nextLine();
int pre[]=lps(s);
int n=s.length();
long presum[]=new long[n+1];
for(int i=1;i<n;i++){
int j=pre[i];
presum[j]++;
}
for(int i=n;i>=1;i--){
presum[pre[i-1]]+=presum[i];
}
//presum[n]=1;
for(int i=1;i<=n;i++){
presum[i]++;
}
ArrayList<Integer> ansI=new ArrayList<>();
int j=n;
while(j>0){
ansI.add(j);
j=pre[j-1];
}
Collections.sort(ansI);
pw.println(ansI.size());
for(int i=0;i<ansI.size();i++){
int l=ansI.get(i);
pw.println(l+" "+presum[l]);
}
// Code ends...
pw.flush();
pw.close();
}
public static Comparator<Long[]> column(int i){
return
new Comparator<Long[]>() {
@Override
public int compare(Long[] o1, Long[] o2) {
return o1[i].compareTo(o2[i]);//for ascending
//return o2[i].compareTo(o1[i]);//for descending
}
};
}
public static Comparator<Integer[]> pair(){
return
new Comparator<Integer[]>() {
@Override
public int compare(Integer[] o1, Integer[] o2) {
int result=o1[0].compareTo(o2[0]);
if(result==0)
result=o1[1].compareTo(o2[1]);
return result;
}
};
}
public static String reverseString(String s){
StringBuilder input1 = new StringBuilder();
input1.append(s);
input1 = input1.reverse();
return input1.toString();
}
public static int[] scanArray(int n){
int a[]=new int [n];
for(int i=0;i<n;i++)
a[i]=sc.nextInt();
return a;
}
public static long[] scanLongArray(int n){
long a[]=new long [n];
for(int i=0;i<n;i++)
a[i]=sc.nextLong();
return a;
}
public static String [] scanStrings(int n){
String a[]=new String [n];
for(int i=0;i<n;i++)
a[i]=sc.nextLine();
return a;
}
public static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int snext() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public String readString() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
class SegmentTree{
int s[],n;
SegmentTree(int l1){
n=l1;
int l=(int)Math.ceil(Math.log(n)/Math.log(2));
l=2*(int)Math.pow(2,l)-1;
s=new int[l];
//createSegmentTreeUtil(a, 0, 0, a.length-1);
}
int createSegmentTreeUtil(int a[],int root,int l,int r){
if(l==r)
s[root]=a[l];
else
s[root]= Compare(createSegmentTreeUtil(a, 2*root+1, l, (l+r)/2), createSegmentTreeUtil(a,2*root+2, (l+r)/2+1,r));
return s[root];
}
int getValue(int gl,int gr){
return getValueUtil(0, 0, n-1, gl, gr);
}
int getValueUtil(int root,int l,int r,int gl,int gr){
if(l>=gl&&r<=gr){
return s[root];
}
if(l>gr||r<gl){
return 0;
}
return Compare(getValueUtil(2*root+1, l, (l+r)/2, gl, gr), getValueUtil(2*root+2, (l+r)/2+1, r, gl, gr));
}
void update(int p,int k){
updateUtil(p, k,0,0,n-1);
}
int updateUtil(int p,int k,int root,int l,int r){
if(l==r&&l==k){
return s[root]=p;
}
else if(l>k||r<k)
return s[root];
else{
return s[root]=Compare(updateUtil(p, k, 2*root+1, l, (l+r)/2), updateUtil(p, k, 2*root+2,(l+r)/2+1,r ));
}
}
int Compare(int a,int b){
return Math.max(a, b);
}
}
class Pair{
int no;
int we;
Pair(int node,int weight){
no=node;
we=weight;
}
}
class Bit{//1...n
int a[];
Bit(int n){
a=new int[n+1];
}
void update(int i,int delta){
if(i<=0){
System.out.println("dfladfl");
return;
}
while(i<a.length){
a[i]+=delta;
i+=i&(-i);
}
}
int query(int i){
int sum=0;
while(i>0){
sum+=a[i];
i-=i&(-i);
}
return sum;
}
}
| Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1 ≤ |s| ≤ 105) — string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | 1d513cf5cd50eb7e980e46689beae478 | train_000.jsonl | 1400167800 | You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException
{
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
char s[] = sc.nextLine().toCharArray();
int z[] = zAlgo(s);
int freq[] = new int[s.length + 1];
freq[s.length] = 1;
boolean valid[] = new boolean[s.length + 1];
valid[s.length] = true;
for(int i = 0; i < s.length; ++i) if(i + z[i] == s.length) valid[z[i]] = true;
for(int i = 0; i < s.length; ++i) freq[z[i]]++;
int var = 0;
int cnt = 0;
for(int i = s.length; i > 0; i--) {
if(freq[i] > 0) { if(valid[i])cnt++; freq[i] += var; var = freq[i]; }
}
out.println(cnt);
for(int i = 1; i <= s.length; ++i) {
if(freq[i] > 0 && valid[i])
out.println(i + " " + freq[i]);
}
out.flush();
out.close();
}
static int [] zAlgo(char [] s) {
int n = s.length;
int z[] = new int[n];
for(int i = 1, L = 0, R = 0; i < n; ++i) {
if(R < i) {
L = R = i;
while(R < n && s[R - L] == s[R]) R++;
z[i] = R - L;
R--;
}
else {
int k = i - L;
if(i + z[k] <= R) z[i] = z[k];
else {
L = i;
while(R < n && s[R] == s[R - L]) R++;
z[i] = R - L; R--;
}
}
}
return z;
}
static class Pair implements Comparable<Pair>{
long a;
int b;
public Pair(long x, int y) {
a = x;
b = y;
}
@Override
public int compareTo(Pair p) {
if(Long.compare(a, p.a) == 0)
return Integer.compare(b, p.b);
return Long.compare(a, p.a);
}
}
static class Scanner{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public Scanner(FileReader r){ br = new BufferedReader(r);}
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 | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1 ≤ |s| ≤ 105) — string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | 02b4cb296ef20b63adf8215da6bff2a3 | train_000.jsonl | 1400167800 | You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Stack;
public class D432
{
static class Scanner
{
BufferedReader br;
StringTokenizer tk=new StringTokenizer("");
public Scanner(InputStream is)
{
br=new BufferedReader(new InputStreamReader(is));
}
public int nextInt() throws IOException
{
if(tk.hasMoreTokens())
return Integer.parseInt(tk.nextToken());
tk=new StringTokenizer(br.readLine());
return nextInt();
}
public long nextLong() throws IOException
{
if(tk.hasMoreTokens())
return Long.parseLong(tk.nextToken());
tk=new StringTokenizer(br.readLine());
return nextLong();
}
public String next() throws IOException
{
if(tk.hasMoreTokens())
return (tk.nextToken());
tk=new StringTokenizer(br.readLine());
return next();
}
public String nextLine() throws IOException
{
tk=new StringTokenizer("");
return br.readLine();
}
public double nextDouble() throws IOException
{
if(tk.hasMoreTokens())
return Double.parseDouble(tk.nextToken());
tk=new StringTokenizer(br.readLine());
return nextDouble();
}
public char nextChar() throws IOException
{
if(tk.hasMoreTokens())
return (tk.nextToken().charAt(0));
tk=new StringTokenizer(br.readLine());
return nextChar();
}
public int[] nextIntArray(int n) throws IOException
{
int a[]=new int[n];
for(int i=0;i<n;i++)
a[i]=nextInt();
return a;
}
public long[] nextLongArray(int n) throws IOException
{
long a[]=new long[n];
for(int i=0;i<n;i++)
a[i]=nextLong();
return a;
}
public int[] nextIntArrayOneBased(int n) throws IOException
{
int a[]=new int[n+1];
for(int i=1;i<=n;i++)
a[i]=nextInt();
return a;
}
public long[] nextLongArrayOneBased(int n) throws IOException
{
long a[]=new long[n+1];
for(int i=1;i<=n;i++)
a[i]=nextLong();
return a;
}
}
public static void main(String args[]) throws IOException
{
Scanner in=new Scanner(System.in);
PrintWriter out=new PrintWriter(System.out);
char c[]=in.next().toCharArray();
int n=c.length;
int f[]=new int[n];
for(int i=1;i<n;i++)
{
int j=f[i-1];
while(j>0&&c[i]!=c[j])
j=f[j-1];
if(c[i]==c[j])
j++;
f[i]=j;
}
int cnt[]=new int[n+1];
for(int i=0;i<n;i++)
cnt[f[i]]++;
cnt[0]=0;
cnt[n]=1;
for(int i=n;i>0;i--)
{
if(cnt[i]!=0)
cnt[f[i-1]]+=cnt[i];
}
Stack<Integer> s1=new Stack<>();
Stack<Integer> s2=new Stack<>();
int l=n;
while(l>0)
{
s1.push(l);
s2.push(cnt[l]);
l=f[l-1];
}
out.println(s1.size());
while(!s1.isEmpty())
out.println(s1.pop()+" "+s2.pop());
out.close();
}
}
| Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1 ≤ |s| ≤ 105) — string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | 933546670afc286037dfadf24e1b9954 | train_000.jsonl | 1400167800 | You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.StringTokenizer;
public class temp4 {
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
/* static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
} */
static class Print
{
private final BufferedWriter bw;
public Print()
{
bw=new BufferedWriter(new OutputStreamWriter(System.out));
}
public void print(String str)throws IOException
{
bw.append(str);
}
public void println(String str)throws IOException
{
print(str);
bw.append("\n");
}
public void close()throws IOException
{
bw.close();
}}
public static void main(String[] args) throws IOException {
FastReader scn=new FastReader();
Print pr=new Print();
String s=" "+scn.next();
int n=s.length(),count=0;
int[] prev=new int[n];
int[] len=new int[n];
int[] inf=new int[n];
for(int i=2,j=0;i<n;i++){
while(j>0&&s.charAt(i)!=s.charAt(j+1))j=prev[j];
if(s.charAt(i)==s.charAt(j+1)) j++;
prev[i]=j;
}
for(int i=n-1;i>0;i=prev[i]) len[++count]=i;
for(int i=n-1;i>0;--i) inf[prev[i]]+= (++inf[i]);
pr.println(""+count);
for(int i=count;i>0;i--)pr.println(len[i]+" "+inf[len[i]]);
pr.close();
}
} | Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1 ≤ |s| ≤ 105) — string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | 4afff863bded2a54996c25f37d1cc6a9 | train_000.jsonl | 1400167800 | You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | import java.util.*;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
public class A
{
public static void main(String ar[]) throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
char c[]=br.readLine().toCharArray();
int n=c.length;
int a[]=new int[n];
int i=1,j=0;
while(i<n)
{
while(j>0 && c[i]!=c[j])
j=a[j-1];
if(c[i]==c[j])
{ a[i]=j+1; j++; }
i++;
}
HashSet<Integer> hs=new HashSet<Integer>();
TreeMap<Integer,Integer> hm=new TreeMap<Integer,Integer>();
int t=a[n-1];
while(t>0)
{
hs.add(t);
hm.put(t,0);
t=a[t-1];
}
// System.out.println(Arrays.toString(a));
for(i=1;i<n;i++)
{
// if(!hs.contains(a[i]))
// continue;
if(hm.containsKey(a[i]))
hm.put(a[i],1+hm.get(a[i]));
else
hm.put(a[i],1);
}
// System.out.println(hs);
int b[]=new int[100001];
for(int v:hm.descendingKeySet())
{
b[v]=hm.get(v);
// if(hm.containsKey(a[v-1]))
// hm.put(a[v-1],hm.get(v)+hm.get(a[v-1]));
// else
// hm.put(a[v-1],);
}
for(i=100000;i>0;i--)
{
if(b[i]==0)
continue;
int u=a[i-1];
b[u]+=b[i];
}
StringBuffer sb=new StringBuffer();
t=0;
for(i=1;i<=100000;i++)
{
if(b[i]>0 && hs.contains(i))
{ t++; sb.append(i+" "+(1+b[i])).append("\n"); }
}
System.out.println(t+1);
System.out.print(sb);
System.out.println(n+" 1");
// System.out.println(1+hm.size());
// for(int k:hm.keySet())
// {
// if(hs.contains(k))
// System.out.println(k+" "+(1+hm.get(k)));
// }
}
} | Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1 ≤ |s| ≤ 105) — string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | b88a77403290be4103bd6d0f39150724 | train_000.jsonl | 1400167800 | You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | import java.io.*;
import java.util.*;
/*
* Heart beats fast
* Colors and promises
* How to be brave
* How can I love when I am afraid to fall...
*/
//read the question correctly (is y a vowel? what are the exact constraints?)
//look out for SPECIAL CASES (n=1?) and overflow (ll vs int?)
public class Main
{
public static void main(String[] args)
{
String s=ns();
int pre[]=new int[s.length()+1];
for(int i=1,j=0; i<s.length(); i++)
if(s.charAt(i)==s.charAt(j))
{
j++;
pre[i]=j;
}
else if(j!=0)
{
i--;
j=pre[j-1];
}
int n=s.length();
int hola[]=new int[n+1];
for(int i=0; i<n; i++)
hola[pre[i]]++;
hola[n]++;
for(int i=n; i>0; i--)
hola[pre[i-1]]+=hola[i];
int te=n;
ArrayList<StringBuilder> ans=new ArrayList<StringBuilder>();
while(te!=0)
{
ans.add(new StringBuilder(te+" "+hola[te]));
te=pre[te-1];
}
pr(ans.size());
for(int i=ans.size()-1; i>=0; i--)
{
pr(ans.get(i));
}
System.out.print(output);
}
///////////////////////////////////////////
///////////////////////////////////////////
///template from here
static class pair
{
int a,b;
pair()
{
}
pair(int c,int d)
{
a=c;
b=d;
}
}
void sort(pair[]a)
{
Arrays.sort(a,new Comparator<pair>()
{
@Override
public int compare(pair a,pair b)
{
if(a.a>b.a)
return 1;
if(b.a>a.a)
return -1;
return 0;
}
});
}
static int log2n(long a)
{
int te=0;
while(a>0)
{
a>>=1;
++te;
}
return te;
}
static class iter
{
vecti a;
int curi=0;
iter(vecti b)
{
a=b;
}
public boolean hasNext()
{
if(a.size>curi)
return true;
return false;
}
public int next()
{
return a.a[curi++];
}
public void previous()
{
curi--;
}
}
static class vecti
{
int a[],size;
vecti()
{
a=new int[10];
size=0;
}
vecti(int n)
{
a=new int[n];
size=0;
}
public void add(int b)
{
if(++size==a.length)
a=Arrays.copyOf(a, 2*size);
a[size-1]=b;
}
public void sort()
{
Arrays.sort(a, 0, size);
}
public void sort(int l, int r)
{
Arrays.sort(a, l, r);
}
public iter iterator()
{
return new iter(this);
}
}
static class lter
{
vectl a;
int curi=0;
lter(vectl b)
{
a=b;
}
public boolean hasNext()
{
if(a.size>curi)
return true;
return false;
}
public long next()
{
return a.a[curi++];
}
public long prev()
{
return a.a[--curi];
}
}
static class vectl
{
long a[];
int size;
vectl()
{
a=new long[10];
size=0;
}
vectl(int n)
{
a=new long[n];
size=0;
}
public void add(long b)
{
if(++size==a.length)
a=Arrays.copyOf(a, 2*size);
a[size-1]=b;
}
public void sort()
{
Arrays.sort(a, 0, size);
}
public void sort(int l, int r)
{
Arrays.sort(a, l, r);
}
public lter iterator()
{
return new lter(this);
}
}
static class dter
{
vectd a;
int curi=0;
dter(vectd b)
{
a=b;
}
public boolean hasNext()
{
if(a.size>curi)
return true;
return false;
}
public double next()
{
return a.a[curi++];
}
public double prev()
{
return a.a[--curi];
}
}
static class vectd
{
double a[];
int size;
vectd()
{
a=new double[10];
size=0;
}
vectd(int n)
{
a=new double[n];
size=0;
}
public void add(double b)
{
if(++size==a.length)
a=Arrays.copyOf(a, 2*size);
a[size-1]=b;
}
public void sort()
{
Arrays.sort(a, 0, size);
}
public void sort(int l, int r)
{
Arrays.sort(a, l, r);
}
public dter iterator()
{
return new dter(this);
}
}
static final int mod=1000000007;
static final double eps=1e-8;
static final long inf=100000000000000000L;
static Reader in=new Reader();
static StringBuilder output=new StringBuilder();
static Random rn=new Random();
//output functions////////////////
static void pr(Object a){output.append(a+"\n");}
static void pr(){output.append("\n");}
static void p(Object a){output.append(a);}
static void pra(int[]a){for(int i:a)output.append(i+" ");output.append("\n");}
static void pra(long[]a){for(long i:a)output.append(i+" ");output.append("\n");}
static void pra(String[]a){for(String i:a)output.append(i+" ");output.append("\n");}
static void pra(double[]a){for(double i:a)output.append(i+" ");output.append("\n");}
static void sop(Object a){System.out.println(a);}
static void flush(){System.out.println(output);output=new StringBuilder();}
//////////////////////////////////
//input functions/////////////////
static int ni(){return in.nextInt();}
static long nl(){return Long.parseLong(in.next());}
static String ns(){return in.next();}
static double nd(){return Double.parseDouble(in.next());}
static int[] nia(int n){int a[]=new int[n];for(int i=0; i<n; i++)a[i]=ni();return a;}
static int[] pnia(int n){int a[]=new int[n+1];for(int i=1; i<=n; i++)a[i]=ni();return a;}
static long[] nla(int n){long a[]=new long[n];for(int i=0; i<n; i++)a[i]=nl();return a;}
static String[] nsa(int n){String a[]=new String[n];for(int i=0; i<n; i++)a[i]=ns();return a;}
static double[] nda(int n){double a[]=new double[n];for(int i=0; i<n; i++)a[i]=nd();return a;}
static vecti niv(int n) {vecti a=new vecti(n);a.size=n;for(int i=0; i<n; i++)a.a[i]=ni();return a;}
static vectl nlv(int n) {vectl a=new vectl(n);a.size=n;for(int i=0; i<n; i++)a.a[i]=nl();return a;}
static vectd ndv(int n) {vectd a=new vectd(n);a.size=n;for(int i=0; i<n; i++)a.a[i]=nd();return a;}
//////////////////////////////////
//some utility functions
static void exit(){System.exit(0);}
static void psort(int[][] a)
{
Arrays.sort(a, new Comparator<int[]>()
{
@Override
public int compare(int[]a,int[]b)
{
if(a[0]>b[0])
return 1;
else if(b[0]>a[0])
return -1;
return 0;
}
});
}
static String pr(String a, long b)
{
String c="";
while(b>0)
{
if(b%2==1)
c=c.concat(a);
a=a.concat(a);
b>>=1;
}
return c;
}
static long powm(long a, long b, long m)
{
long an=1;
long c=a;
while(b>0)
{
if(b%2==1)
an=(an*c)%m;
c=(c*c)%m;
b>>=1;
}
return an;
}
static int gcd(int a, int b)
{
if(b==0)
return a;
else
return gcd(b, a%b);
}
static class Reader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public Reader() {
reader = new BufferedReader(new InputStreamReader(System.in), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
} | Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1 ≤ |s| ≤ 105) — string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | 6d7eca5f9f40013985874ee1d77d72cc | train_000.jsonl | 1400167800 | You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class A {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter wr = new PrintWriter(System.out);
String s=sc.next().toLowerCase();
int a[]=zAlgo(s.toCharArray());
//System.out.println(Arrays.toString(a));
ArrayList<Long>list=new ArrayList<>();
for(int i=0;i<a.length;i++) {
list.add((long) a[i]);
}
Collections.sort(list);
Collections.reverse(list);
HashMap<Long, Long>map=new HashMap<>();
for(int i=0;i<list.size();i++) {
map.put(list.get(i), 1l*i+1);
}
Queue<pair>q=new LinkedList<>();
for(int i=0;i<a.length;i++) {
if(a[a.length-1-i]==i+1)q.add(new pair(i+1,map.get(i+1l)+1));
}
wr.println(q.size()+1);
while(!q.isEmpty()) {
wr.println(q.peek().l+" "+q.poll().c);
}
wr.println(s.length()+" "+1);
wr.close();
}
static int[] zAlgo(char[] s)
{
int n = s.length;
int[] z = new int[n];
for(int i = 1, l = 0, r = 0; i < n; ++i)
{
if(i <= r)
z[i] = Math.min(r - i + 1, z[i - l]);
while(i + z[i] < n && s[z[i]] == s[i + z[i]])
++z[i];
if(i + z[i] - 1 > r)
r = i + z[l = i] - 1;
}
return z;
}
}
class pair{
int l;long c;
pair(int l,long c){
this.l=l;
this.c=c;
}
}
class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(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
{
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if(x.charAt(0) == '-')
{
neg = true;
start++;
}
for(int i = start; i < x.length(); i++)
if(x.charAt(i) == '.')
{
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
}
else
{
sb.append(x.charAt(i));
if(dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg?-1:1);
}
public boolean ready() throws IOException {return br.ready();}
}
| Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1 ≤ |s| ≤ 105) — string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | 97bb5e55e48e4f3a0b09cf3f197780f5 | train_000.jsonl | 1400167800 | You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.StringTokenizer;
import java.util.TreeMap;
public class COVID {
static ArrayList<Integer>[] adjList;
static int mod;
static int INF=(int)1e6;
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter pw= new PrintWriter(System.out);
char[] s=sc.next().toCharArray();
int[] pi=new int[s.length];
for(int i=1,j=0;i<s.length;i++) {
while(j>0&&s[i]!=s[j])
j=pi[j-1];
if(s[i]==s[j])j++;
pi[i]=j;
}
int[] ans=new int[s.length];
for(int a:pi)
ans[a]++;
for(int i=s.length-1;i>0;i--)
ans[pi[i-1]]+=ans[i];
ArrayList<Integer> l=new ArrayList<>();
int j=pi[s.length-1];
while(j>0) {
l.add(j);
j=pi[j-1];
}
Collections.sort(l);
pw.println(l.size()+1);
for(int a:l) {
pw.println(a+" "+(ans[a]+1));
}
if(s.length!=0)
pw.println(s.length+" "+1);
pw.close();
}
static long gcd(long a, long b) {
return (b==0)?a:gcd(b,a%b);
}
static long lcm(long a, long b) {
return a/gcd(a,b)*b;
}
public static int log(int n , int base) {
int ans=0;
while(n+1>base) {
ans++;
n/=base;
}
return ans;
}
static int pow(int b,long e) {
int ans=1;
while(e>0) {
if((e&1)==1)
ans=(int)((ans*1l*b));
e>>=1;{
}
b=(int)((b*1l*b));
}
return ans;
}
static long powmod(long b,long e, int mod) {
long ans=1;
b%=mod;
while(e>0) {
if((e&1)==1)
ans=(int)((ans*1l*b)%mod);
e>>=1;
b=(int)((b*1l*b)%mod);
}
return ans;
}
public static long add(long a, long b) {
return (a+b)%mod;
}
public static long mul(long a, long b) {
return ((a%mod)*(b%mod))%mod;
}
static public class SegmentTree {
int N;
int[] array,sTree,lazy;
// boolean[] marked; // if marked[i]=true this means that sTree[i] is the same value for all of it's children
public SegmentTree(int[] arr) {//note arr must be 1 based arr
array=arr;
N=arr.length-1;// arr must be power of 2 and 1 based array
sTree=new int[N<<1]; // no of nodes is 2N-1 but we add 1 to be 1 index
lazy=new int[N<<1];
// marked=new boolean[N<<1];
// build(1,1,N);
}
public void build(int v,int b ,int e) {//o(N)
if(b==e) {
sTree[v]=array[b];
}else {
int mid =(b+e)>>1;
build((v<<1),b,mid);
build((v<<1)|1,mid+1,e);
sTree[v]=sTree[v<<1]+sTree[(v<<1)|1];
}
}
public int query(int i, int j) {//O(2log(n))
return query(1, 1,N,i,j);
}
public int query(int node , int b ,int e , int i , int j) {
if(b>j||e<i)return 0;
if(b>=i&&e<=j)return sTree[node];
int mid =(b+e)>>1;
propagate(node, b, mid, e);// we propagate the delayed updated because we add left & right child
int leftChild =query(node<<1, b,mid,i,j);
int rightChild =query((node<<1)|1, mid+1,e,i,j);
return leftChild+rightChild;
}
public void set_point(int idx,int val) {
idx+=N-1;
sTree[idx]=val;
while(idx>1) {
idx>>=1;
sTree[idx]=sTree[idx<<1]+sTree[idx<<1|1];
}
}
public void update_point(int idx , int val) {
idx+=N-1;
sTree[idx]+=val;
while(idx>1) {
idx>>=1;//divide by 2 to get the parent
sTree[idx]=sTree[(idx<<1)]+sTree[(idx<<1)|1];
}
}
public void update_range(int i , int j , int val) {
update_range(1,1, N, i,j,val);
}
public void update_range(int node,int b,int e ,int i , int j , int val) {
if(e<i||b>j)return;
if(b>=i&&e<=j) {
sTree[node]+=(e-b+1)*val;
lazy[node]+=val;
}else {
int mid =(b+e)>>1;
propagate(node, b , mid , e);//we make propagate because after these call we make sTree[node]=sTree[node<<1]+sTree[node<<1 |1];
// so it must be the correct value
update_range(node<<1, b, mid, i, j, val);
update_range(node<<1|1, mid+1, e, i, j, val);
sTree[node]=sTree[node<<1]+sTree[node<<1 |1];
}
}
public void propagate(int node , int b ,int mid , int e) { //O(1)
lazy[node<<1]+=lazy[node];
lazy[node<<1|1]+=lazy[node];
sTree[node<<1]+=(mid-b+1)*lazy[node];
sTree[node<<1|1]+=(e-mid)*lazy[node];
lazy[node]=0;
}
}
static class Pair implements Comparable<Pair>{
int x;int y;
public Pair(int a,int b) {
this.x=a;y=b;
}
public int compareTo(Pair o) {
return (x==o.x)?((y>o.y)?1:(y==o.y)?0:-1):((x>o.x)?1:-1);
// return y-o.y;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Pair other = (Pair) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(String s) throws FileNotFoundException{ br = new BufferedReader(new FileReader(s));}
public long[] nextLongArr(int n) throws IOException {
long[] arr=new long[n];
for(int i=0;i<n;i++)
arr[i]=nextLong();
return arr;
}
public int[] nextIntArr(int n) throws IOException {
int[] arr=new int[n];
for(int i=0;i<n;i++)
arr[i]=nextInt();
return arr;
}
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 {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++) {
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
if (sb.length() == 18) {
res += Long.parseLong(sb.toString()) / f;
sb = new StringBuilder("0");
}
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public boolean ready() throws IOException {
return br.ready();
}
}
public static void shuffle(int[] a) {
int n = a.length;
for (int i = 0; i < n; i++) {
int r = i + (int) (Math.random() * (n - i));
int tmp = a[i];
a[i] = a[r];
a[r] = tmp;
}
}
} | Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1 ≤ |s| ≤ 105) — string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | 6b0622710df261fe49e5afa2b3163cca | train_000.jsonl | 1400167800 | You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
import java.awt.image.AreaAveragingScaleFilter;
import static java.lang.Math.*;
import java.lang.*;
public class Main {
static FastScanner in;
static PrintWriter out;
public static void main(String[] args) throws FileNotFoundException {
runIO(0);
Task solver = new Task();
solver.solve(1, in, out);
out.close();
}
public static void runIO(int R) throws FileNotFoundException{
if (R==1){
in = new FastScanner(new File("input.txt"));
out = new PrintWriter(new File("output.txt"));
} else
{
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
}
}
}
class Task {
final int N = 1000010;
int n;
char s[] = new char[N];
int z[] = new int[N];
Set<Integer> M = new TreeSet<Integer>();
long sum[] = new long[N];
void inc(Map<Integer, Integer> m, int pos, int x){
int val = x;
if (m.containsKey(pos)) val+=m.get(pos);
m.remove(pos);
m.put(pos, val);
}
public void solve(int testNumber, FastScanner in, PrintWriter out) {
String ss = in.next();
n = ss.length();
for (int i=0; i<n; i++) s[i]=ss.charAt(i);
Map<Integer, Integer> MP = new TreeMap<>();
for (int i=1, l=0, r=0; i<n; i++){
if (i<=r) z[i] = Math.min(r-i+1, z[i-l]);
while (i+z[i]<n && s[z[i]]==s[i+z[i]]) ++z[i];
if (i+z[i]-1>r) {
l = i;
r = i+z[i]-1;
}
if (i+z[i]==n) M.add(z[i]);
sum[z[i]]++;
}
for (int i=n-1; i>=0; i--) sum[i]+=sum[i+1];
out.println(M.size()+1);
for (int x : M) out.println(x + " " + (sum[x]+1));
out.println(n + " 1\n");
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f));
}
String next() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
boolean hasMoreTokens() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return false;
st = new StringTokenizer(s);
}
return true;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
} | Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1 ≤ |s| ≤ 105) — string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | 42722d078002caf8445d3bd0b65aec63 | train_000.jsonl | 1400167800 | You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
import java.awt.image.AreaAveragingScaleFilter;
import static java.lang.Math.*;
import java.lang.*;
public class Main {
static FastScanner in;
static PrintWriter out;
public static void main(String[] args) throws FileNotFoundException {
runIO(0);
Task solver = new Task();
solver.solve(1, in, out);
out.close();
}
public static void runIO(int R) throws FileNotFoundException{
if (R==1){
in = new FastScanner(new File("input.txt"));
out = new PrintWriter(new File("output.txt"));
} else
{
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
}
}
}
class Task {
final int N = 300010;
int n;
char s[] = new char[N];
int z[] = new int[N];
Set<Integer> M = new TreeSet<Integer>();
long sum[] = new long[N];
public void solve(int testNumber, FastScanner in, PrintWriter out) {
String ss = in.next();
n = ss.length();
for (int i=0; i<n; i++) s[i]=ss.charAt(i);
for (int i=1, l=0, r=0; i<n; i++){
if (i<=r) z[i] = Math.min(r-i+1, z[i-l]);
while (i+z[i]<n && s[z[i]]==s[i+z[i]]) ++z[i];
if (i+z[i]-1>r) {
l = i;
r = i+z[i]-1;
}
if (i+z[i]==n) M.add(z[i]);
sum[z[i]]++;
}
for (int i=n-1; i>=0; i--) sum[i]+=sum[i+1];
out.println(M.size()+1);
for (int x : M) out.println(x + " " + (sum[x]+1));
out.println(n + " 1\n");
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f));
}
String next() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
boolean hasMoreTokens() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return false;
st = new StringTokenizer(s);
}
return true;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
} | Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1 ≤ |s| ≤ 105) — string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | 6b1aca60180365391394ed293436c13d | train_000.jsonl | 1400167800 | You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskE solver = new TaskE();
solver.solve(1, in, out);
out.close();
}
static class TaskE {
public void solve(int testNumber, InputReader in, PrintWriter out) {
String s=in.next();
int l=s.length();
int z[]=new int[l];z[0]=l;
int L=0,R=0;
for(int i=1;i<l;i++){
if(R<i){
L=R=i;
while(R<l&&s.charAt(R)==s.charAt(R-L))R++;
z[i]=R-L;R--;
}else{
if(z[i-L]+i-1<R)z[i]=z[i-L];
else{
L=i;
while(R<l&&s.charAt(R)==s.charAt(R-L))R++;
z[i]=R-L;R--;
}
}
}
int f[]=new int[l+1];ArrayList<Integer> al=new ArrayList<>();
for(int i=l-1;i>=0;i--){
if(z[i]+i-1==l-1)al.add(z[i]);f[z[i]]++;
}
for(int i=l-1;i>=1;i--)f[i]+=f[i+1];
out.println(al.size());
for(int i=0;i<al.size();i++)out.println(al.get(i)+" "+f[al.get(i)]);
}
}
static class InputReader {
BufferedReader br;
StringTokenizer st;
public InputReader(InputStream stream) {
br = new BufferedReader(new InputStreamReader(stream));
st = null;
}
String next() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
boolean hasMoreTokens() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return false;
st = new StringTokenizer(s);
}
return true;
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
}
| Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1 ≤ |s| ≤ 105) — string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | c3d4dbd5b65015bcddf0037fb3565fae | train_000.jsonl | 1400167800 | You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | //package String;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Scanner;
public class prefixAndSuffix {
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
String text = in.next();
in.close();
int size = text.length();
int[] lps = new int[size];
computeLPSArray(text,size,lps);
int num = 1;
int prefix = lps[size-1];
int[] count = KMPSearch(lps);
ArrayDeque<Integer> queue = new ArrayDeque<Integer>();
queue.add(size);
while(prefix != 0)
{
queue.addFirst(prefix);
prefix = lps[prefix - 1];
num++;
}
System.out.println(num);
while(!queue.isEmpty())
{
int fix = queue.removeFirst();
System.out.println(fix + " " + count[fix-1]);
}
}
static int[] KMPSearch(int[] lps)
{
int[] count = new int[lps.length];
Arrays.fill(count, 1);
for(int i = lps.length - 1; i > 0; i--)
{
if(lps[i] > 0)
{
count[lps[i] - 1] += count[i];
}
}
return count;
}
static void computeLPSArray(String pat, int M, int lps[])
{
int len = 0;
int i = 1;
lps[0] = 0;
while (i < M)
{
if (pat.charAt(i) == pat.charAt(len))
{
len++;
lps[i] = len;
i++;
}
else
{
if (len != 0)
{
len = lps[len-1];
}
else
{
lps[i] = len;
i++;
}
}
}
}
}
| Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1 ≤ |s| ≤ 105) — string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | 2dcb8347a2e08d40e4dd36b16f54b77e | train_000.jsonl | 1400167800 | You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | //package String;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Scanner;
public class prefixAndSuffix {
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
String text = in.next();
in.close();
int size = text.length();
int[] lps = new int[size];
computeLPSArray(text,size,lps);
int num = 1;
int prefix = lps[size-1];
int[] count = KMPSearch(lps);
ArrayDeque<Integer> queue = new ArrayDeque<Integer>();
queue.add(size);
while(prefix != 0)
{
queue.addFirst(prefix);
prefix = lps[prefix - 1];
num++;
}
System.out.println(num);
while(!queue.isEmpty())
{
int fix = queue.removeFirst();
System.out.println(fix + " " + count[fix-1]);
}
}
static int[] KMPSearch(int[] lps)
{
int[] count = new int[lps.length];
Arrays.fill(count, 1);
for(int i = lps.length - 1; i > 0; i--)
{
if(lps[i] > 0)
{
count[lps[i] - 1] += count[i];
}
}
return count;
}
static void computeLPSArray(String pat, int M, int lps[])
{
// length of the previous longest prefix suffix
int len = 0;
int i = 1;
lps[0] = 0; // lps[0] is always 0
// the loop calculates lps[i] for i = 1 to M-1
while (i < M)
{
if (pat.charAt(i) == pat.charAt(len))
{
len++;
lps[i] = len; // store the length of prefix and suffix
i++;
}
else // (pat[i] != pat[len])
{
// This is tricky. Consider the example.
// AAACAAAA and i = 7. The idea is similar
// to search step.
if (len != 0)
{
len = lps[len-1];//len is the number of prefix, not index, index is len - 1.
// Also, note that we do not increment
// i here
}
else // if (len == 0)
{
lps[i] = len;
i++;
}
}
}
}
}
| Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1 ≤ |s| ≤ 105) — string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | 2b0e58c3cb3f6e4d01ad22091e4ad533 | train_000.jsonl | 1400167800 | You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class B {
public static void main(String[] args) throws NumberFormatException, IOException {
Scanner sc = new Scanner();
PrintWriter out = new PrintWriter(System.out);
String s = sc.next();
int n = s.length();
StringBuilder s_stringb = new StringBuilder(s);
s_stringb.append("#").append(s);
char [] c = s_stringb.toString().toCharArray();
int [] z_values = zAlgo(c);
int [] occ = new int[n+1];
for (int i = n+1; i < z_values.length; ++i) {
++occ[z_values[i]];
}
for (int i = occ.length-2; i >= 0; --i) {
occ[i] += occ[i+1];
}
int cnt = 0;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; ++i) {
int corresponding_suffix = 2*n-i;
if(z_values[corresponding_suffix] == i+1){
++cnt;
sb.append(i+1).append(" ").append(occ[i+1]).append("\n");
}
}
out.println(cnt);
out.println(sb);
out.close();
}
static int[] zAlgo(char[] s)
{
int n = s.length;
int[] z = new int[n];
for(int i = 1, l = 0, r = 0; i < n; ++i)
{
if(i <= r)
z[i] = Math.min(r - i + 1, z[i - l]);
while(i + z[i] < n && s[z[i]] == s[i + z[i]])
++z[i];
if(i + z[i] - 1 > r)
r = i + z[l = i] - 1;
}
return z;
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
public int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(next());
}
}
}
| Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1 ≤ |s| ≤ 105) — string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | 23d1f545bca5699fdfd0c93fc993eda0 | train_000.jsonl | 1400167800 | You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.OutputStream;
import java.util.Vector;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Stack;
import java.io.InputStream;
import java.io.BufferedOutputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Aeroui
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Kattio in = new Kattio(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
boolean pal = true;
public void solve(int testNumber, Kattio in, PrintWriter out) {
char[] arr = in.next().toCharArray();
int[] pref = prefix(arr);
int[] tmp = new int[arr.length + 1];
for (int i = 0; i < arr.length; ++i)
++tmp[pref[i]];
for (int i = arr.length - 1; i > 0; --i)
tmp[pref[i - 1]] += tmp[i];
Stack<Pair> ans = new Stack<>();
int cur = pref[arr.length - 1];
while (cur > 0) {
if (tmp[cur] != 0)
ans.push(new Pair(cur, tmp[cur]));
cur = pref[cur - 1];
}
out.println(ans.size() + 1);
while (!ans.isEmpty())
out.println(ans.pop());
out.println(arr.length + " " + 1);
}
private int[] prefix(char[] arr) {
int[] pre = new int[arr.length];
int b = 0;
pre[0] = 0;
pal = arr[0] == arr[arr.length - 1];
for (int i = 1; i < arr.length; ++i) {
if (arr[i] != arr[arr.length - i - 1])
pal = false;
while (b > 0 && arr[b] != arr[i]) {
b = pre[b - 1];
}
if (arr[b] == arr[i])
++b;
pre[i] = b;
}
return pre;
}
private class Pair {
int f;
int s;
public Pair(int f, int s) {
this.f = f;
this.s = s + 1;
}
public String toString() {
return f + " " + s;
}
}
}
static class Kattio extends PrintWriter {
private BufferedReader r;
private String line;
private StringTokenizer st;
private String token;
public Kattio(InputStream i) {
super(new BufferedOutputStream(System.out));
r = new BufferedReader(new InputStreamReader(i));
}
public Kattio(InputStream i, OutputStream o) {
super(new BufferedOutputStream(o));
r = new BufferedReader(new InputStreamReader(i));
}
public String next() {
return nextToken();
}
private String peekToken() {
if (token == null)
try {
while (st == null || !st.hasMoreTokens()) {
line = r.readLine();
if (line == null) return null;
st = new StringTokenizer(line);
}
token = st.nextToken();
} catch (IOException e) {
}
return token;
}
private String nextToken() {
String ans = peekToken();
token = null;
return ans;
}
}
}
| Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1 ≤ |s| ≤ 105) — string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | a770fc517bc7a3d5269a4d5f5717d45a | train_000.jsonl | 1400167800 | You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.OutputStream;
import java.util.Arrays;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.io.BufferedOutputStream;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Aeroui
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Kattio in = new Kattio(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
public void solve(int testNumber, Kattio in, PrintWriter out) {
char[] arr = in.next().toCharArray();
int[] z = z_function(arr);
ArrayList<Integer> ans = new ArrayList<>();
for (int i = z.length - 1; i > 0; --i) {
if (i + z[i] == arr.length && z[i] > 0) {
ans.add(z[i]);
}
}
Arrays.sort(z);
out.println(ans.size() + 1);
for (int zz : ans) {
int cnt = lowerBound(z, z.length, zz);
out.println(zz + " " + (1 + (z.length - cnt)));
}
out.println(arr.length + " 1");
}
public static int lowerBound(int[] array, int length, int value) {
int low = 0;
int high = length;
while (low < high) {
final int mid = (low + high) / 2;
if (value <= array[mid]) {
high = mid;
} else {
low = mid + 1;
}
}
return low;
}
public int[] z_function(char[] arr) {
int n = arr.length;
int[] z = new int[n];
for (int i = 1, l = 0, r = 0; i < n; ++i) {
if (i <= r)
z[i] = Math.min(z[i - l], r - i + 1);
while (i + z[i] < n && arr[z[i]] == arr[i + z[i]]) {
++z[i];
}
if (i + z[i] - 1 > r) {
l = i;
r = i + z[i] - 1;
}
}
return z;
}
}
static class Kattio extends PrintWriter {
private BufferedReader r;
private String line;
private StringTokenizer st;
private String token;
public Kattio(InputStream i) {
super(new BufferedOutputStream(System.out));
r = new BufferedReader(new InputStreamReader(i));
}
public Kattio(InputStream i, OutputStream o) {
super(new BufferedOutputStream(o));
r = new BufferedReader(new InputStreamReader(i));
}
public String next() {
return nextToken();
}
private String peekToken() {
if (token == null)
try {
while (st == null || !st.hasMoreTokens()) {
line = r.readLine();
if (line == null) return null;
st = new StringTokenizer(line);
}
token = st.nextToken();
} catch (IOException e) {
}
return token;
}
private String nextToken() {
String ans = peekToken();
token = null;
return ans;
}
}
}
| Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1 ≤ |s| ≤ 105) — string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | ce1e75d7ac97cb5777c40139c45c956f | train_000.jsonl | 1400167800 | You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.TreeSet;
public class _432D {
public static void main(String[] args) throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
int n = s.length();
int[] f = new int[n + 1];
int[] h = new int[n];
int[] ch = new int[n];
f[0] = f[1] = 0;
TreeSet<Integer> set = new TreeSet<Integer>();
for (int i = 2; i <= n; i++) {
int p = f[i - 1];
while (true) {
if (s.charAt(p) == s.charAt(i - 1)) {
f[i] = p + 1;
break;
}
if (p == 0) {
f[i] = 0;
break;
}
p = f[p];
}
if (f[i] != 0) {
h[f[i]]++;
ch[f[i]]++;
set.add(f[i]);
}
}
Iterator<Integer> tsi = set.descendingIterator();
boolean[] isc = new boolean[n];
while (tsi.hasNext()) {
int tse = tsi.next();
if (!isc[tse]) {
int pp = tse;
isc[pp] = true;
ch[pp] = h[pp];
int cp = f[tse];
int cs = h[pp];
while (cp > 0) {
ch[cp] += cs;
if (!isc[cp]) {
cs += h[cp];
isc[cp] = true;
}
pp = cp;
cp = f[pp];
}
}
}
int p = f[n];
ArrayList<Integer> a1 = new ArrayList<Integer>();
ArrayList<Integer> a2 = new ArrayList<Integer>();
a1.add(n);
a2.add(1);
while (p > 0) {
a1.add(p);
a2.add(ch[p] + 1);
p = f[p];
}
System.out.println(a1.size());
for (int i = a1.size() - 1; i >= 0; i--) {
System.out.println(a1.get(i) + " " + a2.get(i));
}
}
} | Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1 ≤ |s| ≤ 105) — string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | ee2843abb90cba75c336b77b0ec5ad90 | train_000.jsonl | 1400167800 | You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes |
import java.io.*;
import java.util.*;
import java.math.*;
import static java.lang.Math.*;
import static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
import static java.lang.Double.parseDouble;
import static java.lang.String.*;
public class Main {
static List<Integer> [] g;
static List<pair> sol;
static int [] num;
static boolean [] ok;
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//(new FileReader("input.in"));
StringBuilder out = new StringBuilder();
StringTokenizer tk;
String s = in.readLine();
int n = s.length();
g = new List[n+1];
sol = new ArrayList<>();
num = new int[n+1];
int [] p = new int[n];
int [] freq = new int[n+1];
ok = new boolean[n+1];
for(int i=1,k=0; i<n; i++) {
while(k>0 && s.charAt(k)!=s.charAt(i))
k = p[k-1];
if(s.charAt(k)==s.charAt(i))
p[i] = ++k;
else p[i] = k;
}
for(int i=0; i<n; i++)
freq[p[i]]++;
for(int i=0; i<=n; i++) g[i] = new ArrayList<>();
for(int i=1; i<=n; i++) {
g[i].add(p[i-1]);
g[p[i-1]].add(i);
num[i] = freq[i];
}
for(int i=n; i>=1; i--)
num[p[i-1]] += num[i];
DFS(0,-1);
for(int i=1; i<n; i++)
if(ok[i])
sol.add(new pair(i,num[i]+1));
sol.add(new pair(n,1));
Collections.sort(sol);
out.append(sol.size()).append("\n");
for(pair pp : sol)
out.append(pp.a).append(" ").append(pp.b).append("\n");
System.out.print(out);
}
static boolean DFS(int u,int p) {
if(u==g.length-1)
return true;
boolean f = false;
for(int v : g[u]) {
if(v != p) {
f = f || DFS(v,u);
// num[u] += num[v];
}
}
return ok[u] = f;
}
}
class pair implements Comparable<pair> {
int a,b;
public pair(int a,int b) {
this.a = a;
this.b = b;
}
@Override
public int compareTo(pair p) {
return a-p.a;
}
}
| Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1 ≤ |s| ≤ 105) — string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | 39b18c17d86a7466da0aab5978824b36 | train_000.jsonl | 1400167800 | You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class Main
{
public static void main(String[] args) {
new Thread(null, new Runnable() {
public void run() {
solve();
}
}, "1", 1 << 26).start();
}
static void solve () {
FastReader fr =new FastReader(); PrintWriter op =new PrintWriter(System.out);
String s =fr.next() ;
int len =s.length() ,prefix[] =new int[len+1] ,i ,j ;
char str[] =new char[len+1] ;
for (i =0 ; i<len ; ++i) str[i+1] =s.charAt(i) ;
for (i =2 ; i<=len ; ++i) {
j =i-1 ;
while (j!=0 && str[i]!=str[prefix[j]+1])
j =prefix[j] ;
prefix[i] =(j==0 ? 0:prefix[j]+1) ;
}
int subCt[] =new int[len] ;
for (i =len-1 ; i>1 ; --i) {
subCt[prefix[i]] += subCt[i] ;
++subCt[prefix[i]] ;
}
ArrayList<node> ans =new ArrayList<>() ;
ans.add(new node(len , 1)) ;
i =len ;
while (prefix[i]!=0) {
ans.add(new node(prefix[i] , 2+subCt[prefix[i]])) ;
i =prefix[i] ;
}
op.println(ans.size()) ;
for (i =ans.size()-1 ; i>-1 ; --i)
op.println(ans.get(i).length +" "+ ans.get(i).count) ;
op.flush(); op.close();
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br =new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st==null || (!st.hasMoreElements()))
{
try
{
st =new StringTokenizer(br.readLine());
}
catch(IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
String nextLine() {
String str ="";
try
{
str =br.readLine();
}
catch(IOException e)
{
e.printStackTrace();
}
return str;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next()) ;
}
}
}
class node {
int length ,count ;
node (int l , int c) {
length =l ;
count =c ;
}
} | Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1 ≤ |s| ≤ 105) — string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | fc2e53436f93abe5e193fa0240c88034 | train_000.jsonl | 1400167800 | You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
char[] s = sc.next().toCharArray();
int n = s.length;
int[] cnt = new int[n + 1];
ArrayList<Integer> ans = new ArrayList<>();
int[] z = zAlgorithm(s);
z[0] = n;
for (int i = 0; i < n; i++) {
if (z[i] + i == n) ans.add(z[i]);
cnt[z[i]]++;
}
for (int i = n - 1; i > 0; i--)
cnt[i] += cnt[i + 1];
Collections.sort(ans);
out.println(ans.size());
for (int x : ans)
out.println(x + " " + cnt[x]);
out.flush();
out.close();
}
static int[] zAlgorithm(char[] s) {
int n = s.length;
int[] z = new int[n];
for (int i = 1, l = 0, r = 0; i < n; ++i) {
if (i <= r)
z[i] = Math.min(r - i + 1, z[i - l]);
while (i + z[i] < n && s[z[i]] == s[i + z[i]])
++z[i];
if (i + z[i] - 1 > r)
r = i + z[l = i] - 1;
}
return z;
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public Scanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public Long nextLong() throws IOException {
return Long.parseLong(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
}
| Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1 ≤ |s| ≤ 105) — string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | a3144bd1ab3ac7e35f5116b19e7a6e45 | train_000.jsonl | 1400167800 | You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
/**
* @author Don Li
*/
public class PrefixesSuffixes {
void solve() {
char[] s = in.nextToken().toCharArray();
int n = s.length;
int[] z = new int[n];
z[0] = n;
for (int i = 1, l = 0, r = 0; i < n; i++) {
if (i <= r) z[i] = Math.min(r - i + 1, z[i - l]);
while (i + z[i] < n && s[i + z[i]] == s[z[i]]) z[i]++;
if (i + z[i] - 1 > r) {
l = i;
r = i + z[i] - 1;
}
}
int[] cnt = new int[n + 1];
for (int i = 0; i < n; i++) cnt[z[i]]++;
for (int i = n - 1; i >= 0; i--) cnt[i] += cnt[i + 1];
List<int[]> res = new ArrayList<>();
for (int i = 1; i <= n; i++) {
if (z[n - i] == i) {
res.add(new int[]{i, cnt[i]});
}
}
out.println(res.size());
for (int i = 0; i < res.size(); i++) {
int[] p = res.get(i);
out.printf("%d %d%n", p[0], p[1]);
}
}
public static void main(String[] args) {
in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(System.out);
new PrefixesSuffixes().solve();
out.close();
}
static FastScanner in;
static PrintWriter out;
static class FastScanner {
BufferedReader in;
StringTokenizer st;
public FastScanner(BufferedReader in) {
this.in = in;
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(in.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public long nextLong() {
return Long.parseLong(nextToken());
}
public double nextDouble() {
return Double.parseDouble(nextToken());
}
}
}
| Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1 ≤ |s| ≤ 105) — string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | c06c42b4bacea134b642b09165d5d56b | train_000.jsonl | 1400167800 | You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | /*
*
* @author Mukesh Singh
*
*/
import java.io.*;
import java.util.*;
import java.text.DecimalFormat;
@SuppressWarnings("unchecked")
public class AB {
//solve test cases
void solve() throws Exception {
String st = in.nextToken();
int n = st.length();
int[]Z = new int[n];
compute(Z,st);
//for(int a : Z) System.out.print(a+" ");
//System.out.println();
int[]over = new int[n+2];
int[]cnt = new int[n+1];
for(int i = 0 ; i < n ; ++i ) ++cnt[Z[i]] ;
//for(int a : cnt) System.out.print(a+" ");
//System.out.println();
for(int i = n ; i >= 0 ; -- i)
over[i]= over[i+1] + cnt[i] ;
//for(int a : over) System.out.print(a+" ");
//System.out.println();
LinkedList<Node> ls = new LinkedList<>();
for(int i = 0 ; i < n ; ++i ){
int t =n-i ;
if(Z[i] < t ) continue ;
ls.addLast(new Node(t , over[t]));
}
Collections.sort(ls, new Comparator<Node>(){
public int compare(Node n1 , Node n2){
return n1.len - n2.len ;
}
});
System.out.println(ls.size());
for(Node nd : ls) System.out.println(nd.len+" "+nd.total);
}
void compute(int[]Z , String text){
int n = text.length();
Z[0] = n ;
int L = 0 ; int R = 0 ;
for(int i = 1 ; i < n ; ++i ){
if(i > R){
L = i ; R = i ;
while( R < n && text.charAt(R) == text.charAt(R-i)) ++R ;
Z[i] = R-L ; --R ;
}else{
int k = i-L ;
if(Z[k] < R-i+1 ){
Z[i] = Z[k] ;
}else{
L = i ;
while( R < n && text.charAt(R) == text.charAt(R-i)) ++R ;
Z[i] = R-L ; --R ;
}
}
}
}
class Node{
int len ; int total ;
Node(int a , int b){
len = a ;
total = b ;
}
}
//@ main function
public static void main(String[] args) throws Exception {
new AB();
}
InputReader in;
PrintStream out ;
DecimalFormat df ;
AB() {
try {
File defaultInput = new File("file.in");
if (defaultInput.exists())
in = new InputReader("file.in");
else
in = new InputReader();
defaultInput = new File("file.out");
if (defaultInput.exists())
out = new PrintStream(new FileOutputStream("file.out"));
else
out = new PrintStream(System.out);
df = new DecimalFormat("######0.00");
solve();
out.close();
}
catch (Exception e) {
e.printStackTrace();
System.exit(261);
}
}
class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
InputReader() {
reader = new BufferedReader(new InputStreamReader(System.in));
}
InputReader(String fileName) throws FileNotFoundException {
reader = new BufferedReader(new FileReader(new File(fileName)));
}
String readLine() throws IOException {
return reader.readLine();
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens())
tokenizer = new StringTokenizer(readLine());
return tokenizer.nextToken();
}
boolean hasMoreTokens() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
String s = readLine();
if (s == null)
return false;
tokenizer = new StringTokenizer(s);
}
return true;
}
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 | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1 ≤ |s| ≤ 105) — string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | 875a7796b9d055bea373b6ae8683b16a | train_000.jsonl | 1400167800 | You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | /*
*
* @author Mukesh Singh
*
*/
import java.io.*;
import java.util.*;
import java.text.DecimalFormat;
@SuppressWarnings("unchecked")
public class AB {
//solve test cases
void solve() throws Exception {
String st = in.nextToken();
int n = st.length();
int[]Z = new int[n];
Z[0] = n ;
for(int i = 1 , l = 0 , r = 0 ; i < n ; ++i ){
if(r < i ){
l = i ; r = i ;
while(r < n && st.charAt(r-i) == st.charAt(r)) ++r ;
Z[i] = r-l; --r ;
}else{
int k = i - l ;
if(Z[k] < r-i+1 ) Z[i] = Z[k] ;
else{
l = i ;
while(r < n && st.charAt(r-i) == st.charAt(r)) ++r ;
Z[i] = r-l; --r ;
}
}
}
//for(int a : Z) System.out.print(a+" ");
//System.out.println();
int[]count = new int[n+1];
for(int a : Z) ++count[a] ;
int[]total = new int[n+2];
for(int i = n ; i >= 0 ; -- i ){
total[i] = total[i+1] + count[i] ;
}
//for(int a : total) System.out.print(a+" ");
//System.out.println();
LinkedList<Node> ls = new LinkedList<>();
for(int i = 0; i < n ; ++i ){
if(Z[i] < n-i ) continue ;
ls.add(new Node(n-i , total[n-i]));
}
Collections.sort(ls,new Comparator<Node>(){
public int compare(Node n1 , Node n2){
return n1.len-n2.len;
}
});
System.out.println(ls.size());
for(Node nd : ls) System.out.println(nd.len+" "+nd.total);
}
class Node{
int len ; int total ;
Node(int a , int b){
len = a ;
total = b ;
}
}
//@ main function
public static void main(String[] args) throws Exception {
new AB();
}
InputReader in;
PrintStream out ;
DecimalFormat df ;
AB() {
try {
File defaultInput = new File("file.in");
if (defaultInput.exists())
in = new InputReader("file.in");
else
in = new InputReader();
defaultInput = new File("file.out");
if (defaultInput.exists())
out = new PrintStream(new FileOutputStream("file.out"));
else
out = new PrintStream(System.out);
df = new DecimalFormat("######0.00");
solve();
out.close();
}
catch (Exception e) {
e.printStackTrace();
System.exit(261);
}
}
class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
InputReader() {
reader = new BufferedReader(new InputStreamReader(System.in));
}
InputReader(String fileName) throws FileNotFoundException {
reader = new BufferedReader(new FileReader(new File(fileName)));
}
String readLine() throws IOException {
return reader.readLine();
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens())
tokenizer = new StringTokenizer(readLine());
return tokenizer.nextToken();
}
boolean hasMoreTokens() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
String s = readLine();
if (s == null)
return false;
tokenizer = new StringTokenizer(s);
}
return true;
}
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 | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1 ≤ |s| ≤ 105) — string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | 17578d9b8c4dee8bfd5d9549226ef1e9 | train_000.jsonl | 1400167800 | You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Scanner;
public class password {
static class SuffixAutomaton {
int last;
ArrayList<Integer> link, length;
ArrayList<int []> edges;
HashSet<Integer> terminals;
public SuffixAutomaton(String s) {
link = new ArrayList<>();
length = new ArrayList<>();
edges = new ArrayList<>();
terminals = new HashSet<>();
edges.add(new int[26]);
link.add(-1);
length.add(0);
for(int i = 0; i < s.length(); i++) {
edges.add(new int[26]);
length.add(i+1);
link.add(0);
int r = edges.size() - 1;
int p = last;
while(p >= 0 && edges.get(p)[s.charAt(i) - 'a'] == 0) {
edges.get(p)[s.charAt(i) - 'a'] = r;
p = link.get(p);
}
if(p != -1) {
int q = edges.get(p)[s.charAt(i)-'a'];
if(length.get(p) + 1 == length.get(q)) {
link.set(r, q);
} else {
edges.add(edges.get(q).clone());
length.add(length.get(p) + 1);
link.add(link.get(q));
int qq = edges.size()-1;
link.set(q,qq);
link.set(r, qq);
while(p >= 0 && edges.get(p)[s.charAt(i)-'a'] == q) {
edges.get(p)[s.charAt(i)-'a']=qq;
p = link.get(p);
}
}
}
last = r;
}
int p = last;
while(p > 0) {
terminals.add(p);
p = link.get(p);
}
}
boolean contains(String s) {
int cur = 0;
for(char c : s.toCharArray()) {
if(edges.get(cur)[c-'a'] == 0)
return false;
cur = edges.get(cur)[c-'a'];
}
return true;
}
public long SubstringCount[];
// First initialize the above array to size edges.size then run function bellow on 0
// Note that this takes the empty string into account so you may need to subtract 1
long getSubstringCount(int u) {
if(SubstringCount[u] != 0)
return SubstringCount[u];
long ans = 1;
for(int i = 0; i < 26; i++) {
if(edges.get(u)[i] != 0) {
ans += getSubstringCount(edges.get(u)[i]);
}
}
return SubstringCount[u] = ans;
}
public long terminalPaths[];
long getTerminalPaths(int u) {
if(terminalPaths[u] != 0)
return terminalPaths[u];
long ans = 0;
if(terminals.contains(u))
ans = 1;
for(int i = 0; i < 26; i++) {
if(edges.get(u)[i] != 0)
ans += getTerminalPaths(edges.get(u)[i]);
}
return terminalPaths[u] = ans;
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String s = in.next().toLowerCase();
SuffixAutomaton sa = new SuffixAutomaton(s);
sa.terminalPaths = new long[sa.edges.size()];
sa.getTerminalPaths(0);
int cur = 0;
int best = -1;
int cnt = 0;
int ans1[] = new int[s.length()];
long ans2[] = new long[s.length()];
for(int i = 0; i < s.length(); i++) {
cur = sa.edges.get(cur)[s.charAt(i)-'a'];
if(sa.terminals.contains(cur)) {
ans1[cnt] = (i+1);
ans2[cnt++] = sa.terminalPaths[cur];
}
}
PrintWriter out = new PrintWriter(System.out);
out.println(cnt);
for(int i = 0; i < cnt; i++) {
out.println(ans1[i] + " " + ans2[i]);
}
out.close();
}
}
| Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1 ≤ |s| ≤ 105) — string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | 41edad6fe06e9826f4592883309dd643 | train_000.jsonl | 1400167800 | You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | // practice with rainboy
import java.io.*;
import java.util.*;
public class CF432D extends PrintWriter {
CF432D() { super(System.out); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF432D o = new CF432D(); o.main(); o.flush();
}
void main() {
byte[] cc = sc.next().getBytes();
int n = cc.length;
int[] zz = new int[n];
int[] cnt = new int[n + 1];
zz[0] = n;
cnt[n] = 1;
for (int i = 1, l = 0, r = 0; i < n; i++) {
if (zz[i - l] < r - i)
zz[i] = zz[i - l];
else {
l = i;
if (r < l)
r = l;
while (r < n && cc[r] == cc[r - l])
r++;
zz[i] = r - l;
}
cnt[zz[i]]++;
}
int k = 0;
for (int i = n - 1; i >= 0; i--) {
cnt[i] += cnt[i + 1];
if (zz[i] == n - i)
k++;
}
println(k);
for (int i = n - 1; i >= 0; i--)
if (zz[i] == n - i)
println(zz[i] + " " + cnt[zz[i]]);
}
}
| Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1 ≤ |s| ≤ 105) — string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | 712fcb05b26a6cd0fc7851be26b6edd0 | train_000.jsonl | 1400167800 | You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
// http://codeforces.com/problemset/problem/432/D
public class PrefixesAndSuffixes {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = scanner.next();
if (s.length() == 0) {
System.out.println(0);
return;
}
int[] lengthCounts = new int[s.length()+1];
int[] zArr = zArr(s, lengthCounts);
int[] cumulativeLengths = new int[s.length()+1];
cumulativeLengths[cumulativeLengths.length-1] = lengthCounts[lengthCounts.length-1];
for (int i=cumulativeLengths.length-2; i>=0; i--) {
cumulativeLengths[i] = lengthCounts[i] + cumulativeLengths[i+1];
}
List<int[]> prefixCounts = new LinkedList<>();
for (int i=s.length()-1; i>=0; i--) {
if (zArr[i] + i == s.length()) {
prefixCounts.add(new int[]{zArr[i], cumulativeLengths[zArr[i]]});
}
}
StringBuilder sb = new StringBuilder();
sb.append(prefixCounts.size());
sb.append('\n');
for (int[] prefixCount : prefixCounts) {
sb.append(prefixCount[0]).append(' ').append(prefixCount[1]).append('\n');
}
System.out.println(sb.toString());
}
private static int[] zArr(String s, int[] lengthCounts) {
int[] zArr = new int[s.length()];
zArr[0] = s.length();
lengthCounts[s.length()] = 1;
int l = 0;
int r = 0;
for (int i=1; i<s.length(); i++) {
if (i <= r) {
zArr[i] = Math.min(r - i + 1, zArr[i-l]);
}
int start = i+zArr[i];
while (start < s.length() && s.charAt(start) == s.charAt(start-i)) start++;
zArr[i] = start - i;
if (i+zArr[i]-1 > r) {
r = zArr[i] + i - 1;
l = i;
}
lengthCounts[zArr[i]]++;
}
return zArr;
}
}
| Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1 ≤ |s| ≤ 105) — string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | 6f3dfd11677e7dd2ac8c1c225051d453 | train_000.jsonl | 1400167800 | You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.FilterInputStream;
import java.io.BufferedInputStream;
import java.io.InputStream;
/**
* @author khokharnikunj8
*/
public class Main {
public static void main(String[] args) {
new Thread(null, new Runnable() {
public void run() {
new Main().solve();
}
}, "1", 1 << 26).start();
}
void solve() {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
ScanReader in = new ScanReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
DPrefixesAndSuffixes solver = new DPrefixesAndSuffixes();
solver.solve(1, in, out);
out.close();
}
static class DPrefixesAndSuffixes {
public int[] findIt(char[] ar) {
int[] z = new int[ar.length];
z[0] = ar.length;
int l = 0;
int r = 0;
for (int i = 1; i < ar.length; i++) {
if (r < i) {
l = i;
r = i;
while (r < ar.length && ar[r - l] == ar[r]) r++;
z[i] = r - l;
r--;
} else {
int k = i - l;
if (z[k] < r - i + 1) {
z[i] = z[k];
} else {
l = i;
while (r < ar.length && ar[r - l] == ar[r]) r++;
z[i] = r - l;
r--;
}
}
}
return z;
}
public void solve(int testNumber, ScanReader in, PrintWriter out) {
char[] ar = in.scanString().toCharArray();
int[] z = findIt(ar);
int[] z1 = Arrays.copyOf(z, z.length);
Arrays.sort(z1);
int[][] ans = new int[ar.length][2];
int tl = 0;
for (int i = 0; i < ar.length; i++) {
if (z[ar.length - 1 - i] != i + 1) continue;
ans[tl][0] = i + 1;
ans[tl][1] = z.length - CodeHash.lbound(z1, 0, z.length - 1, i + 1);
tl++;
}
out.println(tl);
for (int i = 0; i < tl; i++) out.println(ans[i][0] + " " + ans[i][1]);
}
}
static class CodeHash {
public static int lbound(int array[], int l, int h, long x) {
int index = h + 1;
while (l <= h) {
int mid = (l + h) / 2;
if (array[mid] >= x) {
index = mid;
h = mid - 1;
} else l = mid + 1;
}
return index;
}
}
static class ScanReader {
private byte[] buf = new byte[4 * 1024];
private int index;
private BufferedInputStream in;
private int total;
public ScanReader(InputStream inputStream) {
in = new BufferedInputStream(inputStream);
}
private int scan() {
if (index >= total) {
index = 0;
try {
total = in.read(buf);
} catch (Exception e) {
e.printStackTrace();
}
if (total <= 0) return -1;
}
return buf[index++];
}
public String scanString() {
int c = scan();
if (c == -1) return null;
while (isWhiteSpace(c)) c = scan();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = scan();
} while (!isWhiteSpace(c));
return res.toString();
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true;
else return false;
}
}
}
| Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1 ≤ |s| ≤ 105) — string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | c8461d3f0b2a5da99ef8c2a0daf8c008 | train_000.jsonl | 1400167800 | You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | import java.io.*;
import java.util.*;
public class Solution
{
public static void main(String ag[])
{
Scanner sc=new Scanner(System.in);
int i,j,k;
String str=sc.next();
int N=str.length();
int Z[]=new int[N];
int left=0;
int right=0;
for(i=1;i<N;i++)
{
if(i>right)
{
left=right=i;
while(right<N&&str.charAt(right)==str.charAt(right-left))
right++;
Z[i]=right-left;
right--;
}
else
{
int K1=i-left;
if(Z[K1]<right-i+1)
Z[i]=Z[K1];
else
{
left=i;
while(right<N&&str.charAt(right)==str.charAt(right-left))
right++;
Z[i]=right-left;
right--;
}
}
}
int freq[]=new int[N+1];
int cnt=0;
for(i=0;i<N;i++)
{
freq[Z[i]]++;
}
for(i=N-1;i>=0;i--)
{
freq[i]+=freq[i+1];
if(Z[i]==N-i)
cnt++;
}
cnt++;
System.out.println(cnt);
for(i=N-1;i>=0;i--)
{
if(Z[i]==N-i)
System.out.println(Z[i]+" "+(freq[Z[i]]+1));
}
System.out.println(N+" "+1);
}
} | Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1 ≤ |s| ≤ 105) — string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | f3e65507aeac770f8470e1021aaf41d5 | train_000.jsonl | 1400167800 | You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main{
static int[] prefix_function(char[]s) {
int n = (int)s.length;
int[]pi=new int[n];
for (int i = 1; i < n; i++) {
int j = pi[i-1];
while (j > 0 && s[i] != s[j])
j = pi[j-1];
if (s[i] == s[j])
j++;
pi[i] = j;
}
return pi;
}
static int[][] suffixArrayRecursive(char[]in) {//has a terminating character (e.g. '$')
int n=in.length;//O(n*log(n))
int k=0;
while((1<<k)<n) {
k++;
}
return solve(k, in, n);
}
static int[][] solve(int k,char[]in,int n){
if(k==0) {
int[][]a=new int[n][2];
for(int i=0;i<in.length;i++) {
a[i]=new int[] {in[i]-'a',i};
}
Arrays.sort(a,(x,y)->x[0]-y[0]);
int[]p=new int[n],c=new int[n];
for(int i=0;i<n;i++) {
p[i]=a[i][1];
}
c[a[0][1]]=0;
for(int i=1;i<n;i++) {
c[a[i][1]]=(a[i][0]==a[i-1][0])?c[a[i-1][1]]:(c[a[i-1][1]]+1);
}
return new int[][] {p,c};
}
k--;
int[][]prev=solve(k, in, n);
int[]p=prev[0],c=prev[1];
for(int i=0;i<n;i++) {
p[i]=(p[i]+n-(1<<k))%n;
}
p=countingSort(p, c);
int[]newc=new int[n];
newc[p[0]]=0;
for(int i=1;i<n;i++) {
int[]curPair=new int[] {c[p[i]],c[(p[i]+(1<<k))%n]};
int[]prevPair=new int[] {c[p[i-1]],c[(p[i-1]+(1<<k))%n]};
newc[p[i]]=(compare(prevPair, curPair)==0)?newc[p[i-1]]:(newc[p[i-1]]+1);
}
return new int[][] {p,newc};
}
static int compare(int[]x,int[]y) {
return x[0]!=y[0]?x[0]-y[0]:x[1]-y[1];
}
static int[] countingSort(int[]p,int[]c) {
int n=p.length;
int[]cnt=new int[n];
for(int i:p) {
cnt[c[i]]++;
}
int[]pointers=new int[n];
pointers[0]=0;
for(int i=1;i<n;i++) {
pointers[i]=pointers[i-1]+cnt[i-1];
}
int[]newP=new int[n];
for(int i:p) {
newP[pointers[c[i]]++]=i;
}
return newP;
}
static int[] suffixArrayIterative(char[]in) {//has a terminating character (e.g. '$')
int n=in.length;//O(n*log(n))
int[][]a=new int[n][2];
for(int i=0;i<in.length;i++) {
a[i]=new int[] {in[i]-'a',i};
}
Arrays.sort(a,(x,y)->x[0]-y[0]);
int[]p=new int[n],c=new int[n];
for(int i=0;i<n;i++) {
p[i]=a[i][1];
}
c[a[0][1]]=0;
for(int i=1;i<n;i++) {
c[a[i][1]]=(a[i][0]==a[i-1][0])?c[a[i-1][1]]:c[a[i-1][1]]+1;
}
int k=0;
while((1<<k)<n) {
for(int i=0;i<n;i++) {
p[i]=(p[i]+n-(1<<k))%n;
}
p=countingSort(p, c);
int[]newc=new int[n];
newc[p[0]]=0;
for(int i=1;i<n;i++) {
int[]curPair=new int[] {c[p[i]],c[(p[i]+(1<<k))%n]};
int[]prevPair=new int[] {c[p[i-1]],c[(p[i-1]+(1<<k))%n]};
newc[p[i]]=(compare(prevPair, curPair)==0)?newc[p[i-1]]:(newc[p[i-1]]+1);
}
c=newc;
k++;
}
return p;
}
static int[]log,min[],arr;
static int inf=(int)1e9;
static int query(int l,int r) {
int len = r - l + 1;
int lg = log[len];
int u = min[l][lg];
int v = min[r - (1 << lg) + 1][lg];
int bestIdx = arr[u] < arr[v] ? u : v;
return arr[bestIdx];
}
static void preProcess(int n) {
log = new int[n+1];
for (int i = 2; i <= n; i++)
log[i] = log[i / 2] + 1;
min=new int[n][22];
for(int i=0;i<n;i++) {
min[i][0]=i;
}
for(int i=1,len=2;len<=n;i++,len<<=1) {
for(int j=0;j<n;j++) {
int u=min[j][i-1],v=j+(len>>1)>=n?inf:min[j+(len>>1)][i-1];
if(v==inf) {
min[j][i]=u;
}
else
min[j][i]=(arr[u]<arr[v]?u:v);
}
}
}
static int[] lcp(String s) {
char[]in=(s+'$').toCharArray();
int[][]arrs=suffixArrayRecursive(in);
int[]p=arrs[0],c=arrs[1];
int len=in.length;
int[]lcp=new int[len];
int k=0;
for(int i=0;i<len-1;i++) {
int cur=i,prev=p[c[i]-1];
while(in[cur+k]==in[prev+k])k++;
lcp[c[i]]=k;
k=Math.max(k-1, 0);
}
arr=lcp.clone();
preProcess(len);
return c;
}
//count of occurrences of the suffix starting at i
static int solve(int i,int[]c,int n,int len) {
int rank=c[i];
int lo=rank+1,hi=n-1;
int last=rank;
while(lo<=hi) {
int mid=(lo+hi)>>1;
if(query(rank+1, mid)==len) {
last=mid;
lo=mid+1;
}
else {
hi=mid-1;
}
}
return last-rank+1;
}
static void main() throws Exception{
String s=sc.nextLine();
char[]in=s.toCharArray();
int[]pi=prefix_function(in);
LinkedList<int[]>ans=new LinkedList<int[]>();
ans.add(new int[] {in.length,1});
int[]c=lcp(s);
int pref=pi[in.length-1];
while(pref>0) {
int eqSuff=in.length-pref;
ans.addFirst(new int[] {pref,solve(eqSuff, c, in.length+1, pref)});
pref=pi[pref-1];
}
pw.println(ans.size());
while(!ans.isEmpty()) {
int[]cur=ans.poll();
pw.println(cur[0]+" "+cur[1]);
}
}
public static void main(String[] args) throws Exception{
sc=new MScanner(System.in);
pw = new PrintWriter(System.out);
int tc=1;
// tc=sc.nextInt();
while(tc-->0)
main();
pw.flush();
}
static PrintWriter pw;
static MScanner sc;
static class MScanner {
StringTokenizer st;
BufferedReader br;
public MScanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public MScanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int[] intArr(int n) throws IOException {
int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt();
return in;
}
public long[] longArr(int n) throws IOException {
long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong();
return in;
}
public int[] intSortedArr(int n) throws IOException {
int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt();
shuffle(in);
Arrays.sort(in);
return in;
}
public long[] longSortedArr(int n) throws IOException {
long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong();
shuffle(in);
Arrays.sort(in);
return in;
}
public Integer[] IntegerArr(int n) throws IOException {
Integer[]in=new Integer[n];for(int i=0;i<n;i++)in[i]=nextInt();
return in;
}
public Long[] LongArr(int n) throws IOException {
Long[]in=new Long[n];for(int i=0;i<n;i++)in[i]=nextLong();
return in;
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
static void shuffle(int[]in) {
for(int i=0;i<in.length;i++) {
int idx=(int)(Math.random()*in.length);
int tmp=in[i];
in[i]=in[idx];
in[idx]=tmp;
}
}
static void shuffle(long[]in) {
for(int i=0;i<in.length;i++) {
int idx=(int)(Math.random()*in.length);
long tmp=in[i];
in[i]=in[idx];
in[idx]=tmp;
}
}
} | Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1 ≤ |s| ≤ 105) — string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | 9c0c68db03faf44cd31f4a4e3c9766a2 | train_000.jsonl | 1400167800 | You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main{
static int[] prefix_function(char[]s) {
int n = (int)s.length;
int[]pi=new int[n];
for (int i = 1; i < n; i++) {
int j = pi[i-1];
while (j > 0 && s[i] != s[j])
j = pi[j-1];
if (s[i] == s[j])
j++;
pi[i] = j;
}
return pi;
}
static int compare(int[]x,int[]y) {
return x[0]!=y[0]?x[0]-y[0]:x[1]-y[1];
}
static int[] countingSort(int[]p,int[]c) {
int n=p.length;
int[]cnt=new int[n];
for(int i:p) {
cnt[c[i]]++;
}
int[]pointers=new int[n];
pointers[0]=0;
for(int i=1;i<n;i++) {
pointers[i]=pointers[i-1]+cnt[i-1];
}
int[]newP=new int[n];
for(int i:p) {
newP[pointers[c[i]]++]=i;
}
return newP;
}
static int[][] suffixArrayIterative(char[]in) {//has a terminating character (e.g. '$')
int n=in.length;//O(n*log(n))
int[][]a=new int[n][2];
for(int i=0;i<in.length;i++) {
a[i]=new int[] {in[i]-'a',i};
}
Arrays.sort(a,(x,y)->x[0]-y[0]);
int[]p=new int[n],c=new int[n];
for(int i=0;i<n;i++) {
p[i]=a[i][1];
}
c[a[0][1]]=0;
for(int i=1;i<n;i++) {
c[a[i][1]]=(a[i][0]==a[i-1][0])?c[a[i-1][1]]:c[a[i-1][1]]+1;
}
int k=0;
while((1<<k)<n) {
for(int i=0;i<n;i++) {
p[i]=(p[i]+n-(1<<k))%n;
}
p=countingSort(p, c);
int[]newc=new int[n];
newc[p[0]]=0;
for(int i=1;i<n;i++) {
int[]curPair=new int[] {c[p[i]],c[(p[i]+(1<<k))%n]};
int[]prevPair=new int[] {c[p[i-1]],c[(p[i-1]+(1<<k))%n]};
newc[p[i]]=(compare(prevPair, curPair)==0)?newc[p[i-1]]:(newc[p[i-1]]+1);
}
c=newc;
k++;
}
return new int[][] {p,c};
}
static int[]log,min[],arr;
static int inf=(int)1e9;
static int query(int l,int r) {
int len = r - l + 1;
int lg = log[len];
int u = min[l][lg];
int v = min[r - (1 << lg) + 1][lg];
int bestIdx = arr[u] < arr[v] ? u : v;
return arr[bestIdx];
}
static void preProcess(int n) {
log = new int[n+1];
for (int i = 2; i <= n; i++)
log[i] = log[i / 2] + 1;
min=new int[n][22];
for(int i=0;i<n;i++) {
min[i][0]=i;
}
for(int i=1,len=2;len<=n;i++,len<<=1) {
for(int j=0;j<n;j++) {
int u=min[j][i-1],v=j+(len>>1)>=n?inf:min[j+(len>>1)][i-1];
if(v==inf) {
min[j][i]=u;
}
else
min[j][i]=(arr[u]<arr[v]?u:v);
}
}
}
static int[] lcp(String s) {
char[]in=(s+'$').toCharArray();
int[][]arrs=suffixArrayIterative(in);
int[]p=arrs[0],c=arrs[1];
int len=in.length;
int[]lcp=new int[len];
int k=0;
for(int i=0;i<len-1;i++) {
int cur=i,prev=p[c[i]-1];
while(in[cur+k]==in[prev+k])k++;
lcp[c[i]]=k;
k=Math.max(k-1, 0);
}
arr=lcp.clone();
preProcess(len);
return c;
}
//count of occurrences of the suffix starting at i
static int solve(int i,int[]c,int n,int len) {
int rank=c[i];
int lo=rank+1,hi=n-1;
int last=rank;
while(lo<=hi) {
int mid=(lo+hi)>>1;
if(query(rank+1, mid)==len) {
last=mid;
lo=mid+1;
}
else {
hi=mid-1;
}
}
return last-rank+1;
}
static void main() throws Exception{
String s=sc.nextLine();
char[]in=s.toCharArray();
int[]pi=prefix_function(in);
LinkedList<int[]>ans=new LinkedList<int[]>();
ans.add(new int[] {in.length,1});
int[]c=lcp(s);
int pref=pi[in.length-1];
while(pref>0) {
int eqSuff=in.length-pref;
ans.addFirst(new int[] {pref,solve(eqSuff, c, in.length+1, pref)});
pref=pi[pref-1];
}
pw.println(ans.size());
while(!ans.isEmpty()) {
int[]cur=ans.poll();
pw.println(cur[0]+" "+cur[1]);
}
}
public static void main(String[] args) throws Exception{
sc=new MScanner(System.in);
pw = new PrintWriter(System.out);
int tc=1;
// tc=sc.nextInt();
while(tc-->0)
main();
pw.flush();
}
static PrintWriter pw;
static MScanner sc;
static class MScanner {
StringTokenizer st;
BufferedReader br;
public MScanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public MScanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int[] intArr(int n) throws IOException {
int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt();
return in;
}
public long[] longArr(int n) throws IOException {
long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong();
return in;
}
public int[] intSortedArr(int n) throws IOException {
int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt();
shuffle(in);
Arrays.sort(in);
return in;
}
public long[] longSortedArr(int n) throws IOException {
long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong();
shuffle(in);
Arrays.sort(in);
return in;
}
public Integer[] IntegerArr(int n) throws IOException {
Integer[]in=new Integer[n];for(int i=0;i<n;i++)in[i]=nextInt();
return in;
}
public Long[] LongArr(int n) throws IOException {
Long[]in=new Long[n];for(int i=0;i<n;i++)in[i]=nextLong();
return in;
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
static void shuffle(int[]in) {
for(int i=0;i<in.length;i++) {
int idx=(int)(Math.random()*in.length);
int tmp=in[i];
in[i]=in[idx];
in[idx]=tmp;
}
}
static void shuffle(long[]in) {
for(int i=0;i<in.length;i++) {
int idx=(int)(Math.random()*in.length);
long tmp=in[i];
in[i]=in[idx];
in[idx]=tmp;
}
}
} | Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1 ≤ |s| ≤ 105) — string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | 0bd440957205cb9a43a3c216559de0ef | train_000.jsonl | 1400167800 | You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | // http://codeforces.com/problemset/problem/432/D
/*
Input
ABACABA
Output
3
1 4
3 2
7 1
Input
AAA
Output
3
1 3
2 2
3 1
7:35
*/
import java.util.*;
import java.io.*;
public class PrefixesSuffixes {
FastScanner in;
PrintWriter out;
class SuffixTree {
final int m = 27;
int[] str;
int[] parent;
int[][] link;
int[] suf;
int withoutSuf;
int cur;
int left;
int n;
int all;
boolean created;
int free;
int[] start;
int[] depth;
int[] sufNum;
int newNode(int p, int d, int s) {
parent[free] = p;
depth[free] = d;
start[free] = s;
return free++;
}
SuffixTree(int[] a) {
str = a;
n = str.length;
all = 2 * n + 1;
parent = new int[all];
depth = new int[all];
Arrays.fill(parent, -1);
suf = new int[all];
Arrays.fill(suf, -1);
sufNum = new int[all];
Arrays.fill(sufNum, -1);
link = new int[m][all];
for (int[] d : link)
Arrays.fill(d, -1);
start = new int[all];
cur = newNode(0, 0, 0);
suf[cur] = 0;
left = 0;
for (int right = 0; right < n; right++) {
while (left <= right) {
go(right);
if (withoutSuf >= 0) {
suf[withoutSuf] = parent[cur];
withoutSuf = -1;
}
if (!created)
break;
created = false;
cur = parent[cur];
if (suf[cur] == -1) {
withoutSuf = cur;
cur = parent[cur];
}
cur = suf[cur];
++left;
while (depth[cur] >= 0 && depth[cur] < right - left) {
go(left + depth[cur]);
}
}
}
}
void go(int right) {
if (depth[cur] != right - left) {
int len = right - left - depth[parent[cur]];
if (str[start[cur] + len] != str[right]) {
int u = newNode(parent[cur], right - left, start[cur]);
link[str[start[cur] + len]][u] = cur;
link[str[start[cur]]][parent[cur]] = u;
start[cur] += len;
parent[cur] = u;
cur = u;
created = true;
}
}
if (depth[cur] == right - left) {
if (link[str[right]][cur] == -1) {
int u = link[str[right]][cur] = newNode(cur, -1, right);
created = true;
sufNum[u] = left;
}
cur = link[str[right]][cur];
}
}
boolean[] suffix;
int[] count;
void dfs(int v) {
if (link[0][v] != -1)
suffix[v] = true;
boolean leaf = true;
for (int i = 0; i < m; i++) {
if (link[i][v] != -1) {
dfs(link[i][v]);
leaf = false;
count[v] += count[link[i][v]];
}
}
if (leaf)
count[v] = 1;
}
void calcSufAndCount() {
suffix = new boolean[all];
count = new int[all];
dfs(0);
}
void solve() {
int v = -1;
for (int i = 0; i < all; i++)
if (sufNum[i] == 0)
v = i;
class Item implements Comparable<Item> {
int len, count;
public Item(int len, int count) {
super();
this.len = len;
this.count = count;
}
@Override
public int compareTo(Item o) {
return Integer.compare(len, o.len);
}
}
ArrayList<Item> ans = new ArrayList<>();
while (v != 0) {
if (depth[v] != -1 && suffix[v]) {
ans.add(new Item(depth[v], count[v]));
}
v = parent[v];
}
ans.add(new Item(n - 1, 1));
Collections.sort(ans);
out.println(ans.size());
for (Item it : ans) {
out.println(it.len + " " + it.count);
}
}
}
public void solve() throws IOException {
char[] c = in.next().toCharArray();
int[] a = new int[c.length + 1];
for (int i = 0; i < c.length; i++)
a[i] = c[i] - 'A' + 1;
SuffixTree sufTree = new SuffixTree(a);
sufTree.calcSufAndCount();
sufTree.solve();
}
public void run() {
try {
in = new FastScanner();
out = new PrintWriter(System.out);
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
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());
}
}
public static void main(String[] arg) {
new PrefixesSuffixes().run();
}
} | Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1 ≤ |s| ≤ 105) — string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | f3302d1e44617ebc5e3e566c57e968ef | train_000.jsonl | 1400167800 | You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | // http://codeforces.com/problemset/problem/432/D
/*
Input
ABACABA
Output
3
1 4
3 2
7 1
Input
AAA
Output
3
1 3
2 2
3 1
7:35
*/
import java.util.*;
import java.io.*;
public class PrefixesSuffixes {
FastScanner in;
PrintWriter out;
class SuffixTree {
int all, n;
int[] parent;
int[] suf;
int[] depth;
int[] sufNum;
int[][] link;
int withoutSuf;
int cur;
int left;
int free;
int[] str;
boolean created;
int m = 27;
int[] start;
public SuffixTree(int[] a) {
str = a;
n = str.length;
all = 2 * n + 1;
parent = new int[all];
start = new int[all];
suf = new int[all];
depth = new int[all];
sufNum = new int[all];
link = new int[m][all];
for (int[] d : link)
Arrays.fill(d, -1);
Arrays.fill(suf, -1);
Arrays.fill(sufNum, -1);
Arrays.fill(parent, -1);
withoutSuf = -1;
cur = newNode(0, 0, 0);
suf[0] = 0;
left = 0;
for (int right = 0; right < n; right++) {
while (left <= right) {
go(right);
if (withoutSuf >= 0) {
suf[withoutSuf] = parent[cur];
withoutSuf = -1;
}
if (!created)
break;
created = false;
cur = parent[cur];
if (suf[cur] == -1) {
withoutSuf = cur;
cur = parent[cur];
}
cur = suf[cur];
++left;
while (depth[cur] >= 0 && depth[cur] < right - left) {
go(left + depth[cur]);
}
}
}
}
int newNode(int p, int d, int s) {
parent[free] = p;
depth[free] = d;
start[free] = s;
return free++;
}
void go(int right) {
if (depth[cur] != right - left) {
int len = right - left - depth[parent[cur]];
if (str[right] != str[start[cur] + len]) {
int u = newNode(parent[cur], right - left, start[cur]);
link[str[start[cur]]][parent[cur]] = u;
link[str[start[cur] + len]][u] = cur;
start[cur] += len;
parent[cur] = u;
cur = u;
created = true;
}
}
if (depth[cur] == right - left) {
if (link[str[right]][cur] == -1) {
int u = link[str[right]][cur] = newNode(cur, -1, right);
created = true;
sufNum[u] = left;
}
cur = link[str[right]][cur];
}
}
boolean[] suffix;
int[] count;
void dfs(int v) {
if (link[0][v] != -1)
suffix[v] = true;
boolean leaf = true;
for (int i = 0; i < m; i++) {
if (link[i][v] != -1) {
dfs(link[i][v]);
leaf = false;
count[v] += count[link[i][v]];
}
}
if (leaf)
count[v] = 1;
}
void calcSufAndCount() {
suffix = new boolean[all];
count = new int[all];
dfs(0);
}
void solve() {
int v = -1;
for (int i = 0; i < all; i++)
if (sufNum[i] == 0)
v = i;
class Item implements Comparable<Item> {
int len, count;
public Item(int len, int count) {
super();
this.len = len;
this.count = count;
}
@Override
public int compareTo(Item o) {
return Integer.compare(len, o.len);
}
}
ArrayList<Item> ans = new ArrayList<>();
while (v != 0) {
if (depth[v] != -1 && suffix[v]) {
ans.add(new Item(depth[v], count[v]));
}
v = parent[v];
}
ans.add(new Item(n - 1, 1));
Collections.sort(ans);
out.println(ans.size());
for (Item it : ans) {
out.println(it.len + " " + it.count);
}
}
}
public void solve() throws IOException {
char[] c = in.next().toCharArray();
int[] a = new int[c.length + 1];
for (int i = 0; i < c.length; i++)
a[i] = c[i] - 'A' + 1;
SuffixTree sufTree = new SuffixTree(a);
sufTree.calcSufAndCount();
sufTree.solve();
}
public void run() {
try {
in = new FastScanner();
out = new PrintWriter(System.out);
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
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());
}
}
public static void main(String[] arg) {
new PrefixesSuffixes().run();
}
} | Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1 ≤ |s| ≤ 105) — string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | 4267ea0dda0851b48859954c4dea5f44 | train_000.jsonl | 1400167800 | You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | import java.util.*;
import java.io.*;
public class PrefixesSuffixes {
FastScanner in;
PrintWriter out;
class SuffixTree {
final int m = 27;
int[] str;
int[] parent;
int[] suf;
int[] depth;
int[][] link;
int[] start;
int[] sufNum;
int withoutSuf = -1;
int cur = 0;
int cntNodes = 0;
int n;
int left;
int all;
boolean created;
SuffixTree(int[] c) {
str = c;
n = c.length;
all = 2 * n + 1;
parent = new int[all];
Arrays.fill(parent, -1);
suf = new int[all];
depth = new int[all];
link = new int[m][all];
for (int[] d : link)
Arrays.fill(d, -1);
suf = new int[all];
Arrays.fill(suf, -1);
start = new int[all];
sufNum = new int[all];
Arrays.fill(sufNum, -1);
cur = newNode(0, 0, 0);
suf[0] = 0;
left = 0;
for (int right = 0; right < n; right++) {
while (left <= right) {
go(right);
if (withoutSuf >= 0) {
suf[withoutSuf] = parent[cur];
withoutSuf = -1;
}
if (!created) {
break;
}
created = false;
cur = parent[cur];
if (suf[cur] == -1) {
withoutSuf = cur;
cur = parent[cur];
}
cur = suf[cur];
left++;
while (depth[cur] >= 0 && depth[cur] < right - left) {
go(left + depth[cur]);
}
}
}
}
int newNode(int p, int d, int s) {
parent[cntNodes] = p;
depth[cntNodes] = d;
start[cntNodes] = s;
return cntNodes++;
}
void go(int right) {
if (depth[cur] != right - left) {
int len = right - left - depth[parent[cur]];
if (str[start[cur] + len] != str[right]) {
int u = newNode(parent[cur], right - left, start[cur]);
link[str[start[cur] + len]][u] = cur;
link[str[start[cur]]][parent[cur]] = u;
start[cur] += len;
parent[cur] = u;
cur = u;
created = true;
}
}
if (depth[cur] == right - left) {
if (link[str[right]][cur] == -1) {
int u = link[str[right]][cur] = newNode(cur, -1, right);
assert sufNum[u] == -1;
sufNum[u] = left;
created = true;
}
cur = link[str[right]][cur];
}
}
boolean[] suffix;
int[] count;
void dfs(int v) {
if (link[0][v] != -1)
suffix[v] = true;
boolean leaf = true;
for (int i = 0; i < m; i++) {
if (link[i][v] != -1) {
dfs(link[i][v]);
leaf = false;
count[v] += count[link[i][v]];
}
}
if (leaf)
count[v] = 1;
}
void calcSufAndCount() {
suffix = new boolean[all];
count = new int[all];
dfs(0);
}
void solve() {
int v = -1;
for (int i = 0; i < all; i++)
if (sufNum[i] == 0)
v = i;
class Item implements Comparable<Item> {
int len, count;
public Item(int len, int count) {
super();
this.len = len;
this.count = count;
}
@Override
public int compareTo(Item o) {
return Integer.compare(len, o.len);
}
}
ArrayList<Item> ans = new ArrayList<>();
while (v != 0) {
if (depth[v] != -1 && suffix[v]) {
ans.add(new Item(depth[v], count[v]));
}
v = parent[v];
}
ans.add(new Item(n - 1, 1));
Collections.sort(ans);
out.println(ans.size());
for (Item it : ans) {
out.println(it.len + " " + it.count);
}
}
}
public void solve() throws IOException {
char[] c = in.next().toCharArray();
int[] a = new int[c.length + 1];
for (int i = 0; i < c.length; i++)
a[i] = c[i] - 'A' + 1;
SuffixTree sufTree = new SuffixTree(a);
sufTree.calcSufAndCount();
sufTree.solve();
}
public void run() {
try {
in = new FastScanner();
out = new PrintWriter(System.out);
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
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());
}
}
public static void main(String[] arg) {
new PrefixesSuffixes().run();
}
} | Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1 ≤ |s| ≤ 105) — string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | aee6b58c3800dc494aea6807b38c40dc | train_000.jsonl | 1400167800 | You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | // http://codeforces.com/problemset/problem/432/D
/*
Input
ABACABA
Output
3
1 4
3 2
7 1
Input
AAA
Output
3
1 3
2 2
3 1
7:35
*/
import java.util.*;
import java.io.*;
public class PrefixesSuffixes {
FastScanner in;
PrintWriter out;
class SuffixTree {
int m = 27;
int[] parent;
int[] depth;
int[] suf;
int[] start;
int[][] link;
int withoutSuf;
int cur;
int n;
int free;
boolean created;
int left;
int newNode(int p, int d, int s) {
parent[free] = p;
depth[free] = d;
start[free] = s;
return free++;
}
int[] str;
int all;
int[] sufNum;
SuffixTree(int[] a) {
str = a;
n = a.length;
all = 2 * n + 1;
parent = new int[all];
suf = new int[all];
depth = new int[all];
link = new int[m][all];
start = new int[all];
sufNum = new int[all];
withoutSuf = -1;
for (int[] d : link)
Arrays.fill(d, -1);
Arrays.fill(parent, -1);
Arrays.fill(suf, -1);
Arrays.fill(sufNum, -1);
cur = newNode(0, 0, 0);
left = 0;
suf[cur] = 0;
for (int right = 0; right < n; right++) {
while (left <= right) {
go(right);
if (withoutSuf >= 0) {
suf[withoutSuf] = parent[cur];
withoutSuf = -1;
}
if (!created)
break;
created = false;
cur = parent[cur];
if (suf[cur] == -1) {
withoutSuf = cur;
cur = parent[cur];
}
cur = suf[cur];
++left;
while (depth[cur] >= 0 && depth[cur] < right - left) {
go(left + depth[cur]);
}
}
}
}
void go(int right) {
if (depth[cur] != right - left) {
int len = right - left - depth[parent[cur]];
if (str[start[cur] + len] != str[right]) {
int u = newNode(parent[cur], right - left, start[cur]);
link[str[start[cur] + len]][u] = cur;
link[str[start[cur]]][parent[cur]] = u;
parent[cur] = u;
start[cur] += len;
cur = u;
created = true;
}
}
if (depth[cur] == right - left) {
if (link[str[right]][cur] == -1) {
int u = link[str[right]][cur] = newNode(cur, -1, right);
sufNum[u] = left;
created = true;
}
cur = link[str[right]][cur];
}
}
boolean[] suffix;
int[] count;
void dfs(int v) {
if (link[0][v] != -1)
suffix[v] = true;
boolean leaf = true;
for (int i = 0; i < m; i++) {
if (link[i][v] != -1) {
dfs(link[i][v]);
leaf = false;
count[v] += count[link[i][v]];
}
}
if (leaf)
count[v] = 1;
}
void calcSufAndCount() {
suffix = new boolean[all];
count = new int[all];
dfs(0);
}
void solve() {
int v = -1;
for (int i = 0; i < all; i++)
if (sufNum[i] == 0)
v = i;
class Item implements Comparable<Item> {
int len, count;
public Item(int len, int count) {
super();
this.len = len;
this.count = count;
}
@Override
public int compareTo(Item o) {
return Integer.compare(len, o.len);
}
}
ArrayList<Item> ans = new ArrayList<>();
while (v != 0) {
if (depth[v] != -1 && suffix[v]) {
ans.add(new Item(depth[v], count[v]));
}
v = parent[v];
}
ans.add(new Item(n - 1, 1));
Collections.sort(ans);
out.println(ans.size());
for (Item it : ans) {
out.println(it.len + " " + it.count);
}
}
}
public void solve() throws IOException {
char[] c = in.next().toCharArray();
int[] a = new int[c.length + 1];
for (int i = 0; i < c.length; i++)
a[i] = c[i] - 'A' + 1;
SuffixTree sufTree = new SuffixTree(a);
sufTree.calcSufAndCount();
sufTree.solve();
}
public void run() {
try {
in = new FastScanner();
out = new PrintWriter(System.out);
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
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());
}
}
public static void main(String[] arg) {
new PrefixesSuffixes().run();
}
} | Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1 ≤ |s| ≤ 105) — string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | 3a515c18c2fdc5d40ad9db27e2035787 | train_000.jsonl | 1400167800 | You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | // http://codeforces.com/problemset/problem/432/D
/*
Input
ABACABA
Output
3
1 4
3 2
7 1
Input
AAA
Output
3
1 3
2 2
3 1
*/
import java.util.*;
import java.io.*;
public class PrefixesSuffixes {
FastScanner in;
PrintWriter out;
class SuffixTree {
final int m = 27;
int[] str;
int[] parent;
int[] depth;
int[] suf;
int[] start;
int[][] link;
int[] sufNum;
int withoutSuf;
int cur;
int n;
int all;
int free;
int left;
boolean created;
SuffixTree(int[] a) {
str = a;
n = str.length;
all = 2 * n + 1;
parent = new int[all];
Arrays.fill(parent, -1);
suf = new int[all];
Arrays.fill(suf, -1);
start = new int[all];
sufNum = new int[all];
Arrays.fill(sufNum, -1);
link = new int[m][all];
for (int[] d : link)
Arrays.fill(d, -1);
depth = new int[all];
withoutSuf = -1;
cur = newNode(0, 0, 0);
suf[cur] = 0;
left = 0;
for (int right = 0; right < n; right++) {
while (left <= right) {
go(right);
if (withoutSuf >= 0) {
suf[withoutSuf] = parent[cur];
withoutSuf = -1;
}
if (!created)
break;
created = false;
cur = parent[cur];
if (suf[cur] == -1) {
withoutSuf = cur;
cur = parent[cur];
}
cur = suf[cur];
left++;
while (depth[cur] >= 0 && depth[cur] < right - left) {
go(left + depth[cur]);
}
}
}
}
void go(int right) {
if (depth[cur] != right - left) {
int len = right - left - depth[parent[cur]];
if (str[right] != str[start[cur] + len]) {
int u = newNode(parent[cur], right - left, start[cur]);
link[str[start[cur]]][parent[cur]] = u;
link[str[start[cur] + len]][u] = cur;
start[cur] += len;
parent[cur] = u;
cur = u;
created = true;
}
}
if (depth[cur] == right - left) {
if (link[str[right]][cur] == -1) {
int u = link[str[right]][cur] = newNode(cur, -1, right);
created = true;
sufNum[u] = left;
}
cur = link[str[right]][cur];
}
}
int newNode(int p, int d, int s) {
parent[free] = p;
depth[free] = d;
start[free] = s;
return free++;
}
boolean[] suffix;
int[] count;
void dfs(int v) {
if (link[0][v] != -1)
suffix[v] = true;
boolean leaf = true;
for (int i = 0; i < m; i++) {
if (link[i][v] != -1) {
dfs(link[i][v]);
leaf = false;
count[v] += count[link[i][v]];
}
}
if (leaf)
count[v] = 1;
}
void calcSufAndCount() {
suffix = new boolean[all];
count = new int[all];
dfs(0);
}
void solve() {
int v = -1;
for (int i = 0; i < all; i++)
if (sufNum[i] == 0)
v = i;
class Item implements Comparable<Item> {
int len, count;
public Item(int len, int count) {
super();
this.len = len;
this.count = count;
}
@Override
public int compareTo(Item o) {
return Integer.compare(len, o.len);
}
}
ArrayList<Item> ans = new ArrayList<>();
while (v != 0) {
if (depth[v] != -1 && suffix[v]) {
ans.add(new Item(depth[v], count[v]));
}
v = parent[v];
}
ans.add(new Item(n - 1, 1));
Collections.sort(ans);
out.println(ans.size());
for (Item it : ans) {
out.println(it.len + " " + it.count);
}
}
}
public void solve() throws IOException {
char[] c = in.next().toCharArray();
int[] a = new int[c.length + 1];
for (int i = 0; i < c.length; i++)
a[i] = c[i] - 'A' + 1;
SuffixTree sufTree = new SuffixTree(a);
sufTree.calcSufAndCount();
sufTree.solve();
}
public void run() {
try {
in = new FastScanner();
out = new PrintWriter(System.out);
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
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());
}
}
public static void main(String[] arg) {
new PrefixesSuffixes().run();
}
} | Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1 ≤ |s| ≤ 105) — string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | c251d4e3afae324a4b7fde28f3122b3e | train_000.jsonl | 1400167800 | You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.File;
import java.util.ArrayList;
import java.io.FilterInputStream;
import java.util.Collections;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Atharva Nagarkar
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
JoltyScanner in = new JoltyScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
ProblemDPrefixesAndSuffixes solver = new ProblemDPrefixesAndSuffixes();
solver.solve(1, in, out);
out.close();
}
static class ProblemDPrefixesAndSuffixes {
public void solve(int testNumber, JoltyScanner in, PrintWriter out) {
String s = in.next();
int n = s.length();
int[] z = strings.zValues(s);
INT_BIT bit = new INT_BIT(n + 1);
for (int i = 0; i < n; ++i) {
if (z[i] > 0) bit.add(z[i], 1);
}
ArrayList<Data> ans = new ArrayList<>();
for (int i = n - 1, len = 1; i >= 0; --i, ++len) {
if (z[i] == len) {
int curans = bit.sum(len, n + 1);
ans.add(new Data(len, curans));
}
}
Collections.sort(ans);
out.println(ans.size());
for (Data d : ans) out.println(d.len + " " + d.times);
}
class Data implements Comparable<Data> {
int len;
int times;
Data(int l, int t) {
len = l;
times = t;
}
public int compareTo(Data d) {
return len - d.len;
}
}
}
static class JoltyScanner {
public int BS = 1 << 16;
public char NC = (char) 0;
public byte[] buf = new byte[BS];
public int bId = 0;
public int size = 0;
public char c = NC;
public BufferedInputStream in;
public JoltyScanner(InputStream is) {
in = new BufferedInputStream(is, BS);
}
public JoltyScanner(String s) throws FileNotFoundException {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
}
public char nextChar() {
while (bId == size) {
try {
size = in.read(buf);
} catch (Exception e) {
return NC;
}
if (size == -1) return NC;
bId = 0;
}
return (char) buf[bId++];
}
public String next() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = nextChar();
while (c > 32) {
res.append(c);
c = nextChar();
}
return res.toString();
}
}
static class strings {
public static int[] zValues(String string) {
int n = string.length();
char[] s = string.toCharArray();
int[] z = new int[n];
z[0] = n;
int L = 0, R = 0;
int[] left = new int[n], right = new int[n];
for (int i = 1; i < n; ++i) {
if (i > R) {
L = R = i;
while (R < n && s[R - L] == s[R]) R++;
z[i] = R - L;
R--;
} else {
int k = i - L;
if (z[k] < R - i + 1) z[i] = z[k];
else {
L = i;
while (R < n && s[R - L] == s[R]) R++;
z[i] = R - L;
R--;
}
}
left[i] = L;
right[i] = R;
}
return z;
}
}
static class INT_BIT {
int[] tree;
int n;
public INT_BIT(int n) {
this.n = n;
tree = new int[n + 1];
}
public void add(int i, int val) {
while (i <= n) {
tree[i] += val;
i += i & -i;
}
}
public int sum(int to) {
int res = 0;
for (int i = to; i >= 1; i -= (i & -i)) {
res += tree[i];
}
return res;
}
public int sum(int from, int to) {
if (from > to) return 0;
return sum(to) - sum(from - 1);
}
}
}
| Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1 ≤ |s| ≤ 105) — string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | 80a94e338f5fd2aabbaf4885be866cda | train_000.jsonl | 1400167800 | You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class code5 {
InputStream is;
PrintWriter out;
static long mod=pow(10,9)+7;
int arr[];
void solve()
{
String s=ns();
int n=s.length();
int z[]=new int[n];
zalgo(z,s);
ArrayList<Integer> al=new ArrayList<Integer>();
ArrayList<Integer> suffix=new ArrayList<Integer>();
for(int i=0;i<n;i++)
{
if(z[i]!=0)
al.add(z[i]);
if(z[i]!=0&&z[i]==n-i)
suffix.add(z[i]);
}
al.add(n);
suffix.add(n);
Collections.sort(al);
Collections.sort(suffix);
out.println(suffix.size());
for(int i=0;i<suffix.size();i++)
{
out.println(suffix.get(i)+" "+(al.size()-bsupper(al,suffix.get(i))));
}
}
public static int bsupper(ArrayList <Integer>a,int item)
{
int low=0,high=a.size()-1,ans=-1;
while(low<=high)
{
int mid=low+(high-low)/2;
if(a.get(mid)>=item)
{
ans=mid;
high=mid-1;
}
else
low=mid+1;
}
return ans;
}
void zalgo(int z[],String s)
{
int l=0,r=0;
for(int i=1;i<s.length();i++)
{
if(i>r)
{
l=r=i;
while(r<s.length()&&s.charAt(r-l)==s.charAt(r))
r++;
z[i]=r-l;
r--;
}
else
{
if(z[i-l]+i-1<r)
z[i]=z[i-l];
else
{
l=i;
while(r<s.length()&&s.charAt(r-l)==s.charAt(r))
r++;
z[i]=r-l;
r--;
}
}
}
}
int count(String p,String s)
{
precompute(p);
int i=0,j=0,count=0;
while(i<s.length())
{
if(s.charAt(i)==p.charAt(j))
{
i++;
j++;
}
if(j==p.length())
{
count++;
j=arr[j-1];
}
else if(i<s.length()&&s.charAt(i)!=p.charAt(j))
{
if(j!=0)
j=arr[j-1];
else
i=i+1;
}
}
return count;
}
void precompute(String p)
{
arr=new int[p.length()];
arr[0]=0;
for(int i=1;i<p.length();i++)
{
int j=arr[i-1];
while(j>0&&p.charAt(j)!=p.charAt(i))
j=arr[j-1];
if(p.charAt(i)==p.charAt(j))
j++;
arr[i]=j;
}
}
public static int count(int x)
{
int num=0;
while(x!=0)
{
x=x&(x-1);
num++;
}
return num;
}
static long d, x, y;
void extendedEuclid(long A, long B) {
if(B == 0) {
d = A;
x = 1;
y = 0;
}
else {
extendedEuclid(B, A%B);
long temp = x;
x = y;
y = temp - (A/B)*y;
}
}
long modInverse(long A,long M) //A and M are coprime
{
extendedEuclid(A,M);
return (x%M+M)%M; //x may be negative
}
public static void mergeSort(int[] arr, int l ,int r){
if((r-l)>=1){
int mid = (l+r)/2;
mergeSort(arr,l,mid);
mergeSort(arr,mid+1,r);
merge(arr,l,r,mid);
}
}
public static void merge(int arr[], int l, int r, int mid){
int n1 = (mid-l+1), n2 = (r-mid);
int left[] = new int[n1];
int right[] = new int[n2];
for(int i =0 ;i<n1;i++) left[i] = arr[l+i];
for(int i =0 ;i<n2;i++) right[i] = arr[mid+1+i];
int i =0, j =0, k = l;
while(i<n1 && j<n2){
if(left[i]>right[j]){
arr[k++] = right[j++];
}
else{
arr[k++] = left[i++];
}
}
while(i<n1) arr[k++] = left[i++];
while(j<n2) arr[k++] = right[j++];
}
public static void mergeSort(long[] arr, int l ,int r){
if((r-l)>=1){
int mid = (l+r)/2;
mergeSort(arr,l,mid);
mergeSort(arr,mid+1,r);
merge(arr,l,r,mid);
}
}
public static void merge(long arr[], int l, int r, int mid){
int n1 = (mid-l+1), n2 = (r-mid);
long left[] = new long[n1];
long right[] = new long[n2];
for(int i =0 ;i<n1;i++) left[i] = arr[l+i];
for(int i =0 ;i<n2;i++) right[i] = arr[mid+1+i];
int i =0, j =0, k = l;
while(i<n1 && j<n2){
if(left[i]>right[j]){
arr[k++] = right[j++];
}
else{
arr[k++] = left[i++];
}
}
while(i<n1) arr[k++] = left[i++];
while(j<n2) arr[k++] = right[j++];
}
static class Pair implements Comparable<Pair>{
int x,y,k,i;
Pair (int x,int y,int k,int i){
this.x=x;
this.y=y;
this.k=k;
this.i=i;
}
public int compareTo(Pair o) {
return this.x-o.x;
}
public boolean equals(Object o) {
if (o instanceof Pair) {
Pair p = (Pair)o;
return p.x == x && p.y == y && p.k==k;
}
return false;
}
@Override
public String toString() {
return "("+x + " " + y +" "+k+" "+i+" )";
}
}
public static boolean isPal(String s){
for(int i=0, j=s.length()-1;i<=j;i++,j--){
if(s.charAt(i)!=s.charAt(j)) return false;
}
return true;
}
public static String rev(String s){
StringBuilder sb=new StringBuilder(s);
sb.reverse();
return sb.toString();
}
public static long gcd(long x,long y){
if(x%y==0)
return y;
else
return gcd(y,x%y);
}
public static int gcd(int x,int y){
if(y==0)
return x;
return gcd(y,x%y);
}
public static long gcdExtended(long a,long b,long[] x){
if(a==0){
x[0]=0;
x[1]=1;
return b;
}
long[] y=new long[2];
long gcd=gcdExtended(b%a, a, y);
x[0]=y[1]-(b/a)*y[0];
x[1]=y[0];
return gcd;
}
public static int abs(int a,int b){
return (int)Math.abs(a-b);
}
public static long abs(long a,long b){
return (long)Math.abs(a-b);
}
public static int max(int a,int b){
if(a>b)
return a;
else
return b;
}
public static int min(int a,int b){
if(a>b)
return b;
else
return a;
}
public static long max(long a,long b){
if(a>b)
return a;
else
return b;
}
public static long min(long a,long b){
if(a>b)
return b;
else
return a;
}
public static long pow(long n,long p,long m){
long result = 1;
if(p==0)
return 1;
if (p==1)
return n;
while(p!=0)
{
if(p%2==1)
result *= n;
if(result>=m)
result%=m;
p >>=1;
n*=n;
if(n>=m)
n%=m;
}
return result;
}
public static long pow(long n,long p){
long result = 1;
if(p==0)
return 1;
if (p==1)
return n;
while(p!=0)
{
if(p%2==1)
result *= n;
p >>=1;
n*=n;
}
return result;
}
public static void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
void run() throws Exception {
is = System.in;
out = new PrintWriter(System.out);
solve();
out.flush();
}
public static void main(String[] args) throws Exception {
new Thread(null, new Runnable() {
public void run() {
try {
new code5().run();
} catch (Exception e) {
e.printStackTrace();
}
}
}, "1", 1 << 26).start();
}
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte() {
if (lenbuf == -1)
throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0)
return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b));
return b;
}
private double nd() {
return Double.parseDouble(ns());
}
private char nc() {
return (char) skip();
}
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++)
map[i] = ns(m);
return map;
}
private int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = ni();
return a;
}
private int ni() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private long nl() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
} | Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1 ≤ |s| ≤ 105) — string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | b5c66f95990fbf76ab1f222b2f90d6b0 | train_000.jsonl | 1400167800 | You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | import javax.sound.midi.Soundbank;
import java.io.*;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Tester {
static class SuffixArray {
private char str[];
private int MAX_LOG = 30;
private int n, nr0[], nr1[], rank[][], index[], step, cnt;
private int M;
private int minusOneHead;
private int minusOneTail;
private int bucketHead[];
private int bucketTail[];
private int pointTo[];
private int next[];
private int globalPtr;
public SuffixArray(String s) {
str = s.toCharArray();
n = str.length;
nr0 = new int[n];
nr1 = new int[n];
index = new int[n];
rank = new int[MAX_LOG][n];
M = Math.max(128, n);
bucketHead = new int[M];
bucketTail = new int[M];
pointTo = new int[M];
next = new int[M];
for (int i = 0; i < n; i++)
rank[0][i] = str[i];
boolean needSort = true;
for (step = cnt = 1; (cnt >> 1) < n; step++, cnt <<= 1) {
if (!needSort) {
for (int i = 0; i < n; i++)
rank[step][i] = rank[step - 1][i];
continue;
}
for (int i = 0; i < n; i++) {
nr0[i] = rank[step - 1][i];
nr1[i] = i + cnt < n ? rank[step - 1][i + cnt] : -1;
index[i] = i;
}
radixSort1();
radixSort0();
needSort = false;
for (int i = 0; i < n; i++) {
if (i > 0 && nr0[index[i]] == nr0[index[i - 1]] && nr1[index[i]] == nr1[index[i - 1]]) {
rank[step][index[i]] = rank[step][index[i - 1]];
needSort = true;
} else rank[step][index[i]] = i;
}
}
}
private void radixSort0() {
globalPtr = 0;
Arrays.fill(bucketHead, -1);
Arrays.fill(next, -1);
for (int i = 0; i < n; i++) {
int value = nr0[index[i]];
if (bucketHead[value] == -1) bucketHead[value] = bucketTail[value] = globalPtr;
else bucketTail[value] = next[bucketTail[value]] = globalPtr;
pointTo[globalPtr++] = index[i];
}
int ptr = 0;
for (int i = 0; i < M; i++)
for (int j = bucketHead[i]; j != -1; j = next[j])
index[ptr++] = pointTo[j];
}
private void radixSort1() {
globalPtr = 0;
Arrays.fill(bucketHead, -1);
Arrays.fill(next, -1);
minusOneHead = minusOneTail = -1;
for (int i = 0; i < n; i++) {
int value = nr1[index[i]];
if (value == -1) {
if (minusOneHead == -1) minusOneHead = minusOneTail = globalPtr;
else minusOneTail = next[minusOneTail] = globalPtr;
} else {
if (bucketHead[value] == -1) bucketHead[value] = bucketTail[value] = globalPtr;
else bucketTail[value] = next[bucketTail[value]] = globalPtr;
}
pointTo[globalPtr++] = index[i];
}
int ptr = 0;
for (int j = minusOneHead; j != -1; j = next[j])
index[ptr++] = pointTo[j];
for (int i = 0; i < M; i++)
for (int j = bucketHead[i]; j != -1; j = next[j])
index[ptr++] = pointTo[j];
}
public int lcp(int x, int y) {
int k, ret = 0;
if (x == y) return n - x;
for (k = step - 1; k >= 0 && x < n && y < n; k--)
if (rank[k][x] == rank[k][y]) {
x += 1 << k;
y += 1 << k;
ret += 1 << k;
}
return ret;
}
}
public static void main(String[] args) throws Exception {
Reader.init(System.in);
BufferedWriter cout = new BufferedWriter(new OutputStreamWriter(System.out));
String s = Reader.next();
int[] ans = new int[s.length()];
SuffixArray sa = new SuffixArray(s);
int[] rank = sa.rank[sa.step - 1];
// System.out.println(Arrays.toString(rank));
for (int i = 1; i < s.length(); i++) {
if (rank[i] <= rank[0] && sa.lcp(i, 0) == sa.lcp(i, i)) {
int length = sa.lcp(i, i);
// System.out.println(length);
int left = rank[i], right = s.length();
while (left + 1 < right) {
int mid = (left + right) / 2;
if (sa.lcp(i, sa.index[mid]) == length) left = mid;
else right = mid;
}
ans[s.length() - i - 1] = left - rank[i] + 1;
}
}
ans[s.length() - 1] = 1;
StringBuilder builder = new StringBuilder();
int cnt = 0;
for (int i = 0; i < ans.length; i++)
if (ans[i] > 0) {
cnt++;
builder.append(String.format("%d %d%n", i + 1, ans[i]));
}
System.out.println(cnt);
System.out.println(builder.toString());
cout.close();
}
public void test() {
Fuck a = new Fuck();
}
class Fuck {
}
static class Pair<U extends Comparable<U>, V extends Comparable<V>> implements Comparable<Pair<U, V>> {
final U _1;
final V _2;
private Pair(U key, V val) {
this._1 = key;
this._2 = val;
}
public static <U extends Comparable<U>, V extends Comparable<V>> Pair<U, V> instanceOf(U _1, V _2) {
return new Pair<U, V>(_1, _2);
}
@Override
public String toString() {
return _1 + " " + _2;
}
@Override
public int hashCode() {
int res = 17;
res = res * 31 + _1.hashCode();
res = res * 31 + _2.hashCode();
return res;
}
@Override
public int compareTo(Pair<U, V> that) {
int res = this._1.compareTo(that._1);
if (res < 0 || res > 0) return res;
else return this._2.compareTo(that._2);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof Pair)) return false;
Pair<?, ?> that = (Pair<?, ?>) obj;
return _1.equals(that._1) && _2.equals(that._2);
}
}
/**
* Class for buffered reading int and double values
*/
static class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
/**
* call this method to initialize reader for InputStream
*/
static void init(InputStream input) {
reader = new BufferedReader(new InputStreamReader(input));
tokenizer = new StringTokenizer("");
}
/**
* get next word
*/
static String next() throws IOException {
while (!tokenizer.hasMoreTokens()) {
// TODO add check for eof if necessary
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
static class ArrayUtil {
static void swap(int[] a, int i, int j) {
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
static void swap(long[] a, int i, int j) {
long tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
static void swap(double[] a, int i, int j) {
double tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
static void swap(char[] a, int i, int j) {
char tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
static void swap(boolean[] a, int i, int j) {
boolean tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
static void reverse(int[] a, int i, int j) {
for (; i < j; i++, j--)
swap(a, i, j);
}
static void reverse(long[] a, int i, int j) {
for (; i < j; i++, j--)
swap(a, i, j);
}
static void reverse(double[] a, int i, int j) {
for (; i < j; i++, j--)
swap(a, i, j);
}
static void reverse(char[] a, int i, int j) {
for (; i < j; i++, j--)
swap(a, i, j);
}
static void reverse(boolean[] a, int i, int j) {
for (; i < j; i++, j--)
swap(a, i, j);
}
static long sum(int[] a) {
int sum = 0;
for (int i : a)
sum += i;
return sum;
}
static long sum(long[] a) {
long sum = 0;
for (long i : a)
sum += i;
return sum;
}
static double sum(double[] a) {
double sum = 0;
for (double i : a)
sum += i;
return sum;
}
static int max(int[] a) {
int max = Integer.MIN_VALUE;
for (int i : a)
if (i > max) max = i;
return max;
}
static int min(int[] a) {
int min = Integer.MAX_VALUE;
for (int i : a)
if (i < min) min = i;
return min;
}
static long max(long[] a) {
long max = Long.MIN_VALUE;
for (long i : a)
if (i > max) max = i;
return max;
}
static long min(long[] a) {
long min = Long.MAX_VALUE;
for (long i : a)
if (i < min) min = i;
return min;
}
}
}
| Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1 ≤ |s| ≤ 105) — string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | c678b935cb47ec4d722c779574a6e503 | train_000.jsonl | 1400167800 | You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring. | 256 megabytes | import java.io.*;
import java.util.*;
public class _432D {
static List<Integer>[] g;
static int[] size;
static void dfs(int u, int parent) {
size[u] = 1;
for (int v : g[u])
if (v != parent) {
dfs(v, u);
size[u] += size[v];
}
}
public static void main(String[] args) throws Exception {
Reader.init(System.in);
BufferedWriter cout = new BufferedWriter(new OutputStreamWriter(System.out));
String s = "$" + Reader.next();
int[] pi = new int[s.length()];
g = new List[s.length()];
size = new int[g.length];
for (int i = 0; i < g.length; i++) g[i] = new ArrayList<>(1);
pi[1] = 0;
for (int i = 2; i < s.length(); i++) {
int pre = pi[i - 1];
while (pre != 0 && s.charAt(pre + 1) != s.charAt(i)) pre = pi[pre];
pi[i] = pre + (s.charAt(pre + 1) == s.charAt(i) ? 1 : 0);
}
for (int i=1; i<pi.length; i++) {
g[i].add(pi[i]);
g[pi[i]].add(i);
}
dfs(0, -1);
List<Integer> cand = new ArrayList<>();
for (int i = s.length() - 1; i > 0; i = pi[i])
cand.add(i);
Collections.sort(cand);
StringBuilder builder = new StringBuilder();
builder.append(String.format("%d%n", cand.size()));
for (int i : cand)
builder.append(String.format("%d %d%n", i, size[i]));
System.out.println(builder.toString());
cout.close();
}
static class Pair<U extends Comparable<U>, V extends Comparable<V>> implements Comparable<Pair<U, V>> {
final U _1;
final V _2;
private Pair(U key, V val) {
this._1 = key;
this._2 = val;
}
public static <U extends Comparable<U>, V extends Comparable<V>> Pair<U, V> instanceOf(U _1, V _2) {
return new Pair<U, V>(_1, _2);
}
@Override
public String toString() {
return _1 + " " + _2;
}
@Override
public int hashCode() {
int res = 17;
res = res * 31 + _1.hashCode();
res = res * 31 + _2.hashCode();
return res;
}
@Override
public int compareTo(Pair<U, V> that) {
int res = this._1.compareTo(that._1);
if (res < 0 || res > 0) return res;
else return this._2.compareTo(that._2);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof Pair)) return false;
Pair<?, ?> that = (Pair<?, ?>) obj;
return _1.equals(that._1) && _2.equals(that._2);
}
}
/**
* Class for buffered reading int and double values
*/
static class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
/**
* call this method to initialize reader for InputStream
*/
static void init(InputStream input) {
reader = new BufferedReader(new InputStreamReader(input));
tokenizer = new StringTokenizer("");
}
/**
* get next word
*/
static String next() throws IOException {
while (!tokenizer.hasMoreTokens()) {
// TODO add check for eof if necessary
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
static class ArrayUtil {
static void swap(int[] a, int i, int j) {
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
static void swap(long[] a, int i, int j) {
long tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
static void swap(double[] a, int i, int j) {
double tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
static void swap(char[] a, int i, int j) {
char tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
static void swap(boolean[] a, int i, int j) {
boolean tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
static void reverse(int[] a, int i, int j) {
for (; i < j; i++, j--)
swap(a, i, j);
}
static void reverse(long[] a, int i, int j) {
for (; i < j; i++, j--)
swap(a, i, j);
}
static void reverse(double[] a, int i, int j) {
for (; i < j; i++, j--)
swap(a, i, j);
}
static void reverse(char[] a, int i, int j) {
for (; i < j; i++, j--)
swap(a, i, j);
}
static void reverse(boolean[] a, int i, int j) {
for (; i < j; i++, j--)
swap(a, i, j);
}
static long sum(int[] a) {
int sum = 0;
for (int i : a)
sum += i;
return sum;
}
static long sum(long[] a) {
long sum = 0;
for (long i : a)
sum += i;
return sum;
}
static double sum(double[] a) {
double sum = 0;
for (double i : a)
sum += i;
return sum;
}
static int max(int[] a) {
int max = Integer.MIN_VALUE;
for (int i : a)
if (i > max) max = i;
return max;
}
static int min(int[] a) {
int min = Integer.MAX_VALUE;
for (int i : a)
if (i < min) min = i;
return min;
}
static long max(long[] a) {
long max = Long.MIN_VALUE;
for (long i : a)
if (i > max) max = i;
return max;
}
static long min(long[] a) {
long min = Long.MAX_VALUE;
for (long i : a)
if (i < min) min = i;
return min;
}
}
}
| Java | ["ABACABA", "AAA"] | 1 second | ["3\n1 4\n3 2\n7 1", "3\n1 3\n2 2\n3 1"] | null | Java 8 | standard input | [
"dp",
"two pointers",
"string suffix structures",
"strings"
] | 3fb70a77e4de4851ed93f988140df221 | The single line contains a sequence of characters s1s2...s|s| (1 ≤ |s| ≤ 105) — string s. The string only consists of uppercase English letters. | 2,000 | In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li. | standard output | |
PASSED | 0eb725f1cb0399f06057c95bb094a128 | train_000.jsonl | 1486042500 | Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci.Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can.Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex.A subtree of some vertex is a subgraph containing that vertex and all its descendants.Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;
public class TimofeyAndATree {
InputStream is;
PrintWriter pw;
String INPUT = "";
long L_INF = (1L << 60L);
List<Integer> g[];
void solve() {
int n = ni(), x, y, m;
g = new ArrayList[n];
for (int i = 0; i < n; i++) {
g[i] = new ArrayList<>();
}
for (int i = 0; i < n - 1; i++) {
x = ni() - 1;
y = ni() - 1;
g[x].add(y);
g[y].add(x);
}
int c[] = na(n);
long s = Arrays.stream(c).distinct().count();
if(s==1){
pw.println("YES\n1");
return;
}
Set<Integer> st=null;
for (int i = 0; i < n; i++) {
for (int v : g[i]) {
if (c[i] != c[v]) {
if (null==st) {
st = new HashSet<>();
st.add(i);
st.add(v);
} else {
Set<Integer> s2 = new HashSet<>();
s2.add(i);
s2.add(v);
st.retainAll(s2);
}
}
}
}
if(null==st || st.size()==0){
pw.println("NO");
return;
}
pw.println("YES");
pw.println(st.iterator().next()+1);
}
class UnionFind {
private int count; // num of components
private int id[]; // id[i] = root of i
private int rank[]; // rank[i] = size of subtree rooted at i (cant be more than 31)
private int numNodes[];
UnionFind(int n) {
count = n;
id = new int[n];
rank = new int[n];
numNodes = new int[n];
int i;
for (i = 0; i < n; i++) {
id[i] = i; // each tree is its own root
rank[i] = 0;
numNodes[i] = 1; // each tree has 1 node(itself) in the beginning
}
}
/**
* @return the root of the parameter p
*/
int root(int p) {
while (p != id[p]) {
id[p] = id[id[p]]; // path compression
p = id[p];
}
return p;
}
/**
* @return true if a and b belong to same subtree
*/
boolean find(int a, int b) {
if (root(a) == root(b))
return true;
return false;
}
/**
* union of subtree a with b according to rank
*/
void union(int a, int b) {
int root_a = root(a);
int root_b = root(b);
if (root_a == root_b)
return;
if (rank[root_a] > rank[root_b]) {
id[root_b] = root_a;
numNodes[root_a] += numNodes[root_b];
} else if (rank[root_b] > rank[root_a]) {
id[root_a] = root_b;
numNodes[root_b] += numNodes[root_a];
} else {
id[root_a] = root_b;
numNodes[root_b] += numNodes[root_a];
rank[root_b]++;
}
count--;
}
/**
* @return number of components in tree
*/
int componentSize(int a) {
return numNodes[root(a)];
}
int numOfComponents() {
return count;
}
}
void run() throws Exception {
// is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
is = System.in;
pw = new PrintWriter(System.out);
long s = System.currentTimeMillis();
// int t = ni();
// while (t-- > 0)
solve();
pw.flush();
tr(System.currentTimeMillis() - s + "ms");
}
public static void main(String[] args) throws Exception {
new TimofeyAndATree().run();
}
private byte[] inbuf = new byte[1024];
private int lenbuf = 0, ptrbuf = 0;
private int readByte() {
if (lenbuf == -1) throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0) return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b)) ;
return b;
}
private double nd() {
return Double.parseDouble(ns());
}
private char nc() {
return (char) skip();
}
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++) map[i] = ns(m);
return map;
}
private int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = ni();
return a;
}
private int ni() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private long nl() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) {
if (!oj) System.out.println(Arrays.deepToString(o));
}
}
| Java | ["4\n1 2\n2 3\n3 4\n1 2 1 1", "3\n1 2\n2 3\n1 2 3", "4\n1 2\n2 3\n3 4\n1 2 1 2"] | 2 seconds | ["YES\n2", "YES\n2", "NO"] | null | Java 11 | standard input | [
"dp",
"graphs",
"dsu",
"implementation",
"dfs and similar",
"trees"
] | aaca5d07795a42ecab210327c1cf6be9 | The first line contains single integer n (2 ≤ n ≤ 105) — the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 105), denoting the colors of the vertices. | 1,600 | Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. | standard output | |
PASSED | 7b0cfb30af699dfa7f2d0b72e0f1ba92 | train_000.jsonl | 1486042500 | Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci.Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can.Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex.A subtree of some vertex is a subgraph containing that vertex and all its descendants.Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Vector;
import java.util.Scanner;
import java.util.Set;
import java.util.Stack;
import java.util.ArrayList;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Kraken7
*/
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);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
private ArrayList<ArrayList<Integer>> graph = new ArrayList<>();
private boolean[] vis;
private int[] color;
private int n;
private boolean dfs(int vertex) {
boolean possible = true;
Stack<Integer> stack = new Stack<>();
vis = new boolean[n + 1];
for (int i : graph.get(vertex)) {
stack.push(i);
vis[i] = true;
Set<Integer> set = new HashSet<>();
while (!stack.isEmpty()) {
int curr = stack.pop();
set.add(color[curr]);
for (int j : graph.get(curr)) {
if (j == vertex)
continue;
if (!vis[j])
stack.push(j);
vis[j] = true;
}
}
possible &= set.size() == 1;
}
return possible;
}
public void solve(int testNumber, Scanner in, PrintWriter out) {
n = in.nextInt();
ArrayList<Edge> edges = new ArrayList<>();
for (int i = 0; i <= n; i++)
graph.add(new ArrayList<>());
for (int i = 1; i < n; i++) {
int u = in.nextInt(), v = in.nextInt();
edges.add(new Edge(u, v));
graph.get(u).add(v);
graph.get(v).add(u);
}
color = new int[n + 1];
for (int i = 1; i <= n; i++)
color[i] = in.nextInt();
int u = -1, v = -1;
for (Edge i : edges) {
if (color[i.u] != color[i.v]) {
u = i.u;
v = i.v;
break;
}
}
if (u == -1) {
out.println("YES\n1");
return;
}
if (dfs(u)) {
out.println("YES");
out.println(u);
} else if (dfs(v)) {
out.println("YES");
out.println(v);
} else {
out.println("NO");
}
}
private class Edge {
int u;
int v;
public Edge(int u, int v) {
this.u = u;
this.v = v;
}
public String toString() {
return "Edge{" +
"u=" + u +
", v=" + v +
'}';
}
}
}
}
| Java | ["4\n1 2\n2 3\n3 4\n1 2 1 1", "3\n1 2\n2 3\n1 2 3", "4\n1 2\n2 3\n3 4\n1 2 1 2"] | 2 seconds | ["YES\n2", "YES\n2", "NO"] | null | Java 11 | standard input | [
"dp",
"graphs",
"dsu",
"implementation",
"dfs and similar",
"trees"
] | aaca5d07795a42ecab210327c1cf6be9 | The first line contains single integer n (2 ≤ n ≤ 105) — the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 105), denoting the colors of the vertices. | 1,600 | Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. | standard output | |
PASSED | b2038657d32b0c159d4a6d51c4bb79d6 | train_000.jsonl | 1486042500 | Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci.Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can.Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex.A subtree of some vertex is a subgraph containing that vertex and all its descendants.Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
import java.awt.Point;
// SHIVAM GUPTA :
//NSIT
//decoder_1671
// STOP NOT TILL IT IS DONE OR U DIE .
// U KNOW THAT IF THIS DAY WILL BE URS THEN NO ONE CAN DEFEAT U HERE................
// ASCII = 48 + i ;// 2^28 = 268,435,456 > 2* 10^8 // log 10 base 2 = 3.3219
// odd:: (x^2+1)/2 , (x^2-1)/2 ; x>=3// even:: (x^2/4)+1 ,(x^2/4)-1 x >=4
// FOR ANY ODD NO N : N,N-1,N-2
//ALL ARE PAIRWISE COPRIME
//THEIR COMBINED LCM IS PRODUCT OF ALL THESE NOS
// two consecutive odds are always coprime to each other
// two consecutive even have always gcd = 2 ;
/* Name of the class has to be "Main" only if the class is public. */
public class Main
{
// static int[] arr = new int[100002] ;
// static int[] dp = new int[100002] ;
static PrintWriter out;
static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br=new BufferedReader(new InputStreamReader(System.in));
out=new PrintWriter(System.out);
}
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;
}
}
////////////////////////////////////////////////////////////////////////////////////
public static int countDigit(long n)
{
return (int)Math.floor(Math.log10(n) + 1);
}
/////////////////////////////////////////////////////////////////////////////////////////
public static int sumOfDigits(long n)
{
if( n< 0)return -1 ;
int sum = 0;
while( n > 0)
{
sum = sum + (int)( n %10) ;
n /= 10 ;
}
return sum ;
}
//////////////////////////////////////////////////////////////////////////////////////////////////
public static long arraySum(int[] arr , int start , int end)
{
long ans = 0 ;
for(int i = start ; i <= end ; i++)ans += arr[i] ;
return ans ;
}
/////////////////////////////////////////////////////////////////////////////////
public static int mod(int x)
{
if(x <0)return -1*x ;
else return x ;
}
public static long mod(long x)
{
if(x <0)return -1*x ;
else return x ;
}
////////////////////////////////////////////////////////////////////////////////
public static void swapArray(int[] arr , int start , int end)
{
while(start < end)
{
int temp = arr[start] ;
arr[start] = arr[end];
arr[end] = temp;
start++ ;end-- ;
}
}
//////////////////////////////////////////////////////////////////////////////////
public static int[][] rotate(int[][] input){
int n =input.length;
int m = input[0].length ;
int[][] output = new int [m][n];
for (int i=0; i<n; i++)
for (int j=0;j<m; j++)
output [j][n-1-i] = input[i][j];
return output;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
public static int countBits(long n)
{
int count = 0;
while (n != 0)
{
count++;
n = (n) >> (1L) ;
}
return count;
}
/////////////////////////////////////////// ////////////////////////////////////////////////
public static boolean isPowerOfTwo(long n)
{
if(n==0)
return false;
if(((n ) & (n-1)) == 0 ) return true ;
else return false ;
}
/////////////////////////////////////////////////////////////////////////////////////
public static int min(int a ,int b , int c, int d)
{
int[] arr = new int[4] ;
arr[0] = a;arr[1] = b ;arr[2] = c;arr[3] = d;Arrays.sort(arr) ;
return arr[0];
}
/////////////////////////////////////////////////////////////////////////////
public static int max(int a ,int b , int c, int d)
{
int[] arr = new int[4] ;
arr[0] = a;arr[1] = b ;arr[2] = c;arr[3] = d;Arrays.sort(arr) ;
return arr[3];
}
///////////////////////////////////////////////////////////////////////////////////
public static String reverse(String input)
{
StringBuilder str = new StringBuilder("") ;
for(int i =input.length()-1 ; i >= 0 ; i-- )
{
str.append(input.charAt(i));
}
return str.toString() ;
}
///////////////////////////////////////////////////////////////////////////////////////////
public static boolean sameParity(long a ,long b )
{
long x = a% 2L; long y = b%2L ;
if(x==y)return true ;
else return false ;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
public static boolean isPossibleTriangle(int a ,int b , int c)
{
if( a + b > c && c+b > a && a +c > b)return true ;
else return false ;
}
////////////////////////////////////////////////////////////////////////////////////////////
static long xnor(long num1, long num2) {
if (num1 < num2) {
long temp = num1;
num1 = num2;
num2 = temp;
}
num1 = togglebit(num1);
return num1 ^ num2;
}
static long togglebit(long n) {
if (n == 0)
return 1;
long i = n;
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
return i ^ n;
}
///////////////////////////////////////////////////////////////////////////////////////////////
public static int xorOfFirstN(int n)
{
if( n % 4 ==0)return n ;
else if( n % 4 == 1)return 1 ;
else if( n % 4 == 2)return n+1 ;
else return 0 ;
}
//////////////////////////////////////////////////////////////////////////////////////////////
public static int gcd(int a, int b )
{
if(b==0)return a ;
else return gcd(b,a%b) ;
}
public static long gcd(long a, long b )
{
if(b==0)return a ;
else return gcd(b,a%b) ;
}
////////////////////////////////////////////////////////////////////////////////////
public static int lcm(int a, int b ,int c , int d )
{
int temp = lcm(a,b , c) ;
int ans = lcm(temp ,d ) ;
return ans ;
}
///////////////////////////////////////////////////////////////////////////////////////////
public static int lcm(int a, int b ,int c )
{
int temp = lcm(a,b) ;
int ans = lcm(temp ,c) ;
return ans ;
}
////////////////////////////////////////////////////////////////////////////////////////
public static int lcm(int a , int b )
{
int gc = gcd(a,b);
return (a*b)/gc ;
}
public static long lcm(long a , long b )
{
long gc = gcd(a,b);
return (a*b)/gc ;
}
///////////////////////////////////////////////////////////////////////////////////////////
static boolean isPrime(long n)
{
if(n==1)
{
return false ;
}
boolean ans = true ;
for(long i = 2L; i*i <= n ;i++)
{
if(n% i ==0)
{
ans = false ;break ;
}
}
return ans ;
}
///////////////////////////////////////////////////////////////////////////
static int sieve = 1000000 ;
static boolean[] prime = new boolean[sieve + 1] ;
public static void sieveOfEratosthenes()
{
// FALSE == prime
// TRUE == COMPOSITE
// FALSE== 1
// time complexity = 0(NlogLogN)== o(N)
// gives prime nos bw 1 to N
for(int i = 4; i<= sieve ; i++)
{
prime[i] = true ;
i++ ;
}
for(int p = 3; p*p <= sieve; p++)
{
if(prime[p] == false)
{
for(int i = p*p; i <= sieve; i += p)
prime[i] = true;
}
p++ ;
}
}
///////////////////////////////////////////////////////////////////////////////////
public static void sortD(int[] arr , int s , int e)
{
sort(arr ,s , e) ;
int i =s ; int j = e ;
while( i < j)
{
int temp = arr[i] ;
arr[i] =arr[j] ;
arr[j] = temp ;
i++ ; j-- ;
}
return ;
}
/////////////////////////////////////////////////////////////////////////////////////////
public static long countSubarraysSumToK(long[] arr ,long sum )
{
HashMap<Long,Long> map = new HashMap<>() ;
int n = arr.length ;
long prefixsum = 0 ;
long count = 0L ;
for(int i = 0; i < n ; i++)
{
prefixsum = prefixsum + arr[i] ;
if(sum == prefixsum)count = count+1 ;
if(map.containsKey(prefixsum -sum))
{
count = count + map.get(prefixsum -sum) ;
}
if(map.containsKey(prefixsum ))
{
map.put(prefixsum , map.get(prefixsum) +1 );
}
else{
map.put(prefixsum , 1L );
}
}
return count ;
}
///////////////////////////////////////////////////////////////////////////////////////////////
// KMP ALGORITHM : TIME COMPL:O(N+M)
// FINDS THE OCCURENCES OF PATTERN AS A SUBSTRING IN STRING
//RETURN THE ARRAYLIST OF INDEXES
// IF SIZE OF LIST IS ZERO MEANS PATTERN IS NOT PRESENT IN STRING
public static ArrayList<Integer> kmpAlgorithm(String str , String pat)
{
ArrayList<Integer> list =new ArrayList<>();
int n = str.length() ;
int m = pat.length() ;
String q = pat + "#" + str ;
int[] lps =new int[n+m+1] ;
longestPefixSuffix(lps, q,(n+m+1)) ;
for(int i =m+1 ; i < (n+m+1) ; i++ )
{
if(lps[i] == m)
{
list.add(i-2*m) ;
}
}
return list ;
}
public static void longestPefixSuffix(int[] lps ,String str , int n)
{
lps[0] = 0 ;
for(int i = 1 ; i<= n-1; i++)
{
int l = lps[i-1] ;
while( l > 0 && str.charAt(i) != str.charAt(l))
{
l = lps[l-1] ;
}
if(str.charAt(i) == str.charAt(l))
{
l++ ;
}
lps[i] = l ;
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
// CALCULATE TOTIENT Fn FOR ALL VALUES FROM 1 TO n
// TOTIENT(N) = count of nos less than n and grater than 1 whose gcd with n is 1
// or n and the no will be coprime in nature
//time : O(n*(log(logn)))
public static void eulerTotientFunction(int[] arr ,int n )
{
for(int i = 1; i <= n ;i++)arr[i] =i ;
for(int i= 2 ; i<= n ;i++)
{
if(arr[i] == i)
{
arr[i] =i-1 ;
for(int j =2*i ; j<= n ; j+= i )
{
arr[j] = (arr[j]*(i-1))/i ;
}
}
}
return ;
}
/////////////////////////////////////////////////////////////////////////////////////////////
public static long nCr(int n,int k)
{
long ans=1L;
k=k>n-k?n-k:k;
int j=1;
for(;j<=k;j++,n--)
{
if(n%j==0)
{
ans*=n/j;
}else
if(ans%j==0)
{
ans=ans/j*n;
}else
{
ans=(ans*n)/j;
}
}
return ans;
}
///////////////////////////////////////////////////////////////////////////////////////////
public static ArrayList<Integer> allFactors(int n)
{
ArrayList<Integer> list = new ArrayList<>() ;
for(int i = 1; i*i <= n ;i++)
{
if( n % i == 0)
{
if(i*i == n)
{
list.add(i) ;
}
else{
list.add(i) ;
list.add(n/i) ;
}
}
}
return list ;
}
public static ArrayList<Long> allFactors(long n)
{
ArrayList<Long> list = new ArrayList<>() ;
for(long i = 1L; i*i <= n ;i++)
{
if( n % i == 0)
{
if(i*i == n)
{
list.add(i) ;
}
else{
list.add(i) ;
list.add(n/i) ;
}
}
}
return list ;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
static final int MAXN = 10000001;
static int spf[] = new int[MAXN];
static void sieve()
{
spf[1] = 1;
for (int i=2; i<MAXN; i++)
spf[i] = i;
for (int i=4; i<MAXN; i+=2)
spf[i] = 2;
for (int i=3; i*i<MAXN; i++)
{
if (spf[i] == i)
{
for (int j=i*i; j<MAXN; j+=i)
if (spf[j]==j)
spf[j] = i;
}
}
}
// The above code works well for n upto the order of 10^7.
// Beyond this we will face memory issues.
// Time Complexity: The precomputation for smallest prime factor is done in O(n log log n)
// using sieve.
// Where as in the calculation step we are dividing the number every time by
// the smallest prime number till it becomes 1.
// So, let’s consider a worst case in which every time the SPF is 2 .
// Therefore will have log n division steps.
// Hence, We can say that our Time Complexity will be O(log n) in worst case.
static Vector<Integer> getFactorization(int x)
{
Vector<Integer> ret = new Vector<>();
while (x != 1)
{
ret.add(spf[x]);
x = x / spf[x];
}
return ret;
}
//////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////
public static void merge(int arr[], int l, int m, int r)
{
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;
/* Create temp arrays */
int L[] = new int[n1];
int R[] = new int[n2];
//Copy data to temp arrays
for (int i=0; i<n1; ++i)
L[i] = arr[l + i];
for (int j=0; j<n2; ++j)
R[j] = arr[m + 1+ j];
/* Merge the temp arrays */
// Initial indexes of first and second subarrays
int i = 0, j = 0;
// Initial index of merged subarry array
int k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
/* Copy remaining elements of L[] if any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
/* Copy remaining elements of R[] if any */
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
// Main function that sorts arr[l..r] using
// merge()
public static void sort(int arr[], int l, int r)
{
if (l < r)
{
// Find the middle point
int m = (l+r)/2;
// Sort first and second halves
sort(arr, l, m);
sort(arr , m+1, r);
// Merge the sorted halves
merge(arr, l, m, r);
}
}
public static void sort(long arr[], int l, int r)
{
if (l < r)
{
// Find the middle point
int m = (l+r)/2;
// Sort first and second halves
sort(arr, l, m);
sort(arr , m+1, r);
// Merge the sorted halves
merge(arr, l, m, r);
}
}
public static void merge(long arr[], int l, int m, int r)
{
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;
/* Create temp arrays */
long L[] = new long[n1];
long R[] = new long[n2];
//Copy data to temp arrays
for (int i=0; i<n1; ++i)
L[i] = arr[l + i];
for (int j=0; j<n2; ++j)
R[j] = arr[m + 1+ j];
/* Merge the temp arrays */
// Initial indexes of first and second subarrays
int i = 0, j = 0;
// Initial index of merged subarry array
int k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
/* Copy remaining elements of L[] if any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
/* Copy remaining elements of R[] if any */
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
/////////////////////////////////////////////////////////////////////////////////////////
public static long knapsack(int[] weight,long value[],int maxWeight){
int n= value.length ;
//dp[i] stores the profit with KnapSack capacity "i"
long []dp = new long[maxWeight+1];
//initially profit with 0 to W KnapSack capacity is 0
Arrays.fill(dp, 0);
// iterate through all items
for(int i=0; i < n; i++)
//traverse dp array from right to left
for(int j = maxWeight; j >= weight[i]; j--)
dp[j] = Math.max(dp[j] , value[i] + dp[j - weight[i]]);
/*above line finds out maximum of dp[j](excluding ith element value)
and val[i] + dp[j-wt[i]] (including ith element value and the
profit with "KnapSack capacity - ith element weight") */
return dp[maxWeight];
}
///////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
// to return max sum of any subarray in given array
public static long kadanesAlgorithm(long[] arr)
{
long[] dp = new long[arr.length] ;
dp[0] = arr[0] ;
long max = dp[0] ;
for(int i = 1; i < arr.length ; i++)
{
if(dp[i-1] > 0)
{
dp[i] = dp[i-1] + arr[i] ;
}
else{
dp[i] = arr[i] ;
}
if(dp[i] > max)max = dp[i] ;
}
return max ;
}
/////////////////////////////////////////////////////////////////////////////////////////////
public static long kadanesAlgorithm(int[] arr)
{
long[] dp = new long[arr.length] ;
dp[0] = arr[0] ;
long max = dp[0] ;
for(int i = 1; i < arr.length ; i++)
{
if(dp[i-1] > 0)
{
dp[i] = dp[i-1] + arr[i] ;
}
else{
dp[i] = arr[i] ;
}
if(dp[i] > max)max = dp[i] ;
}
return max ;
}
///////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////
public static long binarySerachGreater(int[] arr , int start , int end , int val)
{
// fing total no of elements strictly grater than val in sorted array arr
if(start > end)return 0 ; //Base case
int mid = (start + end)/2 ;
if(arr[mid] <=val)
{
return binarySerachGreater(arr,mid+1, end ,val) ;
}
else{
return binarySerachGreater(arr,start , mid -1,val) + end-mid+1 ;
}
}
//////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
//TO GENERATE ALL(DUPLICATE ALSO EXIST) PERMUTATIONS OF A STRING
// JUST CALL generatePermutation( str, start, end) start :inclusive ,end : exclusive
//Function for swapping the characters at position I with character at position j
public static String swapString(String a, int i, int j) {
char[] b =a.toCharArray();
char ch;
ch = b[i];
b[i] = b[j];
b[j] = ch;
return String.valueOf(b);
}
//Function for generating different permutations of the string
public static void generatePermutation(String str, int start, int end)
{
//Prints the permutations
if (start == end-1)
System.out.println(str);
else
{
for (int i = start; i < end; i++)
{
//Swapping the string by fixing a character
str = swapString(str,start,i);
//Recursively calling function generatePermutation() for rest of the characters
generatePermutation(str,start+1,end);
//Backtracking and swapping the characters again.
str = swapString(str,start,i);
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
public static long factMod(long n, long mod) {
if (n <= 1) return 1;
long ans = 1;
for (int i = 1; i <= n; i++) {
ans = (ans * i) % mod;
}
return ans;
}
/////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////
public static long power(long x ,long n)
{
//time comp : o(logn)
if(n==0)return 1L ;
if(n==1)return x;
long ans =1L ;
while(n>0)
{
if(n % 2 ==1)
{
ans = ans *x ;
}
n /= 2 ;
x = x*x ;
}
return ans ;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
public static long powerMod(long x, long n, long mod) {
//time comp : o(logn)
if(n==0)return 1L ;
if(n==1)return x;
long ans = 1;
while (n > 0) {
if (n % 2 == 1) ans = (ans * x) % mod;
x = (x * x) % mod;
n /= 2;
}
return ans;
}
//////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
/*
lowerBound - finds largest element equal or less than value paased
upperBound - finds smallest element equal or more than value passed
if not present return -1;
*/
public static long lowerBound(long[] arr,long k)
{
long ans=-1;
int start=0;
int end=arr.length-1;
while(start<=end)
{
int mid=(start+end)/2;
if(arr[mid]<=k)
{
ans=arr[mid];
start=mid+1;
}
else
{
end=mid-1;
}
}
return ans;
}
public static int lowerBound(int[] arr,int k)
{
int ans=-1;
int start=0;
int end=arr.length-1;
while(start<=end)
{
int mid=(start+end)/2;
if(arr[mid]<=k)
{
ans=arr[mid];
start=mid+1;
}
else
{
end=mid-1;
}
}
return ans;
}
public static long upperBound(long[] arr,long k)
{
long ans=-1;
int start=0;
int end=arr.length-1;
while(start<=end)
{
int mid=(start+end)/2;
if(arr[mid]>=k)
{
ans=arr[mid];
end=mid-1;
}
else
{
start=mid+1;
}
}
return ans;
}
public static int upperBound(int[] arr,int k)
{
int ans=-1;
int start=0;
int end=arr.length-1;
while(start<=end)
{
int mid=(start+end)/2;
if(arr[mid]>=k)
{
ans=arr[mid];
end=mid-1;
}
else
{
start=mid+1;
}
}
return ans;
}
//////////////////////////////////////////////////////////////////////////////////////////
public static void printArray(int[] arr , int si ,int ei)
{
for(int i = si ; i <= ei ; i++)
{
out.print(arr[i] +" ") ;
}
}
public static void printArrayln(int[] arr , int si ,int ei)
{
for(int i = si ; i <= ei ; i++)
{
out.print(arr[i] +" ") ;
}
out.println() ;
}
public static void printLArray(long[] arr , int si , int ei)
{
for(int i = si ; i <= ei ; i++)
{
out.print(arr[i] +" ") ;
}
}
public static void printLArrayln(long[] arr , int si , int ei)
{
for(int i = si ; i <= ei ; i++)
{
out.print(arr[i] +" ") ;
}
out.println() ;
}
public static void printtwodArray(int[][] ans)
{
for(int i = 0; i< ans.length ; i++)
{
for(int j = 0 ; j < ans[0].length ; j++)out.print(ans[i][j] +" ");
out.println() ;
}
out.println() ;
}
static long modPow(long a, long x, long p) {
//calculates a^x mod p in logarithmic time.
long res = 1;
while(x > 0) {
if( x % 2 != 0) {
res = (res * a) % p;
}
a = (a * a) % p;
x /= 2;
}
return res;
}
static long modInverse(long a, long p) {
//calculates the modular multiplicative of a mod m.
//(assuming p is prime).
return modPow(a, p-2, p);
}
static long modBinomial(long n, long k, long p) {
// calculates C(n,k) mod p (assuming p is prime).
long numerator = 1; // n * (n-1) * ... * (n-k+1)
for (int i=0; i<k; i++) {
numerator = (numerator * (n-i) ) % p;
}
long denominator = 1; // k!
for (int i=1; i<=k; i++) {
denominator = (denominator * i) % p;
}
// numerator / denominator mod p.
return ( numerator* modInverse(denominator,p) ) % p;
}
/////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
static ArrayList<Integer>[] tree ;
// static long[] child;
// static int mod= 1000000007 ;
// static int[][] pre = new int[3001][3001];
// static int[][] suf = new int[3001][3001] ;
//program to calculate noof nodes in subtree for every vertex including itself
public static void countNoOfNodesInsubtree(int child ,int par , int[] dp)
{
int count = 0 ;
for(int x : tree[child])
{
if(x== par)continue ;
countNoOfNodesInsubtree(x,child,dp) ;
count= count + dp[x] + 1 ;
}
dp[child] = count ;
}
public static void depth(int child ,int par , int[] dp , int d )
{
dp[child] =d ;
for(int x : tree[child])
{
if(x== par)continue ;
depth(x,child,dp,d+1) ;
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
public static void solve()
{
FastReader scn = new FastReader() ;
//Scanner scn = new Scanner(System.in);
//int[] store = {2 ,3, 5 , 7 ,11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 } ;
// product of first 11 prime nos is greater than 10 ^ 12;
//ArrayList<Integer> arr[] = new ArrayList[n] ;
ArrayList<Integer> list = new ArrayList<>() ;
ArrayList<Long> listl = new ArrayList<>() ;
ArrayList<Integer> lista = new ArrayList<>() ;
ArrayList<Integer> listb = new ArrayList<>() ;
//ArrayList<String> lists = new ArrayList<>() ;
HashMap<Integer,Integer> map = new HashMap<>() ;
//HashMap<Long,Long> map = new HashMap<>() ;
HashMap<Integer,Integer> map1 = new HashMap<>() ;
HashMap<Integer,Integer> map2 = new HashMap<>() ;
//HashMap<String,Integer> maps = new HashMap<>() ;
//HashMap<Integer,Boolean> mapb = new HashMap<>() ;
//HashMap<Point,Integer> point = new HashMap<>() ;
Set<Integer> set = new HashSet<>() ;
Set<Integer> setx = new HashSet<>() ;
Set<Integer> sety = new HashSet<>() ;
StringBuilder sb =new StringBuilder("") ;
//Collections.sort(list);
//if(map.containsKey(arr[i]))map.put(arr[i] , map.get(arr[i]) +1 ) ;
//else map.put(arr[i],1) ;
// if(map.containsKey(temp))map.put(temp , map.get(temp) +1 ) ;
// else map.put(temp,1) ;
//int bit =Integer.bitCount(n);
// gives total no of set bits in n;
// Arrays.sort(arr, new Comparator<Pair>() {
// @Override
// public int compare(Pair a, Pair b) {
// if (a.first != b.first) {
// return a.first - b.first; // for increasing order of first
// }
// return a.second - b.second ; //if first is same then sort on second basis
// }
// });
int testcase = 1;
//testcase = scn.nextInt() ;
for(int testcases =1 ; testcases <= testcase ;testcases++)
{
//if(map.containsKey(arr[i]))map.put(arr[i],map.get(arr[i])+1) ;else map.put(arr[i],1) ;
//if(map.containsKey(temp))map.put(temp,map.get(temp)+1) ;else map.put(temp,1) ;
// tree = new ArrayList[n] ;
// child = new long[n] ;
int n = scn.nextInt() ;
tree = new ArrayList[n] ;
for(int i = 0; i< n; i++)
{
tree[i] = new ArrayList<Integer>();
}
int[] s = new int[n-1] ; int[] f = new int[n-1] ;
for(int i = 0 ;i <= n-2; i++)
{
int fv = scn.nextInt() ;
int sv = scn.nextInt() ;
fv-- ;
sv-- ;
tree[sv].add(fv) ;tree[fv].add(sv) ;
f[i] = fv; s[i] =sv ;
}
int count = 0 ;
int[] freq = new int[n] ;
int[] c = new int[n] ;
for(int i = 0 ; i< n ;i++)c[i] = scn.nextInt() ;
int j = 0 ;
for( ; j <= n-2; j++)
{
if(c[f[j]] != c[s[j]])
{ count++ ;
freq[f[j]]++ ; freq[s[j]]++ ;
}
}
if(count == 0)
{
out.println("YES") ;out.println(1) ;
out.flush() ;return ;
}
for(int i = 0 ; i< n ;i++)
{
if(freq[i] == count)
{
out.println("YES") ;out.println(i+1) ;
out.flush() ;return ;
}
}
out.println("NO") ;
sb.delete(0 , sb.length()) ;
list.clear() ;listb.clear() ;
map.clear() ;
map1.clear() ;
map2.clear() ;
setx.clear() ;sety.clear() ;
} // test case end loop
out.flush() ;
} // solve fn ends
public static void main (String[] args) throws java.lang.Exception
{
solve() ;
}
}
class Pair
{
int first ;
int second ;
@Override
public String toString() {
String ans = "" ;
ans += this.first ;
ans += " ";
ans += this.second ;
return ans ;
}
}
| Java | ["4\n1 2\n2 3\n3 4\n1 2 1 1", "3\n1 2\n2 3\n1 2 3", "4\n1 2\n2 3\n3 4\n1 2 1 2"] | 2 seconds | ["YES\n2", "YES\n2", "NO"] | null | Java 11 | standard input | [
"dp",
"graphs",
"dsu",
"implementation",
"dfs and similar",
"trees"
] | aaca5d07795a42ecab210327c1cf6be9 | The first line contains single integer n (2 ≤ n ≤ 105) — the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 105), denoting the colors of the vertices. | 1,600 | Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. | standard output | |
PASSED | 27bf4470f940e4caaac3b9bc2cff4832 | train_000.jsonl | 1486042500 | Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci.Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can.Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex.A subtree of some vertex is a subgraph containing that vertex and all its descendants.Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. | 256 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
// 15:26.000 +
public class cf763a {
static BufferedReader __in;
static PrintWriter __out;
static StringTokenizer input;
static int par[], c[], sz[];
static int find(int i) {
return par[i] == i ? i : (par[i] = find(par[i]));
}
static void union(int i, int j) {
int a = find(i), b = find(j);
if(a != b && c[a] == c[b]) {
par[b] = a;
sz[a] += sz[b];
}
}
public static void main(String[] args) throws IOException {
__in = new BufferedReader(new InputStreamReader(System.in));
__out = new PrintWriter(new OutputStreamWriter(System.out));
int n = ri(), e[][] = new int[n - 1][2];
List<List<Integer>> nei = new ArrayList<>();
for(int i = 0; i < n; ++i) {
nei.add(new ArrayList<>());
}
par = new int[n];
c = new int[n];
sz = new int[n];
for(int i = 0; i < n - 1; ++i) {
e[i][0] = rni() - 1;
e[i][1] = ni() - 1;
nei.get(e[i][0]).add(e[i][1]);
nei.get(e[i][1]).add(e[i][0]);
}
r();
for(int i = 0; i < n; ++i) {
par[i] = i;
sz[i] = 1;
c[i] = ni();
}
for(int i = 0; i < n - 1; ++i) {
union(e[i][0], e[i][1]);
}
int ans = -1;
for(int i = 0; i < n; ++i) {
int sum = 0, sub = 1;
Set<Integer> subtrees = new HashSet<>();
for(Integer j : nei.get(i)) {
subtrees.add(find(j));
if(find(i) == find(j)) {
sub = 0;
}
}
for(Integer j : subtrees) {
sum += sz[j];
}
if(sum == n - sub) {
ans = i + 1;
break;
}
}
prYN(ans >= 0);
if(ans > 0) {
prln(ans);
}
close();
}
// references
// IBIG = 1e9 + 7
// IRAND ~= 3e8
// IMAX ~= 2e10
// LMAX ~= 9e18
// constants
static final int IBIG = 1000000007;
static final int IRAND = 327859546;
static final int IMAX = 2147483647;
static final int IMIN = -2147483648;
static final long LMAX = 9223372036854775807L;
static final long LMIN = -9223372036854775808L;
// util
static int minof(int a, int b, int c) {return min(a, min(b, c));}
static int minof(int... x) {return x.length == 1 ? x[0] : x.length == 2 ? min(x[0], x[1]) : min(x[0], minstarting(1, x));}
static int minstarting(int offset, int... x) {assert x.length > 2; return offset == x.length - 2 ? min(x[offset], x[offset + 1]) : min(x[offset], minstarting(offset + 1, x));}
static long minof(long a, long b, long c) {return min(a, min(b, c));}
static long minof(long... x) {return x.length == 1 ? x[0] : x.length == 2 ? min(x[0], x[1]) : min(x[0], minstarting(1, x));}
static long minstarting(int offset, long... x) {assert x.length > 2; return offset == x.length - 2 ? min(x[offset], x[offset + 1]) : min(x[offset], minstarting(offset + 1, x));}
static int maxof(int a, int b, int c) {return max(a, max(b, c));}
static int maxof(int... x) {return x.length == 1 ? x[0] : x.length == 2 ? max(x[0], x[1]) : max(x[0], maxstarting(1, x));}
static int maxstarting(int offset, int... x) {assert x.length > 2; return offset == x.length - 2 ? max(x[offset], x[offset + 1]) : max(x[offset], maxstarting(offset + 1, x));}
static long maxof(long a, long b, long c) {return max(a, max(b, c));}
static long maxof(long... x) {return x.length == 1 ? x[0] : x.length == 2 ? max(x[0], x[1]) : max(x[0], maxstarting(1, x));}
static long maxstarting(int offset, long... x) {assert x.length > 2; return offset == x.length - 2 ? max(x[offset], x[offset + 1]) : max(x[offset], maxstarting(offset + 1, x));}
static int powi(int a, int b) {if(a == 0) return 0; int ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static long powl(long a, int b) {if(a == 0) return 0; long ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static int floori(double d) {return (int)d;}
static int ceili(double d) {return (int)ceil(d);}
static long floorl(double d) {return (long)d;}
static long ceill(double d) {return (long)ceil(d);}
// input
static void r() throws IOException {input = new StringTokenizer(__in.readLine());}
static int ri() throws IOException {return Integer.parseInt(__in.readLine());}
static long rl() throws IOException {return Long.parseLong(__in.readLine());}
static int[] ria(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()); return a;}
static long[] rla(int n) throws IOException {long[] a = new long[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Long.parseLong(input.nextToken()); return a;}
static char[] rcha() throws IOException {return __in.readLine().toCharArray();}
static String rline() throws IOException {return __in.readLine();}
static int rni() throws IOException {input = new StringTokenizer(__in.readLine()); return Integer.parseInt(input.nextToken());}
static int ni() {return Integer.parseInt(input.nextToken());}
static long rnl() throws IOException {input = new StringTokenizer(__in.readLine()); return Long.parseLong(input.nextToken());}
static long nl() {return Long.parseLong(input.nextToken());}
// output
static void pr(int i) {__out.print(i);}
static void prln(int i) {__out.println(i);}
static void pr(long l) {__out.print(l);}
static void prln(long l) {__out.println(l);}
static void pr(double d) {__out.print(d);}
static void prln(double d) {__out.println(d);}
static void pr(char c) {__out.print(c);}
static void prln(char c) {__out.println(c);}
static void pr(char[] s) {__out.print(new String(s));}
static void prln(char[] s) {__out.println(new String(s));}
static void pr(String s) {__out.print(s);}
static void prln(String s) {__out.println(s);}
static void pr(Object o) {__out.print(o);}
static void prln(Object o) {__out.println(o);}
static void prln() {__out.println();}
static void pryes() {__out.println("yes");}
static void pry() {__out.println("Yes");}
static void prY() {__out.println("YES");}
static void prno() {__out.println("no");}
static void prn() {__out.println("No");}
static void prN() {__out.println("NO");}
static void pryesno(boolean b) {__out.println(b ? "yes" : "no");};
static void pryn(boolean b) {__out.println(b ? "Yes" : "No");}
static void prYN(boolean b) {__out.println(b ? "YES" : "NO");}
static void prln(int... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);}
static void prln(long... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);}
static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for(int i = 0; i < n; __out.print(iter.next()), __out.print(' '), ++i); __out.println(iter.next());}
static void flush() {__out.flush();}
static void close() {__out.close();}
} | Java | ["4\n1 2\n2 3\n3 4\n1 2 1 1", "3\n1 2\n2 3\n1 2 3", "4\n1 2\n2 3\n3 4\n1 2 1 2"] | 2 seconds | ["YES\n2", "YES\n2", "NO"] | null | Java 11 | standard input | [
"dp",
"graphs",
"dsu",
"implementation",
"dfs and similar",
"trees"
] | aaca5d07795a42ecab210327c1cf6be9 | The first line contains single integer n (2 ≤ n ≤ 105) — the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 105), denoting the colors of the vertices. | 1,600 | Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. | standard output | |
PASSED | bdb88a6eb431f36907138bd11210359d | train_000.jsonl | 1486042500 | Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci.Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can.Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex.A subtree of some vertex is a subgraph containing that vertex and all its descendants.Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. | 256 megabytes | /*
ID: davidzh8
PROG: subset
LANG: JAVA
*/
import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
import java.lang.*;
// .--------------.
// | Try First One|
// '--------------'
// | .--------------.
// | | |
// V V |
// .--------------. |
// | AC. |<---. |
// '--------------' | |
// (True)| |(False) | |
// .--------' | | |
// | V | |
// | .--------------. | |
// | | Try Again |----' |
// | '--------------' |
// | |
// | .--------------. |
// '->| Try Next One |-------'
// '--------------'
public class timofey {
//Start Stub
static long startTime = System.nanoTime();
static int[] color;
//Globals Go Here
static ArrayList<Integer>[] adj;
//Globals End
public static void main(String[] args) throws IOException {
FastScanner sc = new FastScanner("timofey.in", true);
FastWriter pw = new FastWriter("timofey.out", true);
int N= sc.ni();
adj= new ArrayList[N];
color= new int[N];
for (int x=0;x <N; x++){
adj[x]= new ArrayList<>();
}
for (int x=1; x<N; x++){
int a= sc.ni()-1;
int b= sc.ni()-1;
adj[a].add(b);
adj[b].add(a);
}
for (int x=0;x<N; x++){
color[x]= sc.ni();
}
int conflictedge1=-1;
int conflictedge2=-1;
ArrayDeque<Integer> dq= new ArrayDeque<>();
dq.offer(0);
boolean visited[]= new boolean[N];
while (dq.size()>0){
int cur= dq.poll();
int curcolor= color[cur];
for (int next: adj[cur]){
if (curcolor !=color[next]){
conflictedge1= cur;
conflictedge2= next;
break;
}
if (!visited[next]) {
visited[next]=true;
dq.offer(next);
}
}
}
if (conflictedge1==conflictedge2) {
pw.println("YES");
pw.println(1);
pw.close();
System.exit(0);
}
boolean ans=true;
for (int i: adj[conflictedge1]){
curcolor= color[i];
valid=true;
dfs(i, conflictedge1);
ans= ans&& valid;
}
if (ans) {
pw.println("YES");
pw.println(conflictedge1+1);
pw.close();
}
ans=true;
for (int i: adj[conflictedge2]){
curcolor=color[i];
valid=true;
dfs(i, conflictedge2);
ans= ans&&valid;
}
if (ans) {
pw.println("YES");
pw.println(conflictedge2+1);
pw.close();
}
else pw.println("NO");
/* End Stub */
long endTime = System.nanoTime();
//System.out.println("Execution Time: " + (endTime - startTime) / 1e9 + " s");
pw.close();
}
static int curcolor=-1;
static boolean valid=true;
public static void dfs(int cur, int par){
valid= valid && (color[cur]==curcolor);
for (int i: adj[cur]){
if (i!=par) dfs(i, cur);
}
}
static class Edge implements Comparable<Edge> {
int w;
int a;
int b;
public Edge(int w, int a, int b) {
this.w = w;
this.a = a;
this.b = b;
}
public int compareTo(Edge obj) {
if (obj.w == w) {
if (obj.a == a) {
return b - obj.b;
}
return a - obj.a;
} else return w - obj.w;
}
}
static class Pair implements Comparable<Pair> {
int a;
int b;
public Pair(int a, int b) {
this.a = a;
this.b = b;
}
public int compareTo(Pair obj) {
if (obj.a == a) {
return b - obj.b;
} else return a - obj.a;
}
}
static class SegmentTree {
public long[] arr;
public long[] tree;
public int N;
//Zero initialization
public SegmentTree(int n) {
N = n;
arr = new long[N];
tree = new long[4 * N + 1];
}
public long query(int treeIndex, int lo, int hi, int i, int j) {
// query for arr[i..j]
if (lo > j || hi < i)
return 0;
if (i <= lo && j >= hi)
return tree[treeIndex];
int mid = lo + (hi - lo) / 2;
if (i > mid)
return query(2 * treeIndex + 2, mid + 1, hi, i, j);
else if (j <= mid)
return query(2 * treeIndex + 1, lo, mid, i, j);
long leftQuery = query(2 * treeIndex + 1, lo, mid, i, mid);
long rightQuery = query(2 * treeIndex + 2, mid + 1, hi, mid + 1, j);
// merge query results
return merge(leftQuery, rightQuery);
}
public void update(int treeIndex, int lo, int hi, int arrIndex, long val) {
if (lo == hi) {
tree[treeIndex] = val;
arr[arrIndex] = val;
return;
}
int mid = lo + (hi - lo) / 2;
if (arrIndex > mid)
update(2 * treeIndex + 2, mid + 1, hi, arrIndex, val);
else if (arrIndex <= mid)
update(2 * treeIndex + 1, lo, mid, arrIndex, val);
// merge updates
tree[treeIndex] = merge(tree[2 * treeIndex + 1], tree[2 * treeIndex + 2]);
}
public long merge(long a, long b) {
return (a + b);
}
}
static class djset {
int N;
int[] parent;
// Creates a disjoint set of size n (0, 1, ..., n-1)
public djset(int n) {
parent = new int[n];
N = n;
for (int i = 0; i < n; i++)
parent[i] = i;
}
public int find(int v) {
// I am the club president!!! (root of the tree)
if (parent[v] == v) return v;
// Find my parent's root.
int res = find(parent[v]);
// Attach me directly to the root of my tree.
parent[v] = res;
return res;
}
public boolean union(int v1, int v2) {
// Find respective roots.
int rootv1 = find(v1);
int rootv2 = find(v2);
// No union done, v1, v2 already together.
if (rootv1 == rootv2) return false;
// Attach tree of v2 to tree of v1.
parent[rootv2] = rootv1;
return true;
}
}
static class FastScanner {
public BufferedReader br;
public StringTokenizer st;
public InputStream is;
public FastScanner(String name, boolean debug) throws IOException {
if (debug) {
is = System.in;
} else {
is = new FileInputStream(name);
}
br = new BufferedReader(new InputStreamReader(is), 32768);
st = null;
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int ni() {
return Integer.parseInt(next());
}
public long nl() {
return Long.parseLong(next());
}
public double nd() {
return Double.parseDouble(next());
}
public String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return str;
}
}
static class FastWriter {
public PrintWriter pw;
public FastWriter(String name, boolean debug) throws IOException {
if (debug) {
pw = new PrintWriter(System.out);
} else {
pw = new PrintWriter(new BufferedWriter(new FileWriter(new File(name))));
}
}
public void println(Object text) {
pw.println(text);
}
public void print(Object text) {
pw.print(text);
}
public void close() {
pw.close();
}
public void flush() {
pw.flush();
}
}
}
| Java | ["4\n1 2\n2 3\n3 4\n1 2 1 1", "3\n1 2\n2 3\n1 2 3", "4\n1 2\n2 3\n3 4\n1 2 1 2"] | 2 seconds | ["YES\n2", "YES\n2", "NO"] | null | Java 11 | standard input | [
"dp",
"graphs",
"dsu",
"implementation",
"dfs and similar",
"trees"
] | aaca5d07795a42ecab210327c1cf6be9 | The first line contains single integer n (2 ≤ n ≤ 105) — the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 105), denoting the colors of the vertices. | 1,600 | Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. | standard output | |
PASSED | e32d30c1abd4b9966d2957a3ebcb154d | train_000.jsonl | 1486042500 | Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci.Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can.Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex.A subtree of some vertex is a subgraph containing that vertex and all its descendants.Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class A {
public static int n;
public static int col[];
public static List<Integer> adj[];
public static int edges[][];
public static int nxt = 0;
public static boolean check = false;
public static void main(String[] args)throws IOException {
FastIO sc = new FastIO(System.in);
PrintWriter out = new PrintWriter(System.out);
n = sc.nextInt();
col = new int[n];
edges = new int[n][2];
adj = new ArrayList[n];
for(int i=0; i<n; ++i) {
adj[i] = new ArrayList<>();
}
for(int i=0; i<n-1; ++i) {
int a = sc.nextInt()-1;
int b = sc.nextInt()-1;
edges[i][0] = a;
edges[i][1] = b;
adj[a].add(b);
adj[b].add(a);
}
for(int i=0; i<n; ++i) {
col[i] = sc.nextInt();
}
int curr = -1;
for(int i=0; i<n; ++i) {
if(col[edges[i][0]]!=col[edges[i][1]]) {
curr = i;
}
}
boolean poss = false;
int ans = 0;
if(curr!=-1) {
check = true;
int rt = edges[curr][0];
dfs(rt, rt);
if(check) {
poss = true;
ans = rt;
}
check = true;
rt = edges[curr][1];
dfs(rt, rt);
if(check) {
poss = true;
ans = rt;
}
}else {
poss = true;
}
if(poss) {
System.out.println("YES");
System.out.println(ans+1);
}else {
System.out.println("NO");
}
out.close();
}
public static void dfs(int u, int p) {
for(int v: adj[u]) {
if(v==p) continue;
if(col[v]!=col[u]&&u!=p) {
check = false;
}
dfs(v, u);
}
}
static class FastIO {
InputStream dis;
byte[] buffer = new byte[1 << 17];
int pointer = 0;
public FastIO(String fileName) throws IOException {
dis = new FileInputStream(fileName);
}
public FastIO(InputStream is) throws IOException {
dis = is;
}
int nextInt() throws IOException {
int ret = 0;
byte b;
do {
b = nextByte();
} while (b <= ' ');
boolean negative = false;
if (b == '-') {
negative = true;
b = nextByte();
}
while (b >= '0' && b <= '9') {
ret = 10 * ret + b - '0';
b = nextByte();
}
return (negative) ? -ret : ret;
}
long nextLong() throws IOException {
long ret = 0;
byte b;
do {
b = nextByte();
} while (b <= ' ');
boolean negative = false;
if (b == '-') {
negative = true;
b = nextByte();
}
while (b >= '0' && b <= '9') {
ret = 10 * ret + b - '0';
b = nextByte();
}
return (negative) ? -ret : ret;
}
byte nextByte() throws IOException {
if (pointer == buffer.length) {
dis.read(buffer, 0, buffer.length);
pointer = 0;
}
return buffer[pointer++];
}
String next() throws IOException {
StringBuffer ret = new StringBuffer();
byte b;
do {
b = nextByte();
} while (b <= ' ');
while (b > ' ') {
ret.appendCodePoint(b);
b = nextByte();
}
return ret.toString();
}
}
}
| Java | ["4\n1 2\n2 3\n3 4\n1 2 1 1", "3\n1 2\n2 3\n1 2 3", "4\n1 2\n2 3\n3 4\n1 2 1 2"] | 2 seconds | ["YES\n2", "YES\n2", "NO"] | null | Java 11 | standard input | [
"dp",
"graphs",
"dsu",
"implementation",
"dfs and similar",
"trees"
] | aaca5d07795a42ecab210327c1cf6be9 | The first line contains single integer n (2 ≤ n ≤ 105) — the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 105), denoting the colors of the vertices. | 1,600 | Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. | standard output | |
PASSED | 91639e293d4b64b72362513aec805fd0 | train_000.jsonl | 1486042500 | Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci.Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can.Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex.A subtree of some vertex is a subgraph containing that vertex and all its descendants.Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class A
{
static boolean dfs(int node, int par, ArrayList<Integer> l[]){
boolean ret = true;
for(int adj : l[node]){
if(adj == par)
continue;
boolean flag = dfs(adj, node, l);
ret = ret && flag && (col[node] == col[adj]);
}
return ret;
}
static boolean ok(int node, ArrayList<Integer> l[]){
boolean ret = true;
for(int adj : l[node])
ret = ret && dfs(adj, node, l);
return ret;
}
public static void process(int test_number)throws IOException
{
int n = ni();
col = new int[n + 1];
ArrayList<Integer> l[] = new ArrayList[n + 1];
for(int i = 1; i <= n; i++) l[i] = new ArrayList<>();
for(int i =1; i < n; i++){
int u = ni(), v = ni();
l[u].add(v);
l[v].add(u);
}
for(int i = 1; i <= n; i++)
col[i] = ni();
for(int i = 1; i <= n; i++){
for(int adj : l[i]){
if(col[i] != col[adj]){ //trace(i, adj);
if(ok(i, l)){
System.out.println("YES\n"+i);
return ;
}
if(ok(adj, l)){
System.out.println("YES\n"+adj);
return ;
}
System.out.println("NO");
return ;
}
}
}
System.out.println("YES\n1");
}
static int col[];
static final long mod = (long)1e9+7l;
static FastReader sc;
public static void main(String[]args)throws IOException
{
sc = new FastReader();
long s = System.currentTimeMillis();
int t = 1;
//t = ni();
for(int i = 1; i <= t; i++)
process(i);
System.err.println(System.currentTimeMillis()-s+"ms");
}
static void trace(Object... o){ System.err.println(Arrays.deepToString(o)); };
static int ni()throws IOException{ return Integer.parseInt(sc.next()); }
static long nl()throws IOException{ return Long.parseLong(sc.next()); }
static double nd()throws IOException{ return Double.parseDouble(sc.next()); }
static String nln()throws IOException{ return sc.nextLine(); }
static long gcd(long a, long b)throws IOException{ return (b==0)?a:gcd(b,a%b);}
static int gcd(int a, int b)throws IOException{ return (b==0)?a:gcd(b,a%b); }
static int bit(long n)throws IOException{ return (n==0)?0:(1+bit(n&(n-1))); }
static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br = new BufferedReader(new InputStreamReader(System.in));
}
String next(){
while (st == null || !st.hasMoreElements()){
try{ st = new StringTokenizer(br.readLine()); } catch (IOException e){ e.printStackTrace(); }
}
return st.nextToken();
}
String nextLine(){
String str = "";
try{ str = br.readLine(); } catch (IOException e) { e.printStackTrace(); }
return str;
}
}
}
| Java | ["4\n1 2\n2 3\n3 4\n1 2 1 1", "3\n1 2\n2 3\n1 2 3", "4\n1 2\n2 3\n3 4\n1 2 1 2"] | 2 seconds | ["YES\n2", "YES\n2", "NO"] | null | Java 11 | standard input | [
"dp",
"graphs",
"dsu",
"implementation",
"dfs and similar",
"trees"
] | aaca5d07795a42ecab210327c1cf6be9 | The first line contains single integer n (2 ≤ n ≤ 105) — the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 105), denoting the colors of the vertices. | 1,600 | Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. | standard output | |
PASSED | 97334f9e3b23c8e218c981ace9e2c2ca | train_000.jsonl | 1486042500 | Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci.Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can.Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex.A subtree of some vertex is a subgraph containing that vertex and all its descendants.Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. | 256 megabytes | import java.io.*;
import java.util.*;
public class A {
static FastReader f = new FastReader();
static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args){
int n = f.nextInt();
ArrayList<Integer>[] edge = new ArrayList[n+1];
for(int i=0;i<=n;i++) {
edge[i] = new ArrayList<>();
}
Dsu dsu = new Dsu(n+1);
for(int i=1;i<n;i++) {
int a = f.nextInt(), b = f.nextInt();
edge[a].add(b);
edge[b].add(a);
}
int[] color = new int[n+1];
for(int i=1;i<=n;i++) {
color[i] = f.nextInt();
}
for(int i=1;i<=n;i++) {
for(int j : edge[i]) {
if(color[i] == color[j]) {
dsu.join(i, j);
}
}
}
HashSet<Integer> set = new HashSet<>();
ArrayList<Integer> colorList = new ArrayList<>();
for(int i=1;i<=n;i++) {
int loc = dsu.getPar(i);
if(!set.contains(loc)) {
set.add(loc);
colorList.add(loc);
}
}
for(int i=1;i<=n;i++) {
Set<Integer> ot = new TreeSet<>();
for(int j : edge[i]) {
ot.add(dsu.getPar(j));
}
ot.remove(dsu.getPar(i));
if(ot.size() + 1 == colorList.size()) {
System.out.println("YES");
System.out.println(i);
return;
}
}
System.out.println("NO");
}
static class Dsu {
int[] par;
int[] size;
Dsu(int n) {
par = new int[n];
size = new int[n];
for(int i=0;i<n;i++) {
par[i] = i;
size[i] = 1;
}
}
int getPar(int x) {
if(par[x] == x) {
return x;
}
return par[x] = getPar(par[x]);
}
void join(int a, int b) {
a = getPar(a);
b = getPar(b);
if(a != b) {
if(size[a] < size[b]) {
int temp = a;
a = b;
b = temp;
}
size[a] += size[b];
par[b] = a;
}
}
}
//fast input reader
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
} | Java | ["4\n1 2\n2 3\n3 4\n1 2 1 1", "3\n1 2\n2 3\n1 2 3", "4\n1 2\n2 3\n3 4\n1 2 1 2"] | 2 seconds | ["YES\n2", "YES\n2", "NO"] | null | Java 11 | standard input | [
"dp",
"graphs",
"dsu",
"implementation",
"dfs and similar",
"trees"
] | aaca5d07795a42ecab210327c1cf6be9 | The first line contains single integer n (2 ≤ n ≤ 105) — the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 105), denoting the colors of the vertices. | 1,600 | Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. | standard output | |
PASSED | 2f9e2c3657862907bb82b86bf90e398c | train_000.jsonl | 1486042500 | Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci.Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can.Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex.A subtree of some vertex is a subgraph containing that vertex and all its descendants.Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.StringTokenizer;
import java.util.TreeSet;
import java.lang.Integer;
public class Main {
static ArrayList<Integer>adj[];
static PrintWriter out=new PrintWriter(System.out);
public static int mod = 1000000007;
static int notmemo[][][][];
static int k;
static int a[];
static int b[];
static int m;
static char c[];
static int trace[];
static int h;
static int x;
static int ans1;
static int ans2;
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
n=sc.nextInt();
adj=new ArrayList[n];
for (int i = 0; i <n; i++) {
adj[i]=new ArrayList();
}
for (int i = 0; i < n-1; i++) {
int u=sc.nextInt()-1;
int v=sc.nextInt()-1;
adj[u].add(v);
adj[v].add(u);
}
a=new int[n];
ans1=0;
ans2=0;
boolean f1=true;
for (int i = 0; i <n;i++) {
a[i]=sc.nextInt();
}
label: for (int i = 0; i <adj.length; i++) {
for(int v:adj[i]) {
if(a[v]!=a[i]) {
ans1=v;
ans2=i;
}
}
}
//System.out.println(ans1+" "+ans2);
// System.out.println(ans1+" "+ans2);
vis=new boolean[n];
if(dfs(ans1, a[ans1])) {
System.out.println("YES");
System.out.println(ans1+1);
return;
}
vis=new boolean[n];
ans1=ans2;
if(dfs(ans1, a[ans1])) {
System.out.println("YES");
System.out.println(ans1+1);
return;
}
System.out.println("NO");
}
static boolean dfs(int u,int color) {
vis[u]=true;
boolean f=true;
for(int v:adj[u]) {
if(u!=ans1&&a[v]!=a[u]&&v!=ans1) {
// System.out.println(u+" "+v+" "+a[u]+" "+a[v]+" "+ans1);
return false;
}
if(!vis[v]) {
f&=dfs(v,a[v]);
}
}
return f;
}
static String s;
static boolean isOn(int S, int j) { return (S & 1 << j) != 0; }
static int y, d;
static void extendedEuclid(int a, int b)
{
if(b == 0) { x = 1; y = 0; d = a; return; }
extendedEuclid(b, a % b);
int x1 = y;
int y1 = x - a / b * y;
x = x1; y = y1;
}
static long dp(int i,int count,int state) {
if(count>k) {
return 0;
}
if(i==n) {
if(count==k) {
return 1;
}
else
return 0;
}
if(memo[i][count][state]!=-1) {
return memo[i][count][state];
}
long total=0;
for (int j = 0; j <10; j++) {
if(state==0&&j>Integer.parseInt(""+c[i])) {
continue;
}
else if(state==0&&j==Integer.parseInt(""+c[i])) {
if(j==0)
total+=dp(i+1,count,0);
else
total+=dp(i+1,count+1,0);
}
else if(j==0) {
total+=dp(i+1,count,1);
}
else {
total+=dp(i+1,count+1,1);
}
}
return memo[i][count][state]=total;
}
static boolean f=true;
static class SegmentTree { // 1-based DS, OOP
int N; //the number of elements in the array as a power of 2 (i.e. after padding)
int[] array, sTree, lazy;
SegmentTree(int[] in)
{
array = in; N = in.length - 1;
sTree = new int[N*4]; //no. of nodes = 2*N - 1, we add one to cross out index zero
lazy = new int[N*4];
// build(1,1,N);
}
void build(int node, int b, int e) // O(n)
{
if(b == e)
sTree[node] = array[b];
else
{
int mid = b + e >> 1;
build(node<<1,b,mid);
build(node<<1|1,mid+1,e);
sTree[node] = sTree[node<<1]&sTree[node<<1|1];
}
}
void update_point(int index, int val) // O(log n)
{
index += N - 1;
sTree[index] += val;
while(index>1)
{
index >>= 1;
sTree[index] = sTree[index<<1] + sTree[index<<1|1];
}
}
void update_range(int i, int j,int val) // O(log n)
{
update_range(1,1,N,i,j,val);
}
void update_range(int node, int b, int e, int i, int j,int val)
{
if(i > e || j < b)
return;
if(b >= i && e <= j)
{
sTree[node]|= val;
lazy[node]|=val;
//LAZY LAZY
}
else
{
int mid = b + e >> 1;
propagate(node, b, mid, e);
update_range(node<<1,b,mid,i,j,val);
update_range(node<<1|1,mid+1,e,i,j,val);
sTree[node] = sTree[node<<1]&sTree[node<<1|1];
}
}
void propagate(int node, int b, int mid, int e)
{
lazy[node<<1] |= lazy[node];
lazy[(node<<1)|1] |= lazy[node];
sTree[node<<1] |= lazy[node];
sTree[(node<<1)|1] |= lazy[node];
lazy[node] = 0;
}
int query(int i, int j)
{
return query(1,1,N,i,j);
}
int query(int node, int b, int e, int i, int j) // O(log n)
{
if(i>e || j <b)
return -1;
if(b>= i && e <= j)
return sTree[node];
int mid = b + e >> 1;
propagate(node, b, mid, e);
int q1 = query(node<<1,b,mid,i,j);
int q2 = query(node<<1|1,mid+1,e,i,j);
return q1 &q2;
}
}
static long memo[][][];
static long nCr1(int n , int k)
{
if(n < k)
return 0;
if(k == 0 || k == n)
return 1;
if(comb[n][k] != -1)
return comb[n][k];
if(n - k < k)
return comb[n][k] = nCr1(n, n - k);
return comb[n][k] = ((nCr1(n - 1, k - 1)%mod) +( nCr1(n - 1, k)%mod))%mod;
}
static class UnionFind {
int[] p, rank, setSize;
int numSets;
int max[];
public UnionFind(int N)
{
max=new int[N];
p = new int[numSets = N];
rank = new int[N];
setSize = new int[N];
for (int i = 0; i < N; i++) { p[i] = i; setSize[i] = 1;
max[i]=i;
}
}
public int findSet(int i) { return p[i] == i ? i : (p[i] = findSet(p[i])); }
public boolean isSameSet(int i, int j) { return findSet(i) == findSet(j); }
public void unionSet(int i, int j)
{
if (isSameSet(i, j))
return;
numSets--;
int x = findSet(i), y = findSet(j);
if(rank[x] > rank[y]) { p[y] = x; setSize[x] += setSize[y];
max[x]=Math.max(max[x], max[y]);
}
else
{ p[x] = y; setSize[y] += setSize[x];
if(rank[x] == rank[y]) rank[y]++;
max[y]=Math.max(max[x],max[y]);
}
}
private int getmax(int j) {
return max[findSet(j)];
}
public int numDisjointSets() { return numSets; }
public int sizeOfSet(int i) { return setSize[findSet(i)]; }
}
/**private static void trace(int i, int time) {
if(i==n)
return;
long ans=dp(i,time);
if(time+a[i].t<a[i].burn&&(ans==dp(i+1,time+a[i].t)+a[i].cost)) {
trace(i+1, time+a[i].t);
l1.add(a[i].idx);
return;
}
trace(i+1,time);
}**/
static class incpair implements Comparable<incpair>
{
int a; long b;
int idx;
incpair(int a, long dirg,int i) {this.a = a; b = dirg; idx=i; }
public int compareTo(incpair e){ return (int) (b - e.b); }
}
static class decpair implements Comparable<decpair>
{
int a; long b;int idx;
decpair(int a, long dirg,int i) {this.a = a; b = dirg; idx=i;}
public int compareTo(decpair e){ return (int) (e.b- b); }
}
static long allpowers[];
static class Quad implements Comparable<Quad>{
int u;
int v;
char state;
int turns;
public Quad(int i, int j, char c, int k) {
u=i;
v=j;
state=c;
turns=k;
}
public int compareTo(Quad e){ return (int) (turns - e.turns); }
}
static long dirg[][];
static Edge[] driver;
static int n;
static class Edge implements Comparable<Edge>
{
int node; long cost;
Edge(int a, long dirg) { node = a; cost = dirg; }
public int compareTo(Edge e){ return (int) (cost - e.cost); }
}
static long manhatandistance(long x,long x2,long y,long y2) {
return Math.abs(x-x2)+Math.abs(y-y2);
}
static long fib[];
static long fib(int n) {
if(n==1||n==0) {
return 1;
}
if(fib[n]!=-1) {
return fib[n];
}
else
return fib[n]= ((fib(n-2)%mod+fib(n-1)%mod)%mod);
}
static class Pair {
int a, b;
Pair(int x, int y) {
a = x;
b = y;
}
}
static long[][] comb;
static class Triple implements Comparable<Triple>{
int l;
int r;
long cost;
int idx;
public Triple(int a,int b,long l1,int l2) {
l=a;
r=b;
cost=l1;
idx=l2;
}
public int compareTo(Triple x)
{
if(l!=x.l || idx==x.idx)
return l-x.l;
return -idx;
}
}
static TreeSet<Long> primeFactors(long N) // O(sqrt(N) / ln sqrt(N))
{
TreeSet<Long> factors = new TreeSet<Long>(); //take abs(N) in case of -ve integers
int idx = 0, p = primes.get(idx);
while(p * p <= N)
{
while(N % p == 0) { factors.add((long) p); N /= p; }
if(primes.size()>idx+1)
p = primes.get(++idx);
else
break;
}
if(N != 1) // last prime factor may be > sqrt(N)
factors.add(N); // for integers whose largest prime factor has a power of 1
return factors;
}
static boolean visited[];
/**static int bfs(int s)
{
Queue<Integer> q = new LinkedList<Integer>();
q.add(s);
int count=0;
int maxcost=0;
int dist[]=new int[n];
dist[s]=0;
while(!q.isEmpty())
{
int u = q.remove();
if(dist[u]==k) {
break;
}
for(Pair v: adj[u])
{
maxcost=Math.max(maxcost, v.cost);
if(!visited[v.v]) {
visited[v.v]=true;
q.add(v.v);
dist[v.v]=dist[u]+1;
maxcost=Math.max(maxcost, v.cost);
}
}
}
return maxcost;
}**/
public static boolean FindAllElements(int n, int k) {
int sum = k;
int[] A = new int[k];
Arrays.fill(A, 0, k, 1);
for (int i = k - 1; i >= 0; --i) {
while (sum + A[i] <= n) {
sum += A[i];
A[i] *= 2;
}
}
if(sum==n) {
return true;
}
else
return false;
}
static boolean vis2[][];
static boolean f2=false;
static long[][] matMul(long[][] a2, long[][] b, int p, int q, int r) //C(p x r) = A(p x q) x (q x r) -- O(p x q x r)
{
long[][] C = new long[p][r];
for(int i = 0; i < p; ++i) {
for(int j = 0; j < r; ++j) {
for(int k = 0; k < q; ++k) {
C[i][j] = (C[i][j]+(a2[i][k]%mod * b[k][j]%mod))%mod;
C[i][j]%=mod;
}
}
}
return C;
}
static ArrayList<Pair> a1[];
static int memo1[];
static boolean vis[];
static TreeSet<Integer> set=new TreeSet<Integer>();
static long modPow(long ways, long count, long mod) // O(log e)
{
ways %= mod;
long res = 1;
while(count > 0)
{
if((count & 1) == 1)
res = (res * ways) % mod;
ways = (ways * ways) % mod;
count >>= 1;
}
return res%mod;
}
static long gcd(long ans,long b) {
if(b==0) {
return ans;
}
return gcd(b,ans%b);
}
static int[] isComposite;
static int[] valid;
static ArrayList<Integer> primes;
static ArrayList<Integer> l;
static void sieve(int N) // O(N log log N)
{
isComposite = new int[N+1];
isComposite[0] = isComposite[1] = 1; // 0 indicates a prime number
primes = new ArrayList<Integer>();
l=new ArrayList<>();
valid=new int[N+1];
for (int i = 2; i <= N; ++i) //can loop till i*i <= N if primes array is not needed O(N log log sqrt(N))
if (isComposite[i] == 0) //can loop in 2 and odd integers for slightly better performance
{
primes.add(i);
l.add(i);
valid[i]=1;
for (int j = i*2; j <=N; j +=i) { // j = i * 2 will not affect performance too much, may alter in modified sieve
isComposite[j] = 1;
}
}
for(int i=0 ; i<primes.size() ; i++) {
for(int j:primes) {
if(primes.get(i)*j>N) {
break;
}
valid[primes.get(i)*j]=1;
}
}
}
public static int[] schuffle(int[] a2) {
for (int i = 0; i < a2.length; i++) {
int x=(int)(Math.random()*a2.length);
int temp=a2[x];
a2[x]=a2[i];
a2[i]=temp;
}
return a2;
}
static int V;
static long INF=(long) 1E16;
static class Edge2
{
int node;
long cost;
long next;
Edge2(int a, int c,Long long1) { node = a; cost = long1; next=c;}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public Scanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public Long nextLong() throws IOException {
return Long.parseLong(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
} | Java | ["4\n1 2\n2 3\n3 4\n1 2 1 1", "3\n1 2\n2 3\n1 2 3", "4\n1 2\n2 3\n3 4\n1 2 1 2"] | 2 seconds | ["YES\n2", "YES\n2", "NO"] | null | Java 11 | standard input | [
"dp",
"graphs",
"dsu",
"implementation",
"dfs and similar",
"trees"
] | aaca5d07795a42ecab210327c1cf6be9 | The first line contains single integer n (2 ≤ n ≤ 105) — the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 105), denoting the colors of the vertices. | 1,600 | Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. | standard output | |
PASSED | f001621bc3daa4d6e74ec223a427d400 | train_000.jsonl | 1486042500 | Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci.Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can.Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex.A subtree of some vertex is a subgraph containing that vertex and all its descendants.Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.BigInteger;
public class GFG {
static class edge{
int s,d,w;
public edge(int s,int d,int w)
{
this.s=s;
this.d=d;
this.w=w;
}
}
static class graph{
int v;
LinkedList<edge> li[];
boolean visit[];
boolean visit1[];
int arr[];
int color[];
int a=0,b=0;
boolean check=false;
public graph(int v)
{
this.v=v;
visit=new boolean[v];
visit1=new boolean[v];
arr=new int[v];
color=new int[2];
Arrays.fill(arr,-1);
li=new LinkedList[v];
for(int i=0;i<v;i++)
li[i]=new LinkedList<>();
}
public void addedge(int x,int y,int w)
{
edge e=new edge(x,y,w);
li[x].add(e);
edge e1=new edge(y,x,w);
li[y].add(e1);
}
public void removeedge(int x,int y,int w)
{
Iterator<edge> it =li[x].iterator();
while (it.hasNext()) {
if (it.next().d == y) {
it.remove();
break;
}
}
Iterator<edge> it1 =li[y].iterator();
while (it1.hasNext()) {
if (it1.next().d == x) {
it1.remove();
return;
}
}
}
public boolean hasEdge(int i, int j) {
if(li[i].contains(j)||li[j].contains(i))
return true;
return false;
}
static long power(long x, long y, long p)
{
// Initialize result
long res = 1;
// Update x if it is more
// than or equal to p
x = x % p;
while (y > 0)
{
// If y is odd, multiply x
// with result
if((y & 1)==1)
res = (res * x) % p;
// y must be even now
// y = y / 2
y = y >> 1;
x = (x * x) % p;
}
return res;
}
public void fill()
{
Arrays.fill(visit,false);
}
public boolean dfs(int s,int t,HashSet<Integer> h,int f)
{
visit[s]=true;
h.add(arr[s]);
Iterator<edge> i=li[s].listIterator();
while(i.hasNext()){int n=i.next().d;
if(!visit[n]&&n!=t)
if(!dfs(n,t,h,f)){f=1;break;}
}
if(f==1)
return false;
if(h.size()>1)
return false;
return true;
}
public void get(int [] mat,int p,int q)
{
for(int i=0;i<v;i++)
arr[i]=mat[i];
a=p;b=q;
}
public void print()
{
PrintWriter out= new PrintWriter(System.out);
int p=0,q=0;
int f=0;
HashSet<Integer> h=new HashSet<Integer>();
Iterator<edge> i1=li[a].listIterator();
while(i1.hasNext()){int n=i1.next().d;h.clear();
if(!dfs(n,a,h,0)){f=1;break;}
}
h.clear();
if(f==0){out.println("YES");
out.println(a+1);
}
if(f==1){
f=0;
fill();
Iterator<edge> i2=li[b].listIterator();
while(i2.hasNext()){int n=i2.next().d;h.clear();
if(!dfs(n,b,h,0)){f=1;out.println("NO");break;}
}
if(f==0){
out.println("YES");
out.println(b+1);
}
}
out.flush();
out.close();
}
}
public static void main (String[] args)throws IOException {
Reader sc=new Reader();
//Scanner sc=new Scanner(System.in);
PrintWriter out= new PrintWriter(System.out);
int n=sc.nextInt();
//int m=sc.nextInt();
graph g=new graph(n);
int a[][]=new int[n][2];
for(int i=0;i<n-1;i++)
{
int x=sc.nextInt();
int y=sc.nextInt();
g.addedge(x-1,y-1,0);
a[i][0]=x-1;
a[i][1]=y-1;
}
int arr[]=new int[n];
for(int i=0;i<n;i++)
arr[i]=sc.nextInt();
int p=0,q=0;
for(int i=0;i<n;i++)
{
if(arr[a[i][0]]!=arr[a[i][1]]){
p=a[i][0];q=a[i][1];break;}
}
g.get(arr,p,q);
g.print();
}
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
} | Java | ["4\n1 2\n2 3\n3 4\n1 2 1 1", "3\n1 2\n2 3\n1 2 3", "4\n1 2\n2 3\n3 4\n1 2 1 2"] | 2 seconds | ["YES\n2", "YES\n2", "NO"] | null | Java 11 | standard input | [
"dp",
"graphs",
"dsu",
"implementation",
"dfs and similar",
"trees"
] | aaca5d07795a42ecab210327c1cf6be9 | The first line contains single integer n (2 ≤ n ≤ 105) — the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 105), denoting the colors of the vertices. | 1,600 | Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. | standard output | |
PASSED | 8547a652f1c69eee0fd7ac311c32bacc | train_000.jsonl | 1583246100 | This is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem, Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with $$$n$$$ vertices. The tree is rooted at vertex $$$r$$$, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices $$$u$$$ and $$$v$$$, and it'll return a vertex $$$w$$$, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most $$$\lfloor \frac{n}{2} \rfloor$$$ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location? | 256 megabytes | import java.util.*;
import java.io.*;
public class D1305{
static int n;
static ArrayList<Integer>[] adjList;
static boolean[] check;
static boolean[] vis;
static int global;
public static void clean(int u, int p) {
if(u == p)
return;
vis = new boolean[n];
int x = getNext(u, p);
global = 1;
vis = new boolean[n];
dfs(p, x);
}
public static int getNext(int u, int p) {
vis[u] = true;
int ans = (int)1e9;
for(int v : adjList[u]) {
if(!vis[v]) {
if(v == p) {
return u;
} else {
ans = Math.min(ans, getNext(v, p));
}
}
}
return ans;
}
public static void dfs(int p, int x) {
vis[p] = true;
if(global == 1) {
global++;
for(int v : adjList[p]) {
if(v == x && !vis[v]) {
dfs(v, x);
break;
}
}
} else {
check[p] = true;
for(int v : adjList[p]) {
if(!vis[v]) {
dfs(v, x);
}
}
}
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
//BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
StringTokenizer st;
n = sc.nextInt();
adjList = new ArrayList[n];
for(int i = 0; i < n; i++)
adjList[i] = new ArrayList<Integer>();
for(int i = 0; i < n - 1; i++) {
int u = sc.nextInt() - 1, v = sc.nextInt() - 1;
adjList[u].add(v);
adjList[v].add(u);
}
PriorityQueue<Integer> qu = new PriorityQueue<>((y, x) -> Integer.compare(adjList[y].size(), adjList[x].size()));
for(int i = 0; i < n; i++)
qu.add(i);
check = new boolean[n];
int c = n / 2;
while(c-->0) {
int a = -1, b = -1;
while(!qu.isEmpty()) {
int x = qu.poll();
if(check[x])
continue;
else {
a = x;
break;
}
}
while(!qu.isEmpty()) {
int x = qu.poll();
if(check[x])
continue;
else {
b = x;
break;
}
}
if(a == -1 || b == -1)
break;
System.out.println("? " + (a + 1) + " " + (b + 1));
System.out.flush();
int w = sc.nextInt() - 1;
if(w == -1)
return;
clean(a, w);
clean(b, w);
if(!check[a])
qu.add(a);
else
qu.add(b);
}
for(int j = 0; j < n; j++)
if(!check[j]) {
System.out.println("! " + (j + 1));
System.out.flush();
break;
}
}
}
| Java | ["6\n1 4\n4 2\n5 3\n6 3\n2 3\n\n3\n\n4\n\n4"] | 1 second | ["? 5 6\n\n? 3 1\n\n? 1 2\n\n! 4"] | NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test: | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"trees",
"interactive"
] | a291ee66980d8b5856b24d1541e66fd0 | null | 1,900 | null | standard output | |
PASSED | 95ee8d2962aae1b0241587b42af5f4eb | train_000.jsonl | 1583246100 | This is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem, Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with $$$n$$$ vertices. The tree is rooted at vertex $$$r$$$, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices $$$u$$$ and $$$v$$$, and it'll return a vertex $$$w$$$, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most $$$\lfloor \frac{n}{2} \rfloor$$$ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location? | 256 megabytes | /*
D A R K L _ _ O R D D A
K / | | \ L O R D
A R _ / | | \ _ K L O R
D A R K _ / | _ | \ _ L O R D D
R K L _ / _ | _ | \\ | _ \ O R D D
R K _ / _ | _ | \ \ | _ \ L O R
D A R _ / _ / | / / \ \ | \ _ \ _ K L O
D D _ / _ / | / / \ \ | \ _ \ _ A
K _ / _ / | / / _ \ \ | \ _ \ _ L O R
D A _ / _ / | / / _ \ \ | \ _ \ _ R K
_ / _ / | | | | \ (O) / | | \ _ \ _ O
D _ / _ / | | | | \ / | | \ _ \ _ D
A / _ / | | | \ | \ _ \|/ / | | | \ _ \
K / _ / | | | \ | \ _ V / | | | \ _ \ L
/ / | | | \ _ / \ _ _ / | | | \ \
/ / | | | | | | | \ \
/ / | | | \ \ ROWECHEN / / | | | \ \
/ / _ _ | | | \ \ ZHONG / / | | | _ _ \ \
/ / _ / \ | | | | \ / \ \ / / \ / | | | | / \ _ \ \
/ / _ / \ | | | | \ \ / / | | | | / \ _ \ \
/ / / \ \ \ \ / / \ \ / / / / \ \ \
\ / / \ \ \ \ / / \ \ / / / / \ \ /
\|/ \|/ | | | \|/ \|/
L O \|/ | | | | \|/ R D
A R K L / _ | | | _ \ O R D D A R
L O R / _ | | | _ \ D D A R
L O R D / / / _ | _ | | \ _ \ D A R K
O R D / / / _ | | _ | | \ _ \ D A R K L
R D D A R | / / | | / | | \ / | | \ | K L O R D
A R K | / / | | / | | \ / | | \ | L O R
D A R / \ / | | | / | | / \ / K L O R
D D A / \ / | | | / | | / \/ R K L O
R D D / | / \ | \ / A R K L O R
D A R K L / | / \ | \/ O R D D
R K L O R D \ / | D A R K L O R
D A R \/ | K L O R D D
*/
//TEMPLATE V2
import java.io.*;
import java.util.*;
import java.math.*;
public class D1305 {
//Solution goes below: ------------------------------------
static void mark(int v, int p){
m[v] = true;
mlen+=1;
for(int i:tree.get(v)) if (i != p) mark(i, v);
}
static Arr<Arr<Integer>> tree;
static boolean[] m;
static int mlen;
public static void solution() throws IOException{
int n = nextInt();
tree = new Arr<>();
m = new boolean[n+1];
mlen = 0;
for(int i=0;i<=n;i++){
tree.add(new Arr<>());
}
for(int i=0;i<n-1;i++){
int x = nextInt();
int y = nextInt();
tree.get(x).add(y);
tree.get(y).add(x);
}
int last = 1;
while(mlen<n-2){//While there's more than 2 vertices left.
int d0;
int d1 = tree.get(last).get(0);
int d2;
if(tree.get(d1).size()==1) {
d2 = tree.get(last).get(1);
d0 = d1;
d1 = last;
}else{
d2 = tree.get(d1).get(0);
if(d2==last){
d2 = tree.get(d1).get(1);
}
d0 = last;
}
//Now we have d0 -- d1 -- d2.
println(String.format("? %d %d",d0, d2));
flush();
last = nextInt();
if(last==d0){
mark(d1,d0);
tree.get(d0).remove(new Integer(d1));
}else if(last==d1){
mark(d2, d1);
mark(d0, d1);
tree.get(d1).remove(new Integer(d0));
tree.get(d1).remove(new Integer(d2));
}else if(last==d2){
mark(d1,d2);
tree.get(d2).remove(new Integer(d1));
}else{
//Debug.
println("! 0");
flush();
return;
}
}
if(mlen==n-2){
println(String.format("? %d %d", last,tree.get(last).get(0)));
flush();
last = nextInt();
}
println(String.format("! %d",last));
flush();
}
//Solution goes above: ------------------------------------
public static final String IN_FILE = "";
public static final String OUT_FILE = "";
//-------------------- ------------------------------------
//IO
public static BufferedReader br;
public static StringTokenizer st;
public static BufferedWriter bw;
public static void main(String[] args) throws IOException{
if(IN_FILE==""){
br = new BufferedReader(new InputStreamReader(System.in));
}else{
try {
br = new BufferedReader(new FileReader(IN_FILE));
} catch (FileNotFoundException e) {
br = new BufferedReader(new InputStreamReader(System.in));
}
}
if (OUT_FILE==""){
bw = new BufferedWriter(new OutputStreamWriter(System.out));
}else{
try {
bw = new BufferedWriter (new FileWriter(OUT_FILE) );
} catch (FileNotFoundException e) {
bw = new BufferedWriter(new OutputStreamWriter(System.out));
}
}
solution();
bw.close();//Flushes too.
}
public static String nextToken() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public static String nextLine() {
st = null;
try {
return br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static int nextInt() {
return Integer.parseInt(nextToken());
}
public static long nextLong() {
return Long.parseLong(nextToken());
}
public static double nextDouble() {
return Double.parseDouble(nextToken());
}
public static void println(Object s) throws IOException{
bw.write(s.toString()+"\n");
}
public static void println() throws IOException{
bw.newLine();
}
public static void print(Object s) throws IOException{
bw.write(s.toString());
}
public static void flush() throws IOException{//Useful for debug
bw.flush();
}
//Other
public static class Arr<T> extends ArrayList<T> {} //I hate typing ArrayList
} | Java | ["6\n1 4\n4 2\n5 3\n6 3\n2 3\n\n3\n\n4\n\n4"] | 1 second | ["? 5 6\n\n? 3 1\n\n? 1 2\n\n! 4"] | NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test: | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"trees",
"interactive"
] | a291ee66980d8b5856b24d1541e66fd0 | null | 1,900 | null | standard output | |
PASSED | 88b10a8a7968706fe6d4519825458d28 | train_000.jsonl | 1583246100 | This is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem, Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with $$$n$$$ vertices. The tree is rooted at vertex $$$r$$$, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices $$$u$$$ and $$$v$$$, and it'll return a vertex $$$w$$$, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most $$$\lfloor \frac{n}{2} \rfloor$$$ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location? | 256 megabytes | import java.io.*;
import java.util.*;
/*
Прокрастинирую
*/
public class Main {
static FastReader in;
static PrintWriter out;
static Random rand = new Random();
static final int INF = (int) (1e9 + 10);
static final int MOD = (int) (1e9 + 7);
static final int N = (int) (4e5 + 5);
static final int LOGN = 20;
static TreeSet<Integer>[] g;
static TreeSet<Integer> s;
static int ask(int v, int u) {
out.printf("? %d %d\n", v + 1, u + 1);
out.flush();
return in.nextInt() - 1;
}
static void solve() {
int n = in.nextInt();
g = new TreeSet[n];
Arrays.setAll(g, gi -> new TreeSet<>());
for (int i = 0; i < n - 1; i++) {
int v = in.nextInt() - 1;
int u = in.nextInt() - 1;
g[v].add(u);
g[u].add(v);
}
s = new TreeSet<>((o1, o2) -> {
if (g[o1].size() == g[o2].size()) {
return Integer.compare(o1, o2);
}
return Integer.compare(g[o1].size(), g[o2].size());
});
for (int i = 0; i < n; i++) {
s.add(i);
}
int ans = 0;
for (int i = 0; i < n / 2; i++) {
int v1 = s.pollFirst();
int v2 = s.pollFirst();
int v3 = ask(v1, v2);
if (v3 == v1 || v3 == v2) {
ans = v3;
break;
}
int u1 = g[v1].pollFirst();
s.remove(u1);
g[u1].remove(v1);
s.add(u1);
int u2 = g[v2].pollFirst();
s.remove(u2);
g[u2].remove(v2);
s.add(u2);
if (s.size() == 1) {
ans = s.pollFirst();
break;
}
}
out.printf("! %d\n", ans + 1);
}
public static void main(String[] args) throws FileNotFoundException {
in = new FastReader(System.in);
// in = new FastReader(new FileInputStream("input.txt"));
out = new PrintWriter(System.out);
// out = new PrintWriter(new FileOutputStream("output.txt"));
int q = 1;
// q = in.nextInt();
while (q-- > 0) {
solve();
}
out.close();
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
FastReader(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
Integer nextInt() {
return Integer.parseInt(next());
}
Long nextLong() {
return Long.parseLong(next());
}
Double nextDouble() {
return Double.parseDouble(next());
}
String next() {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(nextLine());
}
return st.nextToken();
}
String nextLine() {
String s = "";
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return s;
}
}
} | Java | ["6\n1 4\n4 2\n5 3\n6 3\n2 3\n\n3\n\n4\n\n4"] | 1 second | ["? 5 6\n\n? 3 1\n\n? 1 2\n\n! 4"] | NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test: | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"trees",
"interactive"
] | a291ee66980d8b5856b24d1541e66fd0 | null | 1,900 | null | standard output | |
PASSED | cae1ab3c4e44e5f494cf5e6891260618 | train_000.jsonl | 1583246100 | This is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem, Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with $$$n$$$ vertices. The tree is rooted at vertex $$$r$$$, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices $$$u$$$ and $$$v$$$, and it'll return a vertex $$$w$$$, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most $$$\lfloor \frac{n}{2} \rfloor$$$ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location? | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.PrintStream;
import java.util.PriorityQueue;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.AbstractCollection;
import java.util.List;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
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);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
OutputWriter out;
InputReader in;
public void solve(int testNumber, InputReader in, OutputWriter out) {
this.out = out;
this.in = in;
int N = in.nextInt();
Node[] graph = new Node[N];
for (int i = 0; i < N; i++) {
graph[i] = new Node(i);
}
for (int i = 0; i < N - 1; i++) {
int u = in.nextInt() - 1, v = in.nextInt() - 1;
graph[u].addEdge(v);
graph[v].addEdge(u);
}
PriorityQueue<Node> queue = new PriorityQueue<>();
for (int i = 0; i < N; i++) {
if (graph[i].degree == 1) {
queue.add(graph[i]);
}
}
int maxQuery = N / 2;
boolean processed[] = new boolean[N];
while (maxQuery > 0) {
Node u = queue.poll();
if (queue.isEmpty()) {
confirm(u.index);
return;
}
while (!queue.isEmpty() && processed[u.index]) {
u = queue.poll();
}
Node v = queue.poll();
while (!queue.isEmpty() && (v.index == u.index || processed[v.index])) {
v = queue.poll();
}
if (v.index == u.index) {
confirm(v.index);
return;
}
int w = query(u, v);
if (u.degree <= 1) {
processed[u.index] = true;
}
if (v.degree <= 1) {
processed[v.index] = true;
}
if (w == u.index || w == v.index) {
confirm(w);
return;
}
for (int x : u.edges) {
graph[x].degree--;
if (graph[x].degree <= 1 && !processed[x]) {
queue.add(graph[x]);
}
}
for (int x : v.edges) {
graph[x].degree--;
if (graph[x].degree <= 1 && !processed[x]) {
queue.add(graph[x]);
}
}
maxQuery--;
}
confirm(queue.poll().index);
}
public int query(Node u, Node v) {
System.out.println("? " + (u.index + 1) + " " + (v.index + 1));
int w = in.nextInt() - 1;
return w;
}
public void confirm(int u) {
u++;
System.out.println("! " + u);
out.close();
}
class Node implements Comparable<Node> {
int index;
List<Integer> edges;
int degree;
public Node(int index) {
edges = new ArrayList<>();
degree = 0;
this.index = index;
}
public void addEdge(int v) {
edges.add(v);
degree++;
}
public int compareTo(Node a) {
if (this.degree != a.degree) {
return this.degree - a.degree;
}
return this.index - a.index;
}
}
}
static class OutputWriter {
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 close() {
writer.close();
}
}
static class InputReader {
BufferedReader in;
StringTokenizer tokenizer = null;
public InputReader(InputStream inputStream) {
in = new BufferedReader(new InputStreamReader(inputStream));
}
public String next() {
try {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(in.readLine());
}
return tokenizer.nextToken();
} catch (IOException e) {
return null;
}
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["6\n1 4\n4 2\n5 3\n6 3\n2 3\n\n3\n\n4\n\n4"] | 1 second | ["? 5 6\n\n? 3 1\n\n? 1 2\n\n! 4"] | NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test: | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"trees",
"interactive"
] | a291ee66980d8b5856b24d1541e66fd0 | null | 1,900 | null | standard output | |
PASSED | a38b612dab0fccfe977fd1dad3184a55 | train_000.jsonl | 1583246100 | This is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem, Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with $$$n$$$ vertices. The tree is rooted at vertex $$$r$$$, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices $$$u$$$ and $$$v$$$, and it'll return a vertex $$$w$$$, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most $$$\lfloor \frac{n}{2} \rfloor$$$ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location? | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class Main {
public static void main(String[] args) throws IOException {
PrintWriter out = new PrintWriter(System.out);
//Scanner sc = new Scanner();
Reader in = new Reader();
Main solver = new Main();
solver.solve(out, in);
out.flush();
out.close();
}
static int INF = (int)1e9;
static int maxn = 2*(int)1e5+5;
static int mod= 1000000321 ;
static int n,m,k,t,q,d,p;
static ArrayList<Integer> adj[];
static boolean[] vis;
static int start;
void solve(PrintWriter out, Reader in) throws IOException{
n = in.nextInt();
adj = new ArrayList[n+1];
for (int i = 1; i <= n; i++) adj[i] = new ArrayList<Integer>();
int u,v;
for (int i = 0; i < n-1; i++) {
u = in.nextInt();
v = in.nextInt();
adj[u].add(v);
adj[v].add(u);
}
start = 0;
root(1,0);
vis = new boolean[n+1];
int ans = start, tmp = 0;
boolean flag = false;
while (true) {
a = 0; b = 0;
DFS(ans, 0, 0);
if (a==0) {
out.println("! "+ans);
out.flush();
return;
} else {
if (b == 0) {
if (flag) {
out.println("? "+a+" "+ans);
out.flush();
tmp = in.nextInt();
if (tmp == a) vis[ans] = true;
else vis[a] = true;
ans = tmp;
} else {
ans = a;
flag = true;
}
} else {
flag = false;
out.println("? "+b+" "+ans);
out.flush();
tmp = in.nextInt();
if (tmp == a) {
vis[ans] = true;
vis[b] = true;
} else if (tmp == b) {
vis[ans] = true;
vis[a] = true;
} else {
vis[a] = true;
vis[b] = true;
}
ans = tmp;
}
}
}
}
//<>
static int a, b;
static void DFS(int s, int p, int d) {
if (d == 1) {
if (a == 0) a = s;
} else if (d == 2) {
if (b == 0) {
b = s;
a = p;
}
}else if (d>2) return;
for (int e:adj[s]) {
if (!vis[e] && e != p) {
DFS(e, s, d+1);
}
}
}
static void root(int s, int p) {
start = s;
for (int e:adj[s]) {
if (e != p) {
root(e, s);
}
}
}
static class Reader {
private InputStream mIs;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public Reader() {
this(System.in);
}
public Reader(InputStream is) {
mIs = is;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = mIs.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String next() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
double nextDouble()
{
return Double.parseDouble(next());
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public 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 boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
} | Java | ["6\n1 4\n4 2\n5 3\n6 3\n2 3\n\n3\n\n4\n\n4"] | 1 second | ["? 5 6\n\n? 3 1\n\n? 1 2\n\n! 4"] | NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test: | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"trees",
"interactive"
] | a291ee66980d8b5856b24d1541e66fd0 | null | 1,900 | null | standard output | |
PASSED | fef76f833df3b3aafb1e4829492b245a | train_000.jsonl | 1583246100 | This is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem, Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with $$$n$$$ vertices. The tree is rooted at vertex $$$r$$$, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices $$$u$$$ and $$$v$$$, and it'll return a vertex $$$w$$$, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most $$$\lfloor \frac{n}{2} \rfloor$$$ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location? | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Random;
import java.util.StringTokenizer;
public class Solution{
static FastScanner fs = new FastScanner();
static PrintWriter out = new PrintWriter(System.out);
static HashSet<Integer>[] adjlist;
//stores the leaf vertices
static HashSet<Integer> leafset;
public static void main(String[] args) throws IOException {
// FastScanner fs = new FastScanner();
// PrintWriter out = new PrintWriter(System.out);
int tt = 1;
while(tt-->0) {
int n = fs.nextInt();
adjlist = new HashSet[n];
for(int i=0;i<n;i++) adjlist[i] = new HashSet<Integer>();
for(int i=0;i<n-1;i++) {
int x = fs.nextInt()-1, y = fs.nextInt()-1;
adjlist[x].add(y);
adjlist[y].add(x);
}
leafset = new HashSet<Integer>();
for(int i=0;i<n;i++) if(adjlist[i].size()==1) leafset.add(i);
HashSet<Integer> LEAFSET0 = leafset;
int y = 1;
//iterating over the leaf nodes in the tree
while(leafset.size()>1) {
int u = leafset.iterator().next(); leafset.remove(u);
int v = leafset.iterator().next(); leafset.remove(v);
int w = query(u, v);
if(w==u || w==v) answer(w);
trim(u, -1, w); trim(v, -1, w);
if(adjlist[w].size()<=1) leafset.add(w);
}
answer(leafset.iterator().next());
}
out.close();
}
static int query(int u, int v) {
out.println("? "+(u+1)+" "+(v+1));
out.flush();
int w = fs.nextInt()-1;
if(w==-2) System.exit(0);
return w;
}
static void answer(int v) {
out.println("! "+(v+1));
out.flush();
System.exit(0);
}
static void trim(int v, int last, int fp) {
leafset.remove(v);
for(int u: adjlist[v]) {
if(u==last) continue;
if(u==fp) adjlist[fp].remove(v);
else trim(u, v, fp);
}
adjlist[v].clear();
}
static final Random random=new Random();
static void ruffleSort(int[] a) {
int n=a.length;//shuffle, then sort
for (int i=0; i<n; i++) {
int oi=random.nextInt(n); int temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static class FastScanner{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
public String next(){
while(!st.hasMoreElements()){
try{
st = new StringTokenizer(br.readLine());
} catch(IOException e){
e.printStackTrace();
}
}
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt(){
return Integer.parseInt(next());
}
public int[] readArray(int n){
int[] a = new int[n];
for(int i=0;i<n;i++)
a[i] = nextInt();
return a;
}
public long nextLong() {
return Long.parseLong(next());
}
public char nextChar() {
return next().toCharArray()[0];
}
}
}
| Java | ["6\n1 4\n4 2\n5 3\n6 3\n2 3\n\n3\n\n4\n\n4"] | 1 second | ["? 5 6\n\n? 3 1\n\n? 1 2\n\n! 4"] | NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test: | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"trees",
"interactive"
] | a291ee66980d8b5856b24d1541e66fd0 | null | 1,900 | null | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.