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 |
---|---|---|---|---|---|
1322 | B | B. Presenttime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputCatherine received an array of integers as a gift for March 8. Eventually she grew bored with it; and she started calculated various useless characteristics for it. She succeeded to do it for each one she came up with. But when she came up with another one — xor of all pairwise sums of elements in the array, she realized that she couldn't compute it for a very large array, thus she asked for your help. Can you do it? Formally, you need to compute(a1+a2)⊕(a1+a3)⊕…⊕(a1+an)⊕(a2+a3)⊕…⊕(a2+an)…⊕(an−1+an)(a1+a2)⊕(a1+a3)⊕…⊕(a1+an)⊕(a2+a3)⊕…⊕(a2+an)…⊕(an−1+an)Here x⊕yx⊕y is a bitwise XOR operation (i.e. xx ^ yy in many modern programming languages). You can read about it in Wikipedia: https://en.wikipedia.org/wiki/Exclusive_or#Bitwise_operation.InputThe first line contains a single integer nn (2≤n≤4000002≤n≤400000) — the number of integers in the array.The second line contains integers a1,a2,…,ana1,a2,…,an (1≤ai≤1071≤ai≤107).OutputPrint a single integer — xor of all pairwise sums of integers in the given array.ExamplesInputCopy2
1 2
OutputCopy3InputCopy3
1 2 3
OutputCopy2NoteIn the first sample case there is only one sum 1+2=31+2=3.In the second sample case there are three sums: 1+2=31+2=3, 1+3=41+3=4, 2+3=52+3=5. In binary they are represented as 0112⊕1002⊕1012=01020112⊕1002⊕1012=0102, thus the answer is 2.⊕⊕ is the bitwise xor operation. To define x⊕yx⊕y, consider binary representations of integers xx and yy. We put the ii-th bit of the result to be 1 when exactly one of the ii-th bits of xx and yy is 1. Otherwise, the ii-th bit of the result is put to be 0. For example, 01012⊕00112=0110201012⊕00112=01102. | [
"binary search",
"bitmasks",
"constructive algorithms",
"data structures",
"math",
"sortings"
] | //package round626;
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 B {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni();
int[] a = na(n);
long ans = 0;
if(n % 2 == 0){
for(int v : a){
ans ^= v;
}
}
for(int d = 0;d < 25;d++){
int[] b = new int[n];
for(int i = 0;i < n;i++){
b[i] = a[i]&(1<<d)-1;
}
b = radixSort(b);
int p = n-1;
int x = 0;
for(int i = 0;i < n;i++){
while(i < p && b[i] + b[p] >= 1<<d){
p--;
}
x ^= n-1-Math.max(p, i);
}
ans ^= (x&1)<<d;
}
out.println(ans);
}
public static int[] radixSort(int[] f){ return radixSort(f, f.length); }
public static int[] radixSort(int[] f, int n)
{
int[] to = new int[n];
{
int[] b = new int[65537];
for(int i = 0;i < n;i++)b[1+(f[i]&0xffff)]++;
for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
for(int i = 0;i < n;i++)to[b[f[i]&0xffff]++] = f[i];
int[] d = f; f = to;to = d;
}
{
int[] b = new int[65537];
for(int i = 0;i < n;i++)b[1+(f[i]>>>16)]++;
for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
for(int i = 0;i < n;i++)to[b[f[i]>>>16]++] = f[i];
int[] d = f; f = to;to = d;
}
return f;
}
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 B().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 |
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 java.io.*;
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[] arr = new int[n];
int[] pre = new int[n];
int[] suff = new int[n+1];
for(int i=0;i<n;i++)
arr[i] = sc.nextInt();
pre[0] = ~arr[0];
for(int i=1;i<n;i++)pre[i] = (~arr[i]) & pre[i-1];
suff[n-1] = ~arr[n-1];
for(int i=n-2;i>=0;i--)suff[i] = (~arr[i]) & suff[i+1];
int maxVal = -1;
int maxInd = -1;
for(int i=0;i<n;i++){
int curr;
if(i==0)curr = arr[i] & suff[i+1];
else if(i==n-1)curr = arr[i] & pre[i-1];
else curr= arr[i] & pre[i-1] & suff[i+1];
if(curr > maxVal){
maxVal = curr;
maxInd = i;
}
}
out.println(arr[maxInd]);
for(int i=0;i<n;i++){
if(i!=maxInd)out.println(arr[i]);
}
}
public static int findComplement(int num) {
// Duplicate the input for reference
int originalNum = num;
// Set a variable for looping on an index
long i = 1;
// Loop while `i` is less or equal to `originalNum`
while(i<=originalNum) {
// Shift the variables
num ^= i;
i <<= 1;
}
// Return the resultant `num`
return num;
}
/*-------------------------------------------EDITING CODE ENDS HERE-------------------------------------------*/
static FastestReader sc;
static PrintWriter out;
private static void openIO() throws IOException{
sc = new FastestReader();
out = new PrintWriter(System.out);
}
/*------------------------------------------HELPER FUNCTION STARTS HERE------------------------------------------*/
public static int mod = (int) 1e9 + 7;
private static int mod2 = 998244353;
public static int inf_int = (int) 2e9 + 10;
public static long inf_long = (long) 2e15;
// time : O(1), space : O(1)
private static int _modIndex(int x, int n){
// return the valid index x in an array , like n % n = 0, -1 % b = n-1
return (x+n) % n;
}
// time : O(1), space : O(1)
public static int _digitCount(long num,int base){
// this will give the # of digits needed for a number num in format : base
return (int)(1 + Math.log(num)/Math.log(base));
}
// time : O(n), space: O(n)
public static long _fact(int n){
// simple factorial calculator
long ans = 1;
for(int i=2;i<=n;i++)
ans = ans * i % mod;
return ans;
}
// time : O(r)
public static int _ncr(int n,int r){
if (r > n) return 0;
long[] inv = new long[r + 1];
inv[0] = 1;
if(r+1>=2)
inv[1] = 1;
// Getting the modular inversion
// for all the numbers
// from 2 to r with respect to mod
for (int i = 2; i <= r; i++)
inv[i] = mod - (mod / i) * inv[(mod % i)] % mod;
int ans = 1;
// for 1/(r!) part
for (int i = 2; i <= r; i++)
ans = (int) (((ans % mod) * (inv[i] % mod)) % mod);
// for (n)*(n-1)*(n-2)*...*(n-r+1) part
for (int i = n; i >= (n - r + 1); i--)
ans = (((ans % mod) * (i % mod)) % mod);
return ans;
}
// euclidean algorithm time O(max (loga ,logb))
public static long _gcd(long a, long b) {
if (a == 0)
return b;
return _gcd(b % a, a);
}
// lcm(a,b) * gcd(a,b) = a * b
public static long _lcm(long a, long b) {
return (a / _gcd(a, b)) * b;
}
// binary exponentiation time O(logn)
public static long _power(long x, long n) {
long ans = 1;
while (n > 0) {
if ((n & 1) == 1) {
ans *= x;
ans %= mod;
n--;
} else {
x *= x;
x %= mod;
n >>= 1;
}
}
return ans;
}
//sieve or first divisor time : O(mx * log ( log (mx) ) )
public static int[] _seive(int mx){
int[] firstDivisor = new int[mx+1];
for(int i=0;i<=mx;i++)firstDivisor[i] = i;
for(int i=2;i*i<=mx;i++)
if(firstDivisor[i] == i)
for(int j = i*i;j<=mx;j+=i)
firstDivisor[j] = i;
return firstDivisor;
}
// check if x is a prime # of not. time : O( n ^ 1/2 )
private static boolean _isPrime(long x){
for(long i=2;i*i<=x;i++)
if(x%i==0)return false;
return true;
}
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);
}
/*------------------------------------------HELPER FUNCTION ENDS HERE-------------------------------------------*/
/*-------------------------------------------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 |
1311 | A | A. Add Odd or Subtract Eventime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integers aa and bb.In one move, you can change aa in the following way: Choose any positive odd integer xx (x>0x>0) and replace aa with a+xa+x; choose any positive even integer yy (y>0y>0) and replace aa with a−ya−y. You can perform as many such operations as you want. You can choose the same numbers xx and yy in different moves.Your task is to find the minimum number of moves required to obtain bb from aa. It is guaranteed that you can always obtain bb from aa.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. Each test case is given as two space-separated integers aa and bb (1≤a,b≤1091≤a,b≤109).OutputFor each test case, print the answer — the minimum number of moves required to obtain bb from aa if you can perform any number of moves described in the problem statement. It is guaranteed that you can always obtain bb from aa.ExampleInputCopy5
2 3
10 10
2 4
7 4
9 3
OutputCopy1
0
2
2
1
NoteIn the first test case; you can just add 11.In the second test case, you don't need to do anything.In the third test case, you can add 11 two times.In the fourth test case, you can subtract 44 and add 11.In the fifth test case, you can just subtract 66. | [
"greedy",
"implementation",
"math"
] | // package c1311;
//
// Codeforces Round #624 (Div. 3) 2020-02-24 06:35
// A. Add Odd or Subtract Even
// https://codeforces.com/contest/1311/problem/A
// 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+).*'
//
// You are given two positive integers a and b.
//
// In one move, you can a in the following way:
// * Choose any positive integer x (x > 0) and replace a with a+x;
// * choose any positive integer y (y > 0) and replace a with a-y.
//
// You can perform as many such operations as you want. You can choose the same numbers x and y in
// different moves.
//
// Your task is to find the minimum number of moves required to obtain b from a. It is guaranteed
// that you can always obtain b from a.
//
// You have to answer t independent test cases.
//
// Input
//
// The first line of the input contains one integer t (1 <= t <= 10^4) -- the number of test cases.
//
// Then t test cases follow. Each test case is given as two space-separated integers a and b (1 <=
// a, b <= 10^9).
//
// Output
//
// For each test case, print the answer -- the minimum number of moves required to obtain b from a
// if you can perform any number of moves described in the problem statement. It is guaranteed that
// you can always obtain b from a.
//
// Example
/*
input:
5
2 3
10 10
2 4
7 4
9 3
output:
1
0
2
2
1
*/
// Note
//
// In the first test case, you can just add 1.
//
// In the second test case, you don't need to do anything.
//
// In the third test case, you can add 1 two times.
//
// In the fourth test case, you can subtract 4 and add 1.
//
// In the fifth test case, you can just subtract 6.
//
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 C1311A {
static final int MOD = 998244353;
static final Random RAND = new Random();
static int solve(int a, int b) {
if (a == b) {
return 0;
} else if (a < b) {
if (a % 2 == 0 && b % 2 == 0) {
// 4 -> 10
return 2;
} else if (a % 2 == 0 && b % 2 == 1) {
// 4 -> 5
return 1;
} else if (a % 2 == 1 && b % 2 == 0) {
// 5 -> 6
return 1;
} else {
// 5 -> 7
return 2;
}
} else {
if (a % 2 == 0 && b % 2 == 0) {
// 10 -> 4
return 1;
} else if (a % 2 == 0 && b % 2 == 1) {
// 6 -> 5
return 2;
} else if (a % 2 == 1 && b % 2 == 0) {
// 7 -> 6
return 2;
} else {
// 7 -> 5
return 1;
}
}
}
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++) {
int a = in.nextInt();
int b = in.nextInt();
int ans = solve(a, b);
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 |
1294 | E | E. Obtain a Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rectangular matrix of size n×mn×m consisting of integers from 11 to 2⋅1052⋅105.In one move, you can: choose any element of the matrix and change its value to any integer between 11 and n⋅mn⋅m, inclusive; take any column and shift it one cell up cyclically (see the example of such cyclic shift below). A cyclic shift is an operation such that you choose some jj (1≤j≤m1≤j≤m) and set a1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,ja1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,j simultaneously. Example of cyclic shift of the first column You want to perform the minimum number of moves to make this matrix look like this: In other words, the goal is to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (i.e. ai,j=(i−1)⋅m+jai,j=(i−1)⋅m+j) with the minimum number of moves performed.InputThe first line of the input contains two integers nn and mm (1≤n,m≤2⋅105,n⋅m≤2⋅1051≤n,m≤2⋅105,n⋅m≤2⋅105) — the size of the matrix.The next nn lines contain mm integers each. The number at the line ii and position jj is ai,jai,j (1≤ai,j≤2⋅1051≤ai,j≤2⋅105).OutputPrint one integer — the minimum number of moves required to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (ai,j=(i−1)m+jai,j=(i−1)m+j).ExamplesInputCopy3 3
3 2 1
1 2 3
4 5 6
OutputCopy6
InputCopy4 3
1 2 3
4 5 6
7 8 9
10 11 12
OutputCopy0
InputCopy3 4
1 6 3 4
5 10 7 8
9 2 11 12
OutputCopy2
NoteIn the first example; you can set a1,1:=7,a1,2:=8a1,1:=7,a1,2:=8 and a1,3:=9a1,3:=9 then shift the first, the second and the third columns cyclically, so the answer is 66. It can be shown that you cannot achieve a better answer.In the second example, the matrix is already good so the answer is 00.In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is 22. | [
"greedy",
"implementation",
"math"
] | import java.io.*;
import java.util.*;
public class Main {
static int func(int[] g,int num,int m) {
int n=g.length;
int[] fill=new int[n];
int ans=n;
for(int i=0;i<n;i++) {
if(g[i%n]%m!=num || g[i%n]>n*m) continue;
int orig=(g[i%n]-num)/m;
if(num==0) orig--;
int shift=-1;
if(orig<=i) {
shift=(i-orig);
}
else {
shift=(n+i-orig);
}
fill[shift]++;
}
// System.out.println(Arrays.toString(fill));
for(int i=0;i<n;i++) {
int temp=i+n-fill[i];
ans=Math.min(ans, temp);
}
return ans;
}
public static void main(String[] args) throws IOException
{
FastScanner f = new FastScanner();
int ttt=1;
// ttt=f.nextInt();
PrintWriter out=new PrintWriter(System.out);
for(int tt=0;tt<ttt;tt++) {
int n=f.nextInt();
int m=f.nextInt();
int[][] g=new int[m][n];
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
g[j][i]=f.nextInt();
}
}
int ans=0;
for(int i=0;i<m;i++) {
ans+=func(g[i],(i+1)%m,m);
// System.out.println(ans);
}
System.out.println(ans);
}
out.close();
}
static void sort(int[] p) {
ArrayList<Integer> q = new ArrayList<>();
for (int i: p) q.add( 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;
}
}
} | java |
1316 | E | E. Team Buildingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice; the president of club FCB, wants to build a team for the new volleyball tournament. The team should consist of pp players playing in pp different positions. She also recognizes the importance of audience support, so she wants to select kk people as part of the audience.There are nn people in Byteland. Alice needs to select exactly pp players, one for each position, and exactly kk members of the audience from this pool of nn people. Her ultimate goal is to maximize the total strength of the club.The ii-th of the nn persons has an integer aiai associated with him — the strength he adds to the club if he is selected as a member of the audience.For each person ii and for each position jj, Alice knows si,jsi,j — the strength added by the ii-th person to the club if he is selected to play in the jj-th position.Each person can be selected at most once as a player or a member of the audience. You have to choose exactly one player for each position.Since Alice is busy, she needs you to help her find the maximum possible strength of the club that can be achieved by an optimal choice of players and the audience.InputThe first line contains 33 integers n,p,kn,p,k (2≤n≤105,1≤p≤7,1≤k,p+k≤n2≤n≤105,1≤p≤7,1≤k,p+k≤n).The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤1091≤ai≤109).The ii-th of the next nn lines contains pp integers si,1,si,2,…,si,psi,1,si,2,…,si,p. (1≤si,j≤1091≤si,j≤109)OutputPrint a single integer resres — the maximum possible strength of the club.ExamplesInputCopy4 1 2
1 16 10 3
18
19
13
15
OutputCopy44
InputCopy6 2 3
78 93 9 17 13 78
80 97
30 52
26 17
56 68
60 36
84 55
OutputCopy377
InputCopy3 2 1
500 498 564
100002 3
422332 2
232323 1
OutputCopy422899
NoteIn the first sample; we can select person 11 to play in the 11-st position and persons 22 and 33 as audience members. Then the total strength of the club will be equal to a2+a3+s1,1a2+a3+s1,1. | [
"bitmasks",
"dp",
"greedy",
"sortings"
] | import java.util.*;
import java.io.*;
public class E20 {
public static void main(String[] args) {
MyScanner sc = new MyScanner();
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
int n = sc.nextInt(); int p = sc.nextInt(); int k = sc.nextInt();
long [][] dp = new long[n + 1][1 << p];
Person [] people = new Person[n];
for (int i = 0; i < n; i++) people[i] = new Person(sc.nextInt());
for (int i = 0; i < n; i++) {
for (int j = 0; j < p; j++) {
people[i].s[j] = sc.nextLong();
}
}
Arrays.sort(people, Comparator.comparingLong(x -> -x.a));
for (long [] arr : dp) Arrays.fill(arr, Long.MIN_VALUE / 2);
for (int i = 0; i < n; i++) {
if (i == 0) {
dp[0][0] = people[0].a;
for (int j = 0; j < p; j++) {
dp[0][1 << j] = people[0].s[j];
}
continue;
}
for (int j = 0; j < (1 << p); j++) {
for (int bit = 0; bit < p; bit++) {
if (((j >> bit) & 1) == 0) continue;
dp[i][j] = Math.max(dp[i][j], dp[i - 1][j ^ (1 << bit)] + people[i].s[bit]);
}
int before = i - Integer.bitCount(j);
if (before < k) {
dp[i][j] = Math.max(dp[i][j], dp[i - 1][j] + people[i].a);
} else dp[i][j] = Math.max(dp[i][j], dp[i - 1][j]);
}
}
out.println(dp[n - 1][(1 << p) - 1]);
out.close();
}
static class Person {
long a;
long [] s;
Person(long a) {
this.a = a;
s = new long[10];
}
}
//-----------MyScanner class for faster input----------
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 |
1304 | C | C. Air Conditionertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong owns a bulgogi restaurant. The restaurant has a lot of customers; so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: titi — the time (in minutes) when the ii-th customer visits the restaurant, lili — the lower bound of their preferred temperature range, and hihi — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the ii-th customer is satisfied if and only if the temperature is between lili and hihi (inclusive) in the titi-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.InputEach test contains one or more test cases. The first line contains the number of test cases qq (1≤q≤5001≤q≤500). Description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1001≤n≤100, −109≤m≤109−109≤m≤109), where nn is the number of reserved customers and mm is the initial temperature of the restaurant.Next, nn lines follow. The ii-th line of them contains three integers titi, lili, and hihi (1≤ti≤1091≤ti≤109, −109≤li≤hi≤109−109≤li≤hi≤109), where titi is the time when the ii-th customer visits, lili is the lower bound of their preferred temperature range, and hihi is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive.The customers are given in non-decreasing order of their visit time, and the current time is 00.OutputFor each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy4
3 0
5 1 2
7 3 5
10 -1 0
2 12
5 7 10
10 16 20
3 -100
100 0 0
100 -50 50
200 100 100
1 100
99 -100 0
OutputCopyYES
NO
YES
NO
NoteIn the first case; Gildong can control the air conditioner to satisfy all customers in the following way: At 00-th minute, change the state to heating (the temperature is 0). At 22-nd minute, change the state to off (the temperature is 2). At 55-th minute, change the state to heating (the temperature is 2, the 11-st customer is satisfied). At 66-th minute, change the state to off (the temperature is 3). At 77-th minute, change the state to cooling (the temperature is 3, the 22-nd customer is satisfied). At 1010-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at 00-th minute and leave it be. Then all customers will be satisfied. Note that the 11-st customer's visit time equals the 22-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied. | [
"dp",
"greedy",
"implementation",
"sortings",
"two pointers"
] | /* 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 Main
{
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;
}
}
int binary(int arr[], int x)
{
int l = 0, r = arr.length - 1;
while (l <= r) {
int m = l + (r - l) / 2;
if (arr[m] == x)
return m;
if (arr[m] < x)
l = m + 1;
else
r = m - 1;
}
return -1;
}
static int[] segment,parent,rank;
static void constructSt(int n, int[] arr){
segment = new int[n*4+1];
formSt(arr, 1,0,n-1);
}
public static void formSt(int[] arr, int node, int s, int e){
if(s==e){
segment[node]= arr[s];
return;
}
formSt(arr, node*2,s,s+(e-s)/2);
formSt(arr, node*2+1,s+(e-s)/2+1,e);
segment[node]=Math.max(segment[node*2],segment[node*2+1]);
}
public static int findMax( int node, int s, int e,int l , int r){
if(l>e||s>r) return -1;
if(s==e) return segment[node];
if(l<=s&&r>=e) return segment[node];
int mid = s+(e-s)/2;
return Math.max(findMax(node*2,s,mid,l,r),findMax(node*2+1,mid+1,e,l,r));
}
public static void dsu(int n){
parent = new int[n]; rank = new int[n];
for(int i =0;i<n;i++) parent[i]=i;
}
public static int find(int i){
if(i==parent[i] ) return i;
return parent[i]=find(parent[i]);
}
public static void merge(int i, int j){
if(rank[i]>=rank[j]){
rank[i]+=rank[j];
parent[j]=i;
}
else {
rank[j]+=rank[i];
parent[i]=j;
}
}
static int count =0;
static boolean[] v;
public static int solve(List<List<Integer>> a , int n, char[] c){
v=new boolean[n+1];
help(a,n,c,1);
count=0;
// System.out.println(a)
for(boolean e:v) if(e) count++;
return count;
}
public static int[] help(List<List<Integer> >a , int n , char[] c , int i ){
int[] arr = new int[2];
arr[c[i-1]=='W'?0:1]++;
for(int e:a.get(i)){
int[] x = help(a,n,c,e);
arr[0]+=x[0]; arr[1]+=x[1];
}
v[i]= arr[0]==arr[1];
return arr;
}
public static int help(char[] a, char[] b, int i, int n){
int count =0;
if(a[i]==a[n-i-1]&&b[i]==b[n-i-1]||a[i]==b[i]&&a[n-i-1]==b[n-i-1]||a[i]==b[n-i-1]&&a[n-i-1]==b[i]) return 2;
if(a[i]==b[i]||a[i]==b[n-i-1]||a[n-i-1]==b[i]||a[n-i-1]==b[n-i-1]||b[i]==b[n-i-1]) return 1;
return count;
}
public static void main (String[] args) throws java.lang.Exception
{
OutputStream outputStream =System.out;
PrintWriter out =new PrintWriter(outputStream);
FastReader sc =new FastReader();
int z = sc.nextInt();
while(z-->0){
int n = sc.nextInt();
long t = sc.nextLong();
long[][] a = new long[n][3];
for(int i =0;i<n;i++){
a[i][0]=sc.nextLong(); a[i][1]=sc.nextLong(); a[i][2]=sc.nextLong();
}
Arrays.sort(a,(x,y)->x[0]<y[0]?-1:1);
int count =0;
long low =t, high = t, prev =0L;
for(long[] e : a)
{
long l = low-(e[0]-prev), h = high+(e[0]-prev);
if(l>=e[1]&&l<=e[2]||h>=e[1]&&h<=e[2]||l>=e[1]&&h<=e[2]||e[1]>=l&&e[2]<=h){
count ++;
low=Math.max(l,e[1]); high = Math.min(h,e[2]);
}
prev = e[0];
}
out.print(count==n?"YES":"NO");
out.print("\n");
}
out.close();
// your code goes here"
}
}
class pair
{
long r;
long d;
public pair(long r , long d)
{
this.r= r;
this.d= d;
}
}
class solution{
}
| java |
1325 | E | E. Ehab's REAL Number Theory Problemtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square.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.InputThe first line contains an integer nn (1≤n≤1051≤n≤105) — the length of aa.The second line contains nn integers a1a1, a2a2, ……, anan (1≤ai≤1061≤ai≤106) — the elements of the array aa.OutputOutput the length of the shortest non-empty subsequence of aa product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print "-1".ExamplesInputCopy3
1 4 6
OutputCopy1InputCopy4
2 3 6 6
OutputCopy2InputCopy3
6 15 10
OutputCopy3InputCopy4
2 3 5 7
OutputCopy-1NoteIn the first sample; you can choose a subsequence [1][1].In the second sample, you can choose a subsequence [6,6][6,6].In the third sample, you can choose a subsequence [6,15,10][6,15,10].In the fourth sample, there is no such subsequence. | [
"brute force",
"dfs and similar",
"graphs",
"number theory",
"shortest paths"
] | import org.w3c.dom.xpath.XPathResult;
import java.io.*;
import java.util.*;
public class Solution {
private static final int MAX_VALUE = 1000000;
private static final int MAX_ROOT = 1000;
public void solve() {
List<Integer> prime = sieve(MAX_VALUE);
HashMap<Integer, Integer> idx = new HashMap<>();
int cnt = 0;
int n = reader.nextInt();
int[][] edges = new int[n][2];
HashSet<Integer> root = new HashSet<>();
HashSet<Integer> existed = new HashSet<>();
boolean repeated = false;
for (int i = 0; i < n; i++) {
int[] a = simplify(prime, reader.nextInt());
int x = a[0], y = a[1];
int s = x * y;
if (s == 1) {
writer.println(1);
return;
}
if (existed.contains(s)) repeated = true;
existed.add(s);
if (!idx.containsKey(x)) idx.put(x, cnt++);
if (!idx.containsKey(y)) idx.put(y, cnt++);
int u = idx.get(x);
int v = idx.get(y);
edges[i][0] = u;
edges[i][1] = v;
if (x <= MAX_ROOT) root.add(u);
if (y <= MAX_ROOT) root.add(v);
}
if (repeated) {
writer.println(2);
return;
}
List<Integer>[] adj = new List[cnt];
for (int i = 0; i < cnt; i++) adj[i] = new ArrayList<>();
for (int i = 0; i < n; i++) {
int u = edges[i][0];
int v = edges[i][1];
adj[u].add(v);
adj[v].add(u);
}
writer.println(shortestCycle(adj, root));
}
private int shortestCycle(List<Integer>[] adj, HashSet<Integer> root) {
int res = MAX_VALUE;
int n = adj.length;
int[] parent = new int[n];
int[] level = new int[n];
Deque<Integer> queue = new LinkedList<>();
for (int start : root) {
Arrays.fill(level, -1);
parent[start] = start;
level[start] = 0;
queue.add(start);
while (!queue.isEmpty()) {
int u = queue.poll();
if (level[u] + 1 >= res) continue;
for (int v : adj[u]) {
if (level[v] == -1) {
parent[v] = u;
level[v] = level[u] + 1;
queue.add(v);
continue;
}
if (v == parent[u]) continue;
res = Math.min(res, level[u] + level[v] + 1);
}
}
}
return res < MAX_VALUE ? res : -1;
}
private int[] simplify(List<Integer> prime, int a) {
for (int p : prime) {
int q = p * p;
if (q > a) break;
while (a % q == 0) a /= q;
}
for (int p : prime) {
if (p * p > a) break;
if (a % p == 0) return new int[]{p, a / p};
}
return new int[]{1, a};
}
private List<Integer> sieve(int n) {
boolean[] removed = new boolean[n + 1];
for (int i = 2; i * i <= n; i++) {
for (int j = i * i; j <= n; j += i) {
removed[j] = true;
}
}
List<Integer> prime = new LinkedList<>();
prime.add(2);
for (int i = 3; i <= n; i += 2) {
if (!removed[i]) prime.add(i);
}
return prime;
}
private InputReader reader;
private PrintWriter writer;
public Solution(InputReader reader, PrintWriter writer) {
this.reader = reader;
this.writer = writer;
}
public static void main(String[] args) {
InputReader reader = new InputReader(System.in);
PrintWriter writer = new PrintWriter(System.out);
Solution solution = new Solution(reader, writer);
solution.solve();
writer.flush();
}
static class InputReader {
private static final int BUFFER_SIZE = 1 << 20;
private BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), BUFFER_SIZE);
tokenizer = null;
}
public String nextToken() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException();
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public long nextLong() {
return Long.parseLong(nextToken());
}
}
}
| java |
1284 | B | B. New Year and Ascent Sequencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputA sequence a=[a1,a2,…,al]a=[a1,a2,…,al] of length ll has an ascent if there exists a pair of indices (i,j)(i,j) such that 1≤i<j≤l1≤i<j≤l and ai<ajai<aj. For example, the sequence [0,2,0,2,0][0,2,0,2,0] has an ascent because of the pair (1,4)(1,4), but the sequence [4,3,3,3,1][4,3,3,3,1] doesn't have an ascent.Let's call a concatenation of sequences pp and qq the sequence that is obtained by writing down sequences pp and qq one right after another without changing the order. For example, the concatenation of the [0,2,0,2,0][0,2,0,2,0] and [4,3,3,3,1][4,3,3,3,1] is the sequence [0,2,0,2,0,4,3,3,3,1][0,2,0,2,0,4,3,3,3,1]. The concatenation of sequences pp and qq is denoted as p+qp+q.Gyeonggeun thinks that sequences with ascents bring luck. Therefore, he wants to make many such sequences for the new year. Gyeonggeun has nn sequences s1,s2,…,sns1,s2,…,sn which may have different lengths. Gyeonggeun will consider all n2n2 pairs of sequences sxsx and sysy (1≤x,y≤n1≤x,y≤n), and will check if its concatenation sx+sysx+sy has an ascent. Note that he may select the same sequence twice, and the order of selection matters.Please count the number of pairs (x,yx,y) of sequences s1,s2,…,sns1,s2,…,sn whose concatenation sx+sysx+sy contains an ascent.InputThe first line contains the number nn (1≤n≤1000001≤n≤100000) denoting the number of sequences.The next nn lines contain the number lili (1≤li1≤li) denoting the length of sisi, followed by lili integers si,1,si,2,…,si,lisi,1,si,2,…,si,li (0≤si,j≤1060≤si,j≤106) denoting the sequence sisi. It is guaranteed that the sum of all lili does not exceed 100000100000.OutputPrint a single integer, the number of pairs of sequences whose concatenation has an ascent.ExamplesInputCopy5
1 1
1 1
1 2
1 4
1 3
OutputCopy9
InputCopy3
4 2 0 2 0
6 9 9 8 8 7 7
1 6
OutputCopy7
InputCopy10
3 62 24 39
1 17
1 99
1 60
1 64
1 30
2 79 29
2 20 73
2 85 37
1 100
OutputCopy72
NoteFor the first example; the following 99 arrays have an ascent: [1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4][1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4]. Arrays with the same contents are counted as their occurences. | [
"binary search",
"combinatorics",
"data structures",
"dp",
"implementation",
"sortings"
] | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class NewYearAndAscentSequence {
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 nextFloat() {
return Float.parseFloat(next());
}
double nextDouble() {
return Double.parseDouble(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] = this.nextInt();
}
return a;
}
long[] nextArrayLong(int n) {
long[] a = new long[n];
for (int i=0; i<n; i++) {
a[i] = this.nextLong();
}
return a;
}
}
public static void solve(int n, int[][] s) {
long aCount = 0;
boolean[] isAscent = new boolean[n];
long buf[] = new long[1000007];
for (int i=0; i<n; i++) {
for (int j=1; j<s[i].length; j++) {
if (s[i][j] > s[i][j-1]) {
isAscent[i] = true;
aCount++;
break;
}
}
}
for (int i=0; i<n; i++) {
if (!isAscent[i]) {
buf[s[i][0]]++;
}
}
for (int i=buf.length-2; i>=0; i--) {
buf[i] += buf[i+1];
}
long ans = aCount * n;
for (int i=0; i<n; i++) {
if (!isAscent[i]) {
ans += (aCount + buf[s[i][s[i].length-1]+1]);
}
}
System.out.println(ans);
}
public static void main(String[] args) {
FastReader in = new FastReader();
int n = in.nextInt();
int[][] s = new int[n][];
for (int i=0; i<n; i++) {
int l = in.nextInt();
s[i] = in.nextArray(l);
}
solve(n, s);
}
}
| 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 cf_31 {
public static void main(String[] args) {
new Solution().solve();
}
}
class Solution {
public void solve() {
FastScanner fs = new FastScanner();
int tests = fs.nextInt();
while (tests > 0) {
tests--;
int n = fs.nextInt(), m = fs.nextInt(), k = fs.nextInt();
int[] arr = fs.readIntArray(n);
if (k >= m-1) {
k = m-1;
}
int max = Integer.MIN_VALUE;
for (int i=k; i >= 0; i--) {
int j=k-i;
int d =m-1-k;
int min = Integer.MAX_VALUE;
for (int l=d; l >=0; l--) {
int t = d-l;
min = Math.min(min, Math.max(arr[l+i], arr[n-1-(j+t)]));
}
max = Math.max(max, min);
}
System.out.println(max);
}
}
}
class FastScanner {
private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
private StringTokenizer st = new StringTokenizer("");
// Below would return next string (delimited by space or new line)
public String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
// Below would return entire string in the line (including spaces)
public String nextLineStr() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
public int[] readIntArray(int n) {
int[] arr = new int[n];
for (int i=0; i<n; i++) {
arr[i] = nextInt();
}
return arr;
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public float nextFloat() {
return Float.parseFloat(next());
}
} | java |
1325 | E | E. Ehab's REAL Number Theory Problemtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square.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.InputThe first line contains an integer nn (1≤n≤1051≤n≤105) — the length of aa.The second line contains nn integers a1a1, a2a2, ……, anan (1≤ai≤1061≤ai≤106) — the elements of the array aa.OutputOutput the length of the shortest non-empty subsequence of aa product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print "-1".ExamplesInputCopy3
1 4 6
OutputCopy1InputCopy4
2 3 6 6
OutputCopy2InputCopy3
6 15 10
OutputCopy3InputCopy4
2 3 5 7
OutputCopy-1NoteIn the first sample; you can choose a subsequence [1][1].In the second sample, you can choose a subsequence [6,6][6,6].In the third sample, you can choose a subsequence [6,15,10][6,15,10].In the fourth sample, there is no such subsequence. | [
"brute force",
"dfs and similar",
"graphs",
"number theory",
"shortest paths"
] | import java.io.*;
import java.util.*;
/*
Прокрастинирую
*/
public class Main {
static FastReader in;
static PrintWriter out;
static Random rand = new Random();
static final int INF = (int) (1e9 + 10);
static final int MOD = (int) (1e9 + 7);
static final int N = (int) (1e6);
static final int LOGN = 62;
static int n;
static int[] a, lp, ind, d, p;
static ArrayList<Integer> primes;
static HashSet<Integer> set;
static ArrayList<Integer>[] g;
static ArrayDeque<Integer> q;
static void solve() {
n = in.nextInt();
a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
lp = new int[N + 1]; lp[1] = 1;
ind = new int[N + 1]; ind[1] = 0;
primes = new ArrayList<>(); primes.add(1);
for (int i = 2; i <= N; i++) {
if (lp[i] == 0) {
lp[i] = i;
ind[i] = primes.size();
primes.add(i);
if ((long) i * i > N) continue;
for (int j = i * i; j <= N; j += i) {
if (lp[j] == 0) lp[j] = i;
}
}
}
set = new HashSet<>();
g = new ArrayList[primes.size()];
Arrays.setAll(g, gg -> new ArrayList<>());
for (int i = 0; i < n; i++) {
int sq = (int) Math.sqrt(a[i]);
if (sq * sq == a[i]) {
out.println(1);
return;
}
int aa = a[i];
int v = lp[aa], u = 1;
int cnt = 0;
while (lp[aa] == v) {
cnt++;
aa /= lp[aa];
}
if (cnt % 2 == 0) v = 1;
if (aa > 1) {
u = lp[aa];
cnt = 0;
while (lp[aa] == u) {
cnt++;
aa /= lp[aa];
}
if (cnt % 2 == 0) u = 1;
}
g[ind[v]].add(ind[u]);
g[ind[u]].add(ind[v]);
set.add(v * u);
}
if (set.size() != n) {
out.println(2);
return;
}
int ans = INF;
int sq = (int) Math.ceil(Math.sqrt(N));
q = new ArrayDeque<>();
d = new int[primes.size()];
p = new int[primes.size()];
for (int i = 1; i <= sq; i++) {
if (lp[i] != i) continue;
for (int v = 0; v < primes.size(); v++) {
d[v] = -1;
p[v] = -1;
}
int v = ind[i];
q.addLast(v);
d[v] = 0;
p[v] = v;
while (!q.isEmpty()) {
v = q.pollFirst();
if (d[v] + 1 >= ans) {
q.clear();
break;
}
for (int u : g[v]) {
if (d[u] == -1) {
d[u] = d[v] + 1;
p[u] = v;
q.addLast(u);
} else if (p[v] != u) {
ans = Math.min(ans, d[v] + d[u] + 1);
}
}
}
}
if (ans == INF) {
out.println(-1);
} else {
out.println(ans);
}
}
public static void main(String[] args) throws FileNotFoundException {
in = new FastReader(System.in);
// in = new FastReader(new FileInputStream("connect.in"));
out = new PrintWriter(System.out);
// out = new PrintWriter(new FileOutputStream("connect.out"));
int q = 1;
// q = in.nextInt();
while (q-- > 0) {
solve();
}
out.close();
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
FastReader(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
Integer nextInt() {
return Integer.parseInt(next());
}
Long nextLong() {
return Long.parseLong(next());
}
Double nextDouble() {
return Double.parseDouble(next());
}
String next() {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(nextLine());
}
return st.nextToken();
}
String nextLine() {
String s = "";
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return s;
}
}
} | java |
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.util.*;
import java.io.*;
import static java.lang.Math.*;
public class Main { public static void main(String[] args) { new MainClass().execute(); } }
class MainClass extends PrintWriter {
MainClass() { super(System.out, true); }
boolean cases = true;
// Solution
char a[], b[];
void solveIt(int testCaseNo) {
this.a = sc.next().toCharArray();
this.b = sc.next().toCharArray();
this.dp = new Boolean[a.length + 1][b.length + 1][b.length + 1];
for (int i = 0; i < b.length; i++) {
if (solve(0, 0, i + 1, i)) {
println("YES");
return;
}
}
println("NO");
}
Boolean dp[][][];
private boolean solve(int p, int i, int j, int k) {
if (i > k && j >= b.length) return true;
if (p == a.length) return false;
if (dp[p][i][j] != null) return dp[p][i][j];
boolean ans = false;
if (i <= k && j < b.length) {
if (a[p] == b[i] && a[p] == b[j]) {
ans |= solve(p + 1, i, j, k);
ans |= solve(p + 1, i + 1, j, k);
ans |= solve(p + 1, i, j + 1, k);
} else if (a[p] == b[i]) {
ans |= solve(p + 1, i, j, k);
ans |= solve(p + 1, i + 1, j, k);
} else if (a[p] == b[j]) {
ans |= solve(p + 1, i, j, k);
ans |= solve(p + 1, i, j + 1, k);
} else {
ans |= solve(p + 1, i, j, k);
}
} else if (i <= k) {
if (a[p] == b[i]) {
ans |= solve(p + 1, i, j, k);
ans |= solve(p + 1, i + 1, j, k);
} else {
ans |= solve(p + 1, i, j, k);
}
} else if (j < b.length) {
if (a[p] == b[j]) {
ans |= solve(p + 1, i, j, k);
ans |= solve(p + 1, i, j + 1, k);
} else {
ans |= solve(p + 1, i, j, k);
}
}
return dp[p][i][j] = ans;
}
<T, V> void mapAdd(Map<T, V> map, T key) {
Integer value = (Integer) map.get(key);
if (value != null) {
value = Integer.valueOf(value.intValue() + 1);
} else {
value = new Integer(1);
}
map.put(key, (V) value);
}
<T, V> void mapRemove(Map<T, V> map, T key) {
Integer value = (Integer) map.get(key);
if (value != null) {
value = Integer.valueOf(value.intValue() - 1);
if (value.intValue() == 0) map.remove(key);
else map.put(key, (V) value);
}
}
void sort(int a[], Comparator<Integer> cmp) {
List<Integer> al = new ArrayList<>();
for (int x : a) al.add(x);
if (cmp != null) al.sort(cmp);
else Collections.sort(al);
for (int i = 0; i < a.length; i++) a[i] = al.get(i);
}
void solve() {
int caseNo = 1;
if (cases) for (int T = sc.nextInt(); T > 1; T--, caseNo++) { solveIt(caseNo); }
solveIt(caseNo);
}
void execute() {
long S = System.currentTimeMillis();
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
this.sc = new FastIO();
solve();
out.flush();
long G = System.currentTimeMillis();
sc.tr(G - S + "ms");
}
class FastIO {
private boolean endOfFile() {
if (bufferLength == -1) return true;
int lptr = ptrbuf;
while (lptr < bufferLength) {
// __
if (!spaceChar(inputBuffer[lptr++])) return false;
}
try {
is.mark(1000);
while (true) {
int b = is.read();
if (b == -1) {
is.reset();
return true;
} else if (!spaceChar(b)) {
is.reset();
return false;
}
}
} catch (IOException e) {
return true;
}
}
private byte[] inputBuffer = new byte[1024];
int bufferLength = 0, ptrbuf = 0;
private int readByte() {
if (bufferLength == -1) throw new InputMismatchException();
if (ptrbuf >= bufferLength) {
ptrbuf = 0;
try {
bufferLength = is.read(inputBuffer);
} catch (IOException e) {
throw new InputMismatchException();
}
if (bufferLength <= 0) return -1;
}
return inputBuffer[ptrbuf++];
}
private boolean spaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skipIt() {
int b;
while ((b = readByte()) != -1 && spaceChar(b));
return b;
}
private double nextDouble() { return Double.parseDouble(next()); }
private char nextChar() { return (char) skipIt(); }
private String next() {
int b = skipIt();
StringBuilder sb = new StringBuilder();
while (!(spaceChar(b))) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] readCharArray(int n) {
char[] buf = new char[n];
int b = skipIt(), p = 0;
while (p < n && !(spaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] readCharMatrix(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++) map[i] = readCharArray(m);
return map;
}
private int[] readIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
private long[] readLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
private int nextInt() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private long nextLong() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private void tr(Object... o) {
if (INPUT.length() != 0) System.out.println(Arrays.deepToString(o));
}
}
InputStream is;
PrintWriter out;
String INPUT = "";
final int ima = Integer.MAX_VALUE, imi = Integer.MIN_VALUE;
final long lma = Long.MAX_VALUE, lmi = Long.MIN_VALUE;
final long mod = (long) 1e9 + 7;
FastIO sc;
} | java |
1312 | D | D. Count the Arraystime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYour task is to calculate the number of arrays such that: each array contains nn elements; each element is an integer from 11 to mm; for each array, there is exactly one pair of equal elements; for each array aa, there exists an index ii such that the array is strictly ascending before the ii-th element and strictly descending after it (formally, it means that aj<aj+1aj<aj+1, if j<ij<i, and aj>aj+1aj>aj+1, if j≥ij≥i). InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105).OutputPrint one integer — the number of arrays that meet all of the aforementioned conditions, taken modulo 998244353998244353.ExamplesInputCopy3 4
OutputCopy6
InputCopy3 5
OutputCopy10
InputCopy42 1337
OutputCopy806066790
InputCopy100000 200000
OutputCopy707899035
NoteThe arrays in the first example are: [1,2,1][1,2,1]; [1,3,1][1,3,1]; [1,4,1][1,4,1]; [2,3,2][2,3,2]; [2,4,2][2,4,2]; [3,4,3][3,4,3]. | [
"combinatorics",
"math"
] | import java.io.*;
import java.util.*;
public class CodeForces {
/*-------------------------------------------EDITING CODE STARTS HERE-------------------------------------------*/
public static void solve(int tCase) throws IOException {
int n = sc.nextInt();
int m = sc.nextInt();
long ans = 0;
_ncr_precompute(m);
for(int i=1;i<n-1;i++){
ans += (long) _ncr(m, n-1) * _ncr(n-2,i) % mod * i % mod;
ans %=mod;
}
// bruteForce(0,new int[n],n,m);
out.println(ans);
// out.println(cnt);
}
// static int cnt = 0;
// private static void bruteForce(int i,int[] arr,int n,int m){
// if(i==n){
// for(int j=1;j<n-1;j++)
// if(isOK(arr,j,n)){
// cnt++;
//// out.println(Arrays.toString(arr));
// break;
// }
// return;
// }
// for(int j=1;j<=m;j++) {
// arr[i] = j;
// bruteForce(i + 1, arr,n,m);
// }
// }
// private static boolean isOK(int[] arr,int top,int n){
// for(int i=1;i<=top;i++)
// if(arr[i] <= arr[i-1])return false;
// for(int i=top;i<n-1;i++)
// if(arr[i] <= arr[i+1])return false;
// Set<Integer> set = new HashSet<>();
// int rep = 0;
// for(int x : arr){
// if(set.contains(x))rep++;
// set.add(x);
// }
// return rep == 1;
// }
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();
}
/*-------------------------------------------EDITING CODE ENDS HERE-------------------------------------------*/
/*--------------------------------------HELPER FUNCTIONS STARTS HERE-----------------------------------------*/
// public static int mod = (int) 1e9 + 7;
public static int mod = 998244353;
public static int inf_int = (int) 2e9+10;
public static long inf_long = (long) 2e18;
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);
}
// time : O(1), space : O(1)
public static int _digitCount(long num,int base){
// this will give the # of digits needed for a number num in format : base
return (int)(1 + Math.log(num)/Math.log(base));
}
// time : O(n), space: O(n)
public static long _fact(int n){
// simple factorial calculator
long ans = 1;
for(int i=2;i<=n;i++)
ans = ans * i % mod;
return ans;
}
// time for pre-computation of factorial and inverse-factorial table : O(nlog(mod))
public static long[] factorial , inverseFact;
public static void _ncr_precompute(int n){
factorial = new long[n+1];
inverseFact = new long[n+1];
factorial[0] = inverseFact[0] = 1;
for (int i = 1; i <=n; i++) {
factorial[i] = (factorial[i - 1] * i) % mod;
inverseFact[i] = _modExpo(factorial[i], mod - 2);
}
}
// time of factorial calculation after pre-computation is O(1)
public static int _ncr(int n,int r){
if(r > n)return 0;
return (int)(factorial[n] * inverseFact[r] % mod * inverseFact[n - r] % mod);
}
public static int _npr(int n,int r){
if(r > n)return 0;
return (int)(factorial[n] * inverseFact[n - r] % mod);
}
// euclidean algorithm time O(max (loga ,logb))
public static long _gcd(long a, long b) {
while (a>0){
long x = a;
a = b % a;
b = x;
}
return b;
// if (a == 0)
// return b;
// return _gcd(b % a, a);
}
// lcm(a,b) * gcd(a,b) = a * b
public static long _lcm(long a, long b) {
return (a / _gcd(a, b)) * b;
}
// binary exponentiation time O(logn)
public static long _modExpo(long x, long n) {
long ans = 1;
while (n > 0) {
if ((n & 1) == 1) {
ans *= x;
ans %= mod;
n--;
} else {
x *= x;
x %= mod;
n >>= 1;
}
}
return ans;
}
// function to find a/b under modulo mod. time : O(logn)
public static long _modInv(long a,long b){
return (a * _modExpo(b,mod-2)) % mod;
}
//sieve or first divisor time : O(mx * log ( log (mx) ) )
public static int[] _seive(int mx){
int[] firstDivisor = new int[mx+1];
for(int i=0;i<=mx;i++)firstDivisor[i] = i;
for(int i=2;i*i<=mx;i++)
if(firstDivisor[i] == i)
for(int j = i*i;j<=mx;j+=i)
firstDivisor[j] = i;
return firstDivisor;
}
// check if x is a prime # of not. time : O( n ^ 1/2 )
private static boolean _isPrime(long x){
for(long i=2;i*i<=x;i++)
if(x%i==0)return false;
return true;
}
static class Pair<K, V>{
K ff;
V ss;
public Pair(K ff, V ss) {
this.ff = ff;
this.ss = ss;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || this.getClass() != o.getClass()) return false;
Pair<?, ?> pair = (Pair<?, ?>) o;
return ff.equals(pair.ff) && ss.equals(pair.ss);
}
@Override
public int hashCode() {
return Objects.hash(ff, ss);
}
@Override
public String toString(){
return ff.toString()+" "+ss.toString();
}
}
/*--------------------------------------HELPER FUNCTIONS ENDS HERE-----------------------------------------*/
/*-------------------------------------------FAST INPUT STARTS HERE---------------------------------------------*/
static FastestReader sc;
static PrintWriter out;
private static void openIO() throws IOException {
sc = new FastestReader();
out = new PrintWriter(System.out);
}
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 |
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.HashSet;
import java.util.Scanner;
public class AddingPowers {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t=in.nextInt();
outerloop:
for (int i = 0; i < t; i++) {
int n=in.nextInt();
int k=in.nextInt();
HashSet<Long> hs=new HashSet<>();
long ar[]=new long[n];
for (int j = 0; j < n; j++) {
ar[j]= in.nextLong();
}
for (int j = 0; j < n; j++) {
long x=ar[j];
long c=0;
while (x>0){
if(x%k==0){
c++;
x=x/k;
}
else if(x%k==1){
x--;
if(hs.contains(c)){
System.out.println("NO");
continue outerloop;
}
else{
hs.add(c);
}
}
else{
System.out.println("NO");
continue outerloop;
}
}
}
System.out.println("YES");
}
}
}
| java |
1295 | B | B. Infinite Prefixestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given string ss of length nn consisting of 0-s and 1-s. You build an infinite string tt as a concatenation of an infinite number of strings ss, or t=ssss…t=ssss… For example, if s=s= 10010, then t=t= 100101001010010...Calculate the number of prefixes of tt with balance equal to xx. The balance of some string qq is equal to cnt0,q−cnt1,qcnt0,q−cnt1,q, where cnt0,qcnt0,q is the number of occurrences of 0 in qq, and cnt1,qcnt1,q is the number of occurrences of 1 in qq. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain descriptions of test cases — two lines per test case. The first line contains two integers nn and xx (1≤n≤1051≤n≤105, −109≤x≤109−109≤x≤109) — the length of string ss and the desired balance, respectively.The second line contains the binary string ss (|s|=n|s|=n, si∈{0,1}si∈{0,1}).It's guaranteed that the total sum of nn doesn't exceed 105105.OutputPrint TT integers — one per test case. For each test case print the number of prefixes or −1−1 if there is an infinite number of such prefixes.ExampleInputCopy4
6 10
010010
5 3
10101
1 0
0
2 0
01
OutputCopy3
0
1
-1
NoteIn the first test case; there are 3 good prefixes of tt: with length 2828, 3030 and 3232. | [
"math",
"strings"
] |
import java.util.*;
import javax.print.DocFlavor.INPUT_STREAM;
import java.io.*;
import java.math.*;
import java.sql.Array;
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 void TEST_CASE() throws IOException {
int n = sc.nextInt() , x = sc.nextInt();
char[] temp = sc.next().toCharArray();
int[] arr = new int[n];
for(int i =0 ; i<n ; i++) {
arr[i] = temp[i] - '0';
}
long tot = 0;
for(int e:arr) {
if(e == 0) tot++;
else tot--;
}
if(tot == 0) {
int s = 0;
if(x == 0) {
sb.append("-1\n");
return;
}
for(int i =0 ; i<n;i++) {
if(s == x) {
sb.append("-1\n");
return;
}else {
if(arr[i] == 0) s++;
else s--;
}
if(s== x) {
sb.append("-1\n");
return;
}
}
if(s == x) {
sb.append("-1\n");
return;
}
sb.append("0\n");
return;
}
// System.out.println(tot);
int ans = 0;
if(x == 0) ans++;
long ps = 0;
for(int i= 0 ; i<n ; i++) {
if(arr[i] == 0) ps++;
else ps--;
long rem = x - ps;
long q = rem/tot;
long r = rem%tot;
if(r==0 && q>=0) ans++;
}
sb.append(ans+"\n");
}
}
/*******************************************************************************************************************************************************/
/**
*/
| 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.StringTokenizer;
public class AnotA {
long x1,x2;
long y1,y2;
AnotA(String s){
StringTokenizer st = new StringTokenizer(s);
this.x1 =Integer.parseInt(st.nextToken());
this.y1 =Integer.parseInt(st.nextToken());
this.x2 =Integer.parseInt(st.nextToken());
this.y2 =Integer.parseInt(st.nextToken());
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
for(int i=0; i<n; i++) {
AnotA a = new AnotA(br.readLine());
AnotA b = new AnotA(br.readLine());
AnotA c = new AnotA(br.readLine());
System.out.println(checkConstraints(a,b,c)||checkConstraints(b,c,a)||checkConstraints(c,a,b)?"YES":"NO");
}
}
//took professors code as reference
private static boolean checkIntersection(long x, long y, AnotA a) {
//check if the point is lying outside the segment
if(x<Math.min(a.x1, a.x2)||x>Math.max(a.x1, a.x2)||y<Math.min(a.y1, a.y2)||y>Math.max(a.y1, a.y2))
return false;
//check ratio between parts
int xpart = (int) Math.abs(a.x1-a.x2);
int ypart = (int) Math.abs(a.y1-a.y2);
int xmin = (int) Math.min(Math.abs(a.x1-x), Math.abs(a.x2-x));
int ymin = (int) Math.min(Math.abs(a.y1-y), Math.abs(a.y2-y));
return xpart<=5*xmin&&ypart<=5*ymin&& (long) (x-a.x2)*(a.y1-a.y2)==(long)(y-a.y2)*(a.x1-a.x2);
}
public static boolean checkConstraints(AnotA a, AnotA b, AnotA c) {
if(a.x1==b.x1&&a.y1==b.y1) {
return getAngle(a.x2,a.y2,b.x2,b.y2,a.x1,a.y1)&&(
checkIntersection(c.x1, c.y1,a)&&checkIntersection(c.x2, c.y2,b)||
checkIntersection(c.x2, c.y2,a)&&checkIntersection(c.x1, c.y1,b));
}
if(a.x2==b.x1&&a.y2==b.y1) {
return getAngle(a.x1, a.y1, b.x2, b.y2, a.x2, a.y2)&&(
checkIntersection(c.x1, c.y1,a)&&checkIntersection(c.x2, c.y2,b)||
checkIntersection(c.x2, c.y2,a)&&checkIntersection(c.x1, c.y1,b));
}
if(a.x1==b.x2&&a.y1==b.y2) {
return getAngle(a.x2, a.y2, b.x1, b.y1, a.x1, a.y1)&&(
checkIntersection(c.x1, c.y1,a)&&checkIntersection(c.x2, c.y2,b)||
checkIntersection(c.x2, c.y2,a)&&checkIntersection(c.x1, c.y1,b));
}
if(a.x2==b.x2&&a.y2==b.y2) {
return getAngle(a.x1, a.y1, b.x1, b.y1, a.x2, a.y2)&&(
checkIntersection(c.x1, c.y1,a)&&checkIntersection(c.x2, c.y2,b)||
checkIntersection(c.x2, c.y2,a)&&checkIntersection(c.x1, c.y1,b));
}
return false;
}
public static boolean getAngle(long x1, long y1, long x2, long y2, long x3, long y3) {
boolean collinear =areCollinear( x1, y1, x2, y2, x3, y3);
//check angle <= 90
long a13 = (long) (x1-x3) * (x1-x3) + (long) (y1-y3) *(y1-y3);
long a23 = (long) (x2-x3) * (x2-x3) + (long) (y2-y3) *(y2-y3);
long a12 = (long) (x1-x2) * (x1-x2) + (long) (y1-y2) *(y1-y2);
return !collinear&&a13+a23>=a12;
}
private static boolean areCollinear(long x1, long y1, long x2, long y2, long x3, long y3) {
long area = (long) (x1-x3)*(y2-y3) - (long) (x2-x3)*(y1-y3);
return area==0?true:false;
}
public static long dotProduct(long x1, long y1, long x2, long y2)
{
return x1*x2+y1*y2;
}
} | java |
1304 | E | E. 1-Trees and Queriestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGildong was hiking a mountain; walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.First, he'll provide you a tree (not 1-tree) with nn vertices, then he will ask you qq queries. Each query contains 55 integers: xx, yy, aa, bb, and kk. This means you're asked to determine if there exists a path from vertex aa to bb that contains exactly kk edges after adding a bidirectional edge between vertices xx and yy. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.InputThe first line contains an integer nn (3≤n≤1053≤n≤105), the number of vertices of the tree.Next n−1n−1 lines contain two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) each, which means there is an edge between vertex uu and vv. All edges are bidirectional and distinct.Next line contains an integer qq (1≤q≤1051≤q≤105), the number of queries Gildong wants to ask.Next qq lines contain five integers xx, yy, aa, bb, and kk each (1≤x,y,a,b≤n1≤x,y,a,b≤n, x≠yx≠y, 1≤k≤1091≤k≤109) – the integers explained in the description. It is guaranteed that the edge between xx and yy does not exist in the original tree.OutputFor each query, print "YES" if there exists a path that contains exactly kk edges from vertex aa to bb after adding an edge between vertices xx and yy. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy5
1 2
2 3
3 4
4 5
5
1 3 1 2 2
1 4 1 3 2
1 4 1 3 3
4 2 3 3 9
5 2 3 3 9
OutputCopyYES
YES
NO
YES
NO
NoteThe image below describes the tree (circles and solid lines) and the added edges for each query (dotted lines). Possible paths for the queries with "YES" answers are: 11-st query: 11 – 33 – 22 22-nd query: 11 – 22 – 33 44-th query: 33 – 44 – 22 – 33 – 44 – 22 – 33 – 44 – 22 – 33 | [
"data structures",
"dfs and similar",
"shortest paths",
"trees"
] | import java.io.*;
import java.util.*;
public class Main {
static int[] depth;
static int[][] table;
static ArrayList<Integer>[] tree;
static void dfs(int curr,int p) {
table[curr][0]=p;
for (int i=1;i<18;i++) {
table[curr][i]=table[table[curr][i-1]][i-1];
}
for(int child:tree[curr]) {
if(child!=p) {
depth[child]=1+depth[curr];
dfs(child,curr);
}
}
}
static int lca(int u, int v)
{
if(depth[u]<depth[v]) {
int temp=u;
u=v;
v=temp;
}
for (int i=17;i>-1;i--) {
if ((depth[u]-(int)Math.pow(2, i))>=depth[v]) {
u=table[u][i];
}
}
if (u==v) {
return u;
}
for(int i=17;i>-1;i--) {
if (table[u][i]!=table[v][i]) {
u=table[u][i];
v=table[v][i];
}
}
return table[u][0];
}
static int dist(int a, int b) {
int c = lca(a, b);
int ans = depth[a] + depth[b] - 2*depth[c];
return ans;
}
public static void main(String[] args) throws IOException
{
FastScanner f = new FastScanner();
int ttt=1;
// ttt=f.nextInt();
PrintWriter out=new PrintWriter(System.out);
for(int tt=0;tt<ttt;tt++) {
int n=f.nextInt();
tree=new ArrayList[n];
depth=new int[n];
table=new int[n][19];
for(int i=0;i<n;i++) tree[i]=new ArrayList<>();
for(int i=0;i<n-1;i++) {
int u=f.nextInt()-1;
int v=f.nextInt()-1;
tree[u].add(v);
tree[v].add(u);
}
dfs(0,0);
int q=f.nextInt();
for(int i=0;i<q;i++) {
int x=f.nextInt()-1;
int y=f.nextInt()-1;
int a=f.nextInt()-1;
int b=f.nextInt()-1;
int k=f.nextInt();
int d1 = dist(a, b);
int d2 = dist(a, x) + 1 + dist(y, b);
int d3 = dist(a, y) + 1 + dist(x, b);
boolean w1 = d1 <= k && d1 % 2 == k % 2;
boolean w2 = d2 <= k && d2 % 2 == k % 2;
boolean w3 = d3 <= k && d3 % 2 == k % 2;
if (w1 || w2 || w3) {
out.println("YES");
} else {
out.println("NO");
}
}
}
out.close();
}
static void sort(int[] p) {
ArrayList<Integer> q = new ArrayList<>();
for (int i: p) q.add( 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;
}
}
} | java |
1296 | A | A. Array with Odd Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.In one move, you can choose two indices 1≤i,j≤n1≤i,j≤n such that i≠ji≠j and set ai:=ajai:=aj. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose ii and jj and replace aiai with ajaj).Your task is to say if it is possible to obtain an array with an odd (not divisible by 22) sum of elements.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤20001≤t≤2000) — 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≤20001≤n≤2000) — the number of elements in aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤20001≤ai≤2000), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 20002000 (∑n≤2000∑n≤2000).OutputFor each test case, print the answer on it — "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise.ExampleInputCopy5
2
2 3
4
2 2 8 8
3
3 3 3
4
5 5 5 5
4
1 1 1 1
OutputCopyYES
NO
YES
NO
NO
| [
"math"
] | import java.util.Scanner;
public class Maths_5 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0){
int n=sc.nextInt();
int odd=0,even=0;
for(int i=0;i<n;i++){
int x=sc.nextInt();
if((x&1)==0)
even++;
else
odd++;
}
if((odd&1)==1)
System.out.println("YES");
else{
if(odd>=1&&even>=1)
System.out.println("YES");
else
System.out.println("NO");
}
}
}
}
| 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 java.util.*;
public class Main{
static long gcd(long a, long b){
if(a%b==0) return b;
return gcd(b, a%b);
}
public static void main(String []args){
Scanner sc = new Scanner(System.in);
long x = sc.nextLong();
long a = 1;
for(long i=1; i*i<=x; i++){
if(x%i==0&&gcd(i,x/i)==1) a = i;
}
System.out.println(a+ " "+ (x/a));
}
} | 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.*;
/**
*
* @author eslam
*/
public class IceCave {
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(problemName + ".out");
r = new BufferedReader(new FileReader(problemName + ".in"));
}
// returns null if no more input
String nextLine() {
String str = "";
try {
str = r.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
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());
}
}
// Beginning of the solution
static Kattio input = new Kattio();
static BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out));
static ArrayList<ArrayList<Long>> powerSet = new ArrayList<>();
static long mod = (long) (Math.pow(10, 9) + 7);
static int dp[][];
static boolean visited[];
static int answ[];
static int ans = 0;
public static void main(String[] args) throws IOException {
long h = input.nextLong();
int n = input.nextInt();
long a[] = new long[n];
long min = Long.MAX_VALUE;
boolean ca = false;
for (int i = 0; i < n; i++) {
a[i] = input.nextLong();
}
prefixSum(a);
for (int i = 0; i < n; i++) {
long d = h + a[i];
if (d <= 0) {
log.write(i + 1 + "\n");
log.flush();
return;
} else if (a[n - 1] < 0) {
long t = i + 1;
long v = d / Math.abs(a[n - 1]) + (d % Math.abs(a[n - 1]) != 0 ? 1 : 0);
v *= n;
t += v;
min = Math.min(t, min);
} else {
ca = true;
}
}
if (ca) {
log.write("-1\n");
} else {
log.write(min + "\n");
}
log.flush();
}
public static void getAns(ArrayList<Integer> a[], int node, int an) {
visited[node] = true;
ArrayList<Integer> nod = new ArrayList<>();
for (Integer x : a[node]) {
if (!visited[x]) {
nod.add(x);
}
}
if (nod.size() == 2) {
int cost = answ[nod.get(1)];
getAns(a, nod.get(0), an + cost);
cost = answ[nod.get(0)];
getAns(a, nod.get(1), an + cost);
} else if (nod.size() == 1) {
an += answ[nod.get(0)];
ans = Math.max(ans, an);
} else {
ans = Math.max(ans, an);
}
}
public static int logK(long v, long k) {
int ans = 0;
while (v > 1) {
ans++;
v /= k;
}
return ans;
}
public static void dfs(ArrayList<Integer> a[], int node) {
visited[node] = true;
for (Integer x : a[node]) {
if (!visited[x]) {
dfs(a, x);
answ[node] += answ[x];
}
}
answ[node] += a[node].size() - 1;
}
public static long power(long a, long n) {
if (n == 1) {
return a;
}
long pow = power(a, n / 2);
pow *= pow;
if (n % 2 != 0) {
pow *= a;
}
return pow;
}
public static long get(long max, long x) {
if (x == 1) {
return max;
}
int cnt = 0;
while (max > 0) {
cnt++;
max /= x;
}
return cnt;
}
public static int numOF1(long v) {
long x = 1;
int cnt = 0;
while (x <= v) {
if ((x & v) != 0) {
cnt++;
}
x *= 2;
}
return cnt;
}
public static int log2(long n) {
int cnt = 0;
while (n > 1) {
n /= 2;
cnt++;
}
return cnt;
}
public static int[] bfs(int node, ArrayList<Integer> a[]) {
Queue<Integer> q = new LinkedList<>();
q.add(node);
int distances[] = new int[a.length];
Arrays.fill(distances, -1);
distances[node] = 0;
while (!q.isEmpty()) {
int parent = q.poll();
ArrayList<Integer> nodes = a[parent];
int cost = distances[parent];
for (Integer node1 : nodes) {
if (distances[node1] == -1) {
q.add(node1);
distances[node1] = cost + 1;
}
}
}
return distances;
}
public static int get(int n) {
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
return sum;
}
public static ArrayList<Integer> primeFactors(int n) {
ArrayList<Integer> a = new ArrayList<>();
while (n % 2 == 0) {
a.add(2);
n /= 2;
}
for (int i = 3; i <= Math.sqrt(n); i += 2) {
while (n % i == 0) {
a.add(i);
n /= i;
}
if (n < i) {
break;
}
}
if (n > 2) {
a.add(n);
}
return a;
}
public static ArrayList<Integer> printPrimeFactoriztion(int n) {
ArrayList<Integer> a = new ArrayList<>();
for (int i = 1; i < Math.sqrt(n) + 1; i++) {
if (n % i == 0) {
if (isPrime(i)) {
a.add(i);
n /= i;
i = 0;
} else if (isPrime(n / i)) {
a.add(n / i);
n = i;
i = 0;
}
}
}
return a;
}
// end of solution
public static void genrate(int ind, long[] a, ArrayList<Long> sub) {
if (ind == a.length) {
powerSet.add(sub);
return;
}
ArrayList<Long> have = new ArrayList<>();
ArrayList<Long> less = new ArrayList<>();
for (int i = 0; i < sub.size(); i++) {
have.add(sub.get(i));
less.add(sub.get(i));
}
have.add(a[ind]);
genrate(ind + 1, a, have);
genrate(ind + 1, a, less);
}
public static long factorial(long n) {
if (n <= 1) {
return 1;
}
long t = n - 1;
while (t > 1) {
n *= t;
t--;
}
return n;
}
public static int rev(int n) {
int t = n;
int ans = 0;
while (t > 0) {
ans = ans * 10 + t % 10;
t /= 10;
}
return ans;
}
public static boolean isPalindrome(int n) {
int t = n;
int ans = 0;
while (t > 0) {
ans = ans * 10 + t % 10;
t /= 10;
}
return ans == n;
}
static class tri {
int x, y, z;
public tri(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
}
static boolean isPrime(long num) {
if (num == 1) {
return false;
}
if (num == 2) {
return true;
}
if (num % 2 == 0) {
return false;
}
if (num == 3) {
return true;
}
for (int i = 3; i <= Math.sqrt(num) + 1; i += 2) {
if (num % i == 0) {
return false;
}
}
return true;
}
public static void prefixSum(long[] a) {
for (int i = 1; i < a.length; i++) {
a[i] = a[i] + a[i - 1];
}
}
public static void suffixSum(long[] a) {
for (int i = a.length - 2; i > -1; i--) {
a[i] = a[i] + a[i + 1];
}
}
static long mod(long a, long b) {
long r = a % b;
return r < 0 ? r + b : r;
}
public static long binaryToDecimal(String w) {
long r = 0;
long l = 0;
for (int i = w.length() - 1; i > -1; i--) {
long x = (w.charAt(i) - '0') * (long) Math.pow(2, l);
r = r + x;
l++;
}
return r;
}
public static String decimalToBinary(long n) {
String w = "";
while (n > 0) {
w = n % 2 + w;
n /= 2;
}
return w;
}
public static boolean isSorted(int[] a) {
for (int i = 0; i < a.length - 1; i++) {
if (a[i] > a[i + 1]) {
return false;
}
}
return true;
}
public static void print(int a[]) throws IOException {
for (int i = 0; i < a.length; i++) {
log.write(a[i] + " ");
}
log.write("\n");
}
public static void read(int[] a) {
for (int i = 0; i < a.length; i++) {
a[i] = input.nextInt();
}
}
static class pair {
long x;
long y;
public pair(long x, long y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return x + " " + y;
}
}
public static long LCM(long x, long y) {
return x / GCD(x, y) * y;
}
public static long GCD(long x, long y) {
if (y == 0) {
return x;
}
return GCD(y, x % y);
}
public static void simplifyTheFraction(long a, long b) {
long GCD = GCD(a, b);
System.out.println(a / GCD + " " + b / GCD);
}
/**
*/ // class RedBlackNode
static class RedBlackNode<T extends Comparable<T>> {
/**
* Possible color for this node
*/
public static final int BLACK = 0;
/**
* Possible color for this node
*/
public static final int RED = 1;
// the key of each node
public T key;
/**
* Parent of node
*/
RedBlackNode<T> parent;
/**
* Left child
*/
RedBlackNode<T> left;
/**
* Right child
*/
RedBlackNode<T> right;
// the number of elements to the left of each node
public int numLeft = 0;
// the number of elements to the right of each node
public int numRight = 0;
// the color of a node
public int color;
RedBlackNode() {
color = BLACK;
numLeft = 0;
numRight = 0;
parent = null;
left = null;
right = null;
}
// Constructor which sets key to the argument.
RedBlackNode(T key) {
this();
this.key = key;
}
}// end class RedBlackNode
static class RedBlackTree<T extends Comparable<T>> {
// Root initialized to nil.
private RedBlackNode<T> nil = new RedBlackNode<T>();
private RedBlackNode<T> root = nil;
public RedBlackTree() {
root.left = nil;
root.right = nil;
root.parent = nil;
}
// @param: X, The node which the lefRotate is to be performed on.
// Performs a leftRotate around X.
private void leftRotate(RedBlackNode<T> x) {
// Call leftRotateFixup() which updates the numLeft
// and numRight values.
leftRotateFixup(x);
// Perform the left rotate as described in the algorithm
// in the course text.
RedBlackNode<T> y;
y = x.right;
x.right = y.left;
// Check for existence of y.left and make pointer changes
if (!isNil(y.left)) {
y.left.parent = x;
}
y.parent = x.parent;
// X's parent is nul
if (isNil(x.parent)) {
root = y;
} // X is the left child of it's parent
else if (x.parent.left == x) {
x.parent.left = y;
} // X is the right child of it's parent.
else {
x.parent.right = y;
}
// Finish of the leftRotate
y.left = x;
x.parent = y;
}// end leftRotate(RedBlackNode X)
// @param: X, The node which the leftRotate is to be performed on.
// Updates the numLeft & numRight values affected by leftRotate.
private void leftRotateFixup(RedBlackNode x) {
// Case 1: Only X, X.right and X.right.right always are not nil.
if (isNil(x.left) && isNil(x.right.left)) {
x.numLeft = 0;
x.numRight = 0;
x.right.numLeft = 1;
} // Case 2: X.right.left also exists in addition to Case 1
else if (isNil(x.left) && !isNil(x.right.left)) {
x.numLeft = 0;
x.numRight = 1 + x.right.left.numLeft
+ x.right.left.numRight;
x.right.numLeft = 2 + x.right.left.numLeft
+ x.right.left.numRight;
} // Case 3: X.left also exists in addition to Case 1
else if (!isNil(x.left) && isNil(x.right.left)) {
x.numRight = 0;
x.right.numLeft = 2 + x.left.numLeft + x.left.numRight;
} // Case 4: X.left and X.right.left both exist in addtion to Case 1
else {
x.numRight = 1 + x.right.left.numLeft
+ x.right.left.numRight;
x.right.numLeft = 3 + x.left.numLeft + x.left.numRight
+ x.right.left.numLeft + x.right.left.numRight;
}
}// end leftRotateFixup(RedBlackNode X)
// @param: X, The node which the rightRotate is to be performed on.
// Updates the numLeft and numRight values affected by the Rotate.
private void rightRotate(RedBlackNode<T> y) {
// Call rightRotateFixup to adjust numRight and numLeft values
rightRotateFixup(y);
// Perform the rotate as described in the course text.
RedBlackNode<T> x = y.left;
y.left = x.right;
// Check for existence of X.right
if (!isNil(x.right)) {
x.right.parent = y;
}
x.parent = y.parent;
// y.parent is nil
if (isNil(y.parent)) {
root = x;
} // y is a right child of it's parent.
else if (y.parent.right == y) {
y.parent.right = x;
} // y is a left child of it's parent.
else {
y.parent.left = x;
}
x.right = y;
y.parent = x;
}// end rightRotate(RedBlackNode y)
// @param: y, the node around which the righRotate is to be performed.
// Updates the numLeft and numRight values affected by the rotate
private void rightRotateFixup(RedBlackNode y) {
// Case 1: Only y, y.left and y.left.left exists.
if (isNil(y.right) && isNil(y.left.right)) {
y.numRight = 0;
y.numLeft = 0;
y.left.numRight = 1;
} // Case 2: y.left.right also exists in addition to Case 1
else if (isNil(y.right) && !isNil(y.left.right)) {
y.numRight = 0;
y.numLeft = 1 + y.left.right.numRight
+ y.left.right.numLeft;
y.left.numRight = 2 + y.left.right.numRight
+ y.left.right.numLeft;
} // Case 3: y.right also exists in addition to Case 1
else if (!isNil(y.right) && isNil(y.left.right)) {
y.numLeft = 0;
y.left.numRight = 2 + y.right.numRight + y.right.numLeft;
} // Case 4: y.right & y.left.right exist in addition to Case 1
else {
y.numLeft = 1 + y.left.right.numRight
+ y.left.right.numLeft;
y.left.numRight = 3 + y.right.numRight
+ y.right.numLeft
+ y.left.right.numRight + y.left.right.numLeft;
}
}// end rightRotateFixup(RedBlackNode y)
public void insert(T key) {
insert(new RedBlackNode<T>(key));
}
// @param: z, the node to be inserted into the Tree rooted at root
// Inserts z into the appropriate position in the RedBlackTree while
// updating numLeft and numRight values.
private void insert(RedBlackNode<T> z) {
// Create a reference to root & initialize a node to nil
RedBlackNode<T> y = nil;
RedBlackNode<T> x = root;
// While we haven't reached a the end of the tree keep
// tryint to figure out where z should go
while (!isNil(x)) {
y = x;
// if z.key is < than the current key, go left
if (z.key.compareTo(x.key) < 0) {
// Update X.numLeft as z is < than X
x.numLeft++;
x = x.left;
} // else z.key >= X.key so go right.
else {
// Update X.numGreater as z is => X
x.numRight++;
x = x.right;
}
}
// y will hold z's parent
z.parent = y;
// Depending on the value of y.key, put z as the left or
// right child of y
if (isNil(y)) {
root = z;
} else if (z.key.compareTo(y.key) < 0) {
y.left = z;
} else {
y.right = z;
}
// Initialize z's children to nil and z's color to red
z.left = nil;
z.right = nil;
z.color = RedBlackNode.RED;
// Call insertFixup(z)
insertFixup(z);
}// end insert(RedBlackNode z)
// @param: z, the node which was inserted and may have caused a violation
// of the RedBlackTree properties
// Fixes up the violation of the RedBlackTree properties that may have
// been caused during insert(z)
private void insertFixup(RedBlackNode<T> z) {
RedBlackNode<T> y = nil;
// While there is a violation of the RedBlackTree properties..
while (z.parent.color == RedBlackNode.RED) {
// If z's parent is the the left child of it's parent.
if (z.parent == z.parent.parent.left) {
// Initialize y to z 's cousin
y = z.parent.parent.right;
// Case 1: if y is red...recolor
if (y.color == RedBlackNode.RED) {
z.parent.color = RedBlackNode.BLACK;
y.color = RedBlackNode.BLACK;
z.parent.parent.color = RedBlackNode.RED;
z = z.parent.parent;
} // Case 2: if y is black & z is a right child
else if (z == z.parent.right) {
// leftRotaet around z's parent
z = z.parent;
leftRotate(z);
} // Case 3: else y is black & z is a left child
else {
// recolor and rotate round z's grandpa
z.parent.color = RedBlackNode.BLACK;
z.parent.parent.color = RedBlackNode.RED;
rightRotate(z.parent.parent);
}
} // If z's parent is the right child of it's parent.
else {
// Initialize y to z's cousin
y = z.parent.parent.left;
// Case 1: if y is red...recolor
if (y.color == RedBlackNode.RED) {
z.parent.color = RedBlackNode.BLACK;
y.color = RedBlackNode.BLACK;
z.parent.parent.color = RedBlackNode.RED;
z = z.parent.parent;
} // Case 2: if y is black and z is a left child
else if (z == z.parent.left) {
// rightRotate around z's parent
z = z.parent;
rightRotate(z);
} // Case 3: if y is black and z is a right child
else {
// recolor and rotate around z's grandpa
z.parent.color = RedBlackNode.BLACK;
z.parent.parent.color = RedBlackNode.RED;
leftRotate(z.parent.parent);
}
}
}
// Color root black at all times
root.color = RedBlackNode.BLACK;
}// end insertFixup(RedBlackNode z)
// @param: node, a RedBlackNode
// @param: node, the node with the smallest key rooted at node
public RedBlackNode<T> treeMinimum(RedBlackNode<T> node) {
// while there is a smaller key, keep going left
while (!isNil(node.left)) {
node = node.left;
}
return node;
}// end treeMinimum(RedBlackNode node)
// @param: X, a RedBlackNode whose successor we must find
// @return: return's the node the with the next largest key
// from X.key
public RedBlackNode<T> treeSuccessor(RedBlackNode<T> x) {
// if X.left is not nil, call treeMinimum(X.right) and
// return it's value
if (!isNil(x.left)) {
return treeMinimum(x.right);
}
RedBlackNode<T> y = x.parent;
// while X is it's parent's right child...
while (!isNil(y) && x == y.right) {
// Keep moving up in the tree
x = y;
y = y.parent;
}
// Return successor
return y;
}// end treeMinimum(RedBlackNode X)
// @param: z, the RedBlackNode which is to be removed from the the tree
// Remove's z from the RedBlackTree rooted at root
public void remove(RedBlackNode<T> v) {
RedBlackNode<T> z = search(v.key);
// Declare variables
RedBlackNode<T> x = nil;
RedBlackNode<T> y = nil;
// if either one of z's children is nil, then we must remove z
if (isNil(z.left) || isNil(z.right)) {
y = z;
} // else we must remove the successor of z
else {
y = treeSuccessor(z);
}
// Let X be the left or right child of y (y can only have one child)
if (!isNil(y.left)) {
x = y.left;
} else {
x = y.right;
}
// link X's parent to y's parent
x.parent = y.parent;
// If y's parent is nil, then X is the root
if (isNil(y.parent)) {
root = x;
} // else if y is a left child, set X to be y's left sibling
else if (!isNil(y.parent.left) && y.parent.left == y) {
y.parent.left = x;
} // else if y is a right child, set X to be y's right sibling
else if (!isNil(y.parent.right) && y.parent.right == y) {
y.parent.right = x;
}
// if y != z, trasfer y's satellite data into z.
if (y != z) {
z.key = y.key;
}
// Update the numLeft and numRight numbers which might need
// updating due to the deletion of z.key.
fixNodeData(x, y);
// If y's color is black, it is a violation of the
// RedBlackTree properties so call removeFixup()
if (y.color == RedBlackNode.BLACK) {
removeFixup(x);
}
}// end remove(RedBlackNode z)
// @param: y, the RedBlackNode which was actually deleted from the tree
// @param: key, the value of the key that used to be in y
private void fixNodeData(RedBlackNode<T> x, RedBlackNode<T> y) {
// Initialize two variables which will help us traverse the tree
RedBlackNode<T> current = nil;
RedBlackNode<T> track = nil;
// if X is nil, then we will start updating at y.parent
// Set track to y, y.parent's child
if (isNil(x)) {
current = y.parent;
track = y;
} // if X is not nil, then we start updating at X.parent
// Set track to X, X.parent's child
else {
current = x.parent;
track = x;
}
// while we haven't reached the root
while (!isNil(current)) {
// if the node we deleted has a different key than
// the current node
if (y.key != current.key) {
// if the node we deleted is greater than
// current.key then decrement current.numRight
if (y.key.compareTo(current.key) > 0) {
current.numRight--;
}
// if the node we deleted is less than
// current.key thendecrement current.numLeft
if (y.key.compareTo(current.key) < 0) {
current.numLeft--;
}
} // if the node we deleted has the same key as the
// current node we are checking
else {
// the cases where the current node has any nil
// children and update appropriately
if (isNil(current.left)) {
current.numLeft--;
} else if (isNil(current.right)) {
current.numRight--;
} // the cases where current has two children and
// we must determine whether track is it's left
// or right child and update appropriately
else if (track == current.right) {
current.numRight--;
} else if (track == current.left) {
current.numLeft--;
}
}
// update track and current
track = current;
current = current.parent;
}
}//end fixNodeData()
// @param: X, the child of the deleted node from remove(RedBlackNode v)
// Restores the Red Black properties that may have been violated during
// the removal of a node in remove(RedBlackNode v)
private void removeFixup(RedBlackNode<T> x) {
RedBlackNode<T> w;
// While we haven't fixed the tree completely...
while (x != root && x.color == RedBlackNode.BLACK) {
// if X is it's parent's left child
if (x == x.parent.left) {
// set w = X's sibling
w = x.parent.right;
// Case 1, w's color is red.
if (w.color == RedBlackNode.RED) {
w.color = RedBlackNode.BLACK;
x.parent.color = RedBlackNode.RED;
leftRotate(x.parent);
w = x.parent.right;
}
// Case 2, both of w's children are black
if (w.left.color == RedBlackNode.BLACK
&& w.right.color == RedBlackNode.BLACK) {
w.color = RedBlackNode.RED;
x = x.parent;
} // Case 3 / Case 4
else {
// Case 3, w's right child is black
if (w.right.color == RedBlackNode.BLACK) {
w.left.color = RedBlackNode.BLACK;
w.color = RedBlackNode.RED;
rightRotate(w);
w = x.parent.right;
}
// Case 4, w = black, w.right = red
w.color = x.parent.color;
x.parent.color = RedBlackNode.BLACK;
w.right.color = RedBlackNode.BLACK;
leftRotate(x.parent);
x = root;
}
} // if X is it's parent's right child
else {
// set w to X's sibling
w = x.parent.left;
// Case 1, w's color is red
if (w.color == RedBlackNode.RED) {
w.color = RedBlackNode.BLACK;
x.parent.color = RedBlackNode.RED;
rightRotate(x.parent);
w = x.parent.left;
}
// Case 2, both of w's children are black
if (w.right.color == RedBlackNode.BLACK
&& w.left.color == RedBlackNode.BLACK) {
w.color = RedBlackNode.RED;
x = x.parent;
} // Case 3 / Case 4
else {
// Case 3, w's left child is black
if (w.left.color == RedBlackNode.BLACK) {
w.right.color = RedBlackNode.BLACK;
w.color = RedBlackNode.RED;
leftRotate(w);
w = x.parent.left;
}
// Case 4, w = black, and w.left = red
w.color = x.parent.color;
x.parent.color = RedBlackNode.BLACK;
w.left.color = RedBlackNode.BLACK;
rightRotate(x.parent);
x = root;
}
}
}// end while
// set X to black to ensure there is no violation of
// RedBlack tree Properties
x.color = RedBlackNode.BLACK;
}// end removeFixup(RedBlackNode X)
// @param: key, the key whose node we want to search for
// @return: returns a node with the key, key, if not found, returns null
// Searches for a node with key k and returns the first such node, if no
// such node is found returns null
public RedBlackNode<T> search(T key) {
// Initialize a pointer to the root to traverse the tree
RedBlackNode<T> current = root;
// While we haven't reached the end of the tree
while (!isNil(current)) {
// If we have found a node with a key equal to key
if (current.key.equals(key)) // return that node and exit search(int)
{
return current;
} // go left or right based on value of current and key
else if (current.key.compareTo(key) < 0) {
current = current.right;
} // go left or right based on value of current and key
else {
current = current.left;
}
}
// we have not found a node whose key is "key"
return null;
}// end search(int key)
// @param: key, any Comparable object
// @return: return's the number of elements greater than key
public int numGreater(T key) {
// Call findNumGreater(root, key) which will return the number
// of nodes whose key is greater than key
return findNumGreater(root, key);
}// end numGreater(int key)
// @param: key, any Comparable object
// @return: return's teh number of elements smaller than key
public int numSmaller(T key) {
// Call findNumSmaller(root,key) which will return
// the number of nodes whose key is greater than key
return findNumSmaller(root, key);
}// end numSmaller(int key)
// @param: node, the root of the tree, the key who we must
// compare other node key's to.
// @return: the number of nodes greater than key.
public int findNumGreater(RedBlackNode<T> node, T key) {
// Base Case: if node is nil, return 0
if (isNil(node)) {
return 0;
} // If key is less than node.key, all elements right of node are
// greater than key, add this to our total and look to the left
else if (key.compareTo(node.key) < 0) {
return 1 + node.numRight + findNumGreater(node.left, key);
} // If key is greater than node.key, then look to the right as
// all elements to the left of node are smaller than key
else {
return findNumGreater(node.right, key);
}
}// end findNumGreater(RedBlackNode, int key)
/**
* Returns sorted list of keys greater than key. Size of list will not
* exceed maxReturned
*
* @param key Key to search for
* @param maxReturned Maximum number of results to return
* @return List of keys greater than key. List may not exceed
* maxReturned
*/
public List<T> getGreaterThan(T key, Integer maxReturned) {
List<T> list = new ArrayList<T>();
getGreaterThan(root, key, list);
return list.subList(0, Math.min(maxReturned, list.size()));
}
private void getGreaterThan(RedBlackNode<T> node, T key,
List<T> list) {
if (isNil(node)) {
return;
} else if (node.key.compareTo(key) > 0) {
getGreaterThan(node.left, key, list);
list.add(node.key);
getGreaterThan(node.right, key, list);
} else {
getGreaterThan(node.right, key, list);
}
}
// @param: node, the root of the tree, the key who we must compare other
// node key's to.
// @return: the number of nodes smaller than key.
public int findNumSmaller(RedBlackNode<T> node, T key) {
// Base Case: if node is nil, return 0
if (isNil(node)) {
return 0;
} // If key is less than node.key, look to the left as all
// elements on the right of node are greater than key
else if (key.compareTo(node.key) <= 0) {
return findNumSmaller(node.left, key);
} // If key is larger than node.key, all elements to the left of
// node are smaller than key, add this to our total and look
// to the right.
else {
return 1 + node.numLeft + findNumSmaller(node.right, key);
}
}// end findNumSmaller(RedBlackNode nod, int key)
// @param: node, the RedBlackNode we must check to see whether it's nil
// @return: return's true of node is nil and false otherwise
private boolean isNil(RedBlackNode node) {
// return appropriate value
return node == nil;
}// end isNil(RedBlackNode node)
// @return: return's the size of the tree
// Return's the # of nodes including the root which the RedBlackTree
// rooted at root has.
public int size() {
// Return the number of nodes to the root's left + the number of
// nodes on the root's right + the root itself.
return root.numLeft + root.numRight + 1;
}// end size()
}// end class RedBlackTree
}
| java |
1311 | E | E. Construct the Binary Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and dd. You need to construct a rooted binary tree consisting of nn vertices with a root at the vertex 11 and the sum of depths of all vertices equals to dd.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex vv is the last different from vv vertex on the path from the root to the vertex vv. The depth of the vertex vv is the length of the path from the root to the vertex vv. Children of vertex vv are all vertices for which vv is the parent. The binary tree is such a tree that no vertex has more than 22 children.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The only line of each test case contains two integers nn and dd (2≤n,d≤50002≤n,d≤5000) — the number of vertices in the tree and the required sum of depths of all vertices.It is guaranteed that the sum of nn and the sum of dd both does not exceed 50005000 (∑n≤5000,∑d≤5000∑n≤5000,∑d≤5000).OutputFor each test case, print the answer.If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print n−1n−1 integers p2,p3,…,pnp2,p3,…,pn in the second line, where pipi is the parent of the vertex ii. Note that the sequence of parents you print should describe some binary tree.ExampleInputCopy3
5 7
10 19
10 18
OutputCopyYES
1 2 1 3
YES
1 2 3 3 9 9 2 1 6
NO
NotePictures corresponding to the first and the second test cases of the example: | [
"brute force",
"constructive algorithms",
"trees"
] | // package c1311;
//
// Codeforces Round #624 (Div. 3) 2020-02-24 06:35
// E. Construct the Binary Tree
// https://codeforces.com/contest/1311/problem/E
// 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+).*'
//
// You are given two integers n and d. You need to construct a rooted binary tree consisting of n
// vertices with a root at the vertex 1 and the sum of depths of all vertices equals to d.
//
// A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A
// parent of a vertex v is the last different from v vertex on the path from the root to the vertex
// v. The depth of the vertex v is the length of the path from the root to the vertex v. Children of
// vertex v are all vertices for which v is the parent. The binary tree is such a tree that no
// vertex has more than 2 children.
//
// You have to answer t independent test cases.
//
// Input
//
// The first line of the input contains one integer t (1 <= t <= 1000) -- the number of test cases.
//
// The only line of each test case contains two integers n and d (2 <= n, d <= 5000) -- the number
// of vertices in the tree and the required sum of depths of all vertices.
//
// It is guaranteed that the sum of n and the sum of d both does not exceed 5000 (\sum n <= 5000,
// \sum d <= 5000).
//
// Output
//
// For each test case, print the answer.
//
// If it is impossible to construct such a tree, print "NO" (without quotes) in the first line.
// Otherwise, print "{YES}" in the first line. Then print n-1 integers p_2, p_3, ..., p_n in the
// second line, where p_i is the parent of the vertex i. Note that the sequence of parents you print
// should describe some binary tree.
//
// Example
/*
input:
3
5 7
10 19
10 18
output:
YES
1 2 1 3
YES
1 2 3 3 9 9 2 1 6
NO
*/
// Note
//
// Pictures corresponding to the first and the second test cases of the example:
//
// https://espresso.codeforces.com/94d2346ee349d5dcb535dcd106cfbaa389c1b21c.png
//
// https://espresso.codeforces.com/c6a4bb4f01e3c79a7c34c54ab163323733690f43.png
//
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.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Random;
import java.util.StringTokenizer;
public class C1311E {
static final int MOD = 998244353;
static final Random RAND = new Random();
static int[] solve(int n, int d) {
int[] ans = new int[n-1];
// compute the minimal possible value
// 0 1 1 2 2 2 2 3 3 3 3 3 3 3 3 4 4 ...
int h = 0;
int min = 0;
int m = 1;
while ((1 << (h + 1)) - 1 < n) {
h++;
min += (1 << h) * h;
m += (1 << h);
}
min -= (m - n) * h;
int max = n * (n-1) / 2;
if (test) System.out.format("n:%d d:%d h:%d m:%d min:%d max:%d\n", n, d, h, m, min, max);
if (d < min || d > max) {
return null;
}
// Construct toward a perfect binary tree
Node[] nodes = new Node[n+1];
Node root = new Node(1);
Queue<Node> q = new LinkedList<>();
q.add(root);
nodes[1] = root;
int id = 1;
while (!q.isEmpty()) {
Node v = q.poll();
if (id < n) {
Node x = new Node(++id, v);
nodes[x.v] = x;
v.left = x;
q.add(x);
}
if (id < n) {
Node x = new Node(++id, v);
nodes[x.v] = x;
v.right = x;
q.add(x);
}
}
dfsSubCnt(root);
List<Node>[] levels = new ArrayList[n];
for (int i = 0; i < n; i++) {
levels[i] = new ArrayList<>();
}
int maxd = refreshLevels(root, levels);
// Identify and move subtree down to meet the expected sum of depth
int ib = 1;
int sum = sumDepth(root);
while (sum < d) {
// System.out.format(" sum:%d ib:%d\n", sum, ib);
while (levels[ib].size() == 1) {
ib++;
}
// Identify a node x at level ib and another node p at level ie >= ib
// Check the gain of depth sum if we move x under p and do it if applicable.
Node x = levels[ib].get(1);
// look for new parent of x bottom up
// The catch is such p must NOT be a descendant of x
Node p = null;
int gain = -1;
for (int ie = maxd - 1; ie >= ib; ie--) {
myAssert(levels[ie].get(0).depth == ie);
gain = (ie - x.p.depth) * x.subcnt;
if (sum + gain > d) {
continue;
}
for (Node v : levels[ie]) {
if (v.v != x.v && (v.left == null || v.right == null)) {
// v must not be a descendant of x
boolean ok = true;
Node y = v;
while (y != null) {
if (y.v == x.v) {
ok = false;
break;
}
y = y.p;
}
if (ok) {
p = v;
break;
}
}
}
if (p != null) {
break;
}
}
if (p == null) {
ib++;
continue;
}
if (test) System.out.format(" sum:%d ib:%d x:%s p:%s gain:%d\n", sum, ib, x, p, gain);
// if we move x under p, we gain total depth of:
myAssert(gain > 0);
myAssert(sum + gain <= d);
myAssert(p.depth >= x.depth);
Node y = x.p;
while (y != null) {
y.subcnt -= x.subcnt;
y = y.p;
}
if (x.p.left != null && x.p.left.v == x.v) {
x.p.left = null;
} else {
x.p.right = null;
}
x.p = p;
x.depth = p.depth + 1;
if (p.left == null) {
p.left = x;
} else {
p.right = x;
}
y = p;
while (y != null) {
y.subcnt += x.subcnt;
y = y.p;
}
sum += gain;
maxd = refreshLevels(root, levels);
dfsSubCnt(root);
}
for (int v = 2; v <= n; v++) {
ans[v-2] = nodes[v].p.v;
}
return ans;
}
static int refreshLevels(Node root, List<Node>[] levels) {
Queue<Node> q = new LinkedList<>();
q.add(root);
int depth = 0;
while (!q.isEmpty()) {
int size = q.size();
levels[depth].clear();
for (int i = 0; i < size; i++) {
Node v = q.poll();
// correct v's depth
v.depth = depth;
levels[v.depth].add(v);
if (v.left != null) {
q.add(v.left);
}
if (v.right != null) {
q.add(v.right);
}
}
depth++;
}
if (depth < levels.length) {
levels[depth].clear();
}
for (int i = 0; i < depth; i++) {
if (!levels[i].isEmpty()) {
if (test) System.out.format(" depth:%d %s\n", i, levels[i].toString());
}
}
return depth;
}
static int sumDepth(Node root) {
Queue<Node> q = new LinkedList<>();
q.add(root);
int sum = 0;
int depth = 0;
while (!q.isEmpty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
Node v = q.poll();
myAssert(v.depth == depth);
sum += depth;
if (v.left != null) {
q.add(v.left);
}
if (v.right != null) {
q.add(v.right);
}
}
depth++;
}
return sum;
}
static void dfsSubCnt(Node root) {
if (root == null) {
return;
}
dfsSubCnt(root.left);
dfsSubCnt(root.right);
root.subcnt = 1 + (root.left == null ? 0 : root.left.subcnt)
+ (root.right == null ? 0 : root.right.subcnt);
}
static class Node {
int v;
Node p;
Node left;
Node right;
// depth of v in the tree
int depth;
// number of node in the subtree rooted at v (inclusive)
int subcnt;
public Node(int v) {
this.v = v;
this.subcnt = 1;
}
public Node(int v, Node p) {
this.v = v;
this.p = p;
this.depth = p.depth + 1;
this.subcnt = 1;
}
@Override
public
String toString() {
return Integer.toString(v);
}
}
static void test(int n, int d) {
int[] ans = solve(n, d);
if (ans == null) {
System.out.format(" %d %d => NO\n", n, d);
} else {
StringBuilder sb = new StringBuilder();
for (int v : ans) {
sb.append(v);
sb.append(' ');
}
System.out.format(" %d %d => YES %s\n", n, d, sb.toString());
}
}
static boolean test = false;
static void doTest() {
if (!test) {
return;
}
long t0 = System.currentTimeMillis();
test(36, 165);
for (int t = 0; t < 20000; t++) {
int n = 2 + RAND.nextInt(50);
int d = 2 + RAND.nextInt(5000);
test(n, d);
}
test(11, 27);
test(12, 32);
test(11, 39);
test(12, 24);
test(12, 55);
test(11, 23);
test(5, 6);
test(11, 51);
test(12, 25);
test(11, 30);
test(9, 20);
test(9, 16);
test(10, 37);
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++) {
int n = in.nextInt();
int d = in.nextInt();
int[] ans = solve(n, d);
output(ans);
}
}
static void output(int[] a) {
if (a == null) {
System.out.println("NO");
return;
}
StringBuilder sb = new StringBuilder();
sb.append("YES\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 |
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.StringTokenizer;
public class test {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
int t = Integer.parseInt(br.readLine());
while (t-- > 0) {
StringTokenizer tokenizer = new StringTokenizer(br.readLine());
int a = Integer.parseInt(tokenizer.nextToken());
int b = Integer.parseInt(tokenizer.nextToken());
int c = Integer.parseInt(tokenizer.nextToken());
int temp = 0;
if (a < b) {
temp = b;
b = a;
a = temp;
}
if (a < c) {
temp = c;
c = a;
a = temp;
}
if (b < c) {
temp = c;
c = b;
b = temp;
}
int result = 0;
if (a != 0) {
result++;
a--;
}
if (b != 0) {
result++;
b--;
}
if (c != 0) {
result++;
c--;
}
if (a != 0 && b != 0) {
result++;
a--;
b--;
}
if (a != 0 && c != 0) {
result++;
a--;
c--;
}
if (c != 0 && b != 0) {
result++;
c--;
b--;
}
if (a != 0 && b != 0 && c != 0) {
result++;
a--;
b--;
c--;
}
pw.println(result);
}
pw.flush();
pw.close();
br.close();
}
} | 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 MyClass {
// public static boolean chek(String str){
// char c = str.charAt(0);
// for(int i=1;i<4;i++){
// for(int j=i;j<4;j++){
// if(c==str.charAt(j)){
// return false;
// }
// }
// c = str.charAt(i);
// }
// return true;
// }
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
s.nextLine();
// int h = s.nextInt();
// int t = s.nextInt();
// String str1 = s.nextLine();
// String str2 = s.nextLine();
// int sum = 0;
for(int i=0;i<n;i++){
int n1 = s.nextInt();
s.nextLine();
int odd = 0;
int even = 0;
int count = 0;
for(int j=0;j<n1;j++){
int n2 = s.nextInt();
count++;
if(n2%2==0){
even++;
}else{
odd++;
}
}
if(count == even){
System.out.println("YES");
}else if(count ==odd){
System.out.println("YES");
}else{
System.out.println("NO");
}
}
}
} | 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.*;
import java.util.*;
public class cf1 {
// author: Utkarsh Singh
// PRIMARY VARIABLES
//private static int n, m, k, x, y;
//private static int[] a, b;
private static long ans=0;
private static long[] a;
private static long[][] dp;
//private static String s, t;
//private static HashMap<Integer, ArrayList<Integer>> g;
//static ArrayList<Integer> al;//=new ArrayList<Integer>();
//static ArrayList<ArrayList<Integer>> al;
private static HashMap<Long,Long> hm=new HashMap<Long,Long>();
private static HashSet<Long> hs=new HashSet<Long>();
//private static Stack<Integer> sk=new Stack<Integer>();
//private static Queue<Integer> q=new LinkedList<Integer>();
//private static PriorityQueue<Integer> pq=new PriorityQueue<Integer>();
//for(int i=0;i<n;i++)
//for (Map.Entry<Integer, Integer> entry : hm.entrySet()) {
// CONSTANTS
/*private static final int MOD = (int) 1e9 + 7;
private static final int[] dx = { -1, 1, 0, 0 };
private static final int[] dy = { 0, 0, -1, 1 };
private static final int MAX = Integer.MAX_VALUE;
private static final int MIN = Integer.MIN_VALUE;
private static final long MAXL = (long) 1e18;
private static final long MINL = -(long) 1e18;*/
static Scanner in= new Scanner(System.in);
public static void main(String[] args) {
//print("Utkarsh");
//int t=ini();
//while(t-->0)
solve();
}
public static void solve()
{
int n=ini();
for(int k=0;k<n;k++)
{
int x=ini();
if(x%2==0)
{
for(int i=0;i<x/2;i++)
System.out.print("1");
System.out.println();
}
else
{
System.out.print("7");
x-=3;
for(int i=0;i<x/2;i++)
System.out.print("1");
System.out.println();
}
}
}
// INPUT SHORTCUTS
private static long[] ina(int n) {
long[] temp = new long[n];
for (int i = 0; i < n; i++) {
temp[i] = in.nextLong();
}
return temp;
}
private static long[][] ina2d(int n, int m) {
long[][] temp = new long[n][m];
for (int i = 0; i < n; i++) {
temp[i] = ina(m);
}
return temp;
}
private static char[][] ina2dChar(int n, int m) {
char[][] temp = new char[n][];
for (int i = 0; i < n; i++) {
temp[i] = ins().toCharArray();
}
return temp;
}
private static int ini() {
return in.nextInt();
}
private static long inl() {
return in.nextLong();
}
private static double ind() {
return Double.parseDouble(ins());
}
private static String ins() {
return in.next();
}
// PRINT ANSWER
private static void print(Object o) {
System.out.println(o);
}
private static void printT(Object o, int testCaseNo) {
System.out.println("Case #" + testCaseNo + ": " + o);
}
private static void printA(int[] a) {
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
System.out.println();
}
}
| 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 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_Fast_Food_Restaurant {
public static void main(String[] args) {
OutputStream outputStream = System.out;
PrintWriter out = new PrintWriter(outputStream);
FastReader f = new FastReader();
int t = f.nextInt();
while(t-- > 0){
solve(f, out);
}
out.close();
}
public static void solve(FastReader f, PrintWriter out) {
int arr[] = {f.nextInt(), f.nextInt(), f.nextInt()};
int ans = 0;
for(int i = 0; i < 3; i++) {
if(arr[i] > 0) {
arr[i]--;
ans++;
}
}
int maxInd = 0;
for(int i = 0; i < 3; i++) {
if(arr[i] > arr[maxInd]) {
maxInd = i;
}
}
int ind1 = (maxInd+1)%3;
int ind2 = (maxInd+2)%3;
if(arr[maxInd] > 0 && arr[ind1] > 0) {
arr[maxInd]--;
arr[ind1]--;
ans++;
}
if(arr[maxInd] > 0 && arr[ind2] > 0) {
arr[maxInd]--;
arr[ind2]--;
ans++;
}
if(arr[ind1] > 0 && arr[ind2] > 0) {
arr[ind1]--;
arr[ind2]--;
ans++;
}
if(arr[0] > 0 && arr[1] > 0 && arr[2] > 0) {
ans++;
}
out.println(ans);
}
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);
}
}
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 + " ");
}
}
}
}
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;
}
public static int gcd(int a, int b) {
int dividend = a > b ? a : b;
int divisor = a < b ? a : b;
while(divisor > 0) {
int reminder = dividend % divisor;
dividend = divisor;
divisor = reminder;
}
return dividend;
}
public static int lcm(int a, int b) {
int lcm = gcd(a, b);
int hcf = (a * b) / lcm;
return hcf;
}
public static String sortString(String inputString) {
char tempArray[] = inputString.toCharArray();
Arrays.sort(tempArray);
return new String(tempArray);
}
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());
}
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
*/
| java |
1311 | B | B. WeirdSorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn.You are also given a set of distinct positions p1,p2,…,pmp1,p2,…,pm, where 1≤pi<n1≤pi<n. The position pipi means that you can swap elements a[pi]a[pi] and a[pi+1]a[pi+1]. You can apply this operation any number of times for each of the given positions.Your task is to determine if it is possible to sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps.For example, if a=[3,2,1]a=[3,2,1] and p=[1,2]p=[1,2], then we can first swap elements a[2]a[2] and a[3]a[3] (because position 22 is contained in the given set pp). We get the array a=[3,1,2]a=[3,1,2]. Then we swap a[1]a[1] and a[2]a[2] (position 11 is also contained in pp). We get the array a=[1,3,2]a=[1,3,2]. Finally, we swap a[2]a[2] and a[3]a[3] again and get the array a=[1,2,3]a=[1,2,3], sorted in non-decreasing order.You can see that if a=[4,1,2,3]a=[4,1,2,3] and p=[3,2]p=[3,2] then you cannot sort the array.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.Then tt test cases follow. The first line of each test case contains two integers nn and mm (1≤m<n≤1001≤m<n≤100) — the number of elements in aa and the number of elements in pp. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100). The third line of the test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n, all pipi are distinct) — the set of positions described in the problem statement.OutputFor each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps. Otherwise, print "NO".ExampleInputCopy6
3 2
3 2 1
1 2
4 2
4 1 2 3
3 2
5 1
1 2 3 4 5
1
4 2
2 1 4 3
1 3
4 2
4 3 2 1
1 3
5 2
2 1 2 3 3
1 4
OutputCopyYES
NO
YES
YES
NO
YES
| [
"dfs and similar",
"sortings"
] | // package c1311;
//
// Codeforces Round #624 (Div. 3) 2020-02-24 06:35
// B. WeirdSort
// https://codeforces.com/contest/1311/problem/B
// 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+).*'
//
// You are given an array a of length n.
//
// You are also given a set of positions p_1, p_2, ..., p_m, where 1 <= p_i < n. The position p_i
// means that you can swap elements a[p_i] and a[p_i + 1]. You can apply this operation any number
// of times for each of the given .
//
// Your task is to determine if it is possible to sort the initial array in non-decreasing order
// (a_1 <= a_2 <= ... <= a_n) using only allowed swaps.
//
// For example, if a = [3, 2, 1] and p = [1, 2], then we can first swap elements a[2] and a[3]
// (because position 2 is contained in the given set p). We get the array a = [3, 1, 2]. Then we
// swap a[1] and a[2] (position 1 is also contained in p). We get the array a = [1, 3, 2]. Finally,
// we swap a[2] and a[3] again and get the array a = [1, 2, 3], sorted in non-decreasing order.
//
// You can see that if a = [4, 1, 2, 3] and p = [3, 2] then you cannot sort the array.
//
// You have to answer t independent test cases.
//
// Input
//
// The first line of the input contains one integer t (1 <= t <= 100) -- the number of test cases.
//
// Then t test cases follow. The first line of each test case contains two integers n and m (1 <= m
// < n <= 100) -- the number of elements in a and the number of elements in p. The second line of
// the test case contains n integers a_1, a_2, ..., a_n (1 <= a_i <= 100). The third line of the
// test case contains m integers p_1, p_2, ..., p_m (1 <= p_i < n, all p_i are distinct) -- the set
// of positions described in the problem statement.
//
// Output
//
// For each test case, print the answer -- "YES" (without quotes) if you can sort the initial array
// in non-decreasing order (a_1 <= a_2 <= ... <= a_n) using only allowed swaps. Otherwise, print
// "NO".
//
// Example
/*
input:
6
3 2
3 2 1
1 2
4 2
4 1 2 3
3 2
5 1
1 2 3 4 5
1
4 2
2 1 4 3
1 3
4 2
4 3 2 1
1 3
5 2
2 1 2 3 3
1 4
output:
YES
NO
YES
YES
NO
YES
*/
//
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.Collections;
import java.util.List;
import java.util.Random;
import java.util.StringTokenizer;
public class C1311B {
static final int MOD = 998244353;
static final Random RAND = new Random();
static boolean solve(int[] a, int[] p) {
int n = a.length;
boolean[] ok = new boolean[n];
for (int v : p) {
ok[v] = true;
}
List<Integer> nums = new ArrayList<>();
List<Integer> curr = new ArrayList<>();
// . . x x . . x . .
// ^
// e
for (int i = 0; i < n; i++) {
curr.add(a[i]);
if (!ok[i]) {
Collections.sort(curr);
nums.addAll(curr);
curr.clear();
}
}
Collections.sort(curr);
nums.addAll(curr);
for (int i = 1; i < n; i++) {
if (nums.get(i) < nums.get(i-1)) {
return false;
}
}
return true;
}
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++) {
int n = in.nextInt();
int m = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt() - 1;
}
int[] p = new int[m];
for (int i = 0; i < m; i++) {
p[i] = in.nextInt() - 1;
}
boolean ans = solve(a, p);
System.out.println(ans? "YES" : "NO");
}
}
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 |
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.util.*;
public class ProblemD {
public static void main(String[] args) throws Exception {
Scanner in = new Scanner();
int test = in.readInt();
int x = in.readInt();
int count[] = new int[x];
StringBuilder sb = new StringBuilder();
Comparator<Pair>cmp = new Comparator<Pair>(){
@Override
public int compare(Pair a, Pair b) {
return a.x == b.x? a.y - b.y: a.x - b.x;
}
};
TreeSet<Pair>set = new TreeSet<>(cmp);
for(int i = 0;i<x;i++)set.add(new Pair(count[i],i));
while(test-->0){
int val = in.readInt();
val%=x;
set.remove(new Pair(count[val],val));
count[val]++;
set.add(new Pair(count[val],val));
sb.append(set.first().x * x + set.first().y);
sb.append("\n");
}
System.out.println(sb);
}
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 |
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 Main {
public static void display(int[] x){
for(int i = 0; i < x.length; i++){
System.out.println(1 + " " + (x[i] - 1));
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int num = in.nextInt();
int[] x = new int[num];
for(int i = 0; i < x.length; i++){
x[i] = in.nextInt();
}
display(x);
}
}
| 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 java.io.*;
import static java.lang.Math.*;
import static java.lang.System.*;
public class D
{
public static void main(String[]args){
InputReader sc = new InputReader(System.in);
PrintWriter pw =new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
//minimum is the number of times where next isint closer
//maximum is the times (didnt go smaller) or (have more than one smaller within reach)
int nodes=sc.nextInt();
int roads=sc.nextInt();
ArrayList<Integer>[] road = new ArrayList[nodes+1];
ArrayList<Integer>[] reversed = new ArrayList[nodes+1];
for(int i=0;i<road.length;i++){
road[i]=new ArrayList<Integer>();
reversed[i]=new ArrayList<Integer>();
}
for(int i=0;i<roads;i++){
int begin=sc.nextInt();
int end=sc.nextInt();
road[begin].add(end);
reversed[end].add(begin);
}
int paths=sc.nextInt();
int[]path=sc.nextIntArray(paths);
int destination=path[path.length-1];
int[]dist=new int[nodes+1];
Arrays.fill(dist,999999);
dist[destination]=0;
Queue<Integer>q=new LinkedList<Integer>();
q.add(destination);
while(!q.isEmpty()){
Integer p=q.remove();
for(int i=0;i<reversed[p].size();i++){
if(dist[reversed[p].get(i)]==999999){
dist[reversed[p].get(i)]=dist[p]+1;
q.add(reversed[p].get(i));
}
}
}
int minimum=0;
int maximum=0;
for(int i=0;i<path.length-1;i++){
if(dist[path[i+1]]>dist[path[i]]-1)minimum++;
}
for(int i=0;i<path.length-1;i++){
if(dist[path[i+1]]>dist[path[i]]-1)maximum++;
else{
//if there exist another path
int cc=0;
for(int a=0;a<road[path[i]].size();a++){
if(dist[road[path[i]].get(a)]<=dist[path[i]]-1)cc++;
}
if(cc>1)maximum++;
}
}
System.out.println(minimum+" "+maximum);
pw.flush();
}
static class InputReader
{
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int snext()
{
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars)
{
curChar = 0;
try
{
snumChars = stream.read(buf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
double res = 0;
while(c<='9'&&c>='0'){
res*=10;
res+=c-'0';
c=snext();
}
if(c=='.'){
double decimal=0;
long multiplier=1;
c=snext();
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
decimal *= 10;
decimal += c - '0';
multiplier*=10;
c = snext();
} while (!isSpaceChar(c));
return sgn*(res+decimal/multiplier);
}else{
if(!isSpaceChar(c)){
throw new InputMismatchException();
}
return sgn*res;
}
}
public int[] nextIntArray(int n)
{
int a[] = new int[n];
for (int i = 0; i < n; i++)
{
a[i] = nextInt();
}
return a;
}
public long[] nextLongArray(int n)
{
long a[] = new long[n];
for (int i = 0; i < n; i++)
{
a[i] = nextLong();
}
return a;
}
public String next(){return readString();}
public String readString()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine()
{
int c = snext();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isEndOfLine(c));
if(isEndOfLine(res.charAt(res.length()-1)))
return res.deleteCharAt(res.length()).toString();
return res.toString();
}
public ArrayList<String> readAll(){
ArrayList<String>a=new ArrayList<String>();
try{
while(true){
a.add(nextLine());
}
}catch(Exception e){
}
return a;
}
public boolean hasNext(){
boolean hasnext=true;
try{
hasnext= stream.available()!=0;
}catch(IOException e){
}
return hasnext||curChar<snumChars;
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c)
{
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
} | java |
1322 | B | B. Presenttime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputCatherine received an array of integers as a gift for March 8. Eventually she grew bored with it; and she started calculated various useless characteristics for it. She succeeded to do it for each one she came up with. But when she came up with another one — xor of all pairwise sums of elements in the array, she realized that she couldn't compute it for a very large array, thus she asked for your help. Can you do it? Formally, you need to compute(a1+a2)⊕(a1+a3)⊕…⊕(a1+an)⊕(a2+a3)⊕…⊕(a2+an)…⊕(an−1+an)(a1+a2)⊕(a1+a3)⊕…⊕(a1+an)⊕(a2+a3)⊕…⊕(a2+an)…⊕(an−1+an)Here x⊕yx⊕y is a bitwise XOR operation (i.e. xx ^ yy in many modern programming languages). You can read about it in Wikipedia: https://en.wikipedia.org/wiki/Exclusive_or#Bitwise_operation.InputThe first line contains a single integer nn (2≤n≤4000002≤n≤400000) — the number of integers in the array.The second line contains integers a1,a2,…,ana1,a2,…,an (1≤ai≤1071≤ai≤107).OutputPrint a single integer — xor of all pairwise sums of integers in the given array.ExamplesInputCopy2
1 2
OutputCopy3InputCopy3
1 2 3
OutputCopy2NoteIn the first sample case there is only one sum 1+2=31+2=3.In the second sample case there are three sums: 1+2=31+2=3, 1+3=41+3=4, 2+3=52+3=5. In binary they are represented as 0112⊕1002⊕1012=01020112⊕1002⊕1012=0102, thus the answer is 2.⊕⊕ is the bitwise xor operation. To define x⊕yx⊕y, consider binary representations of integers xx and yy. We put the ii-th bit of the result to be 1 when exactly one of the ii-th bits of xx and yy is 1. Otherwise, the ii-th bit of the result is put to be 0. For example, 01012⊕00112=0110201012⊕00112=01102. | [
"binary search",
"bitmasks",
"constructive algorithms",
"data structures",
"math",
"sortings"
] | import java.io.*;
import java.util.*;
public class Main{
static int solveLower(int i,int[]in,int left,int right) {
int lo=0,hi=i-1;
int ans=-1;
while(lo<=hi) {
int mid=(lo+hi)>>1;
int sum=in[i]+in[mid];
if(sum<left) {
lo=mid+1;
}
else {
if(sum>right)
hi=mid-1;
else{
ans=mid;
hi=mid-1;
}
}
}
return ans;
}
static int solveUpper(int i,int[]in,int left,int right) {
int lo=0,hi=i-1;
int ans=-1;
while(lo<=hi) {
int mid=(lo+hi)>>1;
int sum=in[i]+in[mid];
if(sum<left) {
lo=mid+1;
}
else {
if(sum>right)
hi=mid-1;
else{
ans=mid;
lo=mid+1;
}
}
}
return ans;
}
public static void main(String[] args) throws Exception{
MScanner sc=new MScanner(System.in);
PrintWriter pw=new PrintWriter(System.out);
int n=sc.nextInt();
int[]in=sc.takearr(n);
int ans=0;
for(int b=0;b<27;b++) {
int tmp[]=new int[n];
for(int i=0;i<n;i++) {
tmp[i]=in[i]%(1<<(b+1));
}
Arrays.sort(tmp);
int left=1<<b,right=(1<<(b+1))-1;
long cnt=0;
for(int i=1;i<n;i++) {
int lower=solveLower(i, tmp, left, right);
if(lower==-1)continue;
int upper=solveUpper(i, tmp, left, right);
cnt+=upper-lower+1;
}
left=(1<<b)+(1<<(b+1));right=(1<<(b+2))-2;
for(int i=1;i<n;i++) {
int lower=solveLower(i, tmp, left, right);
if(lower==-1)continue;
int upper=solveUpper(i, tmp, left, right);
cnt+=upper-lower+1;
}
if(cnt%2==1) {
ans+=1<<b;
}
}
pw.println(ans);
pw.flush();
}
static class MScanner {
StringTokenizer st;
BufferedReader br;
public MScanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public MScanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int[] takearr(int n) throws IOException {
int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt();
return in;
}
public long[] takearrl(int n) throws IOException {
long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong();
return in;
}
public Integer[] takearrobj(int n) throws IOException {
Integer[]in=new Integer[n];for(int i=0;i<n;i++)in[i]=nextInt();
return in;
}
public Long[] takearrlobj(int n) throws IOException {
Long[]in=new Long[n];for(int i=0;i<n;i++)in[i]=nextLong();
return in;
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public Long nextLong() throws IOException {
return Long.parseLong(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
} | java |
1293 | A | A. ConneR and the A.R.C. Markland-Ntime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSakuzyo - ImprintingA.R.C. Markland-N is a tall building with nn floors numbered from 11 to nn. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor ss of the building. On each floor (including floor ss, of course), there is a restaurant offering meals. However, due to renovations being in progress, kk of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases in the test. Then the descriptions of tt test cases follow.The first line of a test case contains three integers nn, ss and kk (2≤n≤1092≤n≤109, 1≤s≤n1≤s≤n, 1≤k≤min(n−1,1000)1≤k≤min(n−1,1000)) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants.The second line of a test case contains kk distinct integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n) — the floor numbers of the currently closed restaurants.It is guaranteed that the sum of kk over all test cases does not exceed 10001000.OutputFor each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor ss to a floor with an open restaurant.ExampleInputCopy5
5 2 3
1 2 3
4 3 3
4 1 2
10 2 6
1 2 3 4 5 7
2 1 1
2
100 76 8
76 75 36 67 41 74 10 77
OutputCopy2
0
4
0
2
NoteIn the first example test case; the nearest floor with an open restaurant would be the floor 44.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the 66-th floor. | [
"binary search",
"brute force",
"implementation"
] | import java.util.*;
public class A1293 {
public static boolean exist(int[] arr, int x) {
for (int i=0; i<arr.length; i++) {
if (arr[i] == x) return true;
}
return false;
}
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int t = scn.nextInt();
while(t-->0){
int n = scn.nextInt();
int s = scn.nextInt();
int k = scn.nextInt();
int[] a = new int[k];
for (int i=0; i<k; i++) a[i] = scn.nextInt();
// long[] blocked = new long[k];
for (int i=0; i<=k; i++) {
if (s-i >= 1 && !exist(a, s-i)) {System.out.println(i);break;}
if (s+i <= n && !exist(a, s+i)) {System.out.println(i);break;}
}
}
}
}
| 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"
] |
import java.io.*;
import java.math.*;
import java.util.*;
public class C_Polycarp_Restores_Permutation
{
public static void main(String[] args)throws Exception
{
new Solver().solve();
}
}
//* Success is not final, failure is not fatal: it is the courage to continue that counts.
class Solver {
void solve() throws Exception
{
int n =sc.nextInt();
int[] arr = new int[n-1];
for(int i =0;i<n-1;i++){
arr[i] = sc.nextInt();
}
int min = arr[0];
for(int i = 1;i<n-1;i++){
arr[i] = arr[i-1]+arr[i];
min = Math.min(arr[i],min);
}
// now we will start with the minimum
ArrayList<Integer> A = new ArrayList<>();
int start;
boolean isPos =true;
if(min>0){
start = min;
}else{
start = Math.abs(min)+1;
}
if(start>n || start<1){
isPos =false;
}
HashSet<Integer> HS = new HashSet<>();
A.add(start);
HS.add(start);
for(int i =0;i<n-1 && isPos;i++){
int x = start +arr[i];
if(x<1 || x>n || HS.contains(x)){
// System.out.println(x);
isPos = false;
break;
}
HS.add(x);
A.add(x);
}
// System.out.println(HS);
if(isPos){
for(int i : A){
sc.print(i+" ");
}
sc.println();
}else{
sc.println(-1);
}
sc.flush();
}
final Helper sc;
final int MAXN = 1000_006;
final long MOD = (long) 1e9 + 7;
Solver() {
sc = new Helper(MOD, MAXN);
sc.initIO(System.in, System.out);
}
}
class Helper {
final long MOD;
final int MAXN;
final Random rnd;
public Helper(long mod, int maxn) {
MOD = mod;
MAXN = maxn;
rnd = new Random();
}
public static int[] sieve;
public static ArrayList<Integer> primes;
public void setSieve() {
primes = new ArrayList<>();
sieve = new int[MAXN];
int i, j;
for (i = 2; i*i < MAXN; ++i)
if (sieve[i] == 0) {
primes.add(i);
for (j = i*i; j < MAXN; j += i) {
sieve[j] = i;
}
}
}
public static long[] factorial;
public void setFactorial() {
factorial = new long[MAXN];
factorial[0] = 1;
for (int i = 1; i < MAXN; ++i) factorial[i] = factorial[i - 1] * i % MOD;
}
public long getFactorial(int n) {
if (factorial == null) setFactorial();
return factorial[n];
}
public long ncr(int n, int r) {
if (r > n) return 0;
if (factorial == null) setFactorial();
long numerator = factorial[n];
long denominator = factorial[r] * factorial[n - r] % MOD;
return numerator * pow(denominator, MOD - 2, MOD) % MOD;
}
public long[] getLongArray(int size) throws Exception {
long[] ar = new long[size];
for (int i = 0; i < size; ++i) ar[i] = nextLong();
return ar;
}
public int[] getIntArray(int size) throws Exception {
int[] ar = new int[size];
for (int i = 0; i < size; ++i) ar[i] = nextInt();
return ar;
}
public long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
public int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
public long max(long[] ar) {
long ret = ar[0];
for (long itr : ar) ret = Math.max(ret, itr);
return ret;
}
public int max(int[] ar) {
int ret = ar[0];
for (int itr : ar) ret = Math.max(ret, itr);
return ret;
}
public long min(long[] ar) {
long ret = ar[0];
for (long itr : ar) ret = Math.min(ret, itr);
return ret;
}
public int min(int[] ar) {
int ret = ar[0];
for (int itr : ar) ret = Math.min(ret, itr);
return ret;
}
public long sum(long[] ar) {
long sum = 0;
for (long itr : ar) sum += itr;
return sum;
}
public long sum(int[] ar) {
long sum = 0;
for (int itr : ar) sum += itr;
return sum;
}
public void shuffle(int[] ar) {
int r;
for (int i = 0; i < ar.length; ++i) {
r = rnd.nextInt(ar.length);
if (r != i) {
ar[i] ^= ar[r];
ar[r] ^= ar[i];
ar[i] ^= ar[r];
}
}
}
public void shuffle(long[] ar) {
int r;
for (int i = 0; i < ar.length; ++i) {
r = rnd.nextInt(ar.length);
if (r != i) {
ar[i] ^= ar[r];
ar[r] ^= ar[i];
ar[i] ^= ar[r];
}
}
}
public long pow(long base, long exp, long MOD) {
base %= MOD;
long ret = 1;
while (exp > 0) {
if ((exp & 1) == 1) ret = ret * base % MOD;
base = base * base % MOD;
exp >>= 1;
}
return ret;
}
static byte[] buf = new byte[1000_006];
static int index, total;
static InputStream in;
static BufferedWriter bw;
public void initIO(InputStream is, OutputStream os) {
try {
in = is;
bw = new BufferedWriter(new OutputStreamWriter(os));
} catch (Exception e) {
}
}
public void initIO(String inputFile, String outputFile) {
try {
in = new FileInputStream(inputFile);
bw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outputFile)));
} catch (Exception e) {
}
}
private int scan() throws Exception {
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0)
return -1;
}
return buf[index++];
}
public String nextLine() throws Exception {
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();
}
public String next() throws Exception {
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();
}
public int nextInt() throws Exception {
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;
}
public long nextLong() throws Exception {
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 print(Object a) throws Exception {
bw.write(a.toString());
}
public void printsp(Object a) throws Exception {
print(a);
print(" ");
}
public void println() throws Exception {
bw.write("\n");
}
public void printArray(int[] arr) throws Exception{
for(int i = 0;i<arr.length;i++){
print(arr[i]+ " ");
}
println();
}
public void println(Object a) throws Exception {
print(a);
println();
}
public void flush() throws Exception {
bw.flush();
}
}
| java |
1321 | C | C. Remove Adjacenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss consisting of lowercase Latin letters. Let the length of ss be |s||s|. You may perform several operations on this string.In one operation, you can choose some index ii and remove the ii-th character of ss (sisi) if at least one of its adjacent characters is the previous letter in the Latin alphabet for sisi. For example, the previous letter for b is a, the previous letter for s is r, the letter a has no previous letters. Note that after each removal the length of the string decreases by one. So, the index ii should satisfy the condition 1≤i≤|s|1≤i≤|s| during each operation.For the character sisi adjacent characters are si−1si−1 and si+1si+1. The first and the last characters of ss both have only one adjacent character (unless |s|=1|s|=1).Consider the following example. Let s=s= bacabcab. During the first move, you can remove the first character s1=s1= b because s2=s2= a. Then the string becomes s=s= acabcab. During the second move, you can remove the fifth character s5=s5= c because s4=s4= b. Then the string becomes s=s= acabab. During the third move, you can remove the sixth character s6=s6='b' because s5=s5= a. Then the string becomes s=s= acaba. During the fourth move, the only character you can remove is s4=s4= b, because s3=s3= a (or s5=s5= a). The string becomes s=s= acaa and you cannot do anything with it. Your task is to find the maximum possible number of characters you can remove if you choose the sequence of operations optimally.InputThe first line of the input contains one integer |s||s| (1≤|s|≤1001≤|s|≤100) — the length of ss.The second line of the input contains one string ss consisting of |s||s| lowercase Latin letters.OutputPrint one integer — the maximum possible number of characters you can remove if you choose the sequence of moves optimally.ExamplesInputCopy8
bacabcab
OutputCopy4
InputCopy4
bcda
OutputCopy3
InputCopy6
abbbbb
OutputCopy5
NoteThe first example is described in the problem statement. Note that the sequence of moves provided in the statement is not the only; but it can be shown that the maximum possible answer to this test is 44.In the second example, you can remove all but one character of ss. The only possible answer follows. During the first move, remove the third character s3=s3= d, ss becomes bca. During the second move, remove the second character s2=s2= c, ss becomes ba. And during the third move, remove the first character s1=s1= b, ss becomes a. | [
"brute force",
"constructive algorithms",
"greedy",
"strings"
] | import java.util.*;
import java.io.*;
public class Main {
static StringBuilder sb;
static dsu dsu;
static long fact[];
static long mod = (long) (1e9 + 7);
static BufferedReader br;
static HashMap<Long, Long> map;
static void solve() throws Exception{
int len = i();
String str = s();
StringBuilder temp = new StringBuilder();
int maxRemovals = 0;
for(char ch='z'; ch>='a';){
temp = new StringBuilder();
len = str.length();
boolean enc = false;
for(int idx=0; idx<len; idx++){
char currCh = str.charAt(idx);
if(currCh==ch){
if(idx+1<len && str.charAt(idx+1) == prev(currCh)){
maxRemovals++;
enc = true;
}else if(idx-1>=0 && str.charAt(idx-1) == prev(currCh)){
maxRemovals++;
enc = true;
}else temp.append(currCh);
}else temp.append(currCh);
}
if(!enc) ch--;
str = temp.toString();
}
sb.append(maxRemovals);
}
private static char prev(char ch){
if(ch=='a') return '!';
return (char)('a'+(ch-'a'-1));
}
public static void main(String[] args) throws Exception{
sb = new StringBuilder();
br = new BufferedReader(new InputStreamReader(System.in));
int test = 1;
while (test-- > 0) {
solve();
}
out.printLine(sb);
out.close();
}
/*
* fact=new long[(int)1e6+10]; fact[0]=fact[1]=1; for(int i=2;i<fact.length;i++)
* { fact[i]=((long)(i%mod)1L(long)(fact[i-1]%mod))%mod; }
*/
//**************NCR%P******************
static long ncr(int n, int r) {
if (r > n)
return (long) 0;
long res = fact[n] % mod;
res = ((long) (res % mod) * (long) (p(fact[r], mod - 2) % mod)) % mod;
res = ((long) (res % mod) * (long) (p(fact[n - r], mod - 2) % mod)) % mod;
return res;
}
static long p(long x, long y)// POWER FXN MODULO //
{
if (y == 0)
return 1;
long res = 1;
while (y > 0) {
if (y % 2 == 1) {
res = (res * x) % mod;
y--;
}
x = (x * x) % mod;
y = y / 2;
}
return res;
}
// *************Disjoint set
// union*********//
static class dsu {
int parent[];
dsu(int n) {
parent = new int[n];
for (int i = 0; i < n; i++)
parent[i] = -1;
}
int find(int a) {
if (parent[a] < 0)
return a;
else {
int x = find(parent[a]);
parent[a] = x;
return x;
}
}
void merge(int a, int b) {
a = find(a);
b = find(b);
if (a == b)
return;
parent[b] = a;
}
}
//**************PRIME FACTORIZE **********************************//
static TreeMap<Integer, Integer> prime(long n) {
TreeMap<Integer, Integer> h = new TreeMap<>();
long num = n;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (n % i == 0) {
int nt = 0;
while (n % i == 0) {
n = n / i;
nt++;
}
h.put(i, nt);
}
}
if (n != 1)
h.put((int) n, 1);
return h;
}
//****CLASS PAIR ************************************************
static class Pair implements Comparable<Pair> {
int x;
long y;
Pair(int x, long y) {
this.x = x;
this.y = y;
}
public int compareTo(Pair o) {
return (int) (this.y - o.y);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int Int() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String String() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return String();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
}
static InputReader in = new InputReader(System.in);
static OutputWriter out = new OutputWriter(System.out);
public static long[] sort(long[] a2) {
int n = a2.length;
ArrayList<Long> l = new ArrayList<>();
for (long i : a2)
l.add(i);
Collections.sort(l);
for (int i = 0; i < l.size(); i++)
a2[i] = l.get(i);
return a2;
}
public static char[] sort(char[] a2) {
int n = a2.length;
ArrayList<Character> l = new ArrayList<>();
for (char i : a2)
l.add(i);
Collections.sort(l);
for (int i = 0; i < l.size(); i++)
a2[i] = l.get(i);
return a2;
}
//*************NORMAL POWER******************************
public static long pow(long x, long y) {
long res = 1;
while (y > 0) {
if (y % 2 != 0) {
res = (res * x);// % modulus;
y--;
}
x = (x * x);// % modulus;
y = y / 2;
}
return res;
}
//GCD___+++++++++++++++++++++++++++++++
public static long gcd(long x, long y) {
if (x == 0)
return y;
else
return gcd(y % x, x);
}
// ******LOWEST COMMON MULTIPLE
// *********************************************
public static long lcm(long x, long y) {
return (x * (y / gcd(x, y)));
}
// ****BINARY SEARCH****//
private static long bins(long arr[], long tar) {
int low = 0;
int high = arr.length - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] > tar) high = mid - 1;
else if (arr[mid] < tar) low = mid + 1;
else return mid;;
}
return -1;
}
// ********COUNTER******//
private static void count(long arr[]) {
map = new HashMap();
for (long val : arr) map.put(val, map.getOrDefault(val, 0l) + 1l);
}
//INPUT PATTERN********************************************************
public static int i() {
return in.Int();
}
public static long l() {
String s = in.String();
return Long.parseLong(s);
}
public static String s() {
return in.String();
}
public static int[] readArrayi(int n) {
int A[] = new int[n];
for (int i = 0; i < n; i++) {
A[i] = i();
}
return A;
}
public static long[] readArray(long n) {
long A[] = new long[(int) n];
for (int i = 0; i < n; i++) {
A[i] = l();
}
return A;
}
} | 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.util.*;
public class MEX_Maximizing {
static FastScanner fs;
static FastWriter fw;
static boolean checkOnlineJudge = System.getProperty("ONLINE_JUDGE") == null;
private static final int[][] kdir = new int[][]{{-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}, {1, -2}, {2, -1}, {2, 1}, {1, 2}};
private static final int[][] dir = new int[][]{{-1, 0}, {1, 0}, {0, 1}, {0, -1}};
private static final int iMax = Integer.MAX_VALUE, iMin = Integer.MIN_VALUE;
private static final long lMax = Long.MAX_VALUE, lMin = Long.MIN_VALUE;
private static final int mod1 = (int) (1e9 + 7);
private static final int mod2 = 998244353;
public static void main(String[] args) throws IOException {
fs = new FastScanner();
fw = new FastWriter();
int t = 1;
//t = fs.nextInt();
while (t-- > 0) {
solve();
}
fw.out.close();
}
private static void solve() {
int n = fs.nextInt(), x = fs.nextInt();
int[] arr = readIntArray(n);
for (int i = 0; i < n; i++) {
arr[i] = (arr[i] % x);
}
int[] mul = new int[n];
for (int i = 0; i < n; i++) {
int num = arr[i];
long curr = num + ((long) mul[num] * x);
if (curr >= n) continue;
arr[i] = (int) curr;
mul[num]++;
}
int[] occ = new int[n + 1];
int idx = 0;
for (int i = 0; i < n; i++) {
occ[arr[i]] = 1;
while (occ[idx] == 1) idx++;
fw.out.println(idx);
}
}
private static class UnionFind {
private final int[] parent;
private final int[] rank;
UnionFind(int n) {
parent = new int[n + 5];
rank = new int[n + 5];
for (int i = 0; i <= n; i++) {
parent[i] = i;
rank[i] = 0;
}
}
private int find(int i) {
if (parent[i] == i)
return i;
return parent[i] = find(parent[i]);
}
private void union(int a, int b) {
a = find(a);
b = find(b);
if (a != b) {
if (rank[a] < rank[b]) {
int temp = a;
a = b;
b = temp;
}
parent[b] = a;
if (rank[a] == rank[b])
rank[a]++;
}
}
}
private static class SCC {
private final int n;
private final List<List<Integer>> adjList;
SCC(int _n, List<List<Integer>> _adjList) {
n = _n;
adjList = _adjList;
}
private List<List<Integer>> getSCC() {
List<List<Integer>> ans = new ArrayList<>();
Stack<Integer> stack = new Stack<>();
boolean[] vis = new boolean[n];
for (int i = 0; i < n; i++) {
if (!vis[i]) dfs(i, adjList, vis, stack);
}
vis = new boolean[n];
List<List<Integer>> rev_adjList = rev_graph(n, adjList);
while (!stack.isEmpty()) {
int curr = stack.pop();
if (!vis[curr]) {
List<Integer> scc_list = new ArrayList<>();
dfs2(curr, rev_adjList, vis, scc_list);
ans.add(scc_list);
}
}
return ans;
}
private void dfs(int curr, List<List<Integer>> adjList, boolean[] vis, Stack<Integer> stack) {
vis[curr] = true;
for (int x : adjList.get(curr)) {
if (!vis[x]) dfs(x, adjList, vis, stack);
}
stack.add(curr);
}
private void dfs2(int curr, List<List<Integer>> adjList, boolean[] vis, List<Integer> scc_list) {
vis[curr] = true;
scc_list.add(curr);
for (int x : adjList.get(curr)) {
if (!vis[x]) dfs2(x, adjList, vis, scc_list);
}
}
}
private static List<List<Integer>> rev_graph(int n, List<List<Integer>> adjList) {
List<List<Integer>> ans = new ArrayList<>();
for (int i = 0; i < n; i++) ans.add(new ArrayList<>());
for (int i = 0; i < n; i++) {
for (int x : adjList.get(i)) {
ans.get(x).add(i);
}
}
return ans;
}
private 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_with_mod(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 int random_between_two_numbers(int l, int r) {
Random ran = new Random();
return ran.nextInt(r - l) + l;
}
private static long gcd(long a, long b) {
return (b == 0 ? a : gcd(b, a % b));
}
private static long lcm(long a, long b) {
return ((a * b) / gcd(a, b));
}
private static long pow(long a, long b) {
long result = 1;
while (b > 0) {
if ((b & 1L) == 1) {
result = (result * a);
}
a = (a * a);
b >>= 1;
}
return result;
}
private static long pow_with_mod(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;
}
private static long ceilDiv(long a, long b) {
return ((a + b - 1) / b);
}
private static long getMin(long... args) {
long min = lMax;
for (long arg : args)
min = Math.min(min, arg);
return min;
}
private static long getMax(long... args) {
long max = lMin;
for (long arg : args)
max = Math.max(max, arg);
return max;
}
private static boolean isPalindrome(String s, int l, int r) {
int i = l, j = r;
while (j - i >= 1) {
if (s.charAt(i) != s.charAt(j))
return false;
i++;
j--;
}
return true;
}
private static List<Integer> primes(int n) {
boolean[] primeArr = new boolean[n + 5];
Arrays.fill(primeArr, true);
for (int i = 2; (i * i) <= n; i++) {
if (primeArr[i]) {
for (int j = i * i; j <= n; j += i) {
primeArr[j] = false;
}
}
}
List<Integer> primeList = new ArrayList<>();
for (int i = 2; i <= n; i++) {
if (primeArr[i])
primeList.add(i);
}
return primeList;
}
private static int noOfSetBits(long x) {
int cnt = 0;
while (x != 0) {
x = x & (x - 1);
cnt++;
}
return cnt;
}
private static int sumOfDigits(long num) {
int cnt = 0;
while (num > 0) {
cnt += (num % 10);
num /= 10;
}
return cnt;
}
private static int noOfDigits(long num) {
int cnt = 0;
while (num > 0) {
cnt++;
num /= 10;
}
return cnt;
}
private static boolean isPerfectSquare(long num) {
long sqrt = (long) Math.sqrt(num);
return ((sqrt * sqrt) == num);
}
private static class Pair<U, V> {
private final U first;
private final V second;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair<?, ?> pair = (Pair<?, ?>) o;
return first.equals(pair.first) && second.equals(pair.second);
}
@Override
public int hashCode() {
return Objects.hash(first, second);
}
@Override
public String toString() {
return "(" + first + ", " + second + ")";
}
private Pair(U ff, V ss) {
this.first = ff;
this.second = ss;
}
}
private static void randomizeIntArr(int[] arr, int n) {
Random r = new Random();
for (int i = (n - 1); i > 0; i--) {
int j = r.nextInt(i + 1);
swapInIntArr(arr, i, j);
}
}
private static void randomizeLongArr(long[] arr, int n) {
Random r = new Random();
for (int i = (n - 1); i > 0; i--) {
int j = r.nextInt(i + 1);
swapInLongArr(arr, i, j);
}
}
private static void swapInIntArr(int[] arr, int a, int b) {
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
private static void swapInLongArr(long[] arr, int a, int b) {
long temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
private static int[] readIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = fs.nextInt();
return arr;
}
private static long[] readLongArray(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++)
arr[i] = fs.nextLong();
return arr;
}
private static List<Integer> readIntList(int n) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++)
list.add(fs.nextInt());
return list;
}
private static List<Long> readLongList(int n) {
List<Long> list = new ArrayList<>();
for (int i = 0; i < n; i++)
list.add(fs.nextLong());
return list;
}
private static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner() throws IOException {
if (checkOnlineJudge)
this.br = new BufferedReader(new FileReader("src/input.txt"));
else
this.br = new BufferedReader(new InputStreamReader(System.in));
this.st = new StringTokenizer("");
}
public String next() {
while (!st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException err) {
err.printStackTrace();
}
}
return st.nextToken();
}
public String nextLine() {
if (st.hasMoreTokens()) {
return st.nextToken("").trim();
}
try {
return br.readLine().trim();
} catch (IOException err) {
err.printStackTrace();
}
return "";
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
private static class FastWriter {
PrintWriter out;
FastWriter() throws IOException {
if (checkOnlineJudge)
out = new PrintWriter(new FileWriter("src/output.txt"));
else
out = new PrintWriter(System.out);
}
}
}
| 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.io.*;
import java.util.*;
public class CF1562C extends PrintWriter {
CF1562C() { super(System.out); }
public static Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF1562C o = new CF1562C(); o.main(); o.flush();
}
static long calculate(long p, long q)
{
long mod = 1000000007, expo;
expo = mod - 2;
// Loop to find the value
// until the expo is not zero
while (expo != 0)
{
// Multiply p with q
// if expo is odd
if ((expo & 1) == 1)
{
p = (p * q) % mod;
}
q = (q * q) % mod;
// Reduce the value of
// expo by 2
expo >>= 1;
}
return p;
}
static String longestPalSubstr(String str)
{
// The result (length of LPS)
int maxLength = 1;
int start = 0;
int len = str.length();
int low, high;
// One by one consider every
// character as center
// point of even and length
// palindromes
for (int i = 1; i < len; ++i) {
// Find the longest even
// length palindrome with
// center points as i-1 and i.
low = i - 1;
high = i;
while (low >= 0 && high < len
&& str.charAt(low)
== str.charAt(high)) {
--low;
++high;
}
// Move back to the last possible valid palindrom substring
// as that will anyway be the longest from above loop
++low; --high;
if (str.charAt(low) == str.charAt(high) && high - low + 1 > maxLength) {
start = low;
maxLength = high - low + 1;
}
// Find the longest odd length
// palindrome with center point as i
low = i - 1;
high = i + 1;
while (low >= 0 && high < len
&& str.charAt(low)
== str.charAt(high)) {
--low;
++high;
}
// Move back to the last possible valid palindrom substring
// as that will anyway be the longest from above loop
++low; --high;
if (str.charAt(low) == str.charAt(high) && high - low + 1 > maxLength) {
start = low;
maxLength = high - low + 1;
}
}
return str.substring(start, start + maxLength - 1);
}
long check(long a){
long ret=0;
for(long k=2;(k*k*k)<=a;k++){
ret=ret+(a/(k*k*k));
}
return ret;
}
/*public static int getFirstSetBitPos(int n)
{
return (int)((Math.log10(n & -n)) / Math.log10(2)) + 1;
}
public static int bfsq(int n, int m, HashMap<Integer,ArrayList<Integer>>h,boolean v ){
v[n]=true;
if(n==m)
return 1;
else
{
int a=h.get(n).get(0);
int b=h.get(n).get(1);
if(b>m)
return(m-n);
else
{
int a1=bfsq(a,m,h,v);
int b1=bfsq(b,m,h,v);
return 1+Math.min(a1,b1);
}
}
}*/
static long nCr(int n, int r)
{ return fact(n) / (fact(r) *
fact(n - r));
}
// Returns factorial of n
static long fact(long n)
{
long res = 1;
for (long i = 2; i <= n; i++)
res = res * i;
return res;
}
/*void bfs(int src, HashMap<Integer,ArrayList<Integer,Integer>>h,int deg, boolean v[] ){
a[src]=deg;
Queue<Integer>= new LinkedList<Integer>();
q.add(src);
while(!q.isEmpty()){
(int a:h.get(src)){
if()
}
}
}*/
/* void dfs(int root, int par, HashMap<Integer,ArrayList<Integer>>h,int dp[], int child[]) {
dp[root]=0;
child[root]=1;
for(int x: h.get(root)){
if(x == par) continue;
dfs(x,root,h,in,dp);
child[root]+=child[x];
}
ArrayList<Integer> mine= new ArrayList<Integer>();
for(int x: h.get(root)) {
if(x == par) continue;
mine.add(x);
}
if(mine.size() >=2){
int y= Math.max(child[mine.get(0)] - 1 + dp[mine.get(1)] , child[mine.get(1)] -1 + dp[mine.get(0)]);
dp[root]=y;}
else if(mine.size() == 1)
dp[root]=child[mine.get(0)] - 1;
}
*/
class Pair implements Comparable<Pair>{
int i;
int j;
Pair (int a, int b){
i = a;
j = b;
}
public int compareTo(Pair A){
return (int)(this.i-A.i);
}}
/*static class Pair {
int i;
int j;
Pair() {
}
Pair(int i, int j) {
this.i = i;
this.j = j;
}
}*/
/*ArrayList<Integer> check(int a[], int b){
int n=a.length;
long ans=0;int k=0;
ArrayList<Integer>ab= new ArrayList<Integer>();
for(int i=0;i<n;i++){
if(a[i]%m==0)
{k=a[i];
while(a[i]%m==0){
a[i]=a[i]/m;
}
for(int z=0;z<k/a[i];z++){
ab.add(a[i]);
}
}
else{
ab.add(a[i]);
}
}
return ab;
} */
/*int check[];
int tree[];
static void build( int []arr)
{
// insert leaf nodes in tree
for (int i = 0; i < n; i++)
tree[n + i] = arr[i];
// build the tree by calculating
// parents
for (int i = n - 1; i > 0; --i){
int ans= Math.min(tree[i << 1],
tree[i << 1 | 1]);
int ans1=Math.max((tree[i << 1],
tree[i << 1 | 1]));
if(ans==0)
}
}*/
/*static void ab(long n)
{
// Note that this loop runs till square root
for (long i=1; i<=Math.sqrt(n); i++)
{
if(i==1)
{
p.add(n/i);
continue;
}
if (n%i==0)
{
// If divisors are equal, print only one
if (n/i == i)
p.add(i);
else // Otherwise print both
{
p.add(i);
p.add(n/i);
}
}
}
}*/
void main() {
int g=sc.nextInt();
int mod=1000000007;
for(int w=0;w<g;w++){
long n=sc.nextLong();
long x=sc.nextLong();
long y=sc.nextLong();
long sum=x+y;
long min=Math.max(1,Math.min(n,x+y-n+1));
long max=Math.min(n,x+y-1);
println(min+" "+max);
}
}
}
| java |
1307 | D | D. Cow and Fieldstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie is out grazing on the farm; which consists of nn fields connected by mm bidirectional roads. She is currently at field 11, and will return to her home at field nn at the end of the day.The Cowfederation of Barns has ordered Farmer John to install one extra bidirectional road. The farm has kk special fields and he has decided to install the road between two different special fields. He may add the road between two special fields that already had a road directly connecting them.After the road is added, Bessie will return home on the shortest path from field 11 to field nn. Since Bessie needs more exercise, Farmer John must maximize the length of this shortest path. Help him!InputThe first line contains integers nn, mm, and kk (2≤n≤2⋅1052≤n≤2⋅105, n−1≤m≤2⋅105n−1≤m≤2⋅105, 2≤k≤n2≤k≤n) — the number of fields on the farm, the number of roads, and the number of special fields. The second line contains kk integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n) — the special fields. All aiai are distinct.The ii-th of the following mm lines contains integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), representing a bidirectional road between fields xixi and yiyi. It is guaranteed that one can reach any field from every other field. It is also guaranteed that for any pair of fields there is at most one road connecting them.OutputOutput one integer, the maximum possible length of the shortest path from field 11 to nn after Farmer John installs one road optimally.ExamplesInputCopy5 5 3
1 3 5
1 2
2 3
3 4
3 5
2 4
OutputCopy3
InputCopy5 4 2
2 4
1 2
2 3
3 4
4 5
OutputCopy3
NoteThe graph for the first example is shown below. The special fields are denoted by red. It is optimal for Farmer John to add a road between fields 33 and 55, and the resulting shortest path from 11 to 55 is length 33. The graph for the second example is shown below. Farmer John must add a road between fields 22 and 44, and the resulting shortest path from 11 to 55 is length 33. | [
"binary search",
"data structures",
"dfs and similar",
"graphs",
"greedy",
"shortest paths",
"sortings"
] | import java.util.*;
import java.lang.*;
public class X
{
public static void main(String[] args)
{
X ob=new X();
Scanner sc=new Scanner(System.in);
int N=sc.nextInt();
int M=sc.nextInt();
int K=sc.nextInt();
int[] KK=new int[K];
for(int i=0;i<K;i++)
{
KK[i]=sc.nextInt();
}
ArrayList<ArrayList<Integer>> LL=new ArrayList<ArrayList<Integer>>();
for(int i=0;i<=N;i++)
{
LL.add(new ArrayList<Integer>());
}
int U;
int V;
for(int i=0;i<M;i++)
{
U=sc.nextInt();
V=sc.nextInt();
LL.get(U).add(V);
LL.get(V).add(U);
}
System.out.println(ob.solve(N,KK,LL));
}
int solve(int N,int[] K,ArrayList<ArrayList<Integer>> LL)
{
int[] SS=new int[N+1];
int[] DD=new int[N+1];
HashSet<Integer> hs=new HashSet<Integer>();
Queue<Integer> q=new LinkedList<>();
hs.add(1);
q.add(1);
SS[1]=0;
int curr=0;
while(0<q.size())
{
curr=q.poll();
for(int i=0;i<LL.get(curr).size();i++)
{
if(!hs.contains(LL.get(curr).get(i)))
{
hs.add(LL.get(curr).get(i));
q.add(LL.get(curr).get(i));
SS[LL.get(curr).get(i)]=SS[curr]+1;
}
}
}
hs.clear();
hs.add(N);
q.add(N);
DD[N]=0;
while(0<q.size())
{
curr=q.poll();
for(int i=0;i<LL.get(curr).size();i++)
{
if(!hs.contains(LL.get(curr).get(i)))
{
hs.add(LL.get(curr).get(i));
q.add(LL.get(curr).get(i));
DD[LL.get(curr).get(i)]=DD[curr]+1;
}
}
}
hs.clear();
for(int i=0;i<K.length;i++)
{
hs.add(K[i]);
}
int[][] P=new int[K.length][2];
PriorityQueue<Point> pq=new PriorityQueue<Point>(new PC());
for(int i=1;i<=N;i++)
{
//System.out.println("SS["+i+"] = " +SS[i]+", DD["+i+"] = "+DD[i]);
if(hs.contains(i))
{
pq.add(new Point(SS[i],DD[i]));
}
}
Point Pt=null;
for(int i=0;i<P.length;i++)
{
Pt=pq.poll();
P[i][0]=Pt.SS;
P[i][1]=Pt.DD;
}
int ms=P[0][1];
int mp=0;
for(int i=1;i<P.length;i++)
{
mp=Math.max(mp,P[i][0]+ms+1);
ms=Math.max(ms,P[i][1]);
}
return Math.min(DD[1],mp);
}
class Point
{
int SS;
int DD;
Point(int ss,int dd)
{
SS=ss;
DD=dd;
}
}
class PC implements Comparator<Point>
{
public int compare(Point P1,Point P2)
{
int p1=P1.DD-P1.SS;
int p2=P2.DD-P1.SS;
return p1-p2;
}
}
} | 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 waytoolong {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
int t=s.nextInt();
for(int i=0;i<t;i++) {
String a=s.next();
String b=s.next();
String c=s.next();
int f=0;
for(int j=0;j<a.length();j++) {
if(c.charAt(j)!=b.charAt(j)&&c.charAt(j)!=a.charAt(j)) {
f=1;
break;
}
}
if(f==1) {
System.out.println("no");
}
else {
System.out.println("yes");
}
}
}
} | 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"
] | //package educational.round83;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.InputMismatchException;
public class G {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni()+1;
int[] from = new int[n-1];
int[] to = new int[n-1];
int[] ws = new int[n-1];
for(int i = 0;i < n-1;i++){
from[i] = ni();
to[i] = i+1;
ws[i] = nc();
}
g = packWU(n, from, to, ws);
for(int[][] row : g){
Arrays.sort(row, new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
return a[1] - b[1];
}
});
}
int[][] pars = parents(g, 0);
par = pars[0];
int[] ord = pars[1], dep = pars[2];
int[] med = na(ni());
which = new int[n];
Arrays.fill(which, -1);
for(int i = 0;i < med.length;i++){
which[med[i]] = i;
}
hld = new HeavyLightDecomposition(g, par, ord, dep);
ssts = new StarrySkyTreeL[hld.m];
for(int i = 0;i < hld.m;i++){
ssts[i] = new StarrySkyTreeL(hld.cluspath[i].length);
}
dp = new long[n];
dfs(0);
for(int i = 0;i < med.length;i++){
out.print(dp[med[i]] + " ");
}
out.println();
}
int[] which;
long[] dp;
int[] par;
HeavyLightDecomposition hld;
StarrySkyTreeL[] ssts;
int[][][] g;
void dfs(int i)
{
if(i == 0){
}else if(which[i] == -1){
dp[i] = dp[par[i]] + 1;
}else{
for(int x = i;x != -1;){
int cx = hld.clus[x];
int r = hld.clusiind[x];
ssts[cx].add(0, r+1, 1);
x = par[hld.cluspath[cx][0]];
}
long dpmin = dp[par[i]]+1;
for(int x = par[i];x != -1;){
int cx = hld.clus[x];
int r = hld.clusiind[x];
dpmin = Math.min(dpmin, ssts[cx].min(0, r+1));
x = par[hld.cluspath[cx][0]];
}
dp[i] = dpmin;
}
ssts[hld.clus[i]].add(hld.clusiind[i], hld.clusiind[i]+1, dp[i]);
for(int[] e : g[i]){
if(par[i] == e[0])continue;
dfs(e[0]);
}
}
public static class StarrySkyTreeL {
public int M, H, N;
public long[] st;
public long[] plus;
public long I = Long.MAX_VALUE/4; // I+plus<long
public StarrySkyTreeL(int n)
{
N = n;
M = Integer.highestOneBit(Math.max(n-1, 1))<<2;
H = M>>>1;
st = new long[M];
plus = new long[H];
}
public StarrySkyTreeL(long[] a)
{
N = a.length;
M = Integer.highestOneBit(Math.max(N-1, 1))<<2;
H = M>>>1;
st = new long[M];
for(int i = 0;i < N;i++){
st[H+i] = a[i];
}
plus = new long[H];
Arrays.fill(st, H+N, M, I);
for(int i = H-1;i >= 1;i--)propagate(i);
}
private void propagate(int i)
{
st[i] = Math.min(st[2*i], st[2*i+1]) + plus[i];
}
public void add(int l, int r, long v){ if(l < r)add(l, r, v, 0, H, 1); }
private void add(int l, int r, long v, int cl, int cr, int cur)
{
if(l <= cl && cr <= r){
if(cur >= H){
st[cur] += v;
}else{
plus[cur] += v;
propagate(cur);
}
}else{
int mid = cl+cr>>>1;
if(cl < r && l < mid){
add(l, r, v, cl, mid, 2*cur);
}
if(mid < r && l < cr){
add(l, r, v, mid, cr, 2*cur+1);
}
propagate(cur);
}
}
public long min(int l, int r){ return l >= r ? I : min(l, r, 0, H, 1);}
private long min(int l, int r, int cl, int cr, int cur)
{
if(l <= cl && cr <= r){
return st[cur];
}else{
int mid = cl+cr>>>1;
long ret = I;
if(cl < r && l < mid){
ret = Math.min(ret, min(l, r, cl, mid, 2*cur));
}
if(mid < r && l < cr){
ret = Math.min(ret, min(l, r, mid, cr, 2*cur+1));
}
return ret + plus[cur];
}
}
public void fall(int i)
{
if(i < H){
if(2*i < H){
plus[2*i] += plus[i];
plus[2*i+1] += plus[i];
}
st[2*i] += plus[i];
st[2*i+1] += plus[i];
plus[i] = 0;
}
}
public int firstle(int l, long v) {
int cur = H+l;
for(int i = 1, j = Integer.numberOfTrailingZeros(H)-1;i <= cur;j--){
fall(i);
i = i*2|cur>>>j&1;
}
while(true){
fall(cur);
if(st[cur] <= v){
if(cur < H){
cur = 2*cur;
}else{
return cur-H;
}
}else{
cur++;
if((cur&cur-1) == 0)return -1;
cur = cur>>>Integer.numberOfTrailingZeros(cur);
}
}
}
public int lastle(int l, long v) {
int cur = H+l;
for(int i = 1, j = Integer.numberOfTrailingZeros(H)-1;i <= cur;j--){
fall(i);
i = i*2|cur>>>j&1;
}
while(true){
fall(cur);
if(st[cur] <= v){
if(cur < H){
cur = 2*cur+1;
}else{
return cur-H;
}
}else{
if((cur&cur-1) == 0)return -1;
cur = cur>>>Integer.numberOfTrailingZeros(cur);
cur--;
}
}
}
public void addx(int l, int r, long v){
if(l >= r)return;
while(l != 0){
int f = l&-l;
if(l+f > r)break;
if(f == 1){
st[(H+l)/f] += v;
}else{
plus[(H+l)/f] += v;
}
l += f;
}
while(l < r){
int f = r&-r;
if(f == 1){
st[(H+r)/f-1] += v;
}else{
plus[(H+r)/f-1] += v;
}
r -= f;
}
}
public long minx(int l, int r){
long lmin = I;
if(l >= r)return lmin;
if(l != 0){
for(int d = 0;H>>>d > 0;d++){
if(d > 0){
int id = (H+l-1>>>d);
lmin += plus[id];
}
if(l<<~d<0 && l+(1<<d) <= r){
long v = st[H+l>>>d];
if(v < lmin)lmin = v;
l += 1<<d;
}
}
}
long rmin = I;
for(int d = 0;H>>>d > 0;d++){
if(d > 0 && r < H)rmin += plus[H+r>>>d];
if(r<<~d<0 && l < r){
long v = st[(H+r>>>d)-1];
if(v < rmin)rmin = v;
r -= 1<<d;
}
}
long min = Math.min(lmin, rmin);
return min;
}
public long[] toArray() { return toArray(1, 0, H, new long[H]); }
private long[] toArray(int cur, int l, int r, long[] ret)
{
if(r-l == 1){
ret[cur-H] = st[cur];
}else{
toArray(2*cur, l, l+r>>>1, ret);
toArray(2*cur+1, l+r>>>1, r, ret);
for(int i = l;i < r;i++)ret[i] += plus[cur];
}
return ret;
}
}
public static class HeavyLightDecomposition {
public int[][][] g;
public int[] clus;
public int[][] cluspath;
public int[] clusiind;
public int[] par, dep;
public int m;
public HeavyLightDecomposition(int[][][] g, int[] par, int[] ord, int[] dep)
{
init(g, par, ord, dep);
}
public void init(int[][][] g, int[] par, int[] ord, int[] dep)
{
clus = decomposeToHeavyLight(g, par, ord);
cluspath = clusPaths(clus, ord);
clusiind = clusIInd(cluspath, g.length);
this.m = cluspath.length;
this.par = par;
this.dep = dep;
this.g = g;
}
public static int[] decomposeToHeavyLight(int[][][] g, int[] par, int[] ord)
{
int n = g.length;
int[] size = new int[n];
Arrays.fill(size, 1);
for(int i = n-1;i > 0;i--)size[par[ord[i]]] += size[ord[i]];
int[] clus = new int[n];
Arrays.fill(clus, -1);
int p = 0;
for(int i = 0;i < n;i++){
int u = ord[i];
if(clus[u] == -1)clus[u] = p++;
// centroid path (not heavy path)
int argmax = -1;
for(int[] v : g[u]){
if(par[u] != v[0] && (argmax == -1 || size[v[0]] > size[argmax]))argmax = v[0];
}
if(argmax != -1)clus[argmax] = clus[u];
}
return clus;
}
public static int[][] clusPaths(int[] clus, int[] ord)
{
int n = clus.length;
int[] rp = new int[n];
int sup = 0;
for(int i = 0;i < n;i++){
rp[clus[i]]++;
sup = Math.max(sup, clus[i]);
}
sup++;
int[][] row = new int[sup][];
for(int i = 0;i < sup;i++)row[i] = new int[rp[i]];
for(int i = n-1;i >= 0;i--){
row[clus[ord[i]]][--rp[clus[ord[i]]]] = ord[i];
}
return row;
}
public static int[] clusIInd(int[][] clusPath, int n)
{
int[] iind = new int[n];
for(int[] path : clusPath){
for(int i = 0;i < path.length;i++){
iind[path[i]] = i;
}
}
return iind;
}
public int lca(int x, int y)
{
int rx = cluspath[clus[x]][0];
int ry = cluspath[clus[y]][0];
while(clus[x] != clus[y]){
if(dep[rx] > dep[ry]){
x = par[rx];
rx = cluspath[clus[x]][0];
}else{
y = par[ry];
ry = cluspath[clus[y]][0];
}
}
return clusiind[x] > clusiind[y] ? y : x;
}
public int ancestor(int x, int v)
{
while(x != -1){
if(v <= clusiind[x])return cluspath[clus[x]][clusiind[x]-v];
v -= clusiind[x]+1;
x = par[cluspath[clus[x]][0]];
}
return x;
}
}
public static int[][] parents(int[][][] g, int root) {
int n = g.length;
int[] par = new int[n];
Arrays.fill(par, -1);
int[] dw = new int[n];
int[] pw = new int[n];
int[] dep = new int[n];
int[] q = new int[n];
q[0] = root;
for (int p = 0, r = 1; p < r; p++) {
int cur = q[p];
for (int[] nex : g[cur]) {
if (par[cur] != nex[0]) {
q[r++] = nex[0];
par[nex[0]] = cur;
dep[nex[0]] = dep[cur] + 1;
dw[nex[0]] = dw[cur] + nex[1];
pw[nex[0]] = nex[1];
}
}
}
return new int[][] { par, q, dep, dw, pw };
}
public static int[][][] packWU(int n, int[] from, int[] to, int[] w) {
int[][][] g = new int[n][][];
int[] p = new int[n];
for (int f : from)
p[f]++;
for (int t : to)
p[t]++;
for (int i = 0; i < n; i++)
g[i] = new int[p[i]][2];
for (int i = 0; i < from.length; i++) {
--p[from[i]];
g[from[i]][p[from[i]]][0] = to[i];
g[from[i]][p[from[i]]][1] = w[i];
--p[to[i]];
g[to[i]][p[to[i]]][0] = from[i];
g[to[i]][p[to[i]]][1] = w[i];
}
return g;
}
void run() throws Exception
{
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
Thread t = new Thread(null, null, "~", Runtime.getRuntime().maxMemory()){
@Override
public void run() {
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
};
t.start();
t.join();
// long s = System.currentTimeMillis();
// solve();
// out.flush();
// tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception {
new G().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 |
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"
] | /*
ID: abdelra29
LANG: JAVA
PROG: zerosum
*/
/*
TO LEARN
2-euler tour
*/
/*
TO SOLVE
codeforces 722 kavi on pairing duty
*/
/*
bit manipulation shit
1-Computer Systems: A Programmer's Perspective
2-hacker's delight
*/
/*
TO WATCH
*/
import java.util.*;
import java.math.*;
import java.io.*;
import java.util.stream.Collectors;
public class A{
static FastScanner scan=new FastScanner();
public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out));
static long pow,ans;
static BigInteger xs,ys;
public static void main(String[] args) throws Exception
{
/*
very important tips
1-just fucking think backwards once in your shitty life
2-consider brute forcing and finding some patterns and observations
3-when you're in contest don't get out because you think there is no enough time
*/
//scan=new FastScanner("binary.in");
///out = new PrintWriter("zerosum.out");
/*
READING
3-Introduction to DP with Bitmasking codefoces
4-Bit Manipulation hackerearth
5-read more about mobious and inculsion-exclusion
*/
/*
*/
int tt=1;
// tt=scan.nextInt();
int T=1;
outer:while(tt-->0)
{
BigInteger x0=new BigInteger(scan.next());
BigInteger y0=new BigInteger(scan.next());
BigInteger ax=new BigInteger(scan.next());
BigInteger ay=new BigInteger(scan.next());
BigInteger bx=new BigInteger(scan.next());
BigInteger by=new BigInteger(scan.next());
xs=new BigInteger(scan.next());
ys=new BigInteger(scan.next());
BigInteger t=new BigInteger(scan.next());
//long secondX=ax*x0+bx,secondY=ay*y0+by;
//long diff=secondX-x0,diff2=secondY-y0;*/
ArrayList<BigInteger[]>have=new ArrayList<BigInteger[]>();
have.add(new BigInteger[]{x0,y0});
//have.add(new Pair(secondX,secondY));
for(int i=0;i<100;i++)
{
BigInteger secondX=ax.multiply(have.get(have.size()-1)[0]).add(bx);
BigInteger secondY=ay.multiply(have.get(have.size()-1)[1]).add(by);
//if((secondX.subtract(have.get(have.size()-1)[0])).abs().add(secondY.subtract(have.get(have.size()-1)[1]).abs())>=0)
have.add(new BigInteger[]{secondX,secondY});
}
//have.remove(0);
//out.println(have);
int res=0;
for(int i=0;i<have.size();i++)
{
BigInteger tmpT=t,tmpXs=xs,tmpYs=ys;
int cnt=0;
for(int j=i;j<have.size();j++)
{
BigInteger first=have.get(j)[0].subtract(tmpXs);
//System.out.println(tmpYs);
BigInteger second=have.get(j)[1].subtract(tmpYs);
BigInteger my1=(have.get(i)[0].subtract(tmpXs).abs()).add(have.get(i)[1].subtract(tmpYs).abs());
BigInteger my2=(have.get(j)[0].subtract(tmpXs).abs()).add(have.get(j)[1].subtract(tmpYs).abs());
if((have.get(j)[0].subtract(have.get(i)[0]).abs()).add(have.get(j)[1].subtract(have.get(i)[1]).abs()).compareTo(tmpT.subtract(my1))>0&&(have.get(j)[0].subtract(have.get(i)[0]).abs()).add(have.get(j)[1].subtract(have.get(i)[1]).abs()).compareTo(tmpT.subtract(my2))>0)
break;
if((have.get(j)[0].subtract(have.get(i)[0]).abs()).add(have.get(j)[1].subtract(have.get(i)[1]).abs()).compareTo(tmpT.subtract(my1))>0&&(have.get(j)[0].subtract(have.get(i)[0]).abs()).add(have.get(j)[1].subtract(have.get(i)[1]).abs()).compareTo(tmpT.subtract(my2))<=0){
//out.println(Arrays.toString(have.get(j))+" "+Arrays.toString(have.get(i)));
//out.println("FUCK");
}
//out.println(j);
res=Math.max(res,j-i+1);
// tmpT=tmpT.subtract((have.get(j)[0].subtract(tmpXs).abs()).add(have.get(j)[1].subtract(tmpYs).abs()));
// tmpXs=have.get(j)[0];
// tmpYs=have.get(j)[1];
cnt++;
}
//out.println();
res=Math.max(res,cnt);
}
out.println(res);
}
out.close();
}
static class DSU{
int par[];
long size[];
public DSU(int n)
{
par=new int[n+1];
size=new long[n+1];
for(int i=0;i<n;i++)
par[i]=i;
Arrays.fill(size,1L);
}
void con(int x,int y)
{
x=find(x);
y=find(y);
// System.out.println("X "+x+" Y "+y);
if(x==y)
return;
//System.out.println("FUCK");
ans-=(this.sz(x)*this.sz(y));
//ans-=sz(y);
//pow*=2;
if(size[x]<=size[y])
{
par[x]=y;
size[y]+=size[x];
}
else
{
par[y]=x;
size[x]+=size[y];
}
}
int find(int x)
{
if(x==par[x])
return x;
return par[x]=find(par[x]);
}
boolean is(int x,int y)
{
return find(x)==find(y);
}
long sz(int x)
{
return size[find(x)];
}
}
static class special{
boolean is;
char c;
public special(boolean is,char c)
{
this.is=is;
this.c=c;
}
@Override
public int hashCode() {
return (int)(c+ 31 *(is?1:0));
}
@Override
public boolean equals(Object o){
// System.out.println("FUCK");
if (o == this) return true;
if (o.getClass() != getClass()) return false;
special t = (special)o;
return t.is == is && t.c == c;
}
}
static long binexp(long a,long n)
{
if(n==0)
return 1;
long res=binexp(a,n/2);
if(n%2==1)
return res*res*a;
else
return res*res;
}
static long powMod(long base, long exp, long mod) {
if (base == 0 || base == 1) return base;
if (exp == 0) return 1;
if (exp == 1) return (base % mod+mod)%mod;
long R = (powMod(base, exp/2, mod) % mod+mod)%mod;
R *= R;
R %= mod;
if ((exp & 1) == 1) {
return (base * R % mod+mod)%mod;
}
else return (R %mod+mod)%mod;
}
static double dis(double x1,double y1,double x2,double y2)
{
return Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
}
static long mod(long x,long y)
{
if(x<0)
x=x+(-x/y+1)*y;
return x%y;
}
public static long pow(long b, long e) {
long r = 1;
while (e > 0) {
if (e % 2 == 1) r = r * b ;
b = b * b;
e >>= 1;
}
return r;
}
private static void sort(long[] arr) {
List<Long> list = new ArrayList<>();
for (long object : arr) list.add(object);
Collections.sort(list);
//Collections.reverse(list);
for (int i = 0; i < list.size(); ++i) arr[i] = list.get(i);
}
private static void sort2(long[] arr) {
List<Long> list = new ArrayList<>();
for (Long object : arr) list.add(object);
Collections.sort(list);
Collections.reverse(list);
for (int i = 0; i < list.size(); ++i) arr[i] = list.get(i);
}
static class FastScanner
{
private int BS = 1 << 16;
private char NC = (char) 0;
private byte[] buf = new byte[BS];
private int bId = 0, size = 0;
private char c = NC;
private double cnt = 1;
private BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
} catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
private char getChar() {
while (bId == size) {
try {
size = in.read(buf);
} catch (Exception e) {
return NC;
}
if (size == -1) return NC;
bId = 0;
}
return (char) buf[bId++];
}
public int nextInt() {
return (int) nextLong();
}
public int[] nextInts(int N) {
int[] res = new int[N];
for (int i = 0; i < N; i++) {
res[i] = (int) nextLong();
}
return res;
}
public long[] nextLongs(int N) {
long[] res = new long[N];
for (int i = 0; i < N; i++) {
res[i] = nextLong();
}
return res;
}
public long nextLong() {
cnt = 1;
boolean neg = false;
if (c == NC) c = getChar();
for (; (c < '0' || c > '9'); c = getChar()) {
if (c == '-') neg = true;
}
long res = 0;
for (; c >= '0' && c <= '9'; c = getChar()) {
res = (res << 3) + (res << 1) + c - '0';
cnt *= 10;
}
return neg ? -res : res;
}
public double nextDouble() {
double cur = nextLong();
return c != '.' ? cur : cur + nextLong() / cnt;
}
public double[] nextDoubles(int N) {
double[] res = new double[N];
for (int i = 0; i < N; i++) {
res[i] = nextDouble();
}
return res;
}
public String next() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c > 32) {
res.append(c);
c = getChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c != '\n') {
res.append(c);
c = getChar();
}
return res.toString();
}
public boolean hasNext() {
if (c > 32) return true;
while (true) {
c = getChar();
if (c == NC) return false;
else if (c > 32) return true;
}
}
}
static class Pair implements Comparable<Pair>{
public long x, y,z;
public Pair(long x1, long y1,long z1) {
x=x1;
y=y1;
z=z1;
}
public Pair(long x1, long y1) {
x=x1;
y=y1;
}
@Override
public int hashCode() {
return (int)(x + 31 * y);
}
public String toString() {
return x + " " + y+" "+z;
}
@Override
public boolean equals(Object o){
if (o == this) return true;
if (o.getClass() != getClass()) return false;
Pair t = (Pair)o;
return t.x == x && t.y == y&&t.z==z;
}
public int compareTo(Pair o)
{
return (int)(x-o.x);
}
}
}
| java |
1322 | C | C. Instant Noodlestime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWu got hungry after an intense training session; and came to a nearby store to buy his favourite instant noodles. After Wu paid for his purchase, the cashier gave him an interesting task.You are given a bipartite graph with positive integers in all vertices of the right half. For a subset SS of vertices of the left half we define N(S)N(S) as the set of all vertices of the right half adjacent to at least one vertex in SS, and f(S)f(S) as the sum of all numbers in vertices of N(S)N(S). Find the greatest common divisor of f(S)f(S) for all possible non-empty subsets SS (assume that GCD of empty set is 00).Wu is too tired after his training to solve this problem. Help him!InputThe first line contains a single integer tt (1≤t≤5000001≤t≤500000) — the number of test cases in the given test set. Test case descriptions follow.The first line of each case description contains two integers nn and mm (1 ≤ n, m ≤ 5000001 ≤ n, m ≤ 500000) — the number of vertices in either half of the graph, and the number of edges respectively.The second line contains nn integers cici (1≤ci≤10121≤ci≤1012). The ii-th number describes the integer in the vertex ii of the right half of the graph.Each of the following mm lines contains a pair of integers uiui and vivi (1≤ui,vi≤n1≤ui,vi≤n), describing an edge between the vertex uiui of the left half and the vertex vivi of the right half. It is guaranteed that the graph does not contain multiple edges.Test case descriptions are separated with empty lines. The total value of nn across all test cases does not exceed 500000500000, and the total value of mm across all test cases does not exceed 500000500000 as well.OutputFor each test case print a single integer — the required greatest common divisor.ExampleInputCopy3
2 4
1 1
1 1
1 2
2 1
2 2
3 4
1 1 1
1 1
1 2
2 2
2 3
4 7
36 31 96 29
1 2
1 3
1 4
2 2
2 4
3 1
4 3
OutputCopy2
1
12
NoteThe greatest common divisor of a set of integers is the largest integer gg such that all elements of the set are divisible by gg.In the first sample case vertices of the left half and vertices of the right half are pairwise connected, and f(S)f(S) for any non-empty subset is 22, thus the greatest common divisor of these values if also equal to 22.In the second sample case the subset {1}{1} in the left half is connected to vertices {1,2}{1,2} of the right half, with the sum of numbers equal to 22, and the subset {1,2}{1,2} in the left half is connected to vertices {1,2,3}{1,2,3} of the right half, with the sum of numbers equal to 33. Thus, f({1})=2f({1})=2, f({1,2})=3f({1,2})=3, which means that the greatest common divisor of all values of f(S)f(S) is 11. | [
"graphs",
"hashing",
"math",
"number theory"
] | import java.util.*;
import java.io.*;
public class E626 {
static long mod = (long) 1e9 + 7;
public static void main(String[] args) {
MyScanner sc = new MyScanner();
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt(); int m = sc.nextInt();
ArrayList<Integer> [] adj = new ArrayList[n + 1];
for (int i = 1; i <= n; i++) adj[i] = new ArrayList<>();
long [] c = new long[n + 1];
for (int i = 1; i <= n; i++) c[i] = sc.nextLong();
for (int i = 0; i < m; i++) {
int left = sc.nextInt(); int right = sc.nextInt();
adj[right].add(left);
}
long ans = 0;
for (int i = 1; i <= n; i++) Collections.sort(adj[i]);
long [] hash = new long[n + 1];
Arrays.fill(hash, -1);
for (int i = 1; i <= n; i++) if (adj[i].size() > 0) hash[i] = hash(adj[i]);
Map<Long, Long> map = new HashMap<>();
for (int i = 1; i <= n; i++) {
if (hash[i] != -1) map.put(hash[i], map.getOrDefault(hash[i], 0L) + c[i]);
}
for (Long l: map.values()) ans = gcd(ans, l);
out.println(ans);
}
out.close();
}
static long hash(ArrayList<Integer> a) {
long pow = 1; long res = 0;
for (int i = 0; i < a.size(); i++) {
res = (res + (pow * a.get(i)) % mod) % mod;
pow = (pow * 998244353) % mod;
}
return res;
}
static long gcd(long a, long b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
//-----------MyScanner class for faster input----------
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 |
1285 | F | F. Classical?time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven an array aa, consisting of nn integers, find:max1≤i<j≤nLCM(ai,aj),max1≤i<j≤nLCM(ai,aj),where LCM(x,y)LCM(x,y) is the smallest positive integer that is divisible by both xx and yy. For example, LCM(6,8)=24LCM(6,8)=24, LCM(4,12)=12LCM(4,12)=12, LCM(2,3)=6LCM(2,3)=6.InputThe first line contains an integer nn (2≤n≤1052≤n≤105) — the number of elements in the array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1051≤ai≤105) — the elements of the array aa.OutputPrint one integer, the maximum value of the least common multiple of two elements in the array aa.ExamplesInputCopy3
13 35 77
OutputCopy1001InputCopy6
1 2 4 8 16 32
OutputCopy32 | [
"binary search",
"combinatorics",
"number theory"
] | import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Stack;
public class Solution {
static ArrayList<Integer>[] pfactors, factors;
static int sieve[];
static int count[];
static long ans;
static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static long lcm(long a, long b, long g) {
long z = gcd(a, b);
ans = Math.max(ans, ((a * b) / z) * g);
if (z == 1)
return 1;
return 0;
}
static int get(int x) {
int val = 0;
int l = pfactors[x].size();
for (int i = 0; i < (1 << l); i++) {
int p = 1, c = 0;
for (int j = 0; j < l; j++) {
if ((i & (1 << j)) > 0) {
p = p * pfactors[x].get(l - 1 - j);
c++;
}
}
if (c % 2 == 0)
val = val + count[p];
else
val = val - count[p];
}
return val;
}
static void add(int x, int v) {
for (int z : factors[x]) {
count[z] += v;
}
}
public static void main(String args[]) throws IOException {
FastReader in = new FastReader(System.in);
StringBuilder sb = new StringBuilder();
/*System.out.println("hi");
for(int i=1;i<=10;i++) {
Toolkit.getDefaultToolkit().beep();
System.cu
}
System.out.println("bye");*/
int i, j, MN = 100000;
sieve = new int[MN + 1];
pfactors = new ArrayList[MN + 1];
factors = new ArrayList[MN + 1];
for (i = 1; i <= MN; i++) {
pfactors[i] = new ArrayList<>();
factors[i] = new ArrayList<>();
}
sieve[1] = 1;
for (i = 1; i <= MN; i++) {
if (sieve[i] == 0) {
for (j = i; j <= MN; j += i) {
sieve[j] = i;
factors[j].add(i);
}
} else {
for (j = i; j <= MN; j += i) {
factors[j].add(i);
}
}
}
for (i = 2; i <= MN; i++) {
int temp = i;
while (temp != 1) {
int x = sieve[temp];
pfactors[i].add(x);
while (temp % x == 0)
temp = temp / x;
}
}
boolean pre[] = new boolean[MN + 1];
ans = 0;
int n = in.nextInt();
for (i = 0; i < n; i++) {
int x = in.nextInt();
ans = Math.max(ans, x);
pre[x] = true;
}
count = new int[MN + 1];
for (int gcd = 1; gcd <= MN; gcd++) {
ArrayList<Integer> list = new ArrayList<>();
for (j = gcd; j <= MN; j += gcd) {
if (pre[j]) {
list.add(j/gcd);
}
}
Stack<Integer> st = new Stack<>();
Collections.sort(list, Collections.reverseOrder());
for (int x : list) {
int z = get(x);
if (z == 0) {
st.add(x);
add(x, 1);
} else {
while (z != 0) {
int y = st.pop();
z -= lcm(x, y, gcd);
add(y, -1);
}
}
}
while (!st.isEmpty()) {
add(st.pop(), -1);
}
}
System.out.println(ans);
}
}
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;
}
}
| java |
1304 | A | A. Two Rabbitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBeing tired of participating in too many Codeforces rounds; Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other.He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits can be represented as integer coordinates on a horizontal line. The taller rabbit is currently on position xx, and the shorter rabbit is currently on position yy (x<yx<y). Every second, each rabbit hops to another position. The taller rabbit hops to the positive direction by aa, and the shorter rabbit hops to the negative direction by bb. For example, let's say x=0x=0, y=10y=10, a=2a=2, and b=3b=3. At the 11-st second, each rabbit will be at position 22 and 77. At the 22-nd second, both rabbits will be at position 44.Gildong is now wondering: Will the two rabbits be at the same position at the same moment? If so, how long will it take? Let's find a moment in time (in seconds) after which the rabbits will be at the same point.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤10001≤t≤1000).Each test case contains exactly one line. The line consists of four integers xx, yy, aa, bb (0≤x<y≤1090≤x<y≤109, 1≤a,b≤1091≤a,b≤109) — the current position of the taller rabbit, the current position of the shorter rabbit, the hopping distance of the taller rabbit, and the hopping distance of the shorter rabbit, respectively.OutputFor each test case, print the single integer: number of seconds the two rabbits will take to be at the same position.If the two rabbits will never be at the same position simultaneously, print −1−1.ExampleInputCopy5
0 10 2 3
0 10 3 3
900000000 1000000000 1 9999999
1 2 1 1
1 3 1 1
OutputCopy2
-1
10
-1
1
NoteThe first case is explained in the description.In the second case; each rabbit will be at position 33 and 77 respectively at the 11-st second. But in the 22-nd second they will be at 66 and 44 respectively, and we can see that they will never be at the same position since the distance between the two rabbits will only increase afterward. | [
"math"
] | import java.util.Scanner;
import java.lang.Math;
public class CF3107{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int testCases = scan.nextInt();
while(testCases-->0){
int leftPos = scan.nextInt();
int rightPos = scan.nextInt();
int leftD = scan.nextInt();
int rightD = scan.nextInt();
int n = leftD+rightD;
int leftEq = leftPos-leftD;
int rightEq = rightPos+rightD;
//System.out.println(rightEq-leftEq);
if((rightEq-leftEq)%n==0){
System.out.println((rightEq-leftEq)/n-1);
}else{
System.out.println(-1);
}
}
}
public static int getSumDigits(long num){
int sum = 0;
while(num>0){
sum += num%10;
num = num/10;
}
return sum;
}
} | java |
1320 | A | A. Journey Planningtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTanya wants to go on a journey across the cities of Berland. There are nn cities situated along the main railroad line of Berland, and these cities are numbered from 11 to nn. Tanya plans her journey as follows. First of all, she will choose some city c1c1 to start her journey. She will visit it, and after that go to some other city c2>c1c2>c1, then to some other city c3>c2c3>c2, and so on, until she chooses to end her journey in some city ck>ck−1ck>ck−1. So, the sequence of visited cities [c1,c2,…,ck][c1,c2,…,ck] should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city ii has a beauty value bibi associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities cici and ci+1ci+1, the condition ci+1−ci=bci+1−bcici+1−ci=bci+1−bci must hold.For example, if n=8n=8 and b=[3,4,4,6,6,7,8,9]b=[3,4,4,6,6,7,8,9], there are several three possible ways to plan a journey: c=[1,2,4]c=[1,2,4]; c=[3,5,6,8]c=[3,5,6,8]; c=[7]c=[7] (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?InputThe first line contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the number of cities in Berland.The second line contains nn integers b1b1, b2b2, ..., bnbn (1≤bi≤4⋅1051≤bi≤4⋅105), where bibi is the beauty value of the ii-th city.OutputPrint one integer — the maximum beauty of a journey Tanya can choose.ExamplesInputCopy6
10 7 1 9 10 15
OutputCopy26
InputCopy1
400000
OutputCopy400000
InputCopy7
8 9 26 11 12 29 14
OutputCopy55
NoteThe optimal journey plan in the first example is c=[2,4,5]c=[2,4,5].The optimal journey plan in the second example is c=[1]c=[1].The optimal journey plan in the third example is c=[3,6]c=[3,6]. | [
"data structures",
"dp",
"greedy",
"math",
"sortings"
] | import java.util.*;
import java.io.*;
import java.security.KeyStore.Entry;
public class Main{
static final Random random=new Random();
static long mod=1000000007L;
static HashMap<String,Integer>map=new HashMap<>();
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;
}
int[] readIntArray(int n){
int[] res=new int[n];
for(int i=0;i<n;i++)res[i]=nextInt();
return res;
}
}
static class FastWriter {
private final BufferedWriter bw;
public FastWriter() {
this.bw = new BufferedWriter(new OutputStreamWriter(System.out));
}
public void print(Object object) throws IOException {
bw.append("" + object);
}
public void println(Object object) throws IOException {
print(object);
bw.append("\n");
}
public void close() throws IOException {
bw.close();
}
}
static int ans=0;
public static void main(String[] args) {
try {
FastReader in=new FastReader();
FastWriter out = new FastWriter();
//int testCases=in.nextInt();
int testCases=1;
while(testCases-- > 0){
solve(in);
}
out.close();
} catch (Exception e) {
System.out.println(e);
return;
}
}
public static void solve( FastReader in){
int n=in.nextInt();
//int m=in.nextInt();
//String s=in.next();
//String t=in.next();
//long y=in.nextInt();
//long n=in.nextLong();
//int k=in.nextInt();
//long k=in.nextLong();
StringBuilder res=new StringBuilder();
int[] arr=in.readIntArray(n);
HashMap<Integer,Long> hp=new HashMap<>();
for(int i=0;i<n;i++){
hp.put(arr[i]-(i+1),(long)hp.getOrDefault(arr[i]-(i+1),0L)+arr[i]);
}
ArrayList<Long> ls=new ArrayList<>(hp.values());
Collections.sort(ls);
long ans=ls.get(ls.size()-1);
res.append(""+ans);
System.out.println(res.toString());
}
static void dfs1(Map<String,String> hp,int i,int n,String r){
if(i>n){
ans+=ch(hp,n,r);
return;
}
for(char x='a';x<='f';x++){
dfs1(hp,i+1,n,r+x);
}
}
static int ch(Map<String,String> hp,int n,String r){
for(int i=0;i<n-1;i++){
String x=r.substring(0,2);
if(!hp.containsKey(x))return 0;
r=hp.get(x)+r.substring(2);
}
if(r.equals("a"))return 1;
return 0;
}
static int gcd(int a,int b){
if(b==0){
return a;
}
return gcd(b,a%b);
}
static void sort(int[] arr)
{
ArrayList<Integer> ls = new ArrayList<Integer>();
for(int x: arr)
ls.add(x);
Collections.sort(ls);
for(int i=0; i < arr.length; i++)
arr[i] = ls.get(i);
}
static void reversesort(int[] arr)
{
ArrayList<Integer> ls = new ArrayList<Integer>();
for(int x: arr)
ls.add(x);
Collections.sort(ls);
Collections.reverse(ls);
for(int i=0; i < arr.length; i++)
arr[i] = ls.get(i);
}
static int lcm(int a, int b)
{
return (a / gcd(a, b)) * b;
}
static void debug(String x){
System.out.println(x);
}
static < E > void print(E res)
{
System.out.println(res);
}
static String rString(String s){
StringBuilder sb=new StringBuilder();
sb.append(s);
return sb.reverse().toString();
}
} | 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.io.*;
import java.util.*;
public class Main {
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.nextInt();
int y=f.nextInt();
int temp=x+y;
int k=Math.min(n,temp);
System.out.println(Math.min(n,temp-k+1)+" "+Math.min(temp-1,n));
}
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 |
1312 | D | D. Count the Arraystime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYour task is to calculate the number of arrays such that: each array contains nn elements; each element is an integer from 11 to mm; for each array, there is exactly one pair of equal elements; for each array aa, there exists an index ii such that the array is strictly ascending before the ii-th element and strictly descending after it (formally, it means that aj<aj+1aj<aj+1, if j<ij<i, and aj>aj+1aj>aj+1, if j≥ij≥i). InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105).OutputPrint one integer — the number of arrays that meet all of the aforementioned conditions, taken modulo 998244353998244353.ExamplesInputCopy3 4
OutputCopy6
InputCopy3 5
OutputCopy10
InputCopy42 1337
OutputCopy806066790
InputCopy100000 200000
OutputCopy707899035
NoteThe arrays in the first example are: [1,2,1][1,2,1]; [1,3,1][1,3,1]; [1,4,1][1,4,1]; [2,3,2][2,3,2]; [2,4,2][2,4,2]; [3,4,3][3,4,3]. | [
"combinatorics",
"math"
] | import java.util.*;
import java.io.*;
public class Main {
static StringBuilder sb;
static dsu dsu;
static long fact[];
static long mod = 998244353l;
static void solve(long n,long m) {
if(n<=2){
sb.append("0");
return;
}
long v1 = ncr((int)m,(int)n-1);
long v2 = n-2;
long v3 = p(2,n-3);
long ans = ((v1*v2)+mod)%mod;
ans = ((ans*v3)+mod)%mod;
sb.append(ans);
}
public static void main(String[] args) {
sb = new StringBuilder();
int test = 1;
while (test-- > 0) {
long n=l();
long m=l();
factorial(m);
solve(n,m);
}
System.out.println(sb);
}
public static void factorial(long m){
fact=new long[(int)m+1];
fact[0] = 1;
fact[1] = 1;
for(int i = 2; i<=m;i++)
fact[i] = ((long
)fact[i-1]*i)%mod;
}
//**************NCR%P******************
static long ncr(int n, int r) {
if (r > n)
return (long) 0;
long res = fact[n] % mod;
// System.out.println(res);
res = ((long) (res % mod) * (long) (p(fact[r], mod - 2) % mod)) % mod;
res = ((long) (res % mod) * (long) (p(fact[n - r], mod - 2) % mod)) % mod;
// System.out.println(res);
return res;
}
static long p(long x, long y)// POWER FXN //
{
if (y == 0)
return 1;
long res = 1;
while (y > 0) {
if (y % 2 == 1) {
res = (res * x) % mod;
y--;
}
x = (x * x) % mod;
y = y / 2;
}
return res;
}
//**************END******************
// *************Disjoint set
// union*********//
static class dsu {
int parent[];
dsu(int n) {
parent = new int[n];
for (int i = 0; i < n; i++)
parent[i] = -1;
}
int find(int a) {
if (parent[a] < 0)
return a;
else {
int x = find(parent[a]);
parent[a] = x;
return x;
}
}
void merge(int a, int b) {
a = find(a);
b = find(b);
if (a == b)
return;
parent[b] = a;
}
}
//**************PRIME FACTORIZE **********************************//
static TreeMap<Integer, Integer> prime(long n) {
TreeMap<Integer, Integer> h = new TreeMap<>();
long num = n;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (n % i == 0) {
int nt = 0;
while (n % i == 0) {
n = n / i;
nt++;
}
h.put(i, nt);
}
}
if (n != 1)
h.put((int) n, 1);
return h;
}
//****CLASS PAIR ************************************************
static class Pair implements Comparable<Pair> {
int x;
long y;
Pair(int x, long y) {
this.x = x;
this.y = y;
}
public int compareTo(Pair o) {
return (int) (this.y - o.y);
}
}
//****CLASS PAIR **************************************************
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int Int() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String String() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return String();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
}
static InputReader in = new InputReader(System.in);
static OutputWriter out = new OutputWriter(System.out);
public static long[] sort(long[] a2) {
int n = a2.length;
ArrayList<Long> l = new ArrayList<>();
for (long i : a2)
l.add(i);
Collections.sort(l);
for (int i = 0; i < l.size(); i++)
a2[i] = l.get(i);
return a2;
}
public static char[] sort(char[] a2) {
int n = a2.length;
ArrayList<Character> l = new ArrayList<>();
for (char i : a2)
l.add(i);
Collections.sort(l);
for (int i = 0; i < l.size(); i++)
a2[i] = l.get(i);
return a2;
}
public static long pow(long x, long y) {
long res = 1;
while (y > 0) {
if (y % 2 != 0) {
res = (res * x);// % modulus;
y--;
}
x = (x * x);// % modulus;
y = y / 2;
}
return res;
}
//GCD___+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
public static long gcd(long x, long y) {
if (x == 0)
return y;
else
return gcd(y % x, x);
}
// ******LOWEST COMMON MULTIPLE
// *********************************************
public static long lcm(long x, long y) {
return (x * (y / gcd(x, y)));
}
//INPUT PATTERN********************************************************
public static int i() {
return in.Int();
}
public static long l() {
String s = in.String();
return Long.parseLong(s);
}
public static String s() {
return in.String();
}
public static int[] readArrayi(int n) {
int A[] = new int[n];
for (int i = 0; i < n; i++) {
A[i] = i();
}
return A;
}
public static long[] readArray(long n) {
long A[] = new long[(int) n];
for (int i = 0; i < n; i++) {
A[i] = l();
}
return A;
}
} | java |
1324 | B | B. Yet Another Palindrome Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.Your task is to determine if aa has some subsequence of length at least 33 that is a palindrome.Recall that an array bb is called a subsequence of the array aa if bb can be obtained by removing some (possibly, zero) elements from aa (not necessarily consecutive) without changing the order of remaining elements. For example, [2][2], [1,2,1,3][1,2,1,3] and [2,3][2,3] are subsequences of [1,2,1,3][1,2,1,3], but [1,1,2][1,1,2] and [4][4] are not.Also, recall that a palindrome is an array that reads the same backward as forward. In other words, the array aa of length nn is the palindrome if ai=an−i−1ai=an−i−1 for all ii from 11 to nn. For example, arrays [1234][1234], [1,2,1][1,2,1], [1,3,2,2,3,1][1,3,2,2,3,1] and [10,100,10][10,100,10] are palindromes, but arrays [1,2][1,2] and [1,2,3,1][1,2,3,1] are not.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.Next 2t2t lines describe test cases. The first line of the test case contains one integer nn (3≤n≤50003≤n≤5000) — the length of aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 50005000 (∑n≤5000∑n≤5000).OutputFor each test case, print the answer — "YES" (without quotes) if aa has some subsequence of length at least 33 that is a palindrome and "NO" otherwise.ExampleInputCopy5
3
1 2 1
5
1 2 2 3 2
3
1 1 2
4
1 2 2 1
10
1 1 2 2 3 3 4 4 5 5
OutputCopyYES
YES
NO
YES
NO
NoteIn the first test case of the example; the array aa has a subsequence [1,2,1][1,2,1] which is a palindrome.In the second test case of the example, the array aa has two subsequences of length 33 which are palindromes: [2,3,2][2,3,2] and [2,2,2][2,2,2].In the third test case of the example, the array aa has no subsequences of length at least 33 which are palindromes.In the fourth test case of the example, the array aa has one subsequence of length 44 which is a palindrome: [1,2,2,1][1,2,2,1] (and has two subsequences of length 33 which are palindromes: both are [1,2,1][1,2,1]).In the fifth test case of the example, the array aa has no subsequences of length at least 33 which are palindromes. | [
"brute force",
"strings"
] |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Zz {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
int numberSets = Integer.parseInt(br.readLine());
loop1: for (int nos = 0; nos < numberSets; nos++) {
int size = Integer.parseInt(br.readLine());
int [] data = Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
Map <Integer, Integer> map = new HashMap<Integer,Integer>();
for (int i = 0; i < data.length; i++) {
if (!map.containsKey(data[i])) {
map.put(data[i], i);
} else {
if (i-map.get(data[i])>1) {
System.out.println("YES");
continue loop1;
}
}
}
System.out.println("NO");
}
}
} | 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 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_NEKO_s_Maze_Game {
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 q = f.nextInt();
int blocked = 0;
int grid[][] = new int[2][n];
while(q-- > 0) {
int r = f.nextInt()-1;
int c = f.nextInt()-1;
int nextR = (r+1)%2;
if(grid[r][c] == 0) {
grid[r][c] = 1;
if(c-1 >= 0 && grid[nextR][c-1] == 1) {
blocked++;
}
if(grid[nextR][c] == 1) {
blocked++;
}
if(c+1 < n && grid[nextR][c+1] == 1) {
blocked++;
}
} else {
grid[r][c] = 0;
if(c-1 >= 0 && grid[nextR][c-1] == 1) {
blocked--;
}
if(grid[nextR][c] == 1) {
blocked--;
}
if(c+1 < n && grid[nextR][c+1] == 1) {
blocked--;
}
}
if(blocked > 0) {
out.println("No");
} else {
out.println("Yes");
}
}
}
// 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 | 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.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class cf1141g {
static Map<p, Integer> ind = new HashMap<>();
public static void main(String[] args) throws IOException {
int n = rni(), k = ni(), deg[] = new int[n];
List<List<Integer>> g = g(n);
for (int i = 1; i < n; ++i) {
int u = rni() - 1, v = ni() - 1;
c(g, u, v);
++deg[u];
++deg[v];
ind.put(new p(u, v), i - 1);
}
int sorted[] = copy(deg);
rsort(sorted);
int r = sorted[n - k - 1], ans[] = new int[n - 1];
fill(ans, 1);
prln(r);
dfs(g, 0, -1, r, ans, deg);
prln(ans);
close();
}
static void dfs(List<List<Integer>> g, int i, int p, int r, int[] ans, int[] deg) {
if (deg[i] > r) {
for (int j : g.get(i)) {
if (j != p) {
dfs(g, j, i, r, ans, deg);
}
}
return;
}
Queue<Integer> available = new LinkedList<>();
int excl = -1, cur = 1;
if (p != -1) {
excl = ans[ind.get(new p(i, p))];
}
if (cur == excl) {
++cur;
}
for (int k : g.get(i)) {
if (k != p) {
ans[ind.get(new p(i, k))] = cur++;
if (cur == excl) {
++cur;
}
dfs(g, k, i, r, ans, deg);
}
}
}
static class p {
int a, b;
p(int a_, int b_) {
a = a_;
b = b_;
}
@Override
public String toString() {
return "Pair{" + "a = " + a + ", b = " + b + '}';
}
public boolean equalsChecked(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
p p = (p) o;
return a == p.a && b == p.b;
}
public boolean equalsUnchecked(Object o) {
p p = (p) o;
return a == p.a && b == p.b || a == p.b && b == p.a;
}
@Override
public boolean equals(Object o) {
return equalsUnchecked(o);
}
@Override
public int hashCode() {
return Objects.hash(a, b) + Objects.hash(b, a);
}
}
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 |
1294 | B | B. Collecting Packagestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot in a warehouse and nn packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point (0,0)(0,0). The ii-th package is at the point (xi,yi)(xi,yi). It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point (x,y)(x,y) to the point (x+1,yx+1,y) or to the point (x,y+1)(x,y+1).As we say above, the robot wants to collect all nn packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string ss of length nn is lexicographically less than the string tt of length nn if there is some index 1≤j≤n1≤j≤n that for all ii from 11 to j−1j−1 si=tisi=ti and sj<tjsj<tj. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.InputThe first line of the input contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases. Then test cases follow.The first line of a test case contains one integer nn (1≤n≤10001≤n≤1000) — the number of packages.The next nn lines contain descriptions of packages. The ii-th package is given as two integers xixi and yiyi (0≤xi,yi≤10000≤xi,yi≤1000) — the xx-coordinate of the package and the yy-coordinate of the package.It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The sum of all values nn over test cases in the test doesn't exceed 10001000.OutputPrint the answer for each test case.If it is impossible to collect all nn packages in some order starting from (0,00,0), print "NO" on the first line.Otherwise, print "YES" in the first line. Then print the shortest path — a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path.Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.ExampleInputCopy3
5
1 3
1 2
3 3
5 5
4 3
2
1 0
0 1
1
4 3
OutputCopyYES
RUUURRRRUU
NO
YES
RRRRUUU
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below: | [
"implementation",
"sortings"
] | import java.math.BigInteger;
import java.util.*;
public class Main{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int testcase=sc.nextInt();
for(int tc=1;tc<=testcase;tc++){
//System.out.print("Case #"+tc+": ");
int n = sc.nextInt();
int a[][] = new int[n][2];
for(int i=0;i<n;i++){
a[i][0] = sc.nextInt();
a[i][1] = sc.nextInt();
}
Arrays.sort(a, (x,y) -> x[0]==y[0]? x[1]-y[1] : x[0]-y[0]);
boolean f = true;
for(int i=1;i<n;i++){
if(a[i][1] < a[i-1][1]){
f = false;
break;
}
}
if(!f){
System.out.println("NO");
continue;
}
System.out.println("YES");
int x = 0, y= 0;
for(int i=0;i<n;i++){
while(x < a[i][0]){
System.out.print("R");
x++;
}
while(y < a[i][1]){
System.out.print("U");
y++;
}
}
System.out.println();
}
// a,b=[{},{}] # two map
// for _ in range(int(input())):
// s,x=list(input().split())
// x=int(x)
// if s=="+":
// a[x]=True
// else:
// if x in b:
// y=b[x]
// else:
// y=x
// while y in a:
// y+=x
// b[x]=y
// print(y)
//}
sc.close();
}
static int binarySearch(int arr[], int l, int r, int x)
{
if (r >= l) {
int mid = l + (r - l) / 2;
// If the element is present at the
// middle itself
if (arr[mid] == x)
return mid;
// If element is smaller than mid, then
// it can only be present in left subarray
if (arr[mid] > x)
return binarySearch(arr, l, mid - 1, x);
// Else the element can only be present
// in right subarray
return binarySearch(arr, mid + 1, r, x);
}
// We reach here when element is not present
// in array
return -1;
}
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
// method to return LCM of two numbers
// static int lcm(int a, int b)
// {
// return (a / gcd(a, b)) * b;
// }
static int upper_bound(int arr[], int key)
{
int mid, N = arr.length;
// Initialise starting index and
// ending index
int low = 0;
int high = N;
// Till low is less than high
while (low < high && low != N) {
// Find the index of the middle element
mid = low + (high - low) / 2;
if(key == arr[mid]) {
return mid;
}
// If key is greater than or equal
// to arr[mid], then find in
// right subarray
if (key >= arr[mid]) {
low = mid + 1;
}
// If key is less than arr[mid]
// then find in left subarray
else {
high = mid;
}
}
// If key is greater than last element which is
// array[n-1] then upper bound
// does not exists in the array
if (low > N ) {
low--;
}
// Print the upper_bound index
return low;
}
static int lower_bound(int array[], int key)
{
// Initialize starting index and
// ending index
int low = 0, high = array.length;
int mid;
// Till high does not crosses low
while (low < high) {
// Find the index of the middle element
mid = low + (high - low) / 2;
// If key is less than or equal
// to array[mid], then find in
// left subarray
if (key <= array[mid]) {
high = mid;
}
// If key is greater than array[mid],
// then find in right subarray
else {
low = mid + 1;
}
}
// If key is greater than last element which is
// array[n-1] then lower bound
// does not exists in the array
if(low==-1)
low++;
// Returning the lower_bound index
return low;
}
static boolean palin(int arr[], int i, int j){
while(i < j){
if(arr[i] != arr[j])
return false;
i++;
j--;
}
return true;
}
static boolean palin(String s){
int i=0,j=s.length()-1;
while(i<j){
if(s.charAt(i)!=s.charAt(j))
return false;
i++;
j--;
}
return true;
}
static long minSum(int arr[], int n, int k)
{
// k must be smaller than n
if (n < k)
{
// System.out.println("Invalid");
return -1;
}
// Compute sum of first window of size k
long res = 0;
for (int i=0; i<k; i++)
res += arr[i];
// Compute sums of remaining windows by
// removing first element of previous
// window and adding last element of
// current window.
long curr_sum = res;
for (int i=k; i<n; i++)
{
curr_sum += arr[i] - arr[i-k];
res = Math.min(res, curr_sum);
}
return res;
}
static int nextIndex(int a[], int x){
int n=a.length;
for(int i=x;i<n-1;i++){
if(a[i]>a[i+1]){
return i;
}
}
return n;
}
static void rev(int a[], int i, int j){
while(i<j){
int t=a[i];
a[i]=a[j];
a[j]=t;
i++;
j--;
}
}
static int sorted(int arr[], int n)
{
// Array has one or no element or the
// rest are already checked and approved.
if (n == 1 || n == 0)
return 1;
// Unsorted pair found (Equal values allowed)
if (arr[n - 1] < arr[n - 2])
return 0;
// Last pair was sorted
// Keep on checking
return sorted(arr, n - 1);
}
static void sieveOfEratosthenes(int n, Set<Integer> set)
{
// 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.
boolean 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 greater than or
// equal to the square of it numbers which
// are multiple of p and are less than p^2
// are already been marked.
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
// Print all prime numbers
for (int i = 2; i <= n; i++) {
if (prime[i] == true)
set.add(i);
}
}
static boolean isPowerOfTwo(int n)
{
return (int)(Math.ceil((Math.log(n) / Math.log(2))))
== (int)(Math.floor(((Math.log(n) / Math.log(2)))));
}
static int countBits(int number)
{
// log function in base 2
// take only integer part
return (int)(Math.log(number) /
Math.log(2) + 1);
}
public static void swap(int ans[], int i, int j) {
int temp=ans[i];
ans[i]=ans[j];
ans[j]=temp;
}
static int power(int x, int y, int p)
{
int res = 1; // Initialize result
x = x % p; // Update x if it is more than or
// equal to p
if (x == 0)
return 0; // In case x is divisible by p;
while (y > 0)
{
// If y is odd, multiply x with result
if ((y & 1) != 0)
res = (res * x) % p;
// y must be even now
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
} | java |
1294 | C | C. Product of Three Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given one integer number nn. Find three distinct integers a,b,ca,b,c such that 2≤a,b,c2≤a,b,c and a⋅b⋅c=na⋅b⋅c=n or say that it is impossible to do it.If there are several answers, you can print any.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 nn lines describe test cases. The ii-th test case is given on a new line as one integer nn (2≤n≤1092≤n≤109).OutputFor each test case, print the answer on it. Print "NO" if it is impossible to represent nn as a⋅b⋅ca⋅b⋅c for some distinct integers a,b,ca,b,c such that 2≤a,b,c2≤a,b,c.Otherwise, print "YES" and any possible such representation.ExampleInputCopy5
64
32
97
2
12345
OutputCopyYES
2 4 8
NO
NO
NO
YES
3 5 823
| [
"greedy",
"math",
"number theory"
] | // Source: https://usaco.guide/general/io
import java.io.*;
import java.util.*;
public class CF1294C {
public static void main(String[] args) throws IOException {
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
StringTokenizer st = new StringTokenizer(r.readLine());
int cases = Integer.parseInt(st.nextToken());
for (int i = 0; i < cases; i++) {
StringTokenizer st1 = new StringTokenizer(r.readLine());
int num = Integer.parseInt(st1.nextToken());
ArrayList<Integer> yippee = new ArrayList<Integer>();
for (int n = 0; n < 2; n++) {
//each time, get a factor and add it to YIPPEE!!!!!!!!!!!
//if no factors then print NO!!
//ok.
for (int j = 2; j < Math.sqrt(num); j++) {
if (num % j == 0 && yippee.contains(j) == false) {
yippee.add(j);
num /= j;
break;
}
}
}
if (yippee.size() == 2) {
pw.println("YES");
pw.println(yippee.get(0) + " " + yippee.get(1) + " " + num);
} else {
pw.println("NO");
}
}
/*
* Make sure to include the line below, as it
* flushes and closes the output stream.
*/
pw.close();
}
}
| java |
1304 | D | D. Shortest and Longest LIStime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong recently learned how to find the longest increasing subsequence (LIS) in O(nlogn)O(nlogn) time for a sequence of length nn. He wants to test himself if he can implement it correctly, but he couldn't find any online judges that would do it (even though there are actually many of them). So instead he's going to make a quiz for you about making permutations of nn distinct integers between 11 and nn, inclusive, to test his code with your output.The quiz is as follows.Gildong provides a string of length n−1n−1, consisting of characters '<' and '>' only. The ii-th (1-indexed) character is the comparison result between the ii-th element and the i+1i+1-st element of the sequence. If the ii-th character of the string is '<', then the ii-th element of the sequence is less than the i+1i+1-st element. If the ii-th character of the string is '>', then the ii-th element of the sequence is greater than the i+1i+1-st element.He wants you to find two possible sequences (not necessarily distinct) consisting of nn distinct integers between 11 and nn, inclusive, each satisfying the comparison results, where the length of the LIS of the first sequence is minimum possible, and the length of the LIS of the second sequence is maximum possible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).Each test case contains exactly one line, consisting of an integer and a string consisting of characters '<' and '>' only. The integer is nn (2≤n≤2⋅1052≤n≤2⋅105), the length of the permutation you need to find. The string is the comparison results explained in the description. The length of the string is n−1n−1.It is guaranteed that the sum of all nn in all test cases doesn't exceed 2⋅1052⋅105.OutputFor each test case, print two lines with nn integers each. The first line is the sequence with the minimum length of the LIS, and the second line is the sequence with the maximum length of the LIS. If there are multiple answers, print any one of them. Each sequence should contain all integers between 11 and nn, inclusive, and should satisfy the comparison results.It can be shown that at least one answer always exists.ExampleInputCopy3
3 <<
7 >><>><
5 >>><
OutputCopy1 2 3
1 2 3
5 4 3 7 2 1 6
4 3 1 7 5 2 6
4 3 2 1 5
5 4 2 1 3
NoteIn the first case; 11 22 33 is the only possible answer.In the second case, the shortest length of the LIS is 22, and the longest length of the LIS is 33. In the example of the maximum LIS sequence, 44 '33' 11 77 '55' 22 '66' can be one of the possible LIS. | [
"constructive algorithms",
"graphs",
"greedy",
"two pointers"
] | 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);
BShortestAndLongestLIS solver = new BShortestAndLongestLIS();
int testCount = Integer.parseInt(in.next());
for (int i = 1; i <= testCount; i++)
solver.solve(i, in, out);
out.close();
}
static class BShortestAndLongestLIS {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
char[] arr = in.next().toCharArray();
int[] a1 = new int[n];
int[] a2 = new int[n];
for (int i = n - 1; i >= 0; i--) {
a1[i] = n - i;
a2[i] = i + 1;
}
for (int i = 0; i < n - 1; i++) {
if (arr[i] == '>') continue;
int j = i;
while (j < n - 1 && arr[j] == '<') {
j++;
}
reverse(a1, i, j);
i = j - 1;
}
for (int i = 0; i < n - 1; i++) {
if (arr[i] == '<') continue;
int j = i;
while (j < n - 1 && arr[j] == '>') j++;
reverse(a2, i, j);
i = j - 1;
}
out.println(a1);
out.println(a2);
}
void reverse(int[] arr, int i, int j) {
while (i < j) {
swap(arr, i++, j--);
}
}
void swap(int[] arr, int i, int j) {
if (i != j) {
arr[i] ^= arr[j];
arr[j] ^= arr[i];
arr[i] ^= arr[j];
}
}
}
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 println(int[] array) {
print(array);
writer.println();
}
public void close() {
writer.close();
}
}
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 nextInt() {
return Integer.parseInt(next());
}
}
}
| 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.IOException;
import java.io.InputStreamReader;
public class Bus {
private static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
private static int findIndexWithLesserDelta(long[] dp, long number){
int start = 0, len = dp.length, index;
long cur;
if(dp[dp.length - 1] <= number)
return dp.length;
int lastgoodjobs = -1;
do{
index = start + len / 2;
len = len == 1 ? 0 : (len / 2 + len % 2);
cur = dp[index];
if(cur >= number) { // ИЩЕМ СЛЕВА
lastgoodjobs = index;
}
else{
start = index;
}
} while (len > 0);
cur = dp[lastgoodjobs];
while(lastgoodjobs < dp.length){
if(cur == dp[lastgoodjobs]){
lastgoodjobs++;
}
else
break;
}
return lastgoodjobs;
}
public static void main(String[] args) throws IOException {
int retries = Integer.parseInt(reader.readLine());
while(retries > 0){
retries--;
int a, b, p;
{
String[] str = reader.readLine().split(" ");
a = Integer.parseInt(str[0]);
b = Integer.parseInt(str[1]);
p = Integer.parseInt(str[2]);
}
String stations = reader.readLine();
long[] dp = new long[stations.length()];
dp[0] = 0;
// if(p < b && p < a)
// {
// System.out.println(stations.length());
// continue;
// }
char cur = stations.charAt(0) == 'A' ? 'B' : 'A';
for(int i = 1; i < dp.length; i++){
if(cur != stations.charAt(i - 1)){
dp[i] = dp[i - 1] + (cur == 'A' ? b : a);
cur = stations.charAt(i - 1);
}
else
dp[i] = dp[i - 1];
}
long delta = dp[stations.length() - 1] - p;
if(delta <= 0) //ДЕНЕГ ХВАТИТ НА ВСЮ ДОРОГУ
System.out.println(1);
else{
System.out.println(findIndexWithLesserDelta(dp, delta));
}
}
}
}
| java |
1296 | B | B. Food Buyingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMishka wants to buy some food in the nearby shop. Initially; he has ss burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number 1≤x≤s1≤x≤s, buy food that costs exactly xx burles and obtain ⌊x10⌋⌊x10⌋ burles as a cashback (in other words, Mishka spends xx burles and obtains ⌊x10⌋⌊x10⌋ back). The operation ⌊ab⌋⌊ab⌋ means aa divided by bb rounded down.It is guaranteed that you can always buy some food that costs xx for any possible value of xx.Your task is to say the maximum number of burles Mishka can spend if he buys food optimally.For example, if Mishka has s=19s=19 burles then the maximum number of burles he can spend is 2121. Firstly, he can spend x=10x=10 burles, obtain 11 burle as a cashback. Now he has s=10s=10 burles, so can spend x=10x=10 burles, obtain 11 burle as a cashback and spend it too.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 separate line and consists of one integer ss (1≤s≤1091≤s≤109) — the number of burles Mishka initially has.OutputFor each test case print the answer on it — the maximum number of burles Mishka can spend if he buys food optimally.ExampleInputCopy6
1
10
19
9876
12345
1000000000
OutputCopy1
11
21
10973
13716
1111111111
| [
"math"
] | import java.util.*;
// 19 --> 21
public class foodbuy{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-- > 0){
long fcount = sc.nextLong();
long ans= 0;
while(1>0){
long x = (fcount/10) * 10;
ans +=x;
long y = fcount-x;
fcount = (fcount/10) + y;
if( fcount< 10){
ans+=fcount;
break;
}
}
System.out.println(ans);
}
}
}
| java |
1320 | C | C. World of Darkraft: Battle for Azathothtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputRoma is playing a new expansion for his favorite game World of Darkraft. He made a new character and is going for his first grind.Roma has a choice to buy exactly one of nn different weapons and exactly one of mm different armor sets. Weapon ii has attack modifier aiai and is worth caicai coins, and armor set jj has defense modifier bjbj and is worth cbjcbj coins.After choosing his equipment Roma can proceed to defeat some monsters. There are pp monsters he can try to defeat. Monster kk has defense xkxk, attack ykyk and possesses zkzk coins. Roma can defeat a monster if his weapon's attack modifier is larger than the monster's defense, and his armor set's defense modifier is larger than the monster's attack. That is, a monster kk can be defeated with a weapon ii and an armor set jj if ai>xkai>xk and bj>ykbj>yk. After defeating the monster, Roma takes all the coins from them. During the grind, Roma can defeat as many monsters as he likes. Monsters do not respawn, thus each monster can be defeated at most one.Thanks to Roma's excessive donations, we can assume that he has an infinite amount of in-game currency and can afford any of the weapons and armor sets. Still, he wants to maximize the profit of the grind. The profit is defined as the total coins obtained from all defeated monsters minus the cost of his equipment. Note that Roma must purchase a weapon and an armor set even if he can not cover their cost with obtained coins.Help Roma find the maximum profit of the grind.InputThe first line contains three integers nn, mm, and pp (1≤n,m,p≤2⋅1051≤n,m,p≤2⋅105) — the number of available weapons, armor sets and monsters respectively.The following nn lines describe available weapons. The ii-th of these lines contains two integers aiai and caicai (1≤ai≤1061≤ai≤106, 1≤cai≤1091≤cai≤109) — the attack modifier and the cost of the weapon ii.The following mm lines describe available armor sets. The jj-th of these lines contains two integers bjbj and cbjcbj (1≤bj≤1061≤bj≤106, 1≤cbj≤1091≤cbj≤109) — the defense modifier and the cost of the armor set jj.The following pp lines describe monsters. The kk-th of these lines contains three integers xk,yk,zkxk,yk,zk (1≤xk,yk≤1061≤xk,yk≤106, 1≤zk≤1031≤zk≤103) — defense, attack and the number of coins of the monster kk.OutputPrint a single integer — the maximum profit of the grind.ExampleInputCopy2 3 3
2 3
4 7
2 4
3 2
5 11
1 2 4
2 1 6
3 4 6
OutputCopy1
| [
"brute force",
"data structures",
"sortings"
] | 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.util.Arrays;
import java.util.Comparator;
import java.util.InputMismatchException;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
static class TaskAdapter implements Runnable {
@Override
public void run() {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
Output out = new Output(outputStream);
CWorldOfDarkraftBattleForAzathoth solver = new CWorldOfDarkraftBattleForAzathoth();
solver.solve(1, in, out);
out.close();
}
}
public static void main(String[] args) throws Exception {
Thread thread = new Thread(null, new TaskAdapter(), "", 1<<28);
thread.start();
thread.join();
}
static class CWorldOfDarkraftBattleForAzathoth {
private final int iinf = 1_000_000_000;
private final long linf = 4_000_000_000_000_000_000L;
public CWorldOfDarkraftBattleForAzathoth() {
}
public void solve(int kase, InputReader in, Output pw) {
int n = in.nextInt(), m = in.nextInt(), p = in.nextInt(), mn = (int) 1e6;
SegmentTree st = new SegmentTree(mn+1);
int[][] arr = in.nextInt(n, 2);
{
int[][] tmp = in.nextInt(m, 2);
Arrays.sort(tmp, Comparator.comparingInt(o -> -o[0]));
int min = iinf;
st.add(tmp[0][0], mn, -linf);
for(int i = 0; i<m; i++) {
st.add(i==m-1 ? 0 : tmp[i+1][0], tmp[i][0]-1, -(min = Math.min(min, tmp[i][1])));
}
}
Arrays.sort(arr, Comparator.comparingInt(o -> o[0]));
int[][] mon = in.nextInt(p, 3);
Arrays.sort(mon, Comparator.comparingInt(o -> o[0]));
long ans = -linf;
int j = 0;
for(int i = 0; i<n; i++) {
while(j<p&&mon[j][0]<arr[i][0]) {
st.add(mon[j][1], mn, mon[j++][2]);
}
ans = Math.max(ans, st.max(0, mn)-arr[i][1]);
}
pw.println(ans);
}
}
static interface InputReader {
int nextInt();
default int[] nextInt(int n) {
int[] ret = new int[n];
for(int i = 0; i<n; i++) {
ret[i] = nextInt();
}
return ret;
}
default int[][] nextInt(int n, int m) {
int[][] ret = new int[n][m];
for(int i = 0; i<n; i++) {
ret[i] = nextInt(m);
}
return ret;
}
}
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 int nextInt() {
int 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 SegmentTree {
public long[] arr;
public long[] sumv;
public long[] minv;
public long[] maxv;
public long[] addv;
public long[] setv;
public long _sum;
public long _min;
public long _max;
public long y1;
public long y2;
public long v;
public int n;
public boolean[] setc;
public boolean add;
public SegmentTree(int n) {
this(new long[n]);
}
public SegmentTree(long[] arr) {
this.arr = arr.clone();
n = arr.length;
sumv = new long[n<<2];
minv = new long[n<<2];
maxv = new long[n<<2];
addv = new long[n<<2];
setv = new long[n<<2];
setc = new boolean[n<<2];
for(int i = 0; i<n; i++) {
set(i, arr[i]);
}
}
public void query(int o, int l, int r, long add) {
if(setc[o]) {
long v = setv[o]+add+addv[o];
_sum += v*(Math.min(r, y2)-Math.max(l, y1)+1);
_min = Math.min(_min, v);
_max = Math.max(_max, v);
}else if(y1<=l&&y2>=r) {
_sum += sumv[o]+add*(r-l+1);
_min = Math.min(_min, minv[o]+add);
_max = Math.max(_max, maxv[o]+add);
}else {
int m = (l+r)/2;
if(y1<=m) {
query(o<<1, l, m, add+addv[o]);
}
if(y2>m) {
query(o<<1|1, m+1, r, add+addv[o]);
}
}
}
public void update(int o, int l, int r) {
int lc = o<<1, rc = o<<1|1;
if(y1<=l&&y2>=r) {
if(add) {
addv[o] += v;
}else {
setv[o] = v;
setc[o] = true;
addv[o] = 0;
}
}else {
pushdown(o);
int m = (l+r)/2;
if(y1<=m) {
update(lc, l, m);
}else {
maintain(lc, l, m);
}
if(y2>m) {
update(rc, m+1, r);
}else {
maintain(rc, m+1, r);
}
}
maintain(o, l, r);
}
private void maintain(int o, int l, int r) {
int lc = o<<1, rc = o<<1|1;
if(r>l) {
sumv[o] = sumv[lc]+sumv[rc];
minv[o] = Math.min(minv[lc], minv[rc]);
maxv[o] = Math.max(maxv[lc], maxv[rc]);
}
if(setc[o]) {
minv[o] = maxv[o] = setv[o];
sumv[o] = setv[o]*(r-l+1);
}
if(addv[o]!=0) {
minv[o] += addv[o];
maxv[o] += addv[o];
sumv[o] += addv[o]*(r-l+1);
}
}
private void pushdown(int o) {
int lc = o<<1, rc = o<<1|1;
if(setc[o]) {
setv[lc] = setv[rc] = setv[o];
addv[lc] = addv[rc] = 0;
setc[o] = false;
setc[lc] = setc[rc] = true;
}
if(addv[o]!=0) {
addv[lc] += addv[o];
addv[rc] += addv[o];
addv[o] = 0;
}
}
public void add(int l, int r, long v) {
y1 = l;
y2 = r;
this.v = v;
add = true;
update(1, 0, n-1);
}
public void set(int l, int r, long v) {
y1 = l;
y2 = r;
this.v = v;
add = false;
update(1, 0, n-1);
}
public void set(int p, long v) {
set(p, p, v);
}
public void query(int l, int r) {
y1 = l;
y2 = r;
_sum = 0;
_max = Long.MIN_VALUE;
_min = Long.MAX_VALUE;
query(1, 0, n-1, 0);
}
public long max(int l, int r) {
query(l, r);
return _max;
}
}
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(long l) {
println(String.valueOf(l));
}
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();
}
}
}
}
| 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.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Random;
import java.util.Set;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeSet;
import java.util.stream.Collectors;
public class Main {
static int mod = (int) (1e9) + 7;
/* ======================DSU===================== */
static class dsu {
static int parent[], n;// min[],value[];
static long size[];
dsu(int n) {
parent = new int[n + 1];
size = new long[n + 1];
// min=new int[n+1];
// value=new int[n+1];
this.n = n;
makeSet();
}
static void makeSet() {
for (int i = 1; i <= n; i++) {
parent[i] = i;
size[i] = 1;
// min[i]=i;
}
}
static int find(int a) {
if (parent[a] == a)
return a;
else {
return parent[a] = find(parent[a]);// Path Compression
}
}
static void union(int a, int b) {
int setA = find(a);
int setB = find(b);
if (setA == setB)
return;
if (size[setA] >= size[setB]) {
parent[setB] = setA;
size[setA] += size[setB];
} else {
parent[setA] = setB;
size[setB] += size[setA];
}
}
}
/* ======================================================== */
static class Pair<X extends Number, Y extends Number> implements Comparator<Pair> {
X x;
Y y;
// Constructor
public Pair(X x, Y y) {
this.x = x;
this.y = y;
}
public Pair() {
}
@Override
public int compare(Main.Pair o1, Main.Pair o2) {
return ((int) (o1.y.intValue() - o2.y.intValue()));// Ascending Order based on 'y'
}
}
/* ===============================Tries================================= */
static class TrieNode {
private HashMap<Character, TrieNode> children = new HashMap<>();
public int size;
boolean endOfWord;
public void putChildIfAbsent(char ch) {
children.putIfAbsent(ch, new TrieNode());
}
public TrieNode getChild(char ch) {
return children.get(ch);
}
}
static private TrieNode root;
public static void insert(String str) {
TrieNode curr = root;
for (char ch : str.toCharArray()) {
curr.putChildIfAbsent(ch);
curr = curr.getChild(ch);
curr.size++;
}
// mark the current nodes endOfWord as true
curr.endOfWord = true;
}
public static int search(String word) {
TrieNode curr = root;
for (char ch : word.toCharArray()) {
curr = curr.getChild(ch);
if (curr == null) {
return 0;
}
}
// size contains words starting with prefix- word
return curr.size;
}
public boolean delete(TrieNode current, String word, int index) {
if (index == word.length()) {
// when end of word is reached only delete if currrent.endOfWord is true.
if (!current.endOfWord) {
return false;
}
current.endOfWord = false;
// if current has no other mapping then return true
return current.children.size() == 0;
}
char ch = word.charAt(index);
TrieNode node = current.children.get(ch);
if (node == null) {
return false;
}
boolean shouldDeleteCurrentNode = delete(node, word, index + 1);
// if true is returned then delete the mapping of character and trienode
// reference from map.
if (shouldDeleteCurrentNode) {
current.children.remove(ch);
// return true if no mappings are left in the map.
return current.children.size() == 0;
}
return false;
}
/* ================================================================= */
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;
}
int[] intArr(int n) {
int res[] = new int[n];
for (int i = 0; i < n; i++)
res[i] = nextInt();
return res;
}
long[] longArr(int n) {
long res[] = new long[n];
for (int i = 0; i < n; i++)
res[i] = nextLong();
return res;
}
}
static FastReader f = new FastReader();
static BufferedWriter w = new BufferedWriter(new OutputStreamWriter(System.out));
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 int lowerBound(int a[], int x) { // x is the target, returns lowerBound. If not found return -1
int l = -1, r = a.length, flag = 0;
while (l + 1 < r) {
int m = (l + r) >>> 1;
if (x == a[m])
flag = 1;
if (a[m] >= x)
r = m;
else
l = m;
}
return r;
}
static int upperBound(int a[], int x) {// x is the target, returns upperBound. If not found return -1
int l = -1, r = a.length, flag = 0;
while (l + 1 < r) {
int m = (l + r) >>> 1;
if (a[m] == x)
flag = 1;
if (a[m] <= x)
l = m;
else
r = m;
}
return (l + 1);
}
static long gcd(long a, long b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
static long lcm(long a, long b) {
return (a * b) / gcd(a, b);
}
static long power(long x, long y) {
long res = 1;
while (y > 0) {
if (y % 2 == 1)
res = (res * x);
y >>= 1;
x = (x * x);
}
return res;
}
public double binPow(double x, int n) {// binary exponentiation with negative power as well
if (n == 0)
return 1.0;
double binPow = binPow(x, n / 2);
if (n % 2 == 0) {
return binPow * binPow;
} else {
return n > 0 ? (binPow * binPow * x) : (binPow * binPow / x);
}
}
static long ceil(long x, long y) {
return (x % y == 0 ? x / y : (x / y + 1));
}
/*
* ===========Modular Operations==================
*/
static long modPower(long x, long y, long p) {
long res = 1;
x = x % p;
while (y > 0) {
if (y % 2 == 1)
res = (res * x) % p;
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
static long modInverse(long n, long p) {
return modPower(n, p - 2, p);
}
static long modAdd(long a, long b) {
return ((a + b + mod) % mod);
}
static long modMul(long a, long b) {
return ((a % mod) * (b % mod)) % mod;
}
static long nCrModPFermat(int n, int r) {
if (r == 0)
return 1;
long[] fac = new long[n + 1];
fac[0] = 1;
for (int i = 1; i <= n; i++)
fac[i] = fac[i - 1] * i % mod;
return (fac[n] * modInverse(fac[r], mod) % mod * modInverse(fac[n - r], mod) % mod) % mod;
}
/*
* ===============================================
*/
static void ruffleSort(long[] a) {
int n = a.length;
Random r = new Random();
for (int i = 0; i < a.length; i++) {
int oi = r.nextInt(n);
long temp = a[i];
a[i] = a[oi];
a[oi] = temp;
}
Arrays.sort(a);
}
static void ruffleSort(int[] a) {
int n = a.length;
Random r = new Random();
for (int i = 0; i < a.length; i++) {
int oi = r.nextInt(n);
int temp = a[i];
a[i] = a[oi];
a[oi] = temp;
}
Arrays.sort(a);
}
static String binString32(int n) {
StringBuilder str = new StringBuilder("");
String bin = Integer.toBinaryString(n);
if (bin.length() != 32) {
for (int k = 0; k < 32 - bin.length(); k++) {
str.append("0");
}
str.append(bin);
}
return str.toString();
}
/*
* ====================================Main=================================
*/
// static int st[], a[];
// static void buildTree(int treeIndex, int lo, int hi) {
// if (hi == lo) {
// st[treeIndex] = a[lo];
// return;
// }
// int mid = (lo + hi) / 2;
// buildTree(treeIndex * 2 + 1, lo, mid);
// buildTree(treeIndex * 2 + 2, mid + 1, hi);
// st[treeIndex] = merge(st[treeIndex * 2 + 1], st[treeIndex * 2 + 2]);
// }
// static void update(int treeIndex, int lo, int hi, int arrIndex, int val) {
// if (hi == lo) {
// st[treeIndex] = val;
// a[arrIndex] = val;
// return;
// }
// int mid = (hi + lo) / 2;
// if (mid < arrIndex) {
// update(treeIndex * 2 + 2, mid + 1, hi, arrIndex, val);
// } else {
// update(treeIndex * 2 + 1, lo, mid, arrIndex, val);
// }
// st[treeIndex] = merge(st[treeIndex * 2 + 1], st[treeIndex * 2 + 2]);
// }
// static int query(int treeIndex, int lo, int hi, int l, int r) {
// if (l <= lo && r >= hi) {
// return st[treeIndex];
// }
// if (l > hi || r < lo) {
// return 0;
// }
// int mid = (hi + lo) / 2;
// return query(treeIndex * 2 + 1, lo, mid, l, Math.min(mid, r));
// }
// static int merge(int a, int b) {
// return a + b;
// }
static long dp[][];
public static long findKthPositive(long[] A, long k) {
int l = 0, r = A.length, m;
while (l < r) {
m = (l + r) / 2;
if (A[m] - 1 - m < k)
l = m + 1;
else
r = m;
}
return l + k;
}
static int hash[] = new int[9];
static class Point {
int x, y, c;
Point(int x, int y, int c) {
this.x = x;
this.y = y;
this.c = c;
}
}
public static void main(String args[]) throws Exception {
// File file = new File("D:\\VS Code\\Java\\Output.txt");
// FileWriter fw = new FileWriter("D:\\VS Code\\Java\\Output.txt");
int t = 1;
t = f.nextInt();
int tc = 1;
while (t-- != 0) {
// BufferedReader br = new BufferedReader(new FileReader("PHOBIA.INP"));
// PrintWriter pw = new PrintWriter(new BufferedWriter(new
// FileWriter("PHOBIA.OUT")));
int n = f.nextInt();
int x=f.nextInt();
int y=f.nextInt();
int min=Math.max(1,Math.min(n,x+y-n+1));
int max=Math.min(n,x+y-1);
w.write(min+" "+max+"\n");
}
w.flush();
}
}
/*
*/ | java |
1310 | A | A. Recommendationstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK news recommendation system daily selects interesting publications of one of nn disjoint categories for each user. Each publication belongs to exactly one category. For each category ii batch algorithm selects aiai publications.The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of ii-th category within titi seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.InputThe first line of input consists of single integer nn — the number of news categories (1≤n≤2000001≤n≤200000).The second line of input consists of nn integers aiai — the number of publications of ii-th category selected by the batch algorithm (1≤ai≤1091≤ai≤109).The third line of input consists of nn integers titi — time it takes for targeted algorithm to find one new publication of category ii (1≤ti≤105)1≤ti≤105).OutputPrint one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.ExamplesInputCopy5
3 7 9 7 8
5 2 5 7 5
OutputCopy6
InputCopy5
1 2 3 4 5
1 1 1 1 1
OutputCopy0
NoteIn the first example; it is possible to find three publications of the second type; which will take 6 seconds.In the second example; all news categories contain a different number of publications. | [
"data structures",
"greedy",
"sortings"
] | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.PriorityQueue;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.AbstractCollection;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Collections;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
ARecommendations solver = new ARecommendations();
solver.solve(1, in, out);
out.close();
}
static class ARecommendations {
public void solve(int testNumber, Scanner sc, PrintWriter pw) {
int n = sc.nextInt();
int[] arr = new int[n];
int[] time = new int[n];
for (int i = 0; i < n; i++)
arr[i] = sc.nextInt();
for (int i = 0; i < n; i++)
time[i] = sc.nextInt();
Integer[] sort = new Integer[n];
for (int i = 0; i < n; i++)
sort[i] = i;
Arrays.sort(sort, (a, b) -> arr[a] - arr[b]);
PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
int last = arr[sort[0]];
long ans = 0;
long cur = 0;
for (int i = 0; i < n; i++) {
if (last != arr[sort[i]]) {
while (last < arr[sort[i]] && !pq.isEmpty()) {
cur -= pq.poll();
ans += cur;
last++;
}
}
pq.add(time[sort[i]]);
cur += time[sort[i]];
last = arr[sort[i]];
}
while (!pq.isEmpty()) {
cur -= pq.poll();
ans += cur;
}
pw.println(ans);
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| java |
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.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
Scanner scn = new Scanner(System.in);
OutputWriter out = new OutputWriter(System.out);
// Always print a trailing "\n" and close the OutputWriter as shown at the end of your output
// example:
int t=scn.nextInt();
for(int i=0;i<t;i++){
long n=scn.nextInt();
long m=scn.nextInt();
long m1=n-m;
long q=m1/(m+1);
long r=m1%(m+1);
long ans=n*(n+1)/2-r*(q+1)*(q+2)/2-(m+1-r)*(q)*(q+1)/2;
out.print(Long.toString(ans)+"\n");
}
out.close();
}
// fast input
static class Scanner {
public BufferedReader reader;
public StringTokenizer tokenizer;
public Scanner(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
String line = reader.readLine();
if (line == null)
return null;
tokenizer = new StringTokenizer(line);
} catch (Exception e) {
throw(new RuntimeException());
}
}
return tokenizer.nextToken();
}
public int nextInt() { return Integer.parseInt(next()); }
public long nextLong() { return Long.parseLong(next()); }
public double nextDouble() { return Double.parseDouble(next()); }
}
// fast output
static class OutputWriter {
BufferedWriter writer;
public OutputWriter(OutputStream stream) {
writer = new BufferedWriter(new OutputStreamWriter(stream));
}
public void print(int i) throws IOException { writer.write(i); }
public void print(String s) throws IOException { writer.write(s); }
public void print(char[] c) throws IOException { writer.write(c); }
public void close() throws IOException { writer.close(); }
}
} | java |
1307 | D | D. Cow and Fieldstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie is out grazing on the farm; which consists of nn fields connected by mm bidirectional roads. She is currently at field 11, and will return to her home at field nn at the end of the day.The Cowfederation of Barns has ordered Farmer John to install one extra bidirectional road. The farm has kk special fields and he has decided to install the road between two different special fields. He may add the road between two special fields that already had a road directly connecting them.After the road is added, Bessie will return home on the shortest path from field 11 to field nn. Since Bessie needs more exercise, Farmer John must maximize the length of this shortest path. Help him!InputThe first line contains integers nn, mm, and kk (2≤n≤2⋅1052≤n≤2⋅105, n−1≤m≤2⋅105n−1≤m≤2⋅105, 2≤k≤n2≤k≤n) — the number of fields on the farm, the number of roads, and the number of special fields. The second line contains kk integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n) — the special fields. All aiai are distinct.The ii-th of the following mm lines contains integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), representing a bidirectional road between fields xixi and yiyi. It is guaranteed that one can reach any field from every other field. It is also guaranteed that for any pair of fields there is at most one road connecting them.OutputOutput one integer, the maximum possible length of the shortest path from field 11 to nn after Farmer John installs one road optimally.ExamplesInputCopy5 5 3
1 3 5
1 2
2 3
3 4
3 5
2 4
OutputCopy3
InputCopy5 4 2
2 4
1 2
2 3
3 4
4 5
OutputCopy3
NoteThe graph for the first example is shown below. The special fields are denoted by red. It is optimal for Farmer John to add a road between fields 33 and 55, and the resulting shortest path from 11 to 55 is length 33. The graph for the second example is shown below. Farmer John must add a road between fields 22 and 44, and the resulting shortest path from 11 to 55 is length 33. | [
"binary search",
"data structures",
"dfs and similar",
"graphs",
"greedy",
"shortest paths",
"sortings"
] | 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.io.BufferedReader;
import java.util.Comparator;
import java.util.ArrayDeque;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author lucasr
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
MyScanner in = new MyScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
DCowAndFields solver = new DCowAndFields();
solver.solve(1, in, out);
out.close();
}
static class DCowAndFields {
public static MyScanner sc;
public static PrintWriter out;
int[] d1;
int[] d2;
public void solve(int testNumber, MyScanner sc, PrintWriter out) {
DCowAndFields.sc = sc;
DCowAndFields.out = out;
int n = sc.nextInt();
int m = sc.nextInt();
int k = sc.nextInt();
Integer[] special = new Integer[k];
for (int i = 0; i < k; i++) {
special[i] = sc.nextInt() - 1;
}
List<Integer>[] adj = new List[n];
for (int i = 0; i < n; i++) {
adj[i] = new ArrayList<>();
}
for (int i = 0; i < m; i++) {
int a = sc.nextInt() - 1;
int b = sc.nextInt() - 1;
adj[a].add(b);
adj[b].add(a);
}
d1 = bfs(adj, 0);
d2 = bfs(adj, n - 1);
Arrays.sort(special, Comparator.comparingInt(this::value));
int ans = d1[n - 1], max = 0;
int maxd1 = 0;
for (int i = 0; i < k; i++) {
if (i > 0) {
max = Math.max(max, maxd1 + 1 + d2[special[i]]);
}
maxd1 = Math.max(maxd1, d1[special[i]]);
}
out.println(Math.min(ans, max));
}
int value(int pos) {
return d1[pos] - d2[pos];
}
int[] bfs(List<Integer>[] adj, int from) {
ArrayDeque<Integer> queue = new ArrayDeque<>();
int[] dist = new int[adj.length];
Arrays.fill(dist, -1);
dist[from] = 0;
queue.add(from);
while (!queue.isEmpty()) {
int cur = queue.pollFirst();
int d = dist[cur];
for (int v : adj[cur])
if (dist[v] == -1) {
dist[v] = d + 1;
queue.addLast(v);
}
}
return dist;
}
}
static class MyScanner {
private BufferedReader br;
private StringTokenizer tokenizer;
public MyScanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| 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.*;
public class Solution
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-->0)
{
String given = sc.next();
String target = sc.next();
System.out.println(solve(given,target));
}
}
private static int solve(String given , String target){
HashMap<Character, TreeSet<Integer>> hm = new HashMap<>();
for (int i = 0; i < given.length(); i++)
{
char ch = given.charAt(i);
if(!hm.containsKey(ch)){
hm.put(ch, new TreeSet<>());
}
hm.get(ch).add(i);
}
// boolean flag = false;
for (char ch : target.toCharArray())
{
if (!hm.containsKey(ch))
{
// System.out.println(-1);
//flag=true;
return -1;
}
}
//if(flag==false){
int ans = 1;
int index = hm.get(target.charAt(0)).first();
for (int i = 1; i < target.length(); i++)
{
char ch = target.charAt(i);
TreeSet<Integer> idxes = hm.get(ch);
Integer next_index = idxes.higher(index);
if (next_index == null)
{
ans++;
index = hm.get(ch).first();
}
else
{
index = next_index;
}
// }
// System.out.println(ans);
//return ans;
}
return ans;
}
} | java |
1311 | B | B. WeirdSorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn.You are also given a set of distinct positions p1,p2,…,pmp1,p2,…,pm, where 1≤pi<n1≤pi<n. The position pipi means that you can swap elements a[pi]a[pi] and a[pi+1]a[pi+1]. You can apply this operation any number of times for each of the given positions.Your task is to determine if it is possible to sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps.For example, if a=[3,2,1]a=[3,2,1] and p=[1,2]p=[1,2], then we can first swap elements a[2]a[2] and a[3]a[3] (because position 22 is contained in the given set pp). We get the array a=[3,1,2]a=[3,1,2]. Then we swap a[1]a[1] and a[2]a[2] (position 11 is also contained in pp). We get the array a=[1,3,2]a=[1,3,2]. Finally, we swap a[2]a[2] and a[3]a[3] again and get the array a=[1,2,3]a=[1,2,3], sorted in non-decreasing order.You can see that if a=[4,1,2,3]a=[4,1,2,3] and p=[3,2]p=[3,2] then you cannot sort the array.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.Then tt test cases follow. The first line of each test case contains two integers nn and mm (1≤m<n≤1001≤m<n≤100) — the number of elements in aa and the number of elements in pp. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100). The third line of the test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n, all pipi are distinct) — the set of positions described in the problem statement.OutputFor each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps. Otherwise, print "NO".ExampleInputCopy6
3 2
3 2 1
1 2
4 2
4 1 2 3
3 2
5 1
1 2 3 4 5
1
4 2
2 1 4 3
1 3
4 2
4 3 2 1
1 3
5 2
2 1 2 3 3
1 4
OutputCopyYES
NO
YES
YES
NO
YES
| [
"dfs and similar",
"sortings"
] | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class WeirdSort {
public static void main(String[] args) throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int t=Integer.parseInt(br.readLine());
int count=0;
while(count<t){
solve(br);
count++;
}
}
static int[] father;
public static void solve(BufferedReader br) throws IOException{
String[] temp=br.readLine().trim().split(" ");
int n=Integer.parseInt(temp[0]);
int m=Integer.parseInt(temp[1]);
int[] nums=new int[n];
temp=br.readLine().trim().split(" ");
Map<Integer,Set<Integer>> map=new HashMap<>();
for(int i=0;i<n;i++){
nums[i]=Integer.parseInt(temp[i]);
if(map.containsKey(nums[i])==false){
map.put(nums[i],new HashSet<>());
}
map.get(nums[i]).add(i);
}
int[] pos=new int[m];
temp=br.readLine().trim().split(" ");
for(int i=0;i<m;i++){
pos[i]=Integer.parseInt(temp[i]);
}
int[] sorted= nums.clone();
Arrays.sort(sorted);
init(n);
for(int p:pos){
union(p,p-1);
}
for(int i=0;i<n;i++){
if(sorted[i]==nums[i]){
continue;
}
int shouldBe=sorted[i];
Set<Integer> indexes=map.get(shouldBe);
boolean find=false;
for(int index:indexes){
if(findFather(i)==findFather(index)){
find=true;
break;
}
}
if(find==false){
System.out.println("NO");
return;
}
}
System.out.println("YES");
}
public static void init(int n){
father=new int[n];
for(int i=0;i<n;i++){
father[i]=i;
}
}
public static int findFather(int x){
if(father[x]==x){
return father[x];
}
father[x]=findFather(father[x]);
return father[x];
}
public static void union(int x1,int x2){
father[findFather(x1)]=findFather(x2);
}
}
| java |
1294 | B | B. Collecting Packagestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot in a warehouse and nn packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point (0,0)(0,0). The ii-th package is at the point (xi,yi)(xi,yi). It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point (x,y)(x,y) to the point (x+1,yx+1,y) or to the point (x,y+1)(x,y+1).As we say above, the robot wants to collect all nn packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string ss of length nn is lexicographically less than the string tt of length nn if there is some index 1≤j≤n1≤j≤n that for all ii from 11 to j−1j−1 si=tisi=ti and sj<tjsj<tj. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.InputThe first line of the input contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases. Then test cases follow.The first line of a test case contains one integer nn (1≤n≤10001≤n≤1000) — the number of packages.The next nn lines contain descriptions of packages. The ii-th package is given as two integers xixi and yiyi (0≤xi,yi≤10000≤xi,yi≤1000) — the xx-coordinate of the package and the yy-coordinate of the package.It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The sum of all values nn over test cases in the test doesn't exceed 10001000.OutputPrint the answer for each test case.If it is impossible to collect all nn packages in some order starting from (0,00,0), print "NO" on the first line.Otherwise, print "YES" in the first line. Then print the shortest path — a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path.Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.ExampleInputCopy3
5
1 3
1 2
3 3
5 5
4 3
2
1 0
0 1
1
4 3
OutputCopyYES
RUUURRRRUU
NO
YES
RRRRUUU
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below: | [
"implementation",
"sortings"
] | import java.util.Arrays;
import java.util.Scanner;
public class sol {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
int[][] arr = new int[n][2];
for (int i = 0; i < n; i++) {
arr[i][0] = sc.nextInt();
arr[i][1] = sc.nextInt();
}
Arrays.sort(arr,(i1,i2)->{
if(i1[0]<i2[0]){
return -1;
}
else if(i1[0]==i2[0]){
return i1[1]<i2[1]?-1:i1[1]>i2[1]?1:0;
}
else{
return 1;
}
});
// Arrays.sort(arr, (a, b) -> a[0] == b[0] ? Integer.compare(a[1], b[1]) : Integer.compare(a[0], b[0]));
StringBuilder sb = new StringBuilder();
boolean ok = true;
int x = 0, y = 0;
for (int i = 0; i < n; i++) {
if (arr[i][1] < y) {
ok = false;
break;
}
while (x < arr[i][0]) {
sb.append("R");
x++;
}
while (y < arr[i][1]) {
sb.append("U");
y++;
}
}
if (ok) {
System.out.println("YES");
System.out.println(sb);
} else {
System.out.println("NO");
}
}
}
}
| 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.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class SimpleStrings {
public static void main(String[] args) throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
solve(br);
}
public static void solve(BufferedReader br) throws IOException{
String s=br.readLine();
int n=s.length();
int[] countRight=new int[n];
countRight[n-1]=(s.charAt(n-1)==')'?1:0);
for(int i=n-2;i>=0;i--){
countRight[i]=countRight[i+1]+(s.charAt(i)==')'?1:0);
}
int maxLeft=0;
int countLeft=0;
for(int i=0;i<n;i++){
char c=s.charAt(i);
if(c=='('){
countLeft++;
if(i+1<n&&countRight[i+1]>=countLeft){
maxLeft=Math.max(maxLeft,countLeft);
}
else{
break;
}
}
}
if(maxLeft==0){
System.out.println(0);
return;
}
List<Integer> res=new ArrayList<>();
int count0=maxLeft;
int count1=maxLeft;
for(int i=0;i<n;i++){
if(s.charAt(i)=='('&&count0>0){
count0--;
res.add(i+1);
}
if(count0==0){
break;
}
}
for(int i=n-1;i>=0;i--){
if(s.charAt(i)==')'&&count1>0){
count1--;
res.add(i+1);
}
if(count1==0){
break;
}
}
Collections.sort(res);
System.out.println(1);
System.out.println(res.size());
for(int num:res){
System.out.print(num);
System.out.print(' ');
}
}
}
| java |
1316 | F | F. Battalion Strengthtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn officers in the Army of Byteland. Each officer has some power associated with him. The power of the ii-th officer is denoted by pipi. As the war is fast approaching, the General would like to know the strength of the army.The strength of an army is calculated in a strange way in Byteland. The General selects a random subset of officers from these nn officers and calls this subset a battalion.(All 2n2n subsets of the nn officers can be chosen equally likely, including empty subset and the subset of all officers).The strength of a battalion is calculated in the following way:Let the powers of the chosen officers be a1,a2,…,aka1,a2,…,ak, where a1≤a2≤⋯≤aka1≤a2≤⋯≤ak. The strength of this battalion is equal to a1a2+a2a3+⋯+ak−1aka1a2+a2a3+⋯+ak−1ak. (If the size of Battalion is ≤1≤1, then the strength of this battalion is 00).The strength of the army is equal to the expected value of the strength of the battalion.As the war is really long, the powers of officers may change. Precisely, there will be qq changes. Each one of the form ii xx indicating that pipi is changed to xx.You need to find the strength of the army initially and after each of these qq updates.Note that the changes are permanent.The strength should be found by modulo 109+7109+7. Formally, let M=109+7M=109+7. It can be shown that the answer can be expressed as an irreducible fraction p/qp/q, where pp and qq are integers and q≢0modMq≢0modM). Output the integer equal to p⋅q−1modMp⋅q−1modM. In other words, output such an integer xx that 0≤x<M0≤x<M and x⋅q≡pmodMx⋅q≡pmodM).InputThe first line of the input contains a single integer nn (1≤n≤3⋅1051≤n≤3⋅105) — the number of officers in Byteland's Army.The second line contains nn integers p1,p2,…,pnp1,p2,…,pn (1≤pi≤1091≤pi≤109).The third line contains a single integer qq (1≤q≤3⋅1051≤q≤3⋅105) — the number of updates.Each of the next qq lines contains two integers ii and xx (1≤i≤n1≤i≤n, 1≤x≤1091≤x≤109), indicating that pipi is updated to xx .OutputIn the first line output the initial strength of the army.In ii-th of the next qq lines, output the strength of the army after ii-th update.ExamplesInputCopy2
1 2
2
1 2
2 1
OutputCopy500000004
1
500000004
InputCopy4
1 2 3 4
4
1 5
2 5
3 5
4 5
OutputCopy625000011
13
62500020
375000027
62500027
NoteIn first testcase; initially; there are four possible battalions {} Strength = 00 {11} Strength = 00 {22} Strength = 00 {1,21,2} Strength = 22 So strength of army is 0+0+0+240+0+0+24 = 1212After changing p1p1 to 22, strength of battallion {1,21,2} changes to 44, so strength of army becomes 11.After changing p2p2 to 11, strength of battalion {1,21,2} again becomes 22, so strength of army becomes 1212. | [
"data structures",
"divide and conquer",
"probabilities"
] | //package com.company;
import java.io.*;
import java.util.*;
public class Main {
public static class Task {
int mod = 1000000007;
int add(int a, int b) {
int c = a + b;
if (c >= mod) return c - mod;
return c;
}
int mul(int a, int b) {
return (int) ((long) a * b % mod);
}
int pow(int a, int b) {
int r = 1;
while (b > 0) {
if (b % 2 == 1) r = mul(r, a);
a = mul(a, a);
b >>= 1;
}
return r;
}
int[] pow2;
public class SegTree {
public class NodeVal {
int len, leftVal, rightVal, totVal;
public NodeVal(int len, int ini) {
this.len = len;
leftVal = rightVal = ini;
totVal = 0;
}
void set(int len, int ini) {
this.len = len;
leftVal = rightVal = ini;
}
public void from(NodeVal left, NodeVal right) {
this.len = left.len + right.len;
this.leftVal = add(right.leftVal, mul(left.leftVal, pow2[right.len]));
this.rightVal = add(left.rightVal, mul(right.rightVal, pow2[left.len]));
this.totVal = add(mul(left.rightVal, right.leftVal),
add(mul(left.totVal, pow2[right.len]), mul(right.totVal, pow2[left.len])));
}
}
NodeVal[] nodes;
int T;
public SegTree(int n) {
T = 1;
while (T < n) T <<= 1;
nodes = new NodeVal[T << 1];
for (int i = 0; i < T << 1; i++) {
nodes[i] = new NodeVal(0, 0);
}
}
void update(int index, int len, int val) {
nodes[index += T].set(len, val);
while (index > 1) {
int parent = index >> 1;
int left = parent << 1;
int right = parent << 1 | 1;
nodes[parent].from(nodes[left], nodes[right]);
index >>= 1;
}
}
}
int solve(int[] strength) {
int n = strength.length;
Arrays.sort(strength);
int ret = 0;
for (int i = 0; i < n; i++) {
int ps = 0;
for (int j = i - 1; j >= 0; j--) {
ps = mul(ps, 2);
ps = add(ps, strength[j]);
}
ps = mul(ps, pow(2, n - 1 - i));
int ss = 0;
for (int j = i + 1; j < n; j++) {
ss = mul(ss, 2);
ss = add(ss, strength[j]);
}
ss = mul(ss, pow(2, i));
ret = add(ret, mul(add(ps, ss), strength[i]));
}
return mul(ret, pow(pow(2, n + 1), mod - 2));
}
public class Pair {
int a, b;
public Pair(int a, int b) {
this.a = a;
this.b = b;
}
}
public void solve(Scanner sc, PrintWriter pw) throws IOException {
int n = sc.nextInt();
int[] a = new int[n];
int[] attachedIndex = new int[n];
List<Pair> ps = new ArrayList<>();
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
ps.add(new Pair(a[i], -(i + 1)));
}
int q = sc.nextInt();
int[][] queries = new int[q][2];
for (int i = 0; i < q; i++) {
for (int j = 0; j < 2; j++) {
queries[i][j] = sc.nextInt();
}
queries[i][0]--;
ps.add(new Pair(queries[i][1], i));
}
ps.sort(new Comparator<Pair>() {
@Override
public int compare(Pair o1, Pair o2) {
return o1.a - o2.a;
}
});
int[] queryIndex = new int[q];
int N = ps.size();
for (int i = 0; i < N; i++) {
if (ps.get(i).b < 0) {
attachedIndex[(-ps.get(i).b) - 1] = i;
} else {
queryIndex[ps.get(i).b] = i;
}
}
int inv2 = pow(pow(2, n), mod - 2);
pow2 = new int[N + 1];
pow2[0] = 1;
for (int i = 1; i <= N; i++) {
pow2[i] = mul(pow2[i - 1], 2);
}
SegTree st = new SegTree(N);
for (int i = 0; i < n; i++) {
st.update(attachedIndex[i], 1, a[i]);
}
int sol = mul(inv2, st.nodes[1].totVal);
// System.err.println(Arrays.toString(attachedIndex));
// System.err.println(sol);
// System.err.println(solve(Arrays.copyOf(a, a.length)));
// if (sol != solve(Arrays.copyOf(a, a.length))) throw new RuntimeException();
pw.println(sol);
for (int i = 0; i < q; i++) {
int index = queries[i][0], value = queries[i][1];
st.update(attachedIndex[index], 0, 0);
st.update(attachedIndex[index] = queryIndex[i], 1, a[index] = value);
sol = mul(inv2, st.nodes[1].totVal);
// if (sol != solve(Arrays.copyOf(a, a.length))) throw new RuntimeException();
pw.println(sol);
}
}
}
static long TIME_START, TIME_END;
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
// Scanner sc = new Scanner(new FileInputStream("input"));
PrintWriter pw = new PrintWriter(new BufferedOutputStream(System.out));
// PrintWriter pw = new PrintWriter(new FileOutputStream("input"));
Runtime runtime = Runtime.getRuntime();
long usedMemoryBefore = runtime.totalMemory() - runtime.freeMemory();
TIME_START = System.currentTimeMillis();
Task t = new Task();
t.solve(sc, pw);
TIME_END = System.currentTimeMillis();
long usedMemoryAfter = runtime.totalMemory() - runtime.freeMemory();
pw.close();
System.err.println("Memory increased: " + (usedMemoryAfter - usedMemoryBefore) / 1000000);
System.err.println("Time used: " + (TIME_END - TIME_START) + ".");
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(FileReader s) throws FileNotFoundException {
br = new BufferedReader(s);
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public boolean ready() throws IOException {
return br.ready();
}
}
} | java |
1295 | B | B. Infinite Prefixestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given string ss of length nn consisting of 0-s and 1-s. You build an infinite string tt as a concatenation of an infinite number of strings ss, or t=ssss…t=ssss… For example, if s=s= 10010, then t=t= 100101001010010...Calculate the number of prefixes of tt with balance equal to xx. The balance of some string qq is equal to cnt0,q−cnt1,qcnt0,q−cnt1,q, where cnt0,qcnt0,q is the number of occurrences of 0 in qq, and cnt1,qcnt1,q is the number of occurrences of 1 in qq. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain descriptions of test cases — two lines per test case. The first line contains two integers nn and xx (1≤n≤1051≤n≤105, −109≤x≤109−109≤x≤109) — the length of string ss and the desired balance, respectively.The second line contains the binary string ss (|s|=n|s|=n, si∈{0,1}si∈{0,1}).It's guaranteed that the total sum of nn doesn't exceed 105105.OutputPrint TT integers — one per test case. For each test case print the number of prefixes or −1−1 if there is an infinite number of such prefixes.ExampleInputCopy4
6 10
010010
5 3
10101
1 0
0
2 0
01
OutputCopy3
0
1
-1
NoteIn the first test case; there are 3 good prefixes of tt: with length 2828, 3030 and 3232. | [
"math",
"strings"
] | import java.util.*;
import java.io.*;
public class Main {
static StringBuilder sb;
static dsu dsu;
static long fact[];
static long mod = (long) (1e9 + 7);
static BufferedReader br;
static HashMap<Long, Long> map;
static void solve() {
int n = i();
int x = i();
String str = s();
int zeros = 0;
for(int i =0;i<n;i++){
if(str.charAt(i)=='0') zeros++;
}
int obal = zeros-(n-zeros); // zero minus one
int cbal = 0;
int ans = 0;
for(int i =0;i<n;i++){
if(obal==0 && cbal==x){
sb.append(-1).append("\n");
return;
}else if(obal!=0){
int div = (x-cbal)/obal;
int mod = (x-cbal)%obal;
if(mod==0 && div>=0) ans++;
}
if(str.charAt(i)=='0') cbal++;
else cbal--;
}
sb.append(ans).append("\n");
}
public static void main(String[] args) throws Exception{
sb = new StringBuilder();
br = new BufferedReader(new InputStreamReader(System.in));
int t = i();
while (t-- > 0) {
solve();
if(t>0) sb.append("\n");
}
out.printLine(sb);
out.close();
}
/*
* fact=new long[(int)1e6+10]; fact[0]=fact[1]=1; for(int i=2;i<fact.length;i++)
* { fact[i]=((long)(i%mod)1L(long)(fact[i-1]%mod))%mod; }
*/
//**************NCR%P******************
static long ncr(int n, int r) {
if (r > n)
return (long) 0;
long res = fact[n] % mod;
res = ((long) (res % mod) * (long) (p(fact[r], mod - 2) % mod)) % mod;
res = ((long) (res % mod) * (long) (p(fact[n - r], mod - 2) % mod)) % mod;
return res;
}
static long p(long x, long y)// POWER FXN MODULO //
{
if (y == 0)
return 1;
long res = 1;
while (y > 0) {
if (y % 2 == 1) {
res = (res * x) % mod;
y--;
}
x = (x * x) % mod;
y = y / 2;
}
return res;
}
// *************Disjoint set
// union*********//
static class dsu {
int parent[];
dsu(int n) {
parent = new int[n];
for (int i = 0; i < n; i++)
parent[i] = -1;
}
int find(int a) {
if (parent[a] < 0)
return a;
else {
int x = find(parent[a]);
parent[a] = x;
return x;
}
}
void merge(int a, int b) {
a = find(a);
b = find(b);
if (a == b)
return;
parent[b] = a;
}
}
//**************PRIME FACTORIZE **********************************//
static TreeMap<Integer, Integer> prime(long n) {
TreeMap<Integer, Integer> h = new TreeMap<>();
long num = n;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (n % i == 0) {
int nt = 0;
while (n % i == 0) {
n = n / i;
nt++;
}
h.put(i, nt);
}
}
if (n != 1)
h.put((int) n, 1);
return h;
}
//****CLASS PAIR ************************************************
static class Pair implements Comparable<Pair> {
int x;
long y;
Pair(int x, long y) {
this.x = x;
this.y = y;
}
public int compareTo(Pair o) {
return (int) (this.y - o.y);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int Int() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String String() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return String();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
}
static InputReader in = new InputReader(System.in);
static OutputWriter out = new OutputWriter(System.out);
public static long[] sort(long[] a2) {
int n = a2.length;
ArrayList<Long> l = new ArrayList<>();
for (long i : a2)
l.add(i);
Collections.sort(l);
for (int i = 0; i < l.size(); i++)
a2[i] = l.get(i);
return a2;
}
public static char[] sort(char[] a2) {
int n = a2.length;
ArrayList<Character> l = new ArrayList<>();
for (char i : a2)
l.add(i);
Collections.sort(l);
for (int i = 0; i < l.size(); i++)
a2[i] = l.get(i);
return a2;
}
//*************NORMAL POWER******************************
public static long pow(long x, long y) {
long res = 1;
while (y > 0) {
if (y % 2 != 0) {
res = (res * x);// % modulus;
y--;
}
x = (x * x);// % modulus;
y = y / 2;
}
return res;
}
//GCD___+++++++++++++++++++++++++++++++
public static long gcd(long x, long y) {
if (x == 0)
return y;
else
return gcd(y % x, x);
}
// ******LOWEST COMMON MULTIPLE
// *********************************************
public static long lcm(long x, long y) {
return (x * (y / gcd(x, y)));
}
// ****BINARY SEARCH****//
private static long bins(long arr[], long tar) {
int low = 0;
int high = arr.length - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] > tar) high = mid - 1;
else if (arr[mid] < tar) low = mid + 1;
else return mid;;
}
return -1;
}
// ********COUNTER******//
private static void count(long arr[]) {
map = new HashMap();
for (long val : arr) map.put(val, map.getOrDefault(val, 0l) + 1l);
}
//INPUT PATTERN********************************************************
public static int i() {
return in.Int();
}
public static long l() {
String s = in.String();
return Long.parseLong(s);
}
public static String s() {
return in.String();
}
public static int[] readArrayi(int n) {
int A[] = new int[n];
for (int i = 0; i < n; i++) {
A[i] = i();
}
return A;
}
public static long[] readArray(long n) {
long A[] = new long[(int) n];
for (int i = 0; i < n; i++) {
A[i] = l();
}
return A;
}
} | 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;
import java.util.StringTokenizer;
public class JustEatIt {
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);
long Yasser = Kadane(arr,0, N - 1);
long Abdel = Math.max(Kadane(arr,0, N - 2), Kadane(arr,1, N - 1));
if (Yasser > Abdel)
{
pw.println("YES");
}
else
{
pw.println("NO");
}
}
pw.close();
}
private static long Kadane(long[] arr, int start, int end)
{
long sum = 0;
long max = Long.MIN_VALUE;
for (int i = start; i <= end; i++)
{
sum += arr[i];
max = Math.max(max, sum);
if (sum < 0)
{
sum = 0;
}
}
return max;
}
private 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 |
1310 | A | A. Recommendationstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK news recommendation system daily selects interesting publications of one of nn disjoint categories for each user. Each publication belongs to exactly one category. For each category ii batch algorithm selects aiai publications.The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of ii-th category within titi seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.InputThe first line of input consists of single integer nn — the number of news categories (1≤n≤2000001≤n≤200000).The second line of input consists of nn integers aiai — the number of publications of ii-th category selected by the batch algorithm (1≤ai≤1091≤ai≤109).The third line of input consists of nn integers titi — time it takes for targeted algorithm to find one new publication of category ii (1≤ti≤105)1≤ti≤105).OutputPrint one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.ExamplesInputCopy5
3 7 9 7 8
5 2 5 7 5
OutputCopy6
InputCopy5
1 2 3 4 5
1 1 1 1 1
OutputCopy0
NoteIn the first example; it is possible to find three publications of the second type; which will take 6 seconds.In the second example; all news categories contain a different number of publications. | [
"data structures",
"greedy",
"sortings"
] | import java.io.*;
import java.util.*;
public class Main {
static IntReader in;
static FastWriter out;
static String INPUT = "";
static void solve() {
int n = ni();
int[][] a = new int[n][2];
for (int i = 0; i < n; i++) {
a[i][0] = ni();
}
for (int i = 0; i < n; i++) {
a[i][1] = ni();
}
PriorityQueue<Integer> q = new PriorityQueue<>((o1, o2) -> o2 - o1);
Arrays.sort(a, (o1, o2) -> (o1[0] - o2[0]));
long sum = 0, t = 0;
long cur = 0;
for (int i = 0; i < n || !q.isEmpty(); i++) {
if (q.isEmpty()) cur = a[i][0];
int j = i;
while (j < n && a[j][0] == cur) {
q.offer(a[j][1]);
t += a[j][1];
j++;
}
i = j - 1;
cur++;
t -= q.poll();
sum += t;
}
out.println(sum);
}
public static void main(String[] args) throws Exception {
in = INPUT.isEmpty() ? new IntReader(System.in) : new IntReader(new ByteArrayInputStream(INPUT.getBytes()));
out = new FastWriter(System.out);
solve();
out.flush();
}
public static class IntReader {
private InputStream is;
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
public IntReader(InputStream is) {
this.is = is;
}
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 int ni() {
return (int) nl();
}
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();
}
}
}
public static class FastWriter {
private static final int BUF_SIZE = 1 << 13;
private final byte[] buf = new byte[BUF_SIZE];
private final OutputStream out;
private int ptr = 0;
private FastWriter() {
out = null;
}
public FastWriter(OutputStream os) {
this.out = os;
}
public FastWriter(String path) {
try {
this.out = new FileOutputStream(path);
} catch (FileNotFoundException e) {
throw new RuntimeException("FastWriter");
}
}
public FastWriter write(byte b) {
buf[ptr++] = b;
if (ptr == BUF_SIZE) innerflush();
return this;
}
public FastWriter write(char c) {
return write((byte) c);
}
public FastWriter write(char[] s) {
for (char c : s) {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerflush();
}
return this;
}
public FastWriter write(String s) {
s.chars().forEach(c -> {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerflush();
});
return this;
}
private static int countDigits(int l) {
if (l >= 1000000000) return 10;
if (l >= 100000000) return 9;
if (l >= 10000000) return 8;
if (l >= 1000000) return 7;
if (l >= 100000) return 6;
if (l >= 10000) return 5;
if (l >= 1000) return 4;
if (l >= 100) return 3;
if (l >= 10) return 2;
return 1;
}
public FastWriter write(int x) {
if (x == Integer.MIN_VALUE) {
return write((long) x);
}
if (ptr + 12 >= BUF_SIZE) innerflush();
if (x < 0) {
write((byte) '-');
x = -x;
}
int d = countDigits(x);
for (int i = ptr + d - 1; i >= ptr; i--) {
buf[i] = (byte) ('0' + x % 10);
x /= 10;
}
ptr += d;
return this;
}
private static int countDigits(long l) {
if (l >= 1000000000000000000L) return 19;
if (l >= 100000000000000000L) return 18;
if (l >= 10000000000000000L) return 17;
if (l >= 1000000000000000L) return 16;
if (l >= 100000000000000L) return 15;
if (l >= 10000000000000L) return 14;
if (l >= 1000000000000L) return 13;
if (l >= 100000000000L) return 12;
if (l >= 10000000000L) return 11;
if (l >= 1000000000L) return 10;
if (l >= 100000000L) return 9;
if (l >= 10000000L) return 8;
if (l >= 1000000L) return 7;
if (l >= 100000L) return 6;
if (l >= 10000L) return 5;
if (l >= 1000L) return 4;
if (l >= 100L) return 3;
if (l >= 10L) return 2;
return 1;
}
public FastWriter write(long x) {
if (x == Long.MIN_VALUE) {
return write("" + x);
}
if (ptr + 21 >= BUF_SIZE) innerflush();
if (x < 0) {
write((byte) '-');
x = -x;
}
int d = countDigits(x);
for (int i = ptr + d - 1; i >= ptr; i--) {
buf[i] = (byte) ('0' + x % 10);
x /= 10;
}
ptr += d;
return this;
}
public FastWriter write(double x, int precision) {
if (x < 0) {
write('-');
x = -x;
}
x += Math.pow(10, -precision) / 2;
// if(x < 0){ x = 0; }
write((long) x).write(".");
x -= (long) x;
for (int i = 0; i < precision; i++) {
x *= 10;
write((char) ('0' + (int) x));
x -= (int) x;
}
return this;
}
public FastWriter writeln(char c) {
return write(c).writeln();
}
public FastWriter writeln(int x) {
return write(x).writeln();
}
public FastWriter writeln(long x) {
return write(x).writeln();
}
public FastWriter writeln(double x, int precision) {
return write(x, precision).writeln();
}
public FastWriter write(int... xs) {
boolean first = true;
for (int x : xs) {
if (!first) write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter write(long... xs) {
boolean first = true;
for (long x : xs) {
if (!first) write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter writeln() {
return write((byte) '\n');
}
public FastWriter writeln(int... xs) {
return write(xs).writeln();
}
public FastWriter writeln(long... xs) {
return write(xs).writeln();
}
public FastWriter writeln(char[] line) {
return write(line).writeln();
}
public FastWriter writeln(char[]... map) {
for (char[] line : map) write(line).writeln();
return this;
}
public FastWriter writeln(String s) {
return write(s).writeln();
}
private void innerflush() {
try {
out.write(buf, 0, ptr);
ptr = 0;
} catch (IOException e) {
throw new RuntimeException("innerflush");
}
}
public void flush() {
innerflush();
try {
out.flush();
} catch (IOException e) {
throw new RuntimeException("flush");
}
}
public FastWriter print(byte b) {
return write(b);
}
public FastWriter print(char c) {
return write(c);
}
public FastWriter print(char[] s) {
return write(s);
}
public FastWriter print(String s) {
return write(s);
}
public FastWriter print(int x) {
return write(x);
}
public FastWriter print(long x) {
return write(x);
}
public FastWriter print(double x, int precision) {
return write(x, precision);
}
public FastWriter println(char c) {
return writeln(c);
}
public FastWriter println(int x) {
return writeln(x);
}
public FastWriter println(long x) {
return writeln(x);
}
public FastWriter println(double x, int precision) {
return writeln(x, precision);
}
public FastWriter print(int... xs) {
return write(xs);
}
public FastWriter print(long... xs) {
return write(xs);
}
public FastWriter println(int... xs) {
return writeln(xs);
}
public FastWriter println(long... xs) {
return writeln(xs);
}
public FastWriter println(char[] line) {
return writeln(line);
}
public FastWriter println(char[]... map) {
return writeln(map);
}
public FastWriter println(String s) {
return writeln(s);
}
public FastWriter println() {
return writeln();
}
}
static int ni() {
return in.ni();
}
static long nl() {
return in.nl();
}
static String ns() {
return in.ns();
}
static double nd() {
return Double.parseDouble(in.ns());
}
}
| 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.io.*;
import java.util.*;
public class swapSort {
public static void main(String[] args)throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader((System.in)));
int n =Integer.parseInt(br.readLine());
String s1 = br.readLine();
String s2 = br.readLine();
HashMap<Character , Stack<Integer>> ri = new HashMap<>();
Stack<Integer> q2=new Stack<>();
Stack<Integer> q1=new Stack<>();
boolean[] li = new boolean [n];
for (int i=0;i<n;i++)
{
char ch = s2.charAt(i);
if (ch=='?') {
q2.push(i+1);
continue;
}
if (!ri.containsKey(ch)) ri.put(ch , new Stack<Integer>());
ri.get(ch).push((i+1));
}
StringBuilder res = new StringBuilder();
long cnt = 0;
for(int i=0;i<n;i++)
{
char ch = s1.charAt(i);
if (ch=='?') {
q1.push(i+1);
li[i]=true;
continue;
}
if (ri.containsKey(ch) && !ri.get(ch).isEmpty())
{
li[i] = true;
res.append((i+1)+" "+ri.get(ch).pop()+"\n");
cnt++;
}
}
for(char ch='a';!q1.isEmpty()&&ch<='z';)
{
if (!ri.containsKey(ch) || ri.get(ch).isEmpty()) ch++;
else
{
res.append(q1.pop()+" "+ri.get(ch).pop()+"\n");
cnt++;
}
}
for (int i=0;!q2.isEmpty()&&i<n;i++)
{
if (!li[i])
{
res.append((i+1)+" "+q2.pop()+"\n");
cnt++;
}
}
while (!q1.isEmpty() && !q2.isEmpty())
{
res.append(q1.pop()+" "+q2.pop()+"\n");
cnt++;
}
System.out.println(cnt);
System.out.println(res);
}
} | 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.*;
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(), m = sc.nextInt();
String s = sc.next();
int p[] = new int[n];
p[n-1]=1;
for(int i=0; i<m; i++){
int pi = sc.nextInt();
p[pi-1]++;
}
int d6[] = new int[26];
d6[s.charAt(n-1)-'a']++;
for(int i=n-2; i>=0; i--){
p[i] += p[i+1];
d6[s.charAt(i)-'a']+=p[i];
}
for(int i=0; i<26; i++) System.out.print(d6[i]+" ");
System.out.println();
}
}
} | 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.io.*;
import java.util.*;
public class Codeforces
{
public static void main(String args[])throws Exception
{
BufferedReader bu=new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb=new StringBuilder();
int t=Integer.parseInt(bu.readLine());
while(t-->0)
{
String s[]=bu.readLine().split(" ");
long n=Integer.parseInt(s[0]),x=Integer.parseInt(s[1]),y=Integer.parseInt(s[2]);
if(x>y) x=x^y^(y=x);
long min=Math.max(1,Math.min(n,x+y-n+1));
long max=Math.min(x+y-1,n);
sb.append(min+" "+max+"\n");
}
System.out.print(sb);
}
}
| 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"
] | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
//BufferedReader f = new BufferedReader(new FileReader("uva.in"));
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int n = Integer.parseInt(f.readLine());
char[] s = f.readLine().toCharArray();
ArrayList<Stack<Integer>> occ = new ArrayList<>(26);
for(int i = 0; i < 26; i++) {
occ.add(new Stack<>());
}
int[] res = new int[n];
int cur = 1;
for(int i = 0; i < n; i++) {
boolean flag = false;
for(int j = s[i]-'a'; j >= 0; j--) {
if(!occ.get(j).isEmpty()) {
flag = true;
occ.get(s[i]-'a').push(occ.get(j).pop());
break;
}
}
if(!flag) {
occ.get(s[i]-'a').push(cur++);
}
res[i] = occ.get(s[i]-'a').peek();
}
out.println(cur-1);
out.print(res[0]);
for(int i = 1; i < n; i++) {
out.print(" " + res[i]);
}
out.println();
f.close();
out.close();
}
}
| 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 array {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int t = in.nextInt();
while(t-->0)
{
int n = in.nextInt();
Integer[] a = new Integer[n];
for(int i = 0 ; i< n ; i++) a[i] = in.nextInt();
Arrays.sort(a, Collections.reverseOrder());
for(int i:a)
System.out.print(i+" ");
System.out.println();
}
in.close();
}
}
| java |
1312 | A | A. Two Regular Polygonstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm (m<nm<n). Consider a convex regular polygon of nn vertices. Recall that a regular polygon is a polygon that is equiangular (all angles are equal in measure) and equilateral (all sides have the same length). Examples of convex regular polygons Your task is to say if it is possible to build another convex regular polygon with mm vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon.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 as two space-separated integers nn and mm (3≤m<n≤1003≤m<n≤100) — the number of vertices in the initial polygon and the number of vertices in the polygon you want to build.OutputFor each test case, print the answer — "YES" (without quotes), if it is possible to build another convex regular polygon with mm vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon and "NO" otherwise.ExampleInputCopy2
6 3
7 3
OutputCopyYES
NO
Note The first test case of the example It can be shown that the answer for the second test case of the example is "NO". | [
"geometry",
"greedy",
"math",
"number theory"
] | import java.util.*;
import java.lang.*;
public class cf {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
int l= sc.nextInt(), r=sc.nextInt();
if (l%r == 0) {
System.out.println("YES");
}
else {
System.out.println("NO");
}
}
}
} | java |
1141 | B | B. Maximal Continuous Resttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEach day in Berland consists of nn hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence a1,a2,…,ana1,a2,…,an (each aiai is either 00 or 11), where ai=0ai=0 if Polycarp works during the ii-th hour of the day and ai=1ai=1 if Polycarp rests during the ii-th hour of the day.Days go one after another endlessly and Polycarp uses the same schedule for each day.What is the maximal number of continuous hours during which Polycarp rests? It is guaranteed that there is at least one working hour in a day.InputThe first line contains nn (1≤n≤2⋅1051≤n≤2⋅105) — number of hours per day.The second line contains nn integer numbers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where ai=0ai=0 if the ii-th hour in a day is working and ai=1ai=1 if the ii-th hour is resting. It is guaranteed that ai=0ai=0 for at least one ii.OutputPrint the maximal number of continuous hours during which Polycarp rests. Remember that you should consider that days go one after another endlessly and Polycarp uses the same schedule for each day.ExamplesInputCopy5
1 0 1 0 1
OutputCopy2
InputCopy6
0 1 0 1 1 0
OutputCopy2
InputCopy7
1 0 1 1 1 0 1
OutputCopy3
InputCopy3
0 0 0
OutputCopy0
NoteIn the first example; the maximal rest starts in last hour and goes to the first hour of the next day.In the second example; Polycarp has maximal rest from the 44-th to the 55-th hour.In the third example, Polycarp has maximal rest from the 33-rd to the 55-th hour.In the fourth example, Polycarp has no rest at all. | [
"implementation"
] | import java.util.*;
import java.io.*;
import static java.lang.Math.*;
public class Main {
static InputStream is;
static PrintWriter out;
static String INPUT = "";
static final int ima = Integer.MAX_VALUE, imi = Integer.MIN_VALUE;
static final long lma = Long.MAX_VALUE, lmi = Long.MIN_VALUE;
static final long mod = (long) 1e9 + 7;
static void solve() {
int caseNo = 1;
// for (int T = sc.nextInt(); T > 1; T--, caseNo++) { solveIt(caseNo); }
solveIt(caseNo);
}
// Solution
static void solveIt(int testCaseNo) {
int n = sc.nextInt();
int a[] = sc.readIntArray(n);
int max = 0;
for (int s = 0, e = 0; e < n; e++) {
if (a[e] == 0) {
s = e + 1;
continue;
}
max = max(max, e - s + 1);
}
int s = 0;
while (s < n && a[s] == 1) s++;
int e = n - 1;
while (e >= 0 && a[e] == 1) e--;
max = max(max, s + (n - e - 1));
System.out.println(max);
}
public static void main(String[] args) throws Exception {
long S = System.currentTimeMillis();
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
solve();
out.flush();
long G = System.currentTimeMillis();
sc.tr(G - S + "ms");
}
static class sc {
private static boolean endOfFile() {
if (bufferLength == -1) return true;
int lptr = ptrbuf;
while (lptr < bufferLength) {
if (!isThisTheSpaceCharacter(inputBufffferBigBoi[lptr++])) return false;
}
try {
is.mark(1000);
while (true) {
int b = is.read();
if (b == -1) {
is.reset();
return true;
} else if (!isThisTheSpaceCharacter(b)) {
is.reset();
return false;
}
}
} catch (IOException e) {
return true;
}
}
private static byte[] inputBufffferBigBoi = new byte[1024];
static int bufferLength = 0, ptrbuf = 0;
private static int justReadTheByte() {
if (bufferLength == -1) throw new InputMismatchException();
if (ptrbuf >= bufferLength) {
ptrbuf = 0;
try {
bufferLength = is.read(inputBufffferBigBoi);
} catch (IOException e) {
throw new InputMismatchException();
}
if (bufferLength <= 0) return -1;
}
return inputBufffferBigBoi[ptrbuf++];
}
private static boolean isThisTheSpaceCharacter(int c) { return !(c >= 33 && c <= 126); }
private static int skipItBishhhhhhh() {
int b;
while ((b = justReadTheByte()) != -1 && isThisTheSpaceCharacter(b));
return b;
}
private static double nextDouble() { return Double.parseDouble(next()); }
private static char nextChar() { return (char) skipItBishhhhhhh(); }
private static String next() {
int b = skipItBishhhhhhh();
StringBuilder sb = new StringBuilder();
while (!(isThisTheSpaceCharacter(b))) {
sb.appendCodePoint(b);
b = justReadTheByte();
}
return sb.toString();
}
private static char[] readCharArray(int n) {
char[] buf = new char[n];
int b = skipItBishhhhhhh(), p = 0;
while (p < n && !(isThisTheSpaceCharacter(b))) {
buf[p++] = (char) b;
b = justReadTheByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private static char[][] readCharMatrix(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++) map[i] = readCharArray(m);
return map;
}
private static int[] readIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
private static long[] readLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
private static int nextInt() {
int num = 0, b;
boolean minus = false;
while ((b = justReadTheByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if (b == '-') {
minus = true;
b = justReadTheByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = justReadTheByte();
}
}
private static long nextLong() {
long num = 0;
int b;
boolean minus = false;
while ((b = justReadTheByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if (b == '-') {
minus = true;
b = justReadTheByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = justReadTheByte();
}
}
private static void tr(Object... o) {
if (INPUT.length() != 0) System.out.println(Arrays.deepToString(o));
}
}
}
// And I wish you could sing along, But this song is a joke, and the melody I
// wrote, wrong | java |
1325 | F | F. Ehab's Last Theoremtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's the year 5555. You have a graph; and you want to find a long cycle and a huge independent set, just because you can. But for now, let's just stick with finding either.Given a connected graph with nn vertices, you can choose to either: find an independent set that has exactly ⌈n−−√⌉⌈n⌉ vertices. find a simple cycle of length at least ⌈n−−√⌉⌈n⌉. An independent set is a set of vertices such that no two of them are connected by an edge. A simple cycle is a cycle that doesn't contain any vertex twice. I have a proof you can always solve one of these problems, but it's too long to fit this margin.InputThe first line contains two integers nn and mm (5≤n≤1055≤n≤105, n−1≤m≤2⋅105n−1≤m≤2⋅105) — the number of vertices and edges in the graph.Each of the next mm lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) that mean there's an edge between vertices uu and vv. It's guaranteed that the graph is connected and doesn't contain any self-loops or multiple edges.OutputIf you choose to solve the first problem, then on the first line print "1", followed by a line containing ⌈n−−√⌉⌈n⌉ distinct integers not exceeding nn, the vertices in the desired independent set.If you, however, choose to solve the second problem, then on the first line print "2", followed by a line containing one integer, cc, representing the length of the found cycle, followed by a line containing cc distinct integers integers not exceeding nn, the vertices in the desired cycle, in the order they appear in the cycle.ExamplesInputCopy6 6
1 3
3 4
4 2
2 6
5 6
5 1
OutputCopy1
1 6 4InputCopy6 8
1 3
3 4
4 2
2 6
5 6
5 1
1 4
2 5
OutputCopy2
4
1 5 2 4InputCopy5 4
1 2
1 3
2 4
2 5
OutputCopy1
3 4 5 NoteIn the first sample:Notice that you can solve either problem; so printing the cycle 2−4−3−1−5−62−4−3−1−5−6 is also acceptable.In the second sample:Notice that if there are multiple answers you can print any, so printing the cycle 2−5−62−5−6, for example, is acceptable.In the third sample: | [
"constructive algorithms",
"dfs and similar",
"graphs",
"greedy"
] | import java.io.*;
import java.util.*;
public class Solution {
int n;
int k;
List<Integer>[] adj;
int[] parent;
int[] level;
boolean[] removed;
List<Integer> cycle;
List<Integer> set;
public void solve() {
n = reader.nextInt();
adj = new List[n + 1];
for (int i = 1; i <= n; i++) {
adj[i] = new LinkedList<>();
}
for (int m = reader.nextInt(); m > 0; m--) {
int u = reader.nextInt();
int v = reader.nextInt();
adj[u].add(v);
adj[v].add(u);
}
k = (int) Math.sqrt(n);
if (k * k < n) k++;
parent = new int[n + 1];
level = new int[n + 1];
removed = new boolean[n + 1];
Arrays.fill(parent, -1);
Arrays.fill(level, -1);
Arrays.fill(removed, false);
int root = 1;
parent[root] = root;
level[root] = 0;
set = new LinkedList<>();
dfs(root);
if (cycle != null) {
writer.println(2);
writer.println(cycle.size());
for (int v : cycle) writer.print(v + " ");
return;
}
writer.println(1);
for (int v : set) writer.print(v + " ");
}
private void dfs(int u) {
int backEdges = 0;
int highest = -1;
for (int v : adj[u]) {
if (parent[v] == -1) {
parent[v] = u;
level[v] = level[u] + 1;
dfs(v);
if (cycle != null) return;
if (set.size() == k) return;
} else if (v != parent[u] && level[v] < level[u]) {
backEdges++;
if (highest == -1 || level[highest] > level[v]) {
highest = v;
}
}
}
if (backEdges >= k - 2) {
cycle = new LinkedList<>();
for (int v = u; v != highest; v = parent[v]) {
cycle.add(v);
}
cycle.add(highest);
return;
}
if (set.size() < k && !removed[u]) {
set.add(u);
removed[u] = true;
for (int v : adj[u]) removed[v] = true;
}
}
private InputReader reader;
private PrintWriter writer;
public Solution(InputReader reader, PrintWriter writer) {
this.reader = reader;
this.writer = writer;
}
public static void main(String[] args) {
InputReader reader = new InputReader(System.in);
PrintWriter writer = new PrintWriter(System.out);
Solution solution = new Solution(reader, writer);
solution.solve();
writer.flush();
}
static class InputReader {
private static final int BUFFER_SIZE = 1 << 20;
private BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), BUFFER_SIZE);
tokenizer = null;
}
public String nextToken() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException();
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public long nextLong() {
return Long.parseLong(nextToken());
}
}
}
| java |
1312 | A | A. Two Regular Polygonstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm (m<nm<n). Consider a convex regular polygon of nn vertices. Recall that a regular polygon is a polygon that is equiangular (all angles are equal in measure) and equilateral (all sides have the same length). Examples of convex regular polygons Your task is to say if it is possible to build another convex regular polygon with mm vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon.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 as two space-separated integers nn and mm (3≤m<n≤1003≤m<n≤100) — the number of vertices in the initial polygon and the number of vertices in the polygon you want to build.OutputFor each test case, print the answer — "YES" (without quotes), if it is possible to build another convex regular polygon with mm vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon and "NO" otherwise.ExampleInputCopy2
6 3
7 3
OutputCopyYES
NO
Note The first test case of the example It can be shown that the answer for the second test case of the example is "NO". | [
"geometry",
"greedy",
"math",
"number theory"
] | import java.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t= sc.nextInt();
for(int i=0;i<t;i++){
int a =sc.nextInt();
int b=sc.nextInt();
if(a%b==0){
System.out.println("Yes");
}
else{
System.out.println("No");
}
}
}
}
| java |
1312 | E | E. Array Shrinkingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements ai=ai+1ai=ai+1 (if there is at least one such pair). Replace them by one element with value ai+1ai+1. After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array aa you can get?InputThe first line contains the single integer nn (1≤n≤5001≤n≤500) — the initial length of the array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000) — the initial array aa.OutputPrint the only integer — the minimum possible length you can get after performing the operation described above any number of times.ExamplesInputCopy5
4 3 2 2 3
OutputCopy2
InputCopy7
3 3 4 4 4 3 3
OutputCopy2
InputCopy3
1 3 5
OutputCopy3
InputCopy1
1000
OutputCopy1
NoteIn the first test; this is one of the optimal sequences of operations: 44 33 22 22 33 →→ 44 33 33 33 →→ 44 44 33 →→ 55 33.In the second test, this is one of the optimal sequences of operations: 33 33 44 44 44 33 33 →→ 44 44 44 44 33 33 →→ 44 44 44 44 44 →→ 55 44 44 44 →→ 55 55 44 →→ 66 44.In the third and fourth tests, you can't perform the operation at all. | [
"dp",
"greedy"
] | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class cf1312e {
static int dp[][];
public static void main(String[] args) throws IOException {
int n = ri(), a[] = ria(n);
dp = new int[n][n];
for (int[] row : dp) {
fill(row, -2);
}
for (int i = 0; i < n; ++i) {
dp[i][i] = a[i];
}
int[] dp2 = new int[n + 1];
for (int i = 0; i <= n; ++i) {
dp2[i] = i;
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j <= i; ++j) {
if (dp(j, i) > 0) {
dp2[i + 1] = min(dp2[i + 1], dp2[j] + 1);
}
}
}
prln(dp2[n]);
close();
}
static int dp(int i, int j) {
if (dp[i][j] != -2) {
return dp[i][j];
}
int ans = -1;
for (int k = i; k < j; ++k) {
int a = dp(i, k), b = dp(k + 1, j);
if (a >= 1 && a == b) {
ans = max(ans, a + 1);
}
}
return dp[i][j] = ans;
}
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 |
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 B {
static FastReader sc=null;
static int nax=(int)1e5;
static int even=0,odd=0;
static int a[];
static int n;
public static void main(String[] args) {
sc=new FastReader();
n=sc.nextInt();
a=sc.readArray(n);
if(n==1) {
System.out.println(0);
return;
}
//DP[I][J][2] -> IS THE MINIMUM PARITY TILL 'I' WE CAN GET IF WE PLACE 'J' EVEN PARITY ONES
//[0] -> INDICATES THE ONE BEFORE IT IS EVEN PARITY
//[1] -> INDICATES THE ONE BEFORE IT IS ODD PARITY
//DP[I][J][0] = DP[I-1][J-1][0] | DP[I-1][J-1][1] + [PLACE EVEN PARITY ONE HERE]
//DP[I][J][1] = DP[I-1][J][0] | DP[I-1][J][1] + [PLACE ODD PARITY ONE HERE]
//DP[I][J][0|1] -> IF NOT '0' = DP[I-1][J][0]
Set<Integer> s=new HashSet<>();
for(int e:a)if(e!=0)s.add(e);
for(int i=1;i<=n;i++) {
if(!s.contains(i)) {
if(i%2==0)even++;
else odd++;
}
}
int dp[][][]=new int[n][even+1][2];
for(int i=0;i<n;i++)
for(int j=0;j<=even;j++)Arrays.fill(dp[i][j], nax);
int curr=0;
if(a[0]!=0) {
dp[0][0][0]=dp[0][0][1]=0;
if(a[0]%2==0) dp[0][0][1]=nax;
else dp[0][0][0]=nax;
}
else {
curr++;
dp[0][0][1]=0;
dp[0][1][0]=0;
}
for(int i=1;i<n;i++) {
for(int j=0;j<=even;j++) {
if(a[i]!=0) {
if(a[i]%2==0) {
dp[i][j][0]=Math.min(dp[i-1][j][0],dp[i-1][j][1]+1);
dp[i][j][1]=nax;
}
else {
dp[i][j][1]=Math.min(dp[i-1][j][1],dp[i-1][j][0]+1);
dp[i][j][0]=nax;
}
}
else {
dp[i][j][1]=Math.min(dp[i-1][j][1], dp[i-1][j][0]+1);
if(j>0)dp[i][j][0]=Math.min(dp[i-1][j-1][0], dp[i-1][j-1][1]+1);
curr++;
}
}
}
System.out.println(Math.min(dp[n-1][even][0],dp[n-1][even][1]));
}
static int[] reverseSort(int a[]) {
ArrayList<Integer> al=new ArrayList<>();
for(int i:a)al.add(i);
Collections.sort(al,Collections.reverseOrder());
for(int i=0;i<a.length;i++)a[i]=al.get(i);
return a;
}
static int[] reverse(int a[]) {
ArrayList<Integer> al=new ArrayList<>();
for(int i:a)al.add(i);
Collections.reverse(al);
for(int i=0;i<a.length;i++)a[i]=al.get(i);
return a;
}
static char[] reverse(char a[]) {
ArrayList<Character> al=new ArrayList<>();
for(char i:a)al.add(i);
Collections.reverse(al);
for(int i=0;i<a.length;i++)a[i]=al.get(i);
return a;
}
static int gcd(int a,int b) {
if(b==0)return a;
else return gcd(b,a%b);
}
static long gcd(long a,long b) {
if(b==0)return a;
else return gcd(b,a%b);
}
static int[] ruffleSort(int a[]) {
ArrayList<Integer> al=new ArrayList<>();
for(int i:a)al.add(i);
Collections.sort(al);
for(int i=0;i<a.length;i++)a[i]=al.get(i);
return a;
}
static void print(int a[]) {
for(int e:a) {
System.out.print(e+" ");
}
System.out.println();
}
static void print(boolean a[]) {
for(boolean e:a) {
System.out.print(e+" ");
}
System.out.println();
}
static void print(long a[]) {
for(long e:a) {
System.out.print(e+" ");
}
System.out.println();
}
static void print(char a[]) {
for(char e:a) {
System.out.print(e);
}
System.out.println();
}
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;
}
int[] readArray(int n) {
int a[]=new int [n];
for(int i=0;i<n;i++) {
a[i]=sc.nextInt();
}
return a;
}
}
}
| 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.IOException;
import java.io.InputStream;
import java.util.*;
public class sol {
static long mod=(long)Math.pow(10,9)+7;
static StringBuilder sb = new StringBuilder();
static ArrayList<Integer> adj[];
static boolean vis[];
static int a[], dist[];
static void bfs(int s) {
Queue<Integer> q = new LinkedList<>();
dist[s]=0;
vis[s]=true;
q.add(s);
while(q.size()>0) {
int v=q.poll();
for(Integer i : adj[v]) {
dist[i]=Math.min(dist[i],dist[v]+1);
if(!vis[i]) {
vis[i]=true;
q.add(i);
}
}
}
}
public static void main(String args[])throws Exception {
FastReader in = new FastReader(System.in);
int t=1,i,j;
start:while(t-->0) {
int n = in.nextInt(),m=in.nextInt();
dist =new int[n];
Arrays.fill(dist,Integer.MAX_VALUE);
adj = new ArrayList[n];
vis = new boolean[n];
for(i=0;i<n;i++)
adj[i]=new ArrayList<>();
int x[]=new int[m];
int y[]=new int[m];
int cnt[]=new int[n];
for(i=0;i<m;i++) {
x[i]=in.nextInt()-1;
y[i]=in.nextInt()-1;
adj[y[i]].add(x[i]);
}
int k=in.nextInt();
a = new int[k];
for(i=0;i<k;i++)
a[i]=in.nextInt()-1;
bfs(a[k-1]);
for(i=0;i<m;i++) {
if(dist[y[i]]+1==dist[x[i]])
cnt[x[i]]++;
}
//for(i=0;i<n;i++)
//System.out.println(dist[i]+" "+cnt[i]);
int min=0,max=0;
for(i=0;i<k-1;i++) {
if(dist[a[i+1]]+1>dist[a[i]]) {
min++;
max++;
}
else if(cnt[a[i]]>1)
max++;
}
System.out.println(min+" "+max);
}
//System.out.print(sb);
}
static long power(long a, long b) {
if(b == 0)
return 1L;
long val = power(a, b / 2);
if(b % 2 == 0)
return val * val % mod;
else
return val * val % mod * a % mod;
}
static void prt(int a[]) {
for(int i=0;i<=a.length;i++)
System.out.print(a[i]+" ");
System.out.println();
}
static void merge(int arr[], int l, int m, int r) {
int n1 = m - l + 1;
int n2 = r - m;
int L[] = new int [n1];
int R[] = new int [n2];
for (int i=0; i<n1; ++i)
L[i] = arr[l + i];
for (int j=0; j<n2; ++j)
R[j] = arr[m + 1+ j];
int i = 0, j = 0;
int k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
}
else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
static void sort(int arr[], int l, int r) {
if (l < r) {
int m = (l+r)/2;
sort(arr, l, m);
sort(arr , m+1, r);
merge(arr, l, m, r);
}
}
static int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static class Pair {
int a;
int b;
Pair(int x, int y) {
a = x;
b = y;
}
}
}
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();
}
String nextLine() throws IOException {
int c;
for (c = scan(); c <= 32; c = scan()) ;
StringBuilder sb = new StringBuilder();
for (; c != 10 && c != 13; c = scan()) {
sb.append((char) c);
}
return sb.toString();
}
char nextChar() throws IOException {
int c;
for (c = scan(); c <= 32; c = scan()) ;
return (char) c;
}
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;
}
} | java |
1286 | B | B. Numbers on Treetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEvlampiy was gifted a rooted tree. The vertices of the tree are numbered from 11 to nn. Each of its vertices also has an integer aiai written on it. For each vertex ii, Evlampiy calculated cici — the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai. Illustration for the second example, the first integer is aiai and the integer in parentheses is ciciAfter the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of cici, but he completely forgot which integers aiai were written on the vertices.Help him to restore initial integers!InputThe first line contains an integer nn (1≤n≤2000)(1≤n≤2000) — the number of vertices in the tree.The next nn lines contain descriptions of vertices: the ii-th line contains two integers pipi and cici (0≤pi≤n0≤pi≤n; 0≤ci≤n−10≤ci≤n−1), where pipi is the parent of vertex ii or 00 if vertex ii is root, and cici is the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai.It is guaranteed that the values of pipi describe a rooted tree with nn vertices.OutputIf a solution exists, in the first line print "YES", and in the second line output nn integers aiai (1≤ai≤109)(1≤ai≤109). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all aiai are between 11 and 109109.If there are no solutions, print "NO".ExamplesInputCopy3
2 0
0 2
2 0
OutputCopyYES
1 2 1 InputCopy5
0 1
1 3
2 1
3 0
2 0
OutputCopyYES
2 3 2 1 2
| [
"constructive algorithms",
"data structures",
"dfs and similar",
"graphs",
"greedy",
"trees"
] | //package numbersontree;
import java.util.*;
import java.io.*;
public class numbersontree {
static ArrayList<ArrayList<Integer>> c;
static int[] nums;
static boolean isValid;
public static ArrayList<Integer> getAns(int node) {
//System.out.println(node);
int midVal = nums[node];
ArrayList<Integer> ans = new ArrayList<Integer>();
if(c.get(node).size() == 0) {
if(midVal != 0) {
isValid = false;
}
ans.add(node);
return ans;
}
else {
if(midVal == 0) {
ans.add(node);
}
for(int i = 0; i < c.get(node).size(); i++) {
ArrayList<Integer> nextAns = getAns(c.get(node).get(i));
for(int j : nextAns) {
ans.add(j);
if(ans.size() == midVal) {
ans.add(node);
}
}
}
if(midVal > ans.size()) {
isValid = false;
}
return ans;
}
}
public static void main(String[] args) throws IOException {
BufferedReader fin = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(fin.readLine());
c = new ArrayList<ArrayList<Integer>>();
for(int i = 0; i < n; i++) {
c.add(new ArrayList<Integer>());
}
int rootIndex = 0;
nums = new int[n];
for(int i = 0; i < n; i++) {
StringTokenizer st = new StringTokenizer(fin.readLine());
int a = Integer.parseInt(st.nextToken()) - 1;
int val = Integer.parseInt(st.nextToken());
if(a != -1) {
c.get(a).add(i);
}
else {
rootIndex = i;
}
nums[i] = val;
}
isValid = true;
ArrayList<Integer> ans = getAns(rootIndex);
StringBuilder fout = new StringBuilder();
if(isValid) {
fout.append("YES\n");
int[] printAns = new int[n];
for(int i = 0; i < ans.size(); i++) {
int next = ans.get(i);
printAns[next] = i + 1;
}
for(int i : printAns) {
fout.append(i).append(" ");
}
fout.append("\n");
}
else {
fout.append("NO\n");
}
System.out.println(fout);
}
}
| java |
1300 | B | B. Assigning to Classestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputReminder: the median of the array [a1,a2,…,a2k+1][a1,a2,…,a2k+1] of odd number of elements is defined as follows: let [b1,b2,…,b2k+1][b1,b2,…,b2k+1] be the elements of the array in the sorted order. Then median of this array is equal to bk+1bk+1.There are 2n2n students, the ii-th student has skill level aiai. It's not guaranteed that all skill levels are distinct.Let's define skill level of a class as the median of skill levels of students of the class.As a principal of the school, you would like to assign each student to one of the 22 classes such that each class has odd number of students (not divisible by 22). The number of students in the classes may be equal or different, by your choice. Every student has to be assigned to exactly one class. Among such partitions, you want to choose one in which the absolute difference between skill levels of the classes is minimized.What is the minimum possible absolute difference you can achieve?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 a single integer nn (1≤n≤1051≤n≤105) — the number of students halved.The second line of each test case contains 2n2n integers a1,a2,…,a2na1,a2,…,a2n (1≤ai≤1091≤ai≤109) — skill levels of students.It is guaranteed that the sum of nn over all test cases does not exceed 105105.OutputFor each test case, output a single integer, the minimum possible absolute difference between skill levels of two classes of odd sizes.ExampleInputCopy3
1
1 1
3
6 5 4 1 2 3
5
13 4 20 13 2 5 8 3 17 16
OutputCopy0
1
5
NoteIn the first test; there is only one way to partition students — one in each class. The absolute difference of the skill levels will be |1−1|=0|1−1|=0.In the second test, one of the possible partitions is to make the first class of students with skill levels [6,4,2][6,4,2], so that the skill level of the first class will be 44, and second with [5,1,3][5,1,3], so that the skill level of the second class will be 33. Absolute difference will be |4−3|=1|4−3|=1.Note that you can't assign like [2,3][2,3], [6,5,4,1][6,5,4,1] or [][], [6,5,4,1,2,3][6,5,4,1,2,3] because classes have even number of students.[2][2], [1,3,4][1,3,4] is also not possible because students with skills 55 and 66 aren't assigned to a class.In the third test you can assign the students in the following way: [3,4,13,13,20],[2,5,8,16,17][3,4,13,13,20],[2,5,8,16,17] or [3,8,17],[2,4,5,13,13,16,20][3,8,17],[2,4,5,13,13,16,20]. Both divisions give minimal possible absolute difference. | [
"greedy",
"implementation",
"sortings"
] | import java.util.*;
import java.io.*;
public class Main {
static FastReader sc;
static PrintWriter out;
static void solve() {
int n = sc.nextInt(), k = 0;
int[] arr = sc.readIntArray(2*n);
Arrays.sort(arr);
//debug(mini);
out.println((arr[n] - arr[n - 1]));
/*
4
33 44 11 22
*/
}
static int gcd(int a,int b){
if(b==0) return a;
return gcd(b,a%b);
}
public static void main(String[] args) throws IOException {
sc = new FastReader();
out = new PrintWriter(System.out);
int tt = sc.nextInt();
for (int t = 1; t <= tt; t++) {
// out.printf("Case %d: ", t);
solve();
}
out.close();
}
static int[] strToIntArray(String s){
String[] sarr = s.split(" ");
int[] arr = new int[sarr.length];
for(int i = 0; i < sarr.length; i++){
arr[i] = Integer.parseInt(sarr[i]);
}
return arr;
}
static <E> void debug(E a) {
System.err.println(a);
}
static void debug(int... a) {
System.err.println(Arrays.toString(a));
}
static <E> void print(E res) {
out.println(res);
}
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;
}
int[] readIntArray(int n) {
int[] res = new int[n];
for (int i = 0; i < n; i++)
res[i] = nextInt();
return res;
}
long[] readLongArray(int n) {
long[] res = new long[n];
for (int i = 0; i < n; i++)
res[i] = nextLong();
return res;
}
}
} | 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"
] | // package c1294;
//
// Codeforces Round #615 (Div. 3) 2020-01-22 06:35
// F. Three Paths on a Tree
// https://codeforces.com/contest/1294/problem/F
// 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+).*'
//
// You are given an unweighted tree with n vertices. Recall that a tree is a connected undirected
// graph without cycles.
//
// Your task is to choose vertices a, b, c on this tree such that the number of edges which belong
// to one of the simple paths between a and b, b and c, or a and c 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.
//
// Input
//
// The first line contains one integer number n (3 <= n <= 2 * 10^5) -- the number of vertices in
// the tree.
//
// Next n - 1 lines describe the edges of the tree in form a_i, b_i (1 <= a_i, b_i <= n, a_i !=
// b_i). It is guaranteed that given graph is a tree.
//
// Output
//
// In the first line print one integer res -- the maximum number of edges which belong to one of the
// simple paths between a and b, b and c, or a and c.
//
// In the second line print three integers a, b, c such that 1 <= a, b, c <= n and a !=, b != c, a
// != c.
//
// If there are several answers, you can print any.
//
// Example
/*
input:
8
1 2
2 3
3 4
4 5
4 6
3 7
3 8
output:
5
1 8 6
*/
// Note
//
// The picture corresponding to the first example (and ):
//
// https://espresso.codeforces.com/a14350f33ff1d0a53f558a037dbaf779e81c1ee9.png
//
// If you choose vertices 1, 5, 6 then the path between 1 and 5 consists of edges (1, 2), (2, 3),
// (3, 4), (4, 5), the path between 1 and 6 consists of edges (1, 2), (2, 3), (3, 4), (4, 6) and the
// path between 5 and 6 consists of edges (4, 5), (4, 6). The union of these paths is (1, 2), (2,
// 3), (3, 4), (4, 5), (4, 6) so the answer is 5. It can be shown that there is no better answer.
//
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.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Random;
import java.util.StringTokenizer;
public class C1294F {
static final int MOD = 998244353;
static final Random RAND = new Random();
static int[] solve(int[][] edges) {
int n = edges.length + 1;
int[] ans = new int[4];
List<Integer>[] adjs = new ArrayList[n+1];
for (int i = 0; i < n + 1; i++) {
adjs[i] = new ArrayList<>();
}
for (int[] edge : edges) {
int u = edge[0];
int v = edge[1];
adjs[u].add(v);
adjs[v].add(u);
}
int r = 1;
List<Integer>[] ca = new ArrayList[n+1];
for (int i = 0; i < n + 1; i++) {
ca[i] = new ArrayList<>();
}
int[] parent = new int[n+1];
int[] depth = new int[n+1];
Queue<Integer> q = new LinkedList<>();
q.add(r);
while (!q.isEmpty()) {
int v = q.poll();
for (int w : adjs[v]) {
if (w == parent[v]) {
continue;
}
ca[v].add(w);
parent[w] = v;
depth[w] = depth[v] + 1;
q.add(w);
}
}
if (test) System.out.format(" parent: %s\n", Arrays.toString(parent));
int[] degs = new int[n+1];
for (int i = 1; i <= n; i++) {
degs[i] = ca[i].size();
if (degs[i] == 0) {
q.add(i);
}
if (test && degs[i] != 0) {
Collections.sort(ca[i]);
System.out.format(" %2d: %s\n", i, ca[i].toString());
}
}
// dp[i][0][0]: deepest node in the subtree i
// dp[i][1]: (p,x,y) where p is the nearest common ancestor of x and y
int[][][] dp = new int[n+1][2][3];
while (!q.isEmpty()) {
int v = q.poll();
if (ca[v].isEmpty()) {
dp[v][0][0] = v;
} else {
// sort children by descending depth
Collections.sort(ca[v], (x,y)->depth[dp[y][0][0]] - depth[dp[x][0][0]]);
int w0 = ca[v].get(0);
dp[v][0][0] = dp[w0][0][0];
if (test) System.out.format(" v:%2d %d %d dp[v][1]: %s ca[v]:%s ans0:%d\n",
v, w0, dp[w0][0][0], Arrays.toString(dp[v][1]), ca[v].toString(), ans[0]);
if (ca[v].size() == 1) {
if (dp[w0][1][0] == 0) {
// subtree is a stick
// update ans with 3 unique nodes and longer path
if (ans[0] < depth[dp[v][0][0]] - depth[v] && w0 != dp[v][0][0]) {
ans[0] = depth[dp[v][0][0]] - depth[v];
ans[1] = v;
ans[2] = w0;
ans[3] = dp[w0][0][0];
}
} else {
// inherit (p,a,b) from the only child, update answer as (v,a,b) has longer path
int p = dp[w0][1][0];
int a = dp[w0][1][1];
int b = dp[w0][1][2];
int score = depth[a] - depth[p] + depth[b] - depth[p] + depth[p] - depth[v];
if (test) System.out.format(" v:%2d p:%d a:%d b:%d score:%d\n", v, p, a, b, score);
dp[v][1][0] = p;
dp[v][1][1] = a;
dp[v][1][2] = b;
if (ans[0] < score) {
ans[0] = score;
ans[1] = v;
ans[2] = a;
ans[3] = b;
}
}
} else {
// Set (v,a,b) as the baseline where a and b are the deepest nodes in first two children.
// 2+ children
// v
// / \
// w0 w1
// / \
// a b
int w1 = ca[v].get(1);
int a = dp[w0][0][0];
int b = dp[w1][0][0];
dp[v][1][0] = v;
dp[v][1][1] = a;
dp[v][1][2] = b;
int score = depth[a] + depth[b] - 2 * depth[v];
if (ans[0] < score) {
ans[0] = score;
ans[1] = v;
ans[2] = a;
ans[3] = b;
}
for (int i = 0; i < ca[v].size(); i++) {
int w = ca[v].get(i);
// Case 1: If (p,a,b) under the child provide higher score, use it.
if (dp[w][1][0] > 0) {
// v
// |
// p
// / \
// a b
int p = dp[w][1][0];
a = dp[w][1][1];
b = dp[w][1][2];
int z = depth[a] + depth[b] - depth[p] - depth[v];
if (z > score) {
dp[v][1][0] = p;
dp[v][1][1] = a;
dp[v][1][2] = b;
score = z;
if (ans[0] < score) {
ans[0] = score;
ans[1] = v;
ans[2] = a;
ans[3] = b;
}
}
// Case 2: (p,a,b) under the child + the deepest node in other children.
// If (p,a,b) under the child provide higher score, use it.
// v
// / \
// * p
// / / \
// u a b
int u = i == 0 ? dp[ca[v].get(1)][0][0] : dp[ca[v].get(0)][0][0];
z = depth[a] - depth[p] + depth[b] - depth[p] + depth[p] - depth[v] + depth[u] - depth[v];
if (ans[0] < z) {
ans[0] = z;
ans[1] = u;
ans[2] = a;
ans[3] = b;
}
}
}
// Case 3: (a,b,c) from the top 3 subtrees
if (ca[v].size() >= 3) {
// v
// / | \
// w0 w1 w2
// / | \
// a b c
int w2 = ca[v].get(2);
a = dp[w0][0][0];
b = dp[w1][0][0];
int c = dp[w2][0][0];
int x = depth[a] + depth[b] + depth[c] - 3 * depth[v];
if (ans[0] < x) {
ans[0] = x;
ans[1] = a;
ans[2] = b;
ans[3] = c;
}
}
}
}
if (test) System.out.format(" v:%2d dp[v][0]:%d dp[v][1]:%s\n", v, dp[v][0][0], Arrays.toString(dp[v][1]));
int p = parent[v];
if (p != 0) {
degs[p]--;
if (degs[p] == 0) {
q.add(p);
}
}
}
return ans;
}
static void test(int exp, int[][] edges) {
System.out.format("edges: %s\n", trace(edges));
int[] ans = solve(edges);
boolean ok = (exp == ans[0] && ans[1] != 0 && ans[2] != 0 && ans[3] != 0);
System.out.format(" => %d %d %d %d\n", ans[0], ans[1], ans[2], ans[3], ok ? "":"Expected " + exp);
myAssert(ok);
}
static boolean test = false;
static void doTest() {
if (!test) {
return;
}
long t0 = System.currentTimeMillis();
test(99, new int[][] {{24,25},{57,58},{83,84},{81,80},{89,88},{34,33},{48,49},{58,59},{95,94},{28,27},
{98,99},{37,36},{77,76},{11,10},{8,9},{51,52},{49,50},{52,53},{92,91},{20,21},
{44,45},{65,66},{44,43},{78,79},{14,15},{48,47},{5,6},{28,29},{100,99},{84,85},
{42,41},{98,97},{40,39},{54,55},{82,83},{75,74},{56,57},{69,68},{11,12},{9,10},
{46,47},{13,12},{46,45},{93,94},{4,3},{77,78},{1,2},{54,53},{22,21},{87,86},
{59,60},{37,38},{15,16},{70,69},{29,30},{75,76},{61,62},{33,32},{62,63},{64,65},
{26,27},{22,23},{73,72},{42,43},{82,81},{66,67},{3,2},{67,68},{93,92},{31,30},
{71,72},{88,87},{86,85},{56,55},{4,5},{70,71},{40,41},{19,18},{25,26},{97,96},
{61,60},{90,91},{8,7},{73,74},{38,39},{50,51},{18,17},{35,34},{79,80},{96,95},
{90,89},{16,17},{20,19},{63,64},{24,23},{7,6},{36,35},{31,32},{14,13}});
test(20, new int[][] {{29,53},{2,1},{55,73},{89,66},{29,12},{18,1},{53,68},{8,60},{24,34},{10,6},
{28,44},{58,92},{87,30},{47,95},{11,5},{15,82},{40,91},{2,39},{20,35},{44,65},
{17,50},{19,33},{45,16},{6,4},{22,76},{26,56},{67,27},{2,9},{4,28},{98,19},
{27,20},{3,4},{3,88},{31,3},{25,24},{8,4},{44,69},{14,4},{68,80},{73,81},
{36,25},{30,27},{70,4},{4,5},{50,79},{78,3},{51,5},{3,15},{4,13},{24,6},
{15,17},{23,62},{1,3},{17,38},{19,54},{19,77},{47,20},{94,97},{34,99},{41,96},
{4,43},{74,54},{22,12},{100,82},{7,2},{46,71},{72,32},{86,59},{10,21},{35,37},
{40,19},{75,83},{9,20},{59,42},{16,9},{23,18},{38,41},{6,46},{49,9},{7,12},
{20,85},{17,90},{58,12},{58,61},{42,17},{19,7},{84,8},{91,93},{63,46},{31,64},
{32,8},{21,55},{26,21},{24,94},{75,11},{31,48},{26,52},{66,44},{57,10}});
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[][] edges = new int[n-1][2];
for (int i = 0; i < n - 1; i++) {
edges[i][0] = in.nextInt();
edges[i][1] = in.nextInt();
}
int[] ans = solve(edges);
System.out.format("%d\n%d %d %d\n", ans[0], ans[1], ans[2], ans[3]);
}
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 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 |
1294 | B | B. Collecting Packagestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot in a warehouse and nn packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point (0,0)(0,0). The ii-th package is at the point (xi,yi)(xi,yi). It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point (x,y)(x,y) to the point (x+1,yx+1,y) or to the point (x,y+1)(x,y+1).As we say above, the robot wants to collect all nn packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string ss of length nn is lexicographically less than the string tt of length nn if there is some index 1≤j≤n1≤j≤n that for all ii from 11 to j−1j−1 si=tisi=ti and sj<tjsj<tj. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.InputThe first line of the input contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases. Then test cases follow.The first line of a test case contains one integer nn (1≤n≤10001≤n≤1000) — the number of packages.The next nn lines contain descriptions of packages. The ii-th package is given as two integers xixi and yiyi (0≤xi,yi≤10000≤xi,yi≤1000) — the xx-coordinate of the package and the yy-coordinate of the package.It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The sum of all values nn over test cases in the test doesn't exceed 10001000.OutputPrint the answer for each test case.If it is impossible to collect all nn packages in some order starting from (0,00,0), print "NO" on the first line.Otherwise, print "YES" in the first line. Then print the shortest path — a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path.Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.ExampleInputCopy3
5
1 3
1 2
3 3
5 5
4 3
2
1 0
0 1
1
4 3
OutputCopyYES
RUUURRRRUU
NO
YES
RRRRUUU
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below: | [
"implementation",
"sortings"
] | import java.io.*;
import java.util.*;
public class cf {
public static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
public static boolean isok(long x, long h, long k) {
long sum = 0;
if (h > k) {
long t1 = h - k;
long t = t1 * k;
sum += (k * (k + 1)) / 2;
sum += t - (t1 * (t1 + 1) / 2);
} else {
sum += (h * (h + 1)) / 2;
}
if (sum < x) {
return true;
}
return false;
}
public static boolean binary_search(long[] a, long k) {
long low = 0;
long high = a.length - 1;
long mid = 0;
while (low <= high) {
mid = low + (high - low) / 2;
if (a[(int) mid] == k) {
return true;
} else if (a[(int) mid] < k) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return false;
}
public static long lowerbound(long a[], long ddp) {
long low = 0;
long high = a.length;
long mid = 0;
while (low < high) {
mid = low + (high - low) / 2;
if (a[(int) mid] == ddp) {
return mid;
}
if (a[(int) mid] < ddp) {
low = mid + 1;
} else {
high = mid;
}
}
// if(low + 1 < a.length && a[(int)low + 1] <= ddp){
// low++;
// }
if (low == a.length && low != 0) {
low--;
return low;
}
if (a[(int) low] > ddp && low != 0) {
low--;
}
return low;
}
public static long upperbound(long a[], long ddp) {
long low = 0;
long high = a.length;
long mid = 0;
while (low < high) {
mid = low + (high - low) / 2;
if (a[(int) mid] <= ddp) {
low = mid + 1;
} else {
high = mid;
}
}
if (low == a.length) {
return a.length - 1;
}
return low;
}
public static class pair implements Comparable<pair> {
long w;
long h;
public pair(long w, long h) {
this.w = w;
this.h = h;
}
public int compareTo(pair b) {
if (this.w != b.w)
return (int) (this.w - b.w);
else
return (int) (this.h - b.h);
}
}
public static class trinary {
long a;
long b;
long c;
public trinary(long a, long b, long c) {
this.a = a;
this.b = b;
this.c = c;
}
}
public static long lowerboundforpairs(pair a[], long pr) {
long low = 0;
long high = a.length;
long mid = 0;
while (low < high) {
mid = low + (high - low) / 2;
if (a[(int) mid].w <= pr) {
low = mid + 1;
} else {
high = mid;
}
}
// if(low + 1 < a.length && a[(int)low + 1] <= ddp){
// low++;
// }
// if(low == a.length && low != 0){
// low--;
// return low;
// }
// if(a[(int)low].w > pr && low != 0){
// low--;
// }
return low;
}
public static pair[] sortpair(pair[] a) {
Arrays.sort(a, new Comparator<pair>() {
public int compare(pair p1, pair p2) {
return (int) p1.w - (int) p2.w;
}
});
return a;
}
public static boolean ispalindrome(String s) {
long i = 0;
long j = s.length() - 1;
boolean is = false;
while (i < j) {
if (s.charAt((int) i) == s.charAt((int) j)) {
is = true;
i++;
j--;
} else {
is = false;
return is;
}
}
return is;
}
public static void sort(long[] arr) {
ArrayList<Long> a = new ArrayList<>();
for (long i : arr) {
a.add(i);
}
Collections.sort(a);
for (int i = 0; i < a.size(); i++) {
arr[i] = a.get(i);
}
}
public static void sortForObjecttypes(Long[] arr) {
ArrayList<Long> a = new ArrayList<>();
for (Long i : arr) {
a.add(i);
}
Collections.sort(a);
for (int i = 0; i < a.size(); i++) {
arr[i] = a.get(i);
}
}
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());
}
float nextFloat() {
return Float.parseFloat(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
void readArr(int[] ar, int n) {
for (int i = 0; i < n; i++) {
ar[i] = nextInt();
}
}
}
public static void solve(FastReader sc, PrintWriter w) throws Exception {
int n = sc.nextInt();
long xi = 0;
long yi = 0;
pair[] p = new pair[n];
String ans = "";
for (int i = 0; i < n; i++) {
long x = sc.nextLong();
long y = sc.nextLong();
p[i] = new pair(x, y);
}
Arrays.sort(p);
// System.out.println();
// for (pair k : p) {
// System.out.println(k.w + " " + k.h);
// }
boolean is = true;
for (int i = 1; i < n; i++) {
if (p[i].w < p[i - 1].w) {
is = false;
System.out.println("NO");
return;
}
}
if (is) {
for (int i = 1; i < n; i++) {
if (p[i].h < p[i - 1].h) {
is = false;
System.out.println("NO");
return;
}
}
if (is) {
for (int i = 0; i < n; i++) {
if (p[i].w == xi) {
for (int j = 0; j < p[i].h - yi; j++) {
ans += 'U';
}
} else if (p[i].h == yi) {
for (int k = 0; k < p[i].w - xi; k++) {
ans += 'R';
}
} else {
for (int k = 0; k < p[i].w - xi; k++) {
ans += 'R';
}
for (int j = 0; j < p[i].h - yi; j++) {
ans += 'U';
}
}
xi = p[i].w;
yi = p[i].h;
}
} else {
System.out.println("NO");
}
} else {
System.out.println("NO");
return;
}
System.out.println("YES");
System.out.println(ans);
}
public static void main(String[] args) throws Exception {
FastReader sc = new FastReader();
PrintWriter w = new PrintWriter(System.out);
long o = sc.nextLong();
while (o > 0) {
solve(sc, w);
o--;
}
w.close();
}
} | 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.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for (int i = 0; i < t; i++) {
int n = sc.nextInt();
while (n > 0)
if (n % 2 == 0) {
System.out.print(1);
n -= 2;
} else {
System.out.print(7);
n -= 3;
}
System.out.println();
}
}
} | java |
1316 | E | E. Team Buildingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice; the president of club FCB, wants to build a team for the new volleyball tournament. The team should consist of pp players playing in pp different positions. She also recognizes the importance of audience support, so she wants to select kk people as part of the audience.There are nn people in Byteland. Alice needs to select exactly pp players, one for each position, and exactly kk members of the audience from this pool of nn people. Her ultimate goal is to maximize the total strength of the club.The ii-th of the nn persons has an integer aiai associated with him — the strength he adds to the club if he is selected as a member of the audience.For each person ii and for each position jj, Alice knows si,jsi,j — the strength added by the ii-th person to the club if he is selected to play in the jj-th position.Each person can be selected at most once as a player or a member of the audience. You have to choose exactly one player for each position.Since Alice is busy, she needs you to help her find the maximum possible strength of the club that can be achieved by an optimal choice of players and the audience.InputThe first line contains 33 integers n,p,kn,p,k (2≤n≤105,1≤p≤7,1≤k,p+k≤n2≤n≤105,1≤p≤7,1≤k,p+k≤n).The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤1091≤ai≤109).The ii-th of the next nn lines contains pp integers si,1,si,2,…,si,psi,1,si,2,…,si,p. (1≤si,j≤1091≤si,j≤109)OutputPrint a single integer resres — the maximum possible strength of the club.ExamplesInputCopy4 1 2
1 16 10 3
18
19
13
15
OutputCopy44
InputCopy6 2 3
78 93 9 17 13 78
80 97
30 52
26 17
56 68
60 36
84 55
OutputCopy377
InputCopy3 2 1
500 498 564
100002 3
422332 2
232323 1
OutputCopy422899
NoteIn the first sample; we can select person 11 to play in the 11-st position and persons 22 and 33 as audience members. Then the total strength of the club will be equal to a2+a3+s1,1a2+a3+s1,1. | [
"bitmasks",
"dp",
"greedy",
"sortings"
] | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class cf1316e {
public static void main(String[] args) throws IOException {
int n = rni(), p = ni(), k = ni(), s[][] = new int[n][p + 1];
r();
for(int i = 0; i < n; ++i) {
s[i][0] = ni();
}
for(int i = 0; i < n; ++i) {
r();
for(int j = 1; j <= p; ++j) {
s[i][j] = ni();
}
}
sort(s, (a, b) -> b[0] - a[0]);
long dp[][] = new long[n + 1][1 << p];
for(long[] row : dp) {
fill(row, -1);
}
dp[0][0] = 0;
for(int i = 1; i <= n; ++i) {
for(int mask = 0; mask < (1 << p); ++mask) {
int c = i - 1 - cntbits(mask);
if(dp[i - 1][mask] != -1) {
dp[i][mask] = dp[i - 1][mask] + (c < k ? s[i - 1][0] : 0);
}
for(int j = 0; j < p; ++j) {
if((mask & (1 << j)) > 0 && dp[i - 1][mask ^ (1 << j)] != -1) {
dp[i][mask] = max(dp[i][mask], dp[i - 1][mask ^ (1 << j)] + s[i - 1][j + 1]);
}
}
}
}
prln(dp[n][(1 << p) - 1]);
close();
}
static int cntbits(int x) {
int cnt = 0;
while(x > 0) {
if((x & 1) > 0) {
++cnt;
}
x >>= 1;
}
return cnt;
}
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 ~= 2e10
// 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 randInt(int min, int max) {return rand.nextInt(max - min + 1) + min;}
static long hash(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(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 rsort(int[] a) {shuffle(a); sort(a);}
static void rsort(long[] 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 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 int[] sorted(int[] a) {int[] ans = copy(a); sort(ans); return ans;}
static long[] sorted(long[] a) {long[] ans = copy(a); sort(ans); return ans;}
static int[] rsorted(int[] a) {int[] ans = copy(a); rsort(ans); return ans;}
static long[] rsorted(long[] a) {long[] ans = copy(a); rsort(ans); return ans;}
// graph util
static List<List<Integer>> graph(int n) {List<List<Integer>> g = new ArrayList<>(); for(int i = 0; i < n; ++i) g.add(new ArrayList<>()); return g;}
static List<List<Integer>> graph(List<List<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) connect(g, rni() - 1, ni() - 1); return g;}
static List<List<Integer>> graph(int n, int m) throws IOException {return graph(graph(n), m);}
static List<List<Integer>> dgraph(List<List<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) connecto(g, rni() - 1, ni() - 1); return g;}
static List<List<Integer>> dgraph(List<List<Integer>> g, int n, int m) throws IOException {return dgraph(graph(n), m);}
static List<Set<Integer>> sgraph(int n) {List<Set<Integer>> g = new ArrayList<>(); for(int i = 0; i < n; ++i) g.add(new HashSet<>()); return g;}
static List<Set<Integer>> sgraph(List<Set<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) connect(g, rni() - 1, ni() - 1); return g;}
static List<Set<Integer>> sgraph(int n, int m) throws IOException {return sgraph(sgraph(n), m);}
static List<Set<Integer>> dsgraph(List<Set<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) connecto(g, rni() - 1, ni() - 1); return g;}
static List<Set<Integer>> dsgraph(List<Set<Integer>> g, int n, int m) throws IOException {return dsgraph(sgraph(n), m);}
static void connect(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v); g.get(v).add(u);}
static void connecto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v);}
static void dconnect(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v); g.get(v).remove(u);}
static void dconnecto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v);}
// 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 int[] riam1(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()) - 1; 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()); else __out.println();}
static void h() {__out.println("hlfd");}
static void flush() {__out.flush();}
static void close() {__out.close();}
} | 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 RestoringPermutation {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
outer:
while(t-->0) {
int n=sc.nextInt();
int arr[]=new int[n];
Set<Integer> foo=new LinkedHashSet<>();
List<Integer> list=new ArrayList<>();
for(int i=0;i<n;i++) {
foo.add(sc.nextInt());
}
for(int i=1;i<=(2*n);i++) {
if(!foo.contains(i)) {
list.add(i);
}
}
Collections.sort(list);
List<Integer> foolist = new ArrayList<>();
List<String> ans=new ArrayList<>();
foolist.addAll(foo);
int count=0;
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) {
if(foolist.get(i)<list.get(j)) {
ans.add(foolist.get(i)+" "+list.get(j)+" ");
foolist.set(i,-1);
list.set(j, -1);
count++;
break;
}
}
if(count==0) {
System.out.println(-1);
continue outer;
}
count=0;
}
for(int i=0;i<ans.size();i++) {
System.out.print(ans.get(i));
}
System.out.println();
}
}
}
| java |
1311 | B | B. WeirdSorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn.You are also given a set of distinct positions p1,p2,…,pmp1,p2,…,pm, where 1≤pi<n1≤pi<n. The position pipi means that you can swap elements a[pi]a[pi] and a[pi+1]a[pi+1]. You can apply this operation any number of times for each of the given positions.Your task is to determine if it is possible to sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps.For example, if a=[3,2,1]a=[3,2,1] and p=[1,2]p=[1,2], then we can first swap elements a[2]a[2] and a[3]a[3] (because position 22 is contained in the given set pp). We get the array a=[3,1,2]a=[3,1,2]. Then we swap a[1]a[1] and a[2]a[2] (position 11 is also contained in pp). We get the array a=[1,3,2]a=[1,3,2]. Finally, we swap a[2]a[2] and a[3]a[3] again and get the array a=[1,2,3]a=[1,2,3], sorted in non-decreasing order.You can see that if a=[4,1,2,3]a=[4,1,2,3] and p=[3,2]p=[3,2] then you cannot sort the array.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.Then tt test cases follow. The first line of each test case contains two integers nn and mm (1≤m<n≤1001≤m<n≤100) — the number of elements in aa and the number of elements in pp. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100). The third line of the test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n, all pipi are distinct) — the set of positions described in the problem statement.OutputFor each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps. Otherwise, print "NO".ExampleInputCopy6
3 2
3 2 1
1 2
4 2
4 1 2 3
3 2
5 1
1 2 3 4 5
1
4 2
2 1 4 3
1 3
4 2
4 3 2 1
1 3
5 2
2 1 2 3 3
1 4
OutputCopyYES
NO
YES
YES
NO
YES
| [
"dfs and similar",
"sortings"
] | import java.util.*;
import java.io.*;
public class Main
{
public static void main(String args[]) throws IOException
{
// BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
Scanner sc=new Scanner(System.in);
// String testcases[]=br.readLine().split(" ");
// int t=Integer.parseInt(testcases[0]);
PrintWriter pw=new PrintWriter(System.out);
int t=sc.nextInt();
for(int i=0;i<t;i++)
{
int n=sc.nextInt();
int p=sc.nextInt();
int a[]=new int[n];
for(int j=0;j<n;j++)
a[j]=sc.nextInt();
HashSet<Integer> hs=new HashSet<>();
for(int j=0;j<p;j++)
hs.add(sc.nextInt());
for(int j=0;j<n;j++)
{
for(int k=0;k<n-1;k++)
{
if(a[k]>=a[k+1]&&hs.contains(k+1))
{
int temp=a[k];
a[k]=a[k+1];
a[k+1]=temp;
}
}
}
if(sortedIncreasing(a))
pw.write("YES\n");
else
pw.write("NO\n");
}
pw.flush();
pw.close();
}
// static int[][] getBitMap(int[] a)
// {
// int n=a.length;
// int[][] bit_map=new int[n][32];
// for(int j=0;j<n;j++)
// Arrays.fill(bit_map[j],0);
// for(int j=0;j<n;j++)
// {
// int counter=0;
// while(a[j]!=0)
// {
// bit_map[j][counter]=a[j]%2;
// a[j]/=2;
// counter++;
// }
// }
// return bit_map;
// }
// static ArrayList<Integer> sieveOfEratosthenes(int n)
// {
// boolean prime[]=new boolean[n+1];
// for(int j=0;j<=n;j++)
// prime[j]=true;
// for(long p=2;p*p<=n;p++)
// {
// if(prime[(int)p]==true)
// {
// for(long j=p*p;j<=n;j+=p)
// prime[(int)j]=false;
// }
// }
// ArrayList<Integer> al=new ArrayList<>();
// for(int j=2;j<=n;j++)
// {
// if(prime[j]==true)
// al.add(j);
// }
// return al;
// }
static boolean sortedIncreasing(int[] a)
{
int f=0;
for(int j=1;j<a.length;j++)
{
if(a[j]<a[j-1])
f=1;
}
return f==0?true:false;
}
// static boolean sortedDecreasing(long[] a)
// {
// int f=0;
// for(int j=1;j<a.length;j++)
// {
// if(a[j]>a[j-1])
// f=1;
// }
// return f==0?true:false;
// }
// static ArrayList<Long> getFactors(long n)
// {
// ArrayList<Long> al=new ArrayList<>();
// for(long i=1;i<=Math.sqrt(n);i++)
// {
// if(n%i==0)
// {
// al.add(i);
// if(n/i!=i)
// al.add(n/i);
// }
// }
// return al;
// }
// 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 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 boolean checkCoprime(int a, int b)
// {
// if(a==1||b==1)
// return true;
// if (gcd(a,b)==1)
// return true;
// else
// return false;
// }
// static boolean checkSquare(long n)
// {
// if (Math.ceil((double)Math.sqrt(n)) ==
// Math.floor((double)Math.sqrt(n)))
// return true;
// else
// return false;
// }
// static long floorSqrt(long x)
// {
// if (x == 0 || x == 1)
// return x;
// long start = 1, end = x / 2, ans = 0;
// while (start <= end) {
// long mid = (start + end) / 2;
// if (mid * mid == x)
// return (int)mid;
// if (mid * mid < x) {
// start = mid + 1;
// ans = mid;
// }
// else
// end = mid - 1;
// }
// return (long)ans;
// }
}
// class Pair
// {
// int h=0;
// int p=0;
// Pair(int x, int y)
// {
// h=x;
// p=y;
// }
// }
// class NewComparator implements Comparator<Pair>
// {
// public int compare(Pair p1, Pair p2)
// {
// if (p1.p < p2.p)
// return 1;
// else if (p1.p > p2.p)
// return -1;
// return 0;
// }
// }
| 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 static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import static java.lang.System.out;
import java.util.*;
import java.io.*;
import java.math.*;
/*
-> Give your 100%, that's it!
-> Rules To Solve Any Problem:
1. Read the problem.
2. Think About It.
3. Solve it!
*/
public class Template {
static int mod = 1000000007;
public static void main(String[] args){
FastScanner sc = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int yo = 1;
while (yo-- > 0) {
int n = sc.nextInt();
char[] a = sc.next().toCharArray();
char[] b = sc.next().toCharArray();
int[] aa = new int[27];
int[] bb = new int[27];
for(char c : a){
if(c == '?'){
aa[26]++;
continue;
}
aa[c-'a']++;
}
for(char c : b){
if(c == '?'){
bb[26]++;
continue;
}
bb[c-'a']++;
}
Map<Integer,Set<Integer>> map1 = new HashMap<>();
Map<Integer,Set<Integer>> map2 = new HashMap<>();
for(int i = 0; i < 27; i++){
map1.computeIfAbsent(i, x -> new LinkedHashSet<>());
map2.computeIfAbsent(i, x -> new LinkedHashSet<>());
}
for(int i = 0; i < n; i++){
char c = a[i];
if(c == '?'){
map1.get(26).add(i);
continue;
}
map1.get(c-'a').add(i);
}
for(int i = 0; i < b.length; i++){
char c = b[i];
if(c == '?'){
map2.get(26).add(i);
continue;
}
map2.get(c-'a').add(i);
}
List<String> list = new ArrayList<>();
for(int i = 0; i < 26; i++){
int min = Math.min(aa[i],bb[i]);
if(min != 0){
aa[i] -= min;
bb[i] -= min;
Set<Integer> set1 = map1.get(i);
Set<Integer> set2 = map2.get(i);
while(!set1.isEmpty() && !set2.isEmpty()){
int i1 = set1.iterator().next();
int i2 = set2.iterator().next();
set1.remove(i1);
set2.remove(i2);
list.add((i1+1) + " " + (i2+1));
}
}
}
if(aa[26] != 0){
for(int i = 0; i < 27; i++){
int min = Math.min(aa[26],bb[i]);
if(min != 0){
aa[26] -= min;
bb[i] -= min;
Set<Integer> set1 = map1.get(26);
Set<Integer> set2 = map2.get(i);
while(!set1.isEmpty() && !set2.isEmpty()){
int i1 = set1.iterator().next();
int i2 = set2.iterator().next();
set1.remove(i1);
set2.remove(i2);
list.add((i1+1) + " " + (i2+1));
}
}
}
}
if(bb[26] != 0){
for(int i = 0; i < 27; i++){
int min = Math.min(aa[i],bb[26]);
if(min != 0){
aa[i] -= min;
bb[26] -= min;
Set<Integer> set1 = map1.get(i);
Set<Integer> set2 = map2.get(26);
while(!set1.isEmpty() && !set2.isEmpty()){
int i1 = set1.iterator().next();
int i2 = set2.iterator().next();
set1.remove(i1);
set2.remove(i2);
list.add((i1+1) + " " + (i2+1));
}
}
}
}
out.println(list.size());
for(String s : list){
out.println(s);
}
}
out.close();
}
/*
Source: hu_tao
Random stuff to try when stuck:
-if it's 2C then it's dp
-for combo/probability problems, expand the given form we're interested in
-make everything the same then build an answer (constructive, make everything 0 then do something)
-something appears in parts of 2 --> model as graph
-assume a greedy then try to show why it works
-find way to simplify into one variable if multiple exist
-treat it like fmc (note any passing thoughts/algo that could be used so you can revisit them)
-find lower and upper bounds on answer
-figure out what ur trying to find and isolate it
-see what observations you have and come up with more continuations
-work backwards (in constructive, go from the goal to the start)
-turn into prefix/suffix sum argument (often works if problem revolves around adjacent array elements)
-instead of solving for answer, try solving for complement (ex, find n-(min) instead of max)
-draw something
-simulate a process
-dont implement something unless if ur fairly confident its correct
-after 3 bad submissions move on to next problem if applicable
-do something instead of nothing and stay organized
-write stuff down
Random stuff to check when wa:
-if code is way too long/cancer then reassess
-switched N/M
-int overflow
-switched variables
-wrong MOD
-hardcoded edge case incorrectly
Random stuff to check when tle:
-continue instead of break
-condition in for/while loop bad
Random stuff to check when rte:
-switched N/M
-long to int/int overflow
-division by 0
-edge case for empty list/data structure/N=1
*/
public static class Pair {
int x;
int y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
public static void sort(int[] arr) {
ArrayList<Integer> ls = new ArrayList<Integer>();
for (int x : arr)
ls.add(x);
Collections.sort(ls);
for (int i = 0; i < arr.length; i++)
arr[i] = ls.get(i);
}
public static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static boolean[] sieve(int N) {
boolean[] sieve = new boolean[N + 1];
for (int i = 2; i <= N; i++)
sieve[i] = true;
for (int i = 2; i <= N; i++) {
if (sieve[i]) {
for (int j = 2 * i; j <= N; j += i) {
sieve[j] = false;
}
}
}
return sieve;
}
public static long power(long x, long y, long p) {
long res = 1L;
x = x % p;
while (y > 0) {
if ((y & 1) == 1)
res = (res * x) % p;
y >>= 1;
x = (x * x) % p;
}
return res;
}
public static void print(int[] arr, PrintWriter out) {
//for debugging only
for (int x : arr)
out.print(x + " ");
out.println();
}
static class FastScanner {
private int BS = 1 << 16;
private char NC = (char) 0;
private byte[] buf = new byte[BS];
private int bId = 0, size = 0;
private char c = NC;
private double cnt = 1;
private BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
} catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
private char getChar() {
while (bId == size) {
try {
size = in.read(buf);
} catch (Exception e) {
return NC;
}
if (size == -1)
return NC;
bId = 0;
}
return (char) buf[bId++];
}
public int nextInt() {
return (int) nextLong();
}
public int[] readInts(int N) {
int[] res = new int[N];
for (int i = 0; i < N; i++) {
res[i] = (int) nextLong();
}
return res;
}
public long[] readLongs(int N) {
long[] res = new long[N];
for (int i = 0; i < N; i++) {
res[i] = nextLong();
}
return res;
}
public long nextLong() {
cnt = 1;
boolean neg = false;
if (c == NC)
c = getChar();
for (; (c < '0' || c > '9'); c = getChar()) {
if (c == '-')
neg = true;
}
long res = 0;
for (; c >= '0' && c <= '9'; c = getChar()) {
res = (res << 3) + (res << 1) + c - '0';
cnt *= 10;
}
return neg ? -res : res;
}
public double nextDouble() {
double cur = nextLong();
return c != '.' ? cur : cur + nextLong() / cnt;
}
public double[] readDoubles(int N) {
double[] res = new double[N];
for (int i = 0; i < N; i++) {
res[i] = nextDouble();
}
return res;
}
public String next() {
StringBuilder res = new StringBuilder();
while (c <= 32)
c = getChar();
while (c > 32) {
res.append(c);
c = getChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while (c <= 32)
c = getChar();
while (c != '\n') {
res.append(c);
c = getChar();
}
return res.toString();
}
public boolean hasNext() {
if (c > 32)
return true;
while (true) {
c = getChar();
if (c == NC)
return false;
else if (c > 32)
return true;
}
}
}
// For Input.txt and Output.txt
// FileInputStream in = new FileInputStream("input.txt");
// FileOutputStream out = new FileOutputStream("output.txt");
// PrintWriter pw = new PrintWriter(out);
// Scanner sc = new Scanner(in);
} | java |
1296 | A | A. Array with Odd Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.In one move, you can choose two indices 1≤i,j≤n1≤i,j≤n such that i≠ji≠j and set ai:=ajai:=aj. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose ii and jj and replace aiai with ajaj).Your task is to say if it is possible to obtain an array with an odd (not divisible by 22) sum of elements.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤20001≤t≤2000) — 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≤20001≤n≤2000) — the number of elements in aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤20001≤ai≤2000), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 20002000 (∑n≤2000∑n≤2000).OutputFor each test case, print the answer on it — "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise.ExampleInputCopy5
2
2 3
4
2 2 8 8
3
3 3 3
4
5 5 5 5
4
1 1 1 1
OutputCopyYES
NO
YES
NO
NO
| [
"math"
] | import java.io.*;
import java.util.*;
public class ProbA {
static int T;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
StringTokenizer st = new StringTokenizer(br.readLine());
T = Integer.parseInt(st.nextToken());
for (int t = 0; t < T; t++) {
st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken());
//odd sum dont do anything
//even sum, make even
int even = 0;
int odd = 0;
int sum = 0;
st = new StringTokenizer(br.readLine());
for(int i = 0; i<N; i++) {
int a = Integer.parseInt(st.nextToken());
if(a % 2 == 0) even++;
else odd++;
sum += a;
}
boolean good = false;
if(sum % 2 == 1) {
good = true;
}else if(even >= 1 && odd >= 1){
good = true;
}
pw.println(good ? "YES": "NO");
}
pw.close();
}
}
| 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.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Random;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
// CFPS -> CodeForcesProblemSet
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 double epsilon = 0.00000001;
static boolean[] isPrime;
static int[] smallestFactorOf;
@SuppressWarnings("unused")
public static void main(String[] args) {
OUTER:
for (int tc = 0; tc < t; tc++) {
int n = fr.nextInt();
long[] arr = fr.nextLongArray(n);
// Observations:
// 1. The task is to determine a value 'X' such that max(a[i] ^ x) is
// minimized.
// 2. Starting from the largest bit level, we will always want to, at
// any cost, prioritize that bit level.
// 3. At the current bit level, if all elements have it OFF, we will
// obviously set it to ON, vice versa.
// 4. At the current bit level, if some elements are OFF (and some ON),
// we will want to explore both possibilities. The set of all elements
// will therefore be split into two, based on our prioritization.
// If,
// a. We set the bit to ON: We have chosen all elements with that bit ON.
// b. We set the bit to OFF: We have chosen all elements with that bit OFF.
HashSet<Long> elems = new HashSet<>();
for (long i : arr) elems.add(i);
long[] bestAns = new long[1];
bestAns[0] = Long.MAX_VALUE;
solve(elems, bestAns, 29, 0, 0);
out.println(bestAns[0]);
}
out.close();
}
static void solve(HashSet<Long> elems, long[] bestAns, int level, long currX, long bestAnsHere) {
if (level < 0) {
bestAns[0] = Math.min(bestAns[0], bestAnsHere);
return;
}
long lleftshift = (1L << level);
int onCnt = 0;
for (long l : elems)
if ((l & lleftshift) > 0)
onCnt++;
if (onCnt == 0) {
// all elements have the bit OFF
// we will have the bit OFF in currX
currX += 0;
solve(elems, bestAns, level - 1, currX, bestAnsHere);
return;
}
if (onCnt == elems.size()) {
// all elements have the bit ON
// we will have the bit ON in currX
currX += (lleftshift);
solve(elems, bestAns, level - 1, currX, bestAnsHere);
return;
}
assert 0 < onCnt && onCnt < elems.size();
// we will explore two passages:
// a. The bit stays OFF in X -> bit stays OFF in X
// b. The bit stays ON in X -> bit stays ON in X
HashSet<Long> offElems = new HashSet<>();
HashSet<Long> onElems = new HashSet<>();
for (long l : elems)
if ((l & lleftshift) > 0)
onElems.add(l);
for (long l : elems)
if (!onElems.contains(l))
offElems.add(l);
solve(offElems, bestAns, level - 1, currX + lleftshift, bestAnsHere + lleftshift);
solve(onElems, bestAns, level - 1, currX + lleftshift, bestAnsHere + lleftshift);
}
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];
diamDFS(farthest, -1, 0, ug, distTo);
return Arrays.stream(distTo).max().getAsInt();
}
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 State {
int node, dist;
State(int ll, int rr) {
node = ll;
dist = rr;
}
}
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 boolean[] prefMatchesSuff(char[] s) {
int n = s.length;
boolean[] res = new boolean[n + 1];
int[] pi = prefixFunction(s);
res[0] = true;
for (int p = n; p != 0; p = pi[p])
res[p] = true;
return res;
}
static int[] prefixFunction(char[] s) {
int k = s.length;
int[] pfunc = new int[k + 1];
pfunc[0] = pfunc[1] = 0;
for (int i = 2; i <= k; i++) {
pfunc[i] = 0;
for (int p = pfunc[i - 1]; p != 0; p = pfunc[p])
if (s[p] == s[i - 1]) {
pfunc[i] = p + 1;
break;
}
if (pfunc[i] == 0 && s[i - 1] == s[0])
pfunc[i] = 1;
}
return pfunc;
}
static class Edge implements Comparable<Edge> {
int from, to;
long weight;
int id;
// int hash;
Edge(int fro, int t, long weigh, int i) {
from = fro;
to = t;
weight = weigh;
id = i;
// 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[][] sparseTable(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 sparseRMQ(long[][] table, int l, int r)
{
// [a,b)
assert l <= r;
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)]);
}
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;
}
/*@Override
public int hashCode() {
return this.hashCode;
}*/
}
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;
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);
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];
// 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, 0);
// 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 int dpDFS(int current, int from, int lvl) {
levelOf[current] = lvl;
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, lvl + 1));
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;
}
}
static class SegmentTree {
private Node[] heap;
private long[] array;
private int size;
public SegmentTree(long[] array) {
this.array = Arrays.copyOf(array, array.length);
//The max size of this array is about 2 * 2 ^ log2(n) + 1
size = (int) (2 * Math.pow(2.0, Math.floor((Math.log((double) array.length) / Math.log(2.0)) + 1)));
heap = new Node[size];
build(1, 0, array.length);
}
public int size() {
return array.length;
}
//Initialize the Nodes of the Segment tree
private void build(int v, int from, int size) {
heap[v] = new Node();
heap[v].from = from;
heap[v].to = from + size - 1;
if (size == 1) {
heap[v].sum = array[from];
heap[v].min = array[from];
heap[v].max = array[from];
} else {
//Build childs
build(2 * v, from, size / 2);
build(2 * v + 1, from + size / 2, size - size / 2);
heap[v].sum = heap[2 * v].sum + heap[2 * v + 1].sum;
//min = min of the children
heap[v].min = Math.min(heap[2 * v].min, heap[2 * v + 1].min);
heap[v].max = Math.max(heap[2 * v].max, heap[2 * v + 1].max);
}
}
public long rsq(int from, int to) {
return rsq(1, from, to);
}
private long rsq(int v, int from, int to) {
Node n = heap[v];
//If you did a range update that contained this node, you can infer the Sum without going down the tree
if (n.pendingVal != null && contains(n.from, n.to, from, to)) {
return (to - from + 1) * n.pendingVal;
}
if (contains(from, to, n.from, n.to)) {
return heap[v].sum;
}
if (intersects(from, to, n.from, n.to)) {
propagate(v);
long leftSum = rsq(2 * v, from, to);
long rightSum = rsq(2 * v + 1, from, to);
return leftSum + rightSum;
}
return 0;
}
public long rMinQ(int from, int to) {
return rMinQ(1, from, to);
}
private long rMinQ(int v, int from, int to) {
Node n = heap[v];
//If you did a range update that contained this node, you can infer the Min value without going down the tree
if (n.pendingVal != null && contains(n.from, n.to, from, to)) {
return n.pendingVal;
}
if (contains(from, to, n.from, n.to)) {
return heap[v].min;
}
if (intersects(from, to, n.from, n.to)) {
propagate(v);
long leftMin = rMinQ(2 * v, from, to);
long rightMin = rMinQ(2 * v + 1, from, to);
return Math.min(leftMin, rightMin);
}
return Integer.MAX_VALUE;
}
public long rMaxQ(int from, int to) {
return rMaxQ(1, from, to);
}
private long rMaxQ(int v, int from, int to) {
Node n = heap[v];
//If you did a range update that contained this node, you can infer the Min value without going down the tree
if (n.pendingVal != null && contains(n.from, n.to, from, to)) {
return n.pendingVal;
}
if (contains(from, to, n.from, n.to)) {
return heap[v].max;
}
if (intersects(from, to, n.from, n.to)) {
propagate(v);
long leftMax = rMaxQ(2 * v, from, to);
long rightMax = rMaxQ(2 * v + 1, from, to);
return Math.max(leftMax, rightMax);
}
return Integer.MIN_VALUE;
}
public void update(int from, int to, long value) {
update(1, from, to, value);
}
private void update(int v, int from, int to, long value) {
//The Node of the heap tree represents a range of the array with bounds: [n.from, n.to]
Node n = heap[v];
if (contains(from, to, n.from, n.to)) {
change(n, value);
}
if (n.size() == 1) return;
if (intersects(from, to, n.from, n.to)) {
propagate(v);
update(2 * v, from, to, value);
update(2 * v + 1, from, to, value);
n.sum = heap[2 * v].sum + heap[2 * v + 1].sum;
n.min = Math.min(heap[2 * v].min, heap[2 * v + 1].min);
n.max = Math.max(heap[2 * v].max, heap[2 * v + 1].max);
}
}
//Propagate temporal values to children
private void propagate(int v) {
Node n = heap[v];
if (n.pendingVal != null) {
change(heap[2 * v], n.pendingVal);
change(heap[2 * v + 1], n.pendingVal);
n.pendingVal = null; //unset the pending propagation value
}
}
//Save the temporal values that will be propagated lazily
private void change(Node n, long value) {
n.pendingVal = value;
n.sum = n.size() * value;
n.min = value;
n.max = value;
array[n.from] = value;
}
//Test if the range1 contains range2
private boolean contains(int from1, int to1, int from2, int to2) {
return from2 >= from1 && to2 <= to1;
}
//check inclusive intersection, test if range1[from1, to1] intersects range2[from2, to2]
private boolean intersects(int from1, int to1, int from2, int to2) {
return from1 <= from2 && to1 >= from2 // (.[..)..] or (.[...]..)
|| from1 >= from2 && from1 <= to2; // [.(..]..) or [..(..)..
}
//The Node class represents a partition range of the array.
static class Node {
long sum;
long min;
long max;
//Here we store the value that will be propagated lazily
Long pendingVal = null;
int from;
int to;
int size() {
return to - from + 1;
}
}
}
@SuppressWarnings("serial")
static class CountMap<T> extends TreeMap<T, Integer>{
CountMap() {
}
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 long hash(long key) {
long h = Long.hashCode(key);
h ^= (h >>> 20) ^ (h >>> 12) ^ (h >>> 7) ^ (h >>> 4);
return h & (gigamod-1);
}
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 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 int bsearch(int[] arr, int val, int lo, int hi) {
// Returns the index of the first element
// larger than or equal to val.
int idx = -1;
while (lo <= hi) {
int mid = lo + (hi - lo)/2;
if (arr[mid] >= val) {
idx = mid;
hi = mid - 1;
} else
lo = mid + 1;
}
return idx;
}
static int bsearch(long[] arr, long val, int lo, int hi) {
// Returns the index of the first element
// larger than or equal to val.
int idx = -1;
while (lo <= hi) {
int mid = lo + (hi - lo)/2;
if (arr[mid] >= val) {
idx = mid;
hi = mid - 1;
} else
lo = mid + 1;
}
return idx;
}
static int bsearch(long[] arr, long val, int lo, int hi, boolean sMode) {
// Returns the index of the last element
// smaller than or equal to val.
int idx = -1;
while (lo <= hi) {
int mid = lo + (hi - lo)/2;
if (arr[mid] > val) {
hi = mid - 1;
} else {
idx = mid;
lo = mid + 1;
}
}
return idx;
}
static int bsearch(int[] arr, long val, int lo, int hi, boolean sMode) {
int idx = -1;
while (lo <= hi) {
int mid = lo + (hi - lo)/2;
if (arr[mid] > val) {
hi = mid - 1;
} else {
idx = mid;
lo = mid + 1;
}
}
return idx;
}
static long nCr(long n, long r, long[] fac) { long p = mod; 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, gigamod - 2, gigamod));}
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;}
static long mod(long num){return(num%gigamod+gigamod)%gigamod;}
}
// 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 |
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 java.io.*;
import java.util.*;
public class CF_1288C {
static long MOD = 1000000007;
public static void main(String[] args) throws IOException {
Kattio io = new Kattio();
int n = io.nextInt();
int m = io.nextInt();
long[][] dp1 = new long[n+1][m];
long[][] dp2 = new long[n+1][m];
for (int i=1; i<=n; i++) {
dp1[i][0] = 1;
dp2[i][0] = 1;
}
for (int k=1; k<m; k++) {
for (int i=1; i<=n; i++) {
for (int j=1; j<=i; j++) {
dp1[i][k] = (dp1[i][k] + dp1[j][k-1]) % MOD;
}
for (int j=i; j<=n; j++) {
dp2[i][k] = (dp2[i][k] + dp2[j][k-1]) % MOD;
}
}
}
long ans = 0;
for (int i=1; i<=n; i++) {
for (int j=1; j<=n; j++) {
if (i > j) continue;
ans = (ans + dp1[i][m-1] * dp2[j][m-1]) % MOD;
}
}
System.out.println(ans);
}
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()); }
}
} | java |
1294 | E | E. Obtain a Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rectangular matrix of size n×mn×m consisting of integers from 11 to 2⋅1052⋅105.In one move, you can: choose any element of the matrix and change its value to any integer between 11 and n⋅mn⋅m, inclusive; take any column and shift it one cell up cyclically (see the example of such cyclic shift below). A cyclic shift is an operation such that you choose some jj (1≤j≤m1≤j≤m) and set a1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,ja1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,j simultaneously. Example of cyclic shift of the first column You want to perform the minimum number of moves to make this matrix look like this: In other words, the goal is to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (i.e. ai,j=(i−1)⋅m+jai,j=(i−1)⋅m+j) with the minimum number of moves performed.InputThe first line of the input contains two integers nn and mm (1≤n,m≤2⋅105,n⋅m≤2⋅1051≤n,m≤2⋅105,n⋅m≤2⋅105) — the size of the matrix.The next nn lines contain mm integers each. The number at the line ii and position jj is ai,jai,j (1≤ai,j≤2⋅1051≤ai,j≤2⋅105).OutputPrint one integer — the minimum number of moves required to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (ai,j=(i−1)m+jai,j=(i−1)m+j).ExamplesInputCopy3 3
3 2 1
1 2 3
4 5 6
OutputCopy6
InputCopy4 3
1 2 3
4 5 6
7 8 9
10 11 12
OutputCopy0
InputCopy3 4
1 6 3 4
5 10 7 8
9 2 11 12
OutputCopy2
NoteIn the first example; you can set a1,1:=7,a1,2:=8a1,1:=7,a1,2:=8 and a1,3:=9a1,3:=9 then shift the first, the second and the third columns cyclically, so the answer is 66. It can be shown that you cannot achieve a better answer.In the second example, the matrix is already good so the answer is 00.In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is 22. | [
"greedy",
"implementation",
"math"
] |
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 {
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 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 MyScanner sc = new MyScanner(); // only in case of less memory
static Reader sc = new Reader();
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() , m = sc.nextInt();
int num = 1;
int[] ans[] = new int[n][m];
for(int i =0 ; i<n ; i++) {
for(int j = 0 ; j<m ; j++)
ans[i][j] = num++;
}
int[][] mat = new int[n][m];
for(int i =0 ; i<n ;i ++) {
for(int j =0 ; j<m ; j++)
mat[i][j] = sc.nextInt();
}
long tot = 0 ;
for(int j = 0 ; j<m ; j++) {
int[] arr = new int[n];
int[] f = new int[n];
for(int i = 0 ; i<n ; i++) {
arr[i] = mat[i][j];
f[i] = ans[i][j];
}
// System.out.println("--------------");
tot += count(arr, f, m);
// System.out.println(j +" " +tot);
}
System.out.println(tot);
}
static int count(int[] arr , int[] f , int m) {
// for(int e:arr) System.out.print(e+ " ");
// System.out.println();
// for(int e:f) System.out.print(e+" ");
// System.out.println();
int n = arr.length;
int count =n ;
int[] shift = new int[n+1];
m = n;
Map<Integer , Integer> map = new HashMap<>();
for(int i = 0 ; i<n ; i++) {
map.put(f[i], i);
}
// System.out.println(map);
for(int i =0 ; i <n ; i++) {
int e = arr[i];
if(!map.containsKey(e)) continue;
int ind = map.get(e);
if(ind <= i) {
shift[i-ind]++;
}else {
int dif = ind - i;
shift[n - dif]++;
}
}
for(int i = 0 ; i<=n ; i++) {
int c = shift[i];
int rem = n - c;
count = min(count , rem + i);
}
return count;
}
}
/*******************************************************************************************************************************************************/
/**
*/
| 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.io.*;
import java.util.*;
public class CopyCopyCopyCopyCopy {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// try {
// scanner = new Scanner(new FileInputStream("input.txt"));
// }
// catch (Exception e) {
// System.out.println("Error");
// }
int t = scanner.nextInt();
for (int x = 0; x < t; x++) {
int n = scanner.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
Arrays.sort(arr);
n = removeduplicates(arr, n);
System.out.println(n);
}
}
public static int removeduplicates(int a[], int n) {
if (n == 0 || n == 1) {
return n;
}
int[] temp = new int[n];
int j = 0;
for (int i = 0; i < n - 1; i++) {
if (a[i] != a[i + 1]) {
temp[j++] = a[i];
}
}
temp[j++] = a[n - 1];
for (int i = 0; i < j; i++) {
a[i] = temp[i];
}
return j;
}
}
| java |
1285 | A | A. Mezo Playing Zomatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Mezo is playing a game. Zoma, a character in that game, is initially at position x=0x=0. Mezo starts sending nn commands to Zoma. There are two possible commands: 'L' (Left) sets the position x:=x−1x:=x−1; 'R' (Right) sets the position x:=x+1x:=x+1. Unfortunately, Mezo's controller malfunctions sometimes. Some commands are sent successfully and some are ignored. If the command is ignored then the position xx doesn't change and Mezo simply proceeds to the next command.For example, if Mezo sends commands "LRLR", then here are some possible outcomes (underlined commands are sent successfully): "LRLR" — Zoma moves to the left, to the right, to the left again and to the right for the final time, ending up at position 00; "LRLR" — Zoma recieves no commands, doesn't move at all and ends up at position 00 as well; "LRLR" — Zoma moves to the left, then to the left again and ends up in position −2−2. Mezo doesn't know which commands will be sent successfully beforehand. Thus, he wants to know how many different positions may Zoma end up at.InputThe first line contains nn (1≤n≤105)(1≤n≤105) — the number of commands Mezo sends.The second line contains a string ss of nn commands, each either 'L' (Left) or 'R' (Right).OutputPrint one integer — the number of different positions Zoma may end up at.ExampleInputCopy4
LRLR
OutputCopy5
NoteIn the example; Zoma may end up anywhere between −2−2 and 22. | [
"math"
] | import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String s = sc.next();
int count1 = 0, count2 = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == 'L') {
count1--;
} else {
count2++;
}
}
System.out.println(count2 - count1 + 1);
}
}
| java |
1304 | F1 | F1. Animal Observation (easy version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the constraint on kk.Gildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue.Gildong is going to take videos for nn days, starting from day 11 to day nn. The forest can be divided into mm areas, numbered from 11 to mm. He'll use the cameras in the following way: On every odd day (11-st, 33-rd, 55-th, ...), bring the red camera to the forest and record a video for 22 days. On every even day (22-nd, 44-th, 66-th, ...), bring the blue camera to the forest and record a video for 22 days. If he starts recording on the nn-th day with one of the cameras, the camera records for only one day. Each camera can observe kk consecutive areas of the forest. For example, if m=5m=5 and k=3k=3, he can put a camera to observe one of these three ranges of areas for two days: [1,3][1,3], [2,4][2,4], and [3,5][3,5].Gildong got information about how many animals will be seen in each area each day. Since he would like to observe as many animals as possible, he wants you to find the best way to place the two cameras for nn days. Note that if the two cameras are observing the same area on the same day, the animals observed in that area are counted only once.InputThe first line contains three integers nn, mm, and kk (1≤n≤501≤n≤50, 1≤m≤2⋅1041≤m≤2⋅104, 1≤k≤min(m,20)1≤k≤min(m,20)) – the number of days Gildong is going to record, the number of areas of the forest, and the range of the cameras, respectively.Next nn lines contain mm integers each. The jj-th integer in the i+1i+1-st line is the number of animals that can be seen on the ii-th day in the jj-th area. Each number of animals is between 00 and 10001000, inclusive.OutputPrint one integer – the maximum number of animals that can be observed.ExamplesInputCopy4 5 2
0 2 1 1 0
0 0 3 1 2
1 0 4 3 1
3 3 0 0 4
OutputCopy25
InputCopy3 3 1
1 2 3
4 5 6
7 8 9
OutputCopy31
InputCopy3 3 2
1 2 3
4 5 6
7 8 9
OutputCopy44
InputCopy3 3 3
1 2 3
4 5 6
7 8 9
OutputCopy45
NoteThe optimal way to observe animals in the four examples are as follows:Example 1: Example 2: Example 3: Example 4: | [
"data structures",
"dp"
] | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
Scanner in = new Scanner(System.in);
int n = in.nextInt(), m = in.nextInt(), k = in.nextInt();
int[][] a = new int[n + 1][m];
for(int i = 0; i < n; ++i)
for(int j = 0; j < m; ++j)
a[i][j] = in.nextInt();
int[][] pre = new int[n + 1][m];
for(int i = 0; i < n; ++i)
pre[i][0] = a[i][0];
for(int i = 0; i < n; ++i)
for(int j = 1; j < m; ++j)
pre[i][j] = a[i][j] + pre[i][j - 1];
int[] dp = new int[m];
int[] pmx = new int[m];
int[] smx = new int[m];
for(int i = 0; i <= m - k; ++i) {
int j = i + k - 1;
dp[i] = pre[0][j] + pre[1][j];
if(i != 0)
dp[i] -= pre[0][i - 1] + pre[1][i - 1];
}
pmx[0] = dp[0];
smx[m - 1] = dp[m - 1];
for(int i = 1; i < m; ++i)
pmx[i] = Math.max(pmx[i - 1], dp[i]);
for(int i = m - 2; i >=0 ; --i)
smx[i] = Math.max(smx[i + 1], dp[i]);
for(int i = 1; i < n; ++i) {
int[] ndp = new int[m];
for(int j = 0; j <= m - k; ++j) {
int nj = j + k - 1;
int num = pre[i][nj] + pre[i + 1][nj];
if(j != 0)
num -= pre[i][j - 1] + pre[i + 1][j - 1];
ndp[j] = num;
int add = 0;
if(j - k >= 0)
add = pmx[j - k];
if(j + k < m)
add = Math.max(add, smx[j + k]);
ndp[j] += add;
int r = Math.min(j + k - 1, m - k);
for(int pos = Math.max(0, j - k + 1); pos <= r; ++pos) {
int val = dp[pos] + num;
int R = Math.min(pos, j) + k;
for(int jj = Math.max(pos, j); jj < R; ++jj)
val -= a[i][jj];
ndp[j] = Math.max(ndp[j], val);
}
}
for(int j = 0; j < m; ++j)
dp[j] = ndp[j];
pmx[0] = dp[0];
smx[m - 1] = dp[m - 1];
for(int j = 1; j < m; ++j)
pmx[j] = Math.max(pmx[j - 1], dp[j]);
for(int j = m - 2; j >= 0; --j)
smx[j] = Math.max(smx[j + 1], dp[j]);
}
int ans = 0;
for(int i = 0; i < m; ++i)
ans = Math.max(ans, dp[i]);
System.out.println(ans);
}
} | 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.*;
import static java.lang.Math.*;
public class CP {
static int MAX = Integer.MAX_VALUE,MIN = Integer.MIN_VALUE,MOD = (int)1e9+7;
static long MAXL = (long)1e18,MINL = -(long)1e18;
static void solve() {
int n = fs.nInt();
int[]ar = new int[n];
int[]br = new int[n];
int[]cr = new int[n];
for(int i=0;i<n;i++)ar[i] = fs.nInt();
for(int i=0;i<n;i++)br[i] = fs.nInt();
for(int i=0;i<n;i++){
cr[i] = ar[i]-br[i];
}
sort(cr);
long ans = 0;
int l = 0, r = n-1;
while ( l < r ){
if( cr[l]+cr[r] > 0 ){
ans += (r-l);
r--;
}else{
l++;
}
}
out.println(ans);
}
static class Triplet<T,U,V>{
T a;
U b;
V c;
Triplet(T a,U b,V c){
this.a = a;
this.b = b;
this.c = c;
}
}
static class Pair<A, B>{
A fst;
B snd;
Pair(A fst,B snd){
this.fst = fst;
this.snd = snd;
}
}
static boolean multipleTestCase = false ;static FastScanner fs;static PrintWriter out;
static int curTC;
public static void main(String[] args) {
try{
fs = new FastScanner();
out = new PrintWriter(System.out);
int tc = (multipleTestCase)?fs.nInt():1;
curTC = 1;
while (curTC<=tc){
solve();
curTC++;
}
out.flush();
out.close();
}catch (Exception e){
e.printStackTrace();
}
}
static class FastScanner extends PrintWriter {
private InputStream stream;
private byte[] buf = new byte[1<<16];
private int curChar, numChars;
// standard input
public FastScanner() { this(System.in,System.out); }
public FastScanner(InputStream i, OutputStream o) {
super(o);
stream = i;
}
// file input
public FastScanner(String i, String o) throws IOException {
super(new FileWriter(o));
stream = new FileInputStream(i);
}
// throws InputMismatchException() if previously detected end of file
private int nextByte() {
if (numChars == -1) throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars == -1) return -1; // end of file
}
return buf[curChar++];
}
// to read in entire lines, replace c <= ' '
// with a function that checks whether c is a line break
public String next() {
int c; do { c = nextByte(); } while (c <= ' ');
StringBuilder res = new StringBuilder();
do { res.appendCodePoint(c); c = nextByte(); } while (c > ' ');
return res.toString();
}
public int nInt() { // nextLong() would be implemented similarly
int c; do { c = nextByte(); } while (c <= ' ');
int sgn = 1; if (c == '-') { sgn = -1; c = nextByte(); }
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = 10*res+c-'0';
c = nextByte();
} while (c > ' ');
return res * sgn;
}
public long nLong(){return Long.parseLong(next());}
public double nextDouble() { return Double.parseDouble(next()); }
}
public static void sort(int[] arr){
ArrayList<Integer> ls = new ArrayList<Integer>();
for(int x: arr)
ls.add(x);
Collections.sort(ls);
for(int i=0; i < arr.length; i++)
arr[i] = ls.get(i);
}
public static void sort(long[] arr){
ArrayList<Long> ls = new ArrayList<>();
for(long x: arr)
ls.add(x);
Collections.sort(ls);
for(int i=0; i < arr.length; i++)
arr[i] = ls.get(i);
}
public static void sortR(int[] arr){
ArrayList<Integer> ls = new ArrayList<>();
for(int x: arr)
ls.add(x);
Collections.sort(ls,Collections.reverseOrder());
for(int i=0; i < arr.length; i++)
arr[i] = ls.get(i);
}
public static void sortR(long[] arr){
ArrayList<Long> ls = new ArrayList<>();
for(long x: arr)
ls.add(x);
Collections.sort(ls,Collections.reverseOrder());
for(int i=0; i < arr.length; i++)
arr[i] = ls.get(i);
}
}
| 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 CF1562C extends PrintWriter {
CF1562C() { super(System.out); }
public static Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF1562C o = new CF1562C(); o.main(); o.flush();
}
static long calculate(long p, long q)
{
long mod = 1000000007, expo;
expo = mod - 2;
// Loop to find the value
// until the expo is not zero
while (expo != 0)
{
// Multiply p with q
// if expo is odd
if ((expo & 1) == 1)
{
p = (p * q) % mod;
}
q = (q * q) % mod;
// Reduce the value of
// expo by 2
expo >>= 1;
}
return p;
}
static String longestPalSubstr(String str)
{
// The result (length of LPS)
int maxLength = 1;
int start = 0;
int len = str.length();
int low, high;
// One by one consider every
// character as center
// point of even and length
// palindromes
for (int i = 1; i < len; ++i) {
// Find the longest even
// length palindrome with
// center points as i-1 and i.
low = i - 1;
high = i;
while (low >= 0 && high < len
&& str.charAt(low)
== str.charAt(high)) {
--low;
++high;
}
// Move back to the last possible valid palindrom substring
// as that will anyway be the longest from above loop
++low; --high;
if (str.charAt(low) == str.charAt(high) && high - low + 1 > maxLength) {
start = low;
maxLength = high - low + 1;
}
// Find the longest odd length
// palindrome with center point as i
low = i - 1;
high = i + 1;
while (low >= 0 && high < len
&& str.charAt(low)
== str.charAt(high)) {
--low;
++high;
}
// Move back to the last possible valid palindrom substring
// as that will anyway be the longest from above loop
++low; --high;
if (str.charAt(low) == str.charAt(high) && high - low + 1 > maxLength) {
start = low;
maxLength = high - low + 1;
}
}
return str.substring(start, start + maxLength - 1);
}
long check(long a){
long ret=0;
for(long k=2;(k*k*k)<=a;k++){
ret=ret+(a/(k*k*k));
}
return ret;
}
/*public static int getFirstSetBitPos(int n)
{
return (int)((Math.log10(n & -n)) / Math.log10(2)) + 1;
}
public static int bfsq(int n, int m, HashMap<Integer,ArrayList<Integer>>h,boolean v ){
v[n]=true;
if(n==m)
return 1;
else
{
int a=h.get(n).get(0);
int b=h.get(n).get(1);
if(b>m)
return(m-n);
else
{
int a1=bfsq(a,m,h,v);
int b1=bfsq(b,m,h,v);
return 1+Math.min(a1,b1);
}
}
}*/
static long nCr(int n, int r)
{ return fact(n) / (fact(r) *
fact(n - r));
}
// Returns factorial of n
static long fact(long n)
{
long res = 1;
for (long i = 2; i <= n; i++)
res = res * i;
return res;
}
/*void bfs(int src, HashMap<Integer,ArrayList<Integer,Integer>>h,int deg, boolean v[] ){
a[src]=deg;
Queue<Integer>= new LinkedList<Integer>();
q.add(src);
while(!q.isEmpty()){
(int a:h.get(src)){
if()
}
}
}*/
/* void dfs(int root, int par, HashMap<Integer,ArrayList<Integer>>h,int dp[], int child[]) {
dp[root]=0;
child[root]=1;
for(int x: h.get(root)){
if(x == par) continue;
dfs(x,root,h,in,dp);
child[root]+=child[x];
}
ArrayList<Integer> mine= new ArrayList<Integer>();
for(int x: h.get(root)) {
if(x == par) continue;
mine.add(x);
}
if(mine.size() >=2){
int y= Math.max(child[mine.get(0)] - 1 + dp[mine.get(1)] , child[mine.get(1)] -1 + dp[mine.get(0)]);
dp[root]=y;}
else if(mine.size() == 1)
dp[root]=child[mine.get(0)] - 1;
}
*/
class Pair implements Comparable<Pair>{
int i;
int j;
Pair (int a, int b){
i = a;
j = b;
}
public int compareTo(Pair A){
return (int)(this.i-A.i);
}}
/*static class Pair {
int i;
int j;
Pair() {
}
Pair(int i, int j) {
this.i = i;
this.j = j;
}
}*/
/*ArrayList<Integer> check(int a[], int b){
int n=a.length;
long ans=0;int k=0;
ArrayList<Integer>ab= new ArrayList<Integer>();
for(int i=0;i<n;i++){
if(a[i]%m==0)
{k=a[i];
while(a[i]%m==0){
a[i]=a[i]/m;
}
for(int z=0;z<k/a[i];z++){
ab.add(a[i]);
}
}
else{
ab.add(a[i]);
}
}
return ab;
} */
/*int check[];
int tree[];
static void build( int []arr)
{
// insert leaf nodes in tree
for (int i = 0; i < n; i++)
tree[n + i] = arr[i];
// build the tree by calculating
// parents
for (int i = n - 1; i > 0; --i){
int ans= Math.min(tree[i << 1],
tree[i << 1 | 1]);
int ans1=Math.max((tree[i << 1],
tree[i << 1 | 1]));
if(ans==0)
}
}*/
/*static void ab(long n)
{
// Note that this loop runs till square root
for (long i=1; i<=Math.sqrt(n); i++)
{
if(i==1)
{
p.add(n/i);
continue;
}
if (n%i==0)
{
// If divisors are equal, print only one
if (n/i == i)
p.add(i);
else // Otherwise print both
{
p.add(i);
p.add(n/i);
}
}
}
}*/
void main() {
// int g=sc.nextInt();
// int mod=1000000007;
// sc.nextLine();
// for(int w=0;w<g;w++){
int n=sc.nextInt();
int a[]= new int[n];
int b[]= new int[n];
for(int i=0;i<n;i++)
a[i]=sc.nextInt();
for(int i=0;i<n;i++)
b[i]=sc.nextInt();
Integer diff[] = new Integer[n];
for(int i=0;i<n;i++)
diff[i]=a[i]-b[i];
Arrays.sort(diff);
// for(int i=0;i<n;i++)
// print(diff[i]+" ");
//println("");
int l=0;
int r=n-1;
long sum=0;
while(l<=r){
//println(diff[l]+" "+diff[r]);
if(diff[r]>(-1*diff[l])){
sum+=r-l;
r--;}
else{
l++;
}
//println(sum);
}
//println(r);
//sum+=(n-1-r);
println(sum);
}
}
| java |
1316 | E | E. Team Buildingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice; the president of club FCB, wants to build a team for the new volleyball tournament. The team should consist of pp players playing in pp different positions. She also recognizes the importance of audience support, so she wants to select kk people as part of the audience.There are nn people in Byteland. Alice needs to select exactly pp players, one for each position, and exactly kk members of the audience from this pool of nn people. Her ultimate goal is to maximize the total strength of the club.The ii-th of the nn persons has an integer aiai associated with him — the strength he adds to the club if he is selected as a member of the audience.For each person ii and for each position jj, Alice knows si,jsi,j — the strength added by the ii-th person to the club if he is selected to play in the jj-th position.Each person can be selected at most once as a player or a member of the audience. You have to choose exactly one player for each position.Since Alice is busy, she needs you to help her find the maximum possible strength of the club that can be achieved by an optimal choice of players and the audience.InputThe first line contains 33 integers n,p,kn,p,k (2≤n≤105,1≤p≤7,1≤k,p+k≤n2≤n≤105,1≤p≤7,1≤k,p+k≤n).The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤1091≤ai≤109).The ii-th of the next nn lines contains pp integers si,1,si,2,…,si,psi,1,si,2,…,si,p. (1≤si,j≤1091≤si,j≤109)OutputPrint a single integer resres — the maximum possible strength of the club.ExamplesInputCopy4 1 2
1 16 10 3
18
19
13
15
OutputCopy44
InputCopy6 2 3
78 93 9 17 13 78
80 97
30 52
26 17
56 68
60 36
84 55
OutputCopy377
InputCopy3 2 1
500 498 564
100002 3
422332 2
232323 1
OutputCopy422899
NoteIn the first sample; we can select person 11 to play in the 11-st position and persons 22 and 33 as audience members. Then the total strength of the club will be equal to a2+a3+s1,1a2+a3+s1,1. | [
"bitmasks",
"dp",
"greedy",
"sortings"
] | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Objects;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.util.Collections;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
ETeamBuilding solver = new ETeamBuilding();
solver.solve(1, in, out);
out.close();
}
static class ETeamBuilding {
int n;
int p;
int k;
int[] arr;
int[][] s;
long[][] dp;
ArrayList<Pair> list;
long[] psum;
public void solve(int testNumber, InputReader in, OutputWriter out) {
n = in.nextInt();
p = in.nextInt();
k = in.nextInt();
arr = in.nextIntArray(n);
s = in.nextIntMatrix(n, p);
dp = new long[n][1 << p];
list = new ArrayList<>();
for (int i = 0; i < n; i++) {
int a = arr[i];
list.add(new Pair(a, i));
}
Collections.sort(list, Collections.reverseOrder());
psum = new long[n];
psum[0] = list.get(0).a;
for (int i = 1; i < n; i++) {
psum[i] = psum[i - 1] + list.get(i).a;
}
for (long[] r : dp) Arrays.fill(r, -1);
out.println(rec(0, 0));
// for(long[] r:dp) out.println(r);
}
long rec(int i, int mask) {
if (i >= n) return 0;
if (dp[i][mask] != -1) return dp[i][mask];
// if(mask==(1<<p)-1){
// long ans=0;
// if(i+1-Integer.bitCount(mask)<=k){
// int rem= k- (i+1- Integer.bitCount(mask))+1;
// ans= psum[i+rem-1]-psum[i-1];
// }
// return dp[i][mask]=ans;
// }
long ans = 0;
if (i + 1 - Integer.bitCount(mask) <= k) {
ans = Math.max(ans, rec(i + 1, mask) + list.get(i).a);
} else {
ans = Math.max(ans, rec(i + 1, mask));
}
for (int j = 0; j < p; j++) {
if (((1 << j) & mask) != 0) continue;
ans = Math.max(ans, s[list.get(i).b][j] + rec(i + 1, mask | (1 << j)));
}
return dp[i][mask] = ans;
}
class Pair implements Comparable<Pair> {
int a;
int b;
Pair(int a, int b) {
this.a = a;
this.b = b;
}
public int hashCode() {
return Objects.hash(a, b);
}
public boolean equals(Object obj) {
Pair that = (Pair) obj;
return a == that.a && b == that.b;
}
public String toString() {
return "[" + a + ", " + b + "]";
}
public int compareTo(Pair v) {
return a - v.a;
}
}
}
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());
}
public int[][] nextIntMatrix(int rows, int cols) {
int[][] matrix = new int[rows][cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
matrix[i][j] = nextInt();
return matrix;
}
}
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 |
1290 | B | B. Irreducible Anagramstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call two strings ss and tt anagrams of each other if it is possible to rearrange symbols in the string ss to get a string, equal to tt.Let's consider two strings ss and tt which are anagrams of each other. We say that tt is a reducible anagram of ss if there exists an integer k≥2k≥2 and 2k2k non-empty strings s1,t1,s2,t2,…,sk,tks1,t1,s2,t2,…,sk,tk that satisfy the following conditions: If we write the strings s1,s2,…,sks1,s2,…,sk in order, the resulting string will be equal to ss; If we write the strings t1,t2,…,tkt1,t2,…,tk in order, the resulting string will be equal to tt; For all integers ii between 11 and kk inclusive, sisi and titi are anagrams of each other. If such strings don't exist, then tt is said to be an irreducible anagram of ss. Note that these notions are only defined when ss and tt are anagrams of each other.For example, consider the string s=s= "gamegame". Then the string t=t= "megamage" is a reducible anagram of ss, we may choose for example s1=s1= "game", s2=s2= "gam", s3=s3= "e" and t1=t1= "mega", t2=t2= "mag", t3=t3= "e": On the other hand, we can prove that t=t= "memegaga" is an irreducible anagram of ss.You will be given a string ss and qq queries, represented by two integers 1≤l≤r≤|s|1≤l≤r≤|s| (where |s||s| is equal to the length of the string ss). For each query, you should find if the substring of ss formed by characters from the ll-th to the rr-th has at least one irreducible anagram.InputThe first line contains a string ss, consisting of lowercase English characters (1≤|s|≤2⋅1051≤|s|≤2⋅105).The second line contains a single integer qq (1≤q≤1051≤q≤105) — the number of queries.Each of the following qq lines contain two integers ll and rr (1≤l≤r≤|s|1≤l≤r≤|s|), representing a query for the substring of ss formed by characters from the ll-th to the rr-th.OutputFor each query, print a single line containing "Yes" (without quotes) if the corresponding substring has at least one irreducible anagram, and a single line containing "No" (without quotes) otherwise.ExamplesInputCopyaaaaa
3
1 1
2 4
5 5
OutputCopyYes
No
Yes
InputCopyaabbbbbbc
6
1 2
2 4
2 2
1 9
5 7
3 5
OutputCopyNo
Yes
Yes
Yes
No
No
NoteIn the first sample; in the first and third queries; the substring is "a"; which has itself as an irreducible anagram since two or more non-empty strings cannot be put together to obtain "a". On the other hand; in the second query, the substring is "aaa", which has no irreducible anagrams: its only anagram is itself, and we may choose s1=s1= "a", s2=s2= "aa", t1=t1= "a", t2=t2= "aa" to show that it is a reducible anagram.In the second query of the second sample, the substring is "abb", which has, for example, "bba" as an irreducible anagram. | [
"binary search",
"constructive algorithms",
"data structures",
"strings",
"two pointers"
] | import java.io.*;
import java.util.*;
/*
*/
public class A {
static FastReader sc=null;
public static void main(String[] args) {
sc=new FastReader();
PrintWriter out=new PrintWriter(System.out);
char line[]=sc.next().toCharArray();
int n=line.length;
int q=sc.nextInt();
int pre[][]=new int[n][26];
pre[0][line[0]-'a']=1;
for(int i=1;i<n;i++)
for(int j=0;j<26;j++)pre[i][j]=pre[i-1][j]+(line[i]==(char)(j+'a')?1:0);
//for(Pair e:seg)System.out.println(e.l+" "+e.r);
while(q-->0) {
int l=sc.nextInt()-1,r=sc.nextInt()-1;
int count=0;
for(int i=0;i<26;i++)if(pre[r][i]!=pre[l][i])count++;
if(line[l]!=line[r] || l==r || count>2)
out.println("Yes");
else
out.println("No");
}
out.close();
}
static int[] ruffleSort(int a[]) {
ArrayList<Integer> al=new ArrayList<>();
for(int i:a)al.add(i);
Collections.sort(al);
for(int i=0;i<a.length;i++)a[i]=al.get(i);
return a;
}
static void print(int a[]) {
for(int e:a) {
System.out.print(e+" ");
}
System.out.println();
}
static class FastReader{
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());
}
long nextLong() {
return Long.parseLong(next());
}
int[] readArray(int n) {
int a[]=new int[n];
for(int i=0;i<n;i++)a[i]=sc.nextInt();
return a;
}
}
}
| 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.nio.file.FileStore;
import java.util.*;
public class zia
{
static boolean prime[] = new boolean[25001];
static void ruffleSort(int[] a) {
int n=a.length;
Random random = new Random();
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);
}
public static int Lcm(int a,int b)
{ int max=Math.max(a,b);
for(int i=1;;i++)
{
if((max*i)%a==0&&(max*i)%b==0)
return (max*i);
}
}
static void sieve(int n,boolean prime[])
{
// boolean 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] == true) {
for (int i = p * p; i <= n; i =i+ p)
prime[i] = false;
}
}
}
// public static String run(int ar[],int n)
// {
// }
public static long lcm(long a,long b)
{
long max=Math.max(a, b);
long min=Math.min(a, b);
for(int i=1;;i++)
{
if((max*i)%min==0)
return max;
}
}
public static long calculate(long a,long b,long x,long y,long n)
{
if(a-x>=n)
{
a-=n;
}
else
{
b=b-(n-(a-x));
a=x;
if(b<y)
b=y;
}
return a*b;
}
public static int upperbound(int s,int e, long ar[],long x)
{
int res=-1;
while(s<=e)
{ int mid=((s-e)/2)+e;
if(ar[mid]>x)
{e=mid-1;res=mid;}
else if(ar[mid]<x)
{s=mid+1;}
else
{e=mid-1;res=mid;
if(mid>0&&ar[mid]==ar[mid-1])
e=mid-1;
else
break;
}
}
return res;
}
public static long lowerbound(int s,int e, long ar[],long x)
{
long res=-1;
while(s<=e)
{ int mid=((s-e)/2)+e;
if(ar[mid]>x)
{e=mid-1;}
else if(ar[mid]<x)
{s=mid+1;res=mid;}
else
{res=mid;
if(mid+1<ar.length&&ar[mid]==ar[mid+1])
s=mid+1;
else
break;}
}
return res;
}
static long modulo=1000000007;
public static long power(long a, long b)
{
if(b==0) return 1;
long temp=power(a,b/2)%modulo;
if((b&1)==0)
return (temp*temp)%modulo;
else
return (((temp*temp)%modulo)*a)%modulo;
}
public static long powerwithoutmod(long a, long b)
{
if(b==0) return 1;
long temp=power(a,b/2);
if((b&1)==0)
return (temp*temp);
else
return ((temp*temp)*a);
}
public static double log2(long a)
{ double d=Math.log(a)/Math.log(2);
return d;
}
public static int log10(long a)
{ double d=Math.log(a)/Math.log(10);
return (int)d;
}
public static int find(int ar[],int x)
{
int count=0;
for(int i=0;i<ar.length;i+=2)
{
if((ar[i]&1)!=x)
count++;
}
return count;
}
public static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
public static long frogK(int index,long height[],long output[],int k)
{
if(index==1)
return 0;
if(output[index]==0)
{
long MinEnergy=Long.MAX_VALUE;
for(int j=1;j<=k&&index-j>=1;j++)
MinEnergy=Math.min(MinEnergy,frogK(index-j, height, output, k)+Math.abs(height[index]-height[index-j]));
output[index]=MinEnergy;
}
return output[index];
}
public static void tree(int s,int e,int ar[],int c)
{
if(s<=e)
{
int max=s;
for(int i=s;i<=e;i++)
if(ar[i]>ar[max])
max=i;
ar[max]=c++;
tree(s,max-1,ar,c);
tree(max+1,e,ar,c);
}
}
public static long solve(int s,int e,int a[],int ai)
{
int mid=0;
while(s<=e)
{
mid=(s+e)/2;
if(ai+a[mid]>0)
e=mid-1;
else if(ai+a[mid]<=0)
s=mid+1;
}
return s;
}
public static boolean isValid(int hour,int minute,int h,int m)
{
int ar[]={0,1,5,-1,-1,2,-1,-1,8,-1};
if(ar[minute%10]==-1||ar[minute/10]==-1 ||ar[hour%10]==-1||ar[hour/10]==-1)
return false;
int mirrorHour=ar[minute%10]*10+ar[minute/10];
int mirrorMinute=ar[hour%10]*10+ar[hour/10];
if(mirrorMinute>=m||mirrorHour>=h)
return false;
return true;
}
public static void main(String[] args) throws Exception
{
FastIO sc = new FastIO();
//sc.println();
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx CODE xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
// int test=sc.nextInt();
// // double c=Math.log(10);
// boolean prime[]=new boolean[1000000001];
// sieve(1000000000, prime);
// while(test-->0)
// {
int n=sc.nextInt();
int a[]=new int[n];
int b[]=new int[n];
for(int i=0;i<n;i++)
a[i]=sc.nextInt();
for(int i=0;i<n;i++)
{
b[i]=sc.nextInt();
a[i]-=b[i];
}
ruffleSort(a);
long result=0;
for(int i=0;i<n-1;i++)
{
if(a[i]>0)
result+=n-1-i;
else
{
result+=(n-solve(i+1,n-1,a, a[i]));
}
}
sc.println(result);
// }
// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx CODE xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
sc.close();
}
}
class pair implements Comparable<pair>{
long a;
long b;
pair(long a,long b)
{this.a=a;
this.b=b;
}
public int compareTo(pair p)
{return (int)(-this.a+p.a);}
}
class triplet implements Comparable<triplet>{
int first,second,third;
triplet(int first,int second,int third)
{this.first=first;
this.second=second;
this.third=third;
}
public int compareTo(triplet p)
{return this.third-p.third;}
}
// class triplet
// {
// int x1,x2,i;
// triplet(int a,int b,int c)
// {x1=a;x2=b;i=c;}
// }
class FastIO extends PrintWriter {
private InputStream stream;
private byte[] buf = new byte[1<<16];
private int curChar, numChars;
// standard input
public FastIO() { this(System.in,System.out); }
public FastIO(InputStream i, OutputStream o) {
super(o);
stream = i;
}
// file input
public FastIO(String i, String o) throws IOException {
super(new FileWriter(o));
stream = new FileInputStream(i);
}
// throws InputMismatchException() if previously detected end of file
private int nextByte() {
if (numChars == -1) throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars == -1) return -1; // end of file
}
return buf[curChar++];
}
public String nextLine() {
int c; do { c = nextByte(); } while (c <= '\n');
StringBuilder res = new StringBuilder();
do { res.appendCodePoint(c); c = nextByte(); } while (c > '\n');
return res.toString();
}
public String next() {
int c; do { c = nextByte(); } while (c <= ' ');
StringBuilder res = new StringBuilder();
do { res.appendCodePoint(c); c = nextByte(); } while (c > ' ');
return res.toString();
}
public int nextInt() {
int c; do { c = nextByte(); } while (c <= ' ');
int sgn = 1; if (c == '-') { sgn = -1; c = nextByte(); }
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = 10*res+c-'0';
c = nextByte();
} while (c > ' ');
return res * sgn;
}
public long nextLong() {
int c; do { c = nextByte(); } while (c <= ' ');
long sgn = 1; if (c == '-') { sgn = -1; c = nextByte(); }
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = 10*res+c-'0';
c = nextByte();
} while (c > ' ');
return res * sgn;
}
public double nextDouble() { return Double.parseDouble(next()); }
}
| java |
1141 | B | B. Maximal Continuous Resttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEach day in Berland consists of nn hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence a1,a2,…,ana1,a2,…,an (each aiai is either 00 or 11), where ai=0ai=0 if Polycarp works during the ii-th hour of the day and ai=1ai=1 if Polycarp rests during the ii-th hour of the day.Days go one after another endlessly and Polycarp uses the same schedule for each day.What is the maximal number of continuous hours during which Polycarp rests? It is guaranteed that there is at least one working hour in a day.InputThe first line contains nn (1≤n≤2⋅1051≤n≤2⋅105) — number of hours per day.The second line contains nn integer numbers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where ai=0ai=0 if the ii-th hour in a day is working and ai=1ai=1 if the ii-th hour is resting. It is guaranteed that ai=0ai=0 for at least one ii.OutputPrint the maximal number of continuous hours during which Polycarp rests. Remember that you should consider that days go one after another endlessly and Polycarp uses the same schedule for each day.ExamplesInputCopy5
1 0 1 0 1
OutputCopy2
InputCopy6
0 1 0 1 1 0
OutputCopy2
InputCopy7
1 0 1 1 1 0 1
OutputCopy3
InputCopy3
0 0 0
OutputCopy0
NoteIn the first example; the maximal rest starts in last hour and goes to the first hour of the next day.In the second example; Polycarp has maximal rest from the 44-th to the 55-th hour.In the third example, Polycarp has maximal rest from the 33-rd to the 55-th hour.In the fourth example, Polycarp has no rest at all. | [
"implementation"
] | // Online Java Compiler
// Use this editor to write, compile and run your Java code online
import java.util.*;
public class HelloWorld {
static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
int n = scan.nextInt();
int[] arr = new int[n];
for(int i =0;i<n;i++){
arr[i]=scan.nextInt();
}
int currOne = 0,maxOne = 0;
for(int i =0;i<2 *arr.length;i++){
if(arr[i % n]==1){
currOne +=1;
maxOne = Math.max(maxOne,currOne);
}
else{
currOne = 0;
}
}
System.out.println(maxOne);
}
} | 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.*;
public class Main {
public static void main(String[] args) {
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
PrintWriter o = new PrintWriter(System.out);
var s = inp(f,false);
var pq = new PriorityQueue<Integer>(Collections.reverseOrder());
int n = s.length();
for(int i=0;i<n;++i){
if(s.charAt(i)==')'){
pq.add(i);
}
}
var ans = new ArrayList<Integer>();
for(int i=0;i<n;++i){
if(s.charAt(i)=='('){
if(pq.size()>0&&pq.peek()>i){
ans.add(i+1);
ans.add(pq.poll()+1);
}
}
}
Collections.sort(ans);
if(ans.size()>0){
out(o,"1\n"+ans.size()+"\n",true);
for(var i:ans){
out(o,i+" ",true);
}
out(o,"\n",true);
}else {
out(o,"0\n",true);
}
o.close();
}
public static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
public static long lcm(long a, long b) {
long gcd = gcd(a, b);
return (a * b) / gcd;
}
public static int[] inp(BufferedReader f, int n) {
try {
StringTokenizer st = new StringTokenizer(f.readLine());
int[] out = new int[n];
for (int i = 0; i < n; ++i)
out[i] = Integer.parseInt(st.nextToken());
return out;
} catch (Exception e) {
return new int[] { 0, 0 };
}
}
public static String inp(BufferedReader f, boolean b) {
try {
return f.readLine();
} catch (Exception e) {
return "";
}
}
public static void out(PrintWriter out, String s, boolean chk) {
if (!chk)
out.println(s);
else
out.print(s);
}
public static void nl() {
System.out.print("\n");
}
public static void out(PrintWriter out, int[] a) {
for (int i = 0; i < a.length; ++i)
out.print(a[i] + " ");
out.print("\n");
}
public static void out(PrintWriter out, long[] a) {
for (int i = 0; i < a.length; ++i)
out.print(a[i] + " ");
out.print("\n");
}
public static void out(PrintWriter out, int n) {
out.println(n);
}
public static void out(PrintWriter out, long n) {
out.println(n);
}
public static void sort(int[] a) {
int n = a.length;
ArrayList<Integer> b = new ArrayList<Integer>();
for (int i : a)
b.add(i);
Collections.sort(b);
for (int i = 0; i < n; ++i) {
a[i] = b.get(i);
}
}
public static int lower_bound(int[] a, int n, int tar) {
int k = -1;
for (int b = n / 2; b >= 1; b /= 2)
while (k + b < n && a[k + b] < tar)
k += b;
return k + 1;
}
public static int upper_bound(ArrayList<Integer> a, int n, int tar) {
int k = 0;
for (int b = n / 2; b >= 1; b /= 2)
while (k + b < n && a.get(k + b) <= tar)
k += b;
return k;
}
static class Pair {
int a;
int b;
Pair(int a, int b) {
this.a = a;
this.b = b;
}
public int a() {
return b;
}
public int b() {
return a;
}
public void b(int nv) {
b = nv;
}
public void a(int nk) {
a = nk;
}
}
} | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.