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 | 3f9a3bc70cfa8c80915e6369eda8d71b | train_000.jsonl | 1517582100 | Let D(x) be the number of positive divisors of a positive integer x. For example, D(2) = 2 (2 is divisible by 1 and 2), D(6) = 4 (6 is divisible by 1, 2, 3 and 6).You are given an array a of n integers. You have to process two types of queries: REPLACE l r — for every replace ai with D(ai); SUM l r — calculate . Print the answer for each SUM query. | 256 megabytes | import java.io.*;
import java.lang.reflect.Array;
import java.math.*;
import java.text.DecimalFormat;
import java.util.*;
public class Main {
private static final int MAX = 1000*1000,MAXP2 = 1 << 19,MAXST = MAXP2 << 1;
private static int n,m;
private static int [] A;
private static int [] sig0;
private static long [] ST = new long[MAXST];
private static boolean [] finite = new boolean[MAXST];
private static void init(){
sig0 = new int[MAX + 1];
for (int i = 1;i <= MAX;i++)
for (int j = i;j <= MAX;j += i)
sig0[j] ++;
}
private static void build(int node,int s,int e) {
if (s == e) {
ST[node] = A[s];
finite[node] = A[s] == sig0[A[s]];
return;
}
int m = (s + e) >> 1,left = node*2 + 1,right = left + 1;
build(left,s,m);
build(right,m+1,e);
ST[node] = ST[left] + ST[right];
finite[node] = finite[left] && finite[right];
}
private static void update(int node,int s,int e,int l,int r) {
if (finite[node]) return;
if (s == e) {
A[s] = sig0[A[s]];
ST[node] = A[s];
finite[node] = A[s] == sig0[A[s]];
return;
}
int m = (s + e) >> 1,left = node*2 + 1,right = left + 1;
if (r <= m) update(left,s,m,l,r);
else if (m < l) update(right,m+1,e,l,r);
else {
update(left,s,m,l,m);
update(right,m+1,e,m+1,r);
}
ST[node] = ST[left] + ST[right];
finite[node] = finite[left] && finite[right];
}
private static long query(int node,int s,int e,int l,int r) {
if (l <= s && e <= r) return ST[node];
int m = (s + e) >> 1,left = node*2 + 1,right = left + 1;
if (r <= m) return query(left,s,m,l,r);
else if (m < l) return query(right,m+1,e,l,r);
else return query(left,s,m,l,m) + query(right,m+1,e,m+1,r);
}
public static void main(String[] args) throws Exception{
IO io = new IO(null,null);
init();
n = io.getNextInt();
m = io.getNextInt();
A = new int[n + 1];
for (int i = 1;i <= n;i++) A[i] = io.getNextInt();
build(0,1,n);
while (m-- > 0) {
int t = io.getNextInt(),l = io.getNextInt(),r = io.getNextInt();
if (t == 1) update(0,1,n,l,r);
else io.println(query(0,1,n,l,r));
}
io.close();
}
}
class IO{
private BufferedReader br;
private StringTokenizer st;
private PrintWriter writer;
private String inputFile,outputFile;
public boolean hasMore() throws IOException{
if(st != null && st.hasMoreTokens()) return true;
if(br != null && br.ready()) return true;
return false;
}
public String getNext() throws FileNotFoundException, IOException{
while(st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String getNextLine() throws FileNotFoundException, IOException{
return br.readLine().trim();
}
public int getNextInt() throws FileNotFoundException, IOException{
return Integer.parseInt(getNext());
}
public long getNextLong() throws FileNotFoundException, IOException{
return Long.parseLong(getNext());
}
public void print(double x,int num_digits) throws IOException{
writer.printf("%." + num_digits + "f" ,x);
}
public void println(double x,int num_digits) throws IOException{
writer.printf("%." + num_digits + "f\n" ,x);
}
public void print(Object o) throws IOException{
writer.print(o.toString());
}
public void println(Object o) throws IOException{
writer.println(o.toString());
}
public IO(String x,String y) throws FileNotFoundException, IOException{
inputFile = x;
outputFile = y;
if(x != null) br = new BufferedReader(new FileReader(inputFile));
else br = new BufferedReader(new InputStreamReader(System.in));
if(y != null) writer = new PrintWriter(new BufferedWriter(new FileWriter(outputFile)));
else writer = new PrintWriter(new OutputStreamWriter(System.out));
}
protected void close() throws IOException{
br.close();
writer.close();
}
public void outputArr(Object [] A) throws IOException{
int L = A.length;
for (int i = 0;i < L;i++) {
if(i > 0) writer.print(" ");
writer.print(A[i]);
}
writer.print("\n");
}
} | Java | ["7 6\n6 4 1 10 3 2 4\n2 1 7\n2 4 5\n1 3 5\n2 4 4\n1 5 7\n2 1 7"] | 2 seconds | ["30\n13\n4\n22"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"number theory",
"brute force"
] | 078cdef32cb5e60dc66c66cae3d4a57a | The first line contains two integers n and m (1 ≤ n, m ≤ 3·105) — the number of elements in the array and the number of queries to process, respectively. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the array. Then m lines follow, each containing 3 integers ti, li, ri denoting i-th query. If ti = 1, then i-th query is REPLACE li ri, otherwise it's SUM li ri (1 ≤ ti ≤ 2, 1 ≤ li ≤ ri ≤ n). There is at least one SUM query. | 2,000 | For each SUM query print the answer to it. | standard output | |
PASSED | bae91be03f0c3b147e7610411d743057 | train_000.jsonl | 1517582100 | Let D(x) be the number of positive divisors of a positive integer x. For example, D(2) = 2 (2 is divisible by 1 and 2), D(6) = 4 (6 is divisible by 1, 2, 3 and 6).You are given an array a of n integers. You have to process two types of queries: REPLACE l r — for every replace ai with D(ai); SUM l r — calculate . Print the answer for each SUM query. | 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.util.StringTokenizer;
public class Main3 {
static int[] D;
static void fill()
{
int n = 1+(int)1e6;
D = new int[n];
for(int i = 1;i<n;++i)
for(int j = i;j<n;j+=i)
++D[j];
}
public static void main(String[] args) throws IOException
{
Scanner sc = new Scanner(System.in);
// Scanner sc = new Scanner("out");
fill();
int n = sc.nextInt() , m = sc.nextInt();
int[] arr = sc.nextIntArr();
StringBuilder sb = new StringBuilder();
SegmentTree st = new SegmentTree(arr);
while(m-->0)
{
int q = sc.nextInt() , l = sc.nextInt()-1 , r = sc.nextInt() -1;
if(q==1)
st.replace(l, r);
else
{
long ans = st.query(l, r);
sb.append(ans+"\n");
}
}
System.out.print(sb);
}
static class SegmentTree
{
int n , a[] ;
long [] sum;
boolean min[];
public SegmentTree(int[] arr)
{
a = arr;
n = 1+a.length<<2;
sum = new long[n];
min = new boolean[n];
build(1, 0, arr.length-1);
}
int left(int n){return n<<1;}
int right(int n){return n<<1|1;}
void build(int n,int l,int r)
{
if(l==r)
{
sum[n] = a[l];
min[n] = sum[n]<3;
}
else
{
int mid = (l+r)>>1;
build(left(n), l, mid);
build(right(n), mid+1, r);
sum[n] = sum[left(n)] + sum[right(n)];
min[n] = min[left(n)] & min[right(n)];
}
}
void replace(int n,int l,int r,int lq,int rq)
{
if(l>rq || r<lq || min[n])return;
if(l==r)
{
sum[n] = D[(int) sum[n]];
min[n] = sum[n] < 3;
}
else
{
int mid = l+r>>1;
replace(left(n), l, mid, lq, rq);
replace(right(n), mid+1, r, lq, rq);
sum[n] = sum[left(n)] + sum[right(n)];
min[n] = min[left(n)] & min[right(n)];
}
}
long query(int n,int l,int r,int lq,int rq)
{
if(l>rq || r<lq)return 0;
if(l>=lq && r<=rq)
return sum[n];
else
{
int mid = l + r>>1;
long ans = query(left(n), l, mid, lq, rq);
ans += query(right(n), mid+1, r, lq, rq);
return ans;
}
}
void replace(int l,int r){replace(1, 0, a.length-1, l, r);}
long query(int l,int r){return query(1, 0, a.length-1, l, r);}
}
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 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 String nextLine() throws IOException {return br.readLine();}
public long nextLong() throws IOException {return Long.parseLong(next());}
public double nextDouble() throws IOException {return Double.parseDouble(next());}
public char nextChar() throws IOException{return next().charAt(0);}
public boolean ready() throws IOException {return br.ready();}
public int[] nextIntArr() throws IOException{
st = new StringTokenizer(br.readLine());
int[] res = new int[st.countTokens()];
for (int i = 0; i < res.length; i++)
res[i] = nextInt();
return res;
}
public char[] nextCharArr() throws IOException{
st = new StringTokenizer(br.readLine());
char[] res = new char[st.countTokens()];
for (int i = 0; i < res.length; i++)
res[i] = nextChar();
return res;
}
}
} | Java | ["7 6\n6 4 1 10 3 2 4\n2 1 7\n2 4 5\n1 3 5\n2 4 4\n1 5 7\n2 1 7"] | 2 seconds | ["30\n13\n4\n22"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"number theory",
"brute force"
] | 078cdef32cb5e60dc66c66cae3d4a57a | The first line contains two integers n and m (1 ≤ n, m ≤ 3·105) — the number of elements in the array and the number of queries to process, respectively. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the array. Then m lines follow, each containing 3 integers ti, li, ri denoting i-th query. If ti = 1, then i-th query is REPLACE li ri, otherwise it's SUM li ri (1 ≤ ti ≤ 2, 1 ≤ li ≤ ri ≤ n). There is at least one SUM query. | 2,000 | For each SUM query print the answer to it. | standard output | |
PASSED | 227c2ac0e1935b22e9a6f15c0d640a1c | train_000.jsonl | 1517582100 | Let D(x) be the number of positive divisors of a positive integer x. For example, D(2) = 2 (2 is divisible by 1 and 2), D(6) = 4 (6 is divisible by 1, 2, 3 and 6).You are given an array a of n integers. You have to process two types of queries: REPLACE l r — for every replace ai with D(ai); SUM l r — calculate . Print the answer for each SUM query. | 256 megabytes | /*Author: Satyajeet Singh, Delhi Technological University*/
import java.io.*;
import java.util.*;
import java.text.*;
import java.lang.*;
import java.math.*;
public class Main{
/*********************************************Constants******************************************/
static PrintWriter out=new PrintWriter(new OutputStreamWriter(System.out));
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static long mod=(long)1e9+7;
static long mod1=998244353;
static boolean sieve[];
static ArrayList<Integer> primes;
static long factorial[],invFactorial[];
static HashSet<Pair> graph[];
static boolean oj = System.getProperty("ONLINE_JUDGE") != null;
/****************************************Solutions Begins***************************************/
static int input[][];
static class segmentTree{
int n=0;
int[] lo,hi;
long[] value;
static int[] status;
segmentTree(int n){
this.n=n;
lo=new int[8*n+1];
hi=new int[8*n+1];
value=new long[8*n+1];
status=new int[8*n+1];
init(1,1,n);
}
void init(int i,int left,int right){
lo[i]=left;
hi[i]=right;
if(left==right){
return;
}
int mid=(left+right)/2;
init(2*i,left,mid);
init(2*i+1,mid+1,right);
}
void update(int left,int right,long val){
update(1,left,right,val);
}
long query(int left,int right){
return query(1,left,right);
}
void update(int i){
long a=value[2*i];
long b=value[2*i+1];
value[i]=a+b;
int a1=status[2*i];
int b1=status[2*i+1];
status[i]=Math.min(a1,b1);
}
void update(int i,int left,int right,long val){
if(left>hi[i]||right<lo[i]){
return;
}
if(lo[i]>=left&&hi[i]<=right){
if(status[i]==8){
return ;
}
}
if(lo[i]==hi[i]){
if(status[i]==8){
return ;
}
value[i]=input[lo[i]-1][status[i]];
status[i]++;
return;
}
update(2*i,left,right,val);
update(2*i+1,left,right,val);
update(i);
}
long query(int i,int left,int right){
if(left>hi[i]||right<lo[i]){
return 0;
}
if(lo[i]>=left&&hi[i]<=right){
return value[i];
}
long l=query(2*i,left,right);
long r=query(2*i+1,left,right);
return l+r;
}
}
public static void main (String[] args) throws Exception {
String st[]=nl();
int n=pi(st[0]);
int q=pi(st[1]);
int k=1000001;
int si[]=new int[k+1];
for(int i=1;i<=k;i++){
for(int j=i;j<=k;j+=i){
si[j]++;
}
}
input=new int[n][8];
int inp[]=new int[n];
st=nl();
for(int i=0;i<n;i++){
inp[i]=pi(st[i]);
input[i][0]=inp[i];
}
for(int j=1;j<8;j++){
for(int i=0;i<n;i++){
input[i][j]=si[input[i][j-1]];
}
}
segmentTree seg=new segmentTree(n);
seg.update(1,n,1);
while(q-->0){
st=nl();
int t=pi(st[0]);
int l=pi(st[1]);
int r=pi(st[2]);
if(t==1){
seg.update(l,r,1);
}
else{
long ans=seg.query(l,r);
out.println(ans);
}
}
/****************************************Solutions Ends**************************************************/
out.flush();
out.close();
}
/****************************************Template Begins************************************************/
static String[] nl() throws Exception{
return br.readLine().split(" ");
}
static String[] nls() throws Exception{
return br.readLine().split("");
}
static int pi(String str) {
return Integer.parseInt(str);
}
static long pl(String str){
return Long.parseLong(str);
}
static double pd(String str){
return Double.parseDouble(str);
}
/***************************************Precision Printing**********************************************/
static void printPrecision(double d){
DecimalFormat ft = new DecimalFormat("0.000000000000000000000");
out.println(ft.format(d));
}
/**************************************Bit Manipulation**************************************************/
static void printMask(long mask){
System.out.println(Long.toBinaryString(mask));
}
static int countBit(int mask){
int ans=0;
while(mask!=0){
if(mask%2==1){
ans++;
}
mask/=2;
}
return ans;
}
/******************************************Graph*********************************************************/
static void Makegraph(int n){
graph=new HashSet[n];
for(int i=0;i<n;i++){
graph[i]=new HashSet<>();
}
}
static void addEdge(int a,int b){
graph[a].add(new Pair(b,1));
}
static void addEdge(int a,int b,int c){
graph[a].add(new Pair(b,c));
}
/*********************************************PAIR********************************************************/
static class PairComp implements Comparator<Pair>{
public int compare(Pair p1,Pair p2){
return p1.u-p2.u;
}
}
static class Pair implements Comparable<Pair> {
int u;
int v;
int index=-1;
public Pair(int u, int v) {
this.u = u;
this.v = v;
}
public int hashCode() {
int hu = (int) (u ^ (u >>> 32));
int hv = (int) (v ^ (v >>> 32));
return 31 * hu + hv;
}
public boolean equals(Object o) {
Pair other = (Pair) o;
return u == other.u && v == other.v;
}
public int compareTo(Pair other) {
if(index!=other.index)
return Long.compare(index, other.index);
return Long.compare(v, other.v)!=0?Long.compare(v, other.v):Long.compare(u, other.u);
}
public String toString() {
return "[u=" + u + ", v=" + v + "]";
}
}
/******************************************Long Pair*******************************************************/
static class PairCompL implements Comparator<Pairl>{
public int compare(Pairl p1,Pairl p2){
if(p1.u-p2.u<0){
return -1;
}
else if(p1.u-p2.u>0){
return 1;
}
else{
if(p1.v-p2.v<0){
return -1;
}
else if(p1.v-p2.v>0){
return 1;
}
else{
return 0;
}
}
}
}
static class Pairl implements Comparable<Pairl> {
long u;
long v;
int index=-1;
public Pairl(long u, long v) {
this.u = u;
this.v = v;
}
public int hashCode() {
int hu = (int) (u ^ (u >>> 32));
int hv = (int) (v ^ (v >>> 32));
return 31 * hu + hv;
}
public boolean equals(Object o) {
Pairl other = (Pairl) o;
return u == other.u && v == other.v;
}
public int compareTo(Pairl other) {
if(index!=other.index)
return Long.compare(index, other.index);
return Long.compare(v, other.v)!=0?Long.compare(v, other.v):Long.compare(u, other.u);
}
public String toString() {
return "[u=" + u + ", v=" + v + "]";
}
}
/*****************************************DEBUG***********************************************************/
public static void debug(Object... o) {
if(!oj)
System.out.println(Arrays.deepToString(o));
}
/************************************MODULAR EXPONENTIATION***********************************************/
static long modulo(long a,long b,long c) {
long x=1;
long y=a;
while(b > 0){
if(b%2 == 1){
x=(x*y)%c;
}
y = (y*y)%c; // squaring the base
b /= 2;
}
return x%c;
}
/********************************************GCD**********************************************************/
static long gcd(long x, long y)
{
if(x==0)
return y;
if(y==0)
return x;
long r=0, a, b;
a = (x > y) ? x : y; // a is greater number
b = (x < y) ? x : y; // b is smaller number
r = b;
while(a % b != 0)
{
r = a % b;
a = b;
b = r;
}
return r;
}
/******************************************SIEVE**********************************************************/
static void sieveMake(int n){
sieve=new boolean[n];
Arrays.fill(sieve,true);
sieve[0]=false;
sieve[1]=false;
for(int i=2;i*i<n;i++){
if(sieve[i]){
for(int j=i*i;j<n;j+=i){
sieve[j]=false;
}
}
}
primes=new ArrayList<Integer>();
for(int i=0;i<n;i++){
if(sieve[i]){
primes.add(i);
}
}
}
/********************************************End***********************************************************/
} | Java | ["7 6\n6 4 1 10 3 2 4\n2 1 7\n2 4 5\n1 3 5\n2 4 4\n1 5 7\n2 1 7"] | 2 seconds | ["30\n13\n4\n22"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"number theory",
"brute force"
] | 078cdef32cb5e60dc66c66cae3d4a57a | The first line contains two integers n and m (1 ≤ n, m ≤ 3·105) — the number of elements in the array and the number of queries to process, respectively. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the array. Then m lines follow, each containing 3 integers ti, li, ri denoting i-th query. If ti = 1, then i-th query is REPLACE li ri, otherwise it's SUM li ri (1 ≤ ti ≤ 2, 1 ≤ li ≤ ri ≤ n). There is at least one SUM query. | 2,000 | For each SUM query print the answer to it. | standard output | |
PASSED | 9c4266b631bf10b023cc21b4eb0fb6dd | train_000.jsonl | 1517582100 | Let D(x) be the number of positive divisors of a positive integer x. For example, D(2) = 2 (2 is divisible by 1 and 2), D(6) = 4 (6 is divisible by 1, 2, 3 and 6).You are given an array a of n integers. You have to process two types of queries: REPLACE l r — for every replace ai with D(ai); SUM l r — calculate . Print the answer for each SUM query. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.TreeSet;
/*
public class _920F {
}
*/
public class _920F {
public class SegmentTree {
long[] st;
int n;
public SegmentTree(int n) {
st = new long[4 * n];
this.n = n;
}
void build(int i, int[] a, int r1, int r2) {
if (r1 == r2) {
st[i] = a[r1];
} else {
build(i * 2 + 1, a, r1, (r1 + r2) / 2);
build(i * 2 + 2, a, (r1 + r2) / 2 + 1, r2);
st[i] = st[i * 2 + 1] + st[i * 2 + 2];
}
}
long query(int i, int ra, int rb, int r1, int r2) {
if (ra > r2 || rb < r1) {
return 0;
}
if (ra >= r1 && rb <= r2) {
return st[i];
}
long p1 = query(i * 2 + 1, ra, (ra + rb) / 2, r1, r2);
long p2 = query(i * 2 + 2, (ra + rb) / 2 + 1, rb, r1, r2);
return p1 + p2;
}
long update(int i, int ra, int rb, int ind, long val) {
if (ra == rb && rb == ind) {
st[i] = val;
return st[i];
}
if (ra > ind || rb < ind) {
return st[i];
}
long p1 = update(i * 2 + 1, ra, (ra + rb) / 2, ind, val);
long p2 = update(i * 2 + 2, (ra + rb) / 2 + 1, rb, ind, val);
return st[i] = p1 + p2;
}
}
public void solve() throws FileNotFoundException {
InputStream inputStream = System.in;
InputHelper in = new InputHelper(inputStream);
// actual solution
int n = in.readInteger();
int m = in.readInteger();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.readInteger();
}
int[] nod = new int[1000001];
for (int i = 1; i <= 1000000; i++) {
for (int j = i; j <= 1000000; j += i) {
nod[j]++;
}
}
TreeSet<Integer> ts = new TreeSet<Integer>();
for (int i = 0; i < n; i++)
ts.add(i);
SegmentTree st = new SegmentTree(n);
st.build(0, a, 0, n - 1);
StringBuilder ans = new StringBuilder();
while (m-- > 0) {
int t = in.readInteger();
int l = in.readInteger() - 1;
int r = in.readInteger() - 1;
if (t == 1) {
Integer ni = ts.ceiling(l);
while (true) {
if (ni == null || ni > r) {
break;
}
if (a[ni] == 1 || a[ni] == 2) {
ts.remove(ni);
} else {
a[ni] = nod[a[ni]];
st.update(0, 0, n - 1, ni, a[ni]);
if (a[ni] == 1 || a[ni] == 2) {
ts.remove(ni);
}
}
ni = ts.ceiling(ni + 1);
}
} else {
ans.append(st.query(0, 0, n - 1, l, r));
ans.append("\n");
}
}
System.out.println(ans.toString());
// end here
}
public static void main(String[] args) throws FileNotFoundException {
(new _920F()).solve();
}
class InputHelper {
StringTokenizer tokenizer = null;
private BufferedReader bufferedReader;
public InputHelper(InputStream inputStream) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
bufferedReader = new BufferedReader(inputStreamReader, 16384);
}
public String read() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
String line = bufferedReader.readLine();
if (line == null) {
return null;
}
tokenizer = new StringTokenizer(line);
} catch (IOException e) {
e.printStackTrace();
}
}
return tokenizer.nextToken();
}
public Integer readInteger() {
return Integer.parseInt(read());
}
public Long readLong() {
return Long.parseLong(read());
}
}
}
| Java | ["7 6\n6 4 1 10 3 2 4\n2 1 7\n2 4 5\n1 3 5\n2 4 4\n1 5 7\n2 1 7"] | 2 seconds | ["30\n13\n4\n22"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"number theory",
"brute force"
] | 078cdef32cb5e60dc66c66cae3d4a57a | The first line contains two integers n and m (1 ≤ n, m ≤ 3·105) — the number of elements in the array and the number of queries to process, respectively. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the array. Then m lines follow, each containing 3 integers ti, li, ri denoting i-th query. If ti = 1, then i-th query is REPLACE li ri, otherwise it's SUM li ri (1 ≤ ti ≤ 2, 1 ≤ li ≤ ri ≤ n). There is at least one SUM query. | 2,000 | For each SUM query print the answer to it. | standard output | |
PASSED | 9e7d9fb4850d6db32f49303137f6eda2 | train_000.jsonl | 1517582100 | Let D(x) be the number of positive divisors of a positive integer x. For example, D(2) = 2 (2 is divisible by 1 and 2), D(6) = 4 (6 is divisible by 1, 2, 3 and 6).You are given an array a of n integers. You have to process two types of queries: REPLACE l r — for every replace ai with D(ai); SUM l r — calculate . Print the answer for each SUM query. | 256 megabytes | import java.util.*;
import java.io.*;
import java.text.*;
public class Main{
static final long MOD = (long)1e9+7;
static final int MAX = (int)1e6+1;
static FastReader in;
static int[] count,A;
static long[] sum,max;
public static void main(String[] args){
in = new FastReader();
count = new int[MAX];
for(int i = 1; i< MAX; i++)for(int j = i; j< MAX; j+=i)count[j]++;
int T = 1;
StringBuilder out = new StringBuilder("");
while(T-->0){
int N = ni(), Q = ni();
A = new int[N];
int M = 1;
while(M<N)M<<=1;
sum = new long[M<<1]; max = new long[M<<1];
for(int i = 0; i< N; i++){
A[i] = ni();
sum[i+M] = A[i];
max[i+M] = A[i];
}
for(int i = M-1; i> 0; i--){
sum[i] = sum[i<<1]+sum[i<<1|1];
max[i] = Math.max(max[i<<1], max[i<<1|1]);
}
while(Q-->0){
int t = ni(), l = ni()-1, r = ni()-1;
if(t==1){
update(0,M-1,l,r,1);
}else{
long ans = 0;
for(l+=M, r+=M+1; l<r; l>>=1, r>>=1){
if((l&1)==1)ans+=sum[l++];
if((r&1)==1)ans+=sum[--r];
}
out.append(ans+"\n");
}
}
}
System.out.println(out.toString());
}
static void update(int L, int R, int l, int r, int i){
if(max[i]<=2 || R<l || L>r)return;
if(L==R){
A[L] = count[A[L]];
sum[i] = A[L];
max[i] = A[L];
return;
}
int mid = (L+R)>>1;
update(L,mid,l,r,i<<1);
update(mid+1,R,l,r,i<<1|1);
sum[i] = sum[i<<1]+sum[i<<1|1];
max[i] = Math.max(max[i<<1], max[i<<1|1]);
}
static void p(Object o){
System.out.print(o);
}
static void pn(Object o){
System.out.println(o);
}
static String n(){
return in.next();
}
static String nln(){
return in.nextLine();
}
static int ni(){
return Integer.parseInt(in.next());
}
static long nl(){
return Long.parseLong(in.next());
}
static double nd(){
return Double.parseDouble(in.next());
}
static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws Exception{
br = new BufferedReader(new FileReader(s));
}
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 | ["7 6\n6 4 1 10 3 2 4\n2 1 7\n2 4 5\n1 3 5\n2 4 4\n1 5 7\n2 1 7"] | 2 seconds | ["30\n13\n4\n22"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"number theory",
"brute force"
] | 078cdef32cb5e60dc66c66cae3d4a57a | The first line contains two integers n and m (1 ≤ n, m ≤ 3·105) — the number of elements in the array and the number of queries to process, respectively. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the array. Then m lines follow, each containing 3 integers ti, li, ri denoting i-th query. If ti = 1, then i-th query is REPLACE li ri, otherwise it's SUM li ri (1 ≤ ti ≤ 2, 1 ≤ li ≤ ri ≤ n). There is at least one SUM query. | 2,000 | For each SUM query print the answer to it. | standard output | |
PASSED | 227b61278c2ccd6a6ae04820384793f5 | train_000.jsonl | 1517582100 | Let D(x) be the number of positive divisors of a positive integer x. For example, D(2) = 2 (2 is divisible by 1 and 2), D(6) = 4 (6 is divisible by 1, 2, 3 and 6).You are given an array a of n integers. You have to process two types of queries: REPLACE l r — for every replace ai with D(ai); SUM l r — calculate . Print the answer for each SUM query. | 256 megabytes | import java.util.*;
import java.io.*;
import java.text.*;
public class Main{
static final long MOD = (long)1e9+7;
static final int MAX = (int)1e6+1;
static FastReader in;
static int[] count,A;
static long[] sum,max;
public static void main(String[] args){
in = new FastReader();
count = new int[MAX];
for(int i = 1; i< MAX; i++)for(int j = i; j< MAX; j+=i)count[j]++;
int T = 1;
StringBuilder out = new StringBuilder("");
while(T-->0){
int N = ni(), Q = ni();
A = new int[N];
int M = 1;
while(M<N)M<<=1;
sum = new long[M<<1]; max = new long[M<<1];
for(int i = 0; i< N; i++){
A[i] = ni();
sum[i+M] = A[i];
max[i+M] = A[i];
}
for(int i = M-1; i> 0; i--){
sum[i] = sum[i<<1]+sum[i<<1|1];
max[i] = Math.max(max[i<<1], max[i<<1|1]);
}
while(Q-->0){
int t = ni(), l = ni()-1, r = ni()-1;
if(t==1){
update(0,M-1,l,r,1);
}else{
long ans = 0;
for(l+=M, r+=M+1; l<r; l>>=1, r>>=1){
if((l&1)==1)ans+=sum[l++];
if((r&1)==1)ans+=sum[--r];
}
out.append(ans+"\n");
}
}
}
System.out.println(out.toString());
}
static void update(int L, int R, int l, int r, int i){
if(max[i]<=2 || R<l || L>r)return;
if(L==R){
A[L] = count[A[L]];
sum[i] = A[L];
max[i] = A[L];
return;
}
int mid = (L+R)>>1;
update(L,mid,l,r,i<<1);
update(mid+1,R,l,r,i<<1|1);
sum[i] = sum[i<<1]+sum[i<<1|1];
max[i] = Math.max(max[i<<1], max[i<<1|1]);
}
static void p(Object o){
System.out.print(o);
}
static void pn(Object o){
System.out.println(o);
}
static String n(){
return in.next();
}
static String nln(){
return in.nextLine();
}
static int ni(){
return Integer.parseInt(in.next());
}
static long nl(){
return Long.parseLong(in.next());
}
static double nd(){
return Double.parseDouble(in.next());
}
static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws Exception{
br = new BufferedReader(new FileReader(s));
}
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 | ["7 6\n6 4 1 10 3 2 4\n2 1 7\n2 4 5\n1 3 5\n2 4 4\n1 5 7\n2 1 7"] | 2 seconds | ["30\n13\n4\n22"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"number theory",
"brute force"
] | 078cdef32cb5e60dc66c66cae3d4a57a | The first line contains two integers n and m (1 ≤ n, m ≤ 3·105) — the number of elements in the array and the number of queries to process, respectively. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the array. Then m lines follow, each containing 3 integers ti, li, ri denoting i-th query. If ti = 1, then i-th query is REPLACE li ri, otherwise it's SUM li ri (1 ≤ ti ≤ 2, 1 ≤ li ≤ ri ≤ n). There is at least one SUM query. | 2,000 | For each SUM query print the answer to it. | standard output | |
PASSED | 80d46356d5511c1bca638a2ccf7b053f | train_000.jsonl | 1517582100 | Let D(x) be the number of positive divisors of a positive integer x. For example, D(2) = 2 (2 is divisible by 1 and 2), D(6) = 4 (6 is divisible by 1, 2, 3 and 6).You are given an array a of n integers. You have to process two types of queries: REPLACE l r — for every replace ai with D(ai); SUM l r — calculate . Print the answer for each SUM query. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
import java.lang.*;
import static java.lang.Math.*;
public class Main implements Runnable
{
static class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
private BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (numChars==-1)
throw new InputMismatchException();
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
public int nextInt()
{
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if(c<'0'||c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.')
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.')
{
c = read();
double m = 1;
while (!isSpaceChar(c))
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next()
{
return readString();
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
public static void main(String args[]) throws Exception
{
new Thread(null, new Main(),"Main",1<<26).start();
}
long querySegTree(int low, int high, int pos, int l, int r) {
if(lazy[pos] != 0) {
if(lazy[pos] >= 6) {
for(int i = 0; i < 6; ++i)
segTree[pos][i] = 2L * (long)(high - low + 1) - (long)cnt[pos];
}
else {
for(int i = lazy[pos]; i < 6; ++i)
segTree[pos][i - lazy[pos]] = segTree[pos][i];
for(int i = 6 - lazy[pos]; i < 6; ++i)
segTree[pos][i] = 2L * (long)(high - low + 1) - (long)cnt[pos];
}
if(low != high) {
lazy[2 * pos + 1] += lazy[pos];
lazy[2 * pos + 2] += lazy[pos];
}
lazy[pos] = 0;
}
if(low >= l && high <= r)
return segTree[pos][0];
if(low > r || high < l)
return 0;
int mid = (low + high) >> 1;
long val1 = querySegTree(low, mid, 2 * pos + 1, l, r);
long val2 = querySegTree(mid + 1, high, 2 * pos + 2, l, r);
return val1 + val2;
}
void updateSegTree(int low, int high, int pos, int l, int r) {
if(lazy[pos] != 0) {
if(lazy[pos] >= 6) {
for(int i = 0; i < 6; ++i)
segTree[pos][i] = 2L * (long)(high - low + 1) - (long)cnt[pos];
}
else {
for(int i = lazy[pos]; i < 6; ++i)
segTree[pos][i - lazy[pos]] = segTree[pos][i];
for(int i = 6 - lazy[pos]; i < 6; ++i)
segTree[pos][i] = 2L * (long)(high - low + 1) - (long)cnt[pos];
}
if(low != high) {
lazy[2 * pos + 1] += lazy[pos];
lazy[2 * pos + 2] += lazy[pos];
}
lazy[pos] = 0;
}
if(low >= l && high <= r) {
for(int i = 1; i < 6; ++i)
segTree[pos][i - 1] = segTree[pos][i];
segTree[pos][5] = 2L * (long)(high - low + 1) - (long)cnt[pos];
if(low != high) {
lazy[2 * pos + 1]++;
lazy[2 * pos + 2]++;
}
return;
}
if(low > r || high < l)
return;
int mid = (low + high) >> 1;
updateSegTree(low, mid, 2 * pos + 1, l, r);
updateSegTree(mid + 1, high, 2 * pos + 2, l, r);
for(int i = 0; i < 6; ++i)
segTree[pos][i] = segTree[2 * pos + 1][i] + segTree[2 * pos + 2][i];
}
void buildSegTree(int low, int high, int pos) {
if(low == high) {
segTree[pos][0] = a[low];
for(int i = 1; i < 6; ++i)
segTree[pos][i] = sieve[(int)segTree[pos][i - 1]];
if(a[low] == 1)
cnt[pos]++;
return;
}
int mid = (low + high) >> 1;
buildSegTree(low, mid, 2 * pos + 1);
buildSegTree(mid + 1, high, 2 * pos + 2);
for(int i = 0; i < 6; ++i)
segTree[pos][i] = segTree[2 * pos + 1][i] + segTree[2 * pos + 2][i];
cnt[pos] = cnt[2 * pos + 1] + cnt[2 * pos + 2];
}
long segTree[][];
int lazy[];
long sieve[];
long a[];
int cnt[];
public void run()
{
InputReader sc= new InputReader(System.in);
PrintWriter w= new PrintWriter(System.out);
int n = sc.nextInt();
int q = sc.nextInt();
sieve = new long[1000001];
for(int i = 1; i <= 1000000; ++i) {
for(int j = i; j <= 1000000; j += i)
sieve[j]++;
}
segTree = new long[4 * n][6];
lazy = new int[4 * n];
cnt = new int[4 * n];
a = new long[n];
for(int i = 0; i < n; ++i)
a[i] = sc.nextLong();
buildSegTree(0, n - 1, 0);
for(int i = 0; i < q; ++i) {
int type = sc.nextInt();
if(type == 1) {
int l = sc.nextInt() - 1;
int r = sc.nextInt() - 1;
updateSegTree(0, n - 1, 0, l, r);
}
else {
int l = sc.nextInt() - 1;
int r = sc.nextInt() - 1;
w.println(querySegTree(0, n - 1, 0, l, r));
}
}
w.close();
}
} | Java | ["7 6\n6 4 1 10 3 2 4\n2 1 7\n2 4 5\n1 3 5\n2 4 4\n1 5 7\n2 1 7"] | 2 seconds | ["30\n13\n4\n22"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"number theory",
"brute force"
] | 078cdef32cb5e60dc66c66cae3d4a57a | The first line contains two integers n and m (1 ≤ n, m ≤ 3·105) — the number of elements in the array and the number of queries to process, respectively. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the array. Then m lines follow, each containing 3 integers ti, li, ri denoting i-th query. If ti = 1, then i-th query is REPLACE li ri, otherwise it's SUM li ri (1 ≤ ti ≤ 2, 1 ≤ li ≤ ri ≤ n). There is at least one SUM query. | 2,000 | For each SUM query print the answer to it. | standard output | |
PASSED | 4f2453838b998f7331b9c794a616153a | train_000.jsonl | 1517582100 | Let D(x) be the number of positive divisors of a positive integer x. For example, D(2) = 2 (2 is divisible by 1 and 2), D(6) = 4 (6 is divisible by 1, 2, 3 and 6).You are given an array a of n integers. You have to process two types of queries: REPLACE l r — for every replace ai with D(ai); SUM l r — calculate . Print the answer for each SUM query. | 256 megabytes | //package educational.round37;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.List;
public class F {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni(), m = ni();
int[] a = na(n);
int[] lpf = enumLowestPrimeFactors(1000000);
int[] nd = enumNumDivisorsFast(1000000, lpf);
LST lst = new LST(n);
for(int i = 0;i < n;i++){
if(a[i] > 2)lst.set(i);
}
long[] ft = buildFenwick(a);
for(int z = 0;z < m;z++){
int t = ni();
int l= ni()-1, r = ni()-1;
if(t == 1){
for(int i = lst.next(l);i != -1 && i <= r;i = lst.next(i+1)){
addFenwick(ft, i, nd[a[i]] - a[i]);
a[i] = nd[a[i]];
if(a[i] <= 2)lst.unset(i);
}
}else{
out.println(sumFenwick(ft, r) - sumFenwick(ft, l-1));
}
}
}
public static long[] buildFenwick(int[] a)
{
int n = a.length;
long[] ft = new long[n+1];
for(int i = 0;i < n;i++){
ft[i+1] = a[i];
}
for(int k = 2, h = 1;k <= n;k*=2, h*=2){
for(int i = k;i <= n;i+=k){
ft[i] += ft[i-h];
}
}
return ft;
}
public static int[] enumNumDivisorsFast(int n, int[] lpf)
{
int[] nd = new int[n+1];
nd[1] = 1;
for(int i = 2;i <= n;i++){
int j = i, e = 0;
while(j % lpf[i] == 0){
j /= lpf[i];
e++;
}
nd[i] = nd[j] * (e+1);
}
return nd;
}
public static int[] enumLowestPrimeFactors(int n) {
int tot = 0;
int[] lpf = new int[n + 1];
int u = n + 32;
double lu = Math.log(u);
int[] primes = new int[(int) (u / lu + u / lu / lu * 1.5)];
for (int i = 2; i <= n; i++)
lpf[i] = i;
for (int p = 2; p <= n; p++) {
if (lpf[p] == p)
primes[tot++] = p;
int tmp;
for (int i = 0; i < tot && primes[i] <= lpf[p] && (tmp = primes[i] * p) <= n; i++) {
lpf[tmp] = primes[i];
}
}
return lpf;
}
public static class LST {
public long[][] set;
public int n;
// public int size;
public LST(int n) {
this.n = n;
int d = 1;
for(int m = n;m > 1;m>>>=6, d++);
set = new long[d][];
for(int i = 0, m = n>>>6;i < d;i++, m>>>=6){
set[i] = new long[m+1];
}
// size = 0;
}
// [0,r)
public LST setRange(int r)
{
for(int i = 0;i < set.length;i++, r=r+63>>>6){
for(int j = 0;j < r>>>6;j++){
set[i][j] = -1L;
}
if((r&63) != 0)set[i][r>>>6] |= (1L<<r)-1;
}
return this;
}
// [0,r)
public LST unsetRange(int r)
{
if(r >= 0){
for(int i = 0;i < set.length;i++, r=r+63>>>6){
for(int j = 0;j < r+63>>>6;j++){
set[i][j] = 0;
}
if((r&63) != 0)set[i][r>>>6] &= ~((1L<<r)-1);
}
}
return this;
}
public LST set(int pos)
{
if(pos >= 0 && pos < n){
// if(!get(pos))size++;
for(int i = 0;i < set.length;i++, pos>>>=6){
set[i][pos>>>6] |= 1L<<pos;
}
}
return this;
}
public LST unset(int pos)
{
if(pos >= 0 && pos < n){
// if(get(pos))size--;
for(int i = 0;i < set.length && (i == 0 || set[i-1][pos] == 0L);i++, pos>>>=6){
set[i][pos>>>6] &= ~(1L<<pos);
}
}
return this;
}
public boolean get(int pos)
{
return pos >= 0 && pos < n && set[0][pos>>>6]<<~pos<0;
}
public int prev(int pos)
{
for(int i = 0;i < set.length && pos >= 0;i++, pos>>>=6, pos--){
int pre = prev(set[i][pos>>>6], pos&63);
if(pre != -1){
pos = pos>>>6<<6|pre;
while(i > 0)pos = pos<<6|63-Long.numberOfLeadingZeros(set[--i][pos]);
return pos;
}
}
return -1;
}
public int next(int pos)
{
for(int i = 0;i < set.length && pos>>>6 < set[i].length;i++, pos>>>=6, pos++){
int nex = next(set[i][pos>>>6], pos&63);
if(nex != -1){
pos = pos>>>6<<6|nex;
while(i > 0)pos = pos<<6|Long.numberOfTrailingZeros(set[--i][pos]);
return pos;
}
}
return -1;
}
private static int prev(long set, int n)
{
long h = set<<~n;
if(h == 0L)return -1;
return -Long.numberOfLeadingZeros(h)+n;
}
private static int next(long set, int n)
{
long h = set>>>n;
if(h == 0L)return -1;
return Long.numberOfTrailingZeros(h)+n;
}
@Override
public String toString()
{
List<Integer> list = new ArrayList<Integer>();
for(int pos = next(0);pos != -1;pos = next(pos+1)){
list.add(pos);
}
return list.toString();
}
}
public static long sumFenwick(long[] ft, int i)
{
long sum = 0;
for(i++;i > 0;i -= i&-i)sum += ft[i];
return sum;
}
public static void addFenwick(long[] ft, int i, long v)
{
if(v == 0)return;
int n = ft.length;
for(i++;i < n;i += i&-i)ft[i] += v;
}
void run() throws Exception
{
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new F().run(); }
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
| Java | ["7 6\n6 4 1 10 3 2 4\n2 1 7\n2 4 5\n1 3 5\n2 4 4\n1 5 7\n2 1 7"] | 2 seconds | ["30\n13\n4\n22"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"number theory",
"brute force"
] | 078cdef32cb5e60dc66c66cae3d4a57a | The first line contains two integers n and m (1 ≤ n, m ≤ 3·105) — the number of elements in the array and the number of queries to process, respectively. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the array. Then m lines follow, each containing 3 integers ti, li, ri denoting i-th query. If ti = 1, then i-th query is REPLACE li ri, otherwise it's SUM li ri (1 ≤ ti ≤ 2, 1 ≤ li ≤ ri ≤ n). There is at least one SUM query. | 2,000 | For each SUM query print the answer to it. | standard output | |
PASSED | 2e2d843afdf669b97924b42ae85ae720 | train_000.jsonl | 1517582100 | Let D(x) be the number of positive divisors of a positive integer x. For example, D(2) = 2 (2 is divisible by 1 and 2), D(6) = 4 (6 is divisible by 1, 2, 3 and 6).You are given an array a of n integers. You have to process two types of queries: REPLACE l r — for every replace ai with D(ai); SUM l r — calculate . Print the answer for each SUM query. | 256 megabytes | import java.io.*;
import java.util.*;
public class F {
public static void main(String[] args) {new F();}
F () {
FastScanner fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
System.err.println("Go!");
int max = (int)1e6+1;
int[] div = new int[max];
for(int i = 1; i < max; i++)
for(int j = i; j < max; j += i)
div[j]++;
int n = fs.nextInt();
int m = fs.nextInt();
int[] a = fs.nextIntArray(n);
Fenwick_Tree ft = new Fenwick_Tree(n);
for(int i = 0; i < n; i++)
ft.update(i+1, a[i]);
TreeSet<Integer> avail = new TreeSet<>();
for(int i = 0; i < n; i++)
if(a[i] > 2) avail.add(i);
while(m-->0) {
int type = fs.nextInt();
int l = fs.nextInt()-1, r = fs.nextInt()-1;
if(type == 2) {
out.println(ft.query(l+1, r+1));
}
else {
Integer next = l;
while((next = avail.ceiling(next)) != null) {
if(next > r) break;
int old = a[next];
a[next] = div[a[next]];
if(a[next] < 3) {
avail.remove(next);
}
ft.update(next+1, -old); ft.update(next+1, a[next]);
next++;
}
}
}
out.close();
}
class Fenwick_Tree {
long[] bit;
int n;
public Fenwick_Tree(int a) {
n = a + 1;
bit = new long[n];
}
//Remember that when querying a sum to query the 1-based index of the value.
void update (int index, int val) {
while(index < n) {
bit[index] += val;
index += (index & (-index));
}
}
long query(int i, int j) {
long sum = sum(j);
if(i > 0) sum -= sum(i-1);
return sum;
}
long sum (int index) {
long sum = 0;
while(index > 0) {
sum += bit[index];
index -= (index & (-index));
}
return sum;
}
}
void sort (long[] a) {
int n = a.length;
for(int i = 0; i < 1000; i++) {
Random r = new Random();
int x = r.nextInt(n), y = r.nextInt(n);
long temp = a[x];
a[x] = a[y];
a[y] = temp;
}
Arrays.sort(a);
}
void sort (int[] a) {
int n = a.length;
for(int i = 0; i < 1000; i++) {
Random r = new Random();
int x = r.nextInt(n), y = r.nextInt(n);
int temp = a[x];
a[x] = a[y];
a[y] = temp;
}
Arrays.sort(a);
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
// br = new BufferedReader(new FileReader("testdata.out"));
st = new StringTokenizer("");
} catch (Exception e){e.printStackTrace();}
}
public String next() {
if (st.hasMoreTokens()) return st.nextToken();
try {st = new StringTokenizer(br.readLine());}
catch (Exception e) {e.printStackTrace();}
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() {
String line = "";
try {line = br.readLine();}
catch (Exception e) {e.printStackTrace();}
return line;
}
public Integer[] nextIntegerArray(int n) {
Integer[] a = new Integer[n];
for(int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
public int[] nextIntArray(int n) {
int[] a = new int[n];
for(int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
public char[] nextCharArray() {return nextLine().toCharArray();}
}
}
| Java | ["7 6\n6 4 1 10 3 2 4\n2 1 7\n2 4 5\n1 3 5\n2 4 4\n1 5 7\n2 1 7"] | 2 seconds | ["30\n13\n4\n22"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"number theory",
"brute force"
] | 078cdef32cb5e60dc66c66cae3d4a57a | The first line contains two integers n and m (1 ≤ n, m ≤ 3·105) — the number of elements in the array and the number of queries to process, respectively. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the array. Then m lines follow, each containing 3 integers ti, li, ri denoting i-th query. If ti = 1, then i-th query is REPLACE li ri, otherwise it's SUM li ri (1 ≤ ti ≤ 2, 1 ≤ li ≤ ri ≤ n). There is at least one SUM query. | 2,000 | For each SUM query print the answer to it. | standard output | |
PASSED | 2db100e320e761198514a8ca5bf5fe60 | train_000.jsonl | 1517582100 | Let D(x) be the number of positive divisors of a positive integer x. For example, D(2) = 2 (2 is divisible by 1 and 2), D(6) = 4 (6 is divisible by 1, 2, 3 and 6).You are given an array a of n integers. You have to process two types of queries: REPLACE l r — for every replace ai with D(ai); SUM l r — calculate . Print the answer for each SUM query. | 256 megabytes | /*
ЗАПУСКАЕМ ВЫСОКОГО
░ГУСЯ░▄▀▀▀▄░РАБОТЯГИ░░
▄███▀░◐░░░▌░░░░░░░
░░░░▌░░░░░▐░░░░░░░
░░░░▐░░░░░▐░░░░░░░
░░░░▌░░░░░▐▄▄░░░░░
░░░░▌░░░░░▐▄▄░░░░░
░░░░▌░░░░░▐▄▄░░░░░
░░░░▌░░░░░▐▄▄░░░░░
░░░░▌░░░░░▐▄▄░░░░░
░░░░▌░░░░░▐▄▄░░░░░
░░░░▌░░░░░▐▄▄░░░░░
░░░░▌░░░░░▐▄▄░░░░░
░░░░▌░░░░░▐▄▄░░░░░
░░░░▌░░░░░▐▄▄░░░░░
░░░░▌░░░░░▐▄▄░░░░░
░░░░▌░░░░░▐▄▄░░░░░
░░░░▌░░░░▄▀▒▒▀▀▀▀▄
░░░▐░░░░▐▒▒▒▒▒▒▒▒▀▀▄
░░░▐░░░░▐▄▒▒▒▒▒▒▒▒▒▒▀▄
░░░░▀▄░░░░▀▄▒▒▒▒▒▒▒▒▒▒▀▄
░░░░░░▀▄▄▄▄▄█▄▄▄▄▄▄▄▄▄▄▄▀▄
░░░░░░░░░░░▌▌░▌▌░░░░░
░░░░░░░░░░░▌▌░▌▌░░░░░
░░░░░░░░░▄▄▌▌▄▌▌░░░░░
*/
import java.io.*;
import java.util.*;
public class Main {
void solve() throws IOException {
simple_ints = new ArrayList<>();
int size = 1000001;
r = new boolean[size];
for (int i = 2; i < size; i++) if (!r[i]) for (int j = 2; j * i < size; j++) r[i * j] = true;
for (int i = 2; i < size; i++) if (!r[i]) simple_ints.add(i);
d = new int[size];
int n = readInt();
int m = readInt();
int[] a = readIntArray(n);
TreeSet<Integer> st = new TreeSet<>();
for (int i = -1; i < n; i++) st.add(i);
for (int i = 0; i < n; i++) if (a[i] <= 2) st.remove(i);
Fenwik fen = new Fenwik(a);
while (m-- > 0) {
int type = readInt();
int lo = readInt() - 1;
int hi = readInt() - 1;
if (type == 1) {
int h = st.floor(hi);
while (h >= lo) {
int pref = a[h];
a[h] = getD(0, a[h]);
fen.inc(h, a[h] - pref);
if (a[h] < 3) st.remove(h);
h = st.floor(h - 1);
}
} else out.println(fen.getSum(hi) - (lo > 0 ? fen.getSum(lo - 1) : 0));
}
}
int[] d;
ArrayList<Integer> simple_ints;
boolean[] r;
int getD(int index, int value) {
if (d[value] != 0) return d[value];
int k = 1;
while (value % simple_ints.get(index) == 0) {
k++;
value /= simple_ints.get(index);
}
if (value == 1) return k;
if (!r[value]) return (k << 1);
int next = getD(index + 1, value);
d[value] = next;
k *= next;
return k;
}
public static void main(String[] args) throws IOException {
new Main().run();
}
BufferedReader in;
PrintWriter out;
StringTokenizer tok;
Main() throws FileNotFoundException {
try {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
} catch (Exception e) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
tok = new StringTokenizer("");
}
void run() throws IOException {
solve();
out.close();
}
class Fenwik {
private long[] t;
private int length;
Fenwik(int[] a) {
this.length = a.length + 100;
this.t = new long[length];
for (int i = 0; i < a.length; ++i) this.inc(i, a[i]);
}
void inc(int i, int delta) {
for (; i < this.length; i = i | (i + 1)) t[i] += delta;
}
long getSum(int r) {
long sum = 0;
for (; r >= 0; r = (r & (r + 1)) - 1) sum += this.t[r];
return sum;
}
}
String delimiter = " ";
String readLine() throws IOException {
return in.readLine();
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
String nextLine = readLine();
if (null == nextLine) return null;
tok = new StringTokenizer(nextLine);
}
return tok.nextToken(delimiter);
}
int readInt() throws IOException {
return Integer.parseInt(readString());
}
long readLong() throws IOException {
return Long.parseLong(readString());
}
double readDouble() throws IOException {
return Double.parseDouble(readString());
}
int[] readIntArray(int b) {
int a[] = new int[b];
for (int i = 0; i < b; i++)
try {
a[i] = readInt();
} catch (IOException e) {
e.printStackTrace();
}
return a;
}
int[] readSortedIntArray(int size) throws IOException {
Integer[] array = new Integer[size];
for (int index = 0; index < size; ++index) array[index] = readInt();
Arrays.sort(array);
int[] sortedArray = new int[size];
for (int index = 0; index < size; ++index) sortedArray[index] = array[index];
return sortedArray;
}
int[] sortedIntArray(int size, int[] array) throws IOException {
for (int index = 0; index < size; ++index) array[index] = readInt();
Arrays.sort(array);
int[] sortedArray = new int[size];
for (int index = 0; index < size; ++index) sortedArray[index] = array[index];
return sortedArray;
}
int minInt(int... values) {
int min = Integer.MAX_VALUE;
for (int value : values) min = Math.min(min, value);
return min;
}
int maxInt(int... values) {
int max = Integer.MIN_VALUE;
for (int value : values) max = Math.max(max, value);
return max;
}
long minLong(long... values) {
long min = Long.MAX_VALUE;
for (long value : values) min = Math.min(min, value);
return min;
}
long maxLong(long... values) {
long max = Long.MIN_VALUE;
for (long value : values) max = Math.max(max, value);
return max;
}
boolean checkIndex(int index, int size) {
return (0 <= index && index < size);
}
int abs(int a) {
if (a < 0) return -a;
return a;
}
} | Java | ["7 6\n6 4 1 10 3 2 4\n2 1 7\n2 4 5\n1 3 5\n2 4 4\n1 5 7\n2 1 7"] | 2 seconds | ["30\n13\n4\n22"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"number theory",
"brute force"
] | 078cdef32cb5e60dc66c66cae3d4a57a | The first line contains two integers n and m (1 ≤ n, m ≤ 3·105) — the number of elements in the array and the number of queries to process, respectively. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the array. Then m lines follow, each containing 3 integers ti, li, ri denoting i-th query. If ti = 1, then i-th query is REPLACE li ri, otherwise it's SUM li ri (1 ≤ ti ≤ 2, 1 ≤ li ≤ ri ≤ n). There is at least one SUM query. | 2,000 | For each SUM query print the answer to it. | standard output | |
PASSED | 71d3748f079b4fc1406a5e70f0d6af48 | train_000.jsonl | 1517582100 | Let D(x) be the number of positive divisors of a positive integer x. For example, D(2) = 2 (2 is divisible by 1 and 2), D(6) = 4 (6 is divisible by 1, 2, 3 and 6).You are given an array a of n integers. You have to process two types of queries: REPLACE l r — for every replace ai with D(ai); SUM l r — calculate . Print the answer for each SUM query. | 256 megabytes | /*
ЗАПУСКАЕМ ВЫСОКОГО
░ГУСЯ░▄▀▀▀▄░РАБОТЯГИ░░
▄███▀░◐░░░▌░░░░░░░
░░░░▌░░░░░▐░░░░░░░
░░░░▐░░░░░▐░░░░░░░
░░░░▌░░░░░▐▄▄░░░░░
░░░░▌░░░░░▐▄▄░░░░░
░░░░▌░░░░░▐▄▄░░░░░
░░░░▌░░░░░▐▄▄░░░░░
░░░░▌░░░░░▐▄▄░░░░░
░░░░▌░░░░░▐▄▄░░░░░
░░░░▌░░░░░▐▄▄░░░░░
░░░░▌░░░░░▐▄▄░░░░░
░░░░▌░░░░░▐▄▄░░░░░
░░░░▌░░░░░▐▄▄░░░░░
░░░░▌░░░░░▐▄▄░░░░░
░░░░▌░░░░░▐▄▄░░░░░
░░░░▌░░░░▄▀▒▒▀▀▀▀▄
░░░▐░░░░▐▒▒▒▒▒▒▒▒▀▀▄
░░░▐░░░░▐▄▒▒▒▒▒▒▒▒▒▒▀▄
░░░░▀▄░░░░▀▄▒▒▒▒▒▒▒▒▒▒▀▄
░░░░░░▀▄▄▄▄▄█▄▄▄▄▄▄▄▄▄▄▄▀▄
░░░░░░░░░░░▌▌░▌▌░░░░░
░░░░░░░░░░░▌▌░▌▌░░░░░
░░░░░░░░░▄▄▌▌▄▌▌░░░░░
*/
import java.io.*;
import java.util.*;
public class Main {
void solve() throws IOException {
simple_ints = new ArrayList<>();
int size = 1000001;
r = new boolean[size];
for (int i = 2; i < size; i++) if (!r[i]) for (int j = 2; j * i < size; j++) r[i * j] = true;
for (int i = 2; i < size; i++) if (!r[i]) simple_ints.add(i);
d = new int[size];
for (int i = 2; i < size; i++) d[i] = getD(0, i);
d[1] = 1;
int n = readInt();
int m = readInt();
int[] a = readIntArray(n);
TreeSet<Integer> st = new TreeSet<>();
for (int i = -1; i < n; i++) st.add(i);
for (int i = 0; i < n; i++) if (a[i] <= 2) st.remove(i);
Fenwik fen = new Fenwik(a);
while (m-- > 0) {
int type = readInt();
int lo = readInt() - 1;
int hi = readInt() - 1;
if (type == 1) {
int h = st.floor(hi);
while (h >= lo) {
int pref = a[h];
a[h] = d[a[h]];
fen.inc(h, a[h] - pref);
if (a[h] < 3) st.remove(h);
h = st.floor(h - 1);
}
} else out.println(fen.getSum(hi) - (lo > 0 ? fen.getSum(lo - 1) : 0));
}
}
int[] d;
ArrayList<Integer> simple_ints;
boolean[] r;
int getD(int index, int value) {
if (d[value] != 0) return d[value];
int k = 1;
while (value % simple_ints.get(index) == 0) {
k++;
value /= simple_ints.get(index);
}
if (value == 1) return k;
if (!r[value]) return (k << 1);
int next = getD(index + 1, value);
d[value] = next;
k *= next;
return k;
}
public static void main(String[] args) throws IOException {
new Main().run();
}
BufferedReader in;
PrintWriter out;
StringTokenizer tok;
Main() throws FileNotFoundException {
try {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
} catch (Exception e) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
tok = new StringTokenizer("");
}
void run() throws IOException {
solve();
out.close();
}
class Fenwik {
private long[] t;
private int length;
Fenwik(int[] a) {
this.length = a.length + 100;
this.t = new long[length];
for (int i = 0; i < a.length; ++i) this.inc(i, a[i]);
}
void inc(int i, int delta) {
for (; i < this.length; i = i | (i + 1)) t[i] += delta;
}
long getSum(int r) {
long sum = 0;
for (; r >= 0; r = (r & (r + 1)) - 1) sum += this.t[r];
return sum;
}
}
String delimiter = " ";
String readLine() throws IOException {
return in.readLine();
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
String nextLine = readLine();
if (null == nextLine) return null;
tok = new StringTokenizer(nextLine);
}
return tok.nextToken(delimiter);
}
int readInt() throws IOException {
return Integer.parseInt(readString());
}
long readLong() throws IOException {
return Long.parseLong(readString());
}
double readDouble() throws IOException {
return Double.parseDouble(readString());
}
int[] readIntArray(int b) {
int a[] = new int[b];
for (int i = 0; i < b; i++)
try {
a[i] = readInt();
} catch (IOException e) {
e.printStackTrace();
}
return a;
}
int[] readSortedIntArray(int size) throws IOException {
Integer[] array = new Integer[size];
for (int index = 0; index < size; ++index) array[index] = readInt();
Arrays.sort(array);
int[] sortedArray = new int[size];
for (int index = 0; index < size; ++index) sortedArray[index] = array[index];
return sortedArray;
}
int[] sortedIntArray(int size, int[] array) throws IOException {
for (int index = 0; index < size; ++index) array[index] = readInt();
Arrays.sort(array);
int[] sortedArray = new int[size];
for (int index = 0; index < size; ++index) sortedArray[index] = array[index];
return sortedArray;
}
int minInt(int... values) {
int min = Integer.MAX_VALUE;
for (int value : values) min = Math.min(min, value);
return min;
}
int maxInt(int... values) {
int max = Integer.MIN_VALUE;
for (int value : values) max = Math.max(max, value);
return max;
}
long minLong(long... values) {
long min = Long.MAX_VALUE;
for (long value : values) min = Math.min(min, value);
return min;
}
long maxLong(long... values) {
long max = Long.MIN_VALUE;
for (long value : values) max = Math.max(max, value);
return max;
}
boolean checkIndex(int index, int size) {
return (0 <= index && index < size);
}
int abs(int a) {
if (a < 0) return -a;
return a;
}
} | Java | ["7 6\n6 4 1 10 3 2 4\n2 1 7\n2 4 5\n1 3 5\n2 4 4\n1 5 7\n2 1 7"] | 2 seconds | ["30\n13\n4\n22"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"number theory",
"brute force"
] | 078cdef32cb5e60dc66c66cae3d4a57a | The first line contains two integers n and m (1 ≤ n, m ≤ 3·105) — the number of elements in the array and the number of queries to process, respectively. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the array. Then m lines follow, each containing 3 integers ti, li, ri denoting i-th query. If ti = 1, then i-th query is REPLACE li ri, otherwise it's SUM li ri (1 ≤ ti ≤ 2, 1 ≤ li ≤ ri ≤ n). There is at least one SUM query. | 2,000 | For each SUM query print the answer to it. | standard output | |
PASSED | f2685c36cb59b0b9e81146bbbe685423 | train_000.jsonl | 1517582100 | Let D(x) be the number of positive divisors of a positive integer x. For example, D(2) = 2 (2 is divisible by 1 and 2), D(6) = 4 (6 is divisible by 1, 2, 3 and 6).You are given an array a of n integers. You have to process two types of queries: REPLACE l r — for every replace ai with D(ai); SUM l r — calculate . Print the answer for each SUM query. | 256 megabytes | /*
ЗАПУСКАЕМ ВЫСОКОГО
░ГУСЯ░▄▀▀▀▄░РАБОТЯГИ░░
▄███▀░◐░░░▌░░░░░░░
░░░░▌░░░░░▐░░░░░░░
░░░░▐░░░░░▐░░░░░░░
░░░░▌░░░░░▐▄▄░░░░░
░░░░▌░░░░░▐▄▄░░░░░
░░░░▌░░░░░▐▄▄░░░░░
░░░░▌░░░░░▐▄▄░░░░░
░░░░▌░░░░░▐▄▄░░░░░
░░░░▌░░░░░▐▄▄░░░░░
░░░░▌░░░░░▐▄▄░░░░░
░░░░▌░░░░░▐▄▄░░░░░
░░░░▌░░░░░▐▄▄░░░░░
░░░░▌░░░░░▐▄▄░░░░░
░░░░▌░░░░░▐▄▄░░░░░
░░░░▌░░░░░▐▄▄░░░░░
░░░░▌░░░░▄▀▒▒▀▀▀▀▄
░░░▐░░░░▐▒▒▒▒▒▒▒▒▀▀▄
░░░▐░░░░▐▄▒▒▒▒▒▒▒▒▒▒▀▄
░░░░▀▄░░░░▀▄▒▒▒▒▒▒▒▒▒▒▀▄
░░░░░░▀▄▄▄▄▄█▄▄▄▄▄▄▄▄▄▄▄▀▄
░░░░░░░░░░░▌▌░▌▌░░░░░
░░░░░░░░░░░▌▌░▌▌░░░░░
░░░░░░░░░▄▄▌▌▄▌▌░░░░░
*/
import java.io.*;
import java.util.*;
public class Main {
void solve() throws IOException {
simple_ints = new ArrayList<>();
int size = 1000001;
r = new boolean[size];
for (int i = 2; i < size; i++) if (!r[i]) for (int j = 2; j * i < size; j++) r[i * j] = true;
for (int i = 2; i < size; i++) if (!r[i]) simple_ints.add(i);
d = new int[size];
for (int i = 2; i < size; i++) d[i] = getD(0, i);
d[1] = 1;
int n = readInt();
int m = readInt();
int[] a = readIntArray(n);
TreeSet<Integer> st = new TreeSet<>();
for (int i = -1; i < n; i++) st.add(i);
for (int i = 0; i < n; i++) if (a[i] <= 2) st.remove(i);
ArrayDeque<Integer> queue = new ArrayDeque<>();
Fenwik fen = new Fenwik(a);
while (m-- > 0) {
int type = readInt();
int lo = readInt() - 1;
int hi = readInt() - 1;
if (type == 1) {
int cur = st.floor(hi);
while (cur >= lo) {
int pref = a[cur];
a[cur] = d[a[cur]];
fen.inc(cur, a[cur] - pref);
st.remove(cur);
if (a[cur] > 2) queue.add(cur);
cur = st.floor(hi);
}
while (queue.size() > 0) st.add(queue.poll());
} else out.println(fen.getSum(hi) - (lo > 0 ? fen.getSum(lo - 1) : 0));
}
}
int[] d;
ArrayList<Integer> simple_ints;
boolean[] r;
int getD(int index, int value) {
if (d[value] != 0) return d[value];
int k = 1;
while (value % simple_ints.get(index) == 0) {
k++;
value /= simple_ints.get(index);
}
if (value == 1) return k;
if (!r[value]) return (k << 1);
int next = getD(index + 1, value);
d[value] = next;
k *= next;
return k;
}
public static void main(String[] args) throws IOException {
new Main().run();
}
BufferedReader in;
PrintWriter out;
StringTokenizer tok;
Main() throws FileNotFoundException {
try {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
} catch (Exception e) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
tok = new StringTokenizer("");
}
void run() throws IOException {
solve();
out.close();
}
class Fenwik {
private long[] t;
private int length;
Fenwik(int[] a) {
this.length = a.length + 100;
this.t = new long[length];
for (int i = 0; i < a.length; ++i) this.inc(i, a[i]);
}
void inc(int i, int delta) {
for (; i < this.length; i = i | (i + 1)) t[i] += delta;
}
long getSum(int r) {
long sum = 0;
for (; r >= 0; r = (r & (r + 1)) - 1) sum += this.t[r];
return sum;
}
}
String delimiter = " ";
String readLine() throws IOException {
return in.readLine();
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
String nextLine = readLine();
if (null == nextLine) return null;
tok = new StringTokenizer(nextLine);
}
return tok.nextToken(delimiter);
}
int readInt() throws IOException {
return Integer.parseInt(readString());
}
long readLong() throws IOException {
return Long.parseLong(readString());
}
double readDouble() throws IOException {
return Double.parseDouble(readString());
}
int[] readIntArray(int b) {
int a[] = new int[b];
for (int i = 0; i < b; i++)
try {
a[i] = readInt();
} catch (IOException e) {
e.printStackTrace();
}
return a;
}
int[] readSortedIntArray(int size) throws IOException {
Integer[] array = new Integer[size];
for (int index = 0; index < size; ++index) array[index] = readInt();
Arrays.sort(array);
int[] sortedArray = new int[size];
for (int index = 0; index < size; ++index) sortedArray[index] = array[index];
return sortedArray;
}
int[] sortedIntArray(int size, int[] array) throws IOException {
for (int index = 0; index < size; ++index) array[index] = readInt();
Arrays.sort(array);
int[] sortedArray = new int[size];
for (int index = 0; index < size; ++index) sortedArray[index] = array[index];
return sortedArray;
}
int minInt(int... values) {
int min = Integer.MAX_VALUE;
for (int value : values) min = Math.min(min, value);
return min;
}
int maxInt(int... values) {
int max = Integer.MIN_VALUE;
for (int value : values) max = Math.max(max, value);
return max;
}
long minLong(long... values) {
long min = Long.MAX_VALUE;
for (long value : values) min = Math.min(min, value);
return min;
}
long maxLong(long... values) {
long max = Long.MIN_VALUE;
for (long value : values) max = Math.max(max, value);
return max;
}
boolean checkIndex(int index, int size) {
return (0 <= index && index < size);
}
int abs(int a) {
if (a < 0) return -a;
return a;
}
} | Java | ["7 6\n6 4 1 10 3 2 4\n2 1 7\n2 4 5\n1 3 5\n2 4 4\n1 5 7\n2 1 7"] | 2 seconds | ["30\n13\n4\n22"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"number theory",
"brute force"
] | 078cdef32cb5e60dc66c66cae3d4a57a | The first line contains two integers n and m (1 ≤ n, m ≤ 3·105) — the number of elements in the array and the number of queries to process, respectively. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the array. Then m lines follow, each containing 3 integers ti, li, ri denoting i-th query. If ti = 1, then i-th query is REPLACE li ri, otherwise it's SUM li ri (1 ≤ ti ≤ 2, 1 ≤ li ≤ ri ≤ n). There is at least one SUM query. | 2,000 | For each SUM query print the answer to it. | standard output | |
PASSED | 609d5710ca296a2eec7b7229e6019f8d | train_000.jsonl | 1517582100 | Let D(x) be the number of positive divisors of a positive integer x. For example, D(2) = 2 (2 is divisible by 1 and 2), D(6) = 4 (6 is divisible by 1, 2, 3 and 6).You are given an array a of n integers. You have to process two types of queries: REPLACE l r — for every replace ai with D(ai); SUM l r — calculate . Print the answer for each SUM query. | 256 megabytes | /*
ЗАПУСКАЕМ ВЫСОКОГО
░ГУСЯ░▄▀▀▀▄░РАБОТЯГИ░░
▄███▀░◐░░░▌░░░░░░░
░░░░▌░░░░░▐░░░░░░░
░░░░▐░░░░░▐░░░░░░░
░░░░▌░░░░░▐▄▄░░░░░
░░░░▌░░░░░▐▄▄░░░░░
░░░░▌░░░░░▐▄▄░░░░░
░░░░▌░░░░░▐▄▄░░░░░
░░░░▌░░░░░▐▄▄░░░░░
░░░░▌░░░░░▐▄▄░░░░░
░░░░▌░░░░░▐▄▄░░░░░
░░░░▌░░░░░▐▄▄░░░░░
░░░░▌░░░░░▐▄▄░░░░░
░░░░▌░░░░░▐▄▄░░░░░
░░░░▌░░░░░▐▄▄░░░░░
░░░░▌░░░░░▐▄▄░░░░░
░░░░▌░░░░▄▀▒▒▀▀▀▀▄
░░░▐░░░░▐▒▒▒▒▒▒▒▒▀▀▄
░░░▐░░░░▐▄▒▒▒▒▒▒▒▒▒▒▀▄
░░░░▀▄░░░░▀▄▒▒▒▒▒▒▒▒▒▒▀▄
░░░░░░▀▄▄▄▄▄█▄▄▄▄▄▄▄▄▄▄▄▀▄
░░░░░░░░░░░▌▌░▌▌░░░░░
░░░░░░░░░░░▌▌░▌▌░░░░░
░░░░░░░░░▄▄▌▌▄▌▌░░░░░
*/
import java.io.*;
import java.util.*;
public class Main {
void solve() throws IOException {
simple_ints = new ArrayList<>();
int size = 1000001;
r = new boolean[size];
for (int i = 2; i < size; i++) if (!r[i]) for (int j = 2; j * i < size; j++) r[i * j] = true;
for (int i = 2; i < size; i++) if (!r[i]) simple_ints.add(i);
d = new int[size];
for (int i = 2; i < size; i++) d[i] = getD(0, i);
d[1] = 1;
int n = readInt();
int m = readInt();
int[] a = readIntArray(n);
TreeSet<Integer> st = new TreeSet<>();
for (int i = -1; i < n; i++) st.add(i);
for (int i = 0; i < n; i++) if (a[i] <= 2) st.remove(i);
int lo, hi, pref;
Fenwik fen = new Fenwik(a);
while (m-- > 0) {
int type = readInt();
lo = readInt() - 1;
hi = readInt() - 1;
if (type == 1) {
int h = st.floor(hi);
while (h >= lo) {
pref = a[h];
a[h] = d[a[h]];
fen.inc(h, a[h] - pref);
if (a[h] < 3) st.remove(h);
h = st.floor(h - 1);
}
} else out.println(fen.getSum(hi) - (lo > 0 ? fen.getSum(lo - 1) : 0));
}
}
int[] d;
ArrayList<Integer> simple_ints;
boolean[] r;
int getD(int index, int value) {
if (d[value] != 0) return d[value];
int k = 1;
while (value % simple_ints.get(index) == 0) {
k++;
value /= simple_ints.get(index);
}
if (value == 1) return k;
if (!r[value]) return (k << 1);
d[value] = getD(index + 1, value);;
k *= d[value];
return k;
}
public static void main(String[] args) throws IOException {
new Main().run();
}
BufferedReader in;
PrintWriter out;
StringTokenizer tok;
Main() throws FileNotFoundException {
try {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
} catch (Exception e) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
tok = new StringTokenizer("");
}
void run() throws IOException {
solve();
out.close();
}
class Fenwik {
private long[] t;
private int length;
Fenwik(int[] a) {
this.length = a.length + 100;
this.t = new long[length];
for (int i = 0; i < a.length; ++i) this.inc(i, a[i]);
}
void inc(int i, int delta) {
for (; i < this.length; i = i | (i + 1)) t[i] += delta;
}
long getSum(int r) {
long sum = 0;
for (; r >= 0; r = (r & (r + 1)) - 1) sum += this.t[r];
return sum;
}
}
String delimiter = " ";
String readLine() throws IOException {
return in.readLine();
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
String nextLine = readLine();
if (null == nextLine) return null;
tok = new StringTokenizer(nextLine);
}
return tok.nextToken(delimiter);
}
int readInt() throws IOException {
return Integer.parseInt(readString());
}
long readLong() throws IOException {
return Long.parseLong(readString());
}
double readDouble() throws IOException {
return Double.parseDouble(readString());
}
int[] readIntArray(int b) {
int a[] = new int[b];
for (int i = 0; i < b; i++)
try {
a[i] = readInt();
} catch (IOException e) {
e.printStackTrace();
}
return a;
}
int[] readSortedIntArray(int size) throws IOException {
Integer[] array = new Integer[size];
for (int index = 0; index < size; ++index) array[index] = readInt();
Arrays.sort(array);
int[] sortedArray = new int[size];
for (int index = 0; index < size; ++index) sortedArray[index] = array[index];
return sortedArray;
}
int[] sortedIntArray(int size, int[] array) throws IOException {
for (int index = 0; index < size; ++index) array[index] = readInt();
Arrays.sort(array);
int[] sortedArray = new int[size];
for (int index = 0; index < size; ++index) sortedArray[index] = array[index];
return sortedArray;
}
int minInt(int... values) {
int min = Integer.MAX_VALUE;
for (int value : values) min = Math.min(min, value);
return min;
}
int maxInt(int... values) {
int max = Integer.MIN_VALUE;
for (int value : values) max = Math.max(max, value);
return max;
}
long minLong(long... values) {
long min = Long.MAX_VALUE;
for (long value : values) min = Math.min(min, value);
return min;
}
long maxLong(long... values) {
long max = Long.MIN_VALUE;
for (long value : values) max = Math.max(max, value);
return max;
}
boolean checkIndex(int index, int size) {
return (0 <= index && index < size);
}
int abs(int a) {
if (a < 0) return -a;
return a;
}
} | Java | ["7 6\n6 4 1 10 3 2 4\n2 1 7\n2 4 5\n1 3 5\n2 4 4\n1 5 7\n2 1 7"] | 2 seconds | ["30\n13\n4\n22"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"number theory",
"brute force"
] | 078cdef32cb5e60dc66c66cae3d4a57a | The first line contains two integers n and m (1 ≤ n, m ≤ 3·105) — the number of elements in the array and the number of queries to process, respectively. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the array. Then m lines follow, each containing 3 integers ti, li, ri denoting i-th query. If ti = 1, then i-th query is REPLACE li ri, otherwise it's SUM li ri (1 ≤ ti ≤ 2, 1 ≤ li ≤ ri ≤ n). There is at least one SUM query. | 2,000 | For each SUM query print the answer to it. | standard output | |
PASSED | 2c3d367e5277e630fc282043933c584a | train_000.jsonl | 1517582100 | Let D(x) be the number of positive divisors of a positive integer x. For example, D(2) = 2 (2 is divisible by 1 and 2), D(6) = 4 (6 is divisible by 1, 2, 3 and 6).You are given an array a of n integers. You have to process two types of queries: REPLACE l r — for every replace ai with D(ai); SUM l r — calculate . Print the answer for each SUM query. | 256 megabytes |
import java.util.*;
import java.io.*;
public class Main {
long[]lo,hi,sum,max,D;
public Main(int arr[]){
int n=arr.length;
lo=new long[4*n+1];
hi=new long[4*n+1];
max=new long[4*n+1];
sum=new long[4*n+1];
D=new long[1000002];
D();
init(1,0,n-1,arr);
}
public void D(){
int n=1000002;
for(int i=1;i<n;i++){
for(int j=i;j<n;j+=i){
D[j]++;
}
}
}
public void init(int i,int l,int r,int arr[]){
lo[i]=l;
hi[i]=r;
if(l==r){
sum[i]=arr[l];
max[i]=arr[r];
return;
}
int m=(l+r)/2;
init(2*i,l,m,arr);
init(2*i+1,m+1,r,arr);
sum[i]=sum[2*i]+sum[2*i+1];
max[i]=Math.max(max[2*i], max[2*i+1]);
}
public void update(int i,int l,int r){
if(max[i]<3)return;
if(lo[i]>r||hi[i]<l)return;
if(lo[i]==hi[i]){
sum[i]=D[(int)sum[i]];
max[i]=D[(int)max[i]];
return;
}
update(2*i,l,r);
update(2*i+1,l,r);
sum[i]=sum[2*i+1]+sum[2*i];
max[i]=Math.max(max[2*i], max[2*i+1]);
}
public long sum(int i,int l,int r){
if(lo[i]>r || hi[i]<l)return 0;
if(lo[i]>=l && hi[i]<=r)return sum[i];
return sum(2*i,l,r)+sum(2*i+1,l,r);
}
public static void main(String[] args) throws IOException {
FastScanner sc=new FastScanner(System.in);
StringBuilder ans=new StringBuilder();
int n=sc.nextInt();
int m=sc.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++)a[i]=sc.nextInt();
Main s=new Main(a);
for(int i=0;i<m;i++){
int t=sc.nextInt();
int l=sc.nextInt()-1;
int r=sc.nextInt()-1;
switch(t){
case 1:
s.update(1, l, r);
break;
case 2:
ans.append(s.sum(1, l, r)+"\n");
break;
}
}
System.out.print(ans.toString());
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream i) {
br = new BufferedReader(new InputStreamReader(i));
st = new StringTokenizer("");
}
public String next() throws IOException {
if(st.hasMoreTokens())return st.nextToken();
else st = new StringTokenizer(br.readLine());
return next();
}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public double nextDouble() throws IOException {return Double.parseDouble(next());}
}
} | Java | ["7 6\n6 4 1 10 3 2 4\n2 1 7\n2 4 5\n1 3 5\n2 4 4\n1 5 7\n2 1 7"] | 2 seconds | ["30\n13\n4\n22"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"number theory",
"brute force"
] | 078cdef32cb5e60dc66c66cae3d4a57a | The first line contains two integers n and m (1 ≤ n, m ≤ 3·105) — the number of elements in the array and the number of queries to process, respectively. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the array. Then m lines follow, each containing 3 integers ti, li, ri denoting i-th query. If ti = 1, then i-th query is REPLACE li ri, otherwise it's SUM li ri (1 ≤ ti ≤ 2, 1 ≤ li ≤ ri ≤ n). There is at least one SUM query. | 2,000 | For each SUM query print the answer to it. | standard output | |
PASSED | f015ef3ce396509bd6b5212f9f7aadc0 | train_000.jsonl | 1517582100 | Let D(x) be the number of positive divisors of a positive integer x. For example, D(2) = 2 (2 is divisible by 1 and 2), D(6) = 4 (6 is divisible by 1, 2, 3 and 6).You are given an array a of n integers. You have to process two types of queries: REPLACE l r — for every replace ai with D(ai); SUM l r — calculate . Print the answer for each SUM query. | 256 megabytes |
import java.io.*;
import java.util.Random;
import java.util.StringTokenizer;
public class Main {
static class Solution extends Helper {
static int[] memo;
static int d(int n) {
return memo[n];
}
public void solve(InputReader in, PrintWriter out) {
memo = new int[(int) 1e6 + 2];
for (int i = 1; i < (int) 1e6 + 2; i++)
for (int j = i; j < (int) 1e6 + 2; j += i)
memo[j]++;
int n = in.getInt(), m = in.getInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = in.getInt();
Seg seg = new Seg(a);
while (m-- > 0) {
int t = in.getInt(), l = in.getInt() - 1, r = in.getInt() - 1;
if (t == 1) seg.update(1, 0, n - 1, l, r);
else out.println(seg.query(1, 0, n - 1, l, r));
}
}
static class Seg {
int[] a;
long[] tree;
boolean[] finished;
int n;
Seg(int[] aa) {
a = aa;
n = a.length;
tree = new long[n << 2];
finished = new boolean[n << 2];
build(1, 0, n - 1);
}
void build(int node, int s, int e) {
if (s == e) {
tree[node] = a[s];
finished[node] = a[s] <= 2;
} else {
int mid = s + e >> 1;
build(node << 1, s, mid);
build(node << 1 | 1, mid + 1, e);
tree[node] = tree[node << 1] + tree[node << 1 | 1];
finished[node] = finished[node << 1] && finished[node << 1 | 1];
}
}
void update(int node, int s, int e, int l, int r) {
if (s > r || e < l) return;
if (finished[node]) return;
if (s == e) {
finished[node] = (tree[node] = d((int) tree[node])) <= 2;
} else {
int mid = s + e >> 1;
update(node << 1, s, mid, l, r);
update(node << 1 | 1, mid + 1, e, l, r);
tree[node] = tree[node << 1] + tree[node << 1 | 1];
finished[node] = finished[node << 1] && finished[node << 1 | 1];
}
}
long query(int node, int s, int e, int l, int r) {
if (s > r || e < l) return 0;
if (s >= l && e <= r) return tree[node];
int mid = s + e >> 1;
return query(node << 1, s, mid, l, r) + query(node << 1 | 1, mid + 1, e, l, r);
}
}
}
public static void main(String[] args) {
Helper helper = new Helper();
helper.RUN();
}
public static class Helper {
public boolean online_judge = System.getProperty("ONLINE_JUDGE") != null;
public static final int INF = Integer.MAX_VALUE;
public static final long INFF = Long.MAX_VALUE;
public static final double PI = Math.PI;
public void RUN() {
Solution solution = new Solution();
InputStream inputStream = System.in;
if (!online_judge)
try {
inputStream = online_judge ? System.in : new FileInputStream("./src/com/company/in.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
if (!online_judge) {
int cur_ans = 1;
while (true) {
try {
if (!in.bufferedReader.ready()) break;
} catch (IOException e) {
e.printStackTrace();
}
out.print("It is test#" + cur_ans + "\n\n");
solution.solve(in, out);
out.print("\n\n");
cur_ans++;
try {
COPY_FILE(inputStream, outputStream, in, out);
} catch (IOException e) {
e.printStackTrace();
}
}
} else
solution.solve(in, out);
out.close();
out.flush();
}
private void COPY_FILE(InputStream inputStream, OutputStream outputStream, InputReader in, PrintWriter out) throws IOException {
inputStream = new FileInputStream("./src/com/company/Main.java");
outputStream = new FileOutputStream("./src/com/company/output/Main.java");
in = new InputReader(inputStream);
out = new PrintWriter(outputStream);
String line = "";
while (in.bufferedReader.ready()) {
line = in.getLine();
if(!line.equals("package com.company;"))
out.write(line + "\n");
}
out.close();
}
}
public static class InputReader {
private BufferedReader bufferedReader;
private StringTokenizer stringTokenizer;
private String line;
public InputReader(InputStream inputStream) {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
stringTokenizer = null;
}
public String getLine() {
line = "";
try {
line = bufferedReader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return line;
}
public String getString() {
while (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) {
try {
stringTokenizer = new StringTokenizer(bufferedReader.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return stringTokenizer.nextToken();
}
public int getInt() {
return Integer.parseInt(getString());
}
public long getLong() {
return Long.parseLong(getString());
}
public double getDouble() {
return Double.parseDouble(getString());
}
}
}
| Java | ["7 6\n6 4 1 10 3 2 4\n2 1 7\n2 4 5\n1 3 5\n2 4 4\n1 5 7\n2 1 7"] | 2 seconds | ["30\n13\n4\n22"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"number theory",
"brute force"
] | 078cdef32cb5e60dc66c66cae3d4a57a | The first line contains two integers n and m (1 ≤ n, m ≤ 3·105) — the number of elements in the array and the number of queries to process, respectively. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the array. Then m lines follow, each containing 3 integers ti, li, ri denoting i-th query. If ti = 1, then i-th query is REPLACE li ri, otherwise it's SUM li ri (1 ≤ ti ≤ 2, 1 ≤ li ≤ ri ≤ n). There is at least one SUM query. | 2,000 | For each SUM query print the answer to it. | standard output | |
PASSED | 87feaa9eeab694e0b7de4ebb007ff6d0 | train_000.jsonl | 1517582100 | Let D(x) be the number of positive divisors of a positive integer x. For example, D(2) = 2 (2 is divisible by 1 and 2), D(6) = 4 (6 is divisible by 1, 2, 3 and 6).You are given an array a of n integers. You have to process two types of queries: REPLACE l r — for every replace ai with D(ai); SUM l r — calculate . Print the answer for each SUM query. | 256 megabytes | import java.io.*;
import java.util.StringTokenizer;
public class Test {
static InputReader in;
static PrintWriter out;
static int[] divisors;
public static void main(String[] args) {
in = new InputReader();
out = new PrintWriter(System.out);
int size = (int)1e6;
divisors = new int[size+1];
for(int i=1;i<=size;++i){
int j = i;
while(j<=size){
divisors[j]++;
j+=i;
}
}
int n = in.ni();
int m = in.ni();
long[] arr = new long[n];
for(int i=0;i<n;++i)
arr[i] = in.ni();
SegmentTree tree = new SegmentTree(arr,n);
while(m-->0){
int type = in.ni();
int l = in.ni()-1;
int r = in.ni()-1;
if(type==1)
tree.replace(0,n-1,l,r,0);
else
out.println(tree.query(0,n-1,l,r,0));
}
out.close();
}
static class Element{
long sum;
boolean allOnesTwos;
Element(long sum, boolean allOnesTwos) {
this.sum = sum;
this.allOnesTwos = allOnesTwos;
}
}
static class SegmentTree{
Element[] tree;
long[] check;
void replace(int start,int end,int qStart,int qEnd,int index){
if(start>qEnd || end<qStart)
return;
if(tree[index].allOnesTwos)
return;
if(start==end){
tree[index].sum = divisors[(int)tree[index].sum];
if(tree[index].sum<=2)
tree[index].allOnesTwos = true;
else
tree[index].allOnesTwos = false;
return;
}
int mid = (start+end)/2;
replace(start,mid,qStart,qEnd,2*index+1);
replace(mid+1,end,qStart,qEnd,2*index+2);
tree[index].sum = tree[2*index+1].sum+tree[2*index+2].sum;
tree[index].allOnesTwos = tree[2*index+1].allOnesTwos && tree[2*index+2].allOnesTwos;
}
long query(int start,int end,int qStart,int qEnd,int index){
if(qStart<=start && qEnd>=end)
return tree[index].sum;
if(start>qEnd || end<qStart)
return 0;
int mid = (start+end)/2;
long first = query(start,mid,qStart,qEnd,2*index+1);
long sec = query(mid+1,end,qStart,qEnd,2*index+2);
return first+sec;
}
SegmentTree(long[] arr,int n){
int temp = (int)Math.ceil(Math.log(n)/Math.log(2));
int sss = 2*(int)Math.pow(2,temp)-1;
check = new long[n];
for(int i=0;i<n;++i)
check[i] = arr[i];
tree = new Element[sss];
for(int i=0;i<sss;++i)
tree[i] = new Element(0,true);
construct(0,n-1,0);
}
void construct(int start,int end,int index){
if(start>end)
return;
if(start==end){
if(check[start]==1 || check[start]==2){
tree[index].allOnesTwos = true;
}
else{
tree[index].allOnesTwos = false;
}
tree[index].sum = check[start];
return;
}
int mid = (start+end)/2;
construct(start,mid,2*index+1);
construct(mid+1,end,2*index+2);
tree[index].sum = tree[2*index+1].sum+tree[2*index+2].sum;
tree[index].allOnesTwos = tree[2*index+1].allOnesTwos && tree[2*index+2].allOnesTwos;
}
}
static class InputReader{
BufferedReader br;
StringTokenizer st;
public InputReader(){
br = new BufferedReader(new InputStreamReader(System.in));
}
String n(){
while (st == null || !st.hasMoreElements()){
try{
st = new StringTokenizer(br.readLine());
}
catch (IOException e){}
}
return st.nextToken();
}
int ni(){
return Integer.parseInt(n());
}
long nl(){
return Long.parseLong(n());
}
double nd(){
return Double.parseDouble(n());
}
String nli(){
String str = "";
try{
str = br.readLine();
}
catch (IOException e){}
return str;
}
int[] nia(int[] arr,int start,int end){
for(int i=start;i<end;++i)
arr[i] = ni();
return arr;
}
}
}
| Java | ["7 6\n6 4 1 10 3 2 4\n2 1 7\n2 4 5\n1 3 5\n2 4 4\n1 5 7\n2 1 7"] | 2 seconds | ["30\n13\n4\n22"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"number theory",
"brute force"
] | 078cdef32cb5e60dc66c66cae3d4a57a | The first line contains two integers n and m (1 ≤ n, m ≤ 3·105) — the number of elements in the array and the number of queries to process, respectively. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the array. Then m lines follow, each containing 3 integers ti, li, ri denoting i-th query. If ti = 1, then i-th query is REPLACE li ri, otherwise it's SUM li ri (1 ≤ ti ≤ 2, 1 ≤ li ≤ ri ≤ n). There is at least one SUM query. | 2,000 | For each SUM query print the answer to it. | standard output | |
PASSED | ac986e7d9a7931bcb6cc2874487d2e37 | train_000.jsonl | 1517582100 | Let D(x) be the number of positive divisors of a positive integer x. For example, D(2) = 2 (2 is divisible by 1 and 2), D(6) = 4 (6 is divisible by 1, 2, 3 and 6).You are given an array a of n integers. You have to process two types of queries: REPLACE l r — for every replace ai with D(ai); SUM l r — calculate . Print the answer for each SUM query. | 256 megabytes |
import java.io.*;
import java.lang.reflect.Array;
import java.math.*;
import java.text.DecimalFormat;
import java.util.*;
public class Main {
private static final int MAX = 1000*1000,MAXP2 = 1 << 19,MAXST = MAXP2 << 1;
private static int n,m;
private static int [] A;
private static int [] sig0;
private static long [] ST = new long[MAXST];
private static boolean [] finite = new boolean[MAXST];
private static void init(){
sig0 = new int[MAX + 1];
for (int i = 1;i <= MAX;i++)
for (int j = i;j <= MAX;j += i)
sig0[j] ++;
}
private static void build(int node,int s,int e) {
if (s == e) {
ST[node] = A[s];
finite[node] = A[s] == sig0[A[s]];
return;
}
int m = (s + e) >> 1,left = node*2 + 1,right = left + 1;
build(left,s,m);
build(right,m+1,e);
ST[node] = ST[left] + ST[right];
finite[node] = finite[left] && finite[right];
}
private static void update(int node,int s,int e,int l,int r) {
if (finite[node]) return;
if (s == e) {
A[s] = sig0[A[s]];
ST[node] = A[s];
finite[node] = A[s] == sig0[A[s]];
return;
}
int m = (s + e) >> 1,left = node*2 + 1,right = left + 1;
if (r <= m) update(left,s,m,l,r);
else if (m < l) update(right,m+1,e,l,r);
else {
update(left,s,m,l,m);
update(right,m+1,e,m+1,r);
}
ST[node] = ST[left] + ST[right];
finite[node] = finite[left] && finite[right];
}
private static long query(int node,int s,int e,int l,int r) {
if (l <= s && e <= r) return ST[node];
int m = (s + e) >> 1,left = node*2 + 1,right = left + 1;
if (r <= m) return query(left,s,m,l,r);
else if (m < l) return query(right,m+1,e,l,r);
else return query(left,s,m,l,m) + query(right,m+1,e,m+1,r);
}
public static void main(String[] args) throws Exception{
IO io = new IO(null,null);
init();
n = io.getNextInt();
m = io.getNextInt();
A = new int[n + 1];
for (int i = 1;i <= n;i++) A[i] = io.getNextInt();
build(0,1,n);
while (m-- > 0) {
int t = io.getNextInt(),l = io.getNextInt(),r = io.getNextInt();
if (t == 1) update(0,1,n,l,r);
else io.println(query(0,1,n,l,r));
}
io.close();
}
}
class IO{
private BufferedReader br;
private StringTokenizer st;
private PrintWriter writer;
private String inputFile,outputFile;
public boolean hasMore() throws IOException{
if(st != null && st.hasMoreTokens()) return true;
if(br != null && br.ready()) return true;
return false;
}
public String getNext() throws FileNotFoundException, IOException{
while(st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String getNextLine() throws FileNotFoundException, IOException{
return br.readLine().trim();
}
public int getNextInt() throws FileNotFoundException, IOException{
return Integer.parseInt(getNext());
}
public long getNextLong() throws FileNotFoundException, IOException{
return Long.parseLong(getNext());
}
public void print(double x,int num_digits) throws IOException{
writer.printf("%." + num_digits + "f" ,x);
}
public void println(double x,int num_digits) throws IOException{
writer.printf("%." + num_digits + "f\n" ,x);
}
public void print(Object o) throws IOException{
writer.print(o.toString());
}
public void println(Object o) throws IOException{
writer.println(o.toString());
}
public IO(String x,String y) throws FileNotFoundException, IOException{
inputFile = x;
outputFile = y;
if(x != null) br = new BufferedReader(new FileReader(inputFile));
else br = new BufferedReader(new InputStreamReader(System.in));
if(y != null) writer = new PrintWriter(new BufferedWriter(new FileWriter(outputFile)));
else writer = new PrintWriter(new OutputStreamWriter(System.out));
}
protected void close() throws IOException{
br.close();
writer.close();
}
public void outputArr(Object [] A) throws IOException{
int L = A.length;
for (int i = 0;i < L;i++) {
if(i > 0) writer.print(" ");
writer.print(A[i]);
}
writer.print("\n");
}
}
| Java | ["7 6\n6 4 1 10 3 2 4\n2 1 7\n2 4 5\n1 3 5\n2 4 4\n1 5 7\n2 1 7"] | 2 seconds | ["30\n13\n4\n22"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"number theory",
"brute force"
] | 078cdef32cb5e60dc66c66cae3d4a57a | The first line contains two integers n and m (1 ≤ n, m ≤ 3·105) — the number of elements in the array and the number of queries to process, respectively. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the array. Then m lines follow, each containing 3 integers ti, li, ri denoting i-th query. If ti = 1, then i-th query is REPLACE li ri, otherwise it's SUM li ri (1 ≤ ti ≤ 2, 1 ≤ li ≤ ri ≤ n). There is at least one SUM query. | 2,000 | For each SUM query print the answer to it. | standard output | |
PASSED | 591a8b5ca96b85193ce00d7c7e92f986 | train_000.jsonl | 1517582100 | Let D(x) be the number of positive divisors of a positive integer x. For example, D(2) = 2 (2 is divisible by 1 and 2), D(6) = 4 (6 is divisible by 1, 2, 3 and 6).You are given an array a of n integers. You have to process two types of queries: REPLACE l r — for every replace ai with D(ai); SUM l r — calculate . Print the answer for each SUM query. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.FilterInputStream;
import java.io.BufferedInputStream;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author khokharnikunj8
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
ScanReader in = new ScanReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
BK1 solver = new BK1();
solver.solve(1, in, out);
out.close();
}
static class BK1 {
int[] D;
int[] lazy;
int[] array;
long[][] tree;
private void pre() {
D = new int[1000007];
D[1] = 1;
for (int i = 2; i < 1000007; i++) {
D[i]++;
for (int j = i; j < 1000007; j += i) D[j]++;
}
}
private void updateLazy(int node, long val, int start, int end) {
if (val != 0) {
for (int i = 0; i <= 7; i++) {
if (i + val > 7) tree[node][i] = tree[node][7];
else tree[node][i] = tree[node][(int) (i + val)];
}
if (start != end) {
lazy[node << 1] += val;
lazy[(node << 1) + 1] += val;
}
lazy[node] = 0;
}
}
private void update(int node, int start, int end, int l, int r) {
updateLazy(node, lazy[node], start, end);
if (tree[node][0] == (end - start + 1))
return;
if (l <= start && end <= r) {
updateLazy(node, 1, start, end);
return;
}
if (l > end || r < start) return;
int mid = (start + end) >> 1;
update(node << 1, start, mid, l, r);
update((node << 1) + 1, mid + 1, end, l, r);
for (int i = 0; i <= 7; i++) tree[node][i] = (tree[node << 1][i] + tree[(node << 1) + 1][i]);
}
private long query(int node, int start, int end, int l, int r) {
updateLazy(node, lazy[node], start, end);
if (l > end || r < start) return 0;
if (l <= start && end <= r) return tree[node][0];
int mid = (start + end) >> 1;
return query(node << 1, start, mid, l, r) +
query((node << 1) + 1, mid + 1, end, l, r);
}
private void build(int node, int start, int end) {
if (start == end) {
tree[node][0] = array[start];
for (int i = 1; i <= 7; i++) tree[node][i] = D[(int) tree[node][i - 1]];
} else {
int mid = (start + end) >> 1;
build(node << 1, start, mid);
build((node << 1) + 1, mid + 1, end);
for (int i = 0; i <= 7; i++) tree[node][i] = (tree[node << 1][i] + tree[(node << 1) + 1][i]);
}
}
public void solve(int testNumber, ScanReader in, PrintWriter out) {
int n = in.scanInt();
int m = in.scanInt();
array = new int[n + 1];
tree = new long[4 * (n + 1)][8];
lazy = new int[4 * (n + 1)];
pre();
for (int i = 1; i <= n; i++) array[i] = in.scanInt();
build(1, 1, n);
int state, l, r;
while (m-- > 0) {
state = in.scanInt();
l = in.scanInt();
r = in.scanInt();
if (state == 1) update(1, 1, n, l, r);
else out.println(query(1, 1, n, l, r));
}
}
}
static class ScanReader {
private byte[] buf = new byte[4 * 1024];
private int index;
private BufferedInputStream in;
private int total;
public ScanReader(InputStream inputStream) {
in = new BufferedInputStream(inputStream);
}
private int scan() {
if (index >= total) {
index = 0;
try {
total = in.read(buf);
} catch (Exception e) {
e.printStackTrace();
}
if (total <= 0) return -1;
}
return buf[index++];
}
public int scanInt() {
int 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();
}
}
return neg * integer;
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true;
else return false;
}
}
}
| Java | ["7 6\n6 4 1 10 3 2 4\n2 1 7\n2 4 5\n1 3 5\n2 4 4\n1 5 7\n2 1 7"] | 2 seconds | ["30\n13\n4\n22"] | null | Java 8 | standard input | [
"data structures",
"dsu",
"number theory",
"brute force"
] | 078cdef32cb5e60dc66c66cae3d4a57a | The first line contains two integers n and m (1 ≤ n, m ≤ 3·105) — the number of elements in the array and the number of queries to process, respectively. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the array. Then m lines follow, each containing 3 integers ti, li, ri denoting i-th query. If ti = 1, then i-th query is REPLACE li ri, otherwise it's SUM li ri (1 ≤ ti ≤ 2, 1 ≤ li ≤ ri ≤ n). There is at least one SUM query. | 2,000 | For each SUM query print the answer to it. | standard output | |
PASSED | cc42b8c2ec01d93d69bfe05cb0bbad8a | train_000.jsonl | 1277391600 | Pete and Bob invented a new interesting game. Bob takes a sheet of paper and locates a Cartesian coordinate system on it as follows: point (0, 0) is located in the bottom-left corner, Ox axis is directed right, Oy axis is directed up. Pete gives Bob requests of three types: add x y — on the sheet of paper Bob marks a point with coordinates (x, y). For each request of this type it's guaranteed that point (x, y) is not yet marked on Bob's sheet at the time of the request. remove x y — on the sheet of paper Bob erases the previously marked point with coordinates (x, y). For each request of this type it's guaranteed that point (x, y) is already marked on Bob's sheet at the time of the request. find x y — on the sheet of paper Bob finds all the marked points, lying strictly above and strictly to the right of point (x, y). Among these points Bob chooses the leftmost one, if it is not unique, he chooses the bottommost one, and gives its coordinates to Pete. Bob managed to answer the requests, when they were 10, 100 or 1000, but when their amount grew up to 2·105, Bob failed to cope. Now he needs a program that will answer all Pete's requests. Help Bob, please! | 256 megabytes | import java.util.List;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.TreeMap;
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.AbstractMap;
import java.util.StringTokenizer;
import java.math.BigInteger;
import java.util.Collection;
import java.util.Collections;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author AlexFetisov
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD_Points solver = new TaskD_Points();
solver.solve(1, in, out);
out.close();
}
}
class TaskD_Points {
TreeMap<Integer, Integer>[] yToX;
private SegmentTree tree;
private CompressData compressData;
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
Query[] queries = new Query[n];
compressData = new CompressData();
for (int i = 0; i < n; ++i) {
queries[i] = new Query(in.nextString(), in.nextInt(), in.nextInt());
compressData.add(queries[i].x);
}
compressData.build();
for (Query q : queries) {
q.x = compressData.originalToMapping(q.x);
}
tree = new SegmentTree(compressData.getSize());
yToX = new TreeMap[compressData.getSize()];
for (int i = 0; i < compressData.getSize(); ++i) {
yToX[i] = new TreeMap<Integer, Integer>();
}
for (Query q : queries) {
if (q.type == TYPE.ADD) {
addPoint(q.x, q.y);
} else if (q.type == TYPE.REMOVE) {
removePoint(q.x, q.y);
} else {
findPoint(out, q.x, q.y);
}
}
}
class SegmentTree {
int[] max;
int maxRight;
int maxTree;
SegmentTree(int size) {
maxTree = 1;
while (maxTree <= size) maxTree <<= 1;
maxRight = maxTree - 1;
maxTree <<= 1;
max = new int[maxTree];
}
void set(int x, int y) {
int v = maxRight + 1 + x;
max[v] = y;
v >>= 1;
while (v > 0) {
max[v] = Math.max(max[v * 2], max[v * 2 + 1]);
v >>= 1;
}
}
Integer getX(int x, int y) {
int t = get(1, 0, maxRight, x, y);
if (t == -1) return null;
return t;
}
private int get(int v, int rangeLeft, int rangeRight, int left, int y) {
if (rangeLeft == rangeRight) {
if (max[v] <= y) {
return -1;
}
return v - maxRight - 1;
}
int middle = (rangeLeft + rangeRight) / 2;
if (max[v] <= y) {
return -1;
}
if (left <= middle) {
int res = get(2 * v, rangeLeft, middle, left, y);
if (res != -1) return res;
}
return get(2 * v + 1, middle + 1, rangeRight, left, y);
}
}
private void findPoint(PrintWriter out, int x, int y) {
Integer nx = tree.getX(x + 1, y);
if (nx == null) {
out.println(-1);
} else {
int ny = yToX[nx.intValue()].higherKey(y);
out.println(compressData.mappingToOriginal(nx.intValue()) + " " + ny);
}
}
private void addPoint(int x, int y) {
Integer max = getMaxY(x);
if (max == null || max < y) {
tree.set(x, y);
}
addToMap(x, y);
}
private void addToMap(int x, int y) {
if (yToX[x].containsKey(y)) {
yToX[x].put(y, yToX[x].get(y) + 1);
} else {
yToX[x].put(y, 1);
}
}
private void removeToMap(int x, int y) {
if (yToX[x].get(y) == 1) {
yToX[x].remove(y);
} else {
yToX[x].put(y, yToX[x].get(y) - 1);
}
}
private Integer getMaxY(int x) {
if (yToX[x].isEmpty()) return null;
return yToX[x].lastKey();
}
private void removePoint(int x, int y) {
Integer max = getMaxY(x);
if (max == y) {
removeToMap(x, y);
Integer ny = getMaxY(x);
if (ny != null) {
tree.set(x, ny.intValue());
} else {
tree.set(x, 0);
}
} else {
removeToMap(x, y);
}
}
enum TYPE {
ADD,
REMOVE,
ASK
}
class Query {
TYPE type;
int x, y;
Query(String s, int x, int y) {
this.type = toType(s);
this.x = x;
this.y = y;
}
private TYPE toType(String s) {
if (s.charAt(0) == 'a') {
return TYPE.ADD;
} else if (s.charAt(0) == 'r') {
return TYPE.REMOVE;
} else {
return TYPE.ASK;
}
}
}
}
class CompressData {
List<Integer> x;
public CompressData(List<Integer> x) {
this.x = x;
CollectionUtils.unique(this.x);
}
public CompressData() {
this.x = new ArrayList<Integer>();
}
public int getSize() {
return this.x.size();
}
public void add(int x) {
this.x.add(x);
}
public void build() {
CollectionUtils.unique(this.x);
}
public int originalToMapping(int original) {
return Collections.binarySearch(x, original);
}
public int mappingToOriginal(int id) {
return x.get(id);
}
}
class InputReader {
private BufferedReader reader;
private StringTokenizer stt;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
}
public String nextLine() {
try {
return reader.readLine().trim();
} catch (IOException e) {
return null;
}
}
public String nextString() {
while (stt == null || !stt.hasMoreTokens()) {
stt = new StringTokenizer(nextLine());
}
return stt.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextString());
}
}
class CollectionUtils {
// public static List<Double> unique(List<Double> a) {
// List<Double> result = new ArrayList<Double>();
// result.add(a.get(0));
// int last = 0;
// for (int i = 1; i < a.size(); ++i) {
// if (DoubleUtils.compareTo(a.get(i), result.get(last)) != 0) {
// result.add(a.get(i));
// ++last;
// }
// }
// return result;
// }
public static void unique(List<Integer> a) {
Collections.sort(a);
int size = 1;
for (int i = 1; i < a.size(); i++) {
if (!a.get(i).equals(a.get(size - 1))) {
a.set(size++, a.get(i));
}
}
for (int i = a.size() - 1; i >= size; i--) {
a.remove(i);
}
}
// public static void unique(List<Long> a) {
// Collections.sort(a);
// int size = 1;
// for (int i = 1; i < a.size(); i++) {
// if (!a.get(i).equals(a.get(size - 1))) {
// a.set(size++, a.get(i));
// }
// }
// for (int i = a.size() - 1; i >= size; i--) {
// a.remove(i);
// }
// }
}
| Java | ["7\nadd 1 1\nadd 3 4\nfind 0 0\nremove 1 1\nfind 0 0\nadd 1 1\nfind 0 0", "13\nadd 5 5\nadd 5 6\nadd 5 7\nadd 6 5\nadd 6 6\nadd 6 7\nadd 7 5\nadd 7 6\nadd 7 7\nfind 6 6\nremove 7 7\nfind 6 6\nfind 4 4"] | 2 seconds | ["1 1\n3 4\n1 1", "7 7\n-1\n5 5"] | null | Java 8 | standard input | [
"data structures"
] | da1206100811e4a51b9453babfa2c821 | The first input line contains number n (1 ≤ n ≤ 2·105) — amount of requests. Then there follow n lines — descriptions of the requests. add x y describes the request to add a point, remove x y — the request to erase a point, find x y — the request to find the bottom-left point. All the coordinates in the input file are non-negative and don't exceed 109. | 2,800 | For each request of type find x y output in a separate line the answer to it — coordinates of the bottommost among the leftmost marked points, lying strictly above and to the right of point (x, y). If there are no points strictly above and to the right of point (x, y), output -1. | standard output | |
PASSED | 1585a32d365958776c10c9b0043f0e55 | train_000.jsonl | 1277391600 | Pete and Bob invented a new interesting game. Bob takes a sheet of paper and locates a Cartesian coordinate system on it as follows: point (0, 0) is located in the bottom-left corner, Ox axis is directed right, Oy axis is directed up. Pete gives Bob requests of three types: add x y — on the sheet of paper Bob marks a point with coordinates (x, y). For each request of this type it's guaranteed that point (x, y) is not yet marked on Bob's sheet at the time of the request. remove x y — on the sheet of paper Bob erases the previously marked point with coordinates (x, y). For each request of this type it's guaranteed that point (x, y) is already marked on Bob's sheet at the time of the request. find x y — on the sheet of paper Bob finds all the marked points, lying strictly above and strictly to the right of point (x, y). Among these points Bob chooses the leftmost one, if it is not unique, he chooses the bottommost one, and gives its coordinates to Pete. Bob managed to answer the requests, when they were 10, 100 or 1000, but when their amount grew up to 2·105, Bob failed to cope. Now he needs a program that will answer all Pete's requests. Help Bob, please! | 256 megabytes | import java.io.*;
import java.util.*;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class Main implements Runnable {
static final int MOD = (int) 1e9 + 7;
static final int MI = (int) 1e9;
static final long ML = (long) 1e18;
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 Main(), "persefone", 1 << 32).start();
}
@Override
public void run() {
solve();
printf();
flush();
}
void solve() {
int n = in.nextInt();
int[] type = new int[n], x = new int[n], y = new int[n];
for (int i = 0; i < n; i++) {
String t = in.next();
type[i] = t.equals("add") ? 1 : (t.equals("remove") ? 2 : 3);
x[i] = in.nextInt();
y[i] = in.nextInt();
}
int[] nx = x.clone();
ArrayUtils.compressed(nx, n);
int[] X = new int[n];
for (int i = 0; i < n; i++) {
X[--nx[i]] = x[i];
}
NavigableSet<Integer>[] sets = Stream.generate(TreeSet::new).limit(n).toArray(TreeSet[]::new);
SegmentTreeMax stmax = new SegmentTreeMax(n);
for (int i = 0; i < n; i++) {
if (type[i] == 1) {
sets[nx[i]].add(y[i]);
stmax.update(nx[i], sets[nx[i]].last());
} else if (type[i] == 2) {
sets[nx[i]].remove(y[i]);
stmax.update(nx[i], sets[nx[i]].isEmpty() ? -1 : sets[nx[i]].last());
} else {
int can = stmax.getFirst(nx[i] + 1, n - 1, y[i]);
if (can == -1) {
printf(-1);
} else {
printf(X[can] + " " + sets[can].higher(y[i]));
}
}
}
}
static class SegmentTreeMax {
private int n;
private int[] max;
public SegmentTreeMax(int n) {
this.n = n;
this.max = new int[4 * n + 4];
Arrays.fill(max, -1);
}
int calc(int x, int y) {
return Math.max(x, y);
}
public void update(int currentVertex, int currentLeft, int currentRight, int pos, int value) {
if (currentLeft == currentRight) max[currentVertex] = value;
else {
int mid = currentLeft + currentRight >> 1, doubleVex = currentVertex << 1;
if (pos <= mid)
update(doubleVex, currentLeft, mid, pos, value);
else
update(doubleVex + 1, mid + 1, currentRight, pos, value);
max[currentVertex] = calc(max[doubleVex], max[doubleVex + 1]);
}
}
public void update(int pos, int value) {
update(1, 0, n - 1, pos, value);
}
public int getFirst(int currentVertex, int currentLeft, int currentRight, int left, int right, int k) {
if (currentLeft > right || currentRight < left || max[currentVertex] <= k) return -1;
if (currentLeft == currentRight) return currentLeft;
int mid = currentLeft + currentRight >> 1, doubleVex = currentVertex << 1;
int ans = getFirst(doubleVex, currentLeft, mid, left, right, k);
if (ans >= 0) {
return ans;
}
return getFirst(doubleVex + 1, mid + 1, currentRight, left, right, k);
}
public int getFirst(int left, int right, int k) {
return getFirst(1, 0, n - 1, left, right, k);
}
}
static class Fenwick {
private int n;
private int[] sum;
public Fenwick(int n) {
this.n = n + 10;
this.sum = new int[n + 10];
}
public void update(int i, int v) {
for (; i < n; i += i & -i) {
sum[i] += v;
}
}
public int sum(int i) {
int res = 0;
for (; i > 0; i -= i & -i) {
res += sum[i];
}
return res;
}
}
static class SegmentTreeSum {
private int n;
private int[] a, sum;
public SegmentTreeSum(int[] a, int n) {
this.n = n;
this.a = a;
this.sum = new int[4 * n + 4];
build(1, 0, n - 1);
}
public void build(int currentVertex, int currentLeft, int currentRight) {
if (currentLeft == currentRight) sum[currentVertex] = a[currentLeft];
else {
int mid = currentLeft + currentRight >> 1, doubleVex = currentVertex << 1;
build(doubleVex, currentLeft, mid);
build(doubleVex + 1, mid + 1, currentRight);
sum[currentVertex] = sum[doubleVex] + sum[doubleVex + 1];
}
}
public void update(int currentVertex, int currentLeft, int currentRight, int pos, int value) {
if (currentLeft == currentRight) sum[currentVertex] = a[pos] = value;
else {
int mid = currentLeft + currentRight >> 1, doubleVex = currentVertex << 1;
if (pos <= mid)
update(doubleVex, currentLeft, mid, pos, value);
else
update(doubleVex + 1, mid + 1, currentRight, pos, value);
sum[currentVertex] = sum[doubleVex] + sum[doubleVex + 1];
}
}
public void update(int pos, int value) {
update(1, 0, n - 1, pos, value);
}
public int sum(int currentVertex, int currentLeft, int currentRight, int left, int right) {
if (currentLeft > right || currentRight < left) return 0;
else if (left <= currentLeft && currentRight <= right) return sum[currentVertex];
int mid = currentLeft + currentRight >> 1, doubleVex = currentVertex << 1;
return sum(doubleVex, currentLeft, mid, left, right) + sum(doubleVex + 1, mid + 1, currentRight, left, right);
}
public int sum(int left, int right) {
return sum(1, 0, n - 1, left, right);
}
public int kth(int currentVertex, int currentLeft, int currentRight, int k) {
if (k > sum[currentVertex]) return -1;
if (currentLeft == currentRight) return currentLeft;
int mid = currentLeft + currentRight >> 1, doubleVex = currentVertex << 1;
if (k <= sum[doubleVex])
return kth(doubleVex, currentLeft, mid, k);
else
return kth(doubleVex + 1, mid + 1, currentRight, k - sum[doubleVex]);
}
public int kth(int k) {
return kth(1, 0, n - 1, k);
}
}
static class TreeSetTree {
private int n;
private int[] a;
private NavigableSet<Integer>[] set;
public TreeSetTree(int[] a, int n) {
this.n = n;
this.a = a;
this.set = Stream.generate(TreeSet::new).limit(4 * n + 4).toArray(NavigableSet[]::new);
build(1, 0, n - 1);
}
void merge(NavigableSet<Integer> z, NavigableSet<Integer> x, NavigableSet<Integer> y) {
z.addAll(x);
z.addAll(y);
}
public void build(int currentVertex, int currentLeft, int currentRight) {
if (currentLeft == currentRight) set[currentVertex].add(a[currentLeft]);
else {
int mid = currentLeft + currentRight >> 1, doubleVex = currentVertex << 1;
build(doubleVex, currentLeft, mid);
build(doubleVex + 1, mid + 1, currentRight);
merge(set[currentVertex], set[doubleVex], set[doubleVex + 1]);
}
}
public void update(int currentVertex, int currentLeft, int currentRight, int pos, int value) {
set[currentVertex].remove(a[pos]);
set[currentVertex].add(value);
if (currentLeft == currentRight) {
a[pos] = value;
} else {
int mid = currentLeft + currentRight >> 1, doubleVex = currentVertex << 1;
if (pos <= mid)
update(doubleVex, currentLeft, mid, pos, value);
else
update(doubleVex + 1, mid + 1, currentRight, pos, value);
}
}
public void update(int pos, int value) {
update(1, 0, n - 1, pos, value);
}
public int get(int currentVertex, int currentLeft, int currentRight, int left, int right, int k) {
if (currentLeft > right || currentRight < left) return 0;
else if (left <= currentLeft && currentRight <= right) {
Integer floor = set[currentVertex].floor(k);
return floor == null ? 0 : floor;
}
int mid = currentLeft + currentRight >> 1, doubleVex = currentVertex << 1;
return Math.max(get(doubleVex, currentLeft, mid, left, right, k),
get(doubleVex + 1, mid + 1, currentRight, left, right, k));
}
public int get(int left, int right, int k) {
return get(1, 0, n - 1, left, right, k);
}
}
static class ListUtils {
static int lowerBound(List<Integer> list, int l, int r, int k) {
int m = 0, ans = r;
while (l < r) if (list.get(m = l + r >> 1) >= k) ans = r = m;
else l = m + 1;
return ans;
}
static int upperBound(List<Integer> list, int l, int r, int k) {
int m = 0, ans = r;
while (l < r) if (list.get(m = l + r >> 1) > k) ans = r = m;
else l = m + 1;
return ans;
}
static int amountOfNumbersEqualTo(List<Integer> list, int l, int r, int k) {
return upperBound(list, l, r, k) - lowerBound(list, l, r, k);
}
static int amountOfNumbersEqualTo(List<Integer> list, int k) {
return upperBound(list, 0, list.size(), k) - lowerBound(list, 0, list.size(), k);
}
}
static class ArrayUtils {
static int lowerBound(int[] a, int l, int r, int k) {
int m = 0, ans = r;
while (l < r) if (a[m = l + r >> 1] >= k) ans = r = m;
else l = m + 1;
return ans;
}
static int upperBound(int[] a, int l, int r, int k) {
int m = 0, ans = r;
while (l < r) if (a[m = l + r >> 1] > k) ans = r = m;
else l = m + 1;
return ans;
}
static int lowerBound(int[] a, int k) {
return lowerBound(a, 0, a.length, k);
}
static int upperBound(int[] a, int k) {
return upperBound(a, 0, a.length, k);
}
static void compressed(int[] a, int n) {
int[] b = a.clone();
Arrays.sort(b);
for (int i = 0; i < n; i++) {
a[i] = lowerBound(b, a[i]) + 1;
}
}
static void compressed(int[] a, int l, int r) {
if (l >= r) return;
int[] b = new int[r - l];
System.arraycopy(a, l, b, 0, r - l);
Arrays.sort(b);
for (int i = l; i < r; i++) a[i] = lowerBound(b, a[i]) + 1;
}
}
static class IntegerUtils {
// returns { gcd(a,b), x, y } such that gcd(a,b) = a*x + b*y
static long[] euclid(long a, long b) {
long x = 1, y = 0, x1 = 0, y1 = 1, t;
while (b != 0) {
long q = a / b;
t = x;
x = x1;
x1 = t - q * x1;
t = y;
y = y1;
y1 = t - q * y1;
t = b;
b = a - q * b;
a = t;
}
return a > 0 ? new long[]{a, x, y} : new long[]{-a, -x, -y};
}
static int[] generatePrimesUpTo(int n) {
boolean[] composite = new boolean[n + 1];
for (int i = 2; i <= n; i++) {
for (int j = i; 1l * i * j <= n; j++) {
composite[i * j] = true;
}
}
return IntStream.rangeClosed(2, n).filter(i -> !composite[i]).toArray();
}
static int[] smallestFactor(int n) {
int[] sf = new int[n + 1];
for (int i = 2; i <= n; i++) {
if (sf[i] == 0) {
sf[i] = i;
for (int j = i; 1l * i * j <= n; j++) {
if (sf[i * j] == 0) {
sf[i * j] = i;
}
}
}
}
return sf;
}
static int phi(int n) {
int result = n;
for (int i = 2; 1l * i * i <= n; i++) {
if (n % i == 0) {
while (n % i == 0) n /= i;
result -= result / i;
}
}
if (n > 1) result -= result / n;
return result;
}
static long phi(long n) {
// n <= 10 ^ 12;
long result = n;
for (int i = 2; 1l * i * i <= n; i++) {
if (n % i == 0) {
while (n % i == 0) n /= i;
result -= result / i;
}
}
if (n > 1) result -= result / n;
return result;
}
static long[] n_thFiboNaCi(long n, int p) {
// f[n + k] = f[n + 1].f[k] + f[n].f[k - 1]
if (n == 0) return new long[]{0, 1};
long[] a = n_thFiboNaCi(n >> 1, p);
long c = (2 * a[1] - a[0] + p) % p * a[0] % p;
long d = (a[1] * a[1] % p + a[0] * a[0] % p) % p;
if (n % 2 == 0) return new long[]{c, d};
else return new long[]{d, (c + d) % p};
}
static long modPow(int base, int exponential, int p) {
if (exponential == 0) return 1;
long x = modPow(base, exponential >> 1, p) % p;
return exponential % 2 == 0 ? x * x % p : x * x % p * base % p;
}
static long modPow(long base, int exponential, int p) {
if (exponential == 0) return 1;
long x = modPow(base, exponential >> 1, p) % p;
return exponential % 2 == 0 ? x * x % p : x * x % p * base % p;
}
static long modPow(long base, long exponential, int p) {
if (exponential == 0) return 1;
long x = modPow(base, exponential >> 1, p) % p;
return exponential % 2 == 0 ? x * x % p : x * x % p * base % p;
}
static long[] generateFactorialArray(int n, int p) {
long[] factorial = new long[n + 1];
factorial[0] = 1;
for (int i = 1; i <= n; i++) factorial[i] = (factorial[i - 1] * i) % p;
return factorial;
}
static long cNkModP(long[] factorial, int n, int k, int p) {
return factorial[n] * modPow(factorial[k], p - 2, p) % p * modPow(factorial[n - k], p - 2, p) % p;
}
static long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
}
static class SparseTableMax {
private int n, blocks;
private int[] log, data;
private int[][] max;
public SparseTableMax(int[] data, int n) {
this.n = n;
this.data = data;
this.log = new int[n + 1];
for (int i = 2; i <= n; i++) {
log[i] = log[i >> 1] + 1;
}
this.blocks = log[n];
this.max = new int[n][blocks + 1];
for (int i = 0; i < n; i++) {
max[i][0] = data[i];
}
build();
}
int calc(int a, int b) {
return Math.max(a, b);
}
void build() {
for (int j = 1; j <= blocks; j++) {
for (int i = 0; i + (1 << j) <= n; i++) {
max[i][j] = calc(max[i][j - 1], max[i + (1 << j - 1)][j - 1]);
}
}
}
int getMax(int l, int r) {
int k = log[r - l + 1];
return calc(max[l][k], max[r - (1 << k) + 1][k]);
}
}
static class DSU {
protected int vertex, countCC;
protected int[] id, size;
public DSU(int vertex) {
this.vertex = vertex;
this.id = IntStream.range(0, vertex).toArray();
this.size = new int[vertex];
Arrays.fill(size, 1);
countCC = vertex;
}
int find(int i) {
return id[i] == i ? i : (id[i] = find(id[i]));
}
void unite(int i, int j) {
int x = find(i);
int y = find(j);
if (x == y) return;
countCC--;
if (size[x] > size[y]) {
id[y] = id[x];
size[x] += size[y];
size[y] = 0;
return;
}
id[x] = id[y];
size[y] += size[x];
size[x] = 0;
}
boolean isConnected(int i, int j) {
return find(i) == find(j);
}
int connectedComponents() {
return countCC;
}
}
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));
}
Reader(String fileName) throws FileNotFoundException {
br = new BufferedReader(new FileReader(fileName));
}
boolean isReady() throws IOException {
return br.ready();
}
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());
}
String nextLine() {
String s = "";
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return s;
}
}
} | Java | ["7\nadd 1 1\nadd 3 4\nfind 0 0\nremove 1 1\nfind 0 0\nadd 1 1\nfind 0 0", "13\nadd 5 5\nadd 5 6\nadd 5 7\nadd 6 5\nadd 6 6\nadd 6 7\nadd 7 5\nadd 7 6\nadd 7 7\nfind 6 6\nremove 7 7\nfind 6 6\nfind 4 4"] | 2 seconds | ["1 1\n3 4\n1 1", "7 7\n-1\n5 5"] | null | Java 8 | standard input | [
"data structures"
] | da1206100811e4a51b9453babfa2c821 | The first input line contains number n (1 ≤ n ≤ 2·105) — amount of requests. Then there follow n lines — descriptions of the requests. add x y describes the request to add a point, remove x y — the request to erase a point, find x y — the request to find the bottom-left point. All the coordinates in the input file are non-negative and don't exceed 109. | 2,800 | For each request of type find x y output in a separate line the answer to it — coordinates of the bottommost among the leftmost marked points, lying strictly above and to the right of point (x, y). If there are no points strictly above and to the right of point (x, y), output -1. | standard output | |
PASSED | f92fc1c52094f0dd6f8c4e267d0e4068 | train_000.jsonl | 1277391600 | Pete and Bob invented a new interesting game. Bob takes a sheet of paper and locates a Cartesian coordinate system on it as follows: point (0, 0) is located in the bottom-left corner, Ox axis is directed right, Oy axis is directed up. Pete gives Bob requests of three types: add x y — on the sheet of paper Bob marks a point with coordinates (x, y). For each request of this type it's guaranteed that point (x, y) is not yet marked on Bob's sheet at the time of the request. remove x y — on the sheet of paper Bob erases the previously marked point with coordinates (x, y). For each request of this type it's guaranteed that point (x, y) is already marked on Bob's sheet at the time of the request. find x y — on the sheet of paper Bob finds all the marked points, lying strictly above and strictly to the right of point (x, y). Among these points Bob chooses the leftmost one, if it is not unique, he chooses the bottommost one, and gives its coordinates to Pete. Bob managed to answer the requests, when they were 10, 100 or 1000, but when their amount grew up to 2·105, Bob failed to cope. Now he needs a program that will answer all Pete's requests. Help Bob, please! | 256 megabytes | import java.io.*;
import java.util.*;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class Main implements Runnable {
static final int MOD = (int) 1e9 + 7;
static final int MI = (int) 1e9;
static final long ML = (long) 1e18;
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 Main(), "persefone", 1 << 32).start();
}
@Override
public void run() {
solve();
printf();
flush();
}
void solve() {
int n = in.nextInt();
int[] type = new int[n], x = new int[n], y = new int[n];
for (int i = 0; i < n; i++) {
String t = in.next();
type[i] = t.equals("add") ? 1 : (t.equals("remove") ? 2 : 3);
x[i] = in.nextInt();
y[i] = in.nextInt();
}
int[] nx = x.clone();
ArrayUtils.compressed(nx, n);
int[] X = new int[n];
for (int i = 0; i < n; i++) {
X[--nx[i]] = x[i];
}
NavigableSet<Integer>[] sets = new TreeSet[n];
for (int i = 0; i < n; i++) sets[i] = new TreeSet<>();
SegmentTreeMax stmax = new SegmentTreeMax(n);
for (int i = 0; i < n; i++) {
if (type[i] == 1) {
sets[nx[i]].add(y[i]);
stmax.update(nx[i], sets[nx[i]].last());
} else if (type[i] == 2) {
sets[nx[i]].remove(y[i]);
stmax.update(nx[i], sets[nx[i]].isEmpty() ? -1 : sets[nx[i]].last());
} else {
int can = stmax.getFirst(nx[i] + 1, n - 1, y[i]);
if (can == -1) {
add(-1, '\n');
} else {
add(X[can] + " " + sets[can].higher(y[i]), '\n');
}
}
}
}
static class SegmentTreeMax {
private int n;
private int[] max;
public SegmentTreeMax(int n) {
this.n = n;
this.max = new int[4 * n + 4];
Arrays.fill(max, -1);
}
int calc(int x, int y) {
return Math.max(x, y);
}
public void update(int currentVertex, int currentLeft, int currentRight, int pos, int value) {
if (currentLeft == currentRight) max[currentVertex] = value;
else {
int mid = currentLeft + currentRight >> 1, doubleVex = currentVertex << 1;
if (pos <= mid)
update(doubleVex, currentLeft, mid, pos, value);
else
update(doubleVex + 1, mid + 1, currentRight, pos, value);
max[currentVertex] = calc(max[doubleVex], max[doubleVex + 1]);
}
}
public void update(int pos, int value) {
update(1, 0, n - 1, pos, value);
}
public int getFirst(int currentVertex, int currentLeft, int currentRight, int left, int right, int k) {
if (currentLeft > right || currentRight < left || max[currentVertex] <= k) return -1;
if (currentLeft == currentRight) return currentLeft;
int mid = currentLeft + currentRight >> 1, doubleVex = currentVertex << 1;
int ans = getFirst(doubleVex, currentLeft, mid, left, right, k);
if (ans >= 0) {
return ans;
}
return getFirst(doubleVex + 1, mid + 1, currentRight, left, right, k);
}
public int getFirst(int left, int right, int k) {
return getFirst(1, 0, n - 1, left, right, k);
}
}
static class Fenwick {
private int n;
private int[] sum;
public Fenwick(int n) {
this.n = n + 10;
this.sum = new int[n + 10];
}
public void update(int i, int v) {
for (; i < n; i += i & -i) {
sum[i] += v;
}
}
public int sum(int i) {
int res = 0;
for (; i > 0; i -= i & -i) {
res += sum[i];
}
return res;
}
}
static class SegmentTreeSum {
private int n;
private int[] a, sum;
public SegmentTreeSum(int[] a, int n) {
this.n = n;
this.a = a;
this.sum = new int[4 * n + 4];
build(1, 0, n - 1);
}
public void build(int currentVertex, int currentLeft, int currentRight) {
if (currentLeft == currentRight) sum[currentVertex] = a[currentLeft];
else {
int mid = currentLeft + currentRight >> 1, doubleVex = currentVertex << 1;
build(doubleVex, currentLeft, mid);
build(doubleVex + 1, mid + 1, currentRight);
sum[currentVertex] = sum[doubleVex] + sum[doubleVex + 1];
}
}
public void update(int currentVertex, int currentLeft, int currentRight, int pos, int value) {
if (currentLeft == currentRight) sum[currentVertex] = a[pos] = value;
else {
int mid = currentLeft + currentRight >> 1, doubleVex = currentVertex << 1;
if (pos <= mid)
update(doubleVex, currentLeft, mid, pos, value);
else
update(doubleVex + 1, mid + 1, currentRight, pos, value);
sum[currentVertex] = sum[doubleVex] + sum[doubleVex + 1];
}
}
public void update(int pos, int value) {
update(1, 0, n - 1, pos, value);
}
public int sum(int currentVertex, int currentLeft, int currentRight, int left, int right) {
if (currentLeft > right || currentRight < left) return 0;
else if (left <= currentLeft && currentRight <= right) return sum[currentVertex];
int mid = currentLeft + currentRight >> 1, doubleVex = currentVertex << 1;
return sum(doubleVex, currentLeft, mid, left, right) + sum(doubleVex + 1, mid + 1, currentRight, left, right);
}
public int sum(int left, int right) {
return sum(1, 0, n - 1, left, right);
}
public int kth(int currentVertex, int currentLeft, int currentRight, int k) {
if (k > sum[currentVertex]) return -1;
if (currentLeft == currentRight) return currentLeft;
int mid = currentLeft + currentRight >> 1, doubleVex = currentVertex << 1;
if (k <= sum[doubleVex])
return kth(doubleVex, currentLeft, mid, k);
else
return kth(doubleVex + 1, mid + 1, currentRight, k - sum[doubleVex]);
}
public int kth(int k) {
return kth(1, 0, n - 1, k);
}
}
static class TreeSetTree {
private int n;
private int[] a;
private NavigableSet<Integer>[] set;
public TreeSetTree(int[] a, int n) {
this.n = n;
this.a = a;
this.set = Stream.generate(TreeSet::new).limit(4 * n + 4).toArray(NavigableSet[]::new);
build(1, 0, n - 1);
}
void merge(NavigableSet<Integer> z, NavigableSet<Integer> x, NavigableSet<Integer> y) {
z.addAll(x);
z.addAll(y);
}
public void build(int currentVertex, int currentLeft, int currentRight) {
if (currentLeft == currentRight) set[currentVertex].add(a[currentLeft]);
else {
int mid = currentLeft + currentRight >> 1, doubleVex = currentVertex << 1;
build(doubleVex, currentLeft, mid);
build(doubleVex + 1, mid + 1, currentRight);
merge(set[currentVertex], set[doubleVex], set[doubleVex + 1]);
}
}
public void update(int currentVertex, int currentLeft, int currentRight, int pos, int value) {
set[currentVertex].remove(a[pos]);
set[currentVertex].add(value);
if (currentLeft == currentRight) {
a[pos] = value;
} else {
int mid = currentLeft + currentRight >> 1, doubleVex = currentVertex << 1;
if (pos <= mid)
update(doubleVex, currentLeft, mid, pos, value);
else
update(doubleVex + 1, mid + 1, currentRight, pos, value);
}
}
public void update(int pos, int value) {
update(1, 0, n - 1, pos, value);
}
public int get(int currentVertex, int currentLeft, int currentRight, int left, int right, int k) {
if (currentLeft > right || currentRight < left) return 0;
else if (left <= currentLeft && currentRight <= right) {
Integer floor = set[currentVertex].floor(k);
return floor == null ? 0 : floor;
}
int mid = currentLeft + currentRight >> 1, doubleVex = currentVertex << 1;
return Math.max(get(doubleVex, currentLeft, mid, left, right, k),
get(doubleVex + 1, mid + 1, currentRight, left, right, k));
}
public int get(int left, int right, int k) {
return get(1, 0, n - 1, left, right, k);
}
}
static class ListUtils {
static int lowerBound(List<Integer> list, int l, int r, int k) {
int m = 0, ans = r;
while (l < r) if (list.get(m = l + r >> 1) >= k) ans = r = m;
else l = m + 1;
return ans;
}
static int upperBound(List<Integer> list, int l, int r, int k) {
int m = 0, ans = r;
while (l < r) if (list.get(m = l + r >> 1) > k) ans = r = m;
else l = m + 1;
return ans;
}
static int amountOfNumbersEqualTo(List<Integer> list, int l, int r, int k) {
return upperBound(list, l, r, k) - lowerBound(list, l, r, k);
}
static int amountOfNumbersEqualTo(List<Integer> list, int k) {
return upperBound(list, 0, list.size(), k) - lowerBound(list, 0, list.size(), k);
}
}
static class ArrayUtils {
static int lowerBound(int[] a, int l, int r, int k) {
int m = 0, ans = r;
while (l < r) if (a[m = l + r >> 1] >= k) ans = r = m;
else l = m + 1;
return ans;
}
static int upperBound(int[] a, int l, int r, int k) {
int m = 0, ans = r;
while (l < r) if (a[m = l + r >> 1] > k) ans = r = m;
else l = m + 1;
return ans;
}
static int lowerBound(int[] a, int k) {
return lowerBound(a, 0, a.length, k);
}
static int upperBound(int[] a, int k) {
return upperBound(a, 0, a.length, k);
}
static void compressed(int[] a, int n) {
int[] b = a.clone();
Arrays.sort(b);
for (int i = 0; i < n; i++) {
a[i] = lowerBound(b, a[i]) + 1;
}
}
static void compressed(int[] a, int l, int r) {
if (l >= r) return;
int[] b = new int[r - l];
System.arraycopy(a, l, b, 0, r - l);
Arrays.sort(b);
for (int i = l; i < r; i++) a[i] = lowerBound(b, a[i]) + 1;
}
}
static class IntegerUtils {
// returns { gcd(a,b), x, y } such that gcd(a,b) = a*x + b*y
static long[] euclid(long a, long b) {
long x = 1, y = 0, x1 = 0, y1 = 1, t;
while (b != 0) {
long q = a / b;
t = x;
x = x1;
x1 = t - q * x1;
t = y;
y = y1;
y1 = t - q * y1;
t = b;
b = a - q * b;
a = t;
}
return a > 0 ? new long[]{a, x, y} : new long[]{-a, -x, -y};
}
static int[] generatePrimesUpTo(int n) {
boolean[] composite = new boolean[n + 1];
for (int i = 2; i <= n; i++) {
for (int j = i; 1l * i * j <= n; j++) {
composite[i * j] = true;
}
}
return IntStream.rangeClosed(2, n).filter(i -> !composite[i]).toArray();
}
static int[] smallestFactor(int n) {
int[] sf = new int[n + 1];
for (int i = 2; i <= n; i++) {
if (sf[i] == 0) {
sf[i] = i;
for (int j = i; 1l * i * j <= n; j++) {
if (sf[i * j] == 0) {
sf[i * j] = i;
}
}
}
}
return sf;
}
static int phi(int n) {
int result = n;
for (int i = 2; 1l * i * i <= n; i++) {
if (n % i == 0) {
while (n % i == 0) n /= i;
result -= result / i;
}
}
if (n > 1) result -= result / n;
return result;
}
static long phi(long n) {
// n <= 10 ^ 12;
long result = n;
for (int i = 2; 1l * i * i <= n; i++) {
if (n % i == 0) {
while (n % i == 0) n /= i;
result -= result / i;
}
}
if (n > 1) result -= result / n;
return result;
}
static long[] n_thFiboNaCi(long n, int p) {
// f[n + k] = f[n + 1].f[k] + f[n].f[k - 1]
if (n == 0) return new long[]{0, 1};
long[] a = n_thFiboNaCi(n >> 1, p);
long c = (2 * a[1] - a[0] + p) % p * a[0] % p;
long d = (a[1] * a[1] % p + a[0] * a[0] % p) % p;
if (n % 2 == 0) return new long[]{c, d};
else return new long[]{d, (c + d) % p};
}
static long modPow(int base, int exponential, int p) {
if (exponential == 0) return 1;
long x = modPow(base, exponential >> 1, p) % p;
return exponential % 2 == 0 ? x * x % p : x * x % p * base % p;
}
static long modPow(long base, int exponential, int p) {
if (exponential == 0) return 1;
long x = modPow(base, exponential >> 1, p) % p;
return exponential % 2 == 0 ? x * x % p : x * x % p * base % p;
}
static long modPow(long base, long exponential, int p) {
if (exponential == 0) return 1;
long x = modPow(base, exponential >> 1, p) % p;
return exponential % 2 == 0 ? x * x % p : x * x % p * base % p;
}
static long[] generateFactorialArray(int n, int p) {
long[] factorial = new long[n + 1];
factorial[0] = 1;
for (int i = 1; i <= n; i++) factorial[i] = (factorial[i - 1] * i) % p;
return factorial;
}
static long cNkModP(long[] factorial, int n, int k, int p) {
return factorial[n] * modPow(factorial[k], p - 2, p) % p * modPow(factorial[n - k], p - 2, p) % p;
}
static long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
}
static class SparseTableMax {
private int n, blocks;
private int[] log, data;
private int[][] max;
public SparseTableMax(int[] data, int n) {
this.n = n;
this.data = data;
this.log = new int[n + 1];
for (int i = 2; i <= n; i++) {
log[i] = log[i >> 1] + 1;
}
this.blocks = log[n];
this.max = new int[n][blocks + 1];
for (int i = 0; i < n; i++) {
max[i][0] = data[i];
}
build();
}
int calc(int a, int b) {
return Math.max(a, b);
}
void build() {
for (int j = 1; j <= blocks; j++) {
for (int i = 0; i + (1 << j) <= n; i++) {
max[i][j] = calc(max[i][j - 1], max[i + (1 << j - 1)][j - 1]);
}
}
}
int getMax(int l, int r) {
int k = log[r - l + 1];
return calc(max[l][k], max[r - (1 << k) + 1][k]);
}
}
static class DSU {
protected int vertex, countCC;
protected int[] id, size;
public DSU(int vertex) {
this.vertex = vertex;
this.id = IntStream.range(0, vertex).toArray();
this.size = new int[vertex];
Arrays.fill(size, 1);
countCC = vertex;
}
int find(int i) {
return id[i] == i ? i : (id[i] = find(id[i]));
}
void unite(int i, int j) {
int x = find(i);
int y = find(j);
if (x == y) return;
countCC--;
if (size[x] > size[y]) {
id[y] = id[x];
size[x] += size[y];
size[y] = 0;
return;
}
id[x] = id[y];
size[y] += size[x];
size[x] = 0;
}
boolean isConnected(int i, int j) {
return find(i) == find(j);
}
int connectedComponents() {
return countCC;
}
}
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));
}
Reader(String fileName) throws FileNotFoundException {
br = new BufferedReader(new FileReader(fileName));
}
boolean isReady() throws IOException {
return br.ready();
}
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());
}
String nextLine() {
String s = "";
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return s;
}
}
} | Java | ["7\nadd 1 1\nadd 3 4\nfind 0 0\nremove 1 1\nfind 0 0\nadd 1 1\nfind 0 0", "13\nadd 5 5\nadd 5 6\nadd 5 7\nadd 6 5\nadd 6 6\nadd 6 7\nadd 7 5\nadd 7 6\nadd 7 7\nfind 6 6\nremove 7 7\nfind 6 6\nfind 4 4"] | 2 seconds | ["1 1\n3 4\n1 1", "7 7\n-1\n5 5"] | null | Java 8 | standard input | [
"data structures"
] | da1206100811e4a51b9453babfa2c821 | The first input line contains number n (1 ≤ n ≤ 2·105) — amount of requests. Then there follow n lines — descriptions of the requests. add x y describes the request to add a point, remove x y — the request to erase a point, find x y — the request to find the bottom-left point. All the coordinates in the input file are non-negative and don't exceed 109. | 2,800 | For each request of type find x y output in a separate line the answer to it — coordinates of the bottommost among the leftmost marked points, lying strictly above and to the right of point (x, y). If there are no points strictly above and to the right of point (x, y), output -1. | standard output | |
PASSED | 212bb9988a94ba93e47a8161d5c749ff | train_000.jsonl | 1277391600 | Pete and Bob invented a new interesting game. Bob takes a sheet of paper and locates a Cartesian coordinate system on it as follows: point (0, 0) is located in the bottom-left corner, Ox axis is directed right, Oy axis is directed up. Pete gives Bob requests of three types: add x y — on the sheet of paper Bob marks a point with coordinates (x, y). For each request of this type it's guaranteed that point (x, y) is not yet marked on Bob's sheet at the time of the request. remove x y — on the sheet of paper Bob erases the previously marked point with coordinates (x, y). For each request of this type it's guaranteed that point (x, y) is already marked on Bob's sheet at the time of the request. find x y — on the sheet of paper Bob finds all the marked points, lying strictly above and strictly to the right of point (x, y). Among these points Bob chooses the leftmost one, if it is not unique, he chooses the bottommost one, and gives its coordinates to Pete. Bob managed to answer the requests, when they were 10, 100 or 1000, but when their amount grew up to 2·105, Bob failed to cope. Now he needs a program that will answer all Pete's requests. Help Bob, please! | 256 megabytes | import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.NavigableSet;
import java.util.Scanner;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
new CF_19D().run();
}
}
class CF_19D {
void run() {
// Scanner cin = new Scanner(new BufferedInputStream(System.in));
// FastScanner cin = new FastScanner(System.in) ;
InputReader cin = new InputReader(System.in) ;
PrintWriter cout = new PrintWriter(new BufferedOutputStream(System.out));
int n = cin.nextInt();
for (int i = 0; i < n; i++) {
switch (cin.next()) {
case "add":
operator[i] = 0;
break;
case "remove":
operator[i] = 1;
break;
case "find":
operator[i] = 2;
break;
}
x[i] = cin.nextInt();
y[i] = cin.nextInt();
}
Hash h = new Hash(n, x);
int limit = h.length() - 1;
for (int i = 0; i <= limit; i++)
set[i].clear();
buildTree(1, 0, limit);
for (int i = 0; i < n; i++) {
int id = h.idx(x[i]);
if (operator[i] == 0) {
set[id].add(y[i]);
update(id, set[id].isEmpty() ? 0 : set[id].last(), 1, 0, limit);
} else if (operator[i] == 1) {
set[id].remove(y[i]);
update(id, set[id].isEmpty() ? 0 : set[id].last(), 1, 0, limit);
} else {
int pos = ask(id + 1, y[i], 1, 0, limit);
if (pos == NOTFIND)
cout.println(NOTFIND);
else
cout.println(h.value(pos) + " " + set[pos].higher(y[i]));
}
}
cout.flush();
}
void buildTree(int t, int l, int r) {
left[t] = l;
right[t] = r;
max[t] = 0;
if (l == r)
return;
int mid = (l + r) >> 1;
buildTree(t << 1, l, mid);
buildTree(t << 1 | 1, mid + 1, r);
up(t);
}
void update(int i, int c, int t, int l, int r) {
if (l > r)
return;
if (l == r) {
max[t] = c;
return;
}
int mid = (l + r) >> 1;
if (i <= mid)
update(i, c, t << 1, l, mid);
else
update(i, c, t << 1 | 1, mid + 1, r);
up(t);
}
int ask(int i, int c, int t, int l, int r) {
if (max[t] <= c || i > r)
return NOTFIND;
if (l == r)
return max[t] > c ? l : NOTFIND;
int mid = (l + r) >> 1;
if (i > mid)
return ask(i, c, t << 1 | 1, mid + 1, r);
else {
int res = ask(i, c, t << 1, l, mid);
if (res != NOTFIND)
return res;
else
return ask(i, c, t << 1 | 1, mid + 1, r);
}
}
void up(int t) {
max[t] = Math.max(max[t << 1], max[t << 1 | 1]);
}
final int NOTFIND = -1;
final int N = 200_008;
int[] x = new int[N];
int[] y = new int[N];
int[] z = new int[N];
int[] operator = new int[N];
NavigableSet<Integer>[] set = new TreeSet[N];
{
for (int i = 0; i < N; i++)
set[i] = new TreeSet<Integer>();
}
int[] left = new int[N << 2];
int[] right = new int[N << 2];
int[] max = new int[N << 2];
}
class Hash {
Hash(int length, int[] array) {
Set<Integer> treeset = new TreeSet<Integer>();
for (int i = 0; i < length; i++) {
treeset.add(array[i]);
}
this.array = new int[treeset.size()];
size = 0;
for (int i : treeset)
this.array[size++] = i;
}
int length() {
return size;
}
int idx(int key) {
return Arrays.binarySearch(array, key);
}
int value(int idx) {
return array[idx];
}
int size;
int[] array;
}
class FastScanner extends BufferedReader {
boolean isEOF;
public FastScanner(InputStream is) {
super(new InputStreamReader(is));
}
public int read() {
try {
int ret = super.read();
if (isEOF && ret < 0) {
throw new InputMismatchException();
}
isEOF = ret == -1;
return ret;
} catch (IOException e) {
throw new InputMismatchException();
}
}
public String next() {
StringBuilder sb = new StringBuilder();
int c = read();
while (isWhiteSpace(c)) {
c = read();
}
while (!isWhiteSpace(c)) {
sb.appendCodePoint(c);
c = read();
}
return sb.toString();
}
static boolean isWhiteSpace(int c) {
return c >= -1 && c <= 32;
}
public int nextInt() {
int c = read();
while (isWhiteSpace(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int ret = 0;
while (!isWhiteSpace(c)) {
if (c < '0' || c > '9') {
throw new NumberFormatException("digit expected " + (char) c
+ " found");
}
ret = ret * 10 + c - '0';
c = read();
}
return ret * sgn;
}
}
class InputReader{
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream){
reader = new BufferedReader(new InputStreamReader(stream), 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());
}
} | Java | ["7\nadd 1 1\nadd 3 4\nfind 0 0\nremove 1 1\nfind 0 0\nadd 1 1\nfind 0 0", "13\nadd 5 5\nadd 5 6\nadd 5 7\nadd 6 5\nadd 6 6\nadd 6 7\nadd 7 5\nadd 7 6\nadd 7 7\nfind 6 6\nremove 7 7\nfind 6 6\nfind 4 4"] | 2 seconds | ["1 1\n3 4\n1 1", "7 7\n-1\n5 5"] | null | Java 8 | standard input | [
"data structures"
] | da1206100811e4a51b9453babfa2c821 | The first input line contains number n (1 ≤ n ≤ 2·105) — amount of requests. Then there follow n lines — descriptions of the requests. add x y describes the request to add a point, remove x y — the request to erase a point, find x y — the request to find the bottom-left point. All the coordinates in the input file are non-negative and don't exceed 109. | 2,800 | For each request of type find x y output in a separate line the answer to it — coordinates of the bottommost among the leftmost marked points, lying strictly above and to the right of point (x, y). If there are no points strictly above and to the right of point (x, y), output -1. | standard output | |
PASSED | ca971c1d968600b62ba2dc5316064449 | train_000.jsonl | 1277391600 | Pete and Bob invented a new interesting game. Bob takes a sheet of paper and locates a Cartesian coordinate system on it as follows: point (0, 0) is located in the bottom-left corner, Ox axis is directed right, Oy axis is directed up. Pete gives Bob requests of three types: add x y — on the sheet of paper Bob marks a point with coordinates (x, y). For each request of this type it's guaranteed that point (x, y) is not yet marked on Bob's sheet at the time of the request. remove x y — on the sheet of paper Bob erases the previously marked point with coordinates (x, y). For each request of this type it's guaranteed that point (x, y) is already marked on Bob's sheet at the time of the request. find x y — on the sheet of paper Bob finds all the marked points, lying strictly above and strictly to the right of point (x, y). Among these points Bob chooses the leftmost one, if it is not unique, he chooses the bottommost one, and gives its coordinates to Pete. Bob managed to answer the requests, when they were 10, 100 or 1000, but when their amount grew up to 2·105, Bob failed to cope. Now he needs a program that will answer all Pete's requests. Help Bob, please! | 256 megabytes | import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.NavigableSet;
import java.util.Scanner;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
new CF_19D().run();
}
}
class CF_19D {
void run() {
// Scanner cin = new Scanner(new BufferedInputStream(System.in));
// FastScanner cin = new FastScanner(System.in) ;
InputReader cin = new InputReader(System.in) ;
PrintWriter cout = new PrintWriter(new BufferedOutputStream(System.out));
int n = cin.nextInt();
for (int i = 0; i < n; i++) {
switch (cin.next()) {
case "add":
operator[i] = 0;
break;
case "remove":
operator[i] = 1;
break;
case "find":
operator[i] = 2;
break;
}
x[i] = cin.nextInt();
y[i] = cin.nextInt();
}
Hash h = new Hash(n, x);
int limit = h.length() - 1;
for (int i = 0; i <= limit; i++)
set[i].clear();
buildTree(1, 0, limit);
for (int i = 0; i < n; i++) {
int id = h.idx(x[i]);
if (operator[i] == 0) {
set[id].add(y[i]);
update(id, set[id].isEmpty() ? 0 : set[id].last(), 1, 0, limit);
} else if (operator[i] == 1) {
set[id].remove(y[i]);
update(id, set[id].isEmpty() ? 0 : set[id].last(), 1, 0, limit);
} else {
int pos = ask(id + 1, y[i], 1, 0, limit);
if (pos == NOTFIND)
cout.println(NOTFIND);
else
cout.println(h.value(pos) + " " + set[pos].higher(y[i]));
}
}
cout.flush();
}
void buildTree(int t, int l, int r) {
left[t] = l;
right[t] = r;
max[t] = 0;
if (l == r)
return;
int mid = (l + r) >> 1;
buildTree(t << 1, l, mid);
buildTree(t << 1 | 1, mid + 1, r);
up(t);
}
void update(int i, int c, int t, int l, int r) {
if (l > r)
return;
if (l == r) {
max[t] = c;
return;
}
int mid = (l + r) >> 1;
if (i <= mid)
update(i, c, t << 1, l, mid);
else
update(i, c, t << 1 | 1, mid + 1, r);
up(t);
}
int ask(int i, int c, int t, int l, int r) {
if (max[t] <= c || i > r)
return NOTFIND;
if (l == r)
return max[t] > c ? l : NOTFIND;
int mid = (l + r) >> 1;
if (i > mid)
return ask(i, c, t << 1 | 1, mid + 1, r);
else {
int res = ask(i, c, t << 1, l, mid);
if (res != NOTFIND)
return res;
else
return ask(i, c, t << 1 | 1, mid + 1, r);
}
}
void up(int t) {
max[t] = Math.max(max[t << 1], max[t << 1 | 1]);
}
final int NOTFIND = -1;
final int N = 200_008;
int[] x = new int[N];
int[] y = new int[N];
int[] z = new int[N];
int[] operator = new int[N];
NavigableSet<Integer>[] set = new TreeSet[N];
{
for (int i = 0; i < N; i++)
set[i] = new TreeSet<Integer>();
}
int[] left = new int[N << 2];
int[] right = new int[N << 2];
int[] max = new int[N << 2];
}
class Hash {
Hash(int length, int[] array) {
Set<Integer> treeset = new TreeSet<Integer>();
for (int i = 0; i < length; i++) {
treeset.add(array[i]);
}
this.array = new int[treeset.size()];
size = 0;
for (int i : treeset)
this.array[size++] = i;
}
int length() {
return size;
}
int idx(int key) {
return Arrays.binarySearch(array, key);
}
int value(int idx) {
return array[idx];
}
int size;
int[] array;
}
class FastScanner extends BufferedReader {
boolean isEOF;
public FastScanner(InputStream is) {
super(new InputStreamReader(is));
}
public int read() {
try {
int ret = super.read();
if (isEOF && ret < 0) {
throw new InputMismatchException();
}
isEOF = ret == -1;
return ret;
} catch (IOException e) {
throw new InputMismatchException();
}
}
public String next() {
StringBuilder sb = new StringBuilder();
int c = read();
while (isWhiteSpace(c)) {
c = read();
}
while (!isWhiteSpace(c)) {
sb.appendCodePoint(c);
c = read();
}
return sb.toString();
}
static boolean isWhiteSpace(int c) {
return c >= -1 && c <= 32;
}
public int nextInt() {
int c = read();
while (isWhiteSpace(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int ret = 0;
while (!isWhiteSpace(c)) {
if (c < '0' || c > '9') {
throw new NumberFormatException("digit expected " + (char) c
+ " found");
}
ret = ret * 10 + c - '0';
c = read();
}
return ret * sgn;
}
}
class InputReader{
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream){
reader = new BufferedReader(new InputStreamReader(stream), 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());
}
}
| Java | ["7\nadd 1 1\nadd 3 4\nfind 0 0\nremove 1 1\nfind 0 0\nadd 1 1\nfind 0 0", "13\nadd 5 5\nadd 5 6\nadd 5 7\nadd 6 5\nadd 6 6\nadd 6 7\nadd 7 5\nadd 7 6\nadd 7 7\nfind 6 6\nremove 7 7\nfind 6 6\nfind 4 4"] | 2 seconds | ["1 1\n3 4\n1 1", "7 7\n-1\n5 5"] | null | Java 8 | standard input | [
"data structures"
] | da1206100811e4a51b9453babfa2c821 | The first input line contains number n (1 ≤ n ≤ 2·105) — amount of requests. Then there follow n lines — descriptions of the requests. add x y describes the request to add a point, remove x y — the request to erase a point, find x y — the request to find the bottom-left point. All the coordinates in the input file are non-negative and don't exceed 109. | 2,800 | For each request of type find x y output in a separate line the answer to it — coordinates of the bottommost among the leftmost marked points, lying strictly above and to the right of point (x, y). If there are no points strictly above and to the right of point (x, y), output -1. | standard output | |
PASSED | f2a177e60a23e32e8cf78625ccb4e2fd | train_000.jsonl | 1277391600 | Pete and Bob invented a new interesting game. Bob takes a sheet of paper and locates a Cartesian coordinate system on it as follows: point (0, 0) is located in the bottom-left corner, Ox axis is directed right, Oy axis is directed up. Pete gives Bob requests of three types: add x y — on the sheet of paper Bob marks a point with coordinates (x, y). For each request of this type it's guaranteed that point (x, y) is not yet marked on Bob's sheet at the time of the request. remove x y — on the sheet of paper Bob erases the previously marked point with coordinates (x, y). For each request of this type it's guaranteed that point (x, y) is already marked on Bob's sheet at the time of the request. find x y — on the sheet of paper Bob finds all the marked points, lying strictly above and strictly to the right of point (x, y). Among these points Bob chooses the leftmost one, if it is not unique, he chooses the bottommost one, and gives its coordinates to Pete. Bob managed to answer the requests, when they were 10, 100 or 1000, but when their amount grew up to 2·105, Bob failed to cope. Now he needs a program that will answer all Pete's requests. Help Bob, please! | 256 megabytes | import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.NavigableSet;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
new CF_19D().run();
}
}
class CF_19D {
void run() {
// Scanner cin = new Scanner(new BufferedInputStream(System.in));
FastScanner cin = new FastScanner(System.in) ;
PrintWriter cout = new PrintWriter(new BufferedOutputStream(System.out));
int n = cin.nextInt();
for (int i = 0; i < n; i++) {
switch (cin.next()) {
case "add":
operator[i] = 0;
break;
case "remove":
operator[i] = 1;
break;
case "find":
operator[i] = 2;
break;
}
x[i] = cin.nextInt();
y[i] = cin.nextInt();
}
Hash h = new Hash(n, x);
int limit = h.length() - 1;
for (int i = 0; i <= limit; i++)
set[i].clear();
buildTree(1, 0, limit);
for (int i = 0; i < n; i++) {
int id = h.idx(x[i]);
if (operator[i] == 0) {
set[id].add(y[i]);
update(id, set[id].isEmpty() ? 0 : set[id].last(), 1, 0, limit);
} else if (operator[i] == 1) {
set[id].remove(y[i]);
update(id, set[id].isEmpty() ? 0 : set[id].last(), 1, 0, limit);
} else {
int pos = ask(id + 1, y[i], 1, 0, limit);
if (pos == NOTFIND)
cout.println(NOTFIND);
else
cout.println(h.value(pos) + " " + set[pos].higher(y[i]));
}
}
cout.flush();
}
void buildTree(int t, int l, int r) {
left[t] = l;
right[t] = r;
max[t] = 0;
if (l == r)
return;
int mid = (l + r) >> 1;
buildTree(t << 1, l, mid);
buildTree(t << 1 | 1, mid + 1, r);
up(t);
}
void update(int i, int c, int t, int l, int r) {
if (l > r)
return;
if (l == r) {
max[t] = c;
return;
}
int mid = (l + r) >> 1;
if (i <= mid)
update(i, c, t << 1, l, mid);
else
update(i, c, t << 1 | 1, mid + 1, r);
up(t);
}
int ask(int i, int c, int t, int l, int r) {
if (max[t] <= c || i > r)
return NOTFIND;
if (l == r)
return max[t] > c ? l : NOTFIND;
int mid = (l + r) >> 1;
if (i > mid)
return ask(i, c, t << 1 | 1, mid + 1, r);
else {
int res = ask(i, c, t << 1, l, mid);
if (res != NOTFIND)
return res;
else
return ask(i, c, t << 1 | 1, mid + 1, r);
}
}
void up(int t) {
max[t] = Math.max(max[t << 1], max[t << 1 | 1]);
}
final int NOTFIND = -1;
final int N = 200_008;
int[] x = new int[N];
int[] y = new int[N];
int[] z = new int[N];
int[] operator = new int[N];
NavigableSet<Integer>[] set = new TreeSet[N];
{
for (int i = 0; i < N; i++)
set[i] = new TreeSet<Integer>();
}
int[] left = new int[N << 2];
int[] right = new int[N << 2];
int[] max = new int[N << 2];
}
class Hash {
Hash(int length, int[] array) {
Set<Integer> treeset = new TreeSet<Integer>();
for (int i = 0; i < length; i++) {
treeset.add(array[i]);
}
this.array = new int[treeset.size()];
size = 0;
for (int i : treeset)
this.array[size++] = i;
}
int length() {
return size;
}
int idx(int key) {
return Arrays.binarySearch(array, key);
}
int value(int idx) {
return array[idx];
}
int size;
int[] array;
}
class FastScanner extends BufferedReader {
boolean isEOF;
public FastScanner(InputStream is) {
super(new InputStreamReader(is));
}
public int read() {
try {
int ret = super.read();
if (isEOF && ret < 0) {
throw new InputMismatchException();
}
isEOF = ret == -1;
return ret;
} catch (IOException e) {
throw new InputMismatchException();
}
}
public String next() {
StringBuilder sb = new StringBuilder();
int c = read();
while (isWhiteSpace(c)) {
c = read();
}
while (!isWhiteSpace(c)) {
sb.appendCodePoint(c);
c = read();
}
return sb.toString();
}
static boolean isWhiteSpace(int c) {
return c >= -1 && c <= 32;
}
public int nextInt() {
int c = read();
while (isWhiteSpace(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int ret = 0;
while (!isWhiteSpace(c)) {
if (c < '0' || c > '9') {
throw new NumberFormatException("digit expected " + (char) c
+ " found");
}
ret = ret * 10 + c - '0';
c = read();
}
return ret * sgn;
}
}
| Java | ["7\nadd 1 1\nadd 3 4\nfind 0 0\nremove 1 1\nfind 0 0\nadd 1 1\nfind 0 0", "13\nadd 5 5\nadd 5 6\nadd 5 7\nadd 6 5\nadd 6 6\nadd 6 7\nadd 7 5\nadd 7 6\nadd 7 7\nfind 6 6\nremove 7 7\nfind 6 6\nfind 4 4"] | 2 seconds | ["1 1\n3 4\n1 1", "7 7\n-1\n5 5"] | null | Java 8 | standard input | [
"data structures"
] | da1206100811e4a51b9453babfa2c821 | The first input line contains number n (1 ≤ n ≤ 2·105) — amount of requests. Then there follow n lines — descriptions of the requests. add x y describes the request to add a point, remove x y — the request to erase a point, find x y — the request to find the bottom-left point. All the coordinates in the input file are non-negative and don't exceed 109. | 2,800 | For each request of type find x y output in a separate line the answer to it — coordinates of the bottommost among the leftmost marked points, lying strictly above and to the right of point (x, y). If there are no points strictly above and to the right of point (x, y), output -1. | standard output | |
PASSED | 1c87df9efcd8a386bf922d18911434bc | train_000.jsonl | 1277391600 | Pete and Bob invented a new interesting game. Bob takes a sheet of paper and locates a Cartesian coordinate system on it as follows: point (0, 0) is located in the bottom-left corner, Ox axis is directed right, Oy axis is directed up. Pete gives Bob requests of three types: add x y — on the sheet of paper Bob marks a point with coordinates (x, y). For each request of this type it's guaranteed that point (x, y) is not yet marked on Bob's sheet at the time of the request. remove x y — on the sheet of paper Bob erases the previously marked point with coordinates (x, y). For each request of this type it's guaranteed that point (x, y) is already marked on Bob's sheet at the time of the request. find x y — on the sheet of paper Bob finds all the marked points, lying strictly above and strictly to the right of point (x, y). Among these points Bob chooses the leftmost one, if it is not unique, he chooses the bottommost one, and gives its coordinates to Pete. Bob managed to answer the requests, when they were 10, 100 or 1000, but when their amount grew up to 2·105, Bob failed to cope. Now he needs a program that will answer all Pete's requests. Help Bob, please! | 256 megabytes |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.TreeSet;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) throws IOException {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader sc = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Task solver = new Task();
solver.solve(1, sc, out);
out.close();
}
static class Task {
public void solve(int testNumber, InputReader sc, PrintWriter out) throws IOException {
int n=sc.nextInt();
OptNode[] query=new OptNode[n];
int[] buf1=new int[n];
int[] buf2=new int[n];
int index1=0;
int index2=0;
for(int i=0;i<n;i++) {
char opt=sc.next().charAt(0);
int x=sc.nextInt();
int y=sc.nextInt();
if(opt!='f')
buf1[index1++]=x;
query[i]=new OptNode(opt,x,y);
}
Arrays.sort(buf1,0,index1);
buf2[index2++]=buf1[0];
for(int i=1;i<index1;i++)
if(buf1[i]!=buf1[i-1])
buf2[index2++]=buf1[i];
SegTree sgt=new SegTree(index2,buf2);
sgt.build(1, 1, index2);
for(int i=0;i<n;i++) {
if(query[i].opt=='f') {
int index=Arrays.binarySearch(buf2, 0, index2, query[i].x+1);
//System.out.println(index);
if(index<0)
index=-index;
else
index++;
if(index>index2) {
out.println("-1");
continue;
}
Ans ans=sgt.ask(1, index, index2, query[i].y+1);
if(ans==null)
out.println("-1");
else
out.println(ans.x+" "+ans.y);
}
else {
int index=Arrays.binarySearch(buf2, 0, index2, query[i].x)+1;
if(query[i].opt=='a')
sgt.change(1, index, true, query[i].y);
else
sgt.change(1, index, false, query[i].y);
}
}
}
}
static class Ans{
int x;
int y;
public Ans(int x,int y) {
this.x=x;
this.y=y;
}
}
static class OptNode{
char opt;
int x;
int y;
public OptNode(char opt,int x,int y) {
this.opt=opt;
this.x=x;
this.y=y;
}
}
static class SegTree{
class Node{
int l;
int r;
int max_y;
int cnt;
TreeSet<Integer> set;
public Node(int l,int r) {
this.l=l;
this.r=r;
if(l==r)
this.set=new TreeSet<Integer>();
}
}
public Node[] t;
public int[] buf;
public SegTree(int n,int[] buf) {
this.t=new Node[(n+10)<<2];
this.buf=buf;
}
public void pushUp(int p) {
t[p].cnt=t[p*2].cnt+t[p*2+1].cnt;
t[p].max_y=Math.max(t[p*2].max_y, t[p*2+1].max_y);
}
public void build(int p,int l,int r) {
t[p]=new Node(l,r);
if(l==r)
return ;
int mid=(l+r)>>1;
build(p*2,l,mid);
build(p*2+1,mid+1,r);
}
public void change(int p,int index,boolean flag,int val) {
if(t[p].l==t[p].r) {
if(flag) {
t[p].cnt++;
t[p].set.add(val);
}
else {
t[p].cnt--;
t[p].set.remove(val);
}
t[p].max_y=t[p].set.size()==0?0:t[p].set.last();
return ;
}
int mid=(t[p].l+t[p].r)>>1;
if(index<=mid)
change(p*2,index,flag,val);
else
change(p*2+1,index,flag,val);
pushUp(p);
}
public Ans ask(int p,int l,int r,int val) {
if(t[p].l>=l&&t[p].r<=r&&(t[p].cnt==0||t[p].max_y<val))
return null;
if(t[p].l==t[p].r) {
if(t[p].cnt==0||t[p].max_y<val)
return null;
Integer res=t[p].set.ceiling(val);
if(res==null)
return null;
return new Ans(buf[t[p].l-1],res);
}
int mid=(t[p].l+t[p].r)>>1;
Ans res1=null;
Ans res2=null;
if(l<=mid)
res1=ask(p*2,l,r,val);
if(res1!=null)
return res1;
if(r>mid)
res2=ask(p*2+1,l,r,val);
return res2;
}
}
static class InputReader{
StreamTokenizer tokenizer;
public InputReader(InputStream stream){
tokenizer=new StreamTokenizer(new BufferedReader(new InputStreamReader(stream)));
tokenizer.ordinaryChars(33,126);
tokenizer.wordChars(33,126);
}
public String next() throws IOException {
tokenizer.nextToken();
return tokenizer.sval;
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public boolean hasNext() throws IOException {
int res=tokenizer.nextToken();
tokenizer.pushBack();
return res!=tokenizer.TT_EOF;
}
}
}
| Java | ["7\nadd 1 1\nadd 3 4\nfind 0 0\nremove 1 1\nfind 0 0\nadd 1 1\nfind 0 0", "13\nadd 5 5\nadd 5 6\nadd 5 7\nadd 6 5\nadd 6 6\nadd 6 7\nadd 7 5\nadd 7 6\nadd 7 7\nfind 6 6\nremove 7 7\nfind 6 6\nfind 4 4"] | 2 seconds | ["1 1\n3 4\n1 1", "7 7\n-1\n5 5"] | null | Java 8 | standard input | [
"data structures"
] | da1206100811e4a51b9453babfa2c821 | The first input line contains number n (1 ≤ n ≤ 2·105) — amount of requests. Then there follow n lines — descriptions of the requests. add x y describes the request to add a point, remove x y — the request to erase a point, find x y — the request to find the bottom-left point. All the coordinates in the input file are non-negative and don't exceed 109. | 2,800 | For each request of type find x y output in a separate line the answer to it — coordinates of the bottommost among the leftmost marked points, lying strictly above and to the right of point (x, y). If there are no points strictly above and to the right of point (x, y), output -1. | standard output | |
PASSED | e3c9dfbd8d844dafc5f2546521166e76 | train_000.jsonl | 1523973900 | You are given two integers $$$a$$$ and $$$b$$$. Moreover, you are given a sequence $$$s_0, s_1, \dots, s_{n}$$$. All values in $$$s$$$ are integers $$$1$$$ or $$$-1$$$. It's known that sequence is $$$k$$$-periodic and $$$k$$$ divides $$$n+1$$$. In other words, for each $$$k \leq i \leq n$$$ it's satisfied that $$$s_{i} = s_{i - k}$$$.Find out the non-negative remainder of division of $$$\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i}$$$ by $$$10^{9} + 9$$$.Note that the modulo is unusual! | 256 megabytes | import java.util.Scanner;
public class code964C {
static long m = 1000000009;
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
int n = s.nextInt();
long a = s.nextLong();
long b = s.nextLong();
int k = s.nextInt();
s.nextLine();
char[] cc = s.nextLine().toCharArray();
long ainv = fp(a,m-2);
long ak = fp(a,k);
long bk = fp(b,k);
long akinv = fp(ak,m-2);
long ainvb = ainv * b %m;
long akinvbk = akinv*bk%m;
int sqn = (int)(Math.floor(Math.sqrt(n+1)));
int q = sqn/k;
long[] sk = new long[k];
sk[0] = fp(a,n);
long sumk = sk[0]*(cc[0]=='+'?1:-1);
for(int i=1;i<k;i++){
sk[i] = sk[i-1]*ainvb%m;
sumk += sk[i]*(cc[i]=='+'?1:-1);
}
sumk %= m;
if(sumk<0)sumk+=m;
if(q==0){
int l = (n+1)/k;
long[] sl = new long[l];
sl[0] = sumk;
for(int i=1;i<l;i++){
sl[i] = sl[i-1]*akinvbk%m;
sumk += sl[i];
}
sumk %= m;
if(sumk<0)sumk+=m;
System.out.println(sumk);
return;
}else{
// cp
long[] sq = new long[q];
sq[0]=sumk;
long sump = sumk;
for(int i=1;i<q;i++){
sq[i]=sq[i-1]*akinvbk%m;
sump += sq[i];
}
sump%=m;
if(sump<0)sump+=m;
int p = q*k;
int l = (n+1)/p;
int g = (n+1)%p/k;
long apinvbp = fp(akinvbk,q);
long[] sp = new long[l];
long sumlp = sump;
sp[0]=sump;
for(int i=1;i<l;i++){
sp[i] = sp[i-1]*apinvbp%m;
sumlp += sp[i];
}
sumlp%=m;
if(sumlp<0)sumlp+=m;
if(g==0){System.out.println(sumlp);
return;}else{
long gs = sumk * fp(akinvbk,l*q)%m;
long[] sg = new long[g];
sg[0]= gs;
long sumg = gs;
for(int i=1;i<g;i++){
sg[i]=sg[i-1]*akinvbk%m;
sumg += sg[i];
}
sumlp += sumg;
sumlp %=m;
if(sumlp<0)sumlp+=m;
System.out.println(sumlp);
return;
}
}
}
static long fp(long a,long i){
long r = 1;
while(i>0){
if((i&1)==1) r = r*a%m;
a = a*a%m;
i=i>>1;
}
return r;
}
}
| Java | ["2 2 3 3\n+-+", "4 1 5 1\n-"] | 1 second | ["7", "999999228"] | NoteIn the first example:$$$(\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i})$$$ = $$$2^{2} 3^{0} - 2^{1} 3^{1} + 2^{0} 3^{2}$$$ = 7In the second example:$$$(\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i}) = -1^{4} 5^{0} - 1^{3} 5^{1} - 1^{2} 5^{2} - 1^{1} 5^{3} - 1^{0} 5^{4} = -781 \equiv 999999228 \pmod{10^{9} + 9}$$$. | Java 8 | standard input | [
"number theory",
"math",
"matrices"
] | 607e670403a40e4fddf389caba79607e | The first line contains four integers $$$n, a, b$$$ and $$$k$$$ $$$(1 \leq n \leq 10^{9}, 1 \leq a, b \leq 10^{9}, 1 \leq k \leq 10^{5})$$$. The second line contains a sequence of length $$$k$$$ consisting of characters '+' and '-'. If the $$$i$$$-th character (0-indexed) is '+', then $$$s_{i} = 1$$$, otherwise $$$s_{i} = -1$$$. Note that only the first $$$k$$$ members of the sequence are given, the rest can be obtained using the periodicity property. | 1,800 | Output a single integer — value of given expression modulo $$$10^{9} + 9$$$. | standard output | |
PASSED | 464902d212fe8164477a15a477682cb1 | train_000.jsonl | 1523973900 | You are given two integers $$$a$$$ and $$$b$$$. Moreover, you are given a sequence $$$s_0, s_1, \dots, s_{n}$$$. All values in $$$s$$$ are integers $$$1$$$ or $$$-1$$$. It's known that sequence is $$$k$$$-periodic and $$$k$$$ divides $$$n+1$$$. In other words, for each $$$k \leq i \leq n$$$ it's satisfied that $$$s_{i} = s_{i - k}$$$.Find out the non-negative remainder of division of $$$\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i}$$$ by $$$10^{9} + 9$$$.Note that the modulo is unusual! | 256 megabytes | /* package whatever; // 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 Main{
public static void main(String[] args){
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();
int a=scan.nextInt();
int b=scan.nextInt();
int k=scan.nextInt();
String s=scan.next();
int[] arr=new int[k];
//System.out.println(s);
for(int i=0;i<k;i++){
if(s.charAt(i)=='+'){
arr[i]=1;
}
else{arr[i]=-1;}
}
scan.close();
System.out.println((new NumberTheory()).doit(arr,n,a,b));
}
}
class NumberTheory{
long P=1000000009;
long pow(int x,int k){
long base=(long)x;
long res=1;
while(k>0){
if((k&1)==1){
res=(res*base)%P;
}
base=(base*base)%P;
k>>=1;
}
return res;
}
long inverse(int x){
return pow(x,(int)P-2);
}
int doit(int[] s,int n,int a,int b){
long t=(b*inverse(a))%P;
long sum=0;
int k=s.length;
//System.out.println(t);
for(int i=0;i<k;i++){
//System.out.println(s[i]);
if(s[i]==1){sum+=pow((int)t,i);}
else{sum-=pow((int)t,i);}
if(sum<0){sum+=P;}
sum%=P;
}
long p=pow(a,n);
long g;
long f=pow((int)t,k);
//System.out.println(sum);
//System.out.println(p);
if(f==1){g=(long)((n+1)/k);}
else{
//long den=f-1;
g=((pow((int)t,n+1)-1)*inverse((int)f-1))%P;
}
return (int)((((p*g)%P)*sum)%P);
}
}
| Java | ["2 2 3 3\n+-+", "4 1 5 1\n-"] | 1 second | ["7", "999999228"] | NoteIn the first example:$$$(\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i})$$$ = $$$2^{2} 3^{0} - 2^{1} 3^{1} + 2^{0} 3^{2}$$$ = 7In the second example:$$$(\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i}) = -1^{4} 5^{0} - 1^{3} 5^{1} - 1^{2} 5^{2} - 1^{1} 5^{3} - 1^{0} 5^{4} = -781 \equiv 999999228 \pmod{10^{9} + 9}$$$. | Java 8 | standard input | [
"number theory",
"math",
"matrices"
] | 607e670403a40e4fddf389caba79607e | The first line contains four integers $$$n, a, b$$$ and $$$k$$$ $$$(1 \leq n \leq 10^{9}, 1 \leq a, b \leq 10^{9}, 1 \leq k \leq 10^{5})$$$. The second line contains a sequence of length $$$k$$$ consisting of characters '+' and '-'. If the $$$i$$$-th character (0-indexed) is '+', then $$$s_{i} = 1$$$, otherwise $$$s_{i} = -1$$$. Note that only the first $$$k$$$ members of the sequence are given, the rest can be obtained using the periodicity property. | 1,800 | Output a single integer — value of given expression modulo $$$10^{9} + 9$$$. | standard output | |
PASSED | 033ab1fb52ecb683556cfeade3a403ac | train_000.jsonl | 1523973900 | You are given two integers $$$a$$$ and $$$b$$$. Moreover, you are given a sequence $$$s_0, s_1, \dots, s_{n}$$$. All values in $$$s$$$ are integers $$$1$$$ or $$$-1$$$. It's known that sequence is $$$k$$$-periodic and $$$k$$$ divides $$$n+1$$$. In other words, for each $$$k \leq i \leq n$$$ it's satisfied that $$$s_{i} = s_{i - k}$$$.Find out the non-negative remainder of division of $$$\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i}$$$ by $$$10^{9} + 9$$$.Note that the modulo is unusual! | 256 megabytes | //Codeforces Round #475 (Div. 2)
import java.io.*;
import java.util.*;
public class TaskC {
public static long P = 1000000009;
/*
def egcd(a, b):
x,y, u,v = 0,1, 1,0
while a != 0:
q, r = b//a, b%a
m, n = x-u*q, y-v*q
b,a, x,y, u,v = a,r, u,v, m,n
gcd = b
return gcd, x, y
print egcd(1432,123211)
*/
public static long div(long t) {
long x = 0;
long y = 1;
long u = 1;
long v = 0;
long a = t%P;
long b = P;
while (a != 0) {
long q = b/a;
long r = b%a;
long m = x - u*q;
long n = y - v*q;
b = a;
a = r;
x = u;
y = v;
u = m;
v = n;
}
while (x < 0) {
x += P;
}
return x%P;
}
public static long pow(long x, int y) {
long p = x%P;
long q = 1;
while (y > 0) {
if ((y & 1) != 0) {
q = (q*p)%P;
}
y >>= 1;
p = (p*p)%P;
}
return q;
}
public static void main (String[] args) throws IOException {
FastScanner fs = new FastScanner(System.in);
PrintWriter pw = new PrintWriter(new BufferedOutputStream(System.out));
int n = fs.nextInt();
long a = fs.nextInt();
long b = fs.nextInt();
int k = fs.nextInt();
String sg = fs.next();
long s = 0;
for (int i = 0; i < k; i++) {
long x = (pow(a, n-i)*pow(b, i))%P;
if (sg.charAt(i) == '-') x = P-x;
s = (s+x)%P;
}
long z;
long y = pow((b*div(a))%P, k);
if (y == 1) {
z = (n+1)/k;
} else {
z = (((pow(y, (n+1)/k)-1+P)%P)*div((y-1+P)%P))%P;
}
z = (s*z)%P;
pw.println(z);
pw.close();
}
static class FastScanner {
BufferedReader reader;
StringTokenizer tokenizer;
FastScanner(InputStream i) {
reader = new BufferedReader(new InputStreamReader(i));
tokenizer = new StringTokenizer("");
}
String next() throws IOException {
while(!tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(reader.readLine());
return tokenizer.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
}
} | Java | ["2 2 3 3\n+-+", "4 1 5 1\n-"] | 1 second | ["7", "999999228"] | NoteIn the first example:$$$(\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i})$$$ = $$$2^{2} 3^{0} - 2^{1} 3^{1} + 2^{0} 3^{2}$$$ = 7In the second example:$$$(\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i}) = -1^{4} 5^{0} - 1^{3} 5^{1} - 1^{2} 5^{2} - 1^{1} 5^{3} - 1^{0} 5^{4} = -781 \equiv 999999228 \pmod{10^{9} + 9}$$$. | Java 8 | standard input | [
"number theory",
"math",
"matrices"
] | 607e670403a40e4fddf389caba79607e | The first line contains four integers $$$n, a, b$$$ and $$$k$$$ $$$(1 \leq n \leq 10^{9}, 1 \leq a, b \leq 10^{9}, 1 \leq k \leq 10^{5})$$$. The second line contains a sequence of length $$$k$$$ consisting of characters '+' and '-'. If the $$$i$$$-th character (0-indexed) is '+', then $$$s_{i} = 1$$$, otherwise $$$s_{i} = -1$$$. Note that only the first $$$k$$$ members of the sequence are given, the rest can be obtained using the periodicity property. | 1,800 | Output a single integer — value of given expression modulo $$$10^{9} + 9$$$. | standard output | |
PASSED | 045616076b38fedeb1ba04bf2d8126d4 | train_000.jsonl | 1523973900 | You are given two integers $$$a$$$ and $$$b$$$. Moreover, you are given a sequence $$$s_0, s_1, \dots, s_{n}$$$. All values in $$$s$$$ are integers $$$1$$$ or $$$-1$$$. It's known that sequence is $$$k$$$-periodic and $$$k$$$ divides $$$n+1$$$. In other words, for each $$$k \leq i \leq n$$$ it's satisfied that $$$s_{i} = s_{i - k}$$$.Find out the non-negative remainder of division of $$$\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i}$$$ by $$$10^{9} + 9$$$.Note that the modulo is unusual! | 256 megabytes | import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
public static Scanner sc=new Scanner(System.in);
public static long mod=1000000000+9;
public static boolean flag[];
public static void main(String[] args){
long n=sc.nextLong();
long a=sc.nextLong()%mod;
long b=sc.nextLong()%mod;
int k=sc.nextInt();
sc.nextLine();
long ar=quickPow(a,mod-2);
long ans=0;
long ab=ar*b%mod;
long cycle=0;
long tmp=1;
long start=quickPow(a,n);
String flag=sc.next();
for(int i=0;i<k;i++){
if(flag.charAt(i)=='+')
cycle=(cycle+tmp+mod)%mod;
else cycle=(cycle-tmp+mod)%mod;
tmp=tmp*ab%mod;
}
long cx=quickPow(ab,k);
//cycle是 一轮 ab^0+...+ab^k-1
if(n+1>k)
ans=T(cx,(n+1)/k-1)+1;
else ans=1;
ans=ans*start%mod;
ans=ans*cycle%mod;
System.out.println(ans);
}
public static long T(long k,long n){
if(n==1) return k;
long pt=T(k,n/2);
if(n%2==1){
return (pt+quickPow(k,n/2)*pt+quickPow(k,n))%mod;
}else{
return (pt+quickPow(k,n/2)*pt)%mod;
}
}
public static long quickPow(long a,long b) {
long r = 1;
long base = a;
while (b!=0) {
if ((b & 1)!=0) {
r = base*r%mod;
}
base = base*base%mod;
b >>= 1;
}
return r;
}
} | Java | ["2 2 3 3\n+-+", "4 1 5 1\n-"] | 1 second | ["7", "999999228"] | NoteIn the first example:$$$(\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i})$$$ = $$$2^{2} 3^{0} - 2^{1} 3^{1} + 2^{0} 3^{2}$$$ = 7In the second example:$$$(\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i}) = -1^{4} 5^{0} - 1^{3} 5^{1} - 1^{2} 5^{2} - 1^{1} 5^{3} - 1^{0} 5^{4} = -781 \equiv 999999228 \pmod{10^{9} + 9}$$$. | Java 8 | standard input | [
"number theory",
"math",
"matrices"
] | 607e670403a40e4fddf389caba79607e | The first line contains four integers $$$n, a, b$$$ and $$$k$$$ $$$(1 \leq n \leq 10^{9}, 1 \leq a, b \leq 10^{9}, 1 \leq k \leq 10^{5})$$$. The second line contains a sequence of length $$$k$$$ consisting of characters '+' and '-'. If the $$$i$$$-th character (0-indexed) is '+', then $$$s_{i} = 1$$$, otherwise $$$s_{i} = -1$$$. Note that only the first $$$k$$$ members of the sequence are given, the rest can be obtained using the periodicity property. | 1,800 | Output a single integer — value of given expression modulo $$$10^{9} + 9$$$. | standard output | |
PASSED | 58cc71d8928992f96a72a7285035280f | train_000.jsonl | 1523973900 | You are given two integers $$$a$$$ and $$$b$$$. Moreover, you are given a sequence $$$s_0, s_1, \dots, s_{n}$$$. All values in $$$s$$$ are integers $$$1$$$ or $$$-1$$$. It's known that sequence is $$$k$$$-periodic and $$$k$$$ divides $$$n+1$$$. In other words, for each $$$k \leq i \leq n$$$ it's satisfied that $$$s_{i} = s_{i - k}$$$.Find out the non-negative remainder of division of $$$\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i}$$$ by $$$10^{9} + 9$$$.Note that the modulo is unusual! | 256 megabytes | import java.util.*;
import java.io.*;
public class ProbC implements Runnable{
private static InputStream stream;
private static byte[] buf = new byte[1024];
private static int curChar;
private static int numChars;
private static SpaceCharFilter filter;
private static PrintWriter pw;
static long MOD = (long)1e9+9;
static long modularExponentiation(long x,long n){
if(n==0)
return 1;
else if(n%2 == 0) //n is even
return modularExponentiation((x*x)%MOD,n/2);
else //n is odd
return (x*modularExponentiation((x*x)%MOD,(n-1)/2))%MOD;
}
private static void soln(){
long n=nextInt(), a=nextInt(), b=nextInt(), k=nextInt();
long kk=k;
String s = nextLine();
StringBuilder sb = new StringBuilder();
sb.append(s);
while(k<50000){
k+=kk;
sb.append(s);
}
long p = 0;
for (long i = 0; i < k; i++)
{
char c = sb.charAt((int)i);
if (c == '+')
p += modularExponentiation(a, k-1-i) * modularExponentiation(b, i);
else
p += MOD - (modularExponentiation(a, k-1-i) * modularExponentiation(b, i) % MOD);
p %= MOD;
}
long ans = 0;
long i = 0;
for (; i <= n; i += k)
{
if (i+k-1 > n)
break;
long bpow = i;
long apow = n-i-k+1;
long add = modularExponentiation(a, apow)*modularExponentiation(b, bpow) % MOD;
add *= p;
ans += add;
ans %= MOD;
}
long c = 0;
while (i <= n)
{
if (sb.charAt((int)c) == '+')
ans += modularExponentiation(a, n-i) * modularExponentiation(b, i);
else
ans += MOD - (modularExponentiation(a, n-i) * modularExponentiation(b, i) % MOD);
ans %= MOD;
c++;
i++;
}
System.out.println(ans);
}
public void run (){
soln();
}
public static void main(String[] args) throws InterruptedException{
InputReader(System.in);
pw = new PrintWriter(System.out);
Thread t = new Thread(null, new ProbC(), "ProbC", 1<<28);
t.start();
t.join();
pw.close();
}
// To Get Input
// Some Buffer Methods
public static void InputReader(InputStream stream1) {
stream = stream1;
}
private static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private static boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
private static int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
private static 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;
}
private static 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;
}
private static String nextToken() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private static 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();
}
private static int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
private static long[] nextLongArray(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
private static void pArray(int[] arr){
for (int i=0; i<arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
return;
}
private static void pArray(long[] arr){
for (int i=0; i<arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
return;
}
private static boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
private interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
} | Java | ["2 2 3 3\n+-+", "4 1 5 1\n-"] | 1 second | ["7", "999999228"] | NoteIn the first example:$$$(\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i})$$$ = $$$2^{2} 3^{0} - 2^{1} 3^{1} + 2^{0} 3^{2}$$$ = 7In the second example:$$$(\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i}) = -1^{4} 5^{0} - 1^{3} 5^{1} - 1^{2} 5^{2} - 1^{1} 5^{3} - 1^{0} 5^{4} = -781 \equiv 999999228 \pmod{10^{9} + 9}$$$. | Java 8 | standard input | [
"number theory",
"math",
"matrices"
] | 607e670403a40e4fddf389caba79607e | The first line contains four integers $$$n, a, b$$$ and $$$k$$$ $$$(1 \leq n \leq 10^{9}, 1 \leq a, b \leq 10^{9}, 1 \leq k \leq 10^{5})$$$. The second line contains a sequence of length $$$k$$$ consisting of characters '+' and '-'. If the $$$i$$$-th character (0-indexed) is '+', then $$$s_{i} = 1$$$, otherwise $$$s_{i} = -1$$$. Note that only the first $$$k$$$ members of the sequence are given, the rest can be obtained using the periodicity property. | 1,800 | Output a single integer — value of given expression modulo $$$10^{9} + 9$$$. | standard output | |
PASSED | 8f5138d0d890a8e9e0291aed0ccb0ed9 | train_000.jsonl | 1523973900 | You are given two integers $$$a$$$ and $$$b$$$. Moreover, you are given a sequence $$$s_0, s_1, \dots, s_{n}$$$. All values in $$$s$$$ are integers $$$1$$$ or $$$-1$$$. It's known that sequence is $$$k$$$-periodic and $$$k$$$ divides $$$n+1$$$. In other words, for each $$$k \leq i \leq n$$$ it's satisfied that $$$s_{i} = s_{i - k}$$$.Find out the non-negative remainder of division of $$$\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i}$$$ by $$$10^{9} + 9$$$.Note that the modulo is unusual! | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
void solve(){
long n=ni(),a=ni(),b=ni();
int k=ni();
char s[]=ns().toCharArray();
long p=(n+1)/k-1;
long ans=0;
for(int i=0;i<s.length;i++){
int d=-1;
if(s[i]=='+') d=1;
long x=(modpow(b,k*(p+1),M)*modInverse(modpow(a,k*(p+1),M),M))%M;
x=(x-1+M)%M;
long y=(modpow(b,k,M)*modInverse(modpow(a,k,M),M))%M;
y=(y-1+M)%M;
long z=(x*modInverse(y,M))%M;
if(z==0){
z=(p+1);
}
z=(z*modpow(a,n-i,M))%M;
z=(z*modpow(b,i,M))%M;
z=(z*d+M)%M;
ans+=z;
ans%=M;
}
pw.println(ans);
}
long mul(long a, long b,long M)
{
return (a*1L*b)%M;
}
long modpow(long a, long b,long M)
{
long r=1;
while(b>0)
{
if((b&1)>0) r=mul(r,a,M);
a=mul(a,a,M);
b>>=1;
}
return r;
}
long modInverse(long A, long M)
{
return modpow(A,M-2,M);
}
long M=(long)1e9+9;
InputStream is;
PrintWriter pw;
String INPUT = "";
void run() throws Exception {
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
pw = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
pw.flush();
if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new Main().run(); }
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte() {
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m) {
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n) {
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni() {
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl() {
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private void tr(Object... o) { if(INPUT.length() > 0)System.out.println(Arrays.deepToString(o)); }
} | Java | ["2 2 3 3\n+-+", "4 1 5 1\n-"] | 1 second | ["7", "999999228"] | NoteIn the first example:$$$(\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i})$$$ = $$$2^{2} 3^{0} - 2^{1} 3^{1} + 2^{0} 3^{2}$$$ = 7In the second example:$$$(\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i}) = -1^{4} 5^{0} - 1^{3} 5^{1} - 1^{2} 5^{2} - 1^{1} 5^{3} - 1^{0} 5^{4} = -781 \equiv 999999228 \pmod{10^{9} + 9}$$$. | Java 8 | standard input | [
"number theory",
"math",
"matrices"
] | 607e670403a40e4fddf389caba79607e | The first line contains four integers $$$n, a, b$$$ and $$$k$$$ $$$(1 \leq n \leq 10^{9}, 1 \leq a, b \leq 10^{9}, 1 \leq k \leq 10^{5})$$$. The second line contains a sequence of length $$$k$$$ consisting of characters '+' and '-'. If the $$$i$$$-th character (0-indexed) is '+', then $$$s_{i} = 1$$$, otherwise $$$s_{i} = -1$$$. Note that only the first $$$k$$$ members of the sequence are given, the rest can be obtained using the periodicity property. | 1,800 | Output a single integer — value of given expression modulo $$$10^{9} + 9$$$. | standard output | |
PASSED | 736e50585824b39e0cfe80dda9c3cb65 | train_000.jsonl | 1523973900 | You are given two integers $$$a$$$ and $$$b$$$. Moreover, you are given a sequence $$$s_0, s_1, \dots, s_{n}$$$. All values in $$$s$$$ are integers $$$1$$$ or $$$-1$$$. It's known that sequence is $$$k$$$-periodic and $$$k$$$ divides $$$n+1$$$. In other words, for each $$$k \leq i \leq n$$$ it's satisfied that $$$s_{i} = s_{i - k}$$$.Find out the non-negative remainder of division of $$$\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i}$$$ by $$$10^{9} + 9$$$.Note that the modulo is unusual! | 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...
*/
public class Main
{
public static void main(String[] args)
{
int n=ni(),b=ni(),a=ni(),k=ni();
long mod=1000000009;
String s=ns();
int ho[]=new int[k];
for(int i=0; i<k; i++)
ho[i]=s.charAt(i)=='+'?1:-1;
int hol=(n/k);
long powa=powm(a,k,mod);
long powb=powm(b,k,mod);
long fac;
if((powa-powb)%mod!=0)
fac=(((powm(powa,hol+1,mod)-powm(powb,hol+1,mod))*(powm(powa-powb,mod-2,mod)))%mod);
else
fac=((hol+1)*powm(powa,hol,mod))%mod;
long ans=0;
int p=n%k;
for(int i=0; i<=p; i++)
ans=(ans+ho[i]*((fac*powm(a,i,mod))%mod)*powm(b,p-i,mod))%mod;
for(int i=p+1; i<k; i++)
ans=(ans+ho[i]*(((fac-powm(powb,hol,mod))*powm(a,i,mod))%mod)*powm(b,p-i,mod))%mod;
pr((ans+mod)%mod);
System.out.println(output);
}
///////////////////////////////////////////
///////////////////////////////////////////
///template from here
static final long 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;}
//////////////////////////////////
//some utility functions
static void psort(Integer[][] a)
{
Arrays.sort(a, new Comparator<Integer[]>()
{
@Override
public int compare(Integer[]a,Integer[]b)
{
if(a[0]>b[0])
return 1;
else if(b[0]>a[1])
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 | ["2 2 3 3\n+-+", "4 1 5 1\n-"] | 1 second | ["7", "999999228"] | NoteIn the first example:$$$(\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i})$$$ = $$$2^{2} 3^{0} - 2^{1} 3^{1} + 2^{0} 3^{2}$$$ = 7In the second example:$$$(\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i}) = -1^{4} 5^{0} - 1^{3} 5^{1} - 1^{2} 5^{2} - 1^{1} 5^{3} - 1^{0} 5^{4} = -781 \equiv 999999228 \pmod{10^{9} + 9}$$$. | Java 8 | standard input | [
"number theory",
"math",
"matrices"
] | 607e670403a40e4fddf389caba79607e | The first line contains four integers $$$n, a, b$$$ and $$$k$$$ $$$(1 \leq n \leq 10^{9}, 1 \leq a, b \leq 10^{9}, 1 \leq k \leq 10^{5})$$$. The second line contains a sequence of length $$$k$$$ consisting of characters '+' and '-'. If the $$$i$$$-th character (0-indexed) is '+', then $$$s_{i} = 1$$$, otherwise $$$s_{i} = -1$$$. Note that only the first $$$k$$$ members of the sequence are given, the rest can be obtained using the periodicity property. | 1,800 | Output a single integer — value of given expression modulo $$$10^{9} + 9$$$. | standard output | |
PASSED | 4f648675e280e819b373a2ebb0206d5c | train_000.jsonl | 1523973900 | You are given two integers $$$a$$$ and $$$b$$$. Moreover, you are given a sequence $$$s_0, s_1, \dots, s_{n}$$$. All values in $$$s$$$ are integers $$$1$$$ or $$$-1$$$. It's known that sequence is $$$k$$$-periodic and $$$k$$$ divides $$$n+1$$$. In other words, for each $$$k \leq i \leq n$$$ it's satisfied that $$$s_{i} = s_{i - k}$$$.Find out the non-negative remainder of division of $$$\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i}$$$ by $$$10^{9} + 9$$$.Note that the modulo is unusual! | 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.flush();out.close();
}
static class TaskE {
long pa[],pb[];int max=100010;
long mod=(long)(1E9)+9;
long rpe(long a,long b){
a=a%mod;
long ans=1;
while(b!=0){
if(b%2!=0){ans=ans*a%mod;}
a=a*a%mod;b/=2;
}return ans;
}
void pre(long a,long b,long n,long k){
long ap=rpe(a,n);long ia=rpe(a,mod-2);
long m=1;pa[0]=ap;
for(int i=1;i<=k;i++)pa[i]=pa[i-1]*ia%mod;
pb[0]=1;
for(int i=1;i<=k;i++)pb[i]=pb[i-1]*b%mod;
}
public void solve(int testNumber, InputReader in, PrintWriter out) {
long n=in.nextLong(),a=in.nextLong(),b=in.nextLong(),k=in.nextLong();
String s=in.next().trim();
long val=0;int l=s.length();
pa=new long[max];pb=new long[max];
pre(a,b,n,k);
for(int i=0;i<l;i++){
if(s.charAt(i)=='+')val=(val+pa[i]*pb[i]%mod)%mod;
else val=(val-pa[i]*pb[i]%mod+mod)%mod;
}
long ak=rpe(a,mod-1L-k);ak=ak*pb[(int)k]%mod;
long x=(n+1)/k;
long num=(rpe(ak,x)-1+mod)%mod;long den=rpe(ak-1+mod,mod-2);
if(ak!=1)out.print(val*num%mod*den%mod);
else out.print(val*x%mod);
}
/*pair ja[][];long w[];int from[],to[],c[];
void make(int n,int m,InputReader in){
ja=new pair[n+1][];w=new long[m];from=new int[m];to=new int[m];c=new int[n+1];
for(int i=0;i<m;i++){
int u=in.nextInt(),v=in.nextInt();long wt=in.nextLong();
c[u]++;c[v]++;from[i]=u;to[i]=v;w[i]=wt;
}
for(int i=1;i<=n;i++){
ja[i]=new pair[c[i]];c[i]=0;
}
for(int i=0;i<m;i++){
ja[from[i]][c[from[i]]++]=new pair(to[i],w[i]);
ja[to[i]][c[to[i]]++]=new pair(from[i],w[i]);
}
}*/
int[] radixSort(int[] f){ return radixSort(f, f.length); }
int[] radixSort(int[] f, int n)
{
int[] to = new int[n];
{
int[] b = new int[65537];
for(int i = 0;i < n;i++)b[1+(f[i]&0xffff)]++;
for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
for(int i = 0;i < n;i++)to[b[f[i]&0xffff]++] = f[i];
int[] d = f; f = to;to = d;
}
{
int[] b = new int[65537];
for(int i = 0;i < n;i++)b[1+(f[i]>>>16)]++;
for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
for(int i = 0;i < n;i++)to[b[f[i]>>>16]++] = f[i];
int[] d = f; f = to;to = d;
}
return f;
}
}
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 | ["2 2 3 3\n+-+", "4 1 5 1\n-"] | 1 second | ["7", "999999228"] | NoteIn the first example:$$$(\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i})$$$ = $$$2^{2} 3^{0} - 2^{1} 3^{1} + 2^{0} 3^{2}$$$ = 7In the second example:$$$(\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i}) = -1^{4} 5^{0} - 1^{3} 5^{1} - 1^{2} 5^{2} - 1^{1} 5^{3} - 1^{0} 5^{4} = -781 \equiv 999999228 \pmod{10^{9} + 9}$$$. | Java 8 | standard input | [
"number theory",
"math",
"matrices"
] | 607e670403a40e4fddf389caba79607e | The first line contains four integers $$$n, a, b$$$ and $$$k$$$ $$$(1 \leq n \leq 10^{9}, 1 \leq a, b \leq 10^{9}, 1 \leq k \leq 10^{5})$$$. The second line contains a sequence of length $$$k$$$ consisting of characters '+' and '-'. If the $$$i$$$-th character (0-indexed) is '+', then $$$s_{i} = 1$$$, otherwise $$$s_{i} = -1$$$. Note that only the first $$$k$$$ members of the sequence are given, the rest can be obtained using the periodicity property. | 1,800 | Output a single integer — value of given expression modulo $$$10^{9} + 9$$$. | standard output | |
PASSED | df77565a7b076c0466fbc079eff926bf | train_000.jsonl | 1523973900 | You are given two integers $$$a$$$ and $$$b$$$. Moreover, you are given a sequence $$$s_0, s_1, \dots, s_{n}$$$. All values in $$$s$$$ are integers $$$1$$$ or $$$-1$$$. It's known that sequence is $$$k$$$-periodic and $$$k$$$ divides $$$n+1$$$. In other words, for each $$$k \leq i \leq n$$$ it's satisfied that $$$s_{i} = s_{i - k}$$$.Find out the non-negative remainder of division of $$$\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i}$$$ by $$$10^{9} + 9$$$.Note that the modulo is unusual! | 256 megabytes | /*
[ ( ^ _ ^ ) ]
*/
import java.io.*;
import java.util.*;
public class test {
int INF = (int)1e9;
long MOD = 1000000009;
long pow(long a, long n) {
if (n == 0) {
return 1;
}
long rs = 1;
while (n > 0) {
if (n % 2 == 1) {
rs *= a;
}
rs %= MOD;
n >>= 1;
a *= a;
a %= MOD;
}
return rs;
}
void solve(InputReader in, PrintWriter out) throws IOException {
long n = in.nextInt();
long a = in.nextInt()%MOD;
long b = in.nextInt()%MOD;
long k = in.nextInt();
char[] s = in.next().toCharArray();
long tot = 0;
long xx = 0;
for(int i=0; i<k; i++) {
tot += (s[i]=='+'?1:-1) * (pow(a, n-i) * pow(b, i) % MOD);
//xx += (s[i]=='+'?1:-1) * (pow(a, n-i) * pow(b, i) % MOD);
tot = (tot%MOD + MOD)%MOD;
}
long t = n+1;
long r = pow(b * pow(a, MOD-2) % MOD, k);
if(r==1) {
r = t/k;
tot *= r;
tot = (tot%MOD + MOD)%MOD;
out.println(tot);
return;
}
//show("xx", xx * (pow(r, t/k)-1)/(r-1));
long num = (pow(r, t/k)-1)*pow(r-1, MOD-2)%MOD;
num *= tot;
num = (num%MOD + MOD)%MOD;
out.println(num);
}
public static void main(String[] args) throws IOException {
if(args.length>0 && args[0].equalsIgnoreCase("d")) {
DEBUG_FLAG = true;
}
InputReader in = new InputReader();
PrintWriter out = new PrintWriter(System.out);
int t = 1;//in.nextInt();
long start = System.nanoTime();
while(t-->0) {
new test().solve(in, out);
}
long end = System.nanoTime();
debug("\nTime: " + (end-start)/1e6 + " \n\n");
out.close();
}
class Pair implements Comparable<Pair> {
long f, s;
Pair(long f, long s) {
this.f=f;
this.s=s;
}
public int hashCode() {
int hf = (int) (f ^ (f >>> 32));
int hs = (int) (s ^ (s >>> 32));
return 31 * hf + hs;
}
public boolean equals(Object o) {
Pair other = (Pair) o;
return s == other.s && f == other.f;
}
public int compareTo(Pair p) {
return Long.compare(this.s, p.s);
}
public String toString() {
return "(" + f + ", " + s + ")";
}
}
static boolean DEBUG_FLAG = false;
static void debug(String s) {
if(DEBUG_FLAG) System.out.print(s);
}
public static void show(Object... o) {
System.out.println(Arrays.deepToString(o));
}
static class InputReader {
static BufferedReader br;
static StringTokenizer st;
public InputReader() {
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());
}
}
} | Java | ["2 2 3 3\n+-+", "4 1 5 1\n-"] | 1 second | ["7", "999999228"] | NoteIn the first example:$$$(\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i})$$$ = $$$2^{2} 3^{0} - 2^{1} 3^{1} + 2^{0} 3^{2}$$$ = 7In the second example:$$$(\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i}) = -1^{4} 5^{0} - 1^{3} 5^{1} - 1^{2} 5^{2} - 1^{1} 5^{3} - 1^{0} 5^{4} = -781 \equiv 999999228 \pmod{10^{9} + 9}$$$. | Java 8 | standard input | [
"number theory",
"math",
"matrices"
] | 607e670403a40e4fddf389caba79607e | The first line contains four integers $$$n, a, b$$$ and $$$k$$$ $$$(1 \leq n \leq 10^{9}, 1 \leq a, b \leq 10^{9}, 1 \leq k \leq 10^{5})$$$. The second line contains a sequence of length $$$k$$$ consisting of characters '+' and '-'. If the $$$i$$$-th character (0-indexed) is '+', then $$$s_{i} = 1$$$, otherwise $$$s_{i} = -1$$$. Note that only the first $$$k$$$ members of the sequence are given, the rest can be obtained using the periodicity property. | 1,800 | Output a single integer — value of given expression modulo $$$10^{9} + 9$$$. | standard output | |
PASSED | 379c79b26f32143fb0fabad5acd22b96 | train_000.jsonl | 1523973900 | You are given two integers $$$a$$$ and $$$b$$$. Moreover, you are given a sequence $$$s_0, s_1, \dots, s_{n}$$$. All values in $$$s$$$ are integers $$$1$$$ or $$$-1$$$. It's known that sequence is $$$k$$$-periodic and $$$k$$$ divides $$$n+1$$$. In other words, for each $$$k \leq i \leq n$$$ it's satisfied that $$$s_{i} = s_{i - k}$$$.Find out the non-negative remainder of division of $$$\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i}$$$ by $$$10^{9} + 9$$$.Note that the modulo is unusual! | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
/**
* @author Don Li
*/
public class AlternatingSum {
int MOD = (int) 1e9 + 9;
void solve() {
int n = in.nextInt(), a = in.nextInt(), b = in.nextInt(), k = in.nextInt();
char[] s = in.nextToken().toCharArray();
long mul = 0;
for (int i = 0; i < k; i++) {
long v = mpow(a, n - i) * mpow(b, i) % MOD;
if (s[i] == '+') mul = (mul + v) % MOD;
else mul = (mul - v + MOD) % MOD;
}
int m = (n + 1) / k;
long q = mpow(b * inverse(a) % MOD, k);
long sum = q == 1 ? m : (mpow(q, m) - 1 + MOD) % MOD * inverse((q - 1 + MOD) % MOD) % MOD;
long ans = sum * mul % MOD;
out.println(ans);
}
long inverse(long a) {
return mpow(a, MOD - 2);
}
long mpow(long a, long n) {
long res = 1;
while (n > 0) {
if ((n & 1) > 0) res = res * a % MOD;
a = a * a % MOD;
n >>= 1;
}
return res;
}
public static void main(String[] args) {
in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(System.out);
new AlternatingSum().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 | ["2 2 3 3\n+-+", "4 1 5 1\n-"] | 1 second | ["7", "999999228"] | NoteIn the first example:$$$(\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i})$$$ = $$$2^{2} 3^{0} - 2^{1} 3^{1} + 2^{0} 3^{2}$$$ = 7In the second example:$$$(\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i}) = -1^{4} 5^{0} - 1^{3} 5^{1} - 1^{2} 5^{2} - 1^{1} 5^{3} - 1^{0} 5^{4} = -781 \equiv 999999228 \pmod{10^{9} + 9}$$$. | Java 8 | standard input | [
"number theory",
"math",
"matrices"
] | 607e670403a40e4fddf389caba79607e | The first line contains four integers $$$n, a, b$$$ and $$$k$$$ $$$(1 \leq n \leq 10^{9}, 1 \leq a, b \leq 10^{9}, 1 \leq k \leq 10^{5})$$$. The second line contains a sequence of length $$$k$$$ consisting of characters '+' and '-'. If the $$$i$$$-th character (0-indexed) is '+', then $$$s_{i} = 1$$$, otherwise $$$s_{i} = -1$$$. Note that only the first $$$k$$$ members of the sequence are given, the rest can be obtained using the periodicity property. | 1,800 | Output a single integer — value of given expression modulo $$$10^{9} + 9$$$. | standard output | |
PASSED | 290ee108c3ba813ef1d40f0c222dca13 | train_000.jsonl | 1523973900 | You are given two integers $$$a$$$ and $$$b$$$. Moreover, you are given a sequence $$$s_0, s_1, \dots, s_{n}$$$. All values in $$$s$$$ are integers $$$1$$$ or $$$-1$$$. It's known that sequence is $$$k$$$-periodic and $$$k$$$ divides $$$n+1$$$. In other words, for each $$$k \leq i \leq n$$$ it's satisfied that $$$s_{i} = s_{i - k}$$$.Find out the non-negative remainder of division of $$$\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i}$$$ by $$$10^{9} + 9$$$.Note that the modulo is unusual! | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Darshandarji
*/
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);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public static final int MODULO = (int) (1e9 + 9);
public static long powermod(long a, long b) {
long res = 1;
while (b > 0) {
if (b % 2 != 0) {
res = (res * a) % MODULO;
}
b = b >> 1;
a = (a * a) % MODULO;
}
return res;
}
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n, a, b, k;
n = in.nextInt();
a = in.nextInt();
b = in.nextInt();
k = in.nextInt();
int[] s = new int[k];
char[] a1 = in.next().toCharArray();
for (int i = 0; i < k; i++) {
s[i] = a1[i] == '+' ? 1 : -1;
}
long ans = 0;
for (int i = 0; i < k; i++) {
ans += s[i % k] * powermod(a, n - i) * powermod(b, i) * 1L;
ans += MODULO;
ans %= MODULO;
}
if (ans < 0)
ans += MODULO;
ans %= MODULO;
long tp = ans;
long req = (n + 1) / k;
if (req == 1)
out.println(ans);
else {
long q = b * powermod(a, MODULO - 2) % MODULO;
q = powermod(q, k);
if (q == 1)
ans = tp * req % MODULO;
else
ans = (tp * (powermod(q, req) - 1) % MODULO * powermod(q - 1, MODULO - 2) % MODULO + MODULO) % MODULO;
out.println(ans);
}
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["2 2 3 3\n+-+", "4 1 5 1\n-"] | 1 second | ["7", "999999228"] | NoteIn the first example:$$$(\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i})$$$ = $$$2^{2} 3^{0} - 2^{1} 3^{1} + 2^{0} 3^{2}$$$ = 7In the second example:$$$(\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i}) = -1^{4} 5^{0} - 1^{3} 5^{1} - 1^{2} 5^{2} - 1^{1} 5^{3} - 1^{0} 5^{4} = -781 \equiv 999999228 \pmod{10^{9} + 9}$$$. | Java 8 | standard input | [
"number theory",
"math",
"matrices"
] | 607e670403a40e4fddf389caba79607e | The first line contains four integers $$$n, a, b$$$ and $$$k$$$ $$$(1 \leq n \leq 10^{9}, 1 \leq a, b \leq 10^{9}, 1 \leq k \leq 10^{5})$$$. The second line contains a sequence of length $$$k$$$ consisting of characters '+' and '-'. If the $$$i$$$-th character (0-indexed) is '+', then $$$s_{i} = 1$$$, otherwise $$$s_{i} = -1$$$. Note that only the first $$$k$$$ members of the sequence are given, the rest can be obtained using the periodicity property. | 1,800 | Output a single integer — value of given expression modulo $$$10^{9} + 9$$$. | standard output | |
PASSED | 7df6319a1d5f130586da5bd46ec459cd | train_000.jsonl | 1523973900 | You are given two integers $$$a$$$ and $$$b$$$. Moreover, you are given a sequence $$$s_0, s_1, \dots, s_{n}$$$. All values in $$$s$$$ are integers $$$1$$$ or $$$-1$$$. It's known that sequence is $$$k$$$-periodic and $$$k$$$ divides $$$n+1$$$. In other words, for each $$$k \leq i \leq n$$$ it's satisfied that $$$s_{i} = s_{i - k}$$$.Find out the non-negative remainder of division of $$$\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i}$$$ by $$$10^{9} + 9$$$.Note that the modulo is unusual! | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
import static java.lang.Math.min ; import static java.lang.Math.max ;
import static java.lang.Math.abs ; import static java.lang.Math.log ;
import static java.lang.Math.pow ; import static java.lang.Math.sqrt ;
/**
* Actual solution is at the top
* This was not generated using chelper.
* @author Satvik Choudhary (satvik007)
*/
public class Main {
public static void main(String[] args) throws IOException{
InputStream inputStream = System.in;
OutputStreamWriter outputStream = new OutputStreamWriter(System.out);
InputReader in = new InputReader(inputStream);
BufferedWriter out = new BufferedWriter(outputStream);
/*/
//*
// Use for fileio
FileInputStream inputStream = new FileInputStream (new File("in.txt"));
InputReader in = new InputReader(inputStream);
FileWriter fileWriter = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(fileWriter);
//*/
satvik solver = new satvik();
solver.solve(1, in, out);
out.close();
}
static class satvik {
final int inf = (int) 1e9;
final long mod = (long)(1e9 + 9);
public void solve(int testNumber, InputReader in, BufferedWriter out) throws IOException {
long n = in.nextLong();
long a = in.nextLong();
long b = in.nextLong();
long k = in.nextLong();
String s = in.nextLine();
long res = 0;
long base = 1;
long a_inv = lpow(a, mod - 2);
long p = b * a_inv % mod;
long q = lpow(b, k) * lpow(a_inv, k) % mod;
long m = (n + 1) / k;
for (int i = 0; i < k; i++) {
if (s.charAt(i) == '+') {
res = (res + base) % mod;
} else {
res = (res - base + mod) % mod;
}
base = (base * p) % mod;
}
res = (res * lpow(a, n)) % mod;
long ans;
if (q == 1) {
ans = res * m % mod;
} else {
ans = (lpow(q, m) - 1 + mod) % mod * lpow((q - 1 + mod) % mod, mod - 2) % mod;
ans = (ans * res) % mod;
}
out.write(Long.toString(ans));
}
long lpow(long a, long p) {
long res = 1;
while (p > 0) {
if ((p & 1) > 0)
res = (res * a) % mod;
a = (a * a) % mod;
p >>= 1;
}
return res;
}
}
static class Util {
static class pair implements Comparable<pair>{
int x ; int y ; int z ;
pair(int _x,int _y,int _z){ x=_x ; y=_y ; z=_z ;}
public int compareTo(pair p){
return (this.x<p.x ? -1 : (this.x>p.x ? 1 : (this.y<p.y ? -1 : (this.y>p.y ? 1 : 0)))) ;
}
}
static public int min(int a[], int left, int right) {
int res = (1 << 30);
for(int i = left; i < right; i++) {
res = Math.min(res, a[i]);
}
return res;
}
static public int min(int a[]) {
return min(a, 0, a.length);
}
static public boolean next_permutation(int[] p) {
for (int a = p.length - 2; a >= 0; --a)
if (p[a] < p[a + 1])
for (int b = p.length - 1;; --b)
if (p[b] > p[a]) {
int t = p[a];
p[a] = p[b];
p[b] = t;
for (++a, b = p.length - 1; a < b; ++a, --b) {
t = p[a];
p[a] = p[b];
p[b] = t;
}
return true;
}
return false;
}
static public int max(int a[], int left, int right) {
int res = -(1 << 30);
for(int i = left; i < right; i++) {
res = Math.max(res, a[i]);
}
return res;
}
static public int max(int a[]) {
return max(a, 0, a.length);
}
static public int upper_bound(int[] a, int left, int right, int value) {
int low = left;
int high = right;
while (low < high) {
int mid = (low + high) / 2;
if (a[mid] <= value) {
low = mid + 1;
} else {
high = mid;
}
}
if (low == right) {
return -1;
}
return low;
}
static public int lower_bound(int[] a, int left, int right, int value) {
int low = left;
int high = right;
while (low < high) {
int mid = (low + high) / 2;
if (a[mid] < value) {
low = mid + 1;
} else {
high = mid;
}
}
if (low == right) {
return -1;
}
return low;
}
static public int upper_bound_rev(int[] a, int left, int right, int value) {
while (left < right) {
int mid = (left + right) >> 1;
if (a[mid] < value) {
left = mid + 1;
} else {
right = mid;
}
}
if (left < 0) {
left *= -1;
}
return --left;
}
static public int lower_bound_rev(int[] a, int left, int right, int value) {
while (left < right) {
int mid = (left + right) >> 1;
if (a[mid] <= value) {
left = mid + 1;
} else {
right = mid;
}
}
if (left < 0) {
left *= -1;
}
return --left;
}
}
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) {
return -1;
//throw new InputMismatchException();
}
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
return -1;
//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 double nextDouble() {
return Double.parseDouble(readString());
}
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 int[][] next2dArray(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] = nextInt();
}
}
return a;
}
public String readString() {
int c = snext();
if(c == -1) {
return null;
}
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();
if(c == -1) {
return null;
}
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
} | Java | ["2 2 3 3\n+-+", "4 1 5 1\n-"] | 1 second | ["7", "999999228"] | NoteIn the first example:$$$(\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i})$$$ = $$$2^{2} 3^{0} - 2^{1} 3^{1} + 2^{0} 3^{2}$$$ = 7In the second example:$$$(\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i}) = -1^{4} 5^{0} - 1^{3} 5^{1} - 1^{2} 5^{2} - 1^{1} 5^{3} - 1^{0} 5^{4} = -781 \equiv 999999228 \pmod{10^{9} + 9}$$$. | Java 8 | standard input | [
"number theory",
"math",
"matrices"
] | 607e670403a40e4fddf389caba79607e | The first line contains four integers $$$n, a, b$$$ and $$$k$$$ $$$(1 \leq n \leq 10^{9}, 1 \leq a, b \leq 10^{9}, 1 \leq k \leq 10^{5})$$$. The second line contains a sequence of length $$$k$$$ consisting of characters '+' and '-'. If the $$$i$$$-th character (0-indexed) is '+', then $$$s_{i} = 1$$$, otherwise $$$s_{i} = -1$$$. Note that only the first $$$k$$$ members of the sequence are given, the rest can be obtained using the periodicity property. | 1,800 | Output a single integer — value of given expression modulo $$$10^{9} + 9$$$. | standard output | |
PASSED | 33d33ab312e0b2c4e1bc227acd5b12a0 | train_000.jsonl | 1523973900 | You are given two integers $$$a$$$ and $$$b$$$. Moreover, you are given a sequence $$$s_0, s_1, \dots, s_{n}$$$. All values in $$$s$$$ are integers $$$1$$$ or $$$-1$$$. It's known that sequence is $$$k$$$-periodic and $$$k$$$ divides $$$n+1$$$. In other words, for each $$$k \leq i \leq n$$$ it's satisfied that $$$s_{i} = s_{i - k}$$$.Find out the non-negative remainder of division of $$$\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i}$$$ by $$$10^{9} + 9$$$.Note that the modulo is unusual! | 256 megabytes | import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.*;
public class C {
/*
16 2 3 3
+-+
4 5 3 1
+
*/
static long N, X, Y;
static int K;
static int ar[];
static long mod = 1000000009;
public static void main(String args[]) {
JS in = new JS();
PrintWriter out = new PrintWriter(System.out);
//System.out.println(4%1);
N = in.nextLong();
X = in.nextLong();
Y = in.nextLong();
K = in.nextInt();
ar = new int[K];
char []c = in.next().toCharArray();
for(int i = 0; i < c.length; i++) {
if(c[i] == '+')ar[i] = 1;
else ar[i] = -1;
}
if(N < K) { //Hardcode it
long res = 0;
for(int i = 0; i <= N; i++) {
int sign = ar[(int)(i%K)];
long term = pow(X,N-i)*pow(Y,i);
res += (sign*term);
res%=mod;
}
while(res < 0) res += mod;
System.out.println(res);
}
else {
long res = 0;
long inv = modInv(pow(X,K));
long M = (pow(Y,K)*inv)%mod;
long eMat[][] = { {M, M, 0},
{0, 0, 1},
{0, 1, 0}
};
//System.out.println("Emat:");
//print(eMat);
long r1[][] = matrixExpo(eMat,((N+1)/K)-1);
for(int i = 0; i < K; i++) {
long firstTerm = (pow(X,N-i)*pow(Y,i))%mod;
long mMat[][] = {{firstTerm, firstTerm, 0}};
long exp = (N+1)/K;
long r2[][] = matrixMultiply(mMat, r1);
//print(r2);
if(ar[i] == -1) {
res -= (r2[0][1]+r2[0][2]);
res %= mod;
}
else {
res += (r2[0][1]+r2[0][2]);
res %= mod;
}
}
while(res<0)res+=mod;
System.out.println(res);
}
out.close();
}
static void print(long a[][]) {
for(int i = 0; i < a.length; i++) {
for(int j =0; j < a[i].length; j++) {
System.out.print(a[i][j]+" ");
}
System.out.println();
}
System.out.println();
}
static long modInv(long a) {
return pow(a, mod-2);
}
//@
static long[][] matrixMultiply(long[][] mat1, long[][] mat2) {
long[][] res = new long[mat1.length][mat2[0].length];
for(int i = 0; i < res.length; ++i) {
for(int j = 0; j < res[i].length; ++j) {
for(int k = 0; k < mat2.length; ++k) {
res[i][j] += mat1[i][k] * mat2[k][j];
res[i][j]%=mod;
}
}
}
return res;
}
static long[][] matrixExpo(long[][] mat, long expo) {
if(expo == 0)
return identity;
if(expo == 1)
return mat;
long[][] ret = matrixExpo(mat, expo/2);
ret = matrixMultiply(ret, ret);
if((expo % 2) == 1)
ret = matrixMultiply(ret, mat);
return ret;
}
static long identity[][] = identity(4);
static long[][] identity(int size) {
long[][] mat = new long[size][size];
for(int i = 0; i < size; ++i)
mat[i][i] = 1;
return mat;
}
static long pow(long base, long exp) {
if(exp < 2) return exp==0?1:base;
if((exp&1) == 0) {
long res = pow(base, exp/2);
res%=mod;
return (res*res)%mod;
}
else {
return (base*pow(base, exp-1))%mod;
}
}
static class JS{
public int BS = 1<<16;
public char NC = (char)0;
byte[] buf = new byte[BS];
int bId = 0, size = 0;
char c = NC;
double num = 1;
BufferedInputStream in;
public JS() {
in = new BufferedInputStream(System.in, BS);
}
public JS(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 int nextInt() {
return (int)nextLong();
}
public long nextLong() {
num=1;
boolean neg = false;
if(c==NC)c=nextChar();
for(;(c<'0' || c>'9'); c = nextChar()) {
if(c=='-')neg=true;
}
long res = 0;
for(; c>='0' && c <='9'; c=nextChar()) {
res = (res<<3)+(res<<1)+c-'0';
num*=10;
}
return neg?-res:res;
}
public double nextDouble() {
double cur = nextLong();
return c!='.' ? cur:cur+nextLong()/num;
}
public String next() {
StringBuilder res = new StringBuilder();
while(c<=32)c=nextChar();
while(c>32) {
res.append(c);
c=nextChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while(c<=32)c=nextChar();
while(c!='\n') {
res.append(c);
c=nextChar();
}
return res.toString();
}
public boolean hasNext() {
if(c>32)return true;
while(true) {
c=nextChar();
if(c==NC)return false;
else if(c>32)return true;
}
}
}
}
| Java | ["2 2 3 3\n+-+", "4 1 5 1\n-"] | 1 second | ["7", "999999228"] | NoteIn the first example:$$$(\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i})$$$ = $$$2^{2} 3^{0} - 2^{1} 3^{1} + 2^{0} 3^{2}$$$ = 7In the second example:$$$(\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i}) = -1^{4} 5^{0} - 1^{3} 5^{1} - 1^{2} 5^{2} - 1^{1} 5^{3} - 1^{0} 5^{4} = -781 \equiv 999999228 \pmod{10^{9} + 9}$$$. | Java 8 | standard input | [
"number theory",
"math",
"matrices"
] | 607e670403a40e4fddf389caba79607e | The first line contains four integers $$$n, a, b$$$ and $$$k$$$ $$$(1 \leq n \leq 10^{9}, 1 \leq a, b \leq 10^{9}, 1 \leq k \leq 10^{5})$$$. The second line contains a sequence of length $$$k$$$ consisting of characters '+' and '-'. If the $$$i$$$-th character (0-indexed) is '+', then $$$s_{i} = 1$$$, otherwise $$$s_{i} = -1$$$. Note that only the first $$$k$$$ members of the sequence are given, the rest can be obtained using the periodicity property. | 1,800 | Output a single integer — value of given expression modulo $$$10^{9} + 9$$$. | standard output | |
PASSED | a78d2321f15d22a23a648ecd79532624 | train_000.jsonl | 1462633500 | Bear Limak has n colored balls, arranged in one long row. Balls are numbered 1 through n, from left to right. There are n possible colors, also numbered 1 through n. The i-th ball has color ti.For a fixed interval (set of consecutive elements) of balls we can define a dominant color. It's a color occurring the biggest number of times in the interval. In case of a tie between some colors, the one with the smallest number (index) is chosen as dominant.There are non-empty intervals in total. For each color, your task is to count the number of intervals in which this color is dominant. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.IOException;
import java.io.Reader;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Denis Nedelyaev
*/
public class Main {
public static void main(String[] args) throws Exception {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA(in, out);
solver.solve(1);
out.close();
}
static class TaskA {
private final FastScanner in;
private final PrintWriter out;
public TaskA(FastScanner in, PrintWriter out) {
this.in = in;
this.out = out;
}
public void solve(int testNumber) throws IOException {
int n = in.nextInt();
int[] c = in.nextInts(n);
int[] ans = new int[n];
for (int i = 0; i < n; i++) {
int[] counts = new int[n];
int maxColor = n;
int maxColorCount = -1;
for (int j = i; j >= 0; j--) {
int color = c[j] - 1;
int count = ++counts[color];
if (count > maxColorCount || count == maxColorCount && color < maxColor) {
maxColorCount = count;
maxColor = color;
}
ans[maxColor]++;
}
}
for (int x : ans) {
out.print(x + " ");
}
out.println();
}
}
static class FastScanner {
private final BufferedReader br;
private String line;
private int pos;
public FastScanner(String s) throws IOException {
this(new StringReader(s));
}
public FastScanner(InputStream is) throws IOException {
this(new InputStreamReader(is, "UTF-8"));
}
public FastScanner(Reader reader) throws IOException {
this(new BufferedReader(reader));
}
public FastScanner(BufferedReader reader) throws IOException {
br = reader;
line = br.readLine();
pos = 0;
}
public String next() throws IOException {
if (!skipWhitespace()) {
return null;
}
int start = pos;
while (pos < line.length()) {
char c = line.charAt(pos);
if (c == ' ' || c == '\t') {
break;
}
pos++;
}
return line.substring(start, pos);
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public int[] nextInts(int n) throws IOException {
int[] res = new int[n];
for (int i = 0; i < n; i++) {
res[i] = nextInt();
}
return res;
}
private boolean skipWhitespace() throws IOException {
while (line != null) {
while (pos < line.length()) {
char c = line.charAt(pos);
if (c != ' ' && c != '\t') {
return true;
}
pos++;
}
line = br.readLine();
pos = 0;
}
return false;
}
}
}
| Java | ["4\n1 2 1 2", "3\n1 1 1"] | 2 seconds | ["7 3 0 0", "6 0 0"] | NoteIn the first sample, color 2 is dominant in three intervals: An interval [2, 2] contains one ball. This ball's color is 2 so it's clearly a dominant color. An interval [4, 4] contains one ball, with color 2 again. An interval [2, 4] contains two balls of color 2 and one ball of color 1. There are 7 more intervals and color 1 is dominant in all of them. | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | f292c099e4eac9259a5bc9e42ff6d1b5 | The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — the number of balls. The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ n) where ti is the color of the i-th ball. | 1,500 | Print n integers. The i-th of them should be equal to the number of intervals where i is a dominant color. | standard output | |
PASSED | 83deacec302d8fbddf0263a5c0e7b192 | train_000.jsonl | 1462633500 | Bear Limak has n colored balls, arranged in one long row. Balls are numbered 1 through n, from left to right. There are n possible colors, also numbered 1 through n. The i-th ball has color ti.For a fixed interval (set of consecutive elements) of balls we can define a dominant color. It's a color occurring the biggest number of times in the interval. In case of a tie between some colors, the one with the smallest number (index) is chosen as dominant.There are non-empty intervals in total. For each color, your task is to count the number of intervals in which this color is dominant. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Rene
*/
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);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int[] t = new int[n];
for (int i = 0; i < n; i++) t[i] = in.nextInt() - 1;
int[] answer = new int[n];
HeapElement[] colors = new HeapElement[n];
for (int i = 0; i < n; i++) colors[i] = new HeapElement(i, 0);
for (int start = 0; start < n; start++) {
MinHeap heap = new MinHeap(n + 1);
for (HeapElement he : colors) {
he.heapIndex = -1;
he.count = 0;
heap.update(he);
}
for (int i = start; i < n; i++) {
colors[t[i]].count++;
heap.update(colors[t[i]]);
HeapElement minElt = heap.getMin();
answer[minElt.color]++;
// System.out.printf("[%d, %d] pick %d\n", start, i, z.color);
}
}
for (int i = 0; i < n; i++) out.printf("%d ", answer[i]);
out.println();
}
public class HeapElement implements Comparable<HeapElement> {
int heapIndex;
int color;
int count;
public HeapElement(int c, int count) {
this.color = c;
this.count = count;
heapIndex = -1;
}
public int compareTo(HeapElement o) {
if (count != o.count) return o.count - count;
return color - o.color;
}
}
public class MinHeap {
HeapElement[] heap;
int size;
public MinHeap(int cap) {
heap = new HeapElement[cap + 2];
size = 0;
}
public HeapElement getMin() {
return size == 0 ? null : heap[1];
}
public void update(HeapElement s) {
if (s.heapIndex == -1) {
size++;
s.heapIndex = size;
heap[size] = s;
}
pushUp(s.heapIndex);
pushDown(s.heapIndex);
}
private void pushUp(int index) {
HeapElement swap;
while (index != 1 && heap[index].compareTo(heap[index / 2]) < 0) {
swap = heap[index];
heap[index] = heap[index / 2];
heap[index].heapIndex = index;
heap[index / 2] = swap;
heap[index / 2].heapIndex = index / 2;
index /= 2;
}
}
private void pushDown(int index) {
HeapElement bestChild;
int nextIndex;
while (2 * index <= size) {
// determine smallest child
bestChild = heap[2 * index];
if (2 * index + 1 <= size && heap[2 * index + 1].compareTo(bestChild) < 0)
bestChild = heap[2 * index + 1];
if (heap[index].compareTo(bestChild) < 0) return;
nextIndex = bestChild.heapIndex;
heap[nextIndex] = heap[index];
heap[nextIndex].heapIndex = nextIndex;
heap[index] = bestChild;
heap[index].heapIndex = index;
index = nextIndex;
}
}
public String toString() {
String s = "";
for (int i = 1; i <= size; i++)
s += heap[i] + "\n";
return s;
}
}
}
static class InputReader {
public InputStream stream;
private int current;
private int size;
private byte[] buffer = new byte[10000];
public InputReader(InputStream stream) {
this.stream = stream;
current = 0;
size = 0;
}
int read() {
int result;
try {
if (current >= size) {
current = 0;
size = stream.read(buffer);
if (size < 0) return -1;
}
} catch (IOException e) {
throw new RuntimeException();
}
return buffer[current++];
}
public int nextInt() {
int sign = 1;
int result = 0;
int c = readNextValid();
if (c == '-') {
sign = -1;
c = read();
}
do {
if (c < '0' || c > '9') throw new RuntimeException();
result = 10 * result + c - '0';
c = read();
} while (!isEmpty(c));
result *= sign;
return result;
}
private int readNextValid() {
int result;
do {
result = read();
} while (isEmpty(result));
return result;
}
private boolean isEmpty(int c) {
return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == -1;
}
}
}
| Java | ["4\n1 2 1 2", "3\n1 1 1"] | 2 seconds | ["7 3 0 0", "6 0 0"] | NoteIn the first sample, color 2 is dominant in three intervals: An interval [2, 2] contains one ball. This ball's color is 2 so it's clearly a dominant color. An interval [4, 4] contains one ball, with color 2 again. An interval [2, 4] contains two balls of color 2 and one ball of color 1. There are 7 more intervals and color 1 is dominant in all of them. | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | f292c099e4eac9259a5bc9e42ff6d1b5 | The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — the number of balls. The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ n) where ti is the color of the i-th ball. | 1,500 | Print n integers. The i-th of them should be equal to the number of intervals where i is a dominant color. | standard output | |
PASSED | 4cd1d2c20e33c132835216d9bd26d180 | train_000.jsonl | 1462633500 | Bear Limak has n colored balls, arranged in one long row. Balls are numbered 1 through n, from left to right. There are n possible colors, also numbered 1 through n. The i-th ball has color ti.For a fixed interval (set of consecutive elements) of balls we can define a dominant color. It's a color occurring the biggest number of times in the interval. In case of a tie between some colors, the one with the smallest number (index) is chosen as dominant.There are non-empty intervals in total. For each color, your task is to count the number of intervals in which this color is dominant. | 256 megabytes |
import java.util.*;
import java.io.*;
public class CF_A {
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st;
static void newST() throws IOException {st = new StringTokenizer(in.readLine());}
static int stInt() {return Integer.parseInt(st.nextToken());}
static long stLong() {return Long.parseLong(st.nextToken());}
static String stStr() {return st.nextToken();}
static int[] getInts(int n) throws IOException {newST(); int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = stInt(); return arr;}
static int readInt() throws IOException {return Integer.parseInt(in.readLine());}
static long readLong() throws IOException {return Long.parseLong(in.readLine());}
static void println(Object o) {System.out.println(o);}
static void println() {System.out.println();}
static void print(Object o) {System.out.print(o);}
static String arr2s(int[] a) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < a.length-1; i++) {
sb.append(a[i] + " ");
}
sb.append(a[a.length-1] + "\n");
return sb.toString();
}
public static void main(String[] args) throws Exception {
int n = readInt();
int[] list = new int[n];
int[] ans = new int[n];
newST();
for (int i = 0; i < n; i++) list[i] = stInt()-1;
for (int i = 0; i < n; i++) {
int[] nums = new int[n];
int win = 0;
int max = 0;
for (int j = i; j < n; j++) {
int c = list[j];
nums[c]++;
if (nums[c] > max) {
max = nums[c];
win = c;
}
if (nums[c] == max) {
win = Math.min(win, c);
}
ans[win]++;
}
}
System.out.print(arr2s(ans));
}
}
| Java | ["4\n1 2 1 2", "3\n1 1 1"] | 2 seconds | ["7 3 0 0", "6 0 0"] | NoteIn the first sample, color 2 is dominant in three intervals: An interval [2, 2] contains one ball. This ball's color is 2 so it's clearly a dominant color. An interval [4, 4] contains one ball, with color 2 again. An interval [2, 4] contains two balls of color 2 and one ball of color 1. There are 7 more intervals and color 1 is dominant in all of them. | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | f292c099e4eac9259a5bc9e42ff6d1b5 | The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — the number of balls. The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ n) where ti is the color of the i-th ball. | 1,500 | Print n integers. The i-th of them should be equal to the number of intervals where i is a dominant color. | standard output | |
PASSED | 0e48a0daa5051c462e2280f5d55fa582 | train_000.jsonl | 1462633500 | Bear Limak has n colored balls, arranged in one long row. Balls are numbered 1 through n, from left to right. There are n possible colors, also numbered 1 through n. The i-th ball has color ti.For a fixed interval (set of consecutive elements) of balls we can define a dominant color. It's a color occurring the biggest number of times in the interval. In case of a tie between some colors, the one with the smallest number (index) is chosen as dominant.There are non-empty intervals in total. For each color, your task is to count the number of intervals in which this color is dominant. | 256 megabytes | import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.io.IOException;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author ilyakor
*/
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);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; ++i) {
a[i] = in.nextInt() - 1;
}
int[] res = new int[n];
int[] cur = new int[n];
for (int start = 0; start < n; ++start) {
Arrays.fill(cur, 0);
int cm = 0;
for (int i = start; i < n; ++i) {
++cur[a[i]];
if (cur[a[i]] > cur[cm] || (cur[a[i]] == cur[cm] && a[i] < cm))
cm = a[i];
++res[cm];
}
}
for (int i = 0; i < n; ++i)
out.print(res[i] + " ");
out.printLine();
}
}
class InputReader {
private InputStream stream;
private byte[] buffer = new byte[10000];
private int cur;
private int count;
public InputReader(InputStream stream) {
this.stream = stream;
}
public static boolean isSpace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int read() {
if (count == -1) {
throw new InputMismatchException();
}
try {
if (cur >= count) {
cur = 0;
count = stream.read(buffer);
if (count <= 0)
return -1;
}
} catch (IOException e) {
throw new InputMismatchException();
}
return buffer[cur++];
}
public int readSkipSpace() {
int c;
do {
c = read();
} while (isSpace(c));
return c;
}
public int nextInt() {
int sgn = 1;
int c = readSkipSpace();
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res = res * 10 + c - '0';
c = read();
} while (!isSpace(c));
res *= sgn;
return res;
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
| Java | ["4\n1 2 1 2", "3\n1 1 1"] | 2 seconds | ["7 3 0 0", "6 0 0"] | NoteIn the first sample, color 2 is dominant in three intervals: An interval [2, 2] contains one ball. This ball's color is 2 so it's clearly a dominant color. An interval [4, 4] contains one ball, with color 2 again. An interval [2, 4] contains two balls of color 2 and one ball of color 1. There are 7 more intervals and color 1 is dominant in all of them. | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | f292c099e4eac9259a5bc9e42ff6d1b5 | The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — the number of balls. The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ n) where ti is the color of the i-th ball. | 1,500 | Print n integers. The i-th of them should be equal to the number of intervals where i is a dominant color. | standard output | |
PASSED | 6d5f46a2542afd1c81cb97a6c5cf9785 | train_000.jsonl | 1462633500 | Bear Limak has n colored balls, arranged in one long row. Balls are numbered 1 through n, from left to right. There are n possible colors, also numbered 1 through n. The i-th ball has color ti.For a fixed interval (set of consecutive elements) of balls we can define a dominant color. It's a color occurring the biggest number of times in the interval. In case of a tie between some colors, the one with the smallest number (index) is chosen as dominant.There are non-empty intervals in total. For each color, your task is to count the number of intervals in which this color is dominant. | 256 megabytes | import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Random;
import java.util.Scanner;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
public class SuffixArray {
private static InputStream stream;
private static byte[] buf = new byte[1024];
private static int curChar;
private static int numChars;
private static SpaceCharFilter filter;
private static PrintWriter pw;
private static long max = Long.MIN_VALUE;
private static int mod = 1000000000 + 7;
private static boolean flag=false;
private static int block;
private static void soln() {
int n=nextInt();
int[] arr=new int[n];
for(int i=0;i<n;i++)
arr[i]=nextInt();
int[] ans=new int[n+1];
for(int i=0;i<n;i++){
int[] cnt=new int[n+1];
int max=1;
int ind=arr[i];
ans[ind]++;
cnt[ind]++;
for(int j=i+1;j<n;j++){
int x=arr[j];
cnt[x]++;
if(cnt[x]>max){
max=cnt[x];
ind=x;
}
if(cnt[x]==max){
if(x<ind)
ind=x;
}
ans[ind]++;
}
}
for(int i=1;i<=n;i++)
pw.print(ans[i]+" ");
}
public static class Segment {
private int[] tree;
private int size;
private int n;
private class node{
private int a;
private int b;
private int c;
public node(int x,int y,int z){
a=x;
b=y;
c=z;
}
}
public Segment(int n){
//this.base=arr;
int x = (int) (Math.ceil(Math.log(n) / Math.log(2)));
size = 2 * (int) Math.pow(2, x) - 1;
tree=new int[size];
this.n=n;
//build(0,0,n-1);
}
private void build(int id,int l,int r){
//pw.println(1);
if(r==l){
tree[id]=0;
return;
}
int mid=l+(r-l)/2;
//System.out.println(2*id+1+" "+l+" "+mid);
build(2*id+1,l,mid);
//System.out.println(2*id+2+" "+(mid+1)+" "+r);
build(2*id+2,mid+1,r);
tree[id]=tree[2*id+1]+tree[2*id+2];
}
public int query(int l,int r){
return queryUtil(l,r,0,0,n-1);
}
private int queryUtil(int x,int y,int id,int l,int r){
if(l>y || x>r)
return 0;
if(x <= l && r<=y)
return tree[id];
int mid=l+(r-l)/2;
return queryUtil(x,y,2*id+1,l,mid)+queryUtil(x,y,2*id+2,mid+1,r);
}
/*private void cnt(int id,int l,int r,HashSet<Integer> set){
if(tree[id]!=0){
set.add(tree[id]);
return;
}
if(r==l)
return;
int mid=l+(r-l)/2;
cnt(2*id+1,l,mid,set);
cnt(2*id+2,mid+1,r,set);
}*/
public void update(int i,int colour,int id,int l,int r){
if(i<l || i>r)
return;
if(l==r){
tree[id]=colour;
return;
}
int mid=l+(r-l)/2;
//shift(id);
update(i,colour,2*id+1,l,mid);
update(i,colour,2*id+2,mid+1,r);
tree[id]=Math.max(tree[2*id+1],tree[2*id+2]);
}
private void shift(int id){
if(tree[id]!=0){
tree[2*id+1]=tree[2*id+2]=tree[id];
}
tree[id]=0;
}
}
private static long pow(long a, long b, long c) {
if (b == 0)
return 1;
long p = pow(a, b / 2, c);
p = (p * p) % c;
return (b % 2 == 0) ? p : (a * p) % c;
}
private static class Pair implements Comparable<Pair> {
int x;
int y;
int z;
public Pair(int a,int b,int c) {
x=a;y=b;z=c;
}
@Override
public int compareTo(Pair arg0) {
return (this.x!=arg0.x)?(this.x-arg0.x):((this.y!=arg0.y)?(this.y-arg0.y):(this.z-arg0.z));
}
}
private static int gcd(int a1, int a2) {
if (a2 == 0)
return a1;
return gcd(a2, a1 % a2);
}
private static long max(long a, long b) {
if (a > b)
return a;
return b;
}
private static long min(long a, long b) {
if (a < b)
return a;
return b;
}
public static void main(String[] args) throws Exception {
InputReader(System.in);
pw = new PrintWriter(System.out);
soln();
pw.close();
}
public static void InputReader(InputStream stream1) {
stream = stream1;
}
private static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private static boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
private static int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
private static 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;
}
private static 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;
}
private static String nextToken() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private static 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();
}
private static int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
private static long[] nextLongArray(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
private static void pArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
return;
}
private static void pArray(long[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
return;
}
private static boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
private interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
} | Java | ["4\n1 2 1 2", "3\n1 1 1"] | 2 seconds | ["7 3 0 0", "6 0 0"] | NoteIn the first sample, color 2 is dominant in three intervals: An interval [2, 2] contains one ball. This ball's color is 2 so it's clearly a dominant color. An interval [4, 4] contains one ball, with color 2 again. An interval [2, 4] contains two balls of color 2 and one ball of color 1. There are 7 more intervals and color 1 is dominant in all of them. | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | f292c099e4eac9259a5bc9e42ff6d1b5 | The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — the number of balls. The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ n) where ti is the color of the i-th ball. | 1,500 | Print n integers. The i-th of them should be equal to the number of intervals where i is a dominant color. | standard output | |
PASSED | 1f46e2663c55567f23c3ca7017ab4e18 | train_000.jsonl | 1462633500 | Bear Limak has n colored balls, arranged in one long row. Balls are numbered 1 through n, from left to right. There are n possible colors, also numbered 1 through n. The i-th ball has color ti.For a fixed interval (set of consecutive elements) of balls we can define a dominant color. It's a color occurring the biggest number of times in the interval. In case of a tie between some colors, the one with the smallest number (index) is chosen as dominant.There are non-empty intervals in total. For each color, your task is to count the number of intervals in which this color is dominant. | 256 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class Main {
FastScanner in;
PrintWriter out;
static final String FILE = "";
public void solve() {
int n = in.nextInt();
int ms[] = new int[n];
int cnt[] = new int[n];
int ans[] = new int[n];
int as[] = new int[n];
for (int i = 0; i < n; i++)
as[i] = in.nextInt() - 1;
for (int i = 0; i < n; i++) {
Arrays.fill(cnt, 0);
int maxi = 0, v = 0;
for (int z = i; z < n; z++) {
cnt[as[z]]++;
if (cnt[as[z]] > maxi) {
maxi = cnt[as[z]];
v = as[z];
} else if (cnt[as[z]] == maxi) {
if (as[z] < v)
v = as[z];
}
ans[v]++;
}
}
for (int i = 0; i < n; i++)
out.print(ans[i] + " ");
}
public void run() {
if (FILE.equals("")) {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
} else {
try {
in = new FastScanner(new FileInputStream(FILE +
".in"));
out = new PrintWriter(new FileOutputStream(FILE +
".out"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
solve();
out.close();
}
public static void main(String[] args) {
(new Main()).run();
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public String nextLine() {
st = null;
try {
return br.readLine();
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public float nextFloat() {
return Float.parseFloat(next());
}
}
class Pair<A extends Comparable<A>, B extends Comparable<B>>
implements Comparable<Pair<A, B>> {
public A a;
public B b;
public Pair(A a, B b) {
this.a = a;
this.b = b;
}
@Override
public int compareTo(Pair<A, B> o) {
if (o == null || o.getClass() != getClass())
return 1;
int cmp = a.compareTo(o.a);
if (cmp == 0)
return b.compareTo(o.b);
return cmp;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair<?, ?> pair = (Pair<?, ?>) o;
if (a != null ? !a.equals(pair.a) : pair.a != null) return
false;
return !(b != null ? !b.equals(pair.b) : pair.b != null);
}
}
class PairInt extends Pair<Integer, Integer> {
public PairInt(Integer u, Integer v) {
super(u, v);
}
}
class PairLong extends Pair<Long, Long> {
public PairLong(Long u, Long v) {
super(u, v);
}
}
} | Java | ["4\n1 2 1 2", "3\n1 1 1"] | 2 seconds | ["7 3 0 0", "6 0 0"] | NoteIn the first sample, color 2 is dominant in three intervals: An interval [2, 2] contains one ball. This ball's color is 2 so it's clearly a dominant color. An interval [4, 4] contains one ball, with color 2 again. An interval [2, 4] contains two balls of color 2 and one ball of color 1. There are 7 more intervals and color 1 is dominant in all of them. | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | f292c099e4eac9259a5bc9e42ff6d1b5 | The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — the number of balls. The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ n) where ti is the color of the i-th ball. | 1,500 | Print n integers. The i-th of them should be equal to the number of intervals where i is a dominant color. | standard output | |
PASSED | ef1a156c982ab8533e52a7ea88aa3e69 | train_000.jsonl | 1462633500 | Bear Limak has n colored balls, arranged in one long row. Balls are numbered 1 through n, from left to right. There are n possible colors, also numbered 1 through n. The i-th ball has color ti.For a fixed interval (set of consecutive elements) of balls we can define a dominant color. It's a color occurring the biggest number of times in the interval. In case of a tie between some colors, the one with the smallest number (index) is chosen as dominant.There are non-empty intervals in total. For each color, your task is to count the number of intervals in which this color is dominant. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ProblemA4 {
BufferedReader rd;
ProblemA4() throws IOException {
rd = new BufferedReader(new InputStreamReader(System.in));
compute();
}
private void compute() throws IOException {
rd.readLine();
int[] a = intarr();
int n = a.length;
for (int i = 0; i < n; i++) {
a[i]--;
}
int[] c = new int[n];
for(int i=0;i<n;i++) {
int[] d = new int[n];
int best = 0;
int bestSize = 0;
for(int j=i;j<n;j++) {
d[a[j]]++;
if(d[a[j]] > bestSize || (d[a[j]] == bestSize && a[j] < best)) {
best = a[j];
bestSize = d[a[j]];
}
c[best]++;
}
}
StringBuilder buf = new StringBuilder();
for(int x: c) {
if(buf.length() > 0) {
buf.append(' ');
}
buf.append(x);
}
out(buf);
}
private int[] intarr() throws IOException {
return intarr(rd.readLine());
}
private int[] intarr(String s) {
String[] q = split(s);
int n = q.length;
int[] a = new int[n];
for(int i=0;i<n;i++) {
a[i] = Integer.parseInt(q[i]);
}
return a;
}
public String[] split(String s) {
if(s == null) {
return new String[0];
}
int n = s.length();
int start = -1;
int end = 0;
int sp = 0;
boolean lastWhitespace = true;
for(int i=0;i<n;i++) {
char c = s.charAt(i);
if(isWhitespace(c)) {
lastWhitespace = true;
} else {
if(lastWhitespace) {
sp++;
}
if(start == -1) {
start = i;
}
end = i;
lastWhitespace = false;
}
}
if(start == -1) {
return new String[0];
}
String[] res = new String[sp];
int last = start;
int x = 0;
lastWhitespace = true;
for(int i=start;i<=end;i++) {
char c = s.charAt(i);
boolean w = isWhitespace(c);
if(w && !lastWhitespace) {
res[x++] = s.substring(last,i);
} else if(!w && lastWhitespace) {
last = i;
}
lastWhitespace = w;
}
res[x] = s.substring(last,end+1);
return res;
}
private boolean isWhitespace(char c) {
return c==' ' || c=='\t';
}
private static void out(Object x) {
System.out.println(x);
}
public static void main(String[] args) throws IOException {
new ProblemA4();
}
} | Java | ["4\n1 2 1 2", "3\n1 1 1"] | 2 seconds | ["7 3 0 0", "6 0 0"] | NoteIn the first sample, color 2 is dominant in three intervals: An interval [2, 2] contains one ball. This ball's color is 2 so it's clearly a dominant color. An interval [4, 4] contains one ball, with color 2 again. An interval [2, 4] contains two balls of color 2 and one ball of color 1. There are 7 more intervals and color 1 is dominant in all of them. | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | f292c099e4eac9259a5bc9e42ff6d1b5 | The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — the number of balls. The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ n) where ti is the color of the i-th ball. | 1,500 | Print n integers. The i-th of them should be equal to the number of intervals where i is a dominant color. | standard output | |
PASSED | 6ce68b4deb071717e51b6e36485bf43e | train_000.jsonl | 1462633500 | Bear Limak has n colored balls, arranged in one long row. Balls are numbered 1 through n, from left to right. There are n possible colors, also numbered 1 through n. The i-th ball has color ti.For a fixed interval (set of consecutive elements) of balls we can define a dominant color. It's a color occurring the biggest number of times in the interval. In case of a tie between some colors, the one with the smallest number (index) is chosen as dominant.There are non-empty intervals in total. For each color, your task is to count the number of intervals in which this color is dominant. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class A {
public static void main(String[] args) throws IOException {
/**/
Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
/*/
Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(new FileInputStream("src/a.in"))));
/**/
int n = sc.nextInt();
int[] t = new int[n];
for (int i = 0; i < n; i++) {
t[i] = sc.nextInt()-1;
}
int[] dom = new int[n];
for (int i = 0; i < n; i++) {
int[] freqs = new int[n];
int maxC = 0;
int maxN = -1;
for (int j = i; j < n; j++) {
freqs[t[j]]++;
if (freqs[t[j]]>maxN || (freqs[t[j]]==maxN&&t[j]<maxC)) {
maxN = freqs[t[j]];
maxC = t[j];
}
dom[maxC]++;
}
}
StringBuilder result = new StringBuilder();
for (int i = 0; i < n; i++) {
if (i>0)
result.append(" ");
result.append(dom[i]);
}
System.out.println(result.toString());
}
} | Java | ["4\n1 2 1 2", "3\n1 1 1"] | 2 seconds | ["7 3 0 0", "6 0 0"] | NoteIn the first sample, color 2 is dominant in three intervals: An interval [2, 2] contains one ball. This ball's color is 2 so it's clearly a dominant color. An interval [4, 4] contains one ball, with color 2 again. An interval [2, 4] contains two balls of color 2 and one ball of color 1. There are 7 more intervals and color 1 is dominant in all of them. | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | f292c099e4eac9259a5bc9e42ff6d1b5 | The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — the number of balls. The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ n) where ti is the color of the i-th ball. | 1,500 | Print n integers. The i-th of them should be equal to the number of intervals where i is a dominant color. | standard output | |
PASSED | 5b52543b55e018f83f84ef041923b951 | train_000.jsonl | 1462633500 | Bear Limak has n colored balls, arranged in one long row. Balls are numbered 1 through n, from left to right. There are n possible colors, also numbered 1 through n. The i-th ball has color ti.For a fixed interval (set of consecutive elements) of balls we can define a dominant color. It's a color occurring the biggest number of times in the interval. In case of a tie between some colors, the one with the smallest number (index) is chosen as dominant.There are non-empty intervals in total. For each color, your task is to count the number of intervals in which this color is dominant. | 256 megabytes | // practice with rainboy
import java.io.*;
import java.util.*;
public class CF674A extends PrintWriter {
CF674A() { super(System.out, true); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF674A o = new CF674A(); o.main(); o.flush();
}
void main() {
int n = sc.nextInt();
int[] aa = new int[n];
for (int i = 0; i < n; i++)
aa[i] = sc.nextInt() - 1;
int[] kk = new int[n];
int[] ans = new int[n];
for (int i = 0; i < n; i++) {
Arrays.fill(kk, 0);
int a_ = -1;
for (int j = i; j < n; j++) {
int a = aa[j];
kk[a]++;
if (a_ == -1 || kk[a_] < kk[a] || kk[a_] == kk[a] && a_ > a)
a_ = a;
ans[a_]++;
}
}
for (int a = 0; a < n; a++)
print(ans[a] + " ");
println();
}
}
| Java | ["4\n1 2 1 2", "3\n1 1 1"] | 2 seconds | ["7 3 0 0", "6 0 0"] | NoteIn the first sample, color 2 is dominant in three intervals: An interval [2, 2] contains one ball. This ball's color is 2 so it's clearly a dominant color. An interval [4, 4] contains one ball, with color 2 again. An interval [2, 4] contains two balls of color 2 and one ball of color 1. There are 7 more intervals and color 1 is dominant in all of them. | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | f292c099e4eac9259a5bc9e42ff6d1b5 | The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — the number of balls. The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ n) where ti is the color of the i-th ball. | 1,500 | Print n integers. The i-th of them should be equal to the number of intervals where i is a dominant color. | standard output | |
PASSED | bd3db78e8ce854eee558a4dbe4c2cb07 | train_000.jsonl | 1462633500 | Bear Limak has n colored balls, arranged in one long row. Balls are numbered 1 through n, from left to right. There are n possible colors, also numbered 1 through n. The i-th ball has color ti.For a fixed interval (set of consecutive elements) of balls we can define a dominant color. It's a color occurring the biggest number of times in the interval. In case of a tie between some colors, the one with the smallest number (index) is chosen as dominant.There are non-empty intervals in total. For each color, your task is to count the number of intervals in which this color is dominant. | 256 megabytes | import static java.lang.Double.parseDouble;
import static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
import static java.lang.System.exit;
import static java.util.Arrays.fill;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class A {
static BufferedReader in;
static PrintWriter out;
static StringTokenizer tok;
static void solve() throws Exception {
int n = nextInt();
int t[] = new int[n];
for (int i = 0; i < n; i++) {
t[i] = nextInt() - 1;
}
int ans[] = new int[n];
int cnts[] = new int[n];
for (int i = 0; i < n; i++) {
fill(cnts, 0);
int maxCnt = 0;
int maxCntPos = -1;
for (int j = i; j < n; j++) {
int cur = t[j];
if (++cnts[cur] > maxCnt || (cnts[cur] == maxCnt && cur < maxCntPos)) {
maxCnt = cnts[cur];
maxCntPos = cur;
}
++ans[maxCntPos];
}
}
for (int i = 0; i < n; i++) {
if (i > 0) {
out.print(' ');
}
out.print(ans[i]);
}
}
static int nextInt() throws IOException {
return parseInt(next());
}
static long nextLong() throws IOException {
return parseLong(next());
}
static double nextDouble() throws IOException {
return parseDouble(next());
}
static String next() throws IOException {
while (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
public static void main(String[] args) {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new OutputStreamWriter(System.out));
solve();
in.close();
out.close();
} catch (Throwable e) {
e.printStackTrace();
exit(1);
}
}
}
| Java | ["4\n1 2 1 2", "3\n1 1 1"] | 2 seconds | ["7 3 0 0", "6 0 0"] | NoteIn the first sample, color 2 is dominant in three intervals: An interval [2, 2] contains one ball. This ball's color is 2 so it's clearly a dominant color. An interval [4, 4] contains one ball, with color 2 again. An interval [2, 4] contains two balls of color 2 and one ball of color 1. There are 7 more intervals and color 1 is dominant in all of them. | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | f292c099e4eac9259a5bc9e42ff6d1b5 | The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — the number of balls. The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ n) where ti is the color of the i-th ball. | 1,500 | Print n integers. The i-th of them should be equal to the number of intervals where i is a dominant color. | standard output | |
PASSED | f67560c28c367c6aca02c78058f5b369 | train_000.jsonl | 1462633500 | Bear Limak has n colored balls, arranged in one long row. Balls are numbered 1 through n, from left to right. There are n possible colors, also numbered 1 through n. The i-th ball has color ti.For a fixed interval (set of consecutive elements) of balls we can define a dominant color. It's a color occurring the biggest number of times in the interval. In case of a tie between some colors, the one with the smallest number (index) is chosen as dominant.There are non-empty intervals in total. For each color, your task is to count the number of intervals in which this color is dominant. | 256 megabytes | import java.util.*;
public class BearAndColors
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] array = new int[n];
for(int x = 0; x < n; x++)
{
array[x] = in.nextInt() - 1;
}
int[] result = new int[n];
for(int y = 0; y < array.length; y++)
{
int[] counts = new int[n];
int best = 0;
for(int z = y; z < array.length; z++)
{
counts[array[z]]++;
if(counts[array[z]] > counts[best] || (array[z] < best && counts[array[z]] == counts[best]))
{
best = array[z];
}
result[best]++;
}
}
for(int a = 0; a < result.length; a++)
{
System.out.print(result[a] + " ");
}
System.out.println();
}
}
| Java | ["4\n1 2 1 2", "3\n1 1 1"] | 2 seconds | ["7 3 0 0", "6 0 0"] | NoteIn the first sample, color 2 is dominant in three intervals: An interval [2, 2] contains one ball. This ball's color is 2 so it's clearly a dominant color. An interval [4, 4] contains one ball, with color 2 again. An interval [2, 4] contains two balls of color 2 and one ball of color 1. There are 7 more intervals and color 1 is dominant in all of them. | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | f292c099e4eac9259a5bc9e42ff6d1b5 | The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — the number of balls. The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ n) where ti is the color of the i-th ball. | 1,500 | Print n integers. The i-th of them should be equal to the number of intervals where i is a dominant color. | standard output | |
PASSED | 4c931e783e35619f64fae65c71e5b9bc | train_000.jsonl | 1462633500 | Bear Limak has n colored balls, arranged in one long row. Balls are numbered 1 through n, from left to right. There are n possible colors, also numbered 1 through n. The i-th ball has color ti.For a fixed interval (set of consecutive elements) of balls we can define a dominant color. It's a color occurring the biggest number of times in the interval. In case of a tie between some colors, the one with the smallest number (index) is chosen as dominant.There are non-empty intervals in total. For each color, your task is to count the number of intervals in which this color is dominant. | 256 megabytes | import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
/**
*
* @author nayrouz
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// Write your awsome code here :D
Scanner read=new Scanner(System.in);
int n=read.nextInt();
int t[]=new int[n];
ArrayList<Integer> liste=new ArrayList<>(n);
for (int i = 0; i <n; i++) {
t[i]=read.nextInt()-1;
// System.out.print(t[i]+" ");
}//System.out.println("");
int answer[]=new int[n];
for (int i = 0; i <t.length; i++) {
int answer1=0;int answer2=0;
int x[]=new int[n];
for (int j = i; j < t.length; j++) {
x[t[j]]++;
if(answer1<x[t[j]]|| x[t[j]]==answer1 && answer2>=t[j] ){
answer1=x[t[j]];
answer2=t[j];
}
answer[answer2]++;
}// System.out.println(best+" best");
}
for (int i = 0; i < answer.length; i++) {
System.out.print(answer[i]+" ");
}
//System.out.println(Arrays.toString(answer));
System.out.println("");
}
}
| Java | ["4\n1 2 1 2", "3\n1 1 1"] | 2 seconds | ["7 3 0 0", "6 0 0"] | NoteIn the first sample, color 2 is dominant in three intervals: An interval [2, 2] contains one ball. This ball's color is 2 so it's clearly a dominant color. An interval [4, 4] contains one ball, with color 2 again. An interval [2, 4] contains two balls of color 2 and one ball of color 1. There are 7 more intervals and color 1 is dominant in all of them. | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | f292c099e4eac9259a5bc9e42ff6d1b5 | The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — the number of balls. The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ n) where ti is the color of the i-th ball. | 1,500 | Print n integers. The i-th of them should be equal to the number of intervals where i is a dominant color. | standard output | |
PASSED | 36b9cdfb33fd002e0a00fc9c8404a73e | train_000.jsonl | 1462633500 | Bear Limak has n colored balls, arranged in one long row. Balls are numbered 1 through n, from left to right. There are n possible colors, also numbered 1 through n. The i-th ball has color ti.For a fixed interval (set of consecutive elements) of balls we can define a dominant color. It's a color occurring the biggest number of times in the interval. In case of a tie between some colors, the one with the smallest number (index) is chosen as dominant.There are non-empty intervals in total. For each color, your task is to count the number of intervals in which this color is dominant. | 256 megabytes |
import java.io.*;
import java.util.*;
public class A {
InputStream is;
int __t__ = 1;
int __f__ = 0;
int __FILE_DEBUG_FLAG__ = __f__;
String __DEBUG_FILE_NAME__ = "src/T";
FastScanner in;
PrintWriter out;
public void solve() {
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt() - 1;
}
int[] res = new int[n];
int[] cnt = new int[n];
int curColor = -1;
for (int i = 0; i < n; i++) {
Arrays.fill(cnt, 0);
for (int j = i; j < n; j++) {
cnt[a[j]]++;
if (curColor == -1 || cnt[curColor] < cnt[a[j]] || (cnt[curColor] == cnt[a[j]] && a[j] < curColor)) {
curColor = a[j];
}
res[curColor]++;
}
}
for (int i = 0; i < n; i++) {
out.print(res[i] + " ");
}
out.println();
out.close();
}
public void run() {
if (__FILE_DEBUG_FLAG__ == __t__) {
try {
is = new FileInputStream(__DEBUG_FILE_NAME__);
} catch (FileNotFoundException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
}
System.out.println("FILE_INPUT!");
} else {
is = System.in;
}
in = new FastScanner(is);
out = new PrintWriter(System.out);
solve();
}
public static void main(String[] args) {
new A().run();
}
public void mapDebug(int[][] a) {
System.out.println("--------map display---------");
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.printf("%3d ", a[i][j]);
}
System.out.println();
}
System.out.println("----------------------------");
System.out.println();
}
public void debug(Object... obj) {
System.out.println(Arrays.deepToString(obj));
}
class FastScanner {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastScanner(InputStream stream) {
this.stream = stream;
//stream = new FileInputStream(new File("dec.in"));
}
int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
boolean isEndline(int c) {
return c == '\n' || c == '\r' || c == -1;
}
int nextInt() {
return Integer.parseInt(next());
}
int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; i++)
array[i] = nextInt();
return array;
}
int[][] nextIntMap(int n, int m) {
int[][] map = new int[n][m];
for (int i = 0; i < n; i++) {
map[i] = in.nextIntArray(m);
}
return map;
}
long nextLong() {
return Long.parseLong(next());
}
long[] nextLongArray(int n) {
long[] array = new long[n];
for (int i = 0; i < n; i++)
array[i] = nextLong();
return array;
}
long[][] nextLongMap(int n, int m) {
long[][] map = new long[n][m];
for (int i = 0; i < n; i++) {
map[i] = in.nextLongArray(m);
}
return map;
}
double nextDouble() {
return Double.parseDouble(next());
}
double[] nextDoubleArray(int n) {
double[] array = new double[n];
for (int i = 0; i < n; i++)
array[i] = nextDouble();
return array;
}
double[][] nextDoubleMap(int n, int m) {
double[][] map = new double[n][m];
for (int i = 0; i < n; i++) {
map[i] = in.nextDoubleArray(m);
}
return map;
}
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();
}
String[] nextStringArray(int n) {
String[] array = new String[n];
for (int i = 0; i < n; i++)
array[i] = next();
return array;
}
String nextLine() {
int c = read();
while (isEndline(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndline(c));
return res.toString();
}
}
}
| Java | ["4\n1 2 1 2", "3\n1 1 1"] | 2 seconds | ["7 3 0 0", "6 0 0"] | NoteIn the first sample, color 2 is dominant in three intervals: An interval [2, 2] contains one ball. This ball's color is 2 so it's clearly a dominant color. An interval [4, 4] contains one ball, with color 2 again. An interval [2, 4] contains two balls of color 2 and one ball of color 1. There are 7 more intervals and color 1 is dominant in all of them. | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | f292c099e4eac9259a5bc9e42ff6d1b5 | The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — the number of balls. The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ n) where ti is the color of the i-th ball. | 1,500 | Print n integers. The i-th of them should be equal to the number of intervals where i is a dominant color. | standard output | |
PASSED | 855bc273d8de478bdf1fb5e262133545 | train_000.jsonl | 1462633500 | Bear Limak has n colored balls, arranged in one long row. Balls are numbered 1 through n, from left to right. There are n possible colors, also numbered 1 through n. The i-th ball has color ti.For a fixed interval (set of consecutive elements) of balls we can define a dominant color. It's a color occurring the biggest number of times in the interval. In case of a tie between some colors, the one with the smallest number (index) is chosen as dominant.There are non-empty intervals in total. For each color, your task is to count the number of intervals in which this color is dominant. | 256 megabytes |
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.SortedSet;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
/**
* #
* @author pttrung
*/
public class A_Round_351_Div1 {
public static long MOD = 1000000007;
public static void main(String[] args) throws FileNotFoundException {
// PrintWriter out = new PrintWriter(new FileOutputStream(new File(
// "output.txt")));
PrintWriter out = new PrintWriter(System.out);
Scanner in = new Scanner();
int n = in.nextInt();
int[] data = new int[n];
int[] count = new int[n + 1];
for (int i = 0; i < n; i++) {
data[i] = in.nextInt();
}
for (int i = 0; i < n; i++) {
int[] cur = new int[n + 1];
int max = 0;
int index = 0;
for (int j = i; j < n; j++) {
cur[data[j]]++;
if(cur[data[j]] > max || (index > data[j] && max == cur[data[j]])){
max = cur[data[j]];
index = data[j];
}
count[index]++;
}
}
for(int i = 1; i <= n; i++){
out.print(count[i] + " ");
}
out.close();
}
public static int[] KMP(String val) {
int i = 0;
int j = -1;
int[] result = new int[val.length() + 1];
result[0] = -1;
while (i < val.length()) {
while (j >= 0 && val.charAt(j) != val.charAt(i)) {
j = result[j];
}
j++;
i++;
result[i] = j;
}
return result;
}
public static boolean nextPer(int[] data) {
int i = data.length - 1;
while (i > 0 && data[i] < data[i - 1]) {
i--;
}
if (i == 0) {
return false;
}
int j = data.length - 1;
while (data[j] < data[i - 1]) {
j--;
}
int temp = data[i - 1];
data[i - 1] = data[j];
data[j] = temp;
Arrays.sort(data, i, data.length);
return true;
}
public static int digit(long n) {
int result = 0;
while (n > 0) {
n /= 10;
result++;
}
return result;
}
public static double dist(long a, long b, long x, long y) {
double val = (b - a) * (b - a) + (x - y) * (x - y);
val = Math.sqrt(val);
double other = x * x + a * a;
other = Math.sqrt(other);
return val + other;
}
public static class Point implements Comparable<Point> {
int x, y;
public Point(int start, int end) {
this.x = start;
this.y = end;
}
@Override
public int hashCode() {
int hash = 5;
hash = 47 * hash + this.x;
hash = 47 * hash + this.y;
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Point other = (Point) obj;
if (this.x != other.x) {
return false;
}
if (this.y != other.y) {
return false;
}
return true;
}
@Override
public int compareTo(Point o) {
if (x != o.x) {
return Integer.compare(o.x, x);
}
return Integer.compare(y, o.y);
}
}
public static class FT {
long[] data;
FT(int n) {
data = new long[n];
}
public void update(int index, long value) {
while (index < data.length) {
data[index] += value;
index += (index & (-index));
}
}
public long get(int index) {
long result = 0;
while (index > 0) {
result += data[index];
index -= (index & (-index));
}
return result;
}
}
public static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
public static long pow(long a, long b, long MOD) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long val = pow(a, b / 2, MOD);
if (b % 2 == 0) {
return val * val % MOD;
} else {
return val * (val * a % MOD) % MOD;
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() throws FileNotFoundException {
// System.setOut(new PrintStream(new BufferedOutputStream(System.out), true));
br = new BufferedReader(new InputStreamReader(System.in));
// br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt"))));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
throw new RuntimeException();
}
}
return st.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
st = null;
try {
return br.readLine();
} catch (Exception e) {
throw new RuntimeException();
}
}
public boolean endLine() {
try {
String next = br.readLine();
while (next != null && next.trim().isEmpty()) {
next = br.readLine();
}
if (next == null) {
return true;
}
st = new StringTokenizer(next);
return st.hasMoreTokens();
} catch (Exception e) {
throw new RuntimeException();
}
}
}
}
| Java | ["4\n1 2 1 2", "3\n1 1 1"] | 2 seconds | ["7 3 0 0", "6 0 0"] | NoteIn the first sample, color 2 is dominant in three intervals: An interval [2, 2] contains one ball. This ball's color is 2 so it's clearly a dominant color. An interval [4, 4] contains one ball, with color 2 again. An interval [2, 4] contains two balls of color 2 and one ball of color 1. There are 7 more intervals and color 1 is dominant in all of them. | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | f292c099e4eac9259a5bc9e42ff6d1b5 | The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — the number of balls. The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ n) where ti is the color of the i-th ball. | 1,500 | Print n integers. The i-th of them should be equal to the number of intervals where i is a dominant color. | standard output | |
PASSED | 32db4fd70f5525dc5e15437565523aca | train_000.jsonl | 1462633500 | Bear Limak has n colored balls, arranged in one long row. Balls are numbered 1 through n, from left to right. There are n possible colors, also numbered 1 through n. The i-th ball has color ti.For a fixed interval (set of consecutive elements) of balls we can define a dominant color. It's a color occurring the biggest number of times in the interval. In case of a tie between some colors, the one with the smallest number (index) is chosen as dominant.There are non-empty intervals in total. For each color, your task is to count the number of intervals in which this color is dominant. | 256 megabytes | // package codeforces.cf3xx.cf351.div1;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
/**
* Created by hama_du on 2016/08/16.
*/
public class A {
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
int[] a = in.nextInts(n);
int[] ans = new int[n+1];
int[] deg = new int[n+1];
for (int i = 0; i < n ; i++) {
Arrays.fill(deg, i);
int best = -1;
int bestCol = -1;
for (int j = i ; j < n ; j++) {
deg[a[j]]++;
if (best < deg[a[j]] || (best == deg[a[j]] && bestCol > a[j])) {
best = deg[a[j]];
bestCol = a[j];
}
ans[bestCol]++;
}
}
StringBuilder line = new StringBuilder();
for (int i = 1 ; i <= n ; i++) {
line.append(' ').append(ans[i]);
}
out.println(line.substring(1));
out.flush();
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
private int[] nextInts(int n) {
int[] ret = new int[n];
for (int i = 0; i < n; i++) {
ret[i] = nextInt();
}
return ret;
}
private int[][] nextIntTable(int n, int m) {
int[][] ret = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
ret[i][j] = nextInt();
}
}
return ret;
}
private long[] nextLongs(int n) {
long[] ret = new long[n];
for (int i = 0; i < n; i++) {
ret[i] = nextLong();
}
return ret;
}
private long[][] nextLongTable(int n, int m) {
long[][] ret = new long[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
ret[i][j] = nextLong();
}
}
return ret;
}
private double[] nextDoubles(int n) {
double[] ret = new double[n];
for (int i = 0; i < n; i++) {
ret[i] = nextDouble();
}
return ret;
}
private int next() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public char nextChar() {
int c = next();
while (isSpaceChar(c))
c = next();
if ('a' <= c && c <= 'z') {
return (char) c;
}
if ('A' <= c && c <= 'Z') {
return (char) c;
}
throw new InputMismatchException();
}
public String nextToken() {
int c = next();
while (isSpaceChar(c))
c = next();
StringBuilder res = new StringBuilder();
do {
res.append((char) c);
c = next();
} while (!isSpaceChar(c));
return res.toString();
}
public int nextInt() {
int c = next();
while (isSpaceChar(c))
c = next();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = next();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = next();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = next();
while (isSpaceChar(c))
c = next();
long sgn = 1;
if (c == '-') {
sgn = -1;
c = next();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = next();
} while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble() {
return Double.valueOf(nextToken());
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static void debug(Object... o) {
System.err.println(Arrays.deepToString(o));
}
}
| Java | ["4\n1 2 1 2", "3\n1 1 1"] | 2 seconds | ["7 3 0 0", "6 0 0"] | NoteIn the first sample, color 2 is dominant in three intervals: An interval [2, 2] contains one ball. This ball's color is 2 so it's clearly a dominant color. An interval [4, 4] contains one ball, with color 2 again. An interval [2, 4] contains two balls of color 2 and one ball of color 1. There are 7 more intervals and color 1 is dominant in all of them. | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | f292c099e4eac9259a5bc9e42ff6d1b5 | The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — the number of balls. The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ n) where ti is the color of the i-th ball. | 1,500 | Print n integers. The i-th of them should be equal to the number of intervals where i is a dominant color. | standard output | |
PASSED | 169fdb3d4bd9e5d9f9ff22f2b222000e | train_000.jsonl | 1462633500 | Bear Limak has n colored balls, arranged in one long row. Balls are numbered 1 through n, from left to right. There are n possible colors, also numbered 1 through n. The i-th ball has color ti.For a fixed interval (set of consecutive elements) of balls we can define a dominant color. It's a color occurring the biggest number of times in the interval. In case of a tie between some colors, the one with the smallest number (index) is chosen as dominant.There are non-empty intervals in total. For each color, your task is to count the number of intervals in which this color is dominant. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt() - 1;
}
int[] b = new int[n];
int[] ans = new int[n];
for (int i = 0; i < n; i++) {
Arrays.fill(b, 0);
int k = -1;
for (int j = i; j < n; j++) {
++b[a[j]];
int nk = a[j];
if (k < 0 || b[k] < b[nk] || b[k] == b[nk] && k > nk) {
k = nk;
}
++ans[k];
}
}
for (int i = 0; i < n; i++) {
if (i > 0) {
out.print(" ");
}
out.print(ans[i]);
}
out.println();
}
}
static class FastScanner {
private BufferedReader in;
private StringTokenizer st;
public FastScanner(InputStream stream) {
in = new BufferedReader(new InputStreamReader(stream));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
String rl = in.readLine();
if (rl == null) {
return null;
}
st = new StringTokenizer(rl);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["4\n1 2 1 2", "3\n1 1 1"] | 2 seconds | ["7 3 0 0", "6 0 0"] | NoteIn the first sample, color 2 is dominant in three intervals: An interval [2, 2] contains one ball. This ball's color is 2 so it's clearly a dominant color. An interval [4, 4] contains one ball, with color 2 again. An interval [2, 4] contains two balls of color 2 and one ball of color 1. There are 7 more intervals and color 1 is dominant in all of them. | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | f292c099e4eac9259a5bc9e42ff6d1b5 | The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — the number of balls. The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ n) where ti is the color of the i-th ball. | 1,500 | Print n integers. The i-th of them should be equal to the number of intervals where i is a dominant color. | standard output | |
PASSED | 8333b33c558446eb44ff2d7979e56002 | train_000.jsonl | 1462633500 | Bear Limak has n colored balls, arranged in one long row. Balls are numbered 1 through n, from left to right. There are n possible colors, also numbered 1 through n. The i-th ball has color ti.For a fixed interval (set of consecutive elements) of balls we can define a dominant color. It's a color occurring the biggest number of times in the interval. In case of a tie between some colors, the one with the smallest number (index) is chosen as dominant.There are non-empty intervals in total. For each color, your task is to count the number of intervals in which this color is dominant. | 256 megabytes | //package vk2016.r3;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class A {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni();
int[] a = na(n);
int[] ret = new int[n];
for(int i = 0;i < n;i++){
int[] f = new int[n+1];
int[] ff = new int[n+1];
ff[0] = n;
int argmax = Integer.MAX_VALUE;
int valmax = 0;
for(int j = i;j < n;j++){
ff[f[a[j]]]--;
f[a[j]]++;
ff[f[a[j]]]++;
if(f[a[j]] > valmax){
valmax = f[a[j]];
argmax = a[j];
}else if(f[a[j]] == valmax && a[j] < argmax){
argmax = a[j];
}
ret[argmax-1]++;
}
}
for(int i = 0;i < n;i++){
out.print(ret[i] + " ");
}
out.println();
}
void run() throws Exception
{
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new A().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 1 2", "3\n1 1 1"] | 2 seconds | ["7 3 0 0", "6 0 0"] | NoteIn the first sample, color 2 is dominant in three intervals: An interval [2, 2] contains one ball. This ball's color is 2 so it's clearly a dominant color. An interval [4, 4] contains one ball, with color 2 again. An interval [2, 4] contains two balls of color 2 and one ball of color 1. There are 7 more intervals and color 1 is dominant in all of them. | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | f292c099e4eac9259a5bc9e42ff6d1b5 | The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — the number of balls. The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ n) where ti is the color of the i-th ball. | 1,500 | Print n integers. The i-th of them should be equal to the number of intervals where i is a dominant color. | standard output | |
PASSED | 0bb1050b25b5e9996d0f4ee7695c10cf | train_000.jsonl | 1462633500 | Bear Limak has n colored balls, arranged in one long row. Balls are numbered 1 through n, from left to right. There are n possible colors, also numbered 1 through n. The i-th ball has color ti.For a fixed interval (set of consecutive elements) of balls we can define a dominant color. It's a color occurring the biggest number of times in the interval. In case of a tie between some colors, the one with the smallest number (index) is chosen as dominant.There are non-empty intervals in total. For each color, your task is to count the number of intervals in which this color is dominant. | 256 megabytes | import java.io.*;
import java.util.*;
public class Solution {
private BufferedReader in;
private StringTokenizer line;
private PrintWriter out;
private static final int mm = 1000000007;
public void solve() throws IOException {
int n = nextInt();
int[] a = nextIntArray(n);
for (int i = 0; i < n; i++) {
a[i]--;
}
int[] res = new int[n];
int[] b = new int[n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
b[j] = 0;
}
int bsti = i;
for (int j = i; j < n; j++) {
int color = a[j];
b[color]++;
if (b[color] > b[bsti] || (b[color] == b[bsti] && bsti > color)) {
bsti = color;
}
res[bsti]++;
}
}
for (int i = 0; i < n; i++) {
out.print(res[i] + " ");
}
}
public static void main(String[] args) throws IOException {
new Solution().run(args);
}
public void run(String[] args) throws IOException {
if (args.length > 0 && "DEBUG_MODE".equals(args[0])) {
in = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt")));
} else {
in = new BufferedReader(new InputStreamReader(System.in));
}
out = new PrintWriter(System.out);
// out = new PrintWriter("output.txt");
// int t = nextInt();
int t = 1;
for (int i = 0; i < t; i++) {
// out.print("Case #" + (i + 1) + ": ");
solve();
}
in.close();
out.flush();
out.close();
}
private int[] nextIntArray(int n) throws IOException {
int[] res = new int[n];
for (int i = 0; i < n; i++) {
res[i] = nextInt();
}
return res;
}
private long[] nextLongArray(int n) throws IOException {
long[] res = new long[n];
for (int i = 0; i < n; i++) {
res[i] = nextInt();
}
return res;
}
private int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
private long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
private double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
private String nextToken() throws IOException {
while (line == null || !line.hasMoreTokens()) {
line = new StringTokenizer(in.readLine());
}
return line.nextToken();
}
private static class Pii {
private int key;
private int value;
public Pii(int key, int value) {
this.key = key;
this.value = value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pii pii = (Pii) o;
if (key != pii.key) return false;
return value == pii.value;
}
@Override
public int hashCode() {
int result = key;
result = 31 * result + value;
return result;
}
}
private static class Pair<K, V> {
private K key;
private V value;
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair<?, ?> pair = (Pair<?, ?>) o;
if (key != null ? !key.equals(pair.key) : pair.key != null) return false;
return !(value != null ? !value.equals(pair.value) : pair.value != null);
}
@Override
public int hashCode() {
int result = key != null ? key.hashCode() : 0;
result = 31 * result + (value != null ? value.hashCode() : 0);
return result;
}
}
} | Java | ["4\n1 2 1 2", "3\n1 1 1"] | 2 seconds | ["7 3 0 0", "6 0 0"] | NoteIn the first sample, color 2 is dominant in three intervals: An interval [2, 2] contains one ball. This ball's color is 2 so it's clearly a dominant color. An interval [4, 4] contains one ball, with color 2 again. An interval [2, 4] contains two balls of color 2 and one ball of color 1. There are 7 more intervals and color 1 is dominant in all of them. | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | f292c099e4eac9259a5bc9e42ff6d1b5 | The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — the number of balls. The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ n) where ti is the color of the i-th ball. | 1,500 | Print n integers. The i-th of them should be equal to the number of intervals where i is a dominant color. | standard output | |
PASSED | 3ec2b76bf3dfc8aa6c0803a39119f249 | train_000.jsonl | 1462633500 | Bear Limak has n colored balls, arranged in one long row. Balls are numbered 1 through n, from left to right. There are n possible colors, also numbered 1 through n. The i-th ball has color ti.For a fixed interval (set of consecutive elements) of balls we can define a dominant color. It's a color occurring the biggest number of times in the interval. In case of a tie between some colors, the one with the smallest number (index) is chosen as dominant.There are non-empty intervals in total. For each color, your task is to count the number of intervals in which this color is dominant. | 256 megabytes | import java.io.*;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main {
private NotMyScanner in;
private PrintWriter out;
// private Timer timer = new Timer();
// Или пиши красиво, или не пиши вообще.
private void solve() throws IOException {
int n = in.nextInt(), a[] = in.nextInts(n), ans[] = new int[n];
for (int i = 0; i < n; i++) {
int cnt[] = new int[n], cur = 0;
for (int j = i; j < n; j++) {
cnt[a[j] - 1]++;
if (cnt[a[j] - 1] > cnt[cur]) {
cur = a[j] - 1;
} else if (cnt[a[j] - 1] == cnt[cur]) {
if (a[j] - 1 < cur) {
cur = a[j] - 1;
}
}
ans[cur]++;
}
}
for (int e : ans) {
out.print(e + " ");
}
out.println();
}
private void run() throws IOException {
in = new NotMyScanner();
out = new PrintWriter(System.out, false);
solve();
out.close();
}
public static void main(String[] args) throws IOException {
new Main().run();
}
}
class NotMyScanner {
private final BufferedReader br;
private StringTokenizer st;
private String last;
public NotMyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public NotMyScanner(String path) throws IOException {
br = new BufferedReader(new FileReader(path));
}
public NotMyScanner(String path, String decoder) throws IOException {
br = new BufferedReader(new InputStreamReader(new FileInputStream(path), decoder));
}
String next() throws IOException {
while (st == null || !st.hasMoreElements())
st = new StringTokenizer(br.readLine());
last = null;
return st.nextToken();
}
String nextLine() throws IOException {
st = null;
return (last == null) ? br.readLine() : last;
}
boolean hasNext() {
if (st != null && st.hasMoreElements())
return true;
try {
while (st == null || !st.hasMoreElements()) {
last = br.readLine();
st = new StringTokenizer(last);
}
} catch (Exception e) {
return false;
}
return true;
}
String[] nextStrings(int n) throws IOException {
String[] arr = new String[n];
for (int i = 0; i < n; i++)
arr[i] = next();
return arr;
}
String[] nextLines(int n) throws IOException {
String[] arr = new String[n];
for (int i = 0; i < n; i++)
arr[i] = nextLine();
return arr;
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
int[] nextInts(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = nextInt();
return arr;
}
Integer[] nextIntegers(int n) throws IOException {
Integer[] arr = new Integer[n];
for (int i = 0; i < n; i++)
arr[i] = nextInt();
return arr;
}
int[][] next2Ints(int n, int m) throws IOException {
int[][] arr = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
arr[i][j] = nextInt();
return arr;
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
long[] nextLongs(int n) throws IOException {
long[] arr = new long[n];
for (int i = 0; i < n; i++)
arr[i] = nextLong();
return arr;
}
long[][] next2Longs(int n, int m) throws IOException {
long[][] arr = new long[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
arr[i][j] = nextLong();
return arr;
}
double nextDouble() throws IOException {
return Double.parseDouble(next().replace(',', '.'));
}
double[] nextDoubles(int size) throws IOException {
double[] arr = new double[size];
for (int i = 0; i < size; i++)
arr[i] = nextDouble();
return arr;
}
boolean nextBool() throws IOException {
String s = next();
if (s.equalsIgnoreCase("true") || s.equals("1"))
return true;
if (s.equalsIgnoreCase("false") || s.equals("0"))
return false;
throw new IOException("Boolean expected, String found!");
}
} | Java | ["4\n1 2 1 2", "3\n1 1 1"] | 2 seconds | ["7 3 0 0", "6 0 0"] | NoteIn the first sample, color 2 is dominant in three intervals: An interval [2, 2] contains one ball. This ball's color is 2 so it's clearly a dominant color. An interval [4, 4] contains one ball, with color 2 again. An interval [2, 4] contains two balls of color 2 and one ball of color 1. There are 7 more intervals and color 1 is dominant in all of them. | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | f292c099e4eac9259a5bc9e42ff6d1b5 | The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — the number of balls. The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ n) where ti is the color of the i-th ball. | 1,500 | Print n integers. The i-th of them should be equal to the number of intervals where i is a dominant color. | standard output | |
PASSED | 6628a431d0cf536740bd34f463dbbba0 | train_000.jsonl | 1462633500 | Bear Limak has n colored balls, arranged in one long row. Balls are numbered 1 through n, from left to right. There are n possible colors, also numbered 1 through n. The i-th ball has color ti.For a fixed interval (set of consecutive elements) of balls we can define a dominant color. It's a color occurring the biggest number of times in the interval. In case of a tie between some colors, the one with the smallest number (index) is chosen as dominant.There are non-empty intervals in total. For each color, your task is to count the number of intervals in which this color is dominant. | 256 megabytes | /**
* Created by ankeet on 1/9/17.
*/
import java.io.*;
import java.util.*;
public class A674 {
static FastReader in = null;
static PrintWriter out = null;
public static void solve()
{
int n = in.nextInt();
int[] t = new int[n+5];
for(int i=1; i<=n; i++) t[i] = in.nextInt();
int[] sol = new int[n+1];
for(int l = 1; l<=n; l++){
int[] cnt = new int[n+1];
int max = -1;
int maxind = -1;
for(int r = l; r<=n; r++){
cnt[t[r]]++;
if(cnt[t[r]] > max){
max = cnt[t[r]];
maxind = t[r];
}
if(cnt[t[r]] == max){
if(t[r] < maxind){
maxind = t[r];
}
}
sol[maxind]++;
}
}
for(int i=1; i<=n; i++) out.print(sol[i] + " ");
out.println(" ");
}
public static void main(String[] args)
{
in = new FastReader(System.in);
out = new PrintWriter(System.out);
solve();
out.flush();
out.close();
}
static class FastReader {
BufferedReader read;
StringTokenizer tokenizer;
public FastReader(InputStream in)
{
read = new BufferedReader(new InputStreamReader(in));
}
public String next()
{
while(tokenizer == null || !tokenizer.hasMoreTokens())
{
try{
tokenizer = new StringTokenizer(read.readLine());
}catch(Exception e){
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public String nextLine(){
try
{
return read.readLine();
}
catch(Exception e)
{
throw new RuntimeException(e);
}
}
public int nextInt()
{
return Integer.parseInt(next());
}
public long nextLong()
{
return Long.parseLong(next());
}
public double nextDouble()
{
return Double.parseDouble(next());
}
public int[] nextIntArr(int n)
{
int[] a = new int[n];
for(int i=0; i<n; ++i)
{
a[i] = nextInt();
}
return a;
}
public long[] nextLongArr(int n)
{
long[] a = new long[n];
for(int i=0; i<n; ++i)
{
a[i] = nextLong();
}
return a;
}
}
}
| Java | ["4\n1 2 1 2", "3\n1 1 1"] | 2 seconds | ["7 3 0 0", "6 0 0"] | NoteIn the first sample, color 2 is dominant in three intervals: An interval [2, 2] contains one ball. This ball's color is 2 so it's clearly a dominant color. An interval [4, 4] contains one ball, with color 2 again. An interval [2, 4] contains two balls of color 2 and one ball of color 1. There are 7 more intervals and color 1 is dominant in all of them. | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | f292c099e4eac9259a5bc9e42ff6d1b5 | The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — the number of balls. The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ n) where ti is the color of the i-th ball. | 1,500 | Print n integers. The i-th of them should be equal to the number of intervals where i is a dominant color. | standard output | |
PASSED | 32bc89c7033f0aefceb82188ba91d7e3 | train_000.jsonl | 1462633500 | Bear Limak has n colored balls, arranged in one long row. Balls are numbered 1 through n, from left to right. There are n possible colors, also numbered 1 through n. The i-th ball has color ti.For a fixed interval (set of consecutive elements) of balls we can define a dominant color. It's a color occurring the biggest number of times in the interval. In case of a tie between some colors, the one with the smallest number (index) is chosen as dominant.There are non-empty intervals in total. For each color, your task is to count the number of intervals in which this color is dominant. | 256 megabytes | import java.util.*;
import java.io.*;
import java.awt.Point;
import java.math.BigDecimal;
import java.math.BigInteger;
import static java.lang.Math.*;
public class A implements Runnable{
final static Random rnd = new Random();
// SOLUTION!!!
// HACK ME PLEASE IF YOU CAN!!!
// PLEASE!!!
// PLEASE!!!
// PLEASE!!!
void solve() {
int n = readInt();
int[] colors = readIntArrayWithDecrease(n);
int[][] prefs = new int[n][n];
for (int i = 0; i < n; ++i) {
for (int color = 0; color < n && i > 0; ++color) {
prefs[i][color] = prefs[i-1][color];
}
prefs[i][colors[i]]++;
}
int[][] dp = new int[n][n];
for (int end = n - 1; end >= 0; --end) {
for (int start = end; start >= 0; --start) {
if (start == end) dp[start][end] = colors[start];
else {
int prevMax = dp[start + 1][end];
int prevMaxCount = prefs[end][prevMax] - prefs[start][prevMax];
int curMax = colors[start];
int curMaxCount = prefs[end][curMax] - (start == 0 ? 0 : prefs[start - 1][curMax]);
if (prevMaxCount < curMaxCount) {
dp[start][end] = curMax;
} else if (prevMaxCount == curMaxCount && prevMax > curMax) {
dp[start][end] = curMax;
} else {
dp[start][end] = prevMax;
}
}
}
}
int[] answers = new int[n];
for (int start = 0; start < n; ++start) {
for (int end = start; end < n; ++end) {
answers[dp[start][end]]++;
}
}
for (int answer : answers) {
out.print(answer + " ");
}
out.println();
}
/////////////////////////////////////////////////////////////////////
final boolean FIRST_INPUT_STRING = false;
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
final static int MAX_STACK_SIZE = 128;
/////////////////////////////////////////////////////////////////////
public void run(){
try{
timeBegin = System.currentTimeMillis();
Locale.setDefault(Locale.US);
init();
if (ONLINE_JUDGE) {
solve();
} else {
while (true) {
try {
solve();
out.println();
} catch (NumberFormatException e) {
break;
} catch (NullPointerException e) {
if (FIRST_INPUT_STRING) break;
else throw e;
}
}
}
out.close();
time();
}catch (Exception e){
e.printStackTrace(System.err);
System.exit(-1);
}
}
/////////////////////////////////////////////////////////////////////
BufferedReader in;
OutputWriter out;
StringTokenizer tok = new StringTokenizer("");
public static void main(String[] args){
new Thread(null, new A(), "", MAX_STACK_SIZE * (1L << 20)).start();
}
/////////////////////////////////////////////////////////////////////
void init() throws FileNotFoundException{
Locale.setDefault(Locale.US);
if (ONLINE_JUDGE){
in = new BufferedReader(new InputStreamReader(System.in));
out = new OutputWriter(System.out);
}else{
in = new BufferedReader(new FileReader("input.txt"));
out = new OutputWriter("output.txt");
}
}
////////////////////////////////////////////////////////////////
long timeBegin, timeEnd;
void time(){
timeEnd = System.currentTimeMillis();
System.err.println("Time = " + (timeEnd - timeBegin));
}
void debug(Object... objects){
if (ONLINE_JUDGE){
for (Object o: objects){
System.err.println(o.toString());
}
}
}
/////////////////////////////////////////////////////////////////////
String delim = " ";
String readLine() {
try {
return in.readLine();
} catch (IOException e) {
throw new RuntimeIOException(e);
}
}
String readString() {
try {
while(!tok.hasMoreTokens()){
tok = new StringTokenizer(readLine());
}
return tok.nextToken(delim);
} catch (NullPointerException e) {
return null;
}
}
/////////////////////////////////////////////////////////////////
final char NOT_A_SYMBOL = '\0';
char readChar() {
try {
int intValue = in.read();
if (intValue == -1){
return NOT_A_SYMBOL;
}
return (char) intValue;
} catch (IOException e) {
throw new RuntimeIOException(e);
}
}
char[] readCharArray() {
return readLine().toCharArray();
}
char[][] readCharField(int rowsCount) {
char[][] field = new char[rowsCount][];
for (int row = 0; row < rowsCount; ++row) {
field[row] = readCharArray();
}
return field;
}
/////////////////////////////////////////////////////////////////
int readInt() {
return Integer.parseInt(readString());
}
int[] readIntArray(int size) {
int[] array = new int[size];
for (int index = 0; index < size; ++index){
array[index] = readInt();
}
return array;
}
int[] readSortedIntArray(int size) {
Integer[] array = new Integer[size];
for (int index = 0; index < size; ++index) {
array[index] = readInt();
}
Arrays.sort(array);
int[] sortedArray = new int[size];
for (int index = 0; index < size; ++index) {
sortedArray[index] = array[index];
}
return sortedArray;
}
int[] readIntArrayWithDecrease(int size) {
int[] array = readIntArray(size);
for (int i = 0; i < size; ++i) {
array[i]--;
}
return array;
}
///////////////////////////////////////////////////////////////////
int[][] readIntMatrix(int rowsCount, int columnsCount) {
int[][] matrix = new int[rowsCount][];
for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) {
matrix[rowIndex] = readIntArray(columnsCount);
}
return matrix;
}
int[][] readIntMatrixWithDecrease(int rowsCount, int columnsCount) {
int[][] matrix = new int[rowsCount][];
for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) {
matrix[rowIndex] = readIntArrayWithDecrease(columnsCount);
}
return matrix;
}
///////////////////////////////////////////////////////////////////
long readLong() {
return Long.parseLong(readString());
}
long[] readLongArray(int size) {
long[] array = new long[size];
for (int index = 0; index < size; ++index){
array[index] = readLong();
}
return array;
}
////////////////////////////////////////////////////////////////////
double readDouble() {
return Double.parseDouble(readString());
}
double[] readDoubleArray(int size) {
double[] array = new double[size];
for (int index = 0; index < size; ++index){
array[index] = readDouble();
}
return array;
}
////////////////////////////////////////////////////////////////////
BigInteger readBigInteger() {
return new BigInteger(readString());
}
BigDecimal readBigDecimal() {
return new BigDecimal(readString());
}
/////////////////////////////////////////////////////////////////////
Point readPoint() {
int x = readInt();
int y = readInt();
return new Point(x, y);
}
Point[] readPointArray(int size) {
Point[] array = new Point[size];
for (int index = 0; index < size; ++index){
array[index] = readPoint();
}
return array;
}
/////////////////////////////////////////////////////////////////////
List<Integer>[] readGraph(int vertexNumber, int edgeNumber) {
@SuppressWarnings("unchecked")
List<Integer>[] graph = new List[vertexNumber];
for (int index = 0; index < vertexNumber; ++index){
graph[index] = new ArrayList<Integer>();
}
while (edgeNumber-- > 0){
int from = readInt() - 1;
int to = readInt() - 1;
graph[from].add(to);
graph[to].add(from);
}
return graph;
}
/////////////////////////////////////////////////////////////////////
static class IntIndexPair {
static Comparator<IntIndexPair> increaseComparator = new Comparator<IntIndexPair>() {
@Override
public int compare(IntIndexPair indexPair1, IntIndexPair indexPair2) {
int value1 = indexPair1.value;
int value2 = indexPair2.value;
if (value1 != value2) return value1 - value2;
int index1 = indexPair1.index;
int index2 = indexPair2.index;
return index1 - index2;
}
};
static Comparator<IntIndexPair> decreaseComparator = new Comparator<IntIndexPair>() {
@Override
public int compare(IntIndexPair indexPair1, IntIndexPair indexPair2) {
int value1 = indexPair1.value;
int value2 = indexPair2.value;
if (value1 != value2) return -(value1 - value2);
int index1 = indexPair1.index;
int index2 = indexPair2.index;
return index1 - index2;
}
};
int value, index;
public IntIndexPair(int value, int index) {
super();
this.value = value;
this.index = index;
}
public int getRealIndex() {
return index + 1;
}
}
IntIndexPair[] readIntIndexArray(int size) {
IntIndexPair[] array = new IntIndexPair[size];
for (int index = 0; index < size; ++index) {
array[index] = new IntIndexPair(readInt(), index);
}
return array;
}
/////////////////////////////////////////////////////////////////////
static class OutputWriter extends PrintWriter {
final int DEFAULT_PRECISION = 12;
protected int precision;
protected String format, formatWithSpace;
{
precision = DEFAULT_PRECISION;
format = createFormat(precision);
formatWithSpace = format + " ";
}
public OutputWriter(OutputStream out) {
super(out);
}
public OutputWriter(String fileName) throws FileNotFoundException {
super(fileName);
}
public int getPrecision() {
return precision;
}
public void setPrecision(int precision) {
precision = max(0, precision);
this.precision = precision;
format = createFormat(precision);
formatWithSpace = format + " ";
}
private String createFormat(int precision){
return "%." + precision + "f";
}
@Override
public void print(double d){
printf(format, d);
}
public void printWithSpace(double d){
printf(formatWithSpace, d);
}
public void printAll(double...d){
for (int i = 0; i < d.length - 1; ++i){
printWithSpace(d[i]);
}
print(d[d.length - 1]);
}
@Override
public void println(double d){
printlnAll(d);
}
public void printlnAll(double... d){
printAll(d);
println();
}
}
/////////////////////////////////////////////////////////////////////
static class RuntimeIOException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = -6463830523020118289L;
public RuntimeIOException(Throwable cause) {
super(cause);
}
}
/////////////////////////////////////////////////////////////////////
//////////////// Some useful constants and functions ////////////////
/////////////////////////////////////////////////////////////////////
static final int[][] steps = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
static final int[][] steps8 = {
{-1, 0}, {1, 0}, {0, -1}, {0, 1},
{-1, -1}, {1, 1}, {1, -1}, {-1, 1}
};
static final boolean checkCell(int row, int rowsCount, int column, int columnsCount) {
return checkIndex(row, rowsCount) && checkIndex(column, columnsCount);
}
static final boolean checkIndex(int index, int lim){
return (0 <= index && index < lim);
}
/////////////////////////////////////////////////////////////////////
static final boolean checkBit(int mask, int bit){
return (mask & (1 << bit)) != 0;
}
/////////////////////////////////////////////////////////////////////
static final long getSum(int[] array) {
long sum = 0;
for (int value: array) {
sum += value;
}
return sum;
}
static final Point getMinMax(int[] array) {
int min = array[0];
int max = array[0];
for (int index = 0, size = array.length; index < size; ++index, ++index) {
int value = array[index];
if (index == size - 1) {
min = min(min, value);
max = max(max, value);
} else {
int otherValue = array[index + 1];
if (value <= otherValue) {
min = min(min, value);
max = max(max, otherValue);
} else {
min = min(min, otherValue);
max = max(max, value);
}
}
}
return new Point(min, max);
}
/////////////////////////////////////////////////////////////////////
static class IdMap<KeyType> extends HashMap<KeyType, Integer> {
/**
*
*/
private static final long serialVersionUID = -3793737771950984481L;
public IdMap() {
super();
}
int getId(KeyType key) {
Integer id = super.get(key);
if (id == null) {
super.put(key, id = size());
}
return id;
}
}
} | Java | ["4\n1 2 1 2", "3\n1 1 1"] | 2 seconds | ["7 3 0 0", "6 0 0"] | NoteIn the first sample, color 2 is dominant in three intervals: An interval [2, 2] contains one ball. This ball's color is 2 so it's clearly a dominant color. An interval [4, 4] contains one ball, with color 2 again. An interval [2, 4] contains two balls of color 2 and one ball of color 1. There are 7 more intervals and color 1 is dominant in all of them. | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | f292c099e4eac9259a5bc9e42ff6d1b5 | The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — the number of balls. The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ n) where ti is the color of the i-th ball. | 1,500 | Print n integers. The i-th of them should be equal to the number of intervals where i is a dominant color. | standard output | |
PASSED | 2eb4695f377662990892f2eba1a9346c | train_000.jsonl | 1462633500 | Bear Limak has n colored balls, arranged in one long row. Balls are numbered 1 through n, from left to right. There are n possible colors, also numbered 1 through n. The i-th ball has color ti.For a fixed interval (set of consecutive elements) of balls we can define a dominant color. It's a color occurring the biggest number of times in the interval. In case of a tie between some colors, the one with the smallest number (index) is chosen as dominant.There are non-empty intervals in total. For each color, your task is to count the number of intervals in which this color is dominant. | 256 megabytes | import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.util.StringTokenizer;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Igor Kraskevich
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = in.nextInt() - 1;
int[] res = new int[n];
for (int l = 0; l < n; l++) {
int c = 0;
int cnt = 0;
int[] cur = new int[n];
for (int r = l; r < n; r++) {
cur[a[r]]++;
if (cur[a[r]] > cnt || cur[a[r]] == cnt && a[r] < c) {
c = a[r];
cnt = cur[a[r]];
}
res[c]++;
}
}
for (int i = 0; i < n; i++)
out.print(res[i] + " ");
}
}
class FastScanner {
private StringTokenizer tokenizer;
private BufferedReader reader;
public FastScanner(InputStream inputStream) {
reader = new BufferedReader(new InputStreamReader(inputStream));
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
String line = null;
try {
line = reader.readLine();
} catch (IOException e) {
}
if (line == null)
return null;
tokenizer = new StringTokenizer(line);
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
| Java | ["4\n1 2 1 2", "3\n1 1 1"] | 2 seconds | ["7 3 0 0", "6 0 0"] | NoteIn the first sample, color 2 is dominant in three intervals: An interval [2, 2] contains one ball. This ball's color is 2 so it's clearly a dominant color. An interval [4, 4] contains one ball, with color 2 again. An interval [2, 4] contains two balls of color 2 and one ball of color 1. There are 7 more intervals and color 1 is dominant in all of them. | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | f292c099e4eac9259a5bc9e42ff6d1b5 | The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — the number of balls. The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ n) where ti is the color of the i-th ball. | 1,500 | Print n integers. The i-th of them should be equal to the number of intervals where i is a dominant color. | standard output | |
PASSED | 782e364b749db933e5dafdaf0ff43e4e | train_000.jsonl | 1462633500 | Bear Limak has n colored balls, arranged in one long row. Balls are numbered 1 through n, from left to right. There are n possible colors, also numbered 1 through n. The i-th ball has color ti.For a fixed interval (set of consecutive elements) of balls we can define a dominant color. It's a color occurring the biggest number of times in the interval. In case of a tie between some colors, the one with the smallest number (index) is chosen as dominant.There are non-empty intervals in total. For each color, your task is to count the number of intervals in which this color is dominant. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class Main
{
static class Reader
{
private InputStream mIs;private byte[] buf = new byte[1024];private int curChar,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 s(){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 l(){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 i(){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 double d() throws IOException {return Double.parseDouble(s()) ;}
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; }
public int[] arr(int n){int[] ret = new int[n];for (int i = 0; i < n; i++) {ret[i] = i();}return ret;}
}
// |----| /\ | | ----- |
// | / / \ | | | |
// |--/ /----\ |----| | |
// | \ / \ | | | |
// | \ / \ | | ----- -------
public static void main(String[] args)throws IOException
{
PrintWriter out= new PrintWriter(System.out);
Reader sc=new Reader();
int n=sc.i();
int arr[]=sc.arr(n);
int ans[]=new int[n+1];
for(int i=0;i<n;i++)
{
int count[]=new int[n+1];
int maxprev=arr[i];
ans[arr[i]]++;
count[arr[i]]++;
for(int j=i+1;j<n;j++)
{
count[arr[j]]++;
if((count[arr[j]]>count[maxprev])||(count[arr[j]]==count[maxprev]&&arr[j]<maxprev))
maxprev=arr[j];
ans[maxprev]++;
}
}
for(int i=1;i<=n;i++)
out.print(ans[i]+" ");
out.flush();
}
} | Java | ["4\n1 2 1 2", "3\n1 1 1"] | 2 seconds | ["7 3 0 0", "6 0 0"] | NoteIn the first sample, color 2 is dominant in three intervals: An interval [2, 2] contains one ball. This ball's color is 2 so it's clearly a dominant color. An interval [4, 4] contains one ball, with color 2 again. An interval [2, 4] contains two balls of color 2 and one ball of color 1. There are 7 more intervals and color 1 is dominant in all of them. | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | f292c099e4eac9259a5bc9e42ff6d1b5 | The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — the number of balls. The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ n) where ti is the color of the i-th ball. | 1,500 | Print n integers. The i-th of them should be equal to the number of intervals where i is a dominant color. | standard output | |
PASSED | c192bd330f27810ed18dc2ac6bdb2caa | train_000.jsonl | 1462633500 | Bear Limak has n colored balls, arranged in one long row. Balls are numbered 1 through n, from left to right. There are n possible colors, also numbered 1 through n. The i-th ball has color ti.For a fixed interval (set of consecutive elements) of balls we can define a dominant color. It's a color occurring the biggest number of times in the interval. In case of a tie between some colors, the one with the smallest number (index) is chosen as dominant.There are non-empty intervals in total. For each color, your task is to count the number of intervals in which this color is dominant. | 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.StringTokenizer;
public class B {
public static void main(String[] args) throws NumberFormatException, IOException
{
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt();
int[][] count = new int[n + 1][n + 1];
int[] max = new int[n];
int[] ans = new int[n + 1];
for (int i = 0; i < n; i++) {
int cur = sc.nextInt();
for (int j = 0; j <= i; j++) {
count[j][cur]++;
if(count[j][cur] > count[j][max[j]] || count[j][cur] == count[j][max[j]] && cur <= max[j])
max[j] = cur;
ans[max[j]]++;
}
}
for (int i = 1; i <= n; i++)
out.print(ans[i] + " ");
out.println();
out.flush();
}
static 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 String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(next());
}
public long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(next());
}
}
} | Java | ["4\n1 2 1 2", "3\n1 1 1"] | 2 seconds | ["7 3 0 0", "6 0 0"] | NoteIn the first sample, color 2 is dominant in three intervals: An interval [2, 2] contains one ball. This ball's color is 2 so it's clearly a dominant color. An interval [4, 4] contains one ball, with color 2 again. An interval [2, 4] contains two balls of color 2 and one ball of color 1. There are 7 more intervals and color 1 is dominant in all of them. | Java 8 | standard input | [
"data structures",
"implementation",
"brute force"
] | f292c099e4eac9259a5bc9e42ff6d1b5 | The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — the number of balls. The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ n) where ti is the color of the i-th ball. | 1,500 | Print n integers. The i-th of them should be equal to the number of intervals where i is a dominant color. | standard output | |
PASSED | 60f68c7aba75d9b723ef5d8566aae6b3 | train_000.jsonl | 1556989500 | Inaka has a disc, the circumference of which is $$$n$$$ units. The circumference is equally divided by $$$n$$$ points numbered clockwise from $$$1$$$ to $$$n$$$, such that points $$$i$$$ and $$$i + 1$$$ ($$$1 \leq i < n$$$) are adjacent, and so are points $$$n$$$ and $$$1$$$.There are $$$m$$$ straight segments on the disc, the endpoints of which are all among the aforementioned $$$n$$$ points.Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer $$$k$$$ ($$$1 \leq k < n$$$), such that if all segments are rotated clockwise around the center of the circle by $$$k$$$ units, the new image will be the same as the original one. | 256 megabytes |
import java.util.HashSet;
import java.util.Scanner;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Andy Phan
*/
public class p1161b {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int k = in.nextInt();
int[][] arr = new int[k][2];
HashSet<Integer>[] set = new HashSet[n];
for(int i = 0; i < n; i++) {
set[i] = new HashSet<>();
}
for(int i = 0; i < k; i++) {
arr[i][0] = in.nextInt()-1;
arr[i][1] = in.nextInt()-1;
set[arr[i][0]].add(arr[i][1]);
set[arr[i][1]].add(arr[i][0]);
}
outer: for(int i = 1; i < n; i++) {
if(n%i != 0) continue;
for(int j = 0; j < k; j++) {
if(!set[(arr[j][0]+i)%n].contains((arr[j][1]+i)%n)) continue outer;
}
System.out.println("Yes");
return;
}
System.out.println("No");
}
}
| Java | ["12 6\n1 3\n3 7\n5 7\n7 11\n9 11\n11 3", "9 6\n4 5\n5 6\n7 8\n8 9\n1 2\n2 3", "10 3\n1 2\n3 2\n7 2", "10 2\n1 6\n2 7"] | 3 seconds | ["Yes", "Yes", "No", "Yes"] | NoteThe first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of $$$120$$$ degrees around the center. | Java 8 | standard input | [
"implementation",
"hashing",
"strings"
] | dd7a7a4e5feb50ab6abb93d90c559c2b | The first line contains two space-separated integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 100\,000$$$, $$$1 \leq m \leq 200\,000$$$) — the number of points and the number of segments, respectively. The $$$i$$$-th of the following $$$m$$$ lines contains two space-separated integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \leq a_i, b_i \leq n$$$, $$$a_i \neq b_i$$$) that describe a segment connecting points $$$a_i$$$ and $$$b_i$$$. It is guaranteed that no segments coincide. | 1,900 | Output one line — "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks). You can output each letter in any case (upper or lower). | standard output | |
PASSED | cc1869fd5a85024f648c59818c578fc7 | train_000.jsonl | 1556989500 | Inaka has a disc, the circumference of which is $$$n$$$ units. The circumference is equally divided by $$$n$$$ points numbered clockwise from $$$1$$$ to $$$n$$$, such that points $$$i$$$ and $$$i + 1$$$ ($$$1 \leq i < n$$$) are adjacent, and so are points $$$n$$$ and $$$1$$$.There are $$$m$$$ straight segments on the disc, the endpoints of which are all among the aforementioned $$$n$$$ points.Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer $$$k$$$ ($$$1 \leq k < n$$$), such that if all segments are rotated clockwise around the center of the circle by $$$k$$$ units, the new image will be the same as the original one. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.AbstractList;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.util.Collections;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
int N;
Node[] nodes;
public void solve(int testNumber, InputReader in, PrintWriter out) {
N = in.nextInt();
int M = in.nextInt();
nodes = new Node[N];
for (int i = 0; i < N; i++) {
nodes[i] = new Node(i);
}
for (int i = 0; i < M; i++) {
int a = in.nextInt() - 1;
int b = in.nextInt() - 1;
nodes[a].add(b);
nodes[b].add(a);
}
for (int i = 0; i < N; i++) {
nodes[i].setUp();
}
if (works(1)) {
out.println("Yes");
return;
}
for (int i = 2; i <= Math.sqrt(N); i++) {
if (N % i == 0) {
if (works(i) || works(N / i)) {
out.println("Yes");
return;
}
}
}
out.println("No");
}
boolean works(int r) {
for (int i = 0; i < r; i++) {
for (int j = i + r; j < N; j += r) {
if (nodes[j].hash != nodes[j - r].hash) {
return false;
}
}
}
return true;
}
class Node {
ArrayList<Integer> arr = new ArrayList<>();
int id;
int hash;
Node(int id) {
this.id = id;
}
void add(int val) {
if (val > id) {
arr.add(val - id);
} else {
arr.add(N - id + val);
}
}
void setUp() {
Collections.sort(arr);
hash = arr.hashCode();
}
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 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());
}
}
}
| Java | ["12 6\n1 3\n3 7\n5 7\n7 11\n9 11\n11 3", "9 6\n4 5\n5 6\n7 8\n8 9\n1 2\n2 3", "10 3\n1 2\n3 2\n7 2", "10 2\n1 6\n2 7"] | 3 seconds | ["Yes", "Yes", "No", "Yes"] | NoteThe first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of $$$120$$$ degrees around the center. | Java 8 | standard input | [
"implementation",
"hashing",
"strings"
] | dd7a7a4e5feb50ab6abb93d90c559c2b | The first line contains two space-separated integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 100\,000$$$, $$$1 \leq m \leq 200\,000$$$) — the number of points and the number of segments, respectively. The $$$i$$$-th of the following $$$m$$$ lines contains two space-separated integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \leq a_i, b_i \leq n$$$, $$$a_i \neq b_i$$$) that describe a segment connecting points $$$a_i$$$ and $$$b_i$$$. It is guaranteed that no segments coincide. | 1,900 | Output one line — "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks). You can output each letter in any case (upper or lower). | standard output | |
PASSED | 53de0c47044d5c0f385aac28501aab0f | train_000.jsonl | 1556989500 | Inaka has a disc, the circumference of which is $$$n$$$ units. The circumference is equally divided by $$$n$$$ points numbered clockwise from $$$1$$$ to $$$n$$$, such that points $$$i$$$ and $$$i + 1$$$ ($$$1 \leq i < n$$$) are adjacent, and so are points $$$n$$$ and $$$1$$$.There are $$$m$$$ straight segments on the disc, the endpoints of which are all among the aforementioned $$$n$$$ points.Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer $$$k$$$ ($$$1 \leq k < n$$$), such that if all segments are rotated clockwise around the center of the circle by $$$k$$$ units, the new image will be the same as the original one. | 256 megabytes | //package que_b;
import java.io.*;
import java.util.*;
import java.math.*;
public class utkarsh {
InputStream is;
PrintWriter out;
long mod = (long)(1e9 + 7), inf = (long)(3e18);
int[] z_Algo(ArrayList <Integer> d) {
int n = d.size();
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 && (int)d.get(r) == (int)d.get(r - l)) 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 && (int)d.get(r) == (int)d.get(r - l)) r++;
z[i] = r - l; r--;
}
}
}
return z;
}
void solve() {
int n = ni(), m = ni();
ArrayList <Integer> a[] = new ArrayList[n];
for(int i = 0; i < n; i++) a[i] = new ArrayList<>();
for(int i = 0; i < m; i++) {
int u = ni() - 1, v = ni() - 1;
if(u > v) {
u ^= v; v ^= u; u ^= v;
}
int d = Math.min(v - u, n - v + u);
a[u].add(d);
a[v].add(d);
}
for(int i = 0; i < n; i++) Collections.sort(a[i]);
ArrayList <Integer> d = new ArrayList<>();
for(int i = 0; i < n; i++) {
if(a[i].isEmpty()) d.add(-1);
for(int x : a[i]) d.add(x);
}
int z[] = z_Algo(d);
n = d.size();
for(int i = 1; i < n; i++) {
if(i + z[i] == n && (n % i) == 0) {
out.println("Yes"); return;
}
}
out.println("No");
}
long mp(long b, long e, long mod) {
b %= mod;
long r = 1;
while(e > 0) {
if((e & 1) == 1) {
r *= b; r %= mod;
}
b *= b; b %= mod;
e >>= 1;
}
return r;
}
//---------- I/O Template ----------
public static void main(String[] args) { new utkarsh().run(); }
void run() {
is = System.in;
out = new PrintWriter(System.out);
solve();
out.flush();
}
byte input[] = new byte[1024];
int len = 0, ptr = 0;
int readByte() {
if(ptr >= len) { ptr = 0;
try { len = is.read(input); }
catch(IOException e) { throw new InputMismatchException(); }
if(len <= 0) { return -1; }
} return input[ptr++];
}
boolean isSpaceChar(int c) { return !( c >= 33 && c <= 126 ); }
int skip() {
int b = readByte();
while(b != -1 && isSpaceChar(b)) { b = readByte(); }
return b;
}
char nc() { return (char)skip(); }
String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while(!isSpaceChar(b)) { sb.appendCodePoint(b); b = readByte(); }
return sb.toString();
}
String nLine() {
int b = skip();
StringBuilder sb = new StringBuilder();
while( !(isSpaceChar(b) && b != ' ') ) { sb.appendCodePoint(b); b = readByte(); }
return sb.toString();
}
int ni() {
int n = 0, b = readByte();
boolean minus = false;
while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')) { b = readByte(); }
if(b == '-') { minus = true; b = readByte(); }
if(b == -1) { return -1; } //no input
while(b >= '0' && b <= '9') { n = n * 10 + (b - '0'); b = readByte(); }
return minus ? -n : n;
}
long nl() {
long n = 0L; int b = readByte();
boolean minus = false;
while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')) { b = readByte(); }
if(b == '-') { minus = true; b = readByte(); }
while(b >= '0' && b <= '9') { n = n * 10 + (b - '0'); b = readByte(); }
return minus ? -n : n;
}
double nd() { return Double.parseDouble(ns()); }
float nf() { return Float.parseFloat(ns()); }
int[] na(int n) {
int a[] = new int[n];
for(int i = 0; i < n; i++) { a[i] = ni(); }
return a;
}
char[] ns(int n) {
char c[] = new char[n];
int i, b = skip();
for(i = 0; i < n; i++) {
if(isSpaceChar(b)) { break; }
c[i] = (char)b; b = readByte();
} return i == n ? c : Arrays.copyOf(c,i);
}
} | Java | ["12 6\n1 3\n3 7\n5 7\n7 11\n9 11\n11 3", "9 6\n4 5\n5 6\n7 8\n8 9\n1 2\n2 3", "10 3\n1 2\n3 2\n7 2", "10 2\n1 6\n2 7"] | 3 seconds | ["Yes", "Yes", "No", "Yes"] | NoteThe first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of $$$120$$$ degrees around the center. | Java 8 | standard input | [
"implementation",
"hashing",
"strings"
] | dd7a7a4e5feb50ab6abb93d90c559c2b | The first line contains two space-separated integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 100\,000$$$, $$$1 \leq m \leq 200\,000$$$) — the number of points and the number of segments, respectively. The $$$i$$$-th of the following $$$m$$$ lines contains two space-separated integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \leq a_i, b_i \leq n$$$, $$$a_i \neq b_i$$$) that describe a segment connecting points $$$a_i$$$ and $$$b_i$$$. It is guaranteed that no segments coincide. | 1,900 | Output one line — "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks). You can output each letter in any case (upper or lower). | standard output | |
PASSED | 37d8e43171f94ea16f089958da24a078 | train_000.jsonl | 1556989500 | Inaka has a disc, the circumference of which is $$$n$$$ units. The circumference is equally divided by $$$n$$$ points numbered clockwise from $$$1$$$ to $$$n$$$, such that points $$$i$$$ and $$$i + 1$$$ ($$$1 \leq i < n$$$) are adjacent, and so are points $$$n$$$ and $$$1$$$.There are $$$m$$$ straight segments on the disc, the endpoints of which are all among the aforementioned $$$n$$$ points.Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer $$$k$$$ ($$$1 \leq k < n$$$), such that if all segments are rotated clockwise around the center of the circle by $$$k$$$ units, the new image will be the same as the original one. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class B {
public static void main(String[] args) throws IOException {
/**/
Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
/*/
Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(new FileInputStream("src/b.in"))));
/**/
int n = sc.nextInt();
int m = sc.nextInt();
ArrayList<ArrayList<Integer>> segs = new ArrayList<>();
for (int i = 0; i < n; i++)
segs.add(new ArrayList<>());
for (int i = 0; i < m; i++) {
int a = sc.nextInt()-1;
int b = sc.nextInt()-1;
segs.get(a).add((b+n-a)%n);
segs.get(b).add((a+n-b)%n);
}
for (int i = 0; i < n; i++) {
Collections.sort(segs.get(i));
}
HashSet<Integer> poss = new HashSet<>();
for (int i = 1; i < n; i++) {
if (n%i==0 && arrEq(segs.get(0),segs.get(i)))
poss.add(i);
}
ArrayDeque<Integer> imp = new ArrayDeque<>();
for (int i = 1; i < n; i++) {
for (int num : poss) {
if (!arrEq(segs.get(i), segs.get((i+num)%n)))
imp.add(num);
}
while (!imp.isEmpty())
poss.remove(imp.removeFirst());
}
System.out.println(poss.isEmpty()?"No":"Yes");
}
public static boolean arrEq(ArrayList<Integer> a, ArrayList<Integer> b) {
if (a.size()!=b.size())
return false;
for (int i = 0; i < a.size(); i++) {
if (!a.get(i).equals(b.get(i)))
return false;
}
return true;
}
} | Java | ["12 6\n1 3\n3 7\n5 7\n7 11\n9 11\n11 3", "9 6\n4 5\n5 6\n7 8\n8 9\n1 2\n2 3", "10 3\n1 2\n3 2\n7 2", "10 2\n1 6\n2 7"] | 3 seconds | ["Yes", "Yes", "No", "Yes"] | NoteThe first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of $$$120$$$ degrees around the center. | Java 8 | standard input | [
"implementation",
"hashing",
"strings"
] | dd7a7a4e5feb50ab6abb93d90c559c2b | The first line contains two space-separated integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 100\,000$$$, $$$1 \leq m \leq 200\,000$$$) — the number of points and the number of segments, respectively. The $$$i$$$-th of the following $$$m$$$ lines contains two space-separated integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \leq a_i, b_i \leq n$$$, $$$a_i \neq b_i$$$) that describe a segment connecting points $$$a_i$$$ and $$$b_i$$$. It is guaranteed that no segments coincide. | 1,900 | Output one line — "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks). You can output each letter in any case (upper or lower). | standard output | |
PASSED | aa24a2ecfe3fa12948f3def3fb9fe7a3 | train_000.jsonl | 1556989500 | Inaka has a disc, the circumference of which is $$$n$$$ units. The circumference is equally divided by $$$n$$$ points numbered clockwise from $$$1$$$ to $$$n$$$, such that points $$$i$$$ and $$$i + 1$$$ ($$$1 \leq i < n$$$) are adjacent, and so are points $$$n$$$ and $$$1$$$.There are $$$m$$$ straight segments on the disc, the endpoints of which are all among the aforementioned $$$n$$$ points.Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer $$$k$$$ ($$$1 \leq k < n$$$), such that if all segments are rotated clockwise around the center of the circle by $$$k$$$ units, the new image will be the same as the original one. | 256 megabytes |
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.*;
public class CFCT1161 {
public static void main(String[] args) throws Exception {
boolean local = System.getProperty("ONLINE_JUDGE") == null;
boolean async = false;
Charset charset = Charset.forName("ascii");
FastIO io = local ? new FastIO(new FileInputStream("D:\\DATABASE\\TESTCASE\\Code.in"), System.out, charset) : new FastIO(System.in, System.out, charset);
Task task = new Task(io, new Debug(local));
if (async) {
Thread t = new Thread(null, task, "dalt", 1 << 27);
t.setPriority(Thread.MAX_PRIORITY);
t.start();
t.join();
} else {
task.run();
}
if (local) {
io.cache.append("\n\n--memory -- \n" + ((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20) + "M");
}
io.flush();
}
public static class Task implements Runnable {
final FastIO io;
final Debug debug;
int inf = (int) 1e8;
int mod = (int) 1e9 + 7;
public int mod(int val) {
val %= mod;
if (val < 0) {
val += mod;
}
return val;
}
public int mod(long val) {
val %= mod;
if (val < 0) {
val += mod;
}
return (int) val;
}
int bitAt(int x, int i) {
return (x >> i) & 1;
}
int bitAt(long x, int i) {
return (int) ((x >> i) & 1);
}
public Task(FastIO io, Debug debug) {
this.io = io;
this.debug = debug;
}
@Override
public void run() {
solve();
}
public void solve() {
int n = io.readInt();
int m = io.readInt();
List<Integer> factors = new ArrayList<>();
for (int i = 1; i < n; i++) {
if (n % i != 0) {
continue;
}
factors.add(i);
}
Set<Long> set = new LinkedHashSet<>();
for (int i = 0; i < m; i++) {
int a = io.readInt() - 1;
int b = io.readInt() - 1;
set.add(combine(a, b));
}
for (int f : factors) {
boolean flag = true;
for (long line : set) {
long a = line >>> 32;
long b = line & 0xffffffffL;
if (!set.contains(combine((a + f) % n, (b + f) % n))) {
flag = false;
break;
}
}
if (flag) {
io.cache.append("Yes");
return;
}
}
io.cache.append("No");
}
public long combine(long a, long b) {
if (a <= b) {
return (a << 32) | b;
} else {
return (b << 32) | a;
}
}
}
public static class FastIO {
public final StringBuilder cache = new StringBuilder();
private final InputStream is;
private final OutputStream os;
private final Charset charset;
private StringBuilder defaultStringBuf = new StringBuilder(1 << 8);
private byte[] buf = new byte[1 << 13];
private int bufLen;
private int bufOffset;
private int next;
public FastIO(InputStream is, OutputStream os, Charset charset) {
this.is = is;
this.os = os;
this.charset = charset;
}
public FastIO(InputStream is, OutputStream os) {
this(is, os, Charset.forName("ascii"));
}
private int read() {
while (bufLen == bufOffset) {
bufOffset = 0;
try {
bufLen = is.read(buf);
} catch (IOException e) {
throw new RuntimeException(e);
}
if (bufLen == -1) {
return -1;
}
}
return buf[bufOffset++];
}
public void skipBlank() {
while (next >= 0 && next <= 32) {
next = read();
}
}
public int readInt() {
int sign = 1;
skipBlank();
if (next == '+' || next == '-') {
sign = next == '+' ? 1 : -1;
next = read();
}
int val = 0;
if (sign == 1) {
while (next >= '0' && next <= '9') {
val = val * 10 + next - '0';
next = read();
}
} else {
while (next >= '0' && next <= '9') {
val = val * 10 - next + '0';
next = read();
}
}
return val;
}
public long readLong() {
int sign = 1;
skipBlank();
if (next == '+' || next == '-') {
sign = next == '+' ? 1 : -1;
next = read();
}
long val = 0;
if (sign == 1) {
while (next >= '0' && next <= '9') {
val = val * 10 + next - '0';
next = read();
}
} else {
while (next >= '0' && next <= '9') {
val = val * 10 - next + '0';
next = read();
}
}
return val;
}
public double readDouble() {
boolean sign = true;
skipBlank();
if (next == '+' || next == '-') {
sign = next == '+';
next = read();
}
long val = 0;
while (next >= '0' && next <= '9') {
val = val * 10 + next - '0';
next = read();
}
if (next != '.') {
return sign ? val : -val;
}
next = read();
long radix = 1;
long point = 0;
while (next >= '0' && next <= '9') {
point = point * 10 + next - '0';
radix = radix * 10;
next = read();
}
double result = val + (double) point / radix;
return sign ? result : -result;
}
public String readString(StringBuilder builder) {
skipBlank();
while (next > 32) {
builder.append((char) next);
next = read();
}
return builder.toString();
}
public String readString() {
defaultStringBuf.setLength(0);
return readString(defaultStringBuf);
}
public int readLine(char[] data, int offset) {
int originalOffset = offset;
while (next != -1 && next != '\n') {
data[offset++] = (char) next;
next = read();
}
return offset - originalOffset;
}
public int readString(char[] data, int offset) {
skipBlank();
int originalOffset = offset;
while (next > 32) {
data[offset++] = (char) next;
next = read();
}
return offset - originalOffset;
}
public int readString(byte[] data, int offset) {
skipBlank();
int originalOffset = offset;
while (next > 32) {
data[offset++] = (byte) next;
next = read();
}
return offset - originalOffset;
}
public char readChar() {
skipBlank();
char c = (char) next;
next = read();
return c;
}
public void flush() {
try {
os.write(cache.toString().getBytes(charset));
os.flush();
cache.setLength(0);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public boolean hasMore() {
skipBlank();
return next != -1;
}
}
public static class Debug {
private boolean allowDebug;
public Debug(boolean allowDebug) {
this.allowDebug = allowDebug;
}
public void assertTrue(boolean flag) {
if (!allowDebug) {
return;
}
if (!flag) {
fail();
}
}
public void fail() {
throw new RuntimeException();
}
public void assertFalse(boolean flag) {
if (!allowDebug) {
return;
}
if (flag) {
fail();
}
}
private void outputName(String name) {
System.out.print(name + " = ");
}
public void debug(String name, int x) {
if (!allowDebug) {
return;
}
outputName(name);
System.out.println("" + x);
}
public void debug(String name, long x) {
if (!allowDebug) {
return;
}
outputName(name);
System.out.println("" + x);
}
public void debug(String name, double x) {
if (!allowDebug) {
return;
}
outputName(name);
System.out.println("" + x);
}
public void debug(String name, int[] x) {
if (!allowDebug) {
return;
}
outputName(name);
System.out.println(Arrays.toString(x));
}
public void debug(String name, long[] x) {
if (!allowDebug) {
return;
}
outputName(name);
System.out.println(Arrays.toString(x));
}
public void debug(String name, double[] x) {
if (!allowDebug) {
return;
}
outputName(name);
System.out.println(Arrays.toString(x));
}
public void debug(String name, Object x) {
if (!allowDebug) {
return;
}
outputName(name);
System.out.println("" + x);
}
public void debug(String name, Object... x) {
if (!allowDebug) {
return;
}
outputName(name);
System.out.println(Arrays.deepToString(x));
}
}
public static class Mathematics {
public static int ceilPowerOf2(int x) {
return 32 - Integer.numberOfLeadingZeros(x - 1);
}
public static int floorPowerOf2(int x) {
return 31 - Integer.numberOfLeadingZeros(x);
}
public static long modmul(long a, long b, long mod) {
return b == 0 ? 0 : ((modmul(a, b >> 1, mod) << 1) % mod + a * (b & 1)) % mod;
}
/**
* Get the greatest common divisor of a and b
*/
public static int gcd(int a, int b) {
return a >= b ? gcd0(a, b) : gcd0(b, a);
}
private static int gcd0(int a, int b) {
return b == 0 ? a : gcd0(b, a % b);
}
public static int extgcd(int a, int b, int[] coe) {
if (a >= b) {
return extgcd0(a, b, coe);
} else {
int g = extgcd0(b, a, coe);
int tmp = coe[0];
coe[0] = coe[1];
coe[1] = tmp;
return g;
}
}
private static int extgcd0(int a, int b, int[] coe) {
if (b == 0) {
coe[0] = 1;
coe[1] = 0;
return a;
}
int g = extgcd0(b, a % b, coe);
int n = coe[0];
int m = coe[1];
coe[0] = m;
coe[1] = n - m * (a / b);
return g;
}
/**
* Get the greatest common divisor of a and b
*/
public static long gcd(long a, long b) {
return a >= b ? gcd0(a, b) : gcd0(b, a);
}
private static long gcd0(long a, long b) {
return b == 0 ? a : gcd0(b, a % b);
}
public static long extgcd(long a, long b, long[] coe) {
if (a >= b) {
return extgcd0(a, b, coe);
} else {
long g = extgcd0(b, a, coe);
long tmp = coe[0];
coe[0] = coe[1];
coe[1] = tmp;
return g;
}
}
private static long extgcd0(long a, long b, long[] coe) {
if (b == 0) {
coe[0] = 1;
coe[1] = 0;
return a;
}
long g = extgcd0(b, a % b, coe);
long n = coe[0];
long m = coe[1];
coe[0] = m;
coe[1] = n - m * (a / b);
return g;
}
/**
* Get y where x * y = 1 (% mod)
*/
public static int inverse(int x, int mod) {
return pow(x, mod - 2, mod);
}
/**
* Get x^n(% mod)
*/
public static int pow(int x, int n, int mod) {
int bit = 31 - Integer.numberOfLeadingZeros(n);
long product = 1;
for (; bit >= 0; bit--) {
product = product * product % mod;
if (((1 << bit) & n) != 0) {
product = product * x % mod;
}
}
return (int) product;
}
public static long longpow(long x, long n, long mod) {
if (n == 0) {
return 1;
}
long prod = longpow(x, n >> 1, mod);
prod = modmul(prod, prod, mod);
if ((n & 1) == 1) {
prod = modmul(prod, x, mod);
}
return prod;
}
/**
* Get x % mod
*/
public static int mod(int x, int mod) {
x %= mod;
if (x < 0) {
x += mod;
}
return x;
}
public static int mod(long x, int mod) {
x %= mod;
if (x < 0) {
x += mod;
}
return (int) x;
}
/**
* Get n!/(n-m)!
*/
public static long permute(int n, int m) {
return m == 0 ? 1 : n * permute(n - 1, m - 1);
}
/**
* Put all primes less or equal to limit into primes after offset
*/
public static int eulerSieve(int limit, int[] primes, int offset) {
boolean[] isComp = new boolean[limit + 1];
int wpos = offset;
for (int i = 2; i <= limit; i++) {
if (!isComp[i]) {
primes[wpos++] = i;
}
for (int j = offset, until = limit / i; j < wpos && primes[j] <= until; j++) {
int pi = primes[j] * i;
isComp[pi] = true;
if (i % primes[j] == 0) {
break;
}
}
}
return wpos - offset;
}
/**
* Round x into integer
*/
public static int intRound(double x) {
if (x < 0) {
return -(int) (-x + 0.5);
}
return (int) (x + 0.5);
}
/**
* Round x into long
*/
public static long longRound(double x) {
if (x < 0) {
return -(long) (-x + 0.5);
}
return (long) (x + 0.5);
}
}
public static class Randomized {
static Random random = new Random(12345678);
public static double nextDouble(double min, double max) {
return random.nextDouble() * (max - min) + min;
}
public static void randomizedArray(int[] data, int from, int to) {
to--;
for (int i = from; i <= to; i++) {
int s = nextInt(i, to);
int tmp = data[i];
data[i] = data[s];
data[s] = tmp;
}
}
public static void randomizedArray(long[] data, int from, int to) {
to--;
for (int i = from; i <= to; i++) {
int s = nextInt(i, to);
long tmp = data[i];
data[i] = data[s];
data[s] = tmp;
}
}
public static void randomizedArray(double[] data, int from, int to) {
to--;
for (int i = from; i <= to; i++) {
int s = nextInt(i, to);
double tmp = data[i];
data[i] = data[s];
data[s] = tmp;
}
}
public static void randomizedArray(float[] data, int from, int to) {
to--;
for (int i = from; i <= to; i++) {
int s = nextInt(i, to);
float tmp = data[i];
data[i] = data[s];
data[s] = tmp;
}
}
public static <T> void randomizedArray(T[] data, int from, int to) {
to--;
for (int i = from; i <= to; i++) {
int s = nextInt(i, to);
T tmp = data[i];
data[i] = data[s];
data[s] = tmp;
}
}
public static int nextInt(int l, int r) {
return random.nextInt(r - l + 1) + l;
}
}
} | Java | ["12 6\n1 3\n3 7\n5 7\n7 11\n9 11\n11 3", "9 6\n4 5\n5 6\n7 8\n8 9\n1 2\n2 3", "10 3\n1 2\n3 2\n7 2", "10 2\n1 6\n2 7"] | 3 seconds | ["Yes", "Yes", "No", "Yes"] | NoteThe first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of $$$120$$$ degrees around the center. | Java 8 | standard input | [
"implementation",
"hashing",
"strings"
] | dd7a7a4e5feb50ab6abb93d90c559c2b | The first line contains two space-separated integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 100\,000$$$, $$$1 \leq m \leq 200\,000$$$) — the number of points and the number of segments, respectively. The $$$i$$$-th of the following $$$m$$$ lines contains two space-separated integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \leq a_i, b_i \leq n$$$, $$$a_i \neq b_i$$$) that describe a segment connecting points $$$a_i$$$ and $$$b_i$$$. It is guaranteed that no segments coincide. | 1,900 | Output one line — "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks). You can output each letter in any case (upper or lower). | standard output | |
PASSED | f8484e78709aa005f1eff05df26fb0c0 | train_000.jsonl | 1556989500 | Inaka has a disc, the circumference of which is $$$n$$$ units. The circumference is equally divided by $$$n$$$ points numbered clockwise from $$$1$$$ to $$$n$$$, such that points $$$i$$$ and $$$i + 1$$$ ($$$1 \leq i < n$$$) are adjacent, and so are points $$$n$$$ and $$$1$$$.There are $$$m$$$ straight segments on the disc, the endpoints of which are all among the aforementioned $$$n$$$ points.Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer $$$k$$$ ($$$1 \leq k < n$$$), such that if all segments are rotated clockwise around the center of the circle by $$$k$$$ units, the new image will be the same as the original one. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.io.UncheckedIOException;
import java.nio.charset.Charset;
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
*
* @author mikit
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
LightScanner in = new LightScanner(inputStream);
LightWriter out = new LightWriter(outputStream);
BChladniFigure solver = new BChladniFigure();
solver.solve(1, in, out);
out.close();
}
static class BChladniFigure {
public void solve(int testNumber, LightScanner in, LightWriter out) {
// out.setBoolLabel(LightWriter.BoolLabel.YES_NO_FIRST_UP);
int n = in.ints(), m = in.ints();
HashSet<BChladniFigure.Edge> edges = new HashSet<>();
for (int i = 0; i < m; i++) {
int x = in.ints() - 1, y = in.ints() - 1;
edges.add(new BChladniFigure.Edge(x, y));
}
outer:
for (int k = 1; k < n; k++) {
if (n % k != 0) continue;
for (BChladniFigure.Edge e : edges) {
BChladniFigure.Edge corsp = new BChladniFigure.Edge((e.x + k) % n, (e.y + k) % n);
if (!edges.contains(corsp)) continue outer;
}
out.yesln();
return;
}
out.noln();
}
private static class Edge {
int x;
int y;
public Edge(int x, int y) {
this.x = Math.min(x, y);
this.y = Math.max(x, y);
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
BChladniFigure.Edge edge = (BChladniFigure.Edge) o;
if (x != edge.x) return false;
return y == edge.y;
}
public int hashCode() {
int result = x;
result = 31 * result + y;
return result;
}
}
}
static class LightWriter implements AutoCloseable {
private final Writer out;
private boolean autoflush = false;
private boolean breaked = true;
private LightWriter.BoolLabel boolLabel = LightWriter.BoolLabel.YES_NO_FIRST_UP;
public LightWriter(Writer out) {
this.out = out;
}
public LightWriter(OutputStream out) {
this(new BufferedWriter(new OutputStreamWriter(out, Charset.defaultCharset())));
}
public LightWriter print(char c) {
try {
out.write(c);
breaked = false;
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
return this;
}
public LightWriter print(String s) {
try {
out.write(s, 0, s.length());
breaked = false;
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
return this;
}
public LightWriter ans(String s) {
if (!breaked) {
print(' ');
}
return print(s);
}
public LightWriter ans(boolean b) {
return ans(boolLabel.transfer(b));
}
public LightWriter yesln() {
return ans(true).ln();
}
public LightWriter noln() {
return ans(false).ln();
}
public LightWriter ln() {
print(System.lineSeparator());
breaked = true;
if (autoflush) {
try {
out.flush();
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
return this;
}
public void close() {
try {
out.close();
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
public enum BoolLabel {
YES_NO_FIRST_UP("Yes", "No"),
YES_NO_ALL_UP("YES", "NO"),
YES_NO_ALL_DOWN("yes", "no"),
POSSIBLE_IMPOSSIBLE_FIRST_UP("Possible", "Impossible"),
POSSIBLE_IMPOSSIBLE_ALL_UP("POSSIBLE", "IMPOSSIBLE"),
POSSIBLE_IMPOSSIBLE_ALL_DOWN("possible", "impossible"),
FIRST_SECOND_FIRST_UP("First", "Second"),
;
private final String positive;
private final String negative;
BoolLabel(String positive, String negative) {
this.positive = positive;
this.negative = negative;
}
private String transfer(boolean f) {
return f ? positive : negative;
}
}
}
static class LightScanner {
private BufferedReader reader = null;
private StringTokenizer tokenizer = null;
public LightScanner(InputStream in) {
reader = new BufferedReader(new InputStreamReader(in));
}
public String string() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
return tokenizer.nextToken();
}
public int ints() {
return Integer.parseInt(string());
}
}
}
| Java | ["12 6\n1 3\n3 7\n5 7\n7 11\n9 11\n11 3", "9 6\n4 5\n5 6\n7 8\n8 9\n1 2\n2 3", "10 3\n1 2\n3 2\n7 2", "10 2\n1 6\n2 7"] | 3 seconds | ["Yes", "Yes", "No", "Yes"] | NoteThe first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of $$$120$$$ degrees around the center. | Java 8 | standard input | [
"implementation",
"hashing",
"strings"
] | dd7a7a4e5feb50ab6abb93d90c559c2b | The first line contains two space-separated integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 100\,000$$$, $$$1 \leq m \leq 200\,000$$$) — the number of points and the number of segments, respectively. The $$$i$$$-th of the following $$$m$$$ lines contains two space-separated integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \leq a_i, b_i \leq n$$$, $$$a_i \neq b_i$$$) that describe a segment connecting points $$$a_i$$$ and $$$b_i$$$. It is guaranteed that no segments coincide. | 1,900 | Output one line — "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks). You can output each letter in any case (upper or lower). | standard output | |
PASSED | 4a939e8299f38c80757195da06eb917c | train_000.jsonl | 1556989500 | Inaka has a disc, the circumference of which is $$$n$$$ units. The circumference is equally divided by $$$n$$$ points numbered clockwise from $$$1$$$ to $$$n$$$, such that points $$$i$$$ and $$$i + 1$$$ ($$$1 \leq i < n$$$) are adjacent, and so are points $$$n$$$ and $$$1$$$.There are $$$m$$$ straight segments on the disc, the endpoints of which are all among the aforementioned $$$n$$$ points.Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer $$$k$$$ ($$$1 \leq k < n$$$), such that if all segments are rotated clockwise around the center of the circle by $$$k$$$ units, the new image will be the same as the original one. | 256 megabytes | import java.io.*;
import java.util.*;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
int n, m;
Map<Integer, Set<Integer>> segments;
public void solve(int testNumber, InputReader in, PrintWriter out) {
n = in.nextInt();
m = in.nextInt();
segments = new HashMap<>();
for (int i = 0; i < m; i++) {
Integer a;
Integer c = in.nextInt() - 1;
Integer b = in.nextInt() - 1;
a = Math.min(c, b);
b = Math.max(c, b);
if (!segments.containsKey(a)) {
segments.put(a, new HashSet<>());
}
if (!segments.containsKey(b)) {
segments.put(b, new HashSet<>());
}
if(!segments.get(a).contains(b-a)) {
segments.get(a).add(b - a);
}
if(!segments.get(b).contains((a - b + n)%n)) {
segments.get(b).add((a - b + n)%n);
}
}
Boolean[] isPrime = new Boolean[n + 1];
for (int i = 0; i <= n; i++) {
isPrime[i] = true;
}
//求小于n的质数
for (int i = 2; i <= n; i++) {
if (isPrime[i]) {
for (int j = 2; i * j <= n; j++) {
isPrime[i * j] = false;
}
}
}
//遍历所有质数,求商,商即旋转角度
for (int i = 2; i <= n; i++) {
if (isPrime[i] && (n % i == 0)) {
int angle = n / i;
boolean allSegmentMatch = true;
for (int j = 0; j < n; j++) {
Set<Integer> remoteBefore = segments.get(j);
Set<Integer> remoteAfter = segments.get((j+angle)%n);
if(remoteBefore == null && remoteAfter != null) {
allSegmentMatch = false;
break;
}
if (remoteBefore!=null && !remoteBefore.equals(remoteAfter)) {
allSegmentMatch = false;
break;
}
}
if (allSegmentMatch) {
out.println("Yes");
return;
}
}
}
out.println("No");
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 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());
}
}
}
| Java | ["12 6\n1 3\n3 7\n5 7\n7 11\n9 11\n11 3", "9 6\n4 5\n5 6\n7 8\n8 9\n1 2\n2 3", "10 3\n1 2\n3 2\n7 2", "10 2\n1 6\n2 7"] | 3 seconds | ["Yes", "Yes", "No", "Yes"] | NoteThe first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of $$$120$$$ degrees around the center. | Java 8 | standard input | [
"implementation",
"hashing",
"strings"
] | dd7a7a4e5feb50ab6abb93d90c559c2b | The first line contains two space-separated integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 100\,000$$$, $$$1 \leq m \leq 200\,000$$$) — the number of points and the number of segments, respectively. The $$$i$$$-th of the following $$$m$$$ lines contains two space-separated integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \leq a_i, b_i \leq n$$$, $$$a_i \neq b_i$$$) that describe a segment connecting points $$$a_i$$$ and $$$b_i$$$. It is guaranteed that no segments coincide. | 1,900 | Output one line — "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks). You can output each letter in any case (upper or lower). | standard output | |
PASSED | ced346ce7c0ed5aa76989fe75053a0df | train_000.jsonl | 1556989500 | Inaka has a disc, the circumference of which is $$$n$$$ units. The circumference is equally divided by $$$n$$$ points numbered clockwise from $$$1$$$ to $$$n$$$, such that points $$$i$$$ and $$$i + 1$$$ ($$$1 \leq i < n$$$) are adjacent, and so are points $$$n$$$ and $$$1$$$.There are $$$m$$$ straight segments on the disc, the endpoints of which are all among the aforementioned $$$n$$$ points.Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer $$$k$$$ ($$$1 \leq k < n$$$), such that if all segments are rotated clockwise around the center of the circle by $$$k$$$ units, the new image will be the same as the original one. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
//http://codeforces.com/contest/1161/problem/B
public class ChladniFigure {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int[] params = Arrays.stream(br.readLine().split(" "))
.mapToInt(x -> Integer.parseInt(x)).toArray();
int n = params[0];
int m = params[1];
List<Integer>[] points = new List[n];
for (int i = 0; i < n; i++) {
points[i] = new ArrayList<>();
}
for (int i = 0; i < m; i++) {
params = Arrays.stream(br.readLine().split(" "))
.mapToInt(x -> Integer.parseInt(x)).toArray();
int s = params[0];
int e = params[1];
points[s % n].add((n + e - s) % n);
points[e % n].add((n + s - e) % n);
}
for (int i = 0; i < n; i++) {
Collections.sort(points[i]);
}
Set<Integer> factors = new HashSet<>();
int nCopy = n;
for (int i = 2; i * i <= nCopy; i++) {
if (nCopy % i == 0) {
factors.add(i);
while (nCopy % i == 0) {
nCopy /= i;
}
}
}
if (nCopy != 1) {
factors.add(nCopy);
}
for (int i : factors) {
int dist = n / i;
boolean possible = true;
for (int j = 0; j < n; j++) {
if (!points[j].equals(points[(j + dist) % n])) {
possible = false;
break;
}
}
if (possible) {
System.out.println("Yes");
return;
}
}
System.out.println("No");
}
}
| Java | ["12 6\n1 3\n3 7\n5 7\n7 11\n9 11\n11 3", "9 6\n4 5\n5 6\n7 8\n8 9\n1 2\n2 3", "10 3\n1 2\n3 2\n7 2", "10 2\n1 6\n2 7"] | 3 seconds | ["Yes", "Yes", "No", "Yes"] | NoteThe first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of $$$120$$$ degrees around the center. | Java 8 | standard input | [
"implementation",
"hashing",
"strings"
] | dd7a7a4e5feb50ab6abb93d90c559c2b | The first line contains two space-separated integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 100\,000$$$, $$$1 \leq m \leq 200\,000$$$) — the number of points and the number of segments, respectively. The $$$i$$$-th of the following $$$m$$$ lines contains two space-separated integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \leq a_i, b_i \leq n$$$, $$$a_i \neq b_i$$$) that describe a segment connecting points $$$a_i$$$ and $$$b_i$$$. It is guaranteed that no segments coincide. | 1,900 | Output one line — "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks). You can output each letter in any case (upper or lower). | standard output | |
PASSED | 666a6343e29bd3a5db6c338cc84c0040 | train_000.jsonl | 1556989500 | Inaka has a disc, the circumference of which is $$$n$$$ units. The circumference is equally divided by $$$n$$$ points numbered clockwise from $$$1$$$ to $$$n$$$, such that points $$$i$$$ and $$$i + 1$$$ ($$$1 \leq i < n$$$) are adjacent, and so are points $$$n$$$ and $$$1$$$.There are $$$m$$$ straight segments on the disc, the endpoints of which are all among the aforementioned $$$n$$$ points.Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer $$$k$$$ ($$$1 \leq k < n$$$), such that if all segments are rotated clockwise around the center of the circle by $$$k$$$ units, the new image will be the same as the original one. | 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.util.HashMap;
import java.io.IOException;
import java.util.InputMismatchException;
import java.util.Random;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.io.Writer;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Niyaz Nigmatullin
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
FastPrinter out = new FastPrinter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
public void solve(int testNumber, FastScanner in, FastPrinter out) {
int n = in.nextInt();
int m = in.nextInt();
List<Integer>[] edges = new List[n];
for (int i = 0; i < n; i++) edges[i] = new ArrayList<>();
for (int i = 0; i < m; i++) {
int a = in.nextInt() - 1;
int b = in.nextInt() - 1;
edges[a].add((b - a + n) % n);
edges[b].add((a - b + n) % n);
}
Map<TaskB.Neighbors, Integer> classes = new HashMap<>();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
int[] z = new int[edges[i].size()];
for (int j = 0; j < z.length; j++) {
z[j] = edges[i].get(j);
}
ArrayUtils.sort(z);
TaskB.Neighbors cur = new TaskB.Neighbors(z);
Integer got = classes.get(cur);
if (got == null) {
got = classes.size();
classes.put(cur, got);
}
a[i] = got;
}
int[] p = new int[n];
int k = -1;
p[0] = -1;
for (int i = 1; i < n; i++) {
while (k > -1 && a[i] != a[k + 1]) k = p[k];
if (a[i] == a[k + 1]) ++k;
p[i] = k;
}
k = -1;
for (int i = 1; i + 1 < n + n; i++) {
int c = a[i % n];
while (k > -1 && c != a[k + 1]) k = p[k];
if (c == a[k + 1]) ++k;
if (k == n - 1) {
out.println("Yes");
return;
}
}
out.println("No");
}
static class Neighbors {
int[] a;
public Neighbors(int[] a) {
this.a = a;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TaskB.Neighbors neighbors = (TaskB.Neighbors) o;
return Arrays.equals(a, neighbors.a);
}
public int hashCode() {
return Arrays.hashCode(a);
}
}
}
static class FastPrinter extends PrintWriter {
public FastPrinter(OutputStream out) {
super(out);
}
public FastPrinter(Writer out) {
super(out);
}
}
static class ArrayUtils {
static final long seed = System.nanoTime();
static final Random rand = new Random(seed);
public static void sort(int[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void shuffle(int[] a) {
for (int i = 0; i < a.length; i++) {
int j = rand.nextInt(i + 1);
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
}
static class FastScanner extends BufferedReader {
public FastScanner(InputStream is) {
super(new InputStreamReader(is));
}
public int read() {
try {
int ret = super.read();
// if (isEOF && ret < 0) {
// throw new InputMismatchException();
// }
// isEOF = ret == -1;
return ret;
} catch (IOException e) {
throw new InputMismatchException();
}
}
static boolean isWhiteSpace(int c) {
return c >= 0 && c <= 32;
}
public int nextInt() {
int c = read();
while (isWhiteSpace(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int ret = 0;
while (c >= 0 && !isWhiteSpace(c)) {
if (c < '0' || c > '9') {
throw new NumberFormatException("digit expected " + (char) c
+ " found");
}
ret = ret * 10 + c - '0';
c = read();
}
return ret * sgn;
}
public String readLine() {
try {
return super.readLine();
} catch (IOException e) {
return null;
}
}
}
}
| Java | ["12 6\n1 3\n3 7\n5 7\n7 11\n9 11\n11 3", "9 6\n4 5\n5 6\n7 8\n8 9\n1 2\n2 3", "10 3\n1 2\n3 2\n7 2", "10 2\n1 6\n2 7"] | 3 seconds | ["Yes", "Yes", "No", "Yes"] | NoteThe first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of $$$120$$$ degrees around the center. | Java 8 | standard input | [
"implementation",
"hashing",
"strings"
] | dd7a7a4e5feb50ab6abb93d90c559c2b | The first line contains two space-separated integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 100\,000$$$, $$$1 \leq m \leq 200\,000$$$) — the number of points and the number of segments, respectively. The $$$i$$$-th of the following $$$m$$$ lines contains two space-separated integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \leq a_i, b_i \leq n$$$, $$$a_i \neq b_i$$$) that describe a segment connecting points $$$a_i$$$ and $$$b_i$$$. It is guaranteed that no segments coincide. | 1,900 | Output one line — "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks). You can output each letter in any case (upper or lower). | standard output | |
PASSED | cf6078b5679b52c1342e2260e1c646a6 | train_000.jsonl | 1556989500 | Inaka has a disc, the circumference of which is $$$n$$$ units. The circumference is equally divided by $$$n$$$ points numbered clockwise from $$$1$$$ to $$$n$$$, such that points $$$i$$$ and $$$i + 1$$$ ($$$1 \leq i < n$$$) are adjacent, and so are points $$$n$$$ and $$$1$$$.There are $$$m$$$ straight segments on the disc, the endpoints of which are all among the aforementioned $$$n$$$ points.Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer $$$k$$$ ($$$1 \leq k < n$$$), such that if all segments are rotated clockwise around the center of the circle by $$$k$$$ units, the new image will be the same as the original one. | 256 megabytes | import java.io.*;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
public class SolverB {
StringTokenizer stok;
BufferedReader br;
PrintWriter pw;
String nextToken() throws IOException {
while (stok == null || !stok.hasMoreTokens()) {
stok = new StringTokenizer(br.readLine());
}
return stok.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
private void run() throws IOException {
// br = new BufferedReader(new FileReader("input.txt"));
// pw = new PrintWriter("output.txt");
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new OutputStreamWriter(System.out));
solve();
pw.flush();
pw.close();
}
public static void main(String[] args) throws IOException {
new SolverB().run();
}
int n,m;
Set<Integer>[] sets;
int[] p1,p2;
private void solve() throws IOException {
n = nextInt();
m = nextInt();
p1 = new int[m];
p2 = new int[m];
sets = new Set[n];
for (int i=0; i<n; i++) {
sets[i] = new HashSet<>();
}
for (int i=0; i<m; i++) {
p1[i] = nextInt()-1;
p2[i] = nextInt()-1;
sets[p1[i]].add(p2[i]);
sets[p2[i]].add(p1[i]);
}
for (int div = 1; div <= n/2; div++) {
if (n % div == 0) {
if (checkDiv(div)) {
pw.println("Yes");
return;
}
}
}
pw.println("No");
}
boolean checkDiv(int div) {
for (int i=0; i<m; i++) {
int n1 = p1[i] + div;
int n2 = p2[i] + div;
if (n1 >= n) {
n1-=n;
}
if (n2 >= n) {
n2-=n;
}
if (!sets[n1].contains(n2)) {
return false;
}
}
return true;
}
} | Java | ["12 6\n1 3\n3 7\n5 7\n7 11\n9 11\n11 3", "9 6\n4 5\n5 6\n7 8\n8 9\n1 2\n2 3", "10 3\n1 2\n3 2\n7 2", "10 2\n1 6\n2 7"] | 3 seconds | ["Yes", "Yes", "No", "Yes"] | NoteThe first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of $$$120$$$ degrees around the center. | Java 8 | standard input | [
"implementation",
"hashing",
"strings"
] | dd7a7a4e5feb50ab6abb93d90c559c2b | The first line contains two space-separated integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 100\,000$$$, $$$1 \leq m \leq 200\,000$$$) — the number of points and the number of segments, respectively. The $$$i$$$-th of the following $$$m$$$ lines contains two space-separated integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \leq a_i, b_i \leq n$$$, $$$a_i \neq b_i$$$) that describe a segment connecting points $$$a_i$$$ and $$$b_i$$$. It is guaranteed that no segments coincide. | 1,900 | Output one line — "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks). You can output each letter in any case (upper or lower). | standard output | |
PASSED | 5969c9896814cffe3b05bc184581bf1e | train_000.jsonl | 1556989500 | Inaka has a disc, the circumference of which is $$$n$$$ units. The circumference is equally divided by $$$n$$$ points numbered clockwise from $$$1$$$ to $$$n$$$, such that points $$$i$$$ and $$$i + 1$$$ ($$$1 \leq i < n$$$) are adjacent, and so are points $$$n$$$ and $$$1$$$.There are $$$m$$$ straight segments on the disc, the endpoints of which are all among the aforementioned $$$n$$$ points.Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer $$$k$$$ ($$$1 \leq k < n$$$), such that if all segments are rotated clockwise around the center of the circle by $$$k$$$ units, the new image will be the same as the original one. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
Pair[] ps = new Pair[2 * m];
for (int i = 0; i < m; i++) {
int a = in.nextInt() - 1;
int b = in.nextInt() - 1;
if (a > b) {
int t = a;
a = b;
b = t;
}
int d = b - a;
ps[2 * i] = new Pair(a, d);
ps[2 * i + 1] = new Pair(b, n - d);
}
Arrays.sort(ps);
int[] seq = new int[ps.length];
for (int i = 0; i < ps.length; i++) {
seq[i] = ps[i].d;
}
int[] p = kmp(seq);
int per = p.length - 1 - p[p.length - 1];
out.println(per < seq.length && seq.length % per == 0 ? "Yes" : "No");
}
private int[] kmp(int[] s) {
int[] p = new int[s.length];
int k = -1;
p[0] = -1;
for (int i = 1; i < s.length; i++) {
while (k >= 0 && s[k + 1] != s[i]) {
k = p[k];
}
if (s[k + 1] == s[i]) {
++k;
}
p[i] = k;
}
return p;
}
class Pair implements Comparable<Pair> {
int a;
int d;
Pair(int a, int d) {
this.a = a;
this.d = d;
}
public int compareTo(Pair o) {
if (a != o.a) {
return a < o.a ? -1 : 1;
}
if (d != o.d) {
return d < o.d ? -1 : 1;
}
return 0;
}
}
}
static class FastScanner {
private BufferedReader in;
private StringTokenizer st;
public FastScanner(InputStream stream) {
in = new BufferedReader(new InputStreamReader(stream));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(in.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["12 6\n1 3\n3 7\n5 7\n7 11\n9 11\n11 3", "9 6\n4 5\n5 6\n7 8\n8 9\n1 2\n2 3", "10 3\n1 2\n3 2\n7 2", "10 2\n1 6\n2 7"] | 3 seconds | ["Yes", "Yes", "No", "Yes"] | NoteThe first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of $$$120$$$ degrees around the center. | Java 8 | standard input | [
"implementation",
"hashing",
"strings"
] | dd7a7a4e5feb50ab6abb93d90c559c2b | The first line contains two space-separated integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 100\,000$$$, $$$1 \leq m \leq 200\,000$$$) — the number of points and the number of segments, respectively. The $$$i$$$-th of the following $$$m$$$ lines contains two space-separated integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \leq a_i, b_i \leq n$$$, $$$a_i \neq b_i$$$) that describe a segment connecting points $$$a_i$$$ and $$$b_i$$$. It is guaranteed that no segments coincide. | 1,900 | Output one line — "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks). You can output each letter in any case (upper or lower). | standard output | |
PASSED | 88e835d52940af3d37eb7bb5e0c7d39e | train_000.jsonl | 1556989500 | Inaka has a disc, the circumference of which is $$$n$$$ units. The circumference is equally divided by $$$n$$$ points numbered clockwise from $$$1$$$ to $$$n$$$, such that points $$$i$$$ and $$$i + 1$$$ ($$$1 \leq i < n$$$) are adjacent, and so are points $$$n$$$ and $$$1$$$.There are $$$m$$$ straight segments on the disc, the endpoints of which are all among the aforementioned $$$n$$$ points.Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer $$$k$$$ ($$$1 \leq k < n$$$), such that if all segments are rotated clockwise around the center of the circle by $$$k$$$ units, the new image will be the same as the original one. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.util.Set;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author prakharjain
*/
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);
BChladniFigure solver = new BChladniFigure();
solver.solve(1, in, out);
out.close();
}
static class BChladniFigure {
long mul = 10000000000L;
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int m = in.nextInt();
Set<Long> segs = new HashSet<>();
for (int i = 0; i < m; i++) {
long x = in.nextInt();
long y = in.nextInt();
if (x > y) {
long t = x;
x = y;
y = t;
}
segs.add(x * mul + y);
}
Set<Long> facs = factors(n);
for (long i : facs) {
if (i == n)
continue;
int ss = (int) i;
boolean poss = true;
for (long cs : segs) {
long csa = cs / mul - ss;
long csb = cs % mul - ss;
if (csa < 1) {
csa += n;
}
if (csb < 1) {
csb += n;
}
if (csa > csb) {
long t = csa;
csa = csb;
csb = t;
}
if (!segs.contains(csa * mul + csb)) {
poss = false;
break;
}
}
// if (cseg.size() == segs.size()) {
// poss = true;
//
// for (long cs : segs) {
// if (!cseg.contains(cs)) {
// poss = false;
// break;
// }
// }
//
// for (long cs : cseg) {
// if (!segs.contains(cs)) {
// poss = false;
// break;
// }
// }
// }
if (poss) {
out.println("Yes");
return;
}
}
out.println("No");
}
Set<Long> factors(long n) {
Set<Long> factors = new HashSet<>();
for (long i = 1; i * i <= n; i++) {
if (n % i == 0) {
factors.add(i);
factors.add(n / i);
}
}
return factors;
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
}
| Java | ["12 6\n1 3\n3 7\n5 7\n7 11\n9 11\n11 3", "9 6\n4 5\n5 6\n7 8\n8 9\n1 2\n2 3", "10 3\n1 2\n3 2\n7 2", "10 2\n1 6\n2 7"] | 3 seconds | ["Yes", "Yes", "No", "Yes"] | NoteThe first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of $$$120$$$ degrees around the center. | Java 8 | standard input | [
"implementation",
"hashing",
"strings"
] | dd7a7a4e5feb50ab6abb93d90c559c2b | The first line contains two space-separated integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 100\,000$$$, $$$1 \leq m \leq 200\,000$$$) — the number of points and the number of segments, respectively. The $$$i$$$-th of the following $$$m$$$ lines contains two space-separated integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \leq a_i, b_i \leq n$$$, $$$a_i \neq b_i$$$) that describe a segment connecting points $$$a_i$$$ and $$$b_i$$$. It is guaranteed that no segments coincide. | 1,900 | Output one line — "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks). You can output each letter in any case (upper or lower). | standard output | |
PASSED | 420277740bb5b8a435f4b7a90f642313 | train_000.jsonl | 1556989500 | Inaka has a disc, the circumference of which is $$$n$$$ units. The circumference is equally divided by $$$n$$$ points numbered clockwise from $$$1$$$ to $$$n$$$, such that points $$$i$$$ and $$$i + 1$$$ ($$$1 \leq i < n$$$) are adjacent, and so are points $$$n$$$ and $$$1$$$.There are $$$m$$$ straight segments on the disc, the endpoints of which are all among the aforementioned $$$n$$$ points.Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer $$$k$$$ ($$$1 \leq k < n$$$), such that if all segments are rotated clockwise around the center of the circle by $$$k$$$ units, the new image will be the same as the original one. | 256 megabytes | import java.util.*;
import java.io.*;
import java.text.*;
public class Main{
//SOLUTION BEGIN
//This code is not meant for understanding, proceed with caution
int[] spf;
void pre() throws Exception{
spf= new int[MX];
for(int i = 2; i< MX; i++)
if(spf[i]==0)
for(int j = i; j< MX; j+=i)
if(spf[j]==0)
spf[j] = i;
}
void solve(int TC) throws Exception{
int n = ni(), m = ni();
TreeSet<Integer>[] set = new TreeSet[n];
for(int i = 0; i< n; i++)set[i] = new TreeSet<>();
for(int i = 0; i< m; i++){
int u = ni()-1, v = ni()-1;
set[u].add(v);
set[v].add(u);
}
int x = n;
boolean y = false;
while(x>1){
int pr = spf[x];
while(x%pr==0)
x/=pr;
boolean valid = true;
int p = n/pr;
for(int i = 0; i< n; i++)
for(int v:set[i])
valid &= set[(i+p)%n].contains((v+p)%n);
y|=valid;
}
pn(y?"Yes":"No");
}
//SOLUTION END
void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");}
long mod = (long)1e9+7, IINF = (long)1e18;
final int INF = (int)1e9, MX = (int)2e5+1;
DecimalFormat df = new DecimalFormat("0.00000000000");
double PI = 3.1415926535897932384626433832792884197169399375105820974944, eps = 1e-8;
static boolean multipleTC = false, memory = false;
FastReader in;PrintWriter out;
void run() throws Exception{
in = new FastReader();
out = new PrintWriter(System.out);
int T = (multipleTC)?ni():1;
pre();for(int t = 1; t<= T; t++)solve(t);
out.flush();
out.close();
}
public static void main(String[] args) throws Exception{
if(memory)new Thread(null, new Runnable() {public void run(){try{new Main().run();}catch(Exception e){e.printStackTrace();}}}, "1", 1 << 28).start();
else new Main().run();
}
long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);}
int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);}
int bit(long n){return (n==0)?0:(1+bit(n&(n-1)));}
void p(Object o){out.print(o);}
void pn(Object o){out.println(o);}
void pni(Object o){out.println(o);out.flush();}
String n()throws Exception{return in.next();}
String nln()throws Exception{return in.nextLine();}
int ni()throws Exception{return Integer.parseInt(in.next());}
long nl()throws Exception{return Long.parseLong(in.next());}
double nd()throws Exception{return Double.parseDouble(in.next());}
class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws Exception{
br = new BufferedReader(new FileReader(s));
}
String next() throws Exception{
while (st == null || !st.hasMoreElements()){
try{
st = new StringTokenizer(br.readLine());
}catch (IOException e){
throw new Exception(e.toString());
}
}
return st.nextToken();
}
String nextLine() throws Exception{
String str = "";
try{
str = br.readLine();
}catch (IOException e){
throw new Exception(e.toString());
}
return str;
}
}
} | Java | ["12 6\n1 3\n3 7\n5 7\n7 11\n9 11\n11 3", "9 6\n4 5\n5 6\n7 8\n8 9\n1 2\n2 3", "10 3\n1 2\n3 2\n7 2", "10 2\n1 6\n2 7"] | 3 seconds | ["Yes", "Yes", "No", "Yes"] | NoteThe first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of $$$120$$$ degrees around the center. | Java 8 | standard input | [
"implementation",
"hashing",
"strings"
] | dd7a7a4e5feb50ab6abb93d90c559c2b | The first line contains two space-separated integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 100\,000$$$, $$$1 \leq m \leq 200\,000$$$) — the number of points and the number of segments, respectively. The $$$i$$$-th of the following $$$m$$$ lines contains two space-separated integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \leq a_i, b_i \leq n$$$, $$$a_i \neq b_i$$$) that describe a segment connecting points $$$a_i$$$ and $$$b_i$$$. It is guaranteed that no segments coincide. | 1,900 | Output one line — "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks). You can output each letter in any case (upper or lower). | standard output | |
PASSED | 223d0507718caaa9137f8f35fa57319f | train_000.jsonl | 1556989500 | Inaka has a disc, the circumference of which is $$$n$$$ units. The circumference is equally divided by $$$n$$$ points numbered clockwise from $$$1$$$ to $$$n$$$, such that points $$$i$$$ and $$$i + 1$$$ ($$$1 \leq i < n$$$) are adjacent, and so are points $$$n$$$ and $$$1$$$.There are $$$m$$$ straight segments on the disc, the endpoints of which are all among the aforementioned $$$n$$$ points.Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer $$$k$$$ ($$$1 \leq k < n$$$), such that if all segments are rotated clockwise around the center of the circle by $$$k$$$ units, the new image will be the same as the original one. | 256 megabytes | import java.util.*;
import java.io.*;
public class TaskB implements Runnable {
public static void main(String[] args) {
new Thread(new TaskB()).start();
}
@Override
public void run() {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
}
BufferedReader br;
StringTokenizer st;
PrintWriter out;
boolean eof = false;
String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
eof = true;
return "0";
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
public void solve() {
int n = nextInt();
int m = nextInt();
int[] a = new int[m];
int[] b = new int[m];
ArrayList<Integer>[] h = new ArrayList[n];
HashSet<Integer>[] hh = new HashSet[n];
for (int i = 0; i < n; i++) {
h[i] = new ArrayList<>();
hh[i] = new HashSet<>();
}
for (int i = 0; i < m; i++) {
a[i] = nextInt() - 1;
b[i] = nextInt() - 1;
int d = b[i] - a[i];
if (d < 0) {
d += n;
}
if (d <= n / 2) {
h[d].add(a[i]);
} else {
h[n - d].add(b[i]);
}
}
for (int i = 1; i <= n / 2; i++) {
for (int x : h[i]) {
hh[i].add(x);
if (i == n / 2) {
hh[i].add((x + i) % n);
}
}
}
// for (int i = 0; i < h.length; i++) {
// out.print(i + ": ");
// for (int x : h[i])
// out.print(x + " ");
// out.println();
// }
for (int i = 1; i <= n / 2; i++) {
if (n % i != 0) {
continue;
}
boolean good = true;
for (int j = 1; j <= n / 2; j++) {
for (int x : h[j]) {
if (!hh[j].contains((x + i) % n)) {
good = false;
break;
}
}
}
if (good) {
out.println("Yes");
// out.println(i);
return;
}
}
out.println("No");
}
}
| Java | ["12 6\n1 3\n3 7\n5 7\n7 11\n9 11\n11 3", "9 6\n4 5\n5 6\n7 8\n8 9\n1 2\n2 3", "10 3\n1 2\n3 2\n7 2", "10 2\n1 6\n2 7"] | 3 seconds | ["Yes", "Yes", "No", "Yes"] | NoteThe first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of $$$120$$$ degrees around the center. | Java 8 | standard input | [
"implementation",
"hashing",
"strings"
] | dd7a7a4e5feb50ab6abb93d90c559c2b | The first line contains two space-separated integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 100\,000$$$, $$$1 \leq m \leq 200\,000$$$) — the number of points and the number of segments, respectively. The $$$i$$$-th of the following $$$m$$$ lines contains two space-separated integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \leq a_i, b_i \leq n$$$, $$$a_i \neq b_i$$$) that describe a segment connecting points $$$a_i$$$ and $$$b_i$$$. It is guaranteed that no segments coincide. | 1,900 | Output one line — "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks). You can output each letter in any case (upper or lower). | standard output | |
PASSED | 548e9b3983955d604e8c0e755ebb43b7 | train_000.jsonl | 1556989500 | Inaka has a disc, the circumference of which is $$$n$$$ units. The circumference is equally divided by $$$n$$$ points numbered clockwise from $$$1$$$ to $$$n$$$, such that points $$$i$$$ and $$$i + 1$$$ ($$$1 \leq i < n$$$) are adjacent, and so are points $$$n$$$ and $$$1$$$.There are $$$m$$$ straight segments on the disc, the endpoints of which are all among the aforementioned $$$n$$$ points.Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer $$$k$$$ ($$$1 \leq k < n$$$), such that if all segments are rotated clockwise around the center of the circle by $$$k$$$ units, the new image will be the same as the original one. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.BigInteger;
import static java.lang.Math.*;
/* spar5h */
public class cf2 implements Runnable {
public void run() {
InputReader s = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int n = s.nextInt(), m = s.nextInt();
ArrayList<Integer> fact = new ArrayList<Integer>();
fact.add(1);
for(int i = 2; (long)i * i <= n; i++) {
if(n % i != 0)
continue;
fact.add(i);
if(n / i != i)
fact.add(n / i);
}
ArrayList<Integer>[] adj = new ArrayList[n / 2 + 1];
for(int i = 0; i <= n / 2; i++)
adj[i] = new ArrayList<Integer>();
for(int i = 0; i < m; i++) {
int u = s.nextInt() - 1, v = s.nextInt() - 1;
if((v - u + n) % n <= (u - v + n) % n)
adj[(v - u + n) % n].add(u);
if((u - v + n) % n <= (v - u + n) % n)
adj[(u - v + n) % n].add(v);
}
boolean res = false;
int[] count = new int[n];
int[] map = new int[n];
Arrays.fill(map, -1);
for(int x : fact) {
boolean check = true;
for(int len = 1; len <= n / 2; len++) {
ArrayList<Integer> set = new ArrayList<Integer>();
for(int i : adj[len]) {
if(map[i % x] == -1) {
map[i % x] = set.size();
set.add(i % x);
}
count[map[i % x]]++;
}
for(int i : set) {
if(count[map[i]] != n / x)
check = false;
count[map[i]] = 0;
map[i] = -1;
}
}
if(check) {
res = true;
break;
}
}
if(res)
w.println("Yes");
else
w.println("No");
w.close();
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars==-1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
}
catch (IOException e) {
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
public int nextInt() {
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if(c<'0'||c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c))
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
public static void main(String args[]) throws Exception {
new Thread(null, new cf2(),"cf2",1<<26).start();
}
} | Java | ["12 6\n1 3\n3 7\n5 7\n7 11\n9 11\n11 3", "9 6\n4 5\n5 6\n7 8\n8 9\n1 2\n2 3", "10 3\n1 2\n3 2\n7 2", "10 2\n1 6\n2 7"] | 3 seconds | ["Yes", "Yes", "No", "Yes"] | NoteThe first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of $$$120$$$ degrees around the center. | Java 8 | standard input | [
"implementation",
"hashing",
"strings"
] | dd7a7a4e5feb50ab6abb93d90c559c2b | The first line contains two space-separated integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 100\,000$$$, $$$1 \leq m \leq 200\,000$$$) — the number of points and the number of segments, respectively. The $$$i$$$-th of the following $$$m$$$ lines contains two space-separated integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \leq a_i, b_i \leq n$$$, $$$a_i \neq b_i$$$) that describe a segment connecting points $$$a_i$$$ and $$$b_i$$$. It is guaranteed that no segments coincide. | 1,900 | Output one line — "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks). You can output each letter in any case (upper or lower). | standard output | |
PASSED | 4a32615caaca01352d6382aeb7c4a22d | train_000.jsonl | 1556989500 | Inaka has a disc, the circumference of which is $$$n$$$ units. The circumference is equally divided by $$$n$$$ points numbered clockwise from $$$1$$$ to $$$n$$$, such that points $$$i$$$ and $$$i + 1$$$ ($$$1 \leq i < n$$$) are adjacent, and so are points $$$n$$$ and $$$1$$$.There are $$$m$$$ straight segments on the disc, the endpoints of which are all among the aforementioned $$$n$$$ points.Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer $$$k$$$ ($$$1 \leq k < n$$$), such that if all segments are rotated clockwise around the center of the circle by $$$k$$$ units, the new image will be the same as the original one. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Set;
import java.io.IOException;
import java.util.Random;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.StringTokenizer;
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);
PrintWriter out = new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
static Random random = new Random(573453151L + System.currentTimeMillis());
static int BUBEN = random.nextInt() * 2 + 1;
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
Set<TaskB.Chord> chords = new HashSet<>();
for (int i = 0; i < m; ++i) {
int a = in.nextInt() - 1;
int b = in.nextInt() - 1;
int first = a;
int len = b - a;
if (len < 0) len += n;
if (len > n - len) {
first = b;
len = n - len;
}
chords.add(new TaskB.Chord(first, len));
if (len == n - len) {
chords.add(new TaskB.Chord(b, len));
}
}
boolean[] prime = new boolean[n + 1];
Arrays.fill(prime, true);
TaskB.Chord tmp = new TaskB.Chord(0, 0);
outer:
for (int g = 2; g <= n; ++g)
if (prime[g]) {
if (n % g != 0) continue;
for (int i = g * 2; i <= n; i += g) prime[i] = false;
int delta = n / g;
for (TaskB.Chord c : chords) {
tmp.len = c.len;
tmp.first = c.first + delta;
if (tmp.first >= n) tmp.first -= n;
if (!chords.contains(tmp)) continue outer;
}
out.println("Yes");
return;
}
out.println("No");
}
static class Chord {
int first;
int len;
public Chord(int first, int len) {
this.first = first;
this.len = len;
}
public boolean equals(Object o) {
TaskB.Chord chord = (TaskB.Chord) o;
return first == chord.first &&
len == chord.len;
}
public int hashCode() {
return first * BUBEN + len;
}
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 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());
}
}
}
| Java | ["12 6\n1 3\n3 7\n5 7\n7 11\n9 11\n11 3", "9 6\n4 5\n5 6\n7 8\n8 9\n1 2\n2 3", "10 3\n1 2\n3 2\n7 2", "10 2\n1 6\n2 7"] | 3 seconds | ["Yes", "Yes", "No", "Yes"] | NoteThe first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of $$$120$$$ degrees around the center. | Java 8 | standard input | [
"implementation",
"hashing",
"strings"
] | dd7a7a4e5feb50ab6abb93d90c559c2b | The first line contains two space-separated integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 100\,000$$$, $$$1 \leq m \leq 200\,000$$$) — the number of points and the number of segments, respectively. The $$$i$$$-th of the following $$$m$$$ lines contains two space-separated integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \leq a_i, b_i \leq n$$$, $$$a_i \neq b_i$$$) that describe a segment connecting points $$$a_i$$$ and $$$b_i$$$. It is guaranteed that no segments coincide. | 1,900 | Output one line — "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks). You can output each letter in any case (upper or lower). | standard output | |
PASSED | 6e69d12d422a631ded1ccda841a82b51 | train_000.jsonl | 1298649600 | Tyndex is again well ahead of the rivals! The reaction to the release of Zoozle Chrome browser was the release of a new browser Tyndex.Brome!The popularity of the new browser is growing daily. And the secret is not even the Tyndex.Bar installed (the Tyndex.Bar automatically fills the glass with the finest 1664 cognac after you buy Tyndex.Bottles and insert in into a USB port). It is highly popular due to the well-thought interaction with the user.Let us take, for example, the system of automatic address correction. Have you entered codehorses instead of codeforces? The gloomy Zoozle Chrome will sadly say that the address does not exist. Tyndex.Brome at the same time will automatically find the closest address and sent you there. That's brilliant!How does this splendid function work? That's simple! For each potential address a function of the F error is calculated by the following rules: for every letter ci from the potential address c the closest position j of the letter ci in the address (s) entered by the user is found. The absolute difference |i - j| of these positions is added to F. So for every i (1 ≤ i ≤ |c|) the position j is chosen such, that ci = sj, and |i - j| is minimal possible. if no such letter ci exists in the address entered by the user, then the length of the potential address |c| is added to F. After the values of the error function have been calculated for all the potential addresses the most suitable one is found. To understand the special features of the above described method better, it is recommended to realize the algorithm of calculating the F function for an address given by the user and some set of potential addresses. Good luck! | 256 megabytes | import java.util.*;
public class P062B {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
String s = sc.next();
ArrayList<TreeSet<Integer>> position = new ArrayList<>();
for (int i = 0; i < 26; i++) {
position.add(new TreeSet<Integer>());
}
for (int i = 0; i < k; i++) {
char c = s.charAt(i);
position.get(c-'a').add(i);
}
for (int i = 0; i < n; i++) {
long result = 0;
String sp = sc.next();
int length = sp.length();
for (int j = 0; j < length; j++) {
char c = sp.charAt(j);
Integer floor = position.get(c-'a').floor(j);
int dist1 = (floor == null ? Integer.MAX_VALUE : j - floor);
Integer ceiling = position.get(c-'a').ceiling(j);
int dist2 = (ceiling == null ? Integer.MAX_VALUE : ceiling - j);
int dist = Math.min(dist1, dist2);
dist = (dist == Integer.MAX_VALUE ? length : dist);
result += dist;
}
System.out.println(result);
}
}
} | Java | ["2 10\ncodeforces\ncodeforces\ncodehorses", "9 9\nvkontakte\nvcontacte\nvkontrakte\nvkollapse\nvkrokodile\nvtopke\nvkapuste\nvpechke\nvk\nvcodeforcese"] | 2 seconds | ["0\n12", "18\n14\n36\n47\n14\n29\n30\n0\n84"] | null | Java 7 | standard input | [
"binary search",
"implementation"
] | a587188db6f0c17927923a158fdca1be | The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 105). They are the number of potential addresses and the length of the address entered by the user. The next line contains k lowercase Latin letters. They are the address entered by the user (s). Each next i-th (1 ≤ i ≤ n) line contains a non-empty sequence of lowercase Latin letters. They are the potential address. It is guaranteed that the total length of all the lines does not exceed 2·105. | 1,800 | On each n line of the output file print a single number: the value of the error function when the current potential address is chosen. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d). | standard output | |
PASSED | b5941ebebc6bbf47831cfac94185f278 | train_000.jsonl | 1298649600 | Tyndex is again well ahead of the rivals! The reaction to the release of Zoozle Chrome browser was the release of a new browser Tyndex.Brome!The popularity of the new browser is growing daily. And the secret is not even the Tyndex.Bar installed (the Tyndex.Bar automatically fills the glass with the finest 1664 cognac after you buy Tyndex.Bottles and insert in into a USB port). It is highly popular due to the well-thought interaction with the user.Let us take, for example, the system of automatic address correction. Have you entered codehorses instead of codeforces? The gloomy Zoozle Chrome will sadly say that the address does not exist. Tyndex.Brome at the same time will automatically find the closest address and sent you there. That's brilliant!How does this splendid function work? That's simple! For each potential address a function of the F error is calculated by the following rules: for every letter ci from the potential address c the closest position j of the letter ci in the address (s) entered by the user is found. The absolute difference |i - j| of these positions is added to F. So for every i (1 ≤ i ≤ |c|) the position j is chosen such, that ci = sj, and |i - j| is minimal possible. if no such letter ci exists in the address entered by the user, then the length of the potential address |c| is added to F. After the values of the error function have been calculated for all the potential addresses the most suitable one is found. To understand the special features of the above described method better, it is recommended to realize the algorithm of calculating the F function for an address given by the user and some set of potential addresses. Good luck! | 256 megabytes | import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main{
static String original;
static boolean[] exists;
static List[] indexes;
static int[] closest;
static int k;
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner s = new Scanner(System.in);
int n = s.nextInt();
k = s.nextInt();
s.nextLine();
original = s.nextLine();
exists = new boolean[26];
indexes = new List[26];
for(int c=0;c<26;c++){
indexes[c] = new ArrayList<Integer>();
}
long length = original.length();
for(int i=0;i<length;i++){
int character = original.charAt(i)-'a';
exists[character] = true;
indexes[character].add(i);
}
for(int i=0;i<n;i++){
closest = new int[26];
System.out.println(distance(s.nextLine()));
}
}
static public long distance(String word){
long distance = 0;
int length = word.length();
for(int i=0;i<length;i++){
int character = word.charAt(i)-'a';
if(i<k && word.charAt(i)==original.charAt(i)){
continue;
}
else if(!exists[character]){
distance+=length;
}
else{
long local_dist = Long.MAX_VALUE;
long temp_dist;
for(int d=closest[character];d<indexes[character].size();d++){
temp_dist = Math.abs(i-(int)indexes[character].get(d));
if(temp_dist < local_dist){
local_dist = temp_dist;
closest[character] = d;
}
else{
break;
}
}
distance+= local_dist;
}
}
return distance;
}
}
| Java | ["2 10\ncodeforces\ncodeforces\ncodehorses", "9 9\nvkontakte\nvcontacte\nvkontrakte\nvkollapse\nvkrokodile\nvtopke\nvkapuste\nvpechke\nvk\nvcodeforcese"] | 2 seconds | ["0\n12", "18\n14\n36\n47\n14\n29\n30\n0\n84"] | null | Java 7 | standard input | [
"binary search",
"implementation"
] | a587188db6f0c17927923a158fdca1be | The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 105). They are the number of potential addresses and the length of the address entered by the user. The next line contains k lowercase Latin letters. They are the address entered by the user (s). Each next i-th (1 ≤ i ≤ n) line contains a non-empty sequence of lowercase Latin letters. They are the potential address. It is guaranteed that the total length of all the lines does not exceed 2·105. | 1,800 | On each n line of the output file print a single number: the value of the error function when the current potential address is chosen. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d). | standard output | |
PASSED | f54950b2b9ff68d26c28958d463d4a6c | train_000.jsonl | 1298649600 | Tyndex is again well ahead of the rivals! The reaction to the release of Zoozle Chrome browser was the release of a new browser Tyndex.Brome!The popularity of the new browser is growing daily. And the secret is not even the Tyndex.Bar installed (the Tyndex.Bar automatically fills the glass with the finest 1664 cognac after you buy Tyndex.Bottles and insert in into a USB port). It is highly popular due to the well-thought interaction with the user.Let us take, for example, the system of automatic address correction. Have you entered codehorses instead of codeforces? The gloomy Zoozle Chrome will sadly say that the address does not exist. Tyndex.Brome at the same time will automatically find the closest address and sent you there. That's brilliant!How does this splendid function work? That's simple! For each potential address a function of the F error is calculated by the following rules: for every letter ci from the potential address c the closest position j of the letter ci in the address (s) entered by the user is found. The absolute difference |i - j| of these positions is added to F. So for every i (1 ≤ i ≤ |c|) the position j is chosen such, that ci = sj, and |i - j| is minimal possible. if no such letter ci exists in the address entered by the user, then the length of the potential address |c| is added to F. After the values of the error function have been calculated for all the potential addresses the most suitable one is found. To understand the special features of the above described method better, it is recommended to realize the algorithm of calculating the F function for an address given by the user and some set of potential addresses. Good luck! | 256 megabytes | import java.util.*;
import java.io.*;
public class B62 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
int k = in.nextInt();
String s = in.next();
int next_left[][] = new int[200001][26];
int next_right[][] = new int[200001][26];
for (int j = 0; j < 26; j++) {
next_left[1][j] = -1;
next_right[s.length()][j] = -1;
}
next_left[1][(int) s.charAt(0) - (int) 'a'] = 0;
for (int j = 2; j < s.length() + 1; j++) {
for (int j1 = 0; j1 < 26; j1++) {
if (next_left[j - 1][j1] != -1) {
next_left[j][j1] = next_left[j - 1][j1] + 1;
} else {
next_left[j][j1] = -1;
}
}
next_left[j][(int) s.charAt(j - 1) - (int) 'a'] = 0;
}
next_right[s.length()][(int) s.charAt(s.length() - 1) - (int) 'a'] = 0;
for (int j = s.length() - 1; j > 0; j--) {
for (int j1 = 0; j1 < 26; j1++) {
if (next_right[j + 1][j1] != -1) {
next_right[j][j1] = next_right[j + 1][j1] + 1;
} else {
next_right[j][j1] = -1;
}
}
next_right[j][(int) s.charAt(j - 1) - (int) 'a'] = 0;
}
for (int i = s.length() + 1; i < 200001; i++) {
for (int j = 0; j < 26; j++) {
next_right[i][j] = -1;
if (next_left[i - 1][j] != -1) {
next_left[i][j] = next_left[i - 1][j] + 1;
} else {
next_left[i][j] = -1;
}
}
}
for (int i = 0; i < n; i++) {
String s1 = in.next();
long ans = 0;
for (int j = 0; j < s1.length(); j++) {
int min = -2;
if ((next_left[j + 1][(int) s1.charAt(j) - (int) 'a'] != -1)) {
min = next_left[j + 1][(int) s1.charAt(j) - (int) 'a'];
}
if ((next_right[j + 1][(int) s1.charAt(j) - (int) 'a'] != -1)) {
if (min != -2) {
min = Math.min(next_right[j + 1][(int) s1.charAt(j)
- (int) 'a'], min);
} else {
min = next_right[j + 1][(int) s1.charAt(j) - (int) 'a'];
}
}
if ((min == -2) || (min == -1)) {
ans += s1.length();
} else {
ans += min;
}
}
out.println(ans);
}
out.close();
}
}
| Java | ["2 10\ncodeforces\ncodeforces\ncodehorses", "9 9\nvkontakte\nvcontacte\nvkontrakte\nvkollapse\nvkrokodile\nvtopke\nvkapuste\nvpechke\nvk\nvcodeforcese"] | 2 seconds | ["0\n12", "18\n14\n36\n47\n14\n29\n30\n0\n84"] | null | Java 7 | standard input | [
"binary search",
"implementation"
] | a587188db6f0c17927923a158fdca1be | The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 105). They are the number of potential addresses and the length of the address entered by the user. The next line contains k lowercase Latin letters. They are the address entered by the user (s). Each next i-th (1 ≤ i ≤ n) line contains a non-empty sequence of lowercase Latin letters. They are the potential address. It is guaranteed that the total length of all the lines does not exceed 2·105. | 1,800 | On each n line of the output file print a single number: the value of the error function when the current potential address is chosen. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d). | standard output | |
PASSED | 2e86be77a09fc8209d654ad2c92eec4b | train_000.jsonl | 1298649600 | Tyndex is again well ahead of the rivals! The reaction to the release of Zoozle Chrome browser was the release of a new browser Tyndex.Brome!The popularity of the new browser is growing daily. And the secret is not even the Tyndex.Bar installed (the Tyndex.Bar automatically fills the glass with the finest 1664 cognac after you buy Tyndex.Bottles and insert in into a USB port). It is highly popular due to the well-thought interaction with the user.Let us take, for example, the system of automatic address correction. Have you entered codehorses instead of codeforces? The gloomy Zoozle Chrome will sadly say that the address does not exist. Tyndex.Brome at the same time will automatically find the closest address and sent you there. That's brilliant!How does this splendid function work? That's simple! For each potential address a function of the F error is calculated by the following rules: for every letter ci from the potential address c the closest position j of the letter ci in the address (s) entered by the user is found. The absolute difference |i - j| of these positions is added to F. So for every i (1 ≤ i ≤ |c|) the position j is chosen such, that ci = sj, and |i - j| is minimal possible. if no such letter ci exists in the address entered by the user, then the length of the potential address |c| is added to F. After the values of the error function have been calculated for all the potential addresses the most suitable one is found. To understand the special features of the above described method better, it is recommended to realize the algorithm of calculating the F function for an address given by the user and some set of potential addresses. Good luck! | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Constructor;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class CodeD
{
static class Scanner
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
public String nextLine()
{
try
{
return br.readLine();
}
catch(Exception e)
{
throw(new RuntimeException());
}
}
public String next()
{
while(!st.hasMoreTokens())
{
String l = nextLine();
if(l == null)
return null;
st = new StringTokenizer(l);
}
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 int[] nextIntArray(int n)
{
int[] res = new int[n];
for(int i = 0; i < res.length; i++)
res[i] = nextInt();
return res;
}
public long[] nextLongArray(int n)
{
long[] res = new long[n];
for(int i = 0; i < res.length; i++)
res[i] = nextLong();
return res;
}
public double[] nextDoubleArray(int n)
{
double[] res = new double[n];
for(int i = 0; i < res.length; i++)
res[i] = nextDouble();
return res;
}
public void sortIntArray(int[] array)
{
Integer[] vals = new Integer[array.length];
for(int i = 0; i < array.length; i++)
vals[i] = array[i];
Arrays.sort(vals);
for(int i = 0; i < array.length; i++)
array[i] = vals[i];
}
public void sortLongArray(long[] array)
{
Long[] vals = new Long[array.length];
for(int i = 0; i < array.length; i++)
vals[i] = array[i];
Arrays.sort(vals);
for(int i = 0; i < array.length; i++)
array[i] = vals[i];
}
public void sortDoubleArray(double[] array)
{
Double[] vals = new Double[array.length];
for(int i = 0; i < array.length; i++)
vals[i] = array[i];
Arrays.sort(vals);
for(int i = 0; i < array.length; i++)
array[i] = vals[i];
}
public String[] nextStringArray(int n)
{
String[] vals = new String[n];
for(int i = 0; i < n; i++)
vals[i] = next();
return vals;
}
Integer nextInteger()
{
String s = next();
if(s == null)
return null;
return Integer.parseInt(s);
}
int[][] nextIntMatrix(int n, int m)
{
int[][] ans = new int[n][];
for(int i = 0; i < n; i++)
ans[i] = nextIntArray(m);
return ans;
}
static <T> T fill(T arreglo, int val)
{
if(arreglo instanceof Object[])
{
Object[] a = (Object[]) arreglo;
for(Object x : a)
fill(x, val);
}
else if(arreglo instanceof int[])
Arrays.fill((int[]) arreglo, val);
else if(arreglo instanceof double[])
Arrays.fill((double[]) arreglo, val);
else if(arreglo instanceof long[])
Arrays.fill((long[]) arreglo, val);
return arreglo;
}
<T> T[] nextObjectArray(Class <T> clazz, int size)
{
@SuppressWarnings("unchecked")
T[] result = (T[]) java.lang.reflect.Array.newInstance(clazz, size);
try
{
Constructor <T> constructor = clazz.getConstructor(Scanner.class, Integer.TYPE);
for(int i = 0; i < result.length; i++)
result[i] = constructor.newInstance(this, i);
return result;
}
catch(Exception e)
{
throw new RuntimeException(e);
}
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner();
int n = sc.nextInt();
int k = sc.nextInt();
String palabra = sc.next();
String[] potenciales = sc.nextStringArray(n);
@SuppressWarnings("unchecked")
TreeSet <Integer> [] sets = new TreeSet[26];
for(int i = 0; i < 26; i++)
sets[i] = new TreeSet <Integer> ();
for(int i = 0; i < k; i++)
{
int pos = palabra.charAt(i) - 'a';
sets[pos].add(i);
}
StringBuilder sb = new StringBuilder();
for(String s : potenciales)
{
long F = 0;
for(int i = 0; i < s.length(); i++)
{
int pos = s.charAt(i) - 'a';
if(sets[pos].isEmpty())
F += s.length();
else
{
Integer mayor = sets[pos].ceiling(i);
int mejor = Integer.MAX_VALUE;
if(mayor != null)
mejor = Math.min(mejor, Math.abs(mayor - i));
Integer menor = sets[pos].floor(i);
if(menor != null)
mejor = Math.min(mejor, Math.abs(menor - i));
F += mejor;
}
}
sb.append(F);
sb.append('\n');
}
System.out.print(sb.toString());
System.out.flush();
}
} | Java | ["2 10\ncodeforces\ncodeforces\ncodehorses", "9 9\nvkontakte\nvcontacte\nvkontrakte\nvkollapse\nvkrokodile\nvtopke\nvkapuste\nvpechke\nvk\nvcodeforcese"] | 2 seconds | ["0\n12", "18\n14\n36\n47\n14\n29\n30\n0\n84"] | null | Java 7 | standard input | [
"binary search",
"implementation"
] | a587188db6f0c17927923a158fdca1be | The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 105). They are the number of potential addresses and the length of the address entered by the user. The next line contains k lowercase Latin letters. They are the address entered by the user (s). Each next i-th (1 ≤ i ≤ n) line contains a non-empty sequence of lowercase Latin letters. They are the potential address. It is guaranteed that the total length of all the lines does not exceed 2·105. | 1,800 | On each n line of the output file print a single number: the value of the error function when the current potential address is chosen. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d). | standard output | |
PASSED | 983fdc233420312ec89564cec588b776 | train_000.jsonl | 1298649600 | Tyndex is again well ahead of the rivals! The reaction to the release of Zoozle Chrome browser was the release of a new browser Tyndex.Brome!The popularity of the new browser is growing daily. And the secret is not even the Tyndex.Bar installed (the Tyndex.Bar automatically fills the glass with the finest 1664 cognac after you buy Tyndex.Bottles and insert in into a USB port). It is highly popular due to the well-thought interaction with the user.Let us take, for example, the system of automatic address correction. Have you entered codehorses instead of codeforces? The gloomy Zoozle Chrome will sadly say that the address does not exist. Tyndex.Brome at the same time will automatically find the closest address and sent you there. That's brilliant!How does this splendid function work? That's simple! For each potential address a function of the F error is calculated by the following rules: for every letter ci from the potential address c the closest position j of the letter ci in the address (s) entered by the user is found. The absolute difference |i - j| of these positions is added to F. So for every i (1 ≤ i ≤ |c|) the position j is chosen such, that ci = sj, and |i - j| is minimal possible. if no such letter ci exists in the address entered by the user, then the length of the potential address |c| is added to F. After the values of the error function have been calculated for all the potential addresses the most suitable one is found. To understand the special features of the above described method better, it is recommended to realize the algorithm of calculating the F function for an address given by the user and some set of potential addresses. Good luck! | 256 megabytes | import java.io.*;
import java.util.*;
public class B62 {
BufferedReader br;
StringTokenizer in;
PrintWriter out;
ArrayList<Integer>[] pos;
public String nextToken() throws IOException {
while (in == null || !in.hasMoreTokens()) {
in = new StringTokenizer(br.readLine());
}
return in.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
public long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
public static void main(String[] args) throws IOException {
new B62().run();
}
int[] binSearch(int id, int val) {
int L = 0;
int R = pos[id].size() - 1;
while (R - L > 1) {
int M = (R + L) / 2;
if (pos[id].get(M) >= val) {
R = M;
} else {
L = M;
}
}
return new int[]{L, R};
}
public void solve() throws IOException {
int n = nextInt();
int k = nextInt();
String s = nextToken();
pos = new ArrayList[26];
for (int i = 0; i < 26; i++) {
pos[i] = new ArrayList<Integer>();
}
for (int i = 0; i < k; i++) {
pos[(int)s.charAt(i) - (int)'a'].add(i);
}
for (int i = 0; i < n; i++) {
long err = 0;
String s1 = nextToken();
for (int j = 0; j < s1.length(); j++) {
int id = (int)s1.charAt(j) - (int)'a';
if (pos[id].isEmpty()) {
err += s1.length();
} else {
int[] a = binSearch(id, j);
err += Math.min(Math.abs(pos[id].get(a[0]) - j), Math.abs(pos[id].get(a[1]) - j));
}
}
out.println(err);
}
}
public void run() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
} | Java | ["2 10\ncodeforces\ncodeforces\ncodehorses", "9 9\nvkontakte\nvcontacte\nvkontrakte\nvkollapse\nvkrokodile\nvtopke\nvkapuste\nvpechke\nvk\nvcodeforcese"] | 2 seconds | ["0\n12", "18\n14\n36\n47\n14\n29\n30\n0\n84"] | null | Java 7 | standard input | [
"binary search",
"implementation"
] | a587188db6f0c17927923a158fdca1be | The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 105). They are the number of potential addresses and the length of the address entered by the user. The next line contains k lowercase Latin letters. They are the address entered by the user (s). Each next i-th (1 ≤ i ≤ n) line contains a non-empty sequence of lowercase Latin letters. They are the potential address. It is guaranteed that the total length of all the lines does not exceed 2·105. | 1,800 | On each n line of the output file print a single number: the value of the error function when the current potential address is chosen. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d). | standard output | |
PASSED | de494057d2c7ed4fe1ebda93b46f5750 | train_000.jsonl | 1298649600 | Tyndex is again well ahead of the rivals! The reaction to the release of Zoozle Chrome browser was the release of a new browser Tyndex.Brome!The popularity of the new browser is growing daily. And the secret is not even the Tyndex.Bar installed (the Tyndex.Bar automatically fills the glass with the finest 1664 cognac after you buy Tyndex.Bottles and insert in into a USB port). It is highly popular due to the well-thought interaction with the user.Let us take, for example, the system of automatic address correction. Have you entered codehorses instead of codeforces? The gloomy Zoozle Chrome will sadly say that the address does not exist. Tyndex.Brome at the same time will automatically find the closest address and sent you there. That's brilliant!How does this splendid function work? That's simple! For each potential address a function of the F error is calculated by the following rules: for every letter ci from the potential address c the closest position j of the letter ci in the address (s) entered by the user is found. The absolute difference |i - j| of these positions is added to F. So for every i (1 ≤ i ≤ |c|) the position j is chosen such, that ci = sj, and |i - j| is minimal possible. if no such letter ci exists in the address entered by the user, then the length of the potential address |c| is added to F. After the values of the error function have been calculated for all the potential addresses the most suitable one is found. To understand the special features of the above described method better, it is recommended to realize the algorithm of calculating the F function for an address given by the user and some set of potential addresses. Good luck! | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.StringTokenizer;
public class Counting {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
String[] line = br.readLine().split(" ");
int n = Integer.parseInt(line[0]);
char[] word = br.readLine().toCharArray();
HashMap<Character, ArrayList<Integer>> map = new HashMap<Character, ArrayList<Integer>>();
for (int i = 0; i < word.length; i++) {
if (!map.containsKey(word[i])) {
map.put(word[i], new ArrayList<Integer>());
}
map.get(word[i]).add(i);
}
for (char c : map.keySet()) {
Collections.sort(map.get(c));
}
for (int i = 0; i < n; i++) {
word = br.readLine().toCharArray();
long F = 0;
for (int j = 0; j < word.length; j++) {
if (map.containsKey(word[j])) {
ArrayList<Integer> posiciones = map.get(word[j]);
int pos = Collections.binarySearch(posiciones, j);
if (pos < 0) {
pos = -pos - 1;
if (pos == 0) {
F += Math.abs(posiciones.get(pos) - j);
} else if (pos == posiciones.size()) {
F += Math.abs(posiciones.get(pos - 1) - j);
} else {
F += Math.min(
Math.abs(posiciones.get(pos - 1) - j),
Math.abs(posiciones.get(pos) - j));
}
}
} else {
F += word.length;
}
}
System.out.println(F);
}
}
}
| Java | ["2 10\ncodeforces\ncodeforces\ncodehorses", "9 9\nvkontakte\nvcontacte\nvkontrakte\nvkollapse\nvkrokodile\nvtopke\nvkapuste\nvpechke\nvk\nvcodeforcese"] | 2 seconds | ["0\n12", "18\n14\n36\n47\n14\n29\n30\n0\n84"] | null | Java 7 | standard input | [
"binary search",
"implementation"
] | a587188db6f0c17927923a158fdca1be | The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 105). They are the number of potential addresses and the length of the address entered by the user. The next line contains k lowercase Latin letters. They are the address entered by the user (s). Each next i-th (1 ≤ i ≤ n) line contains a non-empty sequence of lowercase Latin letters. They are the potential address. It is guaranteed that the total length of all the lines does not exceed 2·105. | 1,800 | On each n line of the output file print a single number: the value of the error function when the current potential address is chosen. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d). | standard output | |
PASSED | efc5ebdb9880fa4d79db58ad979a2a7f | train_000.jsonl | 1298649600 | Tyndex is again well ahead of the rivals! The reaction to the release of Zoozle Chrome browser was the release of a new browser Tyndex.Brome!The popularity of the new browser is growing daily. And the secret is not even the Tyndex.Bar installed (the Tyndex.Bar automatically fills the glass with the finest 1664 cognac after you buy Tyndex.Bottles and insert in into a USB port). It is highly popular due to the well-thought interaction with the user.Let us take, for example, the system of automatic address correction. Have you entered codehorses instead of codeforces? The gloomy Zoozle Chrome will sadly say that the address does not exist. Tyndex.Brome at the same time will automatically find the closest address and sent you there. That's brilliant!How does this splendid function work? That's simple! For each potential address a function of the F error is calculated by the following rules: for every letter ci from the potential address c the closest position j of the letter ci in the address (s) entered by the user is found. The absolute difference |i - j| of these positions is added to F. So for every i (1 ≤ i ≤ |c|) the position j is chosen such, that ci = sj, and |i - j| is minimal possible. if no such letter ci exists in the address entered by the user, then the length of the potential address |c| is added to F. After the values of the error function have been calculated for all the potential addresses the most suitable one is found. To understand the special features of the above described method better, it is recommended to realize the algorithm of calculating the F function for an address given by the user and some set of potential addresses. Good luck! | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
public class Tynder_Brome {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] line = br.readLine().split(" ");
int n = Integer.parseInt(line[0]);
char[] word = br.readLine().toCharArray();
HashMap<Character, ArrayList<Integer>> map = new HashMap<Character, ArrayList<Integer>>();
for (int i = 0; i < word.length; i++) {
if (!map.containsKey(word[i])) {
map.put(word[i], new ArrayList<Integer>());
}
map.get(word[i]).add(i);
}
for (char c : map.keySet()) {
Collections.sort(map.get(c));
}
for (int i = 0; i < n; i++) {
word = br.readLine().toCharArray();
long F = 0;
for (int j = 0; j < word.length; j++) {
if (map.containsKey(word[j])) {
ArrayList<Integer> posiciones = map.get(word[j]);
int pos = Collections.binarySearch(posiciones, j);
if (pos < 0) {
pos = -pos - 1;
if (pos == 0) {
F += Math.abs(posiciones.get(pos) - j);
} else if (pos == posiciones.size()) {
F += Math.abs(posiciones.get(pos - 1) - j);
} else {
F += Math.min(
Math.abs(posiciones.get(pos - 1) - j),
Math.abs(posiciones.get(pos) - j));
}
}
} else {
F += word.length;
}
}
System.out.println(F);
}
}
}
| Java | ["2 10\ncodeforces\ncodeforces\ncodehorses", "9 9\nvkontakte\nvcontacte\nvkontrakte\nvkollapse\nvkrokodile\nvtopke\nvkapuste\nvpechke\nvk\nvcodeforcese"] | 2 seconds | ["0\n12", "18\n14\n36\n47\n14\n29\n30\n0\n84"] | null | Java 7 | standard input | [
"binary search",
"implementation"
] | a587188db6f0c17927923a158fdca1be | The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 105). They are the number of potential addresses and the length of the address entered by the user. The next line contains k lowercase Latin letters. They are the address entered by the user (s). Each next i-th (1 ≤ i ≤ n) line contains a non-empty sequence of lowercase Latin letters. They are the potential address. It is guaranteed that the total length of all the lines does not exceed 2·105. | 1,800 | On each n line of the output file print a single number: the value of the error function when the current potential address is chosen. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d). | standard output | |
PASSED | 8de3e06d924135bb95983dd8be90f8a6 | train_000.jsonl | 1298649600 | Tyndex is again well ahead of the rivals! The reaction to the release of Zoozle Chrome browser was the release of a new browser Tyndex.Brome!The popularity of the new browser is growing daily. And the secret is not even the Tyndex.Bar installed (the Tyndex.Bar automatically fills the glass with the finest 1664 cognac after you buy Tyndex.Bottles and insert in into a USB port). It is highly popular due to the well-thought interaction with the user.Let us take, for example, the system of automatic address correction. Have you entered codehorses instead of codeforces? The gloomy Zoozle Chrome will sadly say that the address does not exist. Tyndex.Brome at the same time will automatically find the closest address and sent you there. That's brilliant!How does this splendid function work? That's simple! For each potential address a function of the F error is calculated by the following rules: for every letter ci from the potential address c the closest position j of the letter ci in the address (s) entered by the user is found. The absolute difference |i - j| of these positions is added to F. So for every i (1 ≤ i ≤ |c|) the position j is chosen such, that ci = sj, and |i - j| is minimal possible. if no such letter ci exists in the address entered by the user, then the length of the potential address |c| is added to F. After the values of the error function have been calculated for all the potential addresses the most suitable one is found. To understand the special features of the above described method better, it is recommended to realize the algorithm of calculating the F function for an address given by the user and some set of potential addresses. Good luck! | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Main {
static ArrayList<Integer>[] arreglos;
static int length;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb=new StringBuilder();
arreglos=new ArrayList[27];
String[] r=br.readLine().split(" ");
int p=Integer.parseInt(r[0]);
length=Integer.parseInt(r[1]);
String adress=br.readLine();
for (int i=0;i<27;i++){
arreglos[i]=new ArrayList<Integer>();
}
for (int i=0;i<length;i++){
arreglos[adress.charAt(i)-'a'].add(i);
}
while (p-->0){
long f=0;
String linea=br.readLine();
int min=Math.min(length,linea.length());
for (int i=0;i<min;i++){
if (linea.charAt(i)!=adress.charAt(i)){
int aux=binarySearch(i,linea.charAt(i)-'a');
if (aux==-1){
f+=linea.length();
}
else{
f+=Math.abs(aux-i);
}
}
}
for (int i=min;i<linea.length();i++){
int aux=binarySearch(i,linea.charAt(i)-'a');
if (aux==-1){
f+=linea.length();
}
else{
f+=Math.abs(aux-i);
}
}
sb.append(f);
sb.append("\n");
}
System.out.print(sb);
}
static int binarySearch(int x, int pos) {
ArrayList<Integer> array=arreglos[pos];
if (array.size()==0){
return -1;
}
int i=0;
int j=array.size()-1;
if (x>=array.get(j)){
return array.get(j);
}
if (x<=array.get(i)){
return array.get(i);
}
while (i<=j){
int mid=(i+j)/2;
if (array.get(mid)<=x && array.get(mid+1)>x){
if (Math.abs(array.get(mid)-x) < Math.abs(array.get(mid+1)-x)){
return array.get(mid);
}
else{
return array.get(mid+1);
}
}
else if(array.get(mid) > x){
j=mid-1;
}
else{
i=mid+1;
}
}
return 0;
}
}
| Java | ["2 10\ncodeforces\ncodeforces\ncodehorses", "9 9\nvkontakte\nvcontacte\nvkontrakte\nvkollapse\nvkrokodile\nvtopke\nvkapuste\nvpechke\nvk\nvcodeforcese"] | 2 seconds | ["0\n12", "18\n14\n36\n47\n14\n29\n30\n0\n84"] | null | Java 7 | standard input | [
"binary search",
"implementation"
] | a587188db6f0c17927923a158fdca1be | The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 105). They are the number of potential addresses and the length of the address entered by the user. The next line contains k lowercase Latin letters. They are the address entered by the user (s). Each next i-th (1 ≤ i ≤ n) line contains a non-empty sequence of lowercase Latin letters. They are the potential address. It is guaranteed that the total length of all the lines does not exceed 2·105. | 1,800 | On each n line of the output file print a single number: the value of the error function when the current potential address is chosen. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d). | standard output | |
PASSED | 55753d3184031d02ef573b1273c77d2c | train_000.jsonl | 1298649600 | Tyndex is again well ahead of the rivals! The reaction to the release of Zoozle Chrome browser was the release of a new browser Tyndex.Brome!The popularity of the new browser is growing daily. And the secret is not even the Tyndex.Bar installed (the Tyndex.Bar automatically fills the glass with the finest 1664 cognac after you buy Tyndex.Bottles and insert in into a USB port). It is highly popular due to the well-thought interaction with the user.Let us take, for example, the system of automatic address correction. Have you entered codehorses instead of codeforces? The gloomy Zoozle Chrome will sadly say that the address does not exist. Tyndex.Brome at the same time will automatically find the closest address and sent you there. That's brilliant!How does this splendid function work? That's simple! For each potential address a function of the F error is calculated by the following rules: for every letter ci from the potential address c the closest position j of the letter ci in the address (s) entered by the user is found. The absolute difference |i - j| of these positions is added to F. So for every i (1 ≤ i ≤ |c|) the position j is chosen such, that ci = sj, and |i - j| is minimal possible. if no such letter ci exists in the address entered by the user, then the length of the potential address |c| is added to F. After the values of the error function have been calculated for all the potential addresses the most suitable one is found. To understand the special features of the above described method better, it is recommended to realize the algorithm of calculating the F function for an address given by the user and some set of potential addresses. Good luck! | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Main {
static ArrayList<Integer>[] arreglos;
static int length;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb=new StringBuilder();
arreglos=new ArrayList[27];
String[] r=br.readLine().split(" ");
int p=Integer.parseInt(r[0]);
length=Integer.parseInt(r[1]);
String adress=br.readLine();
for (int i=0;i<27;i++){
arreglos[i]=new ArrayList<Integer>();
}
for (int i=0;i<length;i++){
arreglos[adress.charAt(i)-'a'].add(i);
}
while (p-->0){
long f=0;
String linea=br.readLine();
int min=Math.min(length,linea.length());
for (int i=0;i<min;i++){
if (linea.charAt(i)!=adress.charAt(i)){
int aux=binarySearch(i,linea.charAt(i)-'a');
if (aux==-1){
f+=linea.length();
}
else{
f+=Math.abs(aux-i);
}
}
}
for (int i=min;i<linea.length();i++){
int aux=binarySearch(i,linea.charAt(i)-'a');
if (aux==-1){
f+=linea.length();
}
else{
f+=Math.abs(aux-i);
}
}
sb.append(f);
sb.append("\n");
}
System.out.print(sb);
}
static int binarySearch(int x, int pos) {
ArrayList<Integer> array=arreglos[pos];
if (array.size()==0){
return -1;
}
int i=0;
int j=array.size()-1;
if (x>=array.get(j)){
return array.get(j);
}
if (x<=array.get(i)){
return array.get(i);
}
while (i<=j){
int mid=(i+j)/2;
if (array.get(mid)<=x && array.get(mid+1)>x){
if (Math.abs(array.get(mid)-x) < Math.abs(array.get(mid+1)-x)){
return array.get(mid);
}
else{
return array.get(mid+1);
}
}
else if(array.get(mid) > x){
j=mid-1;
}
else{
i=mid+1;
}
}
return 0;
}
}
| Java | ["2 10\ncodeforces\ncodeforces\ncodehorses", "9 9\nvkontakte\nvcontacte\nvkontrakte\nvkollapse\nvkrokodile\nvtopke\nvkapuste\nvpechke\nvk\nvcodeforcese"] | 2 seconds | ["0\n12", "18\n14\n36\n47\n14\n29\n30\n0\n84"] | null | Java 7 | standard input | [
"binary search",
"implementation"
] | a587188db6f0c17927923a158fdca1be | The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 105). They are the number of potential addresses and the length of the address entered by the user. The next line contains k lowercase Latin letters. They are the address entered by the user (s). Each next i-th (1 ≤ i ≤ n) line contains a non-empty sequence of lowercase Latin letters. They are the potential address. It is guaranteed that the total length of all the lines does not exceed 2·105. | 1,800 | On each n line of the output file print a single number: the value of the error function when the current potential address is chosen. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d). | standard output | |
PASSED | 9db7fcb08863de521f7a67e72f774d98 | train_000.jsonl | 1298649600 | Tyndex is again well ahead of the rivals! The reaction to the release of Zoozle Chrome browser was the release of a new browser Tyndex.Brome!The popularity of the new browser is growing daily. And the secret is not even the Tyndex.Bar installed (the Tyndex.Bar automatically fills the glass with the finest 1664 cognac after you buy Tyndex.Bottles and insert in into a USB port). It is highly popular due to the well-thought interaction with the user.Let us take, for example, the system of automatic address correction. Have you entered codehorses instead of codeforces? The gloomy Zoozle Chrome will sadly say that the address does not exist. Tyndex.Brome at the same time will automatically find the closest address and sent you there. That's brilliant!How does this splendid function work? That's simple! For each potential address a function of the F error is calculated by the following rules: for every letter ci from the potential address c the closest position j of the letter ci in the address (s) entered by the user is found. The absolute difference |i - j| of these positions is added to F. So for every i (1 ≤ i ≤ |c|) the position j is chosen such, that ci = sj, and |i - j| is minimal possible. if no such letter ci exists in the address entered by the user, then the length of the potential address |c| is added to F. After the values of the error function have been calculated for all the potential addresses the most suitable one is found. To understand the special features of the above described method better, it is recommended to realize the algorithm of calculating the F function for an address given by the user and some set of potential addresses. Good luck! | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Main {
static ArrayList<Integer>[] arreglos;
static int length;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb=new StringBuilder();
arreglos=new ArrayList[27];
String[] r=br.readLine().split(" ");
int p=Integer.parseInt(r[0]);
length=Integer.parseInt(r[1]);
String adress=br.readLine();
for (int i=0;i<27;i++){
arreglos[i]=new ArrayList<Integer>();
}
for (int i=0;i<length;i++){
arreglos[adress.charAt(i)-'a'].add(i);
}
while (p-->0){
long f=0;
String linea=br.readLine();
int min=Math.min(length,linea.length());
for (int i=0;i<min;i++){
if (linea.charAt(i)!=adress.charAt(i)){
int aux=binarySearch(i,linea.charAt(i)-'a');
if (aux==-1){
f+=linea.length();
}
else{
f+=Math.abs(aux-i);
}
}
}
for (int i=min;i<linea.length();i++){
int aux=binarySearch(i,linea.charAt(i)-'a');
if (aux==-1){
f+=linea.length();
}
else{
f+=Math.abs(aux-i);
}
}
sb.append(f);
sb.append("\n");
}
System.out.print(sb);
}
static int binarySearch(int x, int pos) {
ArrayList<Integer> array=arreglos[pos];
if (array.size()==0){
return -1;
}
int i=0;
int j=array.size()-1;
if (x>=array.get(j)){
return array.get(j);
}
if (x<=array.get(i)){
return array.get(i);
}
while (i<=j){
int mid=(i+j)/2;
if (array.get(mid)<=x && array.get(mid+1)>x){
if (Math.abs(array.get(mid)-x) < Math.abs(array.get(mid+1)-x)){
return array.get(mid);
}
else{
return array.get(mid+1);
}
}
else if(array.get(mid) > x){
j=mid-1;
}
else{
i=mid+1;
}
}
return 0;
}
} | Java | ["2 10\ncodeforces\ncodeforces\ncodehorses", "9 9\nvkontakte\nvcontacte\nvkontrakte\nvkollapse\nvkrokodile\nvtopke\nvkapuste\nvpechke\nvk\nvcodeforcese"] | 2 seconds | ["0\n12", "18\n14\n36\n47\n14\n29\n30\n0\n84"] | null | Java 7 | standard input | [
"binary search",
"implementation"
] | a587188db6f0c17927923a158fdca1be | The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 105). They are the number of potential addresses and the length of the address entered by the user. The next line contains k lowercase Latin letters. They are the address entered by the user (s). Each next i-th (1 ≤ i ≤ n) line contains a non-empty sequence of lowercase Latin letters. They are the potential address. It is guaranteed that the total length of all the lines does not exceed 2·105. | 1,800 | On each n line of the output file print a single number: the value of the error function when the current potential address is chosen. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d). | standard output | |
PASSED | f358ddb0cbd415081b07b13a01cacd20 | train_000.jsonl | 1298649600 | Tyndex is again well ahead of the rivals! The reaction to the release of Zoozle Chrome browser was the release of a new browser Tyndex.Brome!The popularity of the new browser is growing daily. And the secret is not even the Tyndex.Bar installed (the Tyndex.Bar automatically fills the glass with the finest 1664 cognac after you buy Tyndex.Bottles and insert in into a USB port). It is highly popular due to the well-thought interaction with the user.Let us take, for example, the system of automatic address correction. Have you entered codehorses instead of codeforces? The gloomy Zoozle Chrome will sadly say that the address does not exist. Tyndex.Brome at the same time will automatically find the closest address and sent you there. That's brilliant!How does this splendid function work? That's simple! For each potential address a function of the F error is calculated by the following rules: for every letter ci from the potential address c the closest position j of the letter ci in the address (s) entered by the user is found. The absolute difference |i - j| of these positions is added to F. So for every i (1 ≤ i ≤ |c|) the position j is chosen such, that ci = sj, and |i - j| is minimal possible. if no such letter ci exists in the address entered by the user, then the length of the potential address |c| is added to F. After the values of the error function have been calculated for all the potential addresses the most suitable one is found. To understand the special features of the above described method better, it is recommended to realize the algorithm of calculating the F function for an address given by the user and some set of potential addresses. Good luck! | 256 megabytes | import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Scanner;
public class Main{
static ArrayList<Integer> index[] = new ArrayList[27];
static String usuario;
public static int router(char c){
if(c=='a'){
return 1;
}
else{
return (int) c-'a'+1;
}
}
public static int buscarIndice(ArrayList<Integer> list,int indice){
int a=0,b=0,anterior=list.get(0);
for(Integer i: list){
if(i>=indice){
a = anterior;b=i;
break;
}
anterior = i;
}
if(b==0){
b = list.get(list.size()-1);
}
if(abs(b-indice)<abs(a-indice)){
return abs(b-indice);
}
else{
return abs(a-indice);
}
}
public static int abs(int a){
return a>0?a:-1*a;
}
public static BigInteger calcularError(String s){
int posicion;
BigInteger suma = BigInteger.ZERO;
long tamanno = s.length();
for(int j=0;j<tamanno;j++){
posicion = router(s.charAt(j));
if(index[posicion].isEmpty()){
suma = suma.add(BigInteger.valueOf(tamanno));
}
else if(j<usuario.length() && s.charAt(j)==usuario.charAt(j)){
continue;
}
else{
suma = suma.add(BigInteger.valueOf(buscarIndice(index[posicion],j)));
}
}
return suma;
}
public static void indexador(String s){
int posicion;
for(int j=0;j<s.length();j++){
posicion = router(s.charAt(j));
index[posicion].add(j);
}
}
public static void main(String[] args){
int i,hosdf;
for(i=0;i<27;i++){
index[i] = new ArrayList<>();
}
Scanner scan = new Scanner(System.in);
String s;
String sArray[];
int a,b;
s = scan.nextLine();
sArray = s.trim().split(" ");
a = Integer.parseInt(sArray[0]);
b = Integer.parseInt(sArray[1]);
usuario = scan.nextLine();
indexador(usuario);
for(int k=0;k<a;k++){
s = scan.nextLine();
if(s.equals(usuario)){
System.out.println(0);
}
else{
System.out.println(calcularError(s));
}
}
}
} | Java | ["2 10\ncodeforces\ncodeforces\ncodehorses", "9 9\nvkontakte\nvcontacte\nvkontrakte\nvkollapse\nvkrokodile\nvtopke\nvkapuste\nvpechke\nvk\nvcodeforcese"] | 2 seconds | ["0\n12", "18\n14\n36\n47\n14\n29\n30\n0\n84"] | null | Java 7 | standard input | [
"binary search",
"implementation"
] | a587188db6f0c17927923a158fdca1be | The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 105). They are the number of potential addresses and the length of the address entered by the user. The next line contains k lowercase Latin letters. They are the address entered by the user (s). Each next i-th (1 ≤ i ≤ n) line contains a non-empty sequence of lowercase Latin letters. They are the potential address. It is guaranteed that the total length of all the lines does not exceed 2·105. | 1,800 | On each n line of the output file print a single number: the value of the error function when the current potential address is chosen. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d). | standard output | |
PASSED | c87e7f99979b1b2808c06a3194c199be | train_000.jsonl | 1298649600 | Tyndex is again well ahead of the rivals! The reaction to the release of Zoozle Chrome browser was the release of a new browser Tyndex.Brome!The popularity of the new browser is growing daily. And the secret is not even the Tyndex.Bar installed (the Tyndex.Bar automatically fills the glass with the finest 1664 cognac after you buy Tyndex.Bottles and insert in into a USB port). It is highly popular due to the well-thought interaction with the user.Let us take, for example, the system of automatic address correction. Have you entered codehorses instead of codeforces? The gloomy Zoozle Chrome will sadly say that the address does not exist. Tyndex.Brome at the same time will automatically find the closest address and sent you there. That's brilliant!How does this splendid function work? That's simple! For each potential address a function of the F error is calculated by the following rules: for every letter ci from the potential address c the closest position j of the letter ci in the address (s) entered by the user is found. The absolute difference |i - j| of these positions is added to F. So for every i (1 ≤ i ≤ |c|) the position j is chosen such, that ci = sj, and |i - j| is minimal possible. if no such letter ci exists in the address entered by the user, then the length of the potential address |c| is added to F. After the values of the error function have been calculated for all the potential addresses the most suitable one is found. To understand the special features of the above described method better, it is recommended to realize the algorithm of calculating the F function for an address given by the user and some set of potential addresses. Good luck! | 256 megabytes | import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Scanner;
public class Main{
static ArrayList<Integer> index[] = new ArrayList[27];
static String usuario;
public static int router(char c){
if(c=='a'){
return 1;
}
else{
return (int) c-'a'+1;
}
}
public static int buscarIndice(ArrayList<Integer> list,int indice){
int a=0,b=0,anterior=list.get(0);
for(Integer i: list){
if(i>=indice){
a = anterior;b=i;
break;
}
anterior = i;
}
if(b==0){
b = list.get(list.size()-1);
}
if(abs(b-indice)<abs(a-indice)){
return abs(b-indice);
}
else{
return abs(a-indice);
}
}
public static int abs(int a){
return a>0?a:-1*a;
}
public static BigInteger calcularError(String s){
int posicion;
BigInteger suma = BigInteger.ZERO;
long tamanno = s.length();
for(int j=0;j<tamanno;j++){
posicion = router(s.charAt(j));
if(index[posicion].isEmpty()){
suma = suma.add(BigInteger.valueOf(tamanno));
}
else if(j<usuario.length() && s.charAt(j)==usuario.charAt(j)){
continue;
}
else{
suma = suma.add(BigInteger.valueOf(buscarIndice(index[posicion],j)));
}
}
return suma;
}
public static void indexador(String s){
int posicion;
for(int j=0;j<s.length();j++){
posicion = router(s.charAt(j));
index[posicion].add(j);
}
}
public static void main(String[] args){
int i;
for(i=0;i<27;i++){
index[i] = new ArrayList<>();
}
Scanner scan = new Scanner(System.in);
String s;
String sArray[];
int a,b;
s = scan.nextLine();
sArray = s.trim().split(" ");
a = Integer.parseInt(sArray[0]);
b = Integer.parseInt(sArray[1]);
usuario = scan.nextLine();
indexador(usuario);
for(int k=0;k<a;k++){
s = scan.nextLine();
if(s.equals(usuario)){
System.out.println(0);
}
else{
System.out.println(calcularError(s));
}
}
}
} | Java | ["2 10\ncodeforces\ncodeforces\ncodehorses", "9 9\nvkontakte\nvcontacte\nvkontrakte\nvkollapse\nvkrokodile\nvtopke\nvkapuste\nvpechke\nvk\nvcodeforcese"] | 2 seconds | ["0\n12", "18\n14\n36\n47\n14\n29\n30\n0\n84"] | null | Java 7 | standard input | [
"binary search",
"implementation"
] | a587188db6f0c17927923a158fdca1be | The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 105). They are the number of potential addresses and the length of the address entered by the user. The next line contains k lowercase Latin letters. They are the address entered by the user (s). Each next i-th (1 ≤ i ≤ n) line contains a non-empty sequence of lowercase Latin letters. They are the potential address. It is guaranteed that the total length of all the lines does not exceed 2·105. | 1,800 | On each n line of the output file print a single number: the value of the error function when the current potential address is chosen. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d). | standard output | |
PASSED | 63d78e9f551c1d4b1f50580c23185144 | train_000.jsonl | 1298649600 | Tyndex is again well ahead of the rivals! The reaction to the release of Zoozle Chrome browser was the release of a new browser Tyndex.Brome!The popularity of the new browser is growing daily. And the secret is not even the Tyndex.Bar installed (the Tyndex.Bar automatically fills the glass with the finest 1664 cognac after you buy Tyndex.Bottles and insert in into a USB port). It is highly popular due to the well-thought interaction with the user.Let us take, for example, the system of automatic address correction. Have you entered codehorses instead of codeforces? The gloomy Zoozle Chrome will sadly say that the address does not exist. Tyndex.Brome at the same time will automatically find the closest address and sent you there. That's brilliant!How does this splendid function work? That's simple! For each potential address a function of the F error is calculated by the following rules: for every letter ci from the potential address c the closest position j of the letter ci in the address (s) entered by the user is found. The absolute difference |i - j| of these positions is added to F. So for every i (1 ≤ i ≤ |c|) the position j is chosen such, that ci = sj, and |i - j| is minimal possible. if no such letter ci exists in the address entered by the user, then the length of the potential address |c| is added to F. After the values of the error function have been calculated for all the potential addresses the most suitable one is found. To understand the special features of the above described method better, it is recommended to realize the algorithm of calculating the F function for an address given by the user and some set of potential addresses. Good luck! | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class tyndexBrome {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(in.readLine());
int n = Integer.parseInt(st.nextToken());
int k = Integer.parseInt(st.nextToken());
String s = in.readLine();
ArrayList<Integer> pos[] = new ArrayList[26];
for (int i = 0; i < pos.length; i++) {
pos[i] = new ArrayList<Integer>();
}
for (int i = 0; i < s.length(); i++) {
pos[s.charAt(i) - 'a'].add(i);
}
for (int i = 0; i < n; i++) {
long sum = 0;
s = in.readLine();
for (int j = 0; j < s.length(); j++) {
int ind = s.charAt(j) - 'a';
if (pos[ind].size() == 0) {
sum += s.length();
} else if (j <= pos[ind].get(0)) {
sum += pos[ind].get(0) - j;
} else if (j >= pos[ind].get(pos[ind].size() - 1)) {
sum += j - pos[ind].get(pos[ind].size() - 1);
} else {
int a = 0, b = pos[ind].size();
while (a < b) {
int m = (a + b + 1) / 2;
if (pos[ind].get(m) > j)
b = m - 1;
else
a = m;
}
sum += Math.min(j - pos[ind].get(a), pos[ind].get(a + 1) - j);
}
}
System.out.println(sum);
}
}
}
| Java | ["2 10\ncodeforces\ncodeforces\ncodehorses", "9 9\nvkontakte\nvcontacte\nvkontrakte\nvkollapse\nvkrokodile\nvtopke\nvkapuste\nvpechke\nvk\nvcodeforcese"] | 2 seconds | ["0\n12", "18\n14\n36\n47\n14\n29\n30\n0\n84"] | null | Java 7 | standard input | [
"binary search",
"implementation"
] | a587188db6f0c17927923a158fdca1be | The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 105). They are the number of potential addresses and the length of the address entered by the user. The next line contains k lowercase Latin letters. They are the address entered by the user (s). Each next i-th (1 ≤ i ≤ n) line contains a non-empty sequence of lowercase Latin letters. They are the potential address. It is guaranteed that the total length of all the lines does not exceed 2·105. | 1,800 | On each n line of the output file print a single number: the value of the error function when the current potential address is chosen. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d). | standard output | |
PASSED | c9a9ed2c51858d650d524396a436e0d6 | train_000.jsonl | 1298649600 | Tyndex is again well ahead of the rivals! The reaction to the release of Zoozle Chrome browser was the release of a new browser Tyndex.Brome!The popularity of the new browser is growing daily. And the secret is not even the Tyndex.Bar installed (the Tyndex.Bar automatically fills the glass with the finest 1664 cognac after you buy Tyndex.Bottles and insert in into a USB port). It is highly popular due to the well-thought interaction with the user.Let us take, for example, the system of automatic address correction. Have you entered codehorses instead of codeforces? The gloomy Zoozle Chrome will sadly say that the address does not exist. Tyndex.Brome at the same time will automatically find the closest address and sent you there. That's brilliant!How does this splendid function work? That's simple! For each potential address a function of the F error is calculated by the following rules: for every letter ci from the potential address c the closest position j of the letter ci in the address (s) entered by the user is found. The absolute difference |i - j| of these positions is added to F. So for every i (1 ≤ i ≤ |c|) the position j is chosen such, that ci = sj, and |i - j| is minimal possible. if no such letter ci exists in the address entered by the user, then the length of the potential address |c| is added to F. After the values of the error function have been calculated for all the potential addresses the most suitable one is found. To understand the special features of the above described method better, it is recommended to realize the algorithm of calculating the F function for an address given by the user and some set of potential addresses. Good luck! | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class tyndex {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(in.readLine());
int n = Integer.parseInt(st.nextToken());
int k = Integer.parseInt(st.nextToken());
String s = in.readLine();
ArrayList<Integer> l[] = new ArrayList[26];
for (int i = 0; i < 26; i++) {
l[i] = new ArrayList<Integer>();
}
for (int i = 0; i < s.length(); i++) {
l[s.charAt(i) - 'a'].add(i);
}
for (int i = 0; i < n; i++) {
long F = 0;
s = in.readLine();
for (int j = 0; j < s.length(); j++) {
int c = s.charAt(j) - 'a';
// System.out.print(s.charAt(j) + " ");
if (l[c].size() == 0) {
F += (long) s.length();
} else if (l[c].get(0) >= j) {
F += (long) l[c].get(0) - j;
} else if (l[c].get(l[c].size() - 1) <= j) {
F += (long) j - l[c].get(l[c].size() - 1);
} else {
int lb, ub = 0;
int a = 0, b = l[c].size() - 1;
while (a < b) {
int m = (a + b + 1) / 2;
if (l[c].get(m) > j)
b = m - 1;
else
a = m;
}
if (a != -1)
lb = l[c].get(a);
else
lb = -1;
if (b < l[c].size())
ub = l[c].get(a + 1);
else
ub = -1;
// System.out.println(ub);
if (lb == -1)
F += (long) ub - j;
else if (ub == -1)
F += (long) j - lb;
else
F += (long) Math.min(ub - j, j - lb);
}
}
System.out.println(F);
}
}
}
| Java | ["2 10\ncodeforces\ncodeforces\ncodehorses", "9 9\nvkontakte\nvcontacte\nvkontrakte\nvkollapse\nvkrokodile\nvtopke\nvkapuste\nvpechke\nvk\nvcodeforcese"] | 2 seconds | ["0\n12", "18\n14\n36\n47\n14\n29\n30\n0\n84"] | null | Java 7 | standard input | [
"binary search",
"implementation"
] | a587188db6f0c17927923a158fdca1be | The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 105). They are the number of potential addresses and the length of the address entered by the user. The next line contains k lowercase Latin letters. They are the address entered by the user (s). Each next i-th (1 ≤ i ≤ n) line contains a non-empty sequence of lowercase Latin letters. They are the potential address. It is guaranteed that the total length of all the lines does not exceed 2·105. | 1,800 | On each n line of the output file print a single number: the value of the error function when the current potential address is chosen. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d). | standard output | |
PASSED | 46a9826ce55d05d2fadd493e6122f742 | train_000.jsonl | 1540740900 | Janusz is a businessman. He owns a company "Januszex", which produces games for teenagers. Last hit of Januszex was a cool one-person game "Make it one". The player is given a sequence of $$$n$$$ integers $$$a_i$$$.It is allowed to select any subset of them, and the score is equal to the greatest common divisor of selected elements. The goal is to take as little elements as it is possible, getting the score $$$1$$$. Now Janusz wonders, for given sequence, how much elements should the player choose? | 256 megabytes | import java.util.*;
public class MakeItOne {
static int LIM = 300001;
public static void main (String [] arg) throws Throwable {
int [] sieveprimes = new int [LIM];
int [] factorization = new int [LIM+1];
int [] prev = new int [LIM+1];
int [] primecount = new int [LIM+1];
boolean [] composite = new boolean [LIM+1];
int primeptr = 0;
for (int j = 2; j<=LIM; j++) {
if (composite[j]) {
int p = factorization[j];
int j2 = j;
while (j2> 0 && j2 % p == 0) j2 /=p;
primecount[j] = 1 + primecount[j2];
prev[j] = j2;
continue;
}
factorization[j] = j;
primecount[j] = 1;
sieveprimes[primeptr++] = j;
for (int k = j+j; k<=LIM; k+=j) {
composite[k] = true;
factorization[k] = j;
}
}
int n = (int)nextLong();
int [] score = new int [n];
int [] primes = new int [7];
int [] inputcount = new int [LIM];
boolean [] used = new boolean [LIM];
int pptr = 0;
int MINSCORE = Integer.MAX_VALUE;
int MINPRIME = Integer.MAX_VALUE;
for (int i = 0; i<n; ++i) {
score[i] = (int)nextLong();
if (score[i] == 1) { System.out.println(1); return;}
int N = score[i];
while (N != 1) {
int p = factorization[N];
inputcount[p]++;
while (N % p == 0) N/= p;
}
}
int pmax = 2;
int MAXCNT = inputcount[2];
for (int i = 3; i<inputcount.length; i+=2) if (!composite[i] && inputcount[i] > MAXCNT) {
MAXCNT = inputcount[i];
pmax = i;
}
boolean found = false;
int ANS = 7;
int loops = 0;
for (int ii = 0; ii<n && ANS > 2; ++ii) {
if (score[ii] % pmax == 0) continue;
int N = score[ii];
int PROD = 1;
pptr = 0;
while (N != 1) {
int p = factorization[N];
PROD *= p;
primes[pptr++] = p;
while (N % p == 0) N/= p;
}
if (used[PROD]) continue;
used[PROD] = true;
loops++;
boolean [] bitmask = new boolean [1<<pptr];
for (int i = 0; i<n; ++i) {
int MASK = 0;
for (int j = 0; j<pptr; ++j) {
if (score[i] % primes[j] == 0)
MASK = MASK | (1<<j);
}
bitmask[MASK] = true;
}
int MASK = (1<<pptr) - 1;
for (int i = 0; i<bitmask.length; ++i) {
if (!bitmask[i]) continue;
if ((MASK & i) == 0) ANS = Math.min(ANS, 2);
for (int j = i+1; j<bitmask.length && ANS > 3; ++j) {
if (!bitmask[j]) continue;
if ((MASK & i & j) == 0) ANS = Math.min(ANS, 3);
for (int k = j+1; k<bitmask.length && ANS > 4; ++k) {
if (!bitmask[k]) continue;
if ((MASK & i & j & k) == 0) ANS = Math.min(ANS, 4);
for (int L=k+1; L<bitmask.length && ANS > 5; ++L) {
if (!bitmask[L]) continue;
if ((MASK & i & j & k & L) == 0) ANS = Math.min(ANS, 5);
for (int M=L+1; M<bitmask.length && ANS > 6; ++M) {
if (!bitmask[M]) continue;
if ((MASK & i & j & k & L & M) == 0) ANS = Math.min(ANS, 6);
}
}
}
}
}
found = true;
break;
}
if (!found) {System.out.println(-1); return;}
System.out.println(ANS);
}
public static long nextLong() throws Throwable {
long i = System.in.read();
boolean neg = false;
while (i < 45) i = System.in.read();
if (i == 45) {neg=true;i=48;}
i = i - 48;
long j = System.in.read();
while (j > 32) {
i*=10;
i+=j-48;
j = System.in.read();
}
return (neg) ? -i : i;
}
} | Java | ["3\n10 6 15", "3\n2 4 6", "7\n30 60 21 42 70 15 30"] | 3 seconds | ["3", "-1", "3"] | NoteIn the first example, selecting a subset of all numbers gives a gcd of $$$1$$$ and for all smaller subsets the gcd is greater than $$$1$$$.In the second example, for all subsets of numbers the gcd is at least $$$2$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"number theory",
"bitmasks",
"shortest paths",
"math"
] | 3baa00206d3bf03ce02a414747e2a633 | The first line contains an only integer $$$n$$$ ($$$1 \le n \le 300\,000$$$) — the number of integers in the sequence. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 300\,000$$$). | 2,500 | If there is no subset of the given sequence with gcd equal to $$$1$$$, output -1. Otherwise, output exactly one integer — the size of the smallest subset with gcd equal to $$$1$$$. | standard output | |
PASSED | 554ea0aeea708640121ce5ab1b940756 | train_000.jsonl | 1540740900 | Janusz is a businessman. He owns a company "Januszex", which produces games for teenagers. Last hit of Januszex was a cool one-person game "Make it one". The player is given a sequence of $$$n$$$ integers $$$a_i$$$.It is allowed to select any subset of them, and the score is equal to the greatest common divisor of selected elements. The goal is to take as little elements as it is possible, getting the score $$$1$$$. Now Janusz wonders, for given sequence, how much elements should the player choose? | 256 megabytes | import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.StringTokenizer;
public class Main {
static class Task {
int NN = 300005;
int MOD = 1000000007;
int INF = 2009000000;
long INFINITY = 2000000000000000000L;
int [] a;
long [] c = new long[NN];
long [] fac = new long[NN];
long [][] dp = new long[10][NN];
long expo(long x, long y) {
long r = 1;
long sq = x;
while(y>0) {
if(y%2!=0) {
r = (r * sq)%MOD;
}
y >>= 1;
sq = (sq * sq) % MOD;
}
return r;
}
long ncr(long n, long r) {
if(r > n)
return 0;
long ret = fac[(int) n];
ret = (ret * expo(fac[(int) (n-r)], MOD - 2))%MOD;
ret = (ret * expo(fac[(int) r], MOD - 2))%MOD;
return ret;
}
public void solve(InputReader in, PrintWriter out) {
int n= in.nextInt();
a = new int[n];
Arrays.fill(c, 0);
fac[0] = 1;
for(int i=1;i<NN;++i) {
fac[i] = (1L * i * fac[i - 1]) % MOD;
}
for(int i=0;i<n;++i) {
a[i] = in.nextInt();
for(int j=1;j*j<=a[i];++j) {
if(a[i]%j != 0)
continue;
int f1 = j;
int f2 = a[i]/ j;
++c[f1];
if(f1 != f2)++c[f2];
}
}
for(int i=1;i<10;++i) {
for(int j=NN-1;j>=1;--j) {
dp[i][j] = ncr(c[j], i);
for(int k=2;k*j<NN;++k)
dp[i][j] = (dp[i][j] - dp[i][k*j] + MOD) % MOD;
}
if(dp[i][1] > 0) {
out.println(i);return;
}
}
out.println(-1);
}
}
static void prepareIO(boolean isFileIO) {
//long t1 = System.currentTimeMillis();
Task solver = new Task();
// Standard IO
if(!isFileIO) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
solver.solve(in, out);
//out.println("time(s): " + (1.0*(System.currentTimeMillis()-t1))/1000.0);
out.close();
}
// File IO
else {
String IPfilePath = System.getProperty("user.home") + "/Downloads/ip.in";
String OPfilePath = System.getProperty("user.home") + "/Downloads/op.out";
InputReader fin = new InputReader(IPfilePath);
PrintWriter fout = null;
try {
fout = new PrintWriter(new File(OPfilePath));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
solver.solve(fin, fout);
//fout.println("time(s): " + (1.0*(System.currentTimeMillis()-t1))/1000.0);
fout.close();
}
}
public static void main(String[] args) {
prepareIO(false);
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public InputReader(String filePath) {
File file = new File(filePath);
try {
reader = new BufferedReader(new FileReader(file));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tokenizer = null;
}
public String nextLine() {
String str = "";
try {
str = reader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}
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 | ["3\n10 6 15", "3\n2 4 6", "7\n30 60 21 42 70 15 30"] | 3 seconds | ["3", "-1", "3"] | NoteIn the first example, selecting a subset of all numbers gives a gcd of $$$1$$$ and for all smaller subsets the gcd is greater than $$$1$$$.In the second example, for all subsets of numbers the gcd is at least $$$2$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"number theory",
"bitmasks",
"shortest paths",
"math"
] | 3baa00206d3bf03ce02a414747e2a633 | The first line contains an only integer $$$n$$$ ($$$1 \le n \le 300\,000$$$) — the number of integers in the sequence. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 300\,000$$$). | 2,500 | If there is no subset of the given sequence with gcd equal to $$$1$$$, output -1. Otherwise, output exactly one integer — the size of the smallest subset with gcd equal to $$$1$$$. | standard output | |
PASSED | 64800aedf1c54849798f93c95e9167db | train_000.jsonl | 1540740900 | Janusz is a businessman. He owns a company "Januszex", which produces games for teenagers. Last hit of Januszex was a cool one-person game "Make it one". The player is given a sequence of $$$n$$$ integers $$$a_i$$$.It is allowed to select any subset of them, and the score is equal to the greatest common divisor of selected elements. The goal is to take as little elements as it is possible, getting the score $$$1$$$. Now Janusz wonders, for given sequence, how much elements should the player choose? | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
/**
* @author Don Li
*/
public class MakeItOne2 {
int N = (int) 3e5 + 10;
int SQRT = (int) (Math.sqrt(N) + .5);
int[] fp = new int[N];
int[][] divs = new int[N][];
int[] dist = new int[N];
int[] cnt = new int[N];
void solve() {
int n = in.nextInt();
init();
Queue<Integer> qu = new ArrayDeque<>(N);
Arrays.fill(dist, -1);
for (int i = 0; i < n; i++) {
int a = base(in.nextInt());
if (dist[a] >= 0) continue;
dist[a] = 1;
qu.offer(a);
for (int d : divs[a]) cnt[d]++;
}
while (!qu.isEmpty()) {
int u = qu.poll();
go(qu, u, dist[u] + 1);
}
out.println(dist[1]);
}
void go(Queue<Integer> qu, int u, int d) {
List<Integer> fac = new ArrayList<>();
while (u > 1) {
fac.add(fp[u]);
u /= fp[u];
}
for (int v : fac) u *= v;
int n = fac.size();
int[] val = new int[1 << n];
for (int mask = 0; mask < 1 << n; mask++) {
val[mask] = u;
for (int i = 0; i < n; i++) {
if ((mask & 1 << i) > 0) {
val[mask] /= fac.get(i);
}
}
}
for (int mask = 0; mask < 1 << n; mask++) {
int ways = 0;
for (int s = mask; ; s = (s - 1) & mask) {
if (Integer.bitCount(mask ^ s) % 2 == 0) {
ways += cnt[val[s]];
} else {
ways -= cnt[val[s]];
}
if (s == 0) break;
}
if (ways > 0 && dist[val[mask]] == -1) {
dist[val[mask]] = d;
qu.offer(val[mask]);
}
}
}
int base(int n) {
int res = 1;
while (n > 1) {
int p = fp[n];
res *= p;
while (n % p == 0) n /= p;
}
return res;
}
void init() {
for (int i = 2; i < N; i++) {
if (fp[i] == 0) {
fp[i] = i;
for (int j = i * i; j < N && i <= SQRT; j += i) {
if (fp[j] == 0) fp[j] = i;
}
}
}
int[] ndiv = new int[N];
for (int i = 1; i < N; i++) {
for (int j = i; j < N; j += i) {
ndiv[j]++;
}
}
for (int i = 1; i < N; i++) divs[i] = new int[ndiv[i]];
for (int i = 1; i < N; i++) {
for (int j = i; j < N; j += i) {
divs[j][--ndiv[j]] = i;
}
}
}
public static void main(String[] args) {
in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(System.out);
new MakeItOne2().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 | ["3\n10 6 15", "3\n2 4 6", "7\n30 60 21 42 70 15 30"] | 3 seconds | ["3", "-1", "3"] | NoteIn the first example, selecting a subset of all numbers gives a gcd of $$$1$$$ and for all smaller subsets the gcd is greater than $$$1$$$.In the second example, for all subsets of numbers the gcd is at least $$$2$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"number theory",
"bitmasks",
"shortest paths",
"math"
] | 3baa00206d3bf03ce02a414747e2a633 | The first line contains an only integer $$$n$$$ ($$$1 \le n \le 300\,000$$$) — the number of integers in the sequence. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 300\,000$$$). | 2,500 | If there is no subset of the given sequence with gcd equal to $$$1$$$, output -1. Otherwise, output exactly one integer — the size of the smallest subset with gcd equal to $$$1$$$. | standard output | |
PASSED | cedaa7838bf885f2abfbafd0f62b9f05 | train_000.jsonl | 1540740900 | Janusz is a businessman. He owns a company "Januszex", which produces games for teenagers. Last hit of Januszex was a cool one-person game "Make it one". The player is given a sequence of $$$n$$$ integers $$$a_i$$$.It is allowed to select any subset of them, and the score is equal to the greatest common divisor of selected elements. The goal is to take as little elements as it is possible, getting the score $$$1$$$. Now Janusz wonders, for given sequence, how much elements should the player choose? | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
/**
* @author Don Li
*/
public class MakeItOne {
int N = (int) 3e5 + 10;
int MOD = (int) 1e9 + 7;
int[] fac = new int[N], ifac = new int[N], inv = new int[N];
{
inv[1] = 1;
for (int i = 2; i < N; i++) inv[i] = (int) ((long) (MOD - MOD / i) * inv[MOD % i] % MOD);
fac[0] = fac[1] = 1;
ifac[0] = ifac[1] = 1;
for (int i = 2; i < N; i++) {
fac[i] = (int) ((long) i * fac[i - 1] % MOD);
ifac[i] = (int) ((long) inv[i] * ifac[i - 1] % MOD);
}
}
void solve() {
int n = in.nextInt();
int[] cnt = new int[N];
for (int i = 0; i < n; i++) cnt[in.nextInt()]++;
for (int i = 1; i < N; i++) {
for (int j = i + i; j < N; j += i) {
cnt[i] += cnt[j];
}
}
int[][] dp = new int[8][N];
for (int i = 1; i < 8; i++) {
for (int j = N - 1; j >= 1; j--) {
dp[i][j] = bc(cnt[j], i);
for (int k = j + j; k < N; k += j) {
dp[i][j] = (dp[i][j] - dp[i][k] + MOD) % MOD;
}
}
if (dp[i][1] > 0) {
out.println(i);
return;
}
}
out.println(-1);
}
int bc(int n, int k) {
if (k > n) return 0;
return (int) ((long) fac[n] * ifac[k] % MOD * ifac[n - k] % MOD);
}
public static void main(String[] args) {
in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(System.out);
new MakeItOne().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 | ["3\n10 6 15", "3\n2 4 6", "7\n30 60 21 42 70 15 30"] | 3 seconds | ["3", "-1", "3"] | NoteIn the first example, selecting a subset of all numbers gives a gcd of $$$1$$$ and for all smaller subsets the gcd is greater than $$$1$$$.In the second example, for all subsets of numbers the gcd is at least $$$2$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"number theory",
"bitmasks",
"shortest paths",
"math"
] | 3baa00206d3bf03ce02a414747e2a633 | The first line contains an only integer $$$n$$$ ($$$1 \le n \le 300\,000$$$) — the number of integers in the sequence. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 300\,000$$$). | 2,500 | If there is no subset of the given sequence with gcd equal to $$$1$$$, output -1. Otherwise, output exactly one integer — the size of the smallest subset with gcd equal to $$$1$$$. | standard output | |
PASSED | 8f9022ffabb1cf9600c05b1660d0e6f6 | train_000.jsonl | 1540740900 | Janusz is a businessman. He owns a company "Januszex", which produces games for teenagers. Last hit of Januszex was a cool one-person game "Make it one". The player is given a sequence of $$$n$$$ integers $$$a_i$$$.It is allowed to select any subset of them, and the score is equal to the greatest common divisor of selected elements. The goal is to take as little elements as it is possible, getting the score $$$1$$$. Now Janusz wonders, for given sequence, how much elements should the player choose? | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Vadim
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskF solver = new TaskF();
solver.solve(1, in, out);
out.close();
}
static class TaskF {
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int n = in.ni();
int[] a = in.na(n);
int MAX_VAL = 300007;
ArrayList<Integer> pr = new ArrayList<>(MAX_VAL);
int[] lp = new int[MAX_VAL];
IntegerUtils.sieve(MAX_VAL - 5, pr, lp);
int[][] divs = new int[MAX_VAL][10];
int[] ndivs = new int[MAX_VAL];
int[] count = new int[MAX_VAL];
boolean[] res = new boolean[MAX_VAL];
for (int i = 0; i < n; i++) {
int[] curDivs = new int[10];
int num = a[i];
int ndiv = 0;
int repl = 1;
while (num > 1) {
int div = lp[num];
curDivs[ndiv++] = div;
while (num % div == 0)
num /= div;
repl *= div;
}
a[i] = repl;
divs[repl] = curDivs;
ndivs[repl] = ndiv;
res[repl] = true;
}
n = 0;
for (int i = 0; i < MAX_VAL; i++) {
if (res[i])
a[n++] = i;
}
for (int i = 0; i < n; i++) {
int[] curDivs = divs[a[i]];
int ndiv = ndivs[a[i]];
for (int mask = 0; mask < 1 << ndiv; mask++) {
int num = 1;
for (int bit = 0; bit < ndiv; bit++) {
if ((mask & 1 << bit) != 0) {
num *= curDivs[bit];
}
}
count[num]++;
}
}
int[] curCount = new int[MAX_VAL];
int ans = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
int[] curDivs = divs[a[i]];
int k = ndivs[a[i]];
for (int mask = (1 << k) - 1; mask >= 0; mask--) {
int num = 1;
for (int bit = 0; bit < k; bit++) {
if ((mask & 1 << bit) != 0)
num *= curDivs[bit];
}
curCount[mask] = count[num];
for (int smask = 0; smask < 1 << k; smask++) {
if ((mask | smask) == smask && smask > mask) {
curCount[mask] -= curCount[smask];
}
}
}
int[] dp = new int[1 << k];
for (int j = 0; j < 1 << k; j++) {
dp[j] = Integer.MAX_VALUE;
}
dp[(1 << k) - 1] = 1;
for (int mask = (1 << k) - 1; mask >= 0; mask--) {
if (dp[mask] < Integer.MAX_VALUE)
for (int smask = 0; smask < 1 << k; smask++) {
if (curCount[smask] > 0)
dp[smask & mask] = Math.min(dp[smask & mask], dp[mask] + 1);
}
}
ans = Math.min(ans, dp[0]);
}
if (ans == Integer.MAX_VALUE)
ans = -1;
out.println(ans);
}
}
static class FastScanner {
private BufferedReader in;
private StringTokenizer st;
public FastScanner(InputStream stream) {
in = new BufferedReader(new InputStreamReader(stream));
}
public String ns() {
while (st == null || !st.hasMoreTokens()) {
try {
String rl = in.readLine();
if (rl == null) {
return null;
}
st = new StringTokenizer(rl);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int ni() {
return Integer.parseInt(ns());
}
public int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = ni();
return a;
}
}
static class IntegerUtils {
public static void sieve(int n, ArrayList<Integer> pr, int[] lp) {
for (int i = 2; i < n + 1; i++) {
if (lp[i] == 0) {
lp[i] = i;
pr.add(i);
}
int j = 0;
while (j < pr.size() && pr.get(j) <= lp[i] && i * pr.get(j) <= n) {
lp[i * pr.get(j)] = pr.get(j);
j++;
}
}
}
}
}
| Java | ["3\n10 6 15", "3\n2 4 6", "7\n30 60 21 42 70 15 30"] | 3 seconds | ["3", "-1", "3"] | NoteIn the first example, selecting a subset of all numbers gives a gcd of $$$1$$$ and for all smaller subsets the gcd is greater than $$$1$$$.In the second example, for all subsets of numbers the gcd is at least $$$2$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"number theory",
"bitmasks",
"shortest paths",
"math"
] | 3baa00206d3bf03ce02a414747e2a633 | The first line contains an only integer $$$n$$$ ($$$1 \le n \le 300\,000$$$) — the number of integers in the sequence. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 300\,000$$$). | 2,500 | If there is no subset of the given sequence with gcd equal to $$$1$$$, output -1. Otherwise, output exactly one integer — the size of the smallest subset with gcd equal to $$$1$$$. | standard output | |
PASSED | 963e02cfe25f460376382aec2da9bbb6 | train_000.jsonl | 1540740900 | Janusz is a businessman. He owns a company "Januszex", which produces games for teenagers. Last hit of Januszex was a cool one-person game "Make it one". The player is given a sequence of $$$n$$$ integers $$$a_i$$$.It is allowed to select any subset of them, and the score is equal to the greatest common divisor of selected elements. The goal is to take as little elements as it is possible, getting the score $$$1$$$. Now Janusz wonders, for given sequence, how much elements should the player choose? | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskF solver = new TaskF();
solver.solve(1, in, out);
out.close();
}
static class TaskF {
private static final int NUMBER_RANGE = 300001;
private static final int DIVISOR_RANGE = 8;
int[][] factors;
int[] divisors;
int[] bit;
boolean[] isPrime;
public void solve(int testNumber, InputReader in, PrintWriter out) {
factors = new int[NUMBER_RANGE][DIVISOR_RANGE];
divisors = new int[NUMBER_RANGE];
int[] sum = new int[NUMBER_RANGE];
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; ++i) {
a[i] = in.nextInt();
++sum[a[i]];
}
isPrime = new boolean[NUMBER_RANGE];
Arrays.fill(isPrime, true);
isPrime[0] = isPrime[1] = false;
for (int i = 1; i < NUMBER_RANGE; ++i) {
for (int j = i; j < NUMBER_RANGE; j += i) {
divisors[i] += sum[j];
}
}
for (int i = 2; i < NUMBER_RANGE; ++i) {
for (int j = i; j < NUMBER_RANGE; j += i) {
if (i != j) {
isPrime[j] = false;
}
if (isPrime[i]) {
// if (factors[j][0] == factors[j].length) System.err.println(Arrays.toString(factors[j]));
// if (factors[j][0] > 8) System.err.println(Arrays.toString(factors[j]));
factors[j][++factors[j][0]] = i;
}
}
}
// out.println(isPrime[5]);
bit = new int[1 << 7];
for (int i = 0; i < 7; ++i) {
bit[1 << i] = i;
}
int[] needed = new int[NUMBER_RANGE];
Arrays.fill(needed, 0x3F3F3F3F);
for (int i = 0; i < n; ++i) {
int prod = 1;
int[] curFact = factors[a[i]];
for (int j = 0; j < curFact[0]; ++j) {
prod *= curFact[j + 1];
}
needed[prod] = 0;
}
// out.println(needed[1]);
int[] dp = new int[1 << 7];
int[] prod = new int[1 << 7];
for (int i = NUMBER_RANGE - 1; i > 1; --i) {
if (needed[i] == 0x3F3F3F3F) {
continue;
}
int numFactors = factors[i][0];
int[] curFact = factors[i];
prod[0] = 1;
for (int j = 1; j < (1 << numFactors); ++j) {
int lb = j & -j;
prod[j] = prod[j - lb] * curFact[bit[lb] + 1];
}
// if (i == 2) out.println(Arrays.toString(curFact));
for (int j = 0; j < (1 << numFactors); ++j) {
dp[j] = divisors[prod[j]];
}
for (int k = 0; k < numFactors; ++k) {
for (int j = 0; j < (1 << numFactors); ++j) {
if (((j >> k) & 1) != 0) continue;
dp[j] -= dp[j ^ (1 << k)];
}
}
int[] factdp = new int[1 << numFactors];
for (int j = 0; j < (1 << numFactors); ++j) {
factdp[j] = dp[j];
}
// if (i == 2) out.println("dp = " + Arrays.toString(factdp));
// if (needed[1] < 100) out.println("needed[1] = " + needed[1] + ", i = " + i);
for (int j = 0; j < (1 << numFactors); ++j) {
assert dp[j] >= 0;
if (dp[j] != 0) {
needed[prod[j]] = Math.min(needed[prod[j]], needed[i] + 1);
}
}
}
if (needed[1] == 0x3F3F3F3F) {
needed[1] = -1;
} else {
++needed[1];
}
out.println(needed[1]);
}
}
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (Exception e) {
throw new UnknownError();
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["3\n10 6 15", "3\n2 4 6", "7\n30 60 21 42 70 15 30"] | 3 seconds | ["3", "-1", "3"] | NoteIn the first example, selecting a subset of all numbers gives a gcd of $$$1$$$ and for all smaller subsets the gcd is greater than $$$1$$$.In the second example, for all subsets of numbers the gcd is at least $$$2$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"number theory",
"bitmasks",
"shortest paths",
"math"
] | 3baa00206d3bf03ce02a414747e2a633 | The first line contains an only integer $$$n$$$ ($$$1 \le n \le 300\,000$$$) — the number of integers in the sequence. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 300\,000$$$). | 2,500 | If there is no subset of the given sequence with gcd equal to $$$1$$$, output -1. Otherwise, output exactly one integer — the size of the smallest subset with gcd equal to $$$1$$$. | standard output | |
PASSED | 343f4af2d59ff5555905ae01378232ae | train_000.jsonl | 1540740900 | Janusz is a businessman. He owns a company "Januszex", which produces games for teenagers. Last hit of Januszex was a cool one-person game "Make it one". The player is given a sequence of $$$n$$$ integers $$$a_i$$$.It is allowed to select any subset of them, and the score is equal to the greatest common divisor of selected elements. The goal is to take as little elements as it is possible, getting the score $$$1$$$. Now Janusz wonders, for given sequence, how much elements should the player choose? | 256 megabytes | import java.io.*;
import java.util.*;
public class C {
FastReader scn;
PrintWriter out;
String INPUT = "";
void solve() {
int n = scn.nextInt();
int[] arr = new int[300001];
for(int i = 0; i < n; i++) {
int x = scn.nextInt();
arr[x] = 1;
}
int[] a = new int[n];
int pos = 0;
for(int i = 1; i < arr.length; i++) {
if(arr[i] == 1) {
a[pos++] = i;
} else {
continue;
}
for(int j = i; j < arr.length; j += i) {
arr[j] = 0;
}
}
a = Arrays.copyOf(a, pos);
Arrays.sort(a);
if(a[0] == 1) {
out.println(1);
return;
}
int g = 0;
for(int x : a) {
g = gcd(g, x);
}
if(g != 1) {
out.println(-1);
return;
}
int ans = 10;
Random r = new Random();
for(int i = 0; i < 2e6; i++) {
g = 0;
int c = 0;
for(int j = 0; j < ans; j++) {
int ind = r.nextInt(pos);
g = gcd(g, a[ind]);
c++;
if(g == 1) {
ans = Math.min(ans, c);
break;
}
}
}
out.println(ans);
}
int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
void run() throws Exception {
long time = System.currentTimeMillis();
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
out = new PrintWriter(System.out);
scn = new FastReader(oj);
solve();
out.flush();
if (!oj) {
System.out.println(Arrays.deepToString(new Object[] { System.currentTimeMillis() - time + " ms" }));
}
}
public static void main(String[] args) throws Exception {
new C().run();
}
class FastReader {
InputStream is;
public FastReader(boolean onlineJudge) {
is = onlineJudge ? System.in : new ByteArrayInputStream(INPUT.getBytes());
}
byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
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++];
}
boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b))
;
return b;
}
double nextDouble() {
return Double.parseDouble(next());
}
char nextChar() {
return (char) skip();
}
String next() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
String nextLine() {
int b = skip();
StringBuilder sb = new StringBuilder();
while ((!isSpaceChar(b) || b == ' ')) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
char[] next(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);
}
int nextInt() {
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();
}
}
long nextLong() {
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();
}
}
char[][] nextMatrix(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++)
map[i] = next(m);
return map;
}
int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
int[][] next2DInt(int n, int m) {
int[][] arr = new int[n][];
for (int i = 0; i < n; i++) {
arr[i] = nextIntArray(m);
}
return arr;
}
long[][] next2DLong(int n, int m) {
long[][] arr = new long[n][];
for (int i = 0; i < n; i++) {
arr[i] = nextLongArray(m);
}
return arr;
}
int[] shuffle(int[] arr) {
Random r = new Random();
for (int i = 1, j; i < arr.length; i++) {
j = r.nextInt(i);
arr[i] = arr[i] ^ arr[j];
arr[j] = arr[i] ^ arr[j];
arr[i] = arr[i] ^ arr[j];
}
return arr;
}
}
} | Java | ["3\n10 6 15", "3\n2 4 6", "7\n30 60 21 42 70 15 30"] | 3 seconds | ["3", "-1", "3"] | NoteIn the first example, selecting a subset of all numbers gives a gcd of $$$1$$$ and for all smaller subsets the gcd is greater than $$$1$$$.In the second example, for all subsets of numbers the gcd is at least $$$2$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"number theory",
"bitmasks",
"shortest paths",
"math"
] | 3baa00206d3bf03ce02a414747e2a633 | The first line contains an only integer $$$n$$$ ($$$1 \le n \le 300\,000$$$) — the number of integers in the sequence. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 300\,000$$$). | 2,500 | If there is no subset of the given sequence with gcd equal to $$$1$$$, output -1. Otherwise, output exactly one integer — the size of the smallest subset with gcd equal to $$$1$$$. | standard output | |
PASSED | a55e7dc3ca20e9e27eddfb58dd7926de | train_000.jsonl | 1540740900 | Janusz is a businessman. He owns a company "Januszex", which produces games for teenagers. Last hit of Januszex was a cool one-person game "Make it one". The player is given a sequence of $$$n$$$ integers $$$a_i$$$.It is allowed to select any subset of them, and the score is equal to the greatest common divisor of selected elements. The goal is to take as little elements as it is possible, getting the score $$$1$$$. Now Janusz wonders, for given sequence, how much elements should the player choose? | 256 megabytes | import java.io.*;
import java.util.*;
public class C {
FastReader scn;
PrintWriter out;
String INPUT = "";
void solve() {
int n = scn.nextInt();
int[] arr = new int[300001];
for(int i = 0; i < n; i++) {
int x = scn.nextInt();
arr[x] = 1;
}
int[] a = new int[n];
int pos = 0;
for(int i = 1; i < arr.length; i++) {
if(arr[i] == 1) {
a[pos++] = i;
} else {
continue;
}
for(int j = i; j < arr.length; j += i) {
arr[j] = 0;
}
}
a = Arrays.copyOf(a, pos);
Arrays.sort(a);
if(a[0] == 1) {
out.println(1);
return;
}
int g = 0;
for(int x : a) {
g = gcd(g, x);
}
if(g != 1) {
out.println(-1);
return;
}
int ans = 10;
Random r = new Random();
for(int i = 0; i < 7e5; i++) {
g = 0;
int c = 0;
for(int j = 0; j < ans; j++) {
int ind = r.nextInt(pos);
g = gcd(g, a[ind]);
c++;
if(g == 1) {
ans = Math.min(ans, c);
if(ans == 2) {
out.println(ans);
return;
}
break;
}
}
}
out.println(ans);
}
int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
void run() throws Exception {
long time = System.currentTimeMillis();
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
out = new PrintWriter(System.out);
scn = new FastReader(oj);
solve();
out.flush();
if (!oj) {
System.out.println(Arrays.deepToString(new Object[] { System.currentTimeMillis() - time + " ms" }));
}
}
public static void main(String[] args) throws Exception {
new C().run();
}
class FastReader {
InputStream is;
public FastReader(boolean onlineJudge) {
is = onlineJudge ? System.in : new ByteArrayInputStream(INPUT.getBytes());
}
byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
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++];
}
boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b))
;
return b;
}
double nextDouble() {
return Double.parseDouble(next());
}
char nextChar() {
return (char) skip();
}
String next() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
String nextLine() {
int b = skip();
StringBuilder sb = new StringBuilder();
while ((!isSpaceChar(b) || b == ' ')) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
char[] next(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);
}
int nextInt() {
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();
}
}
long nextLong() {
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();
}
}
char[][] nextMatrix(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++)
map[i] = next(m);
return map;
}
int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
int[][] next2DInt(int n, int m) {
int[][] arr = new int[n][];
for (int i = 0; i < n; i++) {
arr[i] = nextIntArray(m);
}
return arr;
}
long[][] next2DLong(int n, int m) {
long[][] arr = new long[n][];
for (int i = 0; i < n; i++) {
arr[i] = nextLongArray(m);
}
return arr;
}
int[] shuffle(int[] arr) {
Random r = new Random();
for (int i = 1, j; i < arr.length; i++) {
j = r.nextInt(i);
arr[i] = arr[i] ^ arr[j];
arr[j] = arr[i] ^ arr[j];
arr[i] = arr[i] ^ arr[j];
}
return arr;
}
}
} | Java | ["3\n10 6 15", "3\n2 4 6", "7\n30 60 21 42 70 15 30"] | 3 seconds | ["3", "-1", "3"] | NoteIn the first example, selecting a subset of all numbers gives a gcd of $$$1$$$ and for all smaller subsets the gcd is greater than $$$1$$$.In the second example, for all subsets of numbers the gcd is at least $$$2$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"number theory",
"bitmasks",
"shortest paths",
"math"
] | 3baa00206d3bf03ce02a414747e2a633 | The first line contains an only integer $$$n$$$ ($$$1 \le n \le 300\,000$$$) — the number of integers in the sequence. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 300\,000$$$). | 2,500 | If there is no subset of the given sequence with gcd equal to $$$1$$$, output -1. Otherwise, output exactly one integer — the size of the smallest subset with gcd equal to $$$1$$$. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.