contest_id
stringclasses 33
values | problem_id
stringclasses 14
values | statement
stringclasses 181
values | tags
sequencelengths 1
8
| code
stringlengths 21
64.5k
| language
stringclasses 3
values |
---|---|---|---|---|---|
1323 | B | B. Count Subrectanglestime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn and array bb of length mm both consisting of only integers 00 and 11. Consider a matrix cc of size n×mn×m formed by following rule: ci,j=ai⋅bjci,j=ai⋅bj (i.e. aiai multiplied by bjbj). It's easy to see that cc consists of only zeroes and ones too.How many subrectangles of size (area) kk consisting only of ones are there in cc?A subrectangle is an intersection of a consecutive (subsequent) segment of rows and a consecutive (subsequent) segment of columns. I.e. consider four integers x1,x2,y1,y2x1,x2,y1,y2 (1≤x1≤x2≤n1≤x1≤x2≤n, 1≤y1≤y2≤m1≤y1≤y2≤m) a subrectangle c[x1…x2][y1…y2]c[x1…x2][y1…y2] is an intersection of the rows x1,x1+1,x1+2,…,x2x1,x1+1,x1+2,…,x2 and the columns y1,y1+1,y1+2,…,y2y1,y1+1,y1+2,…,y2.The size (area) of a subrectangle is the total number of cells in it.InputThe first line contains three integers nn, mm and kk (1≤n,m≤40000,1≤k≤n⋅m1≤n,m≤40000,1≤k≤n⋅m), length of array aa, length of array bb and required size of subrectangles.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), elements of aa.The third line contains mm integers b1,b2,…,bmb1,b2,…,bm (0≤bi≤10≤bi≤1), elements of bb.OutputOutput single integer — the number of subrectangles of cc with size (area) kk consisting only of ones.ExamplesInputCopy3 3 2
1 0 1
1 1 1
OutputCopy4
InputCopy3 5 4
1 1 1
1 1 1 1 1
OutputCopy14
NoteIn first example matrix cc is: There are 44 subrectangles of size 22 consisting of only ones in it: In second example matrix cc is: | [
"binary search",
"greedy",
"implementation"
] |
import java.io.*;
import java.util.*;
// SCREAM AS LOUD AS YOU CAN
// FUCK !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
public class Aqueous {
static MyScanner sc = new MyScanner();
static PrintWriter pw = new PrintWriter(System.out);
static class pair{
int k ;
String s;
public pair(int k , String s) {
this.k = k;
this.s = s;
}
}
public static void main(String[] args) {
int n = sc.nextInt();
int m = sc.nextInt();
int k =sc.nextInt();
int nn[] = new int[n];
for(int i = 0; i<n; i++) {
nn[i] = sc.nextInt();
}
int mm[] = new int[m];
for(int i = 0; i<m;i++) {
mm[i] = sc.nextInt();
}
int ans[] = gao(nn);
// for(int e : ans) {
// pw.print(e+" ");
// }
//
// pw.println();
int ans1[] = gao(mm);
// for(int e : ans1) {
// pw.print(e+" ");
// }
// pw.println();
ArrayList<Integer> al = factors(k);
long answer = 0;
for(int e: al) {
if(e<ans.length && (k/e)<ans1.length) {
answer += ans[e]*ans1[k/e];
}
}
pw.println(answer);
pw.close();
}
static int[] gao(int a[]) {
int n = a.length;
int res[] = new int[n+1];
int i = 0;
while(i<n) {
if(a[i]==0) {
i++;
continue;
}
int j = i;
while(j<n && a[j]==1) {
j++;
}
for(int len = 1; len<=j-i; len++) {
res[len] +=j-i-len+1;
}
i=j;
}
return res;
}
static ArrayList<Integer> factors(int k){
ArrayList<Integer> al = new ArrayList<>();
al.add(1);
for(int i = 2; i*i<=k; i++) {
if(k%i==0) {
al.add(i);
if((k/i)!=i) {
al.add(k/i);
}
}
}
if(!al.contains(k)) {
al.add(k);
}
return al;
}
static void ruffleSort(int a[]) {
int n = a.length;
Random r = new Random();
for (int i = 0; i < n; i++) {
int oi = r.nextInt(n);
int temp = a[oi];
a[oi] = a[i];
a[i] = temp;
}
Arrays.sort(a);
}
static void ruffleSort(long a[]) {
int n = a.length;
Random r = new Random();
for (int i = 0; i < n; i++) {
int oi = r.nextInt(n);
long temp = a[oi];
a[oi] = a[i];
a[i] = temp;
}
Arrays.sort(a);
}
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
| java |
1311 | F | F. Moving Pointstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn points on a coordinate axis OXOX. The ii-th point is located at the integer point xixi and has a speed vivi. It is guaranteed that no two points occupy the same coordinate. All nn points move with the constant speed, the coordinate of the ii-th point at the moment tt (tt can be non-integer) is calculated as xi+t⋅vixi+t⋅vi.Consider two points ii and jj. Let d(i,j)d(i,j) be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points ii and jj coincide at some moment, the value d(i,j)d(i,j) will be 00.Your task is to calculate the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of points.The second line of the input contains nn integers x1,x2,…,xnx1,x2,…,xn (1≤xi≤1081≤xi≤108), where xixi is the initial coordinate of the ii-th point. It is guaranteed that all xixi are distinct.The third line of the input contains nn integers v1,v2,…,vnv1,v2,…,vn (−108≤vi≤108−108≤vi≤108), where vivi is the speed of the ii-th point.OutputPrint one integer — the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).ExamplesInputCopy3
1 3 2
-100 2 3
OutputCopy3
InputCopy5
2 1 4 3 5
2 2 2 3 4
OutputCopy19
InputCopy2
2 1
-3 0
OutputCopy0
| [
"data structures",
"divide and conquer",
"implementation",
"sortings"
] | import java.io.*;
import java.util.*;
public class Practice
{
// static final long mod=7420738134811L;
static int mod=1000000007;
static int size=101;
static FastReader sc=new FastReader(System.in);
// static Reader sc=new Reader();
// static Scanner sc=new Scanner(System.in);
static PrintWriter out=new PrintWriter(System.out);
static long[] factorialNumInverse;
static long[] naturalNumInverse;
static int[] sp;
static long[] fact;
static ArrayList<Integer> pr;
public static void main(String[] args) throws IOException, CloneNotSupportedException
{
// System.setIn(new FileInputStream("input.txt"));
// System.setOut(new PrintStream("output.txt"));
// factorial(mod);
// InverseofNumber(mod);
// InverseofFactorial(mod);
// make_seive();
int t=1;
// t=sc.nextInt();
for(int i=1;i<=t;i++)
solve(i);
out.close();
out.flush();
// System.out.flush();
// System.exit(0);
}
static void solve(int CASENO) throws IOException, CloneNotSupportedException
{
int n=sc.nextInt();
int V[]=new int[n];
ArrayList<Pair> point=new ArrayList<Pair>();
HashMap<Integer,Integer> unique=new HashMap<Integer,Integer>();
for(int i=0;i<n;i++)
point.add(new Pair(sc.nextInt(),0));
for(int i=0;i<n;i++)
{
V[i]=sc.nextInt();
point.get(i).y=V[i];
unique.put(V[i],-1);
}
arraySort(V);
int pos=0;
for(int i=0;i<n;i++)
{
if(unique.get(V[i])==-1)
unique.put(V[i], pos++);
}
Collections.sort(point);
long SUM[]=new long[unique.size()],ans=0;
long COUNT[]=new long[unique.size()];
for(Pair p: point)
{
pos=unique.get(p.y);
ans += get(COUNT, pos) * p.x - get(SUM, pos);
upd(COUNT, pos, 1);
upd(SUM, pos, p.x);
}
out.println(ans);
}
static long get(long f[], int pos) {
long res = 0;
for (; pos >= 0; pos = (pos & (pos + 1)) - 1)
res += f[pos];
return res;
}
static void upd(long f[], int pos, int val) {
for (; pos < f.length; pos |= pos + 1) {
f[pos] += val;
}
}
static class Pair implements Cloneable, Comparable<Pair>
{
int x,y;
Pair(int a,int b)
{
this.x=a;
this.y=b;
}
@Override
public boolean equals(Object obj)
{
if(obj instanceof Pair)
{
Pair p=(Pair)obj;
return p.x==this.x && p.y==this.y;
}
return false;
}
@Override
public int hashCode()
{
return (int)Math.abs(x)+500*Math.abs(y);
}
@Override
public String toString()
{
return "("+x+" "+y+")";
}
// @Override
// protected Pair clone() throws CloneNotSupportedException {
// return new Pair(this.x,this.y);
// }
@Override
public int compareTo(Pair a)
{
long t=(this.x-a.x);
if(t!=0)
return t>0?1:-1;
else
return (int)(this.y-a.y);
}
public void swap()
{
this.y=this.y+this.x;
this.x=this.y-this.x;
this.y=this.y-this.x;
}
}
static class Tuple implements Cloneable, Comparable<Tuple>
{
int x,y,z;
Tuple(int a,int b,int c)
{
this.x=a;
this.y=b;
this.z=c;
}
public boolean equals(Object obj)
{
if(obj instanceof Tuple)
{
Tuple p=(Tuple)obj;
return p.x==this.x && p.y==this.y && p.z==this.z;
}
return false;
}
@Override
public int hashCode()
{
return (this.x+501*this.y);
}
@Override
public String toString()
{
return "("+x+","+y+" "+z+")";
}
@Override
protected Tuple clone() throws CloneNotSupportedException {
return new Tuple(this.x,this.y,this.z);
}
@Override
public int compareTo(Tuple a)
{
int x=this.y-a.y;
if(x!=0)
return x;
int X= this.x-a.x;
return X;
}
}
static void arraySort(int arr[])
{
ArrayList<Integer> a=new ArrayList<Integer>();
for (int i = 0; i < arr.length; i++) {
a.add(arr[i]);
}
Collections.sort(a);
// Collections.sort(a,Comparator.reverseOrder());
for (int i = 0; i < arr.length; i++) {
arr[i]=a.get(i);
}
}
static void arraySort(long arr[])
{
ArrayList<Long> a=new ArrayList<Long>();
for (int i = 0; i < arr.length; i++) {
a.add(arr[i]);
}
Collections.sort(a);
for (int i = 0; i < arr.length; i++) {
arr[i]=a.get(i);
}
}
static HashSet<Integer> primeFactors(int n)
{
HashSet<Integer> ans=new HashSet<Integer>();
if(n%2==0)
{
ans.add(2);
while((n&1)==0)
n=n>>1;
}
for(int i=3;i*i<=n;i+=2)
{
if(n%i==0)
{
ans.add(i);
while(n%i==0)
n=n/i;
}
}
if(n!=1)
ans.add(n);
return ans;
}
static ArrayList<Integer> findAllFactors(int n)
{
ArrayList<Integer> ans=new ArrayList<Integer>();
for(int i=1;i*i<=n;i++)
{
ans.add(i);
if(n!=i*i)
ans.add(n/i);
}
return ans;
}
static void make_seive()
{
sp=new int[size];
pr=new ArrayList<Integer>();
for (int i=2; i<size; ++i) {
if (sp[i] == 0) {
sp[i] = i;
pr.add(i);
}
for (int j=0; j<(int)pr.size() && pr.get(j)<=sp[i] && i*pr.get(j)<size; ++j)
sp[i * pr.get(j)] = pr.get(j);
}
}
public static void InverseofNumber(int p)
{
naturalNumInverse=new long[size];
naturalNumInverse[0] = naturalNumInverse[1] = 1;
for(int i = 2; i < size; i++)
naturalNumInverse[i] = naturalNumInverse[p % i] * (long)(p - p / i) % p;
}
// Function to precompute inverse of factorials
public static void InverseofFactorial(int p)
{
factorialNumInverse=new long[size];
factorialNumInverse[0] = factorialNumInverse[1] = 1;
// pre-compute inverse of natural numbers
for(int i = 2; i < size; i++)
factorialNumInverse[i] = (naturalNumInverse[i] * factorialNumInverse[i - 1]) % p;
}
// Function to calculate factorial of 1 to 200001
public static void factorial(int p)
{
fact=new long[size];
fact[0] = 1;
for(int i = 1; i < size; i++)
fact[i] = (fact[i - 1] * (long)i) % p;
}
// Function to return nCr % p in O(1) time
public static long Binomial(int N, int R)
{
if(R<0)
return 1;
// n C r = n!*inverse(r!)*inverse((n-r)!)
long ans = ((fact[N] * factorialNumInverse[R]) % mod * factorialNumInverse[N - R]) % mod;
return ans;
}
static int findXOR(int x) //from 0 to x
{
if(x<0)
return 0;
if(x%4==0)
return x;
if(x%4==1)
return 1;
if(x%4==2)
return x+1;
return 0;
}
static boolean isPrime(long x)
{
if(x==1)
return false;
if(x<=3)
return true;
if(x%2==0 || x%3==0)
return false;
for(int i=5;i<=Math.sqrt(x);i+=2)
if(x%i==0)
return false;
return true;
}
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 Node
{
int vertex,deg;
HashMap<Integer,Integer> adj;
Node(int ver)
{
vertex=ver;
deg=0;
adj=new HashMap<Integer,Integer>();
}
@Override
public String toString()
{
return vertex+" ";
}
}
static class Edge
{
Node to;
int cost;
Edge(Node t,int c)
{
this.to=t;
this.cost=c;
}
@Override
public String toString() {
return "("+to.vertex+","+cost+") ";
}
}
static long power(long x, long y)
{
if(x<=0)
return 1;
long res = 1;
x = x % mod;
if (x == 0)
return 0;
while (y > 0)
{
if ((y & 1) != 0)
res = (res * x) % mod;
y = y >> 1; // y = y/2
x = (x * x) % mod;
}
return res%mod;
}
static long binomialCoeff(long n, long k)
{
if(n<k)
return 0;
long res = 1;
// Since C(n, k) = C(n, n-k)
if (k > n - k)
k = n - k;
// Calculate value of
// [n * (n-1) *---* (n-k+1)] / [k * (k-1) *----* 1]
for (long i = 0; i < k; ++i) {
res *= (n - i);
res /= (i + 1);
}
return res;
}
static class FastReader
{
byte[] buf = new byte[2048];
int index, total;
InputStream in;
FastReader(InputStream is)
{
in = is;
}
int scan() throws IOException
{
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0) {
return -1;
}
}
return buf[index++];
}
String next() throws IOException
{
int c;
for (c = scan(); c <= 32; c = scan());
StringBuilder sb = new StringBuilder();
for (; c > 32; c = scan()) {
sb.append((char) c);
}
return sb.toString();
}
int nextInt() throws IOException
{
int c, val = 0;
for (c = scan(); c <= 32; c = scan());
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
long nextLong() throws IOException
{
int c;
long val = 0;
for (c = scan(); c <= 32; c = scan());
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
public void printarray(int arr[])
{
for (int i = 0; i < arr.length; i++)
System.out.print(arr[i]+" ");
System.out.println();
}
}
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(
new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
if (cnt != 0) {
break;
}
else {
continue;
}
}
buf[cnt++] = (byte)c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0,
BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
public void printarray(int arr[])
{
for (int i = 0; i < arr.length; i++)
System.out.print(arr[i]+" ");
System.out.println();
}
}
}
| java |
1301 | B | B. Motarack's Birthdaytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array aa of nn non-negative integers.Dark created that array 10001000 years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer kk (0≤k≤1090≤k≤109) and replaces all missing elements in the array aa with kk.Let mm be the maximum absolute difference between all adjacent elements (i.e. the maximum value of |ai−ai+1||ai−ai+1| for all 1≤i≤n−11≤i≤n−1) in the array aa after Dark replaces all missing elements with kk.Dark should choose an integer kk so that mm is minimized. Can you help him?InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1041≤t≤104) — the number of test cases. The description of the test cases follows.The first line of each test case contains one integer nn (2≤n≤1052≤n≤105) — the size of the array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−1≤ai≤109−1≤ai≤109). If ai=−1ai=−1, then the ii-th integer is missing. It is guaranteed that at least one integer is missing in every test case.It is guaranteed, that the sum of nn for all test cases does not exceed 4⋅1054⋅105.OutputPrint the answers for each test case in the following format:You should print two integers, the minimum possible value of mm and an integer kk (0≤k≤1090≤k≤109) that makes the maximum absolute difference between adjacent elements in the array aa equal to mm.Make sure that after replacing all the missing elements with kk, the maximum absolute difference between adjacent elements becomes mm.If there is more than one possible kk, you can print any of them.ExampleInputCopy7
5
-1 10 -1 12 -1
5
-1 40 35 -1 35
6
-1 -1 9 -1 3 -1
2
-1 -1
2
0 -1
4
1 -1 3 -1
7
1 -1 7 5 2 -1 5
OutputCopy1 11
5 35
3 6
0 42
0 0
1 2
3 4
NoteIn the first test case after replacing all missing elements with 1111 the array becomes [11,10,11,12,11][11,10,11,12,11]. The absolute difference between any adjacent elements is 11. It is impossible to choose a value of kk, such that the absolute difference between any adjacent element will be ≤0≤0. So, the answer is 11.In the third test case after replacing all missing elements with 66 the array becomes [6,6,9,6,3,6][6,6,9,6,3,6]. |a1−a2|=|6−6|=0|a1−a2|=|6−6|=0; |a2−a3|=|6−9|=3|a2−a3|=|6−9|=3; |a3−a4|=|9−6|=3|a3−a4|=|9−6|=3; |a4−a5|=|6−3|=3|a4−a5|=|6−3|=3; |a5−a6|=|3−6|=3|a5−a6|=|3−6|=3. So, the maximum difference between any adjacent elements is 33. | [
"binary search",
"greedy",
"ternary search"
] | /*----------- ---------------*
Author : Ryan Ranaut
__Hope is a big word, never lose it__
------------- --------------*/
import java.io.*;
import java.util.*;
public class Codeforces2 {
static PrintWriter out = new PrintWriter(System.out);
static final int mod = 1_000_000_007;
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
long[] readLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
/*-------------------------------------------------------------------------*/
//Try seeing general case
public static void main(String[] args) {
FastReader s = new FastReader();
int t = s.nextInt();
while(t-->0)
{
int n = s.nextInt();
int[] a = s.readIntArray(n);
find(n, a);
}
out.close();
}
public static void find(int n, int[] a)
{
int low = 0, high = (int)(1e9);
int diff = Integer.MAX_VALUE, k = -1;
while(low<=high)
{
int mid = low + (high-low)/2;
int r1 = find1(mid, a);
int r2 = find1(mid+1, a);
if(r1<=r2)
{
diff = r1;
k = mid;
high = mid-1;
}
else
{
diff = r2;
k = mid+1;
low = mid+1;
}
}
out.println(diff+" "+k);
}
public static int find1(int x, int[] a)
{
int[] b = a.clone();
for(int i=0;i<a.length;i++)
b[i] = b[i]==-1 ? x : b[i];
int res = Integer.MIN_VALUE;
for(int i=1;i<a.length;i++)
{
res = Math.max(res, Math.abs(b[i]-b[i-1]));
}
return res;
}
/*-----------------------------------End of the road--------------------------------------*/
static class DSU {
int[] parent;
int[] ranks;
int[] groupSize;
int size;
public DSU(int n) {
size = n;
parent = new int[n];//0 based
ranks = new int[n];
groupSize = new int[n];//Size of each component
for (int i = 0; i < n; i++) {
parent[i] = i;
ranks[i] = 1; groupSize[i] = 1;
}
}
public int find(int x)//Path Compression
{
if (parent[x] == x)
return x;
else
return parent[x] = find(parent[x]);
}
public void union(int x, int y)//Union by rank
{
int x_rep = find(x);
int y_rep = find(y);
if (x_rep == y_rep)
return;
if (ranks[x_rep] < ranks[y_rep])
{
parent[x_rep] = y_rep;
groupSize[y_rep] += groupSize[x_rep];
}
else if (ranks[x_rep] > ranks[y_rep])
{
parent[y_rep] = x_rep;
groupSize[x_rep] += groupSize[y_rep];
}
else {
parent[y_rep] = x_rep;
ranks[x_rep]++;
groupSize[x_rep] += groupSize[y_rep];
}
size--;//Total connected components
}
}
public static int gcd(int x,int y)
{
return y==0?x:gcd(y,x%y);
}
public static long gcd(long x,long y)
{
return y==0L?x:gcd(y,x%y);
}
public static int lcm(int a, int b) {
return (a * b) / gcd(a, b);
}
public static long lcm(long a, long b) {
return (a * b) / gcd(a, b);
}
public static long pow(long a,long b)
{
if(b==0L)
return 1L;
long tmp=1;
while(b>1L)
{
if((b&1L)==1)
tmp*=a;
a*=a;
b>>=1;
}
return (tmp*a);
}
public static long modPow(long a,long b,long mod)
{
if(b==0L)
return 1L;
long tmp=1;
while(b>1L)
{
if((b&1L)==1L)
tmp*=a;
a*=a;
a%=mod;
tmp%=mod;
b>>=1;
}
return (tmp*a)%mod;
}
static long mul(long a, long b) {
return a*b%mod;
}
static long fact(int n) {
long ans=1;
for (int i=2; i<=n; i++) ans=mul(ans, i);
return ans;
}
static long fastPow(long base, long exp) {
if (exp==0) return 1;
long half=fastPow(base, exp/2);
if (exp%2==0) return mul(half, half);
return mul(half, mul(half, base));
}
static void debug(int ...a)
{
for(int x: a)
out.print(x+" ");
out.println();
}
static void debug(long ...a)
{
for(long x: a)
out.print(x+" ");
out.println();
}
static void debugMatrix(int[][] a)
{
for(int[] x:a)
out.println(Arrays.toString(x));
}
static void debugMatrix(long[][] a)
{
for(long[] x:a)
out.println(Arrays.toString(x));
}
static void reverseArray(int[] a) {
int n = a.length;
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = a[n - i - 1];
for (int i = 0; i < n; i++)
a[i] = arr[i];
}
static void reverseArray(long[] a) {
int n = a.length;
long[] arr = new long[n];
for (int i = 0; i < n; i++)
arr[i] = a[n - i - 1];
for (int i = 0; i < n; i++)
a[i] = arr[i];
}
static void sort(int[] a)
{
ArrayList<Integer> ls = new ArrayList<>();
for(int x: a) ls.add(x);
Collections.sort(ls);
for(int i=0;i<a.length;i++)
a[i] = ls.get(i);
}
static void sort(long[] a)
{
ArrayList<Long> ls = new ArrayList<>();
for(long x: a) ls.add(x);
Collections.sort(ls);
for(int i=0;i<a.length;i++)
a[i] = ls.get(i);
}
static class Pair{
int x, y;
Pair(int x, int y)
{
this.x = x;
this.y = y;
}
}
}
| java |
1305 | D | D. Kuroni and the Celebrationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem; Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with nn vertices. The tree is rooted at vertex rr, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices uu and vv, and it'll return a vertex ww, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most ⌊n2⌋⌊n2⌋ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location?InteractionThe interaction starts with reading a single integer nn (2≤n≤10002≤n≤1000), the number of vertices of the tree.Then you will read n−1n−1 lines, the ii-th of them has two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), denoting there is an edge connecting vertices xixi and yiyi. It is guaranteed that the edges will form a tree.Then you can make queries of type "? u v" (1≤u,v≤n1≤u,v≤n) to find the lowest common ancestor of vertex uu and vv.After the query, read the result ww as an integer.In case your query is invalid or you asked more than ⌊n2⌋⌊n2⌋ queries, the program will print −1−1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.When you find out the vertex rr, print "! rr" and quit after that. This query does not count towards the ⌊n2⌋⌊n2⌋ limit.Note that the tree is fixed beforehand and will not change during the queries, i.e. the interactor is not adaptive.After printing any query do not forget to print end of line and flush the output. Otherwise, you might get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages.HacksTo hack, use the following format:The first line should contain two integers nn and rr (2≤n≤10002≤n≤1000, 1≤r≤n1≤r≤n), denoting the number of vertices and the vertex with Kuroni's hotel.The ii-th of the next n−1n−1 lines should contain two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n) — denoting there is an edge connecting vertex xixi and yiyi.The edges presented should form a tree.ExampleInputCopy6
1 4
4 2
5 3
6 3
2 3
3
4
4
OutputCopy
? 5 6
? 3 1
? 1 2
! 4NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test: | [
"constructive algorithms",
"dfs and similar",
"interactive",
"trees"
] | import java.util.*;
import java.io.*;
public class Main {
static class Scan {
private byte[] buf=new byte[1024];
private int index;
private InputStream in;
private int total;
public Scan()
{
in=System.in;
}
public int scan()throws IOException
{
if(total<0)
throw new InputMismatchException();
if(index>=total)
{
index=0;
total=in.read(buf);
if(total<=0)
return -1;
}
return buf[index++];
}
public int scanInt()throws IOException
{
int integer=0;
int n=scan();
while(isWhiteSpace(n))
n=scan();
int neg=1;
if(n=='-')
{
neg=-1;
n=scan();
}
while(!isWhiteSpace(n))
{
if(n>='0'&&n<='9')
{
integer*=10;
integer+=n-'0';
n=scan();
}
else throw new InputMismatchException();
}
return neg*integer;
}
public double scanDouble()throws IOException
{
double doub=0;
int n=scan();
while(isWhiteSpace(n))
n=scan();
int neg=1;
if(n=='-')
{
neg=-1;
n=scan();
}
while(!isWhiteSpace(n)&&n!='.')
{
if(n>='0'&&n<='9')
{
doub*=10;
doub+=n-'0';
n=scan();
}
else throw new InputMismatchException();
}
if(n=='.')
{
n=scan();
double temp=1;
while(!isWhiteSpace(n))
{
if(n>='0'&&n<='9')
{
temp/=10;
doub+=(n-'0')*temp;
n=scan();
}
else throw new InputMismatchException();
}
}
return doub*neg;
}
public String scanString()throws IOException
{
StringBuilder sb=new StringBuilder();
int n=scan();
while(isWhiteSpace(n))
n=scan();
while(!isWhiteSpace(n))
{
sb.append((char)n);
n=scan();
}
return sb.toString();
}
private boolean isWhiteSpace(int n)
{
if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1)
return true;
return false;
}
}
public static void sort(int arr[],int l,int r) { //sort(arr,0,n-1);
if(l==r) {
return;
}
int mid=(l+r)/2;
sort(arr,l,mid);
sort(arr,mid+1,r);
merge(arr,l,mid,mid+1,r);
}
public static void merge(int arr[],int l1,int r1,int l2,int r2) {
int tmp[]=new int[r2-l1+1];
int indx1=l1,indx2=l2;
//sorting the two halves using a tmp array
for(int i=0;i<tmp.length;i++) {
if(indx1>r1) {
tmp[i]=arr[indx2];
indx2++;
continue;
}
if(indx2>r2) {
tmp[i]=arr[indx1];
indx1++;
continue;
}
if(arr[indx1]<arr[indx2]) {
tmp[i]=arr[indx1];
indx1++;
continue;
}
tmp[i]=arr[indx2];
indx2++;
}
//Copying the elements of tmp into the main array
for(int i=0,j=l1;i<tmp.length;i++,j++) {
arr[j]=tmp[i];
}
}
public static void sort(long arr[],int l,int r) { //sort(arr,0,n-1);
if(l==r) {
return;
}
int mid=(l+r)/2;
sort(arr,l,mid);
sort(arr,mid+1,r);
merge(arr,l,mid,mid+1,r);
}
public static void merge(long arr[],int l1,int r1,int l2,int r2) {
long tmp[]=new long[r2-l1+1];
int indx1=l1,indx2=l2;
//sorting the two halves using a tmp array
for(int i=0;i<tmp.length;i++) {
if(indx1>r1) {
tmp[i]=arr[indx2];
indx2++;
continue;
}
if(indx2>r2) {
tmp[i]=arr[indx1];
indx1++;
continue;
}
if(arr[indx1]<arr[indx2]) {
tmp[i]=arr[indx1];
indx1++;
continue;
}
tmp[i]=arr[indx2];
indx2++;
}
//Copying the elements of tmp into the main array
for(int i=0,j=l1;i<tmp.length;i++,j++) {
arr[j]=tmp[i];
}
}
static ArrayList<Integer> adj_lst[];
static int max_dist,n1,n2,mid;
public static void main(String args[]) throws IOException {
Scan input=new Scan();
int n=input.scanInt();
adj_lst=new ArrayList[n];
for(int i=0;i<n;i++) {
adj_lst[i]=new ArrayList<>();
}
for(int i=0;i<n-1;i++) {
int u=input.scanInt()-1;
int v=input.scanInt()-1;
adj_lst[u].add(v);
adj_lst[v].add(u);
}
max_dist=0;
n1=n2=-1;
DFS(0,0,-1);
mid=-1;
find(n1,0,-1);
int root=mid;
// System.out.println(n1+" "+n2+" "+root);
boolean done=true;
while(done) {
// System.out.println("root="+(root+1));
done=false;
if(adj_lst[root].size()==1) {
System.out.println("? "+(adj_lst[root].get(0)+1)+" "+(root+1));
System.out.flush();
int tmp=input.scanInt()-1;
adj_lst[root].remove(new Integer(tmp));
adj_lst[tmp].remove(new Integer(root));
if(tmp!=root) {
root=tmp;
done=true;
}
continue;
}
while(adj_lst[root].size()>1) {
int i=0;
if(i+1==adj_lst[root].size()) {
break;
}
System.out.println("? "+(adj_lst[root].get(i)+1)+" "+(adj_lst[root].get(i+1)+1));
System.out.flush();
int tmp=input.scanInt()-1;
if(tmp==root) {
adj_lst[adj_lst[root].get(i)].remove(new Integer(root));
adj_lst[adj_lst[root].get(i+1)].remove(new Integer(root));
adj_lst[root].remove(new Integer(adj_lst[root].get(i)));
adj_lst[root].remove(new Integer(adj_lst[root].get(i)));
continue;
}
adj_lst[root].remove(new Integer(tmp));
adj_lst[tmp].remove(new Integer(root));
root=tmp;
done=true;
break;
}
if(done) {
continue;
}
if(adj_lst[root].size()%2==1) {
root=adj_lst[root].get(adj_lst[root].size()-1);
done=true;
}
}
System.out.println("! "+(root+1));
System.out.flush();
}
public static int[] DFS(int root,int dep,int par) {
ArrayList<Integer> dist,node;
dist=new ArrayList<>();
node=new ArrayList<>();
for(int i=0;i<adj_lst[root].size();i++) {
if(adj_lst[root].get(i)!=par) {
int tmp[]=DFS(adj_lst[root].get(i),dep+1,root);
dist.add(tmp[0]);
node.add(tmp[1]);
}
}
if(dist.size()==0) {
return new int[]{1,root};
}
if(dist.size()==1) {
if(dist.get(0)>max_dist) {
max_dist=dist.get(0);
n1=node.get(0);
n2=root;
}
return new int[]{dist.get(0)+1,node.get(0)};
}
int max=-1,max_indx=-1,sec_max=-1,sec_max_indx=-1;
for(int i=0;i<dist.size();i++) {
if(dist.get(i)>max) {
max=dist.get(i);
max_indx=i;
}
}
for(int i=0;i<dist.size();i++) {
if(i==max_indx) {
continue;
}
if(dist.get(i)>sec_max) {
sec_max=dist.get(i);
sec_max_indx=i;
}
}
if(max+sec_max>max_dist) {
max_dist=max+sec_max;
n1=node.get(max_indx);
n2=node.get(sec_max_indx);
}
return new int[]{max+1,node.get(max_indx)};
}
public static int find(int root,int dep,int par) {
if(root==n2) {
return dep;
}
int tmp=-1;
for(int i=0;i<adj_lst[root].size();i++) {
if(adj_lst[root].get(i)!=par) {
tmp=find(adj_lst[root].get(i),dep+1,root);
if(tmp!=-1) {
break;
}
}
}
if(tmp==-1) {
return -1;
}
if(Math.abs(dep-(tmp/2))==0) {
mid=root;
}
if(mid==-1 && Math.abs(dep-(tmp/2))==1) {
mid=root;
}
return tmp;
}
}
| java |
1322 | A | A. Unusual Competitionstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputA bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example; sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not.The teacher gave Dmitry's class a very strange task — she asked every student to come up with a sequence of arbitrary length, consisting only of opening and closing brackets. After that all the students took turns naming the sequences they had invented. When Dima's turn came, he suddenly realized that all his classmates got the correct bracketed sequence, and whether he got the correct bracketed sequence, he did not know.Dima suspects now that he simply missed the word "correct" in the task statement, so now he wants to save the situation by modifying his sequence slightly. More precisely, he can the arbitrary number of times (possibly zero) perform the reorder operation.The reorder operation consists of choosing an arbitrary consecutive subsegment (substring) of the sequence and then reordering all the characters in it in an arbitrary way. Such operation takes ll nanoseconds, where ll is the length of the subsegment being reordered. It's easy to see that reorder operation doesn't change the number of opening and closing brackets. For example for "))((" he can choose the substring ")(" and do reorder ")()(" (this operation will take 22 nanoseconds).Since Dima will soon have to answer, he wants to make his sequence correct as fast as possible. Help him to do this, or determine that it's impossible.InputThe first line contains a single integer nn (1≤n≤1061≤n≤106) — the length of Dima's sequence.The second line contains string of length nn, consisting of characters "(" and ")" only.OutputPrint a single integer — the minimum number of nanoseconds to make the sequence correct or "-1" if it is impossible to do so.ExamplesInputCopy8
))((())(
OutputCopy6
InputCopy3
(()
OutputCopy-1
NoteIn the first example we can firstly reorder the segment from first to the fourth character; replacing it with "()()"; the whole sequence will be "()()())(". And then reorder the segment from the seventh to eighth character; replacing it with "()". In the end the sequence will be "()()()()"; while the total time spent is 4+2=64+2=6 nanoseconds. | [
"greedy"
] | import java.io.*;
import java.util.*;
public class Run {
public static int mod = 1000000007;
public static PrintWriter out = new PrintWriter(System.out);
public static boolean testing = false;
public static FastIO io;
public static String input_file = "./input.txt";
static {
try {
io = new FastIO();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static int[] sort(int[] arr) {
List<Integer> nums = new ArrayList<>();
for (int el : arr) nums.add(el);
Collections.sort(nums);
int[] res = new int[arr.length];
for (int i = 0; i < arr.length; i++) res[i] = nums.get(i);
return res;
}
public static long[] sort(long[] arr) {
List<Long> nums = new ArrayList<>();
for (long el : arr) nums.add(el);
Collections.sort(nums);
long[] res = new long[arr.length];
for (int i = 0; i < arr.length; i++) res[i] = nums.get(i);
return res;
}
public static void reverse(int[] arr, int i, int j) {
while (i < j) {
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
++i;
--j;
}
}
public static int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
public static int lowerBound(long[] arr, long x) {
int l = -1;
int r = arr.length;
while (r > l + 1) {
int m = l + (r - l) / 2;
if (arr[m] <= x) l = m;
else r = m;
}
return Math.max(0, l);
}
public static int upperBound(long[] arr, long x) {
int l = -1;
int r = arr.length;
while (r > l + 1) {
int m = l + (r - l) / 2;
if (arr[m] >= x) r = m;
else l = m;
}
return Math.min(arr.length - 1, r);
}
public static int log2(int a) {
return (int) (Math.log(a) / Math.log(2));
}
public static void tadd(TreeMap<Integer, Integer> ts, int key) {
ts.put(key, ts.getOrDefault(key, 0) + 1);
}
public static int solve(int d, int k) {
int can = d / (k + 1);
int last_left = d % (k + 1);
if (last_left < k) --can;
return Math.max(0, can);
}
public static void main(String[] args) {
int n = io.nextInt();
char[] arr = io.next().toCharArray();
int open = 0;
int close = 0;
for (char ch : arr) {
if (ch == '(') ++open;
else ++close;
}
if (open != close) {
out.write("-1\n");
} else {
int ans = 0;
open = 0;
close = 0;
List<Character> stack = new ArrayList<>();
for (char ch : arr) {
stack.add(ch);
if (ch == '(') open++;
else close++;
if (open == close && !balanced(stack)) ans += stack.size();
if (open == close) stack.clear();
}
out.write(ans + "\n");
}
out.close();
}
public static boolean balanced(List<Character> arr) {
Stack<Character> stack = new Stack<>();
for (char ch : arr) {
if (ch == '(') stack.push(ch);
else {
if (stack.isEmpty()) return false;
stack.pop();
}
}
return stack.isEmpty();
}
public static void treduce(TreeMap<Integer, Integer> ts, int key) {
ts.put(key, ts.get(key) - 1);
if (ts.get(key) == 0) ts.remove(key);
}
public void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
static class CC implements Comparator<Pair> {
public int compare(Pair o1, Pair o2) {
if (o1.first == o2.first) return o1.second - o2.second;
return o1.first - o2.first;
}
}
static class Pair {
int first, second;
public Pair(int first, int second) {
this.first = first;
this.second = second;
}
@Override
public String toString() {
return "Pair{" +
"first=" + first +
", second=" + second +
'}';
}
}
static class FastIO {
InputStreamReader s = new InputStreamReader(testing ? new FileInputStream(input_file) : System.in);
BufferedReader br = new BufferedReader(s);
StringTokenizer st = new StringTokenizer("");
FastIO() throws FileNotFoundException {
}
String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
}
}
| java |
1324 | F | F. Maximum White Subtreetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn vertices. A tree is a connected undirected graph with n−1n−1 edges. Each vertex vv of this tree has a color assigned to it (av=1av=1 if the vertex vv is white and 00 if the vertex vv is black).You have to solve the following problem for each vertex vv: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex vv? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains cntwcntw white vertices and cntbcntb black vertices, you have to maximize cntw−cntbcntw−cntb.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of vertices in the tree.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where aiai is the color of the ii-th vertex.Each of the next n−1n−1 lines describes an edge of the tree. Edge ii is denoted by two integers uiui and vivi, the labels of vertices it connects (1≤ui,vi≤n,ui≠vi(1≤ui,vi≤n,ui≠vi).It is guaranteed that the given edges form a tree.OutputPrint nn integers res1,res2,…,resnres1,res2,…,resn, where resiresi is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex ii.ExamplesInputCopy9
0 1 1 1 0 0 0 0 1
1 2
1 3
3 4
3 5
2 6
4 7
6 8
5 9
OutputCopy2 2 2 2 2 1 1 0 2
InputCopy4
0 0 1 0
1 2
1 3
1 4
OutputCopy0 -1 1 -1
NoteThe first example is shown below:The black vertices have bold borders.In the second example; the best subtree for vertices 2,32,3 and 44 are vertices 2,32,3 and 44 correspondingly. And the best subtree for the vertex 11 is the subtree consisting of vertices 11 and 33. | [
"dfs and similar",
"dp",
"graphs",
"trees"
] | import java.io.*;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.math.*;
/**
* _ _
* ( _) ( _)
* / / \\ / /\_\_
* / / \\ / / | \ \
* / / \\ / / |\ \ \
* / / , \ , / / /| \ \
* / / |\_ /| / / / \ \_\
* / / |\/ _ '_| \ / / / \ \\
* | / |/ 0 \0\ / | | \ \\
* | |\| \_\_ / / | \ \\
* | | |/ \.\ o\o) / \ | \\
* \ | /\\`v-v / | | \\
* | \/ /_| \\_| / | | \ \\
* | | /__/_ - / ___ | | \ \\
* \| [__] \_/ |_________ \ | \ ()
* / [___] ( \ \ |\ | | //
* | [___] |\| \| / |/
* /| [____] \ |/\ / / ||
* ( \ [____ / ) _\ \ \ \| | ||
* \ \ [_____| / / __/ \ / / //
* | \ [_____/ / / \ | \/ //
* | / '----| /=\____ _/ | / //
* __ / / | / ___/ _/\ \ | ||
* (/-(/-\) / \ (/\/\)/ | / | /
* (/\/\) / / //
* _________/ / /
* \____________/ (
*
*
* @author NTUDragons-Reborn
*/
public class Solution {
public static void main(String[] args) throws Exception {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Task solver = new Task();
solver.solve(in, out);
out.close();
}
// main solver
static class Task {
double eps = 0.00000001;
static final int MAXN = 100005;
static final int MOD = 1000000007;
// stores smallest prime factor for every number
static int spf[] = new int[MAXN];
static boolean[] prime;
Map<Integer, Set<Integer>> dp = new HashMap<>();
// Calculating SPF (Smallest Prime Factor) for every
// number till MAXN.
// Time Complexity : O(nloglogn)
public void sieve() {
spf[1] = 1;
for (int i = 2; i < MAXN; i++)
// marking smallest prime factor for every
// number to be itself.
spf[i] = i;
// separately marking spf for every even
// number as 2
for (int i = 4; i < MAXN; i += 2)
spf[i] = 2;
for (int i = 3; i * i < MAXN; i++) {
// checking if i is prime
if (spf[i] == i) {
// marking SPF for all numbers divisible by i
for (int j = i * i; j < MAXN; j += i)
// marking spf[j] if it is not
// previously marked
if (spf[j] == j)
spf[j] = i;
}
}
}
void sieveOfEratosthenes(int n) {
// Create a boolean array
// "prime[0..n]" and
// initialize all entries
// it as true. A value in
// prime[i] will finally be
// false if i is Not a
// prime, else true.
prime = new boolean[n + 1];
for (int i = 0; i <= n; i++)
prime[i] = true;
for (int p = 2; p * p <= n; p++) {
// If prime[p] is not changed, then it is a
// prime
if (prime[p] == true) {
// Update all multiples of p
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
}
// A O(log n) function returning primefactorization
// by dividing by smallest prime factor at every step
public Set<Integer> getFactorization(int x) {
if (dp.containsKey(x))
return dp.get(x);
Set<Integer> ret = new HashSet<>();
while (x != 1) {
if (spf[x] != 2)
ret.add(spf[x]);
x = x / spf[x];
}
dp.put(x, ret);
return ret;
}
public Map<Integer, Integer> getFactorizationPower(int x) {
Map<Integer, Integer> map = new HashMap<>();
while (x != 1) {
map.put(spf[x], map.getOrDefault(spf[x], 0) + 1);
x /= spf[x];
}
return map;
}
// function to find first index >= x
public int lowerIndex(List<Integer> arr, int n, int x) {
int l = 0, h = n - 1;
while (l <= h) {
int mid = (l + h) / 2;
if (arr.get(mid) >= x)
h = mid - 1;
else
l = mid + 1;
}
return l;
}
public int lowerIndex(int[] arr, int n, int x) {
int l = 0, h = n - 1;
while (l <= h) {
int mid = (l + h) / 2;
if (arr[mid] >= x)
h = mid - 1;
else
l = mid + 1;
}
return l;
}
// function to find last index <= y
public int upperIndex(List<Integer> arr, int n, int y) {
int l = 0, h = n - 1;
while (l <= h) {
int mid = (l + h) / 2;
if (arr.get(mid) <= y)
l = mid + 1;
else
h = mid - 1;
}
return h;
}
public int upperIndex(int[] arr, int n, int y) {
int l = 0, h = n - 1;
while (l <= h) {
int mid = (l + h) / 2;
if (arr[mid] <= y)
l = mid + 1;
else
h = mid - 1;
}
return h;
}
// function to count elements within given range
public int countInRange(List<Integer> arr, int n, int x, int y) {
// initialize result
int count = 0;
count = upperIndex(arr, n, y) -
lowerIndex(arr, n, x) + 1;
return count;
}
public int add(int a, int b) {
a += b;
while (a >= MOD)
a -= MOD;
while (a < 0)
a += MOD;
return a;
}
public int mul(int a, int b) {
long res = (long) a * (long) b;
return (int) (res % MOD);
}
public int power(int a, int b) {
int ans = 1;
while (b > 0) {
if ((b & 1) != 0)
ans = mul(ans, a);
b >>= 1;
a = mul(a, a);
}
return ans;
}
int[] fact = new int[MAXN];
int[] inv = new int[MAXN];
public int Ckn(int n, int k) {
if (k < 0 || n < 0)
return 0;
if (n < k)
return 0;
return mul(mul(fact[n], inv[k]), inv[n - k]);
}
public int inverse(int a) {
return power(a, MOD - 2);
}
public void preprocess() {
fact[0] = 1;
for (int i = 1; i < MAXN; i++)
fact[i] = mul(fact[i - 1], i);
inv[MAXN - 1] = inverse(fact[MAXN - 1]);
for (int i = MAXN - 2; i >= 0; i--) {
inv[i] = mul(inv[i + 1], i + 1);
}
}
/**
* return VALUE of lower bound for unsorted array
*/
public int lowerBoundNormalArray(int[] arr, int x) {
TreeSet<Integer> set = new TreeSet<>();
for (int num : arr)
set.add(num);
return set.lower(x);
}
/**
* return VALUE of upper bound for unsorted array
*/
public int upperBoundNormalArray(int[] arr, int x) {
TreeSet<Integer> set = new TreeSet<>();
for (int num : arr)
set.add(num);
return set.higher(x);
}
public void debugArr(int[] arr) {
for (int i : arr)
out.print(i + " ");
out.println();
}
public int rand() {
int min = 0, max = MAXN;
int random_int = (int) Math.floor(Math.random() * (max - min + 1) + min);
return random_int;
}
public void shuffleSort(int[] arr) {
shuffleArray(arr);
Arrays.sort(arr);
}
public void shuffleArray(int[] ar) {
// If running on Java 6 or older, use new Random() on RHS here
Random rnd = ThreadLocalRandom.current();
for (int i = ar.length - 1; i > 0; i--) {
int index = rnd.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
}
InputReader in;
PrintWriter out;
Scanner sc = new Scanner(System.in);
CustomFileReader cin;
int[] xor = new int[3 * 100000 + 5];
int[] pow2 = new int[1000000 + 1];
public void solve(InputReader in, PrintWriter out) throws Exception {
this.in = in;
this.out = out;
// sieveOfEratosthenes((int) Math.ceil(Math.sqrt(1000000000)));
// sieve();
// pow2[0]=1;
// for(int i=1;i<pow2.length;i++){
// pow2[i]= mul(pow2[i-1],2);
// }
int t = 1;
// preprocess();
// int t=in.nextInt();
// int t= cin.nextIntArrLine()[0];
for (int i = 1; i <= t; i++)
solveD(i);
}
final double pi = Math.acos(-1);
List[] adjs;
int[] a;
int[] cost;
int[] res;
public void solveD(int test) {
int n = in.nextInt();
adjs = new List[n + 1];
a = new int[n + 1];
cost = new int[n + 1];
res = new int[n + 1];
for (int i = 1; i <= n; i++) {
a[i] = in.nextInt();
res[i] = Integer.MIN_VALUE;
if (a[i] == 0)
a[i] = -1; // to eliminate with '1'
adjs[i] = new ArrayList<>();
}
for (int i = 0; i < n - 1; i++) {
int u = in.nextInt(), v = in.nextInt();
adjs[u].add(v);
adjs[v].add(u);
}
precompute(1, 0);
reroot(1, 0);
for (int i = 1; i <= n; i++)
out.print(res[i] + " ");
out.println();
}
void precompute(int u, int p) {
cost[u] += a[u];
for (int v : (List<Integer>) adjs[u]) {
if (v == p)
continue;
precompute(v, u);
cost[u] += Math.max(0, cost[v]);
}
}
void reroot(int u, int p) {
res[u] = cost[u];
for (int v : (List<Integer>) adjs[u]) {
if (v == p)
continue;
cost[u] -= Math.max(cost[v], 0);
cost[v] += Math.max(cost[u], 0);
reroot(v, u);
cost[v] -= Math.max(cost[u], 0);
cost[u] += Math.max(cost[v], 0);
}
}
static class ListNode {
int idx = -1;
ListNode next = null;
public ListNode(int idx) {
this.idx = idx;
}
}
public long _gcd(long a, long b) {
if (b == 0) {
return a;
} else {
return _gcd(b, a % b);
}
}
public long _lcm(long a, long b) {
return (a * b) / _gcd(a, b);
}
}
// static class SEG {
// Pair[] segtree;
// public SEG(int n){
// segtree= new Pair[4*n];
// Arrays.fill(segtree, new Pair(-1,Long.MAX_VALUE));
// }
// // void buildTree(int l, int r, int index) {
// // if (l == r) {
// // segtree[index].y = a[l];
// // return;
// // }
// // int mid = (l + r) / 2;
// // buildTree(l, mid, 2 * index + 1);
// // buildTree(mid + 1, r, 2 * index + 2);
// // segtree[index].y = Math.min(segtree[2 * index + 1].y, segtree[2 * index +
// 2].y);
// // }
// void update(int l, int r, int index, int pos, Pair val) {
// if (l == r) {
// segtree[index] = val;
// return;
// }
// int mid = (l + r) / 2;
// if (pos <= mid) update(l, mid, 2 * index + 1, pos, val);
// else update(mid + 1, r, 2 * index + 2, pos, val);
// if(segtree[2 * index + 1].y < segtree[2 * index + 2].y){
// segtree[index]= segtree[2 * index + 1];
// }
// else {
// segtree[index]= segtree[2 * index + 2];
// }
// }
// // Pair query(int l, int r, int from, int to, int index) {
// // if (from <= l && r <= to)
// // return segtree[index];
// // if (r < from | to < l)
// // return 0;
// // int mid = (l + r) / 2;
// // Pair left= query(l, mid, from, to, 2 * index + 1);
// // Pair right= query(mid + 1, r, from, to, 2 * index + 2);
// // if(left.y < right.y) return left;
// // else return right;
// // }
// }
static class Venice {
public Map<Long, Long> m = new HashMap<>();
public long base = 0;
public long totalValue = 0;
private int M = 1000000007;
private long addMod(long a, long b) {
a += b;
if (a >= M)
a -= M;
return a;
}
public void reset() {
m = new HashMap<>();
base = 0;
totalValue = 0;
}
public void update(long add) {
base = base + add;
}
public void add(long key, long val) {
long newKey = key - base;
m.put(newKey, addMod(m.getOrDefault(newKey, (long) 0), val));
}
}
static class Tuple implements Comparable<Tuple> {
int x, y, z;
public Tuple(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
@Override
public int compareTo(Tuple o) {
return this.z - o.z;
}
}
static class Point implements Comparable<Point> {
public double x;
public long y;
public Point(double x, long y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Point o) {
if (this.y != o.y)
return (int) (this.y - o.y);
return (int) (this.x - o.x);
}
}
// static class Vector {
// public long x;
// public long y;
// // p1 -> p2
// public Vector(Point p1, Point p2){
// this.x= p2.x-p1.x;
// this.y= p2.y-p1.y;
// }
// }
static class Pair implements Comparable<Pair> {
public int x;
public int y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Pair o) {
if (this.x != o.x)
return (int) (this.x - o.x);
return (int) (this.y - o.y);
}
}
// public static class compareL implements Comparator<Tuple>{
// @Override
// public int compare(Tuple t1, Tuple t2) {
// return t2.l - t1.l;
// }
// }
// fast input reader class;
static class InputReader {
BufferedReader br;
StringTokenizer st;
public InputReader(InputStream stream) {
br = new BufferedReader(new InputStreamReader(stream));
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
String line = null;
try {
line = br.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
if (line == null) {
return null;
}
st = new StringTokenizer(line);
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public double nextDouble() {
return Double.parseDouble(nextToken());
}
public long nextLong() {
return Long.parseLong(nextToken());
}
public int[] nextIntArr(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = nextInt();
return arr;
}
public long[] nextLongArr(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++)
arr[i] = nextLong();
return arr;
}
public List<Integer> nextIntList(int n) {
List<Integer> arr = new ArrayList<>();
for (int i = 0; i < n; i++)
arr.add(nextInt());
return arr;
}
public int[][] nextIntMatArr(int n, int m) {
int[][] mat = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
mat[i][j] = nextInt();
return mat;
}
public List<List<Integer>> nextIntMatList(int n, int m) {
List<List<Integer>> mat = new ArrayList<>();
for (int i = 0; i < n; i++) {
List<Integer> temp = new ArrayList<>();
for (int j = 0; j < m; j++)
temp.add(nextInt());
mat.add(temp);
}
return mat;
}
public char[] nextStringCharArr() {
return nextToken().toCharArray();
}
}
static class CustomFileReader {
String path = "";
Scanner sc;
public CustomFileReader(String path) {
this.path = path;
try {
sc = new Scanner(new File(path));
} catch (Exception e) {
}
}
public String nextLine() {
return sc.nextLine();
}
public int[] nextIntArrLine() {
String line = sc.nextLine();
String[] part = line.split("[\\s+]");
int[] res = new int[part.length];
for (int i = 0; i < res.length; i++)
res[i] = Integer.parseInt(part[i]);
return res;
}
}
} | java |
1305 | E | E. Kuroni and the Score Distributiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is the coordinator of the next Mathforces round written by the "Proof by AC" team. All the preparation has been done; and he is discussing with the team about the score distribution for the round.The round consists of nn problems, numbered from 11 to nn. The problems are ordered in increasing order of difficulty, no two problems have the same difficulty. A score distribution for the round can be denoted by an array a1,a2,…,ana1,a2,…,an, where aiai is the score of ii-th problem. Kuroni thinks that the score distribution should satisfy the following requirements: The score of each problem should be a positive integer not exceeding 109109. A harder problem should grant a strictly higher score than an easier problem. In other words, 1≤a1<a2<⋯<an≤1091≤a1<a2<⋯<an≤109. The balance of the score distribution, defined as the number of triples (i,j,k)(i,j,k) such that 1≤i<j<k≤n1≤i<j<k≤n and ai+aj=akai+aj=ak, should be exactly mm. Help the team find a score distribution that satisfies Kuroni's requirement. In case such a score distribution does not exist, output −1−1.InputThe first and single line contains two integers nn and mm (1≤n≤50001≤n≤5000, 0≤m≤1090≤m≤109) — the number of problems and the required balance.OutputIf there is no solution, print a single integer −1−1.Otherwise, print a line containing nn integers a1,a2,…,ana1,a2,…,an, representing a score distribution that satisfies all the requirements. If there are multiple answers, print any of them.ExamplesInputCopy5 3
OutputCopy4 5 9 13 18InputCopy8 0
OutputCopy10 11 12 13 14 15 16 17
InputCopy4 10
OutputCopy-1
NoteIn the first example; there are 33 triples (i,j,k)(i,j,k) that contribute to the balance of the score distribution. (1,2,3)(1,2,3) (1,3,4)(1,3,4) (2,4,5)(2,4,5) | [
"constructive algorithms",
"greedy",
"implementation",
"math"
] | //package com.company;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
long ind=2;
// write your code here
int n=s.nextInt();
int m=s.nextInt();StringBuilder sb=new StringBuilder();
long [] ans=new long[n];ans[0]=1;if(n>1)ans[1]=2;
sb.append(1+" ");
if(n>1) sb.append(2+" ");
for(int i=2;i<n;i++){
if(m==0){
ans[i]=ans[i-1]+ind+1;
if(ans[i]>1000000000) m= Integer.MAX_VALUE;
sb.append(ans[i]+" ");continue;
}
for(int k=i;k>=0;k--){
if(k/2<=m){
m-=k/2;
ans[i]=ans[i-1]+ans[i-k];
ind=ans[i];
if(ans[i]>1000000000) m= Integer.MAX_VALUE;
sb.append(ans[i]+" ");
break;
}
}
}
// System.out.println(m);
// System.out.println(sb.toString());
/* for(int i=1;i<=n;i++){
if(m==0) {sb.append((100000000-(n-i))+" ");continue;}
if(i%2==0){
if((i-1)/2*(4+((i-1)/2-1)*2)/2<m){
sb.append(i+" ");
// ans[i]=i;
}else if((i-1)/2*(4+((i-1)/2-1)*2)/2==m) {
m=0;
sb.append(i+" ");
}
else{
if(m>((i-1)/2)*((2+((i-1)/2-1)*2))/2)
m-=((i-1)/2)*((2+((i-1)/2-1)*2))/2;
m--;
sb.append((i-1+i-2)+" ");
}
}else{
if((i/2)*((2+(i/2-1)*2))/2<m){
sb.append(i+" ");
// ans[i]=i;
}else if((i/2)*((2+(i/2-1)*2))/2==m) {
m=0;
sb.append(i+" ");
}
else{
if((i-2)/2*(4+((i-2)/2-1)*2)/2<m) m-=(i-2)/2*(4+((i-2)/2-1)*2)/2;
m--;
sb.append((i-1+i-2)+" ");
}
}
}*/
// System.out.println(m+" " +sb.toString());
if(m>0) System.out.println(-1);else
System.out.println(sb.toString() );
}
} | java |
1320 | B | B. Navigation Systemtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe map of Bertown can be represented as a set of nn intersections, numbered from 11 to nn and connected by mm one-way roads. It is possible to move along the roads from any intersection to any other intersection. The length of some path from one intersection to another is the number of roads that one has to traverse along the path. The shortest path from one intersection vv to another intersection uu is the path that starts in vv, ends in uu and has the minimum length among all such paths.Polycarp lives near the intersection ss and works in a building near the intersection tt. Every day he gets from ss to tt by car. Today he has chosen the following path to his workplace: p1p1, p2p2, ..., pkpk, where p1=sp1=s, pk=tpk=t, and all other elements of this sequence are the intermediate intersections, listed in the order Polycarp arrived at them. Polycarp never arrived at the same intersection twice, so all elements of this sequence are pairwise distinct. Note that you know Polycarp's path beforehand (it is fixed), and it is not necessarily one of the shortest paths from ss to tt.Polycarp's car has a complex navigation system installed in it. Let's describe how it works. When Polycarp starts his journey at the intersection ss, the system chooses some shortest path from ss to tt and shows it to Polycarp. Let's denote the next intersection in the chosen path as vv. If Polycarp chooses to drive along the road from ss to vv, then the navigator shows him the same shortest path (obviously, starting from vv as soon as he arrives at this intersection). However, if Polycarp chooses to drive to another intersection ww instead, the navigator rebuilds the path: as soon as Polycarp arrives at ww, the navigation system chooses some shortest path from ww to tt and shows it to Polycarp. The same process continues until Polycarp arrives at tt: if Polycarp moves along the road recommended by the system, it maintains the shortest path it has already built; but if Polycarp chooses some other path, the system rebuilds the path by the same rules.Here is an example. Suppose the map of Bertown looks as follows, and Polycarp drives along the path [1,2,3,4][1,2,3,4] (s=1s=1, t=4t=4): Check the picture by the link http://tk.codeforces.com/a.png When Polycarp starts at 11, the system chooses some shortest path from 11 to 44. There is only one such path, it is [1,5,4][1,5,4]; Polycarp chooses to drive to 22, which is not along the path chosen by the system. When Polycarp arrives at 22, the navigator rebuilds the path by choosing some shortest path from 22 to 44, for example, [2,6,4][2,6,4] (note that it could choose [2,3,4][2,3,4]); Polycarp chooses to drive to 33, which is not along the path chosen by the system. When Polycarp arrives at 33, the navigator rebuilds the path by choosing the only shortest path from 33 to 44, which is [3,4][3,4]; Polycarp arrives at 44 along the road chosen by the navigator, so the system does not have to rebuild anything. Overall, we get 22 rebuilds in this scenario. Note that if the system chose [2,3,4][2,3,4] instead of [2,6,4][2,6,4] during the second step, there would be only 11 rebuild (since Polycarp goes along the path, so the system maintains the path [3,4][3,4] during the third step).The example shows us that the number of rebuilds can differ even if the map of Bertown and the path chosen by Polycarp stays the same. Given this information (the map and Polycarp's path), can you determine the minimum and the maximum number of rebuilds that could have happened during the journey?InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105) — the number of intersections and one-way roads in Bertown, respectively.Then mm lines follow, each describing a road. Each line contains two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) denoting a road from intersection uu to intersection vv. All roads in Bertown are pairwise distinct, which means that each ordered pair (u,v)(u,v) appears at most once in these mm lines (but if there is a road (u,v)(u,v), the road (v,u)(v,u) can also appear).The following line contains one integer kk (2≤k≤n2≤k≤n) — the number of intersections in Polycarp's path from home to his workplace.The last line contains kk integers p1p1, p2p2, ..., pkpk (1≤pi≤n1≤pi≤n, all these integers are pairwise distinct) — the intersections along Polycarp's path in the order he arrived at them. p1p1 is the intersection where Polycarp lives (s=p1s=p1), and pkpk is the intersection where Polycarp's workplace is situated (t=pkt=pk). It is guaranteed that for every i∈[1,k−1]i∈[1,k−1] the road from pipi to pi+1pi+1 exists, so the path goes along the roads of Bertown. OutputPrint two integers: the minimum and the maximum number of rebuilds that could have happened during the journey.ExamplesInputCopy6 9
1 5
5 4
1 2
2 3
3 4
4 1
2 6
6 4
4 2
4
1 2 3 4
OutputCopy1 2
InputCopy7 7
1 2
2 3
3 4
4 5
5 6
6 7
7 1
7
1 2 3 4 5 6 7
OutputCopy0 0
InputCopy8 13
8 7
8 6
7 5
7 4
6 5
6 4
5 3
5 2
4 3
4 2
3 1
2 1
1 8
5
8 7 5 2 1
OutputCopy0 3
| [
"dfs and similar",
"graphs",
"shortest paths"
] | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class cf1320b {
public static void main(String[] args) throws IOException {
int n = rni(), m = ni();
List<List<Integer>> adj = new ArrayList<>();
for(int i = 0; i < n; ++i) {
adj.add(new ArrayList<>());
}
for(int i = 0; i < m; ++i) {
int u = rni() - 1, v = ni() - 1;
adj.get(v).add(u);
}
int k = ri(), p[] = ria(k);
for(int i = 0; i < k; ++i) {
--p[i];
}
List<Set<Integer>> par = new ArrayList<>();
for(int i = 0; i < n; ++i) {
par.add(new HashSet<>());
}
int dist[] = new int[n];
fill(dist, IBIG);
int src = p[k - 1];
PriorityQueue<int[]> q = new PriorityQueue<>((a, b) -> a[1] == b[1] ? a[0] - b[0] : a[1] - b[1]);
q.offer(new int[] {src, 0});
while(!q.isEmpty()) {
int[] i = q.poll();
if(i[1] > dist[i[0]]) {
continue;
}
for(int nei : adj.get(i[0])) {
int d = i[1] + 1;
if(d < dist[nei]) {
dist[nei] = d;
par.get(nei).clear();
par.get(nei).add(i[0]);
q.offer(new int[] {nei, dist[nei]});
} else if(d == dist[nei]) {
par.get(nei).add(i[0]);
}
}
}
// prln(par);
int min = 0, max = 0;
for(int i = 0; i < k - 1; ++i) {
if(par.get(p[i]).size() > 1 || !par.get(p[i]).contains(p[i + 1])) {
++max;
if(!par.get(p[i]).contains(p[i + 1])) {
++min;
}
}
}
prln(min, max);
close();
}
// dijk_P = {node, dist}
static int[][] dijk(int src, List<List<dijk_P>> adjList) {
return dijk(src, adjList, IBIG);
}
static int[][] dijk(int src, List<List<dijk_P>> adjList, int inf) {
int n = adjList.size(), dist[] = new int[n], par[] = new int[n];
fill(dist, inf);
fill(par, -1);
dist[src] = 0;
PriorityQueue<dijk_P> q = new PriorityQueue<>((a, b) -> a.b == b.b ? a.a - b.a : b.b - a.b);
q.offer(new dijk_P(src, 0));
while(!q.isEmpty()) {
dijk_P i = q.poll();
if(i.b > dist[i.a]) {
continue;
}
for(dijk_P nei : adjList.get(i.a)) {
int d = i.b + nei.b;
if(d < dist[nei.a]) {
dist[nei.a] = d;
par[nei.a] = i.a;
q.offer(new dijk_P(nei.a, dist[nei.a]));
}
}
}
return new int[][] {dist, par};
}
static class dijk_P {
int a, b;
dijk_P(int a_, int b_) {
a = a_;
b = b_;
}
@Override
public String toString() {
return "Pair{" + "a = " + a + ", b = " + b + '}';
}
public boolean equalsSafe(Object o) {
if(this == o) return true;
if(o == null || getClass() != o.getClass()) return false;
dijk_P p = (dijk_P)o;
return a == p.a && b == p.b;
}
public boolean equalsUnchecked(Object o) {
dijk_P p = (dijk_P)o;
return a == p.a && b == p.b;
}
@Override
public boolean equals(Object o) {
return equalsUnchecked(o);
}
@Override
public int hashCode() {
return Objects.hash(a, b);
}
}
static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out));
static StringTokenizer input;
static Random rand = new Random();
// references
// IBIG = 1e9 + 7
// IRAND ~= 3e8
// IMAX ~= 2e10
// LMAX ~= 9e18
// constants
static final int IBIG = 1000000007;
static final int IRAND = 327859546;
static final int IMAX = 2147483647;
static final int IMIN = -2147483648;
static final long LMAX = 9223372036854775807L;
static final long LMIN = -9223372036854775808L;
// util
static int minof(int a, int b, int c) {return min(a, min(b, c));}
static int minof(int... x) {if(x.length == 1) return x[0]; if(x.length == 2) return min(x[0], x[1]); if(x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] < min) min = x[i]; return min;}
static long minof(long a, long b, long c) {return min(a, min(b, c));}
static long minof(long... x) {if(x.length == 1) return x[0]; if(x.length == 2) return min(x[0], x[1]); if(x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] < min) min = x[i]; return min;}
static int maxof(int a, int b, int c) {return max(a, max(b, c));}
static int maxof(int... x) {if(x.length == 1) return x[0]; if(x.length == 2) return max(x[0], x[1]); if(x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] > max) max = x[i]; return max;}
static long maxof(long a, long b, long c) {return max(a, max(b, c));}
static long maxof(long... x) {if(x.length == 1) return x[0]; if(x.length == 2) return max(x[0], x[1]); if(x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] > max) max = x[i]; return max;}
static int powi(int a, int b) {if(a == 0) return 0; int ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static long powl(long a, int b) {if(a == 0) return 0; long ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static int floori(double d) {return (int)d;}
static int ceili(double d) {return (int)ceil(d);}
static long floorl(double d) {return (long)d;}
static long ceill(double d) {return (long)ceil(d);}
static void shuffle(int[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void shuffle(long[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void shuffle(double[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static <T> void shuffle(T[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); T swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void rsort(int[] a) {shuffle(a); sort(a);}
static void rsort(long[] a) {shuffle(a); sort(a);}
static void rsort(double[] a) {shuffle(a); sort(a);}
static int randInt(int min, int max) {return rand.nextInt(max - min + 1) + min;}
// input
static void r() throws IOException {input = new StringTokenizer(__in.readLine());}
static int ri() throws IOException {return Integer.parseInt(__in.readLine());}
static long rl() throws IOException {return Long.parseLong(__in.readLine());}
static int[] ria(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()); return a;}
static long[] rla(int n) throws IOException {long[] a = new long[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Long.parseLong(input.nextToken()); return a;}
static char[] rcha() throws IOException {return __in.readLine().toCharArray();}
static String rline() throws IOException {return __in.readLine();}
static int rni() throws IOException {input = new StringTokenizer(__in.readLine()); return Integer.parseInt(input.nextToken());}
static int ni() {return Integer.parseInt(input.nextToken());}
static long rnl() throws IOException {input = new StringTokenizer(__in.readLine()); return Long.parseLong(input.nextToken());}
static long nl() {return Long.parseLong(input.nextToken());}
// output
static void pr(int i) {__out.print(i);}
static void prln(int i) {__out.println(i);}
static void pr(long l) {__out.print(l);}
static void prln(long l) {__out.println(l);}
static void pr(double d) {__out.print(d);}
static void prln(double d) {__out.println(d);}
static void pr(char c) {__out.print(c);}
static void prln(char c) {__out.println(c);}
static void pr(char[] s) {__out.print(new String(s));}
static void prln(char[] s) {__out.println(new String(s));}
static void pr(String s) {__out.print(s);}
static void prln(String s) {__out.println(s);}
static void pr(Object o) {__out.print(o);}
static void prln(Object o) {__out.println(o);}
static void prln() {__out.println();}
static void pryes() {__out.println("yes");}
static void pry() {__out.println("Yes");}
static void prY() {__out.println("YES");}
static void prno() {__out.println("no");}
static void prn() {__out.println("No");}
static void prN() {__out.println("NO");}
static void pryesno(boolean b) {__out.println(b ? "yes" : "no");};
static void pryn(boolean b) {__out.println(b ? "Yes" : "No");}
static void prYN(boolean b) {__out.println(b ? "YES" : "NO");}
static void prln(int... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);}
static void prln(long... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);}
static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for(int i = 0; i < n; __out.print(iter.next()), __out.print(' '), ++i); if(n >= 0) __out.println(iter.next());}
static void h() {__out.println("hlfd");}
static void flush() {__out.flush();}
static void close() {__out.close();}
} | java |
1311 | C | C. Perform the Combotime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou want to perform the combo on your opponent in one popular fighting game. The combo is the string ss consisting of nn lowercase Latin letters. To perform the combo, you have to press all buttons in the order they appear in ss. I.e. if s=s="abca" then you have to press 'a', then 'b', 'c' and 'a' again.You know that you will spend mm wrong tries to perform the combo and during the ii-th try you will make a mistake right after pipi-th button (1≤pi<n1≤pi<n) (i.e. you will press first pipi buttons right and start performing the combo from the beginning). It is guaranteed that during the m+1m+1-th try you press all buttons right and finally perform the combo.I.e. if s=s="abca", m=2m=2 and p=[1,3]p=[1,3] then the sequence of pressed buttons will be 'a' (here you're making a mistake and start performing the combo from the beginning), 'a', 'b', 'c', (here you're making a mistake and start performing the combo from the beginning), 'a' (note that at this point you will not perform the combo because of the mistake), 'b', 'c', 'a'.Your task is to calculate for each button (letter) the number of times you'll press it.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.Then tt test cases follow.The first line of each test case contains two integers nn and mm (2≤n≤2⋅1052≤n≤2⋅105, 1≤m≤2⋅1051≤m≤2⋅105) — the length of ss and the number of tries correspondingly.The second line of each test case contains the string ss consisting of nn lowercase Latin letters.The third line of each test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n) — the number of characters pressed right during the ii-th try.It is guaranteed that the sum of nn and the sum of mm both does not exceed 2⋅1052⋅105 (∑n≤2⋅105∑n≤2⋅105, ∑m≤2⋅105∑m≤2⋅105).It is guaranteed that the answer for each letter does not exceed 2⋅1092⋅109.OutputFor each test case, print the answer — 2626 integers: the number of times you press the button 'a', the number of times you press the button 'b', ……, the number of times you press the button 'z'.ExampleInputCopy3
4 2
abca
1 3
10 5
codeforces
2 8 3 2 9
26 10
qwertyuioplkjhgfdsazxcvbnm
20 10 1 2 3 5 10 5 9 4
OutputCopy4 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 9 4 5 3 0 0 0 0 0 0 0 0 9 0 0 3 1 0 0 0 0 0 0 0
2 1 1 2 9 2 2 2 5 2 2 2 1 1 5 4 11 8 2 7 5 1 10 1 5 2
NoteThe first test case is described in the problem statement. Wrong tries are "a"; "abc" and the final try is "abca". The number of times you press 'a' is 44, 'b' is 22 and 'c' is 22.In the second test case, there are five wrong tries: "co", "codeforc", "cod", "co", "codeforce" and the final try is "codeforces". The number of times you press 'c' is 99, 'd' is 44, 'e' is 55, 'f' is 33, 'o' is 99, 'r' is 33 and 's' is 11. | [
"brute force"
] | import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int t = Integer.parseInt(f.readLine());
while (t-- > 0) {
StringTokenizer st = new StringTokenizer(f.readLine());
int n=Integer.parseInt(st.nextToken());
int m=Integer.parseInt(st.nextToken());
char[] arr=f.readLine().toCharArray();
int[] moves=new int[m+1];
st=new StringTokenizer(f.readLine());
for(int i=0;i<m;i++) {
moves[i]=Integer.parseInt(st.nextToken());
}
moves[m]=n;
int[][] pref=new int[26][n];
for(int i=0;i<n;i++) {
int x=arr[i]-'a';
pref[x][i]++;
}
for(int i=1;i<n;i++) {
for(int j=0;j<26;j++) {
pref[j][i]+=pref[j][i-1];
}
}
int[] ans=new int[26];
for(int i=0;i<=m;i++) {
for(int j=0;j<26;j++) {
ans[j]+=pref[j][moves[i]-1];
}
}
for(int i=0;i<26;i++) {
out.print(ans[i]+" ");
}
out.println();
}
out.close();
f.close();
}
}
| java |
1296 | E2 | E2. String Coloring (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is a hard version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters the minimum number of colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to find the minimum number of colors which you have to color the given string in so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIn the first line print one integer resres (1≤res≤n1≤res≤n) — the minimum number of colors in which you have to color the given string so that after coloring it can become sorted by some sequence of swaps.In the second line print any possible coloring that can be used to sort the string using some sequence of swaps described in the problem statement. The coloring is the array cc of length nn, where 1≤ci≤res1≤ci≤res and cici means the color of the ii-th character.ExamplesInputCopy9
abacbecfd
OutputCopy2
1 1 2 1 2 1 2 1 2
InputCopy8
aaabbcbb
OutputCopy2
1 2 1 2 1 2 1 1
InputCopy7
abcdedc
OutputCopy3
1 1 1 1 1 2 3
InputCopy5
abcde
OutputCopy1
1 1 1 1 1
| [
"data structures",
"dp"
] | // package c1296;
//
// Codeforces Round #617 (Div. 3) 2020-02-04 06:35
// E2. String Coloring (hard version)
// https://codeforces.com/contest/1296/problem/E2
// time limit per test 1 second; memory limit per test 256 megabytes
// public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*'
//
// .
//
// You are given a string s consisting of n lowercase Latin letters.
//
// You have to color its characters (each character to exactly one color, the same letters can be
// colored the same or different colors, i.e. you can choose exactly one color for each index in s).
//
// After coloring, you can swap two neighboring characters of the string that are colored colors.
// You can perform such an operation arbitrary (possibly, zero) number of times.
//
// The goal is to make the string sorted, i.e. all characters should be in alphabetical order.
//
// Your task is to find the minimum number of colors which you have to color the given string in so
// that after coloring it can become sorted by sequence of swaps. Note that you have to restore only
// coloring, not the sequence of swaps.
//
// Input
//
// The first line of the input contains one integer n (1 <= n <= 2 * 10^5) -- the length of s.
//
// The second line of the input contains the string s consisting of exactly n lowercase Latin
// letters.
//
// Output
//
// In the first line print one integer res (1 <= res <= n) -- the minimum number of colors in which
// you have to color the given string so that after coloring it can become sorted by sequence of
// swaps.
//
// In the second line print possible coloring that can be used to sort the string using some
// sequence of swaps described in the problem statement. The coloring is the array c of length n,
// where 1 <= c_i <= res and c_i means the color of the i-th character.
//
// Example
/*
input:
9
abacbecfd
output:
2
1 1 2 1 2 1 2 1 2
input:
8
aaabbcbb
output:
2
1 2 1 2 1 2 1 1
input:
7
abcdedc
output:
3
1 1 1 1 1 2 3
input:
5
abcde
output:
1
1 1 1 1 1
*/
//
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.TreeMap;
public class C1296E2 {
static final int MOD = 998244353;
static final Random RAND = new Random();
static final int NOCOLOR = 2;
static int[] solve(String s) {
int n = s.length();
// Array of (src_index, character, color, dst_index)
List<int[]> arr = new ArrayList<>();
for (int i = 0; i < n; i++) {
arr.add(new int[] {i, s.charAt(i) - 'a', NOCOLOR, 0});
}
Collections.sort(arr, (x,y)->x[1] != y[1] ? x[1] - y[1] : x[0] - y[0]);
for (int i = 0; i < n; i++) {
arr.get(i)[3] = i;
}
if (test) System.out.format(" arr:%s %s\n", traceListIntArray(arr), getStr(arr));
// Map from valuie to longest descending sequence in tail
TreeMap<Integer, Integer> vsm = new TreeMap<>();
int[] ans = new int[n];
int[] cnt = new int[n];
for (int i = n - 1; i >= 0; i--) {
int v = arr.get(i)[0];
Map.Entry<Integer, Integer> fe = vsm.floorEntry(v);
if (fe == null) {
vsm.put(v, 1);
} else {
vsm.put(v, fe.getValue() + 1);
}
int value = vsm.get(v);
int w = v + 1;
while (true) {
Map.Entry<Integer, Integer> ce = vsm.ceilingEntry(w);
if (ce == null || ce.getValue() > value) {
break;
} else {
vsm.remove(ce.getKey());
}
}
cnt[v] = value;
ans[v] = value;
}
return ans;
}
public static String traceListIntArray(List<int[]> points) {
StringBuilder sb = new StringBuilder();
sb.append('[');
boolean first = true;
for (int[] v : points) {
if (!first) {
sb.append(',');
}
first = false;
sb.append('[');
boolean first2 = true;
for (int w : v) {
if (!first2) {
sb.append(',');
}
sb.append(w);
first2 = false;
}
sb.append(']');
}
sb.append(']');
return sb.toString();
}
static String getStr(List<int[]> arr) {
StringBuilder sb = new StringBuilder();
for (int[] v : arr) {
sb.append((char)('a' + v[1]));
}
return sb.toString();
}
static void test(int exp, String s) {
int[] ans = solve(s);
int maxv = ans[0];
for (int v : ans) {
maxv = Math.max(maxv, v);
}
System.out.format("%s => %s\n", s, Arrays.toString(ans), maxv == exp ? "":"Expected " + exp);
myAssert(exp == maxv);
}
static boolean test = false;
static void doTest() {
if (!test) {
return;
}
long t0 = System.currentTimeMillis();
test(2, "abacbecfd");
test(2, "aaabbcbb");
test(3, "abcdedc");
test(1, "abcde");
System.out.format("%d msec\n", System.currentTimeMillis() - t0);
System.exit(0);
}
public static void main(String[] args) {
doTest();
MyScanner in = new MyScanner();
int n = in.nextInt();
String s = in.next();
int[] ans = solve(s);
output(ans);
}
static void output(int[] a) {
int maxv = a[0];
for (int v : a) {
maxv = Math.max(maxv, v);
}
StringBuilder sb = new StringBuilder();
sb.append(maxv);
sb.append('\n');
for (int v : a) {
sb.append(v);
sb.append(' ');
if (sb.length() > 4000) {
System.out.print(sb.toString());
sb.setLength(0);
}
}
System.out.println(sb.toString());
}
static void myAssert(boolean cond) {
if (!cond) {
throw new RuntimeException("Unexpected");
}
}
static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
try {
final String USERDIR = System.getProperty("user.dir");
String cname = MethodHandles.lookup().lookupClass().getCanonicalName().replace(".MyScanner", "");
cname = cname.lastIndexOf('.') > 0 ? cname.substring(cname.lastIndexOf('.') + 1) : cname;
final File fin = new File(USERDIR + "/io/c" + cname.substring(1,5) + "/" + cname + ".in");
br = new BufferedReader(new InputStreamReader(fin.exists()
? new FileInputStream(fin) : System.in));
} catch (Exception e) {
br = new BufferedReader(new InputStreamReader(System.in));
}
}
public String next() {
try {
while (st == null || !st.hasMoreElements()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| java |
1288 | A | A. Deadlinetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAdilbek was assigned to a special project. For Adilbek it means that he has nn days to run a special program and provide its results. But there is a problem: the program needs to run for dd days to calculate the results.Fortunately, Adilbek can optimize the program. If he spends xx (xx is a non-negative integer) days optimizing the program, he will make the program run in ⌈dx+1⌉⌈dx+1⌉ days (⌈a⌉⌈a⌉ is the ceiling function: ⌈2.4⌉=3⌈2.4⌉=3, ⌈2⌉=2⌈2⌉=2). The program cannot be run and optimized simultaneously, so the total number of days he will spend is equal to x+⌈dx+1⌉x+⌈dx+1⌉.Will Adilbek be able to provide the generated results in no more than nn days?InputThe first line contains a single integer TT (1≤T≤501≤T≤50) — the number of test cases.The next TT lines contain test cases – one per line. Each line contains two integers nn and dd (1≤n≤1091≤n≤109, 1≤d≤1091≤d≤109) — the number of days before the deadline and the number of days the program runs.OutputPrint TT answers — one per test case. For each test case print YES (case insensitive) if Adilbek can fit in nn days or NO (case insensitive) otherwise.ExampleInputCopy3
1 1
4 5
5 11
OutputCopyYES
YES
NO
NoteIn the first test case; Adilbek decides not to optimize the program at all; since d≤nd≤n.In the second test case, Adilbek can spend 11 day optimizing the program and it will run ⌈52⌉=3⌈52⌉=3 days. In total, he will spend 44 days and will fit in the limit.In the third test case, it's impossible to fit in the limit. For example, if Adilbek will optimize the program 22 days, it'll still work ⌈112+1⌉=4⌈112+1⌉=4 days. | [
"binary search",
"brute force",
"math",
"ternary search"
] | // Jai Shree Ram ⛳⛳⛳
// Jai Bajrang Bali
// Jai Saraswati maa
// Har Har Mahadev
// Thanks Kalash Shah :)
import java.math.BigInteger;
import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import static java.lang.Character.isUpperCase;
public class C {
static FastScanner sn = new FastScanner();
public static void main(String[] args) {
int T = sn.nextInt();
while (T-- > 0)
solve();
}
public static void solve() {
int n = sn.nextInt();
int d = sn.nextInt();
for (int i = 0; i <= 1000000; i++) {
if (i + (d + i) / (i + 1) <= n) {
System.out.println("YES");
return;
}
}
System.out.println("NO");
}
//----------------------------------------------------------------------------------//
public static void mergesort(long[] arr, int l, int r) {
if (l >= r) {
return;
}
int mid = l + (r - l) / 2;
mergesort(arr, l, mid);
mergesort(arr, mid + 1, r);
Merge(arr, l, mid, r);
}
static long getFirstSetBitPos(long n) {
return (long) ((Math.log10(n & -n)) / Math.log10(2)) + 1;
}
static int gcd(int a, int b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
static class Pair implements Comparable<Pair> {
int ind;
int ch;
Pair(int a, int ch) {
this.ind = a;
this.ch = ch;
}
public int compareTo(Pair o) {
if (this.ch == o.ch) {
return this.ind - o.ind;
}
return this.ch - o.ch;
}
public String toString() {
return "";
}
}
static int countSetBits(long n) {
int count = 0;
while (n > 0) {
count += n & 1;
n >>= 1;
}
return count;
}
public static void Merge(long[] arr, int l, int mid, int r) {
long[] B = new long[r - l + 1];
int i = l;
int j = mid + 1;
int k = 0;
while (i <= mid && j <= r) {
if (arr[i] <= arr[j]) {
B[k++] = arr[i++];
} else {
B[k++] = arr[j++];
}
}
while (i <= mid) {
B[k++] = arr[i++];
}
while (j <= r) {
B[k++] = arr[j++];
}
for (int i1 = 0, j1 = l; i1 < B.length; i1++, j1++) {
arr[j1] = B[i1];
}
}
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
char nextChar() {
return next().charAt(0);
}
long[] readArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
int[] scan(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
void print(int[] a) {
for (int j : a) {
System.out.print(j + " ");
}
}
void printl(long[] a) {
for (long j : a) {
System.out.print(j + " ");
}
}
long nextLong() {
return Long.parseLong(next());
}
}
static class Debug {
public static void debug(long a) {
System.out.println("--> " + a);
}
public static void debug(long a, long b) {
System.out.println("--> " + a + " + " + b);
}
public static void debug(char a, char b) {
System.out.println("--> " + a + " + " + b);
}
public static void debug(int[] array) {
System.out.print("Array--> ");
System.out.println(Arrays.toString(array));
}
public static void debug(char[] array) {
System.out.print("Array--> ");
System.out.println(Arrays.toString(array));
}
public static void debug(HashMap<Integer, Integer> map) {
System.out.print("Map--> " + map.toString());
}
}
} | java |
1304 | B | B. Longest Palindrometime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputReturning back to problem solving; Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome.Gildong loves this concept so much, so he wants to play with it. He has nn distinct strings of equal length mm. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one.InputThe first line contains two integers nn and mm (1≤n≤1001≤n≤100, 1≤m≤501≤m≤50) — the number of strings and the length of each string.Next nn lines contain a string of length mm each, consisting of lowercase Latin letters only. All strings are distinct.OutputIn the first line, print the length of the longest palindrome string you made.In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don't print this line at all.ExamplesInputCopy3 3
tab
one
bat
OutputCopy6
tabbat
InputCopy4 2
oo
ox
xo
xx
OutputCopy6
oxxxxo
InputCopy3 5
hello
codef
orces
OutputCopy0
InputCopy9 4
abab
baba
abcd
bcde
cdef
defg
wxyz
zyxw
ijji
OutputCopy20
ababwxyzijjizyxwbaba
NoteIn the first example; "battab" is also a valid answer.In the second example; there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are.In the third example; the empty string is the only valid palindrome string. | [
"brute force",
"constructive algorithms",
"greedy",
"implementation",
"strings"
] | import java.util.*;
public class HelloWorld{
public static void main(String []args){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int len=sc.nextInt();
String ans="";
String s1="",s2="";
String pal="";
HashSet<String>set=new HashSet<>();
while(n-->0){
String str=sc.next();
String rev=reverse(str);
if(str.equals(rev)){
pal=str;
}else if(set.contains(rev)){
set.remove(rev);
s1=s1+rev;
s2=str+s2;
}else{
set.add(str);
}
}
ans=s1+pal+s2;
System.out.println(ans.length() + "\n" + ans);
}
public static String reverse(String s) {
String str = "";
for (int i=s.length()-1;i>=0;i-- )
str += s.charAt(i)+"";
return str;
}
} | java |
1287 | B | B. Hypersettime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBees Alice and Alesya gave beekeeper Polina famous card game "Set" as a Christmas present. The deck consists of cards that vary in four features across three options for each kind of feature: number of shapes; shape, shading, and color. In this game, some combinations of three cards are said to make up a set. For every feature — color, number, shape, and shading — the three cards must display that feature as either all the same, or pairwise different. The picture below shows how sets look.Polina came up with a new game called "Hyperset". In her game, there are nn cards with kk features, each feature has three possible values: "S", "E", or "T". The original "Set" game can be viewed as "Hyperset" with k=4k=4.Similarly to the original game, three cards form a set, if all features are the same for all cards or are pairwise different. The goal of the game is to compute the number of ways to choose three cards that form a set.Unfortunately, winter holidays have come to an end, and it's time for Polina to go to school. Help Polina find the number of sets among the cards lying on the table.InputThe first line of each test contains two integers nn and kk (1≤n≤15001≤n≤1500, 1≤k≤301≤k≤30) — number of cards and number of features.Each of the following nn lines contains a card description: a string consisting of kk letters "S", "E", "T". The ii-th character of this string decribes the ii-th feature of that card. All cards are distinct.OutputOutput a single integer — the number of ways to choose three cards that form a set.ExamplesInputCopy3 3
SET
ETS
TSE
OutputCopy1InputCopy3 4
SETE
ETSE
TSES
OutputCopy0InputCopy5 4
SETT
TEST
EEET
ESTE
STES
OutputCopy2NoteIn the third example test; these two triples of cards are sets: "SETT"; "TEST"; "EEET" "TEST"; "ESTE", "STES" | [
"brute force",
"data structures",
"implementation"
] | import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt(), K = sc.nextInt();
String[] s = new String[N];
HashSet<String> mp = new HashSet<String>(N);
for (int i = 0; i < N; ++i) {
s[i] = sc.next();
mp.add(s[i]);
}
sc.close();
int cnt = 0;
for (int i = 0; i < N; ++i) {
for (int j = 0; j < i; ++j) {
StringBuilder t = new StringBuilder(K);
for (int k = 0; k < K; ++k) {
char c1 = s[i].charAt(k);
char c2 = s[j].charAt(k);
char c3 = (c1 == c2) ? c1 : (char) ('S'+'E'+'T'-c1-c2);
t.append(c3);
}
if (mp.contains(t.toString())) ++cnt;
}
}
System.out.println(cnt/3);
}
} | java |
1324 | F | F. Maximum White Subtreetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn vertices. A tree is a connected undirected graph with n−1n−1 edges. Each vertex vv of this tree has a color assigned to it (av=1av=1 if the vertex vv is white and 00 if the vertex vv is black).You have to solve the following problem for each vertex vv: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex vv? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains cntwcntw white vertices and cntbcntb black vertices, you have to maximize cntw−cntbcntw−cntb.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of vertices in the tree.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where aiai is the color of the ii-th vertex.Each of the next n−1n−1 lines describes an edge of the tree. Edge ii is denoted by two integers uiui and vivi, the labels of vertices it connects (1≤ui,vi≤n,ui≠vi(1≤ui,vi≤n,ui≠vi).It is guaranteed that the given edges form a tree.OutputPrint nn integers res1,res2,…,resnres1,res2,…,resn, where resiresi is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex ii.ExamplesInputCopy9
0 1 1 1 0 0 0 0 1
1 2
1 3
3 4
3 5
2 6
4 7
6 8
5 9
OutputCopy2 2 2 2 2 1 1 0 2
InputCopy4
0 0 1 0
1 2
1 3
1 4
OutputCopy0 -1 1 -1
NoteThe first example is shown below:The black vertices have bold borders.In the second example; the best subtree for vertices 2,32,3 and 44 are vertices 2,32,3 and 44 correspondingly. And the best subtree for the vertex 11 is the subtree consisting of vertices 11 and 33. | [
"dfs and similar",
"dp",
"graphs",
"trees"
] | import java.io.*;
import java.util.*;
public class new1{
static FastReader s = new FastReader();
static int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
public static int dfs1(ArrayList<ArrayList<Integer>> aList, int u, int p, int[] val, int[] arr1) {
int sum = val[u];
for(Integer x : aList.get(u)) {
if(x != p) {
int aa = dfs1(aList, x, u, val, arr1);
if(aa >= 0) sum = sum + aa;
}
}
arr1[u] = sum;
return sum;
}
public static void dfs2(ArrayList<ArrayList<Integer>> aList, int u, int p, int[] val, int[] arr1, int[] ans) {
if(p == -1) {
ans[u] = arr1[u];
}
else {
int ans1 = 0;
if(arr1[u] == -1) ans1 = Math.max(-1, ans[p] - 1);
else ans1 = Math.max(arr1[u], ans[p]);
ans[u] = ans1;
}
for(Integer x : aList.get(u)) {
if(x != p) {
dfs2(aList, x, u, val, arr1, ans);
}
}
}
public static void main(String[] args) throws IOException{
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out));
int t = 1;//s.nextInt();
for(int z = 0; z < t; z++) {
int n = s.nextInt();
int[] val = new int[n + 1];
for(int i = 1; i <= n; i++) {
if(s.nextInt() == 0) val[i] = -1;
else val[i] = 1;
}
ArrayList<ArrayList<Integer>> aList = new ArrayList<ArrayList<Integer>>();
for(int i = 1; i <= n + 1; i++) {
ArrayList<Integer> list = new ArrayList<Integer>();
aList.add(list);
}
for(int i = 0; i < n - 1; i++) {
int u = s.nextInt();
int v = s.nextInt();
aList.get(u).add(v);
aList.get(v).add(u);
}
int[] arr1 = new int[n + 1];
dfs1(aList, 1, -1, val, arr1);
// System.out.println(Arrays.toString(arr1));
int[] ans = new int[n + 1];
dfs2(aList, 1, -1, val, arr1, ans);
for(int i = 1; i <= n; i++) {
output.write(ans[i] + " ");
}
output.write("\n");
//System.out.println(Arrays.toString(ans));
}
output.flush();
}
}
class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}} | java |
1141 | C | C. Polycarp Restores Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn array of integers p1,p2,…,pnp1,p2,…,pn is called a permutation if it contains each number from 11 to nn exactly once. For example, the following arrays are permutations: [3,1,2][3,1,2], [1][1], [1,2,3,4,5][1,2,3,4,5] and [4,3,1,2][4,3,1,2]. The following arrays are not permutations: [2][2], [1,1][1,1], [2,3,4][2,3,4].Polycarp invented a really cool permutation p1,p2,…,pnp1,p2,…,pn of length nn. It is very disappointing, but he forgot this permutation. He only remembers the array q1,q2,…,qn−1q1,q2,…,qn−1 of length n−1n−1, where qi=pi+1−piqi=pi+1−pi.Given nn and q=q1,q2,…,qn−1q=q1,q2,…,qn−1, help Polycarp restore the invented permutation.InputThe first line contains the integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the length of the permutation to restore. The second line contains n−1n−1 integers q1,q2,…,qn−1q1,q2,…,qn−1 (−n<qi<n−n<qi<n).OutputPrint the integer -1 if there is no such permutation of length nn which corresponds to the given array qq. Otherwise, if it exists, print p1,p2,…,pnp1,p2,…,pn. Print any such permutation if there are many of them.ExamplesInputCopy3
-2 1
OutputCopy3 1 2 InputCopy5
1 1 1 1
OutputCopy1 2 3 4 5 InputCopy4
-1 2 2
OutputCopy-1
| [
"math"
] | //package com.company;//Read minute details if coming wrong for no idea questions
import com.sun.source.tree.ArrayAccessTree;
import javax.swing.*;
import java.beans.IntrospectionException;
import java.math.BigInteger;
import java.util.*;
import java.io.*;
public class Main {
static class pair implements Comparable<pair> {
long a = 0;
long b = 0;
// int cnt;
pair(long b, long a) {
this.a = b;
this.b = a;
// cnt = x;
}
@Override
public int compareTo(pair o) {
if(this.a != o.a)
return (int) (this.a - o.a);
else
return (int) (this.b - o.b);
}
// public boolean equals(Object o) {
// if (o instanceof pair) {
// pair p = (pair) o;
// return p.a == a && p.b == b;
// }
// return false;
// }
//
// public int hashCode() {
// return (Long.valueOf(a).hashCode()) * 31 + (Long.valueOf(b).hashCode());
// }
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
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());
}
String nextLine() {
String str = "";
try {
str = br.readLine().trim();
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
}
static class FastWriter {
private final BufferedWriter bw;
public FastWriter() {
this.bw = new BufferedWriter(new OutputStreamWriter(System.out));
}
public void prlong(Object object) throws IOException {
bw.append("" + object);
}
public void prlongln(Object object) throws IOException {
prlong(object);
bw.append("\n");
}
public void close() throws IOException {
bw.close();
}
}
public static long gcd(long a, long b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
//HASHsET COLLISION AVOIDING CODE FOR STORING STRINGS
// HashSet<Long> set = new HashSet<>();
// for(int i = 0; i < s.length(); i++){
// int b = 0;
// long h = 1;
// for(int j=i; j<s.length(); j++){
// h = 131*h + (int)s.charAt(j);
// b += bad[(int)(s.charAt(j)-'a')];
// if(b<=k){
// set.add(h);
// }
// }
// }
// System.out.println(set.size());
//dsu
static int[] par, rank;
public static void dsu(int n) {
par = new int[n];
rank = new int[n];
for (int i = 0; i < n; i++) {
par[i] = i;
rank[i] = 1;
}
}
static int find(int u) {
return par[u] == -1 ? -1 : par[u] == u ? u : (par[u] = find(par[u]));
}
static void union(int u, int v) {
int a = find(u), b = find(v);
if (a != b && a != -1 && b != -1) {
par[b] = a;
rank[a] += rank[b];
}
}
static void disunion(int u, int v) {
int a = find(u), b = find(v);
if (a != -1 && a == b) {
par[a] = -1;
}
}
static class Calc_nCr {
private final long[] fact;
private final long[] invfact;
private final int p;
Calc_nCr(int n, int prime) {
fact = new long[n + 5];
invfact = new long[n + 5];
p = prime;
fact[0] = 1;
for (int i = 1; i <= n; i++) {
fact[i] = (i * fact[i - 1]) % p;
}
invfact[n] = pow(fact[n], p - 2, p);
for (int i = n - 1; i >= 0; i--) {
invfact[i] = (invfact[i + 1] * (i + 1)) % p;
}
}
private long nCr(int n, int r) {
if (r > n || n < 0 || r < 0) return 0;
return (((fact[n] * invfact[r]) % p) * invfact[n - r]) % p;
}
private static long pow(long a, long b, int mod) {
long result = 1;
while (b > 0) {
if ((b & 1L) == 1) {
result = (result * a) % mod;
}
a = (a * a) % mod;
b >>= 1;
}
return result;
}
}
static void sort(long[] a ) {
ArrayList<Long> l = new ArrayList<>();
for(long i: a) {
l.add(i);
}
Collections.sort(l);
for(int i =0;i<a.length;++i) {
a[i] = l.get(i);
}
}
public static void main(String[] args) {
try {
FastReader in = new FastReader();
FastWriter out = new FastWriter();
// int mx=10000000;
// boolean isPrime[] = new boolean[mx+5]; int primeDiv[] = new int[mx+5];
// for (int i = 0; i <= mx; i++) {
// isPrime[i] = true;
// }
// for(int i =0;i<primeDiv.length;i++)
// primeDiv[i]=i;
// isPrime[0] = isPrime[1] = false;
// for (long i = 2; i <= mx; i++) {
// if (isPrime[(int)i]) {
// for (long j = i*i; j <= mx; j += i) {
// if (primeDiv[(int)j] == j) {
// primeDiv[(int)j] = (int)i;
// }
// isPrime[(int)j] = false;
// }
// }
// }
// System.out.println(
// String.format("%.12f", x));
int testCases=1;
// int n =in.nextInt();
// long arr[]=new long[n];
// ArrayList<Long>ans=new ArrayList<>();
// for(int i =0;i<n;i++)
//
//
// } ans.add(in.nextLong());
// Collections.sort(ans);
// for(int i =0;i<n;i++)
// arr[i]=ans.get(i);
int mod =1000000007;
fl:
while (testCases-- > 0) {
int n =in.nextInt();
int arr[]=new int[n-1];
for(int i=0;i<n-1;i++)
{arr[i]=in.nextInt();
}
int q[]=new int[n-1];
for(int i =0;i<n-1;i++)
q[i]=arr[i];
for(int i =1;i<n-1;i++)
arr[i]=arr[i]+arr[i-1];
// for(int i :arr)
// System.out.print(i+" ");
int max=-1000000000;
int min =0;
for(int i :arr)
{
max=Math.max(i,max);
min=Math.min(i,min);
}
int x =1-min;
ArrayList<Integer>ans=new ArrayList<>();
ans.add(x);
for(int i =0;i<n-1;i++)
ans.add(x+arr[i]);
HashSet<Integer>set=new HashSet<>();
//System.out.println(ans);
for(int i :ans)
{
if(set.contains(i)||i>n||i<1)
{
System.out.println(-1);
continue fl;
}
set.add(i);
}
for(int i :ans)
System.out.print(i+" ");
System.out.println();
}
out.close();
} catch (Exception e) {
return;
}
}
public static double dfs(ArrayList<ArrayList<Integer>>adj, int curr, int par) {
double len = 0;
for(int child: adj.get(curr)) {
if(child == par)
continue;
len += dfs(adj, child, curr)+1;
}
//System.out.println(curr+" "+len);
if(len == 0) // leaf node
return 0;
if(par == -1) // root node
return len/adj.get(curr).size();
return len/(adj.get(curr).size()-1);
}
static long comb(int r, int n)
{
long result;
result = factorial(n)/(factorial(r)*factorial(n-r));
return result;
}
static long factorial(int n) {
int c;
long result = 1;
for (c = 1; c <= n; c++)
result = result*c;
return result;
}
static void LongestPalindromicPrefix(String str,int lps[]){
// String temp = str + '/';
// str = reverse(str);
// temp += str;
String temp =str;
int n = temp.length();
for(int i = 1; i < n; i++)
{
int len = lps[i - 1];
while (len > 0 && temp.charAt(len) !=
temp.charAt(i))
{
len = lps[len - 1];
}
if (temp.charAt(i) == temp.charAt(len))
{
len++;
}
lps[i] = len;
}
// return temp.substring(0, lps[n - 1]);
}
static String reverse(String input)
{
char[] a = input.toCharArray();
int l, r = a.length - 1;
for(l = 0; l < r; l++, r--)
{
char temp = a[l];
a[l] = a[r];
a[r] = temp;
}
return String.valueOf(a);
}
}
/*
*
* ┏┓ ┏┓+ +
* ┏┛┻━━━┛┻┓ + +
* ┃ ┃
* ┃ ━ ┃ ++ + + +
* ████━████+
* ◥██◤ ◥██◤ +
* ┃ ┻ ┃
* ┃ ┃ + +
* ┗━┓ ┏━┛
* ┃ ┃ JACKS PET FROM ANOTHER WORLD
* ┃ ┃
* ┃ ┗━━━┓
* ┃ ┣┓-------
* ┃ ┏┛-------
* ┗┓┓┏━┳┓┏┛ + + + +
* ┃┫┫ ┃┫┫
* ┗┻┛ ┗┻┛+ + + +
*/
//RULES
//TAKE INPUT AS LONG IN CASE OF SUM OR MULITPLICATION OR CHECK THE CONTSRaint of the array
//Always use stringbuilder of out.println for strinof out.println for string or high level output
// IMPORTANT TRs1 TO USE BRUTE FORCE TECHNIQUE TO SOLVE THE PROs1 OTHER CERTAIN LIMIT IS GIVENIT IS GIVEN
//Read minute details if coming wrong for no idea questions | java |
1285 | D | D. Dr. Evil Underscorestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; as a friendship gift, Bakry gave Badawy nn integers a1,a2,…,ana1,a2,…,an and challenged him to choose an integer XX such that the value max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X) is minimum possible, where ⊕⊕ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X).InputThe first line contains integer nn (1≤n≤1051≤n≤105).The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤230−10≤ai≤230−1).OutputPrint one integer — the minimum possible value of max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X).ExamplesInputCopy3
1 2 3
OutputCopy2
InputCopy2
1 5
OutputCopy4
NoteIn the first sample; we can choose X=3X=3.In the second sample, we can choose X=5X=5. | [
"bitmasks",
"brute force",
"dfs and similar",
"divide and conquer",
"dp",
"greedy",
"strings",
"trees"
] |
import java.io.*;
import java.math.*;
import java.util.*;
public class test {
static class Pair {
int x;
int y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
static class Compare {
void compare(Pair arr[], int n) {
// Comparator to sort the pair according to second element
Arrays.sort(arr, new Comparator<Pair>() {
@Override
public int compare(Pair p1, Pair p2) {
if (p1.x != p2.x) {
return (int) (p1.x - p2.x);
} else {
return (int) (p1.y - p2.y);
}
// return Double.compare(a[0], b[0]);
}
});
// for (int i = 0; i < n; i++) {
// System.out.print(arr[i].x + " " + arr[i].y + " ");
// }
// System.out.println();
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static int recursion(ArrayList<Integer> a , int bit) {
if(bit == -1) {
return 0;
}
ArrayList<Integer> zero = new ArrayList<>();
ArrayList<Integer> one = new ArrayList<>();
for(int i=0;i<a.size();i++) {
if((( 1 << bit) & a.get(i))!= 0){
one.add(a.get(i));
}
else {
zero.add(a.get(i));
}
}
if(zero.size() == a.size()) {
return recursion(zero,bit-1);
}
if(one.size() == a.size()) {
return recursion(one,bit-1);
}
return (1<<bit) + Math.min(recursion(zero,bit-1), recursion(one,bit-1));
}
public static void main(String args[]) throws Exception {
Scanner sc = new Scanner();
StringBuilder res = new StringBuilder();
int tc = 1;
while (tc-- > 0) {
int n = sc.nextInt();
ArrayList<Integer> a = new ArrayList<>();
for(int i=0;i<n;i++) {
a.add(sc.nextInt());
}
res.append(recursion(a,30));
}
System.out.println(res);
}
}
| java |
1311 | F | F. Moving Pointstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn points on a coordinate axis OXOX. The ii-th point is located at the integer point xixi and has a speed vivi. It is guaranteed that no two points occupy the same coordinate. All nn points move with the constant speed, the coordinate of the ii-th point at the moment tt (tt can be non-integer) is calculated as xi+t⋅vixi+t⋅vi.Consider two points ii and jj. Let d(i,j)d(i,j) be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points ii and jj coincide at some moment, the value d(i,j)d(i,j) will be 00.Your task is to calculate the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of points.The second line of the input contains nn integers x1,x2,…,xnx1,x2,…,xn (1≤xi≤1081≤xi≤108), where xixi is the initial coordinate of the ii-th point. It is guaranteed that all xixi are distinct.The third line of the input contains nn integers v1,v2,…,vnv1,v2,…,vn (−108≤vi≤108−108≤vi≤108), where vivi is the speed of the ii-th point.OutputPrint one integer — the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).ExamplesInputCopy3
1 3 2
-100 2 3
OutputCopy3
InputCopy5
2 1 4 3 5
2 2 2 3 4
OutputCopy19
InputCopy2
2 1
-3 0
OutputCopy0
| [
"data structures",
"divide and conquer",
"implementation",
"sortings"
] | import java.io.*;
import java.util.*;
public class Main {
static class BIT {
int n;
long[] tree;
public BIT(int n) {
this.n = n;
tree = new long[n + 2];
}
long read(int i) {
i++;
long sum = 0;
while (i > 0) {
sum += tree[i];
i -= i & -i;
}
return sum;
}
void update(int i, int val) {
i++;
while (i <= n) {
tree[i] += val;
i += i & -i;
}
}
}
public static void main(String[] args) throws IOException
{
FastScanner f = new FastScanner();
int t=1;
// t=f.nextInt();
PrintWriter out=new PrintWriter(System.out);
for(int tt=0;tt<t;tt++) {
int n= f.nextInt();
int[] x=f.readArray(n);
int[] v=f.readArray(n);
TreeSet<Integer> tree=new TreeSet<>();
for(int i:v) tree.add(i);
HashMap<Integer,Integer> map=new HashMap<>();
int curr=0;
for(int i:tree) {
curr++;
map.put(i, curr);
}
for(int i=0;i<n;i++) {
v[i]=map.get(v[i]);
}
BIT val=new BIT(200005);
BIT count=new BIT(200005);
long ans=0;
int[][] l=new int[n][2];
for(int i=0;i<n;i++) {
l[i]=new int[] {x[i],v[i]};
}
Arrays.sort(l,new Comparator<int[]>() {
public int compare(int[] a,int[] b) {
return Integer.compare(a[0], b[0]);
}
});
for(int i=n-1;i>-1;i--) {
long num=count.read(n)-count.read(l[i][1]-1);
ans+=(-(long)l[i][0]*num+val.read(n)-val.read(l[i][1]-1));
count.update(l[i][1],1);
val.update(l[i][1],l[i][0]);
}
System.out.println(ans);
}
out.close();
}
static void sort(long[] p) {
ArrayList<Integer> q = new ArrayList<>();
for (long i: p) q.add((int) i);
Collections.sort(q);
for (int i = 0; i < p.length; i++) p[i] = q.get(i);
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
long[] readLongArray(int n) {
long[] a=new long[n];
for (int i=0; i<n; i++) a[i]=nextLong();
return a;
}
}
}
//Some things to notice
//Check for the overflow
//Binary Search
//Bitmask
//runtime error most of the time is due to array index out of range | java |
1292 | A | A. NEKO's Maze Gametime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 as DJ Mashiro - Happiness Breeze Ice - DJ Mashiro is dead or aliveNEKO#ΦωΦ has just got a new maze game on her PC!The game's main puzzle is a maze; in the forms of a 2×n2×n rectangle grid. NEKO's task is to lead a Nekomimi girl from cell (1,1)(1,1) to the gate at (2,n)(2,n) and escape the maze. The girl can only move between cells sharing a common side.However, at some moments during the game, some cells may change their state: either from normal ground to lava (which forbids movement into that cell), or vice versa (which makes that cell passable again). Initially all cells are of the ground type.After hours of streaming, NEKO finally figured out there are only qq such moments: the ii-th moment toggles the state of cell (ri,ci)(ri,ci) (either from ground to lava or vice versa).Knowing this, NEKO wonders, after each of the qq moments, whether it is still possible to move from cell (1,1)(1,1) to cell (2,n)(2,n) without going through any lava cells.Although NEKO is a great streamer and gamer, she still can't get through quizzes and problems requiring large amount of Brain Power. Can you help her?InputThe first line contains integers nn, qq (2≤n≤1052≤n≤105, 1≤q≤1051≤q≤105).The ii-th of qq following lines contains two integers riri, cici (1≤ri≤21≤ri≤2, 1≤ci≤n1≤ci≤n), denoting the coordinates of the cell to be flipped at the ii-th moment.It is guaranteed that cells (1,1)(1,1) and (2,n)(2,n) never appear in the query list.OutputFor each moment, if it is possible to travel from cell (1,1)(1,1) to cell (2,n)(2,n), print "Yes", otherwise print "No". There should be exactly qq answers, one after every update.You can print the words in any case (either lowercase, uppercase or mixed).ExampleInputCopy5 5
2 3
1 4
2 4
2 3
1 4
OutputCopyYes
No
No
No
Yes
NoteWe'll crack down the example test here: After the first query; the girl still able to reach the goal. One of the shortest path ways should be: (1,1)→(1,2)→(1,3)→(1,4)→(1,5)→(2,5)(1,1)→(1,2)→(1,3)→(1,4)→(1,5)→(2,5). After the second query, it's impossible to move to the goal, since the farthest cell she could reach is (1,3)(1,3). After the fourth query, the (2,3)(2,3) is not blocked, but now all the 44-th column is blocked, so she still can't reach the goal. After the fifth query, the column barrier has been lifted, thus she can go to the final goal again. | [
"data structures",
"dsu",
"implementation"
] |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.sort;
public class Codeforces {
public static void main(String[] args) {
FastReader fastReader = new FastReader();
PrintWriter out = new PrintWriter(System.out);
int tt = 1;
while(tt--> 0){
int n = fastReader.nextInt();
int q = fastReader.nextInt();
boolean [][] vis = new boolean[2][n];
int size1 = 0;
int size2 = 0;
for(int i = 0; i < q; i++){
int x= fastReader.nextInt()-1;
int y = fastReader.nextInt()-1;
vis[x][y] = !vis[x][y];
if(vis[x][y]){
if(x == 1 && vis[0][y]){
size1++;
}
if(x == 0 && vis[1][y]){
size1++;
}
}
int index = x^1;
if(!vis[x][y] && vis[index][y]){
size1--;
}
if(y-1>=0 && vis[x][y] && vis[index][y-1]){
size2++;
}
if(y+1 < n && vis[x][y] && vis[index][y+1]){
size2++;
}
if(y-1>=0 && !vis[x][y] && vis[index][y-1]){
size2--;
}
if(y+1 < n && !vis[x][y] && vis[index][y+1]){
size2--;
}
if(size1 > 0 || size2 > 0){
out.println("NO");
}else{
out.println("YES");
}
}
}
out.close();
}
static class Pair{
int x;
int y;
Pair(int x, int y){
this.x = x;
this.y = y;
}
}
// constants
static final int IBIG = 1000000007;
static final int IMAX = 2147483647;
static final long LMAX = 9223372036854775807L;
static Random __r = new Random();
// math util
static int minof(int a, int b, int c) {
return min(a, min(b, c));
}
static int minof(int... x) {
if (x.length == 1)
return x[0];
if (x.length == 2)
return min(x[0], x[1]);
if (x.length == 3)
return min(x[0], min(x[1], x[2]));
int min = x[0];
for (int i = 1; i < x.length; ++i)
if (x[i] < min)
min = x[i];
return min;
}
static long minof(long a, long b, long c) {
return min(a, min(b, c));
}
static long minof(long... x) {
if (x.length == 1)
return x[0];
if (x.length == 2)
return min(x[0], x[1]);
if (x.length == 3)
return min(x[0], min(x[1], x[2]));
long min = x[0];
for (int i = 1; i < x.length; ++i)
if (x[i] < min)
min = x[i];
return min;
}
static int maxof(int a, int b, int c) {
return max(a, max(b, c));
}
static int maxof(int... x) {
if (x.length == 1)
return x[0];
if (x.length == 2)
return max(x[0], x[1]);
if (x.length == 3)
return max(x[0], max(x[1], x[2]));
int max = x[0];
for (int i = 1; i < x.length; ++i)
if (x[i] > max)
max = x[i];
return max;
}
static long maxof(long a, long b, long c) {
return max(a, max(b, c));
}
static long maxof(long... x) {
if (x.length == 1)
return x[0];
if (x.length == 2)
return max(x[0], x[1]);
if (x.length == 3)
return max(x[0], max(x[1], x[2]));
long max = x[0];
for (int i = 1; i < x.length; ++i)
if (x[i] > max)
max = x[i];
return max;
}
static int powi(int a, int b) {
if (a == 0)
return 0;
int ans = 1;
while (b > 0) {
if ((b & 1) > 0)
ans *= a;
a *= a;
b >>= 1;
}
return ans;
}
static long powl(long a, int b) {
if (a == 0)
return 0;
long ans = 1;
while (b > 0) {
if ((b & 1) > 0)
ans *= a;
a *= a;
b >>= 1;
}
return ans;
}
static int fli(double d) {
return (int) d;
}
static int cei(double d) {
return (int) ceil(d);
}
static long fll(double d) {
return (long) d;
}
static long cel(double d) {
return (long) ceil(d);
}
static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
static int lcm(int a, int b) {
return (a / gcd(a, b)) * b;
}
static long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
static long lcm(long a, long b) {
return (a / gcd(a, b)) * b;
}
static int[] exgcd(int a, int b) {
if (b == 0)
return new int[] { 1, 0 };
int[] y = exgcd(b, a % b);
return new int[] { y[1], y[0] - y[1] * (a / b) };
}
static long[] exgcd(long a, long b) {
if (b == 0)
return new long[] { 1, 0 };
long[] y = exgcd(b, a % b);
return new long[] { y[1], y[0] - y[1] * (a / b) };
}
static int randInt(int min, int max) {
return __r.nextInt(max - min + 1) + min;
}
static long mix(long x) {
x += 0x9e3779b97f4a7c15L;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L;
x = (x ^ (x >> 27)) * 0x94d049bb133111ebL;
return x ^ (x >> 31);
}
public static boolean[] findPrimes(int limit) {
assert limit >= 2;
final boolean[] nonPrimes = new boolean[limit];
nonPrimes[0] = true;
nonPrimes[1] = true;
int sqrt = (int) Math.sqrt(limit);
for (int i = 2; i <= sqrt; i++) {
if (nonPrimes[i])
continue;
for (int j = i; j < limit; j += i) {
if (!nonPrimes[j] && i != j)
nonPrimes[j] = true;
}
}
return nonPrimes;
}
// array util
static void reverse(int[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
int swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void reverse(long[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
long swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void reverse(double[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
double swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void reverse(char[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
char swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void shuffle(int[] a) {
int n = a.length - 1;
for (int i = 0; i < n; ++i) {
int ind = randInt(i, n);
int swap = a[i];
a[i] = a[ind];
a[ind] = swap;
}
}
static void shuffle(long[] a) {
int n = a.length - 1;
for (int i = 0; i < n; ++i) {
int ind = randInt(i, n);
long swap = a[i];
a[i] = a[ind];
a[ind] = swap;
}
}
static void shuffle(double[] a) {
int n = a.length - 1;
for (int i = 0; i < n; ++i) {
int ind = randInt(i, n);
double swap = a[i];
a[i] = a[ind];
a[ind] = swap;
}
}
static void rsort(int[] a) {
shuffle(a);
sort(a);
}
static void rsort(long[] a) {
shuffle(a);
sort(a);
}
static void rsort(double[] a) {
shuffle(a);
sort(a);
}
static int[] copy(int[] a) {
int[] ans = new int[a.length];
for (int i = 0; i < a.length; ++i)
ans[i] = a[i];
return ans;
}
static long[] copy(long[] a) {
long[] ans = new long[a.length];
for (int i = 0; i < a.length; ++i)
ans[i] = a[i];
return ans;
}
static double[] copy(double[] a) {
double[] ans = new double[a.length];
for (int i = 0; i < a.length; ++i)
ans[i] = a[i];
return ans;
}
static char[] copy(char[] a) {
char[] ans = new char[a.length];
for (int i = 0; i < a.length; ++i)
ans[i] = a[i];
return ans;
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] ria(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = Integer.parseInt(next());
return a;
}
long nextLong() {
return Long.parseLong(next());
}
long[] rla(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = Long.parseLong(next());
return a;
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
| java |
1286 | A | A. Garlandtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVadim loves decorating the Christmas tree; so he got a beautiful garland as a present. It consists of nn light bulbs in a single row. Each bulb has a number from 11 to nn (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland. Now Vadim wants to put them back on.Vadim wants to put all bulb back on the garland. Vadim defines complexity of a garland to be the number of pairs of adjacent bulbs with numbers with different parity (remainder of the division by 22). For example, the complexity of 1 4 2 3 5 is 22 and the complexity of 1 3 5 7 6 4 2 is 11.No one likes complexity, so Vadim wants to minimize the number of such pairs. Find the way to put all bulbs back on the garland, such that the complexity is as small as possible.InputThe first line contains a single integer nn (1≤n≤1001≤n≤100) — the number of light bulbs on the garland.The second line contains nn integers p1, p2, …, pnp1, p2, …, pn (0≤pi≤n0≤pi≤n) — the number on the ii-th bulb, or 00 if it was removed.OutputOutput a single number — the minimum complexity of the garland.ExamplesInputCopy5
0 5 0 2 3
OutputCopy2
InputCopy7
1 0 0 5 0 0 2
OutputCopy1
NoteIn the first example; one should place light bulbs as 1 5 4 2 3. In that case; the complexity would be equal to 2; because only (5,4)(5,4) and (2,3)(2,3) are the pairs of adjacent bulbs that have different parity.In the second case, one of the correct answers is 1 7 3 5 6 4 2. | [
"dp",
"greedy",
"sortings"
] | //package com.example.practice.codeforces.below2000;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.StringTokenizer;
//A. Garland
public class Solution112 {
public static void main (String [] args) throws IOException {
// Use BufferedReader rather than RandomAccessFile; it's much faster
final BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
// input file name goes above
StringTokenizer st = new StringTokenizer(input.readLine());
final int n = Integer.parseInt(st.nextToken());
final int[] ns = readArrayInt(n, input);
out.println(calc(n, ns));
out.close(); // close the output file
}
private static int calc(final int n, final int[] ns) {
int[] rd = new int[n];
boolean[] seen = new boolean[n+1];
int pre = 0, odd = 0, even = 0;
for (int i=0;i<n;++i){
rd[i] = pre;
if (ns[i]==0)pre++;
seen[ns[i]] = true;
}
for (int i=1;i<=n;++i){
if (!seen[i]){
if (i%2==0)even++;
else odd++;
}
}
Integer[][][] dp = new Integer[2][n][odd+1];
return todo(dp, 0, 0, odd, rd, odd, even, ns);
}
private static int todo(Integer[][][] dp, int st, int idx, final int c, int[] rd, final int odd, final int even, int[] ns){
if (idx >= rd.length)return 0;
if (dp[st][idx][c] != null){
return dp[st][idx][c];
}
if (ns[idx] > 0){
dp[st][idx][c] = todo(dp, ns[idx]%2, idx+1, c, rd, odd, even, ns) + (idx==0 || st==(ns[idx]%2) ? 0 : 1);
}else {
dp[st][idx][c] = rd.length;
if (c > 0){
dp[st][idx][c] = todo(dp, 1, idx+1, c-1, rd, odd, even, ns) + (idx==0 || st==1 ? 0 : 1);
}
if (rd[idx]-(odd-c) < even){
dp[st][idx][c] = Math.min(dp[st][idx][c], todo(dp, 0, idx+1, c, rd, odd, even, ns) + (idx==0 || st==0 ? 0 : 1));
}
}
return dp[st][idx][c];
}
private static void printArray(long[] ns, final PrintWriter out){
for (int i=0;i<ns.length;++i){
out.print(ns[i]);
if (i+1<ns.length)out.print(" ");
else out.println();
}
}
private static void printArrayInt(int[] ns, final PrintWriter out){
for (int i=0;i<ns.length;++i){
out.print(ns[i]);
if (i+1<ns.length)out.print(" ");
else out.println();
}
}
private static void printArrayVertical(long[] ns, final PrintWriter out){
for (long a : ns){
out.println(a);
}
}
private static void printArrayVerticalInt(int[] ns, final PrintWriter out){
for (int a : ns){
out.println(a);
}
}
private static void printArray2D(long[][] ns, final int len, final PrintWriter out){
int cnt = 0;
for (long[] kk : ns){
cnt++;
if (cnt > len)break;
for (int i=0;i<kk.length;++i){
out.print(kk[i]);
if (i+1<kk.length)out.print(" ");
else out.println();
}
}
}
private static void printArray2DInt(int[][] ns, final int len, final PrintWriter out){
int cnt = 0;
for (int[] kk : ns){
cnt++;
if (cnt > len)break;
for (int i=0;i<kk.length;++i){
out.print(kk[i]);
if (i+1<kk.length)out.print(" ");
else out.println();
}
}
}
private static long[] readArray(final int n, final BufferedReader input) throws IOException{
long[] ns = new long[n];
StringTokenizer st = new StringTokenizer(input.readLine());
for (int i=0;i<n;++i){
ns[i] = Long.parseLong(st.nextToken());
}
return ns;
}
private static int[] readArrayInt(final int n, final BufferedReader input) throws IOException{
int[] ns = new int[n];
StringTokenizer st = new StringTokenizer(input.readLine());
for (int i=0;i<n;++i){
ns[i] = Integer.parseInt(st.nextToken());
}
return ns;
}
private static long[] readArrayVertical(final int n, final BufferedReader input) throws IOException{
long[] ns = new long[n];
for (int i=0;i<n;++i){
ns[i] = Long.parseLong(input.readLine());
}
return ns;
}
private static long[][] readArray2D(final int n, final int len, final BufferedReader input) throws IOException{
long[][] ns = new long[len][];
for (int i=0;i<n;++i){
StringTokenizer st = new StringTokenizer(input.readLine());
ArrayList<Long> al = new ArrayList<>();
while (st.hasMoreTokens()){
al.add(Long.parseLong(st.nextToken()));
}
long[] kk = new long[al.size()];
for (int j=0;j<kk.length;++j){
kk[j] = al.get(j);
}
ns[i] = kk;
}
return ns;
}
private static int[][] readArray2DInt(final int n, final int len, final BufferedReader input) throws IOException{
int[][] ns = new int[len][];
for (int i=0;i<n;++i){
StringTokenizer st = new StringTokenizer(input.readLine());
ArrayList<Integer> al = new ArrayList<>();
while (st.hasMoreTokens()){
al.add(Integer.parseInt(st.nextToken()));
}
int[] kk = new int[al.size()];
for (int j=0;j<kk.length;++j){
kk[j] = al.get(j);
}
ns[i] = kk;
}
return ns;
}
} | java |
1324 | A | A. Yet Another Tetris Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given some Tetris field consisting of nn columns. The initial height of the ii-th column of the field is aiai blocks. On top of these columns you can place only figures of size 2×12×1 (i.e. the height of this figure is 22 blocks and the width of this figure is 11 block). Note that you cannot rotate these figures.Your task is to say if you can clear the whole field by placing such figures.More formally, the problem can be described like this:The following process occurs while at least one aiai is greater than 00: You place one figure 2×12×1 (choose some ii from 11 to nn and replace aiai with ai+2ai+2); then, while all aiai are greater than zero, replace each aiai with ai−1ai−1. And your task is to determine if it is possible to clear the whole field (i.e. finish the described process), choosing the places for new figures properly.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1≤n≤1001≤n≤100) — the number of columns in the Tetris field. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), where aiai is the initial height of the ii-th column of the Tetris field.OutputFor each test case, print the answer — "YES" (without quotes) if you can clear the whole Tetris field and "NO" otherwise.ExampleInputCopy4
3
1 1 3
4
1 1 2 1
2
11 11
1
100
OutputCopyYES
NO
YES
YES
NoteThe first test case of the example field is shown below:Gray lines are bounds of the Tetris field. Note that the field has no upper bound.One of the correct answers is to first place the figure in the first column. Then after the second step of the process; the field becomes [2,0,2][2,0,2]. Then place the figure in the second column and after the second step of the process, the field becomes [0,0,0][0,0,0].And the second test case of the example field is shown below:It can be shown that you cannot do anything to end the process.In the third test case of the example, you first place the figure in the second column after the second step of the process, the field becomes [0,2][0,2]. Then place the figure in the first column and after the second step of the process, the field becomes [0,0][0,0].In the fourth test case of the example, place the figure in the first column, then the field becomes [102][102] after the first step of the process, and then the field becomes [0][0] after the second step of the process. | [
"implementation",
"number theory"
] | import java.util.*;
public class YetAnotherTetrisProblem {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int t = in.nextInt();
while(t--!=0){
int n = in.nextInt();
int[] a = new int[n];
int even = 0;
int odd = 0;
for(int i=0;i<n;i++){
a[i] = in.nextInt();
if(a[i]%2==0)
even++;
else
odd++;
}
if(even==0 || odd==0)
System.out.println("YES");
else
System.out.println("NO");
}
}
}
| java |
1312 | C | C. Adding Powerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSuppose you are performing the following algorithm. There is an array v1,v2,…,vnv1,v2,…,vn filled with zeroes at start. The following operation is applied to the array several times — at ii-th step (00-indexed) you can: either choose position pospos (1≤pos≤n1≤pos≤n) and increase vposvpos by kiki; or not choose any position and skip this step. You can choose how the algorithm would behave on each step and when to stop it. The question is: can you make array vv equal to the given array aa (vj=ajvj=aj for each jj) after some step?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases. Next 2T2T lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and kk (1≤n≤301≤n≤30, 2≤k≤1002≤k≤100) — the size of arrays vv and aa and value kk used in the algorithm.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10160≤ai≤1016) — the array you'd like to achieve.OutputFor each test case print YES (case insensitive) if you can achieve the array aa after some step or NO (case insensitive) otherwise.ExampleInputCopy5
4 100
0 0 0 0
1 2
1
3 4
1 4 1
3 2
0 1 3
3 9
0 59049 810
OutputCopyYES
YES
NO
NO
YES
NoteIn the first test case; you can stop the algorithm before the 00-th step, or don't choose any position several times and stop the algorithm.In the second test case, you can add k0k0 to v1v1 and stop the algorithm.In the third test case, you can't make two 11 in the array vv.In the fifth test case, you can skip 9090 and 9191, then add 9292 and 9393 to v3v3, skip 9494 and finally, add 9595 to v2v2. | [
"bitmasks",
"greedy",
"implementation",
"math",
"number theory",
"ternary search"
] | import java.util.*;
import java.io.*;
import java.math.*;
public class Main{
public static void main(String[]args){
long s = System.currentTimeMillis();
new Solver().run();
System.err.println(System.currentTimeMillis()-s+"ms");
}
}
class Solver{
final long mod = (long)1e9+7l;
final boolean DEBUG = true, MULTIPLE_TC = true;
FastReader sc;
PrintWriter out;
long MAX_A = (long)1e16;
int N, count[];
long K, arr[];
void init(){
N = ni();
K = ni();
arr = new long[N + 1];
count = new int[60];
for(int i = 1; i <= N; i++){
arr[i] = nl();
}
}
int findLargestRequiredIndexOfK(){
long powK = 1l;
int indexK = 0;
for( ; powK * K <= MAX_A; indexK += 1, powK *= K);
return indexK;
}
void process(int testNumber){
init();
int indexK = findLargestRequiredIndexOfK();
long powK = (long)Math.pow(K, indexK);
for(int i = 1; i <= N; i++){
long tmp = powK;
for(int j = indexK; j >= 0; j--){
if(arr[i] >= tmp){
arr[i] -= tmp;
if(count[j] != 0){
pn("NO"); return;
}
count[j] += 1;
}
tmp /= K;
}
if(arr[i] != 0){
pn("NO"); return;
}
}
pn("YES");
}
void run(){
sc = new FastReader();
out = new PrintWriter(System.out);
int t = MULTIPLE_TC ? ni() : 1;
for(int test = 1; test <= t; test++){
process(test);
}
out.flush();
}
void trace(Object... o){ if(!DEBUG) return; System.err.println(Arrays.deepToString(o)); };
void pn(Object o){ out.println(o); }
void p(Object o){ out.print(o); }
int ni(){ return Integer.parseInt(sc.next()); }
long nl(){ return Long.parseLong(sc.next()); }
double nd(){ return Double.parseDouble(sc.next()); }
String nln(){ return sc.nextLine(); }
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); }
class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br = new BufferedReader(new InputStreamReader(System.in));
}
String next(){
while (st == null || !st.hasMoreElements()){
try{ st = new StringTokenizer(br.readLine()); } catch (IOException e){ e.printStackTrace(); }
}
return st.nextToken();
}
String nextLine(){
String str = "";
try{ str = br.readLine(); } catch (IOException e) { e.printStackTrace(); }
return str;
}
}
}
class pair implements Comparable<pair> {
int first, second;
public pair(int first, int second){
this.first = first;
this.second = second;
}
@Override
public int compareTo(pair ob){
if(this.first != ob.first)
return this.first - ob.first;
return this.second - ob.second;
}
@Override
public String toString(){
return this.first + " " + this.second;
}
static public pair from(int f, int s){
return new pair(f, s);
}
} | java |
1325 | A | A. EhAb AnD gCdtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive integer xx. Find any such 22 positive integers aa and bb such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x.As a reminder, GCD(a,b)GCD(a,b) is the greatest integer that divides both aa and bb. Similarly, LCM(a,b)LCM(a,b) is the smallest integer such that both aa and bb divide it.It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.InputThe first line contains a single integer tt (1≤t≤100)(1≤t≤100) — the number of testcases.Each testcase consists of one line containing a single integer, xx (2≤x≤109)(2≤x≤109).OutputFor each testcase, output a pair of positive integers aa and bb (1≤a,b≤109)1≤a,b≤109) such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x. It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.ExampleInputCopy2
2
14
OutputCopy1 1
6 4
NoteIn the first testcase of the sample; GCD(1,1)+LCM(1,1)=1+1=2GCD(1,1)+LCM(1,1)=1+1=2.In the second testcase of the sample, GCD(6,4)+LCM(6,4)=2+12=14GCD(6,4)+LCM(6,4)=2+12=14. | [
"constructive algorithms",
"greedy",
"number theory"
] | /*
⣿⣿⣿⣿⣿⣿⡷⣯⢿⣿⣷⣻⢯⣿⡽⣻⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣇⠸⣿⣿⣆⠹⣿⣿⢾⣟⣯⣿⣿⣿⣿⣿⣿⣽⣻⣿⣿⣿⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣻⣽⡿⣿⣎⠙⣿⣞⣷⡌⢻⣟⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣿⣿⣿⣿⣿⣿⡄⠹⣿⣿⡆⠻⣿⣟⣯⡿⣽⡿⣿⣿⣿⣿⣽⡷⣯⣿⣿⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣟⣷⣿⣿⣿⡀⠹⣟⣾⣟⣆⠹⣯⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⢠⡘⣿⣿⡄⠉⢿⣿⣽⡷⣿⣻⣿⣿⣿⣿⡝⣷⣯⢿⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣯⢿⣾⢿⣿⡄⢄⠘⢿⣞⡿⣧⡈⢷⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⢸⣧⠘⣿⣷⠈⣦⠙⢿⣽⣷⣻⣽⣿⣿⣿⣿⣌⢿⣯⢿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣟⣯⣿⢿⣿⡆⢸⡷⡈⢻⡽⣷⡷⡄⠻⣽⣿⣿⡿⣿⣿⣿⣿⣿⣿⣷⣿⣿⣿⣿⣏⢰⣯⢷⠈⣿⡆⢹⢷⡌⠻⡾⢋⣱⣯⣿⣿⣿⣿⡆⢻⡿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⡎⣿⢾⡿⣿⡆⢸⣽⢻⣄⠹⣷⣟⣿⣄⠹⣟⣿⣿⣟⣿⣿⣿⣿⣿⣿⣽⣿⣿⣿⡇⢸⣯⣟⣧⠘⣷⠈⡯⠛⢀⡐⢾⣟⣷⣻⣿⣿⣿⡿⡌⢿⣻⣿⣿
⣿⣿⣿⣿⣿⣿⣧⢸⡿⣟⣿⡇⢸⣯⣟⣮⢧⡈⢿⣞⡿⣦⠘⠏⣹⣿⣽⢿⣿⣿⣿⣿⣯⣿⣿⣿⡇⢸⣿⣿⣾⡆⠹⢀⣠⣾⣟⣷⡈⢿⣞⣯⢿⣿⣿⣿⢷⠘⣯⣿⣿
⣿⣿⣿⣿⣿⣿⣿⡈⣿⢿⣽⡇⠘⠛⠛⠛⠓⠓⠈⠛⠛⠟⠇⢀⢿⣻⣿⣯⢿⣿⣿⣿⣷⢿⣿⣿⠁⣾⣿⣿⣿⣧⡄⠇⣹⣿⣾⣯⣿⡄⠻⣽⣯⢿⣻⣿⣿⡇⢹⣾⣿
⣿⣿⣿⣿⣿⣿⣿⡇⢹⣿⡽⡇⢸⣿⣿⣿⣿⣿⣞⣆⠰⣶⣶⡄⢀⢻⡿⣯⣿⡽⣿⣿⣿⢯⣟⡿⢀⣿⣿⣿⣿⣿⣧⠐⣸⣿⣿⣷⣿⣿⣆⠹⣯⣿⣻⣿⣿⣿⢀⣿⢿
⣿⣿⣿⣿⣿⣿⣿⣿⠘⣯⡿⡇⢸⣿⣿⣿⣿⣿⣿⣿⣧⡈⢿⣳⠘⡄⠻⣿⢾⣽⣟⡿⣿⢯⣿⡇⢸⣿⣿⣿⣿⣿⣿⡀⢾⣿⣿⣿⣿⣿⣿⣆⠹⣾⣷⣻⣿⡿⡇⢸⣿
⣿⣿⣿⣿⣿⣿⣿⣿⡇⢹⣿⠇⢸⣿⣿⣿⣿⣿⣿⣿⣿⣷⣄⠻⡇⢹⣆⠹⣟⣾⣽⣻⣟⣿⣽⠁⣾⣿⣿⣿⣿⣿⣿⣇⣿⣿⠿⠛⠛⠉⠙⠋⢀⠁⢘⣯⣿⣿⣧⠘⣿
⣿⣿⣿⣿⣿⣿⣿⣿⣿⡈⣿⡃⢼⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣦⡙⠌⣿⣆⠘⣿⣞⡿⣞⡿⡞⢠⣿⣿⣿⣿⣿⡿⠛⠉⠁⢀⣀⣠⣤⣤⣶⣶⣶⡆⢻⣽⣞⡿⣷⠈⣿
⣿⣿⣿⣿⣿⣿⣿⣿⡿⠃⠘⠁⠉⠉⠉⠉⠉⠉⠉⠉⠉⠙⠛⠛⢿⣄⢻⣿⣧⠘⢯⣟⡿⣽⠁⣾⣿⣿⣿⣿⣿⡃⢀⢀⠘⠛⠿⢿⣻⣟⣯⣽⣻⣵⡀⢿⣯⣟⣿⢀⣿
⣿⣿⣿⣟⣿⣿⣿⣿⣶⣶⡆⢀⣿⣾⣿⣾⣷⣿⣶⠿⠚⠉⢀⢀⣤⣿⣷⣿⣿⣷⡈⢿⣻⢃⣼⣿⣿⣿⣿⣻⣿⣿⣿⡶⣦⣤⣄⣀⡀⠉⠛⠛⠷⣯⣳⠈⣾⡽⣾⢀⣿
⣿⢿⣿⣿⣻⣿⣿⣿⣿⣿⡿⠐⣿⣿⣿⣿⠿⠋⠁⢀⢀⣤⣾⣿⣿⣿⣿⣿⣿⣿⣿⣌⣥⣾⡿⣿⣿⣷⣿⣿⢿⣷⣿⣿⣟⣾⣽⣳⢯⣟⣶⣦⣤⡾⣟⣦⠘⣿⢾⡁⢺
⣿⣻⣿⣿⡷⣿⣿⣿⣿⣿⡗⣦⠸⡿⠋⠁⢀⢀⣠⣴⢿⣿⣽⣻⢽⣾⣟⣷⣿⣟⣿⣿⣿⣳⠿⣵⣧⣼⣿⣿⣿⣿⣿⣾⣿⣿⣿⣿⣿⣽⣳⣯⣿⣿⣿⣽⢀⢷⣻⠄⠘
⣿⢷⣻⣿⣿⣷⣻⣿⣿⣿⡷⠛⣁⢀⣀⣤⣶⣿⣛⡿⣿⣮⣽⡻⣿⣮⣽⣻⢯⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣯⢀⢸⣿⢀⡆
⠸⣟⣯⣿⣿⣷⢿⣽⣿⣿⣷⣿⣷⣆⠹⣿⣶⣯⠿⣿⣶⣟⣻⢿⣷⣽⣻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢀⣯⣟⢀⡇
⣇⠹⣟⣾⣻⣿⣿⢾⡽⣿⣿⣿⣿⣿⣆⢹⣶⣿⣻⣷⣯⣟⣿⣿⣽⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⢀⡿⡇⢸⡇
⣿⣆⠹⣷⡻⣽⣿⣯⢿⣽⣻⣿⣿⣿⣿⣆⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠛⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠇⢸⣿⠇⣼⡇
⡙⠾⣆⠹⣿⣦⠛⣿⢯⣷⢿⡽⣿⣿⣿⣿⣆⠻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠃⠎⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠏⢀⣿⣾⣣⡿⡇
⣿⣷⡌⢦⠙⣿⣿⣌⠻⣽⢯⣿⣽⣻⣿⣿⣿⣧⠩⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡏⢰⢣⠘⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠃⢀⢀⢿⣞⣷⢿⡇
⣿⣽⣆⠹⣧⠘⣿⣿⡷⣌⠙⢷⣯⡷⣟⣿⣿⣿⣷⡀⡹⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣈⠃⣸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⢀⣴⡧⢀⠸⣿⡽⣿⢀
⢻⣽⣿⡄⢻⣷⡈⢿⣿⣿⢧⢀⠙⢿⣻⡾⣽⣻⣿⣿⣄⠌⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠛⢁⣰⣾⣟⡿⢀⡄⢿⣟⣿⢀
⡄⢿⣿⣷⢀⠹⣟⣆⠻⣿⣿⣆⢀⣀⠉⠻⣿⡽⣯⣿⣿⣷⣈⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠋⢀⣠⠘⣯⣷⣿⡟⢀⢆⠸⣿⡟⢸
⣷⡈⢿⣿⣇⢱⡘⢿⣷⣬⣙⠿⣧⠘⣆⢀⠈⠻⣷⣟⣾⢿⣿⣆⠹⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠋⣠⡞⢡⣿⢀⣿⣿⣿⠇⡄⢸⡄⢻⡇⣼
⣿⣷⡈⢿⣿⡆⢣⡀⠙⢾⣟⣿⣿⣷⡈⠂⠘⣦⡈⠿⣯⣿⢾⣿⣆⠙⠻⠿⠿⠿⠿⡿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠿⠛⢋⣠⣾⡟⢠⣿⣿⢀⣿⣿⡟⢠⣿⢈⣧⠘⢠⣿
⣿⣿⣿⣄⠻⣿⡄⢳⡄⢆⡙⠾⣽⣿⣿⣆⡀⢹⡷⣄⠙⢿⣿⡾⣿⣆⢀⡀⢀⢀⢀⢀⢀⢀⢀⢀⢀⢀⢀⢀⣀⣠⣴⡿⣯⠏⣠⣿⣿⡏⢸⣿⡿⢁⣿⣿⢀⣿⠆⢸⣿
⣿⣿⣿⣿⣦⡙⣿⣆⢻⡌⢿⣶⢤⣉⣙⣿⣷⡀⠙⠽⠷⠄⠹⣿⣟⣿⣆⢙⣋⣤⣤⣤⣄⣀⢀⢀⢀⢀⣾⣿⣟⡷⣯⡿⢃⣼⣿⣿⣿⠇⣼⡟⣡⣿⣿⣿⢀⡿⢠⠈⣿
⣿⣿⣿⣿⣿⣷⣮⣿⣿⣿⡌⠁⢤⣤⣤⣤⣬⣭⣴⣶⣶⣶⣆⠈⢻⣿⣿⣆⢻⣿⣿⣿⣿⣿⣿⣷⣶⣤⣌⣉⡘⠛⠻⠶⣿⣿⣿⣿⡟⣰⣫⣴⣿⣿⣿⣿⠄⣷⣿⣿⣿
*/
import java.util.*;
public class Ex3 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int q = in.nextInt();
for (int t = 0; t < q; t++) {
int x = in.nextInt();
if(x == 2){
System.out.println(1+" "+1);
}else if(x % 2 == 1){
System.out.println((x-1)+" "+(1));
}else{
System.out.println((x-2)+" "+(2));
}
}
}
public class ListNode<E> {
private E value;
private Ex3.ListNode next;
public ListNode(E newVal, Ex3.ListNode<E> newNext) {
this.value = newVal;
this.next = newNext;
}
public E getValue() {
return this.value;
}
public Ex3.ListNode<E> getNext() {
return this.next;
}
public void setValue(E newValue) {
this.value = newValue;
}
public void setNext(Ex3.ListNode<E> newNext) {
this.next = newNext;
}
}
}
| java |
1303 | E | E. Erase Subsequencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. You can build new string pp from ss using the following operation no more than two times: choose any subsequence si1,si2,…,siksi1,si2,…,sik where 1≤i1<i2<⋯<ik≤|s|1≤i1<i2<⋯<ik≤|s|; erase the chosen subsequence from ss (ss can become empty); concatenate chosen subsequence to the right of the string pp (in other words, p=p+si1si2…sikp=p+si1si2…sik). Of course, initially the string pp is empty. For example, let s=ababcds=ababcd. At first, let's choose subsequence s1s4s5=abcs1s4s5=abc — we will get s=bads=bad and p=abcp=abc. At second, let's choose s1s2=bas1s2=ba — we will get s=ds=d and p=abcbap=abcba. So we can build abcbaabcba from ababcdababcd.Can you build a given string tt using the algorithm above?InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain test cases — two per test case. The first line contains string ss consisting of lowercase Latin letters (1≤|s|≤4001≤|s|≤400) — the initial string.The second line contains string tt consisting of lowercase Latin letters (1≤|t|≤|s|1≤|t|≤|s|) — the string you'd like to build.It's guaranteed that the total length of strings ss doesn't exceed 400400.OutputPrint TT answers — one per test case. Print YES (case insensitive) if it's possible to build tt and NO (case insensitive) otherwise.ExampleInputCopy4
ababcd
abcba
a
b
defi
fed
xyz
x
OutputCopyYES
NO
NO
YES
| [
"dp",
"strings"
] | import java.io.*;
import java.util.*;
// THIS COMMENT IS FOR SPEED
public class E
{
short[][][] dp;
int n, m;
char[] s, t;
short max(short a, short b)
{
return a > b ? a : b;
}
short go(int i, int j, int k)
{
if (i == n)
return (short)(k == m ? j : -1);
if (j == m && k == m)
return (short)j;
if (dp[i][j][k] != -2)
return dp[i][j][k];
short val = go(i+1, j, k);
if (j != m && s[i] == t[j])
val = max(val, go(i+1, j+1, k));
if (k != m && s[i] == t[k])
val = max(val, go(i+1, j, k+1));
return dp[i][j][k] = val;
}
void solve(BufferedReader in, PrintWriter out) throws Exception
{
String a = in.readLine();
String b = in.readLine();
n = a.length();
m = b.length();
s = a.toCharArray();
t = b.toCharArray();
dp = new short[n][m+1][m+1];
for (int i = 0; i < n; i++)
for (int j = 0; j <= m; j++)
Arrays.fill(dp[i][j], (short)(-2));
for (int i = n-1; i >= 0; i--)
for (int j = m; j >= 0; j--)
for (int k = m; k >= 0; k--)
go(i, j, k);
for (int k = 0; k < m; k++)
if (go(0, 0, k) >= k)
{
out.println("YES");
return;
}
out.println("NO");
}
public static void main(String[] args) throws Exception
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int t = Integer.parseInt(in.readLine());
for (int i = 0; i < t; i++)
new E().solve(in, out);
out.close();
}
}
| java |
1296 | F | F. Berland Beautytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn railway stations in Berland. They are connected to each other by n−1n−1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree.You have a map of that network, so for each railway section you know which stations it connects.Each of the n−1n−1 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 11 to 106106 inclusive.You asked mm passengers some questions: the jj-th one told you three values: his departure station ajaj; his arrival station bjbj; minimum scenery beauty along the path from ajaj to bjbj (the train is moving along the shortest path from ajaj to bjbj). You are planning to update the map and set some value fifi on each railway section — the scenery beauty. The passengers' answers should be consistent with these values.Print any valid set of values f1,f2,…,fn−1f1,f2,…,fn−1, which the passengers' answer is consistent with or report that it doesn't exist.InputThe first line contains a single integer nn (2≤n≤50002≤n≤5000) — the number of railway stations in Berland.The next n−1n−1 lines contain descriptions of the railway sections: the ii-th section description is two integers xixi and yiyi (1≤xi,yi≤n,xi≠yi1≤xi,yi≤n,xi≠yi), where xixi and yiyi are the indices of the stations which are connected by the ii-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway.The next line contains a single integer mm (1≤m≤50001≤m≤5000) — the number of passengers which were asked questions. Then mm lines follow, the jj-th line contains three integers ajaj, bjbj and gjgj (1≤aj,bj≤n1≤aj,bj≤n; aj≠bjaj≠bj; 1≤gj≤1061≤gj≤106) — the departure station, the arrival station and the minimum scenery beauty along his path.OutputIf there is no answer then print a single integer -1.Otherwise, print n−1n−1 integers f1,f2,…,fn−1f1,f2,…,fn−1 (1≤fi≤1061≤fi≤106), where fifi is some valid scenery beauty along the ii-th railway section.If there are multiple answers, you can print any of them.ExamplesInputCopy4
1 2
3 2
3 4
2
1 2 5
1 3 3
OutputCopy5 3 5
InputCopy6
1 2
1 6
3 1
1 5
4 1
4
6 1 3
3 4 1
6 5 2
1 2 5
OutputCopy5 3 1 2 1
InputCopy6
1 2
1 6
3 1
1 5
4 1
4
6 1 1
3 4 3
6 5 3
1 2 4
OutputCopy-1
| [
"constructive algorithms",
"dfs and similar",
"greedy",
"sortings",
"trees"
] | // package c1296;
//
// Codeforces Round #617 (Div. 3) 2020-02-04 06:35
// F. Berland Beauty
// https://codeforces.com/contest/1296/problem/F
// time limit per test 3 seconds; memory limit per test 256 megabytes
// public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*'
//
// There are n railway stations in Berland. They are connected to each other by n-1 railway
// sections. The railway network is connected, i.e. can be represented as an undirected tree.
//
// You have a map of that network, so for each railway section you know which stations it connects.
//
// Each of the n-1 sections has some integer value of the . However, these values are not marked on
// the map and you don't know them. All these values are from 1 to 10^6 inclusive.
//
// You asked m passengers some questions: the j-th one told you three values:
// * his departure station a_j;
// * his arrival station b_j;
// * minimum scenery beauty along the path from a_j to b_j (the train is moving along the shortest
// path from a_j to b_j).
//
// You are planning to update the map and set some value f_i on each railway section -- the . The
// passengers' answers should be consistent with these values.
//
// Print any valid set of values f_1, f_2, ..., f_{n-1}, which the passengers' answer is consistent
// with or report that it doesn't exist.
//
// Input
//
// The first line contains a single integer n (2 <= n <= 5000) -- the number of railway stations in
// Berland.
//
// The next n-1 lines contain descriptions of the railway sections: the i-th section description is
// two integers x_i and y_i (1 <= x_i, y_i <= n, x_i != y_i), where x_i and y_i are the indices of
// the stations which are connected by the i-th railway section. All the railway sections are
// bidirected. Each station can be reached from any other station by the railway.
//
// The next line contains a single integer m (1 <= m <= 5000) -- the number of passengers which were
// asked questions. Then m lines follow, the j-th line contains three integers a_j, b_j and g_j (1
// <= a_j, b_j <= n; a_j != b_j; 1 <= g_j <= 10^6) -- the departure station, the arrival station and
// the minimum scenery beauty along his path.
//
// Output
//
// If there is no answer then print a single integer -1.
//
// Otherwise, print n-1 integers f_1, f_2, ..., f_{n-1} (1 <= f_i <= 10^6), where f_i is some valid
// scenery beauty along the i-th railway section.
//
// If there are multiple answers, you can print any of them.
//
// Example
/*
input:
4
1 2
3 2
3 4
2
1 2 5
1 3 3
output:
5 3 5
input:
6
1 2
1 6
3 1
1 5
4 1
4
6 1 3
3 4 1
6 5 2
1 2 5
output:
5 3 1 2 1
input:
6
1 2
1 6
3 1
1 5
4 1
4
6 1 1
3 4 3
6 5 3
1 2 4
output:
-1
*/
//
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Random;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeMap;
public class C1296F {
static final int MOD = 998244353;
static final Random RAND = new Random();
static int[] solve(int[][] edges, int[][] paths) {
int n = edges.length + 1;
int m = paths.length;
List<int[]>[] adjs = new ArrayList[n+1];
for (int i = 0; i < n+1; i++) {
adjs[i] = new ArrayList<>();
}
for (int i = 0; i < n-1; i++) {
int u = edges[i][0];
int v = edges[i][1];
adjs[u].add(new int[] {v, i});
adjs[v].add(new int[] {u, i});
}
int[][] parent = new int[n+1][2];
int[] depth = new int[n+1];
int r = 1;
Queue<Integer> q = new LinkedList<>();
q.add(r);
while (!q.isEmpty()) {
int v = q.poll();
for (int[] e : adjs[v]) {
int w = e[0];
if (w == parent[v][0]) {
continue;
}
parent[w][0] = v;
parent[w][1] = e[1];
depth[w] = depth[v] + 1;
q.add(w);
}
}
if (test) System.out.format(" parent: %s\n", Arrays.deepToString(parent));
int maxw = 0;
for (int pid = 0; pid < m; pid++) {
maxw = Math.max(maxw, paths[pid][2]);
}
Arrays.sort(paths, (x,y)->y[2]-x[2]);
int[] ans = new int[n-1];
for (int pid = 0; pid < m; pid++) {
int a = paths[pid][0];
int b = paths[pid][1];
int w = paths[pid][2];
List<Integer> eids = getPathEdgesList(a, b, parent, depth);
if (test) System.out.format(" pid:%d a:%d b:%d w:%d eids:%s\n", pid, a, b, w, eids.toString());
// All the involved edges has minimal weight w
boolean ok = false;
for (int eid : eids) {
if (ans[eid] != 0 && ans[eid] < w) {
return null;
} else if (ans[eid] == w || ans[eid] == 0) {
if (test) System.out.format(" assign %d %d\n", eid, w);
ans[eid] = w;
ok = true;
} else {
}
}
if (!ok) {
// no edge in the path support the w
return null;
}
}
for (int i = 0; i < n-1; i++) {
if (ans[i] == 0) {
ans[i] = maxw;
}
}
return ans;
}
// Time limit exceeded on test 268
// 5000
// 1 2
// 2 3
// 3 4
// ...
// test 264 5000 2261 ms 2262 ms
// test 266 5000 2713 ms 2355 ms
static int[] solveA(int[][] edges, int[][] paths) {
int n = edges.length + 1;
int m = paths.length;
List<int[]>[] adjs = new ArrayList[n+1];
for (int i = 0; i < n+1; i++) {
adjs[i] = new ArrayList<>();
}
for (int i = 0; i < n-1; i++) {
int u = edges[i][0];
int v = edges[i][1];
adjs[u].add(new int[] {v, i});
adjs[v].add(new int[] {u, i});
}
int[][] parent = new int[n+1][2];
int[] depth = new int[n+1];
int r = 1;
Queue<Integer> q = new LinkedList<>();
q.add(r);
while (!q.isEmpty()) {
int v = q.poll();
for (int[] e : adjs[v]) {
int w = e[0];
if (w == parent[v][0]) {
continue;
}
parent[w][0] = v;
parent[w][1] = e[1];
depth[w] = depth[v] + 1;
q.add(w);
}
}
if (test) System.out.format(" parent: %s\n", Arrays.deepToString(parent));
// pida[eid] is the path ids that contains edge eid
Set<Integer>[] pida = new HashSet[n-1];
for (int eid = 0; eid < n-1; eid++) {
// Sort paths for the edge in ascending order of weight (smallest path first)
// *** Note that if we sort, ensure the comparison is NOT 0 for different eid regardless ***
// pida[eid] = new TreeSet<>((x, y)->paths[x][2] - paths[y][2]);
pida[eid] = new HashSet<>();
}
TreeMap<Integer, Set<Integer>> wpids = new TreeMap<>();
int maxw = 0;
for (int pid = 0; pid < m; pid++) {
int a = paths[pid][0];
int b = paths[pid][1];
int w = paths[pid][2];
maxw = Math.max(maxw, w);
List<Integer> eids = getPathEdgesList(a, b, parent, depth);
if (test) System.out.format(" pid:%d a:%d b:%d w:%d eids:%s\n", pid, a, b, w, eids.toString());
for (int eid : eids) {
pida[eid].add(pid);
}
wpids.computeIfAbsent(w, x -> new HashSet<>()).add(pid);
}
for (int eid = 0; eid < n-1; eid++) {
if (!pida[eid].isEmpty()) {
if (test) {
List<Integer> pids = new ArrayList<>(pida[eid]);
System.out.format(" eid:%d pids:%s\n", eid, pids.toString());
}
}
}
for (Map.Entry<Integer, Set<Integer>> e : wpids.entrySet()) {
int w = e.getKey();
Set<Integer> pids = e.getValue();
if (test) System.out.format(" w:%d pids:%s\n", w, pids.toString());
}
boolean[] edone = new boolean[n-1];
boolean[] pdone = new boolean[m];
int[] ans = new int[n-1];
Arrays.fill(ans, maxw);
Set<Integer> eids = new HashSet<>();
for (int eid = 0; eid < n-1; eid++) {
if (edone[eid] || pida[eid].isEmpty()) {
continue;
}
eids.add(eid);
}
for (Map.Entry<Integer, Set<Integer>> e : wpids.entrySet()) {
int w = e.getKey();
Set<Integer> pids = e.getValue();
if (test) System.out.format(" w:%d pids:%s\n", w, pids.toString());
while (!pids.isEmpty()) {
int eid = -1;
for (int v : eids) {
boolean ok = true;
for (int pid : pida[v]) {
myAssert(!pdone[pid]);
if (paths[pid][2] != w) {
ok = false;
break;
}
}
if (ok) {
eid = v;
break;
}
}
if (eid < 0) {
if (test) System.out.format(" no edge for %d found\n", w);
return null;
}
if (test) System.out.format(" found edge %d for %d found\n", eid, w);
Set<Integer> epids = pida[eid];
if (test) System.out.format(" epids %s\n", epids.toString());
ans[eid] = w;
edone[eid] = true;
// remove eid from all the paths that contain it
for (int pid : epids) {
pdone[pid] = true;
}
for (int v : eids) {
if (v != eid) {
pida[v].removeAll(epids);
if (test) System.out.format(" v:%d %s\n", v, pida[v].toString());
}
}
eids.remove(eid);
pids.removeAll(epids);
}
}
return ans;
}
static Set<Integer> getPathEdgesSet(int a, int b, int[][] parent, int[] depth) {
if (depth[a] < depth[b]) {
return getPathEdgesSet(b, a, parent, depth);
}
myAssert(depth[a] >= depth[b]);
// root
// /
// p
// / \
// * b
// /
// a
Set<Integer> edges = new HashSet<>();
int x = a;
for (int i = 0; i < depth[a] - depth[b]; i++) {
edges.add(parent[x][1]);
x = parent[x][0];
}
int y = b;
while (x != y) {
edges.add(parent[x][1]);
x = parent[x][0];
edges.add(parent[y][1]);
y = parent[y][0];
}
return edges;
}
static List<Integer> getPathEdgesList(int a, int b, int[][] parent, int[] depth) {
if (depth[a] < depth[b]) {
return getPathEdgesList(b, a, parent, depth);
}
myAssert(depth[a] >= depth[b]);
// root
// /
// p
// / \
// * b
// /
// a
List<Integer> edges = new ArrayList<>();
int x = a;
for (int i = 0; i < depth[a] - depth[b]; i++) {
edges.add(parent[x][1]);
x = parent[x][0];
}
int y = b;
while (x != y) {
edges.add(parent[x][1]);
x = parent[x][0];
edges.add(parent[y][1]);
y = parent[y][0];
}
return edges;
}
static List<Integer> getPathEdgesListOrdered(int a, int b, int[][] parent, int[] depth) {
if (depth[a] < depth[b]) {
return getPathEdgesListOrdered(b, a, parent, depth);
}
myAssert(depth[a] >= depth[b]);
// root
// /
// p
// / \
// * b
// /
// a
List<Integer> edges = new ArrayList<>();
int x = a;
for (int i = 0; i < depth[a] - depth[b]; i++) {
edges.add(parent[x][1]);
x = parent[x][0];
}
int y = b;
List<Integer> other = new ArrayList<>();
while (x != y) {
edges.add(parent[x][1]);
x = parent[x][0];
other.add(parent[y][1]);
y = parent[y][0];
}
Collections.reverse(other);
edges.addAll(other);
return edges;
}
static String trace(int[][] a) {
return Arrays.deepToString(a).replace(" ", "").replace('[', '{').replace(']', '}');
}
static String trace(int[] a) {
return Arrays.toString(a).replace(" ", "").replace('[', '{').replace(']', '}');
}
static void test(int[] exp, int[][] railways, int[][] paths) {
System.out.format("edges:%s\n", trace(railways));
System.out.format("paths:%s\n", trace(paths));
int[] ans = solve(railways, paths);
boolean ok = true;
if (ans == null) {
ok = exp == null;
System.out.format(" => %s %s\n", trace(ans), ok ? "":"Expected " + trace(exp));
} else if (exp == null) {
System.out.format(" => %s Expected -1\n", trace(ans));
ok = false;
} else {
for (int i = 0; i < ans.length; i++) {
if (ans[i] != exp[i]) {
ok = false;
break;
}
}
System.out.format(" => %s %s\n", trace(ans), ok ? "":"Expected " + trace(exp));
}
myAssert(ok);
}
static boolean test = false;
static void doTest() {
if (!test) {
return;
}
long t0 = System.currentTimeMillis();
test(new int[] {5,3,1,2,5}, new int[][] {{1,2},{1,6},{3,1},{1,5},{4,1}},
new int[][] {{6,1,3},{3,4,1},{6,5,2},{1,2,5},{1,4,5}});
test(new int[] {1}, new int[][] {{2,1}}, new int[][] {{1,2,1},{2,1,1}});
test(null, new int[][] {{1,2},{3,1},{4,2}}, new int[][] {{2,4,1},{4,1,2}});
test(new int[] {5,3,5}, new int[][] {{1,2},{3,2},{3,4}}, new int[][] {{1,2,5},{1,3,3}});
test(new int[] {5,3,1,2,5}, new int[][] {{1,2},{1,6},{3,1},{1,5},{4,1}},
new int[][] {{6,1,3},{3,4,1},{6,5,2},{1,2,5}});
test(new int[] {3, 3}, new int[][] {{2,1},{3,1}}, new int[][] {{3,2,3}});
test(new int[] {2, 4}, new int[][] {{1,2},{1,3}}, new int[][] {{3,2,2},{1,3,4}});
test(null, new int[][] {{1,2},{1,6},{3,1},{1,5},{4,1}},
new int[][] {{6,1,1},{3,4,3},{6,5,3},{1,2,4}});
System.out.format("%d msec\n", System.currentTimeMillis() - t0);
System.exit(0);
}
public static void main(String[] args) {
doTest();
MyScanner in = new MyScanner();
int n = in.nextInt();
int[][] railways = new int[n-1][2];
for (int i = 0; i < n-1; i++) {
railways[i][0] = in.nextInt();
railways[i][1] = in.nextInt();
}
int m = in.nextInt();
int[][] questions = new int[m][3];
for (int i = 0; i < m; i++) {
questions[i][0] = in.nextInt();
questions[i][1] = in.nextInt();
questions[i][2] = in.nextInt();
}
int[] ans = solve(railways, questions);
output(ans);
}
static void output(int[] a) {
if (a == null) {
System.out.println("-1");
return;
}
StringBuilder sb = new StringBuilder();
for (int v : a) {
sb.append(v);
sb.append(' ');
if (sb.length() > 4000) {
System.out.print(sb.toString());
sb.setLength(0);
}
}
System.out.println(sb.toString());
}
static void myAssert(boolean cond) {
if (!cond) {
throw new RuntimeException("Unexpected");
}
}
static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
try {
final String USERDIR = System.getProperty("user.dir");
String cname = MethodHandles.lookup().lookupClass().getCanonicalName().replace(".MyScanner", "");
cname = cname.lastIndexOf('.') > 0 ? cname.substring(cname.lastIndexOf('.') + 1) : cname;
final File fin = new File(USERDIR + "/io/c" + cname.substring(1,5) + "/" + cname + ".in");
br = new BufferedReader(new InputStreamReader(fin.exists()
? new FileInputStream(fin) : System.in));
} catch (Exception e) {
br = new BufferedReader(new InputStreamReader(System.in));
}
}
public String next() {
try {
while (st == null || !st.hasMoreElements()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| java |
1295 | D | D. Same GCDstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers aa and mm. Calculate the number of integers xx such that 0≤x<m0≤x<m and gcd(a,m)=gcd(a+x,m)gcd(a,m)=gcd(a+x,m).Note: gcd(a,b)gcd(a,b) is the greatest common divisor of aa and bb.InputThe first line contains the single integer TT (1≤T≤501≤T≤50) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains two integers aa and mm (1≤a<m≤10101≤a<m≤1010).OutputPrint TT integers — one per test case. For each test case print the number of appropriate xx-s.ExampleInputCopy3
4 9
5 10
42 9999999967
OutputCopy6
1
9999999966
NoteIn the first test case appropriate xx-s are [0,1,3,4,6,7][0,1,3,4,6,7].In the second test case the only appropriate xx is 00. | [
"math",
"number theory"
] | import java.io.*;
import java.util.*;
// #FullSolution
public class new1{
public static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
static FastReader s = new FastReader();
public static void main(String[] args) throws IOException{
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out));
int n1 = 1000000;
int[] seive = new int[n1];
for(int i = 2; i < n1; i++) {
for(int j = i; j < n1; j = j + i) {
if(seive[j] == 0) seive[j] = i;
}
}
int t = s.nextInt();
for(int z = 0; z < t; z++) {
long a = s.nextLong();
long m = s.nextLong();
long gcd = gcd(a, m);
a = a / gcd;
m = m / gcd;
long aa = m; int count = 0;
//System.out.println(a + " " + m);
int n = (int) Math.sqrt(m) + 5;
for(int i = 2; i < n; i++) {
if(seive[i] == i && m % i == 0) {
if(aa % i == 0) {
aa = (aa / i) * (i - 1L);
}
else aa = (aa / (i - 1)) * i;
while(m % i == 0) m = m / i;
}
}
if(m > 1) {
if(aa % m == 0) {
aa = (aa / m) * (m - 1L);
}
else aa = (aa / (m - 1)) * m;
}
System.out.println(aa);
}
output.flush();
}
}
class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}} | java |
1285 | B | B. Just Eat It!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Yasser and Adel are at the shop buying cupcakes. There are nn cupcake types, arranged from 11 to nn on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type ii is an integer aiai. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment [l,r][l,r] (1≤l≤r≤n)(1≤l≤r≤n) that does not include all of cupcakes (he can't choose [l,r]=[1,n][l,r]=[1,n]) and buy exactly one cupcake of each of types l,l+1,…,rl,l+1,…,r.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be [7,4,−1][7,4,−1]. Yasser will buy all of them, the total tastiness will be 7+4−1=107+4−1=10. Adel can choose segments [7],[4],[−1],[7,4][7],[4],[−1],[7,4] or [4,−1][4,−1], their total tastinesses are 7,4,−1,117,4,−1,11 and 33, respectively. Adel can choose segment with tastiness 1111, and as 1010 is not strictly greater than 1111, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains nn (2≤n≤1052≤n≤105).The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−109≤ai≤109−109≤ai≤109), where aiai represents the tastiness of the ii-th type of cupcake.It is guaranteed that the sum of nn over all test cases doesn't exceed 105105.OutputFor each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print "NO".ExampleInputCopy3
4
1 2 3 4
3
7 4 -1
3
5 -5 5
OutputCopyYES
NO
NO
NoteIn the first example; the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example; Adel will choose the segment [1,2][1,2] with total tastiness 1111, which is not less than the total tastiness of all cupcakes, which is 1010.In the third example, Adel can choose the segment [3,3][3,3] with total tastiness of 55. Note that Yasser's cupcakes' total tastiness is also 55, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes. | [
"dp",
"greedy",
"implementation"
] | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class JustEatIt {
public static void main(String[] args) throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
PrintWriter pr=new PrintWriter(System.out);
int t=Integer.parseInt(br.readLine());
while(t!=0){
solve(br,pr);
t--;
}
pr.flush();
pr.close();
}
public static void solve(BufferedReader br,PrintWriter pr) throws IOException{
int n=Integer.parseInt(br.readLine());
long[] preSum=new long[n+1];
String[] temp=br.readLine().split(" ");
for(int i=0;i<n;i++){
int num=Integer.parseInt(temp[i]);
preSum[i+1]=preSum[i]+num;
}
long yasser=preSum[n];
long minLeft=0;
long maxAdel=0;
for(int i=1;i<n;i++){
maxAdel=Math.max(maxAdel,preSum[i]-minLeft);
minLeft=Math.min(minLeft,preSum[i]);
}
for(int i=n-1;i>=1;i--){
maxAdel=Math.max(maxAdel,preSum[n]-preSum[i]);
}
pr.println(yasser>maxAdel?"YES":"NO");
}
}
| java |
1324 | D | D. Pair of Topicstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe next lecture in a high school requires two topics to be discussed. The ii-th topic is interesting by aiai units for the teacher and by bibi units for the students.The pair of topics ii and jj (i<ji<j) is called good if ai+aj>bi+bjai+aj>bi+bj (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of topics.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109), where aiai is the interestingness of the ii-th topic for the teacher.The third line of the input contains nn integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤1091≤bi≤109), where bibi is the interestingness of the ii-th topic for the students.OutputPrint one integer — the number of good pairs of topic.ExamplesInputCopy5
4 8 2 6 2
4 5 4 1 3
OutputCopy7
InputCopy4
1 3 2 4
1 3 2 4
OutputCopy0
| [
"binary search",
"data structures",
"sortings",
"two pointers"
] | import java.io.*;
import java.util.*;
public class Mainn {
static StringBuilder sb = new StringBuilder();
static long M = (long) (1e9 + 7);
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
if (st.hasMoreTokens()) {
str = st.nextToken("\n");
} else {
str = br.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public static void swap(int[] a, long i, long j) {
long temp = a[(int) i];
a[(int) i] = a[(int) j];
a[(int) j] = (int) temp;
}
public static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
public static int lcm(int a, int b) {
return (int) (a * b / gcd(a, b));
}
public static String sortString(String inputString) {
char[] tempArray = inputString.toCharArray();
Arrays.sort(tempArray);
return new String(tempArray);
}
static boolean isSquare(int n) {
int v = (int) Math.sqrt(n);
return v * v == n;
}
static boolean PowerOfTwo(int n) {
if (n == 0) return false;
return (int) (Math.ceil((Math.log(n) / Math.log(2)))) ==
(int) (Math.floor(((Math.log(n) / Math.log(2)))));
}
static int power(long a, long b) {
long res = 1;
while (b > 0) {
if (b % 2 == 1) {
res = (res * a) % M;
}
a = ((a * a) % M);
b = b / 2;
}
return (int) res;
}
public static boolean isPrime(int n) {
for (int i = 2; i * i <= n; i++)
if (n % i == 0) {
return false;
}
return true;
}
static long computeXOR(long n) {
if (n % 4 == 0)
return n;
if (n % 4 == 1)
return 1;
if (n % 4 == 2)
return n + 1;
return 0;
}
static long binaryToInteger(String binary) {
char[] numbers = binary.toCharArray();
long result = 0;
for (int i = numbers.length - 1; i >= 0; i--)
if (numbers[i] == '1')
result += Math.pow(2, (numbers.length - i - 1));
return result;
}
static String reverseString(String str) {
char ch[] = str.toCharArray();
String rev = "";
for (int i = ch.length - 1; i >= 0; i--) {
rev += ch[i];
}
return rev;
}
static int countFreq(int[] arr, int n) {
HashMap<Integer, Integer> map = new HashMap<>();
int x = 0;
for (int i = 0; i < n; i++) {
map.put(arr[i], map.getOrDefault(arr[i], 0) + 1);
}
for (int i = 0; i < n; i++) {
if (map.get(arr[i]) == 1)
x++;
}
return x;
}
static void reverse(int[] arr, int l, int r) {
int d = (r - l + 1) / 2;
for (int i = 0; i < d; i++) {
int t = arr[l + i];
arr[l + i] = arr[r - i];
arr[r - i] = t;
}
}
static void sort(String[] s, int n) {
for (int i = 1; i < n; i++) {
String temp = s[i];
int j = i - 1;
while (j >= 0 && temp.length() < s[j].length()) {
s[j + 1] = s[j];
j--;
}
s[j + 1] = temp;
}
}
static int sqr(int n) {
double x = Math.sqrt(n);
if ((int) x == x)
return (int) x;
else
return (int) (x + 1);
}
static class Pair implements Comparable<Pair> {
int start, end;
public Pair(int x, int y) {
this.start = x;
this.end = y;
}
@Override
public int compareTo(Pair p) {
if (start == p.start) {
return end - p.end;
}
return start - p.start;
}
}
static int set_bits_count(int num) {
int count = 0;
while (num > 0) {
num &= (num - 1);
count++;
}
return count;
}
static double factorial(double n)
{
double f=1;
for(int i=1;i<=n;i++)
{
f=f*i;
}
return f;
}
static boolean palindrome(int arr[], int n) {
boolean flag = true;
for (int i = 0; i <= n / 2 && n != 0; i++) {
if (arr[i] != arr[n - i - 1]) {
flag = false;
break;
}
}
return flag;
}
public static boolean isSorted(int[] a) {
if (a == null || a.length <= 1) {
return true;
}
for (int i = 0; i < a.length - 1; i++) {
if (a[i] > a[i + 1]) {
return false;
}
}
return true;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
FastReader sc = new FastReader();
PrintWriter pw = new PrintWriter(System.out);
int n=sc.nextInt();
int[] a=new int[n];
int[] b=new int[n];
Integer[] c=new Integer[n];
long ans=0;
for (int i=0;i<n;++i) {
a[i]=sc.nextInt();
}
for (int i=0;i<n;++i) {
b[i]=sc.nextInt();
c[i]=a[i]-b[i];
}
Arrays.sort(c);
int l=0,r=n-1;
while(l<r){
if ((c[r]+c[l])>0) {
ans+=r-l;
--r;
}
else{
++l;
}
}
System.out.println(ans);
}
static void solve() throws IOException {
}
}
| java |
13 | B | B. Letter Atime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya learns how to write. The teacher gave pupils the task to write the letter A on the sheet of paper. It is required to check whether Petya really had written the letter A.You are given three segments on the plane. They form the letter A if the following conditions hold: Two segments have common endpoint (lets call these segments first and second); while the third segment connects two points on the different segments. The angle between the first and the second segments is greater than 0 and do not exceed 90 degrees. The third segment divides each of the first two segments in proportion not less than 1 / 4 (i.e. the ratio of the length of the shortest part to the length of the longest part is not less than 1 / 4). InputThe first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases to solve. Each case consists of three lines. Each of these three lines contains four space-separated integers — coordinates of the endpoints of one of the segments. All coordinates do not exceed 108 by absolute value. All segments have positive length.OutputOutput one line for each test case. Print «YES» (without quotes), if the segments form the letter A and «NO» otherwise.ExamplesInputCopy34 4 6 04 1 5 24 0 4 40 0 0 60 6 2 -41 1 0 10 0 0 50 5 2 -11 2 0 1OutputCopyYESNOYES | [
"geometry",
"implementation"
] | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
public class LetterA {
static class Point{
int x,y;
Point(int x, int y){
this.x=x;
this.y=y;
}
}
static class Segment{
Point p1,p2;
Segment(Point p1, Point p2){
this.p1=p1;
this.p2=p2;
}
}
static long cross(long x1, long y1, long x2, long y2) {
return x1*y2-x2*y1;
}
static long length(long x, long y){
return x*x+y*y;
}
static boolean acute(Point l, Point m, Point n){
long area= cross(l.x-n.x,l.y-n.y,m.x-n.x,m.y-n.y);
long a=length(l.x-n.x,l.y-n.y);
long b=length(m.x-n.x,m.y-n.y);
long c=length(m.x-l.x,m.y-l.y);
return area!=0 && c<=a+b;
}
static boolean verticalSegment(Segment a, Segment b){
if(a.p1.x==b.p1.x && a.p1.y==b.p1.y){
return acute(a.p2,b.p2,a.p1);
}
if(a.p2.x==b.p2.x && a.p2.y==b.p2.y){
return acute(a.p1,b.p1,a.p2);
}
if(a.p1.x==b.p2.x && a.p1.y==b.p2.y){
return acute(a.p2,b.p1,a.p1);
}
if(a.p2.x==b.p1.x && a.p2.y==b.p1.y){
return acute(a.p1,b.p2,a.p2);
}
return false;
}
static boolean intersecting(Segment s,Point p){
if(p.x<Math.min(s.p1.x,s.p2.x) || p.x>Math.max(s.p1.x,s.p2.x) ||
p.y<Math.min(s.p1.y,s.p2.y)|| p.y>Math.max(s.p1.y,s.p2.y))
return false;
int x=Math.abs(s.p1.x-s.p2.x);
int y=Math.abs(s.p1.y-s.p2.y);
int xm=Math.min(Math.abs(s.p1.x-p.x),Math.abs(s.p2.x-p.x));
int ym=Math.min(Math.abs(s.p1.y-p.y),Math.abs(s.p2.y-p.y));
return x<=5*xm && y<=5*ym &&
(long)(p.x-s.p2.x)*(s.p1.y-s.p2.y)==(long)(p.y-s.p2.y)*(s.p1.x-s.p2.x);
}
static boolean check(Segment a, Segment b, Segment c){
return verticalSegment(a,b)&& (intersecting(a,c.p1)&&intersecting(b,c.p2)
|| intersecting(b,c.p1)&&intersecting(a,c.p2));
}
public static void main(String[] args) throws IOException {
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
int n= Integer.parseInt(br.readLine());
Segment[][] segments= new Segment[n][3];
for(int i=0;i<n;i++) {
for(int j=0; j<3;j++){
StringTokenizer st= new StringTokenizer(br.readLine());
int x1 = Integer.parseInt(st.nextToken());
int y1 = Integer.parseInt(st.nextToken());
int x2 = Integer.parseInt(st.nextToken());
int y2 = Integer.parseInt(st.nextToken());
segments[i][j]= new Segment(new Point(x1,y1),new Point(x2,y2));
}
System.out.println(check(segments[i][0],segments[i][1],segments[i][2])
||check(segments[i][1],segments[i][2],segments[i][0])
||check(segments[i][2],segments[i][0],segments[i][1])?"YES":"NO");
}
}
}
| java |
1316 | C | C. Primitive Primestime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is Professor R's last class of his teaching career. Every time Professor R taught a class; he gave a special problem for the students to solve. You being his favourite student, put your heart into solving it one last time.You are given two polynomials f(x)=a0+a1x+⋯+an−1xn−1f(x)=a0+a1x+⋯+an−1xn−1 and g(x)=b0+b1x+⋯+bm−1xm−1g(x)=b0+b1x+⋯+bm−1xm−1, with positive integral coefficients. It is guaranteed that the cumulative GCD of the coefficients is equal to 11 for both the given polynomials. In other words, gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1. Let h(x)=f(x)⋅g(x)h(x)=f(x)⋅g(x). Suppose that h(x)=c0+c1x+⋯+cn+m−2xn+m−2h(x)=c0+c1x+⋯+cn+m−2xn+m−2. You are also given a prime number pp. Professor R challenges you to find any tt such that ctct isn't divisible by pp. He guarantees you that under these conditions such tt always exists. If there are several such tt, output any of them.As the input is quite large, please use fast input reading methods.InputThe first line of the input contains three integers, nn, mm and pp (1≤n,m≤106,2≤p≤1091≤n,m≤106,2≤p≤109), — nn and mm are the number of terms in f(x)f(x) and g(x)g(x) respectively (one more than the degrees of the respective polynomials) and pp is the given prime number.It is guaranteed that pp is prime.The second line contains nn integers a0,a1,…,an−1a0,a1,…,an−1 (1≤ai≤1091≤ai≤109) — aiai is the coefficient of xixi in f(x)f(x).The third line contains mm integers b0,b1,…,bm−1b0,b1,…,bm−1 (1≤bi≤1091≤bi≤109) — bibi is the coefficient of xixi in g(x)g(x).OutputPrint a single integer tt (0≤t≤n+m−20≤t≤n+m−2) — the appropriate power of xx in h(x)h(x) whose coefficient isn't divisible by the given prime pp. If there are multiple powers of xx that satisfy the condition, print any.ExamplesInputCopy3 2 2
1 1 2
2 1
OutputCopy1
InputCopy2 2 999999937
2 1
3 1
OutputCopy2NoteIn the first test case; f(x)f(x) is 2x2+x+12x2+x+1 and g(x)g(x) is x+2x+2, their product h(x)h(x) being 2x3+5x2+3x+22x3+5x2+3x+2, so the answer can be 1 or 2 as both 3 and 5 aren't divisible by 2.In the second test case, f(x)f(x) is x+2x+2 and g(x)g(x) is x+3x+3, their product h(x)h(x) being x2+5x+6x2+5x+6, so the answer can be any of the powers as no coefficient is divisible by the given prime. | [
"constructive algorithms",
"math",
"ternary search"
] | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import java.util.StringTokenizer;
public class Solution{
public static void main(String[] args) {
FastScanner fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int tt = 1;
while(tt-->0) {
int n = fs.nextInt(), m = fs.nextInt(), p = fs.nextInt();
int p1 = -1;
int p2 = -1;
for(int i=0;i<n;i++) {
int c = fs.nextInt();
if(c%p!=0 && p1==-1) {
p1 = i;
}
}
for(int i=0;i<m;i++) {
int c = fs.nextInt();
if(c%p!=0 && p2==-1) {
p2 = i;
}
}
out.println(p1+p2);
}
out.close();
}
static final Random random=new Random();
static void ruffleSort(int[] a) {
int n=a.length;//shuffle, then sort
for (int i=0; i<n; i++) {
int oi=random.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static class FastScanner{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
public String next(){
while(!st.hasMoreElements()){
try{
st = new StringTokenizer(br.readLine());
} catch(IOException e){
e.printStackTrace();
}
}
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt(){
return Integer.parseInt(next());
}
public int[] readArray(int n){
int[] a = new int[n];
for(int i=0;i<n;i++)
a[i] = nextInt();
return a;
}
public long nextLong() {
return Long.parseLong(next());
}
public char nextChar() {
return next().toCharArray()[0];
}
}
}
| java |
1303 | B | B. National Projecttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour company was appointed to lay new asphalt on the highway of length nn. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are gg days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next bb days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again gg good days, bb bad days and so on.You can be sure that you start repairing at the start of a good season, in other words, days 1,2,…,g1,2,…,g are good.You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the n=5n=5 then at least 33 units of the highway should have high quality; if n=4n=4 then at least 22 units should have high quality.What is the minimum number of days is needed to finish the repair of the whole highway?InputThe first line contains a single integer TT (1≤T≤1041≤T≤104) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains three integers nn, gg and bb (1≤n,g,b≤1091≤n,g,b≤109) — the length of the highway and the number of good and bad days respectively.OutputPrint TT integers — one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.ExampleInputCopy3
5 1 1
8 10 10
1000000 1 1000000
OutputCopy5
8
499999500000
NoteIn the first test case; you can just lay new asphalt each day; since days 1,3,51,3,5 are good.In the second test case, you can also lay new asphalt each day, since days 11-88 are good. | [
"math"
] | import java.io.*;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class NationalProject {
static int mod = 1000000007;
public static void main(String[] args) throws IOException {
FastReader reader = new FastReader();
FastWriter writer = new FastWriter();
int numTests = reader.readSingleInt();
for(int t = 0; t<numTests; t++){
int[] ngb = reader.readIntArray(3);
int n = ngb[0], g = ngb[1], b = ngb[2];
if(g >= b || g >= Math.ceil(n/2.0)){
writer.writeSingleInteger(n);
} else {
long target = n/2;
if(n%2 != 0) target++;
long days = (target/g)*(g+b) + (target%g);
if(target%g == 0) {
days -= b;
}
if(days > n){
writer.writeSingleLong(days);
} else {
writer.writeSingleLong(n);
}
}
}
}
public static void mergeSort(int[] a, int n) {
if (n < 2) {
return;
}
int mid = n / 2;
int[] l = new int[mid];
int[] r = new int[n - mid];
for (int i = 0; i < mid; i++) {
l[i] = a[i];
}
for (int i = mid; i < n; i++) {
r[i - mid] = a[i];
}
mergeSort(l, mid);
mergeSort(r, n - mid);
merge(a, l, r, mid, n - mid);
}
public static void merge(int[] a, int[] l, int[] r, int left, int right) {
int i = 0, j = 0, k = 0;
while (i < left && j < right) {
if (l[i] <= r[j]) {
a[k++] = l[i++];
}
else {
a[k++] = r[j++];
}
}
while (i < left) {
a[k++] = l[i++];
}
while (j < right) {
a[k++] = r[j++];
}
}
public static class FastReader {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tokenizer;
public int readSingleInt() throws IOException {
return Integer.parseInt(reader.readLine());
}
public int[] readIntArray(int numInts) throws IOException {
int[] nums = new int[numInts];
tokenizer = new StringTokenizer(reader.readLine());
for(int i = 0; i<numInts; i++){
nums[i] = Integer.parseInt(tokenizer.nextToken());
}
return nums;
}
public String readString() throws IOException {
return reader.readLine();
}
}
public static class FastWriter {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
public void writeSingleInteger(int i) throws IOException {
writer.write(Integer.toString(i));
writer.newLine();
writer.flush();
}
public void writeSingleLong(long i) throws IOException {
writer.write(Long.toString(i));
writer.newLine();
writer.flush();
}
public void writeIntArrayWithSpaces(int[] nums) throws IOException {
for(int i = 0; i<nums.length; i++){
writer.write(nums[i] + " ");
}
writer.newLine();
writer.flush();
}
public void writeIntArrayListWithSpaces(ArrayList<Integer> nums) throws IOException {
for(int i = 0; i<nums.size(); i++){
writer.write(nums.get(i) + " ");
}
writer.newLine();
writer.flush();
}
public void writeIntArrayWithoutSpaces(int[] nums) throws IOException {
for(int i = 0; i<nums.length; i++){
writer.write(Integer.toString(nums[i]));
}
writer.newLine();
writer.flush();
}
public void writeString(String s) throws IOException {
writer.write(s);
writer.newLine();
writer.flush();
}
}
}
// 7 2 3 | java |
1324 | C | C. Frog Jumpstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a frog staying to the left of the string s=s1s2…sns=s1s2…sn consisting of nn characters (to be more precise, the frog initially stays at the cell 00). Each character of ss is either 'L' or 'R'. It means that if the frog is staying at the ii-th cell and the ii-th character is 'L', the frog can jump only to the left. If the frog is staying at the ii-th cell and the ii-th character is 'R', the frog can jump only to the right. The frog can jump only to the right from the cell 00.Note that the frog can jump into the same cell twice and can perform as many jumps as it needs.The frog wants to reach the n+1n+1-th cell. The frog chooses some positive integer value dd before the first jump (and cannot change it later) and jumps by no more than dd cells at once. I.e. if the ii-th character is 'L' then the frog can jump to any cell in a range [max(0,i−d);i−1][max(0,i−d);i−1], and if the ii-th character is 'R' then the frog can jump to any cell in a range [i+1;min(n+1;i+d)][i+1;min(n+1;i+d)].The frog doesn't want to jump far, so your task is to find the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it can jump by no more than dd cells at once. It is guaranteed that it is always possible to reach n+1n+1 from 00.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. The ii-th test case is described as a string ss consisting of at least 11 and at most 2⋅1052⋅105 characters 'L' and 'R'.It is guaranteed that the sum of lengths of strings over all test cases does not exceed 2⋅1052⋅105 (∑|s|≤2⋅105∑|s|≤2⋅105).OutputFor each test case, print the answer — the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it jumps by no more than dd at once.ExampleInputCopy6
LRLRRLL
L
LLR
RRRR
LLLLLL
R
OutputCopy3
2
3
1
7
1
NoteThe picture describing the first test case of the example and one of the possible answers:In the second test case of the example; the frog can only jump directly from 00 to n+1n+1.In the third test case of the example, the frog can choose d=3d=3, jump to the cell 33 from the cell 00 and then to the cell 44 from the cell 33.In the fourth test case of the example, the frog can choose d=1d=1 and jump 55 times to the right.In the fifth test case of the example, the frog can only jump directly from 00 to n+1n+1.In the sixth test case of the example, the frog can choose d=1d=1 and jump 22 times to the right. | [
"binary search",
"data structures",
"dfs and similar",
"greedy",
"implementation"
] | import java.util.*;
public class frogJumps {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
int t = sc.nextInt();
sc.nextLine();
while(t > 0 ){
solve();
t--;
}
}
public static void solve() {
char[] arr = sc.nextLine().toCharArray();
long length = 0;
long max = Integer.MIN_VALUE;
for(long i = 0;i < arr.length;i++){
if(arr[(int) i] == 'L') length++;
else length = 0;
max = Math.max(max, length);
}
System.out.println(max+1);
}
} | java |
1296 | F | F. Berland Beautytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn railway stations in Berland. They are connected to each other by n−1n−1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree.You have a map of that network, so for each railway section you know which stations it connects.Each of the n−1n−1 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 11 to 106106 inclusive.You asked mm passengers some questions: the jj-th one told you three values: his departure station ajaj; his arrival station bjbj; minimum scenery beauty along the path from ajaj to bjbj (the train is moving along the shortest path from ajaj to bjbj). You are planning to update the map and set some value fifi on each railway section — the scenery beauty. The passengers' answers should be consistent with these values.Print any valid set of values f1,f2,…,fn−1f1,f2,…,fn−1, which the passengers' answer is consistent with or report that it doesn't exist.InputThe first line contains a single integer nn (2≤n≤50002≤n≤5000) — the number of railway stations in Berland.The next n−1n−1 lines contain descriptions of the railway sections: the ii-th section description is two integers xixi and yiyi (1≤xi,yi≤n,xi≠yi1≤xi,yi≤n,xi≠yi), where xixi and yiyi are the indices of the stations which are connected by the ii-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway.The next line contains a single integer mm (1≤m≤50001≤m≤5000) — the number of passengers which were asked questions. Then mm lines follow, the jj-th line contains three integers ajaj, bjbj and gjgj (1≤aj,bj≤n1≤aj,bj≤n; aj≠bjaj≠bj; 1≤gj≤1061≤gj≤106) — the departure station, the arrival station and the minimum scenery beauty along his path.OutputIf there is no answer then print a single integer -1.Otherwise, print n−1n−1 integers f1,f2,…,fn−1f1,f2,…,fn−1 (1≤fi≤1061≤fi≤106), where fifi is some valid scenery beauty along the ii-th railway section.If there are multiple answers, you can print any of them.ExamplesInputCopy4
1 2
3 2
3 4
2
1 2 5
1 3 3
OutputCopy5 3 5
InputCopy6
1 2
1 6
3 1
1 5
4 1
4
6 1 3
3 4 1
6 5 2
1 2 5
OutputCopy5 3 1 2 1
InputCopy6
1 2
1 6
3 1
1 5
4 1
4
6 1 1
3 4 3
6 5 3
1 2 4
OutputCopy-1
| [
"constructive algorithms",
"dfs and similar",
"greedy",
"sortings",
"trees"
] | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class cf1296f {
public static void main(String[] args) throws IOException {
int n = ri(), id[] = new int[n * n];
List<List<Integer>> g = new ArrayList<>();
for (int i = 0; i < n; ++i) {
g.add(new ArrayList<>());
}
for (int i = 0; i < n - 1; ++i) {
int u = rni() - 1, v = ni() - 1;
c(g, u, v);
id[u * n + v] = id[v * n + u] = i;
}
dep = new int[n];
anc = new int[n][15];
for (int[] row : anc) {
fill(row, -1);
}
binary_lifting_dfs(g, 0, -1);
int weight[] = new int[n - 1];
fill(weight, 1);
int m = ri(), rules[][] = new int[m][3];
for (int i = 0; i < m; ++i) {
int u = rni() - 1, v = ni() - 1, w = ni();
rules[i][0] = u;
rules[i][1] = v;
rules[i][2] = w;
int lca = lca(u, v);
while (u != lca) {
int nxt = anc[u][0];
int ind = id[u * n + nxt];
weight[ind] = max(weight[ind], w);
u = nxt;
}
while (v != lca) {
int nxt = anc[v][0];
int ind = id[v * n + nxt];
weight[ind] = max(weight[ind], w);
v = nxt;
}
}
for (int i = 0; i < m; ++i) {
int u = rules[i][0], v = rules[i][1], w = rules[i][2];
int lca = lca(u, v);
int min_weight = 1000000;
while (u != lca) {
int nxt = anc[u][0];
int ind = id[u * n + nxt];
min_weight = min(min_weight, weight[ind]);
u = nxt;
}
while (v != lca) {
int nxt = anc[v][0];
int ind = id[v * n + nxt];
min_weight = min(min_weight, weight[ind]);
v = nxt;
}
if (min_weight != w) {
prln(-1);
close();
return;
}
}
prln(weight);
close();
}
// initialization: dep[n], anc[n][lg(n)], fill(anc, -1)
static int dep[], anc[][];
static int dist(int a, int b) {
int lca = lca(a, b);
return (dep[a] - dep[lca]) + (dep[b] - dep[lca]);
}
static int lca(int a, int b) {
if (dep[a] < dep[b]) {
int __swap = a;
a = b;
b = __swap;
}
for(int i = anc[a].length - 1; i >= 0; --i) {
if(dep[a] - (1 << i) >= dep[b]) {
a = anc[a][i];
}
}
if(a == b) {
return a;
} else {
for(int i = anc[a].length - 1; i >= 0; --i) {
if(anc[a][i] != anc[b][i]) {
a = anc[a][i];
b = anc[b][i];
}
}
return anc[a][0];
}
}
static void binary_lifting_dfs(List<? extends Collection<Integer>> g, int i, int p) {
if (p == -1) {
dep[i] = 0;
} else {
dep[i] = dep[p] + 1;
}
anc[i][0] = p;
for (int j = 1; j < anc[i].length && anc[i][j - 1] >= 0; ++j) {
anc[i][j] = anc[anc[i][j - 1]][j - 1];
}
for (int n : g.get(i)) {
if (n != p) {
binary_lifting_dfs(g, n, i);
}
}
}
static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out));
static StringTokenizer input;
static Random __rand = new Random();
// references
// IBIG = 1e9 + 7
// IMAX ~= 2e9
// LMAX ~= 9e18
// constants
static final int IBIG = 1000000007;
static final int IMAX = 2147483647;
static final int IMIN = -2147483648;
static final long LMAX = 9223372036854775807L;
static final long LMIN = -9223372036854775808L;
// math util
static int minof(int a, int b, int c) {return min(a, min(b, c));}
static int minof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;}
static long minof(long a, long b, long c) {return min(a, min(b, c));}
static long minof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;}
static int maxof(int a, int b, int c) {return max(a, max(b, c));}
static int maxof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;}
static long maxof(long a, long b, long c) {return max(a, max(b, c));}
static long maxof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;}
static int powi(int a, int b) {if (a == 0) return 0; int ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static long powl(long a, int b) {if (a == 0) return 0; long ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static int fli(double d) {return (int) d;}
static int cei(double d) {return (int) ceil(d);}
static long fll(double d) {return (long) d;}
static long cel(double d) {return (long) ceil(d);}
static int gcf(int a, int b) {return b == 0 ? a : gcf(b, a % b);}
static long gcf(long a, long b) {return b == 0 ? a : gcf(b, a % b);}
static int lcm(int a, int b) {return a * b / gcf(a, b);}
static long lcm(long a, long b) {return a * b / gcf(a, b);}
static int randInt(int min, int max) {return __rand.nextInt(max - min + 1) + min;}
static long mix(long x) {x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31);}
// array util
static void reverse(int[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(long[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(double[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(char[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void shuffle(int[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void shuffle(long[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void shuffle(double[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void rsort(int[] a) {shuffle(a); sort(a);}
static void rsort(long[] a) {shuffle(a); sort(a);}
static void rsort(double[] a) {shuffle(a); sort(a);}
static int[] copy(int[] a) {int[] ans = new int[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static long[] copy(long[] a) {long[] ans = new long[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static double[] copy(double[] a) {double[] ans = new double[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static char[] copy(char[] a) {char[] ans = new char[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
// graph util
static List<List<Integer>> g(int n) {List<List<Integer>> g = new ArrayList<>(); for (int i = 0; i < n; ++i) g.add(new ArrayList<>()); return g;}
static List<Set<Integer>> sg(int n) {List<Set<Integer>> g = new ArrayList<>(); for (int i = 0; i < n; ++i) g.add(new HashSet<>()); return g;}
static void c(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v); g.get(v).add(u);}
static void cto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v);}
static void dc(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v); g.get(v).remove(u);}
static void dcto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v);}
// input
static void r() throws IOException {input = new StringTokenizer(rline());}
static int ri() throws IOException {return Integer.parseInt(rline());}
static long rl() throws IOException {return Long.parseLong(rline());}
static double rd() throws IOException {return Double.parseDouble(rline());}
static int[] ria(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni(); return a;}
static int[] riam1(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni() - 1; return a;}
static long[] rla(int n) throws IOException {long[] a = new long[n]; r(); for (int i = 0; i < n; ++i) a[i] = nl(); return a;}
static double[] rda(int n) throws IOException {double[] a = new double[n]; r(); for (int i = 0; i < n; ++i) a[i] = nd(); return a;}
static char[] rcha() throws IOException {return rline().toCharArray();}
static String rline() throws IOException {return __in.readLine();}
static String n() {return input.nextToken();}
static int rni() throws IOException {r(); return ni();}
static int ni() {return Integer.parseInt(n());}
static long rnl() throws IOException {r(); return nl();}
static long nl() {return Long.parseLong(n());}
static double rnd() throws IOException {r(); return nd();}
static double nd() {return Double.parseDouble(n());}
static List<List<Integer>> rg(int n, int m) throws IOException {List<List<Integer>> g = g(n); for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;}
static void rg(List<List<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);}
static List<List<Integer>> rdg(int n, int m) throws IOException {List<List<Integer>> g = g(n); for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;}
static void rdg(List<List<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);}
static List<Set<Integer>> rsg(int n, int m) throws IOException {List<Set<Integer>> g = sg(n); for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;}
static void rsg(List<Set<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);}
static List<Set<Integer>> rdsg(int n, int m) throws IOException {List<Set<Integer>> g = sg(n); for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;}
static void rdsg(List<Set<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);}
// output
static void pr(int i) {__out.print(i);}
static void prln(int i) {__out.println(i);}
static void pr(long l) {__out.print(l);}
static void prln(long l) {__out.println(l);}
static void pr(double d) {__out.print(d);}
static void prln(double d) {__out.println(d);}
static void pr(char c) {__out.print(c);}
static void prln(char c) {__out.println(c);}
static void pr(char[] s) {__out.print(new String(s));}
static void prln(char[] s) {__out.println(new String(s));}
static void pr(String s) {__out.print(s);}
static void prln(String s) {__out.println(s);}
static void pr(Object o) {__out.print(o);}
static void prln(Object o) {__out.println(o);}
static void prln() {__out.println();}
static void pryes() {prln("yes");}
static void pry() {prln("Yes");}
static void prY() {prln("YES");}
static void prno() {prln("no");}
static void prn() {prln("No");}
static void prN() {prln("NO");}
static void pryesno(boolean b) {prln(b ? "yes" : "no");};
static void pryn(boolean b) {prln(b ? "Yes" : "No");}
static void prYN(boolean b) {prln(b ? "YES" : "NO");}
static void prln(int... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();}
static void prln(long... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();}
static void prln(double... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();}
static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for (int i = 0; i < n; pr(iter.next()), pr(' '), ++i); if (n >= 0) prln(iter.next()); else prln();}
static void h() {prln("hlfd"); flush();}
static void flush() {__out.flush();}
static void close() {__out.close();}} | java |
1141 | F2 | F2. Same Sum Blocks (Hard)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],…,a[n].a[1],a[2],…,a[n]. A block is a sequence of contiguous (consecutive) elements a[l],a[l+1],…,a[r]a[l],a[l+1],…,a[r] (1≤l≤r≤n1≤l≤r≤n). Thus, a block is defined by a pair of indices (l,r)(l,r).Find a set of blocks (l1,r1),(l2,r2),…,(lk,rk)(l1,r1),(l2,r2),…,(lk,rk) such that: They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks (li,ri)(li,ri) and (lj,rj(lj,rj) where i≠ji≠j either ri<ljri<lj or rj<lirj<li. For each block the sum of its elements is the same. Formally, a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]=a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]= ⋯=⋯= a[lk]+a[lk+1]+⋯+a[rk].a[lk]+a[lk+1]+⋯+a[rk]. The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks (l′1,r′1),(l′2,r′2),…,(l′k′,r′k′)(l1′,r1′),(l2′,r2′),…,(lk′′,rk′′) satisfying the above two requirements with k′>kk′>k. The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks.InputThe first line contains integer nn (1≤n≤15001≤n≤1500) — the length of the given array. The second line contains the sequence of elements a[1],a[2],…,a[n]a[1],a[2],…,a[n] (−105≤ai≤105−105≤ai≤105).OutputIn the first line print the integer kk (1≤k≤n1≤k≤n). The following kk lines should contain blocks, one per line. In each line print a pair of indices li,rili,ri (1≤li≤ri≤n1≤li≤ri≤n) — the bounds of the ii-th block. You can print blocks in any order. If there are multiple answers, print any of them.ExamplesInputCopy7
4 1 2 2 1 5 3
OutputCopy3
7 7
2 3
4 5
InputCopy11
-5 -4 -3 -2 -1 0 1 2 3 4 5
OutputCopy2
3 4
1 1
InputCopy4
1 1 1 1
OutputCopy4
4 4
1 1
2 2
3 3
| [
"data structures",
"greedy"
] | // package codeforce.Training1900;
import java.io.PrintWriter;
import java.util.*;
//https://codeforces.com/problemset/problem/1141/F2
public class SameSumBlocks {
// MUST SEE BEFORE SUBMISSION
// check whether int part would overflow or not, especially when it is a * b!!!!
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
// int t = sc.nextInt();
int t = 1;
for (int i = 0; i < t; i++) {
solve(sc, pw);
}
pw.close();
}
static void solve(Scanner in, PrintWriter out){
int n = in.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
Map<Long, List<int[]>> mp = new HashMap<>();
long[] pre = new long[n + 1];
for (int i = 1; i <= n; i++) {
pre[i] = pre[i - 1] + arr[i - 1];
}
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
long sz = pre[j + 1] - pre[i];
if (!mp.containsKey(sz)) mp.put(sz, new ArrayList<>());
mp.get(sz).add(new int[]{i, j});
}
}
int max = 0;
List<int[]> ans = new ArrayList<>();
for(List<int[]> ls : mp.values()){
Collections.sort(ls, (a, b) -> {
if (a[1] == b[1]) return b[0] - a[0];
return a[1] - b[1];
});
List<int[]> tt = new ArrayList<>();
int cnt = 0;
int pr = -1;
for (int i = 0; i < ls.size(); i++) {
int[] get = ls.get(i);
if (get[0] <= pr) continue;
cnt++;
tt.add(get);
pr = get[1];
}
if (max < cnt){
ans = tt;
max = cnt;
}
}
out.println(max);
for(int[] v : ans){
out.println((v[0] + 1) + " " + (v[1] + 1));
}
}
}
| java |
1324 | A | A. Yet Another Tetris Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given some Tetris field consisting of nn columns. The initial height of the ii-th column of the field is aiai blocks. On top of these columns you can place only figures of size 2×12×1 (i.e. the height of this figure is 22 blocks and the width of this figure is 11 block). Note that you cannot rotate these figures.Your task is to say if you can clear the whole field by placing such figures.More formally, the problem can be described like this:The following process occurs while at least one aiai is greater than 00: You place one figure 2×12×1 (choose some ii from 11 to nn and replace aiai with ai+2ai+2); then, while all aiai are greater than zero, replace each aiai with ai−1ai−1. And your task is to determine if it is possible to clear the whole field (i.e. finish the described process), choosing the places for new figures properly.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1≤n≤1001≤n≤100) — the number of columns in the Tetris field. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), where aiai is the initial height of the ii-th column of the Tetris field.OutputFor each test case, print the answer — "YES" (without quotes) if you can clear the whole Tetris field and "NO" otherwise.ExampleInputCopy4
3
1 1 3
4
1 1 2 1
2
11 11
1
100
OutputCopyYES
NO
YES
YES
NoteThe first test case of the example field is shown below:Gray lines are bounds of the Tetris field. Note that the field has no upper bound.One of the correct answers is to first place the figure in the first column. Then after the second step of the process; the field becomes [2,0,2][2,0,2]. Then place the figure in the second column and after the second step of the process, the field becomes [0,0,0][0,0,0].And the second test case of the example field is shown below:It can be shown that you cannot do anything to end the process.In the third test case of the example, you first place the figure in the second column after the second step of the process, the field becomes [0,2][0,2]. Then place the figure in the first column and after the second step of the process, the field becomes [0,0][0,0].In the fourth test case of the example, place the figure in the first column, then the field becomes [102][102] after the first step of the process, and then the field becomes [0][0] after the second step of the process. | [
"implementation",
"number theory"
] | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Random;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.stream.IntStream;
public final class CFPS {
static FastReader fr = new FastReader();
static PrintWriter out = new PrintWriter(System.out);
static final int gigamod = 1000000007;
static final int mod = 998244353;
static int t = 1;
static boolean[] isPrime;
static int[] smallestFactorOf;
static final int UP = 0, LEFT = 1, DOWN = 2, RIGHT = 3;
static int cmp;
@SuppressWarnings({"unused"})
public static void main(String[] args) throws Exception {
t = fr.nextInt();
OUTER:
for (int tc = 0; tc < t; tc++) {
int n = fr.nextInt();
int[] arr = fr.nextIntArray(n);
// we can increase one by 2
// --
// can we clear all?
for (int i = 1; i < n; i++)
if (arr[i] % 2 != arr[0] % 2) {
NO();
continue OUTER;
}
YES();
}
out.close();
}
static boolean isPalindrome(char[] s) {
char[] rev = s.clone();
reverse(rev);
return Arrays.compare(s, rev) == 0;
}
static class Segment implements Comparable<Segment> {
int size;
long val;
int stIdx;
Segment left, right;
Segment(int ss, long vv, int ssii) {
size = ss;
val = vv;
stIdx = ssii;
}
@Override
public int compareTo(Segment that) {
cmp = size - that.size;
if (cmp == 0)
cmp = stIdx - that.stIdx;
if (cmp == 0)
cmp = Long.compare(val, that.val);
return cmp;
}
}
static class Pair implements Comparable<Pair> {
int first, second;
int idx;
Pair() { first = second = 0; }
Pair (int ff, int ss) {first = ff; second = ss;}
Pair (int ff, int ss, int ii) { first = ff; second = ss; idx = ii; }
public int compareTo(Pair that) {
cmp = first - that.first;
if (cmp == 0)
cmp = second - that.second;
return (int) cmp;
}
}
// (range add - segment min) segTree
static int nn;
static int[] arr;
static int[] tree;
static int[] lazy;
static void build(int node, int leftt, int rightt) {
if (leftt == rightt) {
tree[node] = arr[leftt];
return;
}
int mid = (leftt + rightt) >> 1;
build(node << 1, leftt, mid);
build(node << 1 | 1, mid + 1, rightt);
tree[node] = Math.min(tree[node << 1], tree[node << 1 | 1]);
}
static void segAdd(int node, int leftt, int rightt, int segL, int segR, int val) {
if (lazy[node] != 0) {
tree[node] += lazy[node];
if (leftt != rightt) {
lazy[node << 1] += lazy[node];
lazy[node << 1 | 1] += lazy[node];
}
lazy[node] = 0;
}
if (segL > rightt || segR < leftt) return;
if (segL <= leftt && rightt <= segR) {
tree[node] += val;
if (leftt != rightt) {
lazy[node << 1] += val;
lazy[node << 1 | 1] += val;
}
lazy[node] = 0;
return;
}
int mid = (leftt + rightt) >> 1;
segAdd(node << 1, leftt, mid, segL, segR, val);
segAdd(node << 1 | 1, mid + 1, rightt, segL, segR, val);
tree[node] = Math.min(tree[node << 1], tree[node << 1 | 1]);
}
static int minQuery(int node, int leftt, int rightt, int segL, int segR) {
if (lazy[node] != 0) {
tree[node] += lazy[node];
if (leftt != rightt) {
lazy[node << 1] += lazy[node];
lazy[node << 1 | 1] += lazy[node];
}
lazy[node] = 0;
}
if (segL > rightt || segR < leftt) return Integer.MAX_VALUE / 10;
if (segL <= leftt && rightt <= segR)
return tree[node];
int mid = (leftt + rightt) >> 1;
return Math.min(minQuery(node << 1, leftt, mid, segL, segR),
minQuery(node << 1 | 1, mid + 1, rightt, segL, segR));
}
static void compute_automaton(String s, int[][] aut) {
s += '#';
int n = s.length();
int[] pi = prefix_function(s.toCharArray());
for (int i = 0; i < n; i++) {
for (int c = 0; c < 26; c++) {
int j = i;
while (j > 0 && 'A' + c != s.charAt(j))
j = pi[j-1];
if ('A' + c == s.charAt(j))
j++;
aut[i][c] = j;
}
}
}
static void timeDFS(int current, int from, UGraph ug,
int[] time, int[] tIn, int[] tOut) {
tIn[current] = ++time[0];
for (int adj : ug.adj(current))
if (adj != from)
timeDFS(adj, current, ug, time, tIn, tOut);
tOut[current] = ++time[0];
}
static boolean areCollinear(long x1, long y1, long x2, long y2, long x3, long y3) {
// we will check if c3 lies on line through (c1, c2)
long a = x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2);
return a == 0;
}
static int[] treeDiameter(UGraph ug) {
int n = ug.V();
int farthest = -1;
int[] distTo = new int[n];
diamDFS(0, -1, 0, ug, distTo);
int maxDist = -1;
for (int i = 0; i < n; i++)
if (maxDist < distTo[i]) {
maxDist = distTo[i];
farthest = i;
}
distTo = new int[n + 1];
diamDFS(farthest, -1, 0, ug, distTo);
distTo[n] = farthest;
return distTo;
}
static void diamDFS(int current, int from, int dist, UGraph ug, int[] distTo) {
distTo[current] = dist;
for (int adj : ug.adj(current))
if (adj != from)
diamDFS(adj, current, dist + 1, ug, distTo);
}
static class TreeDistFinder {
UGraph ug;
int n;
int[] depthOf;
LCA lca;
TreeDistFinder(UGraph ug) {
this.ug = ug;
n = ug.V();
depthOf = new int[n];
depthCalc(0, -1, ug, 0, depthOf);
lca = new LCA(ug, 0);
}
TreeDistFinder(UGraph ug, int a) {
this.ug = ug;
n = ug.V();
depthOf = new int[n];
depthCalc(a, -1, ug, 0, depthOf);
lca = new LCA(ug, a);
}
private void depthCalc(int current, int from, UGraph ug, int depth, int[] depthOf) {
depthOf[current] = depth;
for (int adj : ug.adj(current))
if (adj != from)
depthCalc(adj, current, ug, depth + 1, depthOf);
}
public int dist(int a, int b) {
int lc = lca.lca(a, b);
return (depthOf[a] - depthOf[lc] + depthOf[b] - depthOf[lc]);
}
}
public static long[][] GCDSparseTable(long[] a)
{
int n = a.length;
int b = 32-Integer.numberOfLeadingZeros(n);
long[][] ret = new long[b][];
for(int i = 0, l = 1;i < b;i++, l*=2) {
if(i == 0) {
ret[i] = a;
} else {
ret[i] = new long[n-l+1];
for(int j = 0;j < n-l+1;j++) {
ret[i][j] = gcd(ret[i-1][j], ret[i-1][j+l/2]);
}
}
}
return ret;
}
public static long sparseRangeGCDQ(long[][] table, int l, int r)
{
// [a,b)
if(l > r)return 1;
// 1:0, 2:1, 3:1, 4:2, 5:2, 6:2, 7:2, 8:3
int t = 31-Integer.numberOfLeadingZeros(r-l);
return gcd(table[t][l], table[t][r-(1<<t)]);
}
static class Trie {
TrieNode root;
Trie(char[][] strings) {
root = new TrieNode('A', false);
construct(root, strings);
}
public Stack<String> set(TrieNode root) {
Stack<String> set = new Stack<>();
StringBuilder sb = new StringBuilder();
for (TrieNode next : root.next)
collect(sb, next, set);
return set;
}
private void collect(StringBuilder sb, TrieNode node, Stack<String> set) {
if (node == null) return;
sb.append(node.character);
if (node.isTerminal)
set.add(sb.toString());
for (TrieNode next : node.next)
collect(sb, next, set);
if (sb.length() > 0)
sb.setLength(sb.length() - 1);
}
private void construct(TrieNode root, char[][] strings) {
// we have to construct the Trie
for (char[] string : strings) {
if (string.length == 0) continue;
root.next[string[0] - 'a'] = put(root.next[string[0] - 'a'], string, 0);
if (root.next[string[0] - 'a'] != null)
root.isLeaf = false;
}
}
private TrieNode put(TrieNode node, char[] string, int idx) {
boolean isTerminal = (idx == string.length - 1);
if (node == null) node = new TrieNode(string[idx], isTerminal);
node.character = string[idx];
node.isTerminal |= isTerminal;
if (!isTerminal) {
node.isLeaf = false;
node.next[string[idx + 1] - 'a'] = put(node.next[string[idx + 1] - 'a'], string, idx + 1);
}
return node;
}
class TrieNode {
char character;
TrieNode[] next;
boolean isTerminal, isLeaf;
boolean canWin, canLose;
TrieNode(char c, boolean isTerminallll) {
character = c;
isTerminal = isTerminallll;
next = new TrieNode[26];
isLeaf = true;
}
}
}
static class Edge implements Comparable<Edge> {
int from, to;
long weight, ans;
int id;
// int hash;
Edge(int fro, int t, long wt, int i) {
from = fro;
to = t;
id = i;
weight = wt;
// hash = Objects.hash(from, to, weight);
}
/*public int hashCode() {
return hash;
}*/
public int compareTo(Edge that) {
return Long.compare(this.id, that.id);
}
}
public static long[][] minSparseTable(long[] a)
{
int n = a.length;
int b = 32-Integer.numberOfLeadingZeros(n);
long[][] ret = new long[b][];
for(int i = 0, l = 1;i < b;i++, l*=2) {
if(i == 0) {
ret[i] = a;
}else {
ret[i] = new long[n-l+1];
for(int j = 0;j < n-l+1;j++) {
ret[i][j] = Math.min(ret[i-1][j], ret[i-1][j+l/2]);
}
}
}
return ret;
}
public static long sparseRangeMinQ(long[][] table, int l, int r)
{
// [a,b)
if(l >= r)return Integer.MAX_VALUE;
// 1:0, 2:1, 3:1, 4:2, 5:2, 6:2, 7:2, 8:3
int t = 31-Integer.numberOfLeadingZeros(r-l);
return Math.min(table[t][l], table[t][r-(1<<t)]);
}
public static long[][] maxSparseTable(long[] a)
{
int n = a.length;
int b = 32-Integer.numberOfLeadingZeros(n);
long[][] ret = new long[b][];
for(int i = 0, l = 1;i < b;i++, l*=2) {
if(i == 0) {
ret[i] = a;
}else {
ret[i] = new long[n-l+1];
for(int j = 0;j < n-l+1;j++) {
ret[i][j] = Math.max(ret[i-1][j], ret[i-1][j+l/2]);
}
}
}
return ret;
}
public static long sparseRangeMaxQ(long[][] table, int l, int r)
{
// [a,b)
if(l >= r)return Integer.MIN_VALUE;
// 1:0, 2:1, 3:1, 4:2, 5:2, 6:2, 7:2, 8:3
int t = 31-Integer.numberOfLeadingZeros(r-l);
return Math.max(table[t][l], table[t][r-(1<<t)]);
}
static class LCA {
int[] height, first, segtree;
ArrayList<Integer> euler;
boolean[] visited;
int n;
LCA(UGraph ug, int root) {
n = ug.V();
height = new int[n];
first = new int[n];
euler = new ArrayList<>();
visited = new boolean[n];
dfs(ug, root, 0);
int m = euler.size();
segtree = new int[m * 4];
build(1, 0, m - 1);
}
void dfs(UGraph ug, int node, int h) {
visited[node] = true;
height[node] = h;
first[node] = euler.size();
euler.add(node);
for (int adj : ug.adj(node)) {
if (!visited[adj]) {
dfs(ug, adj, h + 1);
euler.add(node);
}
}
}
void build(int node, int b, int e) {
if (b == e) {
segtree[node] = euler.get(b);
} else {
int mid = (b + e) / 2;
build(node << 1, b, mid);
build(node << 1 | 1, mid + 1, e);
int l = segtree[node << 1], r = segtree[node << 1 | 1];
segtree[node] = (height[l] < height[r]) ? l : r;
}
}
int query(int node, int b, int e, int L, int R) {
if (b > R || e < L)
return -1;
if (b >= L && e <= R)
return segtree[node];
int mid = (b + e) >> 1;
int left = query(node << 1, b, mid, L, R);
int right = query(node << 1 | 1, mid + 1, e, L, R);
if (left == -1) return right;
if (right == -1) return left;
return height[left] < height[right] ? left : right;
}
int lca(int u, int v) {
int left = first[u], right = first[v];
if (left > right) {
int temp = left;
left = right;
right = temp;
}
return query(1, 0, euler.size() - 1, left, right);
}
}
static class FenwickTree {
long[] array; // 1-indexed array, In this array We save cumulative information to perform efficient range queries and updates
public FenwickTree(int size) {
array = new long[size + 1];
}
public long rsq(int ind) {
assert ind > 0;
long sum = 0;
while (ind > 0) {
sum += array[ind];
//Extracting the portion up to the first significant one of the binary representation of 'ind' and decrementing ind by that number
ind -= ind & (-ind);
}
return sum;
}
public long rsq(int a, int b) {
assert b >= a && a > 0 && b > 0;
return rsq(b) - rsq(a - 1);
}
public void update(int ind, long value) {
assert ind > 0;
while (ind < array.length) {
array[ind] += value;
//Extracting the portion up to the first significant one of the binary representation of 'ind' and incrementing ind by that number
ind += ind & (-ind);
}
}
public int size() {
return array.length - 1;
}
}
static class Point implements Comparable<Point> {
long x;
long y;
long z;
long id;
// private int hashCode;
Point() {
x = z = y = 0;
// this.hashCode = Objects.hash(x, y, cost);
}
Point(Point p) {
this.x = p.x;
this.y = p.y;
this.z = p.z;
this.id = p.id;
// this.hashCode = Objects.hash(x, y, cost);
}
Point(long x, long y, long z, long id) {
this.x = x;
this.y = y;
this.z = z;
this.id = id;
// this.hashCode = Objects.hash(x, y, id);
}
Point(long a, long b) {
this.x = a;
this.y = b;
this.z = 0;
// this.hashCode = Objects.hash(a, b);
}
Point(long x, long y, long id) {
this.x = x;
this.y = y;
this.id = id;
}
@Override
public int compareTo(Point o) {
if (this.x < o.x)
return -1;
if (this.x > o.x)
return 1;
if (this.y < o.y)
return -1;
if (this.y > o.y)
return 1;
if (this.z < o.z)
return -1;
if (this.z > o.z)
return 1;
return 0;
}
@Override
public boolean equals(Object that) {
return this.compareTo((Point) that) == 0;
}
}
static class BinaryLift {
// FUNCTIONS: k-th ancestor and LCA in log(n)
int[] parentOf;
int maxJmpPow;
int[][] binAncestorOf;
int n;
int[] lvlOf;
// How this works?
// a. For every node, we store the b-ancestor for b in {1, 2, 4, 8, .. log(n)}.
// b. When we need k-ancestor, we represent 'k' in binary and for each set bit, we
// lift level in the tree.
public BinaryLift(UGraph tree) {
n = tree.V();
maxJmpPow = logk(n, 2) + 1;
parentOf = new int[n];
binAncestorOf = new int[n][maxJmpPow];
lvlOf = new int[n];
for (int i = 0; i < n; i++)
Arrays.fill(binAncestorOf[i], -1);
parentConstruct(0, -1, tree, 0);
binConstruct();
}
// TODO: Implement lvlOf[] initialization
public BinaryLift(int[] parentOf) {
this.parentOf = parentOf;
n = parentOf.length;
maxJmpPow = logk(n, 2) + 1;
binAncestorOf = new int[n][maxJmpPow];
lvlOf = new int[n];
for (int i = 0; i < n; i++)
Arrays.fill(binAncestorOf[i], -1);
UGraph tree = new UGraph(n);
for (int i = 1; i < n; i++)
tree.addEdge(i, parentOf[i]);
binConstruct();
parentConstruct(0, -1, tree, 0);
}
private void parentConstruct(int current, int from, UGraph tree, int depth) {
parentOf[current] = from;
lvlOf[current] = depth;
for (int adj : tree.adj(current))
if (adj != from)
parentConstruct(adj, current, tree, depth + 1);
}
private void binConstruct() {
for (int node = 0; node < n; node++)
for (int lvl = 0; lvl < maxJmpPow; lvl++)
binConstruct(node, lvl);
}
private int binConstruct(int node, int lvl) {
if (node < 0)
return -1;
if (lvl == 0)
return binAncestorOf[node][lvl] = parentOf[node];
if (node == 0)
return binAncestorOf[node][lvl] = -1;
if (binAncestorOf[node][lvl] != -1)
return binAncestorOf[node][lvl];
return binAncestorOf[node][lvl] = binConstruct(binConstruct(node, lvl - 1), lvl - 1);
}
// return ancestor which is 'k' levels above this one
public int ancestor(int node, int k) {
if (node < 0)
return -1;
if (node == 0)
if (k == 0) return node;
else return -1;
if (k > (1 << maxJmpPow) - 1)
return -1;
if (k == 0)
return node;
int ancestor = node;
int highestBit = Integer.highestOneBit(k);
while (k > 0 && ancestor != -1) {
ancestor = binAncestorOf[ancestor][logk(highestBit, 2)];
k -= highestBit;
highestBit = Integer.highestOneBit(k);
}
return ancestor;
}
public int lca(int u, int v) {
if (u == v)
return u;
// The invariant will be that 'u' is below 'v' initially.
if (lvlOf[u] < lvlOf[v]) {
int temp = u;
u = v;
v = temp;
}
// Equalizing the levels.
u = ancestor(u, lvlOf[u] - lvlOf[v]);
if (u == v)
return u;
// We will now raise level by largest fitting power of two until possible.
for (int power = maxJmpPow - 1; power > -1; power--)
if (binAncestorOf[u][power] != binAncestorOf[v][power]) {
u = binAncestorOf[u][power];
v = binAncestorOf[v][power];
}
return ancestor(u, 1);
}
}
static class DFSTree {
// NOTE: The thing is made keeping in mind that the whole
// input graph is connected.
UGraph tree;
UGraph backUG;
int hasBridge;
int n;
Edge backEdge;
DFSTree(UGraph ug) {
this.n = ug.V();
tree = new UGraph(n);
hasBridge = -1;
backUG = new UGraph(n);
treeCalc(0, -1, new boolean[n], ug);
}
private void treeCalc(int current, int from, boolean[] marked, UGraph ug) {
if (marked[current]) {
// This is a backEdge.
backUG.addEdge(from, current);
backEdge = new Edge(from, current, 1, 0);
return;
}
if (from != -1)
tree.addEdge(from, current);
marked[current] = true;
for (int adj : ug.adj(current))
if (adj != from)
treeCalc(adj, current, marked, ug);
}
public boolean hasBridge() {
if (hasBridge != -1)
return (hasBridge == 1);
// We have to determine the bridge.
bridgeFinder();
return (hasBridge == 1);
}
int[] levelOf;
int[] dp;
private void bridgeFinder() {
// Finding the level of each node.
levelOf = new int[n];
levelDFS(0, -1, 0);
// Applying DP solution.
// dp[i] -> Highest level reachable from subtree of 'i' using
// some backEdge.
dp = new int[n];
Arrays.fill(dp, Integer.MAX_VALUE / 100);
dpDFS(0, -1);
// Now, we will check each edge and determine whether its a
// bridge.
for (int i = 0; i < n; i++)
for (int adj : tree.adj(i)) {
// (i -> adj) is the edge.
if (dp[adj] > levelOf[i])
hasBridge = 1;
}
if (hasBridge != 1)
hasBridge = 0;
}
private void levelDFS(int current, int from, int lvl) {
levelOf[current] = lvl;
for (int adj : tree.adj(current))
if (adj != from)
levelDFS(adj, current, lvl + 1);
}
private int dpDFS(int current, int from) {
dp[current] = levelOf[current];
for (int back : backUG.adj(current))
dp[current] = Math.min(dp[current], levelOf[back]);
for (int adj : tree.adj(current))
if (adj != from)
dp[current] = Math.min(dp[current], dpDFS(adj, current));
return dp[current];
}
}
static class UnionFind {
// Uses weighted quick-union with path compression.
private int[] parent; // parent[i] = parent of i
private int[] size; // size[i] = number of sites in tree rooted at i
// Note: not necessarily correct if i is not a root node
private int count; // number of components
public UnionFind(int n) {
count = n;
parent = new int[n];
size = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
size[i] = 1;
}
}
// Number of connected components.
public int count() {
return count;
}
// Find the root of p.
public int find(int p) {
while (p != parent[p])
p = parent[p];
return p;
}
public boolean connected(int p, int q) {
return find(p) == find(q);
}
public int numConnectedTo(int node) {
return size[find(node)];
}
// Weighted union.
public void union(int p, int q) {
int rootP = find(p);
int rootQ = find(q);
if (rootP == rootQ) return;
// make smaller root point to larger one
if (size[rootP] < size[rootQ]) {
parent[rootP] = rootQ;
size[rootQ] += size[rootP];
}
else {
parent[rootQ] = rootP;
size[rootP] += size[rootQ];
}
count--;
}
public static int[] connectedComponents(UnionFind uf) {
// We can do this in nlogn.
int n = uf.size.length;
int[] compoColors = new int[n];
for (int i = 0; i < n; i++)
compoColors[i] = uf.find(i);
HashMap<Integer, Integer> oldToNew = new HashMap<>();
int newCtr = 0;
for (int i = 0; i < n; i++) {
int thisOldColor = compoColors[i];
Integer thisNewColor = oldToNew.get(thisOldColor);
if (thisNewColor == null)
thisNewColor = newCtr++;
oldToNew.put(thisOldColor, thisNewColor);
compoColors[i] = thisNewColor;
}
return compoColors;
}
}
static class UGraph {
// Adjacency list.
private HashSet<Integer>[] adj;
private static final String NEWLINE = "\n";
private int E;
@SuppressWarnings("unchecked")
public UGraph(int V) {
adj = (HashSet<Integer>[]) new HashSet[V];
E = 0;
for (int i = 0; i < V; i++)
adj[i] = new HashSet<Integer>();
}
public void addEdge(int from, int to) {
if (adj[from].contains(to)) return;
E++;
adj[from].add(to);
adj[to].add(from);
}
public HashSet<Integer> adj(int from) {
return adj[from];
}
public int degree(int v) {
return adj[v].size();
}
public int V() {
return adj.length;
}
public int E() {
return E;
}
public String toString() {
StringBuilder s = new StringBuilder();
s.append(V() + " vertices, " + E() + " edges " + NEWLINE);
for (int v = 0; v < V(); v++) {
s.append(v + ": ");
for (int w : adj[v]) {
s.append(w + " ");
}
s.append(NEWLINE);
}
return s.toString();
}
public static void dfsMark(int current, boolean[] marked, UGraph g) {
if (marked[current]) return;
marked[current] = true;
Iterable<Integer> adj = g.adj(current);
for (int adjc : adj)
dfsMark(adjc, marked, g);
}
public static void dfsMark(int current, int from, long[] distTo, boolean[] marked, UGraph g, ArrayList<Integer> endPoints) {
if (marked[current]) return;
marked[current] = true;
if (from != -1)
distTo[current] = distTo[from] + 1;
HashSet<Integer> adj = g.adj(current);
int alreadyMarkedCtr = 0;
for (int adjc : adj) {
if (marked[adjc]) alreadyMarkedCtr++;
dfsMark(adjc, current, distTo, marked, g, endPoints);
}
if (alreadyMarkedCtr == adj.size())
endPoints.add(current);
}
public static void bfsOrder(int current, UGraph g) {
}
public static void dfsMark(int current, int[] colorIds, int color, UGraph g) {
if (colorIds[current] != -1) return;
colorIds[current] = color;
Iterable<Integer> adj = g.adj(current);
for (int adjc : adj)
dfsMark(adjc, colorIds, color, g);
}
public static int[] connectedComponents(UGraph g) {
int n = g.V();
int[] componentId = new int[n];
Arrays.fill(componentId, -1);
int colorCtr = 0;
for (int i = 0; i < n; i++) {
if (componentId[i] != -1) continue;
dfsMark(i, componentId, colorCtr, g);
colorCtr++;
}
return componentId;
}
public static boolean hasCycle(UGraph ug) {
int n = ug.V();
boolean[] marked = new boolean[n];
boolean[] hasCycleFirst = new boolean[1];
for (int i = 0; i < n; i++) {
if (marked[i]) continue;
hcDfsMark(i, ug, marked, hasCycleFirst, -1);
}
return hasCycleFirst[0];
}
// Helper for hasCycle.
private static void hcDfsMark(int current, UGraph ug, boolean[] marked, boolean[] hasCycleFirst, int parent) {
if (marked[current]) return;
if (hasCycleFirst[0]) return;
marked[current] = true;
HashSet<Integer> adjc = ug.adj(current);
for (int adj : adjc) {
if (marked[adj] && adj != parent && parent != -1) {
hasCycleFirst[0] = true;
return;
}
hcDfsMark(adj, ug, marked, hasCycleFirst, current);
}
}
}
static class Digraph {
// Adjacency list.
private HashSet<Integer>[] adj;
private static final String NEWLINE = "\n";
private int E;
@SuppressWarnings("unchecked")
public Digraph(int V) {
adj = (HashSet<Integer>[]) new HashSet[V];
E = 0;
for (int i = 0; i < V; i++)
adj[i] = new HashSet<Integer>();
}
public void addEdge(int from, int to) {
if (adj[from].contains(to)) return;
E++;
adj[from].add(to);
}
public HashSet<Integer> adj(int from) {
return adj[from];
}
public int V() {
return adj.length;
}
public int E() {
return E;
}
public Digraph reversed() {
Digraph dg = new Digraph(V());
for (int i = 0; i < V(); i++)
for (int adjVert : adj(i)) dg.addEdge(adjVert, i);
return dg;
}
public String toString() {
StringBuilder s = new StringBuilder();
s.append(V() + " vertices, " + E() + " edges " + NEWLINE);
for (int v = 0; v < V(); v++) {
s.append(v + ": ");
for (int w : adj[v]) {
s.append(w + " ");
}
s.append(NEWLINE);
}
return s.toString();
}
public static int[] KosarajuSharirSCC(Digraph dg) {
int[] id = new int[dg.V()];
Digraph reversed = dg.reversed();
// Gotta perform topological sort on this one to get the stack.
Stack<Integer> revStack = Digraph.topologicalSort(reversed);
// Initializing id and idCtr.
id = new int[dg.V()];
int idCtr = -1;
// Creating a 'marked' array.
boolean[] marked = new boolean[dg.V()];
while (!revStack.isEmpty()) {
int vertex = revStack.pop();
if (!marked[vertex])
sccDFS(dg, vertex, marked, ++idCtr, id);
}
return id;
}
private static void sccDFS(Digraph dg, int source, boolean[] marked, int idCtr, int[] id) {
marked[source] = true;
id[source] = idCtr;
for (Integer adjVertex : dg.adj(source))
if (!marked[adjVertex]) sccDFS(dg, adjVertex, marked, idCtr, id);
}
public static Stack<Integer> topologicalSort(Digraph dg) {
// dg has to be a directed acyclic graph.
// We'll have to run dfs on the digraph and push the deepest nodes on stack first.
// We'll need a Stack<Integer> and a int[] marked.
Stack<Integer> topologicalStack = new Stack<Integer>();
boolean[] marked = new boolean[dg.V()];
// Calling dfs
for (int i = 0; i < dg.V(); i++)
if (!marked[i])
runDfs(dg, topologicalStack, marked, i);
return topologicalStack;
}
static void runDfs(Digraph dg, Stack<Integer> topologicalStack, boolean[] marked, int source) {
marked[source] = true;
for (Integer adjVertex : dg.adj(source))
if (!marked[adjVertex])
runDfs(dg, topologicalStack, marked, adjVertex);
topologicalStack.add(source);
}
}
static class FastReader {
private BufferedReader bfr;
private StringTokenizer st;
public FastReader() {
bfr = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
if (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(bfr.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());
}
char nextChar() {
return next().toCharArray()[0];
}
String nextString() {
return next();
}
int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = nextInt();
return arr;
}
double[] nextDoubleArray(int n) {
double[] arr = new double[n];
for (int i = 0; i < arr.length; i++)
arr[i] = nextDouble();
return arr;
}
long[] nextLongArray(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++)
arr[i] = nextLong();
return arr;
}
int[][] nextIntGrid(int n, int m) {
int[][] grid = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++)
grid[i][j] = fr.nextInt();
}
return grid;
}
}
@SuppressWarnings("serial")
static class CountMap<T> extends TreeMap<T, Integer>{
CountMap() {
}
CountMap(Comparator<T> cmp) {
}
CountMap(T[] arr) {
this.putCM(arr);
}
public Integer putCM(T key) {
return super.put(key, super.getOrDefault(key, 0) + 1);
}
public Integer removeCM(T key) {
int count = super.getOrDefault(key, -1);
if (count == -1) return -1;
if (count == 1)
return super.remove(key);
else
return super.put(key, count - 1);
}
public Integer getCM(T key) {
return super.getOrDefault(key, 0);
}
public void putCM(T[] arr) {
for (T l : arr)
this.putCM(l);
}
}
static long dioGCD(long a, long b, long[] x0, long[] y0) {
if (b == 0) {
x0[0] = 1;
y0[0] = 0;
return a;
}
long[] x1 = new long[1], y1 = new long[1];
long d = dioGCD(b, a % b, x1, y1);
x0[0] = y1[0];
y0[0] = x1[0] - y1[0] * (a / b);
return d;
}
static boolean diophantine(long a, long b, long c, long[] x0, long[] y0, long[] g) {
g[0] = dioGCD(Math.abs(a), Math.abs(b), x0, y0);
if (c % g[0] > 0) {
return false;
}
x0[0] *= c / g[0];
y0[0] *= c / g[0];
if (a < 0) x0[0] = -x0[0];
if (b < 0) y0[0] = -y0[0];
return true;
}
static long[][] prod(long[][] mat1, long[][] mat2) {
int n = mat1.length;
long[][] prod = new long[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
// determining prod[i][j]
// it will be the dot product of mat1[i][] and mat2[][i]
for (int k = 0; k < n; k++)
prod[i][j] += mat1[i][k] * mat2[k][j];
return prod;
}
static long[][] matExpo(long[][] mat, long power) {
int n = mat.length;
long[][] ans = new long[n][n];
if (power == 0)
return null;
if (power == 1)
return mat;
long[][] half = matExpo(mat, power / 2);
ans = prod(half, half);
if (power % 2 == 1) {
ans = prod(ans, mat);
}
return ans;
}
static int KMPNumOcc(char[] text, char[] pat) {
int n = text.length;
int m = pat.length;
char[] patPlusText = new char[n + m + 1];
for (int i = 0; i < m; i++)
patPlusText[i] = pat[i];
patPlusText[m] = '^'; // Seperator
for (int i = 0; i < n; i++)
patPlusText[m + i] = text[i];
int[] fullPi = piCalcKMP(patPlusText);
int answer = 0;
for (int i = 0; i < n + m + 1; i++)
if (fullPi[i] == m)
answer++;
return answer;
}
static int[] piCalcKMP(char[] s) {
int n = s.length;
int[] pi = new int[n];
for (int i = 1; i < n; i++) {
int j = pi[i - 1];
while (j > 0 && s[i] != s[j])
j = pi[j - 1];
if (s[i] == s[j])
j++;
pi[i] = j;
}
return pi;
}
static boolean[] prefMatchesSuff(char[] s) {
int n = s.length;
boolean[] res = new boolean[n + 1];
int[] pi = prefix_function(s);
res[0] = true;
for (int p = n; p != 0; p = pi[p])
res[p] = true;
return res;
}
static int[] prefix_function(char[] s) {
int n = s.length;
int[] pi = new int[n];
for (int i = 1; i < n; i++) {
int j = pi[i-1];
while (j > 0 && s[i] != s[j])
j = pi[j-1];
if (s[i] == s[j])
j++;
pi[i] = j;
}
return pi;
}
static long hash(long key) {
long h = Long.hashCode(key);
h ^= (h >>> 20) ^ (h >>> 12) ^ (h >>> 7) ^ (h >>> 4);
return h & (gigamod-1);
}
static void Yes() {out.println("Yes");}static void YES() {out.println("YES");}static void yes() {out.println("Yes");}static void No() {out.println("No");}static void NO() {out.println("NO");}static void no() {out.println("no");}
static int mapTo1D(int row, int col, int n, int m) {
// Maps elements in a 2D matrix serially to elements in
// a 1D array.
return row * m + col;
}
static int[] mapTo2D(int idx, int n, int m) {
// Inverse of what the one above does.
int[] rnc = new int[2];
rnc[0] = idx / m;
rnc[1] = idx % m;
return rnc;
}
static long mapTo1D(long row, long col, long n, long m) {
// Maps elements in a 2D matrix serially to elements in
// a 1D array.
return row * m + col;
}
static boolean[] primeGenerator(int upto) {
// Sieve of Eratosthenes:
isPrime = new boolean[upto + 1];
smallestFactorOf = new int[upto + 1];
Arrays.fill(smallestFactorOf, 1);
Arrays.fill(isPrime, true);
isPrime[1] = isPrime[0] = false;
for (long i = 2; i < upto + 1; i++)
if (isPrime[(int) i]) {
smallestFactorOf[(int) i] = (int) i;
// Mark all the multiples greater than or equal
// to the square of i to be false.
for (long j = i; j * i < upto + 1; j++) {
if (isPrime[(int) j * (int) i]) {
isPrime[(int) j * (int) i] = false;
smallestFactorOf[(int) j * (int) i] = (int) i;
}
}
}
return isPrime;
}
static HashMap<Integer, Integer> smolNumPrimeFactorization(int num) {
if (smallestFactorOf == null)
primeGenerator(num + 1);
HashMap<Integer, Integer> fnps = new HashMap<>();
while (num != 1) {
fnps.put(smallestFactorOf[num], fnps.getOrDefault(smallestFactorOf[num], 0) + 1);
num /= smallestFactorOf[num];
}
return fnps;
}
static HashMap<Long, Integer> primeFactorization(long num) {
// Returns map of factor and its power in the number.
HashMap<Long, Integer> map = new HashMap<>();
while (num % 2 == 0) {
num /= 2;
Integer pwrCnt = map.get(2L);
map.put(2L, pwrCnt != null ? pwrCnt + 1 : 1);
}
for (long i = 3; i * i <= num; i += 2) {
while (num % i == 0) {
num /= i;
Integer pwrCnt = map.get(i);
map.put(i, pwrCnt != null ? pwrCnt + 1 : 1);
}
}
// If the number is prime, we have to add it to the
// map.
if (num != 1)
map.put(num, 1);
return map;
}
static HashSet<Long> divisors(long num) {
HashSet<Long> divisors = new HashSet<Long>();
divisors.add(1L);
divisors.add(num);
for (long i = 2; i * i <= num; i++) {
if (num % i == 0) {
divisors.add(num/i);
divisors.add(i);
}
}
return divisors;
}
static void coprimeGenerator(int m, int n, ArrayList<Point> coprimes, int limit, int numCoprimes) {
if (m > limit) return;
if (m <= limit && n <= limit)
coprimes.add(new Point(m, n));
if (coprimes.size() > numCoprimes) return;
coprimeGenerator(2 * m - n, m, coprimes, limit, numCoprimes);
coprimeGenerator(2 * m + n, m, coprimes, limit, numCoprimes);
coprimeGenerator(m + 2 * n, n, coprimes, limit, numCoprimes);
}
static long nCr(long n, long r, long[] fac) { long p = gigamod; if (r == 0) return 1; return (fac[(int)n] * modInverse(fac[(int)r], p) % p * modInverse(fac[(int)n - (int)r], p) % p) % p; }
static long modInverse(long n, long p) { return power(n, p - 2, p); }
static long modDiv(long a, long b){return mod(a * power(b, mod - 2, mod), mod);}
static long power(long x, long y, long p) { long res = 1; x = x % p; while (y > 0) { if ((y & 1)==1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; }
static int logk(long n, long k) { return (int)(Math.log(n) / Math.log(k)); }
static long gcd(long a, long b) { if (b == 0) { return a; } else { return gcd(b, a % b); } } static int gcd(int a, int b) { if (b == 0) { return a; } else { return gcd(b, a % b); } } static long gcd(long[] arr) { int n = arr.length; long gcd = arr[0]; for (int i = 1; i < n; i++) { gcd = gcd(gcd, arr[i]); } return gcd; } static int gcd(int[] arr) { int n = arr.length; int gcd = arr[0]; for (int i = 1; i < n; i++) { gcd = gcd(gcd, arr[i]); } return gcd; } static long lcm(long[] arr) { long lcm = arr[0]; int n = arr.length; for (int i = 1; i < n; i++) { lcm = (lcm * arr[i]) / gcd(lcm, arr[i]); } return lcm; } static long lcm(long a, long b) { return (a * b)/gcd(a, b); } static boolean less(int a, int b) { return a < b ? true : false; } static boolean isSorted(int[] a) { for (int i = 1; i < a.length; i++) { if (less(a[i], a[i - 1])) return false; } return true; } static boolean isSorted(long[] a) { for (int i = 1; i < a.length; i++) { if (a[i] < a[i - 1]) return false; } return true; } static void swap(int[] a, int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } static void swap(long[] a, int i, int j) { long temp = a[i]; a[i] = a[j]; a[j] = temp; } static void swap(double[] a, int i, int j) { double temp = a[i]; a[i] = a[j]; a[j] = temp; } static void swap(char[] a, int i, int j) { char temp = a[i]; a[i] = a[j]; a[j] = temp; }
static void sort(int[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void sort(char[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void sort(long[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void sort(double[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void reverseSort(int[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void reverseSort(char[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void reverse(char[] arr) { int n = arr.length; for (int i = 0; i < n / 2; i++) swap(arr, i, n - 1 - i); } static void reverseSort(long[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void reverseSort(double[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); }
static void shuffleArray(long[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { long tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } static void shuffleArray(int[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { int tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } }
static void shuffleArray(double[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { double tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } }
static void shuffleArray(char[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { char tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } }
static boolean isPrime(long n) {if (n<=1)return false;if(n<=3)return true;if(n%2==0||n%3==0)return false;for(long i=5;i*i<=n;i=i+6)if(n%i==0||n%(i+2)==0)return false;return true;}
static String toString(int[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+" ");return sb.toString();}
static String toString(boolean[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+" ");return sb.toString();}
static String toString(long[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+" ");return sb.toString();}
static String toString(char[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+"");return sb.toString();}
static String toString(int[][] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++){for(int j=0;j<dp[i].length;j++){sb.append(dp[i][j]+" ");}sb.append('\n');}return sb.toString();}
static String toString(long[][] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++){for(int j=0;j<dp[i].length;j++) {sb.append(dp[i][j]+" ");}sb.append('\n');}return sb.toString();}
static String toString(double[][] dp){StringBuilder sb=new StringBuilder();for(int i = 0;i<dp.length;i++){for(int j = 0;j<dp[i].length;j++){sb.append(dp[i][j]+" ");}sb.append('\n');}return sb.toString();}
static String toString(char[][] dp){StringBuilder sb = new StringBuilder();for(int i = 0;i<dp.length;i++){for(int j = 0;j<dp[i].length;j++){sb.append(dp[i][j]+"");}sb.append('\n');}return sb.toString();}
static long mod(long a, long m){return(a%m+1000000L*m)%m;}
}
/*
*
* int[] arr = new int[] {1810, 1700, 1710, 2320, 2000, 1785, 1780
, 2130, 2185, 1430, 1460, 1740, 1860, 1100, 1905, 1650};
int n = arr.length;
sort(arr);
int bel1700 = 0, bet1700n1900 = 0, abv1900 = 0;
for (int i = 0; i < n; i++)
if (arr[i] < 1700)
bel1700++;
else if (1700 <= arr[i] && arr[i] < 1900)
bet1700n1900++;
else if (arr[i] >= 1900)
abv1900++;
out.println("COUNT: " + n);
out.println("PERFS: " + toString(arr));
out.println("MEDIAN: " + arr[n / 2]);
out.println("AVERAGE: " + Arrays.stream(arr).average().getAsDouble());
out.println("[0, 1700): " + bel1700 + "/" + n);
out.println("[1700, 1900): " + bet1700n1900 + "/" + n);
out.println("[1900, 2400): " + abv1900 + "/" + n);
*
* */
// NOTES:
// ASCII VALUE OF 'A': 65
// ASCII VALUE OF 'a': 97
// Range of long: 9 * 10^18
// ASCII VALUE OF '0': 48
// Primes upto 'n' can be given by (n / (logn)). | java |
1313 | C2 | C2. Skyscrapers (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is a harder version of the problem. In this version n≤500000n≤500000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1≤ai≤mi1≤ai≤mi). Also there mustn't be integers jj and kk such that j<i<kj<i<k and aj>ai<akaj>ai<ak. Plots jj and kk are not required to be adjacent to ii.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer nn (1≤n≤5000001≤n≤500000) — the number of plots.The second line contains the integers m1,m2,…,mnm1,m2,…,mn (1≤mi≤1091≤mi≤109) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint nn integers aiai — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInputCopy51 2 3 2 1OutputCopy1 2 3 2 1 InputCopy310 6 8OutputCopy10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10,6,6][10,6,6] is optimal. Note that the answer of [6,6,8][6,6,8] also satisfies all restrictions, but is not optimal. | [
"data structures",
"dp",
"greedy"
] | import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.*;
/**
* @author Mubtasim Shahriar
*/
public class SkyScrappers {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader sc = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Solver solver = new Solver();
// int t = sc.nextInt();
int t = 1;
while (t-- != 0) {
solver.solve(sc, out);
}
out.close();
}
static class Solver {
public void solve(InputReader sc, PrintWriter out) {
int n = sc.nextInt();
long[] arr = sc.nextLongArray(n);
int[] prev = getPrev(arr);
rev(arr);
int[] next = getPrev(arr);
rev(arr);
for(int i = 0; i < n; i++) {
next[i] = n-next[i]-1;
}
rev(next);
long[] l = new long[n];
long[] r = new long[n];
long min = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
min = Math.min(min,arr[i]);
if(min==arr[i]) {
l[i] = min*(i+1);
} else {
int prevSmallIdx = prev[i];
l[i] = (prevSmallIdx>=0 ? l[prevSmallIdx] : 0) + arr[i]*(i-prevSmallIdx);
}
}
min = Integer.MAX_VALUE;
for (int i = n-1; i >= 0; i--) {
min = Math.min(min,arr[i]);
if(min==arr[i]) {
r[i] = min*(n-i);
} else {
int nextSmallIdx = next[i];
r[i] = (nextSmallIdx<n ? r[nextSmallIdx] : 0) + arr[i]*(nextSmallIdx-i);
}
}
long max = 0;
for(int i = 0; i < n; i++) {
max = Math.max(max,l[i]+r[i]-arr[i]);
}
// out.println(max);
int at = -1;
for(int i = 0; i < n; i++) if(l[i]+r[i]-arr[i]==max) {
at = i;
break;
}
long[] ans = new long[n];
ans[at] = arr[at];
int left = at;
while(--left>=0) {
ans[left] = Math.min(arr[left],ans[left+1]);
}
int right = at;
while(++right<n) {
ans[right] = Math.min(arr[right],ans[right-1]);
}
for(int i = 0; i < n; i++) {
if(i>0) out.print(" ");
out.print(ans[i]);
}
}
private void rev(int[] arr) {
int l = 0;
int r = arr.length-1;
while(l<r) {
int tmp = arr[l];
arr[l] = arr[r];
arr[r] = tmp;
l++;
r--;
}
}
private void rev(long[] arr) {
int l = 0;
int r = arr.length-1;
while(l<r) {
long tmp = arr[l];
arr[l] = arr[r];
arr[r] = tmp;
l++;
r--;
}
}
private int[] getPrev(long[] arr) {
int n = arr.length;
int[] ret = new int[n];
Stack<int[]> stk = new Stack<>();
stk.add(new int[] { 0, -1});
for (int i = 0; i < n; i++) {
while(stk.peek()[0]>=arr[i]) stk.pop();
ret[i] = stk.peek()[1];
stk.add(new int[] {(int)arr[i],i});
}
return ret;
}
}
static void sort(int[] arr) {
Random rand = new Random();
int n = arr.length;
for (int i = 0; i < n; i++) {
int idx = rand.nextInt(n);
if (idx == i) continue;
arr[i] ^= arr[idx];
arr[idx] ^= arr[i];
arr[i] ^= arr[idx];
}
Arrays.sort(arr);
}
static void sort(long[] arr) {
Random rand = new Random();
int n = arr.length;
for (int i = 0; i < n; i++) {
int idx = rand.nextInt(n);
if (idx == i) continue;
arr[i] ^= arr[idx];
arr[idx] ^= arr[i];
arr[i] ^= arr[idx];
}
Arrays.sort(arr);
}
static void sortDec(int[] arr) {
Random rand = new Random();
int n = arr.length;
for (int i = 0; i < n; i++) {
int idx = rand.nextInt(n);
if (idx == i) continue;
arr[i] ^= arr[idx];
arr[idx] ^= arr[i];
arr[i] ^= arr[idx];
}
Arrays.sort(arr);
int l = 0;
int r = n - 1;
while (l < r) {
arr[l] ^= arr[r];
arr[r] ^= arr[l];
arr[l] ^= arr[r];
l++;
r--;
}
}
static void sortDec(long[] arr) {
Random rand = new Random();
int n = arr.length;
for (int i = 0; i < n; i++) {
int idx = rand.nextInt(n);
if (idx == i) continue;
arr[i] ^= arr[idx];
arr[idx] ^= arr[i];
arr[i] ^= arr[idx];
}
Arrays.sort(arr);
int l = 0;
int r = n - 1;
while (l < r) {
arr[l] ^= arr[r];
arr[r] ^= arr[l];
arr[l] ^= arr[r];
l++;
r--;
}
}
static class InputReader {
private boolean finished = false;
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 int peek() {
if (numChars == -1) {
return -1;
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar];
}
public 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 String nextString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuilder buf = new StringBuilder();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r') {
buf.appendCodePoint(c);
}
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0) {
s = readLine0();
}
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines) {
return readLine();
} else {
return readLine0();
}
}
public BigInteger readBigInteger() {
try {
return new BigInteger(nextString());
} catch (NumberFormatException e) {
throw new InputMismatchException();
}
}
public char nextCharacter() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
return (char) c;
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, nextInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, nextInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public boolean isExhausted() {
int value;
while (isSpaceChar(value = peek()) && value != -1) {
read();
}
return value == -1;
}
public String next() {
return nextString();
}
public SpaceCharFilter getFilter() {
return filter;
}
public void setFilter(SpaceCharFilter filter) {
this.filter = filter;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
public int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; ++i) array[i] = nextInt();
return array;
}
public int[] nextSortedIntArray(int n) {
int array[] = nextIntArray(n);
Arrays.sort(array);
return array;
}
public int[] nextSumIntArray(int n) {
int[] array = new int[n];
array[0] = nextInt();
for (int i = 1; i < n; ++i) array[i] = array[i - 1] + nextInt();
return array;
}
public long[] nextLongArray(int n) {
long[] array = new long[n];
for (int i = 0; i < n; ++i) array[i] = nextLong();
return array;
}
public long[] nextSumLongArray(int n) {
long[] array = new long[n];
array[0] = nextInt();
for (int i = 1; i < n; ++i) array[i] = array[i - 1] + nextInt();
return array;
}
public long[] nextSortedLongArray(int n) {
long array[] = nextLongArray(n);
Arrays.sort(array);
return array;
}
}
}
| java |
1288 | D | D. Minimax Problemtime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given nn arrays a1a1, a2a2, ..., anan; each array consists of exactly mm integers. We denote the yy-th element of the xx-th array as ax,yax,y.You have to choose two arrays aiai and ajaj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j). After that, you will obtain a new array bb consisting of mm integers, such that for every k∈[1,m]k∈[1,m] bk=max(ai,k,aj,k)bk=max(ai,k,aj,k).Your goal is to choose ii and jj so that the value of mink=1mbkmink=1mbk is maximum possible.InputThe first line contains two integers nn and mm (1≤n≤3⋅1051≤n≤3⋅105, 1≤m≤81≤m≤8) — the number of arrays and the number of elements in each array, respectively.Then nn lines follow, the xx-th line contains the array axax represented by mm integers ax,1ax,1, ax,2ax,2, ..., ax,max,m (0≤ax,y≤1090≤ax,y≤109).OutputPrint two integers ii and jj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j) — the indices of the two arrays you have to choose so that the value of mink=1mbkmink=1mbk is maximum possible. If there are multiple answers, print any of them.ExampleInputCopy6 5
5 0 3 1 2
1 8 9 1 3
1 2 3 4 5
9 1 0 3 7
2 3 0 6 3
6 4 1 7 0
OutputCopy1 5
| [
"binary search",
"bitmasks",
"dp"
] | /*
"Everything in the universe is balanced. Every disappointment
you face in life will be balanced by something good for you!
Keep going, never give up."
*/
import java.util.*;
import java.lang.*;
import java.io.*;
public class Solution {
static int MAX = 1000000000;
static int n, m, allSet = 1;
static int[][] arr;
static List<int[]> valid = new ArrayList<>();
public static void main(String[] args) throws java.lang.Exception {
out = new PrintWriter(new BufferedOutputStream(System.out));
sc = new FastReader();
int test = 1;
for (int t = 0; t < test; t++) {
solve();
}
out.close();
}
private static void solve() {
n = sc.nextInt();
m = sc.nextInt();
arr = new int[n + 1][m];
for (int i = 1; i <= n; i++) {
for (int j = 0; j < m; j++) {
arr[i][j] = sc.nextInt();
}
}
for (int i = 2; i <= m; i++) {
allSet = (allSet << 1) | 1;
}
for (int i = 0; i <= allSet; i++) {
for (int j = i; j <= allSet; j++) {
if ((i | j) == allSet) {
valid.add(new int[]{i, j});
}
}
}
int lo = 0, hi = MAX;
int[] res;
while (lo < hi) {
int mid = (lo + hi + 1) / 2;
res = check(mid);
if (res[0] == -1) {
hi = mid - 1;
}else {
lo = mid;
}
}
res = check((lo + hi + 1) / 2);
out.println(res[0] + " " + res[1]);
}
private static int[] check(int mid) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 1; i <= n; i++) {
int state = 0;
for (int j = 0; j < m; j++) {
int isGood = arr[i][j] >= mid ? 1 : 0;
state = (state << 1) | isGood;
}
map.put(state, i);
}
for (int[] pairs : valid) {
int first = map.getOrDefault(pairs[0], 0);
int second = map.getOrDefault(pairs[1], 0);
if (first > 0 && second > 0) {
return new int[]{first, second};
}
}
return new int[]{-1, -1};
}
public static FastReader sc;
public static PrintWriter out;
static class FastReader
{
BufferedReader br;
StringTokenizer str;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (str == null || !str.hasMoreElements())
{
try
{
str = new StringTokenizer(br.readLine());
}
catch (IOException end)
{
end.printStackTrace();
}
}
return str.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException end)
{
end.printStackTrace();
}
return str;
}
}
} | java |
1294 | F | F. Three Paths on a Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an unweighted tree with nn vertices. Recall that a tree is a connected undirected graph without cycles.Your task is to choose three distinct vertices a,b,ca,b,c on this tree such that the number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc is the maximum possible. See the notes section for a better understanding.The simple path is the path that visits each vertex at most once.InputThe first line contains one integer number nn (3≤n≤2⋅1053≤n≤2⋅105) — the number of vertices in the tree. Next n−1n−1 lines describe the edges of the tree in form ai,biai,bi (1≤ai1≤ai, bi≤nbi≤n, ai≠biai≠bi). It is guaranteed that given graph is a tree.OutputIn the first line print one integer resres — the maximum number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc.In the second line print three integers a,b,ca,b,c such that 1≤a,b,c≤n1≤a,b,c≤n and a≠,b≠c,a≠ca≠,b≠c,a≠c.If there are several answers, you can print any.ExampleInputCopy8
1 2
2 3
3 4
4 5
4 6
3 7
3 8
OutputCopy5
1 8 6
NoteThe picture corresponding to the first example (and another one correct answer):If you choose vertices 1,5,61,5,6 then the path between 11 and 55 consists of edges (1,2),(2,3),(3,4),(4,5)(1,2),(2,3),(3,4),(4,5), the path between 11 and 66 consists of edges (1,2),(2,3),(3,4),(4,6)(1,2),(2,3),(3,4),(4,6) and the path between 55 and 66 consists of edges (4,5),(4,6)(4,5),(4,6). The union of these paths is (1,2),(2,3),(3,4),(4,5),(4,6)(1,2),(2,3),(3,4),(4,5),(4,6) so the answer is 55. It can be shown that there is no better answer. | [
"dfs and similar",
"dp",
"greedy",
"trees"
] | import javax.lang.model.type.ArrayType;
import javax.swing.text.Segment;
import javax.xml.stream.events.ProcessingInstruction;
import java.math.BigInteger;
import java.sql.Array;
import java.util.*;
import java.io.*;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.toList;
public class Solution
{
private static class FastIO {
private static class FastReader
{
BufferedReader br;
StringTokenizer st;
FastReader()
{
br = new BufferedReader(new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble() { return Double.parseDouble(next()); }
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
private static PrintWriter out = new PrintWriter(System.out);
private static FastReader in = new FastReader();
public void print(String s) {out.print(s);}
public void println(String s) {out.println(s);}
public void println() {
println("");
}
public void print(int i) {out.print(i);}
public void print(long i) {out.print(i);}
public void print(char i) {out.print(i);}
public void print(double i) {out.print(i);}
public void println(int i) {out.println(i);}
public void println(long i) {out.println(i);}
public void println(char i) {out.println(i);}
public void println(double i) {out.println(i);}
public void printIntArrayWithoutSpaces(int[] a) {
for(int i : a) {
out.print(i);
}
out.println();
}
public void printIntArrayWithSpaces(int[] a) {
for(int i : a) {
out.print(i + " ");
}
out.println();
}
public void printIntArrayNewLine(int[] a) {
for(int i : a) {
out.println(i);
}
}
public int[] getIntArray(int n) {
int[] res = new int[n];
for(int i = 0; i < n; i++) {
res[i] = in.nextInt();
}
return res;
}
public List<Integer> getIntList(int n) {
List<Integer> list = new ArrayList<>();
for(int i = 0; i < n; i++) {
list.add(in.nextInt());
}
return list;
}
public static void printKickstartCase(int i) {
out.print("Case #" + i + ": ");
}
public String next() {return in.next();}
int nextInt() { return in.nextInt(); }
char nextChar() {return in.next().charAt(0);}
long nextLong() { return in.nextLong(); }
double nextDouble() { return in.nextDouble(); }
String nextLine() {return in.nextLine();}
public void close() {
out.flush();
out.close();
}
}
private static final FastIO io = new FastIO();
private static class MathUtil {
public static final int MOD = 1000000007;
public static int gcd(int a, int b) {
if(b == 0) {
return a;
}
return gcd(b, a % b);
}
public static int gcd(int[] a) {
if(a.length == 0) {
return 0;
}
int res = a[0];
for(int i = 1; i < a.length; i++) {
res = gcd(res, a[i]);
}
return res;
}
public static int gcd(List<Integer> a) {
if(a.size() == 0) {
return 0;
}
int res = a.get(0);
for(int i = 1; i < a.size(); i++) {
res = gcd(res, a.get(i));
}
return res;
}
public static int modular_mult(int a, int b, int M) {
long res = (long)a * b;
return (int)(res % M);
}
public static int modular_mult(int a, int b) {
return modular_mult(a, b, MOD);
}
public static int modular_add(int a, int b, int M) {
long res = (long)a + b;
return (int)(res % M);
}
public static int modular_add(int a, int b) {
return modular_add(a, b, MOD);
}
public static int modular_sub(int a, int b, int M) {
long res = ((long)a - b) + M;
return (int)(res % M);
}
public static int modular_sub(int a, int b) {
return modular_sub(a, b, MOD);
}
//public static int modular_div(int a, int b, int M) {}
//public static int modular_div(int a, int b) {return modular_div(a, b, MOD);}
public static int pow(int a, int b, int M) {
int res = 1;
while (b > 0) {
if ((b & 1) == 1) {
res = modular_mult(res, a, M);
}
a = modular_mult(a, a, M);
b = b >> 1;
}
return res;
}
public static int pow(int a, int b) {
return pow(a, b, MOD);
}
/*public static int fact(int i, int M) {
}
public static int fact(int i) {
}
public static void preComputeFact(int i) {
}
public static int mod_mult_inverse(int den, int mod) {
}
public static void C(int n, int r) {
}*/
}
private static class ArrayUtil {
@FunctionalInterface
private static interface NumberPairComparator {
boolean test(int a, int b);
}
public static int[] nextGreaterOrSmallerRight(int[] a, NumberPairComparator npc) {
int n = a.length;
int[] res = new int[n];
Stack<Integer> stack = new Stack<>();
for(int i = 0; i < n; i++) {
int cur = a[i];
while(!stack.isEmpty() && npc.test(a[stack.peek()], cur)) {
res[stack.pop()] = i;
}
stack.push(i);
}
while(!stack.isEmpty()) {
res[stack.pop()] = n;
}
return res;
}
public static int[] nextGreaterOrSmallerLeft(int[] a, NumberPairComparator npc) {
int n = a.length;
int[] res = new int[n];
Stack<Integer> stack = new Stack<>();
for(int i = n - 1; i >= 0; i--) {
int cur = a[i];
while(!stack.isEmpty() && npc.test(a[stack.peek()], cur)) {
res[stack.pop()] = i;
}
stack.push(i);
}
while(!stack.isEmpty()) {
res[stack.pop()] = n;
}
return res;
}
public static Map<Integer, Integer> getFreqMap(int[] a) {
Map<Integer, Integer> map = new HashMap<>();
for(int i : a) {
map.put(i, map.getOrDefault(i, 0) + 1);
}
return map;
}
public static long arraySum(int[] a) {
long sum = 0;
for(int i : a) {
sum += i;
}
return sum;
}
private static int maxIndex(int[] a) {
int max = Integer.MIN_VALUE;
int max_index = -1;
for(int i = 0; i < a.length; i++) {
if(a[i] > max) {
max = a[i];
max_index = i;
}
}
return max_index;
}
}
private static final int M = 1000000007;
private static final String yes = "YES";
private static final String no = "NO";
private static int MAX = M / 100;
private static final int MIN = -MAX;
private static final int UNVISITED = -1;
private static class Tree {
List<List<Integer>> list;
int n;
Tree(int n) {
this.n = n;
list = new ArrayList<>();
for(int i = 0; i < n; i++) {
list.add(new ArrayList<>());
}
}
public void addUndirectedEdge(int a, int b) {
list.get(a).add(b);
list.get(b).add(a);
}
public boolean isLeaf(int i) {
return (i != 0 && getNeighbours(i).size() == 1);
}
public List<Integer> getNeighbours(int i) {
return list.get(i);
}
public void sortAdjList(Comparator<Integer> comp) {
for(List<Integer> sublist : list) {
Collections.sort(sublist, comp);
}
}
public int[] bfs(int source) {
int[] res = new int[n];
ArrayDeque<Integer> q = new ArrayDeque<>();
ArrayDeque<Integer> q_parent = new ArrayDeque<>();
q.add(source);
q_parent.add(-1);
int level = 0;
while(!q.isEmpty()) {
int q_size = q.size();
for(int i = 0; i < q_size; i++) {
int cur = q.poll();
int parent = q_parent.poll();
res[cur] = level;
List<Integer> neighbours = getNeighbours(cur);
for(int neighbour : neighbours) {
if(neighbour == parent) {
continue;
}
q.add(neighbour);
q_parent.add(cur);
}
}
level ++;
}
return res;
}
@FunctionalInterface
private interface DfsAction<T> {
void perform(int parent, int child, List<T> values);
}
private <T> void dfs(int node, int parent, DfsAction<T> preOrderAction, DfsAction<T> postOrderAction, DfsAction<T> rootAction, DfsAction<T> leafAction, DfsAction<T> leaveAction,List<T> values) {
if(node == 0) {
rootAction.perform(parent, node, values);
}
if(isLeaf(node)) {
leafAction.perform(parent, node, values);
}
preOrderAction.perform(parent, node, values);
List<Integer> children = getNeighbours(node);
for(int child : children) {
if(child == parent) {
continue;
}
dfs(child, node, preOrderAction, postOrderAction, leafAction, rootAction, leaveAction, values);
postOrderAction.perform(node, child, values);
}
leaveAction.perform(parent, node, values);
}
public <T> void dfs(int root, DfsAction<T> preOrderAction, DfsAction<T> postOrderAction, DfsAction<T> rootAction, DfsAction<T> leafAction, DfsAction<T> leaveAction, List<T> values) {
dfs(0, -1, preOrderAction, postOrderAction, rootAction, leafAction, leaveAction, values);
}
public <T> void postOrder(int root, DfsAction<T> postOrderAction, DfsAction<T> leafAction, List<T>values) {
this.<T>dfs(root, (p, c, v) -> {}, postOrderAction, (p, c, v) -> {}, leafAction, (p, c, v) -> {}, values);
}
}
private static class Point {
int x;
int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return "x: " + x + " y: " + y;
}
}
private static class SearchNode {
String num;
int mod;
int sum_of_digits;
public SearchNode(String num, int mod, int sum_of_digits) {
this.num = num;
this.mod = mod;
this.sum_of_digits = sum_of_digits;
}
}
private static int binsearch(int x, long left_items, long left_sum, int cost) {
int lo = 0;
int hi = 1000000000;
int res = 0;
while(lo <= hi) {
int d = lo + (hi - lo) / 2;
long balance = x - (left_items * (d - 1)) - (left_sum) - cost - d + 1;
if(balance >= 0) {
res = d;
lo = d + 1;
}
else {
hi = d - 1;
}
}
return res;
}
public static void main(String[] args)
{
//int t = io.nextInt();
int t = 1;
for(int zqt = 0; zqt < t; zqt ++) {
int n = io.nextInt();
Tree tree = new Tree(n);
for(int i = 0; i < n - 1; i++) {
tree.addUndirectedEdge(io.nextInt() - 1, io.nextInt() - 1);
}
int first_end_point = ArrayUtil.maxIndex(tree.bfs(0));
int[] dist_1 = tree.bfs(first_end_point);
int second_end_point = ArrayUtil.maxIndex(dist_1);
int[] dist_2 = tree.bfs(second_end_point);
int third_end_point = first_end_point;
int diameter = dist_1[second_end_point];
int res = diameter;
if(diameter == n - 1) {
if(first_end_point != 0 && second_end_point != 0) {
third_end_point = 0;
}
else if(first_end_point != 1 && second_end_point != 1) {
third_end_point = 1;
}
else {
third_end_point = 2;
}
io.println(res);
io.println((first_end_point + 1) + " " + (second_end_point + 1) + " " + (third_end_point + 1));
continue;
}
for(int i = 0; i < n; i++) {
int d_plus_two_c = dist_1[i] + dist_2[i];
int two_c = d_plus_two_c - diameter;
int c = two_c / 2;
int local_res = diameter + c;
if (local_res >= res) {
res = local_res;
third_end_point = i;
}
}
io.println(res);
io.println((first_end_point + 1) + " " + (second_end_point + 1) + " " + (third_end_point + 1));
}
io.close();
}
} | java |
1288 | C | C. Two Arraystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm. Calculate the number of pairs of arrays (a,b)(a,b) such that: the length of both arrays is equal to mm; each element of each array is an integer between 11 and nn (inclusive); ai≤biai≤bi for any index ii from 11 to mm; array aa is sorted in non-descending order; array bb is sorted in non-ascending order. As the result can be very large, you should print it modulo 109+7109+7.InputThe only line contains two integers nn and mm (1≤n≤10001≤n≤1000, 1≤m≤101≤m≤10).OutputPrint one integer – the number of arrays aa and bb satisfying the conditions described above modulo 109+7109+7.ExamplesInputCopy2 2
OutputCopy5
InputCopy10 1
OutputCopy55
InputCopy723 9
OutputCopy157557417
NoteIn the first test there are 55 suitable arrays: a=[1,1],b=[2,2]a=[1,1],b=[2,2]; a=[1,2],b=[2,2]a=[1,2],b=[2,2]; a=[2,2],b=[2,2]a=[2,2],b=[2,2]; a=[1,1],b=[2,1]a=[1,1],b=[2,1]; a=[1,1],b=[1,1]a=[1,1],b=[1,1]. | [
"combinatorics",
"dp"
] | import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import java.util.*;
import java.io.*;
import java.math.*;
public class C_Two_Arrays {
static long mod = 1000000007;
static OutputStream outputStream = System.out;
static PrintWriter out = new PrintWriter(outputStream);
static FastReader f = new FastReader();
public static void main(String[] args) {
int t = 1;
while(t-- > 0){
solve();
}
out.close();
}
public static void solve() {
int n = f.nextInt();
int m = f.nextInt();
long dp[][] = new long[2*m+1][n+1];
for(long row[]: dp) {
Arrays.fill(row, -1);
}
out.println(internal(0, 1, n, 2*m, dp));
}
public static long internal(int ind, int val, int n, int len, long dp[][]) {
if(ind == len) {
return 1;
}
if(dp[ind][val] != -1) {
return dp[ind][val];
}
long ans = 0;
for(int curr = val; curr <= n; curr++) {
ans = (ans + internal(ind+1, curr, n, len, dp)) % mod;
}
return dp[ind][val] = ans;
}
// Sort an array
public static void sort(int arr[]) {
ArrayList<Integer> al = new ArrayList<>();
for(int i: arr) {
al.add(i);
}
Collections.sort(al);
for(int i = 0; i < arr.length; i++) {
arr[i] = al.get(i);
}
}
// Find all divisors of n
public static void allDivisors(int n) {
for(int i = 1; i*i <= n; i++) {
if(n%i == 0) {
System.out.println(i + " ");
if(i != n/i) {
System.out.println(n/i + " ");
}
}
}
}
// Check if n is prime or not
public static boolean isPrime(int n) {
if(n < 1) return false;
if(n == 2 || n == 3) return true;
if(n % 2 == 0 || n % 3 == 0) return false;
for(int i = 5; i*i <= n; i += 6) {
if(n % i == 0 || n % (i+2) == 0) {
return false;
}
}
return true;
}
// Find gcd of a and b
public static long gcd(long a, long b) {
long dividend = a > b ? a : b;
long divisor = a < b ? a : b;
while(divisor > 0) {
long reminder = dividend % divisor;
dividend = divisor;
divisor = reminder;
}
return dividend;
}
// Find lcm of a and b
public static long lcm(long a, long b) {
long lcm = gcd(a, b);
long hcf = (a * b) / lcm;
return hcf;
}
// Find factorial in O(n) time
public static long fact(int n) {
long res = 1;
for(int i = 2; i <= n; i++) {
res = res * i;
}
return res;
}
// Find power in O(logb) time
public static long power(long a, long b) {
long res = 1;
while(b > 0) {
if((b&1) == 1) {
res = (res * a)%mod;
}
a = (a * a)%mod;
b >>= 1;
}
return res;
}
// Find nCr
public static long nCr(int n, int r) {
if(r < 0 || r > n) {
return 0;
}
long ans = fact(n) / (fact(r) * fact(n-r));
return ans;
}
// Find nPr
public static long nPr(int n, int r) {
if(r < 0 || r > n) {
return 0;
}
long ans = fact(n) / fact(r);
return ans;
}
// sort all characters of a string
public static String sortString(String inputString) {
char tempArray[] = inputString.toCharArray();
Arrays.sort(tempArray);
return new String(tempArray);
}
// User defined class for fast I/O
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
boolean hasNext() {
if (st != null && st.hasMoreTokens()) {
return true;
}
String tmp;
try {
br.mark(1000);
tmp = br.readLine();
if (tmp == null) {
return false;
}
br.reset();
} catch (IOException e) {
return false;
}
return true;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
float nextFloat() {
return Float.parseFloat(next());
}
boolean nextBoolean() {
return Boolean.parseBoolean(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] nextArray(int n) {
int[] a = new int[n];
for(int i=0; i<n; i++) {
a[i] = nextInt();
}
return a;
}
}
}
/**
Dec Char Dec Char Dec Char Dec Char
--------- --------- --------- ----------
0 NUL (null) 32 SPACE 64 @ 96 `
1 SOH (start of heading) 33 ! 65 A 97 a
2 STX (start of text) 34 " 66 B 98 b
3 ETX (end of text) 35 # 67 C 99 c
4 EOT (end of transmission) 36 $ 68 D 100 d
5 ENQ (enquiry) 37 % 69 E 101 e
6 ACK (acknowledge) 38 & 70 F 102 f
7 BEL (bell) 39 ' 71 G 103 g
8 BS (backspace) 40 ( 72 H 104 h
9 TAB (horizontal tab) 41 ) 73 I 105 i
10 LF (NL line feed, new line) 42 * 74 J 106 j
11 VT (vertical tab) 43 + 75 K 107 k
12 FF (NP form feed, new page) 44 , 76 L 108 l
13 CR (carriage return) 45 - 77 M 109 m
14 SO (shift out) 46 . 78 N 110 n
15 SI (shift in) 47 / 79 O 111 o
16 DLE (data link escape) 48 0 80 P 112 p
17 DC1 (device control 1) 49 1 81 Q 113 q
18 DC2 (device control 2) 50 2 82 R 114 r
19 DC3 (device control 3) 51 3 83 S 115 s
20 DC4 (device control 4) 52 4 84 T 116 t
21 NAK (negative acknowledge) 53 5 85 U 117 u
22 SYN (synchronous idle) 54 6 86 V 118 v
23 ETB (end of trans. block) 55 7 87 W 119 w
24 CAN (cancel) 56 8 88 X 120 x
25 EM (end of medium) 57 9 89 Y 121 y
26 SUB (substitute) 58 : 90 Z 122 z
27 ESC (escape) 59 ; 91 [ 123 {
28 FS (file separator) 60 < 92 \ 124 |
29 GS (group separator) 61 = 93 ] 125 }
30 RS (record separator) 62 > 94 ^ 126 ~
31 US (unit separator) 63 ? 95 _ 127 DEL
*/
// (a/b)%mod == (a * moduloInverse(b)) % mod;
// moduloInverse(b) = power(b, mod-2);
| java |
1299 | A | A. Anu Has a Functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnu has created her own function ff: f(x,y)=(x|y)−yf(x,y)=(x|y)−y where || denotes the bitwise OR operation. For example, f(11,6)=(11|6)−6=15−6=9f(11,6)=(11|6)−6=15−6=9. It can be proved that for any nonnegative numbers xx and yy value of f(x,y)f(x,y) is also nonnegative. She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.A value of an array [a1,a2,…,an][a1,a2,…,an] is defined as f(f(…f(f(a1,a2),a3),…an−1),an)f(f(…f(f(a1,a2),a3),…an−1),an) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?InputThe first line contains a single integer nn (1≤n≤1051≤n≤105).The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109). Elements of the array are not guaranteed to be different.OutputOutput nn integers, the reordering of the array with maximum value. If there are multiple answers, print any.ExamplesInputCopy4
4 0 11 6
OutputCopy11 6 4 0InputCopy1
13
OutputCopy13 NoteIn the first testcase; value of the array [11,6,4,0][11,6,4,0] is f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9.[11,4,0,6][11,4,0,6] is also a valid answer. | [
"brute force",
"greedy",
"math"
] | import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import java.util.*;
import java.io.*;
import java.math.*;
public class A_Anu_Has_a_Function {
static long mod = Long.MAX_VALUE;
public static void main(String[] args) {
OutputStream outputStream = System.out;
PrintWriter out = new PrintWriter(outputStream);
FastReader f = new FastReader();
int t = 1;
while(t-- > 0){
solve(f, out);
}
out.close();
}
public static void solve(FastReader f, PrintWriter out) {
int n = f.nextInt();
int arr[] = f.nextArray(n);
int leftOr[] = new int[n];
int or = 0;
for(int i = 0; i < n; i++) {
leftOr[i] = or;
or |= arr[i];
}
int rightOr[] = new int[n];
or = 0;
for(int i = n-1; i >= 0; i--) {
rightOr[i] = or;
or |= arr[i];
}
// for(int i = 0; i < n; i++) {
// out.print(leftOr[i] + " ");
// }
// out.println();
// for(int i = 0; i < n; i++) {
// out.print(rightOr[i] + " ");
// }
// out.println();
int maxVal = Integer.MIN_VALUE;
int ind = -1;
for(int i = 0; i < n; i++) {
int currOr = (leftOr[i] | rightOr[i]);
int currVal = arr[i] - (arr[i]&currOr);
if(currVal > maxVal) {
maxVal = currVal;
ind = i;
}
}
// out.println(maxVal);
out.print(arr[ind] + " ");
for(int i = 0; i < n; i++) {
if(i == ind) {
continue;
}
out.print(arr[i] + " ");
}
}
// Sort an array
public static void sort(int arr[]) {
ArrayList<Integer> al = new ArrayList<>();
for(int i: arr) {
al.add(i);
}
Collections.sort(al);
for(int i = 0; i < arr.length; i++) {
arr[i] = al.get(i);
}
}
// Find all divisors of n
public static void allDivisors(int n) {
for(int i = 1; i*i <= n; i++) {
if(n%i == 0) {
System.out.println(i + " ");
if(i != n/i) {
System.out.println(n/i + " ");
}
}
}
}
// Check if n is prime or not
public static boolean isPrime(int n) {
if(n < 1) return false;
if(n == 2 || n == 3) return true;
if(n % 2 == 0 || n % 3 == 0) return false;
for(int i = 5; i*i <= n; i += 6) {
if(n % i == 0 || n % (i+2) == 0) {
return false;
}
}
return true;
}
// Find gcd of a and b
public static long gcd(long a, long b) {
long dividend = a > b ? a : b;
long divisor = a < b ? a : b;
while(divisor > 0) {
long reminder = dividend % divisor;
dividend = divisor;
divisor = reminder;
}
return dividend;
}
// Find lcm of a and b
public static long lcm(long a, long b) {
long lcm = gcd(a, b);
long hcf = (a * b) / lcm;
return hcf;
}
// Find factorial in O(n) time
public static long fact(int n) {
long res = 1;
for(int i = 2; i <= n; i++) {
res = res * i;
}
return res;
}
// Find power in O(logb) time
public static long power(long a, long b) {
long res = 1;
while(b > 0) {
if((b&1) == 1) {
res = (res * a)%mod;
}
a = (a * a)%mod;
b >>= 1;
}
return res;
}
// Find nCr
public static long nCr(int n, int r) {
if(r < 0 || r > n) {
return 0;
}
long ans = fact(n) / (fact(r) * fact(n-r));
return ans;
}
// Find nPr
public static long nPr(int n, int r) {
if(r < 0 || r > n) {
return 0;
}
long ans = fact(n) / fact(r);
return ans;
}
// sort all characters of a string
public static String sortString(String inputString) {
char tempArray[] = inputString.toCharArray();
Arrays.sort(tempArray);
return new String(tempArray);
}
// User defined class for fast I/O
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
boolean hasNext() {
if (st != null && st.hasMoreTokens()) {
return true;
}
String tmp;
try {
br.mark(1000);
tmp = br.readLine();
if (tmp == null) {
return false;
}
br.reset();
} catch (IOException e) {
return false;
}
return true;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
float nextFloat() {
return Float.parseFloat(next());
}
boolean nextBoolean() {
return Boolean.parseBoolean(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] nextArray(int n) {
int[] a = new int[n];
for(int i=0; i<n; i++) {
a[i] = nextInt();
}
return a;
}
}
}
/**
Dec Char Dec Char Dec Char Dec Char
--------- --------- --------- ----------
0 NUL (null) 32 SPACE 64 @ 96 `
1 SOH (start of heading) 33 ! 65 A 97 a
2 STX (start of text) 34 " 66 B 98 b
3 ETX (end of text) 35 # 67 C 99 c
4 EOT (end of transmission) 36 $ 68 D 100 d
5 ENQ (enquiry) 37 % 69 E 101 e
6 ACK (acknowledge) 38 & 70 F 102 f
7 BEL (bell) 39 ' 71 G 103 g
8 BS (backspace) 40 ( 72 H 104 h
9 TAB (horizontal tab) 41 ) 73 I 105 i
10 LF (NL line feed, new line) 42 * 74 J 106 j
11 VT (vertical tab) 43 + 75 K 107 k
12 FF (NP form feed, new page) 44 , 76 L 108 l
13 CR (carriage return) 45 - 77 M 109 m
14 SO (shift out) 46 . 78 N 110 n
15 SI (shift in) 47 / 79 O 111 o
16 DLE (data link escape) 48 0 80 P 112 p
17 DC1 (device control 1) 49 1 81 Q 113 q
18 DC2 (device control 2) 50 2 82 R 114 r
19 DC3 (device control 3) 51 3 83 S 115 s
20 DC4 (device control 4) 52 4 84 T 116 t
21 NAK (negative acknowledge) 53 5 85 U 117 u
22 SYN (synchronous idle) 54 6 86 V 118 v
23 ETB (end of trans. block) 55 7 87 W 119 w
24 CAN (cancel) 56 8 88 X 120 x
25 EM (end of medium) 57 9 89 Y 121 y
26 SUB (substitute) 58 : 90 Z 122 z
27 ESC (escape) 59 ; 91 [ 123 {
28 FS (file separator) 60 < 92 \ 124 |
29 GS (group separator) 61 = 93 ] 125 }
30 RS (record separator) 62 > 94 ^ 126 ~
31 US (unit separator) 63 ? 95 _ 127 DEL
*/
// (a/b)%mod == (a * moduloInverse(b)) % mod;
// moduloInverse(b) = power(b, mod-2);
| java |
1141 | E | E. Superhero Battletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA superhero fights with a monster. The battle consists of rounds; each of which lasts exactly nn minutes. After a round ends, the next round starts immediately. This is repeated over and over again.Each round has the same scenario. It is described by a sequence of nn numbers: d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106). The ii-th element means that monster's hp (hit points) changes by the value didi during the ii-th minute of each round. Formally, if before the ii-th minute of a round the monster's hp is hh, then after the ii-th minute it changes to h:=h+dih:=h+di.The monster's initial hp is HH. It means that before the battle the monster has HH hit points. Print the first minute after which the monster dies. The monster dies if its hp is less than or equal to 00. Print -1 if the battle continues infinitely.InputThe first line contains two integers HH and nn (1≤H≤10121≤H≤1012, 1≤n≤2⋅1051≤n≤2⋅105). The second line contains the sequence of integers d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106), where didi is the value to change monster's hp in the ii-th minute of a round.OutputPrint -1 if the superhero can't kill the monster and the battle will last infinitely. Otherwise, print the positive integer kk such that kk is the first minute after which the monster is dead.ExamplesInputCopy1000 6
-100 -200 -300 125 77 -4
OutputCopy9
InputCopy1000000000000 5
-1 0 0 0 0
OutputCopy4999999999996
InputCopy10 4
-3 -6 5 4
OutputCopy-1
| [
"math"
] | import java.io.*;
import java.util.*;
public class ProblemB {
public static void main(String[] args) throws Exception {
Scanner in = new Scanner();
StringBuilder sb = new StringBuilder();
long h = in.readLong();
int n = in.readInt();
int a[] = new int[n];
long sum = 0;
for(int i = 0;i<n;i++){
a[i] = in.readInt();
sum+=a[i];
}
long ans = -1;
long prefix[] = new long[n];
long min = Long.MAX_VALUE;
TreeMap<Long,Integer>mp = new TreeMap<>();
int ind =0;
for(int i = 0;i<n;i++){
prefix[i] = a[i];
if(i-1>=0)prefix[i]+=prefix[i-1];
if(prefix[i]+h<=0){
System.out.println(i+1);
return;
}
if(prefix[i]<0 && !mp.containsKey(-prefix[i]))mp.put(-prefix[i], i);
}
if(mp.size()==0 || sum>=0){
System.out.println(-1);
return;
}else{
long t = mp.lastKey();
sum = -sum;
long full = (h-t+(sum-1))/sum;
h-=(full*sum);
ans = full*n;
for(int i=0;;i=(i+1)%n){
if(h<=0)break;
ans++;
h+=a[i];
}
System.out.println(ans);
}
}
public static void sort(int a[]){
ArrayList<Integer>l = new ArrayList<>();
for(int it:a)l.add(it);
Collections.sort(l);
for(int i = 0;i<l.size();i++)a[i] = l.get(i);
}
public static int lower(int target,int l,int r,int a[]){
int index = l;
while(l<=r){
int mid = (l+r)/2;
if(a[mid]<=target){
index = mid;
l = mid+1;
}else r= mid-1;
}
return index;
}
public static int[] get(long n){
int count1=0,count2=0;
while(n%2 == 0){
n/=2;
count1++;
}
while(n%3 == 0){
n/=3;
count2++;
}
return new int[]{count1,count2};
}
public static boolean isPalindrome(int val){
String s = String.valueOf(val);
for(int i = 0;i<s.length()/2;i++){
if(s.charAt(i) != s.charAt(s.length()-i-1))return false;
}
return true;
}
public static int sum(int n){
int sum = 0;
while(n>0){
sum+=(n%10);
n/=10;
}
return sum;
}
public static void swap(int a[],int i, int j){
int t = a[i];
a[i] = a[j];
a[j] = t;
}
public static boolean subsequence(String cur,String t){
int pos = 0;
for(int i = 0;i<cur.length();i++){
if(pos<t.length() && cur.charAt(i) == t.charAt(pos)){
pos++;
}
}
return pos == t.length();
}
public static long gcd(long a, long b){
return b ==0 ?a:gcd(b,a%b);
}
static class Pair{
int x,y;
public Pair(int x,int y){
this.x = x;
this.y = y;
}
}
static class Scanner{
BufferedReader br;
StringTokenizer st;
public Scanner(){
br = new BufferedReader(new InputStreamReader(System.in));
}
public String read()
{
while (st == null || !st.hasMoreElements()) {
try { st = new StringTokenizer(br.readLine()); }
catch (Exception e) { e.printStackTrace(); }
}
return st.nextToken();
}
public int readInt() { return Integer.parseInt(read()); }
public long readLong() { return Long.parseLong(read()); }
public double readDouble(){return Double.parseDouble(read());}
public String readLine() throws Exception { return br.readLine(); }
}
}
| java |
1294 | A | A. Collecting Coinstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has three sisters: Alice; Barbara, and Cerene. They're collecting coins. Currently, Alice has aa coins, Barbara has bb coins and Cerene has cc coins. Recently Polycarp has returned from the trip around the world and brought nn coins.He wants to distribute all these nn coins between his sisters in such a way that the number of coins Alice has is equal to the number of coins Barbara has and is equal to the number of coins Cerene has. In other words, if Polycarp gives AA coins to Alice, BB coins to Barbara and CC coins to Cerene (A+B+C=nA+B+C=n), then a+A=b+B=c+Ca+A=b+B=c+C.Note that A, B or C (the number of coins Polycarp gives to Alice, Barbara and Cerene correspondingly) can be 0.Your task is to find out if it is possible to distribute all nn coins between sisters in a way described above.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. Each test case is given on a new line and consists of four space-separated integers a,b,ca,b,c and nn (1≤a,b,c,n≤1081≤a,b,c,n≤108) — the number of coins Alice has, the number of coins Barbara has, the number of coins Cerene has and the number of coins Polycarp has.OutputFor each test case, print "YES" if Polycarp can distribute all nn coins between his sisters and "NO" otherwise.ExampleInputCopy5
5 3 2 8
100 101 102 105
3 2 1 100000000
10 20 15 14
101 101 101 3
OutputCopyYES
YES
NO
NO
YES
| [
"math"
] | /* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
for(int i=0;i<t;i++){
long a=sc.nextLong();
long b=sc.nextLong();
long c=sc.nextLong();
long n=sc.nextLong();
long sum=a+b+c+n;
if(sum%3==0&&a<=sum/3&&b<=sum/3&&c<=sum/3){
System.out.println("YES");
}
else{
System.out.println("NO");
}
}
}
}
| java |
1313 | A | A. Fast Food Restauranttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTired of boring office work; Denis decided to open a fast food restaurant.On the first day he made aa portions of dumplings, bb portions of cranberry juice and cc pancakes with condensed milk.The peculiarity of Denis's restaurant is the procedure of ordering food. For each visitor Denis himself chooses a set of dishes that this visitor will receive. When doing so, Denis is guided by the following rules: every visitor should receive at least one dish (dumplings, cranberry juice, pancakes with condensed milk are all considered to be dishes); each visitor should receive no more than one portion of dumplings, no more than one portion of cranberry juice and no more than one pancake with condensed milk; all visitors should receive different sets of dishes. What is the maximum number of visitors Denis can feed?InputThe first line contains an integer tt (1≤t≤5001≤t≤500) — the number of test cases to solve.Each of the remaining tt lines contains integers aa, bb and cc (0≤a,b,c≤100≤a,b,c≤10) — the number of portions of dumplings, the number of portions of cranberry juice and the number of condensed milk pancakes Denis made.OutputFor each test case print a single integer — the maximum number of visitors Denis can feed.ExampleInputCopy71 2 10 0 09 1 72 2 32 3 23 2 24 4 4OutputCopy3045557NoteIn the first test case of the example, Denis can feed the first visitor with dumplings, give the second a portion of cranberry juice, and give the third visitor a portion of cranberry juice and a pancake with a condensed milk.In the second test case of the example, the restaurant Denis is not very promising: he can serve no customers.In the third test case of the example, Denise can serve four visitors. The first guest will receive a full lunch of dumplings, a portion of cranberry juice and a pancake with condensed milk. The second visitor will get only dumplings. The third guest will receive a pancake with condensed milk, and the fourth guest will receive a pancake and a portion of dumplings. Please note that Denis hasn't used all of the prepared products, but is unable to serve more visitors. | [
"brute force",
"greedy",
"implementation"
] | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Random;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
public final class CFPS {
static FastReader fr = new FastReader();
static PrintWriter out = new PrintWriter(System.out);
static final int gigamod = 1000000007;
static final int mod = 998244353;
static int t = 1;
static boolean[] isPrime;
static int[] smallestFactorOf;
static final int UP = 0, LEFT = 1, DOWN = 2, RIGHT = 3;
static int cmp;
@SuppressWarnings({"unused"})
public static void main(String[] args) throws Exception {
t = fr.nextInt();
OUTER:
for (int tc = 0; tc < t; tc++) {
int a = fr.nextInt(), b = fr.nextInt(), c = fr.nextInt();
// a
// b
// c
// a b
// a c
// b c
// a b c
int ans = 0;
if (a > 0)
ans++;
if (b > 0)
ans++;
if (c > 0)
ans++;
a--;
b--;
c--;
int[] abc = new int[] {a, b, c};
reverseSort(abc);
a = abc[0];
b = abc[1];
c = abc[2];
if (a > 0 && b > 0) {
ans++;
a--;
b--;
}
if (a > 0 && c > 0) {
ans++;
a--;
c--;
}
if (b > 0 && c > 0) {
ans++;
b--;
c--;
}
if (a > 0 && b > 0 && c > 0) {
ans++;
}
out.println(ans);
}
out.close();
}
static boolean isPalindrome(char[] s) {
char[] rev = s.clone();
reverse(rev);
return Arrays.compare(s, rev) == 0;
}
static class Segment implements Comparable<Segment> {
int size;
long val;
int stIdx;
Segment left, right;
Segment(int ss, long vv, int ssii) {
size = ss;
val = vv;
stIdx = ssii;
}
@Override
public int compareTo(Segment that) {
cmp = size - that.size;
if (cmp == 0)
cmp = stIdx - that.stIdx;
if (cmp == 0)
cmp = Long.compare(val, that.val);
return cmp;
}
}
static class Pair implements Comparable<Pair> {
int first, second;
int idx;
Pair() { first = second = 0; }
Pair (int ff, int ss) {first = ff; second = ss;}
Pair (int ff, int ss, int ii) { first = ff; second = ss; idx = ii; }
public int compareTo(Pair that) {
cmp = first - that.first;
if (cmp == 0)
cmp = second - that.second;
return (int) cmp;
}
}
// (range add - segment min) segTree
static int nn;
static int[] arr;
static int[] tree;
static int[] lazy;
static void build(int node, int leftt, int rightt) {
if (leftt == rightt) {
tree[node] = arr[leftt];
return;
}
int mid = (leftt + rightt) >> 1;
build(node << 1, leftt, mid);
build(node << 1 | 1, mid + 1, rightt);
tree[node] = Math.min(tree[node << 1], tree[node << 1 | 1]);
}
static void segAdd(int node, int leftt, int rightt, int segL, int segR, int val) {
if (lazy[node] != 0) {
tree[node] += lazy[node];
if (leftt != rightt) {
lazy[node << 1] += lazy[node];
lazy[node << 1 | 1] += lazy[node];
}
lazy[node] = 0;
}
if (segL > rightt || segR < leftt) return;
if (segL <= leftt && rightt <= segR) {
tree[node] += val;
if (leftt != rightt) {
lazy[node << 1] += val;
lazy[node << 1 | 1] += val;
}
lazy[node] = 0;
return;
}
int mid = (leftt + rightt) >> 1;
segAdd(node << 1, leftt, mid, segL, segR, val);
segAdd(node << 1 | 1, mid + 1, rightt, segL, segR, val);
tree[node] = Math.min(tree[node << 1], tree[node << 1 | 1]);
}
static int minQuery(int node, int leftt, int rightt, int segL, int segR) {
if (lazy[node] != 0) {
tree[node] += lazy[node];
if (leftt != rightt) {
lazy[node << 1] += lazy[node];
lazy[node << 1 | 1] += lazy[node];
}
lazy[node] = 0;
}
if (segL > rightt || segR < leftt) return Integer.MAX_VALUE / 10;
if (segL <= leftt && rightt <= segR)
return tree[node];
int mid = (leftt + rightt) >> 1;
return Math.min(minQuery(node << 1, leftt, mid, segL, segR),
minQuery(node << 1 | 1, mid + 1, rightt, segL, segR));
}
static void compute_automaton(String s, int[][] aut) {
s += '#';
int n = s.length();
int[] pi = prefix_function(s.toCharArray());
for (int i = 0; i < n; i++) {
for (int c = 0; c < 26; c++) {
int j = i;
while (j > 0 && 'A' + c != s.charAt(j))
j = pi[j-1];
if ('A' + c == s.charAt(j))
j++;
aut[i][c] = j;
}
}
}
static void timeDFS(int current, int from, UGraph ug,
int[] time, int[] tIn, int[] tOut) {
tIn[current] = ++time[0];
for (int adj : ug.adj(current))
if (adj != from)
timeDFS(adj, current, ug, time, tIn, tOut);
tOut[current] = ++time[0];
}
static boolean areCollinear(long x1, long y1, long x2, long y2, long x3, long y3) {
// we will check if c3 lies on line through (c1, c2)
long a = x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2);
return a == 0;
}
static int[] treeDiameter(UGraph ug) {
int n = ug.V();
int farthest = -1;
int[] distTo = new int[n];
diamDFS(0, -1, 0, ug, distTo);
int maxDist = -1;
for (int i = 0; i < n; i++)
if (maxDist < distTo[i]) {
maxDist = distTo[i];
farthest = i;
}
distTo = new int[n + 1];
diamDFS(farthest, -1, 0, ug, distTo);
distTo[n] = farthest;
return distTo;
}
static void diamDFS(int current, int from, int dist, UGraph ug, int[] distTo) {
distTo[current] = dist;
for (int adj : ug.adj(current))
if (adj != from)
diamDFS(adj, current, dist + 1, ug, distTo);
}
static class TreeDistFinder {
UGraph ug;
int n;
int[] depthOf;
LCA lca;
TreeDistFinder(UGraph ug) {
this.ug = ug;
n = ug.V();
depthOf = new int[n];
depthCalc(0, -1, ug, 0, depthOf);
lca = new LCA(ug, 0);
}
TreeDistFinder(UGraph ug, int a) {
this.ug = ug;
n = ug.V();
depthOf = new int[n];
depthCalc(a, -1, ug, 0, depthOf);
lca = new LCA(ug, a);
}
private void depthCalc(int current, int from, UGraph ug, int depth, int[] depthOf) {
depthOf[current] = depth;
for (int adj : ug.adj(current))
if (adj != from)
depthCalc(adj, current, ug, depth + 1, depthOf);
}
public int dist(int a, int b) {
int lc = lca.lca(a, b);
return (depthOf[a] - depthOf[lc] + depthOf[b] - depthOf[lc]);
}
}
public static long[][] GCDSparseTable(long[] a)
{
int n = a.length;
int b = 32-Integer.numberOfLeadingZeros(n);
long[][] ret = new long[b][];
for(int i = 0, l = 1;i < b;i++, l*=2) {
if(i == 0) {
ret[i] = a;
} else {
ret[i] = new long[n-l+1];
for(int j = 0;j < n-l+1;j++) {
ret[i][j] = gcd(ret[i-1][j], ret[i-1][j+l/2]);
}
}
}
return ret;
}
public static long sparseRangeGCDQ(long[][] table, int l, int r)
{
// [a,b)
if(l > r)return 1;
// 1:0, 2:1, 3:1, 4:2, 5:2, 6:2, 7:2, 8:3
int t = 31-Integer.numberOfLeadingZeros(r-l);
return gcd(table[t][l], table[t][r-(1<<t)]);
}
static class Trie {
TrieNode root;
Trie(char[][] strings) {
root = new TrieNode('A', false);
construct(root, strings);
}
public Stack<String> set(TrieNode root) {
Stack<String> set = new Stack<>();
StringBuilder sb = new StringBuilder();
for (TrieNode next : root.next)
collect(sb, next, set);
return set;
}
private void collect(StringBuilder sb, TrieNode node, Stack<String> set) {
if (node == null) return;
sb.append(node.character);
if (node.isTerminal)
set.add(sb.toString());
for (TrieNode next : node.next)
collect(sb, next, set);
if (sb.length() > 0)
sb.setLength(sb.length() - 1);
}
private void construct(TrieNode root, char[][] strings) {
// we have to construct the Trie
for (char[] string : strings) {
if (string.length == 0) continue;
root.next[string[0] - 'a'] = put(root.next[string[0] - 'a'], string, 0);
if (root.next[string[0] - 'a'] != null)
root.isLeaf = false;
}
}
private TrieNode put(TrieNode node, char[] string, int idx) {
boolean isTerminal = (idx == string.length - 1);
if (node == null) node = new TrieNode(string[idx], isTerminal);
node.character = string[idx];
node.isTerminal |= isTerminal;
if (!isTerminal) {
node.isLeaf = false;
node.next[string[idx + 1] - 'a'] = put(node.next[string[idx + 1] - 'a'], string, idx + 1);
}
return node;
}
class TrieNode {
char character;
TrieNode[] next;
boolean isTerminal, isLeaf;
boolean canWin, canLose;
TrieNode(char c, boolean isTerminallll) {
character = c;
isTerminal = isTerminallll;
next = new TrieNode[26];
isLeaf = true;
}
}
}
static class Edge implements Comparable<Edge> {
int from, to;
long weight, ans;
int id;
// int hash;
Edge(int fro, int t, long wt, int i) {
from = fro;
to = t;
id = i;
weight = wt;
// hash = Objects.hash(from, to, weight);
}
/*public int hashCode() {
return hash;
}*/
public int compareTo(Edge that) {
return Long.compare(this.id, that.id);
}
}
public static long[][] minSparseTable(long[] a)
{
int n = a.length;
int b = 32-Integer.numberOfLeadingZeros(n);
long[][] ret = new long[b][];
for(int i = 0, l = 1;i < b;i++, l*=2) {
if(i == 0) {
ret[i] = a;
}else {
ret[i] = new long[n-l+1];
for(int j = 0;j < n-l+1;j++) {
ret[i][j] = Math.min(ret[i-1][j], ret[i-1][j+l/2]);
}
}
}
return ret;
}
public static long sparseRangeMinQ(long[][] table, int l, int r)
{
// [a,b)
if(l >= r)return Integer.MAX_VALUE;
// 1:0, 2:1, 3:1, 4:2, 5:2, 6:2, 7:2, 8:3
int t = 31-Integer.numberOfLeadingZeros(r-l);
return Math.min(table[t][l], table[t][r-(1<<t)]);
}
public static long[][] maxSparseTable(long[] a)
{
int n = a.length;
int b = 32-Integer.numberOfLeadingZeros(n);
long[][] ret = new long[b][];
for(int i = 0, l = 1;i < b;i++, l*=2) {
if(i == 0) {
ret[i] = a;
}else {
ret[i] = new long[n-l+1];
for(int j = 0;j < n-l+1;j++) {
ret[i][j] = Math.max(ret[i-1][j], ret[i-1][j+l/2]);
}
}
}
return ret;
}
public static long sparseRangeMaxQ(long[][] table, int l, int r)
{
// [a,b)
if(l >= r)return Integer.MIN_VALUE;
// 1:0, 2:1, 3:1, 4:2, 5:2, 6:2, 7:2, 8:3
int t = 31-Integer.numberOfLeadingZeros(r-l);
return Math.max(table[t][l], table[t][r-(1<<t)]);
}
static class LCA {
int[] height, first, segtree;
ArrayList<Integer> euler;
boolean[] visited;
int n;
LCA(UGraph ug, int root) {
n = ug.V();
height = new int[n];
first = new int[n];
euler = new ArrayList<>();
visited = new boolean[n];
dfs(ug, root, 0);
int m = euler.size();
segtree = new int[m * 4];
build(1, 0, m - 1);
}
void dfs(UGraph ug, int node, int h) {
visited[node] = true;
height[node] = h;
first[node] = euler.size();
euler.add(node);
for (int adj : ug.adj(node)) {
if (!visited[adj]) {
dfs(ug, adj, h + 1);
euler.add(node);
}
}
}
void build(int node, int b, int e) {
if (b == e) {
segtree[node] = euler.get(b);
} else {
int mid = (b + e) / 2;
build(node << 1, b, mid);
build(node << 1 | 1, mid + 1, e);
int l = segtree[node << 1], r = segtree[node << 1 | 1];
segtree[node] = (height[l] < height[r]) ? l : r;
}
}
int query(int node, int b, int e, int L, int R) {
if (b > R || e < L)
return -1;
if (b >= L && e <= R)
return segtree[node];
int mid = (b + e) >> 1;
int left = query(node << 1, b, mid, L, R);
int right = query(node << 1 | 1, mid + 1, e, L, R);
if (left == -1) return right;
if (right == -1) return left;
return height[left] < height[right] ? left : right;
}
int lca(int u, int v) {
int left = first[u], right = first[v];
if (left > right) {
int temp = left;
left = right;
right = temp;
}
return query(1, 0, euler.size() - 1, left, right);
}
}
static class FenwickTree {
long[] array; // 1-indexed array, In this array We save cumulative information to perform efficient range queries and updates
public FenwickTree(int size) {
array = new long[size + 1];
}
public long rsq(int ind) {
assert ind > 0;
long sum = 0;
while (ind > 0) {
sum += array[ind];
//Extracting the portion up to the first significant one of the binary representation of 'ind' and decrementing ind by that number
ind -= ind & (-ind);
}
return sum;
}
public long rsq(int a, int b) {
assert b >= a && a > 0 && b > 0;
return rsq(b) - rsq(a - 1);
}
public void update(int ind, long value) {
assert ind > 0;
while (ind < array.length) {
array[ind] += value;
//Extracting the portion up to the first significant one of the binary representation of 'ind' and incrementing ind by that number
ind += ind & (-ind);
}
}
public int size() {
return array.length - 1;
}
}
static class Point implements Comparable<Point> {
long x;
long y;
long z;
long id;
// private int hashCode;
Point() {
x = z = y = 0;
// this.hashCode = Objects.hash(x, y, cost);
}
Point(Point p) {
this.x = p.x;
this.y = p.y;
this.z = p.z;
this.id = p.id;
// this.hashCode = Objects.hash(x, y, cost);
}
Point(long x, long y, long z, long id) {
this.x = x;
this.y = y;
this.z = z;
this.id = id;
// this.hashCode = Objects.hash(x, y, id);
}
Point(long a, long b) {
this.x = a;
this.y = b;
this.z = 0;
// this.hashCode = Objects.hash(a, b);
}
Point(long x, long y, long id) {
this.x = x;
this.y = y;
this.id = id;
}
@Override
public int compareTo(Point o) {
if (this.x < o.x)
return -1;
if (this.x > o.x)
return 1;
if (this.y < o.y)
return -1;
if (this.y > o.y)
return 1;
if (this.z < o.z)
return -1;
if (this.z > o.z)
return 1;
return 0;
}
@Override
public boolean equals(Object that) {
return this.compareTo((Point) that) == 0;
}
}
static class BinaryLift {
// FUNCTIONS: k-th ancestor and LCA in log(n)
int[] parentOf;
int maxJmpPow;
int[][] binAncestorOf;
int n;
int[] lvlOf;
// How this works?
// a. For every node, we store the b-ancestor for b in {1, 2, 4, 8, .. log(n)}.
// b. When we need k-ancestor, we represent 'k' in binary and for each set bit, we
// lift level in the tree.
public BinaryLift(UGraph tree) {
n = tree.V();
maxJmpPow = logk(n, 2) + 1;
parentOf = new int[n];
binAncestorOf = new int[n][maxJmpPow];
lvlOf = new int[n];
for (int i = 0; i < n; i++)
Arrays.fill(binAncestorOf[i], -1);
parentConstruct(0, -1, tree, 0);
binConstruct();
}
// TODO: Implement lvlOf[] initialization
public BinaryLift(int[] parentOf) {
this.parentOf = parentOf;
n = parentOf.length;
maxJmpPow = logk(n, 2) + 1;
binAncestorOf = new int[n][maxJmpPow];
lvlOf = new int[n];
for (int i = 0; i < n; i++)
Arrays.fill(binAncestorOf[i], -1);
UGraph tree = new UGraph(n);
for (int i = 1; i < n; i++)
tree.addEdge(i, parentOf[i]);
binConstruct();
parentConstruct(0, -1, tree, 0);
}
private void parentConstruct(int current, int from, UGraph tree, int depth) {
parentOf[current] = from;
lvlOf[current] = depth;
for (int adj : tree.adj(current))
if (adj != from)
parentConstruct(adj, current, tree, depth + 1);
}
private void binConstruct() {
for (int node = 0; node < n; node++)
for (int lvl = 0; lvl < maxJmpPow; lvl++)
binConstruct(node, lvl);
}
private int binConstruct(int node, int lvl) {
if (node < 0)
return -1;
if (lvl == 0)
return binAncestorOf[node][lvl] = parentOf[node];
if (node == 0)
return binAncestorOf[node][lvl] = -1;
if (binAncestorOf[node][lvl] != -1)
return binAncestorOf[node][lvl];
return binAncestorOf[node][lvl] = binConstruct(binConstruct(node, lvl - 1), lvl - 1);
}
// return ancestor which is 'k' levels above this one
public int ancestor(int node, int k) {
if (node < 0)
return -1;
if (node == 0)
if (k == 0) return node;
else return -1;
if (k > (1 << maxJmpPow) - 1)
return -1;
if (k == 0)
return node;
int ancestor = node;
int highestBit = Integer.highestOneBit(k);
while (k > 0 && ancestor != -1) {
ancestor = binAncestorOf[ancestor][logk(highestBit, 2)];
k -= highestBit;
highestBit = Integer.highestOneBit(k);
}
return ancestor;
}
public int lca(int u, int v) {
if (u == v)
return u;
// The invariant will be that 'u' is below 'v' initially.
if (lvlOf[u] < lvlOf[v]) {
int temp = u;
u = v;
v = temp;
}
// Equalizing the levels.
u = ancestor(u, lvlOf[u] - lvlOf[v]);
if (u == v)
return u;
// We will now raise level by largest fitting power of two until possible.
for (int power = maxJmpPow - 1; power > -1; power--)
if (binAncestorOf[u][power] != binAncestorOf[v][power]) {
u = binAncestorOf[u][power];
v = binAncestorOf[v][power];
}
return ancestor(u, 1);
}
}
static class DFSTree {
// NOTE: The thing is made keeping in mind that the whole
// input graph is connected.
UGraph tree;
UGraph backUG;
int hasBridge;
int n;
Edge backEdge;
DFSTree(UGraph ug) {
this.n = ug.V();
tree = new UGraph(n);
hasBridge = -1;
backUG = new UGraph(n);
treeCalc(0, -1, new boolean[n], ug);
}
private void treeCalc(int current, int from, boolean[] marked, UGraph ug) {
if (marked[current]) {
// This is a backEdge.
backUG.addEdge(from, current);
backEdge = new Edge(from, current, 1, 0);
return;
}
if (from != -1)
tree.addEdge(from, current);
marked[current] = true;
for (int adj : ug.adj(current))
if (adj != from)
treeCalc(adj, current, marked, ug);
}
public boolean hasBridge() {
if (hasBridge != -1)
return (hasBridge == 1);
// We have to determine the bridge.
bridgeFinder();
return (hasBridge == 1);
}
int[] levelOf;
int[] dp;
private void bridgeFinder() {
// Finding the level of each node.
levelOf = new int[n];
levelDFS(0, -1, 0);
// Applying DP solution.
// dp[i] -> Highest level reachable from subtree of 'i' using
// some backEdge.
dp = new int[n];
Arrays.fill(dp, Integer.MAX_VALUE / 100);
dpDFS(0, -1);
// Now, we will check each edge and determine whether its a
// bridge.
for (int i = 0; i < n; i++)
for (int adj : tree.adj(i)) {
// (i -> adj) is the edge.
if (dp[adj] > levelOf[i])
hasBridge = 1;
}
if (hasBridge != 1)
hasBridge = 0;
}
private void levelDFS(int current, int from, int lvl) {
levelOf[current] = lvl;
for (int adj : tree.adj(current))
if (adj != from)
levelDFS(adj, current, lvl + 1);
}
private int dpDFS(int current, int from) {
dp[current] = levelOf[current];
for (int back : backUG.adj(current))
dp[current] = Math.min(dp[current], levelOf[back]);
for (int adj : tree.adj(current))
if (adj != from)
dp[current] = Math.min(dp[current], dpDFS(adj, current));
return dp[current];
}
}
static class UnionFind {
// Uses weighted quick-union with path compression.
private int[] parent; // parent[i] = parent of i
private int[] size; // size[i] = number of sites in tree rooted at i
// Note: not necessarily correct if i is not a root node
private int count; // number of components
public UnionFind(int n) {
count = n;
parent = new int[n];
size = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
size[i] = 1;
}
}
// Number of connected components.
public int count() {
return count;
}
// Find the root of p.
public int find(int p) {
while (p != parent[p])
p = parent[p];
return p;
}
public boolean connected(int p, int q) {
return find(p) == find(q);
}
public int numConnectedTo(int node) {
return size[find(node)];
}
// Weighted union.
public void union(int p, int q) {
int rootP = find(p);
int rootQ = find(q);
if (rootP == rootQ) return;
// make smaller root point to larger one
if (size[rootP] < size[rootQ]) {
parent[rootP] = rootQ;
size[rootQ] += size[rootP];
}
else {
parent[rootQ] = rootP;
size[rootP] += size[rootQ];
}
count--;
}
public static int[] connectedComponents(UnionFind uf) {
// We can do this in nlogn.
int n = uf.size.length;
int[] compoColors = new int[n];
for (int i = 0; i < n; i++)
compoColors[i] = uf.find(i);
HashMap<Integer, Integer> oldToNew = new HashMap<>();
int newCtr = 0;
for (int i = 0; i < n; i++) {
int thisOldColor = compoColors[i];
Integer thisNewColor = oldToNew.get(thisOldColor);
if (thisNewColor == null)
thisNewColor = newCtr++;
oldToNew.put(thisOldColor, thisNewColor);
compoColors[i] = thisNewColor;
}
return compoColors;
}
}
static class UGraph {
// Adjacency list.
private HashSet<Integer>[] adj;
private static final String NEWLINE = "\n";
private int E;
@SuppressWarnings("unchecked")
public UGraph(int V) {
adj = (HashSet<Integer>[]) new HashSet[V];
E = 0;
for (int i = 0; i < V; i++)
adj[i] = new HashSet<Integer>();
}
public void addEdge(int from, int to) {
if (adj[from].contains(to)) return;
E++;
adj[from].add(to);
adj[to].add(from);
}
public HashSet<Integer> adj(int from) {
return adj[from];
}
public int degree(int v) {
return adj[v].size();
}
public int V() {
return adj.length;
}
public int E() {
return E;
}
public String toString() {
StringBuilder s = new StringBuilder();
s.append(V() + " vertices, " + E() + " edges " + NEWLINE);
for (int v = 0; v < V(); v++) {
s.append(v + ": ");
for (int w : adj[v]) {
s.append(w + " ");
}
s.append(NEWLINE);
}
return s.toString();
}
public static void dfsMark(int current, boolean[] marked, UGraph g) {
if (marked[current]) return;
marked[current] = true;
Iterable<Integer> adj = g.adj(current);
for (int adjc : adj)
dfsMark(adjc, marked, g);
}
public static void dfsMark(int current, int from, long[] distTo, boolean[] marked, UGraph g, ArrayList<Integer> endPoints) {
if (marked[current]) return;
marked[current] = true;
if (from != -1)
distTo[current] = distTo[from] + 1;
HashSet<Integer> adj = g.adj(current);
int alreadyMarkedCtr = 0;
for (int adjc : adj) {
if (marked[adjc]) alreadyMarkedCtr++;
dfsMark(adjc, current, distTo, marked, g, endPoints);
}
if (alreadyMarkedCtr == adj.size())
endPoints.add(current);
}
public static void bfsOrder(int current, UGraph g) {
}
public static void dfsMark(int current, int[] colorIds, int color, UGraph g) {
if (colorIds[current] != -1) return;
colorIds[current] = color;
Iterable<Integer> adj = g.adj(current);
for (int adjc : adj)
dfsMark(adjc, colorIds, color, g);
}
public static int[] connectedComponents(UGraph g) {
int n = g.V();
int[] componentId = new int[n];
Arrays.fill(componentId, -1);
int colorCtr = 0;
for (int i = 0; i < n; i++) {
if (componentId[i] != -1) continue;
dfsMark(i, componentId, colorCtr, g);
colorCtr++;
}
return componentId;
}
public static boolean hasCycle(UGraph ug) {
int n = ug.V();
boolean[] marked = new boolean[n];
boolean[] hasCycleFirst = new boolean[1];
for (int i = 0; i < n; i++) {
if (marked[i]) continue;
hcDfsMark(i, ug, marked, hasCycleFirst, -1);
}
return hasCycleFirst[0];
}
// Helper for hasCycle.
private static void hcDfsMark(int current, UGraph ug, boolean[] marked, boolean[] hasCycleFirst, int parent) {
if (marked[current]) return;
if (hasCycleFirst[0]) return;
marked[current] = true;
HashSet<Integer> adjc = ug.adj(current);
for (int adj : adjc) {
if (marked[adj] && adj != parent && parent != -1) {
hasCycleFirst[0] = true;
return;
}
hcDfsMark(adj, ug, marked, hasCycleFirst, current);
}
}
}
static class Digraph {
// Adjacency list.
private HashSet<Integer>[] adj;
private static final String NEWLINE = "\n";
private int E;
@SuppressWarnings("unchecked")
public Digraph(int V) {
adj = (HashSet<Integer>[]) new HashSet[V];
E = 0;
for (int i = 0; i < V; i++)
adj[i] = new HashSet<Integer>();
}
public void addEdge(int from, int to) {
if (adj[from].contains(to)) return;
E++;
adj[from].add(to);
}
public HashSet<Integer> adj(int from) {
return adj[from];
}
public int V() {
return adj.length;
}
public int E() {
return E;
}
public Digraph reversed() {
Digraph dg = new Digraph(V());
for (int i = 0; i < V(); i++)
for (int adjVert : adj(i)) dg.addEdge(adjVert, i);
return dg;
}
public String toString() {
StringBuilder s = new StringBuilder();
s.append(V() + " vertices, " + E() + " edges " + NEWLINE);
for (int v = 0; v < V(); v++) {
s.append(v + ": ");
for (int w : adj[v]) {
s.append(w + " ");
}
s.append(NEWLINE);
}
return s.toString();
}
public static int[] KosarajuSharirSCC(Digraph dg) {
int[] id = new int[dg.V()];
Digraph reversed = dg.reversed();
// Gotta perform topological sort on this one to get the stack.
Stack<Integer> revStack = Digraph.topologicalSort(reversed);
// Initializing id and idCtr.
id = new int[dg.V()];
int idCtr = -1;
// Creating a 'marked' array.
boolean[] marked = new boolean[dg.V()];
while (!revStack.isEmpty()) {
int vertex = revStack.pop();
if (!marked[vertex])
sccDFS(dg, vertex, marked, ++idCtr, id);
}
return id;
}
private static void sccDFS(Digraph dg, int source, boolean[] marked, int idCtr, int[] id) {
marked[source] = true;
id[source] = idCtr;
for (Integer adjVertex : dg.adj(source))
if (!marked[adjVertex]) sccDFS(dg, adjVertex, marked, idCtr, id);
}
public static Stack<Integer> topologicalSort(Digraph dg) {
// dg has to be a directed acyclic graph.
// We'll have to run dfs on the digraph and push the deepest nodes on stack first.
// We'll need a Stack<Integer> and a int[] marked.
Stack<Integer> topologicalStack = new Stack<Integer>();
boolean[] marked = new boolean[dg.V()];
// Calling dfs
for (int i = 0; i < dg.V(); i++)
if (!marked[i])
runDfs(dg, topologicalStack, marked, i);
return topologicalStack;
}
static void runDfs(Digraph dg, Stack<Integer> topologicalStack, boolean[] marked, int source) {
marked[source] = true;
for (Integer adjVertex : dg.adj(source))
if (!marked[adjVertex])
runDfs(dg, topologicalStack, marked, adjVertex);
topologicalStack.add(source);
}
}
static class FastReader {
private BufferedReader bfr;
private StringTokenizer st;
public FastReader() {
bfr = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
if (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(bfr.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());
}
char nextChar() {
return next().toCharArray()[0];
}
String nextString() {
return next();
}
int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = nextInt();
return arr;
}
double[] nextDoubleArray(int n) {
double[] arr = new double[n];
for (int i = 0; i < arr.length; i++)
arr[i] = nextDouble();
return arr;
}
long[] nextLongArray(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++)
arr[i] = nextLong();
return arr;
}
int[][] nextIntGrid(int n, int m) {
int[][] grid = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++)
grid[i][j] = fr.nextInt();
}
return grid;
}
}
@SuppressWarnings("serial")
static class CountMap<T> extends TreeMap<T, Integer>{
CountMap() {
}
CountMap(Comparator<T> cmp) {
}
CountMap(T[] arr) {
this.putCM(arr);
}
public Integer putCM(T key) {
return super.put(key, super.getOrDefault(key, 0) + 1);
}
public Integer removeCM(T key) {
int count = super.getOrDefault(key, -1);
if (count == -1) return -1;
if (count == 1)
return super.remove(key);
else
return super.put(key, count - 1);
}
public Integer getCM(T key) {
return super.getOrDefault(key, 0);
}
public void putCM(T[] arr) {
for (T l : arr)
this.putCM(l);
}
}
static long dioGCD(long a, long b, long[] x0, long[] y0) {
if (b == 0) {
x0[0] = 1;
y0[0] = 0;
return a;
}
long[] x1 = new long[1], y1 = new long[1];
long d = dioGCD(b, a % b, x1, y1);
x0[0] = y1[0];
y0[0] = x1[0] - y1[0] * (a / b);
return d;
}
static boolean diophantine(long a, long b, long c, long[] x0, long[] y0, long[] g) {
g[0] = dioGCD(Math.abs(a), Math.abs(b), x0, y0);
if (c % g[0] > 0) {
return false;
}
x0[0] *= c / g[0];
y0[0] *= c / g[0];
if (a < 0) x0[0] = -x0[0];
if (b < 0) y0[0] = -y0[0];
return true;
}
static long[][] prod(long[][] mat1, long[][] mat2) {
int n = mat1.length;
long[][] prod = new long[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
// determining prod[i][j]
// it will be the dot product of mat1[i][] and mat2[][i]
for (int k = 0; k < n; k++)
prod[i][j] += mat1[i][k] * mat2[k][j];
return prod;
}
static long[][] matExpo(long[][] mat, long power) {
int n = mat.length;
long[][] ans = new long[n][n];
if (power == 0)
return null;
if (power == 1)
return mat;
long[][] half = matExpo(mat, power / 2);
ans = prod(half, half);
if (power % 2 == 1) {
ans = prod(ans, mat);
}
return ans;
}
static int KMPNumOcc(char[] text, char[] pat) {
int n = text.length;
int m = pat.length;
char[] patPlusText = new char[n + m + 1];
for (int i = 0; i < m; i++)
patPlusText[i] = pat[i];
patPlusText[m] = '^'; // Seperator
for (int i = 0; i < n; i++)
patPlusText[m + i] = text[i];
int[] fullPi = piCalcKMP(patPlusText);
int answer = 0;
for (int i = 0; i < n + m + 1; i++)
if (fullPi[i] == m)
answer++;
return answer;
}
static int[] piCalcKMP(char[] s) {
int n = s.length;
int[] pi = new int[n];
for (int i = 1; i < n; i++) {
int j = pi[i - 1];
while (j > 0 && s[i] != s[j])
j = pi[j - 1];
if (s[i] == s[j])
j++;
pi[i] = j;
}
return pi;
}
static boolean[] prefMatchesSuff(char[] s) {
int n = s.length;
boolean[] res = new boolean[n + 1];
int[] pi = prefix_function(s);
res[0] = true;
for (int p = n; p != 0; p = pi[p])
res[p] = true;
return res;
}
static int[] prefix_function(char[] s) {
int n = s.length;
int[] pi = new int[n];
for (int i = 1; i < n; i++) {
int j = pi[i-1];
while (j > 0 && s[i] != s[j])
j = pi[j-1];
if (s[i] == s[j])
j++;
pi[i] = j;
}
return pi;
}
static long hash(long key) {
long h = Long.hashCode(key);
h ^= (h >>> 20) ^ (h >>> 12) ^ (h >>> 7) ^ (h >>> 4);
return h & (gigamod-1);
}
static void Yes() {out.println("Yes");}static void YES() {out.println("YES");}static void yes() {out.println("Yes");}static void No() {out.println("No");}static void NO() {out.println("NO");}static void no() {out.println("no");}
static int mapTo1D(int row, int col, int n, int m) {
// Maps elements in a 2D matrix serially to elements in
// a 1D array.
return row * m + col;
}
static int[] mapTo2D(int idx, int n, int m) {
// Inverse of what the one above does.
int[] rnc = new int[2];
rnc[0] = idx / m;
rnc[1] = idx % m;
return rnc;
}
static long mapTo1D(long row, long col, long n, long m) {
// Maps elements in a 2D matrix serially to elements in
// a 1D array.
return row * m + col;
}
static boolean[] primeGenerator(int upto) {
// Sieve of Eratosthenes:
isPrime = new boolean[upto + 1];
smallestFactorOf = new int[upto + 1];
Arrays.fill(smallestFactorOf, 1);
Arrays.fill(isPrime, true);
isPrime[1] = isPrime[0] = false;
for (long i = 2; i < upto + 1; i++)
if (isPrime[(int) i]) {
smallestFactorOf[(int) i] = (int) i;
// Mark all the multiples greater than or equal
// to the square of i to be false.
for (long j = i; j * i < upto + 1; j++) {
if (isPrime[(int) j * (int) i]) {
isPrime[(int) j * (int) i] = false;
smallestFactorOf[(int) j * (int) i] = (int) i;
}
}
}
return isPrime;
}
static HashMap<Integer, Integer> smolNumPrimeFactorization(int num) {
if (smallestFactorOf == null)
primeGenerator(num + 1);
HashMap<Integer, Integer> fnps = new HashMap<>();
while (num != 1) {
fnps.put(smallestFactorOf[num], fnps.getOrDefault(smallestFactorOf[num], 0) + 1);
num /= smallestFactorOf[num];
}
return fnps;
}
static HashMap<Long, Integer> primeFactorization(long num) {
// Returns map of factor and its power in the number.
HashMap<Long, Integer> map = new HashMap<>();
while (num % 2 == 0) {
num /= 2;
Integer pwrCnt = map.get(2L);
map.put(2L, pwrCnt != null ? pwrCnt + 1 : 1);
}
for (long i = 3; i * i <= num; i += 2) {
while (num % i == 0) {
num /= i;
Integer pwrCnt = map.get(i);
map.put(i, pwrCnt != null ? pwrCnt + 1 : 1);
}
}
// If the number is prime, we have to add it to the
// map.
if (num != 1)
map.put(num, 1);
return map;
}
static HashSet<Long> divisors(long num) {
HashSet<Long> divisors = new HashSet<Long>();
divisors.add(1L);
divisors.add(num);
for (long i = 2; i * i <= num; i++) {
if (num % i == 0) {
divisors.add(num/i);
divisors.add(i);
}
}
return divisors;
}
static void coprimeGenerator(int m, int n, ArrayList<Point> coprimes, int limit, int numCoprimes) {
if (m > limit) return;
if (m <= limit && n <= limit)
coprimes.add(new Point(m, n));
if (coprimes.size() > numCoprimes) return;
coprimeGenerator(2 * m - n, m, coprimes, limit, numCoprimes);
coprimeGenerator(2 * m + n, m, coprimes, limit, numCoprimes);
coprimeGenerator(m + 2 * n, n, coprimes, limit, numCoprimes);
}
static long nCr(long n, long r, long[] fac) { long p = gigamod; if (r == 0) return 1; return (fac[(int)n] * modInverse(fac[(int)r], p) % p * modInverse(fac[(int)n - (int)r], p) % p) % p; }
static long modInverse(long n, long p) { return power(n, p - 2, p); }
static long modDiv(long a, long b){return mod(a * power(b, mod - 2, mod), mod);}
static long power(long x, long y, long p) { long res = 1; x = x % p; while (y > 0) { if ((y & 1)==1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; }
static int logk(long n, long k) { return (int)(Math.log(n) / Math.log(k)); }
static long gcd(long a, long b) { if (b == 0) { return a; } else { return gcd(b, a % b); } } static int gcd(int a, int b) { if (b == 0) { return a; } else { return gcd(b, a % b); } } static long gcd(long[] arr) { int n = arr.length; long gcd = arr[0]; for (int i = 1; i < n; i++) { gcd = gcd(gcd, arr[i]); } return gcd; } static int gcd(int[] arr) { int n = arr.length; int gcd = arr[0]; for (int i = 1; i < n; i++) { gcd = gcd(gcd, arr[i]); } return gcd; } static long lcm(long[] arr) { long lcm = arr[0]; int n = arr.length; for (int i = 1; i < n; i++) { lcm = (lcm * arr[i]) / gcd(lcm, arr[i]); } return lcm; } static long lcm(long a, long b) { return (a * b)/gcd(a, b); } static boolean less(int a, int b) { return a < b ? true : false; } static boolean isSorted(int[] a) { for (int i = 1; i < a.length; i++) { if (less(a[i], a[i - 1])) return false; } return true; } static boolean isSorted(long[] a) { for (int i = 1; i < a.length; i++) { if (a[i] < a[i - 1]) return false; } return true; } static void swap(int[] a, int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } static void swap(long[] a, int i, int j) { long temp = a[i]; a[i] = a[j]; a[j] = temp; } static void swap(double[] a, int i, int j) { double temp = a[i]; a[i] = a[j]; a[j] = temp; } static void swap(char[] a, int i, int j) { char temp = a[i]; a[i] = a[j]; a[j] = temp; }
static void sort(int[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void sort(char[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void sort(long[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void sort(double[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void reverseSort(int[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void reverseSort(char[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void reverse(char[] arr) { int n = arr.length; for (int i = 0; i < n / 2; i++) swap(arr, i, n - 1 - i); } static void reverseSort(long[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void reverseSort(double[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); }
static void shuffleArray(long[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { long tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } static void shuffleArray(int[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { int tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } }
static void shuffleArray(double[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { double tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } }
static void shuffleArray(char[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { char tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } }
static boolean isPrime(long n) {if (n<=1)return false;if(n<=3)return true;if(n%2==0||n%3==0)return false;for(long i=5;i*i<=n;i=i+6)if(n%i==0||n%(i+2)==0)return false;return true;}
static String toString(int[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+" ");return sb.toString();}
static String toString(boolean[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+" ");return sb.toString();}
static String toString(long[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+" ");return sb.toString();}
static String toString(char[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+"");return sb.toString();}
static String toString(int[][] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++){for(int j=0;j<dp[i].length;j++){sb.append(dp[i][j]+" ");}sb.append('\n');}return sb.toString();}
static String toString(long[][] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++){for(int j=0;j<dp[i].length;j++) {sb.append(dp[i][j]+" ");}sb.append('\n');}return sb.toString();}
static String toString(double[][] dp){StringBuilder sb=new StringBuilder();for(int i = 0;i<dp.length;i++){for(int j = 0;j<dp[i].length;j++){sb.append(dp[i][j]+" ");}sb.append('\n');}return sb.toString();}
static String toString(char[][] dp){StringBuilder sb = new StringBuilder();for(int i = 0;i<dp.length;i++){for(int j = 0;j<dp[i].length;j++){sb.append(dp[i][j]+"");}sb.append('\n');}return sb.toString();}
static long mod(long a, long m){return(a%m+1000000L*m)%m;}
}
/*
*
* int[] arr = new int[] {1810, 1700, 1710, 2320, 2000, 1785, 1780
, 2130, 2185, 1430, 1460, 1740, 1860, 1100, 1905, 1650};
int n = arr.length;
sort(arr);
int bel1700 = 0, bet1700n1900 = 0, abv1900 = 0;
for (int i = 0; i < n; i++)
if (arr[i] < 1700)
bel1700++;
else if (1700 <= arr[i] && arr[i] < 1900)
bet1700n1900++;
else if (arr[i] >= 1900)
abv1900++;
out.println("COUNT: " + n);
out.println("PERFS: " + toString(arr));
out.println("MEDIAN: " + arr[n / 2]);
out.println("AVERAGE: " + Arrays.stream(arr).average().getAsDouble());
out.println("[0, 1700): " + bel1700 + "/" + n);
out.println("[1700, 1900): " + bet1700n1900 + "/" + n);
out.println("[1900, 2400): " + abv1900 + "/" + n);
*
* */
// NOTES:
// ASCII VALUE OF 'A': 65
// ASCII VALUE OF 'a': 97
// Range of long: 9 * 10^18
// ASCII VALUE OF '0': 48
// Primes upto 'n' can be given by (n / (logn)). | java |
1324 | E | E. Sleeping Scheduletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVova had a pretty weird sleeping schedule. There are hh hours in a day. Vova will sleep exactly nn times. The ii-th time he will sleep exactly after aiai hours from the time he woke up. You can assume that Vova woke up exactly at the beginning of this story (the initial time is 00). Each time Vova sleeps exactly one day (in other words, hh hours).Vova thinks that the ii-th sleeping time is good if he starts to sleep between hours ll and rr inclusive.Vova can control himself and before the ii-th time can choose between two options: go to sleep after aiai hours or after ai−1ai−1 hours.Your task is to say the maximum number of good sleeping times Vova can obtain if he acts optimally.InputThe first line of the input contains four integers n,h,ln,h,l and rr (1≤n≤2000,3≤h≤2000,0≤l≤r<h1≤n≤2000,3≤h≤2000,0≤l≤r<h) — the number of times Vova goes to sleep, the number of hours in a day and the segment of the good sleeping time.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai<h1≤ai<h), where aiai is the number of hours after which Vova goes to sleep the ii-th time.OutputPrint one integer — the maximum number of good sleeping times Vova can obtain if he acts optimally.ExampleInputCopy7 24 21 23
16 17 14 20 20 11 22
OutputCopy3
NoteThe maximum number of good times in the example is 33.The story starts from t=0t=0. Then Vova goes to sleep after a1−1a1−1 hours, now the time is 1515. This time is not good. Then Vova goes to sleep after a2−1a2−1 hours, now the time is 15+16=715+16=7. This time is also not good. Then Vova goes to sleep after a3a3 hours, now the time is 7+14=217+14=21. This time is good. Then Vova goes to sleep after a4−1a4−1 hours, now the time is 21+19=1621+19=16. This time is not good. Then Vova goes to sleep after a5a5 hours, now the time is 16+20=1216+20=12. This time is not good. Then Vova goes to sleep after a6a6 hours, now the time is 12+11=2312+11=23. This time is good. Then Vova goes to sleep after a7a7 hours, now the time is 23+22=2123+22=21. This time is also good. | [
"dp",
"implementation"
] | import java.io.*;
import java.util.StringTokenizer;
/**
* * @author zhengnaishan
* * @date 2023/2/13 9:21
*/
public class CF1324 {
public static void main(String[] args) {
Kattio io = new Kattio();
int n = io.nextInt();
int h = io.nextInt();
int l = io.nextInt();
int r = io.nextInt();
int[][] s = new int[n + 1][n + 1];
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = io.nextInt();
}
int ans = 0;
long sum = 0;
for (int i = 1; i <= n; i++) {
sum += a[i - 1];
long v = sum % h;
s[i][0] = s[i - 1][0] + (v >= l && v <= r ? 1 : 0);
ans = Math.max(ans, s[i][0]);
for (int j = i; j > 0; j--) {
v = (sum - j) % h;
s[i][j] = s[i - 1][j] + (v >= l && v <= r ? 1 : 0);
s[i][j] = Math.max(s[i - 1][j - 1] + (v >= l && v <= r ? 1 : 0), s[i][j]);
ans = Math.max(ans, s[i][j]);
}
}
io.println(ans);
io.flush();
}
public static class Kattio extends PrintWriter {
private BufferedReader r;
private StringTokenizer st;
// 标准 IO
public Kattio() {
this(System.in, System.out);
}
public Kattio(InputStream i, OutputStream o) {
super(o);
r = new BufferedReader(new InputStreamReader(i));
}
// 文件 IO
public Kattio(String intput, String output) throws IOException {
super(output);
r = new BufferedReader(new FileReader(intput));
}
// 在没有其他输入时返回 null
public String next() {
try {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(r.readLine());
return st.nextToken();
} catch (Exception e) {
}
return null;
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| java |
1316 | C | C. Primitive Primestime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is Professor R's last class of his teaching career. Every time Professor R taught a class; he gave a special problem for the students to solve. You being his favourite student, put your heart into solving it one last time.You are given two polynomials f(x)=a0+a1x+⋯+an−1xn−1f(x)=a0+a1x+⋯+an−1xn−1 and g(x)=b0+b1x+⋯+bm−1xm−1g(x)=b0+b1x+⋯+bm−1xm−1, with positive integral coefficients. It is guaranteed that the cumulative GCD of the coefficients is equal to 11 for both the given polynomials. In other words, gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1. Let h(x)=f(x)⋅g(x)h(x)=f(x)⋅g(x). Suppose that h(x)=c0+c1x+⋯+cn+m−2xn+m−2h(x)=c0+c1x+⋯+cn+m−2xn+m−2. You are also given a prime number pp. Professor R challenges you to find any tt such that ctct isn't divisible by pp. He guarantees you that under these conditions such tt always exists. If there are several such tt, output any of them.As the input is quite large, please use fast input reading methods.InputThe first line of the input contains three integers, nn, mm and pp (1≤n,m≤106,2≤p≤1091≤n,m≤106,2≤p≤109), — nn and mm are the number of terms in f(x)f(x) and g(x)g(x) respectively (one more than the degrees of the respective polynomials) and pp is the given prime number.It is guaranteed that pp is prime.The second line contains nn integers a0,a1,…,an−1a0,a1,…,an−1 (1≤ai≤1091≤ai≤109) — aiai is the coefficient of xixi in f(x)f(x).The third line contains mm integers b0,b1,…,bm−1b0,b1,…,bm−1 (1≤bi≤1091≤bi≤109) — bibi is the coefficient of xixi in g(x)g(x).OutputPrint a single integer tt (0≤t≤n+m−20≤t≤n+m−2) — the appropriate power of xx in h(x)h(x) whose coefficient isn't divisible by the given prime pp. If there are multiple powers of xx that satisfy the condition, print any.ExamplesInputCopy3 2 2
1 1 2
2 1
OutputCopy1
InputCopy2 2 999999937
2 1
3 1
OutputCopy2NoteIn the first test case; f(x)f(x) is 2x2+x+12x2+x+1 and g(x)g(x) is x+2x+2, their product h(x)h(x) being 2x3+5x2+3x+22x3+5x2+3x+2, so the answer can be 1 or 2 as both 3 and 5 aren't divisible by 2.In the second test case, f(x)f(x) is x+2x+2 and g(x)g(x) is x+3x+3, their product h(x)h(x) being x2+5x+6x2+5x+6, so the answer can be any of the powers as no coefficient is divisible by the given prime. | [
"constructive algorithms",
"math",
"ternary search"
] | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
CPrimitivePrimes solver = new CPrimitivePrimes();
solver.solve(1, in, out);
out.close();
}
static class CPrimitivePrimes {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt(), m = in.nextInt(), p = in.nextInt();
int[] a = in.nextIntArray(n);
int[] b = in.nextIntArray(m);
for (int i = 0; i < Math.min(n, m); i++) {
if (a[i] % p != 0 && b[i] % p != 0) {
out.println((long) (i + i));
return;
}
if (a[i] % p != 0) {
for (int j = i + 1; j < m; j++) {
if (b[j] % p != 0) {
out.println((long) (i + j));
return;
}
}
}
if (b[i] % p != 0) {
for (int j = i + 1; j < n; j++) {
if (a[j] % p != 0) {
out.println((long) (i + j));
return;
}
}
}
}
}
}
static class InputReader {
BufferedReader reader;
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[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; ++i) array[i] = nextInt();
return array;
}
public int nextInt() {
return Integer.parseInt(next());
}
}
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 close() {
writer.close();
}
public void println(long i) {
writer.println(i);
}
}
}
| java |
1291 | B | B. Array Sharpeningtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given an array a1,…,ana1,…,an of nn non-negative integers.Let's call it sharpened if and only if there exists an integer 1≤k≤n1≤k≤n such that a1<a2<…<aka1<a2<…<ak and ak>ak+1>…>anak>ak+1>…>an. In particular, any strictly increasing or strictly decreasing array is sharpened. For example: The arrays [4][4], [0,1][0,1], [12,10,8][12,10,8] and [3,11,15,9,7,4][3,11,15,9,7,4] are sharpened; The arrays [2,8,2,8,6,5][2,8,2,8,6,5], [0,1,1,0][0,1,1,0] and [2,5,6,9,8,8][2,5,6,9,8,8] are not sharpened. You can do the following operation as many times as you want: choose any strictly positive element of the array, and decrease it by one. Formally, you can choose any ii (1≤i≤n1≤i≤n) such that ai>0ai>0 and assign ai:=ai−1ai:=ai−1.Tell if it's possible to make the given array sharpened using some number (possibly zero) of these operations.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤15 0001≤t≤15 000) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤3⋅1051≤n≤3⋅105).The second line of each test case contains a sequence of nn non-negative integers a1,…,ana1,…,an (0≤ai≤1090≤ai≤109).It is guaranteed that the sum of nn over all test cases does not exceed 3⋅1053⋅105.OutputFor each test case, output a single line containing "Yes" (without quotes) if it's possible to make the given array sharpened using the described operations, or "No" (without quotes) otherwise.ExampleInputCopy10
1
248618
3
12 10 8
6
100 11 15 9 7 8
4
0 1 1 0
2
0 0
2
0 1
2
1 0
2
1 1
3
0 1 0
3
1 0 1
OutputCopyYes
Yes
Yes
No
No
Yes
Yes
Yes
Yes
No
NoteIn the first and the second test case of the first test; the given array is already sharpened.In the third test case of the first test; we can transform the array into [3,11,15,9,7,4][3,11,15,9,7,4] (decrease the first element 9797 times and decrease the last element 44 times). It is sharpened because 3<11<153<11<15 and 15>9>7>415>9>7>4.In the fourth test case of the first test, it's impossible to make the given array sharpened. | [
"greedy",
"implementation"
] |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class ArraySharpening {
public static void main(String[] args) {
// TODO Auto-generated method stub
FastScanner fs = new FastScanner();
PrintWriter pw = new PrintWriter(System.out);
int T = fs.nextInt();
while (T-- > 0)
{
int N = fs.nextInt();
long[] arr = fs.readArray(N);
//Kahan tak you can achieve strictly inc from left to right
int prefix_last = -1;
for (int i = 0; i < N; i++)
{
if (arr[i] < i)
{
break;
}
prefix_last = i;
}
//Kahan tak tu strictly decreasing kar sakta hai--> check from left
/*
\/
⇗ /\ ⇖
⇗ / \ ⇖
/ \
*/
int suffix_last = N-1;
for (int i = N-1; i >= 0; i--)
{
if (arr[i] < N - i - 1)
{
break;
}
suffix_last = i;
}
//Are these two pointers intersecting?
if (suffix_last <= prefix_last)
{
pw.println("YES");
}
else
{
pw.println("NO");
}
}
pw.close();
}
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
public String next() {
while (!st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
long[] readArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) {
a[i] = nextLong();
}
return a;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
}
| java |
1295 | A | A. Display The Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a large electronic screen which can display up to 998244353998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of 77 segments which can be turned on and off to compose different digits. The following picture describes how you can display all 1010 decimal digits:As you can see, different digits may require different number of segments to be turned on. For example, if you want to display 11, you have to turn on 22 segments of the screen, and if you want to display 88, all 77 segments of some place to display a digit should be turned on.You want to display a really large integer on the screen. Unfortunately, the screen is bugged: no more than nn segments can be turned on simultaneously. So now you wonder what is the greatest integer that can be displayed by turning on no more than nn segments.Your program should be able to process tt different test cases.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases in the input.Then the test cases follow, each of them is represented by a separate line containing one integer nn (2≤n≤1052≤n≤105) — the maximum number of segments that can be turned on in the corresponding testcase.It is guaranteed that the sum of nn over all test cases in the input does not exceed 105105.OutputFor each test case, print the greatest integer that can be displayed by turning on no more than nn segments of the screen. Note that the answer may not fit in the standard 3232-bit or 6464-bit integral data type.ExampleInputCopy2
3
4
OutputCopy7
11
| [
"greedy"
] | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Random;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
public final class CFPS {
static FastReader fr = new FastReader();
static PrintWriter out = new PrintWriter(System.out);
static final int gigamod = 1000000007;
static final int mod = 998244353;
static int t = 1;
static boolean[] isPrime;
static int[] smallestFactorOf;
static final int UP = 0, LEFT = 1, DOWN = 2, RIGHT = 3;
static int cmp;
@SuppressWarnings({"unused"})
public static void main(String[] args) throws Exception {
t = fr.nextInt();
OUTER:
for (int tc = 0; tc < t; tc++) {
int n = fr.nextInt();
int numOnes = n / 2;
char[] ans = new char[numOnes];
Arrays.fill(ans, '1');
n -= numOnes * 2;
if (n > 0)
// one more segment
ans[0] = '7';
out.println(toString(ans));
}
out.close();
}
static boolean isPalindrome(char[] s) {
char[] rev = s.clone();
reverse(rev);
return Arrays.compare(s, rev) == 0;
}
static class Segment implements Comparable<Segment> {
int size;
long val;
int stIdx;
Segment left, right;
Segment(int ss, long vv, int ssii) {
size = ss;
val = vv;
stIdx = ssii;
}
@Override
public int compareTo(Segment that) {
cmp = size - that.size;
if (cmp == 0)
cmp = stIdx - that.stIdx;
if (cmp == 0)
cmp = Long.compare(val, that.val);
return cmp;
}
}
static class Pair implements Comparable<Pair> {
int first, second;
int idx;
Pair() { first = second = 0; }
Pair (int ff, int ss) {first = ff; second = ss;}
Pair (int ff, int ss, int ii) { first = ff; second = ss; idx = ii; }
public int compareTo(Pair that) {
cmp = first - that.first;
if (cmp == 0)
cmp = second - that.second;
return (int) cmp;
}
}
// (range add - segment min) segTree
static int nn;
static int[] arr;
static int[] tree;
static int[] lazy;
static void build(int node, int leftt, int rightt) {
if (leftt == rightt) {
tree[node] = arr[leftt];
return;
}
int mid = (leftt + rightt) >> 1;
build(node << 1, leftt, mid);
build(node << 1 | 1, mid + 1, rightt);
tree[node] = Math.min(tree[node << 1], tree[node << 1 | 1]);
}
static void segAdd(int node, int leftt, int rightt, int segL, int segR, int val) {
if (lazy[node] != 0) {
tree[node] += lazy[node];
if (leftt != rightt) {
lazy[node << 1] += lazy[node];
lazy[node << 1 | 1] += lazy[node];
}
lazy[node] = 0;
}
if (segL > rightt || segR < leftt) return;
if (segL <= leftt && rightt <= segR) {
tree[node] += val;
if (leftt != rightt) {
lazy[node << 1] += val;
lazy[node << 1 | 1] += val;
}
lazy[node] = 0;
return;
}
int mid = (leftt + rightt) >> 1;
segAdd(node << 1, leftt, mid, segL, segR, val);
segAdd(node << 1 | 1, mid + 1, rightt, segL, segR, val);
tree[node] = Math.min(tree[node << 1], tree[node << 1 | 1]);
}
static int minQuery(int node, int leftt, int rightt, int segL, int segR) {
if (lazy[node] != 0) {
tree[node] += lazy[node];
if (leftt != rightt) {
lazy[node << 1] += lazy[node];
lazy[node << 1 | 1] += lazy[node];
}
lazy[node] = 0;
}
if (segL > rightt || segR < leftt) return Integer.MAX_VALUE / 10;
if (segL <= leftt && rightt <= segR)
return tree[node];
int mid = (leftt + rightt) >> 1;
return Math.min(minQuery(node << 1, leftt, mid, segL, segR),
minQuery(node << 1 | 1, mid + 1, rightt, segL, segR));
}
static void compute_automaton(String s, int[][] aut) {
s += '#';
int n = s.length();
int[] pi = prefix_function(s.toCharArray());
for (int i = 0; i < n; i++) {
for (int c = 0; c < 26; c++) {
int j = i;
while (j > 0 && 'A' + c != s.charAt(j))
j = pi[j-1];
if ('A' + c == s.charAt(j))
j++;
aut[i][c] = j;
}
}
}
static void timeDFS(int current, int from, UGraph ug,
int[] time, int[] tIn, int[] tOut) {
tIn[current] = ++time[0];
for (int adj : ug.adj(current))
if (adj != from)
timeDFS(adj, current, ug, time, tIn, tOut);
tOut[current] = ++time[0];
}
static boolean areCollinear(long x1, long y1, long x2, long y2, long x3, long y3) {
// we will check if c3 lies on line through (c1, c2)
long a = x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2);
return a == 0;
}
static int[] treeDiameter(UGraph ug) {
int n = ug.V();
int farthest = -1;
int[] distTo = new int[n];
diamDFS(0, -1, 0, ug, distTo);
int maxDist = -1;
for (int i = 0; i < n; i++)
if (maxDist < distTo[i]) {
maxDist = distTo[i];
farthest = i;
}
distTo = new int[n + 1];
diamDFS(farthest, -1, 0, ug, distTo);
distTo[n] = farthest;
return distTo;
}
static void diamDFS(int current, int from, int dist, UGraph ug, int[] distTo) {
distTo[current] = dist;
for (int adj : ug.adj(current))
if (adj != from)
diamDFS(adj, current, dist + 1, ug, distTo);
}
static class TreeDistFinder {
UGraph ug;
int n;
int[] depthOf;
LCA lca;
TreeDistFinder(UGraph ug) {
this.ug = ug;
n = ug.V();
depthOf = new int[n];
depthCalc(0, -1, ug, 0, depthOf);
lca = new LCA(ug, 0);
}
TreeDistFinder(UGraph ug, int a) {
this.ug = ug;
n = ug.V();
depthOf = new int[n];
depthCalc(a, -1, ug, 0, depthOf);
lca = new LCA(ug, a);
}
private void depthCalc(int current, int from, UGraph ug, int depth, int[] depthOf) {
depthOf[current] = depth;
for (int adj : ug.adj(current))
if (adj != from)
depthCalc(adj, current, ug, depth + 1, depthOf);
}
public int dist(int a, int b) {
int lc = lca.lca(a, b);
return (depthOf[a] - depthOf[lc] + depthOf[b] - depthOf[lc]);
}
}
public static long[][] GCDSparseTable(long[] a)
{
int n = a.length;
int b = 32-Integer.numberOfLeadingZeros(n);
long[][] ret = new long[b][];
for(int i = 0, l = 1;i < b;i++, l*=2) {
if(i == 0) {
ret[i] = a;
} else {
ret[i] = new long[n-l+1];
for(int j = 0;j < n-l+1;j++) {
ret[i][j] = gcd(ret[i-1][j], ret[i-1][j+l/2]);
}
}
}
return ret;
}
public static long sparseRangeGCDQ(long[][] table, int l, int r)
{
// [a,b)
if(l > r)return 1;
// 1:0, 2:1, 3:1, 4:2, 5:2, 6:2, 7:2, 8:3
int t = 31-Integer.numberOfLeadingZeros(r-l);
return gcd(table[t][l], table[t][r-(1<<t)]);
}
static class Trie {
TrieNode root;
Trie(char[][] strings) {
root = new TrieNode('A', false);
construct(root, strings);
}
public Stack<String> set(TrieNode root) {
Stack<String> set = new Stack<>();
StringBuilder sb = new StringBuilder();
for (TrieNode next : root.next)
collect(sb, next, set);
return set;
}
private void collect(StringBuilder sb, TrieNode node, Stack<String> set) {
if (node == null) return;
sb.append(node.character);
if (node.isTerminal)
set.add(sb.toString());
for (TrieNode next : node.next)
collect(sb, next, set);
if (sb.length() > 0)
sb.setLength(sb.length() - 1);
}
private void construct(TrieNode root, char[][] strings) {
// we have to construct the Trie
for (char[] string : strings) {
if (string.length == 0) continue;
root.next[string[0] - 'a'] = put(root.next[string[0] - 'a'], string, 0);
if (root.next[string[0] - 'a'] != null)
root.isLeaf = false;
}
}
private TrieNode put(TrieNode node, char[] string, int idx) {
boolean isTerminal = (idx == string.length - 1);
if (node == null) node = new TrieNode(string[idx], isTerminal);
node.character = string[idx];
node.isTerminal |= isTerminal;
if (!isTerminal) {
node.isLeaf = false;
node.next[string[idx + 1] - 'a'] = put(node.next[string[idx + 1] - 'a'], string, idx + 1);
}
return node;
}
class TrieNode {
char character;
TrieNode[] next;
boolean isTerminal, isLeaf;
boolean canWin, canLose;
TrieNode(char c, boolean isTerminallll) {
character = c;
isTerminal = isTerminallll;
next = new TrieNode[26];
isLeaf = true;
}
}
}
static class Edge implements Comparable<Edge> {
int from, to;
long weight, ans;
int id;
// int hash;
Edge(int fro, int t, long wt, int i) {
from = fro;
to = t;
id = i;
weight = wt;
// hash = Objects.hash(from, to, weight);
}
/*public int hashCode() {
return hash;
}*/
public int compareTo(Edge that) {
return Long.compare(this.id, that.id);
}
}
public static long[][] minSparseTable(long[] a)
{
int n = a.length;
int b = 32-Integer.numberOfLeadingZeros(n);
long[][] ret = new long[b][];
for(int i = 0, l = 1;i < b;i++, l*=2) {
if(i == 0) {
ret[i] = a;
}else {
ret[i] = new long[n-l+1];
for(int j = 0;j < n-l+1;j++) {
ret[i][j] = Math.min(ret[i-1][j], ret[i-1][j+l/2]);
}
}
}
return ret;
}
public static long sparseRangeMinQ(long[][] table, int l, int r)
{
// [a,b)
if(l >= r)return Integer.MAX_VALUE;
// 1:0, 2:1, 3:1, 4:2, 5:2, 6:2, 7:2, 8:3
int t = 31-Integer.numberOfLeadingZeros(r-l);
return Math.min(table[t][l], table[t][r-(1<<t)]);
}
public static long[][] maxSparseTable(long[] a)
{
int n = a.length;
int b = 32-Integer.numberOfLeadingZeros(n);
long[][] ret = new long[b][];
for(int i = 0, l = 1;i < b;i++, l*=2) {
if(i == 0) {
ret[i] = a;
}else {
ret[i] = new long[n-l+1];
for(int j = 0;j < n-l+1;j++) {
ret[i][j] = Math.max(ret[i-1][j], ret[i-1][j+l/2]);
}
}
}
return ret;
}
public static long sparseRangeMaxQ(long[][] table, int l, int r)
{
// [a,b)
if(l >= r)return Integer.MIN_VALUE;
// 1:0, 2:1, 3:1, 4:2, 5:2, 6:2, 7:2, 8:3
int t = 31-Integer.numberOfLeadingZeros(r-l);
return Math.max(table[t][l], table[t][r-(1<<t)]);
}
static class LCA {
int[] height, first, segtree;
ArrayList<Integer> euler;
boolean[] visited;
int n;
LCA(UGraph ug, int root) {
n = ug.V();
height = new int[n];
first = new int[n];
euler = new ArrayList<>();
visited = new boolean[n];
dfs(ug, root, 0);
int m = euler.size();
segtree = new int[m * 4];
build(1, 0, m - 1);
}
void dfs(UGraph ug, int node, int h) {
visited[node] = true;
height[node] = h;
first[node] = euler.size();
euler.add(node);
for (int adj : ug.adj(node)) {
if (!visited[adj]) {
dfs(ug, adj, h + 1);
euler.add(node);
}
}
}
void build(int node, int b, int e) {
if (b == e) {
segtree[node] = euler.get(b);
} else {
int mid = (b + e) / 2;
build(node << 1, b, mid);
build(node << 1 | 1, mid + 1, e);
int l = segtree[node << 1], r = segtree[node << 1 | 1];
segtree[node] = (height[l] < height[r]) ? l : r;
}
}
int query(int node, int b, int e, int L, int R) {
if (b > R || e < L)
return -1;
if (b >= L && e <= R)
return segtree[node];
int mid = (b + e) >> 1;
int left = query(node << 1, b, mid, L, R);
int right = query(node << 1 | 1, mid + 1, e, L, R);
if (left == -1) return right;
if (right == -1) return left;
return height[left] < height[right] ? left : right;
}
int lca(int u, int v) {
int left = first[u], right = first[v];
if (left > right) {
int temp = left;
left = right;
right = temp;
}
return query(1, 0, euler.size() - 1, left, right);
}
}
static class FenwickTree {
long[] array; // 1-indexed array, In this array We save cumulative information to perform efficient range queries and updates
public FenwickTree(int size) {
array = new long[size + 1];
}
public long rsq(int ind) {
assert ind > 0;
long sum = 0;
while (ind > 0) {
sum += array[ind];
//Extracting the portion up to the first significant one of the binary representation of 'ind' and decrementing ind by that number
ind -= ind & (-ind);
}
return sum;
}
public long rsq(int a, int b) {
assert b >= a && a > 0 && b > 0;
return rsq(b) - rsq(a - 1);
}
public void update(int ind, long value) {
assert ind > 0;
while (ind < array.length) {
array[ind] += value;
//Extracting the portion up to the first significant one of the binary representation of 'ind' and incrementing ind by that number
ind += ind & (-ind);
}
}
public int size() {
return array.length - 1;
}
}
static class Point implements Comparable<Point> {
long x;
long y;
long z;
long id;
// private int hashCode;
Point() {
x = z = y = 0;
// this.hashCode = Objects.hash(x, y, cost);
}
Point(Point p) {
this.x = p.x;
this.y = p.y;
this.z = p.z;
this.id = p.id;
// this.hashCode = Objects.hash(x, y, cost);
}
Point(long x, long y, long z, long id) {
this.x = x;
this.y = y;
this.z = z;
this.id = id;
// this.hashCode = Objects.hash(x, y, id);
}
Point(long a, long b) {
this.x = a;
this.y = b;
this.z = 0;
// this.hashCode = Objects.hash(a, b);
}
Point(long x, long y, long id) {
this.x = x;
this.y = y;
this.id = id;
}
@Override
public int compareTo(Point o) {
if (this.x < o.x)
return -1;
if (this.x > o.x)
return 1;
if (this.y < o.y)
return -1;
if (this.y > o.y)
return 1;
if (this.z < o.z)
return -1;
if (this.z > o.z)
return 1;
return 0;
}
@Override
public boolean equals(Object that) {
return this.compareTo((Point) that) == 0;
}
}
static class BinaryLift {
// FUNCTIONS: k-th ancestor and LCA in log(n)
int[] parentOf;
int maxJmpPow;
int[][] binAncestorOf;
int n;
int[] lvlOf;
// How this works?
// a. For every node, we store the b-ancestor for b in {1, 2, 4, 8, .. log(n)}.
// b. When we need k-ancestor, we represent 'k' in binary and for each set bit, we
// lift level in the tree.
public BinaryLift(UGraph tree) {
n = tree.V();
maxJmpPow = logk(n, 2) + 1;
parentOf = new int[n];
binAncestorOf = new int[n][maxJmpPow];
lvlOf = new int[n];
for (int i = 0; i < n; i++)
Arrays.fill(binAncestorOf[i], -1);
parentConstruct(0, -1, tree, 0);
binConstruct();
}
// TODO: Implement lvlOf[] initialization
public BinaryLift(int[] parentOf) {
this.parentOf = parentOf;
n = parentOf.length;
maxJmpPow = logk(n, 2) + 1;
binAncestorOf = new int[n][maxJmpPow];
lvlOf = new int[n];
for (int i = 0; i < n; i++)
Arrays.fill(binAncestorOf[i], -1);
UGraph tree = new UGraph(n);
for (int i = 1; i < n; i++)
tree.addEdge(i, parentOf[i]);
binConstruct();
parentConstruct(0, -1, tree, 0);
}
private void parentConstruct(int current, int from, UGraph tree, int depth) {
parentOf[current] = from;
lvlOf[current] = depth;
for (int adj : tree.adj(current))
if (adj != from)
parentConstruct(adj, current, tree, depth + 1);
}
private void binConstruct() {
for (int node = 0; node < n; node++)
for (int lvl = 0; lvl < maxJmpPow; lvl++)
binConstruct(node, lvl);
}
private int binConstruct(int node, int lvl) {
if (node < 0)
return -1;
if (lvl == 0)
return binAncestorOf[node][lvl] = parentOf[node];
if (node == 0)
return binAncestorOf[node][lvl] = -1;
if (binAncestorOf[node][lvl] != -1)
return binAncestorOf[node][lvl];
return binAncestorOf[node][lvl] = binConstruct(binConstruct(node, lvl - 1), lvl - 1);
}
// return ancestor which is 'k' levels above this one
public int ancestor(int node, int k) {
if (node < 0)
return -1;
if (node == 0)
if (k == 0) return node;
else return -1;
if (k > (1 << maxJmpPow) - 1)
return -1;
if (k == 0)
return node;
int ancestor = node;
int highestBit = Integer.highestOneBit(k);
while (k > 0 && ancestor != -1) {
ancestor = binAncestorOf[ancestor][logk(highestBit, 2)];
k -= highestBit;
highestBit = Integer.highestOneBit(k);
}
return ancestor;
}
public int lca(int u, int v) {
if (u == v)
return u;
// The invariant will be that 'u' is below 'v' initially.
if (lvlOf[u] < lvlOf[v]) {
int temp = u;
u = v;
v = temp;
}
// Equalizing the levels.
u = ancestor(u, lvlOf[u] - lvlOf[v]);
if (u == v)
return u;
// We will now raise level by largest fitting power of two until possible.
for (int power = maxJmpPow - 1; power > -1; power--)
if (binAncestorOf[u][power] != binAncestorOf[v][power]) {
u = binAncestorOf[u][power];
v = binAncestorOf[v][power];
}
return ancestor(u, 1);
}
}
static class DFSTree {
// NOTE: The thing is made keeping in mind that the whole
// input graph is connected.
UGraph tree;
UGraph backUG;
int hasBridge;
int n;
Edge backEdge;
DFSTree(UGraph ug) {
this.n = ug.V();
tree = new UGraph(n);
hasBridge = -1;
backUG = new UGraph(n);
treeCalc(0, -1, new boolean[n], ug);
}
private void treeCalc(int current, int from, boolean[] marked, UGraph ug) {
if (marked[current]) {
// This is a backEdge.
backUG.addEdge(from, current);
backEdge = new Edge(from, current, 1, 0);
return;
}
if (from != -1)
tree.addEdge(from, current);
marked[current] = true;
for (int adj : ug.adj(current))
if (adj != from)
treeCalc(adj, current, marked, ug);
}
public boolean hasBridge() {
if (hasBridge != -1)
return (hasBridge == 1);
// We have to determine the bridge.
bridgeFinder();
return (hasBridge == 1);
}
int[] levelOf;
int[] dp;
private void bridgeFinder() {
// Finding the level of each node.
levelOf = new int[n];
levelDFS(0, -1, 0);
// Applying DP solution.
// dp[i] -> Highest level reachable from subtree of 'i' using
// some backEdge.
dp = new int[n];
Arrays.fill(dp, Integer.MAX_VALUE / 100);
dpDFS(0, -1);
// Now, we will check each edge and determine whether its a
// bridge.
for (int i = 0; i < n; i++)
for (int adj : tree.adj(i)) {
// (i -> adj) is the edge.
if (dp[adj] > levelOf[i])
hasBridge = 1;
}
if (hasBridge != 1)
hasBridge = 0;
}
private void levelDFS(int current, int from, int lvl) {
levelOf[current] = lvl;
for (int adj : tree.adj(current))
if (adj != from)
levelDFS(adj, current, lvl + 1);
}
private int dpDFS(int current, int from) {
dp[current] = levelOf[current];
for (int back : backUG.adj(current))
dp[current] = Math.min(dp[current], levelOf[back]);
for (int adj : tree.adj(current))
if (adj != from)
dp[current] = Math.min(dp[current], dpDFS(adj, current));
return dp[current];
}
}
static class UnionFind {
// Uses weighted quick-union with path compression.
private int[] parent; // parent[i] = parent of i
private int[] size; // size[i] = number of sites in tree rooted at i
// Note: not necessarily correct if i is not a root node
private int count; // number of components
public UnionFind(int n) {
count = n;
parent = new int[n];
size = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
size[i] = 1;
}
}
// Number of connected components.
public int count() {
return count;
}
// Find the root of p.
public int find(int p) {
while (p != parent[p])
p = parent[p];
return p;
}
public boolean connected(int p, int q) {
return find(p) == find(q);
}
public int numConnectedTo(int node) {
return size[find(node)];
}
// Weighted union.
public void union(int p, int q) {
int rootP = find(p);
int rootQ = find(q);
if (rootP == rootQ) return;
// make smaller root point to larger one
if (size[rootP] < size[rootQ]) {
parent[rootP] = rootQ;
size[rootQ] += size[rootP];
}
else {
parent[rootQ] = rootP;
size[rootP] += size[rootQ];
}
count--;
}
public static int[] connectedComponents(UnionFind uf) {
// We can do this in nlogn.
int n = uf.size.length;
int[] compoColors = new int[n];
for (int i = 0; i < n; i++)
compoColors[i] = uf.find(i);
HashMap<Integer, Integer> oldToNew = new HashMap<>();
int newCtr = 0;
for (int i = 0; i < n; i++) {
int thisOldColor = compoColors[i];
Integer thisNewColor = oldToNew.get(thisOldColor);
if (thisNewColor == null)
thisNewColor = newCtr++;
oldToNew.put(thisOldColor, thisNewColor);
compoColors[i] = thisNewColor;
}
return compoColors;
}
}
static class UGraph {
// Adjacency list.
private HashSet<Integer>[] adj;
private static final String NEWLINE = "\n";
private int E;
@SuppressWarnings("unchecked")
public UGraph(int V) {
adj = (HashSet<Integer>[]) new HashSet[V];
E = 0;
for (int i = 0; i < V; i++)
adj[i] = new HashSet<Integer>();
}
public void addEdge(int from, int to) {
if (adj[from].contains(to)) return;
E++;
adj[from].add(to);
adj[to].add(from);
}
public HashSet<Integer> adj(int from) {
return adj[from];
}
public int degree(int v) {
return adj[v].size();
}
public int V() {
return adj.length;
}
public int E() {
return E;
}
public String toString() {
StringBuilder s = new StringBuilder();
s.append(V() + " vertices, " + E() + " edges " + NEWLINE);
for (int v = 0; v < V(); v++) {
s.append(v + ": ");
for (int w : adj[v]) {
s.append(w + " ");
}
s.append(NEWLINE);
}
return s.toString();
}
public static void dfsMark(int current, boolean[] marked, UGraph g) {
if (marked[current]) return;
marked[current] = true;
Iterable<Integer> adj = g.adj(current);
for (int adjc : adj)
dfsMark(adjc, marked, g);
}
public static void dfsMark(int current, int from, long[] distTo, boolean[] marked, UGraph g, ArrayList<Integer> endPoints) {
if (marked[current]) return;
marked[current] = true;
if (from != -1)
distTo[current] = distTo[from] + 1;
HashSet<Integer> adj = g.adj(current);
int alreadyMarkedCtr = 0;
for (int adjc : adj) {
if (marked[adjc]) alreadyMarkedCtr++;
dfsMark(adjc, current, distTo, marked, g, endPoints);
}
if (alreadyMarkedCtr == adj.size())
endPoints.add(current);
}
public static void bfsOrder(int current, UGraph g) {
}
public static void dfsMark(int current, int[] colorIds, int color, UGraph g) {
if (colorIds[current] != -1) return;
colorIds[current] = color;
Iterable<Integer> adj = g.adj(current);
for (int adjc : adj)
dfsMark(adjc, colorIds, color, g);
}
public static int[] connectedComponents(UGraph g) {
int n = g.V();
int[] componentId = new int[n];
Arrays.fill(componentId, -1);
int colorCtr = 0;
for (int i = 0; i < n; i++) {
if (componentId[i] != -1) continue;
dfsMark(i, componentId, colorCtr, g);
colorCtr++;
}
return componentId;
}
public static boolean hasCycle(UGraph ug) {
int n = ug.V();
boolean[] marked = new boolean[n];
boolean[] hasCycleFirst = new boolean[1];
for (int i = 0; i < n; i++) {
if (marked[i]) continue;
hcDfsMark(i, ug, marked, hasCycleFirst, -1);
}
return hasCycleFirst[0];
}
// Helper for hasCycle.
private static void hcDfsMark(int current, UGraph ug, boolean[] marked, boolean[] hasCycleFirst, int parent) {
if (marked[current]) return;
if (hasCycleFirst[0]) return;
marked[current] = true;
HashSet<Integer> adjc = ug.adj(current);
for (int adj : adjc) {
if (marked[adj] && adj != parent && parent != -1) {
hasCycleFirst[0] = true;
return;
}
hcDfsMark(adj, ug, marked, hasCycleFirst, current);
}
}
}
static class Digraph {
// Adjacency list.
private HashSet<Integer>[] adj;
private static final String NEWLINE = "\n";
private int E;
@SuppressWarnings("unchecked")
public Digraph(int V) {
adj = (HashSet<Integer>[]) new HashSet[V];
E = 0;
for (int i = 0; i < V; i++)
adj[i] = new HashSet<Integer>();
}
public void addEdge(int from, int to) {
if (adj[from].contains(to)) return;
E++;
adj[from].add(to);
}
public HashSet<Integer> adj(int from) {
return adj[from];
}
public int V() {
return adj.length;
}
public int E() {
return E;
}
public Digraph reversed() {
Digraph dg = new Digraph(V());
for (int i = 0; i < V(); i++)
for (int adjVert : adj(i)) dg.addEdge(adjVert, i);
return dg;
}
public String toString() {
StringBuilder s = new StringBuilder();
s.append(V() + " vertices, " + E() + " edges " + NEWLINE);
for (int v = 0; v < V(); v++) {
s.append(v + ": ");
for (int w : adj[v]) {
s.append(w + " ");
}
s.append(NEWLINE);
}
return s.toString();
}
public static int[] KosarajuSharirSCC(Digraph dg) {
int[] id = new int[dg.V()];
Digraph reversed = dg.reversed();
// Gotta perform topological sort on this one to get the stack.
Stack<Integer> revStack = Digraph.topologicalSort(reversed);
// Initializing id and idCtr.
id = new int[dg.V()];
int idCtr = -1;
// Creating a 'marked' array.
boolean[] marked = new boolean[dg.V()];
while (!revStack.isEmpty()) {
int vertex = revStack.pop();
if (!marked[vertex])
sccDFS(dg, vertex, marked, ++idCtr, id);
}
return id;
}
private static void sccDFS(Digraph dg, int source, boolean[] marked, int idCtr, int[] id) {
marked[source] = true;
id[source] = idCtr;
for (Integer adjVertex : dg.adj(source))
if (!marked[adjVertex]) sccDFS(dg, adjVertex, marked, idCtr, id);
}
public static Stack<Integer> topologicalSort(Digraph dg) {
// dg has to be a directed acyclic graph.
// We'll have to run dfs on the digraph and push the deepest nodes on stack first.
// We'll need a Stack<Integer> and a int[] marked.
Stack<Integer> topologicalStack = new Stack<Integer>();
boolean[] marked = new boolean[dg.V()];
// Calling dfs
for (int i = 0; i < dg.V(); i++)
if (!marked[i])
runDfs(dg, topologicalStack, marked, i);
return topologicalStack;
}
static void runDfs(Digraph dg, Stack<Integer> topologicalStack, boolean[] marked, int source) {
marked[source] = true;
for (Integer adjVertex : dg.adj(source))
if (!marked[adjVertex])
runDfs(dg, topologicalStack, marked, adjVertex);
topologicalStack.add(source);
}
}
static class FastReader {
private BufferedReader bfr;
private StringTokenizer st;
public FastReader() {
bfr = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
if (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(bfr.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());
}
char nextChar() {
return next().toCharArray()[0];
}
String nextString() {
return next();
}
int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = nextInt();
return arr;
}
double[] nextDoubleArray(int n) {
double[] arr = new double[n];
for (int i = 0; i < arr.length; i++)
arr[i] = nextDouble();
return arr;
}
long[] nextLongArray(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++)
arr[i] = nextLong();
return arr;
}
int[][] nextIntGrid(int n, int m) {
int[][] grid = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++)
grid[i][j] = fr.nextInt();
}
return grid;
}
}
@SuppressWarnings("serial")
static class CountMap<T> extends TreeMap<T, Integer>{
CountMap() {
}
CountMap(Comparator<T> cmp) {
}
CountMap(T[] arr) {
this.putCM(arr);
}
public Integer putCM(T key) {
return super.put(key, super.getOrDefault(key, 0) + 1);
}
public Integer removeCM(T key) {
int count = super.getOrDefault(key, -1);
if (count == -1) return -1;
if (count == 1)
return super.remove(key);
else
return super.put(key, count - 1);
}
public Integer getCM(T key) {
return super.getOrDefault(key, 0);
}
public void putCM(T[] arr) {
for (T l : arr)
this.putCM(l);
}
}
static long dioGCD(long a, long b, long[] x0, long[] y0) {
if (b == 0) {
x0[0] = 1;
y0[0] = 0;
return a;
}
long[] x1 = new long[1], y1 = new long[1];
long d = dioGCD(b, a % b, x1, y1);
x0[0] = y1[0];
y0[0] = x1[0] - y1[0] * (a / b);
return d;
}
static boolean diophantine(long a, long b, long c, long[] x0, long[] y0, long[] g) {
g[0] = dioGCD(Math.abs(a), Math.abs(b), x0, y0);
if (c % g[0] > 0) {
return false;
}
x0[0] *= c / g[0];
y0[0] *= c / g[0];
if (a < 0) x0[0] = -x0[0];
if (b < 0) y0[0] = -y0[0];
return true;
}
static long[][] prod(long[][] mat1, long[][] mat2) {
int n = mat1.length;
long[][] prod = new long[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
// determining prod[i][j]
// it will be the dot product of mat1[i][] and mat2[][i]
for (int k = 0; k < n; k++)
prod[i][j] += mat1[i][k] * mat2[k][j];
return prod;
}
static long[][] matExpo(long[][] mat, long power) {
int n = mat.length;
long[][] ans = new long[n][n];
if (power == 0)
return null;
if (power == 1)
return mat;
long[][] half = matExpo(mat, power / 2);
ans = prod(half, half);
if (power % 2 == 1) {
ans = prod(ans, mat);
}
return ans;
}
static int KMPNumOcc(char[] text, char[] pat) {
int n = text.length;
int m = pat.length;
char[] patPlusText = new char[n + m + 1];
for (int i = 0; i < m; i++)
patPlusText[i] = pat[i];
patPlusText[m] = '^'; // Seperator
for (int i = 0; i < n; i++)
patPlusText[m + i] = text[i];
int[] fullPi = piCalcKMP(patPlusText);
int answer = 0;
for (int i = 0; i < n + m + 1; i++)
if (fullPi[i] == m)
answer++;
return answer;
}
static int[] piCalcKMP(char[] s) {
int n = s.length;
int[] pi = new int[n];
for (int i = 1; i < n; i++) {
int j = pi[i - 1];
while (j > 0 && s[i] != s[j])
j = pi[j - 1];
if (s[i] == s[j])
j++;
pi[i] = j;
}
return pi;
}
static boolean[] prefMatchesSuff(char[] s) {
int n = s.length;
boolean[] res = new boolean[n + 1];
int[] pi = prefix_function(s);
res[0] = true;
for (int p = n; p != 0; p = pi[p])
res[p] = true;
return res;
}
static int[] prefix_function(char[] s) {
int n = s.length;
int[] pi = new int[n];
for (int i = 1; i < n; i++) {
int j = pi[i-1];
while (j > 0 && s[i] != s[j])
j = pi[j-1];
if (s[i] == s[j])
j++;
pi[i] = j;
}
return pi;
}
static long hash(long key) {
long h = Long.hashCode(key);
h ^= (h >>> 20) ^ (h >>> 12) ^ (h >>> 7) ^ (h >>> 4);
return h & (gigamod-1);
}
static void Yes() {out.println("Yes");}static void YES() {out.println("YES");}static void yes() {out.println("Yes");}static void No() {out.println("No");}static void NO() {out.println("NO");}static void no() {out.println("no");}
static int mapTo1D(int row, int col, int n, int m) {
// Maps elements in a 2D matrix serially to elements in
// a 1D array.
return row * m + col;
}
static int[] mapTo2D(int idx, int n, int m) {
// Inverse of what the one above does.
int[] rnc = new int[2];
rnc[0] = idx / m;
rnc[1] = idx % m;
return rnc;
}
static long mapTo1D(long row, long col, long n, long m) {
// Maps elements in a 2D matrix serially to elements in
// a 1D array.
return row * m + col;
}
static boolean[] primeGenerator(int upto) {
// Sieve of Eratosthenes:
isPrime = new boolean[upto + 1];
smallestFactorOf = new int[upto + 1];
Arrays.fill(smallestFactorOf, 1);
Arrays.fill(isPrime, true);
isPrime[1] = isPrime[0] = false;
for (long i = 2; i < upto + 1; i++)
if (isPrime[(int) i]) {
smallestFactorOf[(int) i] = (int) i;
// Mark all the multiples greater than or equal
// to the square of i to be false.
for (long j = i; j * i < upto + 1; j++) {
if (isPrime[(int) j * (int) i]) {
isPrime[(int) j * (int) i] = false;
smallestFactorOf[(int) j * (int) i] = (int) i;
}
}
}
return isPrime;
}
static HashMap<Integer, Integer> smolNumPrimeFactorization(int num) {
if (smallestFactorOf == null)
primeGenerator(num + 1);
HashMap<Integer, Integer> fnps = new HashMap<>();
while (num != 1) {
fnps.put(smallestFactorOf[num], fnps.getOrDefault(smallestFactorOf[num], 0) + 1);
num /= smallestFactorOf[num];
}
return fnps;
}
static HashMap<Long, Integer> primeFactorization(long num) {
// Returns map of factor and its power in the number.
HashMap<Long, Integer> map = new HashMap<>();
while (num % 2 == 0) {
num /= 2;
Integer pwrCnt = map.get(2L);
map.put(2L, pwrCnt != null ? pwrCnt + 1 : 1);
}
for (long i = 3; i * i <= num; i += 2) {
while (num % i == 0) {
num /= i;
Integer pwrCnt = map.get(i);
map.put(i, pwrCnt != null ? pwrCnt + 1 : 1);
}
}
// If the number is prime, we have to add it to the
// map.
if (num != 1)
map.put(num, 1);
return map;
}
static HashSet<Long> divisors(long num) {
HashSet<Long> divisors = new HashSet<Long>();
divisors.add(1L);
divisors.add(num);
for (long i = 2; i * i <= num; i++) {
if (num % i == 0) {
divisors.add(num/i);
divisors.add(i);
}
}
return divisors;
}
static void coprimeGenerator(int m, int n, ArrayList<Point> coprimes, int limit, int numCoprimes) {
if (m > limit) return;
if (m <= limit && n <= limit)
coprimes.add(new Point(m, n));
if (coprimes.size() > numCoprimes) return;
coprimeGenerator(2 * m - n, m, coprimes, limit, numCoprimes);
coprimeGenerator(2 * m + n, m, coprimes, limit, numCoprimes);
coprimeGenerator(m + 2 * n, n, coprimes, limit, numCoprimes);
}
static long nCr(long n, long r, long[] fac) { long p = gigamod; if (r == 0) return 1; return (fac[(int)n] * modInverse(fac[(int)r], p) % p * modInverse(fac[(int)n - (int)r], p) % p) % p; }
static long modInverse(long n, long p) { return power(n, p - 2, p); }
static long modDiv(long a, long b){return mod(a * power(b, mod - 2, mod), mod);}
static long power(long x, long y, long p) { long res = 1; x = x % p; while (y > 0) { if ((y & 1)==1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; }
static int logk(long n, long k) { return (int)(Math.log(n) / Math.log(k)); }
static long gcd(long a, long b) { if (b == 0) { return a; } else { return gcd(b, a % b); } } static int gcd(int a, int b) { if (b == 0) { return a; } else { return gcd(b, a % b); } } static long gcd(long[] arr) { int n = arr.length; long gcd = arr[0]; for (int i = 1; i < n; i++) { gcd = gcd(gcd, arr[i]); } return gcd; } static int gcd(int[] arr) { int n = arr.length; int gcd = arr[0]; for (int i = 1; i < n; i++) { gcd = gcd(gcd, arr[i]); } return gcd; } static long lcm(long[] arr) { long lcm = arr[0]; int n = arr.length; for (int i = 1; i < n; i++) { lcm = (lcm * arr[i]) / gcd(lcm, arr[i]); } return lcm; } static long lcm(long a, long b) { return (a * b)/gcd(a, b); } static boolean less(int a, int b) { return a < b ? true : false; } static boolean isSorted(int[] a) { for (int i = 1; i < a.length; i++) { if (less(a[i], a[i - 1])) return false; } return true; } static boolean isSorted(long[] a) { for (int i = 1; i < a.length; i++) { if (a[i] < a[i - 1]) return false; } return true; } static void swap(int[] a, int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } static void swap(long[] a, int i, int j) { long temp = a[i]; a[i] = a[j]; a[j] = temp; } static void swap(double[] a, int i, int j) { double temp = a[i]; a[i] = a[j]; a[j] = temp; } static void swap(char[] a, int i, int j) { char temp = a[i]; a[i] = a[j]; a[j] = temp; }
static void sort(int[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void sort(char[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void sort(long[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void sort(double[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void reverseSort(int[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void reverseSort(char[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void reverse(char[] arr) { int n = arr.length; for (int i = 0; i < n / 2; i++) swap(arr, i, n - 1 - i); } static void reverseSort(long[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void reverseSort(double[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); }
static void shuffleArray(long[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { long tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } static void shuffleArray(int[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { int tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } }
static void shuffleArray(double[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { double tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } }
static void shuffleArray(char[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { char tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } }
static boolean isPrime(long n) {if (n<=1)return false;if(n<=3)return true;if(n%2==0||n%3==0)return false;for(long i=5;i*i<=n;i=i+6)if(n%i==0||n%(i+2)==0)return false;return true;}
static String toString(int[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+" ");return sb.toString();}
static String toString(boolean[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+" ");return sb.toString();}
static String toString(long[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+" ");return sb.toString();}
static String toString(char[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+"");return sb.toString();}
static String toString(int[][] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++){for(int j=0;j<dp[i].length;j++){sb.append(dp[i][j]+" ");}sb.append('\n');}return sb.toString();}
static String toString(long[][] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++){for(int j=0;j<dp[i].length;j++) {sb.append(dp[i][j]+" ");}sb.append('\n');}return sb.toString();}
static String toString(double[][] dp){StringBuilder sb=new StringBuilder();for(int i = 0;i<dp.length;i++){for(int j = 0;j<dp[i].length;j++){sb.append(dp[i][j]+" ");}sb.append('\n');}return sb.toString();}
static String toString(char[][] dp){StringBuilder sb = new StringBuilder();for(int i = 0;i<dp.length;i++){for(int j = 0;j<dp[i].length;j++){sb.append(dp[i][j]+"");}sb.append('\n');}return sb.toString();}
static long mod(long a, long m){return(a%m+1000000L*m)%m;}
}
/*
*
* int[] arr = new int[] {1810, 1700, 1710, 2320, 2000, 1785, 1780
, 2130, 2185, 1430, 1460, 1740, 1860, 1100, 1905, 1650};
int n = arr.length;
sort(arr);
int bel1700 = 0, bet1700n1900 = 0, abv1900 = 0;
for (int i = 0; i < n; i++)
if (arr[i] < 1700)
bel1700++;
else if (1700 <= arr[i] && arr[i] < 1900)
bet1700n1900++;
else if (arr[i] >= 1900)
abv1900++;
out.println("COUNT: " + n);
out.println("PERFS: " + toString(arr));
out.println("MEDIAN: " + arr[n / 2]);
out.println("AVERAGE: " + Arrays.stream(arr).average().getAsDouble());
out.println("[0, 1700): " + bel1700 + "/" + n);
out.println("[1700, 1900): " + bet1700n1900 + "/" + n);
out.println("[1900, 2400): " + abv1900 + "/" + n);
*
* */
// NOTES:
// ASCII VALUE OF 'A': 65
// ASCII VALUE OF 'a': 97
// Range of long: 9 * 10^18
// ASCII VALUE OF '0': 48
// Primes upto 'n' can be given by (n / (logn)). | java |
1303 | B | B. National Projecttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour company was appointed to lay new asphalt on the highway of length nn. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are gg days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next bb days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again gg good days, bb bad days and so on.You can be sure that you start repairing at the start of a good season, in other words, days 1,2,…,g1,2,…,g are good.You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the n=5n=5 then at least 33 units of the highway should have high quality; if n=4n=4 then at least 22 units should have high quality.What is the minimum number of days is needed to finish the repair of the whole highway?InputThe first line contains a single integer TT (1≤T≤1041≤T≤104) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains three integers nn, gg and bb (1≤n,g,b≤1091≤n,g,b≤109) — the length of the highway and the number of good and bad days respectively.OutputPrint TT integers — one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.ExampleInputCopy3
5 1 1
8 10 10
1000000 1 1000000
OutputCopy5
8
499999500000
NoteIn the first test case; you can just lay new asphalt each day; since days 1,3,51,3,5 are good.In the second test case, you can also lay new asphalt each day, since days 11-88 are good. | [
"math"
] | import java.awt.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.*;
import java.util.List;
public class nationalproject{
static int mod = (int) 1e9 + 7;
static int[][] shows;
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0) {
long n=sc.nextInt(),g=sc.nextInt(),b=sc.nextInt();
long x=(long)Math.ceil(n/(2.0*g));
if((x-1)*b<=n-x*g) System.out.println(n);
else System.out.println((long)Math.ceil(n/2.0)+Math.max((x-1)*b,n-(long)Math.ceil(n/2.0)));
}
}
} | java |
1315 | C | C. Restoring Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence b1,b2,…,bnb1,b2,…,bn. Find the lexicographically minimal permutation a1,a2,…,a2na1,a2,…,a2n such that bi=min(a2i−1,a2i)bi=min(a2i−1,a2i), or determine that it is impossible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1001≤t≤100).The first line of each test case consists of one integer nn — the number of elements in the sequence bb (1≤n≤1001≤n≤100).The second line of each test case consists of nn different integers b1,…,bnb1,…,bn — elements of the sequence bb (1≤bi≤2n1≤bi≤2n).It is guaranteed that the sum of nn by all test cases doesn't exceed 100100.OutputFor each test case, if there is no appropriate permutation, print one number −1−1.Otherwise, print 2n2n integers a1,…,a2na1,…,a2n — required lexicographically minimal permutation of numbers from 11 to 2n2n.ExampleInputCopy5
1
1
2
4 1
3
4 1 3
4
2 3 4 5
5
1 5 7 2 8
OutputCopy1 2
-1
4 5 1 2 3 6
-1
1 3 5 6 7 9 2 4 8 10
| [
"greedy"
] | import java.util.*;
public class Restoring_Permutation {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-->0) {
int n = sc.nextInt();
int b[] = new int[n];
HashSet<Integer> set = new HashSet<>();
int grt = 0;
for(int i=0;i<n;i++) {
b[i] = sc.nextInt();
if(b[i]>n)
grt++;
set.add(b[i]);
}
if(set.contains(2*n)||!set.contains(1)||grt>n/2)
System.out.println(-1);
else {
StringBuilder sb = new StringBuilder();
for(int i=0;i<n;i++) {
for(int j=b[i]+1;j<=2*n;j++) {
if(set.contains(j))
continue;
else {
sb.append(b[i]+" "+j+" ");
set.add(j);
break;
}
}
}
if(set.size()!=2*n) {
System.out.println(-1);
}else {
System.out.println(sb);
}
}
}
}
}
| java |
1290 | A | A. Mind Controltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou and your n−1n−1 friends have found an array of integers a1,a2,…,ana1,a2,…,an. You have decided to share it in the following way: All nn of you stand in a line in a particular order. Each minute, the person at the front of the line chooses either the first or the last element of the array, removes it, and keeps it for himself. He then gets out of line, and the next person in line continues the process.You are standing in the mm-th position in the line. Before the process starts, you may choose up to kk different people in the line, and persuade them to always take either the first or the last element in the array on their turn (for each person his own choice, not necessarily equal for all people), no matter what the elements themselves are. Once the process starts, you cannot persuade any more people, and you cannot change the choices for the people you already persuaded.Suppose that you're doing your choices optimally. What is the greatest integer xx such that, no matter what are the choices of the friends you didn't choose to control, the element you will take from the array will be greater than or equal to xx?Please note that the friends you don't control may do their choice arbitrarily, and they will not necessarily take the biggest element available.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000) — the number of test cases. The description of the test cases follows.The first line of each test case contains three space-separated integers nn, mm and kk (1≤m≤n≤35001≤m≤n≤3500, 0≤k≤n−10≤k≤n−1) — the number of elements in the array, your position in line and the number of people whose choices you can fix.The second line of each test case contains nn positive integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109) — elements of the array.It is guaranteed that the sum of nn over all test cases does not exceed 35003500.OutputFor each test case, print the largest integer xx such that you can guarantee to obtain at least xx.ExampleInputCopy4
6 4 2
2 9 2 3 8 5
4 4 1
2 13 60 4
4 1 3
1 2 2 1
2 2 0
1 2
OutputCopy8
4
1
1
NoteIn the first test case; an optimal strategy is to force the first person to take the last element and the second person to take the first element. the first person will take the last element (55) because he or she was forced by you to take the last element. After this turn the remaining array will be [2,9,2,3,8][2,9,2,3,8]; the second person will take the first element (22) because he or she was forced by you to take the first element. After this turn the remaining array will be [9,2,3,8][9,2,3,8]; if the third person will choose to take the first element (99), at your turn the remaining array will be [2,3,8][2,3,8] and you will take 88 (the last element); if the third person will choose to take the last element (88), at your turn the remaining array will be [9,2,3][9,2,3] and you will take 99 (the first element). Thus, this strategy guarantees to end up with at least 88. We can prove that there is no strategy that guarantees to end up with at least 99. Hence, the answer is 88.In the second test case, an optimal strategy is to force the first person to take the first element. Then, in the worst case, both the second and the third person will take the first element: you will end up with 44. | [
"brute force",
"data structures",
"implementation"
] | import java.util.*;
import java.io.*;
public class MindControl {
PrintWriter out;
StringTokenizer st;
BufferedReader br;
final int imax = Integer.MAX_VALUE, imin = Integer.MIN_VALUE;
final int mod = 1000000007;
void solve() throws Exception {
int t = 1;
t = ni();
for (int ii = 0; ii < t; ii++) {
int n= ni(), m= ni(), k= ni(), max= imin;
int[] a= ni(n);
k= Math.min(k, m-1);
for (int i = 0; i <=k ; i++) {
// out.println(i+" "+(n-(k-i)));
max= Math.max(max, helper(a, i, n-(k-i), m-k-1));
}
out.println(max);
}
}
private int helper(int[] a, int start, int last, int left) {
int ret= imax;
for (int i = 0; i <= left; i++) {
ret= Math.min(ret, Math.max(a[start+ i], a[last- left+ i-1]));
}
// out.println(ret);
// out.println();
return ret;
}
public static void main(String[] args) throws Exception {
new MindControl().run();
}
void run() throws Exception {
if (System.getProperty("ONLINE_JUDGE") == null) {
File file = new File("C:\\college\\CodeForces\\inputf.txt");
br = new BufferedReader(new FileReader(file));
out = new PrintWriter("C:\\college\\CodeForces\\outputf.txt");
} else {
out = new PrintWriter(System.out);
br = new BufferedReader(new InputStreamReader(System.in));
}
long ss = System.currentTimeMillis();
st = new StringTokenizer("");
while (true) {
solve();
String s = br.readLine();
if (s == null) break;
else st = new StringTokenizer(s);
}
//out.println(System.currentTimeMillis()-ss+"ms");
out.flush();
}
void read() throws Exception {
st = new StringTokenizer(br.readLine());
}
int ni() throws Exception {
if (!st.hasMoreTokens()) read();
return Integer.parseInt(st.nextToken());
}
char nc() throws Exception {
if (!st.hasMoreTokens()) read();
return st.nextToken().charAt(0);
}
String nw() throws Exception {
if (!st.hasMoreTokens()) read();
return st.nextToken();
}
long nl() throws Exception {
if (!st.hasMoreTokens()) read();
return Long.parseLong(st.nextToken());
}
int[] ni(int n) throws Exception {
int[] ret = new int[n];
for (int i = 0; i < n; i++) ret[i] = ni();
return ret;
}
long[] nl(int n) throws Exception {
long[] ret = new long[n];
for (int i = 0; i < n; i++) ret[i] = nl();
return ret;
}
double nd() throws Exception {
if (!st.hasMoreTokens()) read();
return Double.parseDouble(st.nextToken());
}
String ns() throws Exception {
String s = br.readLine();
return s.length() == 0 ? br.readLine() : s;
}
void print(int[] arr) {
for (int i : arr) out.print(i + " ");
out.println();
}
void print(long[] arr) {
for (long i : arr) out.print(i + " ");
out.println();
}
void print(int[][] arr) {
for (int[] i : arr) {
for (int j : i) out.print(j + " ");
out.println();
}
}
void print(long[][] arr) {
for (long[] i : arr) {
for (long j : i) out.print(j + " ");
out.println();
}
}
long add(long a, long b) {
if (a + b >= mod) return (a + b) - mod;
else return a + b >= 0 ? a + b : a + b + mod;
}
long mul(long a, long b) {
return (a * b) % mod;
}
void print(boolean b) {
if (b) out.println("YES");
else out.println("NO");
}
long binExp(long base, long power) {
long res = 1l;
while (power != 0) {
if ((power & 1) == 1) res = mul(res, base);
base = mul(base, base);
power >>= 1;
}
return res;
}
long gcd(long a, long b) {
if (b == 0) return a;
else return gcd(b, a % b);
}
// strictly smaller on left
void stack_l(int[] arr, int[] left) {
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < arr.length; i++) {
while (!stack.isEmpty() && arr[stack.peek()] >= arr[i]) stack.pop();
if (stack.isEmpty()) left[i] = -1;
else left[i] = stack.peek();
stack.push(i);
}
}
// strictly smaller on right
void stack_r(int[] arr, int[] right) {
Stack<Integer> stack = new Stack<>();
for (int i = arr.length - 1; i >= 0; i--) {
while (!stack.isEmpty() && arr[stack.peek()] >= arr[i]) stack.pop();
if (stack.isEmpty()) right[i] = arr.length;
else right[i] = stack.peek();
stack.push(i);
}
}
private void sort(int[] arr) {
List<Integer> list = new ArrayList<>();
for (int i : arr) list.add(i);
Collections.sort(list);
for (int i = 0; i < arr.length; i++) arr[i] = list.get(i);
}
} | java |
1301 | A | A. Three Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three strings aa, bb and cc of the same length nn. The strings consist of lowercase English letters only. The ii-th letter of aa is aiai, the ii-th letter of bb is bibi, the ii-th letter of cc is cici.For every ii (1≤i≤n1≤i≤n) you must swap (i.e. exchange) cici with either aiai or bibi. So in total you'll perform exactly nn swap operations, each of them either ci↔aici↔ai or ci↔bici↔bi (ii iterates over all integers between 11 and nn, inclusive).For example, if aa is "code", bb is "true", and cc is "help", you can make cc equal to "crue" taking the 11-st and the 44-th letters from aa and the others from bb. In this way aa becomes "hodp" and bb becomes "tele".Is it possible that after these swaps the string aa becomes exactly the same as the string bb?InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1001≤t≤100) — the number of test cases. The description of the test cases follows.The first line of each test case contains a string of lowercase English letters aa.The second line of each test case contains a string of lowercase English letters bb.The third line of each test case contains a string of lowercase English letters cc.It is guaranteed that in each test case these three strings are non-empty and have the same length, which is not exceeding 100100.OutputPrint tt lines with answers for all test cases. For each test case:If it is possible to make string aa equal to string bb print "YES" (without quotes), otherwise print "NO" (without quotes).You can print either lowercase or uppercase letters in the answers.ExampleInputCopy4
aaa
bbb
ccc
abc
bca
bca
aabb
bbaa
baba
imi
mii
iim
OutputCopyNO
YES
YES
NO
NoteIn the first test case; it is impossible to do the swaps so that string aa becomes exactly the same as string bb.In the second test case, you should swap cici with aiai for all possible ii. After the swaps aa becomes "bca", bb becomes "bca" and cc becomes "abc". Here the strings aa and bb are equal.In the third test case, you should swap c1c1 with a1a1, c2c2 with b2b2, c3c3 with b3b3 and c4c4 with a4a4. Then string aa becomes "baba", string bb becomes "baba" and string cc becomes "abab". Here the strings aa and bb are equal.In the fourth test case, it is impossible to do the swaps so that string aa becomes exactly the same as string bb. | [
"implementation",
"strings"
] | import java.util.Arrays;
import java.util.Scanner;
public class ThreeStrings {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int t = input.nextInt();
boolean[] ans = new boolean[t];
Arrays.fill(ans, true);
for (int i = 0; i < t; i++) {
String a = input.next();
String b = input.next();
String c = input.next();
for (int j = 0; j < a.length(); j++) {
if (c.charAt(j) != a.charAt(j) && c.charAt(j) != b.charAt(j)) {
ans[i] = false;
break;
}
}
}
for (int i = 0; i < t; i++) {
if (ans[i]) System.out.println("YES");
else System.out.println("NO");
}
}
}
| java |
1307 | E | E. Cow and Treatstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a successful year of milk production; Farmer John is rewarding his cows with their favorite treat: tasty grass!On the field, there is a row of nn units of grass, each with a sweetness sisi. Farmer John has mm cows, each with a favorite sweetness fifi and a hunger value hihi. He would like to pick two disjoint subsets of cows to line up on the left and right side of the grass row. There is no restriction on how many cows must be on either side. The cows will be treated in the following manner: The cows from the left and right side will take turns feeding in an order decided by Farmer John. When a cow feeds, it walks towards the other end without changing direction and eats grass of its favorite sweetness until it eats hihi units. The moment a cow eats hihi units, it will fall asleep there, preventing further cows from passing it from both directions. If it encounters another sleeping cow or reaches the end of the grass row, it will get upset. Farmer John absolutely does not want any cows to get upset. Note that grass does not grow back. Also, to prevent cows from getting upset, not every cow has to feed since FJ can choose a subset of them. Surprisingly, FJ has determined that sleeping cows are the most satisfied. If FJ orders optimally, what is the maximum number of sleeping cows that can result, and how many ways can FJ choose the subset of cows on the left and right side to achieve that maximum number of sleeping cows (modulo 109+7109+7)? The order in which FJ sends the cows does not matter as long as no cows get upset. InputThe first line contains two integers nn and mm (1≤n≤50001≤n≤5000, 1≤m≤50001≤m≤5000) — the number of units of grass and the number of cows. The second line contains nn integers s1,s2,…,sns1,s2,…,sn (1≤si≤n1≤si≤n) — the sweetness values of the grass.The ii-th of the following mm lines contains two integers fifi and hihi (1≤fi,hi≤n1≤fi,hi≤n) — the favorite sweetness and hunger value of the ii-th cow. No two cows have the same hunger and favorite sweetness simultaneously.OutputOutput two integers — the maximum number of sleeping cows that can result and the number of ways modulo 109+7109+7. ExamplesInputCopy5 2
1 1 1 1 1
1 2
1 3
OutputCopy2 2
InputCopy5 2
1 1 1 1 1
1 2
1 4
OutputCopy1 4
InputCopy3 2
2 3 2
3 1
2 1
OutputCopy2 4
InputCopy5 1
1 1 1 1 1
2 5
OutputCopy0 1
NoteIn the first example; FJ can line up the cows as follows to achieve 22 sleeping cows: Cow 11 is lined up on the left side and cow 22 is lined up on the right side. Cow 22 is lined up on the left side and cow 11 is lined up on the right side. In the second example, FJ can line up the cows as follows to achieve 11 sleeping cow: Cow 11 is lined up on the left side. Cow 22 is lined up on the left side. Cow 11 is lined up on the right side. Cow 22 is lined up on the right side. In the third example, FJ can line up the cows as follows to achieve 22 sleeping cows: Cow 11 and 22 are lined up on the left side. Cow 11 and 22 are lined up on the right side. Cow 11 is lined up on the left side and cow 22 is lined up on the right side. Cow 11 is lined up on the right side and cow 22 is lined up on the left side. In the fourth example, FJ cannot end up with any sleeping cows, so there will be no cows lined up on either side. | [
"binary search",
"combinatorics",
"dp",
"greedy",
"implementation",
"math"
] | import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.StringTokenizer;
public class E {
public static void main(String[] args) {
var scanner = new BufferedScanner();
var writer = new PrintWriter(new BufferedOutputStream(System.out));
var n = scanner.nextInt();
var m = scanner.nextInt();
var s = new int[n + 1];
for (int i = 1; i <= n; i++) {
s[i] = scanner.nextInt();
}
var f = new int[m + 1];
var h = new int[m + 1];
for (int i = 1; i <= m; i++) {
f[i] = scanner.nextInt();
h[i] = scanner.nextInt();
}
var ans = solve(n, m, s, f, h);
writer.println(ans[0] + " " + ans[1]);
scanner.close();
writer.flush();
writer.close();
}
static final int MODULO = (int) (1e9 + 7);
static class IntList extends ArrayList<Integer> {}
private static int[] solve(int n, int m, int[] s, int[] f, int[] h) {
var sleepL = new int[m + 1];
var sleepR = new int[m + 1];
var byFH = new HashMap<Integer, Integer>() {
public Integer get(int f, int h) {
return get(hash(f, h));
}
void put(int f, int h, int i) {
put(hash(f, h), i);
}
private int hash(int f, int h) {
return f * (n + 1) + h;
}
};
for (int i = 1; i <= m; i++) {
byFH.put(f[i], h[i], i);
}
{
var countS = new int[n + 1];
for (int i = 1; i <= n; i++) {
countS[s[i]]++;
var cow = byFH.get(s[i], countS[s[i]]);
if (cow != null) {
sleepL[cow] = i;
}
}
Arrays.fill(countS, 0);
for (int i = n; i >= 1; i--) {
countS[s[i]]++;
var cow = byFH.get(s[i], countS[s[i]]);
if (cow != null) {
sleepR[cow] = i;
}
}
}
var bySweet = new HashMap<Integer, List<Integer>>();
for (int i = 1; i <= m; i++) {
bySweet.putIfAbsent(f[i], new ArrayList<>());
bySweet.get(f[i]).add(i);
}
var sweets = bySweet.keySet().stream().mapToInt(i -> i).toArray();
var maxCows = Integer.MIN_VALUE;
var maxWays = Long.MIN_VALUE;
// first==0表示左边不选;first一定要用在左边,这样避免计数重复
for (int first = 0; first <= m; first++) {
var leftStart = 1;
var leftEnd = sleepL[first]; // increasing
var rightStart = leftEnd + 1; // increasing
var rightEnd = n;
if (first != 0 && (sleepL[first] < leftStart || sleepL[first] > leftEnd)) {
continue;
}
var cows = 0;
var ways = 1L;
var lefts = new int[n + 1];
var rights = new int[n + 1];
var boths = new int[n + 1];
for (int i = 1; i <= m; i++) {
var t = 0;
if (sleepL[i] >= leftStart && sleepL[i] <= leftEnd) {
lefts[f[i]]++;
t++;
}
if (i == first) {
continue;
}
if (sleepR[i] >= rightStart && sleepR[i] <= rightEnd) {
rights[f[i]]++;
t++;
}
if (t == 2) {
boths[f[i]]++;
lefts[f[i]]--;
rights[f[i]]--;
}
}
for (int sweet : sweets) {
// var left = 0L;
// var right = 0L;
// var both = 0L;
// for (var i : bySweetL[sweet]) {
// var t = 0;
// if (sleepL[i] >= leftStart && sleepL[i] <= leftEnd) {
// left++;
// t++;
// }
// if (i == first) { // first一定在左边
// continue;
// }
// if (sleepR[i] >= rightStart && sleepR[i] <= rightEnd) {
// right++;
// t++;
// }
// if (t == 2) {
// both++;
// left--;
// right--;
// }
// }
var left = lefts[sweet];
var right = rights[sweet];
var both = boths[sweet];
if (sweet == f[first]) {
left = 1; // left被first占据了
}
if (left + right + both == 0) {
continue;
}
long thisWays;
if (sweet == f[first]) {
thisWays = right + both;
} else {
// 尝试任意放两个
thisWays = left * (right + both) + both * (right + both - 1);
}
if (thisWays > 0) {
cows += 2;
ways = (ways * thisWays) % MODULO;
continue;
}
cows++;
// 放一个的方案
thisWays = left + right + both * 2;
ways = (ways * thisWays) % MODULO;
}
if (cows > maxCows) {
maxCows = cows;
maxWays = ways;
} else if (cows == maxCows && cows > 0) {
maxWays = (maxWays + ways) % MODULO;
}
}
return new int[]{maxCows, (int) maxWays};
}
private static void check(boolean predicate, String fmt, Object... args) {
if (!predicate) {
throw new RuntimeException(String.format(fmt, args));
}
}
/**
* @param a ascending ordered array
* @param k key to find
* @param ks key function
* @param gt true for gt/gte, false for lt/lte
* @param e true for equal, false for unequal
* @return min i for gt/gte, max i for lt/lte
*/
private static int binarySearch(int[] a, int k, int[] ks, boolean gt, boolean e) {
var l = 0;
var r = a.length - 1;
var ans = gt ? Integer.MAX_VALUE : Integer.MIN_VALUE;
while (l <= r) {
var m = (l + r) / 2;
var km = ks[a[m]];
if (gt) { // find min i that a[i]>=/>k
if (e && km >= k || km > k) {
ans = Math.min(ans, m);
r = m - 1;
} else { // a[m]</<=k
l = m + 1;
}
} else { // find max i that a[i]<=/<k
if (e && km <= k || km < k) {
ans = Math.max(ans, m);
l = m + 1;
} else { // a[m]>/>=k
r = m - 1;
}
}
}
return ans == Integer.MAX_VALUE ? Integer.MIN_VALUE : ans;
}
public static class BufferedScanner {
BufferedReader br;
StringTokenizer st;
public BufferedScanner(Reader reader) {
br = new BufferedReader(reader);
}
public BufferedScanner() {
this(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
void close() {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
static long gcd(long a, long b) {
if (a < b) {
return gcd(b, a);
}
while (b > 0) {
long tmp = b;
b = a % b;
a = tmp;
}
return a;
}
static long inverse(long a, long m) {
long[] ans = extgcd(a, m);
return ans[0] == 1 ? (ans[1] + m) % m : -1;
}
private static long[] extgcd(long a, long m) {
if (m == 0) {
return new long[]{a, 1, 0};
} else {
long[] ans = extgcd(m, a % m);
long tmp = ans[1];
ans[1] = ans[2];
ans[2] = tmp;
ans[2] -= ans[1] * (a / m);
return ans;
}
}
private static List<Integer> primes(double upperBound) {
var limit = (int) Math.sqrt(upperBound);
var isComposite = new boolean[limit + 1];
var primes = new ArrayList<Integer>();
for (int i = 2; i <= limit; i++) {
if (isComposite[i]) {
continue;
}
primes.add(i);
int j = i + i;
while (j <= limit) {
isComposite[j] = true;
j += i;
}
}
return primes;
}
}
| java |
1323 | A | A. Even Subset Sum Problemtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 22) or determine that there is no such subset.Both the given array and required subset may contain equal values.InputThe first line contains a single integer tt (1≤t≤1001≤t≤100), number of test cases to solve. Descriptions of tt test cases follow.A description of each test case consists of two lines. The first line contains a single integer nn (1≤n≤1001≤n≤100), length of array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), elements of aa. The given array aa can contain equal values (duplicates).OutputFor each test case output −1−1 if there is no such subset of elements. Otherwise output positive integer kk, number of elements in the required subset. Then output kk distinct integers (1≤pi≤n1≤pi≤n), indexes of the chosen elements. If there are multiple solutions output any of them.ExampleInputCopy3
3
1 4 3
1
15
2
3 5
OutputCopy1
2
-1
2
1 2
NoteThere are three test cases in the example.In the first test case; you can choose the subset consisting of only the second element. Its sum is 44 and it is even.In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution.In the third test case, the subset consisting of all array's elements has even sum. | [
"brute force",
"dp",
"greedy",
"implementation"
] | import java.util.*;
public class Main {
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0){
int n=sc.nextInt();
boolean b=false;
for(int i=0;i<n;i++){
int tt=sc.nextInt();
if(tt%2==0 && !b){
System.out.println(1);
System.out.println(i+1);
b=true;
}
}
if(!b){
if(n==1)
System.out.println(-1);
else{
System.out.println(2);
System.out.println(1+" "+2);
}
}
}
}
}
| java |
1311 | F | F. Moving Pointstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn points on a coordinate axis OXOX. The ii-th point is located at the integer point xixi and has a speed vivi. It is guaranteed that no two points occupy the same coordinate. All nn points move with the constant speed, the coordinate of the ii-th point at the moment tt (tt can be non-integer) is calculated as xi+t⋅vixi+t⋅vi.Consider two points ii and jj. Let d(i,j)d(i,j) be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points ii and jj coincide at some moment, the value d(i,j)d(i,j) will be 00.Your task is to calculate the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of points.The second line of the input contains nn integers x1,x2,…,xnx1,x2,…,xn (1≤xi≤1081≤xi≤108), where xixi is the initial coordinate of the ii-th point. It is guaranteed that all xixi are distinct.The third line of the input contains nn integers v1,v2,…,vnv1,v2,…,vn (−108≤vi≤108−108≤vi≤108), where vivi is the speed of the ii-th point.OutputPrint one integer — the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).ExamplesInputCopy3
1 3 2
-100 2 3
OutputCopy3
InputCopy5
2 1 4 3 5
2 2 2 3 4
OutputCopy19
InputCopy2
2 1
-3 0
OutputCopy0
| [
"data structures",
"divide and conquer",
"implementation",
"sortings"
] |
import java.util.*;
import javax.swing.text.Segment;
import java.io.*;
import java.math.*;
import java.sql.Array;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Main {
static class Scanner{
BufferedReader br;
StringTokenizer st;
public Scanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
static long mod = (long)(1e9 + 7);
static void sort(long[] arr ) {
ArrayList<Long> al = new ArrayList<>();
for(long e:arr) al.add(e);
Collections.sort(al);
for(int i = 0 ; i<al.size(); i++) arr[i] = al.get(i);
}
static void sort(int[] arr ) {
ArrayList<Integer> al = new ArrayList<>();
for(int e:arr) al.add(e);
Collections.sort(al);
for(int i = 0 ; i<al.size(); i++) arr[i] = al.get(i);
}
static void sort(char[] arr) {
ArrayList<Character> al = new ArrayList<Character>();
for(char cc:arr) al.add(cc);
Collections.sort(al);
for(int i = 0 ;i<arr.length ;i++) arr[i] = al.get(i);
}
static void rvrs(int[] arr) {
int i =0 , j = arr.length-1;
while(i>=j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
static void rvrs(long[] arr) {
int i =0 , j = arr.length-1;
while(i>=j) {
long temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
static long mod_mul( long mod , long... a) {
long ans = a[0]%mod;
for(int i = 1 ; i<a.length ; i++) {
ans = (ans * (a[i]%mod))%mod;
}
return ans;
}
static long mod_sum(long mod , long... a) {
long ans = 0;
for(long e:a) {
ans = (ans + e)%mod;
}
return ans;
}
static long gcd(long a, long b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static boolean[] prime(int num) {
boolean[] bool = new boolean[num];
for (int i = 0; i< bool.length; i++) {
bool[i] = true;
}
for (int i = 2; i< Math.sqrt(num); i++) {
if(bool[i] == true) {
for(int j = (i*i); j<num; j = j+i) {
bool[j] = false;
}
}
}
if(num >= 0) {
bool[0] = false;
bool[1] = false;
}
return bool;
}
static long modInverse(long a, long m)
{
long g = gcd(a, m);
return power(a, m - 2, m);
}
static long lcm(long a , long b) {
return (a*b)/gcd(a, b);
}
static int lcm(int a , int b) {
return (int)((a*b)/gcd(a, b));
}
static long power(long x, long y, long m){
if (y == 0) return 1; long p = power(x, y / 2, m) % m; p = (int)((p * (long)p) % m);
if (y % 2 == 0) return p; else return (int)((x * (long)p) % m); }
static class Combinations{
private long[] z;
private long[] z1;
private long[] z2;
public Combinations(long N , long mod) {
z = new long[(int)N+1];
z1 = new long[(int)N+1];
z[0] = 1;
for(int i =1 ; i<=N ; i++) z[i] = (z[i-1]*i)%mod;
z2 = new long[(int)N+1];
z2[0] = z2[1] = 1;
for (int i = 2; i <= N; i++)
z2[i] = z2[(int)(mod % i)] * (mod - mod / i) % mod;
z1[0] = z1[1] = 1;
for (int i = 2; i <= N; i++)
z1[i] = (z2[i] * z1[i - 1]) % mod;
}
long fac(long n) {
return z[(int)n];
}
long invrsNum(long n) {
return z2[(int)n];
}
long invrsFac(long n) {
return invrsFac((int)n);
}
long ncr(long N, long R, long mod)
{ if(R<0 || R>N ) return 0;
long ans = ((z[(int)N] * z1[(int)R])
% mod * z1[(int)(N - R)])
% mod;
return ans;
}
}
static class DisjointUnionSets {
int[] rank, parent;
int n;
public DisjointUnionSets(int n)
{
rank = new int[n];
parent = new int[n];
this.n = n;
makeSet();
}
void makeSet()
{
for (int i = 0; i < n; i++) {
parent[i] = i;
}
}
int find(int x)
{
if (parent[x] != x) {
parent[x] = find(parent[x]);
}
return parent[x];
}
void union(int x, int y)
{
int xRoot = find(x), yRoot = find(y);
if (xRoot == yRoot)
return;
if (rank[xRoot] < rank[yRoot])
parent[xRoot] = yRoot;
else if (rank[yRoot] < rank[xRoot])
parent[yRoot] = xRoot;
else
{
parent[yRoot] = xRoot;
rank[xRoot] = rank[xRoot] + 1;
}
}
}
static int max(int... a ) {
int max = a[0];
for(int e:a) max = Math.max(max, e);
return max;
}
static long max(long... a ) {
long max = a[0];
for(long e:a) max = Math.max(max, e);
return max;
}
static int min(int... a ) {
int min = a[0];
for(int e:a) min = Math.min(e, min);
return min;
}
static long min(long... a ) {
long min = a[0];
for(long e:a) min = Math.min(e, min);
return min;
}
static int[] KMP(String str) {
int n = str.length();
int[] kmp = new int[n];
for(int i = 1 ; i<n ; i++) {
int j = kmp[i-1];
while(j>0 && str.charAt(i) != str.charAt(j)) {
j = kmp[j-1];
}
if(str.charAt(i) == str.charAt(j)) j++;
kmp[i] = j;
}
return kmp;
}
/************************************************ Query **************************************************************************************/
/***************************************** Sparse Table ********************************************************/
static class SparseTable{
private long[][] st;
SparseTable(long[] arr){
int n = arr.length;
st = new long[n][25];
log = new int[n+2];
build_log(n+1);
build(arr);
}
private void build(long[] arr) {
int n = arr.length;
for(int i = n-1 ; i>=0 ; i--) {
for(int j = 0 ; j<25 ; j++) {
int r = i + (1<<j)-1;
if(r>=n) break;
if(j == 0 ) st[i][j] = arr[i];
else st[i][j] = Math.max(st[i][j-1] , st[ i + ( 1 << (j-1) ) ][ j-1 ] );
}
}
}
public long gcd(long a ,long b) {
if(a == 0) return b;
return gcd(b%a , a);
}
public long query(int l ,int r) {
int w = r-l+1;
int power = log[w];
return Math.max(st[l][power],st[r - (1<<power) + 1][power]);
}
private int[] log;
void build_log(int n) {
log[1] = 0;
for(int i = 2 ; i<=n ; i++) {
log[i] = 1 + log[i/2];
}
}
}
/******************************************************** Segement Tree *****************************************************/
/**
static class SegmentTree{
long[] tree;
long[] arr;
int n;
SegmentTree(long[] arr){
this.n = arr.length;
tree = new long[4*n+1];
this.arr = arr;
buildTree(0, n-1, 1);
}
void buildTree(int s ,int e ,int index ) {
if(s == e) {
tree[index] = arr[s];
return;
}
int mid = (s+e)/2;
buildTree( s, mid, 2*index);
buildTree( mid+1, e, 2*index+1);
tree[index] = Math.min(tree[2*index] , tree[2*index+1]);
}
long query(int si ,int ei) {
return query(0 ,n-1 , si ,ei , 1 );
}
private long query( int ss ,int se ,int qs , int qe,int index) {
if(ss>=qs && se<=qe) return tree[index];
if(qe<ss || se<qs) return (long)(1e17);
int mid = (ss + se)/2;
long left = query( ss , mid , qs ,qe , 2*index);
long right= query(mid + 1 , se , qs ,qe , 2*index+1);
return Math.min(left, right);
}
public void update(int index , int val) {
arr[index] = val;
for(long e:arr) System.out.print(e+" ");
update(index , 0 , n-1 , 1);
}
private void update(int id ,int si , int ei , int index) {
if(id < si || id>ei) return;
if(si == ei ) {
tree[index] = arr[id];
return;
}
if(si > ei) return;
int mid = (ei + si)/2;
update( id, si, mid , 2*index);
update( id , mid+1, ei , 2*index+1);
tree[index] = Math.min(tree[2*index] ,tree[2*index+1]);
}
}
*/
/* ***************************************************************************************************************************************************/
static Scanner sc = new Scanner();
static StringBuilder sb = new StringBuilder();
public static void main(String args[]) throws IOException {
int tc = 1;
// tc = sc.nextInt();
for(int i = 1 ; i<=tc ; i++) {
// sb.append("Case #" + i + ": " ); // During KickStart && HackerCup
TEST_CASE();
}
System.out.println(sb);
}
static void TEST_CASE() {
int n = sc.nextInt();
int[] x = new int[n];
int[] v = new int[n];
for(int i = 0 ; i<n ; i++)
x[i] = sc.nextInt();
for(int i = 0 ; i<n ; i++)
v[i] = sc.nextInt();
ArrayList<Pair> al = new ArrayList<>();
for(int i = 0 ; i< n ; i++) {
al.add(new Pair(x[i] , v[i]));
}
Collections.sort(al);
long[] arr = new long[n];
for(int i = 0 ; i < n ; i++) {
arr[i] = al.get(i).x;
}
AVLTreePBDS pbds1 = new AVLTreePBDS(false);
// pbds1.add(1);
// pbds1.add(2);
// System.out.println(pbds1.orderOfKey(3));
long tot = 0 ;
// for(long e:arr) System.out.print(e+" ");
// System.out.println();
for(long e:arr) {
tot += pbds1.orderOfKey((int)e)*e;
pbds1.add((int)e);
}
// System.out.println(tot);
AVLTreePBDS pbds2 = new AVLTreePBDS(false);
for(int i = n-1 ; i>=0 ; i--) {
// System.out.println(pbds2.orderOfKey( (int)arr[i]) );
tot -= ((n-i-1) - pbds2.orderOfKey((int)arr[i]))*arr[i];
pbds2.add((int)(arr[i]));
}
System.out.println(tot);
}
static class Pair implements Comparable<Pair>{
int x;
int v;
Pair(int x , int v){
this.x = x;
this.v = v;
}
public int compareTo(Pair o) {
if(this.v != o.v) return Integer.compare(this.v, o.v);
else {
return Integer.compare(this.x, o.x);
}
}
public String toString() {
return "{" +this.x+","+this.v+"}";
}
}
//PBDS JAVA CODE
static public class AVLTreePBDS {
private Node root;
private boolean multi;
AVLTreePBDS(boolean multi) {
this.root = null;
this.multi = multi;
}
int size() {
return size(root);
}
boolean isEmpty() {
return size(root) == 0;
}
boolean contains(int key) {
return contains(root, key);
}
void add(int key) {
root = add(root, key);
}
void remove(int key) {
root = remove(root, key);
}
Integer first() {
Node min = findMin(root);
return min != null ? min.key : null;
}
Integer last() {
Node max = findMax(root);
return max != null ? max.key : null;
}
Integer poolFirst() {
Node min = findMin(root);
if (min != null) {
remove(min.key);
return min.key;
}
return null;
}
Integer poolLast() {
Node max = findMax(root);
if (max != null) {
remove(max.key);
return max.key;
}
return null;
}
// min >= key
Integer ceiling(int key) {
return contains(key) ? key : higher(key);
}
// max <= key
Integer floor(int key) {
return contains(key) ? key : lower(key);
}
// min > key
Integer higher(int key) {
Node min = higher(root, key);
return min == null ? null : min.key;
}
private Node higher(Node cur, int key) {
if (cur == null)
return null;
if (cur.key <= key)
return higher(cur.right, key);
// cur.key > key
Node left = higher(cur.left, key);
return left == null ? cur : left;
}
// max < key
Integer lower(int key) {
Node max = lower(root, key);
return max == null ? null : max.key;
}
private Node lower(Node cur, int key) {
if (cur == null)
return null;
if (cur.key >= key)
return lower(cur.left, key);
// cur.key < key
Node right = lower(cur.right, key);
return right == null ? cur : right;
}
private class Node {
int key, height, size;
Node left, right;
Node(int key) {
this.key = key;
height = size = 1;
left = right = null;
}
private void preOrder(Node root , StringBuilder ans) {
if(root == null) return;
if(root.left != null) preOrder(root.left,ans );
ans.append(root.key+",");
if(root.right!=null) preOrder(root.right, ans);
}
public String toString() {
StringBuilder res = new StringBuilder();
preOrder(root, res);
return "[" + String.valueOf(res.substring(0 , res.length()-1)) +"]" ;
}
}
private int height(Node cur) {
return cur == null ? 0 : cur.height;
}
private int balanceFactor(Node cur) {
return height(cur.right) - height(cur.left);
}
private int size(Node cur) {
return cur == null ? 0 : cur.size;
}
// fixVertex
private void fixHeightAndSize(Node cur) {
cur.height = Math.max(height(cur.left), height(cur.right)) + 1;
cur.size = size(cur.left) + size(cur.right) + 1;
}
private Node rotateRight(Node cur) {
Node prevLeft = cur.left;
cur.left = prevLeft.right;
prevLeft.right = cur;
fixHeightAndSize(cur);
fixHeightAndSize(prevLeft);
return prevLeft;
}
private Node rotateLeft(Node cur) {
Node prevRight = cur.right;
cur.right = prevRight.left;
prevRight.left = cur;
fixHeightAndSize(cur);
fixHeightAndSize(prevRight);
return prevRight;
}
private Node balance(Node cur) {
fixHeightAndSize(cur);
if (balanceFactor(cur) == 2) {
if (balanceFactor(cur.right) < 0)
cur.right = rotateRight(cur.right);
return rotateLeft(cur);
}
if (balanceFactor(cur) == -2) {
if (balanceFactor(cur.left) > 0)
cur.left = rotateLeft(cur.left);
return rotateRight(cur);
}
return cur;
}
private boolean contains(Node cur, int key) {
if (cur == null)
return false;
else if (key < cur.key)
return contains(cur.left, key);
else if (key > cur.key)
return contains(cur.right, key);
else
return true;
}
private Node add(Node cur, int key) {
if (cur == null)
return new Node(key);
if (key < cur.key)
cur.left = add(cur.left, key);
else if (key > cur.key || multi)
cur.right = add(cur.right, key);
return balance(cur);
}
private Node findMin(Node cur) {
return cur.left != null ? findMin(cur.left) : cur;
}
private Node findMax(Node cur) {
return cur.right != null ? findMax(cur.right) : cur;
}
private Node removeMin(Node cur) {
if (cur.left == null)
return cur.right;
cur.left = removeMin(cur.left);
return balance(cur);
}
private Node removeMax(Node cur) {
if (cur.right == null)
return cur.left;
cur.right = removeMax(cur.right);
return balance(cur);
}
private Node remove(Node cur, int key) {
if (cur == null)
return null;
if (key < cur.key)
cur.left = remove(cur.left, key);
else if (key > cur.key)
cur.right = remove(cur.right, key);
else { // k == cur.key
Node prevLeft = cur.left;
Node prevRight = cur.right;
if (prevRight == null)
return prevLeft;
Node min = findMin(prevRight);
min.right = removeMin(prevRight);
min.left = prevLeft;
return balance(min);
}
return balance(cur);
}
int orderOfKey(int key) {
return orderOfKey(root, key);
}
// count < key
private int orderOfKey(Node cur, int key) {
if (cur == null)
return 0;
if (cur.key < key)
return size(cur.left) + 1 + orderOfKey(cur.right, key);
if(cur.key > key || (multi && cur.left!=null && cur.left.key == key))
return orderOfKey(cur.left, key);
// cur.key == key
return size(cur.left);
}
Integer findByOrder(int pos) {
return size(root) > pos ? findByOrder(root, pos) : null;
}
// get i-th
private int findByOrder(Node cur, int pos) {
if (size(cur.left) > pos)
return findByOrder(cur.left, pos);
if (size(cur.left) == pos)
return cur.key;
// size(cur.left) < pos
return findByOrder(cur.right, pos - 1 - size(cur.left));
}
public String toString() {
return String.valueOf(this.root) ;
}
}
}
/*******************************************************************************************************************************************************/
/**
*/
| java |
1325 | B | B. CopyCopyCopyCopyCopytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEhab has an array aa of length nn. He has just enough free time to make a new array consisting of nn copies of the old array, written back-to-back. What will be the length of the new array's longest increasing subsequence?A sequence aa is a subsequence of an array bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements. The longest increasing subsequence of an array is the longest subsequence such that its elements are ordered in strictly increasing order.InputThe first line contains an integer tt — the number of test cases you need to solve. The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1051≤n≤105) — the number of elements in the array aa.The second line contains nn space-separated integers a1a1, a2a2, ……, anan (1≤ai≤1091≤ai≤109) — the elements of the array aa.The sum of nn across the test cases doesn't exceed 105105.OutputFor each testcase, output the length of the longest increasing subsequence of aa if you concatenate it to itself nn times.ExampleInputCopy2
3
3 2 1
6
3 1 4 1 5 9
OutputCopy3
5
NoteIn the first sample; the new array is [3,2,1,3,2,1,3,2,1][3,2,1,3,2,1,3,2,1]. The longest increasing subsequence is marked in bold.In the second sample, the longest increasing subsequence will be [1,3,4,5,9][1,3,4,5,9]. | [
"greedy",
"implementation"
] | import java.util.HashSet;
import java.util.Scanner;
public class Codeforces_1325B_CopyCopyCopyCopyCopy {
public static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
int t = sc.nextInt();
for (int i = 0; i < t; i++) {
int n = sc.nextInt();
HashSet<Integer> record = new HashSet<>();
for (int j = 0; j < n; j++) {
record.add(sc.nextInt());
}
System.out.println(record.size());
}
}
}
| java |
1285 | D | D. Dr. Evil Underscorestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; as a friendship gift, Bakry gave Badawy nn integers a1,a2,…,ana1,a2,…,an and challenged him to choose an integer XX such that the value max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X) is minimum possible, where ⊕⊕ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X).InputThe first line contains integer nn (1≤n≤1051≤n≤105).The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤230−10≤ai≤230−1).OutputPrint one integer — the minimum possible value of max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X).ExamplesInputCopy3
1 2 3
OutputCopy2
InputCopy2
1 5
OutputCopy4
NoteIn the first sample; we can choose X=3X=3.In the second sample, we can choose X=5X=5. | [
"bitmasks",
"brute force",
"dfs and similar",
"divide and conquer",
"dp",
"greedy",
"strings",
"trees"
] | import java.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
PrintWriter out = new PrintWriter(System.out);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tok = new StringTokenizer("");
String next() throws IOException {
if (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); }
return tok.nextToken();
}
int ni() throws IOException { return Integer.parseInt(next()); }
long nl() throws IOException { return Long.parseLong(next()); }
long mod=1000000007;
void solve() throws IOException {
int n=ni();
int[]A=new int[n];
for (int i=0;i<n;i++) A[i]=ni();
Arrays.sort(A);
ArrayList<Integer>B=new ArrayList();
B.add(0);
B.add(n);
int ans=0;
int p=1<<29;
while (p>0) {
ArrayList<Integer>C=new ArrayList();
ArrayList<Integer>D=new ArrayList();
for (int i=0;i<B.size();i+=2) {
int lt=B.get(i);
int rt=B.get(i+1);
int mid=-1;
for (int j=lt;j<rt;j++)
if ((A[j]&p)>0) { mid=j; break; }
if (mid==-1 || mid==lt) { D.add(lt); D.add(rt); }
else { C.add(lt); C.add(mid); C.add(mid); C.add(rt); }
}
B.clear();
if (D.size()==0) {
ans|=p;
for (int v:C) B.add(v);
}
else {
for (int v:D) B.add(v);
}
p>>=1;
}
out.println(ans);
out.flush();
}
int gcd(int a,int b) { return(b==0?a:gcd(b,a%b)); }
long gcd(long a,long b) { return(b==0?a:gcd(b,a%b)); }
long mp(long a,long p) { long r=1; while(p>0) { if ((p&1)==1) r=(r*a)%mod; p>>=1; a=(a*a)%mod; } return r; }
public static void main(String[] args) throws IOException {
new Main().solve();
}
} | java |
1324 | C | C. Frog Jumpstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a frog staying to the left of the string s=s1s2…sns=s1s2…sn consisting of nn characters (to be more precise, the frog initially stays at the cell 00). Each character of ss is either 'L' or 'R'. It means that if the frog is staying at the ii-th cell and the ii-th character is 'L', the frog can jump only to the left. If the frog is staying at the ii-th cell and the ii-th character is 'R', the frog can jump only to the right. The frog can jump only to the right from the cell 00.Note that the frog can jump into the same cell twice and can perform as many jumps as it needs.The frog wants to reach the n+1n+1-th cell. The frog chooses some positive integer value dd before the first jump (and cannot change it later) and jumps by no more than dd cells at once. I.e. if the ii-th character is 'L' then the frog can jump to any cell in a range [max(0,i−d);i−1][max(0,i−d);i−1], and if the ii-th character is 'R' then the frog can jump to any cell in a range [i+1;min(n+1;i+d)][i+1;min(n+1;i+d)].The frog doesn't want to jump far, so your task is to find the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it can jump by no more than dd cells at once. It is guaranteed that it is always possible to reach n+1n+1 from 00.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. The ii-th test case is described as a string ss consisting of at least 11 and at most 2⋅1052⋅105 characters 'L' and 'R'.It is guaranteed that the sum of lengths of strings over all test cases does not exceed 2⋅1052⋅105 (∑|s|≤2⋅105∑|s|≤2⋅105).OutputFor each test case, print the answer — the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it jumps by no more than dd at once.ExampleInputCopy6
LRLRRLL
L
LLR
RRRR
LLLLLL
R
OutputCopy3
2
3
1
7
1
NoteThe picture describing the first test case of the example and one of the possible answers:In the second test case of the example; the frog can only jump directly from 00 to n+1n+1.In the third test case of the example, the frog can choose d=3d=3, jump to the cell 33 from the cell 00 and then to the cell 44 from the cell 33.In the fourth test case of the example, the frog can choose d=1d=1 and jump 55 times to the right.In the fifth test case of the example, the frog can only jump directly from 00 to n+1n+1.In the sixth test case of the example, the frog can choose d=1d=1 and jump 22 times to the right. | [
"binary search",
"data structures",
"dfs and similar",
"greedy",
"implementation"
] | import java.util.Scanner;
public class FrogJumps {
public static void main(String args[]){
Scanner sr=new Scanner(System.in);
int t=sr.nextInt();
for (int i=0;i<t;i++){
System.out.println(findMaxJump(sr.next(), 0, 0,0));
}
}
public static int findMaxJump(String lrs, int maxJump, int currentJump, int i){
if(i>=lrs.length()){
return maxJump+1;
}
if(lrs.charAt(i)=='L'){
currentJump++;
}
else {
currentJump=0;
}
if(currentJump>maxJump){
maxJump=currentJump;
}
return findMaxJump(lrs,maxJump,currentJump,i+1);
}
} | java |
1325 | B | B. CopyCopyCopyCopyCopytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEhab has an array aa of length nn. He has just enough free time to make a new array consisting of nn copies of the old array, written back-to-back. What will be the length of the new array's longest increasing subsequence?A sequence aa is a subsequence of an array bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements. The longest increasing subsequence of an array is the longest subsequence such that its elements are ordered in strictly increasing order.InputThe first line contains an integer tt — the number of test cases you need to solve. The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1051≤n≤105) — the number of elements in the array aa.The second line contains nn space-separated integers a1a1, a2a2, ……, anan (1≤ai≤1091≤ai≤109) — the elements of the array aa.The sum of nn across the test cases doesn't exceed 105105.OutputFor each testcase, output the length of the longest increasing subsequence of aa if you concatenate it to itself nn times.ExampleInputCopy2
3
3 2 1
6
3 1 4 1 5 9
OutputCopy3
5
NoteIn the first sample; the new array is [3,2,1,3,2,1,3,2,1][3,2,1,3,2,1,3,2,1]. The longest increasing subsequence is marked in bold.In the second sample, the longest increasing subsequence will be [1,3,4,5,9][1,3,4,5,9]. | [
"greedy",
"implementation"
] |
import java.util.*;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int n=scn.nextInt();
for(int i=0;i<n;i++)
{
int len=scn.nextInt();
int [] arr=new int[len];
for(int j=0;j<len;j++)
{
arr[j]=scn.nextInt();
}
answer(len, arr);
}
}
public static void answer(int n, int[] arr) {
HashSet<Integer> set=new HashSet<>();
for(int i=0;i<n;i++)
{
set.add(arr[i]);
}
System.out.println(set.size());
}
} | java |
1288 | D | D. Minimax Problemtime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given nn arrays a1a1, a2a2, ..., anan; each array consists of exactly mm integers. We denote the yy-th element of the xx-th array as ax,yax,y.You have to choose two arrays aiai and ajaj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j). After that, you will obtain a new array bb consisting of mm integers, such that for every k∈[1,m]k∈[1,m] bk=max(ai,k,aj,k)bk=max(ai,k,aj,k).Your goal is to choose ii and jj so that the value of mink=1mbkmink=1mbk is maximum possible.InputThe first line contains two integers nn and mm (1≤n≤3⋅1051≤n≤3⋅105, 1≤m≤81≤m≤8) — the number of arrays and the number of elements in each array, respectively.Then nn lines follow, the xx-th line contains the array axax represented by mm integers ax,1ax,1, ax,2ax,2, ..., ax,max,m (0≤ax,y≤1090≤ax,y≤109).OutputPrint two integers ii and jj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j) — the indices of the two arrays you have to choose so that the value of mink=1mbkmink=1mbk is maximum possible. If there are multiple answers, print any of them.ExampleInputCopy6 5
5 0 3 1 2
1 8 9 1 3
1 2 3 4 5
9 1 0 3 7
2 3 0 6 3
6 4 1 7 0
OutputCopy1 5
| [
"binary search",
"bitmasks",
"dp"
] | 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.*;
/**
* #
*
* @author pttrung
*/
public class D_Edu_Round_80 {
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 m = in.nextInt();
int[][] data = new int[n][m];
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
data[i][j] = in.nextInt();
min = Integer.min(data[i][j], min);
max = Integer.max(data[i][j], max);
}
}
int st = min;
int ed = max;
int x = -1, y = -1;
while (st <= ed) {
int mid = (st + ed) / 2;
int[] mask = new int[1 << m];
Arrays.fill(mask, -1);
int a = -1, b = -1;
for (int i = 0; i < n; i++) {
int tmp = 0;
for (int j = 0; j < m; j++) {
if (data[i][j] >= mid) {
tmp |= (1 << j);
}
}
mask[tmp] = i;
}
for (int i = 0; i < 1 << m && a == -1; i++) {
if (mask[i] == -1) {
continue;
}
for (int j = i; j < 1 << m; j++) {
if (mask[j] == -1) {
continue;
}
if ((i | j) + 1 == 1 << m) {
a = mask[i];
b = mask[j];
break;
}
}
}
if (a != -1) {
x = a;
y = b;
st = mid + 1;
} else {
ed = mid - 1;
}
}
out.println((x + 1) + " " + (y + 1));
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 {
int x, y;
public Point(int start, int end) {
this.x = start;
this.y = end;
}
}
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, int b) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long val = pow(a, b / 2);
if (b % 2 == 0) {
return val * val;
} else {
return val * (val * a);
}
}
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 |
1324 | F | F. Maximum White Subtreetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn vertices. A tree is a connected undirected graph with n−1n−1 edges. Each vertex vv of this tree has a color assigned to it (av=1av=1 if the vertex vv is white and 00 if the vertex vv is black).You have to solve the following problem for each vertex vv: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex vv? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains cntwcntw white vertices and cntbcntb black vertices, you have to maximize cntw−cntbcntw−cntb.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of vertices in the tree.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where aiai is the color of the ii-th vertex.Each of the next n−1n−1 lines describes an edge of the tree. Edge ii is denoted by two integers uiui and vivi, the labels of vertices it connects (1≤ui,vi≤n,ui≠vi(1≤ui,vi≤n,ui≠vi).It is guaranteed that the given edges form a tree.OutputPrint nn integers res1,res2,…,resnres1,res2,…,resn, where resiresi is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex ii.ExamplesInputCopy9
0 1 1 1 0 0 0 0 1
1 2
1 3
3 4
3 5
2 6
4 7
6 8
5 9
OutputCopy2 2 2 2 2 1 1 0 2
InputCopy4
0 0 1 0
1 2
1 3
1 4
OutputCopy0 -1 1 -1
NoteThe first example is shown below:The black vertices have bold borders.In the second example; the best subtree for vertices 2,32,3 and 44 are vertices 2,32,3 and 44 correspondingly. And the best subtree for the vertex 11 is the subtree consisting of vertices 11 and 33. | [
"dfs and similar",
"dp",
"graphs",
"trees"
] | import java.io.*;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class MaximumWhiteSubtree {
static int mod = 1000000007;
public static void main(String[] args) throws IOException {
FastReader reader = new FastReader();
FastWriter writer = new FastWriter();
int n = reader.readSingleInt();
int[] a = reader.readIntArray(n);
//Seems very DP.
// white = + 1, Black = -1, and if a subtree contains a negative count, we can discard that subtree.
Node[] nodes = new Node[n];
for(int i = 0; i<n; i++){
boolean isWhite = (a[i] == 1) ? true : false;
nodes[i] = new Node(isWhite, i+1);
}
for(int i = 0; i<n-1; i++){
int[] e = reader.readIntArray(2);
nodes[e[0]-1].adj.add(nodes[e[1]-1]);
nodes[e[1]-1].adj.add(nodes[e[0]-1]);
}
//Root the tree.
nodes[0].dfs();
//Calc diffs
nodes[0].dfsForDiff();
int[] ans = new int[n];
for(int i = 0; i<n; i++){
ans[i] = nodes[i].maxDiff;
}
writer.writeIntArrayWithSpaces(ans);
}
public static class Node {
int count = 0, maxDiff = 0, id;
boolean isWhite;
Node parent;
ArrayList<Node> adj = new ArrayList<>();
public Node(boolean isWhite, int id){
this.isWhite = isWhite;
this.id = id;
}
public int dfs(){
count = (isWhite) ? 1 : -1;
for(int i = 0; i<adj.size(); i++){
Node n = adj.get(i);
if(n == parent) continue;
n.parent = this;
count += Math.max(0, n.dfs());
}
return count;
}
public void dfsForDiff(){
maxDiff = count;
if(parent != null) {
//If my maxDiff is positive, then it has been added to my parents... So i can subtract it from my parents,
//and get what the other trees have contributed.
if(parent.maxDiff > count && count > 0){
maxDiff += (parent.maxDiff - count);
} else if(count <= 0){
maxDiff += Math.max(0, parent.maxDiff);
}
}
for(int i = 0; i<adj.size(); i++){
Node n = adj.get(i);
if(n == parent) continue;
n.dfsForDiff();
}
}
}
public static void mergeSort(int[] a, int n) {
if (n < 2) {
return;
}
int mid = n / 2;
int[] l = new int[mid];
int[] r = new int[n - mid];
for (int i = 0; i < mid; i++) {
l[i] = a[i];
}
for (int i = mid; i < n; i++) {
r[i - mid] = a[i];
}
mergeSort(l, mid);
mergeSort(r, n - mid);
merge(a, l, r, mid, n - mid);
}
public static void merge(int[] a, int[] l, int[] r, int left, int right) {
int i = 0, j = 0, k = 0;
while (i < left && j < right) {
if (l[i] <= r[j]) {
a[k++] = l[i++];
}
else {
a[k++] = r[j++];
}
}
while (i < left) {
a[k++] = l[i++];
}
while (j < right) {
a[k++] = r[j++];
}
}
public static class FastReader {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tokenizer;
public int readSingleInt() throws IOException {
return Integer.parseInt(reader.readLine());
}
public int[] readIntArray(int numInts) throws IOException {
int[] nums = new int[numInts];
tokenizer = new StringTokenizer(reader.readLine());
for(int i = 0; i<numInts; i++){
nums[i] = Integer.parseInt(tokenizer.nextToken());
}
return nums;
}
public String readString() throws IOException {
return reader.readLine();
}
}
public static class FastWriter {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
public void writeSingleInteger(int i) throws IOException {
writer.write(Integer.toString(i));
writer.newLine();
writer.flush();
}
public void writeSingleLong(long i) throws IOException {
writer.write(Long.toString(i));
writer.newLine();
writer.flush();
}
public void writeIntArrayWithSpaces(int[] nums) throws IOException {
for(int i = 0; i<nums.length; i++){
writer.write(nums[i] + " ");
}
writer.newLine();
writer.flush();
}
public void writeIntArrayListWithSpaces(ArrayList<Integer> nums) throws IOException {
for(int i = 0; i<nums.size(); i++){
writer.write(nums.get(i) + " ");
}
writer.newLine();
writer.flush();
}
public void writeIntArrayWithoutSpaces(int[] nums) throws IOException {
for(int i = 0; i<nums.length; i++){
writer.write(Integer.toString(nums[i]));
}
writer.newLine();
writer.flush();
}
public void writeString(String s) throws IOException {
writer.write(s);
writer.newLine();
writer.flush();
}
}
}
| java |
1301 | A | A. Three Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three strings aa, bb and cc of the same length nn. The strings consist of lowercase English letters only. The ii-th letter of aa is aiai, the ii-th letter of bb is bibi, the ii-th letter of cc is cici.For every ii (1≤i≤n1≤i≤n) you must swap (i.e. exchange) cici with either aiai or bibi. So in total you'll perform exactly nn swap operations, each of them either ci↔aici↔ai or ci↔bici↔bi (ii iterates over all integers between 11 and nn, inclusive).For example, if aa is "code", bb is "true", and cc is "help", you can make cc equal to "crue" taking the 11-st and the 44-th letters from aa and the others from bb. In this way aa becomes "hodp" and bb becomes "tele".Is it possible that after these swaps the string aa becomes exactly the same as the string bb?InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1001≤t≤100) — the number of test cases. The description of the test cases follows.The first line of each test case contains a string of lowercase English letters aa.The second line of each test case contains a string of lowercase English letters bb.The third line of each test case contains a string of lowercase English letters cc.It is guaranteed that in each test case these three strings are non-empty and have the same length, which is not exceeding 100100.OutputPrint tt lines with answers for all test cases. For each test case:If it is possible to make string aa equal to string bb print "YES" (without quotes), otherwise print "NO" (without quotes).You can print either lowercase or uppercase letters in the answers.ExampleInputCopy4
aaa
bbb
ccc
abc
bca
bca
aabb
bbaa
baba
imi
mii
iim
OutputCopyNO
YES
YES
NO
NoteIn the first test case; it is impossible to do the swaps so that string aa becomes exactly the same as string bb.In the second test case, you should swap cici with aiai for all possible ii. After the swaps aa becomes "bca", bb becomes "bca" and cc becomes "abc". Here the strings aa and bb are equal.In the third test case, you should swap c1c1 with a1a1, c2c2 with b2b2, c3c3 with b3b3 and c4c4 with a4a4. Then string aa becomes "baba", string bb becomes "baba" and string cc becomes "abab". Here the strings aa and bb are equal.In the fourth test case, it is impossible to do the swaps so that string aa becomes exactly the same as string bb. | [
"implementation",
"strings"
] | import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t=in.nextInt();
in.nextLine();
for(int c=0;c<t;c++)
{
String a=in.nextLine();
String b=in.nextLine();
String s=in.nextLine();
boolean result=true;
for(int i=0;i<a.length();i++)
{
if(!(a.charAt(i)==s.charAt(i)||b.charAt(i)==s.charAt(i)))
{
result=false;
break;
}
}
if(result)
System.out.println("YES");
else
System.out.println("NO");
}
}
} | java |
1315 | B | B. Homecomingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a long party Petya decided to return home; but he turned out to be at the opposite end of the town from his home. There are nn crossroads in the line in the town, and there is either the bus or the tram station at each crossroad.The crossroads are represented as a string ss of length nn, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad. Currently Petya is at the first crossroad (which corresponds to s1s1) and his goal is to get to the last crossroad (which corresponds to snsn).If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a bus station, one can pay aa roubles for the bus ticket, and go from ii-th crossroad to the jj-th crossroad by the bus (it is not necessary to have a bus station at the jj-th crossroad). Formally, paying aa roubles Petya can go from ii to jj if st=Ast=A for all i≤t<ji≤t<j. If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a tram station, one can pay bb roubles for the tram ticket, and go from ii-th crossroad to the jj-th crossroad by the tram (it is not necessary to have a tram station at the jj-th crossroad). Formally, paying bb roubles Petya can go from ii to jj if st=Bst=B for all i≤t<ji≤t<j.For example, if ss="AABBBAB", a=4a=4 and b=3b=3 then Petya needs: buy one bus ticket to get from 11 to 33, buy one tram ticket to get from 33 to 66, buy one bus ticket to get from 66 to 77. Thus, in total he needs to spend 4+3+4=114+3+4=11 roubles. Please note that the type of the stop at the last crossroad (i.e. the character snsn) does not affect the final expense.Now Petya is at the first crossroad, and he wants to get to the nn-th crossroad. After the party he has left with pp roubles. He's decided to go to some station on foot, and then go to home using only public transport.Help him to choose the closest crossroad ii to go on foot the first, so he has enough money to get from the ii-th crossroad to the nn-th, using only tram and bus tickets.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).The first line of each test case consists of three integers a,b,pa,b,p (1≤a,b,p≤1051≤a,b,p≤105) — the cost of bus ticket, the cost of tram ticket and the amount of money Petya has.The second line of each test case consists of one string ss, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad (2≤|s|≤1052≤|s|≤105).It is guaranteed, that the sum of the length of strings ss by all test cases in one test doesn't exceed 105105.OutputFor each test case print one number — the minimal index ii of a crossroad Petya should go on foot. The rest of the path (i.e. from ii to nn he should use public transport).ExampleInputCopy5
2 2 1
BB
1 1 1
AB
3 2 8
AABBBBAABB
5 3 4
BBBBB
2 1 1
ABABAB
OutputCopy2
1
3
1
6
| [
"binary search",
"dp",
"greedy",
"strings"
] |
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.*;
public class weird_algrithm {
static BufferedWriter output = new BufferedWriter(
new OutputStreamWriter(System.out));
static BufferedReader sc = new BufferedReader(new InputStreamReader(System.in));
static int mod = 1000000007;
static String toReturn = "";
static int steps = Integer.MAX_VALUE;
static int maxlen = 1000005;
/*MATHEMATICS FUNCTIONS START HERE
MATHS
MATHS
MATHS
MATHS*/
static long gcd(long a, long b) {
if(b == 0) return a;
else return gcd(b, a % b);
}
static long powerMod(long x, long y, int mod) {
if(y == 0) return 1;
long temp = powerMod(x, y / 2, mod);
temp = ((temp % mod) * (temp % mod)) % mod;
if(y % 2 == 0) return temp;
else return ((x % mod) * (temp % mod)) % mod;
}
static long modInverse(long n, int p) {
return powerMod(n, p - 2, p);
}
static long nCr(int n, int r, int mod, long [] fact, long [] ifact) {
return ((fact[n] % mod) * ((ifact[r] * ifact[n - r]) % mod)) % mod;
}
static boolean isPrime(long a) {
if(a == 1) return false;
else if(a == 2 || a == 3 || a== 5) return true;
else if(a % 2 == 0 || a % 3 == 0) return false;
for(int i = 5; i * i <= a; i = i + 6) {
if(a % i == 0 || a % (i + 2) == 0) return false;
}
return true;
}
static int [] seive(int a) {
int [] toReturn = new int [a + 1];
for(int i = 0; i < a; i++) toReturn[i] = 1;
toReturn[0] = 0;
toReturn[1] = 0;
toReturn[2] = 1;
for(int i = 2; i * i <= a; i++) {
if(toReturn[i] == 0) continue;
for(int j = 2 * i; j <= a; j += i) toReturn[j] = 0;
}
return toReturn;
}
static long [] fact(int a) {
long [] arr = new long[a + 1];
arr[0] = 1;
for(int i = 1; i < a + 1; i++) {
arr[i] = (arr[i - 1] * i) % mod;
}
return arr;
}
/*MATHS
MATHS
MATHS
MATHS
MATHEMATICS FUNCTIONS END HERE */
/*SWAP FUNCTION START HERE
SWAP
SWAP
SWAP
SWAP
*/
static void swap(int i, int j, long[] arr) {
long temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
static void swap(int i, int j, int[] arr) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
static void swap(int i, int j, String [] arr) {
String temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
static void swap(int i, int j, char [] arr) {
char temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
/*SWAP
SWAP
SWAP
SWAP
SWAP FUNCTION END HERE*/
/*BINARY SEARCH METHODS START HERE
* BINARY SEARCH
* BINARY SEARCH
* BINARY SEARCH
* BINARY SEARCH
*/
static boolean BinaryCheck(long test, long [] arr, long health) {
for(int i = 0; i <= arr.length - 1; i++) {
if(i == arr.length - 1) health -= test;
else if(arr[i + 1] - arr[i] > test) {
health = health - test;
}else {
health = health - (arr[i + 1] - arr[i]);
}
if(health <= 0) return true;
}
return false;
}
static long binarySearchModified(long start1, long n, ArrayList<Long> arr, int a, long r) {
long start = start1, end = n, ans = -1;
while(start < end) {
long mid = (start + end) / 2;
//System.out.println(mid);
if(arr.get((int)mid) + arr.get(a) <= r && mid != start1) {
ans = mid;
start = mid + 1;
}else{
end = mid;
}
}
//System.out.println();
return ans;
}
static int binarySearch(int start, int end, ArrayList<Integer> arr, long val) {
while(start <= end) {
int mid = (start + end) / 2;
if(arr.get(mid) > val) end = mid - 1;
else if(arr.get(mid) == val) {
if(mid - 1 >= 0 && arr.get(mid - 1) == val) {
end = mid - 1;
}else return mid;
}
else start = mid + 1;
}
return start;
}
/*BINARY SEARCH
* BINARY SEARCH
* BINARY SEARCH
* BINARY SEARCH
* BINARY SEARCH
BINARY SEARCH METHODS END HERE*/
/*RECURSIVE FUNCTION START HERE
* RECURSIVE
* RECURSIVE
* RECURSIVE
* RECURSIVE
*/
static int recurse(int x, int y, int n, int steps1, Integer [][] dp) {
if(x > n || y > n) return 0;
if(dp[x][y] != null) {
return dp[x][y];
}
else if(x == n || y == n) {
return steps1;
}
return dp[x][y] = Math.max(recurse(x + y, y, n, steps1 + 1, dp), recurse(x, x + y, n, steps1 + 1, dp));
}
/*RECURSIVE
* RECURSIVE
* RECURSIVE
* RECURSIVE
* RECURSIVE
RECURSIVE FUNCTION END HERE*/
/*GRAPH FUNCTIONS START HERE
* GRAPH
* GRAPH
* GRAPH
* GRAPH
* */
static class edge{
int from, to;
long weight;
public edge(int x, int y, long weight2) {
this.from = x;
this.to = y;
this.weight = weight2;
}
}
static class sort implements Comparator<pair>{
@Override
public int compare(pair o1, pair o2) {
// TODO Auto-generated method stub
return (int)o1.a - (int)o2.a;
}
}
static void addEdge(ArrayList<ArrayList<edge>> graph, int from, int to, long weight) {
edge temp = new edge(from, to, weight);
edge temp1 = new edge(to, from, weight);
graph.get(from).add(temp);
//graph.get(to).add(temp1);
}
static int ans = 0;
static void topoSort(ArrayList<ArrayList<Integer>> graph, int vertex, boolean [] visited, ArrayList<Integer> toReturn) {
if(visited[vertex]) return;
visited[vertex] = true;
for(int i = 0; i < graph.get(vertex).size(); i++) {
if(!visited[graph.get(vertex).get(i)]) topoSort(graph, graph.get(vertex).get(i), visited, toReturn);
}
toReturn.add(vertex);
}
static boolean isCyclicDirected(ArrayList<ArrayList<Integer>> graph, int vertex, boolean [] visited, boolean [] reStack) {
if(reStack[vertex]) return true;
if(visited[vertex]) return false;
reStack[vertex] = true;
visited[vertex] = true;
for(int i = 0; i < graph.get(vertex).size(); i++) {
if(isCyclicDirected(graph, graph.get(vertex).get(i), visited, reStack)) return true;
}
reStack[vertex] = false;
return false;
}
static int e = 0;
static long mst(PriorityQueue<edge> pq, int nodes) {
long weight = 0;
while(!pq.isEmpty()) {
edge temp = pq.poll();
int x = parent(parent, temp.to);
int y = parent(parent, temp.from);
if(x != y) {
//System.out.println(temp.weight);
union(x, y, rank, parent);
weight += temp.weight;
e++;
}
}
return weight;
}
static void floyd(long [][] dist) { // to find min distance between two nodes
for(int k = 0; k < dist.length; k++) {
for(int i = 0; i < dist.length; i++) {
for(int j = 0; j < dist.length; j++) {
if(dist[i][j] > dist[i][k] + dist[k][j]) {
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
}
}
static void dijkstra(ArrayList<ArrayList<edge>> graph, long [] dist, int src) {
for(int i = 0; i < dist.length; i++) dist[i] = Long.MAX_VALUE / 2;
dist[src] = 0;
boolean visited[] = new boolean[dist.length];
PriorityQueue<pair> pq = new PriorityQueue<>(new sort());
pq.add(new pair(src, 0));
while(!pq.isEmpty()) {
pair temp = pq.poll();
int index = (int)temp.a;
for(int i = 0; i < graph.get(index).size(); i++) {
if(dist[graph.get(index).get(i).to] > dist[index] + graph.get(index).get(i).weight) {
dist[graph.get(index).get(i).to] = dist[index] + graph.get(index).get(i).weight;
pq.add(new pair(graph.get(index).get(i).to, graph.get(index).get(i).weight));
}
}
}
}
static int parent1 = -1;
static boolean ford(ArrayList<ArrayList<edge>> graph1, ArrayList<edge> graph, long [] dist, int src, int [] parent) {
for(int i = 0; i < dist.length; i++) dist[i] = Long.MIN_VALUE / 2;
dist[src] = 0;
boolean hasNeg = false;
for(int i = 0; i < dist.length - 1; i++) {
for(int j = 0; j < graph.size(); j++) {
int from = graph.get(j).from;
int to = graph.get(j).to;
long weight = graph.get(j).weight;
if(dist[to] < dist[from] + weight) {
dist[to] = dist[from] + weight;
parent[to] = from;
}
}
}
for(int i = 0; i < graph.size(); i++) {
int from = graph.get(i).from;
int to = graph.get(i).to;
long weight = graph.get(i).weight;
if(dist[to] < dist[from] + weight) {
parent1 = from;
hasNeg = true;
/*
* dfs(graph1, parent1, new boolean[dist.length], dist.length - 1);
* //System.out.println(ans); dfs(graph1, 0, new boolean[dist.length], parent1);
*/
//System.out.println(ans);
if(ans == 2) break;
else ans = 0;
}
}
return hasNeg;
}
/*GRAPH FUNCTIONS END HERE
* GRAPH
* GRAPH
* GRAPH
* GRAPH
*/
/*disjoint Set START HERE
* disjoint Set
* disjoint Set
* disjoint Set
* disjoint Set
*/
static int [] rank;
static int [] parent;
static int parent(int [] parent, int x) {
if(parent[x] == x) return x;
else return parent[x] = parent(parent, parent[x]);
}
static boolean union(int x, int y, int [] rank, int [] parent) {
if(parent(parent, x) == parent(parent, y)) {
return true;
}
if(rank[x] > rank[y]) {
swap(x, y, rank);
}
rank[x] += rank[y];
parent[y] = x;
return false;
}
/*disjoint Set END HERE
* disjoint Set
* disjoint Set
* disjoint Set
* disjoint Set
*/
/*INPUT START HERE
* INPUT
* INPUT
* INPUT
* INPUT
* INPUT
*/
static int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(sc.readLine());
}
static long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(sc.readLine());
}
static long [] inputLongArr() throws NumberFormatException, IOException{
String [] s = sc.readLine().split(" ");
long [] toReturn = new long[s.length];
for(int i = 0; i < s.length; i++) {
toReturn[i] = Long.parseLong(s[i]);
}
return toReturn;
}
static int max = 0;
static int [] inputIntArr() throws NumberFormatException, IOException{
String [] s = sc.readLine().split(" ");
//System.out.println(s.length);
int [] toReturn = new int[s.length];
for(int i = 0; i < s.length; i++) {
toReturn[i] = Integer.parseInt(s[i]);
}
return toReturn;
}
/*INPUT
* INPUT
* INPUT
* INPUT
* INPUT
* INPUT END HERE
*/
static long [] preCompute(int level) {
long [] toReturn = new long[level];
toReturn[0] = 1;
toReturn[1] = 16;
for(int i = 2; i < level; i++) {
toReturn[i] = ((toReturn[i - 1] % mod) * (toReturn[i - 1] % mod)) % mod;
}
return toReturn;
}
static class pair{
long a;
long b;
long d;
public pair(long in, long y) {
this.a = in;
this.b = y;
this.d = 0;
}
}
static int [] nextGreaterBack(char [] s) {
Stack<Integer> stack = new Stack<>();
int [] toReturn = new int[s.length];
for(int i = 0; i < s.length; i++) {
if(!stack.isEmpty() && s[stack.peek()] >= s[i]) {
stack.pop();
}
if(stack.isEmpty()) {
stack.push(i);
toReturn[i] = -1;
}else {
toReturn[i] = stack.peek();
stack.push(i);
}
}
return toReturn;
}
static int [] nextGreaterFront(char [] s) {
Stack<Integer> stack = new Stack<>();
int [] toReturn = new int[s.length];
for(int i = s.length - 1; i >= 0; i--) {
if(!stack.isEmpty() && s[stack.peek()] >= s[i]) {
stack.pop();
}
if(stack.isEmpty()) {
stack.push(i);
toReturn[i] = -1;
}else {
toReturn[i] = stack.peek();
stack.push(i);
}
}
return toReturn;
}
static int lps(String s) {
int max = 0;
int [] lps = new int[s.length()];
lps[0] = 0;
int j = 0;
for(int i = 1; i < lps.length; i++) {
j = lps[i - 1];
while(j > 0 && s.charAt(i) != s.charAt(j)) j = lps[j - 1];
if(s.charAt(i) == s.charAt(j)) {
lps[i] = j + 1;
max = Math.max(max, lps[i]);
}
}
return max;
}
static int [][] vectors = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
static String dir = "DRUL";
static boolean check(int i, int j, boolean [][] visited) {
if(i >= visited.length || j >= visited[0].length) return false;
if(i < 0 || j < 0) return false;
return true;
}
static void selectionSort(long arr[], long [] arr1, ArrayList<ArrayList<Integer>> ans)
{
int n = arr.length;
for (int i = 0; i < n-1; i++)
{
int min_idx = i;
for (int j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
else if(arr[j] == arr[min_idx]) {
if(arr1[j] < arr1[min_idx]) min_idx = j;
}
if(i == min_idx) {
continue;
}
ArrayList<Integer> p = new ArrayList<Integer>();
p.add(min_idx + 1);
p.add(i + 1);
ans.add(new ArrayList<Integer>(p));
swap(i, min_idx, arr);
swap(i, min_idx, arr1);
}
}
static int saved = Integer.MAX_VALUE;
static String ans1 = "";
public static boolean isValid(int x, int y, String [] mat) {
if(x >= mat.length || x < 0) return false;
if(y >= mat[0].length() || y < 0) return false;
return true;
}
static boolean recurse1(int i, int j, int [][] arr, int sum, Boolean [][][] dp) {
if(i == arr.length - 1 && j == arr[0].length - 1) {
if(sum + arr[i][j] == 0) return true;
return false;
}
if(i == arr.length) return false;
else if(j == arr[0].length) return false;
if(sum < 0 && dp[i][j][arr.length + arr[0].length + 1 + sum] != null) return dp[i][j][arr.length + arr[0].length + 1 + sum];
if(sum > 0 && dp[i][j][sum] != null) return dp[i][j][sum];
if(sum < 0) dp[i][j][arr.length + arr[0].length + 1 + sum] = recurse1(i + 1, j, arr, sum + arr[i][j], dp) || recurse1(i, j + 1, arr, sum + arr[i][j], dp);
return dp[i][j][sum] = recurse1(i + 1, j, arr, sum + arr[i][j], dp) || recurse1(i, j + 1, arr, sum + arr[i][j], dp);
}
public static void recurse3(ArrayList<Character> arr, int index, String s, int max, ArrayList<String> toReturn) {
if(s.length() == max) {
toReturn.add(s);
return;
}
if(index == arr.size()) return;
recurse3(arr, index + 1, s + arr.get(index), max, toReturn);
recurse3(arr, index + 1, s, max, toReturn);
}
/*
if(arr[i] > q) return Math.max(f(i + 1, q - 1) + 1, f(i + 1, q);
else return f(i + 1, q) + 1
*/
static void dfsDP(ArrayList<ArrayList<Integer>> graph, int src, int [] dp1, int [] dp2, int parent) {
int sum1 = 0; int sum2 = 0;
for(int x : graph.get(src)) {
if(x == parent) continue;
dfsDP(graph, x, dp1, dp2, src);
sum1 += Math.min(dp1[x], dp2[x]);
sum2 += dp1[x];
}
dp1[src] = 1 + sum1;
dp2[src] = sum2;
System.out.println(src + " " + dp1[src] + " " + dp2[src]);
}
static int balanced = 0;
static int [] dfs(ArrayList<ArrayList<Integer>> graph, int src, int parent, String color) {
int black = 0; int white = 0;
for(int x : graph.get(src)) {
if(x == parent) continue;
int [] temp = dfs(graph, x, src, color);
black += temp[0];
white += temp[1];
}
int [] toReturn = new int [2];
if(color.charAt(src) == 'W') {
toReturn[0] = black;
toReturn[1] = white + 1;
if(toReturn[0] == toReturn[1]) {
balanced++;
}
}else {
toReturn[0] = black + 1;
toReturn[1] = white;
if(toReturn[0] == toReturn[1]) {
balanced++;
}
}
return toReturn;
}
public static long recurse(ArrayList<Integer> arr, int i, int a, int b, Long [][] dp, int taken) {
if(i >= arr.size()) return 0;
if(arr.get(i - 1) + 1 == arr.get(i)) {
if(taken == 1) return dp[i][taken] = recurse(arr, i + 1, a, b, dp, 1);
else return dp[i][taken] = recurse(arr, i + 1, a, b, dp, 1) + a;
}
if(dp[i][taken] != null) return dp[i][taken];
int size = arr.get(i) - arr.get(i - 1) - 1;
if(taken == 1) {
long poss1 = recurse(arr, i + 1, a, b, dp, 1) + size * b;
long poss2 = recurse(arr, i + 1, a, b, dp, 1) + a;
return dp[i][taken] = Math.min(poss1, poss2);
}else {
long poss1 = recurse(arr, i + 1, a, b, dp, 1) + size * b + a;
long poss2 = recurse(arr, i + 1, a, b, dp, 0) + 2 * a;
return dp[i][taken] = Math.min(poss1, poss2);
}
}
static void solve() throws IOException {
int [] n = inputIntArr();
int b = n[0]; int t = n[1]; int p = n[2];
String s = sc.readLine();
long [] pre = new long[s.length() + 1];
pre[1] = (s.charAt(0) == 'B' ? t : b);
char prev = s.charAt(0);
for(int i = 1; i < s.length() - 1; i++) {
if(prev == s.charAt(i)) {
pre[i + 1] = pre[i];
continue;
}else {
pre[i + 1] = pre[i] + (s.charAt(i) == 'B' ? t : b);
prev = s.charAt(i);
}
}
long sum = pre[pre.length - 2];
/*
for(int i = 0; i < pre.length; i++) System.out.print(pre[i] + " ");
System.out.println();
*/
if(sum <= p) {
output.write(1 + "\n");
return;
}
int index = 0;
for(int i = 1; i < pre.length; i++) {
if(sum - pre[i] <= p) {
sum = sum - pre[i];
index = i - 1;
break;
}
}
//System.out.println(index);
prev = s.charAt(index);
for(int i = index + 1; i < s.length(); i++) {
if(s.charAt(i) == prev) {
index = i;
continue;
}else {
index = i;
break;
}
}
output.write(index + 1 + "\n");
/*
if(index + 1 > s.length()) output.write(s.length() + " \n");
else {
if(sum - pre[index + 1] <= p) {
index += 2;
if(index > s.length()) {
output.write(s.length() + " \n");
return;
}
}
else index++;
output.write(index + "\n");
}
*/
}
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
int t = Integer.parseInt(sc.readLine()); for(int i = 0; i < t; i++)
solve();
output.flush();
}
}
class TreeNode {
int val;
TreeNode next;
public TreeNode(int x, TreeNode y) {
this.val = x;
this.next = y;
}
}
/*
1
10
6 10 7 9 11 99 45 20 88 31
*/
| java |
1325 | D | D. Ehab the Xorcisttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven 2 integers uu and vv, find the shortest array such that bitwise-xor of its elements is uu, and the sum of its elements is vv.InputThe only line contains 2 integers uu and vv (0≤u,v≤1018)(0≤u,v≤1018).OutputIf there's no array that satisfies the condition, print "-1". Otherwise:The first line should contain one integer, nn, representing the length of the desired array. The next line should contain nn positive integers, the array itself. If there are multiple possible answers, print any.ExamplesInputCopy2 4
OutputCopy2
3 1InputCopy1 3
OutputCopy3
1 1 1InputCopy8 5
OutputCopy-1InputCopy0 0
OutputCopy0NoteIn the first sample; 3⊕1=23⊕1=2 and 3+1=43+1=4. There is no valid array of smaller length.Notice that in the fourth sample the array is empty. | [
"bitmasks",
"constructive algorithms",
"greedy",
"number theory"
] | import java.util.*;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scn = new Scanner(System.in);
long u = scn.nextLong();
long v = scn.nextLong();
if(u%2 != v%2 || u>v) {
System.out.println(-1);
}else if(u==v && u==0 && v==0) {
System.out.println(0);
}else if(u==v) {
System.out.println(1);
System.out.println(u);
}else {
long x = (v-u)/2;
if((u&x)==0) {
System.out.println(2);
System.out.println((u+x) + " " + (x));
}else {
System.out.println(3);
System.out.println(u+ " " + x + " " + x);
}
}
}
}
| java |
1324 | C | C. Frog Jumpstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a frog staying to the left of the string s=s1s2…sns=s1s2…sn consisting of nn characters (to be more precise, the frog initially stays at the cell 00). Each character of ss is either 'L' or 'R'. It means that if the frog is staying at the ii-th cell and the ii-th character is 'L', the frog can jump only to the left. If the frog is staying at the ii-th cell and the ii-th character is 'R', the frog can jump only to the right. The frog can jump only to the right from the cell 00.Note that the frog can jump into the same cell twice and can perform as many jumps as it needs.The frog wants to reach the n+1n+1-th cell. The frog chooses some positive integer value dd before the first jump (and cannot change it later) and jumps by no more than dd cells at once. I.e. if the ii-th character is 'L' then the frog can jump to any cell in a range [max(0,i−d);i−1][max(0,i−d);i−1], and if the ii-th character is 'R' then the frog can jump to any cell in a range [i+1;min(n+1;i+d)][i+1;min(n+1;i+d)].The frog doesn't want to jump far, so your task is to find the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it can jump by no more than dd cells at once. It is guaranteed that it is always possible to reach n+1n+1 from 00.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. The ii-th test case is described as a string ss consisting of at least 11 and at most 2⋅1052⋅105 characters 'L' and 'R'.It is guaranteed that the sum of lengths of strings over all test cases does not exceed 2⋅1052⋅105 (∑|s|≤2⋅105∑|s|≤2⋅105).OutputFor each test case, print the answer — the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it jumps by no more than dd at once.ExampleInputCopy6
LRLRRLL
L
LLR
RRRR
LLLLLL
R
OutputCopy3
2
3
1
7
1
NoteThe picture describing the first test case of the example and one of the possible answers:In the second test case of the example; the frog can only jump directly from 00 to n+1n+1.In the third test case of the example, the frog can choose d=3d=3, jump to the cell 33 from the cell 00 and then to the cell 44 from the cell 33.In the fourth test case of the example, the frog can choose d=1d=1 and jump 55 times to the right.In the fifth test case of the example, the frog can only jump directly from 00 to n+1n+1.In the sixth test case of the example, the frog can choose d=1d=1 and jump 22 times to the right. | [
"binary search",
"data structures",
"dfs and similar",
"greedy",
"implementation"
] | // package c1324;
//
// Codeforces Round #627 (Div. 3) 2020-03-12 05:05
// C. Frog Jumps
// https://codeforces.com/contest/1324/problem/C
// time limit per test 2 seconds; memory limit per test 256 megabytes
// public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*'
//
// There is a frog staying to the left of the string s = s_1 s_2 ... s_n consisting of n characters
// (to be more precise, the frog initially stays at the cell 0). Each character of s is either 'L'
// or 'R'. It means that if the frog is staying at the i-th cell and the i-th character is 'L', the
// frog can jump only to the left. If the frog is staying at the i-th cell and the i-th character is
// 'R', the frog can jump only to the right. .
//
// .
//
// The frog wants to reach the n+1-th cell. The frog chooses some value d (and cannot change it
// later) and jumps by no more than d cells at once. I.e. if the i-th character is 'L' then the frog
// can jump to any cell in a range [max(0, i - d); i - 1], and if the i-th character is 'R' then the
// frog can jump to any cell in a range [i + 1; min(n + 1; i + d)].
//
// The frog doesn't want to jump far, so your task is to find the minimum possible value of d such
// that the frog can reach the cell n+1 from the cell 0 if it can jump by no more than d cells at
// once. .
//
// You have to answer t independent test cases.
//
// Input
//
// The first line of the input contains one integer t (1 <= t <= 10^4) -- the number of test cases.
//
// The next t lines describe test cases. The i-th test case is described as a string s consisting of
// at least 1 and at most 2 * 10^5 characters 'L' and 'R'.
//
// It is guaranteed that the sum of lengths of strings over all test cases does not exceed 2 * 10^5
// (\sum |s| <= 2 * 10^5).
//
// Output
//
// For each test case, print the answer -- the minimum possible value of d such that the frog can
// reach the cell n+1 from the cell 0 if it jumps by no more than d at once.
//
// Example
/*
input:
6
LRLRRLL
L
LLR
RRRR
LLLLLL
R
output:
3
2
3
1
7
1
*/
// Note
//
// The picture describing the first test case of the example and one of the possible answers:
//
// https://espresso.codeforces.com/de84e2ea205b39d12a73b422b7f6b0229de451ba.png
//
// In the second test case of the example, the frog can only jump directly from 0 to n+1.
//
// In the third test case of the example, the frog can choose d=3, jump to the cell 3 from the cell
// 0 and then to the cell 4 from the cell 3.
//
// In the fourth test case of the example, the frog can choose d=1 and jump 5 times to the right.
//
// In the fifth test case of the example, the frog can only jump directly from 0 to n+1.
//
// In the sixth test case of the example, the frog can choose d=1 and jump 2 times to the right.
//
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.lang.invoke.MethodHandles;
import java.util.Random;
import java.util.StringTokenizer;
public class C1324C {
static final int MOD = 998244353;
static final Random RAND = new Random();
static int solve(String s) {
int n = s.length();
int ans = 0;
int maxd = 0;
int prev = -1;
for (int i = 0; i < n; i++) {
if (s.charAt(i) == 'R') {
maxd = Math.max(maxd, i - prev);
prev = i;
}
}
maxd = Math.max(maxd, n - prev);
return maxd;
}
static boolean test = false;
static void doTest() {
if (!test) {
return;
}
long t0 = System.currentTimeMillis();
System.out.format("%d msec\n", System.currentTimeMillis() - t0);
System.exit(0);
}
public static void main(String[] args) {
doTest();
MyScanner in = new MyScanner();
int T = in.nextInt();
for (int t = 1; t <= T; t++) {
String s = in.next();
int ans = solve(s);
System.out.println(ans);
}
}
static void output(int[] a) {
if (a == null) {
System.out.println("-1");
return;
}
StringBuilder sb = new StringBuilder();
for (int v : a) {
sb.append(v);
sb.append(' ');
if (sb.length() > 4000) {
System.out.print(sb.toString());
sb.setLength(0);
}
}
System.out.println(sb.toString());
}
static void myAssert(boolean cond) {
if (!cond) {
throw new RuntimeException("Unexpected");
}
}
static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
try {
final String USERDIR = System.getProperty("user.dir");
String cname = MethodHandles.lookup().lookupClass().getCanonicalName().replace(".MyScanner", "");
cname = cname.lastIndexOf('.') > 0 ? cname.substring(cname.lastIndexOf('.') + 1) : cname;
final File fin = new File(USERDIR + "/io/c" + cname.substring(1,5) + "/" + cname + ".in");
br = new BufferedReader(new InputStreamReader(fin.exists()
? new FileInputStream(fin) : System.in));
} catch (Exception e) {
br = new BufferedReader(new InputStreamReader(System.in));
}
}
public String next() {
try {
while (st == null || !st.hasMoreElements()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| java |
1285 | E | E. Delete a Segmenttime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn segments on a OxOx axis [l1,r1][l1,r1], [l2,r2][l2,r2], ..., [ln,rn][ln,rn]. Segment [l,r][l,r] covers all points from ll to rr inclusive, so all xx such that l≤x≤rl≤x≤r.Segments can be placed arbitrarily — be inside each other, coincide and so on. Segments can degenerate into points, that is li=rili=ri is possible.Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example: if n=3n=3 and there are segments [3,6][3,6], [100,100][100,100], [5,8][5,8] then their union is 22 segments: [3,8][3,8] and [100,100][100,100]; if n=5n=5 and there are segments [1,2][1,2], [2,3][2,3], [4,5][4,5], [4,6][4,6], [6,6][6,6] then their union is 22 segments: [1,3][1,3] and [4,6][4,6]. Obviously, a union is a set of pairwise non-intersecting segments.You are asked to erase exactly one segment of the given nn so that the number of segments in the union of the rest n−1n−1 segments is maximum possible.For example, if n=4n=4 and there are segments [1,4][1,4], [2,3][2,3], [3,6][3,6], [5,7][5,7], then: erasing the first segment will lead to [2,3][2,3], [3,6][3,6], [5,7][5,7] remaining, which have 11 segment in their union; erasing the second segment will lead to [1,4][1,4], [3,6][3,6], [5,7][5,7] remaining, which have 11 segment in their union; erasing the third segment will lead to [1,4][1,4], [2,3][2,3], [5,7][5,7] remaining, which have 22 segments in their union; erasing the fourth segment will lead to [1,4][1,4], [2,3][2,3], [3,6][3,6] remaining, which have 11 segment in their union. Thus, you are required to erase the third segment to get answer 22.Write a program that will find the maximum number of segments in the union of n−1n−1 segments if you erase any of the given nn segments.Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n−1n−1 segments.InputThe first line contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases in the test. Then the descriptions of tt test cases follow.The first of each test case contains a single integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of segments in the given set. Then nn lines follow, each contains a description of a segment — a pair of integers lili, riri (−109≤li≤ri≤109−109≤li≤ri≤109), where lili and riri are the coordinates of the left and right borders of the ii-th segment, respectively.The segments are given in an arbitrary order.It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105.OutputPrint tt integers — the answers to the tt given test cases in the order of input. The answer is the maximum number of segments in the union of n−1n−1 segments if you erase any of the given nn segments.ExampleInputCopy3
4
1 4
2 3
3 6
5 7
3
5 5
5 5
5 5
6
3 3
1 1
5 5
1 5
2 2
4 4
OutputCopy2
1
5
| [
"brute force",
"constructive algorithms",
"data structures",
"dp",
"graphs",
"sortings",
"trees",
"two pointers"
] | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class cf1285e {
public static void main(String[] args) throws IOException {
int t = ri();
while (t --> 0) {
int n = ri();
List<int[]> events = new ArrayList<>();
for (int i = 0; i < n; ++i) {
int l = rni(), r = ni();
int left[] = {l, i, 0}, right[] = {r + 1, i, 1};
events.add(left);
events.add(right);
}
events.sort((a, b) -> a[0] == b[0] ? b[2] - a[2] : a[0] - b[0]);
int cnt[] = new int[2 * n + 1], prefix_cnt1[] = new int[2 * n + 1], l[] = new int[n], r[] = new int[n], segs = 0;
fill(l, -1);
for (int i = 0; i < 2 * n; ++i) {
int[] e = events.get(i);
cnt[i + 1] = cnt[i] + (l[e[1]] == -1 ? 1 : -1);
if (cnt[i + 1] == 0) {
++segs;
}
if (l[e[1]] == -1) {
l[e[1]] = i + 1;
} else {
r[e[1]] = i + 1;
}
prefix_cnt1[i + 1] = cnt[i + 1] == 1 ? prefix_cnt1[i] + 1 : prefix_cnt1[i];
}
int create = -1;
// prln(cnt);
// prln(prefix_cnt1);
for (int i = 0; i < n; ++i) {
// prln(i, l[i], r[i], prefix_cnt1[r[i]] - prefix_cnt1[l[i]]);
create = max(create, prefix_cnt1[r[i]] - prefix_cnt1[l[i]] + (cnt[r[i]] > 1 ? 0 : -1));
}
prln(segs + create);
}
close();
}
static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out));
static StringTokenizer input;
static Random __rand = new Random();
// references
// IBIG = 1e9 + 7
// IMAX ~= 2e9
// LMAX ~= 9e18
// constants
static final int IBIG = 1000000007;
static final int IMAX = 2147483647;
static final int IMIN = -2147483648;
static final long LMAX = 9223372036854775807L;
static final long LMIN = -9223372036854775808L;
// math util
static int minof(int a, int b, int c) {return min(a, min(b, c));}
static int minof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;}
static long minof(long a, long b, long c) {return min(a, min(b, c));}
static long minof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;}
static int maxof(int a, int b, int c) {return max(a, max(b, c));}
static int maxof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;}
static long maxof(long a, long b, long c) {return max(a, max(b, c));}
static long maxof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;}
static int powi(int a, int b) {if (a == 0) return 0; int ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static long powl(long a, int b) {if (a == 0) return 0; long ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static int fli(double d) {return (int) d;}
static int cei(double d) {return (int) ceil(d);}
static long fll(double d) {return (long) d;}
static long cel(double d) {return (long) ceil(d);}
static int gcf(int a, int b) {return b == 0 ? a : gcf(b, a % b);}
static long gcf(long a, long b) {return b == 0 ? a : gcf(b, a % b);}
static int lcm(int a, int b) {return a * b / gcf(a, b);}
static long lcm(long a, long b) {return a * b / gcf(a, b);}
static int randInt(int min, int max) {return __rand.nextInt(max - min + 1) + min;}
static long mix(long x) {x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31);}
// array util
static void reverse(int[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(long[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(double[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(char[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void shuffle(int[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void shuffle(long[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void shuffle(double[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void rsort(int[] a) {shuffle(a); sort(a);}
static void rsort(long[] a) {shuffle(a); sort(a);}
static void rsort(double[] a) {shuffle(a); sort(a);}
static int[] copy(int[] a) {int[] ans = new int[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static long[] copy(long[] a) {long[] ans = new long[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static double[] copy(double[] a) {double[] ans = new double[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static char[] copy(char[] a) {char[] ans = new char[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
// input
static void r() throws IOException {input = new StringTokenizer(rline());}
static int ri() throws IOException {return Integer.parseInt(rline());}
static long rl() throws IOException {return Long.parseLong(rline());}
static double rd() throws IOException {return Double.parseDouble(rline());}
static int[] ria(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni(); return a;}
static int[] riam1(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni() - 1; return a;}
static long[] rla(int n) throws IOException {long[] a = new long[n]; r(); for (int i = 0; i < n; ++i) a[i] = nl(); return a;}
static double[] rda(int n) throws IOException {double[] a = new double[n]; r(); for (int i = 0; i < n; ++i) a[i] = nd(); return a;}
static char[] rcha() throws IOException {return rline().toCharArray();}
static String rline() throws IOException {return __in.readLine();}
static String n() {return input.nextToken();}
static int rni() throws IOException {r(); return ni();}
static int ni() {return Integer.parseInt(n());}
static long rnl() throws IOException {r(); return nl();}
static long nl() {return Long.parseLong(n());}
static double rnd() throws IOException {r(); return nd();}
static double nd() {return Double.parseDouble(n());}
// output
static void pr(int i) {__out.print(i);}
static void prln(int i) {__out.println(i);}
static void pr(long l) {__out.print(l);}
static void prln(long l) {__out.println(l);}
static void pr(double d) {__out.print(d);}
static void prln(double d) {__out.println(d);}
static void pr(char c) {__out.print(c);}
static void prln(char c) {__out.println(c);}
static void pr(char[] s) {__out.print(new String(s));}
static void prln(char[] s) {__out.println(new String(s));}
static void pr(String s) {__out.print(s);}
static void prln(String s) {__out.println(s);}
static void pr(Object o) {__out.print(o);}
static void prln(Object o) {__out.println(o);}
static void prln() {__out.println();}
static void pryes() {prln("yes");}
static void pry() {prln("Yes");}
static void prY() {prln("YES");}
static void prno() {prln("no");}
static void prn() {prln("No");}
static void prN() {prln("NO");}
static void pryesno(boolean b) {prln(b ? "yes" : "no");};
static void pryn(boolean b) {prln(b ? "Yes" : "No");}
static void prYN(boolean b) {prln(b ? "YES" : "NO");}
static void prln(int... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();}
static void prln(long... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();}
static void prln(double... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();}
static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for (int i = 0; i < n; pr(iter.next()), pr(' '), ++i); if (n >= 0) prln(iter.next()); else prln();}
static void h() {prln("hlfd"); flush();}
static void flush() {__out.flush();}
static void close() {__out.close();}
} | java |
1295 | C | C. Obtain The Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings ss and tt consisting of lowercase Latin letters. Also you have a string zz which is initially empty. You want string zz to be equal to string tt. You can perform the following operation to achieve this: append any subsequence of ss at the end of string zz. A subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, if z=acz=ac, s=abcdes=abcde, you may turn zz into following strings in one operation: z=acacez=acace (if we choose subsequence aceace); z=acbcdz=acbcd (if we choose subsequence bcdbcd); z=acbcez=acbce (if we choose subsequence bcebce). Note that after this operation string ss doesn't change.Calculate the minimum number of such operations to turn string zz into string tt. InputThe first line contains the integer TT (1≤T≤1001≤T≤100) — the number of test cases.The first line of each testcase contains one string ss (1≤|s|≤1051≤|s|≤105) consisting of lowercase Latin letters.The second line of each testcase contains one string tt (1≤|t|≤1051≤|t|≤105) consisting of lowercase Latin letters.It is guaranteed that the total length of all strings ss and tt in the input does not exceed 2⋅1052⋅105.OutputFor each testcase, print one integer — the minimum number of operations to turn string zz into string tt. If it's impossible print −1−1.ExampleInputCopy3
aabce
ace
abacaba
aax
ty
yyt
OutputCopy1
-1
3
| [
"dp",
"greedy",
"strings"
] | import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException{
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
int test = Integer.parseInt(r.readLine());
for (int t = 0; t < test; t++) {
char[] a = r.readLine().toCharArray();
char[] b = r.readLine().toCharArray();
if (!check(a, b)) {
pw.println(-1);
continue;
}
HashMap<Character, TreeSet<Integer>> loco = new HashMap<>();
for (int i = 0; i < a.length; i++) {
if (!loco.containsKey(a[i])) loco.put(a[i], new TreeSet<>());
loco.get(a[i]).add(i);
}
int finalans = 0;
int ai = -1;
int bi = 0;
while (bi < b.length) {
if (ai < loco.get(b[bi]).last()) {//more substring to add
ai = loco.get(b[bi]).higher(ai);
bi++;
}
else {//we reached end of string a
finalans++;
ai = -1;
}
//pw.println(ai + " " + bi);
}
//pw.println(loco);
pw.println(finalans+1);
}
r.close();
pw.close();
}
static boolean check(char[] a, char[] b) {
HashSet<Character> set = new HashSet<>();
for (int i = 0; i < a.length; i++) set.add(a[i]);
for (int i = 0; i < b.length; i++) if (!set.contains(b[i])) return false;
return true;
}
} | java |
1313 | C1 | C1. Skyscrapers (easy version)time limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an easier version of the problem. In this version n≤1000n≤1000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1≤ai≤mi1≤ai≤mi). Also there mustn't be integers jj and kk such that j<i<kj<i<k and aj>ai<akaj>ai<ak. Plots jj and kk are not required to be adjacent to ii.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer nn (1≤n≤10001≤n≤1000) — the number of plots.The second line contains the integers m1,m2,…,mnm1,m2,…,mn (1≤mi≤1091≤mi≤109) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint nn integers aiai — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInputCopy51 2 3 2 1OutputCopy1 2 3 2 1 InputCopy310 6 8OutputCopy10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10,6,6][10,6,6] is optimal. Note that the answer of [6,6,8][6,6,8] also satisfies all restrictions, but is not optimal. | [
"brute force",
"data structures",
"dp",
"greedy"
] | //Some of the methods are copied from GeeksforGeeks Website
import java.util.*;
import java.lang.*;
import java.io.*;
public class C_1_Skyscrapers_easy_version
{
//static Scanner sc=new Scanner(System.in);
//static Reader sc=new Reader();
static FastReader sc=new FastReader(System.in);
static long mod = (long)(1e9)+ 7;
static int max_num=(int)1e5+5;
public static void main (String[] args) throws java.lang.Exception
{
try{
/*
Collections.sort(al,(a,b)->a.x-b.x);
Collections.sort(al,Collections.reverseOrder());
StringBuilder sb=new StringBuilder(""); sb.append(cur); sb=sb.reverse(); String rev=sb.toString();
long n=sc.nextLong();
String s=sc.next();
char a[]=s.toCharArray();
StringBuilder sb=new StringBuilder();
map.put(a[i],map.getOrDefault(a[i],0)+1);
map.putIfAbsent(x,new ArrayList<>());
out.println("Case #"+tt+": "+ans );
*/
int t =1;// sc.nextInt();
for(int tt=1;tt<=t;tt++)
{
int n=sc.nextInt();
long a[]=new long[n];
for(int i=0;i<n;i++)
{
a[i]=sc.nextLong();
}
long max=0;
int point=0;
for(int i=0;i<n;i++)
{
long c[]=new long[n];
c[i]=a[i];
for(int j=i-1;j>=0;j--)
{
long cur=a[j];
long min=Math.min(cur,c[j+1]);
c[j]=min;
}
for(int j=i+1;j<n;j++)
{
long cur=a[j];
long min=Math.min(cur,c[j-1]);
c[j]=min;
}
long sum=sum_array(c);
if(sum>max)
{
max=sum;
point=i;
}
}
long ans[]=new long[n];
ans[point]=a[point];
for(int j=point-1;j>=0;j--)
{
long cur=a[j];
long min=Math.min(cur,ans[j+1]);
ans[j]=min;
}
for(int j=point+1;j<n;j++)
{
long cur=a[j];
long min=Math.min(cur,ans[j-1]);
ans[j]=min;
}
print(ans);
//out.println( );
}
out.flush();
out.close();
}
catch(Exception e)
{}
}
/*
...SOLUTION ENDS HERE...........SOLUTION ENDS HERE...
*/
static void flag(boolean flag)
{
out.println(flag ? "YES" : "NO");
out.flush();
}
/*
Map<Long,Long> map=new HashMap<>();
for(int i=0;i<n;i++)
{
if(!map.containsKey(a[i]))
map.put(a[i],1);
else
map.replace(a[i],map.get(a[i])+1);
}
Set<Map.Entry<Long,Long>> hmap=map.entrySet();
for(Map.Entry<Long,Long> data : hmap)
{
}
Iterator<Integer> itr = set.iterator();
while(itr.hasNext())
{
int val=itr.next();
}
*/
// static class Pair
// {
// int x,y;
// Pair(int x,int y)
// {
// this.x=x;
// this.y=y;
// }
// }
// Arrays.sort(p, new Comparator<Pair>()
// {
// @Override
// public int compare(Pair o1,Pair o2)
// {
// if(o1.x>o2.x) return 1;
// else if(o1.x==o2.x)
// {
// if(o1.y>o2.y) return 1;
// else return -1;
// }
// else return -1;
// }});
static void print(int a[])
{
int n=a.length;
for(int i=0;i<n;i++)
{
out.print(a[i]+" ");
}
out.println();
out.flush();
}
static void print(long a[])
{
int n=a.length;
for(int i=0;i<n;i++)
{
out.print(a[i]+" ");
}
out.println();
out.flush();
}
static void print_int(ArrayList<Integer> al)
{
int si=al.size();
for(int i=0;i<si;i++)
{
out.print(al.get(i)+" ");
}
out.println();
out.flush();
}
static void print_long(ArrayList<Long> al)
{
int si=al.size();
for(int i=0;i<si;i++)
{
out.print(al.get(i)+" ");
}
out.println();
out.flush();
}
static void pn(int x)
{
out.println(x);
out.flush();
}
static void pn(long x)
{
out.println(x);
out.flush();
}
static void pn(String x)
{
out.println(x);
out.flush();
}
static int LowerBound(int a[], int x)
{
int l=-1,r=a.length;
while(l+1<r) {
int m=(l+r)>>>1;
if(a[m]>=x) r=m;
else l=m;
}
return r;
}
static int UpperBound(int a[], int x)
{// x is the key or target value
int l=-1,r=a.length;
while(l+1<r) {
int m=(l+r)>>>1;
if(a[m]<=x) l=m;
else r=m;
}
return l+1;
}
static void DFS(ArrayList<Integer> graph[],boolean[] visited, int u)
{
visited[u]=true;
int v=0;
for(int i=0;i<graph[u].size();i++)
{
v=graph[u].get(i);
if(!visited[v])
DFS(graph,visited,v);
}
}
static boolean[] prime(int num)
{
boolean[] bool = new boolean[num];
for (int i = 0; i< bool.length; i++) {
bool[i] = true;
}
for (int i = 2; i< Math.sqrt(num); i++) {
if(bool[i] == true) {
for(int j = (i*i); j<num; j = j+i) {
bool[j] = false;
}
}
}
if(num >= 0) {
bool[0] = false;
bool[1] = false;
}
return bool;
}
static long nCr(long a,long b,long mod)
{
return (((fact[(int)a] * modInverse(fact[(int)b],mod))%mod * modInverse(fact[(int)(a - b)],mod))%mod + mod)%mod;
}
static long fact[]=new long[max_num];
static void fact_fill()
{
fact[0]=1l;
for(int i=1;i<max_num;i++)
{
fact[i]=(fact[i-1]*(long)i);
if(fact[i]>=mod)
fact[i]%=mod;
}
}
static long modInverse(long a, long m)
{
return power(a, m - 2, m);
}
static long power(long x, long y, long m)
{
if (y == 0)
return 1;
long p = power(x, y / 2, m) % m;
p = (long)((p * (long)p) % m);
if (y % 2 == 0)
return p;
else
return (long)((x * (long)p) % m);
}
static long sum_array(int a[])
{
int n=a.length;
long sum=0;
for(int i=0;i<n;i++)
sum+=a[i];
return sum;
}
static long sum_array(long a[])
{
int n=a.length;
long sum=0;
for(int i=0;i<n;i++)
sum+=a[i];
return sum;
}
static void sort(int[] a)
{
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static void sort(long[] a)
{
ArrayList<Long> l=new ArrayList<>();
for (long i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static void reverse_array(int a[])
{
int n=a.length;
int i,t;
for (i = 0; i < n / 2; i++) {
t = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = t;
}
}
static void reverse_array(long a[])
{
int n=a.length;
int i; long t;
for (i = 0; i < n / 2; i++) {
t = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = t;
}
}
static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
static class FastReader{
byte[] buf = new byte[2048];
int index, total;
InputStream in;
FastReader(InputStream is) {
in = is;
}
int scan() throws IOException {
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0) {
return -1;
}
}
return buf[index++];
}
String next() throws IOException {
int c;
for (c = scan(); c <= 32; c = scan());
StringBuilder sb = new StringBuilder();
for (; c > 32; c = scan()) {
sb.append((char) c);
}
return sb.toString();
}
int nextInt() throws IOException {
int c, val = 0;
for (c = scan(); c <= 32; c = scan());
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
long nextLong() throws IOException {
int c;
long val = 0;
for (c = scan(); c <= 32; c = scan());
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
}
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
static PrintWriter out=new PrintWriter(System.out);
static int int_max=Integer.MAX_VALUE;
static int int_min=Integer.MIN_VALUE;
static long long_max=Long.MAX_VALUE;
static long long_min=Long.MIN_VALUE;
}
// Thank You ! | java |
1285 | C | C. Fadi and LCMtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Osama gave Fadi an integer XX, and Fadi was wondering about the minimum possible value of max(a,b)max(a,b) such that LCM(a,b)LCM(a,b) equals XX. Both aa and bb should be positive integers.LCM(a,b)LCM(a,b) is the smallest positive integer that is divisible by both aa and bb. For example, LCM(6,8)=24LCM(6,8)=24, LCM(4,12)=12LCM(4,12)=12, LCM(2,3)=6LCM(2,3)=6.Of course, Fadi immediately knew the answer. Can you be just like Fadi and find any such pair?InputThe first and only line contains an integer XX (1≤X≤10121≤X≤1012).OutputPrint two positive integers, aa and bb, such that the value of max(a,b)max(a,b) is minimum possible and LCM(a,b)LCM(a,b) equals XX. If there are several possible such pairs, you can print any.ExamplesInputCopy2
OutputCopy1 2
InputCopy6
OutputCopy2 3
InputCopy4
OutputCopy1 4
InputCopy1
OutputCopy1 1
| [
"brute force",
"math",
"number theory"
] | import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import java.util.*;
import java.io.*;
import java.math.*;
public class C_Fadi_and_LCM {
static long mod = Long.MAX_VALUE;
public static void main(String[] args) {
OutputStream outputStream = System.out;
PrintWriter out = new PrintWriter(outputStream);
FastReader f = new FastReader();
int t = 1;
while(t-- > 0){
solve(f, out);
}
out.close();
}
public static void solve(FastReader f, PrintWriter out) {
long x = f.nextLong();
if(x == 1) {
out.println(1 + " " + 1);
return;
}
ArrayList<Long> factors = new ArrayList<>();
allDivisors(x, factors);
// Collections.sort(factors);
// out.println(factors.size());
long first = Long.MAX_VALUE;
long second = Long.MAX_VALUE;
for(int i = 0; i < factors.size(); i++) {
if(lcm(factors.get(i), x/factors.get(i)) == x) {
long p = factors.get(i);
long q = x/factors.get(i);
if(max(first, second) > max(p, q)) {
first = p;
second = q;
}
}
}
// for(int i = 0; i < factors.size(); i++) {
// for(int j = i+1; j < factors.size(); j++) {
// long p = factors.get(i);
// long q = factors.get(j);
// if(gcd(p, q) == 1) {
// long cf = x / (p*q);
// p *= cf;
// q *= cf;
// long max = max(p, q);
// if(max < first) {
// first = max;
// second = min(p, q);
// }
// }
// }
// }
out.println(first + " " + second);
}
// Sort an array
public static void sort(int arr[]) {
ArrayList<Integer> al = new ArrayList<>();
for(int i: arr) {
al.add(i);
}
Collections.sort(al);
for(int i = 0; i < arr.length; i++) {
arr[i] = al.get(i);
}
}
// Find all divisors of n
public static void allDivisors(long n, ArrayList<Long> arrli) {
for(long i = 1; i*i <= n; i++) {
if(n%i == 0) {
arrli.add(i);
}
}
}
// Check if n is prime or not
public static boolean isPrime(int n) {
if(n < 1) return false;
if(n == 2 || n == 3) return true;
if(n % 2 == 0 || n % 3 == 0) return false;
for(int i = 5; i*i <= n; i += 6) {
if(n % i == 0 || n % (i+2) == 0) {
return false;
}
}
return true;
}
// Find gcd of a and b
public static long gcd(long a, long b) {
long dividend = a > b ? a : b;
long divisor = a < b ? a : b;
while(divisor > 0) {
long reminder = dividend % divisor;
dividend = divisor;
divisor = reminder;
}
return dividend;
}
// Find lcm of a and b
public static long lcm(long a, long b) {
long lcm = gcd(a, b);
long hcf = (a * b) / lcm;
return hcf;
}
// Find factorial in O(n) time
public static long fact(int n) {
long res = 1;
for(int i = 2; i <= n; i++) {
res = res * i;
}
return res;
}
// Find power in O(logb) time
public static long power(long a, long b) {
long res = 1;
while(b > 0) {
if((b&1) == 1) {
res = (res * a)%mod;
}
a = (a * a)%mod;
b >>= 1;
}
return res;
}
// Find nCr
public static long nCr(int n, int r) {
if(r < 0 || r > n) {
return 0;
}
long ans = fact(n) / (fact(r) * fact(n-r));
return ans;
}
// Find nPr
public static long nPr(int n, int r) {
if(r < 0 || r > n) {
return 0;
}
long ans = fact(n) / fact(r);
return ans;
}
// sort all characters of a string
public static String sortString(String inputString) {
char tempArray[] = inputString.toCharArray();
Arrays.sort(tempArray);
return new String(tempArray);
}
// User defined class for fast I/O
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
boolean hasNext() {
if (st != null && st.hasMoreTokens()) {
return true;
}
String tmp;
try {
br.mark(1000);
tmp = br.readLine();
if (tmp == null) {
return false;
}
br.reset();
} catch (IOException e) {
return false;
}
return true;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
float nextFloat() {
return Float.parseFloat(next());
}
boolean nextBoolean() {
return Boolean.parseBoolean(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] nextArray(int n) {
int[] a = new int[n];
for(int i=0; i<n; i++) {
a[i] = nextInt();
}
return a;
}
}
}
/**
Dec Char Dec Char Dec Char Dec Char
--------- --------- --------- ----------
0 NUL (null) 32 SPACE 64 @ 96 `
1 SOH (start of heading) 33 ! 65 A 97 a
2 STX (start of text) 34 " 66 B 98 b
3 ETX (end of text) 35 # 67 C 99 c
4 EOT (end of transmission) 36 $ 68 D 100 d
5 ENQ (enquiry) 37 % 69 E 101 e
6 ACK (acknowledge) 38 & 70 F 102 f
7 BEL (bell) 39 ' 71 G 103 g
8 BS (backspace) 40 ( 72 H 104 h
9 TAB (horizontal tab) 41 ) 73 I 105 i
10 LF (NL line feed, new line) 42 * 74 J 106 j
11 VT (vertical tab) 43 + 75 K 107 k
12 FF (NP form feed, new page) 44 , 76 L 108 l
13 CR (carriage return) 45 - 77 M 109 m
14 SO (shift out) 46 . 78 N 110 n
15 SI (shift in) 47 / 79 O 111 o
16 DLE (data link escape) 48 0 80 P 112 p
17 DC1 (device control 1) 49 1 81 Q 113 q
18 DC2 (device control 2) 50 2 82 R 114 r
19 DC3 (device control 3) 51 3 83 S 115 s
20 DC4 (device control 4) 52 4 84 T 116 t
21 NAK (negative acknowledge) 53 5 85 U 117 u
22 SYN (synchronous idle) 54 6 86 V 118 v
23 ETB (end of trans. block) 55 7 87 W 119 w
24 CAN (cancel) 56 8 88 X 120 x
25 EM (end of medium) 57 9 89 Y 121 y
26 SUB (substitute) 58 : 90 Z 122 z
27 ESC (escape) 59 ; 91 [ 123 {
28 FS (file separator) 60 < 92 \ 124 |
29 GS (group separator) 61 = 93 ] 125 }
30 RS (record separator) 62 > 94 ^ 126 ~
31 US (unit separator) 63 ? 95 _ 127 DEL
*/
// (a/b)%mod == (a * moduloInverse(b)) % mod;
// moduloInverse(b) = power(b, mod-2);
| java |
1295 | D | D. Same GCDstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers aa and mm. Calculate the number of integers xx such that 0≤x<m0≤x<m and gcd(a,m)=gcd(a+x,m)gcd(a,m)=gcd(a+x,m).Note: gcd(a,b)gcd(a,b) is the greatest common divisor of aa and bb.InputThe first line contains the single integer TT (1≤T≤501≤T≤50) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains two integers aa and mm (1≤a<m≤10101≤a<m≤1010).OutputPrint TT integers — one per test case. For each test case print the number of appropriate xx-s.ExampleInputCopy3
4 9
5 10
42 9999999967
OutputCopy6
1
9999999966
NoteIn the first test case appropriate xx-s are [0,1,3,4,6,7][0,1,3,4,6,7].In the second test case the only appropriate xx is 00. | [
"math",
"number theory"
] | import java.io.*;
import java.util.*;
import java.math.BigInteger;
/**
__ __
( _) ( _)
/ / \\ / /\_\_
/ / \\ / / | \ \
/ / \\ / / |\ \ \
/ / , \ , / / /| \ \
/ / |\_ /| / / / \ \_\
/ / |\/ _ '_| \ / / / \ \\
| / |/ 0 \0\ / | | \ \\
| |\| \_\_ / / | \ \\
| | |/ \.\ o\o) / \ | \\
\ | /\\`v-v / | | \\
| \/ /_| \\_| / | | \ \\
| | /__/_ `-` / _____ | | \ \\
\| [__] \_/ |_________ \ | \ ()
/ [___] ( \ \ |\ | | //
| [___] |\| \| / |/
/| [____] \ |/\ / / ||
( \ [____ / ) _\ \ \ \| | ||
\ \ [_____| / / __/ \ / / //
| \ [_____/ / / \ | \/ //
| / '----| /=\____ _/ | / //
__ / / | / ___/ _/\ \ | ||
(/-(/-\) / \ (/\/\)/ | / | /
(/\/\) / / //
_________/ / /
\____________/ (
@author NTUDragons-Reborn
*/
public class C{
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Task solver = new Task();
solver.solve(in, out);
out.close();
}
// main solver
static class Task{
double eps= 0.00000001;
static final int MAXN = 100005;
static final int MOD= 998244353;
// stores smallest prime factor for every number
static int spf[] = new int[MAXN];
Map<Integer,Set<Integer>> dp= new HashMap<>();
// Calculating SPF (Smallest Prime Factor) for every
// number till MAXN.
// Time Complexity : O(nloglogn)
public void sieve()
{
spf[1] = 1;
for (int i=2; i<MAXN; i++)
// marking smallest prime factor for every
// number to be itself.
spf[i] = i;
// separately marking spf for every even
// number as 2
for (int i=4; i<MAXN; i+=2)
spf[i] = 2;
for (int i=3; i*i<MAXN; i++)
{
// checking if i is prime
if (spf[i] == i)
{
// marking SPF for all numbers divisible by i
for (int j=i*i; j<MAXN; j+=i)
// marking spf[j] if it is not
// previously marked
if (spf[j]==j)
spf[j] = i;
}
}
}
// A O(log n) function returning primefactorization
// by dividing by smallest prime factor at every step
public Set<Integer> getFactorization(int x)
{
if(dp.containsKey(x)) return dp.get(x);
Set<Integer> ret = new HashSet<>();
while (x != 1)
{
if(spf[x]!=2) ret.add(spf[x]);
x = x / spf[x];
}
dp.put(x,ret);
return ret;
}
// function to find first index >= x
public int lowerIndex(List<Integer> arr, int n, int x)
{
int l = 0, h = n - 1;
while (l <= h)
{
int mid = (l + h) / 2;
if (arr.get(mid) >= x)
h = mid - 1;
else
l = mid + 1;
}
return l;
}
// function to find last index <= y
public int upperIndex(List<Integer> arr, int n, int y)
{
int l = 0, h = n - 1;
while (l <= h)
{
int mid = (l + h) / 2;
if (arr.get(mid) <= y)
l = mid + 1;
else
h = mid - 1;
}
return h;
}
// function to count elements within given range
public int countInRange(List<Integer> arr, int n, int x, int y)
{
// initialize result
int count = 0;
count = upperIndex(arr, n, y) -
lowerIndex(arr, n, x) + 1;
return count;
}
public int add(int a, int b){
a+=b;
if(a>=MOD) a-=MOD;
else if(a<0) a+=MOD;
return a;
}
public int mul(int a, int b){
long res= (long)a*(long)b;
return (int)(res%MOD);
}
public int power(int a, int b) {
int ans=1;
while(b>0){
if((b&1)!=0) ans= mul(ans,a);
b>>=1;
a= mul(a,a);
}
return ans;
}
int[] fact= new int[MAXN];
int[] inv= new int[MAXN];
public int Ckn(int n, int k){
if(k<0 || n<0) return 0;
return mul(mul(fact[n],inv[k]),inv[n-k]);
}
public int inverse(int a){
return power(a,MOD-2);
}
public void preprocess() {
fact[0]=1;
for(int i=1;i<MAXN;i++) fact[i]= mul(fact[i-1],i);
inv[MAXN-1]= inverse(fact[MAXN-1]);
for(int i=MAXN-2;i>=0;i--){
inv[i]= mul(inv[i+1],i+1);
}
}
public void solve(InputReader in, PrintWriter out) {
int t= in.nextInt();
while(t-->0){
long a= in.nextLong(), m= in.nextLong();
out.println(phi(m/_gcd(a,m)));
}
}
public long phi(long n) {
long result = n;
for (long i = 2; 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;
}
class Cell{
public int i,j,l,r;
public Cell (int i, int j, int l, int r){
this.i=i; this.j=j; this.l= l; this.r= r;
}
}
// public static class compareL implements Comparator<Tuple>{
// @Override
// public int compare(Tuple t1, Tuple t2) {
// return t2.l - t1.l;
// }
// }
public int _gcd(int a, int b)
{
if(b == 0) {
return a;
}
else {
return _gcd(b, a % b);
}
}
public long _gcd(long a, long b){
if(b == 0) {
return a;
}
else {
return _gcd(b, a % b);
}
}
}
static class Venice{
public Map<Long,Long> m= new HashMap<>();
public long base=0;
public long totalValue=0;
private int M= 1000000007;
private long addMod(long a, long b){
a+=b;
if(a>=M) a-=M;
return a;
}
public void reset(){
m= new HashMap<>();
base=0;
totalValue=0;
}
public void update(long add){
base= base+ add;
}
public void add(long key, long val){
long newKey= key-base;
m.put(newKey, addMod(m.getOrDefault(newKey,(long)0),val));
}
}
static class Tuple implements Comparable<Tuple>{
int x, y, z;
public Tuple(int x, int y, int z){
this.x= x;
this.y= y;
this.z=z;
}
@Override
public int compareTo(Tuple o){
return this.x-o.x;
}
}
static class Pair implements Comparable<Pair>{
public int x;
public int y;
public Pair(int x, int y){
this.x= x;
this.y= y;
}
@Override
public int compareTo(Pair o) {
return this.x-o.x;
}
}
// fast input reader class;
static class InputReader {
BufferedReader br;
StringTokenizer st;
public InputReader(InputStream stream) {
br = new BufferedReader(new InputStreamReader(stream));
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
String line = null;
try {
line = br.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
if (line == null) {
return null;
}
st = new StringTokenizer(line);
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public double nextDouble(){
return Double.parseDouble(nextToken());
}
public long nextLong(){
return Long.parseLong(nextToken());
}
}
} | java |
1141 | F1 | F1. Same Sum Blocks (Easy)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],…,a[n].a[1],a[2],…,a[n]. A block is a sequence of contiguous (consecutive) elements a[l],a[l+1],…,a[r]a[l],a[l+1],…,a[r] (1≤l≤r≤n1≤l≤r≤n). Thus, a block is defined by a pair of indices (l,r)(l,r).Find a set of blocks (l1,r1),(l2,r2),…,(lk,rk)(l1,r1),(l2,r2),…,(lk,rk) such that: They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks (li,ri)(li,ri) and (lj,rj(lj,rj) where i≠ji≠j either ri<ljri<lj or rj<lirj<li. For each block the sum of its elements is the same. Formally, a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]=a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]= ⋯=⋯= a[lk]+a[lk+1]+⋯+a[rk].a[lk]+a[lk+1]+⋯+a[rk]. The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks (l′1,r′1),(l′2,r′2),…,(l′k′,r′k′)(l1′,r1′),(l2′,r2′),…,(lk′′,rk′′) satisfying the above two requirements with k′>kk′>k. The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks.InputThe first line contains integer nn (1≤n≤501≤n≤50) — the length of the given array. The second line contains the sequence of elements a[1],a[2],…,a[n]a[1],a[2],…,a[n] (−105≤ai≤105−105≤ai≤105).OutputIn the first line print the integer kk (1≤k≤n1≤k≤n). The following kk lines should contain blocks, one per line. In each line print a pair of indices li,rili,ri (1≤li≤ri≤n1≤li≤ri≤n) — the bounds of the ii-th block. You can print blocks in any order. If there are multiple answers, print any of them.ExamplesInputCopy7
4 1 2 2 1 5 3
OutputCopy3
7 7
2 3
4 5
InputCopy11
-5 -4 -3 -2 -1 0 1 2 3 4 5
OutputCopy2
3 4
1 1
InputCopy4
1 1 1 1
OutputCopy4
4 4
1 1
2 2
3 3
| [
"greedy"
] | import java.io.*;
import java.util.*;
public class ProblemA {
public static void main(String[] args) throws Exception {
Scanner in = new Scanner();
int n = in.readInt();
int a[] = new int[n];
for(int i = 0;i<n;i++)a[i] = in.readInt();
ArrayList<Pair>res = new ArrayList<>();
for(int i = 0;i<n;i++){
long sum =0;
for(int j = i;j<n;j++){
sum+=a[j];
HashMap<Long,Integer>mp = new HashMap<>();
ArrayList<Pair>l = new ArrayList<>();
mp.put(0l, -1);
long cur = 0;
for(int z = 0;z<n;z++){
cur+=a[z];
if(mp.containsKey(cur - sum)){
l.add(new Pair(mp.get(cur-sum)+2,z+1));
mp.clear();
}
mp.put(cur, z);
}
if(l.size()>res.size()){
res = l;
}
}
}
System.out.println(res.size());
for(Pair it:res)System.out.println(it.x+" "+it.y);
}
public static void build(int seg[],int ind,int l,int r,int a[]){
if(l == r){
seg[ind] = a[l];
return;
}
int mid = (l+r)/2;
build(seg,(2*ind)+1,l,mid,a);
build(seg,(2*ind)+2,mid+1,r,a);
seg[ind] = Math.min(seg[(2*ind)+1],seg[(2*ind)+2]);
}
public static long gcd(long a, long b){
return b ==0 ?a:gcd(b,a%b);
}
public static long nearest(TreeSet<Long> list,long target){
long nearest = -1,sofar = Integer.MAX_VALUE;
for(long it:list){
if(Math.abs(it - target)<sofar){
sofar = Math.abs(it - target);
nearest = it;
}
}
return nearest;
}
public static ArrayList<Long> factors(long n){
ArrayList<Long>l = new ArrayList<>();
for(long i = 1;i*i<=n;i++){
if(n%i == 0){
l.add(i);
if(n/i != i)l.add(n/i);
}
}
Collections.sort(l);
return l;
}
public static void swap(int a[],int i, int j){
int t = a[i];
a[i] = a[j];
a[j] = t;
}
public static boolean isSorted(long a[]){
for(int i =0;i<a.length;i++){
if(i+1<a.length && a[i]>a[i+1])return false;
}
return true;
}
public static int first(ArrayList<Long>list,long target){
int index = -1;
int l = 0,r = list.size()-1;
while(l<=r){
int mid = (l+r)/2;
if(list.get(mid) == target){
index = mid;
r = mid-1;
}else if(list.get(mid)>target){
r = mid-1;
}else l = mid+1;
}
return index;
}
public static int last(ArrayList<Long>list,long target){
int index = -1;
int l = 0,r = list.size()-1;
while(l<=r){
int mid = (l+r)/2;
if(list.get(mid) == target){
index= mid;
l = mid+1;
}else if(list.get(mid)<target){
l = mid+1;
}else r = mid-1;
}
return index;
}
public static void sort(int arr[]){
ArrayList<Integer>list = new ArrayList<>();
for(int it:arr)list.add(it);
Collections.sort(list);
for(int i = 0;i<arr.length;i++)arr[i] = list.get(i);
}
static class Pair{
int x,y;
public Pair(int x,int y){
this.x = x;
this.y = y;
}
}
static class Scanner{
BufferedReader br;
StringTokenizer st;
public Scanner(){
br = new BufferedReader(new InputStreamReader(System.in));
}
public String read()
{
while (st == null || !st.hasMoreElements()) {
try { st = new StringTokenizer(br.readLine()); }
catch (Exception e) { e.printStackTrace(); }
}
return st.nextToken();
}
public int readInt() { return Integer.parseInt(read()); }
public long readLong() { return Long.parseLong(read()); }
public double readDouble(){return Double.parseDouble(read());}
public String readLine() throws Exception { return br.readLine(); }
}
}
| java |
1301 | C | C. Ayoub's functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAyoub thinks that he is a very smart person; so he created a function f(s)f(s), where ss is a binary string (a string which contains only symbols "0" and "1"). The function f(s)f(s) is equal to the number of substrings in the string ss that contains at least one symbol, that is equal to "1".More formally, f(s)f(s) is equal to the number of pairs of integers (l,r)(l,r), such that 1≤l≤r≤|s|1≤l≤r≤|s| (where |s||s| is equal to the length of string ss), such that at least one of the symbols sl,sl+1,…,srsl,sl+1,…,sr is equal to "1". For example, if s=s="01010" then f(s)=12f(s)=12, because there are 1212 such pairs (l,r)(l,r): (1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5)(1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5).Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers nn and mm and asked him this problem. For all binary strings ss of length nn which contains exactly mm symbols equal to "1", find the maximum value of f(s)f(s).Mahmoud couldn't solve the problem so he asked you for help. Can you help him? InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1051≤t≤105) — the number of test cases. The description of the test cases follows.The only line for each test case contains two integers nn, mm (1≤n≤1091≤n≤109, 0≤m≤n0≤m≤n) — the length of the string and the number of symbols equal to "1" in it.OutputFor every test case print one integer number — the maximum value of f(s)f(s) over all strings ss of length nn, which has exactly mm symbols, equal to "1".ExampleInputCopy5
3 1
3 2
3 3
4 0
5 2
OutputCopy4
5
6
0
12
NoteIn the first test case; there exists only 33 strings of length 33, which has exactly 11 symbol, equal to "1". These strings are: s1=s1="100", s2=s2="010", s3=s3="001". The values of ff for them are: f(s1)=3,f(s2)=4,f(s3)=3f(s1)=3,f(s2)=4,f(s3)=3, so the maximum value is 44 and the answer is 44.In the second test case, the string ss with the maximum value is "101".In the third test case, the string ss with the maximum value is "111".In the fourth test case, the only string ss of length 44, which has exactly 00 symbols, equal to "1" is "0000" and the value of ff for that string is 00, so the answer is 00.In the fifth test case, the string ss with the maximum value is "01010" and it is described as an example in the problem statement. | [
"binary search",
"combinatorics",
"greedy",
"math",
"strings"
] | import java.io.*;
import java.util.*;
public class function {
public static void main(String[] args) throws IOException {
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
int testcases = Integer.parseInt(r.readLine());
for (int t = 0; t < testcases; t++) {
StringTokenizer st = new StringTokenizer(r.readLine());
long len = Integer.parseInt(st.nextToken());
long ones = Integer.parseInt(st.nextToken());
long zeroes = len-ones;
long complement = 0;
complement += substrings(zeroes/(ones+1)+1) * (zeroes%(ones+1));
//pw.println(substrings(zeroes/(ones+1)+1));
//pw.println("complement is " + complement);
complement += substrings(zeroes/(ones+1)) * ((ones+1)-zeroes%(ones+1));
long total = len*(len+1)/2;
//pw.println("complement is " + complement);
pw.println(total - complement);
}
pw.close();
}
public static long substrings(long n) {
return n*(n+1)/2;
}
} | java |
1301 | F | F. Super Jabertime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputJaber is a superhero in a large country that can be described as a grid with nn rows and mm columns, where every cell in that grid contains a different city.Jaber gave every city in that country a specific color between 11 and kk. In one second he can go from the current city to any of the cities adjacent by the side or to any city with the same color as the current city color.Jaber has to do qq missions. In every mission he will be in the city at row r1r1 and column c1c1, and he should help someone in the city at row r2r2 and column c2c2.Jaber wants your help to tell him the minimum possible time to go from the starting city to the finishing city for every mission.InputThe first line contains three integers nn, mm and kk (1≤n,m≤10001≤n,m≤1000, 1≤k≤min(40,n⋅m)1≤k≤min(40,n⋅m)) — the number of rows, columns and colors.Each of the next nn lines contains mm integers. In the ii-th line, the jj-th integer is aijaij (1≤aij≤k1≤aij≤k), which is the color assigned to the city in the ii-th row and jj-th column.The next line contains one integer qq (1≤q≤1051≤q≤105) — the number of missions.For the next qq lines, every line contains four integers r1r1, c1c1, r2r2, c2c2 (1≤r1,r2≤n1≤r1,r2≤n, 1≤c1,c2≤m1≤c1,c2≤m) — the coordinates of the starting and the finishing cities of the corresponding mission.It is guaranteed that for every color between 11 and kk there is at least one city of that color.OutputFor every mission print the minimum possible time to reach city at the cell (r2,c2)(r2,c2) starting from city at the cell (r1,c1)(r1,c1).ExamplesInputCopy3 4 5
1 2 1 3
4 4 5 5
1 2 1 3
2
1 1 3 4
2 2 2 2
OutputCopy2
0
InputCopy4 4 8
1 2 2 8
1 3 4 7
5 1 7 6
2 3 8 8
4
1 1 2 2
1 1 3 4
1 1 2 4
1 1 4 4
OutputCopy2
3
3
4
NoteIn the first example: mission 11: Jaber should go from the cell (1,1)(1,1) to the cell (3,3)(3,3) because they have the same colors, then from the cell (3,3)(3,3) to the cell (3,4)(3,4) because they are adjacent by side (two moves in total); mission 22: Jaber already starts in the finishing cell. In the second example: mission 11: (1,1)(1,1) →→ (1,2)(1,2) →→ (2,2)(2,2); mission 22: (1,1)(1,1) →→ (3,2)(3,2) →→ (3,3)(3,3) →→ (3,4)(3,4); mission 33: (1,1)(1,1) →→ (3,2)(3,2) →→ (3,3)(3,3) →→ (2,4)(2,4); mission 44: (1,1)(1,1) →→ (1,2)(1,2) →→ (1,3)(1,3) →→ (1,4)(1,4) →→ (4,4)(4,4). | [
"dfs and similar",
"graphs",
"implementation",
"shortest paths"
] | //package round619;
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 F {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni(), m = ni(), K = ni();
int[][] a = new int[n][];
for(int i = 0;i < n;i++) {
a[i] = na(m);
for(int j = 0;j < m;j++)a[i][j]--;
}
int[][] b = new int[K][n*m];
int[] bp = new int[K];
for(int i = 0;i < n;i++) {
for(int j = 0;j < m;j++) {
b[a[i][j]][bp[a[i][j]]++] = i*m+j;
}
}
for(int i = 0;i < K;i++)b[i] = Arrays.copyOf(b[i], bp[i]);
int[] dr = { 1, 0, -1, 0 };
int[] dc = { 0, 1, 0, -1 };
int[][] dss = new int[K][];
DQ q = new DQ(10005000);
for(int k = 0;k < K;k++) {
int[] ds = new int[n*m+K];
// Deque<Integer> q = new ArrayDeque<>();
q.clear();
q.addLast(n*m+k);
Arrays.fill(ds, 99999999);
ds[n*m+k] = 0;
while(!q.isEmpty()) {
int cur = q.pollFirst();
if(cur >= n*m) {
int id = cur-n*m;
for(int j = 0;j < bp[id];j++) {
int to = b[id][j];
// int nr = to / m, nc = to % m;
if(ds[to] > ds[cur] + 1) {
ds[to] = ds[cur] + 1;
q.addLast(to);
}
}
}else {
int r = cur/m, c = cur-r*m;
for(int u = 0;u < 4;u++) {
int nr = r + dr[u], nc = c + dc[u];
if(nr >= 0 && nr < n && nc >= 0 && nc < m && ds[nr*m+nc] > ds[cur] + 1) {
ds[nr*m+nc] = ds[cur] + 1;
q.addLast(nr*m+nc);
}
}
int to = n*m+a[r][c];
if(ds[to] > ds[cur]) {
ds[to] = ds[cur];
q.addFirst(to);
}
}
}
dss[k] = ds;
}
for(int Q = ni();Q > 0;Q--) {
int r1 = ni()-1, c1 = ni()-1, r2 = ni()-1, c2 = ni()-1;
int ans = Math.abs(r1-r2) + Math.abs(c1-c2);
for(int k = 0;k < K;k++) {
ans = Math.min(ans, dss[k][r2*m+c2] + dss[k][r1*m+c1] - 1);
}
out.println(ans);
}
}
public static class DQ {
public int[] q;
public int n;
protected int pt, ph;
public DQ(int n){ this.n = Integer.highestOneBit(n)<<1; q = new int[this.n]; pt = ph = 0; }
public void addLast(int x){ q[ph] = x; ph = ph+1&n-1; }
public void addFirst(int x){ pt = pt+n-1&n-1; q[pt] = x; }
public int pollFirst(){ int ret = q[pt]; pt = pt+1&n-1; return ret; }
public int pollLast(){ ph = ph+n-1&n-1; int ret = q[ph]; return ret; }
public int getFirst(){ return q[pt]; }
public int getFirst(int k){ return q[pt+k&n-1]; }
public int getLast(){ return q[ph+n-1&n-1]; }
public int getLast(int k){ return q[ph+n-k-1&n-1]; }
public void clear(){ pt = ph = 0; }
public int size(){ return ph-pt+n&n-1; }
public boolean isEmpty(){ return ph==pt; }
}
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 |
1307 | B | B. Cow and Friendtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically; he wants to get from (0,0)(0,0) to (x,0)(x,0) by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its nn favorite numbers: a1,a2,…,ana1,a2,…,an. What is the minimum number of hops Rabbit needs to get from (0,0)(0,0) to (x,0)(x,0)? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination.Recall that the Euclidean distance between points (xi,yi)(xi,yi) and (xj,yj)(xj,yj) is (xi−xj)2+(yi−yj)2−−−−−−−−−−−−−−−−−−√(xi−xj)2+(yi−yj)2.For example, if Rabbit has favorite numbers 11 and 33 he could hop from (0,0)(0,0) to (4,0)(4,0) in two hops as shown below. Note that there also exists other valid ways to hop to (4,0)(4,0) in 22 hops (e.g. (0,0)(0,0) →→ (2,−5–√)(2,−5) →→ (4,0)(4,0)). Here is a graphic for the first example. Both hops have distance 33, one of Rabbit's favorite numbers. In other words, each time Rabbit chooses some number aiai and hops with distance equal to aiai in any direction he wants. The same number can be used multiple times.InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤10001≤t≤1000) — the number of test cases. Next 2t2t lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and xx (1≤n≤1051≤n≤105, 1≤x≤1091≤x≤109) — the number of favorite numbers and the distance Rabbit wants to travel, respectively.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109) — Rabbit's favorite numbers. It is guaranteed that the favorite numbers are distinct.It is guaranteed that the sum of nn over all the test cases will not exceed 105105.OutputFor each test case, print a single integer — the minimum number of hops needed.ExampleInputCopy42 41 33 123 4 51 552 1015 4OutputCopy2
3
1
2
NoteThe first test case of the sample is shown in the picture above. Rabbit can hop to (2,5–√)(2,5), then to (4,0)(4,0) for a total of two hops. Each hop has a distance of 33, which is one of his favorite numbers.In the second test case of the sample, one way for Rabbit to hop 33 times is: (0,0)(0,0) →→ (4,0)(4,0) →→ (8,0)(8,0) →→ (12,0)(12,0).In the third test case of the sample, Rabbit can hop from (0,0)(0,0) to (5,0)(5,0).In the fourth test case of the sample, Rabbit can hop: (0,0)(0,0) →→ (5,102–√)(5,102) →→ (10,0)(10,0). | [
"geometry",
"greedy",
"math"
] |
import java.util.Scanner;
public class mo {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int tt = in.nextInt();
for(int w = 0 ; w < tt; w++) {
int n = in.nextInt();
int k = in.nextInt();
long[] a = new long[n];
long max = Long.MIN_VALUE;
boolean nasao = false;
for(int i = 0 ; i<n; i++) {
a[i] = in.nextLong();
max = Math.max(a[i], max);
if(a[i]==k) {
nasao = true;
}
}
if(nasao) {
System.out.println(1);
}
else {
System.out.println(Math.max((int) Math.ceil((double) k/max),2));
}
}
}
}
| java |
1288 | D | D. Minimax Problemtime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given nn arrays a1a1, a2a2, ..., anan; each array consists of exactly mm integers. We denote the yy-th element of the xx-th array as ax,yax,y.You have to choose two arrays aiai and ajaj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j). After that, you will obtain a new array bb consisting of mm integers, such that for every k∈[1,m]k∈[1,m] bk=max(ai,k,aj,k)bk=max(ai,k,aj,k).Your goal is to choose ii and jj so that the value of mink=1mbkmink=1mbk is maximum possible.InputThe first line contains two integers nn and mm (1≤n≤3⋅1051≤n≤3⋅105, 1≤m≤81≤m≤8) — the number of arrays and the number of elements in each array, respectively.Then nn lines follow, the xx-th line contains the array axax represented by mm integers ax,1ax,1, ax,2ax,2, ..., ax,max,m (0≤ax,y≤1090≤ax,y≤109).OutputPrint two integers ii and jj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j) — the indices of the two arrays you have to choose so that the value of mink=1mbkmink=1mbk is maximum possible. If there are multiple answers, print any of them.ExampleInputCopy6 5
5 0 3 1 2
1 8 9 1 3
1 2 3 4 5
9 1 0 3 7
2 3 0 6 3
6 4 1 7 0
OutputCopy1 5
| [
"binary search",
"bitmasks",
"dp"
] | import java.util.*;
import javax.swing.text.PlainDocument;
import java.io.*;
public class Main {
static int n, m;
static int[][] grid;
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
grid = new int[n][m];
int max = 0;
for (int i = 0; i < n; i++) {
grid[i] = sc.nextIntArray(m);
}
int start = 0;
int end = (int) 1e9;
Integer[] result = new Integer[2];
while (start <= end) {
int mid = (start + end) / 2;
HashMap<Integer, Integer> set = new HashMap<>();
for (int i = 0; i < n; i++) {
int mask = 0;
for (int j = 0; j < m; j++) {
if (grid[i][j] >= mid)
mask = setBit(mask, j);
}
if (set.getOrDefault(mask, -1) == -1)
set.put(mask, i);
// pw.println(set.toString());
if (set.size() == (1 << m))
break;
}
boolean flag = false;
for (Integer integer : set.keySet()) {
for (Integer integer2 : set.keySet()) {
if ((integer | integer2) == ((1 << m) - 1)) {
result = new Integer[] { set.get(integer) + 1, set.get(integer2) + 1 };
flag = true;
break;
}
}
if (flag)
break;
}
if (flag)
start = mid + 1;
else
end = mid - 1;
}
pw.println(toString(result));
pw.close();
}
static long[][] memo;
public static long dp(int idx1) {
if (idx1 == n)
return 0;
long res = 0;
for (int i = idx1; i < n; i++) {
res = Math.max(res, getMin(grid[idx1], grid[i]));
}
return res;
}
public static int getMin(int[] arr1, int arr2[]) {
int min = Integer.MAX_VALUE;
for (int i = 0; i < arr2.length; i++) {
min = Math.min(min, Math.max(arr2[i], arr1[i]));
}
return min;
}
public static int setBit(int mask, int ind) {
return mask | (1 << ind);
}
public static boolean checkBit(int mask, int ind) {
return (mask & (1 << ind)) != 0;
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public long[] nextlongArray(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public Long[] nextLongArray(int n) throws IOException {
Long[] a = new Long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public int[] nextIntArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public Integer[] nextIntegerArray(int n) throws IOException {
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public boolean ready() throws IOException {
return br.ready();
}
}
static class pair implements Comparable<pair> {
long x;
long y;
public pair(long x, long y) {
this.x = x;
this.y = y;
}
public String toString() {
return x + " " + y;
}
public boolean equals(Object o) {
if (o instanceof pair) {
pair p = (pair) o;
return p.x == x && p.y == y;
}
return false;
}
public int hashCode() {
return new Long(x).hashCode() * 31 + new Long(y).hashCode();
}
public int compareTo(pair other) {
if (this.x == other.x) {
return Long.compare(this.y, other.y);
}
return Long.compare(this.x, other.x);
}
}
static class tuble implements Comparable<tuble> {
int x;
int y;
int z;
public tuble(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
public String toString() {
return x + " " + y + " " + z;
}
public int compareTo(tuble other) {
if (this.x == other.x) {
if (this.y == other.y) {
return this.z - other.z;
}
return this.y - other.y;
} else {
return this.x - other.x;
}
}
}
public static String toString(int[] arr) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < arr.length; i++) {
sb.append(arr[i] + " ");
}
return sb.toString().trim();
}
public static String toString(Integer[] arr) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < arr.length; i++) {
sb.append(arr[i] + " ");
}
return sb.toString().trim();
}
static long mod = 1000000007;
static Random rn = new Random();
static Scanner sc = new Scanner(System.in);
static PrintWriter pw = new PrintWriter(System.out);
}
| java |
1286 | A | A. Garlandtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVadim loves decorating the Christmas tree; so he got a beautiful garland as a present. It consists of nn light bulbs in a single row. Each bulb has a number from 11 to nn (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland. Now Vadim wants to put them back on.Vadim wants to put all bulb back on the garland. Vadim defines complexity of a garland to be the number of pairs of adjacent bulbs with numbers with different parity (remainder of the division by 22). For example, the complexity of 1 4 2 3 5 is 22 and the complexity of 1 3 5 7 6 4 2 is 11.No one likes complexity, so Vadim wants to minimize the number of such pairs. Find the way to put all bulbs back on the garland, such that the complexity is as small as possible.InputThe first line contains a single integer nn (1≤n≤1001≤n≤100) — the number of light bulbs on the garland.The second line contains nn integers p1, p2, …, pnp1, p2, …, pn (0≤pi≤n0≤pi≤n) — the number on the ii-th bulb, or 00 if it was removed.OutputOutput a single number — the minimum complexity of the garland.ExamplesInputCopy5
0 5 0 2 3
OutputCopy2
InputCopy7
1 0 0 5 0 0 2
OutputCopy1
NoteIn the first example; one should place light bulbs as 1 5 4 2 3. In that case; the complexity would be equal to 2; because only (5,4)(5,4) and (2,3)(2,3) are the pairs of adjacent bulbs that have different parity.In the second case, one of the correct answers is 1 7 3 5 6 4 2. | [
"dp",
"greedy",
"sortings"
] | import java.io.*;
import java.util.*;
public class Solution
{
static class Pair
{
int beg;
int end;
boolean isEven;
Pair(int beg, int end, boolean isEven)
{
this.beg = beg;
this.end = end;
this.isEven = isEven;
}
}
static Scanner scan = new Scanner(System.in);
static BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out));
static void tc() throws Exception
{
int n = scan.nextInt();
int[] a = new int[n];
int i, j, k;
int even = 0;
int odd = 0;
for(i=0;i<n;++i)
{
a[i] = scan.nextInt();
if(a[i] == 0)
continue;
if(a[i] % 2 == 0)
++even;
else
++odd;
}
even = n / 2 - even;
odd = n / 2 + (n % 2) - odd;
if(even + odd == n)
{
if(n > 1)
output.write("1\n");
else
output.write("0\n");
output.flush();
return;
}
List<Pair>[] list = new ArrayList[n + 1];
for(i=1;i<=n;++i)
list[i] = new ArrayList<Pair>();
boolean _new = true;
for(i=0;i<n;++i)
{
if(a[i] != 0)
{
_new = true;
continue;
}
if(!_new)
continue;
_new = false;
int beg = -1;
int end = -1;
for(j=i;j>=0;--j)
{
if(a[j] == 0)
beg = j;
else
break;
}
for(j=i;j<n;++j)
{
if(a[j] == 0)
end = j;
else
break;
}
if(beg - 1 >= 0 && end + 1 < n && (a[beg - 1] % 2) == (a[end + 1] % 2))
{
int len = end - beg + 1;
list[len].add(new Pair(beg, end, (beg - 1 >= 0) ? (a[beg - 1] % 2 == 0) : (a[end + 1] % 2 == 0)));
}
}
for(i=1;i<=n;++i)
{
int size = list[i].size();
for(j=0;j<size;++j)
{
Pair pair = list[i].get(j);
int beg = pair.beg;
int end = pair.end;
boolean isEven = pair.isEven;
if(isEven && end - beg + 1 <= even)
{
even -= end - beg + 1;
for(k=beg;k<=end;++k)
a[k] = 2;
}
else if(!isEven && end - beg + 1 <= odd)
{
odd -= end - beg + 1;
for(k=beg;k<=end;++k)
a[k] = 1;
}
}
}
for(i=0;i<n;++i)
if(a[i] != 0)
{
if(i == 0)
break;
if(a[i] % 2 == 1 && i <= odd)
{
j = i - 1;
while(j >= 0)
{
a[j--] = 1;
--odd;
}
}
else if(a[i] % 2 == 0 && i <= even)
{
j = i - 1;
while(j >= 0)
{
a[j--] = 2;
--even;
}
}
break;
}
for(i=n-1;i>=0;--i)
if(a[i] != 0)
{
if(i == n - 1)
break;
if(a[i] % 2 == 1 && n - 1 - i <= odd)
{
j = i + 1;
while(j < n)
{
a[j++] = 1;
--odd;
}
}
else if(a[i] % 2 == 0 && n - 1 - i <= even)
{
j = i + 1;
while(j < n)
{
a[j++] = 2;
--even;
}
}
break;
}
for(i=0;i<n;++i)
if(a[i] != 0)
{
if(i == 0)
break;
if(a[i] % 2 == 1)
{
j = i - 1;
while(j >= 0 && odd > 0)
{
a[j--] = 1;
--odd;
}
while(j >= 0)
{
a[j--] = 2;
--even;
}
}
else if(a[i] % 2 == 0)
{
j = i - 1;
while(j >= 0 && even > 0)
{
a[j--] = 2;
--even;
}
while(j >= 0)
{
a[j--] = 1;
--odd;
}
}
break;
}
for(i=n-1;i>=0;--i)
if(a[i] != 0)
{
if(i == n - 1)
break;
if(a[i] % 2 == 1)
{
j = i + 1;
while(j < n && odd > 0)
{
a[j++] = 1;
--odd;
}
while(j < n)
{
a[j++] = 2;
--even;
}
}
else if(a[i] % 2 == 0)
{
j = i + 1;
while(j < n && even > 0)
{
a[j++] = 2;
--even;
}
while(j < n)
{
a[j++] = 1;
--odd;
}
}
break;
}
int ans = 0;
for(i=1;i<n;++i)
if(a[i] > 0 && a[i - 1] > 0 && (a[i] % 2) != (a[i - 1] % 2))
ans += 1;
_new = true;
for(i=0;i<n;++i)
{
if(a[i] != 0)
{
_new = true;
continue;
}
if(!_new)
continue;
_new = false;
int beg = -1;
int end = -1;
for(j=i;j>=0;--j)
{
if(a[j] == 0)
beg = j;
else
break;
}
for(j=i;j<n;++j)
{
if(a[j] == 0)
end = j;
else
break;
}
if(beg - 1 >= 0 && end + 1 < n && (a[beg - 1] % 2) == (a[end + 1] % 2))
ans += 2;
else
ans += 1;
}
output.write(ans + "");
output.write("\n");
output.flush();
}
public static void main(String[] args) throws Exception
{
int t = 1;
// t = scan.nextInt();
while(t-- > 0)
tc();
}
} | java |
1312 | G | G. Autocompletiontime limit per test7 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a set of strings SS. Each string consists of lowercase Latin letters.For each string in this set, you want to calculate the minimum number of seconds required to type this string. To type a string, you have to start with an empty string and transform it into the string you want to type using the following actions: if the current string is tt, choose some lowercase Latin letter cc and append it to the back of tt, so the current string becomes t+ct+c. This action takes 11 second; use autocompletion. When you try to autocomplete the current string tt, a list of all strings s∈Ss∈S such that tt is a prefix of ss is shown to you. This list includes tt itself, if tt is a string from SS, and the strings are ordered lexicographically. You can transform tt into the ii-th string from this list in ii seconds. Note that you may choose any string from this list you want, it is not necessarily the string you are trying to type. What is the minimum number of seconds that you have to spend to type each string from SS?Note that the strings from SS are given in an unusual way.InputThe first line contains one integer nn (1≤n≤1061≤n≤106).Then nn lines follow, the ii-th line contains one integer pipi (0≤pi<i0≤pi<i) and one lowercase Latin character cici. These lines form some set of strings such that SS is its subset as follows: there are n+1n+1 strings, numbered from 00 to nn; the 00-th string is an empty string, and the ii-th string (i≥1i≥1) is the result of appending the character cici to the string pipi. It is guaranteed that all these strings are distinct.The next line contains one integer kk (1≤k≤n1≤k≤n) — the number of strings in SS.The last line contains kk integers a1a1, a2a2, ..., akak (1≤ai≤n1≤ai≤n, all aiai are pairwise distinct) denoting the indices of the strings generated by above-mentioned process that form the set SS — formally, if we denote the ii-th generated string as sisi, then S=sa1,sa2,…,sakS=sa1,sa2,…,sak.OutputPrint kk integers, the ii-th of them should be equal to the minimum number of seconds required to type the string saisai.ExamplesInputCopy10
0 i
1 q
2 g
0 k
1 e
5 r
4 m
5 h
3 p
3 e
5
8 9 1 10 6
OutputCopy2 4 1 3 3
InputCopy8
0 a
1 b
2 a
2 b
4 a
4 b
5 c
6 d
5
2 3 4 7 8
OutputCopy1 2 2 4 4
NoteIn the first example; SS consists of the following strings: ieh, iqgp, i, iqge, ier. | [
"data structures",
"dfs and similar",
"dp"
] | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.BitSet;
import java.io.BufferedReader;
import java.util.Comparator;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author AnandOza
*/
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);
GAutocompletion solver = new GAutocompletion();
solver.solve(1, in, out);
out.close();
}
static class GAutocompletion {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
GAutocompletion.N[] input = new GAutocompletion.N[n];
for (int i = 1; i <= n; i++) {
input[i - 1] = new GAutocompletion.N(i, in.nextInt(), in.next().charAt(0) - 'a');
}
Arrays.sort(input, Comparator.comparingInt(i -> i.alpha));
n++; // because there's a special root node
List<Integer>[] adj = new List[n];
for (int i = 0; i < adj.length; i++) {
adj[i] = new ArrayList<>();
}
int[] parent = new int[n];
parent[0] = -1;
for (GAutocompletion.N p : input) {
adj[p.parent].add(p.index);
parent[p.index] = p.parent;
}
int k = in.nextInt();
int[] specialArray = in.readIntArray(k);
BitSet special = new BitSet();
for (int i : specialArray) {
special.set(i);
}
int[] answer = new int[n];
Arrays.fill(answer, Integer.MAX_VALUE);
answer[0] = 0;
int specialIndex = 0;
IntStack curStack = new IntStack();
IntStack savingsStack = new IntStack();
curStack.push(0);
savingsStack.push(0);
while (!curStack.isEmpty()) {
int cur = curStack.pop();
int savings = savingsStack.pop();
if (special.get(cur)) {
specialIndex++;
}
if (special.get(cur))
answer[cur] = savings + specialIndex;
if (parent[cur] != -1)
answer[cur] = Math.min(answer[cur], answer[parent[cur]] + 1);
int newSavings = Math.min(savings, answer[cur] + (special.get(cur) ? 1 : 0) - specialIndex);
for (int i = adj[cur].size() - 1; i >= 0; i--) {
int child = adj[cur].get(i);
curStack.push(child);
savingsStack.push(newSavings);
}
}
for (int i : specialArray) {
out.print(answer[i] + " ");
}
out.println();
}
private static class N {
final int index;
final int parent;
final int alpha;
private N(int index, int parent, int alpha) {
this.index = index;
this.parent = parent;
this.alpha = alpha;
}
}
}
static class IntStack {
int[] array;
int size = 0;
public IntStack() {
this(8);
}
public IntStack(int capacity) {
array = new int[capacity];
}
public void push(int item) {
if (size >= array.length)
array = resize(array);
array[size++] = item;
}
public int pop() {
return array[--size];
}
public boolean isEmpty() {
return size == 0;
}
private static int[] resize(int[] array) {
int[] newArray = new int[array.length << 1];
System.arraycopy(array, 0, newArray, 0, array.length);
return newArray;
}
public String toString() {
int[] trimmed = new int[size];
System.arraycopy(array, 0, trimmed, 0, size);
return Arrays.toString(trimmed);
}
}
static class InputReader {
public final 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 int[] readIntArray(int n) {
int[] x = new int[n];
for (int i = 0; i < n; i++) {
x[i] = nextInt();
}
return x;
}
}
}
| java |
1303 | E | E. Erase Subsequencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. You can build new string pp from ss using the following operation no more than two times: choose any subsequence si1,si2,…,siksi1,si2,…,sik where 1≤i1<i2<⋯<ik≤|s|1≤i1<i2<⋯<ik≤|s|; erase the chosen subsequence from ss (ss can become empty); concatenate chosen subsequence to the right of the string pp (in other words, p=p+si1si2…sikp=p+si1si2…sik). Of course, initially the string pp is empty. For example, let s=ababcds=ababcd. At first, let's choose subsequence s1s4s5=abcs1s4s5=abc — we will get s=bads=bad and p=abcp=abc. At second, let's choose s1s2=bas1s2=ba — we will get s=ds=d and p=abcbap=abcba. So we can build abcbaabcba from ababcdababcd.Can you build a given string tt using the algorithm above?InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain test cases — two per test case. The first line contains string ss consisting of lowercase Latin letters (1≤|s|≤4001≤|s|≤400) — the initial string.The second line contains string tt consisting of lowercase Latin letters (1≤|t|≤|s|1≤|t|≤|s|) — the string you'd like to build.It's guaranteed that the total length of strings ss doesn't exceed 400400.OutputPrint TT answers — one per test case. Print YES (case insensitive) if it's possible to build tt and NO (case insensitive) otherwise.ExampleInputCopy4
ababcd
abcba
a
b
defi
fed
xyz
x
OutputCopyYES
NO
NO
YES
| [
"dp",
"strings"
] | /**
* ******* Created on 25/2/20 12:44 PM*******
*/
import java.io.*;
import java.util.*;
// t = a+b
public class ED82E implements Runnable {
private static final int MAX = (int) (1E5 + 5);
private static final int MOD = (int) (1E9 + 7);
private static final long Inf = (long) (1E14 + 10);
long[][] nxt = new long[405][26];
private void solve() throws IOException {
int t = reader.nextInt();
while(t-- >0){
String s = reader.next();
String p = reader.next();
int n = s.length();
for(int i=0;i<405;i++)
for(int j=0;j<26;j++)
nxt[i][j] = Inf;
for(int i=n-1;i>=0;i--){
for(int j=0;j<26;j++)
nxt[i][j] = nxt[i+1][j];
nxt[i][s.charAt(i)-'a']=i;
}
int pn = p.length();
boolean flag =false;
for(int i=0;i<p.length();i++){
if(calc(p.substring(0,i),p.substring(i,pn),n)){
writer.println("YES");
flag =true;
break;
}
}
if(!flag)
writer.println("NO");
}
}
long[][] dp = new long[405][405];
private boolean calc(String s1, String s2, int n) {
int n1 = s1.length();
int n2 = s2.length();
for(int i=0;i<=n1;i++)
for(int j=0;j<=n2;j++)
dp[i][j]=Inf;
dp[0][0]=0;
for(int i=0;i<=n1;i++){
for(int j=0;j <=n2;j++){
if(dp[i][j] > n)
continue;
int len = (int) dp[i][j];
if(i < n1 && nxt[len][s1.charAt(i)-'a']< Inf)
dp[i+1][j] = Math.min(dp[i+1][j], nxt[len][s1.charAt(i)-'a']+1);
if(j < n2 && nxt[len][s2.charAt(j)-'a']< Inf)
dp[i][j+1] = Math.min(dp[i][j+1], nxt[len][s2.charAt(j)-'a']+1);
if(dp[i][j] > n)
continue;
}
}
if(dp[n1][n2]< Inf)
return true;
return false;
}
public static void main(String[] args) throws IOException {
try (Input reader = new StandardInput(); PrintWriter writer = new PrintWriter(System.out)) {
new ED82E().run();
}
}
StandardInput reader;
PrintWriter writer;
@Override
public void run() {
try {
reader = new StandardInput();
writer = new PrintWriter(System.out);
solve();
reader.close();
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
interface Input extends Closeable {
String next() throws IOException;
default int nextInt() throws IOException {
return Integer.parseInt(next());
}
default long nextLong() throws IOException {
return Long.parseLong(next());
}
default double nextDouble() throws IOException {
return Double.parseDouble(next());
}
default int[] readIntArray() throws IOException {
return readIntArray(nextInt());
}
default int[] readIntArray(int size) throws IOException {
int[] array = new int[size];
for (int i = 0; i < array.length; i++) {
array[i] = nextInt();
}
return array;
}
default long[] readLongArray(int size) throws IOException {
long[] array = new long[size];
for (int i = 0; i < array.length; i++) {
array[i] = nextLong();
}
return array;
}
}
private static class StandardInput implements Input {
private final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
private StringTokenizer stringTokenizer;
@Override
public void close() throws IOException {
reader.close();
}
@Override
public String next() throws IOException {
if (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) {
stringTokenizer = new StringTokenizer(reader.readLine());
}
return stringTokenizer.nextToken();
}
}
}
| java |
1301 | A | A. Three Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three strings aa, bb and cc of the same length nn. The strings consist of lowercase English letters only. The ii-th letter of aa is aiai, the ii-th letter of bb is bibi, the ii-th letter of cc is cici.For every ii (1≤i≤n1≤i≤n) you must swap (i.e. exchange) cici with either aiai or bibi. So in total you'll perform exactly nn swap operations, each of them either ci↔aici↔ai or ci↔bici↔bi (ii iterates over all integers between 11 and nn, inclusive).For example, if aa is "code", bb is "true", and cc is "help", you can make cc equal to "crue" taking the 11-st and the 44-th letters from aa and the others from bb. In this way aa becomes "hodp" and bb becomes "tele".Is it possible that after these swaps the string aa becomes exactly the same as the string bb?InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1001≤t≤100) — the number of test cases. The description of the test cases follows.The first line of each test case contains a string of lowercase English letters aa.The second line of each test case contains a string of lowercase English letters bb.The third line of each test case contains a string of lowercase English letters cc.It is guaranteed that in each test case these three strings are non-empty and have the same length, which is not exceeding 100100.OutputPrint tt lines with answers for all test cases. For each test case:If it is possible to make string aa equal to string bb print "YES" (without quotes), otherwise print "NO" (without quotes).You can print either lowercase or uppercase letters in the answers.ExampleInputCopy4
aaa
bbb
ccc
abc
bca
bca
aabb
bbaa
baba
imi
mii
iim
OutputCopyNO
YES
YES
NO
NoteIn the first test case; it is impossible to do the swaps so that string aa becomes exactly the same as string bb.In the second test case, you should swap cici with aiai for all possible ii. After the swaps aa becomes "bca", bb becomes "bca" and cc becomes "abc". Here the strings aa and bb are equal.In the third test case, you should swap c1c1 with a1a1, c2c2 with b2b2, c3c3 with b3b3 and c4c4 with a4a4. Then string aa becomes "baba", string bb becomes "baba" and string cc becomes "abab". Here the strings aa and bb are equal.In the fourth test case, it is impossible to do the swaps so that string aa becomes exactly the same as string bb. | [
"implementation",
"strings"
] | import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
in = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out));
try {
int t = in.nextInt(); while(t-- > 0) { solve(); out.println();}
// solve();
} finally {
out.close();
}
return;
}
public static void solve() {
char[] a = fillArray();
char[] b = fillArray();
char[] c = fillArray();
int n = a.length;
for(int i = 0; i < n; i++) {
if(c[i] == a[i] || c[i] == b[i]) {
continue;
}
out.print("NO");
return;
}
out.print("YES");
}
//-------------- Helper methods-------------------
public static int[] fillArray(int n) {
int[] array = new int[n];
for(int i = 0; i < n; i++) {
array[i] = in.nextInt();
}
return array;
}
public static char[] fillArray() {
char[] array = in.next().toCharArray();
return array;
}
//-----------PrintWriter for faster output---------------------------------
public static PrintWriter out;
public static MyScanner in;
//-----------MyScanner class for faster input----------x§x
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static void shuffleArray(int[] arr){
int n = arr.length;
Random rnd = new Random();
for(int i=0; i<n; ++i){
int tmp = arr[i];
int randomPos = i + rnd.nextInt(n-i);
arr[i] = arr[randomPos];
arr[randomPos] = tmp;
}
}
//--------------------------------------------------------
}
| java |
1313 | B | B. Different Rulestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNikolay has only recently started in competitive programming; but already qualified to the finals of one prestigious olympiad. There going to be nn participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules.Suppose in the first round participant A took xx-th place and in the second round — yy-th place. Then the total score of the participant A is sum x+yx+y. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every ii from 11 to nn exactly one participant took ii-th place in first round and exactly one participant took ii-th place in second round.Right after the end of the Olympiad, Nikolay was informed that he got xx-th place in first round and yy-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question.InputThe first line contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases to solve.Each of the following tt lines contains integers nn, xx, yy (1≤n≤1091≤n≤109, 1≤x,y≤n1≤x,y≤n) — the number of participants in the olympiad, the place that Nikolay took in the first round and the place that Nikolay took in the second round.OutputPrint two integers — the minimum and maximum possible overall place Nikolay could take.ExamplesInputCopy15 1 3OutputCopy1 3InputCopy16 3 4OutputCopy2 6NoteExplanation for the first example:Suppose there were 5 participants A-E. Let's denote Nikolay as A. The the most favorable results for Nikolay could look as follows: However, the results of the Olympiad could also look like this: In the first case Nikolay would have taken first place, and in the second — third place. | [
"constructive algorithms",
"greedy",
"implementation",
"math"
] | import java.util.*;
import java.io.*;
import java.math.BigInteger;
public class _practise {
public static void main(String args[])
{
FastReader in=new FastReader();
PrintWriter so = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int t = in.nextInt();
//int t = 1;
while(t-->0)
{
long n = in.nextLong();
long x = in.nextLong();
long y = in.nextLong();
//min
{
if(x+y<=n) so.print(1);
else so.print(((x+y)%n==0)?n:(x+y)%n+1);
}
//max
{
if(x+y>n) so.print(" "+n);
else so.print(" "+(x+y-1));
}
so.println();
}
so.flush();
/*String s = in.next();
* BigInteger f = new BigInteger("1"); 1 ke jagah koi bhi value ho skta jo aap
* initial value banan chahte
int a[] = new int[n];
ArrayList<Integer> al = new ArrayList<Integer>();
StringBuilder sb = new StringBuilder();
Set<Long> a = new HashSet<Long>();
so.println("HELLO");*/
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
int[] readIntArray(int n)
{
int a[]=new int[n];
for(int i=0;i<n;i++)a[i]=nextInt();
return a;
}
long[] readLongArray(int n)
{
long a[]=new long[n];
for(int i=0;i<n;i++)a[i]=nextLong();
return a;
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
} | java |
1294 | D | D. MEX maximizingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecall that MEX of an array is a minimum non-negative integer that does not belong to the array. Examples: for the array [0,0,1,0,2][0,0,1,0,2] MEX equals to 33 because numbers 0,10,1 and 22 are presented in the array and 33 is the minimum non-negative integer not presented in the array; for the array [1,2,3,4][1,2,3,4] MEX equals to 00 because 00 is the minimum non-negative integer not presented in the array; for the array [0,1,4,3][0,1,4,3] MEX equals to 22 because 22 is the minimum non-negative integer not presented in the array. You are given an empty array a=[]a=[] (in other words, a zero-length array). You are also given a positive integer xx.You are also given qq queries. The jj-th query consists of one integer yjyj and means that you have to append one element yjyj to the array. The array length increases by 11 after a query.In one move, you can choose any index ii and set ai:=ai+xai:=ai+x or ai:=ai−xai:=ai−x (i.e. increase or decrease any element of the array by xx). The only restriction is that aiai cannot become negative. Since initially the array is empty, you can perform moves only after the first query.You have to maximize the MEX (minimum excluded) of the array if you can perform any number of such operations (you can even perform the operation multiple times with one element).You have to find the answer after each of qq queries (i.e. the jj-th answer corresponds to the array of length jj).Operations are discarded before each query. I.e. the array aa after the jj-th query equals to [y1,y2,…,yj][y1,y2,…,yj].InputThe first line of the input contains two integers q,xq,x (1≤q,x≤4⋅1051≤q,x≤4⋅105) — the number of queries and the value of xx.The next qq lines describe queries. The jj-th query consists of one integer yjyj (0≤yj≤1090≤yj≤109) and means that you have to append one element yjyj to the array.OutputPrint the answer to the initial problem after each query — for the query jj print the maximum value of MEX after first jj queries. Note that queries are dependent (the array changes after each query) but operations are independent between queries.ExamplesInputCopy7 3
0
1
2
2
0
0
10
OutputCopy1
2
3
3
4
4
7
InputCopy4 3
1
2
1
2
OutputCopy0
0
0
0
NoteIn the first example: After the first query; the array is a=[0]a=[0]: you don't need to perform any operations, maximum possible MEX is 11. After the second query, the array is a=[0,1]a=[0,1]: you don't need to perform any operations, maximum possible MEX is 22. After the third query, the array is a=[0,1,2]a=[0,1,2]: you don't need to perform any operations, maximum possible MEX is 33. After the fourth query, the array is a=[0,1,2,2]a=[0,1,2,2]: you don't need to perform any operations, maximum possible MEX is 33 (you can't make it greater with operations). After the fifth query, the array is a=[0,1,2,2,0]a=[0,1,2,2,0]: you can perform a[4]:=a[4]+3=3a[4]:=a[4]+3=3. The array changes to be a=[0,1,2,2,3]a=[0,1,2,2,3]. Now MEX is maximum possible and equals to 44. After the sixth query, the array is a=[0,1,2,2,0,0]a=[0,1,2,2,0,0]: you can perform a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3. The array changes to be a=[0,1,2,2,3,0]a=[0,1,2,2,3,0]. Now MEX is maximum possible and equals to 44. After the seventh query, the array is a=[0,1,2,2,0,0,10]a=[0,1,2,2,0,0,10]. You can perform the following operations: a[3]:=a[3]+3=2+3=5a[3]:=a[3]+3=2+3=5, a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3, a[5]:=a[5]+3=0+3=3a[5]:=a[5]+3=0+3=3, a[5]:=a[5]+3=3+3=6a[5]:=a[5]+3=3+3=6, a[6]:=a[6]−3=10−3=7a[6]:=a[6]−3=10−3=7, a[6]:=a[6]−3=7−3=4a[6]:=a[6]−3=7−3=4. The resulting array will be a=[0,1,2,5,3,6,4]a=[0,1,2,5,3,6,4]. Now MEX is maximum possible and equals to 77. | [
"data structures",
"greedy",
"implementation",
"math"
] | import java.io.*;
import java.text.DecimalFormat;
import java.util.*;
public class Main {
static class Pair
{
long l;
long r;
public Pair(long l,long r)
{
this.l = l;
this.r=r;
}
public String toString() {
return l +" "+r;
}
}
static final int INF = 1 << 30;
static final long INFL = 1L << 60;
static final long NINF = INFL * -1;
static final long mod = (long) 1e9 + 7;
static final long mod2 = 998244353;
static DecimalFormat df = new DecimalFormat("0.00000000000000");
public static final double PI = 3.141592653589793d, eps = 1e-9;
public static void main(String[] args) throws IOException {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC
{
public static void solve(int testNumber, InputReader in, OutputWriter out)
{
int t1=1;
while (t1-->0)
{
int q=in.readInt();
long x=in.nextLong();
int[] cnt=new int[(int)(x+1)];
int tp=0;
while(q-->0)
{
long num=in.nextLong();
++cnt[(int)(num%x)];
while(cnt[(int)(tp%x)]!=0)
{
--cnt[(int)(tp%x)];
++tp;
}
out.printLine(tp);
}
}
}
}
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 readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int arraySize) {
int[] array = new int[arraySize];
for (int i = 0; i < arraySize; i++) {
array[i] = readInt();
}
return array;
}
private int skip() {
int b;
while ((b = read()) != -1 && isSpaceChar(b)) ;
return b;
}
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = read();
}
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 = read();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isNewLine(int c) {
return c == '\n';
}
public String nextLine() {
int c = read();
StringBuilder result = new StringBuilder();
do {
result.appendCodePoint(c);
c = read();
} while (!isNewLine(c));
return result.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sign = 1;
if (c == '-') {
sign = -1;
c = read();
}
long result = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
result *= 10;
result += c & 15;
c = read();
} while (!isSpaceChar(c));
return result * sign;
}
public long[] nextLongArray(int arraySize) {
long array[] = new long[arraySize];
for (int i = 0; i < arraySize; i++) {
array[i] = nextLong();
}
return array;
}
public double nextDouble() {
double ret = 0, div = 1;
byte c = (byte) read();
while (c <= ' ') {
c = (byte) read();
}
boolean neg = (c == '-');
if (neg) {
c = (byte) read();
}
do {
ret = ret * 10 + c - '0';
} while ((c = (byte) read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = (byte) read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg) {
return -ret;
}
return ret;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
public static class CP {
static boolean isPrime(long n) {
if (n <= 1)
return false;
if (n == 2 || n == 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
for (int i = 5; (long) i * i <= n; i += 6) {
if (n % i == 0 || n % (i + 2) == 0)
return false;
}
return true;
}
public static int log2(int N) {
int result = (int) (Math.log(N) / Math.log(2));
return result;
}
public static long pow(long a, long n, long mod) {
// a %= mod;
long ret = 1;
int x = 63 - Long.numberOfLeadingZeros(n);
for (; x >= 0; x--) {
ret = ret * ret % mod;
if (n << 63 - x < 0)
ret = ret * a % mod;
}
return ret;
}
public static boolean isComposite(long n) {
if (n < 2)
return true;
if (n == 2 || n == 3)
return false;
if (n % 2 == 0 || n % 3 == 0)
return true;
for (long i = 6L; i * i <= n; i += 6)
if (n % (i - 1) == 0 || n % (i + 1) == 0)
return true;
return false;
}
static int ifnotPrime(int[] prime, int x) {
return (prime[x / 64] & (1 << ((x >> 1) & 31)));
}
static int log2(long n) {
return (int) (Math.log10(n) / Math.log10(2));
}
static void makeComposite(int[] prime, int x) {
prime[x / 64] |= (1 << ((x >> 1) & 31));
}
public static String swap(String a, int i, int j) {
char temp;
char[] charArray = a.toCharArray();
temp = charArray[i];
charArray[i] = charArray[j];
charArray[j] = temp;
return String.valueOf(charArray);
}
static void reverse(long arr[]){
int l = 0, r = arr.length-1;
while(l<r){
long temp = arr[l];
arr[l] = arr[r];
arr[r] = temp;
l++;
r--;
}
}
static void reverse(int arr[]){
int l = 0, r = arr.length-1;
while(l<r){
int temp = arr[l];
arr[l] = arr[r];
arr[r] = temp;
l++;
r--;
}
}
public static int[] sieveEratosthenes(int n) {
if (n <= 32) {
int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31};
for (int i = 0; i < primes.length; i++) {
if (n < primes[i]) {
return Arrays.copyOf(primes, i);
}
}
return primes;
}
int u = n + 32;
double lu = Math.log(u);
int[] ret = new int[(int) (u / lu + u / lu / lu * 1.5)];
ret[0] = 2;
int pos = 1;
int[] isnp = new int[(n + 1) / 32 / 2 + 1];
int sup = (n + 1) / 32 / 2 + 1;
int[] tprimes = {3, 5, 7, 11, 13, 17, 19, 23, 29, 31};
for (int tp : tprimes) {
ret[pos++] = tp;
int[] ptn = new int[tp];
for (int i = (tp - 3) / 2; i < tp << 5; i += tp)
ptn[i >> 5] |= 1 << (i & 31);
for (int j = 0; j < sup; j += tp) {
for (int i = 0; i < tp && i + j < sup; i++) {
isnp[j + i] |= ptn[i];
}
}
}
// 3,5,7
// 2x+3=n
int[] magic = {0, 1, 23, 2, 29, 24, 19, 3, 30, 27, 25, 11, 20, 8, 4,
13, 31, 22, 28, 18, 26, 10, 7, 12, 21, 17, 9, 6, 16, 5, 15, 14};
int h = n / 2;
for (int i = 0; i < sup; i++) {
for (int j = ~isnp[i]; j != 0; j &= j - 1) {
int pp = i << 5 | magic[(j & -j) * 0x076be629 >>> 27];
int p = 2 * pp + 3;
if (p > n)
break;
ret[pos++] = p;
if ((long) p * p > n)
continue;
for (int q = (p * p - 3) / 2; q <= h; q += p)
isnp[q >> 5] |= 1 << q;
}
}
return Arrays.copyOf(ret, pos);
}
static int digit(long s) {
int brute = 0;
while (s > 0) {
s /= 10;
brute++;
}
return brute;
}
public static int[] primefacs(int n, int[] primes) {
int[] ret = new int[15];
int rp = 0;
for (int p : primes) {
if (p * p > n) break;
int i;
for (i = 0; n % p == 0; n /= p, i++) ;
if (i > 0) ret[rp++] = p;
}
if (n != 1) ret[rp++] = n;
return Arrays.copyOf(ret, rp);
}
static ArrayList<Integer> bitWiseSieve(int n) {
ArrayList<Integer> al = new ArrayList<>();
int prime[] = new int[n / 64 + 1];
for (int i = 3; i * i <= n; i += 2) {
if (ifnotPrime(prime, i) == 0)
for (int j = i * i, k = i << 1;
j < n; j += k)
makeComposite(prime, j);
}
al.add(2);
for (int i = 3; i <= n; i += 2)
if (ifnotPrime(prime, i) == 0)
al.add(i);
return al;
}
public static long[] sort(long arr[]) {
List<Long> list = new ArrayList<>();
for (long n : arr) {
list.add(n);
}
Collections.sort(list);
for (int i = 0; i < arr.length; i++) {
arr[i] = list.get(i);
}
return arr;
}
public static long[] revsort(long[] arr) {
List<Long> list = new ArrayList<>();
for (long n : arr) {
list.add(n);
}
Collections.sort(list, Collections.reverseOrder());
for (int i = 0; i < arr.length; i++) {
arr[i] = list.get(i);
}
return arr;
}
public static int[] revsort(int[] arr) {
List<Integer> list = new ArrayList<>();
for (int n : arr) {
list.add(n);
}
Collections.sort(list, Collections.reverseOrder());
for (int i = 0; i < arr.length; i++) {
arr[i] = list.get(i);
}
return arr;
}
public static ArrayList<Integer> reverse(
ArrayList<Integer> data,
int left, int right)
{
// Reverse the sub-array
while (left < right)
{
int temp = data.get(left);
data.set(left++,
data.get(right));
data.set(right--, temp);
}
// Return the updated array
return data;
}
static ArrayList<Integer> sieve(long size) {
ArrayList<Integer> pr = new ArrayList<Integer>();
boolean prime[] = new boolean[(int) size];
for (int i = 2; i < prime.length; i++) prime[i] = true;
for (int i = 2; i * i < prime.length; i++) {
if (prime[i]) {
for (int j = i * i; j < prime.length; j += i) {
prime[j] = false;
}
}
}
for (int i = 2; i < prime.length; i++) if (prime[i]) pr.add(i);
return pr;
}
static ArrayList<Integer> segmented_sieve(int l, int r, ArrayList<Integer> primes) {
ArrayList<Integer> al = new ArrayList<>();
if (l == 1) ++l;
int max = r - l + 1;
int arr[] = new int[max];
for (int p : primes) {
if (p * p <= r) {
int i = (l / p) * p;
if (i < l) i += p;
for (; i <= r; i += p) {
if (i != p) {
arr[i - l] = 1;
}
}
}
}
for (int i = 0; i < max; ++i) {
if (arr[i] == 0) {
al.add(l + i);
}
}
return al;
}
static boolean isfPrime(long n, int iteration) {
if (n == 0 || n == 1)
return false;
if (n == 2)
return true;
if (n % 2 == 0)
return false;
Random rand = new Random();
for (int i = 0; i < iteration; i++) {
long r = Math.abs(rand.nextLong());
long a = r % (n - 1) + 1;
if (modPow(a, n - 1, n) != 1)
return false;
}
return true;
}
static long modPow(long a, long b, long c) {
long res = 1;
for (int i = 0; i < b; i++) {
res *= a;
res %= c;
}
return res % c;
}
private static long binPower(long a, long l, long mod) {
long res = 0;
while (l > 0) {
if ((l & 1) == 1) {
res = mulmod(res, a, mod);
l >>= 1;
}
a = mulmod(a, a, mod);
}
return res;
}
private static long mulmod(long a, long b, long c) {
long x = 0, y = a % c;
while (b > 0) {
if (b % 2 == 1) {
x = (x + y) % c;
}
y = (y * 2L) % c;
b /= 2;
}
return x % c;
}
static long binary_Expo(long a, long b) {
long res = 1;
while (b != 0) {
if ((b & 1) == 1) {
res *= a;
--b;
}
a *= a;
b /= 2;
}
return res;
}
static void swap(int a, int b) {
int tp = b;
b = a;
a = tp;
}
static long Modular_Expo(long a, long b, long mod) {
long res = 1;
while (b != 0) {
if ((b & 1) == 1) {
res = (res * a) % mod;
--b;
}
a = (a * a) % mod;
b /= 2;
}
return res % mod;
}
static int i_gcd(int a, int b) {
while (true) {
if (b == 0)
return a;
int c = a;
a = b;
b = c % b;
}
}
static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static long ceil_div(long a, long b) {
return (a + b - 1) / b;
}
static int getIthBitFromInt(int bits, int i) {
return (bits >> (i - 1)) & 1;
}
private static TreeMap<Long, Long> primeFactorize(long n) {
TreeMap<Long, Long> pf = new TreeMap<>(Collections.reverseOrder());
long cnt = 0;
long total = 1;
for (long i = 2; (long) i * i <= n; ++i) {
if (n % i == 0) {
cnt = 0;
while (n % i == 0) {
++cnt;
n /= i;
}
pf.put(cnt, i);
//total*=(cnt+1);
}
}
if (n > 1) {
pf.put(1L, n);
//total*=2;
}
return pf;
}
//less than or equal
private static int lower_bound(List<Integer> list, int val) {
int ans = -1, lo = 0, hi = list.size() - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (list.get(mid) <= val) {
ans = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return ans;
}
private static int lower_bound(int[] arr, int val) {
int ans = -1, lo = 0, hi = arr.length - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (arr[mid] <= val) {
ans = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return ans;
}
private static int lower_bound(long[] arr, long val) {
int ans = -1, lo = 0, hi = arr.length - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (arr[mid] <= val) {
ans = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return ans;
}
// greater than or equal
private static int upper_bound(List<Integer> list, int val) {
int ans = list.size(), lo = 0, hi = ans - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (list.get(mid) >= val) {
ans = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
return ans;
}
private static int upper_bound(int[] arr, int val) {
int ans = arr.length, lo = 0, hi = ans - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (arr[mid] >= val) {
ans = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
return ans;
}
private static int upper_bound(long[] arr, long val) {
int ans = arr.length, lo = 0, hi = ans - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (arr[mid] >= val) {
ans = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
return ans;
}
// ==================== LIS & LNDS ================================
private static int[] LIS(long arr[], int n) {
List<Long> list = new ArrayList<>();
int[] cnt=new int[n];
for (int i = 0; i < n; i++) {
int idx = find1(list, arr[i]);
if (idx < list.size())
list.set(idx, arr[i]);
else
list.add(arr[i]);
cnt[i]=list.size();
}
return cnt;
}
private static int find1(List<Long> list, long val) {
int ret = list.size(), i = 0, j = list.size() - 1;
while (i <= j) {
int mid = (i + j) / 2;
if (list.get(mid)>=val) {
ret = mid;
j = mid - 1;
} else {
i = mid + 1;
}
}
return ret;
}
private static int LNDS(int[] arr, int n) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
int idx = find2(list, arr[i]);
if (idx < list.size())
list.set(idx, arr[i]);
else
list.add(arr[i]);
}
return list.size();
}
private static int find2(List<Integer> list, int val) {
int ret = list.size(), i = 0, j = list.size() - 1;
while (i <= j) {
int mid = (i + j) / 2;
if (list.get(mid) <= val) {
i = mid + 1;
} else {
ret = mid;
j = mid - 1;
}
}
return ret;
}
private static long nCr(long n, long r,long mod) {
if (n - r > r)
r = n - r;
long ans = 1L;
for (long i = r + 1; i <= n; i++)
ans = (ans%mod*i%mod)%mod;
for (long i = 2; i <= n - r; i++)
ans /= i;
return ans%mod;
}
private static boolean isPalindrome(String str) {
int i = 0, j = str.length() - 1;
while (i < j)
if (str.charAt(i++) != str.charAt(j--))
return false;
return true;
}
private static String reverseString(String str) {
StringBuilder sb = new StringBuilder(str);
return sb.reverse().toString();
}
private static String sortString(String str) {
int[] arr = new int[256];
for (char ch : str.toCharArray())
arr[ch]++;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 256; i++)
while (arr[i]-- > 0)
sb.append((char) i);
return sb.toString();
}
static boolean isSquarefactor(int x, int factor, int target) {
int s = (int) Math.round(Math.sqrt(x));
return factor * s * s == target;
}
static boolean isSquare(int x) {
int s = (int) Math.round(Math.sqrt(x));
return x * x == s;
}
static int bs(ArrayList<Integer> al, int val) {
int l = 0, h = al.size() - 1, mid = 0, ans = -1;
while (l <= h) {
mid = (l + h) >> 1;
if (al.get(mid) == val) {
return mid;
} else if (al.get(mid) > val) {
h = mid - 1;
} else {
l = mid + 1;
}
}
return ans;
}
static void sort(int a[]) // heap sort
{
PriorityQueue<Integer> q = new PriorityQueue<>();
for (int i = 0; i < a.length; i++)
q.add(a[i]);
for (int i = 0; i < a.length; i++)
a[i] = q.poll();
}
static void shuffle(int[] in) {
for (int i = 0; i < in.length; i++) {
int idx = (int) (Math.random() * in.length);
fast_swap(in, idx, i);
}
}
public static int[] radixSort2(int[] a) {
int n = a.length;
int[] c0 = new int[0x101];
int[] c1 = new int[0x101];
int[] c2 = new int[0x101];
int[] c3 = new int[0x101];
for (int v : a) {
c0[(v & 0xff) + 1]++;
c1[(v >>> 8 & 0xff) + 1]++;
c2[(v >>> 16 & 0xff) + 1]++;
c3[(v >>> 24 ^ 0x80) + 1]++;
}
for (int i = 0; i < 0xff; i++) {
c0[i + 1] += c0[i];
c1[i + 1] += c1[i];
c2[i + 1] += c2[i];
c3[i + 1] += c3[i];
}
int[] t = new int[n];
for (int v : a) t[c0[v & 0xff]++] = v;
for (int v : t) a[c1[v >>> 8 & 0xff]++] = v;
for (int v : a) t[c2[v >>> 16 & 0xff]++] = v;
for (int v : t) a[c3[v >>> 24 ^ 0x80]++] = v;
return a;
}
static int[] computeLps(String pat) {
int len = 0, i = 1, m = pat.length();
int lps[] = new int[m];
lps[0] = 0;
while (i < m) {
if (pat.charAt(i) == pat.charAt(len)) {
++len;
lps[i] = len;
++i;
} else {
if (len != 0) {
len = lps[len - 1];
} else {
lps[i] = len;
++i;
}
}
}
return lps;
}
static ArrayList<Integer> kmp(String s, String pat) {
ArrayList<Integer> al = new ArrayList<>();
int n = s.length(), m = pat.length();
int lps[] = computeLps(pat);
int i = 0, j = 0;
while (i < n) {
if (s.charAt(i) == pat.charAt(j)) {
i++;
j++;
if (j == m) {
al.add(i - j);
j = lps[j - 1];
}
} else {
if (j != 0) {
j = lps[j - 1];
} else {
i++;
}
}
}
return al;
}
static void reverse_ruffle_sort(int a[]) {
shuffle(a);
Arrays.sort(a);
for (int l = 0, r = a.length - 1; l < r; ++l, --r)
fast_swap(a, l, r);
}
static void ruffle_sort(int a[]) {
shuffle(a);
Arrays.sort(a);
}
static int getMax(int arr[], int n) {
int mx = arr[0];
for (int i = 1; i < n; i++)
if (arr[i] > mx)
mx = arr[i];
return mx;
}
static ArrayList<Long> primeFactors(long n) {
ArrayList<Long> al = new ArrayList<>();
al.add(1L);
while (n % 2 == 0) {
if (!al.contains(2L)) {
al.add(2L);
}
n /= 2L;
}
for (long i = 3; (long) i * i <= n; i += 2) {
while ((n % i == 0)) {
if (!al.contains((long) i)) {
al.add((long) i);
}
n /= i;
}
}
if (n > 2) {
if (!al.contains(n)) {
al.add(n);
}
}
return al;
}
public static long totFactors(long n) {
long cnt = 0, tot = 1;
while (n % 2 == 0) {
n /= 2;
++cnt;
}
tot *= (cnt + 1);
for (int i = 3; i <= Math.sqrt(n); i += 2) {
cnt = 0;
while (n % i == 0) {
n /= i;
++cnt;
}
tot *= (cnt + 1);
}
if (n > 2) {
tot *= 2;
}
return tot;
}
static int[] z_function(String s) {
int n = s.length(), z[] = new int[n];
for (int i = 1, l = 0, r = 0; i < n; ++i) {
if (i <= r)
z[i] = Math.min(z[i - l], r - i + 1);
while (i + z[i] < n && s.charAt(z[i]) == s.charAt(i + z[i]))
++z[i];
if (i + z[i] - 1 > r) {
l = i;
r = i + z[i] - 1;
}
}
return z;
}
static void fast_swap(int[] a, int idx1, int idx2) {
if (a[idx1] == a[idx2])
return;
a[idx1] ^= a[idx2];
a[idx2] ^= a[idx1];
a[idx1] ^= a[idx2];
}
static void fast_swap(long[] a, int idx1, int idx2) {
if (a[idx1] == a[idx2])
return;
a[idx1] ^= a[idx2];
a[idx2] ^= a[idx1];
a[idx1] ^= a[idx2];
}
public static void fast_sort(long[] array) {
ArrayList<Long> copy = new ArrayList<>();
for (long i : array)
copy.add(i);
Collections.sort(copy);
for (int i = 0; i < array.length; i++)
array[i] = copy.get(i);
}
static int factorsCount(int n) {
boolean hash[] = new boolean[n + 1];
Arrays.fill(hash, true);
for (int p = 2; p * p < n; p++)
if (hash[p] == true)
for (int i = p * 2; i < n; i += p)
hash[i] = false;
int total = 1;
for (int p = 2; p <= n; p++) {
if (hash[p]) {
int count = 0;
if (n % p == 0) {
while (n % p == 0) {
n = n / p;
count++;
}
total = total * (count + 1);
}
}
}
return total;
}
static long binomialCoeff(long n, long k) {
long res = 1;
if (k > n - k)
k = n - k;
for (int i = 0; i < k; ++i) {
res = (res * (n - i));
res /= (i + 1);
}
return res;
}
static long nck(long fact[], long inv[], long n, long k) {
if (k > n) return 0;
long res = fact[(int) n]%mod;
res = (int) ((res%mod* inv[(int) k]%mod))%mod;
res = (int) ((res%mod*inv[(int) (n - k)]%mod))%mod;
return res % mod;
}
public static long fact(long x) {
long fact = 1;
for (int i = 2; i <= x; ++i) {
fact = fact * i;
}
return fact;
}
public static ArrayList<Long> getFact(long x) {
ArrayList<Long> facts = new ArrayList<>();
for (long i = 2; i * i <= x; ++i) {
if (x % i == 0) {
facts.add(i);
if (i != x / i) {
facts.add(x / i);
}
}
}
return facts;
}
static void matrix_ex(long n, long[][] A, long[][] I) {
while (n > 0) {
if (n % 2 == 0) {
Multiply(A, A);
n /= 2;
} else {
Multiply(I, A);
n--;
}
}
}
static void Multiply(long[][] A, long[][] B) {
int n = A.length, m = A[0].length, p = B[0].length;
long[][] C = new long[n][p];
for (int i = 0; i < n; i++) {
for (int j = 0; j < p; j++) {
for (int k = 0; k < m; k++) {
C[i][j] += ((A[i][k] % mod) * (B[k][j] % mod)) % mod;
C[i][j] = C[i][j] % mod;
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < p; j++) {
A[i][j] = C[i][j];
}
}
}
public static HashMap<Character, Integer> sortMapDesc(HashMap<Character, Integer> map) {
List<Map.Entry<Character, Integer>> list = new LinkedList<>(map.entrySet());
Collections.sort(list, (o1, o2) -> o2.getValue() - o1.getValue());
HashMap<Character, Integer> temp = new LinkedHashMap<>();
for (Map.Entry<Character, Integer> i : list) {
temp.put(i.getKey(), i.getValue());
}
return temp;
}
public static HashMap<Integer, Integer> sortMapAsc(HashMap<Integer, Integer> map) {
List<Map.Entry<Integer, Integer>> list = new LinkedList<>(map.entrySet());
Collections.sort(list, (o1, o2) -> o1.getValue() - o2.getValue());
HashMap<Integer, Integer> temp = new LinkedHashMap<>();
for (Map.Entry<Integer, Integer> i : list) {
temp.put(i.getKey(), i.getValue());
}
return temp;
}
public static long lcm(long l, long l2) {
long val = gcd(l, l2);
return (l * l2) / val;
}
public static int isSubsequence(String s, String t) {
int n = s.length();
int m = t.length();
if (m > n) {
return Integer.MAX_VALUE;
}
int i = 0, j = 0, skip = 0;
while (i < n && j < m) {
if (s.charAt(i) == t.charAt(j)) {
--skip;
++j;
}
++skip;
++i;
}
while (i < n) {
++i;
++skip;
}
if (j != m) {
skip = Integer.MAX_VALUE;
}
return skip;
}
public static long[][] combination(int l, int r) {
long[][] pascal = new long[l + 1][r + 1];
pascal[0][0] = 1;
for (int i = 1; i <= l; ++i) {
pascal[i][0] = 1;
for (int j = 1; j <= r; ++j) {
pascal[i][j] = pascal[i - 1][j - 1] + pascal[i - 1][j];
}
}
return pascal;
}
public static long gcd(long... array) {
long ret = array[0];
for (int i = 1; i < array.length; ++i) ret = gcd(ret, array[i]);
return ret;
}
public static long lcm(int... array) {
long ret = array[0];
for (int i = 1; i < array.length; ++i) ret = lcm(ret, array[i]);
return ret;
}
public static int min(int a, int b) {
return a < b ? a : b;
}
public static int min(int... array) {
int ret = array[0];
for (int i = 1; i < array.length; ++i) ret = min(ret, array[i]);
return ret;
}
public static long min(long a, long b) {
return a < b ? a : b;
}
public static long min(long... array) {
long ret = array[0];
for (int i = 1; i < array.length; ++i) ret = min(ret, array[i]);
return ret;
}
public static int max(int a, int b) {
return a > b ? a : b;
}
public static int max(int... array) {
int ret = array[0];
for (int i = 1; i < array.length; ++i) ret = max(ret, array[i]);
return ret;
}
public static long max(long a, long b) {
return a > b ? a : b;
}
public static long max(long... array) {
long ret = array[0];
for (int i = 1; i < array.length; ++i) ret = max(ret, array[i]);
return ret;
}
public static long sum(int... array) {
long ret = 0;
for (int i : array) ret += i;
return ret;
}
public static long sum(long... array) {
long ret = 0;
for (long i : array) ret += i;
return ret;
}
public static long[] facts(int n)
{
long[] fact=new long[1005];
fact[0]=1;
fact[1]=1;
for(int i=2;i<n;i++)
{
fact[i]=(long)(i*fact[i-1])%mod;
}
return fact;
}
public static long[] inv(long[] fact,int n)
{
long[] inv=new long[n];
inv[n-1]= CP.Modular_Expo(fact[n-1],mod-2,mod)%mod;
for(int i=n-2;i>=0;--i)
{
inv[i]=(inv[i+1]*(i+1))%mod;
}
return inv;
}
public static int modinv(long x, long mod) {
return (int) (CP.Modular_Expo(x, mod - 2, mod) % mod);
}
public static int lcs(String s, String t) {
int n = s.length(), m = t.length();
int dp[][] = new int[n + 1][m + 1];
for (int i = 0; i <= n; ++i) {
for (int j = 0; j <= m; ++j) {
if (i == 0 || j == 0) {
dp[i][j] = 0;
} else if (s.charAt(i - 1) == t.charAt(j - 1)) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[n][m];
}
}
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(int[] array) {
for (int i = 0; i < array.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(array[i]);
}
}
public void printLine(int[] array) {
print(array);
writer.println();
}
public void close() {
writer.close();
}
public void printLine(long i) {
writer.println(i);
}
public void printLine(int i) {
writer.println(i);
}
public void printLine(char c) {
writer.println(c);
}
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();
}
void flush() {
writer.flush();
}
}
}
| java |
1305 | B | B. Kuroni and Simple Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNow that Kuroni has reached 10 years old; he is a big boy and doesn't like arrays of integers as presents anymore. This year he wants a Bracket sequence as a Birthday present. More specifically, he wants a bracket sequence so complex that no matter how hard he tries, he will not be able to remove a simple subsequence!We say that a string formed by nn characters '(' or ')' is simple if its length nn is even and positive, its first n2n2 characters are '(', and its last n2n2 characters are ')'. For example, the strings () and (()) are simple, while the strings )( and ()() are not simple.Kuroni will be given a string formed by characters '(' and ')' (the given string is not necessarily simple). An operation consists of choosing a subsequence of the characters of the string that forms a simple string and removing all the characters of this subsequence from the string. Note that this subsequence doesn't have to be continuous. For example, he can apply the operation to the string ')()(()))', to choose a subsequence of bold characters, as it forms a simple string '(())', delete these bold characters from the string and to get '))()'. Kuroni has to perform the minimum possible number of operations on the string, in such a way that no more operations can be performed on the remaining string. The resulting string does not have to be empty.Since the given string is too large, Kuroni is unable to figure out how to minimize the number of operations. Can you help him do it instead?A sequence of characters aa is a subsequence of a string bb if aa can be obtained from bb by deletion of several (possibly, zero or all) characters.InputThe only line of input contains a string ss (1≤|s|≤10001≤|s|≤1000) formed by characters '(' and ')', where |s||s| is the length of ss.OutputIn the first line, print an integer kk — the minimum number of operations you have to apply. Then, print 2k2k lines describing the operations in the following format:For each operation, print a line containing an integer mm — the number of characters in the subsequence you will remove.Then, print a line containing mm integers 1≤a1<a2<⋯<am1≤a1<a2<⋯<am — the indices of the characters you will remove. All integers must be less than or equal to the length of the current string, and the corresponding subsequence must form a simple string.If there are multiple valid sequences of operations with the smallest kk, you may print any of them.ExamplesInputCopy(()((
OutputCopy1
2
1 3
InputCopy)(
OutputCopy0
InputCopy(()())
OutputCopy1
4
1 2 5 6
NoteIn the first sample; the string is '(()(('. The operation described corresponds to deleting the bolded subsequence. The resulting string is '((('; and no more operations can be performed on it. Another valid answer is choosing indices 22 and 33, which results in the same final string.In the second sample, it is already impossible to perform any operations. | [
"constructive algorithms",
"greedy",
"strings",
"two pointers"
] | import java.util.*;
import java.io.*;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.math.BigInteger;
public final class Main{
static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException {
din = new DataInputStream(
new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
if (cnt != 0) {
break;
}
else {
continue;
}
}
buf[cnt++] = (byte)c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ') c = read();
boolean neg = (c == '-');
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg) return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0,
BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null)
return;
din.close();
}
}
static class Kattio extends PrintWriter {
private BufferedReader r;
private StringTokenizer st;
// standard input
public Kattio() { this(System.in, System.out); }
public Kattio(InputStream i, OutputStream o) {
super(o);
r = new BufferedReader(new InputStreamReader(i));
}
// USACO-style file input
public Kattio(String problemName) throws IOException {
super(new FileWriter(problemName + ".out"));
r = new BufferedReader(new FileReader(problemName + ".in"));
}
// returns null if no more input
public String next() {
try {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(r.readLine());
return st.nextToken();
} catch (Exception e) { }
return null;
}
public int nextInt() { return Integer.parseInt(next()); }
public double nextDouble() { return Double.parseDouble(next()); }
public long nextLong() { return Long.parseLong(next()); }
}
static Kattio sc = new Kattio();
static long mod = 998244353l;
static PrintWriter out =new PrintWriter(System.out);
//Heapify function to maintain heap property.
public static void swap(int i,int j,int arr[]) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static void swap(int i,int j,long arr[]) {
long temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static void swap(int i,int j,char arr[]) {
char temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
static String endl = "\n" , gap = " ";
public static void main(String[] args)throws IOException {
int t =1;
while(t-->0) {
solve();
}
out.close();
}
public static void solve()throws IOException {
char s[] = rac();
List<Integer> l1 = new ArrayList<>();
List<Integer> l2 = new ArrayList<>();
int i =0 , j = s.length -1;
while(i < j) {
while(i < j && s[i] == ')') i++;
while(i < j && s[j] == '(') j--;
while(i < j && s[i] == '(' && s[j] == ')') {
l1.add(i + 1);
l2.add(j + 1);
i++;
j--;
}
}
if(l1.size() == 0) {
System.out.println(0);
return;
}
System.out.println(1);
System.out.println(l1.size() + l2.size()) ;
for(int x : l1)
System.out.print(x + " ");
for( i =l2.size() -1;i>=0;i--) {
System.out.print(l2.get(i) + " ");
}
System.out.println();
}
public static boolean isSubsequene(char a[], char b[] ) {
int i =0 , j = 0;
while(i < a.length && j <b.length) {
if(a[i] == b[j]) {
j++;
}
i++;
}
return j >= b.length;
}
public static int dfs(int node , HashMap<Integer , List<Integer>> map ,boolean[] vis , HashSet<Integer> set) {
System.out.println("At node " + node);
vis[node] = true;
boolean canGo = false;
int ans = 0;
for(int x : map.get(node)) {
if(!vis[x]) {
int curans = dfs(x , map , vis , set);
if(curans > 0 ) {
set.add(node);
}
canGo = true;
}
}
if(!canGo) {
ans++;
}
return ans;
}
public static int[] getCnt1(int arr[][] ,int max) {
int n = arr.length;
int tree[] = new int[max + 4];
int cnt2[] = new int[n];
for(int i =n-1;i>=0;i--) {
int index = arr[i][2] , start = arr[i][0] , end = arr[i][1];
int curPos = end;
int res = 0;
while(curPos >0) {
res += tree[curPos];
curPos -= curPos&(-curPos);
}
// System.out.println("IS res " + res);
curPos = end;
cnt2[index] = res;
while(curPos < tree.length) {
tree[curPos] += 1;
curPos += curPos&(-curPos);
}
}
return cnt2;
}
public static int getIndex(List<Integer> list , int val ) {
if(list.size() == 0) return 0;
int l =0 , r =list.size()-1;
while(l <= r) {
int mid = l + (r-l)/2;
if(list.get(mid) <= val) l = mid + 1;
else r = mid-1;
}
if(r == -1) return 0;
return r;
}
public static long getSum(long n ) {
long ans = 0;
while(n > 0) {
ans += n%10;
n /= 10;
}
return ans;
}
public static long fib(int n ,long M) {
if (n == 0) {
return 0;
} else if (n == 1) {
return 1;
} else {
long[][] mat = {{1, 1}, {1, 0}};
mat = pow(mat, n-1 , M);
return mat[0][0];
}
}
public static long[][] pow(long[][] mat, int n ,long M) {
if (n == 1) return mat;
else if (n % 2 == 0) return pow(mul(mat, mat , M), n/2 , M);
else return mul(pow(mul(mat, mat,M), n/2,M), mat , M);
}
static long[][] mul(long[][] p, long[][] q,long M) {
long a = (p[0][0]*q[0][0] + p[0][1]*q[1][0])%M;
long b = (p[0][0]*q[0][1] + p[0][1]*q[1][1])%M;
long c = (p[1][0]*q[0][0] + p[1][1]*q[1][0])%M;
long d = (p[1][0]*q[0][1] + p[1][1]*q[1][1])%M;
return new long[][] {{a, b}, {c, d}};
}
public static long[] kdane(long arr[]) {
int n = arr.length;
long dp[] = new long[n];
dp[0] = arr[0];
long ans = dp[0];
for(int i = 1;i<n;i++) {
dp[i] = Math.max(dp[i-1] + arr[i] , arr[i]);
ans = Math.max(ans , dp[i]);
}
return dp;
}
public static void update(int low , int high , int l , int r, int val , int treeIndex ,int tree[]) {
if(low > r || high < l || high < low) return;
if(l <= low && high <= r) {
System.out.println("At " +low + " and " + high + " ans ttreeIndex " + treeIndex);
tree[treeIndex] += val;
return;
}
int mid = low + (high - low)/2;
update(low , mid , l , r , val , treeIndex*2 + 1, tree);
update(mid + 1 , high , l , r , val , treeIndex*2 + 2 , tree);
}
static int colx[] = {1 ,-1, 0,0 , 1,1,-1,-1};
static int coly[] = {0 ,0, 1,-1,1,-1,1,-1};
public static void reverse(char arr[]) {
int i =0 , j = arr.length-1;
while(i < j) {
swap(i , j , arr);
i++;
j--;
}
}
public static long[] reverse(long arr[]) {
long newans[] = arr.clone();
int i =0 , j = arr.length-1;
while(i < j) {
swap(i , j , newans);
i++;
j--;
}
return newans;
}
public static long inverse(long x , long mod) {
return pow(x , mod -2 , mod);
}
public static int maxArray(int arr[]) {
int ans = arr[0] , n = arr.length;
for(int i =1;i<n;i++) {
ans = Math.max(ans , arr[i]);
}
return ans;
}
public static long maxArray(long arr[]) {
long ans = arr[0];
int n = arr.length;
for(int i =1;i<n;i++) {
ans = Math.max(ans , arr[i]);
}
return ans;
}
public static int minArray(int arr[]) {
int ans = arr[0] , n = arr.length;
for(int i =0;i<n;i++ ) {
ans = Math.min(ans ,arr[i]);
}
return ans;
}
public static long minArray(long arr[]) {
long ans = arr[0];
int n = arr.length;
for(int i =0;i<n;i++ ) {
ans = Math.min(ans ,arr[i]);
}
return ans;
}
public static int sumArray(int arr[]) {
int ans = 0;
for(int x : arr) {
ans += x;
}
return ans;
}
public static long sumArray(long arr[]) {
long ans = 0;
for(long x : arr) {
ans += x;
}
return ans;
}
public static long rl() {
return sc.nextLong();
}
public static char[] rac() {
return sc.next().toCharArray();
}
public static String rs() {
return sc.next();
}
public static char rc() {
return sc.next().charAt(0);
}
public static int [] rai(int n) {
int ans[] = new int[n];
for(int i =0;i<n;i++) {
ans[i] = sc.nextInt();
}
return ans;
}
public static long [] ral(int n) {
long ans[] = new long[n];
for(int i =0;i<n;i++) {
ans[i] = sc.nextLong();
}
return ans;
}
public static int ri() {
return sc.nextInt();
}
public static int getValue(int num ) {
int ans = 0;
while(num > 0) {
ans++;
num = num&(num-1);
}
return ans;
}
public static boolean isValid(int x ,int y , int n,char arr[][],boolean visited[][][][]) {
return x>=0 && x<n && y>=0 && y <n && !(arr[x][y] == '#');
}
// public static Pair join(Pair a , Pair b) {
// Pair res = new Pair(Math.min(a.min , b.min) , Math.max(a.max , b.max) , a.count + b.count);
// return res;
// }
// segment tree query over range
// public static int query(int node,int l , int r,int a,int b ,Pair tree[] ) {
// if(tree[node].max < a || tree[node].min > b) return 0;
// if(l > r) return 0;
// if(tree[node].min >= a && tree[node].max <= b) {
// return tree[node].count;
// }
// int mid = l + (r-l)/2;
// int ans = query(node*2 ,l , mid ,a , b , tree) + query(node*2 +1,mid + 1, r , a , b, tree);
// return ans;
// }
// // segment tree update over range
// public static void update(int node, int i , int j ,int l , int r,long value, long arr[] ) {
// if(l >= i && j >= r) {
// arr[node] += value;
// return;
// }
// if(j < l|| r < i) return;
// int mid = l + (r-l)/2;
// update(node*2 ,i ,j ,l,mid,value, arr);
// update(node*2 +1,i ,j ,mid + 1,r, value , arr);
// }
public static long pow(long a , long b , long mod) {
if(b == 1) return a;
if(b == 0) return 1;
long ans = pow(a , b/2 , mod)%mod;
if(b%2 == 0) {
return (ans*ans)%mod;
}
else {
return ((ans*ans)%mod*a)%mod;
}
}
public static boolean isVowel(char ch) {
if(ch == 'a' || ch == 'e'||ch == 'i' || ch == 'o' || ch == 'u') return true;
return false;
}
public static int getFactor(int num) {
if(num==1) return 1;
int ans = 2;
int k = num/2;
for(int i = 2;i<=k;i++) {
if(num%i==0) ans++;
}
return Math.abs(ans);
}
public static int[] readarr()throws IOException {
int n = sc.nextInt();
int arr[] = new int[n];
for(int i =0;i<n;i++) {
arr[i] = sc.nextInt();
}
return arr;
}
public static boolean isPowerOfTwo (long x) {
return x!=0 && ((x&(x-1)) == 0);
}
public static boolean isPrime(long num) {
if(num==1) return false;
if(num<=3) return true;
if(num%2==0||num%3==0) return false;
for(long i =5;i*i<=num;i+=6) {
if(num%i==0 || num%(i+2) == 0) return false;
}
return true;
}
public static boolean isPrime(int num) {
// System.out.println("At pr " + num);
if(num==1) return false;
if(num<=3) return true;
if(num%2==0||num%3==0) return false;
for(int i =5;i*i<=num;i+=6) {
if(num%i==0 || num%(i+2) == 0) return false;
}
return true;
}
// public static boolean isPrime(long num) {
// if(num==1) return false;
// if(num<=3) return true;
// if(num%2==0||num%3==0) return false;
// for(int i =5;i*i<=num;i+=6) {
// if(num%i==0) return false;
// }
// return true;
// }
public static long gcd(long a , long b) {
if (b == 0) return a;
return gcd(b, a % b);
}
public static int gcd(int a , int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
public static int get_gcd(int a , int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
public static long get_gcd(long a , long b) {
if (b == 0) return a;
return gcd(b, a % b);
}
// public static long fac(long num) {
// long ans = 1;
// int mod = (int)1e9+7;
// for(long i = 2;i<=num;i++) {
// ans = (ans*i)%mod;
// }
// return ans;
// }
} | java |
1295 | C | C. Obtain The Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings ss and tt consisting of lowercase Latin letters. Also you have a string zz which is initially empty. You want string zz to be equal to string tt. You can perform the following operation to achieve this: append any subsequence of ss at the end of string zz. A subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, if z=acz=ac, s=abcdes=abcde, you may turn zz into following strings in one operation: z=acacez=acace (if we choose subsequence aceace); z=acbcdz=acbcd (if we choose subsequence bcdbcd); z=acbcez=acbce (if we choose subsequence bcebce). Note that after this operation string ss doesn't change.Calculate the minimum number of such operations to turn string zz into string tt. InputThe first line contains the integer TT (1≤T≤1001≤T≤100) — the number of test cases.The first line of each testcase contains one string ss (1≤|s|≤1051≤|s|≤105) consisting of lowercase Latin letters.The second line of each testcase contains one string tt (1≤|t|≤1051≤|t|≤105) consisting of lowercase Latin letters.It is guaranteed that the total length of all strings ss and tt in the input does not exceed 2⋅1052⋅105.OutputFor each testcase, print one integer — the minimum number of operations to turn string zz into string tt. If it's impossible print −1−1.ExampleInputCopy3
aabce
ace
abacaba
aax
ty
yyt
OutputCopy1
-1
3
| [
"dp",
"greedy",
"strings"
] | import java.util.*;
import java.io.*;
public class Main {
static int[] parent, size;
static ArrayList<Integer>[] arr;
static char[] a, b;
public static void main(String[] args) throws IOException {
int t = sc.nextInt();
while (t-- > 0) {
a = sc.next().toCharArray();
b = sc.next().toCharArray();
if (!check()) {
pw.println(-1);
continue;
}
arr = new ArrayList[26];
for (int i = 0; i < arr.length; i++) {
arr[i] = new ArrayList<>();
}
for (int i = 0; i < a.length; i++) {
arr[a[i] - 'a'].add(i);
}
int idx = 0;
int ans = 0;
while (idx < b.length) {
int cur = -1;
while (true) {
if (idx >= b.length)
break;
int next = query(cur, b[idx]);
if (next == -1) {
ans++;
break;
}
cur = next;
idx++;
}
}
pw.println(ans + 1);
}
pw.close();
}
static boolean check() {
boolean[] arrA = new boolean[26];
boolean[] arrB = new boolean[26];
for (int i = 0; i < a.length; i++) {
arrA[a[i] - 'a'] = true;
}
for (int i = 0; i < b.length; i++) {
arrB[b[i] - 'a'] = true;
}
for (int i = 0; i < arrB.length; i++) {
if (arrB[i] && !arrA[i])
return false;
}
return true;
}
static int query(int idx, char c) {
ArrayList<Integer> list = arr[c - 'a'];
if (list.isEmpty() || list.get(list.size() - 1) <= idx)
return -1;
int l = 0;
int r = list.size() - 1;
while (l <= r) {
int m = l + r >> 1;
if (list.get(m) <= idx)
l = m + 1;
else
r = m - 1;
}
return list.get(l);
}
static int find(int a) {
if (a == parent[a])
return a;
return parent[a] = find(parent[a]);
}
static void union(int a, int b) {
a = find(a);
b = find(b);
if (a == b)
return;
if (size[a] < size[b])
parent[a] = b;
else
parent[b] = a;
}
static long[] HashStr(char[] arr) {
long[] hash = new long[arr.length];
int p = 31;
int m = 1000000007;
long hashValue = 0;
long power = 1;
for (int i = 0; i < arr.length; i++) {
hashValue = (hashValue + (arr[i] - 'a' + 1) * power) % m;
power = (power * p) % m;
hash[i] = hashValue;
}
return hash;
}
static int toInt(boolean flag) {
return flag ? 1 : 0;
}
static int log2(int n) {
return (int) (Math.log(n) / Math.log(2));
}
static int[] sieve() {
int n = (int) 1e5;
int[] arr = new int[n];
for (int i = 2; i < arr.length; i++) {
for (int j = i; j < arr.length; j += i) {
if (arr[j] == 0)
arr[j] = i;
}
}
return arr;
}
static void shuffle(int[] arr) {
int n = arr.length;
for (int i = 0; i < n; i++) {
int r = i + (int) (Math.random() * (n - i));
int tmp = arr[i];
arr[i] = arr[r];
arr[r] = tmp;
}
}
static void sort(int[] arr) {
shuffle(arr);
Arrays.sort(arr);
}
static long getSum(int[] arr) {
long sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
static int getMin(int[] arr) {
int min = Integer.MAX_VALUE;
for (int i = 0; i < arr.length; i++) {
min = Math.min(min, arr[i]);
}
return min;
}
static int getMax(int[] arr) {
int max = Integer.MIN_VALUE;
for (int i = 0; i < arr.length; i++) {
max = Math.max(max, arr[i]);
}
return max;
}
static boolean isEqual(int[] a, int[] b) {
if (a.length != b.length)
return false;
for (int i = 0; i < b.length; i++) {
if (a[i] != b[i])
return false;
}
return true;
}
static void reverse(int[] arr, int start, int end) {
while (start < end) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
static boolean isSorted(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i + 1])
return false;
}
return true;
}
static int gcd(int x, int y) {
if (x == 0)
return y;
return gcd(y % x, x);
}
static HashMap<Integer, Integer> Hash(int[] arr) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int i : arr) {
map.put(i, map.getOrDefault(i, 0) + 1);
}
return map;
}
static HashMap<Character, Integer> Hash(char[] arr) {
HashMap<Character, Integer> map = new HashMap<>();
for (char i : arr) {
map.put(i, map.getOrDefault(i, 0) + 1);
}
return map;
}
static boolean isPrime(int n) {
if (n <= 1)
return false;
for (int i = 2; i <= Math.sqrt(n); i++)
if (n % i == 0)
return false;
return true;
}
public static long combination(long n, long r) {
return factorial(n) / (factorial(n - r) * factorial(r));
}
static long factorial(Long n) {
if (n == 0)
return 1;
return (n % mod) * (factorial(n - 1) % mod) % mod;
}
static boolean isPalindrome(char[] str, int i, int j) {
while (i < j) {
if (str[i] != str[j])
return false;
i++;
j--;
}
return true;
}
public static int setBit(int mask, int idx) {
return mask | (1 << idx);
}
public static boolean checkBit(int mask, int idx) {
return (mask & (1 << idx)) != 0;
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public long[] nextlongArray(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public Long[] nextLongArray(int n) throws IOException {
Long[] a = new Long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public int[] nextIntArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public int[] nextIntCharArray(int n) throws IOException {
int[] a = new int[n];
char[] b = sc.next().toCharArray();
for (int i = 0; i < n; i++)
a[i] = b[i] - '0';
return a;
}
public int[] NextIntArray(int n) throws IOException {
int[] arr = new int[n + 1];
for (int i = 1; i < arr.length; i++) {
arr[i] = nextInt();
}
return arr;
}
public Integer[] nextIntegerArray(int n) throws IOException {
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public ArrayList<Integer>[] directedGraph(int n, int m) throws IOException {
ArrayList<Integer>[] graph = new ArrayList[n];
for (int i = 0; i < graph.length; i++) {
graph[i] = new ArrayList<>();
}
while (m-- > 0) {
int a = nextInt();
int b = nextInt();
graph[a].add(b);
}
return graph;
}
public ArrayList<Integer>[] undirectedGraph(int n, int m) throws IOException {
ArrayList<Integer>[] graph = new ArrayList[n];
for (int i = 0; i < graph.length; i++) {
graph[i] = new ArrayList<>();
}
while (m-- > 0) {
int a = nextInt();
int b = nextInt();
graph[a].add(b);
graph[b].add(a);
}
return graph;
}
public boolean ready() throws IOException {
return br.ready();
}
}
static class pair implements Comparable<pair> {
long x;
long y;
public pair(long x, long y) {
this.x = x;
this.y = y;
}
public String toString() {
return x + " " + y;
}
public boolean equals(Object o) {
if (o instanceof pair) {
pair p = (pair) o;
return p.x == x && p.y == y;
}
return false;
}
public int hashCode() {
return new Long(x).hashCode() * 31 + new Long(y).hashCode();
}
public int compareTo(pair other) {
if (this.x == other.x) {
return Long.compare(this.y, other.y);
}
return Long.compare(this.x, other.x);
}
}
public static void print(int[] arr) {
for (int i = 0; i < arr.length; i++) {
pw.print(arr[i] + " ");
}
pw.println();
}
public static void print(int[] arr, String separator) {
for (int i = 0; i < arr.length; i++) {
pw.print(arr[i] + separator);
}
pw.println();
}
public static void print(long[] arr) {
for (int i = 0; i < arr.length; i++) {
pw.print(arr[i] + " ");
}
pw.println();
}
public static void print(ArrayList arr) {
for (int i = 0; i < arr.size(); i++) {
pw.print(arr.get(i) + " ");
}
pw.println();
}
public static void print(int[][] arr) {
for (int[] i : arr) {
print(i);
}
}
public static void print(boolean[] arr) {
for (int i = 0; i < arr.length; i++) {
pw.print(arr[i] + " ");
}
pw.println();
}
public static void print(char[] arr) {
for (int i = 0; i < arr.length; i++) {
pw.print(arr[i] + " ");
}
pw.println();
}
static int inf = Integer.MAX_VALUE;
static long mod = 1000000007;
static Random rn = new Random();
static Scanner sc = new Scanner(System.in);
static PrintWriter pw = new PrintWriter(System.out);
} | java |
1315 | A | A. Dead Pixeltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputScreen resolution of Polycarp's monitor is a×ba×b pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates (x,y)(x,y) (0≤x<a,0≤y<b0≤x<a,0≤y<b). You can consider columns of pixels to be numbered from 00 to a−1a−1, and rows — from 00 to b−1b−1.Polycarp wants to open a rectangular window of maximal size, which doesn't contain the dead pixel. The boundaries of the window should be parallel to the sides of the screen.Print the maximal area (in pixels) of a window that doesn't contain the dead pixel inside itself.InputIn the first line you are given an integer tt (1≤t≤1041≤t≤104) — the number of test cases in the test. In the next lines you are given descriptions of tt test cases.Each test case contains a single line which consists of 44 integers a,b,xa,b,x and yy (1≤a,b≤1041≤a,b≤104; 0≤x<a0≤x<a; 0≤y<b0≤y<b) — the resolution of the screen and the coordinates of a dead pixel. It is guaranteed that a+b>2a+b>2 (e.g. a=b=1a=b=1 is impossible).OutputPrint tt integers — the answers for each test case. Each answer should contain an integer equal to the maximal possible area (in pixels) of a rectangular window, that doesn't contain the dead pixel.ExampleInputCopy6
8 8 0 0
1 10 0 3
17 31 10 4
2 1 0 0
5 10 3 9
10 10 4 8
OutputCopy56
6
442
1
45
80
NoteIn the first test case; the screen resolution is 8×88×8, and the upper left pixel is a dead pixel. Here you can see one of two possible layouts of the maximal window. | [
"implementation"
] | import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t =in.nextInt();
while(t--!=0){
int a = in.nextInt();
int b = in.nextInt();
int x = in.nextInt();
int y = in.nextInt();
// the numbers are in 0 indexed so we need to increse x and y for easy calcuation
x = x+1;
y = y+1;
//now the areas
int area1 = a*(b-y);
int area2 = b*(a-x);
int area3 = a*(y-1);
int area4 = b*(x-1);
int ans = Math.max(area1,Math.max(area2,Math.max(area3,area4)));
System.out.println(ans);
}
//while(t--!=0) {
//int n = in.nextInt();
// int[] dep = new int[n + 1];
// int[] tm = new int[n + 1];
//String reg = "//+";
//String[] arr = str1.split("\\+");
//Arrays.sort(arr);
//String str2 = str1.substring(0,1).toUpperCase() + str1.substring(1);
}
} | java |
1315 | C | C. Restoring Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence b1,b2,…,bnb1,b2,…,bn. Find the lexicographically minimal permutation a1,a2,…,a2na1,a2,…,a2n such that bi=min(a2i−1,a2i)bi=min(a2i−1,a2i), or determine that it is impossible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1001≤t≤100).The first line of each test case consists of one integer nn — the number of elements in the sequence bb (1≤n≤1001≤n≤100).The second line of each test case consists of nn different integers b1,…,bnb1,…,bn — elements of the sequence bb (1≤bi≤2n1≤bi≤2n).It is guaranteed that the sum of nn by all test cases doesn't exceed 100100.OutputFor each test case, if there is no appropriate permutation, print one number −1−1.Otherwise, print 2n2n integers a1,…,a2na1,…,a2n — required lexicographically minimal permutation of numbers from 11 to 2n2n.ExampleInputCopy5
1
1
2
4 1
3
4 1 3
4
2 3 4 5
5
1 5 7 2 8
OutputCopy1 2
-1
4 5 1 2 3 6
-1
1 3 5 6 7 9 2 4 8 10
| [
"greedy"
] | import java.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
static final PrintWriter out =new PrintWriter(System.out);
static final FastReader sc = new FastReader();
//I invented a new word!Plagiarism!
//Did you hear about the mathematician who’s afraid of negative numbers?He’ll stop at nothing to avoid them
//What do Alexander the Great and Winnie the Pooh have in common? Same middle name.
//I finally decided to sell my vacuum cleaner. All it was doing was gathering dust!
//ArrayList<Integer> a=new ArrayList <Integer>();
//PriorityQueue<Integer> pq=new PriorityQueue<>();
//char[] a = s.toCharArray();
// char s[]=sc.next().toCharArray();
public static boolean sorted(int a[])
{
int n=a.length,i;
int b[]=new int[n];
for(i=0;i<n;i++)
b[i]=a[i];
Arrays.sort(b);
for(i=0;i<n;i++)
{
if(a[i]!=b[i])
return false;
}
return true;
}
public static void main (String[] args) throws java.lang.Exception
{
int tes=sc.nextInt();
label:while(tes-->0)
{
int n=sc.nextInt();
int a[]=new int[n];
int b[]=new int[2*n];
int i;
for(i=0;i<n;i++)
a[i]=sc.nextInt();
TreeSet<Integer> set1=new TreeSet<>(); TreeSet<Integer> set2=new TreeSet<>();
for(i=0;i<n;i++)
{
set1.add(a[i]);
b[2*i]=a[i];
}
for(i=1;i<=2*n;i++)
{
if(!set1.contains(i))
set2.add(i);
}
for(i=0;i<n;i++)
{
if(set2.ceiling(a[i])==null)
b[(2*i)+1]=-1;
else
{
b[(2*i)+1]=set2.ceiling(a[i]);
set2.remove(b[(2*i)+1]);
}
}
for(i=0;i<2*n;i++)
{
if(b[i]==-1)
{
System.out.println(-1);
continue label;
}
}
for(i=0;i<2*n;i++)
System.out.print(b[i]+" ");
System.out.println();
}
}
public static int first(ArrayList<Integer> arr, int low, int high, int x, int n)
{
if (high >= low) {
int mid = low + (high - low) / 2;
if ((mid == 0 || x > arr.get(mid-1)) && arr.get(mid) == x)
return mid;
else if (x > arr.get(mid))
return first(arr, (mid + 1), high, x, n);
else
return first(arr, low, (mid - 1), x, n);
}
return -1;
}
public static int last(ArrayList<Integer> arr, int low, int high, int x, int n)
{
if (high >= low) {
int mid = low + (high - low) / 2;
if ((mid == n - 1 || x < arr.get(mid+1)) && arr.get(mid) == x)
return mid;
else if (x < arr.get(mid))
return last(arr, low, (mid - 1), x, n);
else
return last(arr, (mid + 1), high, x, n);
}
return -1;
}
public static int lis(int[] arr) {
int n = arr.length;
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(arr[0]);
for(int i = 1 ; i<n;i++) {
int x = al.get(al.size()-1);
if(arr[i]>=x) {
al.add(arr[i]);
}else {
int v = upper_bound(al, 0, al.size(), arr[i]);
al.set(v, arr[i]);
}
}
return al.size();
}
public static int lower_bound(ArrayList<Long> ar,int lo , int hi , long k)
{
Collections.sort(ar);
int s=lo;
int e=hi;
while (s !=e)
{
int mid = s+e>>1;
if (ar.get((int)mid) <k)
{
s=mid+1;
}
else
{
e=mid;
}
}
if(s==ar.size())
{
return -1;
}
return s;
}
public static int upper_bound(ArrayList<Integer> ar,int lo , int hi, int k)
{
Collections.sort(ar);
int s=lo;
int e=hi;
while (s !=e)
{
int mid = s+e>>1;
if (ar.get(mid) <=k)
{
s=mid+1;
}
else
{
e=mid;
}
}
if(s==ar.size())
{
return -1;
}
return s;
}
static boolean isPrime(long N)
{
if (N<=1) return false;
if (N<=3) return true;
if (N%2 == 0 || N%3 == 0) return false;
for (int i=5; i*i<=N; i=i+6)
if (N%i == 0 || N%(i+2) == 0)
return false;
return true;
}
static int countBits(long a)
{
return (int)(Math.log(a)/Math.log(2)+1);
}
static long fact(long N)
{
long mod=1000000007;
long n=2;
if(N<=1)return 1;
else
{
for(int i=3; i<=N; i++)n=(n*i)%mod;
}
return n;
}
private static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch (NumberFormatException e) {
return false;
} catch (NullPointerException e) {
return false;
}
return true;
}
private static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
private static long lcm(long a, long b) {
return (a / gcd(a, b)) * b;
}
private static boolean isPalindrome(String str) {
int i = 0, j = str.length() - 1;
while (i < j)
if (str.charAt(i++) != str.charAt(j--))
return false;
return true;
}
private static String reverseString(String str) {
StringBuilder sb = new StringBuilder(str);
return sb.reverse().toString();
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | java |
1141 | D | D. Colored Bootstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn left boots and nn right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings ll and rr, both of length nn. The character lili stands for the color of the ii-th left boot and the character riri stands for the color of the ii-th right boot.A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color.For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z').Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible.Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair.InputThe first line contains nn (1≤n≤1500001≤n≤150000), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots).The second line contains the string ll of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th left boot.The third line contains the string rr of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th right boot.OutputPrint kk — the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors.The following kk lines should contain pairs aj,bjaj,bj (1≤aj,bj≤n1≤aj,bj≤n). The jj-th of these lines should contain the index ajaj of the left boot in the jj-th pair and index bjbj of the right boot in the jj-th pair. All the numbers ajaj should be distinct (unique), all the numbers bjbj should be distinct (unique).If there are many optimal answers, print any of them.ExamplesInputCopy10
codeforces
dodivthree
OutputCopy5
7 8
4 9
2 2
9 10
3 1
InputCopy7
abaca?b
zabbbcc
OutputCopy5
6 5
2 3
4 6
7 4
1 2
InputCopy9
bambarbia
hellocode
OutputCopy0
InputCopy10
code??????
??????test
OutputCopy10
6 2
1 6
7 3
3 5
4 8
9 7
5 1
2 4
10 9
8 10
| [
"greedy",
"implementation"
] | 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 Pupil
{
static FastReader sc = new FastReader();
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
int t=1;
while(t>0){
int n=sc.nextInt();
String s1=sc.next();
String s2=sc.next();
PriorityQueue<pair>pr1=new PriorityQueue<pair>(Collections.reverseOrder());
PriorityQueue<pair>pr2=new PriorityQueue<pair>( Collections.reverseOrder());
for(int i=0;i<s1.length();i++)
{
char c=s1.charAt(i);
if(c=='?')
{
pr1.add(new pair(200,i));
}
else {
pr1.add(new pair((int)c,i));
}
}
for(int i=0;i<s2.length();i++)
{
char c=s2.charAt(i);
if(c=='?')
{
pr2.add(new pair(200,i));
}
else {
pr2.add(new pair((int)c,i));
}
}
// while(!pr1.isEmpty())
// {
// pair j=pr1.poll();
// System.out.println(j.value+" "+j.index);
// }
ArrayList<pair>waste1=new ArrayList<pair>();
ArrayList<pair>waste2=new ArrayList<pair>();
ArrayList<pair>ans=new ArrayList<pair>();
ArrayList<pair>question1=new ArrayList<pair>();
ArrayList<pair>question2=new ArrayList<pair>();
while(!pr1.isEmpty() && !pr2.isEmpty())
{
pair val1=pr1.poll();
pair val2=pr2.poll();
int check1=val1.value;
int check2=val2.value;
if(check1==200 || check2==200)
{
if(check1==200 && check2==200)
{
question1.add(new pair(check1,val1.index));
question2.add(new pair(check2,val2.index));
}
else if(check1==200)
{
question1.add(new pair(check1,val1.index));
pr2.add(new pair(check2,val2.index));
}
else {
question2.add(new pair(check2,val2.index));
pr1.add(new pair(check1,val1.index));
}
}
else if(check1==check2 && check1!=200)
{
ans.add(new pair(val1.index+1,val2.index+1));
}
else {
if(check1>check2)
{
waste2.add(new pair(check2,val2.index));
pr1.add(new pair(check1,val1.index));
}
else {
waste1.add(new pair(check1,val1.index));
pr2.add(new pair(check2,val2.index));
}
}
}
if(!pr1.isEmpty())
{
while(!pr1.isEmpty())
{
pair g=pr1.poll();
if(g.value==200)
{
question1.add(new pair(g.value,g.index));
}
else {
waste1.add(new pair(g.value,g.index));
}
}
}
else if(!pr2.isEmpty())
{
while(!pr2.isEmpty())
{
pair g=pr2.poll();
if(g.value==200)
{
question2.add(new pair(g.value,g.index));
}
else {
waste2.add(new pair(g.value,g.index));
}
}
}
else {}
// for(int i=0;i<waste1.size();i++)
// {
// pair waste=waste1.get(i);
// System.out.println(waste.value+" "+waste.index);
// }
// System.out.println();
// for(int i=0;i<waste2.size();i++)
// {
// pair waste=waste2.get(i);
// System.out.println(waste.value+" "+waste.index);
// }
// System.out.println();
// for(int i=0;i<question1.size();i++)
// {
// pair waste=question1.get(i);
// System.out.println(waste.value+" "+waste.index);
// }
// System.out.println();
// for(int i=0;i<question2.size();i++)
// {
// pair waste=question2.get(i);
// System.out.println(waste.value+" "+waste.index);
// }
// System.out.println();
int chick1=0;
for(int i=0;i<Math.min(waste1.size(), question2.size());i++)
{
pair waste=waste1.get(i);
pair question=question2.get(i);
ans.add(new pair(waste.index+1,question.index+1));
chick1=i+1;
}
int chick2=0;
for(int i=0;i<Math.min(waste2.size(), question1.size());i++)
{
pair waste=waste2.get(i);
pair question=question1.get(i);
ans.add(new pair(question.index+1,waste.index+1));
chick2=i+1;
}
if(question1.size()>waste2.size() && question2.size()>waste1.size())
{
int jinx1=question1.size()-chick1;
int jinx2=question2.size()-chick2;
for(int i=0;i<Math.min(jinx1,jinx2);i++)
{
pair u=question1.get(chick1);
pair u1=question2.get(chick2);
ans.add(new pair(u.index+1,u1.index+1));
chick1++;
chick2++;
}
}
System.out.println(ans.size());
for(int i=0;i<ans.size();i++)
{
pair obaidbhadwa=ans.get(i);
System.out.println(obaidbhadwa.value+" "+obaidbhadwa.index);
}
t--;
}
}
// FAST I/O
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public static boolean two(int n)//power of two
{
if((n&(n-1))==0)
{
return true;
}
else{
return false;
}
}
public static boolean isPrime(long n){
for (int i = 2; i * i <= n; ++i) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static int digit(int n)
{
int n1=(int)Math.floor((int)Math.log10(n)) + 1;
return n1;
}
}
//CAAL THE BELOW FUNCTION IF PARING PRIORITY IS NEEDED //
// PriorityQueue<pair> pq = new PriorityQueue<>(); **********declare the syntax in the main function******
// pq.add(1,2)///////
class pair implements Comparable<pair> {
int value, index;
pair(int v, int i) { index = i; value = v; }
@Override
public int compareTo(pair o) { return o.value - value; }
}
// User defined Pair class
// class Pair {
// int x;
// int y;
//
// // Constructor
// public Pair(int x, int y)
// {
// this.x = x;
// this.y = y;
// }
// }
// Arrays.sort(arr, new Comparator<Pair>() {
// @Override public int compare(Pair p1, Pair p2)
// {
// return p1.x - p2.x;
// }
// });
// class Pair {
// int height, id;
//
// public Pair(int i, int s) {
// this.height = s;
// this.id = i;
// }
// }
//Arrays.sort(trips, (a, b) -> Integer.compare(a[1], b[1]));
// ArrayList<ArrayList<Integer>> connections = new ArrayList<ArrayList<Integer>>();
// for(int i = 0; i<n;i++)
// connections.add(new ArrayList<Integer>()); | java |
1141 | A | A. Game 23time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp plays "Game 23". Initially he has a number nn and his goal is to transform it to mm. In one move, he can multiply nn by 22 or multiply nn by 33. He can perform any number of moves.Print the number of moves needed to transform nn to mm. Print -1 if it is impossible to do so.It is easy to prove that any way to transform nn to mm contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation).InputThe only line of the input contains two integers nn and mm (1≤n≤m≤5⋅1081≤n≤m≤5⋅108).OutputPrint the number of moves to transform nn to mm, or -1 if there is no solution.ExamplesInputCopy120 51840
OutputCopy7
InputCopy42 42
OutputCopy0
InputCopy48 72
OutputCopy-1
NoteIn the first example; the possible sequence of moves is: 120→240→720→1440→4320→12960→25920→51840.120→240→720→1440→4320→12960→25920→51840. The are 77 steps in total.In the second example, no moves are needed. Thus, the answer is 00.In the third example, it is impossible to transform 4848 to 7272. | [
"implementation",
"math"
] | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
if (m %n != 0) {
System.out.println("-1");
} else if (m == n) {
System.out.println("0");
} else if (m %n == 0) {
int x = m / n;
if (x %2 != 0 && x %3 != 0) {
System.out.println("-1");
} else {
int count2 = 0, count3 = 0;
while (x %3 == 0 && x > 0) {
x /= 3;
count3++;
}
while (x %2 == 0 && x > 0) {
x /= 2;
count2++;
}
if (x != 1) {
System.out.println("-1");
} else {
System.out.println(count2 + count3);
}
}
}
}
}
| java |
1141 | G | G. Privatization of Roads in Treelandtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTreeland consists of nn cities and n−1n−1 roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right — the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed kk and the number of companies taking part in the privatization is minimal.Choose the number of companies rr such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most kk. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal rr that there is such assignment to companies from 11 to rr that the number of cities which are not good doesn't exceed kk. The picture illustrates the first example (n=6,k=2n=6,k=2). The answer contains r=2r=2 companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number 33) is not good. The number of such vertices (just one) doesn't exceed k=2k=2. It is impossible to have at most k=2k=2 not good cities in case of one company. InputThe first line contains two integers nn and kk (2≤n≤200000,0≤k≤n−12≤n≤200000,0≤k≤n−1) — the number of cities and the maximal number of cities which can have two or more roads belonging to one company.The following n−1n−1 lines contain roads, one road per line. Each line contains a pair of integers xixi, yiyi (1≤xi,yi≤n1≤xi,yi≤n), where xixi, yiyi are cities connected with the ii-th road.OutputIn the first line print the required rr (1≤r≤n−11≤r≤n−1). In the second line print n−1n−1 numbers c1,c2,…,cn−1c1,c2,…,cn−1 (1≤ci≤r1≤ci≤r), where cici is the company to own the ii-th road. If there are multiple answers, print any of them.ExamplesInputCopy6 2
1 4
4 3
3 5
3 6
5 2
OutputCopy2
1 2 1 1 2 InputCopy4 2
3 1
1 4
1 2
OutputCopy1
1 1 1 InputCopy10 2
10 3
1 2
1 3
1 4
2 5
2 6
2 7
3 8
3 9
OutputCopy3
1 1 2 3 2 3 1 3 1 | [
"binary search",
"constructive algorithms",
"dfs and similar",
"graphs",
"greedy",
"trees"
] | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Iterator;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.io.Closeable;
import java.io.Writer;
import java.io.OutputStreamWriter;
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 Exception {
Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27);
thread.start();
thread.join();
}
static class TaskAdapter implements Runnable {
@Override
public void run() {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastInput in = new FastInput(inputStream);
FastOutput out = new FastOutput(outputStream);
TaskG solver = new TaskG();
solver.solve(1, in, out);
out.close();
}
}
static class TaskG {
MultiWayStack<Edge> edges;
int[] cnt;
int[] size;
public void solve(int testNumber, FastInput in, FastOutput out) {
int n = in.readInt();
int k = in.readInt();
edges = new MultiWayStack<>(n + 1, n * 2);
Edge[] es = new Edge[n];
cnt = new int[n + 1];
size = new int[n + 1];
for (int i = 1; i < n; i++) {
Edge e = new Edge();
es[i] = e;
e.a = in.readInt();
e.b = in.readInt();
edges.addFirst(e.a, e);
edges.addFirst(e.b, e);
size[e.a]++;
size[e.b]++;
}
IntBinarySearch bs = new IntBinarySearch() {
public boolean check(int mid) {
dfs(1, null, mid);
return cnt[1] <= k;
}
};
int ans = bs.binarySearch(1, n);
bs.check(ans);
out.println(ans);
paint(1, null, ans);
for (int i = 1; i < n; i++) {
out.append(es[i].color + 1).append(' ');
}
}
public void paint(int root, Edge p, int c) {
int color = 0;
if (p != null) {
color = p.color + 1;
}
for (Edge e : edges.queue(root)) {
if (e == p) {
continue;
}
int node = e.other(root);
e.color = color % c;
color++;
paint(node, e, c);
}
}
public void dfs(int root, Edge p, int c) {
cnt[root] = 0;
if (size[root] > c) {
cnt[root]++;
}
for (Edge e : edges.queue(root)) {
if (e == p) {
continue;
}
int node = e.other(root);
dfs(node, e, c);
cnt[root] += cnt[node];
}
}
}
static class MultiWayStack<T> {
private Object[] values;
private int[] next;
private int[] heads;
private int alloc;
private int queueNum;
public RevokeIterator iterator(final int queue) {
return new RevokeIterator<T>() {
int ele = heads[queue];
int pre = 0;
public boolean hasNext() {
return ele != 0;
}
public T next() {
T ans = (T) values[ele];
pre = ele;
ele = next[ele];
return ans;
}
public void revoke() {
ele = pre;
pre = 0;
}
};
}
public Iterable<T> queue(int qId) {
return new Iterable<T>() {
public Iterator<T> iterator() {
return MultiWayStack.this.iterator(qId);
}
};
}
private void doubleCapacity() {
int newSize = Math.max(next.length + 10, next.length * 2);
next = Arrays.copyOf(next, newSize);
values = Arrays.copyOf(values, newSize);
}
public void alloc() {
alloc++;
if (alloc >= next.length) {
doubleCapacity();
}
next[alloc] = 0;
}
public MultiWayStack(int qNum, int totalCapacity) {
values = (T[]) new Object[totalCapacity + 1];
next = new int[totalCapacity + 1];
heads = new int[qNum];
queueNum = qNum;
}
public void addFirst(int qId, T x) {
alloc();
values[alloc] = x;
next[alloc] = heads[qId];
heads[qId] = alloc;
}
public String toString() {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < queueNum; i++) {
builder.append(i).append(": ");
for (Iterator iterator = iterator(i); iterator.hasNext(); ) {
builder.append(iterator.next()).append(",");
}
if (builder.charAt(builder.length() - 1) == ',') {
builder.setLength(builder.length() - 1);
}
builder.append('\n');
}
return builder.toString();
}
}
static class Edge {
int a;
int b;
int color;
int other(int x) {
return a ^ b ^ x;
}
}
static abstract class IntBinarySearch {
public abstract boolean check(int mid);
public int binarySearch(int l, int r) {
if (l > r) {
throw new IllegalArgumentException();
}
while (l < r) {
int mid = (l + r) >>> 1;
if (check(mid)) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
}
}
static interface RevokeIterator<E> extends Iterator<E> {
}
static class FastOutput implements AutoCloseable, Closeable {
private StringBuilder cache = new StringBuilder(10 << 20);
private final Writer os;
public FastOutput(Writer os) {
this.os = os;
}
public FastOutput(OutputStream os) {
this(new OutputStreamWriter(os));
}
public FastOutput append(char c) {
cache.append(c);
return this;
}
public FastOutput append(int c) {
cache.append(c);
return this;
}
public FastOutput println(int c) {
cache.append(c).append('\n');
return this;
}
public FastOutput flush() {
try {
os.append(cache);
os.flush();
cache.setLength(0);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return this;
}
public void close() {
flush();
try {
os.close();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public String toString() {
return cache.toString();
}
}
static class FastInput {
private final InputStream is;
private byte[] buf = new byte[1 << 13];
private int bufLen;
private int bufOffset;
private int next;
public FastInput(InputStream is) {
this.is = is;
}
private int read() {
while (bufLen == bufOffset) {
bufOffset = 0;
try {
bufLen = is.read(buf);
} catch (IOException e) {
bufLen = -1;
}
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;
}
}
}
| java |
1284 | C | C. New Year and Permutationtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputRecall that the permutation is an array consisting of nn distinct integers from 11 to nn in arbitrary order. For example, [2,3,1,5,4][2,3,1,5,4] is a permutation, but [1,2,2][1,2,2] is not a permutation (22 appears twice in the array) and [1,3,4][1,3,4] is also not a permutation (n=3n=3 but there is 44 in the array).A sequence aa is a subsegment of a sequence bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. We will denote the subsegments as [l,r][l,r], where l,rl,r are two integers with 1≤l≤r≤n1≤l≤r≤n. This indicates the subsegment where l−1l−1 elements from the beginning and n−rn−r elements from the end are deleted from the sequence.For a permutation p1,p2,…,pnp1,p2,…,pn, we define a framed segment as a subsegment [l,r][l,r] where max{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−lmax{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−l. For example, for the permutation (6,7,1,8,5,3,2,4)(6,7,1,8,5,3,2,4) some of its framed segments are: [1,2],[5,8],[6,7],[3,3],[8,8][1,2],[5,8],[6,7],[3,3],[8,8]. In particular, a subsegment [i,i][i,i] is always a framed segments for any ii between 11 and nn, inclusive.We define the happiness of a permutation pp as the number of pairs (l,r)(l,r) such that 1≤l≤r≤n1≤l≤r≤n, and [l,r][l,r] is a framed segment. For example, the permutation [3,1,2][3,1,2] has happiness 55: all segments except [1,2][1,2] are framed segments.Given integers nn and mm, Jongwon wants to compute the sum of happiness for all permutations of length nn, modulo the prime number mm. Note that there exist n!n! (factorial of nn) different permutations of length nn.InputThe only line contains two integers nn and mm (1≤n≤2500001≤n≤250000, 108≤m≤109108≤m≤109, mm is prime).OutputPrint rr (0≤r<m0≤r<m), the sum of happiness for all permutations of length nn, modulo a prime number mm.ExamplesInputCopy1 993244853
OutputCopy1
InputCopy2 993244853
OutputCopy6
InputCopy3 993244853
OutputCopy32
InputCopy2019 993244853
OutputCopy923958830
InputCopy2020 437122297
OutputCopy265955509
NoteFor sample input n=3n=3; let's consider all permutations of length 33: [1,2,3][1,2,3], all subsegments are framed segment. Happiness is 66. [1,3,2][1,3,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55. [2,1,3][2,1,3], all subsegments except [2,3][2,3] are framed segment. Happiness is 55. [2,3,1][2,3,1], all subsegments except [2,3][2,3] are framed segment. Happiness is 55. [3,1,2][3,1,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55. [3,2,1][3,2,1], all subsegments are framed segment. Happiness is 66. Thus, the sum of happiness is 6+5+5+5+5+6=326+5+5+5+5+6=32. | [
"combinatorics",
"math"
] | import java.util.Scanner;
public class NewYearAndPermutation {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
long mod = scanner.nextLong();
long[] fact = new long[n+1];
fact[0] = 1;
for (int i = 1; i <= n; i++) {
fact[i] = (fact[i-1] * i) % mod;
}
long res = 0;
for (int i = n; i > 0; i--) {
res = (res + ((((i * fact[i]) % mod) * fact[n-i+1]) % mod)) % mod;
}
System.out.println(res);
}
} | java |
1141 | E | E. Superhero Battletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA superhero fights with a monster. The battle consists of rounds; each of which lasts exactly nn minutes. After a round ends, the next round starts immediately. This is repeated over and over again.Each round has the same scenario. It is described by a sequence of nn numbers: d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106). The ii-th element means that monster's hp (hit points) changes by the value didi during the ii-th minute of each round. Formally, if before the ii-th minute of a round the monster's hp is hh, then after the ii-th minute it changes to h:=h+dih:=h+di.The monster's initial hp is HH. It means that before the battle the monster has HH hit points. Print the first minute after which the monster dies. The monster dies if its hp is less than or equal to 00. Print -1 if the battle continues infinitely.InputThe first line contains two integers HH and nn (1≤H≤10121≤H≤1012, 1≤n≤2⋅1051≤n≤2⋅105). The second line contains the sequence of integers d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106), where didi is the value to change monster's hp in the ii-th minute of a round.OutputPrint -1 if the superhero can't kill the monster and the battle will last infinitely. Otherwise, print the positive integer kk such that kk is the first minute after which the monster is dead.ExamplesInputCopy1000 6
-100 -200 -300 125 77 -4
OutputCopy9
InputCopy1000000000000 5
-1 0 0 0 0
OutputCopy4999999999996
InputCopy10 4
-3 -6 5 4
OutputCopy-1
| [
"math"
] | import java.util.Scanner;
public class SuperheroBattle {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
long H = s.nextLong();
int n = s.nextInt();
int a[] = new int[n];
long pre[] = new long[n];
for(int i=0; i<n; i++){
a[i] = s.nextInt();
}
pre[0] = a[0];
for (int i = 1; i < n; ++i) pre[i] += a[i] + pre[i - 1];
//initial check
for (int i = 0; i < n; ++i) {
if (pre[i] + H <= 0) {
System.out.println(i + 1);
return;
}
}
if (pre[n - 1] >= 0) {
System.out.println(-1);
return;
}
//possible
long ans = Long.MAX_VALUE;
for (int i = 0; i < n; ++i) {
long time = (-H - pre[i]) / pre[n - 1];
//System.out.println("time: " + time);
if (pre[n - 1] * time + pre[i] + H <= 0) {
ans = Math.min(ans, time*n + (i + 1));
} else if (pre[n - 1] * (time+1) + pre[i] + H <= 0) {
ans = Math.min(ans, (time + 1) * n + (i + 1));
}
}
System.out.println(ans);
}
}
| java |
1287 | B | B. Hypersettime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBees Alice and Alesya gave beekeeper Polina famous card game "Set" as a Christmas present. The deck consists of cards that vary in four features across three options for each kind of feature: number of shapes; shape, shading, and color. In this game, some combinations of three cards are said to make up a set. For every feature — color, number, shape, and shading — the three cards must display that feature as either all the same, or pairwise different. The picture below shows how sets look.Polina came up with a new game called "Hyperset". In her game, there are nn cards with kk features, each feature has three possible values: "S", "E", or "T". The original "Set" game can be viewed as "Hyperset" with k=4k=4.Similarly to the original game, three cards form a set, if all features are the same for all cards or are pairwise different. The goal of the game is to compute the number of ways to choose three cards that form a set.Unfortunately, winter holidays have come to an end, and it's time for Polina to go to school. Help Polina find the number of sets among the cards lying on the table.InputThe first line of each test contains two integers nn and kk (1≤n≤15001≤n≤1500, 1≤k≤301≤k≤30) — number of cards and number of features.Each of the following nn lines contains a card description: a string consisting of kk letters "S", "E", "T". The ii-th character of this string decribes the ii-th feature of that card. All cards are distinct.OutputOutput a single integer — the number of ways to choose three cards that form a set.ExamplesInputCopy3 3
SET
ETS
TSE
OutputCopy1InputCopy3 4
SETE
ETSE
TSES
OutputCopy0InputCopy5 4
SETT
TEST
EEET
ESTE
STES
OutputCopy2NoteIn the third example test; these two triples of cards are sets: "SETT"; "TEST"; "EEET" "TEST"; "ESTE", "STES" | [
"brute force",
"data structures",
"implementation"
] | // have faith in yourself!!!!!
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
public class CodeForces {
/*-------------------------------------------EDITING CODE STARTS HERE-------------------------------------------*/
public static void main(String[] args) throws IOException {
openIO();
int testCase = 1;
// testCase = sc. nextInt();
for (int i = 1; i <= testCase; i++) solve(i);
closeIO();
}
public static void solve(int tCase) throws IOException {
int n= sc.nextInt();
int k = sc.nextInt();
Set<String> set = new HashSet<>();
String[] str = new String[n];
for(int i=0;i<n;i++){
str[i] = sc.next();
set.add(str[i]);
}
int cnt = 0;
for(int i=0;i<n-1;i++){
for(int j=i+1;j<n;j++){
StringBuilder third = new StringBuilder();
for(int l=0;l<k;l++){
if(str[i].charAt(l)==str[j].charAt(l))third.append(str[i].charAt(l));
else {
if(str[i].charAt(l)!='S' && str[j].charAt(l)!='S')third.append('S');
else if(str[i].charAt(l)!='E' && str[j].charAt(l)!='E')third.append('E');
else if(str[i].charAt(l)!='T' && str[j].charAt(l)!='T')third.append('T');
}
}
if(set.contains(third.toString())){
// out.println(str[i]+" "+str[j]+" "+third);
cnt++;
}
}
}
out.println(cnt/3);
}
public static int mod = (int) 1e9 + 7;
// public static int mod = 998244353;
public static int inf_int = (int) 2e9 ;
public static long inf_long = (long) 2e14;
public static void _sort(int[] arr,boolean isAscending){
int n = arr.length;
List<Integer> list = new ArrayList<>();
for(int ele : arr)list.add(ele);
Collections.sort(list);
if(!isAscending)Collections.reverse(list);
for(int i=0;i<n;i++)arr[i] = list.get(i);
}
public static void _sort(long[] arr,boolean isAscending){
int n = arr.length;
List<Long> list = new ArrayList<>();
for(long ele : arr)list.add(ele);
Collections.sort(list);
if(!isAscending)Collections.reverse(list);
for(int i=0;i<n;i++)arr[i] = list.get(i);
}
static class Pair<K,V> {
K f;
V s;
public Pair(K f) {
this.f = f;
}
public Pair(K f, V s) {
this.f = f;
this.s = s;
}
}
/*-------------------------------------------EDITING CODE ENDS HERE-------------------------------------------*/
static FastestReader sc;
static PrintWriter out;
private static void openIO() throws IOException{
sc = new FastestReader();
out = new PrintWriter(System.out);
}
/*-------------------------------------------FAST INPUT STARTS HERE---------------------------------------------*/
public static void closeIO() throws IOException{
out.flush();
out.close();
sc.close();
}
private static final class FastestReader {
private static final int BUFFER_SIZE = 1 << 16;
private final DataInputStream din;
private final byte[] buffer;
private int bufferPointer, bytesRead;
public FastestReader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public FastestReader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() throws IOException {
int b;
//noinspection StatementWithEmptyBody
while ((b = read()) != -1 && isSpaceChar(b)) {}
return b;
}
public String next() throws IOException {
int b = skip();
final StringBuilder sb = new StringBuilder();
while (!isSpaceChar(b)) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = read();
}
return sb.toString();
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
final boolean neg = c == '-';
if (neg) { c = read(); }
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) { return -ret; }
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ') { c = read(); }
final boolean neg = c == '-';
if (neg) { c = read(); }
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) { return -ret; }
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ') { c = read(); }
final boolean neg = c == '-';
if (neg) { c = read(); }
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg) { return -ret; }
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) { buffer[0] = -1; }
}
private byte read() throws IOException {
if (bufferPointer == bytesRead) { fillBuffer(); }
return buffer[bufferPointer++];
}
public void close() throws IOException {
din.close();
}
}
/*---------------------------------------------FAST INPUT ENDS HERE ---------------------------------------------*/
} | java |
1313 | A | A. Fast Food Restauranttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTired of boring office work; Denis decided to open a fast food restaurant.On the first day he made aa portions of dumplings, bb portions of cranberry juice and cc pancakes with condensed milk.The peculiarity of Denis's restaurant is the procedure of ordering food. For each visitor Denis himself chooses a set of dishes that this visitor will receive. When doing so, Denis is guided by the following rules: every visitor should receive at least one dish (dumplings, cranberry juice, pancakes with condensed milk are all considered to be dishes); each visitor should receive no more than one portion of dumplings, no more than one portion of cranberry juice and no more than one pancake with condensed milk; all visitors should receive different sets of dishes. What is the maximum number of visitors Denis can feed?InputThe first line contains an integer tt (1≤t≤5001≤t≤500) — the number of test cases to solve.Each of the remaining tt lines contains integers aa, bb and cc (0≤a,b,c≤100≤a,b,c≤10) — the number of portions of dumplings, the number of portions of cranberry juice and the number of condensed milk pancakes Denis made.OutputFor each test case print a single integer — the maximum number of visitors Denis can feed.ExampleInputCopy71 2 10 0 09 1 72 2 32 3 23 2 24 4 4OutputCopy3045557NoteIn the first test case of the example, Denis can feed the first visitor with dumplings, give the second a portion of cranberry juice, and give the third visitor a portion of cranberry juice and a pancake with a condensed milk.In the second test case of the example, the restaurant Denis is not very promising: he can serve no customers.In the third test case of the example, Denise can serve four visitors. The first guest will receive a full lunch of dumplings, a portion of cranberry juice and a pancake with condensed milk. The second visitor will get only dumplings. The third guest will receive a pancake with condensed milk, and the fourth guest will receive a pancake and a portion of dumplings. Please note that Denis hasn't used all of the prepared products, but is unable to serve more visitors. | [
"brute force",
"greedy",
"implementation"
] | import java.util.*;
public class JavaApplication38 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int T, a, b, c;
T = in.nextInt();
for (int t = 0; t < T; t++) {
a = in.nextInt();
b = in.nextInt();
c = in.nextInt();
int x[] = {a, b, c};
Arrays.sort(x);
int ans = 0;
for (int i = 0; i < 3; i++) {
if (x[i] > 0) {
ans++;
x[i]--;
}
}
if (x[0] > 0 && x[2] > 0) {
ans++;
x[0]--;
x[2]--;
}
if (x[1] > 0 && x[2] > 0) {
ans++;
x[1]--;
x[2]--;
}
if (x[0] > 0 && x[1] > 0) {
ans++;
x[0]--;
x[1]--;
}
if (x[0] > 0 && x[1] > 0 && x[2] > 0) {
ans++;
}
System.out.println(ans);
}
}
}
| java |
1299 | B | B. Aerodynamictime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are going to build a polygon spaceship. You're given a strictly convex (i. e. no three points are collinear) polygon PP which is defined by coordinates of its vertices. Define P(x,y)P(x,y) as a polygon obtained by translating PP by vector (x,y)−→−−(x,y)→. The picture below depicts an example of the translation:Define TT as a set of points which is the union of all P(x,y)P(x,y) such that the origin (0,0)(0,0) lies in P(x,y)P(x,y) (both strictly inside and on the boundary). There is also an equivalent definition: a point (x,y)(x,y) lies in TT only if there are two points A,BA,B in PP such that AB−→−=(x,y)−→−−AB→=(x,y)→. One can prove TT is a polygon too. For example, if PP is a regular triangle then TT is a regular hexagon. At the picture below PP is drawn in black and some P(x,y)P(x,y) which contain the origin are drawn in colored: The spaceship has the best aerodynamic performance if PP and TT are similar. Your task is to check whether the polygons PP and TT are similar.InputThe first line of input will contain a single integer nn (3≤n≤1053≤n≤105) — the number of points.The ii-th of the next nn lines contains two integers xi,yixi,yi (|xi|,|yi|≤109|xi|,|yi|≤109), denoting the coordinates of the ii-th vertex.It is guaranteed that these points are listed in counterclockwise order and these points form a strictly convex polygon.OutputOutput "YES" in a separate line, if PP and TT are similar. Otherwise, output "NO" in a separate line. You can print each letter in any case (upper or lower).ExamplesInputCopy4
1 0
4 1
3 4
0 3
OutputCopyYESInputCopy3
100 86
50 0
150 0
OutputCopynOInputCopy8
0 0
1 0
2 1
3 3
4 6
3 6
2 5
1 3
OutputCopyYESNoteThe following image shows the first sample: both PP and TT are squares. The second sample was shown in the statements. | [
"geometry"
] | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class cf1299b {
public static void main(String[] args) throws IOException {
int n = ri(), v[][] = new int[n][2];
for(int i = 0; i < n; ++i) {
r();
v[i][0] = ni();
v[i][1] = ni();
}
if((n & 1) > 0) {
prN();
} else {
int half = n / 2, sx = v[0][0] + v[half][0], sy = v[0][1] + v[half][1];
for(int i = 1; i < half; ++i) {
int x = v[i][0] + v[i + half][0], y = v[i][1] + v[i + half][1];
if(x != sx || y != sy) {
prN();
close();
return;
}
}
prY();
}
close();
}
static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out));
static StringTokenizer input;
static Random rand = new Random();
// references
// IBIG = 1e9 + 7
// IRAND ~= 3e8
// IMAX ~= 2e10
// LMAX ~= 9e18
// constants
static final int IBIG = 1000000007;
static final int IRAND = 327859546;
static final int IMAX = 2147483647;
static final int IMIN = -2147483648;
static final long LMAX = 9223372036854775807L;
static final long LMIN = -9223372036854775808L;
// util
static int minof(int a, int b, int c) {return min(a, min(b, c));}
static int minof(int... x) {if(x.length == 1) return x[0]; if(x.length == 2) return min(x[0], x[1]); if(x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] < min) min = x[i]; return min;}
static long minof(long a, long b, long c) {return min(a, min(b, c));}
static long minof(long... x) {if(x.length == 1) return x[0]; if(x.length == 2) return min(x[0], x[1]); if(x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] < min) min = x[i]; return min;}
static int maxof(int a, int b, int c) {return max(a, max(b, c));}
static int maxof(int... x) {if(x.length == 1) return x[0]; if(x.length == 2) return max(x[0], x[1]); if(x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] > max) max = x[i]; return max;}
static long maxof(long a, long b, long c) {return max(a, max(b, c));}
static long maxof(long... x) {if(x.length == 1) return x[0]; if(x.length == 2) return max(x[0], x[1]); if(x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] > max) max = x[i]; return max;}
static int powi(int a, int b) {if(a == 0) return 0; int ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static long powl(long a, int b) {if(a == 0) return 0; long ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static int floori(double d) {return (int)d;}
static int ceili(double d) {return (int)ceil(d);}
static long floorl(double d) {return (long)d;}
static long ceill(double d) {return (long)ceil(d);}
static void reverse(int[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(long[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(double[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(char[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static <T> void reverse(T[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {T swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void shuffle(int[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void shuffle(long[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void shuffle(double[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void shuffle(char[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); char swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static <T> void shuffle(T[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); T swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void rsort(int[] a) {shuffle(a); Arrays.sort(a);}
static void rsort(long[] a) {shuffle(a); Arrays.sort(a);}
static void rsort(double[] a) {shuffle(a); Arrays.sort(a);}
static void rsort(char[] a) {shuffle(a); Arrays.sort(a);}
static <T> void rsort(T[] a) {shuffle(a); Arrays.sort(a);}
static int randInt(int min, int max) {return rand.nextInt(max - min + 1) + min;}
// input
static void r() throws IOException {input = new StringTokenizer(__in.readLine());}
static int ri() throws IOException {return Integer.parseInt(__in.readLine());}
static long rl() throws IOException {return Long.parseLong(__in.readLine());}
static int[] ria(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()); return a;}
static long[] rla(int n) throws IOException {long[] a = new long[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Long.parseLong(input.nextToken()); return a;}
static char[] rcha() throws IOException {return __in.readLine().toCharArray();}
static String rline() throws IOException {return __in.readLine();}
static int rni() throws IOException {input = new StringTokenizer(__in.readLine()); return Integer.parseInt(input.nextToken());}
static int ni() {return Integer.parseInt(input.nextToken());}
static long rnl() throws IOException {input = new StringTokenizer(__in.readLine()); return Long.parseLong(input.nextToken());}
static long nl() {return Long.parseLong(input.nextToken());}
// output
static void pr(int i) {__out.print(i);}
static void prln(int i) {__out.println(i);}
static void pr(long l) {__out.print(l);}
static void prln(long l) {__out.println(l);}
static void pr(double d) {__out.print(d);}
static void prln(double d) {__out.println(d);}
static void pr(char c) {__out.print(c);}
static void prln(char c) {__out.println(c);}
static void pr(char[] s) {__out.print(new String(s));}
static void prln(char[] s) {__out.println(new String(s));}
static void pr(String s) {__out.print(s);}
static void prln(String s) {__out.println(s);}
static void pr(Object o) {__out.print(o);}
static void prln(Object o) {__out.println(o);}
static void prln() {__out.println();}
static void pryes() {__out.println("yes");}
static void pry() {__out.println("Yes");}
static void prY() {__out.println("YES");}
static void prno() {__out.println("no");}
static void prn() {__out.println("No");}
static void prN() {__out.println("NO");}
static void pryesno(boolean b) {__out.println(b ? "yes" : "no");};
static void pryn(boolean b) {__out.println(b ? "Yes" : "No");}
static void prYN(boolean b) {__out.println(b ? "YES" : "NO");}
static void prln(int... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);}
static void prln(long... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);}
static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for(int i = 0; i < n; __out.print(iter.next()), __out.print(' '), ++i); if(n >= 0) __out.println(iter.next());}
static void h() {__out.println("hlfd");}
static void flush() {__out.flush();}
static void close() {__out.close();}
} | java |
13 | A | A. Numberstime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18.Now he wonders what is an average value of sum of digits of the number A written in all bases from 2 to A - 1.Note that all computations should be done in base 10. You should find the result as an irreducible fraction; written in base 10.InputInput contains one integer number A (3 ≤ A ≤ 1000).OutputOutput should contain required average value in format «X/Y», where X is the numerator and Y is the denominator.ExamplesInputCopy5OutputCopy7/3InputCopy3OutputCopy2/1NoteIn the first sample number 5 written in all bases from 2 to 4 looks so: 101, 12, 11. Sums of digits are 2, 3 and 2, respectively. | [
"implementation",
"math"
] | import java.util.Scanner;
public class Numbers {
public static void main(String[] args) {
short a;
short a_clone;
int i_sumDigits;
int i_GCD;
Scanner sc;
sc = new Scanner(System.in);
a = sc.nextShort();
sc.close();
i_sumDigits = 0;
for(int i = 2; i < a; i++) {
a_clone = a;
while(a_clone != 0) {
a_clone /= (short) Math.pow(i, NumOfDivisorA(a_clone, i));
i_sumDigits += a_clone % i;
a_clone /= i;
}
}
i_GCD = GCD(i_sumDigits, a - 2);
System.out.print((i_sumDigits / i_GCD) + "/" + ((a - 2) / i_GCD));
}
static double logaN(int a, int n) {
return Math.log(n) / Math.log(a);
}
static int NumOfDivisorA(int n, int a) {
int i = (int) Math.ceil(logaN(a, n));
while(n % Math.pow(a, i) != 0) {
i--;
}
return i;
}
static int GCD(int a, int b) {
while(a != b) {
if(a > b) {
a -= b;
}
else {
b -= a;
}
}
return a;
}
}
| java |
1301 | C | C. Ayoub's functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAyoub thinks that he is a very smart person; so he created a function f(s)f(s), where ss is a binary string (a string which contains only symbols "0" and "1"). The function f(s)f(s) is equal to the number of substrings in the string ss that contains at least one symbol, that is equal to "1".More formally, f(s)f(s) is equal to the number of pairs of integers (l,r)(l,r), such that 1≤l≤r≤|s|1≤l≤r≤|s| (where |s||s| is equal to the length of string ss), such that at least one of the symbols sl,sl+1,…,srsl,sl+1,…,sr is equal to "1". For example, if s=s="01010" then f(s)=12f(s)=12, because there are 1212 such pairs (l,r)(l,r): (1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5)(1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5).Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers nn and mm and asked him this problem. For all binary strings ss of length nn which contains exactly mm symbols equal to "1", find the maximum value of f(s)f(s).Mahmoud couldn't solve the problem so he asked you for help. Can you help him? InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1051≤t≤105) — the number of test cases. The description of the test cases follows.The only line for each test case contains two integers nn, mm (1≤n≤1091≤n≤109, 0≤m≤n0≤m≤n) — the length of the string and the number of symbols equal to "1" in it.OutputFor every test case print one integer number — the maximum value of f(s)f(s) over all strings ss of length nn, which has exactly mm symbols, equal to "1".ExampleInputCopy5
3 1
3 2
3 3
4 0
5 2
OutputCopy4
5
6
0
12
NoteIn the first test case; there exists only 33 strings of length 33, which has exactly 11 symbol, equal to "1". These strings are: s1=s1="100", s2=s2="010", s3=s3="001". The values of ff for them are: f(s1)=3,f(s2)=4,f(s3)=3f(s1)=3,f(s2)=4,f(s3)=3, so the maximum value is 44 and the answer is 44.In the second test case, the string ss with the maximum value is "101".In the third test case, the string ss with the maximum value is "111".In the fourth test case, the only string ss of length 44, which has exactly 00 symbols, equal to "1" is "0000" and the value of ff for that string is 00, so the answer is 00.In the fifth test case, the string ss with the maximum value is "01010" and it is described as an example in the problem statement. | [
"binary search",
"combinatorics",
"greedy",
"math",
"strings"
] | import java.io.*;
import java.util.*;
import java.math.BigInteger;
import static java.lang.Math.min;
import static java.lang.Math.max;
import static java.lang.Math.abs;
public class CodeForces {
static int mod=1000000000+7;
static FastScanner in=new FastScanner();
static PrintWriter out=new PrintWriter(System.out);
public static void main(String[] args) {
int T=in.nextInt();
//int T=1;
for (int tt=0; tt<T; tt++) {
//begin
long n=in.nextLong();long m=in.nextLong();
long tot=(n*(n+1))/2;
long zero_pos=m+1;
long first_freqval=(n-m)/zero_pos;long first_freq=(n-m>=zero_pos)?m+1:n-m;
long second_freqval=((n-m)/zero_pos)+1;long second_freq=(n-m)%zero_pos;
first_freq-=second_freq;
long aa=first_freq*(first_freqval*(first_freqval+1))/2;
long bb=second_freq*(( second_freqval)*(second_freqval+1))/2;
p(tot-aa-bb);
//end
}
out.close();
}
static class Pair implements Comparable<Pair>{
int first;int second;
Pair(int first,int second){
this.first=first;
this.second=second;
}
public int compareTo(Pair o) {
return o.second-this.second;
}
}
static boolean isPrime(long n)
{
if(n < 2) return false;
if(n == 2 || n == 3) return true;
if(n%2 == 0 || n%3 == 0) return false;
long sqrtN = (long)Math.sqrt(n)+1;
for(long i = 6L; i <= sqrtN; i += 6) {
if(n%(i-1) == 0 || n%(i+1) == 0) return false;
}
return true;
}
static long gcd(long a, long b)
{
if(a > b)
a = (a+b)-(b=a);
if(a == 0L)
return b;
return gcd(b%a, a);
}
static Pair[] pair(Map<Integer,Integer> map) {
Pair pair[]=new Pair[map.size()];int i=0;
for(int ele:map.keySet()) {
pair[i]=new Pair(ele,map.get(ele));i++;}
Arrays.sort(pair);
return pair;
}
static Map map(int[] ar) {
Map<Integer,Integer> map=new HashMap<>();
for(int i=0;i<ar.length;i++) {
if(map.containsKey(ar[i]))
map.put(ar[i], map.get(ar[i])+1);
else
map.put(ar[i], 1);
}
return map;
}
static void p(int arr[]) {
for(int i=0;i<arr.length;i++)
out.print(arr[i]+" ");
out.println();
}
static<T> void p(T abcd) {
out.println(abcd);
}
static void py() {
out.println("YES");
}
static void pn() {
out.println("NO");
}
static void sort(int[] a) {
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static void sortd(int[] a) {
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l,Comparator.reverseOrder());
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
String nextLine(){
String str = "";
try{
str = br.readLine();
}catch (IOException e){
e.printStackTrace();
}
return str;
}
int nextInt() {
return Integer.parseInt(next());
}
double nextDouble(){
return Double.parseDouble(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
String[] readStringArray(int n) {
String[] a=new String[n];
for (int i=0; i<n; i++) a[i]=next();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
} | java |
1312 | B | B. Bogosorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. Array is good if for each pair of indexes i<ji<j the condition j−aj≠i−aij−aj≠i−ai holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option).For example, if a=[1,1,3,5]a=[1,1,3,5], then shuffled arrays [1,3,5,1][1,3,5,1], [3,5,1,1][3,5,1,1] and [5,3,1,1][5,3,1,1] are good, but shuffled arrays [3,1,5,1][3,1,5,1], [1,1,3,5][1,1,3,5] and [1,1,5,3][1,1,5,3] aren't.It's guaranteed that it's always possible to shuffle an array to meet this condition.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The first line of each test case contains one integer nn (1≤n≤1001≤n≤100) — the length of array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100).OutputFor each test case print the shuffled version of the array aa which is good.ExampleInputCopy3
1
7
4
1 1 3 5
6
3 2 1 5 6 4
OutputCopy7
1 5 1 3
2 4 6 1 3 5
| [
"constructive algorithms",
"sortings"
] | import java.util.*;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
for (int i = 0; i < num; i++) {
int size = scanner.nextInt();
int[] arr = new int[size];
for (int j = 0; j < size; j++) {
arr[j] = scanner.nextInt();
}
Arrays.sort(arr);
printArr(arr);
}
}
void printArr(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[arr.length - 1 - i] + " ");
}
System.out.println();
}
} | java |
1287 | A | A. Angry Studentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's a walking tour day in SIS.Winter; so tt groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P": "A" corresponds to an angry student "P" corresponds to a patient student Such string describes the row from the last to the first student.Every minute every angry student throws a snowball at the next student. Formally, if an angry student corresponds to the character with index ii in the string describing a group then they will throw a snowball at the student that corresponds to the character with index i+1i+1 (students are given from the last to the first student). If the target student was not angry yet, they become angry. Even if the first (the rightmost in the string) student is angry, they don't throw a snowball since there is no one in front of them.Let's look at the first example test. The row initially looks like this: PPAP. Then, after a minute the only single angry student will throw a snowball at the student in front of them, and they also become angry: PPAA. After that, no more students will become angry.Your task is to help SIS.Winter teachers to determine the last moment a student becomes angry for every group.InputThe first line contains a single integer tt — the number of groups of students (1≤t≤1001≤t≤100). The following 2t2t lines contain descriptions of groups of students.The description of the group starts with an integer kiki (1≤ki≤1001≤ki≤100) — the number of students in the group, followed by a string sisi, consisting of kiki letters "A" and "P", which describes the ii-th group of students.OutputFor every group output single integer — the last moment a student becomes angry.ExamplesInputCopy1
4
PPAP
OutputCopy1
InputCopy3
12
APPAPPPAPPPP
3
AAP
3
PPA
OutputCopy4
1
0
NoteIn the first test; after 11 minute the state of students becomes PPAA. After that, no new angry students will appear.In the second tets, state of students in the first group is: after 11 minute — AAPAAPPAAPPP after 22 minutes — AAAAAAPAAAPP after 33 minutes — AAAAAAAAAAAP after 44 minutes all 1212 students are angry In the second group after 11 minute, all students are angry. | [
"greedy",
"implementation"
] | import java.util.Scanner;
public class Main {
static Scanner input = new Scanner(System.in);
public static void main(String[]args) {
method( );
}
public static void method ( ) {
int group = input.nextInt();
while(group!=0) {
int num = input.nextInt();
StringBuilder str = new StringBuilder(input.next());
int count =0;
int numOuter = num;
while(numOuter !=0) {
int round = 0;
for(int i = 0 ; i < str.length()-1; i++) {
if(str.charAt(i)=='A' && str.charAt(i+1)=='P') {
round++;
str.deleteCharAt(i+1);
}
}
if( round!=0 ) {
count++;
}
numOuter--;
}
System.out.println(count);
group--;
}
}
}
| java |
1292 | B | B. Aroma's Searchtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTHE SxPLAY & KIVΛ - 漂流 KIVΛ & Nikki Simmons - PerspectivesWith a new body; our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 00, with their coordinates defined as follows: The coordinates of the 00-th node is (x0,y0)(x0,y0) For i>0i>0, the coordinates of ii-th node is (ax⋅xi−1+bx,ay⋅yi−1+by)(ax⋅xi−1+bx,ay⋅yi−1+by) Initially Aroma stands at the point (xs,ys)(xs,ys). She can stay in OS space for at most tt seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (xs,ys)(xs,ys) to warp home.While within the OS space, Aroma can do the following actions: From the point (x,y)(x,y), Aroma can move to one of the following points: (x−1,y)(x−1,y), (x+1,y)(x+1,y), (x,y−1)(x,y−1) or (x,y+1)(x,y+1). This action requires 11 second. If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 00 seconds. Of course, each data node can be collected at most once. Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within tt seconds?InputThe first line contains integers x0x0, y0y0, axax, ayay, bxbx, byby (1≤x0,y0≤10161≤x0,y0≤1016, 2≤ax,ay≤1002≤ax,ay≤100, 0≤bx,by≤10160≤bx,by≤1016), which define the coordinates of the data nodes.The second line contains integers xsxs, ysys, tt (1≤xs,ys,t≤10161≤xs,ys,t≤1016) – the initial Aroma's coordinates and the amount of time available.OutputPrint a single integer — the maximum number of data nodes Aroma can collect within tt seconds.ExamplesInputCopy1 1 2 3 1 0
2 4 20
OutputCopy3InputCopy1 1 2 3 1 0
15 27 26
OutputCopy2InputCopy1 1 2 3 1 0
2 2 1
OutputCopy0NoteIn all three examples; the coordinates of the first 55 data nodes are (1,1)(1,1), (3,3)(3,3), (7,9)(7,9), (15,27)(15,27) and (31,81)(31,81) (remember that nodes are numbered from 00).In the first example, the optimal route to collect 33 nodes is as follows: Go to the coordinates (3,3)(3,3) and collect the 11-st node. This takes |3−2|+|3−4|=2|3−2|+|3−4|=2 seconds. Go to the coordinates (1,1)(1,1) and collect the 00-th node. This takes |1−3|+|1−3|=4|1−3|+|1−3|=4 seconds. Go to the coordinates (7,9)(7,9) and collect the 22-nd node. This takes |7−1|+|9−1|=14|7−1|+|9−1|=14 seconds. In the second example, the optimal route to collect 22 nodes is as follows: Collect the 33-rd node. This requires no seconds. Go to the coordinates (7,9)(7,9) and collect the 22-th node. This takes |15−7|+|27−9|=26|15−7|+|27−9|=26 seconds. In the third example, Aroma can't collect any nodes. She should have taken proper rest instead of rushing into the OS space like that. | [
"brute force",
"constructive algorithms",
"geometry",
"greedy",
"implementation"
] | import java.io.BufferedOutputStream;
import java.io.Closeable;
import java.io.DataInputStream;
import java.io.Flushable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Objects;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
static class TaskAdapter implements Runnable {
@Override
public void run() {
long startTime = System.currentTimeMillis();
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
Output out = new Output(outputStream);
BAromasSearch solver = new BAromasSearch();
solver.solve(1, in, out);
out.close();
System.err.println(System.currentTimeMillis()-startTime+"ms");
}
}
public static void main(String[] args) throws Exception {
Thread thread = new Thread(null, new TaskAdapter(), "", 1<<28);
thread.start();
thread.join();
}
static class BAromasSearch {
BigInteger sx;
BigInteger sy;
BigInteger ax;
BigInteger ay;
BigInteger bx;
BigInteger by;
BigInteger[] powx;
BigInteger[] powy;
int n;
public BAromasSearch() {
}
private Pair<BigInteger, BigInteger> s(int ind) {
BigInteger tmpx = powx[ind], tmpy = powy[ind];
return new Pair<>(eval(tmpx, sx, bx, tmpx, ax), eval(tmpy, sy, by, tmpy, ay));
}
private BigInteger eval(BigInteger a, BigInteger b, BigInteger c, BigInteger d, BigInteger e) {
return a.multiply(b).add(c.multiply((BigInteger.ONE.subtract(d)).divide(BigInteger.ONE.subtract(e))));
}
private BigInteger dist(Pair<BigInteger, BigInteger> a, BigInteger x, BigInteger y) {
return a.a.subtract(x).abs().add(a.b.subtract(y).abs());
}
private int solve(BigInteger xs, BigInteger xy, BigInteger t, int ind) {
if(t.longValue()<0) {
return 0;
}else if(t.longValue()==0) {
return 1;
}
int ans = 0;
for(int i = 0; i<=ind; i++) {
BigInteger dist;
dist = dist(s(i), xs, xy);
if(dist.compareTo(t)>0) {
continue;
}
ans = Math.max(ans, ind-i+1);
BigInteger tt = t.subtract(dist.multiply(BigInteger.TEN));
if(tt.compareTo(BigInteger.ZERO)>0) {
int cnt = ind-i+1;
for(int j = i+1; j<=n; j++) {
if(dist(s(j), xs, xy).compareTo(tt)>0) {
cnt += j-ind-1;
break;
}
if(j==n) {
cnt += n-ind-1;
}
}
ans = Math.max(ans, cnt);
}
}
for(int i = ind; i<=n; i++) {
BigInteger dist;
dist = dist(s(i), xs, xy);
if(dist.compareTo(t)>0) {
continue;
}
ans = Math.max(ans, i-ind+1);
BigInteger tt = t.subtract(dist.multiply(BigInteger.TEN));
if(tt.compareTo(BigInteger.ZERO)>0) {
int cnt = i-ind+1;
for(int j = ind-1; j>=0; j--) {
if(dist(s(j), xs, xy).compareTo(tt)>0) {
cnt += j-ind-1;
break;
}
if(j==0) {
cnt += ind-1;
}
}
ans = Math.max(ans, cnt);
}
}
return ans;
}
public void solve(int kase, InputReader in, Output pw) {
sx = BigInteger.valueOf(in.nextLong());
sy = BigInteger.valueOf(in.nextLong());
ax = BigInteger.valueOf(in.nextLong());
ay = BigInteger.valueOf(in.nextLong());
bx = BigInteger.valueOf(in.nextLong());
by = BigInteger.valueOf(in.nextLong());
BigInteger xs = BigInteger.valueOf(in.nextLong()), ys = BigInteger.valueOf(in.nextLong()), t = BigInteger.valueOf(in.nextLong());
n = 55;
Utilities.Debug.dbg(n);
powx = new BigInteger[n+1];
powy = new BigInteger[n+1];
powx[0] = powy[0] = BigInteger.ONE;
for(int i = 1; i<=n; i++) {
powx[i] = powx[i-1].multiply(ax);
powy[i] = powy[i-1].multiply(ay);
}
int ans = 0;
for(int i = 0; i<=n; i++) {
var v = s(i);
ans = Math.max(ans, solve(v.a, v.b, t.subtract(dist(v, xs, ys)), i));
Utilities.Debug.dbg(i, ans);
}
pw.println(ans);
}
}
static class Output implements Closeable, Flushable {
public StringBuilder sb;
public OutputStream os;
public int BUFFER_SIZE;
public String lineSeparator;
public Output(OutputStream os) {
this(os, 1<<16);
}
public Output(OutputStream os, int bs) {
BUFFER_SIZE = bs;
sb = new StringBuilder(BUFFER_SIZE);
this.os = new BufferedOutputStream(os, 1<<17);
lineSeparator = System.lineSeparator();
}
public void println(int i) {
println(String.valueOf(i));
}
public void println(String s) {
sb.append(s);
println();
}
public void println() {
sb.append(lineSeparator);
}
private void flushToBuffer() {
try {
os.write(sb.toString().getBytes());
}catch(IOException e) {
e.printStackTrace();
}
sb = new StringBuilder(BUFFER_SIZE);
}
public void flush() {
try {
flushToBuffer();
os.flush();
}catch(IOException e) {
e.printStackTrace();
}
}
public void close() {
flush();
try {
os.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
static class Pair<T1, T2> implements Comparable<Pair<T1, T2>> {
public T1 a;
public T2 b;
public Pair(Pair<T1, T2> p) {
this(p.a, p.b);
}
public Pair(T1 a, T2 b) {
this.a = a;
this.b = b;
}
public String toString() {
return a+" "+b;
}
public int hashCode() {
return Objects.hash(a, b);
}
public boolean equals(Object o) {
if(o instanceof Pair) {
Pair p = (Pair) o;
return a.equals(p.a)&&b.equals(p.b);
}
return false;
}
public int compareTo(Pair<T1, T2> p) {
int cmp = ((Comparable<T1>) a).compareTo(p.a);
if(cmp==0) {
return ((Comparable<T2>) b).compareTo(p.b);
}
return cmp;
}
}
static interface InputReader {
long nextLong();
}
static class FastReader implements InputReader {
final private int BUFFER_SIZE = 1<<16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer;
private int bytesRead;
public FastReader(InputStream is) {
din = new DataInputStream(is);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public long nextLong() {
long ret = 0;
byte c = skipToDigit();
boolean neg = (c=='-');
if(neg) {
c = read();
}
do {
ret = ret*10+c-'0';
} while((c = read())>='0'&&c<='9');
if(neg) {
return -ret;
}
return ret;
}
private boolean isDigit(byte b) {
return b>='0'&&b<='9';
}
private byte skipToDigit() {
byte ret;
while(!isDigit(ret = read())&&ret!='-') ;
return ret;
}
private void fillBuffer() {
try {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
}catch(IOException e) {
e.printStackTrace();
throw new InputMismatchException();
}
if(bytesRead==-1) {
buffer[0] = -1;
}
}
private byte read() {
if(bytesRead==-1) {
throw new InputMismatchException();
}else if(bufferPointer==bytesRead) {
fillBuffer();
}
return buffer[bufferPointer++];
}
}
static class Utilities {
public static class Debug {
public static final boolean LOCAL = System.getProperty("ONLINE_JUDGE")==null;
private static <T> String ts(T t) {
if(t==null) {
return "null";
}
try {
return ts((Iterable) t);
}catch(ClassCastException e) {
if(t instanceof int[]) {
String s = Arrays.toString((int[]) t);
return "{"+s.substring(1, s.length()-1)+"}";
}else if(t instanceof long[]) {
String s = Arrays.toString((long[]) t);
return "{"+s.substring(1, s.length()-1)+"}";
}else if(t instanceof char[]) {
String s = Arrays.toString((char[]) t);
return "{"+s.substring(1, s.length()-1)+"}";
}else if(t instanceof double[]) {
String s = Arrays.toString((double[]) t);
return "{"+s.substring(1, s.length()-1)+"}";
}else if(t instanceof boolean[]) {
String s = Arrays.toString((boolean[]) t);
return "{"+s.substring(1, s.length()-1)+"}";
}
try {
return ts((Object[]) t);
}catch(ClassCastException e1) {
return t.toString();
}
}
}
private static <T> String ts(T[] arr) {
StringBuilder ret = new StringBuilder();
ret.append("{");
boolean first = true;
for(T t: arr) {
if(!first) {
ret.append(", ");
}
first = false;
ret.append(ts(t));
}
ret.append("}");
return ret.toString();
}
private static <T> String ts(Iterable<T> iter) {
StringBuilder ret = new StringBuilder();
ret.append("{");
boolean first = true;
for(T t: iter) {
if(!first) {
ret.append(", ");
}
first = false;
ret.append(ts(t));
}
ret.append("}");
return ret.toString();
}
public static void dbg(Object... o) {
if(LOCAL) {
System.err.print("Line #"+Thread.currentThread().getStackTrace()[2].getLineNumber()+": [");
for(int i = 0; i<o.length; i++) {
if(i!=0) {
System.err.print(", ");
}
System.err.print(ts(o[i]));
}
System.err.println("]");
}
}
}
}
}
| java |
1320 | B | B. Navigation Systemtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe map of Bertown can be represented as a set of nn intersections, numbered from 11 to nn and connected by mm one-way roads. It is possible to move along the roads from any intersection to any other intersection. The length of some path from one intersection to another is the number of roads that one has to traverse along the path. The shortest path from one intersection vv to another intersection uu is the path that starts in vv, ends in uu and has the minimum length among all such paths.Polycarp lives near the intersection ss and works in a building near the intersection tt. Every day he gets from ss to tt by car. Today he has chosen the following path to his workplace: p1p1, p2p2, ..., pkpk, where p1=sp1=s, pk=tpk=t, and all other elements of this sequence are the intermediate intersections, listed in the order Polycarp arrived at them. Polycarp never arrived at the same intersection twice, so all elements of this sequence are pairwise distinct. Note that you know Polycarp's path beforehand (it is fixed), and it is not necessarily one of the shortest paths from ss to tt.Polycarp's car has a complex navigation system installed in it. Let's describe how it works. When Polycarp starts his journey at the intersection ss, the system chooses some shortest path from ss to tt and shows it to Polycarp. Let's denote the next intersection in the chosen path as vv. If Polycarp chooses to drive along the road from ss to vv, then the navigator shows him the same shortest path (obviously, starting from vv as soon as he arrives at this intersection). However, if Polycarp chooses to drive to another intersection ww instead, the navigator rebuilds the path: as soon as Polycarp arrives at ww, the navigation system chooses some shortest path from ww to tt and shows it to Polycarp. The same process continues until Polycarp arrives at tt: if Polycarp moves along the road recommended by the system, it maintains the shortest path it has already built; but if Polycarp chooses some other path, the system rebuilds the path by the same rules.Here is an example. Suppose the map of Bertown looks as follows, and Polycarp drives along the path [1,2,3,4][1,2,3,4] (s=1s=1, t=4t=4): Check the picture by the link http://tk.codeforces.com/a.png When Polycarp starts at 11, the system chooses some shortest path from 11 to 44. There is only one such path, it is [1,5,4][1,5,4]; Polycarp chooses to drive to 22, which is not along the path chosen by the system. When Polycarp arrives at 22, the navigator rebuilds the path by choosing some shortest path from 22 to 44, for example, [2,6,4][2,6,4] (note that it could choose [2,3,4][2,3,4]); Polycarp chooses to drive to 33, which is not along the path chosen by the system. When Polycarp arrives at 33, the navigator rebuilds the path by choosing the only shortest path from 33 to 44, which is [3,4][3,4]; Polycarp arrives at 44 along the road chosen by the navigator, so the system does not have to rebuild anything. Overall, we get 22 rebuilds in this scenario. Note that if the system chose [2,3,4][2,3,4] instead of [2,6,4][2,6,4] during the second step, there would be only 11 rebuild (since Polycarp goes along the path, so the system maintains the path [3,4][3,4] during the third step).The example shows us that the number of rebuilds can differ even if the map of Bertown and the path chosen by Polycarp stays the same. Given this information (the map and Polycarp's path), can you determine the minimum and the maximum number of rebuilds that could have happened during the journey?InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105) — the number of intersections and one-way roads in Bertown, respectively.Then mm lines follow, each describing a road. Each line contains two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) denoting a road from intersection uu to intersection vv. All roads in Bertown are pairwise distinct, which means that each ordered pair (u,v)(u,v) appears at most once in these mm lines (but if there is a road (u,v)(u,v), the road (v,u)(v,u) can also appear).The following line contains one integer kk (2≤k≤n2≤k≤n) — the number of intersections in Polycarp's path from home to his workplace.The last line contains kk integers p1p1, p2p2, ..., pkpk (1≤pi≤n1≤pi≤n, all these integers are pairwise distinct) — the intersections along Polycarp's path in the order he arrived at them. p1p1 is the intersection where Polycarp lives (s=p1s=p1), and pkpk is the intersection where Polycarp's workplace is situated (t=pkt=pk). It is guaranteed that for every i∈[1,k−1]i∈[1,k−1] the road from pipi to pi+1pi+1 exists, so the path goes along the roads of Bertown. OutputPrint two integers: the minimum and the maximum number of rebuilds that could have happened during the journey.ExamplesInputCopy6 9
1 5
5 4
1 2
2 3
3 4
4 1
2 6
6 4
4 2
4
1 2 3 4
OutputCopy1 2
InputCopy7 7
1 2
2 3
3 4
4 5
5 6
6 7
7 1
7
1 2 3 4 5 6 7
OutputCopy0 0
InputCopy8 13
8 7
8 6
7 5
7 4
6 5
6 4
5 3
5 2
4 3
4 2
3 1
2 1
1 8
5
8 7 5 2 1
OutputCopy0 3
| [
"dfs and similar",
"graphs",
"shortest paths"
] |
import java.util.*;
import javax.print.DocFlavor.INPUT_STREAM;
import java.io.*;
import java.math.*;
import java.sql.Array;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;
public class Main {
private static class MyScanner {
private static final int BUF_SIZE = 2048;
BufferedReader br;
private MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
private boolean isSpace(char c) {
return c == '\n' || c == '\r' || c == ' ';
}
String next() {
try {
StringBuilder sb = new StringBuilder();
int r;
while ((r = br.read()) != -1 && isSpace((char)r));
if (r == -1) {
return null;
}
sb.append((char) r);
while ((r = br.read()) != -1 && !isSpace((char)r)) {
sb.append((char)r);
}
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
static class Reader{
BufferedReader br;
StringTokenizer st;
public Reader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
static long mod = (long)(1e9 + 7);
static void sort(long[] arr ) {
ArrayList<Long> al = new ArrayList<>();
for(long e:arr) al.add(e);
Collections.sort(al);
for(int i = 0 ; i<al.size(); i++) arr[i] = al.get(i);
}
static void sort(int[] arr ) {
ArrayList<Integer> al = new ArrayList<>();
for(int e:arr) al.add(e);
Collections.sort(al);
for(int i = 0 ; i<al.size(); i++) arr[i] = al.get(i);
}
static void sort(char[] arr) {
ArrayList<Character> al = new ArrayList<Character>();
for(char cc:arr) al.add(cc);
Collections.sort(al);
for(int i = 0 ;i<arr.length ;i++) arr[i] = al.get(i);
}
static long mod_mul( long... a) {
long ans = a[0]%mod;
for(int i = 1 ; i<a.length ; i++) {
ans = (ans * (a[i]%mod))%mod;
}
return ans;
}
static long mod_sum( long... a) {
long ans = 0;
for(long e:a) {
ans = (ans + e)%mod;
}
return ans;
}
static long gcd(long a, long b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static void print(long[] arr) {
System.out.println("---print---");
for(long e:arr) System.out.print(e+" ");
System.out.println("-----------");
}
static void print(int[] arr) {
System.out.println("---print---");
for(long e:arr) System.out.print(e+" ");
System.out.println("-----------");
}
static boolean[] prime(int num) {
boolean[] bool = new boolean[num];
for (int i = 0; i< bool.length; i++) {
bool[i] = true;
}
for (int i = 2; i< Math.sqrt(num); i++) {
if(bool[i] == true) {
for(int j = (i*i); j<num; j = j+i) {
bool[j] = false;
}
}
}
if(num >= 0) {
bool[0] = false;
bool[1] = false;
}
return bool;
}
static long modInverse(long a, long m)
{
long g = gcd(a, m);
return power(a, m - 2);
}
static long lcm(long a , long b) {
return (a*b)/gcd(a, b);
}
static int lcm(int a , int b) {
return (int)((a*b)/gcd(a, b));
}
static long power(long x, long y){
if(y<0) return 0;
long m = mod;
if (y == 0) return 1; long p = power(x, y / 2) % m; p = (int)((p * (long)p) % m);
if (y % 2 == 0) return p; else return (int)((x * (long)p) % m); }
static class Combinations{
private long[] z; // factorial
private long[] z1; // inverse factorial
private long[] z2; // incerse number
private long mod;
public Combinations(long N , long mod) {
this.mod = mod;
z = new long[(int)N+1];
z1 = new long[(int)N+1];
z[0] = 1;
for(int i =1 ; i<=N ; i++) z[i] = (z[i-1]*i)%mod;
z2 = new long[(int)N+1];
z2[0] = z2[1] = 1;
for (int i = 2; i <= N; i++)
z2[i] = z2[(int)(mod % i)] * (mod - mod / i) % mod;
z1[0] = z1[1] = 1;
for (int i = 2; i <= N; i++)
z1[i] = (z2[i] * z1[i - 1]) % mod;
}
long fac(long n) {
return z[(int)n];
}
long invrsNum(long n) {
return z2[(int)n];
}
long invrsFac(long n) {
return z1[(int)n];
}
long ncr(long N, long R)
{ if(R<0 || R>N ) return 0;
long ans = ((z[(int)N] * z1[(int)R])
% mod * z1[(int)(N - R)])
% mod;
return ans;
}
}
static class DisjointUnionSets {
int[] rank, parent;
int n;
public DisjointUnionSets(int n)
{
rank = new int[n];
parent = new int[n];
this.n = n;
makeSet();
}
void makeSet()
{
for (int i = 0; i < n; i++) {
parent[i] = i;
}
}
int find(int x)
{
if (parent[x] != x) {
parent[x] = find(parent[x]);
}
return parent[x];
}
void union(int x, int y)
{
int xRoot = find(x), yRoot = find(y);
if (xRoot == yRoot)
return;
if (rank[xRoot] < rank[yRoot])
parent[xRoot] = yRoot;
else if (rank[yRoot] < rank[xRoot])
parent[yRoot] = xRoot;
else
{
parent[yRoot] = xRoot;
rank[xRoot] = rank[xRoot] + 1;
}
}
}
static int max(int... a ) {
int max = a[0];
for(int e:a) max = Math.max(max, e);
return max;
}
static long max(long... a ) {
long max = a[0];
for(long e:a) max = Math.max(max, e);
return max;
}
static int min(int... a ) {
int min = a[0];
for(int e:a) min = Math.min(e, min);
return min;
}
static long min(long... a ) {
long min = a[0];
for(long e:a) min = Math.min(e, min);
return min;
}
static int[] KMP(String str) {
int n = str.length();
int[] kmp = new int[n];
for(int i = 1 ; i<n ; i++) {
int j = kmp[i-1];
while(j>0 && str.charAt(i) != str.charAt(j)) {
j = kmp[j-1];
}
if(str.charAt(i) == str.charAt(j)) j++;
kmp[i] = j;
}
return kmp;
}
/************************************************ Query **************************************************************************************/
/***************************************** Sparse Table ********************************************************/
static class SparseTable{
private long[][] st;
SparseTable(long[] arr){
int n = arr.length;
st = new long[n][25];
log = new int[n+2];
build_log(n+1);
build(arr);
}
private void build(long[] arr) {
int n = arr.length;
for(int i = n-1 ; i>=0 ; i--) {
for(int j = 0 ; j<25 ; j++) {
int r = i + (1<<j)-1;
if(r>=n) break;
if(j == 0 ) st[i][j] = arr[i];
else st[i][j] = Math.min(st[i][j-1] , st[ i + ( 1 << (j-1) ) ][ j-1 ] );
}
}
}
public long gcd(long a ,long b) {
if(a == 0) return b;
return gcd(b%a , a);
}
public long query(int l ,int r) {
int w = r-l+1;
int power = log[w];
return Math.min(st[l][power],st[r - (1<<power) + 1][power]);
}
private int[] log;
void build_log(int n) {
log[1] = 0;
for(int i = 2 ; i<=n ; i++) {
log[i] = 1 + log[i/2];
}
}
}
/******************************************************** Segement Tree *****************************************************/
static class SegmentTree{
long[] tree;
long[] arr;
int n;
SegmentTree(long[] arr){
this.n = arr.length;
tree = new long[4*n+1];
this.arr = arr;
buildTree(0, n-1, 1);
}
void buildTree(int s ,int e ,int index ) {
if(s == e) {
tree[index] = arr[s];
return;
}
int mid = (s+e)/2;
buildTree( s, mid, 2*index);
buildTree( mid+1, e, 2*index+1);
tree[index] = gcd(tree[2*index] , tree[2*index+1]);
}
long query(int si ,int ei) {
return query(0 ,n-1 , si ,ei , 1 );
}
private long query( int ss ,int se ,int qs , int qe,int index) {
if(ss>=qs && se<=qe) return tree[index];
if(qe<ss || se<qs) return (long)(0);
int mid = (ss + se)/2;
long left = query( ss , mid , qs ,qe , 2*index);
long right= query(mid + 1 , se , qs ,qe , 2*index+1);
return gcd(left, right);
}
public void update(int index , int val) {
arr[index] = val;
// for(long e:arr) System.out.print(e+" ");
update(index , 0 , n-1 , 1);
}
private void update(int id ,int si , int ei , int index) {
if(id < si || id>ei) return;
if(si == ei ) {
tree[index] = arr[id];
return;
}
if(si > ei) return;
int mid = (ei + si)/2;
update( id, si, mid , 2*index);
update( id , mid+1, ei , 2*index+1);
tree[index] = Math.min(tree[2*index] ,tree[2*index+1]);
}
}
/* ***************************************************************************************************************************************************/
// static MyScanner sc = new MyScanner(); // only in case of less memory
static Reader sc = new Reader();
static int TC;
static StringBuilder sb = new StringBuilder();
static PrintWriter out=new PrintWriter(System.out);
public static void main(String args[]) throws IOException {
int tc = 1;
// tc = sc.nextInt();
TC = 0;
for(int i = 1 ; i<=tc ; i++) {
TC++;
// sb.append("Case #" + i + ": " ); // During KickStart && HackerCup
TEST_CASE();
}
System.out.print(sb);
}
static class Pair {
String name;
int roles ;
Map<String , Integer> skill;
Pair(String name ,int roles ){
this.name = name;
this.roles = roles;
skill = new HashMap<>();
}
}
static class Pro implements Comparable<Pro>{
String name;
int d , s , b , c;
ArrayList<String> skill;
ArrayList<Integer> level;
Pro(String name , int d, int s , int b ,int c,ArrayList<String > skill ,ArrayList<Integer> level ){
this.name = name;
this.d = d;
this.s = s;
this.b = b;
this.c = c;
this.skill = skill;
this.level = level;
}
public int compareTo(Pro o) {
return -Integer.compare(this.s, o.s);
}
}
static ArrayList<ArrayList<Integer>> adj;
static int[] bfs(int n ,int s) {
int[] ans = new int[n];
boolean[] visit = new boolean[n];
LinkedList<int[]> ll = new LinkedList<>();
// f == x , s == d
ll.add(new int[] {s , 0});
while(!ll.isEmpty()) {
int[] pp = ll.removeFirst();
if(visit[pp[0]]) continue;
visit[pp[0]] = true;
ans[pp[0]] = pp[1];
for(int v:adj.get(pp[0])) {
if(visit[v]) continue;
ll.addLast(new int[] {v , pp[1]+1});
}
}
return ans;
}
static void TEST_CASE() throws IOException {
int n = sc.nextInt();
int m = sc.nextInt();
adj = new ArrayList<>();
graph = new ArrayList<>();
for(int i = 0 ; i<n ;i ++) {
graph.add(new ArrayList<>());
adj.add(new ArrayList<>());
}
for(int i = 0 ;i<m ; i++) {
int v = sc.nextInt()-1 , u = sc.nextInt()-1;
adj.get(u).add(v);
graph.get(v).add(u);
}
int k = sc.nextInt();
int[] arr = new int[k];
for(int i = 0 ;i<k ; i++) {
arr[i] = sc.nextInt()-1;
}
int[] bfs = bfs(n, arr[k-1]);
adj = graph;
// System.out.println(adj);
int[] ans = dfs(arr, 0, bfs, 0, 0);
System.out.println(ans[0]+" "+ans[1]);
}
static ArrayList<ArrayList<Integer>> graph;
static int[] dfs(int[] arr , int i , int[] bfs ,int min ,int max) {
if(i == arr.length-1) {
return new int[] {min , max};
}
int u1 = arr[i];
int u2 = arr[i+1];
int[] ans;
int m = Integer.MAX_VALUE;
for(int v:adj.get(u1)) m = min(m ,bfs[v] );
int t = 0;
for(int v:adj.get(u1)) if(bfs[v] == m) t++;
int minAdd = 0 , maxAdd = 0;
if(bfs[u2] != m) {
maxAdd = 1;
minAdd = 1;
}else {
if(t>1) maxAdd = 1;
}
ans = dfs(arr, i+1, bfs, minAdd + min, maxAdd+max);
return ans;
}
}
/*******************************************************************************************************************************************************/
/**
*/
| java |
1303 | C | C. Perfect Keyboardtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp wants to assemble his own keyboard. Layouts with multiple rows are too complicated for him — his keyboard will consist of only one row; where all 2626 lowercase Latin letters will be arranged in some order.Polycarp uses the same password ss on all websites where he is registered (it is bad, but he doesn't care). He wants to assemble a keyboard that will allow to type this password very easily. He doesn't like to move his fingers while typing the password, so, for each pair of adjacent characters in ss, they should be adjacent on the keyboard. For example, if the password is abacaba, then the layout cabdefghi... is perfect, since characters a and c are adjacent on the keyboard, and a and b are adjacent on the keyboard. It is guaranteed that there are no two adjacent equal characters in ss, so, for example, the password cannot be password (two characters s are adjacent).Can you help Polycarp with choosing the perfect layout of the keyboard, if it is possible?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases.Then TT lines follow, each containing one string ss (1≤|s|≤2001≤|s|≤200) representing the test case. ss consists of lowercase Latin letters only. There are no two adjacent equal characters in ss.OutputFor each test case, do the following: if it is impossible to assemble a perfect keyboard, print NO (in upper case, it matters in this problem); otherwise, print YES (in upper case), and then a string consisting of 2626 lowercase Latin letters — the perfect layout. Each Latin letter should appear in this string exactly once. If there are multiple answers, print any of them. ExampleInputCopy5
ababa
codedoca
abcda
zxzytyz
abcdefghijklmnopqrstuvwxyza
OutputCopyYES
bacdefghijklmnopqrstuvwxyz
YES
edocabfghijklmnpqrstuvwxyz
NO
YES
xzytabcdefghijklmnopqrsuvw
NO
| [
"dfs and similar",
"greedy",
"implementation"
] | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class PerfectKeyboard {
public static void main(String[] args) {
MyScanner scanner = new MyScanner();
int input = Integer.parseInt(scanner.nextLine());
for(int i=0; i<input; i++){
String str = scanner.nextLine();
Map<Character, Set<Character>> map = new HashMap<>();
for(int j=0; j<str.length()-1; j++){
if(!map.containsKey(str.charAt(j))){
map.put(str.charAt(j),new HashSet<>());
}
if(!map.containsKey(str.charAt(j+1))){
map.put(str.charAt(j+1),new HashSet<>());
}
map.get(str.charAt(j)).add(str.charAt(j+1));
map.get(str.charAt(j+1)).add(str.charAt(j));
}
helper2(map,str);
}
}
public static void helper2(Map<Character, Set<Character>> map,String str){
int count = 0;
for(Set<Character> set:map.values()){
if(set.size()>2) {
System.out.println("NO");
return;
} else if (set.size() == 1) {
count++;
}
}
if(count<2 && str.length()>1){
System.out.println("NO");
return;
}
boolean[] visited = new boolean[26];
StringBuilder sb = new StringBuilder();
for(char j='a'; j<='z'; j++){
if(!visited[j-'a'] && map.getOrDefault(j,new HashSet<>()).size()==1){
if(!helper(j,map,visited,sb)){
System.out.println("NO");
return;
}
}
}
for(char j='a'; j<='z'; j++){
if(!visited[j-'a'])sb.append(j);
}
System.out.println("YES");
System.out.println(sb);
}
public static boolean helper(char curr,Map<Character, Set<Character>> map,boolean[] visited,StringBuilder sb ){
visited[curr-'a']=true;
sb.append(curr);
for(char letter:map.get(curr)){
if(!visited[letter-'a']){
helper(letter,map,visited,sb);
}
}
return true;
}
}
class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
| java |
1301 | B | B. Motarack's Birthdaytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array aa of nn non-negative integers.Dark created that array 10001000 years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer kk (0≤k≤1090≤k≤109) and replaces all missing elements in the array aa with kk.Let mm be the maximum absolute difference between all adjacent elements (i.e. the maximum value of |ai−ai+1||ai−ai+1| for all 1≤i≤n−11≤i≤n−1) in the array aa after Dark replaces all missing elements with kk.Dark should choose an integer kk so that mm is minimized. Can you help him?InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1041≤t≤104) — the number of test cases. The description of the test cases follows.The first line of each test case contains one integer nn (2≤n≤1052≤n≤105) — the size of the array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−1≤ai≤109−1≤ai≤109). If ai=−1ai=−1, then the ii-th integer is missing. It is guaranteed that at least one integer is missing in every test case.It is guaranteed, that the sum of nn for all test cases does not exceed 4⋅1054⋅105.OutputPrint the answers for each test case in the following format:You should print two integers, the minimum possible value of mm and an integer kk (0≤k≤1090≤k≤109) that makes the maximum absolute difference between adjacent elements in the array aa equal to mm.Make sure that after replacing all the missing elements with kk, the maximum absolute difference between adjacent elements becomes mm.If there is more than one possible kk, you can print any of them.ExampleInputCopy7
5
-1 10 -1 12 -1
5
-1 40 35 -1 35
6
-1 -1 9 -1 3 -1
2
-1 -1
2
0 -1
4
1 -1 3 -1
7
1 -1 7 5 2 -1 5
OutputCopy1 11
5 35
3 6
0 42
0 0
1 2
3 4
NoteIn the first test case after replacing all missing elements with 1111 the array becomes [11,10,11,12,11][11,10,11,12,11]. The absolute difference between any adjacent elements is 11. It is impossible to choose a value of kk, such that the absolute difference between any adjacent element will be ≤0≤0. So, the answer is 11.In the third test case after replacing all missing elements with 66 the array becomes [6,6,9,6,3,6][6,6,9,6,3,6]. |a1−a2|=|6−6|=0|a1−a2|=|6−6|=0; |a2−a3|=|6−9|=3|a2−a3|=|6−9|=3; |a3−a4|=|9−6|=3|a3−a4|=|9−6|=3; |a4−a5|=|6−3|=3|a4−a5|=|6−3|=3; |a5−a6|=|3−6|=3|a5−a6|=|3−6|=3. So, the maximum difference between any adjacent elements is 33. | [
"binary search",
"greedy",
"ternary search"
] | import java.util.*;
import java.io.*;
public class Practice {
static boolean multipleTC = true;
final static int mod = 1000000007;
final static int mod2 = 998244353;
final double E = 2.7182818284590452354;
final double PI = 3.14159265358979323846;
int MAX = 10000005;
void pre() throws Exception {
}
// All the best
void solve(int TC) throws Exception {
int n = ni();
long arr[] = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = ni();
}
boolean missing[] = new boolean[n];
for (int i = 0; i < n; i++)
if (arr[i] < 0)
missing[i] = true;
TreeSet<Long> set = new TreeSet<>();
for (int i = 0; i < n; i++) {
if (missing[i]) {
if (i > 0 && arr[i - 1] >= 0) {
set.add(arr[i - 1]);
}
if (i + 1 < n && arr[i + 1] >= 0)
set.add(arr[i + 1]);
}
}
if (set.size() == 0) {
pn("0 1");
return;
}
long x = ((set.first() + set.last()) / 2);
for (int k = 0; k < n; k++) {
if (missing[k]) {
arr[k] = x;
}
}
long cur = 0;
for (int k = 1; k < n; k++) {
cur = max(cur, abs(arr[k] - arr[k - 1]));
}
pn(cur + " " + x);
}
void leftRotatebyOne(int arr[], int n) {
int temp = arr[0], i;
for (i = 0; i < n - 1; i++)
arr[i] = arr[i + 1];
arr[n - 1] = temp;
}
boolean isFibo(int arr[]) {
int n = arr.length;
for (int i = 0; i + 2 < n; i++) {
if (arr[i] + arr[i + 1] == arr[i + 2]) {
return true;
}
}
return false;
}
public void permute(int[] arr) {
permuteHelper(arr, 0);
}
ArrayList<int[]> perm = new ArrayList<>();
private void permuteHelper(int[] arr, int index) {
if (index >= arr.length - 1) {
perm.add(arr.clone());
return;
}
if (perm.size() > 3 * arr.length) {
return;
}
for (int i = index; i < arr.length; i++) {
int t = arr[index];
arr[index] = arr[i];
arr[i] = t;
permuteHelper(arr, index + 1);
t = arr[index];
arr[index] = arr[i];
arr[i] = t;
}
}
int[] readArr(int n) throws Exception {
int arr[] = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = ni();
}
return arr;
}
void sort(int arr[], int left, int right) {
ArrayList<Integer> list = new ArrayList<>();
for (int i = left; i <= right; i++)
list.add(arr[i]);
Collections.sort(list);
for (int i = left; i <= right; i++)
arr[i] = list.get(i - left);
}
void sort(int arr[]) {
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < arr.length; i++)
list.add(arr[i]);
Collections.sort(list);
for (int i = 0; i < arr.length; i++)
arr[i] = list.get(i);
}
public long max(long... arr) {
long max = arr[0];
for (long itr : arr)
max = Math.max(max, itr);
return max;
}
public int max(int... arr) {
int max = arr[0];
for (int itr : arr)
max = Math.max(max, itr);
return max;
}
public long min(long... arr) {
long min = arr[0];
for (long itr : arr)
min = Math.min(min, itr);
return min;
}
public int min(int... arr) {
int min = arr[0];
for (int itr : arr)
min = Math.min(min, itr);
return min;
}
public long sum(long... arr) {
long sum = 0;
for (long itr : arr)
sum += itr;
return sum;
}
public long sum(int... arr) {
long sum = 0;
for (int itr : arr)
sum += itr;
return sum;
}
String bin(long n) {
return Long.toBinaryString(n);
}
String bin(int n) {
return Integer.toBinaryString(n);
}
static int bitCount(int x) {
return x == 0 ? 0 : (1 + bitCount(x & (x - 1)));
}
static void dbg(Object... o) {
System.err.println(Arrays.deepToString(o));
}
int bit(long n) {
return (n == 0) ? 0 : (1 + bit(n & (n - 1)));
}
int abs(int a) {
return (a < 0) ? -a : a;
}
long abs(long a) {
return (a < 0) ? -a : a;
}
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());
}
public static void main(String[] args) throws Exception {
new Practice().run();
}
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();
}
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 |
1291 | A | A. Even But Not Eventime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a number ebne (even but not even) if and only if its sum of digits is divisible by 22 but the number itself is not divisible by 22. For example, 1313, 12271227, 185217185217 are ebne numbers, while 1212, 22, 177013177013, 265918265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clarification.You are given a non-negative integer ss, consisting of nn digits. You can delete some digits (they are not necessary consecutive/successive) to make the given number ebne. You cannot change the order of the digits, that is, after deleting the digits the remaining digits collapse. The resulting number shouldn't contain leading zeros. You can delete any number of digits between 00 (do not delete any digits at all) and n−1n−1.For example, if you are given s=s=222373204424185217171912 then one of possible ways to make it ebne is: 222373204424185217171912 →→ 2237344218521717191. The sum of digits of 2237344218521717191 is equal to 7070 and is divisible by 22, but number itself is not divisible by 22: it means that the resulting number is ebne.Find any resulting number that is ebne. If it's impossible to create an ebne number from the given number report about it.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤30001≤n≤3000) — the number of digits in the original number.The second line of each test case contains a non-negative integer number ss, consisting of nn digits.It is guaranteed that ss does not contain leading zeros and the sum of nn over all test cases does not exceed 30003000.OutputFor each test case given in the input print the answer in the following format: If it is impossible to create an ebne number, print "-1" (without quotes); Otherwise, print the resulting number after deleting some, possibly zero, but not all digits. This number should be ebne. If there are multiple answers, you can print any of them. Note that answers with leading zeros or empty strings are not accepted. It's not necessary to minimize or maximize the number of deleted digits.ExampleInputCopy4
4
1227
1
0
6
177013
24
222373204424185217171912
OutputCopy1227
-1
17703
2237344218521717191
NoteIn the first test case of the example; 12271227 is already an ebne number (as 1+2+2+7=121+2+2+7=12, 1212 is divisible by 22, while in the same time, 12271227 is not divisible by 22) so we don't need to delete any digits. Answers such as 127127 and 1717 will also be accepted.In the second test case of the example, it is clearly impossible to create an ebne number from the given number.In the third test case of the example, there are many ebne numbers we can obtain by deleting, for example, 11 digit such as 1770317703, 7701377013 or 1701317013. Answers such as 17011701 or 770770 will not be accepted as they are not ebne numbers. Answer 013013 will not be accepted as it contains leading zeroes.Explanation: 1+7+7+0+3=181+7+7+0+3=18. As 1818 is divisible by 22 while 1770317703 is not divisible by 22, we can see that 1770317703 is an ebne number. Same with 7701377013 and 1701317013; 1+7+0+1=91+7+0+1=9. Because 99 is not divisible by 22, 17011701 is not an ebne number; 7+7+0=147+7+0=14. This time, 1414 is divisible by 22 but 770770 is also divisible by 22, therefore, 770770 is not an ebne number.In the last test case of the example, one of many other possible answers is given. Another possible answer is: 222373204424185217171912 →→ 22237320442418521717191 (delete the last digit). | [
"greedy",
"math",
"strings"
] | import java.util.*;
public class Main{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-->0){
int n = sc.nextInt();
String str = sc.next();
System.out.println(ebne(str,n));
}
}
public static String ebne(String str,int n){
int last = str.charAt(n-1) - '0';
int i;
if(last%2==0){
for( i=n-1;i>=0;i--){
if((str.charAt(i)-'0')%2!=0)
break;
}
if(i==-1)
return "-1";
else
str = str.substring(0,i+1);
}
int sum=0;
n = str.length();
for(i=n-1;i>=0;i--){
sum+= str.charAt(i)-'0';
if(sum%2==0){
return str.substring(i,n);
}
}
return "-1";
}
} | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.