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 |
---|---|---|---|---|---|
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.io.*;
import java.util.Arrays;
public class Cv {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
int numberSets = Integer.parseInt(br.readLine());
for (int nos = 0; nos < numberSets; nos++) {
int [] data = Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
if (data[0]%data[1] == 0) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
}
| java |
1303 | A | A. Erasing Zeroestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. Each character is either 0 or 1.You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met.You may erase some (possibly none) 0's from the string. What is the minimum number of 0's that you have to erase?InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Then tt lines follow, each representing a test case. Each line contains one string ss (1≤|s|≤1001≤|s|≤100); each character of ss is either 0 or 1.OutputPrint tt integers, where the ii-th integer is the answer to the ii-th testcase (the minimum number of 0's that you have to erase from ss).ExampleInputCopy3
010011
0
1111000
OutputCopy2
0
0
NoteIn the first test case you have to delete the third and forth symbols from string 010011 (it turns into 0111). | [
"implementation",
"strings"
] | import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0) {
String s = sc.next();
int a = 0, b = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '1') {
a = i;
break;
}
}
for (int i = s.length() - 1; i > 0; i--) {
if (s.charAt(i) == '1') {
b = i;
break;
}
}
int count = 0;
for (int i = a; i < b; i++) {
if (s.charAt(i) == '0') {
count++;
}
}
System.out.println(count);
}
}
}
| java |
1294 | F | F. Three Paths on a Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an unweighted tree with nn vertices. Recall that a tree is a connected undirected graph without cycles.Your task is to choose three distinct vertices a,b,ca,b,c on this tree such that the number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc is the maximum possible. See the notes section for a better understanding.The simple path is the path that visits each vertex at most once.InputThe first line contains one integer number nn (3≤n≤2⋅1053≤n≤2⋅105) — the number of vertices in the tree. Next n−1n−1 lines describe the edges of the tree in form ai,biai,bi (1≤ai1≤ai, bi≤nbi≤n, ai≠biai≠bi). It is guaranteed that given graph is a tree.OutputIn the first line print one integer resres — the maximum number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc.In the second line print three integers a,b,ca,b,c such that 1≤a,b,c≤n1≤a,b,c≤n and a≠,b≠c,a≠ca≠,b≠c,a≠c.If there are several answers, you can print any.ExampleInputCopy8
1 2
2 3
3 4
4 5
4 6
3 7
3 8
OutputCopy5
1 8 6
NoteThe picture corresponding to the first example (and another one correct answer):If you choose vertices 1,5,61,5,6 then the path between 11 and 55 consists of edges (1,2),(2,3),(3,4),(4,5)(1,2),(2,3),(3,4),(4,5), the path between 11 and 66 consists of edges (1,2),(2,3),(3,4),(4,6)(1,2),(2,3),(3,4),(4,6) and the path between 55 and 66 consists of edges (4,5),(4,6)(4,5),(4,6). The union of these paths is (1,2),(2,3),(3,4),(4,5),(4,6)(1,2),(2,3),(3,4),(4,5),(4,6) so the answer is 55. It can be shown that there is no better answer. | [
"dfs and similar",
"dp",
"greedy",
"trees"
] | import java.io.*;
import java.util.*;
/*
*/
public class A {
static FastReader sc=null;
static int from[];
public static void main(String[] args) {
sc=new FastReader();
int n=sc.nextInt();
Node nodes[]=new Node[n];
for(int i=0;i<n;i++)nodes[i]=new Node(i);
for(int i=0;i+1<n;i++) {
int v=sc.nextInt()-1,w=sc.nextInt()-1;
nodes[v].adj.add(nodes[w]);
nodes[w].adj.add(nodes[v]);
}
from=new int[n];
Node a=bfs(nodes,nodes[0]);
Node b=bfs(nodes,a);
long ans=b.dist;
ArrayList<Node> mul=new ArrayList<>();
mul.add(b);
Node temp=b;
while(b!=a) {
b=nodes[from[b.id]];
mul.add(b);
}
Node c=bfs(nodes,mul,a,b);
ans+=c.dist;
System.out.println(ans);
System.out.println((a.id+1)+" "+(temp.id+1)+" "+(c.id+1));
}
static class Node{
int id,dist;
ArrayList<Node> adj=new ArrayList<>();
Node(int id){
this.id=id;
}
}
static Node bfs(Node nodes[],Node s) {
ArrayDeque<Node> bfs=new ArrayDeque<>();
for(Node nn:nodes)nn.dist=-1;
s.dist=0;
bfs.add(s);
Node far=null;
while(!bfs.isEmpty()) {
Node q=bfs.remove();
far=q;
for(Node nn:q.adj) {
if(nn.dist==-1) {
from[nn.id]=q.id;
nn.dist=q.dist+1;
bfs.add(nn);
}
}
}
return far;
}
static Node bfs(Node nodes[],ArrayList<Node> mul,Node a,Node b) {
ArrayDeque<Node> bfs=new ArrayDeque<>();
for(Node nn:nodes)nn.dist=-1;
for(Node nn:mul) {
bfs.add(nn);
nn.dist=0;
}
Node far=null;
while(!bfs.isEmpty()) {
Node q=bfs.remove();
if(q!=a && q!=b)far=q;
for(Node nn:q.adj) {
if(nn.dist==-1) {
from[nn.id]=q.id;
nn.dist=q.dist+1;
bfs.add(nn);
}
}
}
return far;
}
static int[] reverse(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 gcd(int a,int 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(long a[]) {
for(long 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 |
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.lang.*;
import java.util.*;
import java.io.*;
public class practice{
static int components;
private static int find(int[] parent, int x){
if (!(x>=0 && x<parent.length))
return -1;
if (parent[x] < 0){
return x;
}
return (parent[x] = find(parent, parent[x]));
}
private static void union(int[] parent, int x1, int x2){
int r1 = find(parent, x1), r2 = find(parent, x2);
if (r1 == r2)
return;
components--;
if (parent[r1] <= parent[r2]){
parent[r1] += parent[r2];
parent[r2] = r1;
}else{
parent[r2] += parent[r1];
parent[r1] = r2;
}
}
private static void union1(int[] parent, int[] cost, int x1, int x2){
int r1 = find(parent, x1), r2 = find(parent, x2);
if (r1 == r2)
return;
if (cost[r1] >= cost[r2]){
parent[r1] += parent[r2];
parent[r2] = r1;
}else{
parent[r2] += parent[r1];
parent[r1] = r2;
}
}
private static boolean check(int[] parent, int x1, int x2){
int r1 = find(parent, x1), r2 = find(parent, x2);
if (r1 == r2){
return false;
}
return true;
}
private static int dfs(List<List<Integer>> adj, int idx){
if (adj.get(idx).size() == 0){
return 1;
}
List<Integer> nei = adj.get(idx);
int count = 0;
for (int ne : nei){
count += dfs(adj, ne);
}
return count;
}
public static class Pair{
private int idx;
private int sum;
Pair(int idx, int sum){
this.idx = idx;
this.sum = sum;
}
}
private static int rec(int v, int[] dp){
if (v == 0){
return 0;
}
if (dp[v] != -1){
return dp[v];
}
return (dp[v]=1+Math.min(rec((v+1)%32768, dp), rec((2*v)%32768, dp)));
}
static class Node {
int idx, level;
public Node(int v, int d) {
this.idx = v;
this.level = d;
}
}
static boolean vis[] = new boolean[100005];
public static void main(String args[]) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//StringTokenizer st = new StringTokenizer(br.readLine());
int t = Integer.parseInt(br.readLine().trim());
while (t-->0){
String[] tmp = br.readLine().trim().split(" ");
int n = Integer.parseInt(tmp[0]);
int m = Integer.parseInt(tmp[1]);
tmp = br.readLine().trim().split(" ");
int[] arr = new int[n+1];
for (int i=0 ; i<n ; i++){
arr[i] = Integer.parseInt(tmp[i]);
}
arr[n] = Integer.MAX_VALUE;
int[] parents = new int[n];
Arrays.fill(parents, -1);
tmp = br.readLine().trim().split(" ");
int[] markers = new int[m];
for (int i=0 ; i<m ; i++){
markers[i] = Integer.parseInt(tmp[i])-1;
}
Arrays.sort(markers);
int[][] minmax = new int[n][2];
for (int i=0 ; i<n ; i++){
minmax[i][0] = arr[i];
minmax[i][1] = arr[i];
}
for (int i=0 ; i<m ; i++){
int u = markers[i];
int v = (n<=u+1)?-1:u+1;
if (v == -1)
continue;
minmax[v][0] = Math.min(minmax[v-1][0], Math.min(arr[u], arr[v]));
minmax[v][1] = Math.max(minmax[v-1][1], Math.max(arr[u], arr[v]));
union(parents, u, v);
}
for (int i=0 ; i<n ; i++){
find(parents, i);
}
/*System.out.println();
for (int i=0 ; i<n ; i++){
System.out.print(parents[i]+" ");
}
System.out.println();
for (int i=0 ; i<n ; i++){
System.out.println(i+" "+minmax[i][0]+" "+minmax[i][1]);
}*/
boolean ans = true;
int i=0;
while (i<n){
if (i==0 || parents[i]>=0){
i++;
continue;
}
int parent = find(parents, i-1);
if (parents[i] < -1){
int min = minmax[i-parents[i]-1][0];
if (minmax[i-1][1]>min){
ans = false;
break;
}
i = i-parents[i];
}else if (parents[i] == -1){
int max = minmax[i-1][1];
//System.out.println(max);
if (arr[i] < max){
ans = false;
break;
}
i++;
}
}
if (ans){
System.out.println("YES");
}else{
System.out.println("NO");
}
}
}
} | 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.util.*;
import java.lang.*;
import java.io.*;
public class Solution {
public static void main(String[] args) throws java.lang.Exception {
out = new PrintWriter(new BufferedOutputStream(System.out));
sc = new FastReader();
int test = sc.nextInt();
for (int t = 0; t < test; t++) {
solve();
}
out.close();
}
private static void solve() {
int n = sc.nextInt();
char[] arr = sc.next().toCharArray();
int[] res = new int[n];
int num = n;
int last = 0;
for (int i = 0; i < n; i++) {
if (i == n - 1 || arr[i] == '>') {
for (int j = i; j >= last; j--) {
res[j] = num;
num--;
}
last = i + 1;
}
}
display(res, n);
num = 1;
last = 0;
for (int i = 0; i < n; i++) {
if (i == n - 1 || arr[i] == '<') {
for (int j = i; j >= last; j--) {
res[j] = num;
num++;
}
last = i + 1;
}
}
display(res, n);
}
private static void display(int[] res, int n) {
for (int i = 0; i < n; i++) {
out.print(res[i] + " ");
}
out.println();
}
public static FastReader sc;
public static PrintWriter out;
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
} | java |
1313 | B | B. Different Rulestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNikolay has only recently started in competitive programming; but already qualified to the finals of one prestigious olympiad. There going to be nn participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules.Suppose in the first round participant A took xx-th place and in the second round — yy-th place. Then the total score of the participant A is sum x+yx+y. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every ii from 11 to nn exactly one participant took ii-th place in first round and exactly one participant took ii-th place in second round.Right after the end of the Olympiad, Nikolay was informed that he got xx-th place in first round and yy-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question.InputThe first line contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases to solve.Each of the following tt lines contains integers nn, xx, yy (1≤n≤1091≤n≤109, 1≤x,y≤n1≤x,y≤n) — the number of participants in the olympiad, the place that Nikolay took in the first round and the place that Nikolay took in the second round.OutputPrint two integers — the minimum and maximum possible overall place Nikolay could take.ExamplesInputCopy15 1 3OutputCopy1 3InputCopy16 3 4OutputCopy2 6NoteExplanation for the first example:Suppose there were 5 participants A-E. Let's denote Nikolay as A. The the most favorable results for Nikolay could look as follows: However, the results of the Olympiad could also look like this: In the first case Nikolay would have taken first place, and in the second — third place. | [
"constructive algorithms",
"greedy",
"implementation",
"math"
] | import java.util.*;
import java.io.*;
public class File {
public static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
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());
}
}
public static void main(String[] args) {
FastScanner sc = new FastScanner();
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
int T = sc.nextInt();
for (int t = 1; t <= T; t++) {
long n = sc.nextLong();
long x = sc.nextLong();
long y = sc.nextLong();
// Min = n - #lower score
// Minimum overall place
long lowerCount = 0L;
// x-1 participants got a better score
// Pair those with y_i such that
// x_i + y_i > total
// x-1 pairs with y+2
// x-2 pairs with y+3...
long lowerX = x - 1;
long greaterY = Math.max(n - y - 1, 0);
long pairs1 = Math.min(lowerX, greaterY);
long greatestY = Math.min(n + 1, y + pairs1 + 1);
// y-1 participants got a better score
// Pair those with x_i such that
// y-1 pairs with x+2
// y-2 pairs with x+3...
long lowerY = y - 1;
long greaterX = Math.max(n - x - 1, 0);
long pairs2 = Math.min(lowerY, greaterX);
long greatestX = Math.min(n + 1, x + pairs2 + 1);
// Then pair all remaining score x_i > x AND y_i > y with each other.
long pairs3 = Math.max(0, Math.min(n - greatestY + 1, n - greatestX + 1));
lowerCount = pairs1 + pairs2 + pairs3;
long min = n - lowerCount;
// Max = #equal score + #lower score
// Maximum overall place
long equalCount = 0L;
lowerCount = 0L;
// x-1 got better score
// Pair those with y_i
// x_i + y_i = total
// x-1 pairs with y+1
// x-2 pairs with y+2...
long betterX = x - 1;
long worseY = n - y;
pairs1 = Math.min(betterX, worseY);
long smallestX = betterX - pairs1;
// y-1 got better y score
// Pair with x_i
// y-1 pairs with x+1
// y-2 pairs with x+2...
long betterY = y - 1;
long worseX = n - x;
pairs2 = Math.min(betterY, worseX);
long smallestY = betterY - pairs2;
// Then pair all remaining x_i, y_i where x_i < x AND y_i < y
pairs3 = Math.max(0, Math.min(smallestX, smallestY));
equalCount = pairs1 + pairs2;
lowerCount = pairs3;
long max = equalCount + lowerCount + 1; // Including self.
out.println(min + " " + max);
}
out.close();
}
}
| java |
1141 | F2 | F2. Same Sum Blocks (Hard)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],…,a[n].a[1],a[2],…,a[n]. A block is a sequence of contiguous (consecutive) elements a[l],a[l+1],…,a[r]a[l],a[l+1],…,a[r] (1≤l≤r≤n1≤l≤r≤n). Thus, a block is defined by a pair of indices (l,r)(l,r).Find a set of blocks (l1,r1),(l2,r2),…,(lk,rk)(l1,r1),(l2,r2),…,(lk,rk) such that: They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks (li,ri)(li,ri) and (lj,rj(lj,rj) where i≠ji≠j either ri<ljri<lj or rj<lirj<li. For each block the sum of its elements is the same. Formally, a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]=a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]= ⋯=⋯= a[lk]+a[lk+1]+⋯+a[rk].a[lk]+a[lk+1]+⋯+a[rk]. The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks (l′1,r′1),(l′2,r′2),…,(l′k′,r′k′)(l1′,r1′),(l2′,r2′),…,(lk′′,rk′′) satisfying the above two requirements with k′>kk′>k. The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks.InputThe first line contains integer nn (1≤n≤15001≤n≤1500) — the length of the given array. The second line contains the sequence of elements a[1],a[2],…,a[n]a[1],a[2],…,a[n] (−105≤ai≤105−105≤ai≤105).OutputIn the first line print the integer kk (1≤k≤n1≤k≤n). The following kk lines should contain blocks, one per line. In each line print a pair of indices li,rili,ri (1≤li≤ri≤n1≤li≤ri≤n) — the bounds of the ii-th block. You can print blocks in any order. If there are multiple answers, print any of them.ExamplesInputCopy7
4 1 2 2 1 5 3
OutputCopy3
7 7
2 3
4 5
InputCopy11
-5 -4 -3 -2 -1 0 1 2 3 4 5
OutputCopy2
3 4
1 1
InputCopy4
1 1 1 1
OutputCopy4
4 4
1 1
2 2
3 3
| [
"data structures",
"greedy"
] | /*
7
4 1 2 2 1 5 3
*/
import java.util.*;
import java.io.*;
public class Main{
public static int n;
public static int[] vals;
public static HashMap<Integer, ArrayList<Block>> sortedBlocks = new HashMap<Integer, ArrayList<Block>>(); //all blocks of a certain value, sorted from earliest to latest endpoint and then earliest to latest starting point
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
n = Integer.parseInt(br.readLine());
vals = new int[n];
StringTokenizer vs = new StringTokenizer(br.readLine());
for(int a = 0; a < n; a++) vals[a] = Integer.parseInt(vs.nextToken());
int[] pre = new int[n];
pre[0] = vals[0];
for(int b = 1; b < n; b++){
pre[b] = vals[b] + pre[b - 1];
}
for(int fi = 0; fi < n; fi++){
for(int si = fi; si < n; si++){
int v = pre[si];
if(fi > 0) v -= pre[fi-1];
if(!sortedBlocks.containsKey(v)) sortedBlocks.put(v, new ArrayList<Block>());
sortedBlocks.get(v).add(new Block(fi, si, v));
}
}
//System.out.println(sortedBlocks);
int lg = 0; //most blocks of a certain value
String best = "";
for(int value : sortedBlocks.keySet()){
Collections.sort(sortedBlocks.get(value));
int t = -1;
int sm = 0;
StringBuilder cr = new StringBuilder();
for(Block b : sortedBlocks.get(value)){ //given a set of ranges, what is the most ranges that you can use?
if(b.a > t){
t = b.b;
sm++;
cr.append((b.a + 1) + " " + (b.b + 1) + "\n");
}
}
if(sm > lg){
lg = sm;
best = cr.toString();
}
}
System.out.println(lg + "\n" + best.toString());
br.close();
}
}
class Block implements Comparable<Block>{
int a;
int b; //starting and ending indices
int val;
public Block(int ac, int bc, int v){
a = ac;
b = bc;
val = v;
}
public int compareTo(Block c){
if(c.b != b) return b - c.b;
if(c.a != a) return a - c.a;
return val - c.val;
}
public String toString(){
return a + " " + b;
}
} | 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"
] | import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import java.util.*;
import java.io.*;
import java.math.*;
public class C_Air_Conditioner {
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 = f.nextInt();
while(t-- > 0){
solve(f, out);
}
out.close();
}
public static void solve(FastReader f, PrintWriter out) {
int n = f.nextInt();
long start = f.nextLong();
ArrayList<Pair> arrli = new ArrayList<>();
arrli.add(new Pair(f.nextLong(), f.nextLong(), f.nextLong()));
boolean flag = true;
for(int i = 1; i < n; i++) {
long t = f.nextLong();
long lo = f.nextLong();
long hi = f.nextLong();
Pair last = arrli.get(arrli.size()-1);
if(t == last.t) {
last.lo = max(last.lo, lo);
last.hi = min(last.hi, hi);
if(last.hi < last.lo) {
flag = false;
}
} else {
arrli.add(new Pair(t, lo, hi));
}
}
if(!flag) {
out.println("NO");
return;
}
long lastHi = start;
long lastLo = start;
for(int i = 0; i < arrli.size(); i++) {
long delT = (i != 0) ? arrli.get(i).t-arrli.get(i-1).t : arrli.get(i).t;
long currHi = lastHi + delT;
long currLo = lastLo - delT;
if(currLo > arrli.get(i).hi || currHi < arrli.get(i).lo) {
out.println("NO");
return;
}
lastHi = min(currHi, arrli.get(i).hi);
lastLo = max(currLo, arrli.get(i).lo);
}
out.println("YES");
}
static class Pair {
long t;
long lo;
long hi;
public Pair(long t, long lo, long hi) {
this.t = t;
this.lo = lo;
this.hi = hi;
}
}
// 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 |
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"
] | /*
"Everything in the universe is balanced. Every disappointment
you face in life will be balanced by something good for you!
Keep going, never give up."
Just have Patience + 1...
*/
import java.util.*;
import java.lang.*;
import java.io.*;
public class Solution {
public static void main(String[] args) throws java.lang.Exception {
out = new PrintWriter(new BufferedOutputStream(System.out));
sc = new FastReader();
int test = 1;
for (int t = 0; t < test; t++) {
solve();
}
out.close();
}
private static void solve() {
int n = sc.nextInt();
int m = sc.nextInt();
int[][] arr = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
arr[i][j] = sc.nextInt() - 1;
}
}
long moves = 0;
for (int j = 0; j < m; j++) {
int[] matches = new int[n];
for (int i = 0; i < n; i++) {
if (arr[i][j] % m == j) {
int position = arr[i][j] / m;
if (position < n) {
int shiftTo = (i - position + n) % n;
matches[shiftTo]++;
}
}
}
int minRequired = n - matches[0];
for (int i = 1; i < n; i++) { // for each cyclic shift
minRequired = Math.min(minRequired, n - matches[i] + i);
}
moves += minRequired;
}
out.println(moves);
}
public static FastReader sc;
public static PrintWriter out;
static class FastReader
{
BufferedReader br;
StringTokenizer str;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (str == null || !str.hasMoreElements())
{
try
{
str = new StringTokenizer(br.readLine());
}
catch (IOException lastMonthOfVacation)
{
lastMonthOfVacation.printStackTrace();
}
}
return str.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException lastMonthOfVacation)
{
lastMonthOfVacation.printStackTrace();
}
return str;
}
}
}
| 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 ThreeStrings {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
sc.nextLine();
for(int i=0;i<t;i++)
{
int count=0;
String a=sc.nextLine();
String b=sc.nextLine();
String c=sc.nextLine();
/*if(a.equals(b))
{
System.out.println("YES");
continue;
}*/
for(int j=0;j<a.length();j++)
{
char ch1=a.charAt(j);
char ch2=c.charAt(j);
char ch3=b.charAt(j);
if(ch1==ch2)
{
b= swap(b,c,j);
count++;
}
else if(ch3==ch2)
{
a=swap(a,c,j);
count++;
}
else
continue;
}
if(a.equals(b)&&count==a.length())
System.out.println("YES");
else
System.out.println("NO");
}
}
private static String swap(String s1, String s2, int idx) {
char ch1=s2.charAt(idx);
char ch2=s1.charAt(idx);
s1=s1.substring(0,idx)+ch1+s1.substring(idx+1);
s2=s2.substring(0,idx)+ch2+s2.substring(idx+1);
return s1;
}
}
| 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 B {
public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
public static void main(String[] args) throws IOException {
readInput();
out.close();
}
static int n,x,y;
static int best() {
if (x + y < n+1) return 1;
// How many numbers can we make strictly bigger than x+y?
int opp = x+y-n;
return Integer.min(n, opp+1);
}
static int worst() {// I trust this.
if (x + y >= n+1) return n;
return (x+y-1);
}
public static void readInput() throws IOException {
// br = new BufferedReader(new FileReader(".in"));
// out = new PrintWriter(new FileWriter(".out"));
int t = Integer.parseInt(br.readLine());
while (t-->0) {
StringTokenizer st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
x = Integer.parseInt(st.nextToken());
y = Integer.parseInt(st.nextToken());
out.println(best() +" " + worst());
}
}
}
| 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;
int del = (grid[r][c] == 1) ? -1 : 1;
grid[r][c] = 1 - grid[r][c];
for(int dc = -1; dc <= 1; dc++) {
if(c+dc < 0 || c+dc >= n) continue;
if(grid[nextR][c+dc] == 1) {
blocked += del;
}
}
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 |
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 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 B_New_Year_and_Ascent_Sequence {
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();
ArrayList<Pair> arrli = new ArrayList<>();
long ascentCount = 0;
for(int i = 0; i < n; i++) {
int l = f.nextInt();
int max = 0;
int min = Integer.MAX_VALUE;
boolean ascent = false;
for(int j = 0; j < l; j++) {
int x = f.nextInt();
if(j > 0 && x > min) {
ascent = true;
}
max = max(max, x);
min = min(min, x);
}
if(ascent) {
ascentCount++;
} else {
arrli.add(new Pair(max, min));
}
}
Collections.sort(arrli, (p1, p2) -> {
return p1.max - p2.max;
});
long ans = 0;
for(int i = 0; i < arrli.size(); i++) {
ans += func(arrli, arrli.get(i).min);
}
ans += ascentCount*(ascentCount-1) + ascentCount + 2*ascentCount*(n-ascentCount);
out.println(ans);
}
static class Pair {
int max;
int min;
public Pair(int max, int min) {
this.max = max;
this.min = min;
}
}
public static int func(ArrayList<Pair> arrli, int min) {
int i = 0;
int j = arrli.size()-1;
int ind = -1;
while(j >= i) {
int mid = (i+j)/2;
if(arrli.get(mid).max > min) {
ind = mid;
j = mid-1;
} else {
i = mid+1;
}
}
return (ind == -1) ? 0 : arrli.size()-ind;
}
// 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 |
1300 | A | A. Non-zerotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas have an array aa of nn integers [a1,a2,…,ana1,a2,…,an]. In one step they can add 11 to any element of the array. Formally, in one step they can choose any integer index ii (1≤i≤n1≤i≤n) and do ai:=ai+1ai:=ai+1.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make a1+a2+a1+a2+ …… +an≠0+an≠0 and a1⋅a2⋅a1⋅a2⋅ …… ⋅an≠0⋅an≠0.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1031≤t≤103). The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1001≤n≤100) — the size of the array.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−100≤ai≤100−100≤ai≤100) — elements of the array .OutputFor each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.ExampleInputCopy4
3
2 -1 -1
4
-1 0 0 1
2
-1 2
3
0 -2 1
OutputCopy1
2
0
2
NoteIn the first test case; the sum is 00. If we add 11 to the first element, the array will be [3,−1,−1][3,−1,−1], the sum will be equal to 11 and the product will be equal to 33.In the second test case, both product and sum are 00. If we add 11 to the second and the third element, the array will be [−1,1,1,1][−1,1,1,1], the sum will be equal to 22 and the product will be equal to −1−1. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding 11 twice to the first element the array will be [2,−2,1][2,−2,1], the sum will be 11 and the product will be −4−4. | [
"implementation",
"math"
] | import java.util.Scanner;
public class CF1508{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int testCases = scan.nextInt();
while(testCases>0){
int arrayLength = scan.nextInt();
int totalSum = 0;
int numberOfZeroes = 0;
for(int i = 0; i<arrayLength; i++){
int num = scan.nextInt();
if(num == 0){
numberOfZeroes++;
}
totalSum += num;
}
if(numberOfZeroes==0){
if(totalSum==0){
System.out.println(1);
}else{
System.out.println(0);
}
}else{
if(totalSum + numberOfZeroes == 0){
System.out.println(numberOfZeroes+1);
}else{
System.out.println(numberOfZeroes);
}
}
testCases--;
}
}
} | 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"
] | import java.util.Scanner;
import java.util.HashSet;
import java.util.ArrayList;
public class Main {
static int[] c;
static HashSet<Integer>[] graph;
static int[] res;
static ArrayList<Integer> v;
static int[] allSubNodes;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
c = new int[n + 1];
int root = 0;
v = new ArrayList<>();
graph = new HashSet[n + 1];
for (int i = 1; i <= n; ++i)
graph[i] = new HashSet<Integer>();
allSubNodes = new int[n + 1];
for (int i = 1; i <= n; ++i) {
v.add(i);
int pi = sc.nextInt();
int ci = sc.nextInt();
if (pi == 0)
root = i;
else
graph[pi].add(i);
c[i] = ci;
}
getAllSubNodes(root);
for (int i = 1; i <= n; ++i) {
if (allSubNodes[i] < c[i]) {
System.out.println("NO");
System.exit(0);
}
}
System.out.println("YES");
res = new int[n + 1];
dfs(root);
for (int i = 1; i <= n; ++i)
System.out.print(res[i] + " ");
System.out.println();
}
public static void getAllSubNodes(int node) {
if (graph[node].size() == 0) {
allSubNodes[node] = 0;
return;
}
for (int subNode : graph[node]) {
getAllSubNodes(subNode);
allSubNodes[node] += allSubNodes[subNode] + 1;
}
}
public static void dfs(int node) {
res[node] = v.remove(c[node]);
for (int subNode : graph[node])
dfs(subNode);
}
} | 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"
] | /*
"Everything in the universe is balanced. Every disappointment
you face in life will be balanced by something good for you!
Keep going, never give up."
Just have Patience + 1...
*/
import java.util.*;
import java.lang.*;
import java.io.*;
public class Solution {
static class Node {
int distance;
int node;
Node (int distance, int node) {
this.distance = distance;
this.node = node;
}
}
static int MAX = 200005;
static Map<Integer, List<Integer>> graph = new HashMap<>();
static List<Integer> diameterNodes = new ArrayList<>();
static int[] parentNode = new int[MAX];
static int[] distanceFromDiameter = new int[MAX];
static int n, m;
public static void main(String[] args) throws java.lang.Exception {
out = new PrintWriter(new BufferedOutputStream(System.out));
sc = new FastReader();
int test = 1;
for (int t = 0; t < test; t++) {
solve();
}
out.close();
}
private static void solve() {
n = sc.nextInt();
for (int i = 1; i <= n; i++) {
graph.put(i, new ArrayList<>());
distanceFromDiameter[i] = -1;
}
for (int i = 0; i < n - 1; i++) {
int u = sc.nextInt();
int v = sc.nextInt();
graph.get(u).add(v);
graph.get(v).add(u);
}
// find diameter endpoints
int start = dfs(1, -1, 0).node;
int end = dfs(start, -1, 0).node;
// find diameter path
int currNode = end;
while (currNode != start) {
diameterNodes.add(currNode);
currNode = parentNode[currNode];
}
diameterNodes.add(start);
m = diameterNodes.size();
if (m == n) {
out.println(m - 1);
out.println(diameterNodes.get(0) + " " + diameterNodes.get(1) + " " + diameterNodes.get(m - 1));
return;
}
// find the farthest node from this path
bfs();
}
private static void bfs() {
Queue<Integer> q = new LinkedList<>();
for (int node : diameterNodes) {
distanceFromDiameter[node] = 0;
q.add(node);
}
while (!q.isEmpty()) {
int currNode = q.poll();
for (int adjacentNode : graph.get(currNode)) {
if (distanceFromDiameter[adjacentNode] == -1) {
distanceFromDiameter[adjacentNode] = distanceFromDiameter[currNode] + 1;
q.add(adjacentNode);
}
}
}
int farthestNode = 1, maxDistance = distanceFromDiameter[1];
for (int i = 1; i <= n; i++) {
if (distanceFromDiameter[i] > maxDistance) {
maxDistance = distanceFromDiameter[i];
farthestNode = i;
}
}
out.println(m - 1 + maxDistance);
out.println(diameterNodes.get(0) + " " + farthestNode + " " + diameterNodes.get(m - 1));
}
private static Node dfs(int currNode, int parent, int distance) {
Node node = new Node(distance, currNode);
parentNode[currNode] = parent;
for (int adjacentNode : graph.get(currNode)) {
if (adjacentNode == parent) {
continue;
}
Node next = dfs(adjacentNode, currNode, distance + 1);
if (next.distance >= node.distance) {
node = next;
}
}
return node;
}
public static FastReader sc;
public static PrintWriter out;
static class FastReader
{
BufferedReader br;
StringTokenizer str;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (str == null || !str.hasMoreElements())
{
try
{
str = new StringTokenizer(br.readLine());
}
catch (IOException lastMonthOfVacation)
{
lastMonthOfVacation.printStackTrace();
}
}
return str.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException lastMonthOfVacation)
{
lastMonthOfVacation.printStackTrace();
}
return str;
}
}
}
| java |
1323 | B | B. Count Subrectanglestime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn and array bb of length mm both consisting of only integers 00 and 11. Consider a matrix cc of size n×mn×m formed by following rule: ci,j=ai⋅bjci,j=ai⋅bj (i.e. aiai multiplied by bjbj). It's easy to see that cc consists of only zeroes and ones too.How many subrectangles of size (area) kk consisting only of ones are there in cc?A subrectangle is an intersection of a consecutive (subsequent) segment of rows and a consecutive (subsequent) segment of columns. I.e. consider four integers x1,x2,y1,y2x1,x2,y1,y2 (1≤x1≤x2≤n1≤x1≤x2≤n, 1≤y1≤y2≤m1≤y1≤y2≤m) a subrectangle c[x1…x2][y1…y2]c[x1…x2][y1…y2] is an intersection of the rows x1,x1+1,x1+2,…,x2x1,x1+1,x1+2,…,x2 and the columns y1,y1+1,y1+2,…,y2y1,y1+1,y1+2,…,y2.The size (area) of a subrectangle is the total number of cells in it.InputThe first line contains three integers nn, mm and kk (1≤n,m≤40000,1≤k≤n⋅m1≤n,m≤40000,1≤k≤n⋅m), length of array aa, length of array bb and required size of subrectangles.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), elements of aa.The third line contains mm integers b1,b2,…,bmb1,b2,…,bm (0≤bi≤10≤bi≤1), elements of bb.OutputOutput single integer — the number of subrectangles of cc with size (area) kk consisting only of ones.ExamplesInputCopy3 3 2
1 0 1
1 1 1
OutputCopy4
InputCopy3 5 4
1 1 1
1 1 1 1 1
OutputCopy14
NoteIn first example matrix cc is: There are 44 subrectangles of size 22 consisting of only ones in it: In second example matrix cc is: | [
"binary search",
"greedy",
"implementation"
] | // have faith in yourself!!!!!
/*
Naive mistakes in java :
--> Arrays.sort(primitive) is O(n^2)
--> Never use '=' to compare to Integer data types, instead use 'equals()'
*/
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
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 m = sc.nextInt();
int k = sc.nextInt();
int[] arr = new int[n];
int[] brr = new int[m];
for(int i=0;i<n;i++)arr[i] = sc.nextInt();
for(int i=0;i<m;i++)brr[i] = sc.nextInt();
long sum = 0;
for(int i=1;i*i<=k;i++){
if(k % i ==0){
long a = getCount(arr,n,i);
long b = getCount(brr,m,k/i);
sum += a*b;
if(i!=k/i){
a = getCount(arr,n,k/i);
b = getCount(brr,m,i);
sum += a*b;
}
}
}
out.println(sum);
}
private static long getCount(int[] arr,int n,int x){
if(x>n)return 0;
int sum = 0;
for(int i=0;i<x;i++)sum += arr[i];
int cnt = sum==x?1:0;
for(int i=x;i<n;i++) {
sum += arr[i] - arr[i - x];
if(sum==x)cnt++;
}
return cnt;
}
// public static int mod = (int) 1e9 + 7;
public static int mod = 998244353;
public static int inf_int = (int) 2e9 ;
public static long inf_long = (long) 2e14;
public static void _sort(int[] arr,boolean isAscending){
int n = arr.length;
List<Integer> list = new ArrayList<>();
for(int ele : arr)list.add(ele);
Collections.sort(list);
if(!isAscending)Collections.reverse(list);
for(int i=0;i<n;i++)arr[i] = list.get(i);
}
public static void _sort(long[] arr,boolean isAscending){
int n = arr.length;
List<Long> list = new ArrayList<>();
for(long ele : arr)list.add(ele);
Collections.sort(list);
if(!isAscending)Collections.reverse(list);
for(int i=0;i<n;i++)arr[i] = list.get(i);
}
static class Pair<K,V> {
K f;
V s;
public Pair(K f) {
this.f = f;
}
public Pair(K f, V s) {
this.f = f;
this.s = s;
}
}
/*-------------------------------------------EDITING CODE ENDS HERE-------------------------------------------*/
static FastestReader sc;
static PrintWriter out;
private static void openIO() throws IOException{
sc = new FastestReader();
out = new PrintWriter(System.out);
}
/*-------------------------------------------FAST INPUT STARTS HERE---------------------------------------------*/
public static void closeIO() throws IOException{
out.flush();
out.close();
sc.close();
}
private static final class FastestReader {
private static final int BUFFER_SIZE = 1 << 16;
private final DataInputStream din;
private final byte[] buffer;
private int bufferPointer, bytesRead;
public FastestReader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public FastestReader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() throws IOException {
int b;
//noinspection StatementWithEmptyBody
while ((b = read()) != -1 && isSpaceChar(b)) {}
return b;
}
public String next() throws IOException {
int b = skip();
final StringBuilder sb = new StringBuilder();
while (!isSpaceChar(b)) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = read();
}
return sb.toString();
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
final boolean neg = c == '-';
if (neg) { c = read(); }
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) { return -ret; }
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ') { c = read(); }
final boolean neg = c == '-';
if (neg) { c = read(); }
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) { return -ret; }
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ') { c = read(); }
final boolean neg = c == '-';
if (neg) { c = read(); }
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg) { return -ret; }
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) { buffer[0] = -1; }
}
private byte read() throws IOException {
if (bufferPointer == bytesRead) { fillBuffer(); }
return buffer[bufferPointer++];
}
public void close() throws IOException {
din.close();
}
}
/*---------------------------------------------FAST INPUT ENDS HERE ---------------------------------------------*/
} | java |
1294 | F | F. Three Paths on a Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an unweighted tree with nn vertices. Recall that a tree is a connected undirected graph without cycles.Your task is to choose three distinct vertices a,b,ca,b,c on this tree such that the number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc is the maximum possible. See the notes section for a better understanding.The simple path is the path that visits each vertex at most once.InputThe first line contains one integer number nn (3≤n≤2⋅1053≤n≤2⋅105) — the number of vertices in the tree. Next n−1n−1 lines describe the edges of the tree in form ai,biai,bi (1≤ai1≤ai, bi≤nbi≤n, ai≠biai≠bi). It is guaranteed that given graph is a tree.OutputIn the first line print one integer resres — the maximum number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc.In the second line print three integers a,b,ca,b,c such that 1≤a,b,c≤n1≤a,b,c≤n and a≠,b≠c,a≠ca≠,b≠c,a≠c.If there are several answers, you can print any.ExampleInputCopy8
1 2
2 3
3 4
4 5
4 6
3 7
3 8
OutputCopy5
1 8 6
NoteThe picture corresponding to the first example (and another one correct answer):If you choose vertices 1,5,61,5,6 then the path between 11 and 55 consists of edges (1,2),(2,3),(3,4),(4,5)(1,2),(2,3),(3,4),(4,5), the path between 11 and 66 consists of edges (1,2),(2,3),(3,4),(4,6)(1,2),(2,3),(3,4),(4,6) and the path between 55 and 66 consists of edges (4,5),(4,6)(4,5),(4,6). The union of these paths is (1,2),(2,3),(3,4),(4,5),(4,6)(1,2),(2,3),(3,4),(4,5),(4,6) so the answer is 55. It can be shown that there is no better answer. | [
"dfs and similar",
"dp",
"greedy",
"trees"
] | import java.io.*;
import java.util.*;
public class F{
static boolean[] vis;
static int n;
static List<Integer>[] adj;
static int furthest;
static int farNode;
static void dfs1(int i, int p, int d) {
if (d > furthest) {
furthest = d;
farNode = i;
}
for (int x: adj[i]) {
if (x==p) continue;
dfs1(x,i,d+1);
}
}
static boolean dfs2(int i, int p, int t) {
if (i == t) return vis[i] = true;
for (int x: adj[i]) {
if (x==p) continue;
vis[i] |= dfs2(x,i,t);
}
return vis[i];
}
static void dfs3(int i, int p, int d) {
if (d > furthest) {
furthest = d;
farNode = i;
}
for (int x: adj[i]) {
if (vis[x] || x == p) continue;
dfs3(x,i,d+1);
}
}
public static void main(String[] args) throws IOException {
// br = new BufferedReader(new FileReader(".in"));
// out = new PrintWriter(new FileWriter(".out"));
//new Thread(null, new (), "peepee", 1<<28).start();
// Select diameter andthen longest path
n = readInt();
adj = new List[n];
for (int i = 0; i < n; i++) adj[i] = new ArrayList<Integer>();
for (int i = 0; i < n-1; i++) {
int x = readInt()-1;
int y = readInt()-1;
adj[x].add(y);
adj[y].add(x);
}
farNode = furthest = 0;
dfs1(0,0,0);
List<Integer> b = new ArrayList<Integer>();
b.add(farNode);
furthest = 0;
int cur = farNode;
dfs1(farNode,farNode,0);
b.add(farNode);
long val = furthest;
vis = new boolean[n];
dfs2(farNode,farNode, cur);
furthest = 0;
for (int i =0 ; i < n; i++) {
if (vis[i]) {
//System.out.println("using this as jumpoff " + i + " " + adj[i]);
dfs3(i,i,0);
}
}
val += furthest;
if (furthest== 0) {
for (int i = 0; i < n; i++) if (!b.contains(i)) {
farNode = i;
break;
}
}
b.add(farNode);
out.println(val);
for (int x: b) out.print(x +1+ " ");
out.println();
out.close();
}
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
static StringTokenizer st = new StringTokenizer("");
static String read() throws IOException{return st.hasMoreTokens() ? st.nextToken():(st = new StringTokenizer(br.readLine())).nextToken();}
static int readInt() throws IOException{return Integer.parseInt(read());}
static long readLong() throws IOException{return Long.parseLong(read());}
static double readDouble() throws IOException{return Double.parseDouble(read());}
} | java |
1305 | E | E. Kuroni and the Score Distributiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is the coordinator of the next Mathforces round written by the "Proof by AC" team. All the preparation has been done; and he is discussing with the team about the score distribution for the round.The round consists of nn problems, numbered from 11 to nn. The problems are ordered in increasing order of difficulty, no two problems have the same difficulty. A score distribution for the round can be denoted by an array a1,a2,…,ana1,a2,…,an, where aiai is the score of ii-th problem. Kuroni thinks that the score distribution should satisfy the following requirements: The score of each problem should be a positive integer not exceeding 109109. A harder problem should grant a strictly higher score than an easier problem. In other words, 1≤a1<a2<⋯<an≤1091≤a1<a2<⋯<an≤109. The balance of the score distribution, defined as the number of triples (i,j,k)(i,j,k) such that 1≤i<j<k≤n1≤i<j<k≤n and ai+aj=akai+aj=ak, should be exactly mm. Help the team find a score distribution that satisfies Kuroni's requirement. In case such a score distribution does not exist, output −1−1.InputThe first and single line contains two integers nn and mm (1≤n≤50001≤n≤5000, 0≤m≤1090≤m≤109) — the number of problems and the required balance.OutputIf there is no solution, print a single integer −1−1.Otherwise, print a line containing nn integers a1,a2,…,ana1,a2,…,an, representing a score distribution that satisfies all the requirements. If there are multiple answers, print any of them.ExamplesInputCopy5 3
OutputCopy4 5 9 13 18InputCopy8 0
OutputCopy10 11 12 13 14 15 16 17
InputCopy4 10
OutputCopy-1
NoteIn the first example; there are 33 triples (i,j,k)(i,j,k) that contribute to the balance of the score distribution. (1,2,3)(1,2,3) (1,3,4)(1,3,4) (2,4,5)(2,4,5) | [
"constructive algorithms",
"greedy",
"implementation",
"math"
] | import static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
import static java.lang.System.exit;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class E {
static void solve() throws Exception {
int n = scanInt(), m = scanInt();
int a[] = new int[n];
int x = 0, y = 0;
for (int i = 0; i < n; i++) {
if (m >= i / 2) {
a[i] = i + 1;
m -= i / 2;
} else if (x == 0) {
x = 2 * i - 2 * m;
a[i] = x + 1;
m = 0;
y = 2 * x;
} else {
a[i] = y + 1;
y += x;
}
}
if (m != 0) {
out.print(-1);
} else {
for (int i = 0; i < n; i++) {
out.print(a[i] + " ");
}
}
}
static int scanInt() throws IOException {
return parseInt(scanString());
}
static long scanLong() throws IOException {
return parseLong(scanString());
}
static String scanString() throws IOException {
while (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
static BufferedReader in;
static PrintWriter out;
static StringTokenizer tok;
public static void main(String[] args) {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
in.close();
out.close();
} catch (Throwable e) {
e.printStackTrace();
exit(1);
}
}
} | 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.*;
import java.util.*;
public class d2prac implements Runnable
{
private boolean console=false;
public void solve()
{
int i; int n=in.ni(); char a[]=in.ns().toCharArray(); int max[]=new int[n]; int min[]=new int[n]; int p=n;
ArrayList<Integer> lo=new ArrayList(); ArrayList<Integer> hi=new ArrayList(); int left=0;
for(i=0;i<p-1;i++)
if(a[i]=='<')
{
lo.add(n); hi.add(n); n--;
}
Collections.reverse(hi);
max[0]=min[0]=n--;
for(i=0;i<p-1;i++)
{
if(a[i]=='<')
{
int st=i;
while(i<p-1&&a[i]=='<')
{
min[i+1]=lo.remove(lo.size()-1); i++;
}
i--;
for(int j=i;j>=st;j--)
max[j+1]=hi.remove(hi.size()-1);
}
else
{
min[i+1]=n; max[i+1]=n--;
}
}
for(int v:max) out.print(v+" "); out.println();
for(int v:min) out.print(v+" "); out.println();
}
@Override
public void run() {
try { init(); }
catch (FileNotFoundException e) { e.printStackTrace(); }
int t= in.ni();
while (t-->0) {
solve();
out.flush(); }
}
private FastInput in; private PrintWriter out;
public static void main(String[] args) throws Exception { new d2prac().run(); }
private void init() throws FileNotFoundException {
InputStream inputStream = System.in; OutputStream outputStream = System.out;
try { if (!console && System.getProperty("user.name").equals("sachan")) {
outputStream = new FileOutputStream("/home/sachan/Desktop/output.txt");
inputStream = new FileInputStream("/home/sachan/Desktop/input.txt"); }
} catch (Exception ignored) { }
out = new PrintWriter(outputStream); in = new FastInput(inputStream);
}
static class FastInput { InputStream obj;
public FastInput(InputStream obj) { this.obj = obj; }
byte inbuffer[] = new byte[1024]; int lenbuffer = 0, ptrbuffer = 0;
int readByte() { if (lenbuffer == -1) throw new InputMismatchException();
if (ptrbuffer >= lenbuffer) { ptrbuffer = 0;
try { lenbuffer = obj.read(inbuffer); }
catch (IOException e) { throw new InputMismatchException(); } }
if (lenbuffer <= 0) return -1;return inbuffer[ptrbuffer++]; }
String ns() { int b = skip();StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { sb.appendCodePoint(b);b = readByte(); }return sb.toString();}
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(); }}
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 * 10L + (b - '0'); } else {
return minus ? -num : num; }b = readByte(); } }
boolean isSpaceChar(int c) { return (!(c >= 33 && c <= 126)); }
int skip() { int b;while ((b = readByte()) != -1 && isSpaceChar(b)) ;return b; }
float nf() {return Float.parseFloat(ns());}
double nd() {return Double.parseDouble(ns());}
char nc() {return (char) skip();}
}
}
| java |
1292 | A | A. NEKO's Maze Gametime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 as DJ Mashiro - Happiness Breeze Ice - DJ Mashiro is dead or aliveNEKO#ΦωΦ has just got a new maze game on her PC!The game's main puzzle is a maze; in the forms of a 2×n2×n rectangle grid. NEKO's task is to lead a Nekomimi girl from cell (1,1)(1,1) to the gate at (2,n)(2,n) and escape the maze. The girl can only move between cells sharing a common side.However, at some moments during the game, some cells may change their state: either from normal ground to lava (which forbids movement into that cell), or vice versa (which makes that cell passable again). Initially all cells are of the ground type.After hours of streaming, NEKO finally figured out there are only qq such moments: the ii-th moment toggles the state of cell (ri,ci)(ri,ci) (either from ground to lava or vice versa).Knowing this, NEKO wonders, after each of the qq moments, whether it is still possible to move from cell (1,1)(1,1) to cell (2,n)(2,n) without going through any lava cells.Although NEKO is a great streamer and gamer, she still can't get through quizzes and problems requiring large amount of Brain Power. Can you help her?InputThe first line contains integers nn, qq (2≤n≤1052≤n≤105, 1≤q≤1051≤q≤105).The ii-th of qq following lines contains two integers riri, cici (1≤ri≤21≤ri≤2, 1≤ci≤n1≤ci≤n), denoting the coordinates of the cell to be flipped at the ii-th moment.It is guaranteed that cells (1,1)(1,1) and (2,n)(2,n) never appear in the query list.OutputFor each moment, if it is possible to travel from cell (1,1)(1,1) to cell (2,n)(2,n), print "Yes", otherwise print "No". There should be exactly qq answers, one after every update.You can print the words in any case (either lowercase, uppercase or mixed).ExampleInputCopy5 5
2 3
1 4
2 4
2 3
1 4
OutputCopyYes
No
No
No
Yes
NoteWe'll crack down the example test here: After the first query; the girl still able to reach the goal. One of the shortest path ways should be: (1,1)→(1,2)→(1,3)→(1,4)→(1,5)→(2,5)(1,1)→(1,2)→(1,3)→(1,4)→(1,5)→(2,5). After the second query, it's impossible to move to the goal, since the farthest cell she could reach is (1,3)(1,3). After the fourth query, the (2,3)(2,3) is not blocked, but now all the 44-th column is blocked, so she still can't reach the goal. After the fifth query, the column barrier has been lifted, thus she can go to the final goal again. | [
"data structures",
"dsu",
"implementation"
] | import java.text.DecimalFormat;
import java.io.*;
import java.util.*;
public class Main
{
static class Pair
{
String name;
int s,e;
public Pair(String name,int s,int e)
{
this.name=name;
this.s=s;
this.e=e;
}
}
static final int INF = 1 << 30;
static final long INFL = 1L << 60;
static final long NINF = INFL * -1;
static final long mod = (long) 1e9 + 7;
static final long mod2 = 998244353;
static DecimalFormat df = new DecimalFormat("0.00000000000000");
public static final double PI = 3.141592653589793d, eps = 1e-9;
public static void main(String[] args) throws IOException {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskC solver = new TaskC();
//int t=in.ni();
solver.solve(1, in, out);
out.close();
}
static class TaskC
{
public static void solve(int testNumber, InputReader in, OutputWriter out) {
//Scanner sc=new Scanner(System.in);
int t=1;
//int t=in.ni();
while(t-->0)
{
int n=in.ni();
int q=in.ni();
boolean[][] arr=new boolean[2][n];
int f=1,cnt=0;
while(q-->0)
{
int r=in.ni()-1;
int c=in.ni()-1;
if(arr[r][c])
{
for(int k=Math.max(0,c-1);k<=c+1 && k<n;++k)
{
if(arr[r^1][k])
{
--cnt;
}
}
}
arr[r][c]^=true;
if(arr[r][c])
{
for(int k=Math.max(0,c-1);k<=c+1 && k<n;++k)
{
if(arr[r^1][k])
{
++cnt;
}
}
}
out.printLine((cnt==0)?"Yes" : "No");
}
}
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int ni() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
private char nc() { return (char)skip(); }
public int[] na(int arraySize) {
int[] array = new int[arraySize];
for (int i = 0; i < arraySize; i++) {
array[i] = ni();
}
return array;
}
private int skip() {
int b;
while ((b = read()) != -1 && isSpaceChar(b)) ;
return b;
}
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = read();
}
return sb.toString();
}
private char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = read();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
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;
}
int[][] nim(int h, int w) {
int[][] a = new int[h][w];
for (int i = 0; i < h; i++) {
a[i] = na(w);
}
return a;
}
long[][] nlm(int h, int w) {
long[][] a = new long[h][w];
for (int i = 0; i < h; i++) {
a[i] = nla(w);
}
return a;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isNewLine(int c) {
return c == '\n';
}
public String nextLine() {
int c = read();
StringBuilder result = new StringBuilder();
do {
result.appendCodePoint(c);
c = read();
} while (!isNewLine(c));
return result.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sign = 1;
if (c == '-') {
sign = -1;
c = read();
}
long result = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
result *= 10;
result += c & 15;
c = read();
} while (!isSpaceChar(c));
return result * sign;
}
public long[] nla(int arraySize) {
long array[] = new long[arraySize];
for (int i = 0; i < arraySize; i++) {
array[i] = nextLong();
}
return array;
}
public double nextDouble() {
double ret = 0, div = 1;
byte c = (byte) read();
while (c <= ' ') {
c = (byte) read();
}
boolean neg = (c == '-');
if (neg) {
c = (byte) read();
}
do {
ret = ret * 10 + c - '0';
} while ((c = (byte) read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = (byte) read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg) {
return -ret;
}
return ret;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
public static class CP
{
static boolean isPrime(long n) {
if (n <= 1)
return false;
if (n == 2 || n == 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
for (int i = 5; (long) i * i <= n; i += 6) {
if (n % i == 0 || n % (i + 2) == 0)
return false;
}
return true;
}
public static int log2(int N) {
int result = (int) (Math.log(N) / Math.log(2));
return result;
}
public static long pow(long a, long n, long mod) {
// a %= mod;
long ret = 1;
int x = 63 - Long.numberOfLeadingZeros(n);
for (; x >= 0; x--) {
ret = ret * ret % mod;
if (n << 63 - x < 0)
ret = ret * a % mod;
}
return ret;
}
public static void nextPermutation(int[] nums) {
//find first decreasing digit
int mark = -1;
for (int i = nums.length - 1; i > 0; i--) {
if (nums[i] > nums[i - 1]) {
mark = i - 1;
break;
}
}
if (mark == -1) {
reverse(nums, 0, nums.length - 1);
return;
}
int idx = nums.length-1;
for (int i = nums.length-1; i >= mark+1; i--) {
if (nums[i] > nums[mark]) {
idx = i;
break;
}
}
CP.swap(nums, mark, idx);
CP.reverse(nums, mark + 1, nums.length - 1);
}
public static boolean nextPer(int[] data) {
int i = data.length - 1;
while (i > 0 && data[i] < data[i - 1]) {
i--;
}
if (i == 0) {
return false;
}
int j = data.length - 1;
while (data[j] < data[i - 1]) {
j--;
}
int temp = data[i - 1];
data[i - 1] = data[j];
data[j] = temp;
Arrays.sort(data, i, data.length);
return true;
}
public static void swap(int[] nums, int i, int j) {
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
public static void reverse(int[] nums, int i, int j) {
while (i < j) {
swap(nums, i, j);
i++;
j--;
}
}
public static boolean isComposite(long n) {
if (n < 2)
return true;
if (n == 2 || n == 3)
return false;
if (n % 2 == 0 || n % 3 == 0)
return true;
for (long i = 6L; i * i <= n; i += 6)
if (n % (i - 1) == 0 || n % (i + 1) == 0)
return true;
return false;
}
static int ifnotPrime(int[] prime, int x) {
return (prime[x / 64] & (1 << ((x >> 1) & 31)));
}
static long log2(long n)
{
return (long)(Math.log10(n)/Math.log10(2L));
}
static void makeComposite(int[] prime, int x) {
prime[x / 64] |= (1 << ((x >> 1) & 31));
}
public static String swap(String a, int i, int j) {
char temp;
char[] charArray = a.toCharArray();
temp = charArray[i];
charArray[i] = charArray[j];
charArray[j] = temp;
return String.valueOf(charArray);
}
static void reverse(long arr[]){
int l = 0, r = arr.length-1;
while(l<r){
long temp = arr[l];
arr[l] = arr[r];
arr[r] = temp;
l++;
r--;
}
}
static void reverse(int arr[]){
int l = 0, r = arr.length-1;
while(l<r){
int temp = arr[l];
arr[l] = arr[r];
arr[r] = temp;
l++;
r--;
}
}
public static int[] sieveEratosthenes(int n) {
if (n <= 32) {
int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31};
for (int i = 0; i < primes.length; i++) {
if (n < primes[i]) {
return Arrays.copyOf(primes, i);
}
}
return primes;
}
int u = n + 32;
double lu = Math.log(u);
int[] ret = new int[(int) (u / lu + u / lu / lu * 1.5)];
ret[0] = 2;
int pos = 1;
int[] isnp = new int[(n + 1) / 32 / 2 + 1];
int sup = (n + 1) / 32 / 2 + 1;
int[] tprimes = {3, 5, 7, 11, 13, 17, 19, 23, 29, 31};
for (int tp : tprimes) {
ret[pos++] = tp;
int[] ptn = new int[tp];
for (int i = (tp - 3) / 2; i < tp << 5; i += tp)
ptn[i >> 5] |= 1 << (i & 31);
for (int j = 0; j < sup; j += tp) {
for (int i = 0; i < tp && i + j < sup; i++) {
isnp[j + i] |= ptn[i];
}
}
}
// 3,5,7
// 2x+3=n
int[] magic = {0, 1, 23, 2, 29, 24, 19, 3, 30, 27, 25, 11, 20, 8, 4,
13, 31, 22, 28, 18, 26, 10, 7, 12, 21, 17, 9, 6, 16, 5, 15, 14};
int h = n / 2;
for (int i = 0; i < sup; i++) {
for (int j = ~isnp[i]; j != 0; j &= j - 1) {
int pp = i << 5 | magic[(j & -j) * 0x076be629 >>> 27];
int p = 2 * pp + 3;
if (p > n)
break;
ret[pos++] = p;
if ((long) p * p > n)
continue;
for (int q = (p * p - 3) / 2; q <= h; q += p)
isnp[q >> 5] |= 1 << q;
}
}
return Arrays.copyOf(ret, pos);
}
static long digitSum(long s) {
long brute = 0;
while (s > 0) {
brute+=s%10;
s /= 10;
}
return brute;
}
public static int[] primefacts(int n, int[] primes) {
int[] ret = new int[15];
int rp = 0;
for (int p : primes) {
if (p * p > n) break;
int i;
for (i = 0; n % p == 0; n /= p, i++) ;
if (i > 0) ret[rp++] = p;
}
if (n != 1) ret[rp++] = n;
return Arrays.copyOf(ret, rp);
}
public static long[] sort(long arr[]) {
List<Long> list = new ArrayList<>();
for (long n : arr) {
list.add(n);
}
Collections.sort(list);
for (int i = 0; i < arr.length; i++) {
arr[i] = list.get(i);
}
return arr;
}
public static long[] revsort(long[] arr) {
List<Long> list = new ArrayList<>();
for (long n : arr) {
list.add(n);
}
Collections.sort(list, Collections.reverseOrder());
for (int i = 0; i < arr.length; i++) {
arr[i] = list.get(i);
}
return arr;
}
public static int[] revsort(int[] arr) {
List<Integer> list = new ArrayList<>();
for (int n : arr) {
list.add(n);
}
Collections.sort(list, Collections.reverseOrder());
for (int i = 0; i < arr.length; i++) {
arr[i] = list.get(i);
}
return arr;
}
public static ArrayList<Integer> reverse(
ArrayList<Integer> data,
int left, int right)
{
while (left < right)
{
int temp = data.get(left);
data.set(left++,
data.get(right));
data.set(right--, temp);
}
return data;
}
static ArrayList<Integer> sieve(long size)
{
ArrayList<Integer> pr = new ArrayList<Integer>();
boolean prime[] = new boolean[(int) size];
for (int i = 2; i < prime.length; i++) prime[i] = true;
for (int i = 2; i * i < prime.length; i++) {
if (prime[i]) {
for (int j = i * i; j < prime.length; j += i) {
prime[j] = false;
}
}
}
for (int i = 2; i < prime.length; i++) if (prime[i]) pr.add(i);
return pr;
}
static ArrayList<Integer> segmented_sieve(int l, int r, ArrayList<Integer> primes) {
ArrayList<Integer> al = new ArrayList<>();
if (l == 1) ++l;
int max = r - l + 1;
int arr[] = new int[max];
for (int p : primes) {
if (p * p <= r) {
int i = (l / p) * p;
if (i < l) i += p;
for (; i <= r; i += p) {
if (i != p) {
arr[i - l] = 1;
}
}
}
}
for (int i = 0; i < max; ++i) {
if (arr[i] == 0) {
al.add(l + i);
}
}
return al;
}
static boolean isfPrime(long n, int iteration) {
if (n == 0 || n == 1)
return false;
if (n == 2)
return true;
if (n % 2 == 0)
return false;
Random rand = new Random();
for (int i = 0; i < iteration; i++) {
long r = Math.abs(rand.nextLong());
long a = r % (n - 1) + 1;
if (modPow(a, n - 1, n) != 1)
return false;
}
return true;
}
static long modPow(long a, long b, long c) {
long res = 1;
for (int i = 0; i < b; i++) {
res *= a;
res %= c;
}
return res % c;
}
private static long binPower(long a, long l, long mod) {
long res = 0;
while (l > 0) {
if ((l & 1) == 1) {
res = mulmod(res, a, mod);
l >>= 1;
}
a = mulmod(a, a, mod);
}
return res;
}
private static long mulmod(long a, long b, long c) {
long x = 0, y = a % c;
while (b > 0) {
if (b % 2 == 1) {
x = (x + y) % c;
}
y = (y * 2L) % c;
b /= 2;
}
return x % c;
}
static long binary_Expo(long a, long b) {
long res = 1;
while (b != 0) {
if ((b & 1) == 1) {
res *= a;
--b;
}
a *= a;
b /= 2;
}
return res;
}
static void swap(int a, int b) {
int tp = b;
b = a;
a = tp;
}
static long Modular_Expo(long a, long b, long mod) {
long res = 1;
while (b != 0) {
if ((b & 1) == 1) {
res = (res * a) % mod;
--b;
}
a = (a * a) % mod;
b /= 2;
}
return res % mod;
}
static int i_gcd(int a, int b) {
while (true) {
if (b == 0)
return a;
int c = a;
a = b;
b = c % b;
}
}
static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static int gcd(int a,int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static long ceil_div(long a, long b) {
return (a + b - 1) / b;
}
static int getIthBitFromInt(int bits, int i) {
return (bits >> (i - 1)) & 1;
}
static long getIthBitFromLong(long bits, int i) {
return (bits >> (i - 1)) & 1;
}
static boolean isPerfectSquare(long a)
{
long sq=(long)(Math.floor(Math.sqrt(a))*Math.floor(Math.sqrt(a)));
return sq==a;
}
private static TreeMap<Long, Long> primeFactorize(long n) {
TreeMap<Long, Long> pf = new TreeMap<>(Collections.reverseOrder());
long cnt = 0;
long total = 1;
for (long i = 2; (long) i * i <= n; ++i) {
if (n % i == 0) {
cnt = 0;
while (n % i == 0) {
++cnt;
n /= i;
}
pf.put(cnt, i);
//total*=(cnt+1);
}
}
if (n > 1) {
pf.put(1L, n);
//total*=2;
}
return pf;
}
//less than or equal
private static int lower_bound(ArrayList<Long> list, long val) {
int ans = -1, lo = 0, hi = list.size() - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (list.get(mid)<val) {
ans = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return ans;
}
private static int lower_bound(int[] arr, int val) {
int ans = -1, lo = 0, hi = arr.length - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (arr[mid] <= val) {
ans = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return ans;
}
private static int lower_bound(long[] arr, long val) {
int ans = -1, lo = 0, hi = arr.length - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (arr[mid]>=val) {
ans = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
return ans;
}
// greater than or equal
private static int upper_bound(List<Integer> list, int val) {
int ans = list.size(), lo = 0, hi = ans - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (list.get(mid) >= val) {
ans = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
return ans;
}
private static int upper_bound(int[] arr, int val) {
int ans = arr.length, lo = 0, hi = ans - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (arr[mid] >= val) {
ans = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
return ans;
}
private static int upper_bound(long[] arr, long val) {
int ans = arr.length, lo = 0, hi = ans - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (arr[mid] >= val) {
ans = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
return ans;
}
private static int[] LIS(long arr[], int n) {
List<Long> list = new ArrayList<>();
int[] cnt=new int[n];
for (int i = 0; i < n; i++) {
int idx = find1(list, arr[i]);
if (idx < list.size())
list.set(idx, arr[i]);
else
list.add(arr[i]);
cnt[i]=list.size();
}
return cnt;
}
private static int find1(List<Long> list, long val) {
int ret = list.size(), i = 0, j = list.size() - 1;
while (i <= j) {
int mid = (i + j) / 2;
if (list.get(mid)>=val) {
ret = mid;
j = mid - 1;
} else {
i = mid + 1;
}
}
return ret;
}
private static int LNDS(int[] arr, int n) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
int idx = find2(list, arr[i]);
if (idx < list.size())
list.set(idx, arr[i]);
else
list.add(arr[i]);
}
return list.size();
}
private static int find2(List<Integer> list, int val) {
int ret = list.size(), i = 0, j = list.size() - 1;
while (i <= j) {
int mid = (i + j) / 2;
if (list.get(mid) <= val) {
i = mid + 1;
} else {
ret = mid;
j = mid - 1;
}
}
return ret;
}
private static long nCr(long n, long r,long mod) {
if (n - r > r)
r = n - r;
long ans = 1L;
for (long i = r + 1; i <= n; i++)
ans = (ans%mod*i%mod)%mod;
for (long i = 2; i <= n - r; i++)
ans /= i;
return ans%mod;
}
private static boolean isPalindrome(String str) {
int i = 0, j = str.length() - 1;
while (i < j)
if (str.charAt(i++) != str.charAt(j--))
return false;
return true;
}
static void initStringHash(String s,long[] dp,long[] inv,long p)
{
long pow=1;
inv[0]=1;
int n=s.length();
dp[0]=((s.charAt(0)-'a')+1);
for(int i=1;i<n;++i)
{
pow=(pow*p)%mod;
dp[i]=(dp[i-1]+((s.charAt(i)-'a')+1)*pow)%mod;
inv[i]=CP.modinv(pow,mod)%mod;
}
}
static long getStringHash(long[] dp,long[] inv,int l,int r)
{
long ans=dp[r];
if(l-1>=0)
{
ans-=dp[l-1];
}
ans=(ans*inv[l])%mod;
return ans;
}
private static String reverseString(String str) {
StringBuilder sb = new StringBuilder(str);
return sb.reverse().toString();
}
private static String sortString(String str) {
int[] arr = new int[256];
for (char ch : str.toCharArray())
arr[ch]++;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 256; i++)
while (arr[i]-- > 0)
sb.append((char) i);
return sb.toString();
}
static boolean isSquarefactor(int x, int factor, int target) {
int s = (int) Math.round(Math.sqrt(x));
return factor * s * s == target;
}
static boolean isSquare(long x) {
long s = (long) Math.round(Math.sqrt(x));
return x * x == s;
}
static int bs(ArrayList<Integer> al, int val) {
int l = 0, h = al.size() - 1, mid = 0, ans = -1;
while (l <= h) {
mid = (l + h) >> 1;
if (al.get(mid) == val) {
return mid;
} else if (al.get(mid) > val) {
h = mid - 1;
} else {
l = mid + 1;
}
}
return ans;
}
static void sort(int a[]) // heap sort
{
PriorityQueue<Integer> q = new PriorityQueue<>();
for (int i = 0; i < a.length; i++)
q.add(a[i]);
for (int i = 0; i < a.length; i++)
a[i] = q.poll();
}
static void shuffle(int[] in) {
for (int i = 0; i < in.length; i++) {
int idx = (int) (Math.random() * in.length);
fast_swap(in, idx, i);
}
}
public static int[] radixSort2(int[] a) {
int n = a.length;
int[] c0 = new int[0x101];
int[] c1 = new int[0x101];
int[] c2 = new int[0x101];
int[] c3 = new int[0x101];
for (int v : a) {
c0[(v & 0xff) + 1]++;
c1[(v >>> 8 & 0xff) + 1]++;
c2[(v >>> 16 & 0xff) + 1]++;
c3[(v >>> 24 ^ 0x80) + 1]++;
}
for (int i = 0; i < 0xff; i++) {
c0[i + 1] += c0[i];
c1[i + 1] += c1[i];
c2[i + 1] += c2[i];
c3[i + 1] += c3[i];
}
int[] t = new int[n];
for (int v : a) t[c0[v & 0xff]++] = v;
for (int v : t) a[c1[v >>> 8 & 0xff]++] = v;
for (int v : a) t[c2[v >>> 16 & 0xff]++] = v;
for (int v : t) a[c3[v >>> 24 ^ 0x80]++] = v;
return a;
}
static int[] computeLps(String pat) {
int len = 0, i = 1, m = pat.length();
int lps[] = new int[m];
lps[0] = 0;
while (i < m) {
if (pat.charAt(i) == pat.charAt(len)) {
++len;
lps[i] = len;
++i;
} else {
if (len != 0) {
len = lps[len - 1];
} else {
lps[i] = len;
++i;
}
}
}
return lps;
}
static ArrayList<Integer> kmp(String s, String pat) {
ArrayList<Integer> al = new ArrayList<>();
int n = s.length(), m = pat.length();
int lps[] = computeLps(pat);
int i = 0, j = 0;
while (i < n) {
if (s.charAt(i) == pat.charAt(j)) {
i++;
j++;
if (j == m) {
al.add(i - j);
j = lps[j - 1];
}
} else {
if (j != 0) {
j = lps[j - 1];
} else {
i++;
}
}
}
return al;
}
static ArrayList<Long> primeFact(long n) {
ArrayList<Long> al = new ArrayList<>();
al.add(1L);
while (n % 2 == 0) {
if (!al.contains(2L)) {
al.add(2L);
}
n /= 2L;
}
for (long i = 3; (long) i * i <= n; i += 2) {
while ((n % i == 0)) {
if (!al.contains((long) i)) {
al.add((long) i);
}
n /= i;
}
}
if (n > 2) {
if (!al.contains(n)) {
al.add(n);
}
}
return al;
}
public static long totFact(long n)
{
long cnt = 0, tot = 1;
while (n % 2 == 0) {
n /= 2;
++cnt;
}
tot *= (cnt + 1);
for (int i = 3; i <= Math.sqrt(n); i += 2) {
cnt = 0;
while (n % i == 0) {
n /= i;
++cnt;
}
tot *= (cnt + 1);
}
if (n > 2) {
tot *= 2;
}
return tot;
}
static int[] z_function(String s)
{
int n = s.length(), z[] = new int[n];
for (int i = 1, l = 0, r = 0; i < n; ++i) {
if (i <= r)
z[i] = Math.min(z[i - l], r - i + 1);
while (i + z[i] < n && s.charAt(z[i]) == s.charAt(i + z[i]))
++z[i];
if (i + z[i] - 1 > r) {
l = i;
r = i + z[i] - 1;
}
}
return z;
}
static void fast_swap(int[] a, int idx1, int idx2) {
if (a[idx1] == a[idx2])
return;
a[idx1] ^= a[idx2];
a[idx2] ^= a[idx1];
a[idx1] ^= a[idx2];
}
public static void fast_sort(long[] array) {
ArrayList<Long> copy = new ArrayList<>();
for (long i : array)
copy.add(i);
Collections.sort(copy);
for (int i = 0; i < array.length; i++)
array[i] = copy.get(i);
}
static int factorsCount(int n) {
boolean hash[] = new boolean[n + 1];
Arrays.fill(hash, true);
for (int p = 2; p * p < n; p++)
if (hash[p] == true)
for (int i = p * 2; i < n; i += p)
hash[i] = false;
int total = 1;
for (int p = 2; p <= n; p++) {
if (hash[p]) {
int count = 0;
if (n % p == 0) {
while (n % p == 0) {
n = n / p;
count++;
}
total = total * (count + 1);
}
}
}
return total;
}
static long binomialCoeff(long n, long k) {
long res = 1;
if (k > n - k)
k = n - k;
for (int i = 0; i < k; ++i) {
res = (res * (n - i));
res /= (i + 1);
}
return res;
}
static long nck(long fact[], long inv[], long n, long k) {
if (k > n) return 0;
long res = fact[(int) n]%mod;
res = (int) ((res%mod* inv[(int) k]%mod))%mod;
res = (int) ((res%mod*inv[(int) (n - k)]%mod))%mod;
return res % mod;
}
public static long fact(long x) {
long fact = 1;
for (int i = 2; i <= x; ++i) {
fact = fact * i;
}
return fact;
}
public static ArrayList<Long> getFact(long x) {
ArrayList<Long> facts = new ArrayList<>();
facts.add(1L);
for (long i = 2; i * i <= x; ++i) {
if (x % i == 0) {
facts.add(i);
if (i != x / i) {
facts.add(x / i);
}
}
}
return facts;
}
static void matrix_ex(long n, long[][] A, long[][] I) {
while (n > 0) {
if (n % 2 == 0) {
Multiply(A, A);
n /= 2;
} else {
Multiply(I, A);
n--;
}
}
}
static void Multiply(long[][] A, long[][] B) {
int n = A.length, m = A[0].length, p = B[0].length;
long[][] C = new long[n][p];
for (int i = 0; i < n; i++) {
for (int j = 0; j < p; j++) {
for (int k = 0; k < m; k++) {
C[i][j] += ((A[i][k] % mod) * (B[k][j] % mod)) % mod;
C[i][j] = C[i][j] % mod;
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < p; j++) {
A[i][j] = C[i][j];
}
}
}
public static HashMap<Integer,Integer> sortIntMapDesc(HashMap<Integer,Integer> map) {
List<Map.Entry<Integer, Integer>> list = new LinkedList<>(map.entrySet());
Collections.sort(list, (o1, o2) ->(int) (o2.getValue() - o1.getValue()));
HashMap<Integer,Integer> temp = new LinkedHashMap<>();
for (Map.Entry<Integer,Integer> i : list) {
temp.put(i.getKey(),i.getValue());
}
return temp;
}
public static HashMap<Long, Integer> sortMapDesc(HashMap<Long,Integer> map) {
List<Map.Entry<Long, Integer>> list = new LinkedList<>(map.entrySet());
Collections.sort(list, (o1, o2) -> o2.getValue() - o1.getValue());
HashMap<Long, Integer> temp = new LinkedHashMap<>();
for (Map.Entry<Long, Integer> i : list) {
temp.put(i.getKey(), i.getValue());
}
return temp;
}
public static HashMap<Character, Integer> sortMapDescch(HashMap<Character, Integer> map) {
List<Map.Entry<Character, Integer>> list = new LinkedList<>(map.entrySet());
Collections.sort(list, (o1, o2) -> o2.getValue() - o1.getValue());
HashMap<Character, Integer> temp = new LinkedHashMap<>();
for (Map.Entry<Character, Integer> i : list) {
temp.put(i.getKey(), i.getValue());
}
return temp;
}
public static HashMap<Long,Long> sortMapAsclng(HashMap<Long,Long> map) {
List<Map.Entry<Long,Long>> list = new LinkedList<>(map.entrySet());
Collections.sort(list, (o1, o2) -> (int)(o1.getValue() - o2.getValue()));
HashMap<Long,Long> temp = new LinkedHashMap<>();
for (Map.Entry<Long,Long> i : list) {
temp.put(i.getKey(), i.getValue());
}
return temp;
}
public static HashMap<Integer, Integer> sortMapAsc(HashMap<Integer, Integer> map) {
List<Map.Entry<Integer, Integer>> list = new LinkedList<>(map.entrySet());
Collections.sort(list, (o1, o2) -> o1.getValue() - o2.getValue());
HashMap<Integer, Integer> temp = new LinkedHashMap<>();
for (Map.Entry<Integer, Integer> i : list) {
temp.put(i.getKey(), i.getValue());
}
return temp;
}
public static long lcm(long l, long l2) {
long val = gcd(l, l2);
return (l * l2) / val;
}
public static boolean isSubsequence(String s, String t) {
int n = s.length();
int m = t.length();
if (m > n) {
return false;
}
int i = 0, j = 0, skip = 0;
while (i < n && j < m) {
if (s.charAt(i) == t.charAt(j)) {
--skip;
++j;
}
++skip;
++i;
}
return j==m;
}
public static long[][] combination(int l, int r) {
long[][] pascal = new long[l + 1][r + 1];
pascal[0][0] = 1;
for (int i = 1; i <= l; ++i) {
pascal[i][0] = 1;
for (int j = 1; j <= r; ++j) {
pascal[i][j] = pascal[i - 1][j - 1] + pascal[i - 1][j];
}
}
return pascal;
}
public static long gcd(long... array) {
long ret = array[0];
for (int i = 1; i < array.length; ++i) ret = gcd(ret, array[i]);
return ret;
}
public static long min(long... array) {
long ret = array[0];
for (int i = 1; i < array.length; ++i) ret = min(ret, array[i]);
return ret;
}
public static long max(long a, long b) {
return a > b ? a : b;
}
public static long max(long... array) {
long ret = array[0];
for (int i = 1; i < array.length; ++i) ret = max(ret, array[i]);
return ret;
}
public static long sum(long... array) {
long ret = 0;
for (long i : array) ret += i;
return ret;
}
public static long[] facts(int n,long m)
{
long[] fact=new long[n];
fact[0]=1;
fact[1]=1;
for(int i=2;i<n;i++)
{
fact[i]=(long)(i*fact[i-1])%m;
}
return fact;
}
public static long[] inv(long[] fact,int n,long mod)
{
long[] inv=new long[n];
inv[n-1]= CP.Modular_Expo(fact[n-1],mod-2,mod)%mod;
for(int i=n-2;i>=0;--i)
{
inv[i]=(inv[i+1]*(i+1))%mod;
}
return inv;
}
public static int modinv(long x, long mod) {
return (int) (CP.Modular_Expo(x, mod - 2, mod) % mod);
}
}
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 print(long[] array) {
for (int i = 0; i < array.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(array[i]);
}
}
public void printLine(int[] array) {
print(array);
writer.println();
}
public void printLine(long[] array) {
print(array);
writer.println();
}
public void close() {
writer.close();
}
public void printLine(long i) {
writer.println(i);
}
public void printLine(int i) {
writer.println(i);
}
public void printLine(char c) {
writer.println(c);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void py()
{
print("YES");
writer.println();
}
public void pn()
{
print("NO");
writer.println();
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
void flush() {
writer.flush();
}
}
} | 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"
] | /*
Author : Akshat Jindal
from NIT Jalandhar , Punjab , India
JAI MATA DI
*/
import java.util.*;
import javax.swing.text.Segment;
import java.io.*;
import java.math.*;
import java.sql.Array;
public class Main {
static class FR{
BufferedReader br;
StringTokenizer st;
public FR() {
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 a , long b ,long mod) {
return ((a%mod)*(b%mod))%mod;
}
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 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[] 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] = 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 FR sc = new FR();
static StringBuilder sb = new StringBuilder();
public static void main(String args[]) throws IOException {
int tc = 1;
tc = sc.nextInt();
while(tc-->0) {
TEST_CASE();
}
System.out.println(sb);
}
static void TEST_CASE() {
int n = sc.nextInt();
String s = sc.next();
char[] str1 = s.toCharArray();
int[] ans1 = fnc1(str1, n);
for(int e:ans1) sb.append(e+" ");
sb.append("\n");
String rvrs = String.valueOf(rvrs(str1));
// System.out.println(rvrs);
char[] str2 = rvrs.toCharArray();
int[] ans2 = fnc1(str2, n);
// for(int e:ans2) System.out.print(e+" ");
// System.out.println();
int l = 0 ,r = n-1;
while(l<=r) {
int temp = ans2[l];
ans2[l] = ans2[r];
ans2[r] = temp;
l++; r--;
}
for(int e:ans2) sb.append(e+" ");
sb.append("\n");
}
static String rvrs(char[] arr) {
int n = arr.length;
char[] temp = new char[n];
int l = 0 , r = n-1;
while(l<n) {
if(arr[r] == '<') temp[l] = '>';
else temp[l] = '<';
l++;
r--;
}
return String.valueOf(temp);
}
static int[] fnc1( char[] arr , int n) {
int[] ans = new int[n];
if(arr[0] == '>') {
int m = n;
ans[0] = m--;
int i =0 ;
int j = 1 ;
while(i<n-1) {
while(i<n-1 && arr[i] == '>') {
ans[j] = m--;
j++;
i++;
}
int s = j-1;
while(i<n-1 && arr[i] == '<') {
ans[j] = m--;
j++;
i++;
}
int e = j-1;
while(s<=e) {
int temp = ans[s];
ans[s] = ans[e];
ans[e] = temp;
s++;
e--;
}
}
return ans;
}
int c = 0;
int j = 0;
int i = 0;
int m = n;
while(i<n-1 && arr[i] == '<') {
i++; j++;
}
for(int ind = j ; ind>=0 ; ind--) ans[ind] = m--;
j++;
while(i<n-1) {
while(i<n-1 && arr[i] == '>') {
ans[j] = m--;
j++;
i++;
}
int s = j-1;
while(i<n-1 && arr[i] == '<') {
ans[j] = m--;
j++;
i++;
}
int e = j-1;
while(s<=e) {
int temp = ans[s];
ans[s] = ans[e];
ans[e] = temp;
s++;
e--;
}
}
return ans;
}
}
/***
<<
>><>><
<<<>><><
*/
/*******************************************************************************************************************************************************/
| java |
1307 | B | B. Cow and Friendtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically; he wants to get from (0,0)(0,0) to (x,0)(x,0) by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its nn favorite numbers: a1,a2,…,ana1,a2,…,an. What is the minimum number of hops Rabbit needs to get from (0,0)(0,0) to (x,0)(x,0)? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination.Recall that the Euclidean distance between points (xi,yi)(xi,yi) and (xj,yj)(xj,yj) is (xi−xj)2+(yi−yj)2−−−−−−−−−−−−−−−−−−√(xi−xj)2+(yi−yj)2.For example, if Rabbit has favorite numbers 11 and 33 he could hop from (0,0)(0,0) to (4,0)(4,0) in two hops as shown below. Note that there also exists other valid ways to hop to (4,0)(4,0) in 22 hops (e.g. (0,0)(0,0) →→ (2,−5–√)(2,−5) →→ (4,0)(4,0)). Here is a graphic for the first example. Both hops have distance 33, one of Rabbit's favorite numbers. In other words, each time Rabbit chooses some number aiai and hops with distance equal to aiai in any direction he wants. The same number can be used multiple times.InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤10001≤t≤1000) — the number of test cases. Next 2t2t lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and xx (1≤n≤1051≤n≤105, 1≤x≤1091≤x≤109) — the number of favorite numbers and the distance Rabbit wants to travel, respectively.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109) — Rabbit's favorite numbers. It is guaranteed that the favorite numbers are distinct.It is guaranteed that the sum of nn over all the test cases will not exceed 105105.OutputFor each test case, print a single integer — the minimum number of hops needed.ExampleInputCopy42 41 33 123 4 51 552 1015 4OutputCopy2
3
1
2
NoteThe first test case of the sample is shown in the picture above. Rabbit can hop to (2,5–√)(2,5), then to (4,0)(4,0) for a total of two hops. Each hop has a distance of 33, which is one of his favorite numbers.In the second test case of the sample, one way for Rabbit to hop 33 times is: (0,0)(0,0) →→ (4,0)(4,0) →→ (8,0)(8,0) →→ (12,0)(12,0).In the third test case of the sample, Rabbit can hop from (0,0)(0,0) to (5,0)(5,0).In the fourth test case of the sample, Rabbit can hop: (0,0)(0,0) →→ (5,102–√)(5,102) →→ (10,0)(10,0). | [
"geometry",
"greedy",
"math"
] | // Source: https://usaco.guide/general/io
import java.io.*;
import java.util.StringTokenizer;
public class CF1370B2 {
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 len = Integer.parseInt(st1.nextToken());
int dist = Integer.parseInt(st1.nextToken());
StringTokenizer st2 = new StringTokenizer(r.readLine());
int hoppage = -1;
for (int j = 0; j < len; j++) {
int next = Integer.parseInt(st2.nextToken());
if (next == dist) {
hoppage = next;
break;
}
hoppage = Math.max(hoppage, next);
}
if (hoppage == dist) {
pw.println(1);
} else {
//pw.println(dist/(double)hoppage);
pw.println( (int) Math.max(Math.ceil(dist/(double) hoppage), 2));
}
}
/*
* Make sure to include the line below, as it
* flushes and closes the output stream.
*/
pw.close();
}
}
| 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 codeforce {
static boolean multipleTC = false;
final static int Mod = 1000000007;
final static int Mod2 = 998244353;
final double PI = 3.14159265358979323846;
int MAX = 1000000007;
void pre() throws Exception {
}
long combination(int n, int r, long fact[], long ifact[]) {
long val1 = fact[n];
long val2 = ifact[(n-r)];
long val3 = ifact[r];
return (((val1*val2)%Mod)*val3)%Mod;
}
long expo(long a, long b, long mod) {
long res = 1;
while (b != 0) {
if ((b & 1) == 1)
res = (res * a) % mod;
a = (a * a) % mod;
b >>= 1;
}
return res;
}
long gcd(long a, long b) {
if(b == 0)
return a;
return gcd(b, a%b);
}
long mminvprime(long a, long b) {
return expo(a, b - 2, b);
}
void solve(int t) throws Exception {
int n = ni();
String str = n();
if(str.length() == 1) {
pn(0);
return;
}
long ans = 0;
for(char c='z';c>'a';c--) {
for(int i=0;i<str.length();i++) {
if(str.length() == 1)
break;
if(str.charAt(i) != c)
continue;
if(i == 0) {
if(str.charAt(i+1) == c-1) {
ans++;
str = str.substring(0, i) + str.substring(i+1);
i--;
}
}
else if(i == str.length()-1) {
if(str.charAt(i-1) == c-1) {
ans++;
str = str.substring(0, i) + str.substring(i+1);
i -= 2;
}
}
else {
if(str.charAt(i-1) == c-1 || str.charAt(i+1) == c-1) {
ans++;
str = str.substring(0, i) + str.substring(i+1);
i -= 2;
}
}
}
}
pn(ans);
}
double dist(int x1, int y1, int x2, int y2) {
double a = x1 - x2, b = y1 - y2;
return Math.sqrt((a * a) + (b * b));
}
long xor_sum_upton(long n) {
if (n % 4 == 0)
return n;
if (n % 4 == 1)
return 1;
if (n % 4 == 2)
return n + 1;
return 0;
}
int[] readArr(int n) throws Exception {
int arr[] = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = ni();
}
return arr;
}
void sort(int arr[], int left, int right) {
ArrayList<Integer> list = new ArrayList<>();
for (int i = left; i <= right; i++)
list.add(arr[i]);
Collections.sort(list);
for (int i = left; i <= right; i++)
arr[i] = list.get(i - left);
}
void sort(int arr[]) {
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < arr.length; i++)
list.add(arr[i]);
Collections.sort(list);
for (int i = 0; i < arr.length; i++)
arr[i] = list.get(i);
}
public long max(long... arr) {
long max = arr[0];
for (long itr : arr)
max = Math.max(max, itr);
return max;
}
public int max(int... arr) {
int max = arr[0];
for (int itr : arr)
max = Math.max(max, itr);
return max;
}
public long min(long... arr) {
long min = arr[0];
for (long itr : arr)
min = Math.min(min, itr);
return min;
}
public int min(int... arr) {
int min = arr[0];
for (int itr : arr)
min = Math.min(min, itr);
return min;
}
public long sum(long... arr) {
long sum = 0;
for (long itr : arr)
sum += itr;
return sum;
}
public long sum(int... arr) {
long sum = 0;
for (int itr : arr)
sum += itr;
return sum;
}
String bin(long n) {
return Long.toBinaryString(n);
}
String bin(int n) {
return Integer.toBinaryString(n);
}
static int bitCount(int x) {
return x == 0 ? 0 : (1 + bitCount(x & (x - 1)));
}
static void dbg(Object... o) {
System.err.println(Arrays.deepToString(o));
}
int bit(long n) {
return (n == 0) ? 0 : (1 + bit(n & (n - 1)));
}
int abs(int a) {
return (a < 0) ? -a : a;
}
long abs(long a) {
return (a < 0) ? -a : a;
}
void p(Object o) {
out.print(o);
}
void pn(Object o) {
out.println(o);
}
void pni(Object o) {
out.println(o);
out.flush();
}
void pn(int[] arr) {
int n = arr.length;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(arr[i] + " ");
}
pn(sb);
}
void pn(long[] arr) {
int n = arr.length;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(arr[i] + " ");
}
pn(sb);
}
String n() throws Exception {
return in.next();
}
String nln() throws Exception {
return in.nextLine();
}
char c() throws Exception {
return in.next().charAt(0);
}
int ni() throws Exception {
return Integer.parseInt(in.next());
}
long nl() throws Exception {
return Long.parseLong(in.next());
}
double nd() throws Exception {
return Double.parseDouble(in.next());
}
public static void main(String[] args) throws Exception {
new codeforce().run();
}
FastReader in;
PrintWriter out;
void run() throws Exception {
in = new FastReader();
out = new PrintWriter(System.out);
int T = (multipleTC) ? ni() : 1;
pre();
for (int t = 1; t <= T; t++)
solve(t);
out.flush();
out.close();
}
class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws Exception {
br = new BufferedReader(new FileReader(s));
}
String next() throws Exception {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new Exception(e.toString());
}
}
return st.nextToken();
}
String nextLine() throws Exception {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
throw new Exception(e.toString());
}
return str;
}
}
} | java |
1303 | E | E. Erase Subsequencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. You can build new string pp from ss using the following operation no more than two times: choose any subsequence si1,si2,…,siksi1,si2,…,sik where 1≤i1<i2<⋯<ik≤|s|1≤i1<i2<⋯<ik≤|s|; erase the chosen subsequence from ss (ss can become empty); concatenate chosen subsequence to the right of the string pp (in other words, p=p+si1si2…sikp=p+si1si2…sik). Of course, initially the string pp is empty. For example, let s=ababcds=ababcd. At first, let's choose subsequence s1s4s5=abcs1s4s5=abc — we will get s=bads=bad and p=abcp=abc. At second, let's choose s1s2=bas1s2=ba — we will get s=ds=d and p=abcbap=abcba. So we can build abcbaabcba from ababcdababcd.Can you build a given string tt using the algorithm above?InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain test cases — two per test case. The first line contains string ss consisting of lowercase Latin letters (1≤|s|≤4001≤|s|≤400) — the initial string.The second line contains string tt consisting of lowercase Latin letters (1≤|t|≤|s|1≤|t|≤|s|) — the string you'd like to build.It's guaranteed that the total length of strings ss doesn't exceed 400400.OutputPrint TT answers — one per test case. Print YES (case insensitive) if it's possible to build tt and NO (case insensitive) otherwise.ExampleInputCopy4
ababcd
abcba
a
b
defi
fed
xyz
x
OutputCopyYES
NO
NO
YES
| [
"dp",
"strings"
] | import java.io.*;
import java.util.*;
public class Main {
static int n, m;
static int[][] nxt;
static char[] s, t;
static int[][] dp;
static boolean solve(char[] t1, char[] t2) {
dp[0][0]=-1;
for(int i=0; i<=t1.length; ++i) {
for(int j=0; j<=t2.length; ++j) {
if(i==0 && j==0) continue;
dp[i][j]=n;
if(i>0)
dp[i][j]=Math.min(dp[i][j], nxt[dp[i-1][j]+1][t1[i-1]-'a']);
if(j>0)
dp[i][j]=Math.min(dp[i][j], nxt[dp[i][j-1]+1][t2[j-1]-'a']);
}
}
return dp[t1.length][t2.length]<n;
}
public static void main(String[] args) throws IOException
{
FastScanner f = new FastScanner();
int ttt=1;
ttt=f.nextInt();
PrintWriter out=new PrintWriter(System.out);
outer:for(int tt=0;tt<ttt;tt++) {
s=f.next().toCharArray();
t=f.next().toCharArray();
nxt=new int[402][26];
dp=new int[401][401];
n=s.length;
m=t.length;
for(int i=0; i<26; ++i)
nxt[n][i]=nxt[n+1][i]=n;
for(int i=n-1; i>-1;i--) {
for(int j=0;j<26;j++) {
nxt[i][j]=nxt[i+1][j];
}
nxt[i][s[i]-'a']=i;
}
for(int i=0; i<m; ++i) {
char[] t1=new char[i];
char[] t2=new char[m-i];
for(int j=0;j<m;j++) {
if(j<t1.length) {
t1[j]=t[j];
}
else {
t2[j-t1.length]=t[j];
}
}
if(solve(t1, t2)) {
System.out.println("YES");;
continue outer;
}
}
System.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;
}
}
}
//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 | 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"
] | /*
This article is written by
Pawan Kumar Kesarwani
Dynamic Programming Solution
to reduce the size of array by
Replacing the two
consecutive equal
elementse greater value
*/
import java.util.*;
import java.lang.*;
import java.io.*;
public class ReplaceConsecutiveEqualElements
{
// Method to return minimum of two values
public static int min(int a, int b)
{
if(a>b)
return b;
return a;
}
// Method to replace consecutive equal elements
// with a one greater value
// It recieves the array and the size of array
// as parameter
public static int replaceConsecutiveEqualElements(int arr[], int n)
{
/*
Creating two arrays to build the solution
in a bottom up manner
dp[i][j] = Number of elements remaining after
replacing consecutive equal elememts with one
greater value in arr[i..j]
element[i][j] = The result value after replacing
consecutive equal elememts with one greater value
in arr[i..j]
*/
int[][] dp = new int[n][n];
int[][] element = new int[n][n];
int i, j, k, len;
// For length = 1
for(i = 0; i <= n-1; i++)
{
dp[i][i] = 1;
element[i][i] = arr[i];
}
// Initialising the dp[i][j] with the number of elements
// in the range i..j
for (i = 0; i <= n-1; i++)
{
for (j = i; j <= n-1; j++)
{
dp[i][j] = j - i + 1;
}
}
// len is the length of array considering at a time
// Building the solution in a bottom up manner
// The loop structure is same as Matrix Chain Multiplication
for(len = 2; len <= n; len++)
{
// For all segments of length len
// different possible starting indexes
for(i = 0; i + len - 1 <= n-1; i++)
{
j = i + len - 1;
for (k = i; k < j; k++)
{
// updating the length of segment in i..j
dp[i][j] = min (dp[i][j], (dp[i][k] + dp[k + 1][j]));
// if segment i..k and k+1..j both have been converted to
// unit length and the value in both segment is same
// update dp[i][j] to unity and
// element[i][j] to either element[i][k]+1 or element[k+1][j]+1
if ((dp[i][k] == 1) && (dp[k + 1][j]==1) &&
(element[i][k] == element[k + 1][j]))
{
dp[i][j] = 1;
element[i][j] = element[i][k]+1;
}
}
}
}
// Return the number of values remaining in the array[1..n]
return dp[0][n-1];
}
// Driver Code
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
// The size of the array
int n = sc.nextInt();
// Accepting the array
int i;
int[] arr = new int[n];
for(i = 0; i <= n-1; i++)
{
int key = sc.nextInt();
arr[i] = key;
}
// Calling the function and Printing the result
System.out.println("" + replaceConsecutiveEqualElements(arr, n));
}
}
//int arr[] = { 7, 7, 5, 5, 6, 6, 6, 8, 7, 7, 7, 5, 5, 6, 10 };
//int n=15; | 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 cf1316e {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken());
int P = Integer.parseInt(st.nextToken());
int K = Integer.parseInt(st.nextToken());
//@todo Audience
st = new StringTokenizer(br.readLine());
pair[] A = new pair[N];
for (int i = 0; i < N; i++) {
A[i] = new pair(i, Integer.parseInt(st.nextToken()));
}
Arrays.sort(A);
//@todo Skill matrix
int[][] skill = new int[N][P];
for (int i = 0; i < N; i++) {
st = new StringTokenizer(br.readLine());
for (int j = 0; j < P; j++) {
skill[i][j] = Integer.parseInt(st.nextToken());
}
}
long[][] dp = new long[N + 1][(1 << P)];
for (int i = 0; i <= N; i++) {
Arrays.fill(dp[i], -1);
}
dp[0][0] = 0;
for (int i = 1; i <= N; i++) {
int ind = A[i - 1].idx;
for (int m = 0; m < (1 << P); m++) {
//@todo Count number of bits in M.
int bits = 0;
for (int j = 0; j < P; j++) {
if ((m & (1 << j)) > 0) {
bits++;
}
}
int c = i - 1 - bits;
//@todo Audience is not full.
if (c < K) {
if (dp[i - 1][m] != -1) {
dp[i][m] = dp[i - 1][m] + A[i - 1].val;
}
} else {
if (dp[i - 1][m] != -1) {
dp[i][m] = dp[i - 1][m];
}
}
//@TODO Put in the team
for (int j = 0; j < P; j++) {
if ((m & (1 << j)) > 0 && (dp[i - 1][m ^ (1 << j)]) != -1) {
dp[i][m] = Math.max(dp[i][m], dp[i - 1][m ^ (1 << j)] + skill[ind][j]);
}
}
}
}
System.out.println(dp[N][(1<< P)- 1]);
}
static class pair implements Comparable<pair> {
int idx, val;
public pair(int idx, int val) {
this.idx = idx;
this.val = val;
}
public int compareTo(pair other) {
return other.val - val;
}
}
}
| java |
1324 | F | F. Maximum White Subtreetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn vertices. A tree is a connected undirected graph with n−1n−1 edges. Each vertex vv of this tree has a color assigned to it (av=1av=1 if the vertex vv is white and 00 if the vertex vv is black).You have to solve the following problem for each vertex vv: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex vv? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains cntwcntw white vertices and cntbcntb black vertices, you have to maximize cntw−cntbcntw−cntb.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of vertices in the tree.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where aiai is the color of the ii-th vertex.Each of the next n−1n−1 lines describes an edge of the tree. Edge ii is denoted by two integers uiui and vivi, the labels of vertices it connects (1≤ui,vi≤n,ui≠vi(1≤ui,vi≤n,ui≠vi).It is guaranteed that the given edges form a tree.OutputPrint nn integers res1,res2,…,resnres1,res2,…,resn, where resiresi is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex ii.ExamplesInputCopy9
0 1 1 1 0 0 0 0 1
1 2
1 3
3 4
3 5
2 6
4 7
6 8
5 9
OutputCopy2 2 2 2 2 1 1 0 2
InputCopy4
0 0 1 0
1 2
1 3
1 4
OutputCopy0 -1 1 -1
NoteThe first example is shown below:The black vertices have bold borders.In the second example; the best subtree for vertices 2,32,3 and 44 are vertices 2,32,3 and 44 correspondingly. And the best subtree for the vertex 11 is the subtree consisting of vertices 11 and 33. | [
"dfs and similar",
"dp",
"graphs",
"trees"
] | import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
public class Main {
static final long MOD=1000000007;
static final long MOD1=998244353;
static int size = 0;
static long MAX = 1000000000000000000l;
static long M;
public static void main(String[] args){
PrintWriter out = new PrintWriter(System.out);
InputReader sc=new InputReader(System.in);
int n = sc.nextInt();
int[] a = sc.nextIntArray(n);
for (int i = 0; i < a.length; i++) {
if(a[i]==0) a[i] = -1;
}
graph G = new graph(n);
for (int i = 0; i < n-1; i++) {
int s = sc.nextInt()-1;
int t = sc.nextInt()-1;
G.addEdge(s, t, 1);
G.addEdge(t, s, 1);
}
long[] ans = new long[n];
Rerooting rerooting = new Rerooting(n, 0, G, a);
rerooting.calc(0, -1, ans);
for (int i = 0; i < n; i++) {
out.println(ans[i]);
}
out.flush();
}
//全方位木dp, 更新するものが1つver
//関数merge, f, gを変えて使う
//注)fとgについて、dp2の更新のときのindexに注意
static class Rerooting {
long E;
long[] dp1;
long[] dp2;
graph G;
int[] a;
public Rerooting(int n, long E, graph G, int[] a){
this.E = E;
this.dp1 = new long[n];
this.dp2 = new long[n];
this.G = G;
this.a = Arrays.copyOf(a, n);
dfs1(0, -1);
dfs2(0, -1);
}
//dp_v = g(merge(f(dp_ch1,c), f(dp_ch2,c), ..))
//vは辺の重み
long f(long dp, int index, long v) {
return Math.max(dp, 0);
}
long g(long x, int index) {
return x + a[index];
}
long merge(long x, long y) {
return x + y;
}
void dfs1(int v, int p) {
long res = E;
for (Edge e: G.list[v]) {
if (e.to == p) continue;
dfs1(e.to, v);
res = merge(res, f(dp1[e.to], e.to, e.v));
}
dp1[v] = g(res, v);
}
void dfs2(int v, int p) {
if (p==-1) dp2[v] = E;
int size = G.list[v].size();
long[] dp_l = new long[size+1];
long[] dp_r = new long[size+1];
dp_l[0] = E;
dp_r[size] = E;
long par_w = 0;
for (int i = 1; i < size; i++) {
int to = G.list[v].get(i-1).to;
long w = G.list[v].get(i-1).v;
if (to == p) {
par_w = w;
dp_l[i] = dp_l[i-1];
continue;
}
dp_l[i] = merge(dp_l[i-1], f(dp1[to], to, w));
}
for (int i = size-1; i >= 0; i--) {
int to = G.list[v].get(i).to;
long w = G.list[v].get(i).v;
if (to == p) {
par_w = w;
dp_r[i] = dp_r[i+1];
continue;
}
dp_r[i] = merge(dp_r[i+1], f(dp1[to], to, w));
}
for (int i = 0; i < size; i++) {
int to = G.list[v].get(i).to;
if (to == p) continue;
dp2[to] = merge(dp_l[i], dp_r[i+1]);
if(v!=0) dp2[to] = merge(dp2[to], f(dp2[v], p, par_w));//親方向の辺の重さを入れることに注意
dp2[to] = g(dp2[to], v);//toの親(v)を更新するのでindexにはvをいれる
dfs2(to, v);
}
}
void calc(int v, int p, long[] ans) {
ans[v] = E;
for (Edge e: G.list[v]) {
if (e.to == p) {
ans[v] = merge(ans[v], f(dp2[v], p, e.v));//vの親(p)を見ているのでindexにはpを入れる
continue;
}
ans[v] = merge(ans[v], f(dp1[e.to], e.to, e.v));
calc(e.to, v, ans);
}
ans[v] = g(ans[v], v);
}
}
static class Edge implements Comparable<Edge>{
int to;
long v;
public Edge(int to,long v) {
this.to=to;
this.v=v;
}
@Override
public boolean equals(Object obj){
if(obj instanceof Edge) {
Edge other = (Edge) obj;
return other.to==this.to && other.v==this.v;
}
return false;
}//同値の定義
@Override
public int hashCode() {
return Objects.hash(this.to,this.v);
}
@Override
public int compareTo( Edge p2 ){
if (this.v>p2.v) {
return 1;
}
else if (this.v<p2.v) {
return -1;
}
else {
return 0;
}
}
}
static class graph{
ArrayList<Edge>[] list;
int size;
long INF=Long.MAX_VALUE/2;
int[] color;
@SuppressWarnings("unchecked")
public graph(int n) {
size = n;
list = new ArrayList[n];
color =new int[n];
for(int i=0;i<n;i++){
list[i] = new ArrayList<Edge>();
}
}
void addEdge(int from,int to,long w) {
list[from].add(new Edge(to,w));
}
}
static class InputReader {
private InputStream in;
private byte[] buffer = new byte[1024];
private int curbuf;
private int lenbuf;
public InputReader(InputStream in) {
this.in = in;
this.curbuf = this.lenbuf = 0;
}
public boolean hasNextByte() {
if (curbuf >= lenbuf) {
curbuf = 0;
try {
lenbuf = in.read(buffer);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0)
return false;
}
return true;
}
private int readByte() {
if (hasNextByte())
return buffer[curbuf++];
else
return -1;
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private void skip() {
while (hasNextByte() && isSpaceChar(buffer[curbuf]))
curbuf++;
}
public boolean hasNext() {
skip();
return hasNextByte();
}
public String next() {
if (!hasNext())
throw new NoSuchElementException();
StringBuilder sb = new StringBuilder();
int b = readByte();
while (!isSpaceChar(b)) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public int nextInt() {
if (!hasNext())
throw new NoSuchElementException();
int c = readByte();
while (isSpaceChar(c))
c = readByte();
boolean minus = false;
if (c == '-') {
minus = true;
c = readByte();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = res * 10 + c - '0';
c = readByte();
} while (!isSpaceChar(c));
return (minus) ? -res : res;
}
public long nextLong() {
if (!hasNext())
throw new NoSuchElementException();
int c = readByte();
while (isSpaceChar(c))
c = readByte();
boolean minus = false;
if (c == '-') {
minus = true;
c = readByte();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = res * 10 + c - '0';
c = readByte();
} while (!isSpaceChar(c));
return (minus) ? -res : res;
}
public double nextDouble() {
return Double.parseDouble(next());
}
public int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public double[] nextDoubleArray(int n) {
double[] a = new double[n];
for (int i = 0; i < n; i++)
a[i] = nextDouble();
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 char[][] nextCharMap(int n, int m) {
char[][] map = new char[n][m];
for (int i = 0; i < n; i++)
map[i] = next().toCharArray();
return map;
}
}
} | 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.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.StringTokenizer;
/**
* @submission : Nithin Bharathi 28-Jan-2023
*/
public class Problem {
public static void main(String[] args) {
Template t = new Template();
int test = t.readInt();
int x = t.readInt();
HashMap<Integer,Integer>mp = new HashMap<>();
StringBuilder sb = new StringBuilder();
int mex = 0;
boolean vis[] = new boolean[test];
while(test-->0){
int rem = t.readInt()%x;
mp.put(rem,mp.getOrDefault(rem, 0)+1);
while(mp.containsKey(mex%x)){
rem = mex%x;
mp.put(rem, mp.get(rem)-1);
if(mp.get(rem) == 0)mp.remove(rem);
mex++;
}
sb.append(mex+"\n");
}
System.out.println(sb);
}
}
class Template {
private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
private static StringTokenizer st;
public static boolean isSorted(int a[]) {
for (int i = 0; i < a.length; i++) {
if (i + 1 < a.length && a[i] > a[i + 1])
return false;
}
return true;
}
public static boolean isPrime(int n) {
for (int i = 2; i * i <= n; i++) {
if (n % i == 0)
return false;
}
return true;
}
public static long factorial(int n) {
long fac = 1;
for (int i = 1; i <= n; i++)
fac *= i;
return fac;
}
public static ArrayList<Integer> factors(int n) {
ArrayList<Integer> l = new ArrayList<>();
for (int i = 1; i * i <= n; i++) {
if (n % i == 0) {
l.add(i);
if (n / i != i)
l.add(n / i);
}
}
return l;
}
public static void build(int seg[], int ind, int l, int r, int a[]) {
if (l == r) {
seg[ind] = a[l];
return;
}
int mid = (l + r) / 2;
build(seg, (2 * ind) + 1, l, mid, a);
build(seg, (2 * ind) + 2, mid + 1, r, a);
seg[ind] = Math.min(seg[(2 * ind) + 1], seg[(2 * ind) + 2]);
}
public static long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
public static void swap(int a[], int i, int j) {
int t = a[i];
a[i] = a[j];
a[j] = t;
}
public static void swap(ArrayList<Integer> l, int i, int j) {
int t = l.get(i);
l.set(i, l.get(j));
l.set(j, t);
}
public static void sort(int arr[]) {
ArrayList<Integer> list = new ArrayList<>();
for (int it : arr)
list.add(it);
Collections.sort(list);
int z = 0;
for (int i = 0; i < arr.length; i++)
arr[z++] = list.get(i);
}
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 |
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.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.FilterInputStream;
import java.io.BufferedInputStream;
import java.util.Random;
import java.util.HashMap;
import java.util.Collections;
import java.util.ArrayList;
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;
ScanReader in = new ScanReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
CInstantNoodles solver = new CInstantNoodles();
solver.solve(1, in, out);
out.close();
}
static class CInstantNoodles {
long[] random;
public void solve(int testNumber, ScanReader in, PrintWriter out) {
int t = in.scanInt();
random = new long[500005];
for (int i = 0; i < random.length; i++) random[i] = new Random().nextInt(1000000000) + 234792734l;
while (t-- > 0) {
int n = in.scanInt();
int m = in.scanInt();
long cost[] = new long[n + 1];
for (int i = 1; i <= n; i++) cost[i] = in.scanLong();
ArrayList<Integer> arrayList[] = new ArrayList[n + 1];
for (int i = 1; i <= n; i++) arrayList[i] = new ArrayList<>();
HashMap<Long, Long> hashMap = new HashMap<>();
for (int i = 0; i < m; i++) {
int a = in.scanInt();
int b = in.scanInt();
arrayList[b].add(a);
}
for (int i = 1; i <= n; i++) {
if (arrayList[i].size() == 0) continue;
Collections.sort(arrayList[i]);
long hash = findHash(arrayList[i]);
hashMap.put(hash, cost[i] + hashMap.getOrDefault(hash, 0l));
}
long gcd = 0;
for (long kkk : hashMap.values()) {
gcd = CodeX.GCD(gcd, kkk);
}
out.println(gcd);
}
}
long findHash(ArrayList<Integer> arrayList) {
int p = 0;
long res = 0;
for (int k : arrayList) {
// res ^= k;
res = (res + ((k * random[p++]) % 1000000007)) % 1000000007;
}
return res;
}
}
static class CodeX {
public static long GCD(long A, long B) {
if (B == 0)
return A;
else
return GCD(B, A % B);
}
}
static class ScanReader {
private byte[] buf = new byte[4 * 1024];
private int INDEX;
private BufferedInputStream in;
private int TOTAL;
public ScanReader(InputStream inputStream) {
in = new BufferedInputStream(inputStream);
}
private int scan() {
if (INDEX >= TOTAL) {
INDEX = 0;
try {
TOTAL = in.read(buf);
} catch (Exception e) {
e.printStackTrace();
}
if (TOTAL <= 0) return -1;
}
return buf[INDEX++];
}
public int scanInt() {
int I = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
I *= 10;
I += n - '0';
n = scan();
}
}
return neg * I;
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true;
else return false;
}
public long scanLong() {
long I = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
I *= 10;
I += n - '0';
n = scan();
}
}
return neg * I;
}
}
}
| java |
1303 | A | A. Erasing Zeroestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. Each character is either 0 or 1.You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met.You may erase some (possibly none) 0's from the string. What is the minimum number of 0's that you have to erase?InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Then tt lines follow, each representing a test case. Each line contains one string ss (1≤|s|≤1001≤|s|≤100); each character of ss is either 0 or 1.OutputPrint tt integers, where the ii-th integer is the answer to the ii-th testcase (the minimum number of 0's that you have to erase from ss).ExampleInputCopy3
010011
0
1111000
OutputCopy2
0
0
NoteIn the first test case you have to delete the third and forth symbols from string 010011 (it turns into 0111). | [
"implementation",
"strings"
] | import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
public class A {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t= in.nextInt();
for(int T=1; T<=t; T++)
{
String s = in.next();
int cnt=0,p1=0, p2=s.length()-1;
while(p1<p2)
{
if(s.charAt(p1)=='0') p1++;
if(s.charAt(p2)=='0') p2--;
if(s.charAt(p1)=='1' && s.charAt(p2)=='1') break;
}
for(int i=p1; i<p2; i++)
{
if(s.charAt(i)=='0') cnt++;
}
if(s.length()==1)
cnt=0;
System.out.println(cnt);
}
}
} | java |
1303 | C | C. Perfect Keyboardtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp wants to assemble his own keyboard. Layouts with multiple rows are too complicated for him — his keyboard will consist of only one row; where all 2626 lowercase Latin letters will be arranged in some order.Polycarp uses the same password ss on all websites where he is registered (it is bad, but he doesn't care). He wants to assemble a keyboard that will allow to type this password very easily. He doesn't like to move his fingers while typing the password, so, for each pair of adjacent characters in ss, they should be adjacent on the keyboard. For example, if the password is abacaba, then the layout cabdefghi... is perfect, since characters a and c are adjacent on the keyboard, and a and b are adjacent on the keyboard. It is guaranteed that there are no two adjacent equal characters in ss, so, for example, the password cannot be password (two characters s are adjacent).Can you help Polycarp with choosing the perfect layout of the keyboard, if it is possible?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases.Then TT lines follow, each containing one string ss (1≤|s|≤2001≤|s|≤200) representing the test case. ss consists of lowercase Latin letters only. There are no two adjacent equal characters in ss.OutputFor each test case, do the following: if it is impossible to assemble a perfect keyboard, print NO (in upper case, it matters in this problem); otherwise, print YES (in upper case), and then a string consisting of 2626 lowercase Latin letters — the perfect layout. Each Latin letter should appear in this string exactly once. If there are multiple answers, print any of them. ExampleInputCopy5
ababa
codedoca
abcda
zxzytyz
abcdefghijklmnopqrstuvwxyza
OutputCopyYES
bacdefghijklmnopqrstuvwxyz
YES
edocabfghijklmnpqrstuvwxyz
NO
YES
xzytabcdefghijklmnopqrsuvw
NO
| [
"dfs and similar",
"greedy",
"implementation"
] | import java.io.*;
import java.util.*;
public class Main {
static PrintWriter out = new PrintWriter(System.out);
static FastScanner fs = new FastScanner();
public static void solve() throws IOException {
String password = fs.next();
LinkedList<Character> q = new LinkedList<>();
boolean[] used = new boolean[26];
ArrayList<HashSet<Integer>> nextTo = new ArrayList<>();
for (int i = 0; i < 26; i++) nextTo.add(new HashSet<Integer>());
for (int i = 1; i < password.length(); i++) {
nextTo.get((int)password.charAt(i)-97).add((int)password.charAt(i-1) - 97);
nextTo.get((int)password.charAt(i-1)-97).add((int)password.charAt(i)-97);
}
for (char c : password.toCharArray()) {
if(used[(int)c - 97]) continue;
if(q.isEmpty()) q.add(c);
else {
if(nextTo.get((int)c - 97).contains((int)q.getFirst() - 97)) {
q.addFirst(c);
}
else {
q.addLast(c);
}
}
used[(int)c-97]=true;
}
for (int i = 0; i < 26; i++) {
if(!used[i]) q.add((char)(i+97));
}
boolean[][] adj = new boolean[26][26];
char[] perm = new char[26];
for (int i = 0; i < 26; i++) perm[i] = q.removeFirst();
for (int i = 1; i < 26; i++) {
adj[(int)perm[i] - 97][(int)perm[i-1] - 97] = true;
adj[(int)perm[i-1]-97][(int)perm[i]-97] = true;
}
for (int i = 1; i < password.length(); i++) {
if(!adj[(int)password.charAt(i)-97][(int)password.charAt(i-1)-97]) {
out.println("NO");
return;
}
}
out.println("YES");
out.println(new String(perm));
}
public static void main(String[] args) throws IOException {
int t = fs.nextInt();
for (int i = 0; i < t; i++) solve();
out.close();
}
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());
}
}
} | java |
1311 | D | D. Three Integerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers a≤b≤ca≤b≤c.In one move, you can add +1+1 or −1−1 to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero) number of times, you can even perform this operation several times with one number. Note that you cannot make non-positive numbers using such operations.You have to perform the minimum number of such operations in order to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB.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 tt lines describe test cases. Each test case is given on a separate line as three space-separated integers a,ba,b and cc (1≤a≤b≤c≤1041≤a≤b≤c≤104).OutputFor each test case, print the answer. In the first line print resres — the minimum number of operations you have to perform to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB. On the second line print any suitable triple A,BA,B and CC.ExampleInputCopy8
1 2 3
123 321 456
5 10 15
15 18 21
100 100 101
1 22 29
3 19 38
6 30 46
OutputCopy1
1 1 3
102
114 228 456
4
4 8 16
6
18 18 18
1
100 100 100
7
1 22 22
2
1 19 38
8
6 24 48
| [
"brute force",
"math"
] | 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.ArrayList;
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);
DThreeIntegers solver = new DThreeIntegers();
solver.solve(1, in, out);
out.close();
}
static class DThreeIntegers {
ArrayList<Integer>[] d;
public void solve(int testNumber, InputReader in, OutputWriter out) {
d = new ArrayList[20001];
for (int i = 0; i <= 20000; i++) {
d[i] = findDiv(i);
}
int t = in.nextInt();
while (t-- > 0) {
int[] f = new int[3];
int a = in.nextInt(), b = in.nextInt(), c = in.nextInt();
int ans = Integer.MAX_VALUE;
for (int i = 1; i <= 20000; i++) {
// out.println(d[i]);
int c1 = 0, a1 = 0;
int val = Math.abs(b - i);
if (c <= i) {
val += Math.abs(i - c);
c1 = i;
} else {
val += Math.min(c % i, i - (c % i));
if (c % i < i - (c % i)) {
c1 = c - (c % i);
} else {
c1 = c + (i - (c % i));
}
}
if (a >= i) {
val += a - i;
a1 = i;
} else {
int id = LowerBound(d[i], a);
if (id >= d[i].size()) {
val += Math.abs(a - d[i].get(id - 1));
a1 = d[i].get(id - 1);
} else {
int v = d[i].get(id);
if (id - 1 >= 0) {
val += Math.min(Math.abs(a - v), Math.abs(a - d[i].get(id - 1)));
if (Math.abs(a - v) > Math.abs(a - d[i].get(id - 1))) {
a1 = d[i].get(id - 1);
} else {
a1 = v;
}
} else {
val += Math.abs(a - v);
a1 = v;
}
}
}
if (val < ans) {
f[0] = a1;
f[1] = i;
f[2] = c1;
}
ans = Math.min(ans, val);
}
out.println(ans);
out.println(f);
}
}
int LowerBound(ArrayList<Integer> a, int x) { // first element greater or equal to x
int l = -1, r = a.size();
while (l + 1 < r) {
int m = (l + r) >>> 1;
if (a.get(m) >= x) r = m;
else l = m;
}
return r;
}
ArrayList<Integer> findDiv(int N) {
//gens all divisors of N
ArrayList<Integer> ls1 = new ArrayList<Integer>();
ArrayList<Integer> ls2 = new ArrayList<Integer>();
for (int i = 1; i <= (int) (Math.sqrt(N) + 0.00000001); i++)
if (N % i == 0) {
ls1.add(i);
ls2.add(N / i);
}
Collections.reverse(ls2);
for (int b : ls2)
if (b != ls1.get(ls1.size() - 1))
ls1.add(b);
return ls1;
}
}
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());
}
}
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();
}
public void println(int i) {
writer.println(i);
}
}
}
| 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.util.*;
import java.io.*;
public class G547 {
static ArrayList<Integer> [] adj;
static boolean [] bad;
static HashSet<Edge> colored;
static Map<Edge, Integer> map;
static int [] ret;
static boolean [] vis;
public static void main(String[] args) {
MyScanner sc = new MyScanner();
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
int n = sc.nextInt(); int k = sc.nextInt();
map = new HashMap<>();
ret = new int[n - 1];
adj = new ArrayList[n + 1];
colored = new HashSet<>();
vis = new boolean[n + 1];
for (int i = 1; i <= n; i++) adj[i] = new ArrayList<>();
for (int i = 0; i < n - 1; i++) {
int u = sc.nextInt(); int v = sc.nextInt();
Edge e = new Edge(u, v);
e.c = -1;
colored.add(e);
map.put(e, i);
adj[u].add(v); adj[v].add(u);
}
ArrayList<Integer> deg = new ArrayList<>();
for (int i = 1; i <= n; i++) deg.add(i);
Collections.sort(deg, Comparator.comparingInt(x -> -adj[x].size()));
bad = new boolean[n + 1];
for (int i = 0; i < k; i++) bad[deg.get(i)] = true;
//colored = new HashSet<>();
for (int i = 1; i <= n; i++) {
if (!vis[i] && !bad[i]) dfs(i, -1, -1);
}
for (int i = 1; i <= n; i++) {
for (Integer a: adj[i]) {
if (bad[i] && bad[a]) {
Edge toAdd = new Edge(i, a);
toAdd.c = 1;
Edge in = new Edge(i, a); in.c = -1;
colored.remove(in);
colored.add(toAdd);
ret[map.get(in)] = 1;
}
}
}
int max = 0;
for (int i = 0; i < n - 1; i++) max = Math.max(max, ret[i]);
out.println(max);
for (int i = 0; i < n - 1; i++) out.print(ret[i] + " ");
out.close();
}
static void dfs(int cur, int par, int c) {
vis[cur] = true;
Edge toAdd = new Edge(cur, par); toAdd.c = c;
if (par != -1) {
Edge in = new Edge(cur, par); in.c = -1;
colored.remove(in);
colored.add(toAdd);
ret[map.get(in)] = c;
}
if (bad[cur]) return;
int start = 1;
if (c == 1) ++start;
for (Integer next: adj[cur]) {
if (next != par) {
dfs(next, cur, start);
++start;
if (start == c) ++start;
}
}
}
static class Edge {
int a; int b; int c;
Edge(int u, int v) {
this.a = Math.min(u, v); this.b = Math.max(u, v);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Edge edge = (Edge) o;
return a == edge.a &&
b == edge.b &&
c == edge.c;
}
@Override
public int hashCode() {
return Objects.hash(a, b, c);
}
}
//-----------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 |
1293 | B | B. JOE is on TV!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 - Standby for ActionOur dear Cafe's owner; JOE Miller, will soon take part in a new game TV-show "1 vs. nn"!The game goes in rounds, where in each round the host asks JOE and his opponents a common question. All participants failing to answer are eliminated. The show ends when only JOE remains (we assume that JOE never answers a question wrong!).For each question JOE answers, if there are ss (s>0s>0) opponents remaining and tt (0≤t≤s0≤t≤s) of them make a mistake on it, JOE receives tsts dollars, and consequently there will be s−ts−t opponents left for the next question.JOE wonders what is the maximum possible reward he can receive in the best possible scenario. Yet he has little time before show starts, so can you help him answering it instead?InputThe first and single line contains a single integer nn (1≤n≤1051≤n≤105), denoting the number of JOE's opponents in the show.OutputPrint a number denoting the maximum prize (in dollars) JOE could have.Your answer will be considered correct if it's absolute or relative error won't exceed 10−410−4. In other words, if your answer is aa and the jury answer is bb, then it must hold that |a−b|max(1,b)≤10−4|a−b|max(1,b)≤10−4.ExamplesInputCopy1
OutputCopy1.000000000000
InputCopy2
OutputCopy1.500000000000
NoteIn the second example; the best scenario would be: one contestant fails at the first question; the other fails at the next one. The total reward will be 12+11=1.512+11=1.5 dollars. | [
"combinatorics",
"greedy",
"math"
] |
import java.util.*;
import java.io.*;
public class BBB {
static void solve() throws IOException{
}
public static void main(String[] args) throws IOException {
int n =readInt();
double x = 0.0;
for(int i = 1; i <= n; i++){
x += (double) 1.0/(double) i;
}
System.out.println(x);
}
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter pr = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
static StringTokenizer st;
static String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine().trim());
return st.nextToken();
}
static long readLong() throws IOException {
return Long.parseLong(next());
}
static int readInt() throws IOException {
return Integer.parseInt(next());
}
static double readDouble() throws IOException {
return Double.parseDouble(next());
}
static char readCharacter() throws IOException {
return next().charAt(0);
}
static String readLine() throws IOException {
return br.readLine().trim();
}
} | java |
1323 | B | B. Count Subrectanglestime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn and array bb of length mm both consisting of only integers 00 and 11. Consider a matrix cc of size n×mn×m formed by following rule: ci,j=ai⋅bjci,j=ai⋅bj (i.e. aiai multiplied by bjbj). It's easy to see that cc consists of only zeroes and ones too.How many subrectangles of size (area) kk consisting only of ones are there in cc?A subrectangle is an intersection of a consecutive (subsequent) segment of rows and a consecutive (subsequent) segment of columns. I.e. consider four integers x1,x2,y1,y2x1,x2,y1,y2 (1≤x1≤x2≤n1≤x1≤x2≤n, 1≤y1≤y2≤m1≤y1≤y2≤m) a subrectangle c[x1…x2][y1…y2]c[x1…x2][y1…y2] is an intersection of the rows x1,x1+1,x1+2,…,x2x1,x1+1,x1+2,…,x2 and the columns y1,y1+1,y1+2,…,y2y1,y1+1,y1+2,…,y2.The size (area) of a subrectangle is the total number of cells in it.InputThe first line contains three integers nn, mm and kk (1≤n,m≤40000,1≤k≤n⋅m1≤n,m≤40000,1≤k≤n⋅m), length of array aa, length of array bb and required size of subrectangles.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), elements of aa.The third line contains mm integers b1,b2,…,bmb1,b2,…,bm (0≤bi≤10≤bi≤1), elements of bb.OutputOutput single integer — the number of subrectangles of cc with size (area) kk consisting only of ones.ExamplesInputCopy3 3 2
1 0 1
1 1 1
OutputCopy4
InputCopy3 5 4
1 1 1
1 1 1 1 1
OutputCopy14
NoteIn first example matrix cc is: There are 44 subrectangles of size 22 consisting of only ones in it: In second example matrix cc is: | [
"binary search",
"greedy",
"implementation"
] | //Some of the methods are copied from GeeksforGeeks Website
import java.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
//static Scanner sc=new Scanner(System.in);
static Reader sc=new Reader();
// static FastReader sc=new FastReader(System.in);
static long mod = (long)(1e9)+ 7;
static int max_num=(int)1e5+5;
static long[] solve(int a[],int max)
{
long len[]=new long[max+1];
int i=0,n=a.length;
while(i<n)
{
if(a[i]==0)
{
i++;
continue;
}
int j=i;
while(j<n && a[j]==1)
{
j++;
}
int window=j-i;
for(int k=1;k<=window;k++)
{
len[k]+=window-k+1;
}
i=j;
}
return len;
}
public static void main (String[] args) throws java.lang.Exception
{
// try{
/*
int n=sc.nextInt();
Collections.sort(al,Collections.reverseOrder());
long n=sc.nextLong();
String s=sc.next();
StringBuilder sb=new StringBuilder();
*/
int t = 1;//sc.nextInt();
while(t-->0)
{
int n=sc.nextInt();
int m=sc.nextInt();
int k=sc.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++)
{
a[i]=sc.nextInt();
}
int b[]=new int[m];
for(int i=0;i<m;i++)
{
b[i]=sc.nextInt();
}
int max=Math.max(n,m);
long dp1[]=solve(a,max);
long dp2[]=solve(b,max);
long ans=0;
for(int i=1;i<dp1.length;i++)
{
if(k%i!=0 || k/i>m) continue;
int p=i;
int q=k/i;
ans+=dp1[p]*dp2[q];
}
out.println(ans);
}
out.flush();
out.close();
// }
// catch(Exception e)
// {}
}
/*
...SOLUTION ENDS HERE...........SOLUTION ENDS HERE...
*/
static void flag(boolean flag)
{
out.println(flag ? "YES" : "NO");
out.flush();
}
/*
Map<Long,Long> map=new HashMap<>();
for(int i=0;i<n;i++)
{
if(!map.containsKey(a[i]))
map.put(a[i],1);
else
map.replace(a[i],map.get(a[i])+1);
}
Set<Map.Entry<Long,Long>> hmap=map.entrySet();
for(Map.Entry<Long,Long> data : hmap)
{
}
*/
// static class Pair
// {
// int x,y;
// Pair(int x,int y)
// {
// this.x=x;
// this.y=y;
// }
// }
// Arrays.sort(p, new Comparator<Pair>()
// {
// @Override
// public int compare(Pair o1,Pair o2)
// {
// if(o1.x>o2.x) return 1;
// else if(o1.x==o2.x)
// {
// if(o1.y>o2.y) return 1;
// else return -1;
// }
// else return -1;
// }});
static void print(int a[])
{
int n=a.length;
for(int i=0;i<n;i++)
{
out.print(a[i]+" ");
}
out.println();
out.flush();
}
static void print(long a[])
{
int n=a.length;
for(int i=0;i<n;i++)
{
out.print(a[i]+" ");
}
out.println();
out.flush();
}
static void print_int(ArrayList<Integer> al)
{
int si=al.size();
for(int i=0;i<si;i++)
{
out.print(al.get(i)+" ");
}
out.println();
out.flush();
}
static void print_long(ArrayList<Long> al)
{
int si=al.size();
for(int i=0;i<si;i++)
{
out.print(al.get(i)+" ");
}
out.println();
out.flush();
}
static int LowerBound(int a[], int x)
{ // x is the target value or key
int l=-1,r=a.length;
while(l+1<r) {
int m=(l+r)>>>1;
if(a[m]>=x) r=m;
else l=m;
}
return r;
}
static int UpperBound(int a[], int x)
{// x is the key or target value
int l=-1,r=a.length;
while(l+1<r) {
int m=(l+r)>>>1;
if(a[m]<=x) l=m;
else r=m;
}
return l+1;
}
static void DFS(ArrayList<Integer> graph[],boolean[] visited, int u)
{
visited[u]=true;
int v=0;
for(int i=0;i<graph[u].size();i++)
{
v=graph[u].get(i);
if(!visited[v])
DFS(graph,visited,v);
}
}
static boolean[] prime(int num)
{
boolean[] bool = new boolean[num];
for (int i = 0; i< bool.length; i++) {
bool[i] = true;
}
for (int i = 2; i< Math.sqrt(num); i++) {
if(bool[i] == true) {
for(int j = (i*i); j<num; j = j+i) {
bool[j] = false;
}
}
}
if(num >= 0) {
bool[0] = false;
bool[1] = false;
}
return bool;
}
static long nCr(long a,long b,long mod)
{
return (((fact[(int)a] * modInverse(fact[(int)b],mod))%mod * modInverse(fact[(int)(a - b)],mod))%mod + mod)%mod;
}
static long fact[]=new long[max_num];
static void fact_fill()
{
long fact[]=new long[max_num];
fact[0]=1l;
for(int i=1;i<max_num;i++)
{
fact[i]=(fact[i-1]*(long)i);
if(fact[i]>=mod)
fact[i]%=mod;
}
}
static long modInverse(long a, long m)
{
return power(a, m - 2, m);
}
static long power(long x, long y, long m)
{
if (y == 0)
return 1;
long p = power(x, y / 2, m) % m;
p = (long)((p * (long)p) % m);
if (y % 2 == 0)
return p;
else
return (long)((x * (long)p) % m);
}
static long sum_array(int a[])
{
int n=a.length;
long sum=0;
for(int i=0;i<n;i++)
sum+=a[i];
return sum;
}
static long sum_array(long a[])
{
int n=a.length;
long sum=0;
for(int i=0;i<n;i++)
sum+=a[i];
return sum;
}
static void sort(int[] a)
{
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static void sort(long[] a)
{
ArrayList<Long> l=new ArrayList<>();
for (long i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static void reverse_array(int a[])
{
int n=a.length;
int i,t;
for (i = 0; i < n / 2; i++) {
t = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = t;
}
}
static void reverse_array(long a[])
{
int n=a.length;
int i; long t;
for (i = 0; i < n / 2; i++) {
t = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = t;
}
}
static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
static class FastReader{
byte[] buf = new byte[2048];
int index, total;
InputStream in;
FastReader(InputStream is) {
in = is;
}
int scan() throws IOException {
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0) {
return -1;
}
}
return buf[index++];
}
String next() throws IOException {
int c;
for (c = scan(); c <= 32; c = scan());
StringBuilder sb = new StringBuilder();
for (; c > 32; c = scan()) {
sb.append((char) c);
}
return sb.toString();
}
int nextInt() throws IOException {
int c, val = 0;
for (c = scan(); c <= 32; c = scan());
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
long nextLong() throws IOException {
int c;
long val = 0;
for (c = scan(); c <= 32; c = scan());
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
}
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
static PrintWriter out=new PrintWriter(System.out);
static int int_max=Integer.MAX_VALUE;
static int int_min=Integer.MIN_VALUE;
static long long_max=Long.MAX_VALUE;
static long long_min=Long.MIN_VALUE;
}
// Thank You ! | java |
1141 | D | D. Colored Bootstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn left boots and nn right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings ll and rr, both of length nn. The character lili stands for the color of the ii-th left boot and the character riri stands for the color of the ii-th right boot.A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color.For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z').Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible.Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair.InputThe first line contains nn (1≤n≤1500001≤n≤150000), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots).The second line contains the string ll of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th left boot.The third line contains the string rr of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th right boot.OutputPrint kk — the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors.The following kk lines should contain pairs aj,bjaj,bj (1≤aj,bj≤n1≤aj,bj≤n). The jj-th of these lines should contain the index ajaj of the left boot in the jj-th pair and index bjbj of the right boot in the jj-th pair. All the numbers ajaj should be distinct (unique), all the numbers bjbj should be distinct (unique).If there are many optimal answers, print any of them.ExamplesInputCopy10
codeforces
dodivthree
OutputCopy5
7 8
4 9
2 2
9 10
3 1
InputCopy7
abaca?b
zabbbcc
OutputCopy5
6 5
2 3
4 6
7 4
1 2
InputCopy9
bambarbia
hellocode
OutputCopy0
InputCopy10
code??????
??????test
OutputCopy10
6 2
1 6
7 3
3 5
4 8
9 7
5 1
2 4
10 9
8 10
| [
"greedy",
"implementation"
] |
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.io.*;
public class Array {
public static void mergeSort(int[] array) {
if (array == null) {
return;
}
if (array.length > 1) {
int mid = array.length / 2;
// Split left part
int[] left = new int[mid];
for (int i = 0; i < mid; i++) {
left[i] = array[i];
}
// Split right part
int[] right = new int[array.length - mid];
for (int i = mid; i < array.length; i++) {
right[i - mid] = array[i];
}
mergeSort(left);
mergeSort(right);
int i = 0;
int j = 0;
int k = 0;
// Merge left and right arrays
while (i < left.length && j < right.length) {
if (left[i] < right[j]) {
array[k] = left[i];
i++;
} else {
array[k] = right[j];
j++;
}
k++;
}
// Collect remaining elements
while (i < left.length) {
array[k] = left[i];
i++;
k++;
}
while (j < right.length) {
array[k] = right[j];
j++;
k++;
}
}
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = sc.nextInt();
String s1 = sc.next();
String s2 = sc.next();
ArrayList<Integer>[] freq1 = new ArrayList[27];
ArrayList<Integer>[] freq2 = new ArrayList[27];
int[] arr1 = new int[150000];
int[] arr2 = new int[150000];
int o1 = 0;
int o2 = 0;
int f1 = 0;
int f2 = 0;
int[] ind = new int[300002];
int j = 0;
for (int i = 0; i < 27; i++) {
freq1[i] = new ArrayList<>();
freq2[i] = new ArrayList<>();
}
for (int i = 0; i < n; i++) {
if (s1.charAt(i) == '?') {
freq1[26].add(i + 1);
continue;
}
freq1[s1.charAt(i) - 'a'].add(i + 1);
}
for (int i = 0; i < n; i++) {
if (s2.charAt(i) == '?') {
freq2[26].add(i + 1);
continue;
}
freq2[s2.charAt(i) - 'a'].add(i + 1);
}
for (int i = 0; i < 26; i++) {
int len = Math.min(freq1[i].size(), freq2[i].size());
for (int k = len; k < freq1[i].size(); k++) {
arr1[o1++] = freq1[i].get(k);
}
for (int k = len; k < freq2[i].size(); k++) {
arr2[o2++] = freq2[i].get(k);
}
for (int b = 0; b < len; b++) {
ind[j++] = freq1[i].get(b);
ind[j++] = freq2[i].get(b);
}
}
int len = Math.min(o2, freq1[26].size());
{
for (int i = 0; i < len; i++) {
ind[j++] = freq1[26].get(f1++);
ind[j++] = arr2[--o2];
}
}
len = Math.min(o1, freq2[26].size());
{
for (int i = 0; i < len; i++) {
ind[j++] = arr1[--o1];
ind[j++] = freq2[26].get(f2++);
}
}
for (int i = 0; i <freq1[26].size()-f1; i++) {
ind[j++] = freq1[26].get(i+f1);
ind[j++] = freq2[26].get(i+f2);
}
/*
* 5
6 5
4 6
7 4
2 3
1 2
*/
int ans = j/2;
pw.println(ans);
while (j >= 1) {
pw.println(ind[j - 2] + " " + ind[j - 1]);
j -= 2;
}
pw.flush();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(String file) throws IOException {
br = new BufferedReader(new FileReader(file));
}
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
protected String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String readAllLines(BufferedReader reader) throws IOException {
StringBuilder content = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
content.append(line);
content.append(System.lineSeparator());
}
return content.toString();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public long[] nextlongArray(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public Long[] nextLongArray(int n) throws IOException {
Long[] a = new Long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public int[] nextIntArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public Integer[] nextIntegerArray(int n) throws IOException {
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public boolean ready() throws IOException {
return br.ready();
}
}
}
| java |
1295 | C | C. Obtain The Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings ss and tt consisting of lowercase Latin letters. Also you have a string zz which is initially empty. You want string zz to be equal to string tt. You can perform the following operation to achieve this: append any subsequence of ss at the end of string zz. A subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, if z=acz=ac, s=abcdes=abcde, you may turn zz into following strings in one operation: z=acacez=acace (if we choose subsequence aceace); z=acbcdz=acbcd (if we choose subsequence bcdbcd); z=acbcez=acbce (if we choose subsequence bcebce). Note that after this operation string ss doesn't change.Calculate the minimum number of such operations to turn string zz into string tt. InputThe first line contains the integer TT (1≤T≤1001≤T≤100) — the number of test cases.The first line of each testcase contains one string ss (1≤|s|≤1051≤|s|≤105) consisting of lowercase Latin letters.The second line of each testcase contains one string tt (1≤|t|≤1051≤|t|≤105) consisting of lowercase Latin letters.It is guaranteed that the total length of all strings ss and tt in the input does not exceed 2⋅1052⋅105.OutputFor each testcase, print one integer — the minimum number of operations to turn string zz into string tt. If it's impossible print −1−1.ExampleInputCopy3
aabce
ace
abacaba
aax
ty
yyt
OutputCopy1
-1
3
| [
"dp",
"greedy",
"strings"
] | import java.util.*;
import java.io.*;
public class Main {
static int[] parent, size;
static int[][] arr;
static char[] a, b;
public static void main(String[] args) throws IOException {
int t = sc.nextInt();
while (t-- > 0) {
a = sc.next().toCharArray();
b = sc.next().toCharArray();
arr = new int[a.length][26];
if (!check()) {
pw.println(-1);
continue;
}
for (int[] nums : arr) {
Arrays.fill(nums, -1);
}
for (int i = arr.length - 2; i >= 0; i--) {
for (int j = 0; j < 26; j++) {
arr[i][j] = arr[i + 1][j];
}
arr[i][a[i + 1] - 'a'] = i + 1;
}
int ans = 0;
int idx = 0;
while (idx < b.length) {
int cur = -1;
while (true) {
if (idx >= b.length)
break;
int next = query(cur, b[idx], idx);
if (next == -1) {
ans++;
break;
}
idx++;
cur = next;
}
}
pw.println(ans + 1);
}
pw.close();
}
static boolean check() {
boolean[] arrA = new boolean[26];
boolean[] arrB = new boolean[26];
for (int i = 0; i < a.length; i++) {
arrA[a[i] - 'a'] = true;
}
for (int i = 0; i < b.length; i++) {
arrB[b[i] - 'a'] = true;
}
for (int i = 0; i < arrB.length; i++) {
if (arrB[i] && !arrA[i])
return false;
}
return true;
}
static int query(int cur, char c, int idx) {
if (cur == -1) {
if (b[idx] == a[0])
return 0;
else
return arr[0][c - 'a'];
}
return arr[cur][c - 'a'];
}
static int find(int a) {
if (a == parent[a])
return a;
return parent[a] = find(parent[a]);
}
static void union(int a, int b) {
a = find(a);
b = find(b);
if (a == b)
return;
if (size[a] < size[b])
parent[a] = b;
else
parent[b] = a;
}
static long[] HashStr(char[] arr) {
long[] hash = new long[arr.length];
int p = 31;
int m = 1000000007;
long hashValue = 0;
long power = 1;
for (int i = 0; i < arr.length; i++) {
hashValue = (hashValue + (arr[i] - 'a' + 1) * power) % m;
power = (power * p) % m;
hash[i] = hashValue;
}
return hash;
}
static int toInt(boolean flag) {
return flag ? 1 : 0;
}
static int log2(int n) {
return (int) (Math.log(n) / Math.log(2));
}
static int[] sieve() {
int n = (int) 1e5;
int[] arr = new int[n];
for (int i = 2; i < arr.length; i++) {
for (int j = i; j < arr.length; j += i) {
if (arr[j] == 0)
arr[j] = i;
}
}
return arr;
}
static void shuffle(int[] arr) {
int n = arr.length;
for (int i = 0; i < n; i++) {
int r = i + (int) (Math.random() * (n - i));
int tmp = arr[i];
arr[i] = arr[r];
arr[r] = tmp;
}
}
static void sort(int[] arr) {
shuffle(arr);
Arrays.sort(arr);
}
static long getSum(int[] arr) {
long sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
static int getMin(int[] arr) {
int min = Integer.MAX_VALUE;
for (int i = 0; i < arr.length; i++) {
min = Math.min(min, arr[i]);
}
return min;
}
static int getMax(int[] arr) {
int max = Integer.MIN_VALUE;
for (int i = 0; i < arr.length; i++) {
max = Math.max(max, arr[i]);
}
return max;
}
static boolean isEqual(int[] a, int[] b) {
if (a.length != b.length)
return false;
for (int i = 0; i < b.length; i++) {
if (a[i] != b[i])
return false;
}
return true;
}
static void reverse(int[] arr, int start, int end) {
while (start < end) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
static boolean isSorted(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i + 1])
return false;
}
return true;
}
static int gcd(int x, int y) {
if (x == 0)
return y;
return gcd(y % x, x);
}
static HashMap<Integer, Integer> Hash(int[] arr) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int i : arr) {
map.put(i, map.getOrDefault(i, 0) + 1);
}
return map;
}
static HashMap<Character, Integer> Hash(char[] arr) {
HashMap<Character, Integer> map = new HashMap<>();
for (char i : arr) {
map.put(i, map.getOrDefault(i, 0) + 1);
}
return map;
}
static boolean isPrime(int n) {
if (n <= 1)
return false;
for (int i = 2; i <= Math.sqrt(n); i++)
if (n % i == 0)
return false;
return true;
}
public static long combination(long n, long r) {
return factorial(n) / (factorial(n - r) * factorial(r));
}
static long factorial(Long n) {
if (n == 0)
return 1;
return (n % mod) * (factorial(n - 1) % mod) % mod;
}
static boolean isPalindrome(char[] str, int i, int j) {
while (i < j) {
if (str[i] != str[j])
return false;
i++;
j--;
}
return true;
}
public static int setBit(int mask, int idx) {
return mask | (1 << idx);
}
public static boolean checkBit(int mask, int idx) {
return (mask & (1 << idx)) != 0;
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public long[] nextlongArray(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public Long[] nextLongArray(int n) throws IOException {
Long[] a = new Long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public int[] nextIntArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public int[] nextIntCharArray(int n) throws IOException {
int[] a = new int[n];
char[] b = sc.next().toCharArray();
for (int i = 0; i < n; i++)
a[i] = b[i] - '0';
return a;
}
public int[] NextIntArray(int n) throws IOException {
int[] arr = new int[n + 1];
for (int i = 1; i < arr.length; i++) {
arr[i] = nextInt();
}
return arr;
}
public Integer[] nextIntegerArray(int n) throws IOException {
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public ArrayList<Integer>[] directedGraph(int n, int m) throws IOException {
ArrayList<Integer>[] graph = new ArrayList[n];
for (int i = 0; i < graph.length; i++) {
graph[i] = new ArrayList<>();
}
while (m-- > 0) {
int a = nextInt();
int b = nextInt();
graph[a].add(b);
}
return graph;
}
public ArrayList<Integer>[] undirectedGraph(int n, int m) throws IOException {
ArrayList<Integer>[] graph = new ArrayList[n];
for (int i = 0; i < graph.length; i++) {
graph[i] = new ArrayList<>();
}
while (m-- > 0) {
int a = nextInt();
int b = nextInt();
graph[a].add(b);
graph[b].add(a);
}
return graph;
}
public boolean ready() throws IOException {
return br.ready();
}
}
static class pair implements Comparable<pair> {
long x;
long y;
public pair(long x, long y) {
this.x = x;
this.y = y;
}
public String toString() {
return x + " " + y;
}
public boolean equals(Object o) {
if (o instanceof pair) {
pair p = (pair) o;
return p.x == x && p.y == y;
}
return false;
}
public int hashCode() {
return new Long(x).hashCode() * 31 + new Long(y).hashCode();
}
public int compareTo(pair other) {
if (this.x == other.x) {
return Long.compare(this.y, other.y);
}
return Long.compare(this.x, other.x);
}
}
public static void print(int[] arr) {
for (int i = 0; i < arr.length; i++) {
pw.print(arr[i] + " ");
}
pw.println();
}
public static void print(int[] arr, String separator) {
for (int i = 0; i < arr.length; i++) {
pw.print(arr[i] + separator);
}
pw.println();
}
public static void print(long[] arr) {
for (int i = 0; i < arr.length; i++) {
pw.print(arr[i] + " ");
}
pw.println();
}
public static void print(ArrayList arr) {
for (int i = 0; i < arr.size(); i++) {
pw.print(arr.get(i) + " ");
}
pw.println();
}
public static void print(int[][] arr) {
for (int[] i : arr) {
print(i);
}
}
public static void print(boolean[] arr) {
for (int i = 0; i < arr.length; i++) {
pw.print(arr[i] + " ");
}
pw.println();
}
public static void print(char[] arr) {
for (int i = 0; i < arr.length; i++) {
pw.print(arr[i] + " ");
}
pw.println();
}
static int inf = Integer.MAX_VALUE;
static long mod = 1000000007;
static Random rn = new Random();
static Scanner sc = new Scanner(System.in);
static PrintWriter pw = new PrintWriter(System.out);
} | java |
1305 | A | A. Kuroni and the Giftstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni has nn daughters. As gifts for them, he bought nn necklaces and nn bracelets: the ii-th necklace has a brightness aiai, where all the aiai are pairwise distinct (i.e. all aiai are different), the ii-th bracelet has a brightness bibi, where all the bibi are pairwise distinct (i.e. all bibi are different). Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the ii-th daughter receives a necklace with brightness xixi and a bracelet with brightness yiyi, then the sums xi+yixi+yi should be pairwise distinct. Help Kuroni to distribute the gifts.For example, if the brightnesses are a=[1,7,5]a=[1,7,5] and b=[6,1,2]b=[6,1,2], then we may distribute the gifts as follows: Give the third necklace and the first bracelet to the first daughter, for a total brightness of a3+b1=11a3+b1=11. Give the first necklace and the third bracelet to the second daughter, for a total brightness of a1+b3=3a1+b3=3. Give the second necklace and the second bracelet to the third daughter, for a total brightness of a2+b2=8a2+b2=8. Here is an example of an invalid distribution: Give the first necklace and the first bracelet to the first daughter, for a total brightness of a1+b1=7a1+b1=7. Give the second necklace and the second bracelet to the second daughter, for a total brightness of a2+b2=8a2+b2=8. Give the third necklace and the third bracelet to the third daughter, for a total brightness of a3+b3=7a3+b3=7. This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!InputThe input consists of multiple test cases. The first line contains an 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 single integer nn (1≤n≤1001≤n≤100) — the number of daughters, necklaces and bracelets.The second line of each test case contains nn distinct integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000) — the brightnesses of the necklaces.The third line of each test case contains nn distinct integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤10001≤bi≤1000) — the brightnesses of the bracelets.OutputFor each test case, print a line containing nn integers x1,x2,…,xnx1,x2,…,xn, representing that the ii-th daughter receives a necklace with brightness xixi. In the next line print nn integers y1,y2,…,yny1,y2,…,yn, representing that the ii-th daughter receives a bracelet with brightness yiyi.The sums x1+y1,x2+y2,…,xn+ynx1+y1,x2+y2,…,xn+yn should all be distinct. The numbers x1,…,xnx1,…,xn should be equal to the numbers a1,…,ana1,…,an in some order, and the numbers y1,…,yny1,…,yn should be equal to the numbers b1,…,bnb1,…,bn in some order. It can be shown that an answer always exists. If there are multiple possible answers, you may print any of them.ExampleInputCopy2
3
1 8 5
8 4 5
3
1 7 5
6 1 2
OutputCopy1 8 5
8 4 5
5 1 7
6 2 1
NoteIn the first test case; it is enough to give the ii-th necklace and the ii-th bracelet to the ii-th daughter. The corresponding sums are 1+8=91+8=9, 8+4=128+4=12, and 5+5=105+5=10.The second test case is described in the statement. | [
"brute force",
"constructive algorithms",
"greedy",
"sortings"
] | import java.util.*;
public class p1305a{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-- > 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();
Arrays.sort(a);
Arrays.sort(b);
for(int i=0; i<n; i++)
System.out.print(a[i] + " ");
System.out.println("");
for(int i=0; i<n; i++)
System.out.print(b[i] + " ");
System.out.println("");
}
}
}
| java |
1300 | A | A. Non-zerotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas have an array aa of nn integers [a1,a2,…,ana1,a2,…,an]. In one step they can add 11 to any element of the array. Formally, in one step they can choose any integer index ii (1≤i≤n1≤i≤n) and do ai:=ai+1ai:=ai+1.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make a1+a2+a1+a2+ …… +an≠0+an≠0 and a1⋅a2⋅a1⋅a2⋅ …… ⋅an≠0⋅an≠0.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1031≤t≤103). The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1001≤n≤100) — the size of the array.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−100≤ai≤100−100≤ai≤100) — elements of the array .OutputFor each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.ExampleInputCopy4
3
2 -1 -1
4
-1 0 0 1
2
-1 2
3
0 -2 1
OutputCopy1
2
0
2
NoteIn the first test case; the sum is 00. If we add 11 to the first element, the array will be [3,−1,−1][3,−1,−1], the sum will be equal to 11 and the product will be equal to 33.In the second test case, both product and sum are 00. If we add 11 to the second and the third element, the array will be [−1,1,1,1][−1,1,1,1], the sum will be equal to 22 and the product will be equal to −1−1. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding 11 twice to the first element the array will be [2,−2,1][2,−2,1], the sum will be 11 and the product will be −4−4. | [
"implementation",
"math"
] | import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
in = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out));
try {
int t = in.nextInt(); while(t-- > 0) { solve(); out.println();}
// solve();
} finally {
out.close();
}
return;
}
public static void solve() {
int n = in.nextInt();
int[] a = fillArray(n);
long cnt = Arrays.stream(a).filter(el -> el == 0).count();
long sum = Arrays.stream(a).sum();
if(sum + cnt == 0) {
out.print(cnt + 1);
return;
} else {
out.print(cnt);
}
return;
}
//-------------- Helper methods-------------------
public static int[] fillArray(int n) {
int[] array = new int[n];
for(int i = 0; i < n; i++) {
array[i] = in.nextInt();
}
return array;
}
public static char[] fillArray() {
char[] array = in.next().toCharArray();
return array;
}
//-----------PrintWriter for faster output---------------------------------
public static PrintWriter out;
public static MyScanner in;
//-----------MyScanner class for faster input----------x§x
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static void shuffleArray(int[] arr){
int n = arr.length;
Random rnd = new Random();
for(int i=0; i<n; ++i){
int tmp = arr[i];
int randomPos = i + rnd.nextInt(n-i);
arr[i] = arr[randomPos];
arr[randomPos] = tmp;
}
}
//--------------------------------------------------------
}
| java |
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"
] |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class ProductOfThreeNumbersAgain {
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();
int a = -1, b = -1, c = -1;
//boolean ok = true;
for (int i = 2; i * i <= N; i++)
{
if (a == -1)
{
if (N%i == 0)
{
a = i;
N /= a;
}
}
else
{
if (N%i == 0)
{
b = i;
N /= b;
c = N;
if (N > b)
{
pw.println("YES");
pw.println(a + " " + b + " " + c);
break;
}
else
{
pw.println("NO");
break;
}
}
}
}
if (a == -1 || b == -1 || c == -1)
{
pw.println("NO");
}
}
pw.close();
}
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
public String next() {
while (!st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
long[] readArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) {
a[i] = nextLong();
}
return a;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
}
| java |
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.*;
final public class B {
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
char[] arr = br.readLine().toCharArray();
int q = Integer.parseInt(br.readLine()), len = arr.length;
int[][] pref = new int[len+1][26];
for(int i = 1; i<= len; i++){
for(int j = 0; j<26; j++) {
if(j == arr[i-1]-97) pref[i][j] = pref[i-1][j] + 1;
else pref[i][j] = pref[i-1][j];
}
}
for(int i = 0; i< q; i++){
String[] str = br.readLine().split(" ");
int l = Integer.parseInt(str[0])-1, r = Integer.parseInt(str[1])-1;
int cnt = 0;
for(int j = 0; j<26; j++){
if((pref[r+1][j] - pref[l][j])>0) cnt++;
}
if(cnt >= 3 || r == l || arr[l]!=arr[r]) sb.append("Yes");
else sb.append("No");
sb.append('\n');
}
System.out.println(sb);
}
}
| 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.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.lang.reflect.Array;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.io.*;
import java.math.*;
import java.util.Arrays;
import java.util.Comparator;
import java.util.*;
import java.util.Collections;
import java.util.Date;
import java.util.Random;
import java.util.LinkedList;
import java.util.Scanner;
import java.util.Date;
public class div {
static PrintWriter output = new PrintWriter(System.out);
public static void main(String[] args) throws java.lang.Exception {
OutputWriter out = new OutputWriter(System.out);
div.FastReader sc =new FastReader();
int t=sc.nextInt();
for(int e =0;e<t;e++) {
int n =sc.nextInt(); int m =sc.nextInt();
String s =sc.next();int arr[]= new int [n];
for(int ee=0;ee<m;ee++) {
int p=sc.nextInt();arr[p-1]++;
}
int arr1[]= new int [26];
for (int i = n - 1; i > 0; --i) {
arr[i - 1] += arr[i];
}
for (int i = 0; i < n; ++i) {
arr1[s.charAt(i) - 'a'] += arr[i];
++arr1[s.charAt(i) - 'a'];
}
for(int ee=0;ee<25;ee++)out.print(arr1[ee]+" ");
out.println(arr1[25]);
}
out.close();
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
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;
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long[] readArrayLong(int n) {
long[] a=new long[n];
for (int i=0; i<n; i++) a[i]=nextLong();
return a;
}
}
//////////////////////////////////////////////////////////////////////////////////////////
public 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(char[] array) {
writer.print(array);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void print(int[] array) {
for (int i = 0; i < array.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(array[i]);
}
}
public void print(double[] array) {
for (int i = 0; i < array.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(array[i]);
}
}
public void print(long[] 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 println(double[] array) {
print(array);
writer.println();
}
public void println(long[] array) {
print(array);
writer.println();
}
public void println() {
writer.println();
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void print(char i) {
writer.print(i);
}
public void println(char i) {
writer.println(i);
}
public void println(char[] array) {
writer.println(array);
}
public void printf(String format, Object... objects) {
writer.printf(format, objects);
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
public void print(long i) {
writer.print(i);
}
public void println(long i) {
writer.println(i);
}
public void print(int i) {
writer.print(i);
}
public void println(int i) {
writer.println(i);
}
public void separateLines(int[] array) {
for (int i : array) {
println(i);
}
}
}
/*
Arrays.sort(arr, Comparator.comparingDouble(o -> o[0]));
q.replace(i, i+1, "4");
StringBuilder q = new StringBuilder(s);
List arr1 = new ArrayList();
String.format("%.2f",arr[ee][0])
Hashtable s = new Hashtable();
*/
} | java |
1286 | C2 | C2. Madhouse (Hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is different with easy version only by constraints on total answers lengthIt is an interactive problemVenya joined a tour to the madhouse; in which orderlies play with patients the following game. Orderlies pick a string ss of length nn, consisting only of lowercase English letters. The player can ask two types of queries: ? l r – ask to list all substrings of s[l..r]s[l..r]. Substrings will be returned in random order, and in every substring, all characters will be randomly shuffled. ! s – guess the string picked by the orderlies. This query can be asked exactly once, after that the game will finish. If the string is guessed correctly, the player wins, otherwise he loses. The player can ask no more than 33 queries of the first type.To make it easier for the orderlies, there is an additional limitation: the total number of returned substrings in all queries of the first type must not exceed ⌈0.777(n+1)2⌉⌈0.777(n+1)2⌉ (⌈x⌉⌈x⌉ is xx rounded up).Venya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules.Your program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer.Note that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive.InputFirst line contains number nn (1≤n≤1001≤n≤100) — the length of the picked string.InteractionYou start the interaction by reading the number nn.To ask a query about a substring from ll to rr inclusively (1≤l≤r≤n1≤l≤r≤n), you should output? l ron a separate line. After this, all substrings of s[l..r]s[l..r] will be returned in random order, each substring exactly once. In every returned substring all characters will be randomly shuffled.In the case, if you ask an incorrect query, ask more than 33 queries of the first type or there will be more than ⌈0.777(n+1)2⌉⌈0.777(n+1)2⌉ substrings returned in total, you will receive verdict Wrong answer.To guess the string ss, you should output! son a separate line.After printing each query, do not forget to flush the output. Otherwise, you will get Idleness limit exceeded. To flush the output, you can use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. If you received - (dash) as an answer to any query, you need to terminate your program with exit code 0 (for example, by calling exit(0)). This means that there was an error in the interaction protocol. If you don't terminate with exit code 0, you can receive any unsuccessful verdict. Hack formatTo hack a solution, use the following format:The first line should contain one integer nn (1≤n≤1001≤n≤100) — the length of the string, and the following line should contain the string ss.ExampleInputCopy4
a
aa
a
cb
b
c
cOutputCopy? 1 2
? 3 4
? 4 4
! aabc | [
"brute force",
"constructive algorithms",
"hashing",
"interactive",
"math"
] | 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.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in Actual solution is at the top
*
* @author ilyakor
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskC1 solver = new TaskC1();
solver.solve(1, in, out);
out.close();
}
static class TaskC1 {
InputReader in;
OutputWriter out;
public void solve(int testNumber, InputReader in, OutputWriter out) {
// Random random = new Random(0xdead);
// for (int it = 0; it < 10000; ++it) {
// int n = 19;
// StringBuilder sb = new StringBuilder();
// for (int i = 0; i < n; ++i)
// sb.append((char)('a' + random.nextInt(26)));
// S = sb.toString();
// sum = 0;
// String res = new String(doSolve(S.length()));
// if (sum > (n + 1) * (n + 1))
// throw new RuntimeException();
// if (!res.equals(S))
// throw new RuntimeException();
// }
this.in = in;
this.out = out;
int n = in.nextInt();
if (n == 1) {
char c1 = doQuery(1, 1).get(0)[0];
out.printLine("! " + c1);
out.flush();
return;
}
if (n == 2) {
char c1 = doQuery(1, 1).get(0)[0];
out.printLine("? 2 2");
out.flush();
char c2 = in.nextToken().toCharArray()[0];
out.printLine("! " + c1 + "" + c2);
out.flush();
return;
}
if (n == 3) {
char c1 = doQuery(1, 1).get(0)[0];
out.printLine("? 2 2");
out.flush();
char c2 = in.nextToken().toCharArray()[0];
out.printLine("? 3 3");
out.flush();
char c3 = in.nextToken().toCharArray()[0];
out.printLine("! " + c1 + "" + c2 + "" + c3);
out.flush();
return;
}
char[] res = doSolve(n);
out.printLine("! " + new String(res));
out.flush();
}
public char[] doSolve(int n) {
char[][] qn = query(1, n);
int m = n / 2;
while (check(n, m) == -1) {
--m;
}
int start = check(n, m);
// System.err.println(m);
// int m = n / 2 - 1;
// if ((n - m) % 2 == 1) ++m;
char[][] qm = query(1, m);
char[][] qmn = query(m + 1, n);
char[] res = new char[n];
char c;
if (start == n - 1 - start) {
c = qn[Math.min(start, n - 1 - start)][0];
} else if (start == n + m - 1 - start) {
c = qmn[Math.min(start, n + m - 1 - start) - m][0];
} else {
c = qm[Math.min(start, m - 1 - start)][0];
}
int pos = start;
for (int it = 0; it < n; ++it) {
res[pos] = c;
if (it == n - 1) {
break;
}
if (res[n - 1 - pos] == 0) {
c = other(qn[Math.min(pos, n - 1 - pos)], c);
pos = n - 1 - pos;
} else if (pos >= m && res[m + n - 1 - pos] == 0) {
c = other(qmn[Math.min(pos, m + n - 1 - pos) - m], c);
pos = m + n - 1 - pos;
} else {
if (res[m - 1 - pos] != 0) {
throw new RuntimeException();
}
c = other(qm[Math.min(pos, m - 1 - pos)], c);
pos = m - 1 - pos;
}
}
return res;
}
private int check(int n, int m) {
boolean[] u = new boolean[n];
int pos = -1;
for (int i = 0; i < n; ++i) {
if (i == n - i - 1 || i == n + m - i - 1 || i == m - i - 1) {
pos = i;
break;
}
}
if (pos == -1) {
return pos;
}
int start = pos;
for (int it = 0; it < n - 1; ++it) {
u[pos] = true;
if (!u[n - 1 - pos]) {
pos = n - 1 - pos;
} else if (pos >= m && !u[m + n - 1 - pos]) {
pos = m + n - 1 - pos;
} else if (pos < m && !u[m - 1 - pos]) {
pos = m - 1 - pos;
} else {
return -1;
}
}
return start;
}
private char other(char[] a, char c) {
if (a[0] != c) {
return a[0];
}
return a[1];
}
private char[][] query(int l, int r) {
int n = r - l + 1;
ArrayList<char[]> output = doQuery(l, r);
ArrayList<char[]>[] ans = new ArrayList[n + 1];
for (int i = 0; i < ans.length; ++i) {
ans[i] = new ArrayList<>();
}
for (char[] s : output) {
Arrays.sort(s);
ans[s.length].add(s);
}
char[][] res = new char[(n + 1) / 2][2];
if (n == 1) {
res[0][0] = ans[1].get(0)[0];
res[0][1] = ans[1].get(0)[0];
return res;
}
int[] cnts = new int[26];
char[] st = new char[20];
int ss = 0;
for (char[] s : ans[n - 1]) {
char[] os = ans[n].get(0);
Arrays.fill(cnts, 0);
for (char c : os) {
++cnts[c - 'a'];
}
for (char c : s) {
--cnts[c - 'a'];
}
for (int i = 0; i < cnts.length; ++i) {
if (cnts[i] > 0) {
st[ss++] = (char) ('a' + i);
}
}
}
if (ss != 2) {
throw new RuntimeException();
}
res[0][0] = st[0];
res[0][1] = st[1];
for (int i = 1; i < res.length; ++i) {
int len = n - i - 1;
Arrays.fill(cnts, 0);
for (char[] s : ans[len]) {
for (char c : s) {
++cnts[c - 'a'];
}
}
for (int j = 0; j < i; ++j) {
for (char c : res[j]) {
cnts[c - 'a'] -= j + 1;
}
}
ss = 0;
for (int j = 0; j < cnts.length; ++j) {
if (cnts[j] % (i + 2) != 0) {
st[ss++] = (char) ('a' + j);
}
}
if (ss != 1 && ss != 2) {
throw new RuntimeException();
}
if (ss == 1) {
st[1] = st[0];
}
res[i][0] = st[0];
res[i][1] = st[1];
}
return res;
}
ArrayList<char[]> doQuery(int l, int r) {
// ArrayList<char[]> res = new ArrayList<>();
// for (int i = l - 1; i <= r - 1; ++i)
// for (int j = i; j <= r - 1; ++j)
// res.add(S.substring(i, j + 1).toCharArray());
// sum += res.size();
// return res;
out.printLine("? " + l + " " + r);
out.flush();
int n = r - l + 1;
ArrayList<char[]> res = new ArrayList<>();
for (int i = 0; i < (n * (n + 1)) / 2; ++i) {
res.add(in.nextToken().toCharArray());
}
return res;
}
}
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 class InputReader {
private InputStream stream;
private byte[] buffer = new byte[10000];
private int cur;
private int count;
public InputReader(InputStream stream) {
this.stream = stream;
}
public static boolean isSpace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int read() {
if (count == -1) {
throw new InputMismatchException();
}
try {
if (cur >= count) {
cur = 0;
count = stream.read(buffer);
if (count <= 0) {
return -1;
}
}
} catch (IOException e) {
throw new InputMismatchException();
}
return buffer[cur++];
}
public int readSkipSpace() {
int c;
do {
c = read();
} while (isSpace(c));
return c;
}
public String nextToken() {
int c = readSkipSpace();
StringBuilder sb = new StringBuilder();
while (!isSpace(c)) {
sb.append((char) c);
c = read();
}
return sb.toString();
}
public int nextInt() {
int sgn = 1;
int c = readSkipSpace();
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res = res * 10 + c - '0';
c = read();
} while (!isSpace(c));
res *= sgn;
return res;
}
}
}
| 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 Main {
public static void main(String[] args) {
new Main();
}
public Main() {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
scanner.nextLine();
for (int i = 0; i < n; i++) {
String a = scanner.nextLine(), b = scanner.nextLine(), c = scanner.nextLine();
boolean possible = true;
for (int j = 0; j < a.length() && possible; j++) {
char cc = c.charAt(j);
if (a.charAt(j) == cc || b.charAt(j) == cc) continue;
possible = false;
}
System.out.println(possible ? "YES" : "NO");
}
}
}
| java |
1295 | E | E. Permutation Separationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation p1,p2,…,pnp1,p2,…,pn (an array where each integer from 11 to nn appears exactly once). The weight of the ii-th element of this permutation is aiai.At first, you separate your permutation into two non-empty sets — prefix and suffix. More formally, the first set contains elements p1,p2,…,pkp1,p2,…,pk, the second — pk+1,pk+2,…,pnpk+1,pk+2,…,pn, where 1≤k<n1≤k<n.After that, you may move elements between sets. The operation you are allowed to do is to choose some element of the first set and move it to the second set, or vice versa (move from the second set to the first). You have to pay aiai dollars to move the element pipi.Your goal is to make it so that each element of the first set is less than each element of the second set. Note that if one of the sets is empty, this condition is met.For example, if p=[3,1,2]p=[3,1,2] and a=[7,1,4]a=[7,1,4], then the optimal strategy is: separate pp into two parts [3,1][3,1] and [2][2] and then move the 22-element into first set (it costs 44). And if p=[3,5,1,6,2,4]p=[3,5,1,6,2,4], a=[9,1,9,9,1,9]a=[9,1,9,9,1,9], then the optimal strategy is: separate pp into two parts [3,5,1][3,5,1] and [6,2,4][6,2,4], and then move the 22-element into first set (it costs 11), and 55-element into second set (it also costs 11).Calculate the minimum number of dollars you have to spend.InputThe first line contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the length of permutation.The second line contains nn integers p1,p2,…,pnp1,p2,…,pn (1≤pi≤n1≤pi≤n). It's guaranteed that this sequence contains each element from 11 to nn exactly once.The third line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109).OutputPrint one integer — the minimum number of dollars you have to spend.ExamplesInputCopy3
3 1 2
7 1 4
OutputCopy4
InputCopy4
2 4 1 3
5 9 8 3
OutputCopy3
InputCopy6
3 5 1 6 2 4
9 1 9 9 1 9
OutputCopy2
| [
"data structures",
"divide and conquer"
] | import java.io.BufferedOutputStream;
import java.io.Closeable;
import java.io.DataInputStream;
import java.io.Flushable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.function.IntUnaryOperator;
/**
* 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);
EPermutationSeparation solver = new EPermutationSeparation();
solver.solve(1, in, out);
out.close();
}
}
public static void main(String[] args) throws Exception {
Thread thread = new Thread(null, new TaskAdapter(), "", 1<<29);
thread.start();
thread.join();
}
static class EPermutationSeparation {
public EPermutationSeparation() {
}
public void solve(int kase, InputReader in, Output pw) {
int n = in.nextInt();
int[] arr = in.nextInt(n, (IntUnaryOperator) o -> o-1), cost = new int[n];
for(int i = 0; i<n; i++) {
cost[arr[i]] = in.nextInt();
}
long[] dp = new long[n+1];
dp[0] = cost[arr[0]];
for(int i = 1; i<=n; i++) {
dp[i] = dp[i-1];
if(arr[0]==i-1) {
dp[i] -= cost[i-1];
}else {
dp[i] += cost[i-1];
}
}
Utilities.Debug.dbg(dp);
SegmentTree st = new SegmentTree(dp);
long ans = st.min(0, n);
for(int i = 1; i<n-1; i++) {
int cur = arr[i];
Utilities.Debug.dbg(cur, cost[cur]);
if(cur>0) {
st.add(0, cur, cost[cur]);
}
st.add(cur+1, n, -cost[cur]);
ans = Math.min(ans, st.min(0, n));
}
pw.println(ans);
}
}
static class Utilities {
public static class Debug {
public static final boolean LOCAL = System.getProperty("ONLINE_JUDGE")==null;
private static <T> String ts(T t) {
if(t==null) {
return "null";
}
try {
return ts((Iterable) t);
}catch(ClassCastException e) {
if(t instanceof int[]) {
String s = Arrays.toString((int[]) t);
return "{"+s.substring(1, s.length()-1)+"}";
}else if(t instanceof long[]) {
String s = Arrays.toString((long[]) t);
return "{"+s.substring(1, s.length()-1)+"}";
}else if(t instanceof char[]) {
String s = Arrays.toString((char[]) t);
return "{"+s.substring(1, s.length()-1)+"}";
}else if(t instanceof double[]) {
String s = Arrays.toString((double[]) t);
return "{"+s.substring(1, s.length()-1)+"}";
}else if(t instanceof boolean[]) {
String s = Arrays.toString((boolean[]) t);
return "{"+s.substring(1, s.length()-1)+"}";
}
try {
return ts((Object[]) t);
}catch(ClassCastException e1) {
return t.toString();
}
}
}
private static <T> String ts(T[] arr) {
StringBuilder ret = new StringBuilder();
ret.append("{");
boolean first = true;
for(T t: arr) {
if(!first) {
ret.append(", ");
}
first = false;
ret.append(ts(t));
}
ret.append("}");
return ret.toString();
}
private static <T> String ts(Iterable<T> iter) {
StringBuilder ret = new StringBuilder();
ret.append("{");
boolean first = true;
for(T t: iter) {
if(!first) {
ret.append(", ");
}
first = false;
ret.append(ts(t));
}
ret.append("}");
return ret.toString();
}
public static void dbg(Object... o) {
if(LOCAL) {
System.err.print("Line #"+Thread.currentThread().getStackTrace()[2].getLineNumber()+": [");
for(int i = 0; i<o.length; i++) {
if(i!=0) {
System.err.print(", ");
}
System.err.print(ts(o[i]));
}
System.err.println("]");
}
}
}
}
static class Output implements Closeable, Flushable {
public StringBuilder sb;
public OutputStream os;
public int BUFFER_SIZE;
public boolean autoFlush;
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);
autoFlush = false;
LineSeparator = System.lineSeparator();
}
public void println(long l) {
println(String.valueOf(l));
}
public void println(String s) {
sb.append(s);
println();
if(autoFlush) {
flush();
}else if(sb.length()>BUFFER_SIZE >> 1) {
flushToBuffer();
}
}
public void println() {
sb.append(LineSeparator);
}
private void flushToBuffer() {
try {
os.write(sb.toString().getBytes());
}catch(IOException e) {
e.printStackTrace();
}
sb = new StringBuilder(BUFFER_SIZE);
}
public void flush() {
try {
flushToBuffer();
os.flush();
}catch(IOException e) {
e.printStackTrace();
}
}
public void close() {
flush();
try {
os.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
static interface InputReader {
int nextInt();
default int[] nextInt(int n, IntUnaryOperator operator) {
int[] ret = new int[n];
for(int i = 0; i<n; i++) {
ret[i] = operator.applyAsInt(nextInt());
}
return ret;
}
}
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 min(int l, int r) {
query(l, r);
return _min;
}
}
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++];
}
}
}
| 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.*;
public class Main {
FastScanner fastScanner = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int n, p, k;
long[][] dp;
long[] csum;
List<Data> inp = new ArrayList<Data>();
public void run() throws Exception {
n = fastScanner.nextInt();
p = fastScanner.nextInt();
k = fastScanner.nextInt();
for(int i = 0; i < n; i++){
inp.add(new Data(fastScanner.nextLong()));
}
for(int i = 0; i < n; i++){
long[] tmp = new long[p];
for(int j = 0; j < p; j++){
tmp[j] = fastScanner.nextLong();
}
inp.get(i).setP(tmp);
}
Collections.sort(inp, new Comparator<Data>() {
@Override
public int compare(Data o1, Data o2) {
long diff = o1.getA() - o2.getA();
if(diff > 0) return -1;
else if(diff < 0) return 1;
else {
return 0;
}
}
});
csum = new long[n];
for(int i = 0; i < n; i++){
csum[i] = inp.get(i).getA();
if(i > 0) csum[i] += csum[i - 1];
}
dp = new long[n][1 << p];
for(int i = 0; i < n; i++) {
Arrays.fill(dp[i], -1);
}
out.println(go(0, 0));
out.flush();
}
public long go(int pos, int mask){
if(mask == (1 << p) - 1){
int rem = allOk(pos, p);
long extra = 0;
if(pos + rem <= n && rem > 0){
extra = csum[pos + rem - 1] - csum[pos - 1];
}
return extra;
}
if(pos >= n){
return 0;
}
if(dp[pos][mask] != -1){
return dp[pos][mask];
}
long c = allOk(pos, Integer.bitCount(mask)) > 0 ? inp.get(pos).getA() : 0, d = go(pos + 1, mask);
c += go(pos + 1, mask);
for(int i = 0; i < p; i++){
if((mask & (1 << i)) == 0){
d = Math.max(d, inp.get(pos).getP()[i] + go(pos + 1, mask | (1 << i)));
}
}
return dp[pos][mask] = Math.max(c, d);
}
public int allOk(int pos, int taken){
int lft = pos - taken;
return k - lft;
}
class Data {
long a;
long[] p;
public Data(long a){
this.a = a;
}
public Data(long[] p){
this.p = p;
}
public long getA(){
return this.a;
}
public long[] getP(){
return this.p;
}
public void setA(long a){
this.a = a;
}
public void setP(long[] p){
this.p = p;
}
}
public static void main(String[] args) throws Exception {
new Main().run();
}
static class FastScanner {
public BufferedReader reader;
public StringTokenizer tokenizer;
public FastScanner() {
this.reader = new BufferedReader(new InputStreamReader(System.in), 32768);
tokenizer = null;
}
public String next(){
while (tokenizer == null || !tokenizer.hasMoreTokens()){
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e){
throw new RuntimeException();
}
}
return tokenizer.nextToken();
}
public int nextInt(){
return Integer.parseInt(next());
}
public long nextLong(){
return Long.parseLong(next());
}
public double nextDouble(){
return Double.parseDouble(next());
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e){
throw new RuntimeException();
}
}
}
}
| 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"
] | // package c1324;
//
// Codeforces Round #627 (Div. 3) 2020-03-12 05:05
// D. Pair of Topics
// https://codeforces.com/contest/1324/problem/D
// 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+).*'
//
// The next lecture in a high school requires two topics to be discussed. The i-th topic is
// interesting by a_i units for the teacher and by b_i units for the students.
//
// The pair of topics i and j (i < j) is called if a_i + a_j > b_i + b_j (i.e. it is more
// interesting for the teacher).
//
// Your task is to find the number of pairs of topics.
//
// Input
//
// The first line of the input contains one integer n (2 <= n <= 2 * 10^5) -- the number of topics.
//
// The second line of the input contains n integers a_1, a_2, ..., a_n (1 <= a_i <= 10^9), where a_i
// is the interestingness of the i-th topic for the teacher.
//
// The third line of the input contains n integers b_1, b_2, ..., b_n (1 <= b_i <= 10^9), where b_i
// is the interestingness of the i-th topic for the students.
//
// Output
//
// Print one integer -- the number of pairs of topic.
//
// Example
/*
input:
5
4 8 2 6 2
4 5 4 1 3
output:
7
input:
4
1 3 2 4
1 3 2 4
output:
0
*/
//
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 C1324D {
static final int MOD = 998244353;
static final Random RAND = new Random();
static long solve(int[] a, int[] b) {
int n = a.length;
List<Integer> nums = new ArrayList<>();
for (int i = 0; i < n; i++) {
nums.add(a[i]-b[i]);
}
Collections.sort(nums);
// System.out.format(" nums:%s\n", nums.toString());
long ans = 0;
int j = n;
for (int i = 0; i < n; i++) {
int v = nums.get(i);
j = Math.max(i+1, j);
while (j - 1 > i && nums.get(j-1) + v > 0) {
j--;
}
// System.out.format(" i:%d j:%d\n", i, j);
ans += n - j;
}
return ans;
}
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 n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
int[] b = new int[n];
for (int i = 0; i < n; i++) {
b[i] = in.nextInt();
}
long 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 |
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"
] | /*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
import java.util.*;
/**
*
* @author Caio
*/
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-->0){
long tastinessYasser = 0;
int n = sc.nextInt();
int[] a = new int[n];
boolean flag = true;
for(int i=0; i<n; i++){
a[i] = sc.nextInt();
}
for(int i=0; i < n; i++){
tastinessYasser += a[i];
if(tastinessYasser<=0) flag = false;
}
tastinessYasser = 0;
for(int i=a.length - 1; i>=0; i--){
tastinessYasser += a[i];
if(tastinessYasser<=0) flag = false;
}
System.out.println(flag ? "YES":"NO ");
}
}
}
| 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 code {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-- > 0){
int even = 0;
int n = sc.nextInt();
for(int i = 0;i<n;i++){
int a = sc.nextInt();
if(a % 2 == 0){
even ++;
}
}
System.out.println((even == 0 || even == n)?"YES":"NO");
}
}
} | java |
1141 | E | E. Superhero Battletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA superhero fights with a monster. The battle consists of rounds; each of which lasts exactly nn minutes. After a round ends, the next round starts immediately. This is repeated over and over again.Each round has the same scenario. It is described by a sequence of nn numbers: d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106). The ii-th element means that monster's hp (hit points) changes by the value didi during the ii-th minute of each round. Formally, if before the ii-th minute of a round the monster's hp is hh, then after the ii-th minute it changes to h:=h+dih:=h+di.The monster's initial hp is HH. It means that before the battle the monster has HH hit points. Print the first minute after which the monster dies. The monster dies if its hp is less than or equal to 00. Print -1 if the battle continues infinitely.InputThe first line contains two integers HH and nn (1≤H≤10121≤H≤1012, 1≤n≤2⋅1051≤n≤2⋅105). The second line contains the sequence of integers d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106), where didi is the value to change monster's hp in the ii-th minute of a round.OutputPrint -1 if the superhero can't kill the monster and the battle will last infinitely. Otherwise, print the positive integer kk such that kk is the first minute after which the monster is dead.ExamplesInputCopy1000 6
-100 -200 -300 125 77 -4
OutputCopy9
InputCopy1000000000000 5
-1 0 0 0 0
OutputCopy4999999999996
InputCopy10 4
-3 -6 5 4
OutputCopy-1
| [
"math"
] | import java.util.Scanner;
public class SuperheroBattle {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
long hp = scanner.nextLong();
int length = scanner.nextInt();
int[] minutes = new int[length + 1];
long[] sum = new long[length + 1];
long maxSum = Long.MAX_VALUE;
for (int i = 1; i <= length; i++) {
minutes[i] = scanner.nextInt();
sum[i] = minutes[i] + sum[i - 1];
maxSum = Math.min(sum[i], maxSum);
}
long result = 0;
if (hp + maxSum > 0 && sum[length] >= 0) {
System.out.println(-1);
return;
}
if (-sum[length] != 0 && hp + maxSum > 0) {
long times = (long) Math.ceil((hp + maxSum + 0.0) / -sum[length]);
result += times * length;
hp -= -sum[length] * times;
}
for (int i = 1; i <= length; i++) {
if (sum[i] + hp <= 0) {
result += i;
System.out.println(result);
return;
}
}
System.out.println(-1);
}
}
| java |
1324 | C | C. Frog Jumpstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a frog staying to the left of the string s=s1s2…sns=s1s2…sn consisting of nn characters (to be more precise, the frog initially stays at the cell 00). Each character of ss is either 'L' or 'R'. It means that if the frog is staying at the ii-th cell and the ii-th character is 'L', the frog can jump only to the left. If the frog is staying at the ii-th cell and the ii-th character is 'R', the frog can jump only to the right. The frog can jump only to the right from the cell 00.Note that the frog can jump into the same cell twice and can perform as many jumps as it needs.The frog wants to reach the n+1n+1-th cell. The frog chooses some positive integer value dd before the first jump (and cannot change it later) and jumps by no more than dd cells at once. I.e. if the ii-th character is 'L' then the frog can jump to any cell in a range [max(0,i−d);i−1][max(0,i−d);i−1], and if the ii-th character is 'R' then the frog can jump to any cell in a range [i+1;min(n+1;i+d)][i+1;min(n+1;i+d)].The frog doesn't want to jump far, so your task is to find the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it can jump by no more than dd cells at once. It is guaranteed that it is always possible to reach n+1n+1 from 00.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. The ii-th test case is described as a string ss consisting of at least 11 and at most 2⋅1052⋅105 characters 'L' and 'R'.It is guaranteed that the sum of lengths of strings over all test cases does not exceed 2⋅1052⋅105 (∑|s|≤2⋅105∑|s|≤2⋅105).OutputFor each test case, print the answer — the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it jumps by no more than dd at once.ExampleInputCopy6
LRLRRLL
L
LLR
RRRR
LLLLLL
R
OutputCopy3
2
3
1
7
1
NoteThe picture describing the first test case of the example and one of the possible answers:In the second test case of the example; the frog can only jump directly from 00 to n+1n+1.In the third test case of the example, the frog can choose d=3d=3, jump to the cell 33 from the cell 00 and then to the cell 44 from the cell 33.In the fourth test case of the example, the frog can choose d=1d=1 and jump 55 times to the right.In the fifth test case of the example, the frog can only jump directly from 00 to n+1n+1.In the sixth test case of the example, the frog can choose d=1d=1 and jump 22 times to the right. | [
"binary search",
"data structures",
"dfs and similar",
"greedy",
"implementation"
] | //package com.company;
import com.sun.source.tree.ArrayAccessTree;
import javax.swing.*;
import java.beans.IntrospectionException;
import java.math.BigInteger;
import java.util.*;
import java.io.*;
public class Main {
static class pair implements Comparable<pair> {
long a = 0;
long b = 0;
// int cnt;
pair(long b, long a) {
this.a = b;
this.b = a;
// cnt = x;
}
@Override
public int compareTo(pair o) {
if(this.a != o.a)
return (int) (this.a - o.a);
else
return (int) (this.b - o.b);
}
// public boolean equals(Object o) {
// if (o instanceof pair) {
// pair p = (pair) o;
// return p.a == a && p.b == b;
// }
// return false;
// }
//
// public int hashCode() {
// return (Long.valueOf(a).hashCode()) * 31 + (Long.valueOf(b).hashCode());
// }
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine().trim();
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
}
static class FastWriter {
private final BufferedWriter bw;
public FastWriter() {
this.bw = new BufferedWriter(new OutputStreamWriter(System.out));
}
public void prlong(Object object) throws IOException {
bw.append("" + object);
}
public void prlongln(Object object) throws IOException {
prlong(object);
bw.append("\n");
}
public void close() throws IOException {
bw.close();
}
}
public static long gcd(long a, long b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
//HASHsET COLLISION AVOIDING CODE FOR STORING STRINGS
// HashSet<Long> set = new HashSet<>();
// for(int i = 0; i < s.length(); i++){
// int b = 0;
// long h = 1;
// for(int j=i; j<s.length(); j++){
// h = 131*h + (int)s.charAt(j);
// b += bad[(int)(s.charAt(j)-'a')];
// if(b<=k){
// set.add(h);
// }
// }
// }
// System.out.println(set.size());
//dsu
static int[] par, rank;
public static void dsu(int n) {
par = new int[n];
rank = new int[n];
for (int i = 0; i < n; i++) {
par[i] = i;
rank[i] = 1;
}
}
static int find(int u) {
return par[u] == -1 ? -1 : par[u] == u ? u : (par[u] = find(par[u]));
}
static void union(int u, int v) {
int a = find(u), b = find(v);
if (a != b && a != -1 && b != -1) {
par[b] = a;
rank[a] += rank[b];
}
}
static void disunion(int u, int v) {
int a = find(u), b = find(v);
if (a != -1 && a == b) {
par[a] = -1;
}
}
static class Calc_nCr {
private final long[] fact;
private final long[] invfact;
private final int p;
Calc_nCr(int n, int prime) {
fact = new long[n + 5];
invfact = new long[n + 5];
p = prime;
fact[0] = 1;
for (int i = 1; i <= n; i++) {
fact[i] = (i * fact[i - 1]) % p;
}
invfact[n] = pow(fact[n], p - 2, p);
for (int i = n - 1; i >= 0; i--) {
invfact[i] = (invfact[i + 1] * (i + 1)) % p;
}
}
private long nCr(int n, int r) {
if (r > n || n < 0 || r < 0) return 0;
return (((fact[n] * invfact[r]) % p) * invfact[n - r]) % p;
}
private static long pow(long a, long b, int mod) {
long result = 1;
while (b > 0) {
if ((b & 1L) == 1) {
result = (result * a) % mod;
}
a = (a * a) % mod;
b >>= 1;
}
return result;
}
}
public static void main(String[] args) {
try {
FastReader in = new FastReader();
FastWriter out = new FastWriter();
// int mx=10000000;
// boolean isPrime[] = new boolean[mx+5]; int primeDiv[] = new int[mx+5];
// for (int i = 0; i <= mx; i++) {
// isPrime[i] = true;
// }
// for(int i =0;i<primeDiv.length;i++)
// primeDiv[i]=i;
// isPrime[0] = isPrime[1] = false;
// for (long i = 2; i <= mx; i++) {
// if (isPrime[(int)i]) {
// for (long j = i*i; j <= mx; j += i) {
// if (primeDiv[(int)j] == j) {
// primeDiv[(int)j] = (int)i;
// }
// isPrime[(int)j] = false;
// }
// }
// }
// System.out.println(
// String.format("%.12f", x));
int testCases=in.nextInt();
// int n =in.nextInt();
// long arr[]=new long[n];
// ArrayList<Long>ans=new ArrayList<>();
// for(int i =0;i<n;i++)
//
//
// } ans.add(in.nextLong());
// Collections.sort(ans);
// for(int i =0;i<n;i++)
// arr[i]=ans.get(i);
fl:
while (testCases-- > 0) {
String s =in.next();
s=s+"R";
s="R"+s;
ArrayList<Integer>ans=new ArrayList<>();
for(int i =0;i<s.length();i++)
{
if(s.charAt(i)=='R')
ans.add(i);
}
int f =0;
for(int i=0;i<ans.size()-1;i++)
f=Math.max(f,ans.get(i+1)-ans.get(i));
System.out.println(f);
}
out.close();
} catch (Exception e) {
return;
}
}
static long comb(int r,int n)
{
long result;
result = factorial(n)/(factorial(r)*factorial(n-r));
return result;
}
static long factorial(int n) {
int c;
long result = 1;
for (c = 1; c <= n; c++)
result = result*c;
return result;
}
static void LongestPalindromicPrefix(String str,int lps[]){
// String temp = str + '/';
// str = reverse(str);
// temp += str;
String temp =str;
int n = temp.length();
for(int i = 1; i < n; i++)
{
int len = lps[i - 1];
while (len > 0 && temp.charAt(len) !=
temp.charAt(i))
{
len = lps[len - 1];
}
if (temp.charAt(i) == temp.charAt(len))
{
len++;
}
lps[i] = len;
}
// return temp.substring(0, lps[n - 1]);
}
static String reverse(String input)
{
char[] a = input.toCharArray();
int l, r = a.length - 1;
for(l = 0; l < r; l++, r--)
{
char temp = a[l];
a[l] = a[r];
a[r] = temp;
}
return String.valueOf(a);
}
}
/*
*
* ┏┓ ┏┓+ +
* ┏┛┻━━━┛┻┓ + +
* ┃ ┃
* ┃ ━ ┃ ++ + + +
* ████━████+
* ◥██◤ ◥██◤ +
* ┃ ┻ ┃
* ┃ ┃ + +
* ┗━┓ ┏━┛
* ┃ ┃ JACKS PET FROM ANOTHER WORLD
* ┃ ┃
* ┃ ┗━━━┓
* ┃ ┣┓-------
* ┃ ┏┛-------
* ┗┓┓┏━┳┓┏┛ + + + +
* ┃┫┫ ┃┫┫
* ┗┻┛ ┗┻┛+ + + +
*/
//RULES
//TAKE INPUT AS LONG IN CASE OF SUM OR MULITPLICATION OR CHECK THE CONTSRaint of the array
//Always use stringbuilder of out.println for strinof out.println for string or high level output
// IMPORTANT TRs1 TO USE BRUTE FORCE TECHNIQUE TO SOLVE THE PROs1 OTHER CERTAIN LIMIT IS GIVENIT IS GIVEN
//Read minute details if coming wrong for no idea questions | java |
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 javax.swing.text.Segment;
import java.io.*;
import java.math.*;
import java.sql.Array;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Main {
static class Scanner{
BufferedReader br;
StringTokenizer st;
public Scanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
static long mod = (long)(1e9 + 7);
static void sort(long[] arr ) {
ArrayList<Long> al = new ArrayList<>();
for(long e:arr) al.add(e);
Collections.sort(al);
for(int i = 0 ; i<al.size(); i++) arr[i] = al.get(i);
}
static void sort(int[] arr ) {
ArrayList<Integer> al = new ArrayList<>();
for(int e:arr) al.add(e);
Collections.sort(al);
for(int i = 0 ; i<al.size(); i++) arr[i] = al.get(i);
}
static void sort(char[] arr) {
ArrayList<Character> al = new ArrayList<Character>();
for(char cc:arr) al.add(cc);
Collections.sort(al);
for(int i = 0 ;i<arr.length ;i++) arr[i] = al.get(i);
}
static void rvrs(int[] arr) {
int i =0 , j = arr.length-1;
while(i>=j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
static void rvrs(long[] arr) {
int i =0 , j = arr.length-1;
while(i>=j) {
long temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
static long mod_mul( long mod , long... a) {
long ans = a[0]%mod;
for(int i = 1 ; i<a.length ; i++) {
ans = (ans * (a[i]%mod))%mod;
}
return ans;
}
static long mod_sum(long mod , long... a) {
long ans = 0;
for(long e:a) {
ans = (ans + e)%mod;
}
return ans;
}
static long gcd(long a, long b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static boolean[] prime(int num) {
boolean[] bool = new boolean[num];
for (int i = 0; i< bool.length; i++) {
bool[i] = true;
}
for (int i = 2; i< Math.sqrt(num); i++) {
if(bool[i] == true) {
for(int j = (i*i); j<num; j = j+i) {
bool[j] = false;
}
}
}
if(num >= 0) {
bool[0] = false;
bool[1] = false;
}
return bool;
}
static long modInverse(long a, long m)
{
long g = gcd(a, m);
return power(a, m - 2, m);
}
static long lcm(long a , long b) {
return (a*b)/gcd(a, b);
}
static int lcm(int a , int b) {
return (int)((a*b)/gcd(a, b));
}
static long power(long x, long y, long m){
if (y == 0) return 1; long p = power(x, y / 2, m) % m; p = (int)((p * (long)p) % m);
if (y % 2 == 0) return p; else return (int)((x * (long)p) % m); }
static class Combinations{
private long[] z;
private long[] z1;
private long[] z2;
public Combinations(long N , long mod) {
z = new long[(int)N+1];
z1 = new long[(int)N+1];
z[0] = 1;
for(int i =1 ; i<=N ; i++) z[i] = (z[i-1]*i)%mod;
z2 = new long[(int)N+1];
z2[0] = z2[1] = 1;
for (int i = 2; i <= N; i++)
z2[i] = z2[(int)(mod % i)] * (mod - mod / i) % mod;
z1[0] = z1[1] = 1;
for (int i = 2; i <= N; i++)
z1[i] = (z2[i] * z1[i - 1]) % mod;
}
long fac(long n) {
return z[(int)n];
}
long invrsNum(long n) {
return z2[(int)n];
}
long invrsFac(long n) {
return invrsFac((int)n);
}
long ncr(long N, long R, long mod)
{ if(R<0 || R>N ) return 0;
long ans = ((z[(int)N] * z1[(int)R])
% mod * z1[(int)(N - R)])
% mod;
return ans;
}
}
static class DisjointUnionSets {
int[] rank, parent;
int n;
public DisjointUnionSets(int n)
{
rank = new int[n];
parent = new int[n];
this.n = n;
makeSet();
}
void makeSet()
{
for (int i = 0; i < n; i++) {
parent[i] = i;
}
}
int find(int x)
{
if (parent[x] != x) {
parent[x] = find(parent[x]);
}
return parent[x];
}
void union(int x, int y)
{
int xRoot = find(x), yRoot = find(y);
if (xRoot == yRoot)
return;
if (rank[xRoot] < rank[yRoot])
parent[xRoot] = yRoot;
else if (rank[yRoot] < rank[xRoot])
parent[yRoot] = xRoot;
else
{
parent[yRoot] = xRoot;
rank[xRoot] = rank[xRoot] + 1;
}
}
}
static int max(int... a ) {
int max = a[0];
for(int e:a) max = Math.max(max, e);
return max;
}
static long max(long... a ) {
long max = a[0];
for(long e:a) max = Math.max(max, e);
return max;
}
static int min(int... a ) {
int min = a[0];
for(int e:a) min = Math.min(e, min);
return min;
}
static long min(long... a ) {
long min = a[0];
for(long e:a) min = Math.min(e, min);
return min;
}
static int[] KMP(String str) {
int n = str.length();
int[] kmp = new int[n];
for(int i = 1 ; i<n ; i++) {
int j = kmp[i-1];
while(j>0 && str.charAt(i) != str.charAt(j)) {
j = kmp[j-1];
}
if(str.charAt(i) == str.charAt(j)) j++;
kmp[i] = j;
}
return kmp;
}
/************************************************ Query **************************************************************************************/
/***************************************** Sparse Table ********************************************************/
static class SparseTable{
private long[][] st;
SparseTable(long[] arr){
int n = arr.length;
st = new long[n][25];
log = new int[n+2];
build_log(n+1);
build(arr);
}
private void build(long[] arr) {
int n = arr.length;
for(int i = n-1 ; i>=0 ; i--) {
for(int j = 0 ; j<25 ; j++) {
int r = i + (1<<j)-1;
if(r>=n) break;
if(j == 0 ) st[i][j] = arr[i];
else st[i][j] = Math.max(st[i][j-1] , st[ i + ( 1 << (j-1) ) ][ j-1 ] );
}
}
}
public long gcd(long a ,long b) {
if(a == 0) return b;
return gcd(b%a , a);
}
public long query(int l ,int r) {
int w = r-l+1;
int power = log[w];
return Math.max(st[l][power],st[r - (1<<power) + 1][power]);
}
private int[] log;
void build_log(int n) {
log[1] = 0;
for(int i = 2 ; i<=n ; i++) {
log[i] = 1 + log[i/2];
}
}
}
/******************************************************** Segement Tree *****************************************************/
/**
static class SegmentTree{
long[] tree;
long[] arr;
int n;
SegmentTree(long[] arr){
this.n = arr.length;
tree = new long[4*n+1];
this.arr = arr;
buildTree(0, n-1, 1);
}
void buildTree(int s ,int e ,int index ) {
if(s == e) {
tree[index] = arr[s];
return;
}
int mid = (s+e)/2;
buildTree( s, mid, 2*index);
buildTree( mid+1, e, 2*index+1);
tree[index] = Math.min(tree[2*index] , tree[2*index+1]);
}
long query(int si ,int ei) {
return query(0 ,n-1 , si ,ei , 1 );
}
private long query( int ss ,int se ,int qs , int qe,int index) {
if(ss>=qs && se<=qe) return tree[index];
if(qe<ss || se<qs) return (long)(1e17);
int mid = (ss + se)/2;
long left = query( ss , mid , qs ,qe , 2*index);
long right= query(mid + 1 , se , qs ,qe , 2*index+1);
return Math.min(left, right);
}
public void update(int index , int val) {
arr[index] = val;
for(long e:arr) System.out.print(e+" ");
update(index , 0 , n-1 , 1);
}
private void update(int id ,int si , int ei , int index) {
if(id < si || id>ei) return;
if(si == ei ) {
tree[index] = arr[id];
return;
}
if(si > ei) return;
int mid = (ei + si)/2;
update( id, si, mid , 2*index);
update( id , mid+1, ei , 2*index+1);
tree[index] = Math.min(tree[2*index] ,tree[2*index+1]);
}
}
*/
/* ***************************************************************************************************************************************************/
static Scanner sc = new Scanner();
static StringBuilder sb = new StringBuilder();
public static void main(String args[]) throws IOException {
int tc = 1;
tc = sc.nextInt();
for(int i = 1 ; i<=tc ; i++) {
// sb.append("Case #" + i + ": " ); // During KickStart && HackerCup
TEST_CASE();
}
System.out.println(sb);
}
static void TEST_CASE() {
int n = sc.nextInt();
int m = sc.nextInt();
int k = sc.nextInt();
int pos = 1;
int[] arr = new int[n];
for(int i = 0 ; i<n ; i++) {
arr[i] = sc.nextInt();
}
// int l = 0 , r = n-1;
int[][] dp = new int[n][n];
if(k>=m) {
int l = 0 , r = n-1;
int ans = 0;
while(m-- > 0 ) {
ans = max(ans , arr[l] , arr[r]);
l++;
r--;
}
sb.append(ans+"\n");
return;
}
boolean[][] visit = new boolean[n][n];
int ans = 0;
for(int i = 0 ; i<=k ; i++) {
int rem = k - i;
int r = n - rem-1;
int l = i;
int ma = fnc(k+1, m, arr, l, r, visit, dp);
// System.out.println(l+" "+r +" "+(k+1)+" "+ma);
ans = max(ans ,ma);
}
sb.append(ans+"\n");
}
static int fnc(int pos , int m,int[] arr,int l ,int r , boolean[][] visit ,int[][] dp) {
if(l == arr.length || r < 0) return (int)(1e9);
if(pos == m) {
return max(arr[l] , arr[r]);
}
if(visit[l][r]) return dp[l][r];
int min1 = fnc(pos+1 , m ,arr , l+1 ,r , visit , dp );
int min2 = fnc(pos+1 , m ,arr , l , r-1, visit , dp );
visit[l][r] = true;
return dp[l][r] = min(min1 , min2);
}
}
/*******************************************************************************************************************************************************/
/**
*/
| 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.util.*;
import java.io.*;
public class Array {
public static void mergeSort(int[] array) {
if (array == null) {
return;
}
if (array.length > 1) {
int mid = array.length / 2;
// Split left part
int[] left = new int[mid];
for (int i = 0; i < mid; i++) {
left[i] = array[i];
}
// Split right part
int[] right = new int[array.length - mid];
for (int i = mid; i < array.length; i++) {
right[i - mid] = array[i];
}
mergeSort(left);
mergeSort(right);
int i = 0;
int j = 0;
int k = 0;
// Merge left and right arrays
while (i < left.length && j < right.length) {
if (left[i] < right[j]) {
array[k] = left[i];
i++;
} else {
array[k] = right[j];
j++;
}
k++;
}
// Collect remaining elements
while (i < left.length) {
array[k] = left[i];
i++;
k++;
}
while (j < right.length) {
array[k] = right[j];
j++;
k++;
}
}
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = sc.nextInt();
int[] a = sc.nextIntArray(n-1);
int last= 200000;
int [] arr= new int[n];
arr[n-1]=last;
int min=last;
for (int i=n-2;i>=0;i--) {
arr[i]=arr[i+1]-a[i];
min=Math.min(min, arr[i]);
}
for (int i=0;i<n;i++) {
arr[i]-=(min-1);
//pw.println(arr[i]);
}
int[] newArr=arr.clone();
mergeSort(newArr);
boolean flag= true;
for (int i=0;i<n;i++) {
if(newArr[i]-1!=i) {
pw.println(-1);
flag= false;
break;
}
}
if(flag) {
for (int i=0;i<n;i++)
pw.print(arr[i]+" ");
}
pw.flush();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(String file) throws IOException {
br = new BufferedReader(new FileReader(file));
}
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
protected String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String readAllLines(BufferedReader reader) throws IOException {
StringBuilder content = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
content.append(line);
content.append(System.lineSeparator());
}
return content.toString();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public long[] nextlongArray(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public Long[] nextLongArray(int n) throws IOException {
Long[] a = new Long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public int[] nextIntArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public Integer[] nextIntegerArray(int n) throws IOException {
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public boolean ready() throws IOException {
return br.ready();
}
}
}
| java |
1288 | A | A. Deadlinetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAdilbek was assigned to a special project. For Adilbek it means that he has nn days to run a special program and provide its results. But there is a problem: the program needs to run for dd days to calculate the results.Fortunately, Adilbek can optimize the program. If he spends xx (xx is a non-negative integer) days optimizing the program, he will make the program run in ⌈dx+1⌉⌈dx+1⌉ days (⌈a⌉⌈a⌉ is the ceiling function: ⌈2.4⌉=3⌈2.4⌉=3, ⌈2⌉=2⌈2⌉=2). The program cannot be run and optimized simultaneously, so the total number of days he will spend is equal to x+⌈dx+1⌉x+⌈dx+1⌉.Will Adilbek be able to provide the generated results in no more than nn days?InputThe first line contains a single integer TT (1≤T≤501≤T≤50) — the number of test cases.The next TT lines contain test cases – one per line. Each line contains two integers nn and dd (1≤n≤1091≤n≤109, 1≤d≤1091≤d≤109) — the number of days before the deadline and the number of days the program runs.OutputPrint TT answers — one per test case. For each test case print YES (case insensitive) if Adilbek can fit in nn days or NO (case insensitive) otherwise.ExampleInputCopy3
1 1
4 5
5 11
OutputCopyYES
YES
NO
NoteIn the first test case; Adilbek decides not to optimize the program at all; since d≤nd≤n.In the second test case, Adilbek can spend 11 day optimizing the program and it will run ⌈52⌉=3⌈52⌉=3 days. In total, he will spend 44 days and will fit in the limit.In the third test case, it's impossible to fit in the limit. For example, if Adilbek will optimize the program 22 days, it'll still work ⌈112+1⌉=4⌈112+1⌉=4 days. | [
"binary search",
"brute force",
"math",
"ternary search"
] | import java.util.Scanner;
public class Task1 {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int repeats = scn.nextInt();
for (int i = 0; i < repeats; i++) {
int n = scn.nextInt(); //5
int d = scn.nextInt();
if(d<=n){
System.out.println("YES");
continue;
}
int x = 1;
int c = func(x,d);
int c1 = func(x+1,d);
while (x<d && c >= c1 ) {
x++;
c = c1;
c1 = func(x+1,d);
}
if (c <= n) {
System.out.println("YES");
}else {
System.out.println("NO");
}
}
}
public static int func(int x, int d){
return (int) (x + Math.ceil(d / (x + 1.0)));
}
} | java |
1295 | A | A. Display The Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a large electronic screen which can display up to 998244353998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of 77 segments which can be turned on and off to compose different digits. The following picture describes how you can display all 1010 decimal digits:As you can see, different digits may require different number of segments to be turned on. For example, if you want to display 11, you have to turn on 22 segments of the screen, and if you want to display 88, all 77 segments of some place to display a digit should be turned on.You want to display a really large integer on the screen. Unfortunately, the screen is bugged: no more than nn segments can be turned on simultaneously. So now you wonder what is the greatest integer that can be displayed by turning on no more than nn segments.Your program should be able to process tt different test cases.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases in the input.Then the test cases follow, each of them is represented by a separate line containing one integer nn (2≤n≤1052≤n≤105) — the maximum number of segments that can be turned on in the corresponding testcase.It is guaranteed that the sum of nn over all test cases in the input does not exceed 105105.OutputFor each test case, print the greatest integer that can be displayed by turning on no more than nn segments of the screen. Note that the answer may not fit in the standard 3232-bit or 6464-bit integral data type.ExampleInputCopy2
3
4
OutputCopy7
11
| [
"greedy"
] |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class Vc {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
int numberSets = Integer.parseInt(br.readLine());
for (int nos = 0; nos < numberSets; nos++) {
// int [] data = Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
int number = Integer.parseInt(br.readLine());
StringBuilder sb = new StringBuilder();
if (number%2 == 0) {
for (int i = 0; i < number/2; i++) {
sb.append("1");
}
System.out.println(sb.toString());
} else {
sb.append("7");
for (int i = 0; i < (number-3)/2; i++) {
sb.append("1");
}
System.out.println(sb.toString());
}
}
}
} | java |
1296 | E1 | E1. String Coloring (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an easy 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 one of the two 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 say if it is possible to color the given string 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≤2001≤n≤200) — the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIf it is impossible to color the given string so that after coloring it can become sorted by some sequence of swaps, print "NO" (without quotes) in the first line.Otherwise, print "YES" in the first line and any correct coloring in the second line (the coloring is the string consisting of nn characters, the ii-th character should be '0' if the ii-th character is colored the first color and '1' otherwise).ExamplesInputCopy9
abacbecfd
OutputCopyYES
001010101
InputCopy8
aaabbcbb
OutputCopyYES
01011011
InputCopy7
abcdedc
OutputCopyNO
InputCopy5
abcde
OutputCopyYES
00000
| [
"constructive algorithms",
"dp",
"graphs",
"greedy",
"sortings"
] | import java.io.*;
import java.util.*;
public class E {
static ArrayList<Integer>[] grf;
static int[] color;
static boolean isBipartite = true;
static void dfs(int ver, boolean[] vis, int c){
color[ver] = c;
vis[ver] = true;
for(int chld: grf[ver]){
if(color[chld] == -1 || color[chld] == (c^1)){
if(!vis[chld]) dfs(chld, vis, c^1);
}
else{
isBipartite = false;
return;
}
}
}
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
//int tst = Integer.parseInt(br.readLine());
int tst = 1;
while(tst-->0){
int n = Integer.parseInt(br.readLine());
char[] arr = br.readLine().toCharArray();
grf = new ArrayList[n];
char[] sorted = new char[n];
for(int i = 0; i<n; i++){
sorted[i] = arr[i];
grf[i] = new ArrayList<>();
}
Arrays.sort(sorted);
color = new int[n];
//make a grf and check if its bipartite
boolean[] assigned = new boolean[n];
int u = -1;
for(int i = 0; i<n; i++){
for(int j = i+1; j<n; j++){
if(arr[i] > arr[j]){
grf[i].add(j);
grf[j].add(i);
}
}
}
Arrays.fill(color, -1);
boolean[] vis = new boolean[n];
for(int i = 0; i<n; i++){
if(vis[i] == false) dfs(i, vis, 0);
}
if(isBipartite){
sb.append("YES").append('\n');
for(int c: color) {
if(c == -1) sb.append(0);
else sb.append(c);
}
sb.append('\n');
}
else sb.append("NO").append('\n');
}
System.out.println(sb);
}
}
| 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.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
public class F {
static int n, m, k;
static int[][] ani; // animals
public static void main(String[] args) {
var scanner = new BufferedScanner();
var writer = new PrintWriter(new BufferedOutputStream(System.out));
n = scanner.nextInt();
m = scanner.nextInt();
k = scanner.nextInt();
ani = new int[n + 1][m + 1];
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
ani[i][j] = scanner.nextInt();
}
}
// System.out.println(watch(1, 1, 1));
writer.println(solve());
scanner.close();
writer.flush();
writer.close();
}
private static int solve() {
dfsCache = new int[n + 1][m + 1];
for (var i = 1; i <= n; i++) {
Arrays.fill(dfsCache[i], -1);
}
var ans = 0;
for (int start = 1; start + k - 1 <= m; start++) {
ans = Math.max(ans, dfs(2, start) + range(1, start, start + k - 1));
}
return ans;
}
static int[][] dfsCache;
private static int dfs(int row, int lastStart) {
if (row > n) {
return 0;
}
if (dfsCache[row][lastStart] >= 0) {
return dfsCache[row][lastStart];
}
var ans = 0;
// TODO 2020/4/9: 这里m太大,两层搜索就受不了
// for (int thisStart = 1; thisStart + k - 1 <= m; thisStart++) {
// var ans1 = dfs(row + 1, thisStart)
// + watch(row, lastStart, thisStart);
// ans = Math.max(ans, ans1);
// }
var lastEnd = lastStart + k - 1;
// no intersection
{
int ans0 = leftMax(row, lastStart - 1);
ans = Math.max(ans, ans0 + range(row, lastStart, lastEnd));
}
{
int ans0 = rightMax(row, lastEnd + 1);
ans = Math.max(ans, ans0 + range(row, lastStart, lastEnd));
}
// intersected
for (int thisStart = Math.max(1, lastStart - k + 1);
thisStart <= lastEnd && thisStart + k - 1 <= m; thisStart++) {
var ans1 = dfs(row + 1, thisStart)
+ watch(row, lastStart, thisStart);
ans = Math.max(ans, ans1);
}
return dfsCache[row][lastStart] = ans;
}
static int[][] rightMaxCache;
static int[] rightMaxAlready;
private static int rightMax(int row, int minStart) {
if (minStart + k - 1 > m) {
return 0;
}
if (rightMaxCache == null) {
rightMaxCache = new int[n + 1][m + 2];
rightMaxAlready = new int[n + 1];
Arrays.fill(rightMaxAlready, m - k + 2);
for (int i = 1; i <= n; i++) {
Arrays.fill(rightMaxCache[i], -1);
rightMaxCache[i][m - k + 2] = 0;
}
}
// System.out.println("row = " + row + ", minStart = " + minStart);
if (rightMaxCache[row][minStart] >= 0) {
return rightMaxCache[row][minStart];
}
var ans0 = rightMaxCache[row][rightMaxAlready[row]];
for (int start = rightMaxAlready[row] - 1; start >= minStart; start--) {
if (rightMaxCache[row][start] >= 0) {
continue;
}
var end = start + k - 1;
var ans1 = dfs(row + 1, start) + range(row, start, end);
rightMaxCache[row][start] = Math.max(rightMaxCache[row][start + 1], ans1);
ans0 = Math.max(ans0, ans1);
}
rightMaxAlready[row] = minStart;
assert ans0 == rightMaxCache[row][minStart];
return ans0;
}
static int[][] leftMaxCache;
static int[] leftMaxAlready;
private static int leftMax(int row, int maxEnd) {
var maxStart = maxEnd - k + 1;
if (maxStart <= 0) {
return 0;
}
if (leftMaxCache == null) {
leftMaxCache = new int[n + 1][m + 1];
leftMaxAlready = new int[n + 1];
Arrays.fill(leftMaxAlready, 0);
for (int i = 1; i <= n; i++) {
Arrays.fill(leftMaxCache[i], -1);
leftMaxCache[i][0] = 0;
}
}
if (leftMaxCache[row][maxStart] >= 0) {
return leftMaxCache[row][maxStart];
}
var ans0 = leftMaxCache[row][leftMaxAlready[row]];
// leftMaxCache[row][k - 1] = 0;
for (int start = leftMaxAlready[row] + 1; start <= maxStart; start++) {
var end = start + k - 1;
if (leftMaxCache[row][start] >= 0) {
continue;
}
var ans1 = dfs(row + 1, start) + range(row, start, end);
leftMaxCache[row][start] = Math.max(leftMaxCache[row][start - 1], ans1);
ans0 = Math.max(ans0, ans1);
}
leftMaxAlready[row] = maxStart;
// System.out.println("row = " + row + ", maxEnd = " + maxEnd);
assert ans0 == leftMaxCache[row][maxStart];
// return ans0;
return leftMaxCache[row][maxStart];
}
private static int watch(int row, int start1, int start2) {
// System.out.println("row = " + row + ", start1 = " + start1 + ", start2 = " + start2);
if (start1 > start2) {
return watch(row, start2, start1);
}
var end2 = start2 + k - 1;
if (start1 <= 0) {
return range(row, start2, end2);
}
var end1 = start1 + k - 1;
if (end2 < start1 || end1 < start2) {
return range(row, start1, end1) + range(row, start2, end2);
}
return range(row, start1, end1) + range(row, start2, end2)
- range(row, start2, Math.min(end1, end2));
}
static int[][] rangeCache;
private static int range(int row, int start, int end) {
if (start <= 0 || start > end) {
return 0;
}
if (rangeCache == null) {
rangeCache = new int[n + 1][m + 1];
for (int i = 1; i <= n; i++) {
rangeCache[i][0] = 0;
for (int j = 1; j <= m; j++) {
rangeCache[i][j] = rangeCache[i][j - 1] + ani[i][j];
}
}
}
debug("range(%d,%d)=%d", start, end, rangeCache[row][end] - rangeCache[row][start - 1]);
return rangeCache[row][end] - rangeCache[row][start - 1];
}
static final boolean DEBUG = false;
private static void debug(String fmt, Object... args) {
if (DEBUG) {
System.out.println(String.format(fmt, args));
}
}
public static class BufferedScanner {
BufferedReader br;
StringTokenizer st;
public BufferedScanner(Reader reader) {
br = new BufferedReader(reader);
}
public BufferedScanner() {
this(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
void close() {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
static long gcd(long a, long b) {
if (a < b) {
return gcd(b, a);
}
while (b > 0) {
long tmp = b;
b = a % b;
a = tmp;
}
return a;
}
static long inverse(long a, long m) {
long[] ans = extgcd(a, m);
return ans[0] == 1 ? (ans[1] + m) % m : -1;
}
private static long[] extgcd(long a, long m) {
if (m == 0) {
return new long[]{a, 1, 0};
} else {
long[] ans = extgcd(m, a % m);
long tmp = ans[1];
ans[1] = ans[2];
ans[2] = tmp;
ans[2] -= ans[1] * (a / m);
return ans;
}
}
private static List<Integer> primes(double upperBound) {
var limit = (int) Math.sqrt(upperBound);
var isComposite = new boolean[limit + 1];
var primes = new ArrayList<Integer>();
for (int i = 2; i <= limit; i++) {
if (isComposite[i]) {
continue;
}
primes.add(i);
int j = i + i;
while (j <= limit) {
isComposite[j] = true;
j += i;
}
}
return primes;
}
}
| java |
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, m = 0;
static int[] a, lp, primes, ind, d, p;
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;
primes = new int[N + 1]; primes[0] = 1;
ind = new int[N + 1]; primes[1] = m++;
for (int i = 2; i <= N; i++) {
if (lp[i] == 0) {
lp[i] = i;
primes[m] = i;
ind[i] = m++;
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[m];
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[m];
p = new int[m];
for (int i = 1; i <= sq; i++) {
if (lp[i] != i) continue;
for (int v = 0; v < m; 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 |
1316 | C | C. Primitive Primestime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is Professor R's last class of his teaching career. Every time Professor R taught a class; he gave a special problem for the students to solve. You being his favourite student, put your heart into solving it one last time.You are given two polynomials f(x)=a0+a1x+⋯+an−1xn−1f(x)=a0+a1x+⋯+an−1xn−1 and g(x)=b0+b1x+⋯+bm−1xm−1g(x)=b0+b1x+⋯+bm−1xm−1, with positive integral coefficients. It is guaranteed that the cumulative GCD of the coefficients is equal to 11 for both the given polynomials. In other words, gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1. Let h(x)=f(x)⋅g(x)h(x)=f(x)⋅g(x). Suppose that h(x)=c0+c1x+⋯+cn+m−2xn+m−2h(x)=c0+c1x+⋯+cn+m−2xn+m−2. You are also given a prime number pp. Professor R challenges you to find any tt such that ctct isn't divisible by pp. He guarantees you that under these conditions such tt always exists. If there are several such tt, output any of them.As the input is quite large, please use fast input reading methods.InputThe first line of the input contains three integers, nn, mm and pp (1≤n,m≤106,2≤p≤1091≤n,m≤106,2≤p≤109), — nn and mm are the number of terms in f(x)f(x) and g(x)g(x) respectively (one more than the degrees of the respective polynomials) and pp is the given prime number.It is guaranteed that pp is prime.The second line contains nn integers a0,a1,…,an−1a0,a1,…,an−1 (1≤ai≤1091≤ai≤109) — aiai is the coefficient of xixi in f(x)f(x).The third line contains mm integers b0,b1,…,bm−1b0,b1,…,bm−1 (1≤bi≤1091≤bi≤109) — bibi is the coefficient of xixi in g(x)g(x).OutputPrint a single integer tt (0≤t≤n+m−20≤t≤n+m−2) — the appropriate power of xx in h(x)h(x) whose coefficient isn't divisible by the given prime pp. If there are multiple powers of xx that satisfy the condition, print any.ExamplesInputCopy3 2 2
1 1 2
2 1
OutputCopy1
InputCopy2 2 999999937
2 1
3 1
OutputCopy2NoteIn the first test case; f(x)f(x) is 2x2+x+12x2+x+1 and g(x)g(x) is x+2x+2, their product h(x)h(x) being 2x3+5x2+3x+22x3+5x2+3x+2, so the answer can be 1 or 2 as both 3 and 5 aren't divisible by 2.In the second test case, f(x)f(x) is x+2x+2 and g(x)g(x) is x+3x+3, their product h(x)h(x) being x2+5x+6x2+5x+6, so the answer can be any of the powers as no coefficient is divisible by the given prime. | [
"constructive algorithms",
"math",
"ternary search"
] | import java.io.*;
import java.util.*;
public class C {
public static void main (String[] args) throws IOException {
Kattio io = new Kattio();
int n = io.nextInt();
int m = io.nextInt();
long p = io.nextLong();
long[] a = new long[n];
long[] b = new long[m];
int inda = -1;
int indb = -1;
for (int i=0; i<n; i++) {
a[i] = io.nextLong();
if (a[i]%p != 0 && inda == -1) {
inda = i;
}
}
for (int i=0; i<m; i++) {
b[i] = io.nextLong();
if (b[i]%p != 0 && indb == -1) {
indb = i;
}
}
System.out.println(inda + indb);
}
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 |
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 MyClass {
public static void main(String args[])
{
Scanner kb = new Scanner(System.in);
int t = kb.nextInt();
while(t-- > 0)
{
String a = kb.next();
String b = kb.next();
String c = kb.next();
boolean flag = true;
for(int i=0;i<a.length();i++)
{
char c1 = a.charAt(i);
char c2 = b.charAt(i);
char c3 = c.charAt(i);
if(!(c1==c3 ||c2==c3))
{
flag = false;
break;
}
}
if(flag)
{
System.out.println("YES");
}
else
{
System.out.println("NO");
}
}
}
} | java |
1305 | F | F. Kuroni and the Punishmenttime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is very angry at the other setters for using him as a theme! As a punishment; he forced them to solve the following problem:You have an array aa consisting of nn positive integers. An operation consists of choosing an element and either adding 11 to it or subtracting 11 from it, such that the element remains positive. We say the array is good if the greatest common divisor of all its elements is not 11. Find the minimum number of operations needed to make the array good.Unable to match Kuroni's intellect, the setters failed to solve the problem. Help them escape from Kuroni's punishment!InputThe first line contains an integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of elements in the array.The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤10121≤ai≤1012) — the elements of the array.OutputPrint a single integer — the minimum number of operations required to make the array good.ExamplesInputCopy3
6 2 4
OutputCopy0
InputCopy5
9 8 7 3 1
OutputCopy4
NoteIn the first example; the first array is already good; since the greatest common divisor of all the elements is 22.In the second example, we may apply the following operations: Add 11 to the second element, making it equal to 99. Subtract 11 from the third element, making it equal to 66. Add 11 to the fifth element, making it equal to 22. Add 11 to the fifth element again, making it equal to 33. The greatest common divisor of all elements will then be equal to 33, so the array will be good. It can be shown that no sequence of three or less operations can make the array good. | [
"math",
"number theory",
"probabilities"
] | import java.io.*;
import java.util.*;
public class A {
FastScanner in;
PrintWriter out;
long findAns(long[] a, long prime) {
long res = 0;
for (long x : a) {
long z = x / prime * prime;
long diff = z == 0 ? prime - x : Math.min(x - z, z + prime - x);
res += diff;
}
return res;
}
void solve() {
int n = in.nextInt();
long[] a = new long[n];
Random rnd = new Random(123);
for (int i = 0; i < n; i++) {
a[i] = in.nextLong();
}
long ans = n * 2;
boolean[] checked = new boolean[n];
long START = System.currentTimeMillis();
HashSet<Long> primes = new HashSet<>();
while (System.currentTimeMillis() - START < 1500) {
int id = rnd.nextInt(n);
if (checked[id]) {
continue;
}
checked[id] = true;
for (long val = a[id] - 3; val <= a[id] + 3; val++) {
if (val < 2) {
continue;
}
long tmp = val;
for (long x = 2; x * x <= tmp; x++) {
if (tmp % x == 0) {
if (!primes.contains(x)) {
primes.add(x);
ans = Math.min(ans, findAns(a, x));
}
while (tmp % x == 0) {
tmp /= x;
}
}
}
if (tmp != 1) {
if (!primes.contains(tmp)) {
primes.add(tmp);
ans = Math.min(ans, findAns(a, tmp));
}
}
}
}
out.println(ans);
}
void run() {
try {
in = new FastScanner(new File("A.in"));
out = new PrintWriter(new File("A.out"));
solve();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
void runIO() {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
solve();
out.close();
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f));
}
String next() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
boolean hasMoreTokens() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return false;
st = new StringTokenizer(s);
}
return true;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
public static void main(String[] args) {
new A().runIO();
}
} | 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.util.Scanner;
import java.util.Arrays;
public class JavaApplication2 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n, AND=0, frq[] = new int[35], t, best=0, mx=0;
n = in.nextInt();
int []a=new int [n];
for (int i = 0; i <= 30; ++i) {
AND |= (1 << i);
}
for (int i = 0; i < n; ++i) {
a[i] = in.nextInt();
for (int j = 0; j < 30; ++j) {
if ((a[i]&(1 << j)) != 0) {
frq[j]++;
}
}
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < 30; ++j) {
if ((a[i] & (1 << j)) != 0) {
AND &= ~(1 << j);
} else {
AND &= (1 << j);
}
}
}
for (int i = 0; i < n; ++i) {
int tmp_AND = AND;
for (int j = 0; j <= 30; ++j) {
if ((a[i]&(1 << j)) != 0 && frq[j] == 1) {
tmp_AND |= (1 << j);
}
}
if (mx < (tmp_AND)) {
mx = (tmp_AND);
best = i;
}
}
System.out.print(a[best] + " ");
for (int i = 0; i < n; ++i) {
if (i == best) {
continue;
}
System.out.print(a[i] + " ");
}
}
}
| 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.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int t = sc.nextInt(), n;
int a[] = new int[100];
boolean c;
while(t -- > 0){
c = true;
n = sc.nextInt();
for(int i = 0; i < n; i ++) a[i] = sc.nextInt();
if(n == 1) System.out.println("YES");
else{
if(a[0] % 2 == 0){
for(int i = 1; i < n; i ++){
if(a[i] % 2 != 0){
c = false;
break;
}
}
}
else{
for(int i = 1; i < n; i ++){
if(a[i] % 2 == 0){
c = false;
break;
}
}
}
System.out.println(c ? "YES" : "NO");
}
}
sc.close();
}
} | java |
13 | E | E. Holestime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to play a lot. Most of all he likes to play a game «Holes». This is a game for one person with following rules:There are N holes located in a single row and numbered from left to right with numbers from 1 to N. Each hole has it's own power (hole number i has the power ai). If you throw a ball into hole i it will immediately jump to hole i + ai; then it will jump out of it and so on. If there is no hole with such number, the ball will just jump out of the row. On each of the M moves the player can perform one of two actions: Set the power of the hole a to value b. Throw a ball into the hole a and count the number of jumps of a ball before it jump out of the row and also write down the number of the hole from which it jumped out just before leaving the row. Petya is not good at math, so, as you have already guessed, you are to perform all computations.InputThe first line contains two integers N and M (1 ≤ N ≤ 105, 1 ≤ M ≤ 105) — the number of holes in a row and the number of moves. The second line contains N positive integers not exceeding N — initial values of holes power. The following M lines describe moves made by Petya. Each of these line can be one of the two types: 0 a b 1 a Type 0 means that it is required to set the power of hole a to b, and type 1 means that it is required to throw a ball into the a-th hole. Numbers a and b are positive integers do not exceeding N.OutputFor each move of the type 1 output two space-separated numbers on a separate line — the number of the last hole the ball visited before leaving the row and the number of jumps it made.ExamplesInputCopy8 51 1 1 1 1 2 8 21 10 1 31 10 3 41 2OutputCopy8 78 57 3 | [
"data structures",
"dsu"
] | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class holes {
static int[] arr;
static int[] nxt;
static int[] cnt;
static int[] nxtseg;
static int n,m;
static int sqrt;
public static void main(String[] args) {
FastScanner fs=new FastScanner();
PrintWriter out = new PrintWriter(System.out);
n = fs.nextInt() ; m = fs.nextInt();
sqrt = (int)Math.sqrt(n);
arr = fs.readArray(n);
nxt = new int[n];
cnt = new int[n];
nxtseg = new int[n];//yaha se next segment me pehla kon milega
for(int i=n-1 ;i>=0 ;i--){
update(i);
}
// System.out.println("here");
while(m-->0){
if(fs.nextInt()==1){
int ind = fs.nextInt()-1;
int ans=0,last=ind;
while(ind!=n){
ans += cnt[ind];
last = nxtseg[ind];
ind = nxt[ind];
}
out.println(last+1 +" " + ans);
}else{
int ind = fs.nextInt()-1;
arr[ind] = fs.nextInt();
for(int j = ind ; j/sqrt == ind/sqrt && j>=0; j--){
update(j);
}
}
// System.out.println("wh "+ m);
}
out.close();
}
public static void update(int ind){
int nextind = ind + arr[ind];
if(nextind>=n){
nxt[ind] = n;
cnt[ind] = 1;
nxtseg[ind] = ind;
}else if(ind/sqrt == nextind/sqrt){
nxtseg[ind] = nxtseg[nextind];
cnt[ind] = 1 + cnt[nextind];
nxt[ind] = nxt[nextind];
}else{
nxt[ind] = nxtseg[ind] = nextind;
cnt[ind] = 1;
}
}
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());
}
}
}
| 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.IOException;
import java.io.InputStreamReader;
import java.util.*;
import java.util.Map.Entry;
public class Solution2 {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static boolean isPrime(long n)
{
// Corner cases
if (n <= 1)
return false;
if (n <= 3)
return true;
// This is checked so that we can skip
// middle five numbers in below loop
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;
}
public static int gcd(int a, int b) {
int t;
while(b != 0){
t = a;
a = b;
b = t%b;
}
return a;
}
public static boolean relativelyPrime(int a, int b) {
return gcd(a,b) == 1;
}
static int __gcd(int a, int b)
{
return b == 0? a:__gcd(b, a % b);
}
// recursive implementation
static int GcdOfArray(int[] arr, int idx)
{
if (idx == arr.length - 1) {
return arr[idx];
}
int a = arr[idx];
int b = GcdOfArray(arr, idx + 1);
return __gcd(
a, b); // __gcd(a,b) is inbuilt library function
}
public static class Pair{
long a;
long b;
Pair(long a, long b){
this.a = a;
this.b = b;
}
}
static int merge(ArrayList<int[]> intervals){
int[] temp = new int[2];
temp[0] = intervals.get(0)[0];
temp[1] = intervals.get(0)[1];
ArrayList<int[]> ls = new ArrayList<>();
ls.add(temp);
int j = 0;
for(int i=0; i<intervals.size()-1; i++){
if((temp[1]>=intervals.get(i+1)[0] && temp[1]<=intervals.get(i+1)[1]) || (temp[0]>=intervals.get(i+1)[0] && temp[0]<=intervals.get(i+1)[1])){
if(temp[0]<intervals.get(i+1)[0]) temp[0] = intervals.get(i+1)[0];
if(temp[1]>intervals.get(i+1)[1]) temp[1] = intervals.get(i+1)[1];
}
else{
return 0;
}
}
// for(int[] arr: ls) {
// System.out.println(arr[0] + " " + arr[1]);
// }
return Math.abs(temp[1]-temp[0]);
}
public static void main(String[] args) throws Exception{
FastReader sc = new FastReader();
int t = sc.nextInt();
while(t-- > 0) {
long n = sc.nextLong();
long x = sc.nextLong();
long y = sc.nextLong();
long total = x + y;
long a = x==1&&y==1 ? total - 2 : total - 1;
if(a<=0) a = 1;
if(a>n) a = n;
if(a<y) {
a++;
}
long worst = a;
long b = y==n&&x==n ? n-1 : n;
long c = total - b + 1;
if(c<=0) c = 1;
if(c>n) c = n;
System.out.println(c + " " + worst);
// for(int i=1; i<n+1; i++) {
// if(i!=x) {
// if(j!=y && j>0) {
// if(total<i+j) ans++;
// j--;
// }
// else {
// j--;
// }
// }
// }1
// 1000000000 1 1000000000
// System.out.println(ans + " " + Integer.valueOf(n-ans));
}
}
}
| java |
1305 | F | F. Kuroni and the Punishmenttime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is very angry at the other setters for using him as a theme! As a punishment; he forced them to solve the following problem:You have an array aa consisting of nn positive integers. An operation consists of choosing an element and either adding 11 to it or subtracting 11 from it, such that the element remains positive. We say the array is good if the greatest common divisor of all its elements is not 11. Find the minimum number of operations needed to make the array good.Unable to match Kuroni's intellect, the setters failed to solve the problem. Help them escape from Kuroni's punishment!InputThe first line contains an integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of elements in the array.The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤10121≤ai≤1012) — the elements of the array.OutputPrint a single integer — the minimum number of operations required to make the array good.ExamplesInputCopy3
6 2 4
OutputCopy0
InputCopy5
9 8 7 3 1
OutputCopy4
NoteIn the first example; the first array is already good; since the greatest common divisor of all the elements is 22.In the second example, we may apply the following operations: Add 11 to the second element, making it equal to 99. Subtract 11 from the third element, making it equal to 66. Add 11 to the fifth element, making it equal to 22. Add 11 to the fifth element again, making it equal to 33. The greatest common divisor of all elements will then be equal to 33, so the array will be good. It can be shown that no sequence of three or less operations can make the array good. | [
"math",
"number theory",
"probabilities"
] | import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.StringTokenizer;
import java.util.stream.Collectors;
public class C1305F {
public static void main(String[] args) {
var scanner = new BufferedScanner();
var writer = new PrintWriter(new BufferedOutputStream(System.out));
var n = scanner.nextInt();
var a = new long[n];
for (int i = 0; i < a.length; i++) {
a[i] = scanner.nextLong();
}
var distinct = Arrays.stream(a).boxed().collect(Collectors.toList());
Collections.shuffle(distinct);
var factors = new HashSet<Long>();
for (int guess = 0; guess < 20 && guess < distinct.size(); guess++) {
for (int j = -1; j <= 1; j++) {
factors.addAll(factor(distinct.get(guess) + j));
}
}
var ans = countOps(2, a, n);
factors.remove(2L);
for (var factor : factors) {
var ops = countOps(factor, a, ans);
ans = Math.min(ans, ops);
}
writer.println(ans);
scanner.close();
writer.flush();
writer.close();
}
private static long countOps(long factor, long[] a, long already) {
var ans = 0L;
for (var x : a) {
if (x < factor) {
ans += factor - x;
} else {
var remain = x % factor;
ans += Math.min(remain, factor - remain);
// if (remain < factor / 2) {
// ans += remain;
// } else {
// ans += factor - remain;
// }
}
if (ans >= already) {
break;
}
}
return ans;
}
private static List<Long> factor(long a) {
if (a <= 1) {
return List.of();
}
var limit = (long) Math.sqrt(a);
var ans = new ArrayList<Long>();
for (long i = 2; i <= limit; i++) {
var count = 0;
while (a % i == 0) {
a /= i;
count++;
}
if (count > 0) {
ans.add(i);
}
}
if (a > 1) {
ans.add(a);
}
return ans;
}
public static class BufferedScanner {
BufferedReader br;
StringTokenizer st;
public BufferedScanner(Reader reader) {
br = new BufferedReader(reader);
}
public BufferedScanner() {
this(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
void close() {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
static long gcd(long a, long b) {
if (a < b) {
return gcd(b, a);
}
while (b > 0) {
long tmp = b;
b = a % b;
a = tmp;
}
return a;
}
static long inverse(long a, long m) {
long[] ans = extgcd(a, m);
return ans[0] == 1 ? (ans[1] + m) % m : -1;
}
private static long[] extgcd(long a, long m) {
if (m == 0) {
return new long[]{a, 1, 0};
} else {
long[] ans = extgcd(m, a % m);
long tmp = ans[1];
ans[1] = ans[2];
ans[2] = tmp;
ans[2] -= ans[1] * (a / m);
return ans;
}
}
private static List<Integer> primes(double upperBound) {
var limit = (int) Math.sqrt(upperBound);
var isComposite = new boolean[limit + 1];
var primes = new ArrayList<Integer>();
for (int i = 2; i <= limit; i++) {
if (isComposite[i]) {
continue;
}
primes.add(i);
int j = i + i;
while (j <= limit) {
isComposite[j] = true;
j += i;
}
}
return primes;
}
}
| java |
1307 | C | C. Cow and Messagetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However; Bessie is sure that there is a secret message hidden inside.The text is a string ss of lowercase Latin letters. She considers a string tt as hidden in string ss if tt exists as a subsequence of ss whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices 11, 33, and 55, which form an arithmetic progression with a common difference of 22. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of SS are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message!For example, in the string aaabb, a is hidden 33 times, b is hidden 22 times, ab is hidden 66 times, aa is hidden 33 times, bb is hidden 11 time, aab is hidden 22 times, aaa is hidden 11 time, abb is hidden 11 time, aaab is hidden 11 time, aabb is hidden 11 time, and aaabb is hidden 11 time. The number of occurrences of the secret message is 66.InputThe first line contains a string ss of lowercase Latin letters (1≤|s|≤1051≤|s|≤105) — the text that Bessie intercepted.OutputOutput a single integer — the number of occurrences of the secret message.ExamplesInputCopyaaabb
OutputCopy6
InputCopyusaco
OutputCopy1
InputCopylol
OutputCopy2
NoteIn the first example; these are all the hidden strings and their indice sets: a occurs at (1)(1), (2)(2), (3)(3) b occurs at (4)(4), (5)(5) ab occurs at (1,4)(1,4), (1,5)(1,5), (2,4)(2,4), (2,5)(2,5), (3,4)(3,4), (3,5)(3,5) aa occurs at (1,2)(1,2), (1,3)(1,3), (2,3)(2,3) bb occurs at (4,5)(4,5) aab occurs at (1,3,5)(1,3,5), (2,3,4)(2,3,4) aaa occurs at (1,2,3)(1,2,3) abb occurs at (3,4,5)(3,4,5) aaab occurs at (1,2,3,4)(1,2,3,4) aabb occurs at (2,3,4,5)(2,3,4,5) aaabb occurs at (1,2,3,4,5)(1,2,3,4,5) Note that all the sets of indices are arithmetic progressions.In the second example, no hidden string occurs more than once.In the third example, the hidden string is the letter l. | [
"brute force",
"dp",
"math",
"strings"
] | import java.util.*;
import java.io.*;
public class Main extends PrintWriter {
Main() { super(System.out); }
static boolean cases = false;
// Solution
void solve(int t) {
char a[] = sc.next().toCharArray();
long f[] = new long[26];
long max = 0;
for (char ch : a) {
f[ch - 'a']++;
max = Math.max(max, f[ch - 'a']);
}
f = new long[26];
long dp[][] = new long[26][26];
for (char ch : a) {
for (int i = 0; i < 26; i++) { dp[ch - 'a'][i] += (f[i]); }
f[ch - 'a']++;
}
for (long x[] : dp) { for (long i : x) max = Math.max(max, i); }
System.out.println(max);
}
public static void main(String[] args) {
Main obj = new Main();
int c = 1;
for (int t = (cases ? sc.nextInt() : 0); t > 1; t--, c++) obj.solve(c);
obj.solve(c);
obj.flush();
}
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[] readIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
char[] readCharArray(int n) {
char a[] = new char[n];
String s = sc.next();
for (int i = 0; i < n; i++) { a[i] = s.charAt(i); }
return a;
}
long[] readLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
long nextLong() { return Long.parseLong(next()); }
}
private static final FastScanner sc = new FastScanner();
private PrintWriter out = new PrintWriter(System.out);
}
| java |
1300 | A | A. Non-zerotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas have an array aa of nn integers [a1,a2,…,ana1,a2,…,an]. In one step they can add 11 to any element of the array. Formally, in one step they can choose any integer index ii (1≤i≤n1≤i≤n) and do ai:=ai+1ai:=ai+1.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make a1+a2+a1+a2+ …… +an≠0+an≠0 and a1⋅a2⋅a1⋅a2⋅ …… ⋅an≠0⋅an≠0.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1031≤t≤103). The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1001≤n≤100) — the size of the array.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−100≤ai≤100−100≤ai≤100) — elements of the array .OutputFor each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.ExampleInputCopy4
3
2 -1 -1
4
-1 0 0 1
2
-1 2
3
0 -2 1
OutputCopy1
2
0
2
NoteIn the first test case; the sum is 00. If we add 11 to the first element, the array will be [3,−1,−1][3,−1,−1], the sum will be equal to 11 and the product will be equal to 33.In the second test case, both product and sum are 00. If we add 11 to the second and the third element, the array will be [−1,1,1,1][−1,1,1,1], the sum will be equal to 22 and the product will be equal to −1−1. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding 11 twice to the first element the array will be [2,−2,1][2,−2,1], the sum will be 11 and the product will be −4−4. | [
"implementation",
"math"
] | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
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 {
if(st.hasMoreTokens()){
str = st.nextToken("\n");
}
else{
str = br.readLine();
}
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public static int ans (int[] arr)
{
int ans = 0;
int sum = 0;
for (int i = 0; i < arr.length; i++) {
if(arr[i]==0)
{
ans++;
arr[i] = arr[i] + 1;
}
sum+=arr[i];
}
if(sum==0)
{
return ans+1;
}
return ans;
}
public static void main(String[] args) throws IOException {
FastReader s = new FastReader();
int n = s.nextInt();
StringBuilder answer = new StringBuilder();
while (n-->0) {
int len = s.nextInt();
int[] arr = new int[len];
for (int i = 0; i < len; i++) {
arr[i] = s.nextInt();
}
answer.append(ans(arr)).append("\n");
}
System.out.println(answer);
}
} | 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"
] | /*package whatever //do not write package name her*/
import java.util.Scanner;
public class code{
public static void main(String args[]){
Scanner s = new Scanner(System.in);
int T = s.nextInt();
while(T-->0){
int x = s.nextInt();
int a = x/2;
int b = x/2;
if(x%2!=0){
a = 1;
b = x-1;
}
System.out.println(a+" "+b);
}
}
} | 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;
import java.io.PrintWriter;
public class Homecoming {
public static void main(String[] args) throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
PrintWriter pr=new PrintWriter(System.out);
int t=Integer.parseInt(br.readLine());
while(t!=0){
solve(br,pr);
t--;
}
pr.flush();
pr.close();
}
public static void solve(BufferedReader br,PrintWriter pr) throws IOException{
String[] temp=br.readLine().split(" ");
int a=Integer.parseInt(temp[0]);
int b=Integer.parseInt(temp[1]);
int p=Integer.parseInt(temp[2]);
String s=br.readLine();
char[] letters=s.toCharArray();
int n=s.length();
long[] needed=new long[n];
needed[n-2]=(letters[n-2]=='A'?a:b);
for(int i=n-3;i>=0;i--){
needed[i]=needed[i+1];
if(letters[i]!=letters[i+1]){
needed[i]+=(letters[i]=='A'?a:b);
}
}
for(int i=0;i<n;i++){
if(needed[i]<=p){
pr.println(i+1);
return;
}
}
}
}
| 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.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
long mod= (long) (1e9+7);
int n=sc.nextInt();
int m=sc.nextInt();
long[][] dp=new long[n+1][2*m+1];
for(int i=1;i<=2*m;i++){
dp[1][i]=1;
}
for(int i=1;i<=n;i++){
dp[i][1]=i;
}
for(int i=2;i<=n;i++){
for(int j=2;j<=2*m;j++){
dp[i][j]=(dp[i-1][j]+dp[i][j-1])%mod;
}
}
System.out.println(dp[n][2*m]);
// write your code here
}
}
| java |
1141 | D | D. Colored Bootstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn left boots and nn right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings ll and rr, both of length nn. The character lili stands for the color of the ii-th left boot and the character riri stands for the color of the ii-th right boot.A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color.For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z').Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible.Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair.InputThe first line contains nn (1≤n≤1500001≤n≤150000), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots).The second line contains the string ll of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th left boot.The third line contains the string rr of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th right boot.OutputPrint kk — the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors.The following kk lines should contain pairs aj,bjaj,bj (1≤aj,bj≤n1≤aj,bj≤n). The jj-th of these lines should contain the index ajaj of the left boot in the jj-th pair and index bjbj of the right boot in the jj-th pair. All the numbers ajaj should be distinct (unique), all the numbers bjbj should be distinct (unique).If there are many optimal answers, print any of them.ExamplesInputCopy10
codeforces
dodivthree
OutputCopy5
7 8
4 9
2 2
9 10
3 1
InputCopy7
abaca?b
zabbbcc
OutputCopy5
6 5
2 3
4 6
7 4
1 2
InputCopy9
bambarbia
hellocode
OutputCopy0
InputCopy10
code??????
??????test
OutputCopy10
6 2
1 6
7 3
3 5
4 8
9 7
5 1
2 4
10 9
8 10
| [
"greedy",
"implementation"
] | import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Pupil
{
static FastReader sc = new FastReader();
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
int t=1;
while(t>0){
int n=sc.nextInt();
String s1=sc.next();
String s2=sc.next();
PriorityQueue<pair>pr1=new PriorityQueue<pair>(Collections.reverseOrder());
PriorityQueue<pair>pr2=new PriorityQueue<pair>( Collections.reverseOrder());
for(int i=0;i<s1.length();i++)
{
char c=s1.charAt(i);
if(c=='?')
{
pr1.add(new pair(200,i));
}
else {
pr1.add(new pair((int)c,i));
}
}
for(int i=0;i<s2.length();i++)
{
char c=s2.charAt(i);
if(c=='?')
{
pr2.add(new pair(200,i));
}
else {
pr2.add(new pair((int)c,i));
}
}
// while(!pr1.isEmpty())
// {
// pair j=pr1.poll();
// System.out.println(j.value+" "+j.index);
// }
ArrayList<pair>waste1=new ArrayList<pair>();
ArrayList<pair>waste2=new ArrayList<pair>();
ArrayList<pair>ans=new ArrayList<pair>();
ArrayList<pair>question1=new ArrayList<pair>();
ArrayList<pair>question2=new ArrayList<pair>();
while(!pr1.isEmpty() && !pr2.isEmpty())
{
pair val1=pr1.poll();
pair val2=pr2.poll();
int check1=val1.value;
int check2=val2.value;
if(check1==200 || check2==200)
{
if(check1==200 && check2==200)
{
question1.add(new pair(check1,val1.index));
question2.add(new pair(check2,val2.index));
}
else if(check1==200)
{
question1.add(new pair(check1,val1.index));
pr2.add(new pair(check2,val2.index));
}
else {
question2.add(new pair(check2,val2.index));
pr1.add(new pair(check1,val1.index));
}
}
else if(check1==check2 && check1!=200)
{
ans.add(new pair(val1.index+1,val2.index+1));
}
else {
if(check1>check2)
{
waste2.add(new pair(check2,val2.index));
pr1.add(new pair(check1,val1.index));
}
else {
waste1.add(new pair(check1,val1.index));
pr2.add(new pair(check2,val2.index));
}
}
}
if(!pr1.isEmpty())
{
while(!pr1.isEmpty())
{
pair g=pr1.poll();
if(g.value==200)
{
question1.add(new pair(g.value,g.index));
}
else {
waste1.add(new pair(g.value,g.index));
}
}
}
else if(!pr2.isEmpty())
{
while(!pr2.isEmpty())
{
pair g=pr2.poll();
if(g.value==200)
{
question2.add(new pair(g.value,g.index));
}
else {
waste2.add(new pair(g.value,g.index));
}
}
}
else {}
// for(int i=0;i<waste1.size();i++)
// {
// pair waste=waste1.get(i);
// System.out.println(waste.value+" "+waste.index);
// }
// System.out.println();
// for(int i=0;i<waste2.size();i++)
// {
// pair waste=waste2.get(i);
// System.out.println(waste.value+" "+waste.index);
// }
// System.out.println();
// for(int i=0;i<question1.size();i++)
// {
// pair waste=question1.get(i);
// System.out.println(waste.value+" "+waste.index);
// }
// System.out.println();
// for(int i=0;i<question2.size();i++)
// {
// pair waste=question2.get(i);
// System.out.println(waste.value+" "+waste.index);
// }
// System.out.println();
int chick1=0;
for(int i=0;i<Math.min(waste1.size(), question2.size());i++)
{
pair waste=waste1.get(i);
pair question=question2.get(i);
ans.add(new pair(waste.index+1,question.index+1));
chick1=i+1;
}
int chick2=0;
for(int i=0;i<Math.min(waste2.size(), question1.size());i++)
{
pair waste=waste2.get(i);
pair question=question1.get(i);
ans.add(new pair(question.index+1,waste.index+1));
chick2=i+1;
}
if(question1.size()>waste2.size() && question2.size()>waste1.size())
{
int jinx1=question1.size()-chick1;
int jinx2=question2.size()-chick2;
for(int i=0;i<Math.min(jinx1,jinx2);i++)
{
pair u=question1.get(chick1);
pair u1=question2.get(chick2);
ans.add(new pair(u.index+1,u1.index+1));
chick1++;
chick2++;
}
}
System.out.println(ans.size());
for(int i=0;i<ans.size();i++)
{
pair obaidbhadwa=ans.get(i);
System.out.println(obaidbhadwa.value+" "+obaidbhadwa.index);
}
t--;
}
}
// FAST I/O
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public static boolean two(int n)//power of two
{
if((n&(n-1))==0)
{
return true;
}
else{
return false;
}
}
public static boolean isPrime(long n){
for (int i = 2; i * i <= n; ++i) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static int digit(int n)
{
int n1=(int)Math.floor((int)Math.log10(n)) + 1;
return n1;
}
}
//CAAL THE BELOW FUNCTION IF PARING PRIORITY IS NEEDED //
// PriorityQueue<pair> pq = new PriorityQueue<>(); **********declare the syntax in the main function******
// pq.add(1,2)///////
class pair implements Comparable<pair> {
int value, index;
pair(int v, int i) { index = i; value = v; }
@Override
public int compareTo(pair o) { return o.value - value; }
}
// User defined Pair class
// class Pair {
// int x;
// int y;
//
// // Constructor
// public Pair(int x, int y)
// {
// this.x = x;
// this.y = y;
// }
// }
// Arrays.sort(arr, new Comparator<Pair>() {
// @Override public int compare(Pair p1, Pair p2)
// {
// return p1.x - p2.x;
// }
// });
// class Pair {
// int height, id;
//
// public Pair(int i, int s) {
// this.height = s;
// this.id = i;
// }
// }
//Arrays.sort(trips, (a, b) -> Integer.compare(a[1], b[1]));
// ArrayList<ArrayList<Integer>> connections = new ArrayList<ArrayList<Integer>>();
// for(int i = 0; i<n;i++)
// connections.add(new ArrayList<Integer>()); | java |
1141 | F1 | F1. Same Sum Blocks (Easy)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],…,a[n].a[1],a[2],…,a[n]. A block is a sequence of contiguous (consecutive) elements a[l],a[l+1],…,a[r]a[l],a[l+1],…,a[r] (1≤l≤r≤n1≤l≤r≤n). Thus, a block is defined by a pair of indices (l,r)(l,r).Find a set of blocks (l1,r1),(l2,r2),…,(lk,rk)(l1,r1),(l2,r2),…,(lk,rk) such that: They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks (li,ri)(li,ri) and (lj,rj(lj,rj) where i≠ji≠j either ri<ljri<lj or rj<lirj<li. For each block the sum of its elements is the same. Formally, a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]=a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]= ⋯=⋯= a[lk]+a[lk+1]+⋯+a[rk].a[lk]+a[lk+1]+⋯+a[rk]. The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks (l′1,r′1),(l′2,r′2),…,(l′k′,r′k′)(l1′,r1′),(l2′,r2′),…,(lk′′,rk′′) satisfying the above two requirements with k′>kk′>k. The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks.InputThe first line contains integer nn (1≤n≤501≤n≤50) — the length of the given array. The second line contains the sequence of elements a[1],a[2],…,a[n]a[1],a[2],…,a[n] (−105≤ai≤105−105≤ai≤105).OutputIn the first line print the integer kk (1≤k≤n1≤k≤n). The following kk lines should contain blocks, one per line. In each line print a pair of indices li,rili,ri (1≤li≤ri≤n1≤li≤ri≤n) — the bounds of the ii-th block. You can print blocks in any order. If there are multiple answers, print any of them.ExamplesInputCopy7
4 1 2 2 1 5 3
OutputCopy3
7 7
2 3
4 5
InputCopy11
-5 -4 -3 -2 -1 0 1 2 3 4 5
OutputCopy2
3 4
1 1
InputCopy4
1 1 1 1
OutputCopy4
4 4
1 1
2 2
3 3
| [
"greedy"
] | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class cf1141f2_2 {
public static void main(String[] args) throws IOException {
int n = ri(), a[] = ria(n), pre[] = new int[n + 1];
for (int i = 0; i < n; ++i) {
pre[i + 1] = pre[i] + a[i];
}
Map<Integer, List<p>> sums = new HashMap<>();
for (int i = 0; i < n; ++i) {
for (int j = 0; j <= i; ++j) {
sums.computeIfAbsent(pre[i + 1] - pre[j], k -> new ArrayList<>()).add(new p(j, i));
}
}
int k = 0;
List<p> ans = new ArrayList<>();
for (int key : sums.keySet()) {
List<p> segs = sums.get(key);
segs.sort((x, y) -> x.b == y.b ? x.a - y.a : x.b - y.b);
int last = -1, cnt = 0;
for (int i = 0, end = segs.size(); i < end; ++i) {
if (segs.get(i).a > last) {
++cnt;
last = segs.get(i).b;
}
}
if (cnt > k) {
k = cnt;
ans = segs;
}
}
prln(k);
int last = -1;
for (int i = 0, end = ans.size(); i < end; ++i) {
if (ans.get(i).a > last) {
prln(ans.get(i).a + 1, ans.get(i).b + 1);
last = ans.get(i).b;
}
}
close();
}
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 asymmetricEquals(Object o) {
p p = (p) o;
return a == p.a && b == p.b;
}
public boolean symmetricEquals(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 asymmetricEquals(o);
}
public int asymmetricHashCode() {
return Objects.hash(a, b);
}
public int symmetricHashCode() {
return Objects.hash(a, b) + Objects.hash(b, a);
}
@Override
public int hashCode() {
return asymmetricHashCode();
}
}
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 |
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.awt.MultipleGradientPaint.ColorSpaceType;
import java.io.*;
import java.sql.PreparedStatement;
import java.util.*;
public class cp {
static int mod=998244353;//(int)1e9+7;
// static Reader sc=new Reader();
static FastReader sc=new FastReader(System.in);
static int[] sp;
static int size=(int)1e6;
static int[] arInt;
static long[] arLong;
static long ans;
public static void main(String[] args) throws IOException {
long tc=sc.nextLong();
// Scanner sc=new Scanner(System.in);
// int tc=1;
// print_int(pre);
// primeSet=new HashSet<>();
// primeCnt=new int[(int)1e9];
// sieveOfEratosthenes((int)1e9);
// factorial(mod);
// InverseofNumber(mod);
// InverseofFactorial(mod);
while(tc-->0)
{
int n=sc.nextInt();
long x=sc.nextLong();
char[] s=sc.next().toCharArray();
int zero=0;
for (int i = 0; i < s.length; i++) {
if (s[i]=='0') {
zero++;
}
}
int ans=0;
boolean flag=false;
int cnt=0;
int total=zero-(n-zero);
for(int i=0;i<n;i++)
{
if (total==0) {
if (cnt==x) {
flag=true;
}
}
else if(Math.abs(x-cnt)%Math.abs(total)==0){
if ((x-cnt)/total>=0) {
ans++;
}
}
if (s[i]=='0') {
cnt++;
}
else {
cnt--;
}
}
if (flag) {
out.println(-1);
}
else {
out.println(ans);
}
}
// System.out.flush();
out.flush();
out.close();
System.gc();
}
/*
...SOLUTION ENDS HERE...........SOLUTION ENDS HERE...
*/
static class Node{
int a;
ArrayList<Pair> adj;
public Node(int a) {
this.a=a;
this.adj=new ArrayList<>();
}
}
static void dijkstra(Node[] g,int dist[],int parent[],int src)
{
Arrays.fill(dist, int_max);
Arrays.fill(parent, -1);
boolean vis[]=new boolean[dist.length];
// vis[1]=true;
PriorityQueue<Pair> q=new PriorityQueue<>();
q.add(new Pair(1, 0));
dist[1]=0;
while(!q.isEmpty())
{
Pair curr=q.poll();
vis[curr.x]=true;
for(Pair edge:g[curr.x].adj)
{
if (vis[edge.x]) {
continue;
}
if (dist[edge.x]>dist[curr.x]+edge.y) {
dist[edge.x]=dist[curr.x]+edge.y;
parent[edge.x]=curr.x;
q.add(new Pair(edge.x, dist[edge.x]));
}
}
}
}
static void mapping(int a[])
{
Pair[] temp=new Pair[a.length];
for (int i = 0; i < temp.length; i++) {
temp[i]=new Pair(a[i], i);
}
Arrays.sort(temp);
int k=0;
for (int i = 0; i < temp.length; i++) {
a[temp[i].y]=k++;
}
}
static boolean palin(String s)
{
for(int i=0;i<s.length()/2;i++)
if(s.charAt(i)!=s.charAt(s.length()-i-1))
return false;
return true;
}
static class temp implements Comparable<temp>{
int x;
int y;
int sec;
public temp(int x,int y,int l) {
// TODO Auto-generated constructor stub
this.x=x;
this.y=y;
this.sec=l;
}
@Override
public int compareTo(cp.temp o) {
// TODO Auto-generated method stub
return this.sec-o.sec;
}
}
// static class Node{
// int x;
// int y;
// ArrayList<Integer> edges;
// public Node(int x,int y) {
// // TODO Auto-generated constructor stub
// this.x=x;
// this.y=y;
// this.edges=new ArrayList<>();
// }
// }
static int lis(int arr[],int n)
{
int ans=0;
int dp[]=new int[n+1];
Arrays.fill(dp, int_max);
dp[0]=int_min;
for(int i=0;i<n;i++)
{
int j=UpperBound(dp,arr[i]);
if(dp[j-1]<=arr[i] && arr[i]<dp[j])
dp[j]=arr[i];
}
for(int i=0;i<=n;i++)
{
if(dp[i]<int_max)
ans=i;
}
return ans;
}
static long get(long n)
{
return n*(n+1)/2L;
}
static boolean go(ArrayList<Pair> caves,int k)
{
for(Pair each:caves)
{
if(k<=each.x)
return false;
k+=each.y;
}
return true;
}
static String revString(String s)
{
char arr[]=s.toCharArray();
int n=s.length();
for(int i=0;i<n/2;i++)
{
char temp=arr[i];
arr[i]=arr[n-i-1];
arr[n-i-1]=temp;
}
return String.valueOf(arr);
}
// Fuction return the number of set bits in n
static int SetBits(int n)
{
int cnt=0;
while(n>0)
{
if((n&1)==1)
{
cnt++;
}
n=n>>1;
}
return cnt;
}
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 void arrInt(int n) throws IOException
{
arInt=new int[n];
for (int i = 0; i < arInt.length; i++) {
arInt[i]=sc.nextInt();
}
}
static void arrLong(int n) throws IOException
{
arLong=new long[n];
for (int i = 0; i < arLong.length; i++) {
arLong[i]=sc.nextLong();
}
}
static ArrayList<Integer> add(int id,int c)
{
ArrayList<Integer> newArr=new ArrayList<>();
for(int i=0;i<id;i++)
newArr.add(arInt[i]);
newArr.add(c);
for(int i=id;i<arInt.length;i++)
{
newArr.add(arInt[i]);
}
return newArr;
}
// function to find first index >= y
static int upper(ArrayList<Integer> arr, int n, int x)
{
int l = 0, h = n - 1;
while (h-l>1)
{
int mid = (l + h) / 2;
if (arr.get(mid) <= x)
l=mid+1;
else
{
h=mid;
}
}
if(arr.get(l)>x)
{
return l;
}
if(arr.get(h)>x)
return h;
return -1;
}
static int upper(ArrayList<Long> arr, int n, long x)
{
int l = 0, h = n - 1;
while (h-l>1)
{
int mid = (l + h) / 2;
if (arr.get(mid) <= x)
l=mid+1;
else
{
h=mid;
}
}
if(arr.get(l)>x)
{
return l;
}
if(arr.get(h)>x)
return h;
return -1;
}
static int lower(ArrayList<Integer> arr, int n, int x)
{
int l = 0, h = n - 1;
while (h-l>1)
{
int mid = (l + h) / 2;
if (arr.get(mid) < x)
l=mid+1;
else
{
h=mid;
}
}
if(arr.get(l)>=x)
{
return l;
}
if(arr.get(h)>=x)
return h;
return -1;
}
static int N = (int)2e5+5;
// Array to store inverse of 1 to N
static long[] factorialNumInverse = new long[N + 1];
// Array to precompute inverse of 1! to N!
static long[] naturalNumInverse = new long[N + 1];
// Array to store factorial of first N numbers
static long[] fact = new long[N + 1];
// Function to precompute inverse of numbers
public static void InverseofNumber(int p)
{
naturalNumInverse[0] = naturalNumInverse[1] = 1;
for(int i = 2; i <= N; i++)
naturalNumInverse[i] = naturalNumInverse[p % i] *
(long)(p - p / i) % p;
}
// Function to precompute inverse of factorials
public static void InverseofFactorial(int p)
{
factorialNumInverse[0] = factorialNumInverse[1] = 1;
// Precompute inverse of natural numbers
for(int i = 2; i <= N; i++)
factorialNumInverse[i] = (naturalNumInverse[i] *
factorialNumInverse[i - 1]) % p;
}
// Function to calculate factorial of 1 to N
public static void factorial(int p)
{
fact[0] = 1;
// Precompute factorials
for(int i = 1; i <= N; i++)
{
fact[i] = (fact[i - 1] * (long)i) % p;
}
}
// Function to return nCr % p in O(1) time
public static long Binomial(int N, int R, int p)
{
// n C r = n!*inverse(r!)*inverse((n-r)!)
long ans = ((fact[N] * factorialNumInverse[R]) %
p * factorialNumInverse[N - R]) % p;
return ans;
}
static String tr(String s)
{
int now = 0;
while (now + 1 < s.length() && s.charAt(now)== '0')
++now;
return s.substring(now);
}
static boolean isPrime(long n)
{
// Corner cases
if (n <= 1)
return false;
if (n <= 3)
return true;
// This is checked so that we can skip
// middle five numbers in below loop
if (n % 2 == 0 || n % 3 == 0)
return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static ArrayList<Integer> commDiv(int a, int b)
{
// find gcd of a, b
int n = gcd(a, b);
// Count divisors of n.
ArrayList<Integer> Div=new ArrayList<>();
for (int i = 1; i <= Math.sqrt(n); i++) {
// if 'i' is factor of n
if (n % i == 0) {
// check if divisors are equal
if (n / i == i)
Div.add(i);
else
{
Div.add(i);
Div.add(n/i);
}
}
}
return Div;
}
static HashSet<Integer> factors(int x)
{
HashSet<Integer> a=new HashSet<Integer>();
for(int i=2;i*i<=x;i++)
{
if(x%i==0)
{
a.add(i);
a.add(x/i);
}
}
return a;
}
static void primeFactors(int n,HashSet<Integer> factors)
{
// Print the number of 2s that divide n
while (n%2==0)
{
factors.add(2);
n /= 2;
}
// n must be odd at this point. So we can
// skip one element (Note i = i +2)
for (int i = 3; i <= Math.sqrt(n); i+= 2)
{
// While i divides n, print i and divide n
while (n%i == 0)
{
factors.add(i);
n /= i;
}
}
// This condition is to handle the case when
// n is a prime number greater than 2
if (n > 2)
factors.add(n);
}
static class Tuple{
int a;
int b;
int c;
public Tuple(int a,int b,int c) {
this.a=a;
this.b=b;
this.c=c;
}
}
//function to find prime factors of n
static HashMap<Long,Long> findFactors(long n2)
{
HashMap<Long,Long> ans=new HashMap<>();
if(n2%2==0)
{
ans.put(2L, 0L);
// cnt++;
while((n2&1)==0)
{
n2=n2>>1;
ans.put(2L, ans.get(2L)+1);
//
}
}
for(long i=3;i*i<=n2;i+=2)
{
if(n2%i==0)
{
ans.put((long)i, 0L);
// cnt++;
while(n2%i==0)
{
n2=n2/i;
ans.put((long)i, ans.get((long)i)+1);
}
}
}
if(n2!=1)
{
ans.put(n2, ans.getOrDefault(n2, (long) 0)+1);
}
return ans;
}
//fenwick tree implementaion
static class fwt
{
int n;
long BITree[];
fwt(int n)
{
this.n=n;
BITree=new long[n+1];
}
fwt(int arr[], int n)
{
this.n=n;
BITree=new long[n+1];
for(int i = 0; i < n; i++)
updateBIT(n, i, arr[i]);
}
long getSum(int index)
{
long sum = 0;
index = index + 1;
while(index>0)
{
sum += BITree[index];
index -= index & (-index);
}
return sum;
}
void updateBIT(int n, int index,int val)
{
index = index + 1;
while(index <= n)
{
BITree[index] += val;
index += index & (-index);
}
}
long sum(int l, int r) {
return getSum(r) - getSum(l - 1);
}
void print()
{
for(int i=0;i<n;i++)
out.print(getSum(i)+" ");
out.println();
}
}
static class sparseTable{
int n;
long[][]dp;
int log2[];
int P;
void buildTable(long[] arr)
{
n=arr.length;
P=(int)Math.floor(Math.log(n)/Math.log(2));
log2=new int[n+1];
log2[0]=log2[1]=0;
for(int i=2;i<=n;i++)
{
log2[i]=log2[i/2]+1;
}
dp=new long[P+1][n];
for(int i=0;i<n;i++)
{
dp[0][i]=arr[i];
}
for(int p=1;p<=P;p++)
{
for(int i=0;i+(1<<p)<=n;i++)
{
long left=dp[p-1][i];
long right=dp[p-1][i+(1<<(p-1))];
dp[p][i]=Math.min(left, right);
}
}
}
long maxQuery(int l,int r)
{
int len=r-l+1;
int p=(int)Math.floor(log2[len]);
long left=dp[p][l];
long right=dp[p][r-(1<<p)+1];
return Math.min(left,right);
}
}
//Function to find number of set bits
static int setBitNumber(long n)
{
if (n == 0)
return 0;
int msb = 0;
n = n / 2;
while (n != 0) {
n = n / 2;
msb++;
}
return msb;
}
static int getFirstSetBitPos(long n)
{
return (int)((Math.log10(n & -n)) / Math.log10(2)) + 1;
}
static ArrayList<Integer> primes;
static HashSet<Integer> primeSet;
static boolean prime[];
static int primeCnt[];
static void sieveOfEratosthenes(int n)
{
prime= new boolean[n + 1];
for (int i = 2; i <= n; i++)
prime[i] = true;
for (int p = 2; p * p <= n; p++)
{
// If prime[p] is not changed, then it is a
// prime
if (prime[p] == true)
{
// Update all multiples of p
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
// Print all prime numbers
for (int i = 2; i <= n; i++)
{
if (prime[i] == true)
primeCnt[i]=primeCnt[i-1]+1;
}
}
static long mod(long a, long b) {
long c = a % b;
return (c < 0) ? c + b : c;
}
static void swap(long arr[],int i,int j)
{
long temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
static boolean util(int a,int b,int c)
{
if(b>a)util(b, a, c);
while(c>=a)
{
c-=a;
if(c%b==0)
return true;
}
return (c%b==0);
}
static void flag(boolean flag)
{
out.println(flag ? "YES" : "NO");
out.flush();
}
static void print(int a[])
{
int n=a.length;
for(int i=0;i<n;i++)
{
out.print(a[i]+" ");
}
out.println();
out.flush();
}
static void print(long a[])
{
int n=a.length;
for(int i=0;i<n;i++)
{
out.print(a[i]+" ");
}
out.println();
out.flush();
}
static void print_int(ArrayList<Integer> al)
{
int si=al.size();
for(int i=0;i<si;i++)
{
out.print(al.get(i)+" ");
}
out.println();
out.flush();
}
static void print_long(ArrayList<Long> al)
{
int si=al.size();
for(int i=0;i<si;i++)
{
out.print(al.get(i)+" ");
}
out.println();
out.flush();
}
static void printYesNo(boolean condition)
{
if (condition) {
out.println("YES");
}
else {
out.println("NO");
}
}
static int LowerBound(int a[], int x)
{ // x is the target value or key
int l=-1,r=a.length;
while(l+1<r) {
int m=(l+r)>>>1;
if(a[m]>=x) r=m;
else l=m;
}
return r;
}
static int lowerIndex(int arr[], int n, int x)
{
int l = 0, h = n - 1;
while (l<=h)
{
int mid = (l + h) / 2;
if (arr[mid] >= x)
h = mid -1 ;
else
l = mid + 1;
}
return l;
}
// function to find last index <= y
static int upperIndex(int arr[], int n, int y)
{
int l = 0, h = n - 1;
while (l <= h)
{
int mid = (l + h) / 2;
if (arr[mid] <= y)
l = mid + 1;
else
h = mid - 1;
}
return h;
}
static int upperIndex(long arr[], int n, long y)
{
int l = 0, h = n - 1;
while (l <= h)
{
int mid = (l + h) / 2;
if (arr[mid] <= y)
l = mid + 1;
else
h = mid - 1;
}
return h;
}
static int UpperBound(int a[], int x)
{// x is the key or target value
int l=-1,r=a.length;
while(l+1<r) {
int m=(l+r)>>>1;
if(a[m]<=x) l=m;
else r=m;
}
return l+1;
}
static int UpperBound(long a[], long x)
{// x is the key or target value
int l=-1,r=a.length;
while(l+1<r) {
int m=(l+r)>>>1;
if(a[m]<=x) l=m;
else r=m;
}
return l+1;
}
static class DisjointUnionSets
{
int[] rank, parent;
int n;
// Constructor
public DisjointUnionSets(int n)
{
rank = new int[n];
parent = new int[n];
this.n = n;
makeSet();
}
// Creates n sets with single item in each
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];
}
// Unites the set that includes x and the set
// that includes 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 // if ranks are the same
{
parent[yRoot] = xRoot;
rank[xRoot] = rank[xRoot] + 1;
}
// if(xRoot!=yRoot)
// parent[y]=x;
}
int connectedComponents()
{
int cnt=0;
for(int i=0;i<n;i++)
{
if(parent[i]==i)
cnt++;
}
return cnt;
}
}
// static class Graph
// {
// int v;
// ArrayList<Integer> list[];
// Graph(int v)
// {
// this.v=v;
// list=new ArrayList[v+1];
// for(int i=1;i<=v;i++)
// list[i]=new ArrayList<Integer>();
// }
// void addEdge(int a, int b)
// {
// this.list[a].add(b);
// }
//
//
//
// }
static class Pair implements Comparable<Pair>
{
int x;
int y;
Pair(int x,int y)
{
this.x=x;
this.y=y;
}
@Override
public int compareTo(Pair o) {
// TODO Auto-generated method stub
return this.y-o.y;
}
}
static class PairL implements Comparable<PairL>
{
long x;
long y;
PairL(long x,long y)
{
this.x=x;
this.y=y;
}
@Override
public int compareTo(PairL o) {
// TODO Auto-generated method stub
return (this.y>o.y)?1:-1;
}
}
static long sum_array(int a[])
{
int n=a.length;
long sum=0;
for(int i=0;i<n;i++)
sum+=a[i];
return sum;
}
static long sum_array(long a[])
{
int n=a.length;
long sum=0;
for(int i=0;i<n;i++)
sum+=a[i];
return sum;
}
static void sort(int[] a)
{
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static void sort(long[] a)
{
ArrayList<Long> l=new ArrayList<>();
for (long i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static void reverse_array(int a[])
{
int n=a.length;
int i,t;
for (i = 0; i < n / 2; i++) {
t = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = t;
}
}
static void reverse_array(long a[])
{
int n=a.length;
int i; long t;
for (i = 0; i < n / 2; i++) {
t = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = t;
}
}
// static long modInverse(long a, long m)
// {
// long g = gcd(a, m);
//
// return power(a, m - 2, m);
//
// }
static long power(long x, long y)
{
long res = 1;
x = x % mod;
if (x == 0)
return 0;
while (y > 0)
{
if ((y & 1) != 0)
res = (res * x) % mod;
y = y >> 1; // y = y/2
x = (x * x) % mod;
}
return res;
}
static int power(int x, int y)
{
int res = 1;
x = x % mod;
if (x == 0)
return 0;
while (y > 0)
{
if ((y & 1) != 0)
res = (res * x) % mod;
y = y >> 1; // y = y/2
x = (x * x) % mod;
}
return res;
}
static long gcd(long a, long b)
{
if (a == 0)
return b;
//cnt+=a/b;
return gcd(b%a,a);
}
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
static class FastReader{
byte[] buf = new byte[2048];
int index, total;
InputStream in;
FastReader(InputStream is) {
in = is;
}
int scan() throws IOException {
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0) {
return -1;
}
}
return buf[index++];
}
String next() throws IOException {
int c;
for (c = scan(); c <= 32; c = scan());
StringBuilder sb = new StringBuilder();
for (; c > 32; c = scan()) {
sb.append((char) c);
}
return sb.toString();
}
int nextInt() throws IOException {
int c, val = 0;
for (c = scan(); c <= 32; c = scan());
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
long nextLong() throws IOException {
int c;
long val = 0;
for (c = scan(); c <= 32; c = scan());
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
}
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
static PrintWriter out=new PrintWriter(System.out);
static int int_max=Integer.MAX_VALUE;
static int int_min=Integer.MIN_VALUE;
static long long_max=Long.MAX_VALUE;
static long long_min=Long.MIN_VALUE;
}
| java |
1288 | B | B. Yet Another Meme Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers AA and BB, calculate the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true; conc(a,b)conc(a,b) is the concatenation of aa and bb (for example, conc(12,23)=1223conc(12,23)=1223, conc(100,11)=10011conc(100,11)=10011). aa and bb should not contain leading zeroes.InputThe first line contains tt (1≤t≤1001≤t≤100) — the number of test cases.Each test case contains two integers AA and BB (1≤A,B≤109)(1≤A,B≤109).OutputPrint one integer — the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true.ExampleInputCopy31 114 2191 31415926OutputCopy1
0
1337
NoteThere is only one suitable pair in the first test case: a=1a=1; b=9b=9 (1+9+1⋅9=191+9+1⋅9=19). | [
"math"
] | import java.io.*;
import java.util.*;
public class sportmafia {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
int t = input.nextInt();
while(t-->0){
long A = input.nextLong();
long B = input.nextLong();
System.out.println(A*(long)Math.log10(B+1));
}
}
} | java |
1323 | B | B. Count Subrectanglestime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn and array bb of length mm both consisting of only integers 00 and 11. Consider a matrix cc of size n×mn×m formed by following rule: ci,j=ai⋅bjci,j=ai⋅bj (i.e. aiai multiplied by bjbj). It's easy to see that cc consists of only zeroes and ones too.How many subrectangles of size (area) kk consisting only of ones are there in cc?A subrectangle is an intersection of a consecutive (subsequent) segment of rows and a consecutive (subsequent) segment of columns. I.e. consider four integers x1,x2,y1,y2x1,x2,y1,y2 (1≤x1≤x2≤n1≤x1≤x2≤n, 1≤y1≤y2≤m1≤y1≤y2≤m) a subrectangle c[x1…x2][y1…y2]c[x1…x2][y1…y2] is an intersection of the rows x1,x1+1,x1+2,…,x2x1,x1+1,x1+2,…,x2 and the columns y1,y1+1,y1+2,…,y2y1,y1+1,y1+2,…,y2.The size (area) of a subrectangle is the total number of cells in it.InputThe first line contains three integers nn, mm and kk (1≤n,m≤40000,1≤k≤n⋅m1≤n,m≤40000,1≤k≤n⋅m), length of array aa, length of array bb and required size of subrectangles.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), elements of aa.The third line contains mm integers b1,b2,…,bmb1,b2,…,bm (0≤bi≤10≤bi≤1), elements of bb.OutputOutput single integer — the number of subrectangles of cc with size (area) kk consisting only of ones.ExamplesInputCopy3 3 2
1 0 1
1 1 1
OutputCopy4
InputCopy3 5 4
1 1 1
1 1 1 1 1
OutputCopy14
NoteIn first example matrix cc is: There are 44 subrectangles of size 22 consisting of only ones in it: In second example matrix cc is: | [
"binary search",
"greedy",
"implementation"
] |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.sort;
public class Round12 {
public static void main(String[] args) {
FastReader fastReader = new FastReader();
PrintWriter out = new PrintWriter(System.out);
int t = 1;
while (t-- > 0) {
int n = fastReader.nextInt();
int m = fastReader.nextInt();
int k = fastReader.nextInt();
int a[] = fastReader.ria(n);
int b[] = fastReader.ria(m);
long ans = 0;
int val1[] = list(a);
int val2[] = list(b);
for (int i = 1; i < val1.length; i++) {
if (k % i == 0 && k/i <= m) {
ans += ((long) val1[i] * val2[k / i]);
}
}
out.println(ans);
}
out.close();
}
public static int[] list(int a[]) {
int n = a.length;
int ret[] = new int[n + 1];
int i = 0;
while (i < n) {
if (a[i] == 0) {
i++;
continue;
}
int j = i;
while (j < n && a[j] == 1) {
j++;
}
for (int len = 1; len <= j - i; len++) {
ret[len] += j - i - len + 1;
}
i = j;
}
return ret;
}
// constants
static final int IBIG = 1000000007;
static final int IMAX = 2147483647;
static final long LMAX = 9223372036854775807L;
static Random __r = new Random();
// math util
static int minof(int a, int b, int c) {
return min(a, min(b, c));
}
static int minof(int... x) {
if (x.length == 1) return x[0];
if (x.length == 2) return min(x[0], x[1]);
if (x.length == 3) return min(x[0], min(x[1], x[2]));
int min = x[0];
for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i];
return min;
}
static long minof(long a, long b, long c) {
return min(a, min(b, c));
}
static long minof(long... x) {
if (x.length == 1) return x[0];
if (x.length == 2) return min(x[0], x[1]);
if (x.length == 3) return min(x[0], min(x[1], x[2]));
long min = x[0];
for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i];
return min;
}
static int maxof(int a, int b, int c) {
return max(a, max(b, c));
}
static int maxof(int... x) {
if (x.length == 1) return x[0];
if (x.length == 2) return max(x[0], x[1]);
if (x.length == 3) return max(x[0], max(x[1], x[2]));
int max = x[0];
for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i];
return max;
}
static long maxof(long a, long b, long c) {
return max(a, max(b, c));
}
static long maxof(long... x) {
if (x.length == 1) return x[0];
if (x.length == 2) return max(x[0], x[1]);
if (x.length == 3) return max(x[0], max(x[1], x[2]));
long max = x[0];
for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i];
return max;
}
static int powi(int a, int b) {
if (a == 0) return 0;
int ans = 1;
while (b > 0) {
if ((b & 1) > 0) ans *= a;
a *= a;
b >>= 1;
}
return ans;
}
static long powl(long a, int b) {
if (a == 0) return 0;
long ans = 1;
while (b > 0) {
if ((b & 1) > 0) ans *= a;
a *= a;
b >>= 1;
}
return ans;
}
static int fli(double d) {
return (int) d;
}
static int cei(double d) {
return (int) ceil(d);
}
static long fll(double d) {
return (long) d;
}
static long cel(double d) {
return (long) ceil(d);
}
static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
static int lcm(int a, int b) {
return (a / gcd(a, b)) * b;
}
static long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
static long lcm(long a, long b) {
return (a / gcd(a, b)) * b;
}
static int[] exgcd(int a, int b) {
if (b == 0) return new int[]{1, 0};
int[] y = exgcd(b, a % b);
return new int[]{y[1], y[0] - y[1] * (a / b)};
}
static long[] exgcd(long a, long b) {
if (b == 0) return new long[]{1, 0};
long[] y = exgcd(b, a % b);
return new long[]{y[1], y[0] - y[1] * (a / b)};
}
static int randInt(int min, int max) {
return __r.nextInt(max - min + 1) + min;
}
static long mix(long x) {
x += 0x9e3779b97f4a7c15L;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L;
x = (x ^ (x >> 27)) * 0x94d049bb133111ebL;
return x ^ (x >> 31);
}
public static boolean[] findPrimes(int limit) {
assert limit >= 2;
final boolean[] nonPrimes = new boolean[limit];
nonPrimes[0] = true;
nonPrimes[1] = true;
int sqrt = (int) Math.sqrt(limit);
for (int i = 2; i <= sqrt; i++) {
if (nonPrimes[i]) continue;
for (int j = i; j < limit; j += i) {
if (!nonPrimes[j] && i != j) nonPrimes[j] = true;
}
}
return nonPrimes;
}
// array util
static void reverse(int[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
int swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void reverse(long[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
long swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void reverse(double[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
double swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void reverse(char[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
char swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void shuffle(int[] a) {
int n = a.length - 1;
for (int i = 0; i < n; ++i) {
int ind = randInt(i, n);
int swap = a[i];
a[i] = a[ind];
a[ind] = swap;
}
}
static void shuffle(long[] a) {
int n = a.length - 1;
for (int i = 0; i < n; ++i) {
int ind = randInt(i, n);
long swap = a[i];
a[i] = a[ind];
a[ind] = swap;
}
}
static void shuffle(double[] a) {
int n = a.length - 1;
for (int i = 0; i < n; ++i) {
int ind = randInt(i, n);
double swap = a[i];
a[i] = a[ind];
a[ind] = swap;
}
}
static void rsort(int[] a) {
shuffle(a);
sort(a);
}
static void rsort(long[] a) {
shuffle(a);
sort(a);
}
static void rsort(double[] a) {
shuffle(a);
sort(a);
}
static int[] copy(int[] a) {
int[] ans = new int[a.length];
for (int i = 0; i < a.length; ++i) ans[i] = a[i];
return ans;
}
static long[] copy(long[] a) {
long[] ans = new long[a.length];
for (int i = 0; i < a.length; ++i) ans[i] = a[i];
return ans;
}
static double[] copy(double[] a) {
double[] ans = new double[a.length];
for (int i = 0; i < a.length; ++i) ans[i] = a[i];
return ans;
}
static char[] copy(char[] a) {
char[] ans = new char[a.length];
for (int i = 0; i < a.length; ++i) ans[i] = a[i];
return ans;
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] ria(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = Integer.parseInt(next());
return a;
}
long nextLong() {
return Long.parseLong(next());
}
long[] rla(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = Long.parseLong(next());
return a;
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
| java |
1284 | C | C. New Year and Permutationtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputRecall that the permutation is an array consisting of nn distinct integers from 11 to nn in arbitrary order. For example, [2,3,1,5,4][2,3,1,5,4] is a permutation, but [1,2,2][1,2,2] is not a permutation (22 appears twice in the array) and [1,3,4][1,3,4] is also not a permutation (n=3n=3 but there is 44 in the array).A sequence aa is a subsegment of a sequence bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. We will denote the subsegments as [l,r][l,r], where l,rl,r are two integers with 1≤l≤r≤n1≤l≤r≤n. This indicates the subsegment where l−1l−1 elements from the beginning and n−rn−r elements from the end are deleted from the sequence.For a permutation p1,p2,…,pnp1,p2,…,pn, we define a framed segment as a subsegment [l,r][l,r] where max{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−lmax{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−l. For example, for the permutation (6,7,1,8,5,3,2,4)(6,7,1,8,5,3,2,4) some of its framed segments are: [1,2],[5,8],[6,7],[3,3],[8,8][1,2],[5,8],[6,7],[3,3],[8,8]. In particular, a subsegment [i,i][i,i] is always a framed segments for any ii between 11 and nn, inclusive.We define the happiness of a permutation pp as the number of pairs (l,r)(l,r) such that 1≤l≤r≤n1≤l≤r≤n, and [l,r][l,r] is a framed segment. For example, the permutation [3,1,2][3,1,2] has happiness 55: all segments except [1,2][1,2] are framed segments.Given integers nn and mm, Jongwon wants to compute the sum of happiness for all permutations of length nn, modulo the prime number mm. Note that there exist n!n! (factorial of nn) different permutations of length nn.InputThe only line contains two integers nn and mm (1≤n≤2500001≤n≤250000, 108≤m≤109108≤m≤109, mm is prime).OutputPrint rr (0≤r<m0≤r<m), the sum of happiness for all permutations of length nn, modulo a prime number mm.ExamplesInputCopy1 993244853
OutputCopy1
InputCopy2 993244853
OutputCopy6
InputCopy3 993244853
OutputCopy32
InputCopy2019 993244853
OutputCopy923958830
InputCopy2020 437122297
OutputCopy265955509
NoteFor sample input n=3n=3; let's consider all permutations of length 33: [1,2,3][1,2,3], all subsegments are framed segment. Happiness is 66. [1,3,2][1,3,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55. [2,1,3][2,1,3], all subsegments except [2,3][2,3] are framed segment. Happiness is 55. [2,3,1][2,3,1], all subsegments except [2,3][2,3] are framed segment. Happiness is 55. [3,1,2][3,1,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55. [3,2,1][3,2,1], all subsegments are framed segment. Happiness is 66. Thus, the sum of happiness is 6+5+5+5+5+6=326+5+5+5+5+6=32. | [
"combinatorics",
"math"
] | /*
JAI MATA DI
*/
import java.util.*;
import java.io.*;
import java.math.BigInteger;
import java.sql.Array;
public class Codechef {
static class FR{
BufferedReader br;
StringTokenizer st;
public FR() {
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 = 1000000007;
static int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
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 int UB(long[] arr , long find , int l , int r) {
while(l<=r) {
int m = (l+r)/2;
if(arr[m]<find) l = m+1;
else r = m-1;
}
return l;
}
static int LB(long[] arr , long find,int l ,int r ) {
while(l<=r) {
int m = (l+r)/2;
if(arr[m] > find) r = m-1;
else l = m+1;
}
return r;
}
static int UB(int[] arr , long find , int l , int r) {
while(l<=r) {
int m = (l+r)/2;
if(arr[m]<find) l = m+1;
else r = m-1;
}
return l;
}
static int LB(int[] arr , long find,int l ,int r ) {
while(l<=r) {
int m = (l+r)/2;
if(arr[m] > find) r = m-1;
else l = m+1;
}
return r;
}
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 FR sc = new FR();
static StringBuilder sb = new StringBuilder();
public static void main(String args[]) {
// int tc = sc.nextInt();
int tc = 1;
while(tc-- > 0) {
test_case();
}
System.out.println(sb);
}
static void test_case() {
long n = sc.nextLong() ,mod = sc.nextLong();
long[] fac = new long[(int)n+1];
fac[0] = 1;
for(int i = 1;i<=n ; i++)
fac[i] = (fac[i-1]*i)%mod;
long ans = (fac[(int)n]*n)%mod;
for(int i = 2 ; i<=n ; i++) {
long out = n - (i);
long terms = n-i+1;
long a = fac[(int)out+1];
long b = (fac[(int)i])%mod;
a = (a*b)%mod;
a = (terms*a)%mod;
// System.out.println(a+" "+i);
ans = (ans + (a)%mod)%mod;
}
sb.append(ans);
}
}
| java |
1307 | B | B. Cow and Friendtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically; he wants to get from (0,0)(0,0) to (x,0)(x,0) by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its nn favorite numbers: a1,a2,…,ana1,a2,…,an. What is the minimum number of hops Rabbit needs to get from (0,0)(0,0) to (x,0)(x,0)? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination.Recall that the Euclidean distance between points (xi,yi)(xi,yi) and (xj,yj)(xj,yj) is (xi−xj)2+(yi−yj)2−−−−−−−−−−−−−−−−−−√(xi−xj)2+(yi−yj)2.For example, if Rabbit has favorite numbers 11 and 33 he could hop from (0,0)(0,0) to (4,0)(4,0) in two hops as shown below. Note that there also exists other valid ways to hop to (4,0)(4,0) in 22 hops (e.g. (0,0)(0,0) →→ (2,−5–√)(2,−5) →→ (4,0)(4,0)). Here is a graphic for the first example. Both hops have distance 33, one of Rabbit's favorite numbers. In other words, each time Rabbit chooses some number aiai and hops with distance equal to aiai in any direction he wants. The same number can be used multiple times.InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤10001≤t≤1000) — the number of test cases. Next 2t2t lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and xx (1≤n≤1051≤n≤105, 1≤x≤1091≤x≤109) — the number of favorite numbers and the distance Rabbit wants to travel, respectively.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109) — Rabbit's favorite numbers. It is guaranteed that the favorite numbers are distinct.It is guaranteed that the sum of nn over all the test cases will not exceed 105105.OutputFor each test case, print a single integer — the minimum number of hops needed.ExampleInputCopy42 41 33 123 4 51 552 1015 4OutputCopy2
3
1
2
NoteThe first test case of the sample is shown in the picture above. Rabbit can hop to (2,5–√)(2,5), then to (4,0)(4,0) for a total of two hops. Each hop has a distance of 33, which is one of his favorite numbers.In the second test case of the sample, one way for Rabbit to hop 33 times is: (0,0)(0,0) →→ (4,0)(4,0) →→ (8,0)(8,0) →→ (12,0)(12,0).In the third test case of the sample, Rabbit can hop from (0,0)(0,0) to (5,0)(5,0).In the fourth test case of the sample, Rabbit can hop: (0,0)(0,0) →→ (5,102–√)(5,102) →→ (10,0)(10,0). | [
"geometry",
"greedy",
"math"
] | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author saikat021
*/
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);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int T = in.nextInt();
while (T-- > 0) {
int n = in.nextInt(), x = in.nextInt();
int[] oneSteps = in.nextIntArray(n);
int max = Integer.MIN_VALUE;
boolean found = false;
for (int i = 0; i < n; i++) {
if (x == oneSteps[i]) {
found = true;
}
max = Math.max(max, oneSteps[i]);
}
out.println(found ? 1 : Math.max((x + max - 1) / max, 2));
}
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; ++i) array[i] = nextInt();
return array;
}
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 close() {
writer.close();
}
public void println(int i) {
writer.println(i);
}
}
}
| 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"
] |
// 20:18 ; 2'50" ; %%I02V2L4L //
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class E {
static class pair implements Comparable<pair> {
int a;
int b;
pair(int a, int b) {
this.a = a;
this.b = b;
}
public int compareTo(pair o) {
return this.a - o.a;
}
}
static int a[][];
static int n;
public static void main(String[] args) {
FastScanner sc = new FastScanner();
int tt = sc.nextInt();
o: while (tt-- > 0) {
n = sc.nextInt();
int m = sc.nextInt();
a = new int[n][3];
for (int i = 0; i < n; i++) {
a[i][0] = sc.nextInt();
a[i][1] = sc.nextInt();
a[i][2] = sc.nextInt();
}
int prev = 0;
int mx = m;
int mi = m;
for (int i = 0; i < n; i++) {
mx += a[i][0] - prev;
mi -= a[i][0] - prev;
if (mi > a[i][2] || mx < a[i][1]) {
System.out.println("NO");
continue o;
}
mx = Math.min(mx, a[i][2]);
mi = Math.max(mi, a[i][1]);
prev = a[i][0];
}
System.out.println("YES");
}
}
static void sort(int[] a) {
// ruffle
int n = a.length;
Random r = new Random();
for (int i = 0; i < a.length; i++) {
int oi = r.nextInt(n), temp = a[i];
a[i] = a[oi];
a[oi] = temp;
}
// then sort
Arrays.sort(a);
}
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());
}
double nextDouble() {
return Double.parseDouble(next());
}
String str = "";
String nextLine() {
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] = nextInt();
return a;
}
long[] readLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
static long gcd(long n, long l) {
if (l == 0)
return n;
return gcd(l, n % l);
}
static void sieveOfEratosthenes(int n, ArrayList<Integer> al) {
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 += p)
prime[i] = false;
}
}
for (int i = 2; i <= n; i++) {
if (prime[i] == true)
al.get(i);
}
}
static final int mod = 1_000_000_000 + 7;
static final int max_val = 2147483647;
static final int min_val = max_val + 1;
// a -> z == 97 -> 122
// String.format("%.9f", ans) ,--> to get upto 9 decimal places , (ans is
// double)
}
| java |
1141 | D | D. Colored Bootstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn left boots and nn right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings ll and rr, both of length nn. The character lili stands for the color of the ii-th left boot and the character riri stands for the color of the ii-th right boot.A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color.For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z').Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible.Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair.InputThe first line contains nn (1≤n≤1500001≤n≤150000), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots).The second line contains the string ll of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th left boot.The third line contains the string rr of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th right boot.OutputPrint kk — the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors.The following kk lines should contain pairs aj,bjaj,bj (1≤aj,bj≤n1≤aj,bj≤n). The jj-th of these lines should contain the index ajaj of the left boot in the jj-th pair and index bjbj of the right boot in the jj-th pair. All the numbers ajaj should be distinct (unique), all the numbers bjbj should be distinct (unique).If there are many optimal answers, print any of them.ExamplesInputCopy10
codeforces
dodivthree
OutputCopy5
7 8
4 9
2 2
9 10
3 1
InputCopy7
abaca?b
zabbbcc
OutputCopy5
6 5
2 3
4 6
7 4
1 2
InputCopy9
bambarbia
hellocode
OutputCopy0
InputCopy10
code??????
??????test
OutputCopy10
6 2
1 6
7 3
3 5
4 8
9 7
5 1
2 4
10 9
8 10
| [
"greedy",
"implementation"
] |
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.io.*;
public class Main{
public static void mergeSort(int[] array) {
if (array == null) {
return;
}
if (array.length > 1) {
int mid = array.length / 2;
// Split left part
int[] left = new int[mid];
for (int i = 0; i < mid; i++) {
left[i] = array[i];
}
// Split right part
int[] right = new int[array.length - mid];
for (int i = mid; i < array.length; i++) {
right[i - mid] = array[i];
}
mergeSort(left);
mergeSort(right);
int i = 0;
int j = 0;
int k = 0;
// Merge left and right arrays
while (i < left.length && j < right.length) {
if (left[i] < right[j]) {
array[k] = left[i];
i++;
} else {
array[k] = right[j];
j++;
}
k++;
}
// Collect remaining elements
while (i < left.length) {
array[k] = left[i];
i++;
k++;
}
while (j < right.length) {
array[k] = right[j];
j++;
k++;
}
}
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = sc.nextInt();
String s1 = sc.next();
String s2 = sc.next();
ArrayList<Integer>[] freq1 = new ArrayList[27];
ArrayList<Integer>[] freq2 = new ArrayList[27];
int[] arr1 = new int[150000];
int[] arr2 = new int[150000];
int o1 = 0;
int o2 = 0;
int f1 = 0;
int f2 = 0;
int[] ind = new int[300002];
int j = 0;
for (int i = 0; i < 27; i++) {
freq1[i] = new ArrayList<>();
freq2[i] = new ArrayList<>();
}
for (int i = 0; i < n; i++) {
if (s1.charAt(i) == '?') {
freq1[26].add(i + 1);
continue;
}
freq1[s1.charAt(i) - 'a'].add(i + 1);
}
for (int i = 0; i < n; i++) {
if (s2.charAt(i) == '?') {
freq2[26].add(i + 1);
continue;
}
freq2[s2.charAt(i) - 'a'].add(i + 1);
}
for (int i = 0; i < 26; i++) {
int len = Math.min(freq1[i].size(), freq2[i].size());
for (int k = len; k < freq1[i].size(); k++) {
arr1[o1++] = freq1[i].get(k);
}
for (int k = len; k < freq2[i].size(); k++) {
arr2[o2++] = freq2[i].get(k);
}
for (int b = 0; b < len; b++) {
ind[j++] = freq1[i].get(b);
ind[j++] = freq2[i].get(b);
}
}
int len = Math.min(o2, freq1[26].size());
{
for (int i = 0; i < len; i++) {
ind[j++] = freq1[26].get(f1++);
ind[j++] = arr2[--o2];
}
}
len = Math.min(o1, freq2[26].size());
{
for (int i = 0; i < len; i++) {
ind[j++] = arr1[--o1];
ind[j++] = freq2[26].get(f2++);
}
}
for (int i = 0; i <freq1[26].size()-f1; i++) {
ind[j++] = freq1[26].get(i+f1);
ind[j++] = freq2[26].get(i+f2);
}
/*
* 5
6 5
4 6
7 4
2 3
1 2
*/
int ans = j/2;
pw.println(ans);
while (j >= 1) {
pw.println(ind[j - 2] + " " + ind[j - 1]);
j -= 2;
}
pw.flush();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(String file) throws IOException {
br = new BufferedReader(new FileReader(file));
}
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
protected String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String readAllLines(BufferedReader reader) throws IOException {
StringBuilder content = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
content.append(line);
content.append(System.lineSeparator());
}
return content.toString();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public long[] nextlongArray(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public Long[] nextLongArray(int n) throws IOException {
Long[] a = new Long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public int[] nextIntArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public Integer[] nextIntegerArray(int n) throws IOException {
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public boolean ready() throws IOException {
return br.ready();
}
}
}
| 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"
] |
// * * * 2100 * * * //
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class A {
static class pair implements Comparable<pair> {
int a;
int b;
pair(int a, int b) {
this.a = a;
this.b = b;
}
public int compareTo(pair o) {
return this.a - o.a;
}
}
static int n, m;
static String str, ttr;
static char s[], t[];
static int dp[];
public static void main(String[] args) {
FastScanner sc = new FastScanner();
int tt = sc.nextInt();
while (tt-- > 0) {
str = sc.nextLine();
ttr = sc.nextLine();
s = str.toCharArray();
t = ttr.toCharArray();
n = s.length;
m = t.length;
HashSet<Character> set = new HashSet<>();
for (char x : s) {
set.add(x);
}
boolean can = true;
for (char x : t) {
if (!set.contains(x)) {
can = false;
break;
}
}
if (!can) {
System.out.println(-1);
continue;
}
HashMap<Character, TreeSet<Integer>> map = new HashMap<>();
for (int i = 0; i < n; i++) {
map.putIfAbsent(s[i], new TreeSet<Integer>());
map.get(s[i]).add(i);
}
int j = -1;
int cnt = 1;
for (int i = 0; i < m; i++) {
Integer temp = map.get(t[i]).ceiling(j + 1); // returns the value of element greater than or equal to
// given
// value or if not exists return null
if (temp == null) {
cnt++;
temp = map.get(t[i]).first();
j = temp;
} else {
j = temp;
}
}
System.out.println(cnt);
}
}
static void sort(int[] a) {
// ruffle
int n = a.length;
Random r = new Random();
for (int i = 0; i < a.length; i++) {
int oi = r.nextInt(n), temp = a[i];
a[i] = a[oi];
a[oi] = temp;
}
// then sort
Arrays.sort(a);
}
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());
}
double nextDouble() {
return Double.parseDouble(next());
}
String str = "";
String nextLine() {
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] = nextInt();
return a;
}
long[] readLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
static long gcd(long n, long l) {
if (l == 0)
return n;
return gcd(l, n % l);
}
static void sieveOfEratosthenes(int n, ArrayList<Integer> al) {
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 += p)
prime[i] = false;
}
}
for (int i = 2; i <= n; i++) {
if (prime[i] == true)
al.get(i);
}
}
static final int mod = 1_000_000_000 + 7;
static final int max_val = 2147483647;
static final int min_val = max_val + 1;
static long fastPow(long base, long exp) {
if (exp == 0)
return 1;
long half = fastPow(base, exp / 2);
if (exp % 2 == 0)
return mul(half, half);
return mul(half, mul(half, base));
}
static long mul(long a, long b) {
return a * b % mod;
}
static int nCr(int n, int r) {
return fact(n) / (fact(r) *
fact(n - r));
}
static int fact(int n) {
int res = 1;
for (int i = 2; i <= n; i++)
res = res * i;
return res;
}
// a -> z == 97 -> 122
// String.format("%.9f", ans) ,--> to get upto 9 decimal places , (ans is
// double)
}
| java |
1315 | C | C. Restoring Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence b1,b2,…,bnb1,b2,…,bn. Find the lexicographically minimal permutation a1,a2,…,a2na1,a2,…,a2n such that bi=min(a2i−1,a2i)bi=min(a2i−1,a2i), or determine that it is impossible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1001≤t≤100).The first line of each test case consists of one integer nn — the number of elements in the sequence bb (1≤n≤1001≤n≤100).The second line of each test case consists of nn different integers b1,…,bnb1,…,bn — elements of the sequence bb (1≤bi≤2n1≤bi≤2n).It is guaranteed that the sum of nn by all test cases doesn't exceed 100100.OutputFor each test case, if there is no appropriate permutation, print one number −1−1.Otherwise, print 2n2n integers a1,…,a2na1,…,a2n — required lexicographically minimal permutation of numbers from 11 to 2n2n.ExampleInputCopy5
1
1
2
4 1
3
4 1 3
4
2 3 4 5
5
1 5 7 2 8
OutputCopy1 2
-1
4 5 1 2 3 6
-1
1 3 5 6 7 9 2 4 8 10
| [
"greedy"
] | import java.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
static long mod = (int)1e9+7;
static PrintWriter out=new PrintWriter(new BufferedOutputStream(System.out));
public static void main (String[] args) throws java.lang.Exception
{
FastReader sc =new FastReader();
int t=sc.nextInt();
// int t=1;
O : while(t-->0)
{
int n=sc.nextInt();
int a[]=sc.readArray(n);
boolean gone[]=new boolean[2*n+1];
ArrayList<Integer> list=new ArrayList<>();
for(int i=0;i<n;i++){
gone[a[i]]=true;
}
for(int i=0;i<n;i++){
for(int j=a[i]+1;j<=2*n;j++){
if(!gone[j]){
list.add(a[i]);
list.add(j);
gone[j]=true;
break;
}
}
}
if(list.size()!=2*n){
System.out.println(-1);
}
else{
for(int i=0;i<list.size();i++){
System.out.print(list.get(i)+" ");
}
System.out.println();
}
}
out.flush();
}
static void printN()
{
System.out.println("NO");
}
static void printY()
{
System.out.println("YES");
}
static int findfrequencies(int a[],int n)
{
int count=0;
for(int i=0;i<a.length;i++)
{
if(a[i]==n)
{
count++;
}
}
return count;
}
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;
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long[] readArrayLong(int n) {
long[] a=new long[n];
for (int i=0; i<n; i++) a[i]=nextLong();
return a;
}
}
public static int[] radixSort2(int[] a)
{
int n = a.length;
int[] c0 = new int[0x101];
int[] c1 = new int[0x101];
int[] c2 = new int[0x101];
int[] c3 = new int[0x101];
for(int v : a) {
c0[(v&0xff)+1]++;
c1[(v>>>8&0xff)+1]++;
c2[(v>>>16&0xff)+1]++;
c3[(v>>>24^0x80)+1]++;
}
for(int i = 0;i < 0xff;i++) {
c0[i+1] += c0[i];
c1[i+1] += c1[i];
c2[i+1] += c2[i];
c3[i+1] += c3[i];
}
int[] t = new int[n];
for(int v : a)t[c0[v&0xff]++] = v;
for(int v : t)a[c1[v>>>8&0xff]++] = v;
for(int v : a)t[c2[v>>>16&0xff]++] = v;
for(int v : t)a[c3[v>>>24^0x80]++] = v;
return a;
}
static int[] EvenOddArragement(int nums[])
{
int i1=0,i2=nums.length-1;
while(i1<i2){
while(nums[i1]%2==0 && i1<i2){
i1++;
}
while(nums[i2]%2!=0 && i2>i1){
i2--;
}
int temp=nums[i1];
nums[i1]=nums[i2];
nums[i2]=temp;
}
return nums;
}
static int gcd(int a, int b) {
while (b != 0) {
int t = a;
a = b;
b = t % b;
}
return a;
}
static int lcm(int a, int b)
{
return (a / gcd(a, b)) * b;
}
public static HashMap<Integer, Integer> sortByValue(HashMap<Integer, Integer> hm)
{
// Create a list from elements of HashMap
List<Map.Entry<Integer, Integer> > list =
new LinkedList<Map.Entry<Integer, Integer> >(hm.entrySet());
// Sort the list
Collections.sort(list, new Comparator<Map.Entry<Integer, Integer> >() {
public int compare(Map.Entry<Integer, Integer> o1,
Map.Entry<Integer, Integer> o2)
{
return (o1.getValue()).compareTo(o2.getValue());
}
});
// put data from sorted list to hashmap
HashMap<Integer, Integer> temp = new LinkedHashMap<Integer, Integer>();
for (Map.Entry<Integer, Integer> aa : list) {
temp.put(aa.getKey(), aa.getValue());
}
return temp;
}
static int DigitSum(int n)
{
int r=0,sum=0;
while(n>=0)
{
r=n%10;
sum=sum+r;
n=n/10;
}
return sum;
}
static boolean checkPerfectSquare(int number)
{
double sqrt=Math.sqrt(number);
return ((sqrt - Math.floor(sqrt)) == 0);
}
static boolean isPowerOfTwo(int n)
{
if(n==0)
return false;
return (int)(Math.ceil((Math.log(n) / Math.log(2)))) == (int)(Math.floor(((Math.log(n) / Math.log(2)))));
}
static boolean isPrime2(int n)
{
if (n <= 1)
{
return false;
}
if (n == 2)
{
return true;
}
if (n % 2 == 0)
{
return false;
}
for (int i = 3; i <= Math.sqrt(n) + 1; i = i + 2)
{
if (n % i == 0)
{
return false;
}
}
return true;
}
static String minLexRotation(String str)
{
int n = str.length();
String arr[] = new String[n];
String concat = str + str;
for(int i=0;i<n;i++)
{
arr[i] = concat.substring(i, i + n);
}
Arrays.sort(arr);
return arr[0];
}
static String maxLexRotation(String str)
{
int n = str.length();
String arr[] = new String[n];
String concat = str + str;
for (int i = 0; i < n; i++)
{
arr[i] = concat.substring(i, i + n);
}
Arrays.sort(arr);
return arr[arr.length-1];
}
static class P implements Comparable<P> {
int i, j;
public P(int i, int j) {
this.i=i;
this.j=j;
}
public int compareTo(P o) {
return Integer.compare(i, o.i);
}
}
static class pair{
int i,j;
pair(int x,int y){
i=x;
j=y;
}
}
static int binary_search(int a[],int value)
{
int start=0;
int end=a.length-1;
int mid=start+(end-start)/2;
while(start<=end)
{
if(a[mid]==value)
{
return mid;
}
if(a[mid]>value)
{
end=mid-1;
}
else
{
start=mid+1;
}
mid=start+(end-start)/2;
}
return -1;
}
} | java |
1303 | D | D. Fill The Bagtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a bag of size nn. Also you have mm boxes. The size of ii-th box is aiai, where each aiai is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if n=10n=10 and a=[1,1,32]a=[1,1,32] then you have to divide the box of size 3232 into two parts of size 1616, and then divide the box of size 1616. So you can fill the bag with boxes of size 11, 11 and 88.Calculate the minimum number of divisions required to fill the bag of size nn.InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The first line of each test case contains two integers nn and mm (1≤n≤1018,1≤m≤1051≤n≤1018,1≤m≤105) — the size of bag and the number of boxes, respectively.The second line of each test case contains mm integers a1,a2,…,ama1,a2,…,am (1≤ai≤1091≤ai≤109) — the sizes of boxes. It is guaranteed that each aiai is a power of two.It is also guaranteed that sum of all mm over all test cases does not exceed 105105.OutputFor each test case print one integer — the minimum number of divisions required to fill the bag of size nn (or −1−1, if it is impossible).ExampleInputCopy3
10 3
1 32 1
23 4
16 1 4 1
20 5
2 1 16 1 8
OutputCopy2
-1
0
| [
"bitmasks",
"greedy"
] | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
outer: while(t-- > 0) {
long n = in.nextLong(), sum = 0;
int m = in.nextInt(), ans = 0;
TreeMap<Integer, Integer> mp = new TreeMap<>();
for(int i = 0; i < m; ++i) {
int x = in.nextInt();
sum += x;
int key = 31 - Integer.numberOfLeadingZeros(x);
Integer cnt = mp.get(key);
if(cnt == null)
mp.put(key, 1);
else
mp.put(key, cnt + 1);
}
if(sum < n) {
System.out.println(-1);
continue outer;
}
for(int i = 0; i < 60; ++i) {
if((n >> i & 1) != 0) {
Integer cnt = mp.get(i);
if(cnt != null && cnt > 0)
mp.put(i, cnt - 1);
else {
Integer key = mp.higherKey(i);
cnt = mp.get(key);
mp.put(key, cnt - 1);
Integer low = mp.get(key - 1);
if(low == null)
mp.put(key - 1, 2);
else
mp.put(key - 1, low + 2);
++ans;
--i;
continue;
}
}
Integer cnt = mp.get(i);
if(cnt != null && cnt > 1) {
Integer high = mp.get(i + 1);
if(high == null)
mp.put(i + 1, cnt / 2);
else
mp.put(i + 1, high + cnt / 2);
}
}
System.out.println(ans);
}
}
} | java |
1290 | C | C. Prefix Enlightenmenttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn lamps on a line, numbered from 11 to nn. Each one has an initial state off (00) or on (11).You're given kk subsets A1,…,AkA1,…,Ak of {1,2,…,n}{1,2,…,n}, such that the intersection of any three subsets is empty. In other words, for all 1≤i1<i2<i3≤k1≤i1<i2<i3≤k, Ai1∩Ai2∩Ai3=∅Ai1∩Ai2∩Ai3=∅.In one operation, you can choose one of these kk subsets and switch the state of all lamps in it. It is guaranteed that, with the given subsets, it's possible to make all lamps be simultaneously on using this type of operation.Let mimi be the minimum number of operations you have to do in order to make the ii first lamps be simultaneously on. Note that there is no condition upon the state of other lamps (between i+1i+1 and nn), they can be either off or on.You have to compute mimi for all 1≤i≤n1≤i≤n.InputThe first line contains two integers nn and kk (1≤n,k≤3⋅1051≤n,k≤3⋅105).The second line contains a binary string of length nn, representing the initial state of each lamp (the lamp ii is off if si=0si=0, on if si=1si=1).The description of each one of the kk subsets follows, in the following format:The first line of the description contains a single integer cc (1≤c≤n1≤c≤n) — the number of elements in the subset.The second line of the description contains cc distinct integers x1,…,xcx1,…,xc (1≤xi≤n1≤xi≤n) — the elements of the subset.It is guaranteed that: The intersection of any three subsets is empty; It's possible to make all lamps be simultaneously on using some operations. OutputYou must output nn lines. The ii-th line should contain a single integer mimi — the minimum number of operations required to make the lamps 11 to ii be simultaneously on.ExamplesInputCopy7 3
0011100
3
1 4 6
3
3 4 7
2
2 3
OutputCopy1
2
3
3
3
3
3
InputCopy8 6
00110011
3
1 3 8
5
1 2 5 6 7
2
6 8
2
3 5
2
4 7
1
2
OutputCopy1
1
1
1
1
1
4
4
InputCopy5 3
00011
3
1 2 3
1
4
3
3 4 5
OutputCopy1
1
1
1
1
InputCopy19 5
1001001001100000110
2
2 3
2
5 6
2
8 9
5
12 13 14 15 16
1
19
OutputCopy0
1
1
1
2
2
2
3
3
3
3
4
4
4
4
4
4
4
5
NoteIn the first example: For i=1i=1; we can just apply one operation on A1A1, the final states will be 10101101010110; For i=2i=2, we can apply operations on A1A1 and A3A3, the final states will be 11001101100110; For i≥3i≥3, we can apply operations on A1A1, A2A2 and A3A3, the final states will be 11111111111111. In the second example: For i≤6i≤6, we can just apply one operation on A2A2, the final states will be 1111110111111101; For i≥7i≥7, we can apply operations on A1,A3,A4,A6A1,A3,A4,A6, the final states will be 1111111111111111. | [
"dfs and similar",
"dsu",
"graphs"
] | //package com.company;
import java.io.*;
import java.util.*;
public class Main {
public static class Task {
public class DJS {
int n;
int[] arr;
int[] sizes;
int unAssign;
public DJS(int n) {
this.n = n;
arr = new int[n * 2 + 2];
sizes = new int[n * 2 + 2];
Arrays.fill(arr, -1);
Arrays.fill(sizes, 0);
for (int i = 0; i < n; i++) {
sizes[i] = 1;
}
unAssign = n;
}
int find(int u) {
return arr[u] < 0 ? u: (arr[u] = find(arr[u]));
}
int size(int u) {
return arr[u] < 0 ? sizes[u]: 0;
}
void link(int a, int b) { // b -> a
int ra = find(a);
int rb = find(b);
if (ra == rb) return;
sizes[ra] += sizes[rb];
arr[rb] = ra;
}
int getOther(int k) {
if (k < n) throw new RuntimeException();
int v = k - (n + 2);
return v % 2 == 0 ? k + 1: k - 1;
}
int vv(int k) {
if (k < n) {
throw new RuntimeException();
}
if (k == n || k == n + 1) return 0;
return Math.min(size(k), size(getOther(k)));
}
int getEmp() {
return (unAssign += 2);
}
}
public void solve(Scanner sc, PrintWriter pw) throws IOException {
int n = sc.nextInt();
int k = sc.nextInt();
String s = sc.next();
List<Integer>[] vs = new List[n];
for (int i = 0; i < n; i++) {
vs[i] = new ArrayList<>();
}
for (int i = 0; i < k; i++) {
int c = sc.nextInt();
for (int j = 0; j < c; j++) {
int q = sc.nextInt() - 1;
vs[q].add(i);
}
}
DJS djs = new DJS(k);
int better = 0;
for (int i = 0; i < n; i++) {
// System.err.print(s.charAt(i) + " ");
if (vs[i].size() == 1) {
int u = vs[i].get(0);
int ru = djs.find(u);
// System.err.println(u + " " + ru);
if (ru == k || ru == k + 1) {
} else if (ru < k) {
djs.link(s.charAt(i) == '0' ? k: k + 1, u);
} else {
int rup = djs.getOther(ru);
better -= djs.vv(ru);
djs.link(s.charAt(i) == '0' ? k: k + 1, ru);
djs.link(s.charAt(i) != '0' ? k: k + 1, rup);
}
} else if (vs[i].size() == 2) {
int u = vs[i].get(0), v = vs[i].get(1);
int ru = djs.find(u), rv = djs.find(v);
// System.err.println(u + " " + v + " " + ru + " " + rv);
if (ru < k && rv < k) {
int y = djs.getEmp();
if (s.charAt(i) == '1') {
djs.link(ru, rv);
djs.link(y, ru);
} else {
djs.link(y, ru);
djs.link(djs.getOther(y), rv);
}
better += djs.vv(y);
} else if (ru < k) {
better -= djs.vv(rv);
if (s.charAt(i) == '1') {
djs.link(rv, ru);
} else {
djs.link(djs.getOther(rv), ru);
}
better += djs.vv(rv);
} else if (rv < k) {
better -= djs.vv(ru);
if (s.charAt(i) == '1') {
djs.link(ru, rv);
} else {
djs.link(djs.getOther(ru), rv);
}
better += djs.vv(ru);
} else {// ru -> rv;
if (ru == rv || ru == djs.getOther(rv)) {
} else {
if (rv > ru) {
int tt = rv; rv = ru; ru = tt;
}
better -= djs.vv(ru);
better -= djs.vv(rv);
if (s.charAt(i) == '1') {
djs.link(rv, ru);
djs.link(djs.getOther(rv), djs.getOther(ru));
} else {
djs.link(djs.getOther(rv), ru);
djs.link(rv, djs.getOther(ru));
}
better += djs.vv(rv);
}
}
}
pw.println(djs.size(k) + better);
}
}
}
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("joker.in"));
PrintWriter pw = new PrintWriter(new BufferedOutputStream(System.out));
// PrintWriter pw = new PrintWriter(new FileOutputStream("joker.out"));
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 |
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.util.*;
import java.lang.*;
import java.io.*;
import java.math.BigInteger;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.math.BigInteger;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
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.Iterator;
public class codeee
{ //public static int mod=1000000007;
public static ArrayList<Long> Factors(long n)
{
ArrayList<Long> arr=new ArrayList<Long>();
int k=0;
while (n%2==0)
{
k++;
n /=2;
arr.add((long)2);
}
int p=(int) Math.sqrt(n);
for (int i = 3; i <=p; i+= 2)
{ if(n==1)break;
while (n%i == 0)
{
k++;
arr.add((long)i);
n /= i;
}
}
if (n > 2)
{
arr.add(n);
}
arr.add((long) 1);
return arr;
}
static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(
new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
if (cnt != 0) {
break;
}
else {
continue;
}
}
buf[cnt++] = (byte)c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0,
BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
public static long gcd(long x, long p)
{
if (x == 0)
return p;
return gcd(p%x, x);
}
// method to return LCM of two numbers
static long lcm(long a, long b)
{
return (a / gcd(a, b)) * b;
}
public static HashMap<Integer, Integer> sortByValue(HashMap<Integer, Integer> hm)
{
// Create a list from elements of HashMap
List<Map.Entry<Integer, Integer> > list =
new LinkedList<Map.Entry<Integer, Integer> >(hm.entrySet());
// Sort the list
Collections.sort(list, new Comparator<Map.Entry<Integer, Integer> >() {
public int compare(Map.Entry<Integer, Integer> o1,
Map.Entry<Integer, Integer> o2)
{
return (o1.getValue()).compareTo(o2.getValue());
}
});
// put data from sorted list to hashmap
HashMap<Integer, Integer> temp = new LinkedHashMap<Integer, Integer>();
for (Map.Entry<Integer, Integer> aa : list) {
temp.put(aa.getKey(), aa.getValue());
}
return temp;
}
static int sieve = 1000000 ;
static boolean[] prime = new boolean[sieve + 1] ;
public static void sieveOfEratosthenes()
{
// FALSE == prime and 1 // TRUE == COMPOSITE
// time complexity = 0(NlogLogN)== o(N)
// gives prime nos bw 1 to N // size - 1e7(at max)
for(int i = 4; i<= sieve ; i++)
{
prime[i] = true ; i++ ;
}
for(int p = 3; p*p <= sieve; p++)
{
if(prime[p] == false)
{
for(int i = p*p; i <= sieve; i += p)
prime[i] = true;
}
p++ ;
}
}
public static void arrInpInt(int [] arr, int n) throws IOException
{
Reader reader = new Reader();
for(int i=0;i<n;i++)
{
arr[i]=reader.nextInt();
}
}
public static void arrInpLong(long [] arr, int n) throws IOException
{
Reader reader = new Reader();
for(int i=0;i<n;i++)
{
arr[i]=reader.nextLong();
}
}
public static void printArr(int[] arr)
{
for(int i=0;i<arr.length;i++)
{
System.out.print(arr[i]+" ");
}
System.out.println();
}
public static int[] decSort(int[] arr)
{
int[] arr1 = Arrays.stream(arr).boxed().sorted(Collections.reverseOrder()).mapToInt(Integer::intValue).toArray();
return arr1;
}
//if present - return the first occurrence of the no
//not present- return the index of next greater value
//if greater than all the values return N(taking high=N-1)
//if smaller than all the values return 0(taking low =0)
static int lower_bound(int arr[], int low,int high, int X)
{
if (low > high) {
return low;
}
int mid = low + (high - low) / 2;
if (arr[mid] >= X) {
return lower_bound(arr, low,
mid - 1, X);
}
return lower_bound(arr, mid + 1,
high, X);
}
//if present - return the index of next greater value
//not present- return the index of next greater value
//if greater than all the values return N(taking high=N-1)
//if smaller than all the values return 0(taking low =0)\
static int upper_bound(int arr[], int low, int high, int X)
{
if (low > high)
return low;
int mid = low + (high - low) / 2;
if (arr[mid] <= X) {
return upper_bound(arr, mid + 1,
high, X);
}
return upper_bound(arr, low,
mid - 1, X);
}
public static class Pair {// comparator with class
int x;
int y;
public Pair(int x, int y)
{
this.x = x;
this.y = y;
}
}
public static void sortbyColumn(int arr[][], int col) // send 2d array and col no
{
Arrays.sort(arr, new Comparator<int[]>() {
@Override
public int compare(final int[] entry1,
final int[] entry2) {
if (entry1[col] > entry2[col])
return 1;
else if (entry1[col] < entry2[col])
return -1;
else return 0;
}
});
}
public static void sortbyColumn1(int arr[][], int col) // send 2d array and col no
{
Arrays.sort(arr, new Comparator<int[]>() {
@Override
public int compare(final int[] entry1,
final int[] entry2) {
if (entry1[col] > entry2[col])
return 1;
else if (entry1[col] < entry2[col])
return -1;
else if(entry1[col] == entry2[col])
{
if(entry1[col-1]>entry2[col-1])
return -1;
else if(entry1[col-1]<entry2[col-1])
return 1;
else return 0;
}
else return 0;
}
});
}
public static void print2D(int mat[][])
{
// Loop through all rows
for (int i = 0; i < mat.length; i++)
{ // Loop through all elements of current row
{
for (int j = 0; j < mat[i].length; j++)
System.out.print(mat[i][j] + " ");
}
System.out.println();
}
}
public static int biggestFactor(int num) {
int result = 1;
for(int i=2; i*i <=num; i++){
if(num%i==0){
result = num/i;
break;
}
}
return result;
}
public static class p
{
int no;
int h;
public p(int no, long h)
{
this.no=no;
this.h=(int) h;
}
}
public static class k
{
boolean inc;
int min;
int max;
public k(boolean inc,int min, int max)
{
this.inc=inc;
this.min=min;
this.max=max;
}
}
static class com implements Comparator<p>{
public int compare(p s1, p s2) {
if (s1.h > s2.h)
return -1;
else if (s1.h < s2.h)
return 1;
else if(s1.h==s2.h)
{
if(s1.no>s2.no)return -1;
else return 1;
}
return 0;
}
}
static long hcf(long a,long b)
{
while (b > 0)
{
long temp = b;
b = a % b;
a = temp;
}
return a;
}
static int lower_bound_arr(ArrayList<Integer> arr, int low,
int high, int X)
{
if (low > high) {
return low;
}
int mid = low + (high - low) / 2;
if (arr.get(mid) >= X) {
return lower_bound_arr(arr, low,
mid - 1, X);
}
return lower_bound_arr(arr, mid + 1,
high, X);
}
public static void main(String args[]) throws NumberFormatException, IOException ,java.lang.Exception
{
Reader reader = new Reader();
//sieveOfEratosthenes();
//System.out.println(prime[0]+" "+prime[1]+" "+prime[2]+" "+prime[3]+" "+prime[4]);
//Scanner reader=new Scanner(System.in);
// BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
// int cases=Integer.parseInt(br.readLine());
int cases=1;
//BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out));
// int cases=reader.nextInt();
while (cases-->0){
long V=reader.nextLong();
//long C=reader.nextLong();
//long N=reader.nextLong();
//long M=reader.nextLong();
//int N=reader.nextInt();
//int G=reader.nextInt();
//int B=reader.nextInt();
//BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out));
// int P=reader.nextInt();
//int[][] arr=new int[N][N];
//int K=reader.nextInt();
//int X=reader.nextInt();
//int K=reader.nextInt();
//int S=reader.nextInt();
//int circum=reader.nextInt();
//int K=reader.nextInt();
// String[] firs=br.readLine().split(" ");
// int N=Integer.parseInt(firs[0]);
//char p=first[1].charAt(0);
//int P=Integer.parseInt(first[1]);
//int K=Integer.parseInt(first[2]);
//String[] first=br.readLine().split(" ");
//int N=Integer.parseInt(first[0]);
//int K=Integer.parseInt(first[1]);
//int X=reader.nextInt();
//int Y=reader.nextInt();
//String s2=br.readLine();
// String s3=br.readLine();
// char[] s11=s2.toCharArray();
// char[] s12=new char[s11.length];
//String[] first1=br.readLine().split(" ");
//int C=Integer.parseInt(first1[0]);
//int C1=Integer.parseInt(first1[1]);
//char[] s12=s3.toCharArray();
//int max=Integer.MIN_VALUE;
//int min=Integer.MAX_VALUE;
//int ind=-1;
// HashMap<String,Integer> map=new HashMap<String,Integer>();
// HashMap<String,Integer> map1=new HashMap<String,Integer>();
//HashMap<Character,Integer> path=new HashMap<Character,Integer>();
//TreeMap<Integer,Integer> map=new TreeMap<Integer,Integer>(Collections.reverseOrder());
//HashSet<Long> left =new HashSet<Long>();
// HashSet<Integer> right =new HashSet<Integer>();
//TreeSet<Integer> a =new TreeSet<Integer>();
//TreeSet<Long> b =new TreeSet<Long>();
//TreeSet<Integer> map=new TreeSet<Integer>();
int[] arr1=new int[(int) V];
int[] arr2=new int[(int) V];
// Integer[] arr1=new Integer[V];
//Integer[] arr2=new Integer[V];
// Integer[] diff=new Integer[N];
// int[] diff=new int[N];
// int[] arr1= {2,3,5,7,11,13,17,19,23,29,31};
//Integer[] arr2=new Integer[N];
//boolean[]arr1=new boolean[N];
// long[] arr=new long[N];
// ArrayList<Integer> k=new ArrayList<Integer>();
//ArrayList<Long> arr1=Factors(V);
//int [][] arr=new int[N][5];
//System.out.println(map);
//PriorityQueue<p> Q=new PriorityQueue<p>(new com());
//PriorityQueue<Long> w=new PriorityQueue<Long>();
//int min=Integer.MAX_VALUE;
//ArrayList<ArrayList<Integer>> arr1=new ArrayList<ArrayList<Ineteger>>();
//System.out.println();
//System.out.println(zero+" "+one);
for(int i=0;i<V;i++)
{
int N=reader.nextInt();
int min=Integer.MAX_VALUE;
int max=Integer.MIN_VALUE;
boolean des=true;
int last=Integer.MAX_VALUE;
for(int j=0;j<N;j++)
{
int k=reader.nextInt();
min=Math.min(min, k);
max=Math.max(max, k);
if(k>last)
{
des=false;
}
last=k;
}
if(!des)
{
arr1[i]=Integer.MIN_VALUE;
arr2[i]=Integer.MAX_VALUE;
}
else
{
arr1[i]=min;
arr2[i]=max;
}
//System.out.println(i+" "+arr1[i]+" "+arr2[i]);
}
Arrays.sort(arr1);
Arrays.sort(arr2);
long ans=0;
for(int i=0;i<V;i++)
{
if(arr1[i]==Integer.MIN_VALUE)
{
ans=ans+V;
}
else
{
int ind=upper_bound(arr2,0,(int)V-1,arr1[i]);
ans=ans+V-ind;
}
}
// System.out.println(Arrays.toString(arr1));
// System.out.println(Arrays.toString(arr2));
System.out.println(ans);
//System.out.println(Arrays.toString(arr2));
}
}
}
| java |
1303 | A | A. Erasing Zeroestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. Each character is either 0 or 1.You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met.You may erase some (possibly none) 0's from the string. What is the minimum number of 0's that you have to erase?InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Then tt lines follow, each representing a test case. Each line contains one string ss (1≤|s|≤1001≤|s|≤100); each character of ss is either 0 or 1.OutputPrint tt integers, where the ii-th integer is the answer to the ii-th testcase (the minimum number of 0's that you have to erase from ss).ExampleInputCopy3
010011
0
1111000
OutputCopy2
0
0
NoteIn the first test case you have to delete the third and forth symbols from string 010011 (it turns into 0111). | [
"implementation",
"strings"
] | /*
⣿⣿⣿⣿⣿⣿⡷⣯⢿⣿⣷⣻⢯⣿⡽⣻⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣇⠸⣿⣿⣆⠹⣿⣿⢾⣟⣯⣿⣿⣿⣿⣿⣿⣽⣻⣿⣿⣿⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣻⣽⡿⣿⣎⠙⣿⣞⣷⡌⢻⣟⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣿⣿⣿⣿⣿⣿⡄⠹⣿⣿⡆⠻⣿⣟⣯⡿⣽⡿⣿⣿⣿⣿⣽⡷⣯⣿⣿⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣟⣷⣿⣿⣿⡀⠹⣟⣾⣟⣆⠹⣯⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⢠⡘⣿⣿⡄⠉⢿⣿⣽⡷⣿⣻⣿⣿⣿⣿⡝⣷⣯⢿⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣯⢿⣾⢿⣿⡄⢄⠘⢿⣞⡿⣧⡈⢷⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⢸⣧⠘⣿⣷⠈⣦⠙⢿⣽⣷⣻⣽⣿⣿⣿⣿⣌⢿⣯⢿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣟⣯⣿⢿⣿⡆⢸⡷⡈⢻⡽⣷⡷⡄⠻⣽⣿⣿⡿⣿⣿⣿⣿⣿⣿⣷⣿⣿⣿⣿⣏⢰⣯⢷⠈⣿⡆⢹⢷⡌⠻⡾⢋⣱⣯⣿⣿⣿⣿⡆⢻⡿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⡎⣿⢾⡿⣿⡆⢸⣽⢻⣄⠹⣷⣟⣿⣄⠹⣟⣿⣿⣟⣿⣿⣿⣿⣿⣿⣽⣿⣿⣿⡇⢸⣯⣟⣧⠘⣷⠈⡯⠛⢀⡐⢾⣟⣷⣻⣿⣿⣿⡿⡌⢿⣻⣿⣿
⣿⣿⣿⣿⣿⣿⣧⢸⡿⣟⣿⡇⢸⣯⣟⣮⢧⡈⢿⣞⡿⣦⠘⠏⣹⣿⣽⢿⣿⣿⣿⣿⣯⣿⣿⣿⡇⢸⣿⣿⣾⡆⠹⢀⣠⣾⣟⣷⡈⢿⣞⣯⢿⣿⣿⣿⢷⠘⣯⣿⣿
⣿⣿⣿⣿⣿⣿⣿⡈⣿⢿⣽⡇⠘⠛⠛⠛⠓⠓⠈⠛⠛⠟⠇⢀⢿⣻⣿⣯⢿⣿⣿⣿⣷⢿⣿⣿⠁⣾⣿⣿⣿⣧⡄⠇⣹⣿⣾⣯⣿⡄⠻⣽⣯⢿⣻⣿⣿⡇⢹⣾⣿
⣿⣿⣿⣿⣿⣿⣿⡇⢹⣿⡽⡇⢸⣿⣿⣿⣿⣿⣞⣆⠰⣶⣶⡄⢀⢻⡿⣯⣿⡽⣿⣿⣿⢯⣟⡿⢀⣿⣿⣿⣿⣿⣧⠐⣸⣿⣿⣷⣿⣿⣆⠹⣯⣿⣻⣿⣿⣿⢀⣿⢿
⣿⣿⣿⣿⣿⣿⣿⣿⠘⣯⡿⡇⢸⣿⣿⣿⣿⣿⣿⣿⣧⡈⢿⣳⠘⡄⠻⣿⢾⣽⣟⡿⣿⢯⣿⡇⢸⣿⣿⣿⣿⣿⣿⡀⢾⣿⣿⣿⣿⣿⣿⣆⠹⣾⣷⣻⣿⡿⡇⢸⣿
⣿⣿⣿⣿⣿⣿⣿⣿⡇⢹⣿⠇⢸⣿⣿⣿⣿⣿⣿⣿⣿⣷⣄⠻⡇⢹⣆⠹⣟⣾⣽⣻⣟⣿⣽⠁⣾⣿⣿⣿⣿⣿⣿⣇⣿⣿⠿⠛⠛⠉⠙⠋⢀⠁⢘⣯⣿⣿⣧⠘⣿
⣿⣿⣿⣿⣿⣿⣿⣿⣿⡈⣿⡃⢼⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣦⡙⠌⣿⣆⠘⣿⣞⡿⣞⡿⡞⢠⣿⣿⣿⣿⣿⡿⠛⠉⠁⢀⣀⣠⣤⣤⣶⣶⣶⡆⢻⣽⣞⡿⣷⠈⣿
⣿⣿⣿⣿⣿⣿⣿⣿⡿⠃⠘⠁⠉⠉⠉⠉⠉⠉⠉⠉⠉⠙⠛⠛⢿⣄⢻⣿⣧⠘⢯⣟⡿⣽⠁⣾⣿⣿⣿⣿⣿⡃⢀⢀⠘⠛⠿⢿⣻⣟⣯⣽⣻⣵⡀⢿⣯⣟⣿⢀⣿
⣿⣿⣿⣟⣿⣿⣿⣿⣶⣶⡆⢀⣿⣾⣿⣾⣷⣿⣶⠿⠚⠉⢀⢀⣤⣿⣷⣿⣿⣷⡈⢿⣻⢃⣼⣿⣿⣿⣿⣻⣿⣿⣿⡶⣦⣤⣄⣀⡀⠉⠛⠛⠷⣯⣳⠈⣾⡽⣾⢀⣿
⣿⢿⣿⣿⣻⣿⣿⣿⣿⣿⡿⠐⣿⣿⣿⣿⠿⠋⠁⢀⢀⣤⣾⣿⣿⣿⣿⣿⣿⣿⣿⣌⣥⣾⡿⣿⣿⣷⣿⣿⢿⣷⣿⣿⣟⣾⣽⣳⢯⣟⣶⣦⣤⡾⣟⣦⠘⣿⢾⡁⢺
⣿⣻⣿⣿⡷⣿⣿⣿⣿⣿⡗⣦⠸⡿⠋⠁⢀⢀⣠⣴⢿⣿⣽⣻⢽⣾⣟⣷⣿⣟⣿⣿⣿⣳⠿⣵⣧⣼⣿⣿⣿⣿⣿⣾⣿⣿⣿⣿⣿⣽⣳⣯⣿⣿⣿⣽⢀⢷⣻⠄⠘
⣿⢷⣻⣿⣿⣷⣻⣿⣿⣿⡷⠛⣁⢀⣀⣤⣶⣿⣛⡿⣿⣮⣽⡻⣿⣮⣽⣻⢯⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣯⢀⢸⣿⢀⡆
⠸⣟⣯⣿⣿⣷⢿⣽⣿⣿⣷⣿⣷⣆⠹⣿⣶⣯⠿⣿⣶⣟⣻⢿⣷⣽⣻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢀⣯⣟⢀⡇
⣇⠹⣟⣾⣻⣿⣿⢾⡽⣿⣿⣿⣿⣿⣆⢹⣶⣿⣻⣷⣯⣟⣿⣿⣽⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⢀⡿⡇⢸⡇
⣿⣆⠹⣷⡻⣽⣿⣯⢿⣽⣻⣿⣿⣿⣿⣆⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠛⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠇⢸⣿⠇⣼⡇
⡙⠾⣆⠹⣿⣦⠛⣿⢯⣷⢿⡽⣿⣿⣿⣿⣆⠻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠃⠎⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠏⢀⣿⣾⣣⡿⡇
⣿⣷⡌⢦⠙⣿⣿⣌⠻⣽⢯⣿⣽⣻⣿⣿⣿⣧⠩⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡏⢰⢣⠘⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠃⢀⢀⢿⣞⣷⢿⡇
⣿⣽⣆⠹⣧⠘⣿⣿⡷⣌⠙⢷⣯⡷⣟⣿⣿⣿⣷⡀⡹⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣈⠃⣸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⢀⣴⡧⢀⠸⣿⡽⣿⢀
⢻⣽⣿⡄⢻⣷⡈⢿⣿⣿⢧⢀⠙⢿⣻⡾⣽⣻⣿⣿⣄⠌⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠛⢁⣰⣾⣟⡿⢀⡄⢿⣟⣿⢀
⡄⢿⣿⣷⢀⠹⣟⣆⠻⣿⣿⣆⢀⣀⠉⠻⣿⡽⣯⣿⣿⣷⣈⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠋⢀⣠⠘⣯⣷⣿⡟⢀⢆⠸⣿⡟⢸
⣷⡈⢿⣿⣇⢱⡘⢿⣷⣬⣙⠿⣧⠘⣆⢀⠈⠻⣷⣟⣾⢿⣿⣆⠹⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠋⣠⡞⢡⣿⢀⣿⣿⣿⠇⡄⢸⡄⢻⡇⣼
⣿⣷⡈⢿⣿⡆⢣⡀⠙⢾⣟⣿⣿⣷⡈⠂⠘⣦⡈⠿⣯⣿⢾⣿⣆⠙⠻⠿⠿⠿⠿⡿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠿⠛⢋⣠⣾⡟⢠⣿⣿⢀⣿⣿⡟⢠⣿⢈⣧⠘⢠⣿
⣿⣿⣿⣄⠻⣿⡄⢳⡄⢆⡙⠾⣽⣿⣿⣆⡀⢹⡷⣄⠙⢿⣿⡾⣿⣆⢀⡀⢀⢀⢀⢀⢀⢀⢀⢀⢀⢀⢀⢀⣀⣠⣴⡿⣯⠏⣠⣿⣿⡏⢸⣿⡿⢁⣿⣿⢀⣿⠆⢸⣿
⣿⣿⣿⣿⣦⡙⣿⣆⢻⡌⢿⣶⢤⣉⣙⣿⣷⡀⠙⠽⠷⠄⠹⣿⣟⣿⣆⢙⣋⣤⣤⣤⣄⣀⢀⢀⢀⢀⣾⣿⣟⡷⣯⡿⢃⣼⣿⣿⣿⠇⣼⡟⣡⣿⣿⣿⢀⡿⢠⠈⣿
⣿⣿⣿⣿⣿⣷⣮⣿⣿⣿⡌⠁⢤⣤⣤⣤⣬⣭⣴⣶⣶⣶⣆⠈⢻⣿⣿⣆⢻⣿⣿⣿⣿⣿⣿⣷⣶⣤⣌⣉⡘⠛⠻⠶⣿⣿⣿⣿⡟⣰⣫⣴⣿⣿⣿⣿⠄⣷⣿⣿⣿
*/
import java.awt.*;
import java.io.*;
import java.util.*;
import java.util.List;
import java.util.StringTokenizer;
public class Ex3 {
static FastScanner in = new FastScanner();
public static void main(String[] args) {
PrintWriter out = new PrintWriter(System.out);
int q = in.nextInt();
for (int e = 0; e < q; e++) {
String str = in.nextToken();
int cout = 0;
int len =str.length();
int idx = 0;
int end = 0;
for(int i = 0; i < len;i++){
if(str.charAt(i) == '1'){
idx = i;
break;
}
}
for(int i = len-1; i >= 0;i--){
if(str.charAt(i) == '1'){
end = i;
break;
}
}
for(int i = idx; i <= end;i++){
if(end!=0 && str.charAt(i) == '0'){
cout++;
}
}
out.println(cout);
}
out.flush();
}
static int[] arr(int n) {
int arr[] = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
return arr;
}
static private long factorial(long n) {
long result = 1;
if (n == 1 || n == 0) {
return result;
}
result = n * factorial(n - 1);
return result;
}
static long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
static long lcm(long a, long b) {
return a * b / gcd(a, b);
}
public static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
init();
}
public FastScanner(String name) {
init(name);
}
public FastScanner(boolean isOnlineJudge) {
if (!isOnlineJudge || System.getProperty("ONLINE_JUDGE") != null) {
init();
} else {
init("input.txt");
}
}
private void init() {
br = new BufferedReader(new InputStreamReader(System.in));
}
private void init(String name) {
try {
br = new BufferedReader(new FileReader(name));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public String nextToken() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public long nextLong() {
return Long.parseLong(nextToken());
}
public double nextDouble() {
return Double.parseDouble(nextToken());
}
}
public static void mergeSort(int[] arr) {
int n = arr.length;
if (n == 1) return;
int mid = n / 2;
int left[] = new int[mid];
int right[] = new int[n - mid];
for (int i = 0; i < mid; i++) {
left[i] = arr[i];
}
for (int i = mid; i < n; i++) {
right[i - mid] = arr[i];
}
mergeSort(left);
mergeSort(right);
merge(arr, left, right);
}
public static void merge(int arr[], int left[], int right[]) {
int lenLeft = left.length;
int lenRight = right.length;
int i = 0;
int j = 0;
int idx = 0;
while (i < lenLeft && j < lenRight) {
if (left[i] < right[j]) {
arr[idx] = left[i];
i++;
idx++;
} else {
arr[idx] = right[j];
j++;
idx++;
}
}
for (int ll = i; ll < lenLeft; ll++) {
arr[idx++] = left[ll];
}
for (int rr = j; rr < lenRight; rr++) {
arr[idx++] = right[rr];
}
}
public static void bubbleSort(int [] sort_arr){
int len = sort_arr.length;
for (int i=0;i<len-1;++i){
for(int j=0;j<len-i-1; ++j){
if(sort_arr[j+1]<sort_arr[j]){
int swap = sort_arr[j];
sort_arr[j] = sort_arr[j+1];
sort_arr[j+1] = swap;
}
}
}
}
}
| 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.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.*;
public class weird_algrithm {
static BufferedWriter output = new BufferedWriter(
new OutputStreamWriter(System.out));
static BufferedReader sc = new BufferedReader(new InputStreamReader(System.in));
static int mod = 1000000007;
static String toReturn = "";
static int steps = Integer.MAX_VALUE;
static int maxlen = 1000005;
/*MATHEMATICS FUNCTIONS START HERE
MATHS
MATHS
MATHS
MATHS*/
static long gcd(long a, long b) {
if(b == 0) return a;
else return gcd(b, a % b);
}
static long powerMod(long x, long y, int mod) {
if(y == 0) return 1;
long temp = powerMod(x, y / 2, mod);
temp = ((temp % mod) * (temp % mod)) % mod;
if(y % 2 == 0) return temp;
else return ((x % mod) * (temp % mod)) % mod;
}
static long modInverse(long n, int p) {
return powerMod(n, p - 2, p);
}
static long nCr(int n, int r, int mod, long [] fact, long [] ifact) {
return ((fact[n] % mod) * ((ifact[r] * ifact[n - r]) % mod)) % mod;
}
static boolean isPrime(long a) {
if(a == 1) return false;
else if(a == 2 || a == 3 || a== 5) return true;
else if(a % 2 == 0 || a % 3 == 0) return false;
for(int i = 5; i * i <= a; i = i + 6) {
if(a % i == 0 || a % (i + 2) == 0) return false;
}
return true;
}
static int [] seive(int a) {
int [] toReturn = new int [a + 1];
for(int i = 0; i < a; i++) toReturn[i] = 1;
toReturn[0] = 0;
toReturn[1] = 0;
toReturn[2] = 1;
for(int i = 2; i * i <= a; i++) {
if(toReturn[i] == 0) continue;
for(int j = 2 * i; j <= a; j += i) toReturn[j] = 0;
}
return toReturn;
}
static long [] fact(int a) {
long [] arr = new long[a + 1];
arr[0] = 1;
for(int i = 1; i < a + 1; i++) {
arr[i] = (arr[i - 1] * i) % mod;
}
return arr;
}
/*MATHS
MATHS
MATHS
MATHS
MATHEMATICS FUNCTIONS END HERE */
/*SWAP FUNCTION START HERE
SWAP
SWAP
SWAP
SWAP
*/
static void swap(int i, int j, long[] arr) {
long temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
static void swap(int i, int j, int[] arr) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
static void swap(int i, int j, String [] arr) {
String temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
static void swap(int i, int j, char [] arr) {
char temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
/*SWAP
SWAP
SWAP
SWAP
SWAP FUNCTION END HERE*/
/*BINARY SEARCH METHODS START HERE
* BINARY SEARCH
* BINARY SEARCH
* BINARY SEARCH
* BINARY SEARCH
*/
static boolean BinaryCheck(long test, long [] arr, long health) {
for(int i = 0; i <= arr.length - 1; i++) {
if(i == arr.length - 1) health -= test;
else if(arr[i + 1] - arr[i] > test) {
health = health - test;
}else {
health = health - (arr[i + 1] - arr[i]);
}
if(health <= 0) return true;
}
return false;
}
static long binarySearchModified(long start1, long n, ArrayList<Long> arr, int a, long r) {
long start = start1, end = n, ans = -1;
while(start < end) {
long mid = (start + end) / 2;
//System.out.println(mid);
if(arr.get((int)mid) + arr.get(a) <= r && mid != start1) {
ans = mid;
start = mid + 1;
}else{
end = mid;
}
}
//System.out.println();
return ans;
}
static int binarySearch(int start, int end, ArrayList<Integer> arr, long val) {
while(start <= end) {
int mid = (start + end) / 2;
if(arr.get(mid) > val) end = mid - 1;
else if(arr.get(mid) == val) {
if(mid - 1 >= 0 && arr.get(mid - 1) == val) {
end = mid - 1;
}else return mid;
}
else start = mid + 1;
}
return start;
}
/*BINARY SEARCH
* BINARY SEARCH
* BINARY SEARCH
* BINARY SEARCH
* BINARY SEARCH
BINARY SEARCH METHODS END HERE*/
/*RECURSIVE FUNCTION START HERE
* RECURSIVE
* RECURSIVE
* RECURSIVE
* RECURSIVE
*/
static int recurse(int x, int y, int n, int steps1, Integer [][] dp) {
if(x > n || y > n) return 0;
if(dp[x][y] != null) {
return dp[x][y];
}
else if(x == n || y == n) {
return steps1;
}
return dp[x][y] = Math.max(recurse(x + y, y, n, steps1 + 1, dp), recurse(x, x + y, n, steps1 + 1, dp));
}
/*RECURSIVE
* RECURSIVE
* RECURSIVE
* RECURSIVE
* RECURSIVE
RECURSIVE FUNCTION END HERE*/
/*GRAPH FUNCTIONS START HERE
* GRAPH
* GRAPH
* GRAPH
* GRAPH
* */
static class edge{
int from, to;
long weight;
public edge(int x, int y, long weight2) {
this.from = x;
this.to = y;
this.weight = weight2;
}
}
static class sort implements Comparator<pair>{
@Override
public int compare(pair o1, pair o2) {
// TODO Auto-generated method stub
return (int)o1.a - (int)o2.a;
}
}
static void addEdge(ArrayList<ArrayList<edge>> graph, int from, int to, long weight) {
edge temp = new edge(from, to, weight);
edge temp1 = new edge(to, from, weight);
graph.get(from).add(temp);
//graph.get(to).add(temp1);
}
static int ans = 0;
static void topoSort(ArrayList<ArrayList<Integer>> graph, int vertex, boolean [] visited, ArrayList<Integer> toReturn) {
if(visited[vertex]) return;
visited[vertex] = true;
for(int i = 0; i < graph.get(vertex).size(); i++) {
if(!visited[graph.get(vertex).get(i)]) topoSort(graph, graph.get(vertex).get(i), visited, toReturn);
}
toReturn.add(vertex);
}
static boolean isCyclicDirected(ArrayList<ArrayList<Integer>> graph, int vertex, boolean [] visited, boolean [] reStack) {
if(reStack[vertex]) return true;
if(visited[vertex]) return false;
reStack[vertex] = true;
visited[vertex] = true;
for(int i = 0; i < graph.get(vertex).size(); i++) {
if(isCyclicDirected(graph, graph.get(vertex).get(i), visited, reStack)) return true;
}
reStack[vertex] = false;
return false;
}
static int e = 0;
static long mst(PriorityQueue<edge> pq, int nodes) {
long weight = 0;
while(!pq.isEmpty()) {
edge temp = pq.poll();
int x = parent(parent, temp.to);
int y = parent(parent, temp.from);
if(x != y) {
//System.out.println(temp.weight);
union(x, y, rank, parent);
weight += temp.weight;
e++;
}
}
return weight;
}
static void floyd(long [][] dist) { // to find min distance between two nodes
for(int k = 0; k < dist.length; k++) {
for(int i = 0; i < dist.length; i++) {
for(int j = 0; j < dist.length; j++) {
if(dist[i][j] > dist[i][k] + dist[k][j]) {
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
}
}
static void dijkstra(ArrayList<ArrayList<edge>> graph, long [] dist, int src) {
for(int i = 0; i < dist.length; i++) dist[i] = Long.MAX_VALUE / 2;
dist[src] = 0;
boolean visited[] = new boolean[dist.length];
PriorityQueue<pair> pq = new PriorityQueue<>(new sort());
pq.add(new pair(src, 0));
while(!pq.isEmpty()) {
pair temp = pq.poll();
int index = (int)temp.a;
for(int i = 0; i < graph.get(index).size(); i++) {
if(dist[graph.get(index).get(i).to] > dist[index] + graph.get(index).get(i).weight) {
dist[graph.get(index).get(i).to] = dist[index] + graph.get(index).get(i).weight;
pq.add(new pair(graph.get(index).get(i).to, graph.get(index).get(i).weight));
}
}
}
}
static int parent1 = -1;
static boolean ford(ArrayList<ArrayList<edge>> graph1, ArrayList<edge> graph, long [] dist, int src, int [] parent) {
for(int i = 0; i < dist.length; i++) dist[i] = Long.MIN_VALUE / 2;
dist[src] = 0;
boolean hasNeg = false;
for(int i = 0; i < dist.length - 1; i++) {
for(int j = 0; j < graph.size(); j++) {
int from = graph.get(j).from;
int to = graph.get(j).to;
long weight = graph.get(j).weight;
if(dist[to] < dist[from] + weight) {
dist[to] = dist[from] + weight;
parent[to] = from;
}
}
}
for(int i = 0; i < graph.size(); i++) {
int from = graph.get(i).from;
int to = graph.get(i).to;
long weight = graph.get(i).weight;
if(dist[to] < dist[from] + weight) {
parent1 = from;
hasNeg = true;
/*
* dfs(graph1, parent1, new boolean[dist.length], dist.length - 1);
* //System.out.println(ans); dfs(graph1, 0, new boolean[dist.length], parent1);
*/
//System.out.println(ans);
if(ans == 2) break;
else ans = 0;
}
}
return hasNeg;
}
/*GRAPH FUNCTIONS END HERE
* GRAPH
* GRAPH
* GRAPH
* GRAPH
*/
/*disjoint Set START HERE
* disjoint Set
* disjoint Set
* disjoint Set
* disjoint Set
*/
static int [] rank;
static int [] parent;
static int parent(int [] parent, int x) {
if(parent[x] == x) return x;
else return parent[x] = parent(parent, parent[x]);
}
static boolean union(int x, int y, int [] rank, int [] parent) {
if(parent(parent, x) == parent(parent, y)) {
return true;
}
if(rank[x] > rank[y]) {
swap(x, y, rank);
}
rank[x] += rank[y];
parent[y] = x;
return false;
}
/*disjoint Set END HERE
* disjoint Set
* disjoint Set
* disjoint Set
* disjoint Set
*/
/*INPUT START HERE
* INPUT
* INPUT
* INPUT
* INPUT
* INPUT
*/
static int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(sc.readLine());
}
static long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(sc.readLine());
}
static long [] inputLongArr() throws NumberFormatException, IOException{
String [] s = sc.readLine().split(" ");
long [] toReturn = new long[s.length];
for(int i = 0; i < s.length; i++) {
toReturn[i] = Long.parseLong(s[i]);
}
return toReturn;
}
static int max = 0;
static int [] inputIntArr() throws NumberFormatException, IOException{
String [] s = sc.readLine().split(" ");
//System.out.println(s.length);
int [] toReturn = new int[s.length];
for(int i = 0; i < s.length; i++) {
toReturn[i] = Integer.parseInt(s[i]);
}
return toReturn;
}
/*INPUT
* INPUT
* INPUT
* INPUT
* INPUT
* INPUT END HERE
*/
static long [] preCompute(int level) {
long [] toReturn = new long[level];
toReturn[0] = 1;
toReturn[1] = 16;
for(int i = 2; i < level; i++) {
toReturn[i] = ((toReturn[i - 1] % mod) * (toReturn[i - 1] % mod)) % mod;
}
return toReturn;
}
static class pair{
long a;
long b;
long d;
public pair(long in, long y) {
this.a = in;
this.b = y;
this.d = 0;
}
}
static int [] nextGreaterBack(char [] s) {
Stack<Integer> stack = new Stack<>();
int [] toReturn = new int[s.length];
for(int i = 0; i < s.length; i++) {
if(!stack.isEmpty() && s[stack.peek()] >= s[i]) {
stack.pop();
}
if(stack.isEmpty()) {
stack.push(i);
toReturn[i] = -1;
}else {
toReturn[i] = stack.peek();
stack.push(i);
}
}
return toReturn;
}
static int [] nextGreaterFront(char [] s) {
Stack<Integer> stack = new Stack<>();
int [] toReturn = new int[s.length];
for(int i = s.length - 1; i >= 0; i--) {
if(!stack.isEmpty() && s[stack.peek()] >= s[i]) {
stack.pop();
}
if(stack.isEmpty()) {
stack.push(i);
toReturn[i] = -1;
}else {
toReturn[i] = stack.peek();
stack.push(i);
}
}
return toReturn;
}
static int lps(String s) {
int max = 0;
int [] lps = new int[s.length()];
lps[0] = 0;
int j = 0;
for(int i = 1; i < lps.length; i++) {
j = lps[i - 1];
while(j > 0 && s.charAt(i) != s.charAt(j)) j = lps[j - 1];
if(s.charAt(i) == s.charAt(j)) {
lps[i] = j + 1;
max = Math.max(max, lps[i]);
}
}
return max;
}
static int [][] vectors = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
static String dir = "DRUL";
static boolean check(int i, int j, boolean [][] visited) {
if(i >= visited.length || j >= visited[0].length) return false;
if(i < 0 || j < 0) return false;
return true;
}
static void selectionSort(long arr[], long [] arr1, ArrayList<ArrayList<Integer>> ans)
{
int n = arr.length;
for (int i = 0; i < n-1; i++)
{
int min_idx = i;
for (int j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
else if(arr[j] == arr[min_idx]) {
if(arr1[j] < arr1[min_idx]) min_idx = j;
}
if(i == min_idx) {
continue;
}
ArrayList<Integer> p = new ArrayList<Integer>();
p.add(min_idx + 1);
p.add(i + 1);
ans.add(new ArrayList<Integer>(p));
swap(i, min_idx, arr);
swap(i, min_idx, arr1);
}
}
static int saved = Integer.MAX_VALUE;
static String ans1 = "";
public static boolean isValid(int x, int y, String [] mat) {
if(x >= mat.length || x < 0) return false;
if(y >= mat[0].length() || y < 0) return false;
return true;
}
static boolean recurse1(int i, int j, int [][] arr, int sum, Boolean [][][] dp) {
if(i == arr.length - 1 && j == arr[0].length - 1) {
if(sum + arr[i][j] == 0) return true;
return false;
}
if(i == arr.length) return false;
else if(j == arr[0].length) return false;
if(sum < 0 && dp[i][j][arr.length + arr[0].length + 1 + sum] != null) return dp[i][j][arr.length + arr[0].length + 1 + sum];
if(sum > 0 && dp[i][j][sum] != null) return dp[i][j][sum];
if(sum < 0) dp[i][j][arr.length + arr[0].length + 1 + sum] = recurse1(i + 1, j, arr, sum + arr[i][j], dp) || recurse1(i, j + 1, arr, sum + arr[i][j], dp);
return dp[i][j][sum] = recurse1(i + 1, j, arr, sum + arr[i][j], dp) || recurse1(i, j + 1, arr, sum + arr[i][j], dp);
}
public static void recurse3(ArrayList<Character> arr, int index, String s, int max, ArrayList<String> toReturn) {
if(s.length() == max) {
toReturn.add(s);
return;
}
if(index == arr.size()) return;
recurse3(arr, index + 1, s + arr.get(index), max, toReturn);
recurse3(arr, index + 1, s, max, toReturn);
}
/*
if(arr[i] > q) return Math.max(f(i + 1, q - 1) + 1, f(i + 1, q);
else return f(i + 1, q) + 1
*/
static void dfsDP(ArrayList<ArrayList<Integer>> graph, int src, int [] dp1, int [] dp2, int parent) {
int sum1 = 0; int sum2 = 0;
for(int x : graph.get(src)) {
if(x == parent) continue;
dfsDP(graph, x, dp1, dp2, src);
sum1 += Math.min(dp1[x], dp2[x]);
sum2 += dp1[x];
}
dp1[src] = 1 + sum1;
dp2[src] = sum2;
System.out.println(src + " " + dp1[src] + " " + dp2[src]);
}
static int balanced = 0;
static int [] dfs(ArrayList<ArrayList<Integer>> graph, int src, int parent, String color) {
int black = 0; int white = 0;
for(int x : graph.get(src)) {
if(x == parent) continue;
int [] temp = dfs(graph, x, src, color);
black += temp[0];
white += temp[1];
}
int [] toReturn = new int [2];
if(color.charAt(src) == 'W') {
toReturn[0] = black;
toReturn[1] = white + 1;
if(toReturn[0] == toReturn[1]) {
balanced++;
}
}else {
toReturn[0] = black + 1;
toReturn[1] = white;
if(toReturn[0] == toReturn[1]) {
balanced++;
}
}
return toReturn;
}
public static long recurse(String s, int i, int p, int k, int [] cost) {
if(i >= s.length()) return 0;
if(i < p) {
return recurse(s, i + 1, p, k, cost);
}else {
if(i == p) {
long poss1 = Long.MAX_VALUE;
if(s.charAt(i) == '1') {
poss1 = Math.min(recurse(s, i + k, p, k, cost), recurse(s, i + 1, p + 1, k, cost) + cost[1]);
}else {
poss1 = Math.min(recurse(s, i + k, p, k, cost) + cost[0], recurse(s, i + 1, p + 1, k, cost) + cost[1]);
}
return poss1;
}else {
if(s.charAt(i) == '1') {
return recurse(s, i + k, p, k, cost);
}else return recurse(s, i + k, p, k, cost) + cost[0];
}
}
}
static void solve() throws IOException {
int n = nextInt();
int [] arr = inputIntArr();
HashMap<Integer, Long> map = new HashMap<Integer, Long>();
int max1 = 0;
for(int i = 0; i < arr.length; i++) {
int diff = arr[i] - (i + 1);
max1 = Math.max(max1, arr[i]);
if(map.containsKey(diff)) {
map.put(diff, map.get(diff) + arr[i]);
}else {
map.put(diff, (long)arr[i]);
}
}
long max = 0;
for(int x : map.keySet()) {
max = Math.max(max, map.get(x));
}
output.write(Math.max(max1, max) + "\n");
}
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
//int t = Integer.parseInt(sc.readLine()); for(int i = 0; i < t; i++)
solve();
output.flush();
}
}
class TreeNode {
int val;
TreeNode next;
public TreeNode(int x, TreeNode y) {
this.val = x;
this.next = y;
}
}
/*
1
10
6 10 7 9 11 99 45 20 88 31
*/
| java |
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.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.*;
import java.util.function.BiFunction;
import java.util.function.Function;
public class Main {
static BiFunction<Integer, Integer, Integer> ADD = (x, y) -> (x + y);
static BiFunction<ArrayList<Integer>, ArrayList<Integer>, ArrayList<Integer>> ADD_ARRAY_LIST = (x, y) -> {
x.addAll(y);
return x;
};
static Function<Pair<Integer, Integer>, Integer> GET_FIRST = (x) -> (x.first);
static Function<Pair<Integer, Integer>, Integer> GET_SECOND = (x) -> (x.second);
static Comparator<Pair<Integer, Integer>> C = Comparator.comparing(x -> x.first + x.second);
static long MOD = 1_000_000_000 + 7;
public static void main(String[] args) throws Exception {
long startTime = System.nanoTime();
int t =in.nextInt();
while (t-- > 0) {
solve();
}
long endTime = System.nanoTime();
err.println("Execution Time : +" + (endTime - startTime) / 1000000 + " ms");
exit(0);
}
static void solve() {
int n = in.nextInt();
int[] data = ArrayUtils.MergeSort(in.readAllInts(2*n));
out.println(data[n] - data[n - 1]);
}
static void debug(Object... args) {
for (Object a : args) {
out.println(a);
}
}
static int dist(Pair<Integer, Integer> a, Pair<Integer, Integer> b) {
return Math.abs(a.first - b.first) + Math.abs(a.second - b.second);
}
static void y() {
out.println("YES");
}
static void n() {
out.println("NO");
}
static int[] stringToArray(String s) {
return s.chars().map(x -> Character.getNumericValue(x)).toArray();
}
static <T> T min(T a, T b, Comparator<T> C) {
if (C.compare(a, b) <= 0) {
return a;
}
return b;
}
static <T> T max(T a, T b, Comparator<T> C) {
if (C.compare(a, b) >= 0) {
return a;
}
return b;
}
static void fail() {
out.println("-1");
}
static class Pair<T, R> {
public T first;
public R second;
public Pair(T first, R second) {
this.first = first;
this.second = second;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final Pair<?, ?> pair = (Pair<?, ?>) o;
return Objects.equals(first, pair.first) && Objects.equals(second, pair.second);
}
@Override
public int hashCode() {
return Objects.hash(first, second);
}
@Override
public String toString() {
return "Pair{" + "a=" + first + ", b=" + second + '}';
}
public T getFirst() {
return first;
}
public R getSecond() {
return second;
}
}
static <T, R> Pair<T, R> make_pair(T a, R b) {
return new Pair<>(a, b);
}
static long mod_inverse(long a, long m) {
Number x = new Number(0);
Number y = new Number(0);
extended_gcd(a, m, x, y);
return (m + x.v % m) % m;
}
static long extended_gcd(long a, long b, Number x, Number y) {
long d = a;
if (b != 0) {
d = extended_gcd(b, a % b, y, x);
y.v -= (a / b) * x.v;
} else {
x.v = 1;
y.v = 0;
}
return d;
}
static class Number {
long v = 0;
public Number(long v) {
this.v = v;
}
}
static long lcm(long a, long b, long c) {
return lcm(a, lcm(b, c));
}
static long lcm(long a, long b) {
long p = 1L * a * b;
return p / gcd(a, b);
}
static long gcd(long a, long b) {
while (b != 0) {
long t = b;
b = a % b;
a = t;
}
return a;
}
static long gcd(long a, long b, long c) {
return gcd(a, gcd(b, c));
}
static class ArrayUtils {
static void swap(int[] a, int i, int j) {
int 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 print(char[] a) {
for (char c : a) {
out.print(c);
}
out.println("");
}
static int[] reverse(int[] data) {
int[] p = new int[data.length];
for (int i = 0, j = data.length - 1; i < data.length; i++, j--) {
p[i] = data[j];
}
return p;
}
static void prefixSum(long[] data) {
for (int i = 1; i < data.length; i++) {
data[i] += data[i - 1];
}
}
static void prefixSum(int[] data) {
for (int i = 1; i < data.length; i++) {
data[i] += data[i - 1];
}
}
static long[] reverse(long[] data) {
long[] p = new long[data.length];
for (int i = 0, j = data.length - 1; i < data.length; i++, j--) {
p[i] = data[j];
}
return p;
}
static char[] reverse(char[] data) {
char[] p = new char[data.length];
for (int i = 0, j = data.length - 1; i < data.length; i++, j--) {
p[i] = data[j];
}
return p;
}
static int[] MergeSort(int[] A) {
if (A.length > 1) {
int q = A.length / 2;
int[] left = new int[q];
int[] right = new int[A.length - q];
System.arraycopy(A, 0, left, 0, q);
System.arraycopy(A, q, right, 0, A.length - q);
int[] left_sorted = MergeSort(left);
int[] right_sorted = MergeSort(right);
return Merge(left_sorted, right_sorted);
} else {
return A;
}
}
static int[] Merge(int[] left, int[] right) {
int[] A = new int[left.length + right.length];
int i = 0;
int j = 0;
for (int k = 0; k < A.length; k++) {
// To handle left becoming empty
if (i == left.length && j < right.length) {
A[k] = right[j];
j++;
continue;
}
// To handle right becoming empty
if (j == right.length && i < left.length) {
A[k] = left[i];
i++;
continue;
}
if (left[i] <= right[j]) {
A[k] = left[i];
i++;
} else {
A[k] = right[j];
j++;
}
}
return A;
}
static long[] MergeSort(long[] A) {
if (A.length > 1) {
int q = A.length / 2;
long[] left = new long[q];
long[] right = new long[A.length - q];
System.arraycopy(A, 0, left, 0, q);
System.arraycopy(A, q, right, 0, A.length - q);
long[] left_sorted = MergeSort(left);
long[] right_sorted = MergeSort(right);
return Merge(left_sorted, right_sorted);
} else {
return A;
}
}
static long[] Merge(long[] left, long[] right) {
long[] A = new long[left.length + right.length];
int i = 0;
int j = 0;
for (int k = 0; k < A.length; k++) {
// To handle left becoming empty
if (i == left.length && j < right.length) {
A[k] = right[j];
j++;
continue;
}
// To handle right becoming empty
if (j == right.length && i < left.length) {
A[k] = left[i];
i++;
continue;
}
if (left[i] <= right[j]) {
A[k] = left[i];
i++;
} else {
A[k] = right[j];
j++;
}
}
return A;
}
static int upper_bound(long[] data, long num, int start) {
int low = start;
int high = data.length - 1;
int mid = 0;
int ans = -1;
while (low <= high) {
mid = (low + high) / 2;
if (data[mid] < num) {
low = mid + 1;
} else if (data[mid] >= num) {
high = mid - 1;
ans = mid;
}
}
if (ans == -1) {
return 100000000;
}
return ans;
}
static int lower_bound(int[] data, int num, int start) {
int low = start;
int high = data.length - 1;
int mid = 0;
int ans = -1;
while (low <= high) {
mid = (low + high) / 2;
if (data[mid] <= num) {
low = mid + 1;
ans = mid;
} else if (data[mid] > num) {
high = mid - 1;
}
}
if (ans == -1) {
return 100000000;
}
return ans;
}
}
static boolean[] primeSieve(int n) {
boolean[] primes = new boolean[n + 1];
Arrays.fill(primes, true);
primes[0] = false;
primes[1] = false;
for (int i = 2; i <= Math.sqrt(n); i++) {
if (primes[i]) {
for (int j = i * i; j <= n; j += i) {
primes[j] = false;
}
}
}
return primes;
}
// Iterative Version
static HashMap<Integer, Boolean> subsets_sum_iter(int[] data) {
HashMap<Integer, Boolean> temp = new HashMap<Integer, Boolean>();
temp.put(data[0], true);
for (int i = 1; i < data.length; i++) {
HashMap<Integer, Boolean> t1 = new HashMap<Integer, Boolean>(temp);
t1.put(data[i], true);
for (int j : temp.keySet()) {
t1.put(j + data[i], true);
}
temp = t1;
}
return temp;
}
static HashMap<Integer, Integer> subsets_sum_count(int[] data) {
HashMap<Integer, Integer> temp = new HashMap<>();
temp.put(data[0], 1);
for (int i = 1; i < data.length; i++) {
HashMap<Integer, Integer> t1 = new HashMap<>(temp);
t1.merge(data[i], 1, ADD);
for (int j : temp.keySet()) {
t1.merge(j + data[i], temp.get(j) + 1, ADD);
}
temp = t1;
}
return temp;
}
static class Graph {
ArrayList<Integer>[] g;
boolean[] visited;
ArrayList<Integer>[] graph(int n) {
g = new ArrayList[n];
visited = new boolean[n];
for (int i = 0; i < n; i++) {
g[i] = new ArrayList<>();
}
return g;
}
void BFS(int s) {
Queue<Integer> Q = new ArrayDeque<>();
visited[s] = true;
Q.add(s);
while (!Q.isEmpty()) {
int v = Q.poll();
for (int a : g[v]) {
if (!visited[a]) {
visited[a] = true;
Q.add(a);
}
}
}
}
}
static class SparseTable {
int[] log;
int[][] st;
public SparseTable(int n, int k, int[] data, BiFunction<Integer, Integer, Integer> f) {
log = new int[n + 1];
st = new int[n][k + 1];
log[1] = 0;
for (int i = 2; i <= n; i++) {
log[i] = log[i / 2] + 1;
}
for (int i = 0; i < data.length; i++) {
st[i][0] = data[i];
}
for (int j = 1; j <= k; j++)
for (int i = 0; i + (1 << j) <= data.length; i++)
st[i][j] = f.apply(st[i][j - 1], st[i + (1 << (j - 1))][j - 1]);
}
public int query(int L, int R, BiFunction<Integer, Integer, Integer> f) {
int j = log[R - L + 1];
return f.apply(st[L][j], st[R - (1 << j) + 1][j]);
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 2048);
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 long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public int[] readAllInts(int n) {
int[] p = new int[n];
for (int i = 0; i < n; i++) {
p[i] = in.nextInt();
}
return p;
}
public int[] readAllInts(int n, int s) {
int[] p = new int[n + s];
for (int i = s; i < n + s; i++) {
p[i] = in.nextInt();
}
return p;
}
public long[] readAllLongs(int n) {
long[] p = new long[n];
for (int i = 0; i < n; i++) {
p[i] = in.nextLong();
}
return p;
}
public long[] readAllLongs(int n, int s) {
long[] p = new long[n + s];
for (int i = s; i < n + s; i++) {
p[i] = in.nextLong();
}
return p;
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
static void exit(int a) {
out.close();
err.close();
System.exit(a);
}
static InputStream inputStream = System.in;
static OutputStream outputStream = System.out;
static OutputStream errStream = System.err;
static InputReader in = new InputReader(inputStream);
static PrintWriter out = new PrintWriter(outputStream);
static PrintWriter err = new PrintWriter(errStream);
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
} | java |
1311 | F | F. Moving Pointstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn points on a coordinate axis OXOX. The ii-th point is located at the integer point xixi and has a speed vivi. It is guaranteed that no two points occupy the same coordinate. All nn points move with the constant speed, the coordinate of the ii-th point at the moment tt (tt can be non-integer) is calculated as xi+t⋅vixi+t⋅vi.Consider two points ii and jj. Let d(i,j)d(i,j) be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points ii and jj coincide at some moment, the value d(i,j)d(i,j) will be 00.Your task is to calculate the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of points.The second line of the input contains nn integers x1,x2,…,xnx1,x2,…,xn (1≤xi≤1081≤xi≤108), where xixi is the initial coordinate of the ii-th point. It is guaranteed that all xixi are distinct.The third line of the input contains nn integers v1,v2,…,vnv1,v2,…,vn (−108≤vi≤108−108≤vi≤108), where vivi is the speed of the ii-th point.OutputPrint one integer — the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).ExamplesInputCopy3
1 3 2
-100 2 3
OutputCopy3
InputCopy5
2 1 4 3 5
2 2 2 3 4
OutputCopy19
InputCopy2
2 1
-3 0
OutputCopy0
| [
"data structures",
"divide and conquer",
"implementation",
"sortings"
] | import java.io.*;
import java.util.*;
public class Main {
static class segtree{
long[] t;
int n;
public segtree(int[] a) {
this.n = a.length;
this.t = new long[4 * this.n];
Arrays.fill(this.t, 0);
build(a, 1, 0, this.n-1);
}
public segtree(int n) {
this.n = n;
this.t = new long[4 * n];
Arrays.fill(this.t, 0);
}
public void build(int[] a, int v, int tl, int tr) {
if(tl == tr)
t[v] = a[tl];
else {
int tm = (tl + tr) / 2;
build(a, 2 * v, tl, tm);
build(a, 2 * v + 1, tm + 1, tr);
t[v] = t[2 * v] + t[2 * v + 1];
}
}
public long query(int v, int tl, int tr, int l, int r) {
if(l > r)
return 0;
if(l == tl && r == tr)
return t[v];
int tm = (tl + tr) / 2;
return query(2 * v, tl, tm, l, Math.min(r, tm)) +
query(2 * v + 1, tm + 1, tr, Math.max(l, tm + 1), r);
}
public long query(int l, int r){
return query(1, 0, n - 1, l, r);
}
public void update(int pos, int val, int v, int tl, int tr) {
if(tl == tr)
t[v] += val;
else {
int tm = (tl + tr) / 2;
if(pos <= tm)
update(pos, val, 2 * v, tl, tm);
else
update(pos, val, 2 * v + 1, tm + 1 ,tr);
t[v] = t[2 * v] + t[2 * v + 1];
}
}
public void update(int pos, int val) {
update(pos, val, 1, 0, n - 1);
}
}
static class pair {
int x, y;
public pair(int x, int y) {
this.x = x;
this.y = y;
}
}
public static void main(String args[]) throws Exception {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] x = new int[n];
int[] v = new int[n];
pair a[] = new pair[n];
for(int i = 0; i < n; ++i)
x[i] = in.nextInt();
for(int i = 0; i < n; ++i){
v[i] = in.nextInt();
a[i] = new pair(x[i], v[i]);
}
ArrayList<pair> list = new ArrayList<>();
for(int i = 0; i < n; ++i)
list.add(a[i]);
Collections.sort(list, new Comparator<pair>() {
@Override public int compare(pair a, pair b) {
return a.x - b.x;
}
});
for(int i = 0; i < n; ++i)
a[i] = list.get(i);
ArrayList<Integer> speed = new ArrayList<>();
for(int i = 0; i < n; ++i)
speed.add(v[i]);
Collections.sort(speed);
for(int i = 0; i < n; ++i)
v[i] = speed.get(i);
ArrayList<Integer> uniq = new ArrayList<>();
for(int i = 0, j = 0; i < n; i = j) {
while(j < n && v[i] == v[j]) ++j;
uniq.add(v[i]);
}
int k = uniq.size();
v = new int[k];
for(int i = 0; i < k; ++i)
v[i] = uniq.get(i);
long ans = 0;
segtree cnt = new segtree(k);
segtree sumx = new segtree(k);
for(int i = 0; i < n; ++i) {
int pos = Arrays.binarySearch(v, a[i].y);
ans += cnt.query(0, pos) * a[i].x - sumx.query(0,pos);
cnt.update(pos, 1);
sumx.update(pos, a[i].x);
}
System.out.println(ans);
}
} | 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.util.Arrays;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.io.OutputStreamWriter;
import java.util.LinkedList;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.util.Collection;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Objects;
import java.util.TreeMap;
import java.io.Writer;
import java.io.BufferedReader;
import java.util.Queue;
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);
DCowAndFields solver = new DCowAndFields();
solver.solve(1, in, out);
out.close();
}
static class DCowAndFields {
int n;
int m;
int k;
int[] sp;
ArrayList<Integer>[] g;
int[] dist;
boolean[] vis;
public void solve(int testNumber, InputReader in, OutputWriter out) {
pre(in);
int[] d1 = bfs(0);
int[] d2 = bfs(n - 1);
int ini = d1[n - 1];
ArrayList<Pair> list = new ArrayList<>();
TreeMap<Pair, Integer> hm = new TreeMap<>();
for (int a : sp) {
list.add(new Pair(d1[a], d2[a]));
push(hm, new Pair(d2[a], d1[a]), 1);
}
int max = 0;
Collections.sort(list);
for (int i = 0; i < k - 1; i++) {
Pair p = list.get(i);
pull(hm, new Pair(p.b, p.a), 1);
Pair p2 = hm.lastKey();
int val = Math.min(ini, Math.min(p.a + p.b, Math.min(p2.a + p2.b, p.a + 1 + p2.a)));
max = Math.max(val, max);
}
int ans = Math.min(max, ini);
out.println(ans);
}
void push(TreeMap<Pair, Integer> map, Pair k, int v) {
//map[k] += v;
if (!map.containsKey(k))
map.put(k, v);
else
map.put(k, map.get(k) + v);
}
void pull(TreeMap<Pair, Integer> map, Pair k, int v) {
//assumes map[k] >= v
//map[k] -= v
int lol = map.get(k);
if (lol == v)
map.remove(k);
else
map.put(k, lol - v);
}
int[] bfs(int st) {
int[] d = new int[n];
Arrays.fill(d, Integer.MAX_VALUE);
Queue<Integer> q = new LinkedList<>();
q.add(st);
d[st] = 0;
while (!q.isEmpty()) {
int p = q.poll();
for (int a : g[p]) {
if (d[a] > d[p] + 1) {
d[a] = d[p] + 1;
q.add(a);
}
}
}
return d;
}
void pre(InputReader in) {
n = in.nextInt();
m = in.nextInt();
k = in.nextInt();
sp = new int[k];
for (int i = 0; i < k; i++) {
sp[i] = in.nextInt() - 1;
}
g = new ArrayList[n];
dist = new int[n];
vis = new boolean[n];
for (int i = 0; i < n; i++) g[i] = new ArrayList<>();
for (int i = 0; i < m; i++) {
int a = in.nextInt() - 1, b = in.nextInt() - 1;
g[a].add(b);
g[b].add(a);
}
}
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 nextInt() {
return Integer.parseInt(next());
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void println(int i) {
writer.println(i);
}
}
}
| 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.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.LinkedList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Abhishek Patel
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
String ls = in.nextString();
String rs = in.nextString();
LinkedList<Integer> larr[] = new LinkedList[27];
LinkedList<Integer> rarr[] = new LinkedList[27];
LinkedList<Pair<Integer, Integer>> ans = new LinkedList<>();
int i = 0, j;
for (i = 0; i < 27; i++) {
larr[i] = new LinkedList<>();
rarr[i] = new LinkedList<>();
}
for (i = 0; i < n; i++) {
char c = ls.charAt(i);
char d = rs.charAt(i);
if (c == '?')
larr[26].add(i);
else
larr[c - 'a'].add(i);
if (d == '?')
rarr[26].add(i);
else
rarr[d - 'a'].add(i);
}
for (i = 0; i < 26; i++) {
int d = Math.min(larr[i].size(), rarr[i].size());
for (j = 0; j < d; j++) {
int u = larr[i].remove(0) + 1;
int y = rarr[i].remove(0) + 1;
ans.add(new Pair(u, y));
}
}
for (i = 0; i < 26; i++) {
int d = Math.min(larr[i].size(), rarr[26].size());
for (j = 0; j < d; j++) {
int u = larr[i].remove(0) + 1;
int y = rarr[26].remove(0) + 1;
ans.add(new Pair(u, y));
}
if (rarr[26].size() == 0)
break;
}
for (i = 0; i < 26; i++) {
int d = Math.min(larr[26].size(), rarr[i].size());
for (j = 0; j < d; j++) {
int u = larr[26].remove(0) + 1;
int y = rarr[i].remove(0) + 1;
ans.add(new Pair(u, y));
}
if (larr[26].size() == 0)
break;
}
int d = Math.min(larr[26].size(), rarr[26].size());
for (j = 0; j < d; j++) {
int u = larr[26].remove(0) + 1;
int y = rarr[26].remove(0) + 1;
ans.add(new Pair(u, y));
}
out.println(ans.size());
for (Pair t : ans) {
out.println(t.getFirst() + " " + t.getSecond());
}
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String nextString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class Pair<A, B> {
A first;
B second;
public Pair(A first, B second) {
super();
this.first = first;
this.second = second;
}
public int hashCode() {
int hashFirst = first != null ? first.hashCode() : 0;
int hashSecond = second != null ? second.hashCode() : 0;
return (hashFirst + hashSecond) * hashSecond + hashFirst;
}
public boolean equals(Object other) {
if (other instanceof Pair) {
Pair otherPair = (Pair) other;
return
((this.first == otherPair.first ||
(this.first != null && otherPair.first != null &&
this.first.equals(otherPair.first))) &&
(this.second == otherPair.second ||
(this.second != null && otherPair.second != null &&
this.second.equals(otherPair.second))));
}
return false;
}
public String toString() {
return "(" + first + ", " + second + ")";
}
public A getFirst() {
return first;
}
public B getSecond() {
return second;
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void println(int i) {
writer.println(i);
}
}
}
| java |
1291 | B | B. Array Sharpeningtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given an array a1,…,ana1,…,an of nn non-negative integers.Let's call it sharpened if and only if there exists an integer 1≤k≤n1≤k≤n such that a1<a2<…<aka1<a2<…<ak and ak>ak+1>…>anak>ak+1>…>an. In particular, any strictly increasing or strictly decreasing array is sharpened. For example: The arrays [4][4], [0,1][0,1], [12,10,8][12,10,8] and [3,11,15,9,7,4][3,11,15,9,7,4] are sharpened; The arrays [2,8,2,8,6,5][2,8,2,8,6,5], [0,1,1,0][0,1,1,0] and [2,5,6,9,8,8][2,5,6,9,8,8] are not sharpened. You can do the following operation as many times as you want: choose any strictly positive element of the array, and decrease it by one. Formally, you can choose any ii (1≤i≤n1≤i≤n) such that ai>0ai>0 and assign ai:=ai−1ai:=ai−1.Tell if it's possible to make the given array sharpened using some number (possibly zero) of these operations.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤15 0001≤t≤15 000) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤3⋅1051≤n≤3⋅105).The second line of each test case contains a sequence of nn non-negative integers a1,…,ana1,…,an (0≤ai≤1090≤ai≤109).It is guaranteed that the sum of nn over all test cases does not exceed 3⋅1053⋅105.OutputFor each test case, output a single line containing "Yes" (without quotes) if it's possible to make the given array sharpened using the described operations, or "No" (without quotes) otherwise.ExampleInputCopy10
1
248618
3
12 10 8
6
100 11 15 9 7 8
4
0 1 1 0
2
0 0
2
0 1
2
1 0
2
1 1
3
0 1 0
3
1 0 1
OutputCopyYes
Yes
Yes
No
No
Yes
Yes
Yes
Yes
No
NoteIn the first and the second test case of the first test; the given array is already sharpened.In the third test case of the first test; we can transform the array into [3,11,15,9,7,4][3,11,15,9,7,4] (decrease the first element 9797 times and decrease the last element 44 times). It is sharpened because 3<11<153<11<15 and 15>9>7>415>9>7>4.In the fourth test case of the first test, it's impossible to make the given array sharpened. | [
"greedy",
"implementation"
] | import 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 B_Array_Sharpening {
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 n = f.nextInt();
int arr[] = f.nextArray(n);
if(n == 1) {
out.println("Yes");
return;
}
boolean flag1 = true;
int ind1 = -1;
for(int i = 0; i < n; i++) {
if(arr[i] < i) {
flag1 = false;
ind1 = i;
break;
}
}
if(flag1) {
out.println("Yes");
return;
}
int curr = arr[ind1-1];
while(ind1 < n) {
int prev = curr;
curr = min(arr[ind1], prev-1);
ind1++;
}
if(curr >= 0) {
out.println("Yes");
return;
}
boolean flag2 = true;
int ind2 = -1;
for(int i = n-1; i >= 0; i--) {
if(arr[i] < n-i-1) {
flag2 = false;
ind2 = i;
break;
}
}
if(flag2) {
out.println("Yes");
return;
}
curr = arr[ind2+1];
while(ind2 >= 0) {
int next = curr;
curr = min(arr[ind2], next-1);
ind2--;
}
if(curr >= 0) {
out.println("Yes");
return;
}
out.println("No");
}
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 |
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"
] | //package round628;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.Set;
public class E2 {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni();
int[] a = na(n);
int[] lpf = enumLowestPrimeFactors(1000000);
int[] from = new int[n];
int[] to = new int[n];
Set<Integer> sol = new HashSet<>();
Set<Long> cors = new HashSet<>();
int ep = 0;
boolean two = false;
for(int v : a){
int[][] f = factorFast(v, lpf);
assert f.length <= 2;
int dis = 0;
int whi = 0;
for(int[] u : f){
u[1] &= 1;
if(u[1] == 1){
dis++;
whi = u[0];
}
}
if(dis == 0){
out.println(1);
return;
}
if(dis == 1){
if(!sol.add(whi)){
two = true;
}
}else{
long code = (long)f[0][0]<<32|f[1][0];
if(!cors.add(code)){
two = true;
}
from[ep] = f[0][0];
to[ep] = f[1][0];
ep++;
}
}
if(two){
out.println(2);
return;
}
// o - - o
// cycle
// simple
int[][] g = packU(1000001, from, to, ep);
int ans = Integer.MAX_VALUE;
{
int I = 999999999;
int[] qs = new int[n+5];
int[] ds = new int[1000005];
Arrays.fill(ds, I);
for(int s : sol){
int qp = 0;
qs[qp++] = s;
ds[s] = 0;
inner:
for(int y = 0;y < qp;y++){
int cur = qs[y];
if(ds[cur] + 2 >= ans)break;
for(int e : g[cur]){
if(ds[e] > ds[cur] + 1){
ds[e] = ds[cur] + 1;
if(sol.contains(e)){
ans = Math.min(ans, ds[e] + 2);
break inner;
}
qs[qp++] = e;
}
}
}
for(int y = 0;y < qp;y++){
ds[qs[y]] = I;
}
}
}
int[] primes = sieveEratosthenes(1000);
int m = primes.length;
int[] lds = new int[1000001];
Arrays.fill(lds, 9999999);
int[] qs = new int[n+5];
int[] pre = new int[1000005];
Arrays.fill(pre, -1);
for(int i = 0;i < m;i++){
int qp = 0;
qs[qp++] = primes[i];
lds[primes[i]] = 0;
pre[primes[i]] = -1;
for(int y = 0;y < qp;y++){
int cur = qs[y];
for(int e : g[cur]){
if(lds[e] > lds[cur] + 1){
lds[e] = lds[cur] + 1;
pre[e] = cur;
qs[qp++] = e;
}else if(e != pre[cur]){
ans = Math.min(ans, lds[e] + lds[cur] + 1);
}
}
}
for(int y = 0;y < qp;y++){
lds[qs[y]] = 9999999;
pre[qs[y]] = -1;
}
}
if(ans >= 999999){
out.println(-1);
}else{
out.println(ans);
}
}
public static int[] sieveEratosthenes(int n) {
if (n <= 32) {
int[] primes = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31 };
for (int i = 0; i < primes.length; i++) {
if (n < primes[i]) {
return Arrays.copyOf(primes, i);
}
}
return primes;
}
int u = n + 32;
double lu = Math.log(u);
int[] ret = new int[(int) (u / lu + u / lu / lu * 1.5)];
ret[0] = 2;
int pos = 1;
int[] isnp = new int[(n + 1) / 32 / 2 + 1];
int sup = (n + 1) / 32 / 2 + 1;
int[] tprimes = { 3, 5, 7, 11, 13, 17, 19, 23, 29, 31 };
for (int tp : tprimes) {
ret[pos++] = tp;
int[] ptn = new int[tp];
for (int i = (tp - 3) / 2; i < tp << 5; i += tp)
ptn[i >> 5] |= 1 << (i & 31);
for (int j = 0; j < sup; j += tp) {
for (int i = 0; i < tp && i + j < sup; i++) {
isnp[j + i] |= ptn[i];
}
}
}
// 3,5,7
// 2x+3=n
int[] magic = { 0, 1, 23, 2, 29, 24, 19, 3, 30, 27, 25, 11, 20, 8, 4, 13, 31, 22, 28, 18, 26, 10, 7, 12, 21, 17,
9, 6, 16, 5, 15, 14 };
int h = n / 2;
for (int i = 0; i < sup; i++) {
for (int j = ~isnp[i]; j != 0; j &= j - 1) {
int pp = i << 5 | magic[(j & -j) * 0x076be629 >>> 27];
int p = 2 * pp + 3;
if (p > n)
break;
ret[pos++] = p;
if ((long) p * p > n)
continue;
for (int q = (p * p - 3) / 2; q <= h; q += p)
isnp[q >> 5] |= 1 << q;
}
}
return Arrays.copyOf(ret, pos);
}
public static int[][] packU(int n, int[] from, int[] to){ return packU(n, from, to, from.length); }
public static int[][] packU(int n, int[] from, int[] to, int sup)
{
int[][] g = new int[n][];
int[] p = new int[n];
for(int i = 0;i < sup;i++)p[from[i]]++;
for(int i = 0;i < sup;i++)p[to[i]]++;
for(int i = 0;i < n;i++)g[i] = new int[p[i]];
for(int i = 0;i < sup;i++){
g[from[i]][--p[from[i]]] = to[i];
g[to[i]][--p[to[i]]] = from[i];
}
return g;
}
public static int[][] factorFast(int n, int[] lpf)
{
int[][] f = new int[9][];
int q = 0;
while(lpf[n] > 0){
int p = lpf[n];
if(q == 0 || p != f[q-1][0]){
f[q++] = new int[]{p, 1};
}else{
f[q-1][1]++;
}
n /= p;
}
if(n > 1){
// big prime
return new int[][]{{n, 1}};
}
return Arrays.copyOf(f, q);
}
public static int[] enumLowestPrimeFactors(int n) {
int tot = 0;
int[] lpf = new int[n + 1];
int u = n + 32;
double lu = Math.log(u);
int[] primes = new int[(int) (u / lu + u / lu / lu * 1.5)];
for (int i = 2; i <= n; i++)
lpf[i] = i;
for (int p = 2; p <= n; p++) {
if (lpf[p] == p)
primes[tot++] = p;
int tmp;
for (int i = 0; i < tot && primes[i] <= lpf[p] && (tmp = primes[i] * p) <= n; i++) {
lpf[tmp] = primes[i];
}
}
return lpf;
}
void run() throws Exception
{
// int n = 100000, m = 99999;
// int[] primes = sieveEratosthenes(500000);
//
// Random gen = new Random();
// StringBuilder sb = new StringBuilder();
// sb.append(n + " ");
// Set<Integer> hey = new HashSet<>();
// for(int rep = 0;rep < n;rep++){
// tr(rep);
// inner:
// while(true){
// int x = gen.nextInt(primes.length);
// int y = gen.nextInt(primes.length);
// if(x != y && (long)primes[x] * primes[y] <= 500000){
// if(hey.add(primes[x] * primes[y])){
// sb.append(primes[x] * primes[y] + " ");
// break inner;
// }
// }
// }
// }
//
// int num = 0;
// for(int i = 0;i < primes.length;i++){
// for(int j = i+1;j < primes.length && num <= n;j++){
// if((long)primes[i] * primes[j] <= 1000000){
// sb.append(primes[i] * primes[j] + " ");
// num++;
// }
// }
// }
// INPUT = sb.toString();
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 E2().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 |
1311 | D | D. Three Integerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers a≤b≤ca≤b≤c.In one move, you can add +1+1 or −1−1 to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero) number of times, you can even perform this operation several times with one number. Note that you cannot make non-positive numbers using such operations.You have to perform the minimum number of such operations in order to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB.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 tt lines describe test cases. Each test case is given on a separate line as three space-separated integers a,ba,b and cc (1≤a≤b≤c≤1041≤a≤b≤c≤104).OutputFor each test case, print the answer. In the first line print resres — the minimum number of operations you have to perform to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB. On the second line print any suitable triple A,BA,B and CC.ExampleInputCopy8
1 2 3
123 321 456
5 10 15
15 18 21
100 100 101
1 22 29
3 19 38
6 30 46
OutputCopy1
1 1 3
102
114 228 456
4
4 8 16
6
18 18 18
1
100 100 100
7
1 22 22
2
1 19 38
8
6 24 48
| [
"brute force",
"math"
] | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
static int mod=(int)1e9+7;
public static void main(String[] args) throws Exception {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0){
int a=sc.nextInt(),b=sc.nextInt(),c=sc.nextInt();
int aa=0, bb=0, cc=0, ans = Integer.MAX_VALUE;
for (int i = 1; i <= c; i++) {
int curA = i, curB = 0, curC = 0;
for (int j = 1; j * i <= 2 * b; j++) {
curB = j * i;
for (int k = 1; k * curB <= 2 * c; k++) {
curC = k * curB;
int tmp = Math.abs(a - curA) + Math.abs(b - curB) + Math.abs(c - curC);
if (tmp < ans) {
ans = tmp;
aa = curA; bb = curB; cc = curC;
}
}
}
}
System.out.println(ans);
System.out.println(aa+" "+bb+" "+cc);
}
}
} | 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.util.*;
import java.io.*;
public class practice {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(new BufferedWriter(new PrintWriter(System.out)));
StringBuilder sb = new StringBuilder();
int t = Integer.parseInt(br.readLine());
while (t --> 0) {
int n = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
Map<Integer, Integer> map = new HashMap<>();
boolean ans = false;
for (int i = 0; i < n; i++) {
int ele = Integer.parseInt(st.nextToken());
if (map.containsKey(ele)) {
int diff = i - map.get(ele);
if (diff > 1) ans = true;
} else map.put(ele, i);
}
sb.append(ans ? "YES" : "NO").append("\n");
}
pw.println(sb.toString().trim());
pw.close();
br.close();
}
} | java |
1305 | A | A. Kuroni and the Giftstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni has nn daughters. As gifts for them, he bought nn necklaces and nn bracelets: the ii-th necklace has a brightness aiai, where all the aiai are pairwise distinct (i.e. all aiai are different), the ii-th bracelet has a brightness bibi, where all the bibi are pairwise distinct (i.e. all bibi are different). Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the ii-th daughter receives a necklace with brightness xixi and a bracelet with brightness yiyi, then the sums xi+yixi+yi should be pairwise distinct. Help Kuroni to distribute the gifts.For example, if the brightnesses are a=[1,7,5]a=[1,7,5] and b=[6,1,2]b=[6,1,2], then we may distribute the gifts as follows: Give the third necklace and the first bracelet to the first daughter, for a total brightness of a3+b1=11a3+b1=11. Give the first necklace and the third bracelet to the second daughter, for a total brightness of a1+b3=3a1+b3=3. Give the second necklace and the second bracelet to the third daughter, for a total brightness of a2+b2=8a2+b2=8. Here is an example of an invalid distribution: Give the first necklace and the first bracelet to the first daughter, for a total brightness of a1+b1=7a1+b1=7. Give the second necklace and the second bracelet to the second daughter, for a total brightness of a2+b2=8a2+b2=8. Give the third necklace and the third bracelet to the third daughter, for a total brightness of a3+b3=7a3+b3=7. This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!InputThe input consists of multiple test cases. The first line contains an 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 single integer nn (1≤n≤1001≤n≤100) — the number of daughters, necklaces and bracelets.The second line of each test case contains nn distinct integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000) — the brightnesses of the necklaces.The third line of each test case contains nn distinct integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤10001≤bi≤1000) — the brightnesses of the bracelets.OutputFor each test case, print a line containing nn integers x1,x2,…,xnx1,x2,…,xn, representing that the ii-th daughter receives a necklace with brightness xixi. In the next line print nn integers y1,y2,…,yny1,y2,…,yn, representing that the ii-th daughter receives a bracelet with brightness yiyi.The sums x1+y1,x2+y2,…,xn+ynx1+y1,x2+y2,…,xn+yn should all be distinct. The numbers x1,…,xnx1,…,xn should be equal to the numbers a1,…,ana1,…,an in some order, and the numbers y1,…,yny1,…,yn should be equal to the numbers b1,…,bnb1,…,bn in some order. It can be shown that an answer always exists. If there are multiple possible answers, you may print any of them.ExampleInputCopy2
3
1 8 5
8 4 5
3
1 7 5
6 1 2
OutputCopy1 8 5
8 4 5
5 1 7
6 2 1
NoteIn the first test case; it is enough to give the ii-th necklace and the ii-th bracelet to the ii-th daughter. The corresponding sums are 1+8=91+8=9, 8+4=128+4=12, and 5+5=105+5=10.The second test case is described in the statement. | [
"brute force",
"constructive algorithms",
"greedy",
"sortings"
] | import java.util.Scanner;
import java.util.Arrays;
import java.util.Collections;
public class CF2510{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int testCases = scan.nextInt();
while(testCases>0){
int arrayLength = scan.nextInt();
Integer[] bracelets = new Integer[arrayLength];
Integer[] necklaces = new Integer[arrayLength];
for(int i=0; i<arrayLength; i++){
bracelets[i] = scan.nextInt();
}
for(int i=0; i<arrayLength; i++){
necklaces[i] = scan.nextInt();
}
Arrays.sort(bracelets, Collections.reverseOrder());
Arrays.sort(necklaces, Collections.reverseOrder());
for(int num: bracelets){
System.out.print(num+" ");
}
System.out.println();
for(int num: necklaces){
System.out.print(num+" ");
}
System.out.println();
testCases--;
}
}
} | java |
1284 | A | A. New Year and Namingtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputHappy new year! The year 2020 is also known as Year Gyeongja (경자년; gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of nn strings s1,s2,s3,…,sns1,s2,s3,…,sn and mm strings t1,t2,t3,…,tmt1,t2,t3,…,tm. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings xx and yy as the string that is obtained by writing down strings xx and yy one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings s1s1 and t1t1. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if n=3,m=4,s=n=3,m=4,s={"a", "b", "c"}, t=t= {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat. You are given two sequences of strings of size nn and mm and also qq queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system?InputThe first line contains two integers n,mn,m (1≤n,m≤201≤n,m≤20).The next line contains nn strings s1,s2,…,sns1,s2,…,sn. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.The next line contains mm strings t1,t2,…,tmt1,t2,…,tm. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.Among the given n+mn+m strings may be duplicates (that is, they are not necessarily all different).The next line contains a single integer qq (1≤q≤20201≤q≤2020).In the next qq lines, an integer yy (1≤y≤1091≤y≤109) is given, denoting the year we want to know the name for.OutputPrint qq lines. For each line, print the name of the year as per the rule described above.ExampleInputCopy10 12
sin im gye gap eul byeong jeong mu gi gyeong
yu sul hae ja chuk in myo jin sa o mi sin
14
1
2
3
4
10
11
12
13
73
2016
2017
2018
2019
2020
OutputCopysinyu
imsul
gyehae
gapja
gyeongo
sinmi
imsin
gyeyu
gyeyu
byeongsin
jeongyu
musul
gihae
gyeongja
NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal. | [
"implementation",
"strings"
] | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class NewYearAndNaming {
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 m, String[] s, String[] t, int q, int[] y) {
StringBuilder ans = new StringBuilder();
for (int year : y) {
ans.append(s[(year-1)%n]);
ans.append(t[(year-1)%m] + "\n");
}
System.out.print(ans);
}
public static void main(String[] args) {
FastReader in = new FastReader();
int n = in.nextInt();
int m = in.nextInt();
String[] s = new String[n];
for (int i=0; i<n; i++) {
s[i] = in.next();
}
String[] t = new String[m];
for (int i=0; i<m; i++) {
t[i] = in.next();
}
int q = in.nextInt();
int[] y = in.nextArray(q);
solve(n, m, s, t, q, y);
}
}
| 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.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.IOException;
import java.util.TreeSet;
import java.util.ArrayList;
import java.util.HashSet;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
FEhabsLastTheorem solver = new FEhabsLastTheorem();
solver.solve(1, in, out);
out.close();
}
static class FEhabsLastTheorem {
PrintWriter out;
InputReader in;
ArrayList<Integer>[] graph;
HashSet<Integer>[] tset;
int[] par;
int[] dep;
int max_cycle = 0;
int start = 0;
int end = 0;
DSU ob;
boolean[] visited;
int[] tin;
int[] low;
int timer = 0;
int[] cnt = new int[2];
void dfs(int v, int p, int h) {
dep[v] = h;
for (int u : graph[v]) {
if (dep[u] == -1) {
par[u] = v;
dfs(u, v, h + 1);
} else if (u != par[v]) {
if (dep[v] - dep[u] + 1 > max_cycle) {
max_cycle = dep[v] - dep[u] + 1;
start = v;
end = u;
}
}
}
}
void tarjan(int v, int p) {
visited[v] = true;
tin[v] = low[v] = timer++;
for (int u : graph[v]) {
int to = u;
if (to == p) continue;
if (visited[to]) {
low[v] = Math.min(low[v], tin[to]);
} else {
tarjan(to, v);
low[v] = Math.min(low[v], low[to]);
if (low[to] > tin[v]) {
//its a bridge
} else {
ob.unite(to, v);
}
}
}
}
void dfs2(int v, int p, int h) {
dep[v] = h;
cnt[h % 2]++;
for (int u : tset[v]) {
if (u != p)
dfs2(u, v, h + 1);
}
}
TreeSet<Integer> MIS(int n) {
TreeSet<Integer> is = new TreeSet<>();
TreeSet<Pair> set = new TreeSet<>();
int deg[] = new int[n + 1];
for (int i = 0; i < n; ++i) {
set.add(new Pair(graph[i].size(), i));
deg[i] = graph[i].size();
}
while (!set.isEmpty()) {
Pair v = set.pollFirst();
for (int e : graph[v.y]) {
if (set.contains(new Pair(deg[e], e))) {
for (int f : graph[e]) {
if (set.contains(new Pair(deg[f], f))) {
set.remove(new Pair(deg[f], f));
set.add(new Pair(--deg[f], f));
}
}
set.remove(new Pair(deg[e], e));
}
}
is.add(v.y);
}
return is;
}
public void solve(int testNumber, InputReader in, PrintWriter out) {
this.out = out;
this.in = in;
int n = ni();
int m = ni();
visited = new boolean[n];
low = new int[n];
tin = new int[n];
ob = new DSU(n);
graph = new ArrayList[n];
tset = new HashSet[n];
par = new int[n];
dep = new int[n];
int sq = (int) Math.sqrt(n);
if (sq * sq != n)
sq++;
int i = 0;
for (i = 0; i < n; i++) {
graph[i] = new ArrayList<>();
tset[i] = new HashSet<>();
}
Arrays.fill(dep, -1);
for (i = 0; i < m; i++) {
int u = ni() - 1;
int v = ni() - 1;
graph[u].add(v);
graph[v].add(u);
}
dfs(0, -1, 0);
if (max_cycle >= sq) {
pn(2);
pn(max_cycle);
ArrayList<Integer> ans = new ArrayList<>();
for (i = start; i != end; i = par[i])
ans.add(i);
ans.add(end);
for (int x : ans)
p(x + 1 + " ");
return;
}
if (n < 100) {
TreeSet<Integer> mis = MIS(n);
pn(1);
int c = 0;
for (int x : mis) {
p(x + 1 + " ");
c++;
if (c == sq)
break;
}
return;
}
tarjan(0, -1);
int root = -1;
HashSet<Integer> hset = new HashSet<>();
for (i = 0; i < n; i++) {
int father = ob.find(i);
for (int x : graph[i]) {
int lull = ob.find(x);
if (lull == father)
continue;
tset[lull].add(father);
tset[father].add(lull);
}
hset.add(father);
if (father == i)
root = i;
}
dfs2(root, -1, 0);
ArrayList<Integer> ans = new ArrayList<>();
pn(1);
TreeSet<Integer> good = new TreeSet<>();
for (i = 0; i < n; i++)
good.add(i);
if (cnt[0] > cnt[1]) {
int c = 0;
for (int x : hset) {
if (dep[x] % 2 == 0) {
ans.add(x);
good.remove(x);
for (int y : graph[x]) {
good.remove(y);
}
}
if (ans.size() == sq)
break;
}
} else {
int c = 0;
for (int x : hset) {
if (dep[x] % 2 != 0) {
ans.add(x);
good.remove(x);
for (int y : graph[x]) {
good.remove(y);
}
}
if (ans.size() == sq)
break;
}
}
while (ans.size() < sq) {
int x = good.pollFirst();
ans.add(x);
for (int y : graph[x])
good.remove(y);
}
for (int x : ans)
p(x + 1 + " ");
}
int ni() {
return in.nextInt();
}
void pn(long zx) {
out.println(zx);
}
void p(Object o) {
out.print(o);
}
class DSU {
int[] par;
int[] sz;
DSU(int n) {
par = new int[n];
sz = new int[n];
int i = 0;
for (i = 0; i < n; i++) {
par[i] = i;
sz[i] = 1;
}
}
int find(int x) {
if (par[x] != x)
return par[x] = find(par[x]);
return par[x];
}
void unite(int x, int y) {
int x_root = find(x);
int y_root = find(y);
if (x_root == y_root)
return;
if (sz[x_root] <= sz[y_root]) {
par[x_root] = y_root;
sz[y_root] += sz[x_root];
} else {
par[y_root] = x_root;
sz[x_root] += sz[y_root];
}
}
}
class Pair implements Comparable<Pair> {
int x;
int y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
public int compareTo(Pair other) {
if (this.x != other.x)
return this.x - other.x;
return this.y - other.y;
}
public String toString() {
return "(" + x + "," + y + ")";
}
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new UnknownError();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new UnknownError();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
return Integer.parseInt(next());
}
public String next() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuffer res = new StringBuffer();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
| java |
1321 | A | A. Contest for Robotstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is preparing the first programming contest for robots. There are nn problems in it, and a lot of robots are going to participate in it. Each robot solving the problem ii gets pipi points, and the score of each robot in the competition is calculated as the sum of pipi over all problems ii solved by it. For each problem, pipi is an integer not less than 11.Two corporations specializing in problem-solving robot manufacturing, "Robo-Coder Inc." and "BionicSolver Industries", are going to register two robots (one for each corporation) for participation as well. Polycarp knows the advantages and flaws of robots produced by these companies, so, for each problem, he knows precisely whether each robot will solve it during the competition. Knowing this, he can try predicting the results — or manipulating them. For some reason (which absolutely cannot involve bribing), Polycarp wants the "Robo-Coder Inc." robot to outperform the "BionicSolver Industries" robot in the competition. Polycarp wants to set the values of pipi in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot. However, if the values of pipi will be large, it may look very suspicious — so Polycarp wants to minimize the maximum value of pipi over all problems. Can you help Polycarp to determine the minimum possible upper bound on the number of points given for solving the problems?InputThe first line contains one integer nn (1≤n≤1001≤n≤100) — the number of problems.The second line contains nn integers r1r1, r2r2, ..., rnrn (0≤ri≤10≤ri≤1). ri=1ri=1 means that the "Robo-Coder Inc." robot will solve the ii-th problem, ri=0ri=0 means that it won't solve the ii-th problem.The third line contains nn integers b1b1, b2b2, ..., bnbn (0≤bi≤10≤bi≤1). bi=1bi=1 means that the "BionicSolver Industries" robot will solve the ii-th problem, bi=0bi=0 means that it won't solve the ii-th problem.OutputIf "Robo-Coder Inc." robot cannot outperform the "BionicSolver Industries" robot by any means, print one integer −1−1.Otherwise, print the minimum possible value of maxi=1npimaxi=1npi, if all values of pipi are set in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot.ExamplesInputCopy5
1 1 1 0 0
0 1 1 1 1
OutputCopy3
InputCopy3
0 0 0
0 0 0
OutputCopy-1
InputCopy4
1 1 1 1
1 1 1 1
OutputCopy-1
InputCopy9
1 0 0 0 0 0 0 0 1
0 1 1 0 1 1 1 1 0
OutputCopy4
NoteIn the first example; one of the valid score assignments is p=[3,1,3,1,1]p=[3,1,3,1,1]. Then the "Robo-Coder" gets 77 points, the "BionicSolver" — 66 points.In the second example, both robots get 00 points, and the score distribution does not matter.In the third example, both robots solve all problems, so their points are equal. | [
"greedy"
] | import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[] r=new int[n];
for(int i=0;i<n;i++)
r[i]=sc.nextInt();
int[] b=new int[n];
for(int i=0;i<n;i++)
b[i]=sc.nextInt();
int pa=0,pb=0,diff=0,lh=0;int flag=0;
for(int i=0;i<n;i++)
{
if(r[i]==1)
pa++;
if(b[i]==1)
pb++;
if(r[i]==1&&b[i]==0)
lh++;
if(r[i]!=b[i])
flag=1;
}
if(lh==0||pa==0||flag==0)
{
System.out.println("-1");return;
}
if(pa>pb){System.out.println("1");return;}
if(pa==pb){System.out.println("2");return;}
diff=Math.abs(pa-pb);
int c=((diff+1)/lh)+1;
if((diff+1)%lh>0)
System.out.println(c+1);
else
System.out.println(c);
}
}
| java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.