filename_1
stringlengths 8
15
| filename_2
stringlengths 8
12
| code_1
stringlengths 591
24.4k
| code_2
stringlengths 591
35.2k
| labels
int64 0
1
| notes
stringclasses 2
values |
---|---|---|---|---|---|
b8b08542
|
d783d815
|
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.PriorityQueue;
import java.util.Scanner;
import java.util.StringJoiner;
import java.util.StringTokenizer;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.HashSet;
import static java.lang.System.out;
import static java.util.stream.Collectors.joining;
public class C {
static FastScanner sc = new FastScanner(System.in);
public static void main(String[] args) {
try (PrintWriter out = new PrintWriter(System.out)) {
int T = sc.nextInt();
for (int tt = 1; tt <= T; tt++) {
int n = sc.nextInt();
String[] strings = new String[n];
PriorityQueue<Pair>[] frequencies = new PriorityQueue[5];
for (int i = 0; i < 5; i++)
frequencies[i] = new PriorityQueue<>();
for (int i = 0; i < n; i++) {
strings[i] = sc.next();
int[] freq = new int[5];
for (char c : strings[i].toCharArray())
freq[c - 'a']++;
for (int j = 0; j < 5; j++) {
frequencies[j].add(new Pair(freq[j], strings[i].length()));
}
}
int ans = 0;
for (PriorityQueue<Pair> pq : frequencies) {
long curlen = 0;
long curfreq = 0;
int cnt = 0;
while (!pq.isEmpty()) {
Pair pair = pq.remove();
curfreq += pair.freq;
curlen += pair.len;
if (curfreq >= curlen / 2 + 1) {
cnt++;
} else {
break;
}
}
ans = Math.max(ans, cnt);
}
System.out.println(ans);
}
}
}
static class Pair implements Comparable<Pair> {
int freq, len;
public Pair(int freq, int len) {
this.freq = freq;
this.len = len;
}
@Override
public int compareTo(Pair o) {
return -(o.len - 2 * o.freq - len + 2 * freq);
}
@Override
public String toString() {
return freq + " " + len;
}
}
/*
1
5
cbdca
d
a
d
eb
*/
static 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), 32768);
}
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());
}
}
}
|
//package codeforce.div3.r734;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.PriorityQueue;
import java.util.Scanner;
import java.util.StringJoiner;
import java.util.StringTokenizer;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.HashSet;
import static java.lang.System.out;
import static java.util.stream.Collectors.joining;
public class C {
static FastScanner sc = new FastScanner(System.in);
public static void main(String[] args) {
try (PrintWriter out = new PrintWriter(System.out)) {
int T = sc.nextInt();
for (int tt = 1; tt <= T; tt++) {
int n = sc.nextInt();
String[] strings = new String[n];
PriorityQueue<Pair>[] frequencies = new PriorityQueue[5];
for (int i = 0; i < 5; i++)
frequencies[i] = new PriorityQueue<>();
for (int i = 0; i < n; i++) {
strings[i] = sc.next();
int[] freq = new int[5];
for (char c : strings[i].toCharArray())
freq[c - 'a']++;
for (int j = 0; j < 5; j++) {
//if (freq[j] > 0)
frequencies[j].add(new Pair(freq[j], strings[i].length()));
}
}
/* for (int i = 0; i < 5; i++) {
while (!frequencies[i].isEmpty())
System.out.print(frequencies[i].remove() + ", ");
System.out.println();
}*/
int ans = 0;
for (PriorityQueue<Pair> pq : frequencies) {
long curlen = 0;
long curfreq = 0;
int cnt = 0;
while (!pq.isEmpty()) {
Pair pair = pq.remove();
curfreq += pair.freq;
curlen += pair.len;
if (curfreq >= curlen / 2 + 1) {
cnt++;
} else {
break;
}
}
ans = Math.max(ans, cnt);
}
System.out.println(ans);
}
}
}
static class Pair implements Comparable<Pair> {
int freq, len;
public Pair(int freq, int len) {
this.freq = freq;
this.len = len;
}
@Override
public int compareTo(Pair o) {
/*if(freq == 0 && o.freq == 0)
return len - o.len;
if(freq == 0)
return len - (o.len - o.freq);
if(o.freq == 0)
return o.len - (len - freq);
int diff1 = freq * o.len;
int diff2 = o.freq * len;
return diff2 - diff1;*/
return -(o.len - 2*o.freq - len + 2*freq);
}
@Override
public String toString() {
return freq + " " + len;
}
}
/*
1
5
cbdca
d
a
d
eb
*/
static 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), 32768);
}
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());
}
}
}
| 1 |
Plagiarised
|
98950986
|
b9595381
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.*;
public class ReverseString {
static class pair implements Comparable<pair>{
String s;
int contribution;
pair(String s , int contribution){
this.s = s;
this.contribution = contribution;
}
@Override
public int compareTo(pair pair) {
return this.contribution-pair.contribution;
}
public String toString(){
return s + " " + contribution;
}
public int getValue(){
return contribution;
}
}
static int factorOfLetter(String s , char c){
int sum = 0;
for (int i = 0; i < s.length(); i++) {
if(s.charAt(i)==c)sum++;
}
int rem = Math.abs(sum-s.length());
return sum-rem;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
int t = Integer.parseInt(br.readLine());
while (t-->0){
int n = Integer.parseInt(br.readLine());
int max = Integer.MIN_VALUE;
String [] arr = new String[n];
for (int i = 0; i < n; i++) {
arr[i] = br.readLine();
}
for (int i = 0; i < 5; i++) {
int word = 0;
ArrayList<pair> tmp = new ArrayList<>();
for (int j = 0; j < arr.length; j++) {
tmp.add(new pair(arr[j] , factorOfLetter(arr[j] , (char)(i+97))));
}
Collections.sort(tmp);
//System.out.println(tmp);
int acc = 0;
for (int j = tmp.size()-1; j >=0 ; j--) {
acc += tmp.get(j).contribution;
if (acc<=0)break;
else word++;
}
max = Math.max(max , word);
}
System.out.println(max);
}
}
}
|
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main{
static int dest1;
static int dest2;
public static void main(String args[]){
FastScanner in = new FastScanner();
int test=in.nextInt();
while(test-->0){
int n=in.nextInt();
int count[][]=new int[n][5];
int total[]=new int[n];
String words[]=new String[n];
for(int i=0;i<n;i++){
words[i]=in.next();
for(int j=0;j<words[i].length();j++)
count[i][words[i].charAt(j)-'a']++;
total[i]=words[i].length();
}
int max=Integer.MIN_VALUE;
for(int i=0;i<5;i++){
Integer ans[]=new Integer[n];
for(int j=0;j<n;j++){
ans[j]=count[j][i]-(total[j]-count[j][i]);
}
Arrays.sort(ans,Collections.reverseOrder());
int j=0;
int r=0;
while(j<n && r+ans[j]>0){
r+=ans[j];
j++;
}
max=Math.max(j,max);
}
System.out.println(max);
}
}
public static int solve(int start[], int end[], int n)
{
int distance[][]=new int[n][n];
int r=n;
int c=n;
boolean visited[][]=new boolean[n][n];
int startx=start[0];
int starty=start[1];
int endx=end[0];
int endy=end[1];
Pair tmp=new Pair(startx,starty);
Queue<Pair> q=new LinkedList<>();
q.add(tmp);
visited[startx][starty]=true;
distance[startx][starty]=0;
int dx[]={-2,-1,1,2,2,1,-1,-2};
int dy[]={1,2,2,1,-1,-2,-2,-1};
while(!q.isEmpty())
{
Pair cell=q.poll();
int x=cell.x;
int y=cell.y;
int d=distance[x][y];
for(int i=0;i<8;i++)
{
int childx=x+dx[i];
int childy=y+dy[i];
if(valid(childx,childy,r,c,visited))
{
visited[childx][childy]=true;
distance[childx][childy]=d+1;
q.add(new Pair(childx,childy));
}
}
}
return distance[endx][endy];
}
public static boolean valid(int x,int y,int r,int c,boolean visited[][])
{
if(x<0||y<0||x>=r||y>=c)
return false;
if(visited[x][y])
return false;
return true;
}
public static int knight(int i,int j){
if(i==dest1 && j==dest2)
return 0;
if(i<1 || j<1)
return 0;
if(i>8 || j>8)
return 0;
if(i<1 || j>8)
return 0;
if(i>8 || j<1)
return 0;
int min=0;
if(i-1>=1 && j-2>=1)
min+=1+knight(i-1,j-2);
if(i-1>=1 && j+2<=8)
min+=1+knight(i-1,j+2);
if(i-2>=1 && j-1>=1)
min+=1+knight(i-2,j-1);
if(i-2>=1 && j+1<=8)
min+=1+knight(i-2,j+1);
if(i+1<=8 && j-2>=1)
min+=1+knight(i+1,j-2);
if(i+1<=8 && j+2<=8)
min+=1+knight(i+1,j+2);
if(i+2<=8 && j-1>=1)
min+=1+knight(i+2,j-1);
if(i+2<=8 && j+1<=8)
min+=1+knight(i+2,j+1);
return min;
}
}
class FastScanner {
java.io.BufferedReader br = new java.io.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());
}
}
class Pair
{
int x;
int y;
Pair(int i,int j)
{
x=i;
y=j;
}
}
| 0 |
Non-plagiarised
|
ac180326
|
b728ba1d
|
//This code is written by प्रविण शंखपाळ
//package wizard;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.Collections;
import java.util.Comparator;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Stack;
import java.util.Queue;
import java.util.PriorityQueue;
import java.util.List;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.TreeSet;
import java.util.Map;
import java.util.HashMap;
import java.util.Scanner;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.Vector;
public class Dobby {
public static void main(String[] args) {
try {
FastReader fr = new FastReader();
PrintWriter pt = new PrintWriter(System.out);
int t = fr.nextInt();
while (t > 0) {
int n = fr.nextInt(), m = fr.nextInt(), x = fr.nextInt();
ArrayList<Pair> pp = new ArrayList<>();
int A[] = new int[n];
for (int i = 0; i < n; i++) {
A[i] = fr.nextInt();
Pair pr = new Pair(A[i], i);
pp.add(pr);
}
Collections.sort(pp);
Collections.reverse(pp);
int ps[] = new int[n];
int pk[] = new int[n];
Arrays.fill(ps, 0);
Arrays.fill(pk, 0);
int index = 0;
for (int i = 0; i < n; i++) {
if (pk[index] < x) {
pk[index] += pp.get(i).a;
}
ps[pp.get(i).b] = index + 1;
index++;
index = index == m ? 0 : index;
}
pt.println("YES");
for (int i = 0; i < n; i++) {
pt.print(ps[i] + " ");
}
pt.println();
t--;
}
pt.close();
} catch (
Exception e) {
return;
}
}
static void merge(long arr[], int l, int m, int r) {
int n1 = m - l + 1;
int n2 = r - m;
long L[] = new long[n1];
long R[] = new long[n2];
for (int i = 0; i < n1; ++i)
L[i] = arr[l + i];
for (int j = 0; j < n2; ++j)
R[j] = arr[m + 1 + j];
int i = 0, j = 0;
int k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
static void sort(long arr[], int l, int r) {
if (l < r) {
int m = l + (r - l) / 2;
sort(arr, l, m);
sort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
static class Pair implements Comparable<Pair> {
int a, b;
Pair(int a, int b) {
this.a = a;
this.b = b;
}
public int compareTo(Pair o) {
// TODO Auto-generated method stub
if (this.a != o.a)
return Integer.compare(this.a, o.a);
else
return Integer.compare(this.b, o.b);
// return 0;
}
public boolean equals(Object o) {
if (o instanceof Pair) {
Pair p = (Pair) o;
return p.a == a && p.b == b;
}
return false;
}
}
static int binarySearch(int arr[], int first, int last, int key) {
int mid = (first + last) / 2;
while (first <= last) {
if (arr[mid] < key) {
first = mid + 1;
} else if (arr[mid] == key) {
return mid;
} else {
last = mid - 1;
}
mid = (first + last) / 2;
}
return -1;
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
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;
}
}
}
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Objects;
import java.util.Collections;
import java.io.InputStream;
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
CPhoenixAndTowers solver = new CPhoenixAndTowers();
int testCount = Integer.parseInt(in.next());
for (int i = 1; i <= testCount; i++)
solver.solve(i, in, out);
out.close();
}
static class CPhoenixAndTowers {
public void solve(int testNumber, FastReader in, PrintWriter out) {
int n = in.nextInt(), m = in.nextInt(), k = in.nextInt();
ArrayList<Pair<Integer, Integer>> a = new ArrayList<>();
for (int i = 0; i < n; ++i) {
a.add(new Pair<>(in.nextInt(), i));
}
Collections.sort(a);
int[] ans = new int[n];
int[] sum = new int[m];
int j = 1;
for (int i = 0; i < n; ++i) {
ans[a.get(i).y] = j;
sum[j - 1] += a.get(i).x;
j++;
if (j == m + 1) j = 1;
}
for (int i = 1; i < m; ++i) {
if (Math.abs(sum[i - 1] - sum[i]) > k) {
out.println("NO");
}
}
out.println("YES");
for (int e : ans) {
out.print(e + " ");
}
out.println();
}
}
static class Pair<U, V> implements Comparable<Pair<U, V>> {
public U x;
public V y;
public Pair(U x, V y) {
this.x = x;
this.y = y;
}
public int compareTo(Pair<U, V> o) {
int value = ((Comparable<U>) x).compareTo(o.x);
if (value != 0) return value;
return ((Comparable<V>) y).compareTo(o.y);
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair<?, ?> pair = (Pair<?, ?>) o;
return x.equals(pair.x) && y.equals(pair.y);
}
public int hashCode() {
return Objects.hash(x, y);
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private FastReader.SpaceCharFilter filter;
public FastReader(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 next() {
int c = read();
while (isSpaceChar(c)) c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| 0 |
Non-plagiarised
|
51d857bc
|
c392efe7
|
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Round659 {
static int rec = 0;
static int X[] = { -1, 0, 0, 1 };
static int Y[] = { 0, -1, 1, 0 };
static long mod = 1000000007;
static int last=0;
static int maxDepth=0;
static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null)
return;
din.close();
}
}
public static long[] initArray(int n, Reader scan) throws IOException {
long arr[] = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = scan.nextLong();
}
return arr;
}
public static long sum(long arr[]) {
long sum = 0;
for (long i : arr) {
sum += (long) i;
}
return sum;
}
public static long max(long arr[]) {
long max = Long.MIN_VALUE;
for (long i : arr) {
max = Math.max(i, max);
}
return max;
}
public static long min(long arr[]) {
long min = Long.MAX_VALUE;
for (long i : arr) {
min = Math.min(i, min);
}
return min;
}
public static List<Integer>[] initAdjacency(int n, int e, Reader scan, boolean type) throws IOException {
List<Integer> adj[] = new ArrayList[n + 1];
for (int i = 0; i < e; i++) {
int u = scan.nextInt();
int v = scan.nextInt();
if (adj[u] == null)
adj[u] = new ArrayList<>();
if (type && adj[v] == null)
adj[v] = new ArrayList<>();
adj[u].add(v);
if (type)
adj[v].add(u);
}
return adj;
}
public static void main(String[] args) throws IOException {
Reader scan = new Reader();
// Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
while (t-- > 0) {
D(scan);
}
}
public static void D(Reader scan) throws IOException {
int n=scan.nextInt();
int a=scan.nextInt();
int b=scan.nextInt();
int da=scan.nextInt();
int db=scan.nextInt();
List<Integer> adj[]=initAdjacency(n, n-1, scan, true);
int d= dist(a, 0, adj, b);
if(d<=da) {
System.out.println("Alice");
return;
}
if(db<=2*da) {
System.out.println("Alice");
return;
}
MyPair far1= farthest(1, 0, adj);
MyPair far2=farthest(far1.weight, 0, adj);
int diameter= far2.value-1;
if(diameter<=2*da) {
System.out.println("Alice");
}else {
System.out.println("Bob");
}
// int val=d-2*a;
//
// if(val>0) {
// System.out.println("Bob");
// return;
// }
//
// int dep=0;
// for(Integer x: adj[a]) {
// if(x==last) continue;
//
// dep=Math.max(getDepth(x, a, adj), dep);
// }
//
// if(dep>=val) {
// System.out.println("Bob");
// }else {
// System.out.println("Alice");
// }
}
public static MyPair farthest(int i, int parent, List<Integer> adj[]) {
int dist=0;
int node= i;
for(Integer x: adj[i]) {
if(x==parent) continue;
MyPair recAns= farthest(x, i, adj);
if(recAns.value>dist) {
dist= recAns.value;
node= recAns.weight;
}
}
return new MyPair(dist+1, node);
}
public static int getDepth(int i, int parent, List<Integer> adj[]) {
int max=0;
for(Integer x: adj[i]) {
if(x==parent) continue;
max=Math.max(max, getDepth(x, i, adj));
}
return max+1;
}
public static int dist(int i, int parent, List<Integer> adj[], int target) {
if(i==target) return 0;
for(Integer x: adj[i]) {
if(x==parent) continue;
int recAns= dist(x, i, adj, target);
if(recAns!=-1) {
last=x;
return recAns+1;
}
}
return -1;
}
public static void C(int n, String s, int k) {
char arr[]= s.toCharArray();
for(int i=0;i<n;i++) {
if(i+k>=n) break;
if(arr[i]=='0'&&arr[i+k]=='1') {
System.out.println("NO");
return;
}
if(arr[i]=='1'&&arr[i+k]=='0') {
System.out.println("NO");
return;
}
if(arr[i]=='0'||arr[i]=='1') {
if(arr[i+k]=='?') {
arr[i+k]=arr[i];
}
continue;
}
if(arr[i+k]=='0'||arr[i+k]=='1') {
if(arr[i]=='?') {
arr[i]=arr[i+k];
}
continue;
}
}
int c0[]=new int[n];
int c1[]=new int[n];
int last0=0;
int last1=0;
for(int i=0;i<n;i++) {
if(arr[i]=='0') {
last0++;
}else if(arr[i]=='1'){
last1++;
}
c0[i]=last0;
c1[i]=last1;
}
for(int i=k-1;i<n;i++) {
int count0= c0[i]- ((i-k<0)?0: c0[i-k]);
int count1= c1[i]- ((i-k<0)?0: c1[i-k]);
if(count0>k/2||count1>k/2) {
System.out.println("NO");
return;
}
}
System.out.println("YES");
}
public static void A(int n, long arr[]) {
for(int i=n-1;i>=0;i--) {
System.out.print(arr[i]+" ");
}
System.out.println();
}
public static void B(int n, long arr[]) {
for(int i=1;i<n;i++) {
if(arr[i-1]>0) {
arr[i]+= arr[i-1];
arr[i-1]=0;
}
}
// System.out.println(Arrays.toString(arr));
long ans=0;
for(Long x: arr) {
if(x<0) ans+= -x;
}
System.out.println(ans);
}
}
class MyPair {
int value;
int weight;
public MyPair(int value, int w) {
this.value = value;
weight = w;
}
}
|
import java.util.*;
import java.io.*;
import java.math.*;
/**
*
* @Har_Har_Mahadev
*/
/**
* Main , Solution , Remove Public
*/
public class D {
static int visited[];
static int distance[];
private static ArrayList<Integer>[] adj;
private static void BFS(int node) {
visited[node] = 1;
Queue<Integer> q = new LinkedList<Integer>();
q.offer(node);
distance[node] = 0;
while(!q.isEmpty()) {
int curr = q.poll();
for(int child : adj[curr]) {
if(visited[child] == 0) {
q.offer(child);
distance[child] = distance[curr] + 1;
visited[child] = 1;
}
}
}
}
public static void process() throws IOException {
int n = sc.nextInt(),a = sc.nextInt(),b = sc.nextInt(),
da = sc.nextInt(),db = sc.nextInt();
adj = new ArrayList[n+1];
distance = new int[n+1];
visited = new int[n+1];
for(int i = 0; i<=n; i++)adj[i] = new ArrayList<Integer>();
for(int i =1; i<n; i++) {
int u = sc.nextInt(),v = sc.nextInt();
adj[u].add(v);
adj[v].add(u);
}
BFS(a);
if(distance[b] <= da || db-da<=da) {
System.out.println("Alice");
return;
}
ArrayList<Pair> lis = new ArrayList<D.Pair>();
for(int i = 1; i<=n; i++)lis.add(new Pair(distance[i], i));
Collections.sort(lis);
Pair e = lis.get(n-1);
distance = new int[n+1];
visited = new int[n+1];
BFS(e.y);
int max = 0;
for(int i = 1; i<=n; i++)max = max(max,distance[i]);
if(max-da<=da) {
System.out.println("Alice");
return;
}
System.out.println("Bob");
}
//=============================================================================
//--------------------------The End---------------------------------
//=============================================================================
private static void google(int tt) {
System.out.print("Case #" + (tt) + ": ");
}
static FastScanner sc;
static PrintWriter out;
public static void main(String[] args) throws IOException {
boolean oj = true;
if (oj) {
sc = new FastScanner();
out = new PrintWriter(System.out);
} else {
sc = new FastScanner(100);
out = new PrintWriter("output.txt");
}
int t = 1;
t = sc.nextInt();
int TTT = 1;
while (t-- > 0) {
// google(TTT++);
process();
}
out.flush();
out.close();
}
static class Pair implements Comparable<Pair> {
int x, y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Pair o) {
return Integer.compare(this.x, o.x);
}
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (!(o instanceof Pair)) return false;
// Pair key = (Pair) o;
// return x == key.x && y == key.y;
// }
//
// @Override
// public int hashCode() {
// int result = x;
// result = 31 * result + y;
// return result;
// }
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
static void debug(Object o) {
System.out.println(o);
}
static void debug(Object x, Object y) {
System.out.println("(" + x + " , " + y + ")");
}
static void println(Object o) {
out.println(o);
}
static void println(int[] o) {
for (int e : o)
print(e + " ");
println();
}
static void println(long[] o) {
for (long e : o)
print(e + " ");
println();
}
static void println() {
out.println();
}
static void print(Object o) {
out.print(o);
}
static void pflush(Object o) {
out.println(o);
out.flush();
}
static int ceil(int x, int y) {
return (x % y == 0 ? x / y : (x / y + 1));
}
static long ceil(long x, long y) {
return (x % y == 0 ? x / y : (x / y + 1));
}
static int max(int x, int y) {
return Math.max(x, y);
}
static int min(int x, int y) {
return Math.min(x, y);
}
static int abs(int x) {
return Math.abs(x);
}
static long abs(long x) {
return Math.abs(x);
}
static long sqrt(long z) {
long sqz = (long) Math.sqrt(z);
while (sqz * 1L * sqz < z) {
sqz++;
}
while (sqz * 1L * sqz > z) {
sqz--;
}
return sqz;
}
static int log2(int N) {
int result = (int) (Math.log(N) / Math.log(2));
return result;
}
static long max(long x, long y) {
return Math.max(x, y);
}
static long min(long x, long y) {
return Math.min(x, y);
}
public static int gcd(int a, int b) {
BigInteger b1 = BigInteger.valueOf(a);
BigInteger b2 = BigInteger.valueOf(b);
BigInteger gcd = b1.gcd(b2);
return gcd.intValue();
}
public static long gcd(long a, long b) {
BigInteger b1 = BigInteger.valueOf(a);
BigInteger b2 = BigInteger.valueOf(b);
BigInteger gcd = b1.gcd(b2);
return gcd.longValue();
}
public static long lcm(long a, long b) {
return (a * b) / gcd(a, b);
}
public static int lcm(int a, int b) {
return (a * b) / gcd(a, b);
}
public static int lower_bound(int[] arr, int x) {
int low = 0, high = arr.length, mid = -1;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] >= x)
high = mid;
else
low = mid + 1;
}
return low;
}
public static int upper_bound(int[] arr, int x) {
int low = 0, high = arr.length, mid = -1;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] > x)
high = mid;
else
low = mid + 1;
}
return low;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner() throws FileNotFoundException {
br = new BufferedReader(new InputStreamReader(System.in));
}
FastScanner(int a) throws FileNotFoundException {
br = new BufferedReader(new FileReader("input.txt"));
}
String next() throws IOException {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
String nextLine() throws IOException {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] readArray(int n) throws IOException {
int[] A = new int[n];
for (int i = 0; i != n; i++) {
A[i] = sc.nextInt();
}
return A;
}
long[] readArrayLong(int n) throws IOException {
long[] A = new long[n];
for (int i = 0; i != n; i++) {
A[i] = sc.nextLong();
}
return A;
}
}
static void ruffleSort(int[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
Arrays.sort(a);
}
static void ruffleSort(long[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
long temp = a[i];
a[i] = a[r];
a[r] = temp;
}
Arrays.sort(a);
}
static void reverseArray(int[] a) {
int n = a.length;
int arr[] = new int[n];
for (int i = 0; i < n; i++)
arr[i] = a[n - i - 1];
for (int i = 0; i < n; i++)
a[i] = arr[i];
}
static void reverseArray(long[] a) {
int n = a.length;
long arr[] = new long[n];
for (int i = 0; i < n; i++)
arr[i] = a[n - i - 1];
for (int i = 0; i < n; i++)
a[i] = arr[i];
}
}
| 0 |
Non-plagiarised
|
5aebbb1b
|
e647bef7
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Learning {
static LinkedList<Integer>[] adj;
public static void main(String[] args) throws Exception {
FastInput in = new FastInput();
StringBuilder sb = new StringBuilder();
int t = in.nextInt();
while (t-- > 0) {
int n = in.nextInt();
int a = in.nextInt() - 1;
int b = in.nextInt() - 1;
int da = in.nextInt();
int db = in.nextInt();
adj = new LinkedList[n];
for (int i = 0; i < n; i++) {
adj[i] = new LinkedList<>();
}
for (int i = 0; i < n - 1; i++) {
int u = in.nextInt() - 1;
int v = in.nextInt() - 1;
adj[u].add(v);
adj[v].add(u);
}
boolean f = solve(n, a, b, da, db);
if (f) {
sb.append("Bob");
} else {
sb.append("Alice");
}
sb.append("\n");
}
System.out.println(sb.toString());
}
private static boolean solve(int n, int a, int b, int da, int db) {
if (db <= da * 2) {
return false;
}
Queue<Integer> que = new LinkedList<>();
que.add(a);
int[] dist = new int[n];
Arrays.fill(dist, -1);
dist[a] = 0;
while (!que.isEmpty()) {
int t = que.poll();
for (int i : adj[t]) {
if (dist[i] == -1) {
que.add(i);
dist[i] = dist[t] + 1;
}
}
}
if (dist[b] <= da) {
return false;
}
int maxPath = 0;
for (int i = 0; i < n; i++) {
maxPath = Math.max(maxPath, dfs(i, new boolean[n]));
}
if (2 * da >= maxPath-1) {
return false;
}
return true;
}
private static int dfs(int i, boolean[] vis) {
vis[i] = true;
int max = 0;
for (int v : adj[i]) {
if (!vis[v]) {
max = Math.max(dfs(v, vis), max);
}
}
return max + 1;
}
static long calculate(int[] arr, int x) {
long val = 0L;
long p = 1;
for (int value : arr) {
val += Math.abs(value - p);
p *= x;
}
return val;
}
}
class FastInput {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
String next() throws IOException {
if (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
Integer nextInt() throws IOException {
return Integer.parseInt(next());
}
Long nextLong() throws IOException {
return Long.parseLong(next());
}
}
|
import java.io.*;
import java.util.*;
public class Main {
private static final boolean N_CASE = true;
private List<List<Integer>> g;
private int a;
private int b;
private int da;
private int db;
private int max;
private int ab;
private int dfs(int u, int fa, int depth) {
if (u == a) {
ab = depth;
}
int m1 = 0, m2 = 0;
for (int v : g.get(u)) {
if (v != fa) {
int m = dfs(v, u, depth + 1) + 1;
if (m > m1) { m2 = m1; m1 = m; }
else if (m > m2) { m2 = m; }
}
}
max = Math.max(max, m1 + m2);
int cmax = Math.max(m1, m2);
max = Math.max(max, cmax + depth);
return cmax;
}
private void solve() {
int n = sc.nextInt();
a = sc.nextInt() - 1; b = sc.nextInt() - 1;
da = sc.nextInt(); db = sc.nextInt();
g = createGraph(n);
for (int i = 0; i < n - 1; ++i) {
int u = sc.nextInt() - 1, v = sc.nextInt() - 1;
g.get(u).add(v);
g.get(v).add(u);
}
max = 0;
dfs(b, -1, 0);
db = Math.min(max, db);
boolean win = true;
if (ab > da) {
if (db > da * 2) {
win = false;
}
}
out.println(win ? "Alice" : "Bob");
}
private void run() {
int T = N_CASE ? sc.nextInt() : 1;
for (int t = 0; t < T; ++t) {
solve();
}
}
private static MyWriter out;
private static MyScanner sc;
private static class MyScanner {
BufferedReader br;
StringTokenizer st;
private 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());
}
int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
int[][] nextIntArray(int n, int m) {
int[][] a = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
a[i][j] = sc.nextInt();
}
}
return a;
}
long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) {
a[i] = nextLong();
}
return a;
}
long[][] nextLongArray(int n, int m) {
long[][] a = new long[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
a[i][j] = nextLong();
}
}
return a;
}
List<Integer> nextList(int n) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
list.add(nextInt());
}
return list;
}
List<Long> nextLongList(int n) {
List<Long> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
list.add(nextLong());
}
return list;
}
char[] nextCharArray(int n) {
return sc.next().toCharArray();
}
char[][] nextCharArray(int n, int m) {
char[][] c = new char[n][m];
for (int i = 0; i < n; i++) {
String s = sc.next();
for (int j = 0; j < m; j++) {
c[i][j] = s.charAt(j);
}
}
return c;
}
}
private static class MyWriter extends PrintWriter {
private MyWriter(OutputStream outputStream) {
super(outputStream);
}
void printArray(int[] a) {
for (int i = 0; i < a.length; ++i) {
print(a[i]);
print(i == a.length - 1 ? '\n' : ' ');
}
}
void printArray(long[] a) {
for (int i = 0; i < a.length; ++i) {
print(a[i]);
print(i == a.length - 1 ? '\n' : ' ');
}
}
void println(int[] a) {
for (int v : a) {
println(v);
}
}
void print(List<Integer> list) {
for (int i = 0; i < list.size(); ++i) {
print(list.get(i));
print(i == list.size() - 1 ? '\n' : ' ');
}
}
void println(List<Integer> list) {
list.forEach(this::println);
}
}
private <T> List<List<T>> createGraph(int n) {
List<List<T>> g = new ArrayList<>();
for (int i = 0; i < n; ++i) {
g.add(new ArrayList<>());
}
return g;
}
private void fill(int[][] a, int value) {
for (int[] row : a) {
fill(row, value);
}
}
private void fill(int[] a, int value) {
Arrays.fill(a, value);
}
public static void main(String[] args) {
out = new MyWriter(new BufferedOutputStream(System.out));
sc = new MyScanner();
new Main().run();
out.close();
}
}
| 0 |
Non-plagiarised
|
927384f2
|
b2bae06a
|
import java.util.*;
import java.io.*;
public class Main{
static class Point{
int x,y,z;
Point(int nx, int ny){
x = nx; y = ny;
}
@Override
public boolean equals(Object o) {
Point p = (Point)o;
return p.x == x && p.y == y;
}
}
public static void main(String[] args) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int n = pint(in);
Stack<Integer> min = new Stack<Integer>();
Stack<Integer> max = new Stack<Integer>();
int[] a = new int[n];
int[] dp = new int[n];
StringTokenizer st = new StringTokenizer(in.readLine());
a[0] = pint(st);
min.add(0);
max.add(0);
for(int i = 1; i < n; i++) {
a[i] = pint(st);
int h = dp[i - 1] + 1;
while(!max.isEmpty() && a[i] > a[max.peek()]) {
int k = a[max.peek()];
h = Math.min(h, dp[max.pop()] + 1);
while(!max.isEmpty() && a[max.peek()] == k) {max.pop();}
}
if(!max.isEmpty()) {
h = Math.min(h, dp[max.peek()] + 1);
}
while(!min.isEmpty() && a[i] < a[min.peek()]) {
int k = a[min.peek()];
h = Math.min(h, dp[min.pop()] + 1);
while(!min.isEmpty() && a[min.peek()] == k) {min.pop();}
}
if(!min.isEmpty()) {
h = Math.min(h, dp[min.peek()] + 1);
}
dp[i] = h;
min.add(i);
max.add(i);
}
System.out.println(dp[n - 1]);
}
static int[] resize(int[] a) {
int[] r = new int[a.length * 2];
for(int i = 0; i < a.length; i++) {
r[i] = a[i];
}
return r;
}
static int pint(BufferedReader in) throws IOException {return Integer.parseInt(in.readLine());}
static int pint(StringTokenizer st) {return Integer.parseInt(st.nextToken());}
}
|
import java.util.*;
import java.io.*;
public class D{
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int snext() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public String readString() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
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 int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static int mod = (int)(1e9+7);
public static long pow(long a,long b)
{
long ans = 1;
while(b> 0)
{
if((b & 1)==1){
ans = (ans*a) % mod;
}
a = (a*a) % mod;
b = b>>1;
}
return ans;
}
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
OutputWriter out = new OutputWriter(System.out);
int n = in.nextInt();
int[] arr = in.nextIntArray(n);
Stack<Integer> min = new Stack<>();
Stack<Integer> max = new Stack<>();
int[] dp = new int[n];
// Arrays.fill(dp,(int)1e9);
dp[0] = 0;
min.push(0);
max.push(0);
for(int i=1;i<n;i++)
{
int h=dp[i-1]+1;
while(!max.isEmpty() && arr[i]>arr[max.peek()])
{
int x = arr[max.peek()];
h = Math.min(h,1+dp[max.pop()]);
while(!max.isEmpty() && arr[max.peek()]==x)
{
max.pop();
}
}
if(!max.isEmpty())
{
h = Math.min(h,1+dp[max.peek()]);
}
while(!min.isEmpty() && arr[i]<arr[min.peek()])
{
int x = arr[min.peek()];
h = Math.min(h,1+dp[min.pop()]);
while(!min.isEmpty() && arr[min.peek()]==x)
{
min.pop();
}
}
if(!min.isEmpty())
{
h = Math.min(h,1+dp[min.peek()]);
}
dp[i] = h;
min.push(i);
max.push(i);
}
out.printLine(dp[n-1]);
out.flush();
out.close();
}
}
| 1 |
Plagiarised
|
976fe834
|
da54dec3
|
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import static java.lang.System.out;
import java.util.*;
import java.io.*;
import java.math.*;
/*
-> Give your 100%, that's it!
-> Feynman Rule To Solve Any Problem:
1. Read the problem.
2. Think About It.
3. Solve it!
*/
public class Template {
static int mod = 1000000007;
public static void main(String[] args){
FastScanner sc = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int yo = sc.nextInt();
while (yo-- > 0) {
int n = sc.nextInt();
int m = sc.nextInt();
int[][] arr = new int[n][m];
for(int i = 0; i < n; i++){
String s = sc.next();
for(int j = 0; j < m; j++){
arr[i][j] = s.charAt(j)-'0';
}
}
List<String> list = new ArrayList<>();
for(int i = 0; i < n-1; i++){
for(int j = 0; j < m-1; j++){
check(list,i,j,n,m,arr);
}
}
// for(int i = 0; i < n; i++){
// for(int j = 0; j < m; j++){
// out.print(arr[i][j] + " ");
// }
// out.println();
// }
out.println(list.size()/3);
for(int i = 0; i < list.size(); i+=3){
out.println(list.get(i) + " " + list.get(i+1) + " " + list.get(i+2));
}
// out.println(list.size());
// for(int i = 0; i < list.size(); i++){
// out.println(list.get(i));
// }
}
out.close();
}
static void check(List<String> list, int i, int j, int n, int m, int[][] arr){
int[][] a = new int[2][2];
a[0][0] = arr[i][j];
a[0][1] = arr[i][j+1];
a[1][0] = arr[i+1][j];
a[1][1] = arr[i+1][j+1];
int ones = 0;
for(int x = 0; x < 2; x++){
for(int y = 0; y < 2; y++){
if(a[x][y] == 1) ones++;
}
}
if(ones == 0) return;
if(ones == 1){
ones(i,j,list,a);
twos(i,j,list,a);
threes(i,j,list,a);
}
else if(ones == 2){
twos(i,j,list,a);
threes(i,j,list,a);
}
else if(ones == 3){
threes(i,j,list,a);
}
else if(ones == 4){
fours(i,j,list,a);
// for(int x = 0; x < 2; x++){
// for(int y = 0; y < 2; y++){
// out.print(a[x][y] + " ");
// }
// out.println();
// }
ones(i,j,list,a);
// for(int x = 0; x < 2; x++){
// for(int y = 0; y < 2; y++){
// out.print(a[x][y] + " ");
// }
// out.println();
// }
twos(i,j,list,a);
// for(int x = 0; x < 2; x++){
// for(int y = 0; y < 2; y++){
// out.print(a[x][y] + " ");
// }
// out.println();
// }
threes(i,j,list,a);
// for(int x = 0; x < 2; x++){
// for(int y = 0; y < 2; y++){
// out.print(a[x][y] + " ");
// }
// out.println();
// }
}
arr[i][j] = a[0][0];
arr[i+1][j] = a[1][0];
arr[i][j+1] = a[0][1];
arr[i+1][j+1] = a[1][1];
}
public static void twos(int i, int j, List<String> list, int[][] a){
int count = 0;
for(int x = 0; x < 2; x++){
for(int y = 0; y < 2; y++){
if(a[x][y] == 1 && count < 1) {
count++;
a[x][y] = 0;
list.add(get(x,y,i,j));
}
else if(a[x][y] == 0){
list.add(get(x,y,i,j));
a[x][y] = 1;
}
}
}
}
public static void threes(int i, int j, List<String> list, int[][] a){
int count = 0;
for(int x = 0; x < 2; x++){
for(int y = 0; y < 2; y++){
if(a[x][y] == 1) {
a[x][y] = 0;
list.add(get(x,y,i,j));
}
}
}
}
public static void fours(int i, int j, List<String> list, int[][] a){
int count = 0;
for(int x = 0; x < 2; x++){
for(int y = 0; y < 2; y++){
if(a[x][y] == 1 && count < 3) {
count++;
a[x][y] = 0;
list.add(get(x,y,i,j));
}
}
}
}
public static void ones(int i, int j, List<String> list, int[][] a){
int count = 0;
for(int x = 0; x < 2; x++){
for(int y = 0; y < 2; y++){
if(a[x][y] == 1) {
a[x][y] = 0;
list.add(get(x,y,i,j));
}
else if(a[x][y] == 0 && count < 2){
a[x][y] = 1;
count++;
list.add(get(x,y,i,j));
}
}
}
}
public static String get(int x, int y, int i, int j){
if(x == 0 && y == 0) {
return (i+1) + " " + (j+1);
}
else if(x == 0 && y == 1){
return (i+1) + " " + (j+2);
}
else if(x == 1 && y == 0){
return (i+2) + " " + (j+1);
}
else {
return (i+2) + " " + (j+2);
}
}
/*
Random stuff to try when stuck:
-if it's 2C then it's dp
-for combo/probability problems, expand the given form we're interested in
-make everything the same then build an answer (constructive, make everything 0 then do something)
-something appears in parts of 2 --> model as graph
-assume a greedy then try to show why it works
-find way to simplify into one variable if multiple exist
-treat it like fmc (note any passing thoughts/algo that could be used so you can revisit them)
-find lower and upper bounds on answer
-figure out what ur trying to find and isolate it
-see what observations you have and come up with more continuations
-work backwards (in constructive, go from the goal to the start)
-turn into prefix/suffix sum argument (often works if problem revolves around adjacent array elements)
-instead of solving for answer, try solving for complement (ex, find n-(min) instead of max)
-draw something
-simulate a process
-dont implement something unless if ur fairly confident its correct
-after 3 bad submissions move on to next problem if applicable
-do something instead of nothing and stay organized
-write stuff down
Random stuff to check when wa:
-if code is way too long/cancer then reassess
-switched N/M
-int overflow
-switched variables
-wrong MOD
-hardcoded edge case incorrectly
Random stuff to check when tle:
-continue instead of break
-condition in for/while loop bad
Random stuff to check when rte:
-switched N/M
-long to int/int overflow
-division by 0
-edge case for empty list/data structure/N=1
*/
public static class Pair {
int x;
int y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
public static void sort(int[] arr) {
ArrayList<Integer> ls = new ArrayList<Integer>();
for (int x : arr)
ls.add(x);
Collections.sort(ls);
for (int i = 0; i < arr.length; i++)
arr[i] = ls.get(i);
}
public static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static boolean[] sieve(int N) {
boolean[] sieve = new boolean[N + 1];
for (int i = 2; i <= N; i++)
sieve[i] = true;
for (int i = 2; i <= N; i++) {
if (sieve[i]) {
for (int j = 2 * i; j <= N; j += i) {
sieve[j] = false;
}
}
}
return sieve;
}
public static long power(long x, long y, long p) {
long res = 1L;
x = x % p;
while (y > 0) {
if ((y & 1) == 1)
res = (res * x) % p;
y >>= 1;
x = (x * x) % p;
}
return res;
}
public static void print(int[] arr) {
//for debugging only
for (int x : arr)
out.print(x + " ");
out.println();
}
static class FastScanner {
private int BS = 1 << 16;
private char NC = (char) 0;
private byte[] buf = new byte[BS];
private int bId = 0, size = 0;
private char c = NC;
private double cnt = 1;
private BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
} catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
private char getChar() {
while (bId == size) {
try {
size = in.read(buf);
} catch (Exception e) {
return NC;
}
if (size == -1)
return NC;
bId = 0;
}
return (char) buf[bId++];
}
public int nextInt() {
return (int) nextLong();
}
public int[] readInts(int N) {
int[] res = new int[N];
for (int i = 0; i < N; i++) {
res[i] = (int) nextLong();
}
return res;
}
public long[] readLongs(int N) {
long[] res = new long[N];
for (int i = 0; i < N; i++) {
res[i] = nextLong();
}
return res;
}
public long nextLong() {
cnt = 1;
boolean neg = false;
if (c == NC)
c = getChar();
for (; (c < '0' || c > '9'); c = getChar()) {
if (c == '-')
neg = true;
}
long res = 0;
for (; c >= '0' && c <= '9'; c = getChar()) {
res = (res << 3) + (res << 1) + c - '0';
cnt *= 10;
}
return neg ? -res : res;
}
public double nextDouble() {
double cur = nextLong();
return c != '.' ? cur : cur + nextLong() / cnt;
}
public double[] readDoubles(int N) {
double[] res = new double[N];
for (int i = 0; i < N; i++) {
res[i] = nextDouble();
}
return res;
}
public String next() {
StringBuilder res = new StringBuilder();
while (c <= 32)
c = getChar();
while (c > 32) {
res.append(c);
c = getChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while (c <= 32)
c = getChar();
while (c != '\n') {
res.append(c);
c = getChar();
}
return res.toString();
}
public boolean hasNext() {
if (c > 32)
return true;
while (true) {
c = getChar();
if (c == NC)
return false;
else if (c > 32)
return true;
}
}
}
// For Input.txt and Output.txt
// FileInputStream in = new FileInputStream("input.txt");
// FileOutputStream out = new FileOutputStream("output.txt");
// PrintWriter pw = new PrintWriter(out);
// Scanner sc = new Scanner(in);
}
|
import java.util.*;
import java.math.*;
public class Solution {
final static int MOD = 1000000007;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = Integer.parseInt(in.next());
for(int tt = 0; tt < t; tt++) {
int n = Integer.parseInt(in.next());
int m = Integer.parseInt(in.next());
char[][] grid = new char[n][m];
List<Integer> ans = new ArrayList<>();
for(int i = 0; i < n; i++) {
grid[i] = in.next().toCharArray();
}
int iii = 0;
int jjj = 0;
if(n % 2 != 0) {
iii = 1;
for(int j = 0; j + 1 < m; j++) {
if(grid[0][j] == '1') {
grid[0][j] = '0';
grid[1][j] = (grid[1][j] == '1') ? '0' : '1';
grid[1][j + 1] = (grid[1][j + 1] == '1') ? '0' : '1';
ans.add(1); ans.add(j + 1);
ans.add(2); ans.add(j + 1);
ans.add(2); ans.add(j + 2);
}
if(grid[0][j + 1] == '1') {
grid[0][j + 1] = '0';
grid[1][j] = (grid[1][j] == '1') ? '0' : '1';
grid[1][j + 1] = (grid[1][j + 1] == '1') ? '0' : '1';
ans.add(1); ans.add(j + 2);
ans.add(2); ans.add(j + 1);
ans.add(2); ans.add(j + 2);
}
}
}
if(m % 2 != 0) {
jjj = 1;
for(int i = (n % 2 == 0) ? 0 : 1; i + 1 < n; i++) {
if(grid[i][0] == '1') {
grid[i][0] = '0';
grid[i][1] = (grid[i][1] == '1') ? '0' : '1';
grid[i + 1][1] = (grid[i + 1][1] == '1') ? '0' : '1';
ans.add(i + 1); ans.add(1);
ans.add(i + 1); ans.add(2);
ans.add(i + 2); ans.add(2);
}
if(grid[i + 1][0] == '1') {
grid[i + 1][0] = '0';
grid[i][1] = (grid[i][1] == '1') ? '0' : '1';
grid[i + 1][1] = (grid[i + 1][1] == '1') ? '0' : '1';
ans.add(i + 2); ans.add(1);
ans.add(i + 1); ans.add(2);
ans.add(i + 2); ans.add(2);
}
}
}
for(int i = iii; i < n; i += 2) {
for(int j = jjj; j < m; j += 2) {
int cnt = count(grid, i, j);
while(cnt > 0) {
List<G> g = new ArrayList<>();
for(int k = i; k < i + 2; k++) {
for(int l = j; l < j + 2; l++) {
g.add(new G(grid[k][l], k, l));
}
}
Collections.sort(g);
int l = 0;
int r = 0;
if(cnt == 1 || cnt == 3) {
l = 1; r = 3;
}else {
l = 0; r = 2;
}
for(int k = l; k <= r; k++) {
int ii = g.get(k).i;
int jj = g.get(k).j;
grid[ii][jj] = (grid[ii][jj] == '1') ? '0' : '1';
ans.add(ii + 1);
ans.add(jj + 1);
}
cnt = count(grid, i, j);
}
}
}
System.out.println(ans.size() / 6);
for(int i = 0; i < ans.size(); i += 6) {
for(int j = i; j < i + 6; j++) {
System.out.print(ans.get(j) + " " );
}
System.out.println();
}
}
}
public static int count(char[][] grid, int i, int j) {
int cnt = 0;
for(int k = i; k < i + 2; k++) {
for(int l = j; l < j + 2; l++) {
if(grid[k][l] == '1') cnt += 1;
}
}
return cnt;
}
}
class G implements Comparable <G> {
Character val;
int i;
int j;
public G(char val, int i, int j) {
this.val = val;
this.i = i;
this.j = j;
}
@Override
public int compareTo(G obj) {
return this.val.compareTo(obj.val);
}
}
| 0 |
Non-plagiarised
|
e6a6e318
|
fadc1365
|
//package codeforces;
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class solution {
public static void main(String args[]) throws java.lang.Exception{
FastScanner s=new FastScanner();
PrintWriter out=new PrintWriter(System.out);
int t=s.nextInt();
for(int tt=0;tt<t;tt++) {
int n=s.nextInt(), k=s.nextInt();
int[] a=s.readArray(k), temp=s.readArray(k);
long[] ans=new long[n];
Arrays.fill(ans, Integer.MAX_VALUE);
for (int i=0; i<k; i++) {
ans[a[i]-1]=temp[i];
}
for (int i=1; i<n; i++) {
ans[i]=Math.min(ans[i],ans[i-1]+1);
}
for (int i=n-2; i>=0; i--) {
ans[i]=Math.min(ans[i],ans[i+1]+1);
}
for (int i=0; i<n; i++) {
out.print(ans[i]+" ");
}
out.println();
}
out.close();
}
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 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 int gcd(int a, int b){
if (b == 0)
return a;
return gcd(b, a % b);
}
static void sortcol(int a[][],int c) {
Arrays.sort(a, (x, y) -> {
if(x[c]>y[c]) {
return 1;
}else {
return -1;
}
});
}
public static void printb(boolean ans) {
if(ans) {
System.out.println("Yes");
}else {
System.out.println("No");
}
}
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();
}
double nextDouble() {
return Double.parseDouble(next());
}
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());
}
}
static class Pair implements Comparable<Pair>{
int a , b;
Pair(int x , int y){
a=x;
b=y;
}
public int compareTo(Pair o) {
return a != o.a ? a - o.a : b - o.b;
}
}
}
|
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class a{
public static void main(String args[]) throws java.lang.Exception{
FastScanner s=new FastScanner();
PrintWriter out=new PrintWriter(System.out);
int t=s.nextInt();
for(int tt=0;tt<t;tt++) {
int n=s.nextInt(),k=s.nextInt();
int pos[]=s.readArray(k);
int temp[]=s.readArray(k);
long ans[]=new long[n];
Arrays.fill(ans,Integer.MAX_VALUE);
for(int i=0;i<k;i++){
ans[pos[i]-1]=temp[i];
}
for(int i=1;i<n;i++){
ans[i]=Math.min(ans[i-1]+1,ans[i]);
}
for(int i=n-2;i>=0;i--){
ans[i]=Math.min(ans[i],ans[i+1]+1);
}
for(int i=0;i<n;i++){
out.print(ans[i]+" ");
}
out.println();
}
out.close();
}
static boolean isPrime(int n){
if (n <= 1)
return false;
else if (n == 2)
return true;
else if (n % 2 == 0)
return false;
for (int i = 3; i <= Math.sqrt(n); i += 2){
if (n % i == 0)
return false;
}
return true;
}
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 sort(char [] a) {
ArrayList<Character> l=new ArrayList<>();
for (char i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
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 int gcd(int a, int b){
if (b == 0)
return a;
return gcd(b, a % b);
}
static void sortcol(int a[][],int c) {
Arrays.sort(a, (x, y) -> {
if(x[c]>y[c]) {
return 1;
}else {
return -1;
}
});
}
public static void printb(boolean ans) {
if(ans) {
System.out.println("Yes");
}else {
System.out.println("No");
}
}
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();
}
double nextDouble() {
return Double.parseDouble(next());
}
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());
}
}
static class Pair implements Comparable<Pair>{
int a , b;
Pair(int x , int y){
a=x;
b=y;
}
public int compareTo(Pair o) {
return a != o.a ? a - o.a : b - o.b;
}
}
}
| 1 |
Plagiarised
|
34aa6a45
|
dd5fd2a2
|
/*
ID: abdelra29
LANG: JAVA
TASK: skidesign
*/
import java.util.*;
import java.math.*;
import java.io.*;
public class B{
static int[] dx = new int[]{-1,0,1,0};
static int[] dy = new int[]{0,1,0,-1};
static FastReader scan=new FastReader();
public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out));
static ArrayList<Pair>es;
static LinkedList<Integer>edges[];
static Set<Pair>edges2[][];
static boolean prime[];
static void sieve(int n)
{
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;
}
}
}
public static int lowerBound(int[] array, int length, int value) {
int low = 0;
int high = length;
while (low < high) {
final int mid = (low + high) / 2;
//checks if the value is less than middle element of the array
if (value <= array[mid]) {
high = mid;
} else {
low = mid+1 ;
}
}
return low;
}
public static int upperBound(int[] array, int length, int value) {
int low = 0;
int high = length;
while (low < high) {
final int mid = low+(high-low) / 2;
if ( array[mid]>value) {
high = mid ;
} else {
low = mid+1;
}
}
return low;
}
static long mod(long x,long y)
{
if(x<0)
x=x+(-x/y+1)*y;
return x%y;
}
static boolean isPowerOfTwo(long n)
{
if (n == 0)
return false;
while (n != 1) {
if (n % 2 != 0)
return false;
n = n / 2;
}
return true;
}
static boolean isprime(long x)
{
for(long i=2;i*i<=x;i++)
if(x%i==0)
return false;
return true;
}
static int dist(int x1,int y1,int x2,int y2){
return Math.abs(x1-x2)+Math.abs(y1-y2);
}
static long cuberoot(long x)
{
long lo = 0, hi = 1000005;
while(lo<hi)
{
long m = (lo+hi+1)/2;
if(m*m*m>x)
hi = m-1;
else
lo = m;
}
return lo;
}
public static int log2(int N)
{
// calculate log2 N indirectly
// using log() method
int result = (int)(Math.log(N) / Math.log(2));
return result;
}
static long gcd(long a, long b) {
if(a!=0&&b!=0)
while((a%=b)!=0&&(b%=a)!=0);
return a^b;
}
static long LCM(long a,long b){
return (Math.abs(a*b))/gcd(a,b);
}
static int mid;
public static class comp1 implements Comparator<ArrayList<Integer>>{
public int compare(ArrayList<Integer> o1,ArrayList<Integer> o2){
return (int)(o2.size()-o1.size());
}
}
public static class comp2 implements Comparator<Pair>{
public int compare(Pair o1,Pair o2){
return (int)((o1.x+o1.y*mid)-(o2.x+o2.y*mid));
}
}
static boolean can(int m,int s)
{
return (s>=0&&s<=m*9);
}
static boolean collinear(long x1, long y1, long x2,
long y2, long x3, long y3)
{
long a = x1 * (y2 - y3) +
x2 * (y3 - y1) +
x3 * (y1 - y2);
if(a==0)
return true;
return false;
}
static int ceil(int a,int b)
{
if(a%b!=0)
return (a/b)+1;
else return a/b;
}
static int cnt=0;
static int count1[];
static void numberOfNodes(int s, int e)
{
count1[s] = 1;
for(Integer u: edges[s])
{
// condition to omit reverse path
// path from children to parent
if(u == e)
continue;
// recursive call for DFS
numberOfNodes(u ,s);
// update count[] value of parent using
// its children
count1[s] += count1[u];
}
}
/*static int rec(int i)
{
}*/
static long arr[];
static int n;
static long res,tmpres;
static ArrayList<Pair>pairs;
static boolean vis[];
static long dp[][];
static long dfs(int x,long last,int prev)
{
// vis[x]=true;
// System.out.println
if(dp[x][prev]!=-1){
// out.println("FUCK");
return dp[x][prev];
}
long ch1=0,ch2=0,res=0;
for(int v:edges[x])
{
if(!vis[v])
{
vis[v]=true;
// ch1+=
//vis[v]=false;
res+=Math.max((dfs(v,pairs.get(v).x,1)+Math.abs(pairs.get(v).x-last)),(dfs(v,pairs.get(v).y,2)+Math.abs(pairs.get(v).y-last)));
// res+=Math.max(ch1,ch2);
vis[v]=false;
}
}
return dp[x][prev]=res;
}
public static void main(String[] args) throws Exception
{
/*int xx=253;
for(int i=1;i*i<=xx;i++)
{
if(xx%i==0)
{
System.out.println(i);
System.out.println(xx/i);
}
}*/
//java.util.Scanner scan=new java.util.Scanner(new File("mootube.in"));
// PrintWriter out = new PrintWriter (new FileWriter("mootube.out"));
//scan=new FastReader("skidesign.in");
//out = new PrintWriter ("skidesign.out");
//System.out.println(3^2);
//System.out.println(19%4);
//StringBuilder news=new StringBuilder("ab");
//news.deleteCharAt(1);
//news.insert(0,'c');
//news.deleteCharAt(0);
//System.out.println(news);
//System.out.println(can(2,15));
//System.out.println(LCM(2,2));
// System.out.println(31^15);
//System.out.println("");
//System.out.println(824924296372176000L>(long)1e16);
int tt=1;
//rec(2020);
//System.out.println(Long.MAX_VALUE);
//System.out.println(Integer.MAX_VALUE);
//int st=scan.nextInt();
//System.out.println(calc(91));
//sieve(21000);
//SNWNSENSNNSWNNW
// System.out.println(set.remove(new Pair(1,1)));
//System.out.println(count("cccccccccccccccccccccccccooooooooooooooooooooooooodddddddddddddeeeeeeeeeeeeeeeeeeeeeeeeeffffffffffffforrrrrrrrrrrrrcesssssssssssss","codeforces"));
//S0ystem.out.println(isPowerOfTwo(446265625L));
//System.out.println("daaa".compareTo("bccc"));
//System.out.println(2999000999L>1999982505L);
//System.out.println("?bac?bac??a?a?a?abac????abacab?ca?a".length());
//StringBuilder s=new StringBuilder("");
//tt=scan.nextInt();
//String ok="ABDC";
//System.out.println(ok.substring(2));
//System.out.println(2000000000/2);
tt=scan.nextInt();
//System.out.println(LCM(4,6));
//System.out.println(isprime(23335));
//int T=1;
outer:while(tt-->0)
{
int n=scan.nextInt();
pairs=new ArrayList<Pair>();
edges=new LinkedList[n];
for(int i=0;i<n;i++)
edges[i]=new LinkedList();
for(int i=0;i<n;i++)
{
long l=scan.nextLong(),r=scan.nextLong();
pairs.add(new Pair(l,r));
}
for(int i=0;i<n-1;i++)
{
int a=scan.nextInt()-1;
int b=scan.nextInt()-1;
edges[a].add(b);
edges[b].add(a);
}
vis=new boolean[n];
vis[0]=true;
dp=new long[n][3];
for(long K[]:dp)
Arrays.fill(K,-1);
long x=dfs(0,pairs.get(0).x,0);
vis=new boolean[n];
vis[0]=true;
dp=new long[n][3];
for(long K[]:dp)
Arrays.fill(K,-1);
out.println(Math.max(x,dfs(0,pairs.get(0).y,0)));
}
out.close();
}
static class dsu{
static int id[]=new int[101];
dsu()
{
for(int i=0;i<101;i++)
id[i]=i;
}
static int find(int x)
{
if(x==id[x])
return x;
return find(id[x]);
}
static void connect(int i,int j)
{
i=find(i);
j=find(j);
id[i]=j;
}
static boolean is(int i,int j)
{
return find(i)==find(j);
}
}
static long binexp(long a,long n,long mod)
{
if(n==0)
return 1;
long res=binexp(a,n/2,mod)%mod;
res=res*res;
if(n%2==1)
return (res*a)%mod;
else
return res%mod;
}
static class special{
Pair x;
Pair y;
special(Pair x,Pair y)
{
this.x=new Pair(x.x,x.y);
this.y=new Pair(y.x,y.y);
}
@Override
public int hashCode() {
return (int)(x.x + 31 * y.y);
}
public boolean equals(Object other)
{
if(other instanceof special)
{
special e =(special)other;
return this.x.x==e.x.x && this.x.y==e.x.y && this.y.x==e.y.x && this.y.y==e.y.y;
}
else return false;
}
}
static long powMod(long base, long exp, long mod) {
if (base == 0 || base == 1) return base;
if (exp == 0) return 1;
if (exp == 1) return base % mod;
long R = powMod(base, exp/2, mod) % mod;
R *= R;
R %= mod;
if ((exp & 1) == 1) {
return base * R % mod;
}
else return R % mod;
}
public static long pow(long b, long e) {
long r = 1;
while (e > 0) {
if (e % 2 == 1) r = r * b ;
b = b * b;
e >>= 1;
}
return r;
}
private static void sort(int[] arr) {
List<Integer> list = new ArrayList<>();
for (int object : arr) list.add(object);
Collections.sort(list);
for (int i = 0; i < list.size(); ++i) arr[i] = list.get(i);
}
public static class FastReader {
BufferedReader br;
StringTokenizer root;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
FastReader(String filename)throws Exception
{
br=new BufferedReader(new FileReader(filename));
}
String next() {
while (root == null || !root.hasMoreTokens()) {
try {
root = new StringTokenizer(br.readLine());
} catch (Exception addd) {
addd.printStackTrace();
}
}
return root.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
long nextLong() {
return Long.parseLong(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (Exception addd) {
addd.printStackTrace();
}
return str;
}
public int[] nextIntArray(int arraySize) {
int array[] = new int[arraySize];
for (int i = 0; i < arraySize; i++) {
array[i] = nextInt();
}
return array;
}
}
public static class Pair implements Comparable<Pair>{
long x;
long y;
long ab;
long z;
public Pair(){}
public Pair(long x1, long y1,long z) {
x=x1;
y=y1;
this.z=z;
}
public Pair(long x1, long y1) {
x=x1;
y=y1;
this.ab=x+y;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result +(int) x;
result = prime * result + (int)y;
return result;
}
public String toString() {
return x + " " + y;
}
@Override
public boolean equals(Object o){
if (o == this) return true;
if(o==null)
return false;
if (o.getClass() != getClass()) return false;
Pair t = (Pair)o;
return t.x == x && t.y == y&&t.z==z;
}
public int compareTo(Pair o)
{
return (int)(y-o.y);
}
}
}
|
import java.util.*;
import java.io.*;
import java.math.*;
public class A {
static FastReader f = new FastReader();
static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) {
int t = f.nextInt();
while(t-- > 0)
solve();
out.close();
}
static Node[] nodes;
static long[][] dp;
static void solve() {
int n = f.nextInt();
nodes = new Node[n];
for(int i=0;i<n;i++) {
nodes[i] = new Node(f.nextInt(), f.nextInt());
}
for(int i=1;i<n;i++) {
int u = f.nextInt() - 1;
int v = f.nextInt() - 1;
nodes[u].adj.add(v);
nodes[v].adj.add(u);
}
dp = new long[n][2];
for(int i=0;i<n;i++) {
for(int j=0;j<2;j++) {
dp[i][j] = -1;
}
}
System.out.println(Math.max(rek(-1, 0,false),rek(-1, 0,true)));
}
static long rek(int from, int now, boolean left) { //TODO: DP
if(dp[now][left?0:1] != -1) {
return dp[now][left?0:1];
}
long ret = 0;
for(int i : nodes[now].adj) {
if(i == from) {
continue;
}
long l = rek(now,i,false) + Math.abs(nodes[i].right - (left ? nodes[now].left : nodes[now].right));
long r = rek(now,i,true) + Math.abs(nodes[i].left - (left ? nodes[now].left : nodes[now].right));
ret += Math.max(l, r);
}
dp[now][left?0:1] = ret;
return ret;
}
static class Node {
int left, right;
ArrayList<Integer> adj = new ArrayList<>();
Node(int left, int right) {
this.left = left;
this.right = right;
}
}
static class FastReader {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
String next() {
while(st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
return st.nextToken();
}
String nextLine() {
String s = "";
try {
s = br.readLine();
} catch(IOException ioe) {
ioe.printStackTrace();
}
return s;
}
int nextInt() {
return Integer.parseInt(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
long nextLong() {
return Long.parseLong(next());
}
}
}
| 0 |
Non-plagiarised
|
ae716b8f
|
f1a42a42
|
//package training2200;
import java.io.*;
import java.util.*;
public class DisCenJump {
public static void main(String[] args) throws IOException {
DisCenJump obj = new DisCenJump();
obj.doStuff();
}
int bslo(int v) {
int l = 0, r = lo.size()-1;
while (l < r) {
int m = (l+r)/2;
if (v <= lo.get(m)[0]) {
if (v > lo.get(m+1)[0]) return m;
l = m+1;
} else r = m;
}
return l;
}
int bshi(int v) {
int l = 0, r = hi.size()-1;
while (l < r) {
int m = (l+r)/2;
if (v >= hi.get(m)[0]) {
if (v < hi.get(m+1)[0]) return m;
l = m+1;
} else r = m;
}
return l;
}
int[] nums;
int[] dp;
ArrayList<int[]> lo, hi;
private void doStuff() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
nums = new int[Integer.parseInt(br.readLine())];
StringTokenizer st = new StringTokenizer(br.readLine());
for (int i = 0; i < nums.length; i++) {
nums[i] = Integer.parseInt(st.nextToken());
}
br.close();
dp = new int[nums.length];
lo = new ArrayList<>();
hi = new ArrayList<>();
lo.add(new int[] {nums[nums.length-1], nums.length-1});
hi.add(new int[] {nums[nums.length-1], nums.length-1});
for (int i = dp.length-2; i >= 0; i--) {
dp[i] = dp[i+1]+1;
int pos = bslo(nums[i]);
for (int j = pos; j < lo.size(); j++) {
dp[i] = Math.min(dp[i], dp[lo.get(j)[1]]+1);
}
pos = bshi(nums[i]);
for (int j = pos; j < hi.size(); j++) {
dp[i] = Math.min(dp[i], dp[hi.get(j)[1]]+1);
}
while (lo.size() > 0 && lo.get(lo.size()-1)[0] <= nums[i]) {
lo.remove(lo.size()-1);
}
lo.add(new int[] {nums[i], i});
while (hi.size() > 0 && hi.get(hi.size()-1)[0] >= nums[i]) {
hi.remove(hi.size()-1);
}
hi.add(new int[] {nums[i], i});
}
System.out.println(dp[0]);
}
}
|
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
public class Jumps {
public static void main(String[] args) {
FastScanner sc = new FastScanner();
int n = sc.nextInt();
int ar[] = sc.nextIntArray(n);
// 1 4 6 9 3 2
int dp[] = new int[n];
int nextLower[] = new int[n];
int nextHigher[] = new int[n];
int nextLowerE[] = new int[n];
int nextHigherE[] = new int[n];
Arrays.fill(nextHigher, n);
Arrays.fill(nextLower, n);
Arrays.fill(nextHigherE, n);
Arrays.fill(nextLowerE, n);
dp[n-1] = 0;
Stack<Integer> stack = new Stack<>();
for(int i = n-1; i >= 0; i--) {
while(stack.size() > 0 && ar[stack.peek()] < ar[i])
stack.pop();
if(stack.size() > 0)
nextHigherE[i] = stack.peek();
stack.push(i);
}
stack.clear();
for(int i = n-1; i >= 0; i--) {
while(stack.size() > 0 && ar[stack.peek()] <= ar[i])
stack.pop();
if(stack.size() > 0)
nextHigher[i] = stack.peek();
stack.push(i);
}
stack.clear();
for(int i = n-1; i >= 0; i--) {
while(stack.size() > 0 && ar[stack.peek()] > ar[i])
stack.pop();
if(stack.size() > 0)
nextLowerE[i] = stack.peek();
stack.push(i);
}
stack.clear();
for(int i = n-1; i >= 0; i--) {
while(stack.size() > 0 && ar[stack.peek()] >= ar[i])
stack.pop();
if(stack.size() > 0)
nextLower[i] = stack.peek();
stack.push(i);
}
for(int i = n-2; i >= 0; i--) {
int maxIndex = max(nextHigherE[i], nextLowerE[i]);
int ans = dp[i+1];
if(maxIndex < n) {
ans = min(ans, dp[maxIndex]);
}
if(nextHigherE[i] < nextLowerE[i]) {
int cur = nextHigherE[i];
while(cur < maxIndex) {
ans = min(ans, dp[cur]);
cur = nextLower[cur];
}
} else {
int cur = nextLowerE[i];
while(cur < maxIndex) {
ans = min(ans, dp[cur]);
cur = nextHigher[cur];
}
}
dp[i] = ans + 1;
}
System.out.println(dp[0]);
}
static final Random random = new Random();
static class FastScanner {
private InputStream sin = System.in;
private final byte[] buffer = new byte[1024];
private int ptr = 0;
private int buflen = 0;
public FastScanner(){}
public FastScanner(String filename) throws FileNotFoundException {
File file = new File(filename);
sin = new FileInputStream(file);
}
private boolean hasNextByte() {
if (ptr < buflen) {
return true;
}else{
ptr = 0;
try {
buflen = sin.read(buffer);
} catch (IOException e) {
e.printStackTrace();
}
if (buflen <= 0) {
return false;
}
}
return true;
}
private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;}
private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;}
public boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte();}
public String next() {
if (!hasNext()) throw new NoSuchElementException();
StringBuilder sb = new StringBuilder();
int b = readByte();
while(isPrintableChar(b)) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public long nextLong() {
if (!hasNext()) throw new NoSuchElementException();
long n = 0;
boolean minus = false;
int b = readByte();
if (b == '-') {
minus = true;
b = readByte();
}
if (b < '0' || '9' < b) {
throw new NumberFormatException();
}
while(true){
if ('0' <= b && b <= '9') {
n *= 10;
n += b - '0';
}else if(b == -1 || !isPrintableChar(b) || b == ':'){
return minus ? -n : n;
}else{
throw new NumberFormatException();
}
b = readByte();
}
}
public int nextInt() {
long nl = nextLong();
if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException();
return (int) nl;
}
public double nextDouble() { return Double.parseDouble(next());}
public long[] nextLongArray(final int n){
final long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public int[] nextIntArray(final int n){
final int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public double[] nextDoubleArray(final int n){
final double[] a = new double[n];
for (int i = 0; i < n; i++)
a[i] = nextDouble();
return a;
}
public List<Integer>[] adjacencyList(int nodes, int edges) {
return adjacencyList(nodes, edges, false);
}
public List<Integer>[] adjacencyList(int nodes, int edges, boolean isDirected) {
List<Integer>[] adj = new ArrayList[nodes + 1];
Arrays.setAll(adj, (i) -> new ArrayList<>());
for (int i = 0; i < edges; i++) {
int a = nextInt(), b = nextInt();
adj[a].add(b);
if (!isDirected) adj[b].add(a);
}
return adj;
}
}
static int findDistance(List<Integer> G[], int nodes, int src, int dst) {
LinkedList<Integer> queue = new LinkedList<>();
int dist[] = new int[nodes + 1];
int ans = -1;
dist[src] = 0;
queue.add(src);
while(queue.size() > 0) {
int u = queue.poll();
if(u == dst) {
ans = dist[u];
}
for(int v : G[u]) {
if(dist[v] >= 0)
continue;
queue.add(v);
dist[v] = dist[u] + 1;
}
}
return ans;
}
static void sort(int A[]) {
shuffleArray(A);
Arrays.sort(A);
}
static void sort(long A[]) {
shuffleArray(A);
Arrays.sort(A);
}
static void sort(double A[]) {
shuffleArray(A);
Arrays.sort(A);
}
static void shuffleArray(int[] A) {
int n = A.length;
for(int i = 0; i < n; i++) {
int tmp = A[i];
int randomPos = i + random.nextInt(n-i);
A[i] = A[randomPos];
A[randomPos] = tmp;
}
}
static void shuffleArray(long[] A) {
int n = A.length;
for(int i = 0; i < n; i++) {
long tmp = A[i];
int randomPos = i + random.nextInt(n-i);
A[i] = A[randomPos];
A[randomPos] = tmp;
}
}
static void shuffleArray(double[] A) {
int n = A.length;
for(int i = 0; i < n; i++) {
double tmp = A[i];
int randomPos = i + random.nextInt(n-i);
A[i] = A[randomPos];
A[randomPos] = tmp;
}
}
static int[] subArray(int A[], int x, int y) {
int B[] = new int[y - x + 1];
for(int i = x; i <= y; i++)
B[i-x] = A[i];
return B;
}
static int[] toArray(List<Integer> L) {
return L.stream().mapToInt(x -> x).toArray();
}
static void println(int[] A) {
for(int e: A) System.out.print(e + " ");
System.out.println();
}
static void println(long[] A) {
for(long e: A) System.out.print(e + " ");
System.out.println();
}
static void println(List arr) {
for(Object e: arr) System.out.print(e + " ");
System.out.println();
}
static void print(String s) {
System.out.print(s);
}
static void println(String s) {
System.out.println(s);
}
static List<Integer> toList(int ar[]) {
return Arrays.stream(ar).boxed().collect(Collectors.toList());
}
static List<Long> toList(long ar[]) {
return Arrays.stream(ar).boxed().collect(Collectors.toList());
}
static List<Double> toList(double ar[]) {
return Arrays.stream(ar).boxed().collect(Collectors.toList());
}
static long gcd(long a, long b) {
if(b == 0)
return a;
return gcd(b, a % b);
}
private static int abs(int a){ return (a>=0) ? a: -a; }
private static int min(int... ins){ return Arrays.stream(ins).min().getAsInt(); }
private static int max(int... ins){ return Arrays.stream(ins).max().getAsInt(); }
private static int sum(int... ins){ return Arrays.stream(ins).sum(); }
private static long abs(long a){ return (a>=0) ? a: -a; }
private static long min(long... ins){ return Arrays.stream(ins).min().getAsLong(); }
private static long max(long... ins){ return Arrays.stream(ins).max().getAsLong(); }
private static long sum(long... ins){ return Arrays.stream(ins).sum(); }
private static double abs(double a){ return (a>=0) ? a: -a; }
private static double min(double... ins){ return Arrays.stream(ins).min().getAsDouble(); }
private static double max(double... ins){ return Arrays.stream(ins).max().getAsDouble(); }
private static double sum(double... ins){ return Arrays.stream(ins).sum(); }
private static class Pair implements Comparable<Pair> {
int x, y;
Pair(int x, int y) { this.x = x; this.y = y; }
Pair() {}
@Override
public int compareTo(Pair other) {
return x == other.x ? y - other.y : x - other.x;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair pair = (Pair) o;
return x == pair.x &&
y == pair.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
}
}
| 0 |
Non-plagiarised
|
9f354c5c
|
cb032314
|
import java.util.*;
import java.io.*;
import java.math.*;
import java.sql.Array;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Solution {
private static class MyScanner {
private static final int BUF_SIZE = 2048;
BufferedReader br;
private MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
private boolean isSpace(char c) {
return c == '\n' || c == '\r' || c == ' ';
}
String next() {
try {
StringBuilder sb = new StringBuilder();
int r;
while ((r = br.read()) != -1 && isSpace((char)r));
if (r == -1) {
return null;
}
sb.append((char) r);
while ((r = br.read()) != -1 && !isSpace((char)r)) {
sb.append((char)r);
}
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
static class Reader{
BufferedReader br;
StringTokenizer st;
public Reader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
static long mod = (long)(1e9 + 7);
static void sort(long[] arr ) {
ArrayList<Long> al = new ArrayList<>();
for(long e:arr) al.add(e);
Collections.sort(al);
for(int i = 0 ; i<al.size(); i++) arr[i] = al.get(i);
}
static void sort(int[] arr ) {
ArrayList<Integer> al = new ArrayList<>();
for(int e:arr) al.add(e);
Collections.sort(al);
for(int i = 0 ; i<al.size(); i++) arr[i] = al.get(i);
}
static void sort(char[] arr) {
ArrayList<Character> al = new ArrayList<Character>();
for(char cc:arr) al.add(cc);
Collections.sort(al);
for(int i = 0 ;i<arr.length ;i++) arr[i] = al.get(i);
}
static long mod_mul( long... a) {
long ans = a[0]%mod;
for(int i = 1 ; i<a.length ; i++) {
ans = (ans * (a[i]%mod))%mod;
}
return ans;
}
static long mod_sum( long... a) {
long ans = 0;
for(long e:a) {
ans = (ans + e)%mod;
}
return ans;
}
static long gcd(long a, long b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static 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;
private long mod;
public Combinations(long N , long mod) {
this.mod = mod;
z = new long[(int)N+1];
z1 = new long[(int)N+1];
z[0] = 1;
for(int i =1 ; i<=N ; i++) z[i] = (z[i-1]*i)%mod;
z2 = new long[(int)N+1];
z2[0] = z2[1] = 1;
for (int i = 2; i <= N; i++)
z2[i] = z2[(int)(mod % i)] * (mod - mod / i) % mod;
z1[0] = z1[1] = 1;
for (int i = 2; i <= N; i++)
z1[i] = (z2[i] * z1[i - 1]) % mod;
}
long fac(long n) {
return z[(int)n];
}
long invrsNum(long n) {
return z2[(int)n];
}
long invrsFac(long n) {
return invrsFac((int)n);
}
long ncr(long N, long R)
{ if(R<0 || R>N ) return 0;
long ans = ((z[(int)N] * z1[(int)R])
% mod * z1[(int)(N - R)])
% mod;
return ans;
}
}
static class DisjointUnionSets {
int[] rank, parent;
int n;
public DisjointUnionSets(int n)
{
rank = new int[n];
parent = new int[n];
this.n = n;
makeSet();
}
void makeSet()
{
for (int i = 0; i < n; i++) {
parent[i] = i;
}
}
int find(int x)
{
if (parent[x] != x) {
parent[x] = find(parent[x]);
}
return parent[x];
}
void union(int x, int y)
{
int xRoot = find(x), yRoot = find(y);
if (xRoot == yRoot)
return;
if (rank[xRoot] < rank[yRoot])
parent[xRoot] = yRoot;
else if (rank[yRoot] < rank[xRoot])
parent[yRoot] = xRoot;
else
{
parent[yRoot] = xRoot;
rank[xRoot] = rank[xRoot] + 1;
}
}
}
static int max(int... a ) {
int max = a[0];
for(int e:a) max = Math.max(max, e);
return max;
}
static long max(long... a ) {
long max = a[0];
for(long e:a) max = Math.max(max, e);
return max;
}
static int min(int... a ) {
int min = a[0];
for(int e:a) min = Math.min(e, min);
return min;
}
static long min(long... a ) {
long min = a[0];
for(long e:a) min = Math.min(e, min);
return min;
}
static int[] KMP(String str) {
int n = str.length();
int[] kmp = new int[n];
for(int i = 1 ; i<n ; i++) {
int j = kmp[i-1];
while(j>0 && str.charAt(i) != str.charAt(j)) {
j = kmp[j-1];
}
if(str.charAt(i) == str.charAt(j)) j++;
kmp[i] = j;
}
return kmp;
}
/************************************************ Query **************************************************************************************/
/***************************************** Sparse Table ********************************************************/
static class SparseTable{
private long[][] st;
SparseTable(long[] arr){
int n = arr.length;
st = new long[n][25];
log = new int[n+2];
build_log(n+1);
build(arr);
}
private void build(long[] arr) {
int n = arr.length;
for(int i = n-1 ; i>=0 ; i--) {
for(int j = 0 ; j<25 ; j++) {
int r = i + (1<<j)-1;
if(r>=n) break;
if(j == 0 ) st[i][j] = arr[i];
else st[i][j] = Math.min(st[i][j-1] , st[ i + ( 1 << (j-1) ) ][ j-1 ] );
}
}
}
public long gcd(long a ,long b) {
if(a == 0) return b;
return gcd(b%a , a);
}
public long query(int l ,int r) {
int w = r-l+1;
int power = log[w];
return Math.min(st[l][power],st[r - (1<<power) + 1][power]);
}
private int[] log;
void build_log(int n) {
log[1] = 0;
for(int i = 2 ; i<=n ; i++) {
log[i] = 1 + log[i/2];
}
}
}
/******************************************************** Segement Tree *****************************************************/
/**
static class SegmentTree{
long[] tree;
long[] arr;
int n;
SegmentTree(long[] arr){
this.n = arr.length;
tree = new long[4*n+1];
this.arr = arr;
buildTree(0, n-1, 1);
}
void buildTree(int s ,int e ,int index ) {
if(s == e) {
tree[index] = arr[s];
return;
}
int mid = (s+e)/2;
buildTree( s, mid, 2*index);
buildTree( mid+1, e, 2*index+1);
tree[index] = Math.min(tree[2*index] , tree[2*index+1]);
}
long query(int si ,int ei) {
return query(0 ,n-1 , si ,ei , 1 );
}
private long query( int ss ,int se ,int qs , int qe,int index) {
if(ss>=qs && se<=qe) return tree[index];
if(qe<ss || se<qs) return (long)(1e17);
int mid = (ss + se)/2;
long left = query( ss , mid , qs ,qe , 2*index);
long right= query(mid + 1 , se , qs ,qe , 2*index+1);
return Math.min(left, right);
}
public void update(int index , int val) {
arr[index] = val;
for(long e:arr) System.out.print(e+" ");
update(index , 0 , n-1 , 1);
}
private void update(int id ,int si , int ei , int index) {
if(id < si || id>ei) return;
if(si == ei ) {
tree[index] = arr[id];
return;
}
if(si > ei) return;
int mid = (ei + si)/2;
update( id, si, mid , 2*index);
update( id , mid+1, ei , 2*index+1);
tree[index] = Math.min(tree[2*index] ,tree[2*index+1]);
}
}
*/
/* ***************************************************************************************************************************************************/
// static MyScanner sc = new MyScanner(); // only in case of less memory
static Reader sc = new Reader();
static StringBuilder sb = new StringBuilder();
public static void main(String args[]) throws IOException {
int tc = 1;
tc = sc.nextInt();
for(int i = 1 ; i<=tc ; i++) {
// sb.append("Case #" + i + ": " ); // During KickStart && HackerCup
TEST_CASE();
}
System.out.println(sb);
}
static void TEST_CASE() {
int n = sc.nextInt();
ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
for(int i =0 ; i<n ; i++) adj.add(new ArrayList<>());
int[] U = new int[n-1] , V = new int[n-1];
for(int i = 0 ; i<n-1 ; i++) {
int u = sc.nextInt()-1 , v = sc.nextInt()-1;
U[i] = u; V[i] = v;
adj.get(u).add(v);
adj.get(v).add(u);
}
int ind = -1;
for(int i =0 ; i<n ; i++) {
if(adj.get(i).size()>2) {
sb.append("-1\n");
return;
}
if(adj.get(i).size() == 1) {
ind = i;
}
}
Map<String , Integer> map = new HashMap<>();
dfs(adj, ind, -1, true, map);
for(int i =0 ; i<n-1 ; i++) {
int u = U[i];
int v = V[i];
if(map.containsKey(u+" "+v)) sb.append(map.get(u+" "+v)+" ");
else sb.append(map.get(v+" "+u)+" ");
}
sb.append("\n");
}
static void dfs(ArrayList<ArrayList<Integer>> adj ,int u , int p ,boolean eve ,Map<String , Integer> map ) {
if(eve) {
map.put(u+" "+p, 2);
}else {
map.put(u+" "+p, 3);
}
for(int v:adj.get(u)) {
if(v == p) continue;
eve = !eve;
dfs(adj, v, u, eve, map);
}
}
}
/*******************************************************************************************************************************************************/
/**
1
*/
|
import java.io.*;
import java.util.*;
public class C {
static FastScanner sc = new FastScanner();
static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
static class pair{
public pair(int x, int y) {
this.x = x;
this.y = y;
}
int x;
int y;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
pair pair = (pair) o;
return x == pair.x && y == pair.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
}
static void solve(){
int n = sc.nextInt();
int[]degree = new int[n];
List<Integer>[]grid = new List[n];
for (int i = 0; i < n; i++) {
grid[i] = new ArrayList();
}
List<pair>list = new ArrayList<>();
for (int i = 0; i < n - 1; i++) {
int x = sc.nextInt() - 1;
int y = sc.nextInt() - 1;
grid[x].add(y);
grid[y].add(x);
degree[x]++;
degree[y]++;
list.add(new pair(Math.min(x,y),Math.max(x,y)));
}
int begin = 0;
for(int i = 0;i < degree.length;i++){
if(degree[i] > 2){
System.out.println(-1);
return;
}
if(degree[i] == 1){
begin = i;
}
}
boolean[]used = new boolean[n];
int[]p = new int[]{5,2,11,2};
int idx = 0;
HashMap<pair,Integer>map = new HashMap<>();
while (!used[begin]){
used[begin] = true;
for(int next : grid[begin]){
if(used[next])
continue;
map.put(new pair(Math.min(begin,next),Math.max(begin,next)),p[idx % 4]);
idx++;
begin = next;
}
}
StringBuilder bd = new StringBuilder();
for(pair pp : list){
bd.append(map.get(pp) + " ");
}
System.out.println(bd.toString().trim());
}
public static void main(String[] args) {
int n = sc.nextInt();
for(int i = 0;i < n;i++){
solve();
}
}
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());
}
}
}
| 0 |
Non-plagiarised
|
3e93b259
|
e431de28
|
import java.util.*;
import java.io.*;
public class Main
{
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
static class Pair implements Comparable<Pair>
{
int f,s;
Pair(int f,int s)
{
this.f=f;
this.s=s;
}
public int compareTo(Pair p)
{
return this.f-p.f;
}
}
public static void main(String args[])
{
FastReader fs=new FastReader();
PrintWriter pw=new PrintWriter(System.out);
int tc=fs.nextInt();
while(tc-->0)
{
int n=fs.nextInt();
long a[]=new long[n];
for(int i=0;i<n;i++)
a[i]=fs.nextLong();
long minans=a[0]*n+a[1]*n;
long sum=a[0]+a[1];
long min1=a[0],min2=a[1];
for(int i=2;i<n;i++)
{
sum+=a[i];
if(i%2==0)
min1=Math.min(min1,a[i]);
else
min2=Math.min(min2,a[i]);
long tsum=sum-min1-min2;
if(i%2==0)
tsum=tsum+(n-i/2+1)*min2+(n-i/2)*min1;
else
tsum=tsum+(min1+min2)*(n-((i+1)/2)+1);
minans=Math.min(minans,tsum);
//minans=Math.min(minans,(n-cnt1)*a[i]+(n-cnt2)*a[i-1]+sum);
}
pw.println(minans);
}
pw.flush();
pw.close();
}
}
|
import java.io.*;
import java.lang.*;
import java.util.*;
public class MinGridPath {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner s=new Scanner(System.in);
int t=s.nextInt();
while(t-->0){
int n = s.nextInt();
long[] aa =new long[n];
for(int i=0;i<n;i++)
aa[i]=s.nextLong();
long minEven = aa[0];
long minOdd = aa[1];
long sum = aa[0]+aa[1];
long best = n*minEven + n*minOdd;
int numOdd = 1;
int numEven = 1;
for(int i=2; i<n; ++i) {
if(i%2 == 0) {
minEven = Math.min(aa[i], minEven);
numEven++;
}else {
minOdd = Math.min(aa[i], minOdd);
numOdd++;
}
sum += aa[i];
long score = sum;
score += minEven*(n-numEven);
score += minOdd*(n-numOdd);
best = Math.min(best, score);
}
System.out.println(best);
}
}
}
| 0 |
Non-plagiarised
|
d2a4c1fb
|
dcdaf666
|
import java.util.*;
public class CodeForcesRound {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for (int i = 0; i<t; i++)
System.out.println(solve(sc));
sc.close();
}
public static long solve(Scanner sc) {
int n = sc.nextInt();
long[] c = new long[n];
long[] ps = new long[n];
c[0] = sc.nextLong();
c[1] = sc.nextLong();
ps[0] = c[0];
ps[1] = c[1];
for (int i = 2; i<n; i++) {
c[i] = sc.nextLong();
ps[i] = ps[i-2] + c[i];
}
long res = Long.MAX_VALUE;
long[] mins = new long[n];
mins[0] = n*c[0];
mins[1] = n*c[1];
int minEven = 0;
int minOdd = 1;
for (int i = 2; i<n; i++) {
if (i%2==0) {
if (c[i]<c[minEven])
minEven = i;
mins[i] = ps[minEven]-c[minEven] + ps[i]-ps[minEven] + c[minEven]*(n-i/2);
} else {
if (c[i]<c[minOdd])
minOdd = i;
mins[i] = ps[minOdd]-c[minOdd] + ps[i]-ps[minOdd] + c[minOdd]*(n-i/2);
}
}
for (int i = 1; i<n; i++) {
res = Math.min(res, mins[i]+mins[i-1]);
}
return res;
}
public static long min(long a, long b, long c) {
long t = Math.min(a, b);
return Math.min(t, c);
}
}
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.StringTokenizer;
public class Solution {
//
public static void main(String[] args) {
PrintStream out = System.out;
FastScanner fs = new FastScanner();
int T = fs.nextInt();
while (T-- > 0) {
int n = fs.nextInt();
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = fs.nextLong();
}
long[] ps = new long[n];
ps[0] = arr[0];
for (int i = 1; i < n; i++) {
ps[i] = ps[i - 1] + arr[i];
}
long min = arr[0] * n + arr[1] * n;
int even = 0;
int odd = 1;
for (int i = 2; i < n; i++) {
if (i % 2 == 0) {
if (arr[i] < arr[even]) {
even = i;
}
} else {
if (arr[i] < arr[odd]) {
odd = i;
}
}
int tmp = i + 1;
int oddCount = tmp / 2;
int evenCount = (tmp + 1) / 2;
long local = ps[i];
local += (n - oddCount) * arr[odd];
local += (n - evenCount) * arr[even];
min = Math.min(min, local);
}
out.println(min);
}
}
// if these strings are both balanced then as one or zero goes out of the window one or zero must come in
//
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();
}
int[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
}
}
| 0 |
Non-plagiarised
|
49b94994
|
d8654140
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Main1582D {
public static void main(String[] args) {
final FastScanner in = new FastScanner(System.in);
final PrintWriter out = new PrintWriter(System.out);
int t = in.nextInt();
for (int i = 0; i < t; i++) {
int n = in.nextInt();
int[] a = new int[n];
for (int j = 0; j < n; j++) {
a[j] = in.nextInt();
}
int[] b = solution(a, n);
for (int j = 0; j < n; j++) {
out.print(b[j]);
out.print(" ");
}
out.println();
}
out.flush();
out.close();
in.close();
}
private static int[] solution(int[] a, int n) {
int[] b = new int[n];
int start = 0;
if (n % 2 == 1) {
if (a[0] + a[1] != 0) {
b[0] = -a[2];
b[1] = -a[2];
b[2] = a[0] + a[1];
} else if (a[0] + a[2] != 0) {
b[0] = -a[1];
b[1] = a[0] + a[2];
b[2] = -a[1];
} else {
b[0] = a[1] + a[2];
b[1] = -a[0];
b[2] = -a[0];
}
start = 3;
} else {
b[0] = -a[1];
b[1] = a[0];
int gcd = gcd(b[0], b[1]);
b[0] /= gcd;
b[1] /= gcd;
start = 2;
}
for (int i = start; i < n; i += 2) {
b[i] = -a[i + 1];
b[i + 1] = a[i];
}
return b;
}
private static int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
private static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(InputStream stream) {
try {
br = new BufferedReader(new InputStreamReader(stream));
} catch (Exception e) {
e.printStackTrace();
}
}
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());
}
double nextDouble() {
return Double.parseDouble(next());
}
int[] readIntArr(int n) {
int[] result = new int[n];
for (int i = 0; i < n; i++) {
result[i] = Integer.parseInt(next());
}
return result;
}
long[] readLongArr(int n) {
long[] result = new long[n];
for (int i = 0; i < n; i++) {
result[i] = Long.parseLong(next());
}
return result;
}
void close() {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
long nextLong() {
return Long.parseLong(next());
}
}
}
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.*;
public class Codeforces {
static int mod=1000000007 ;
static List<Integer>[] adj;
static boolean vst[];
static int dp[];
public static void main(String[] args) throws Exception {
PrintWriter out=new PrintWriter(System.out);
FastScanner fs=new FastScanner();
int t=fs.nextInt();
while(t-->0) {
int n=fs.nextInt();
int arr[]=fs.readArray(n);
int ans[]=new int[n];
if(n%2==0) {
for(int i=0;i<n;i+=2) {
ans[i]=-arr[i+1];
ans[i+1]=arr[i];
}
}
else {
for(int i=3;i<n;i+=2) {
ans[i]=-arr[i+1];
ans[i+1]=arr[i];
}
int a=0, b=0, c=0;
outer:for(int i=0;i<3;i++) {
for(int j=i+1;j<3;j++) {
if(arr[i]+arr[j]!=0) {
b=i;
c=j;
a= 3-c-b;
break outer;
}
}
}
ans[a]=arr[b]+arr[c];
ans[b]=-arr[a];
ans[c]=-arr[a];
}
for(int i=0;i<n;i++) {
out.print(ans[i]+" ");
}
out.println();
// long sum=0;
// for(int i=0;i<n;i++) {
// sum+=arr[i]*ans[i];
// }
// if(sum!=0) System.out.println(false);
}
out.close();
}
static long pow(long a,long b) {
if(b<0) return 1;
long res=1;
while(b!=0) {
if((b&1)!=0) {
res*=a;
res%=mod;
}
a*=a;
a%=mod;
b=b>>1;
}
return res;
}
static long gcd(long a,long b) {
if(b==0) return a;
return gcd(b,a%b);
}
static long nck(int n,int k) {
if(k>n) return 0;
long res=1;
res*=fact(n);
res%=mod;
res*=modInv(fact(k));
res%=mod;
res*=modInv(fact(n-k));
res%=mod;
return res;
}
static long fact(long n) {
// return fact[(int)n];
long res=1;
for(int i=2;i<=n;i++) {
res*=i;
res%=mod;
}
return res;
}
static long modInv(long n) {
return pow(n,mod-2);
}
static void sort(int[] a) {
//suffle
int n=a.length;
Random r=new Random();
for (int i=0; i<a.length; i++) {
int oi=r.nextInt(n);
int temp=a[i];
a[i]=a[oi];
a[oi]=temp;
}
//then sort
Arrays.sort(a);
}
// Use this to input code since it is faster than a Scanner
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());
}
long[] lreadArray(int n) {
long a[]=new long[n];
for(int i=0;i<n;i++) a[i]=nextLong();
return a;
}
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());
}
}
}
| 0 |
Non-plagiarised
|
3951966f
|
9bc690ef
|
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
public class Armchairs {
static ArrayList<Integer> f;
static ArrayList<Integer> u;
static int dp[][];
static int fun(int i, int j){
if(i == f.size()) return 0;
if(j == u.size()) return 99999999;
if(dp[i][j] != -1) return dp[i][j];
int ans1 = fun(i, j+1);
int ans2 = fun(i+1, j+1) + Math.abs(f.get(i)-u.get(j));
return dp[i][j] = Math.min(ans1, ans2);
}
private static int solve(int n, int a[]) {
for (int i = 0; i < n; i++) {
if (a[i]==0)
u.add(i);
else
f.add(i);
}
return fun(0,0);
}
public static void main(String[] args)
throws IOException {
Scanner s = new Scanner();
int t = 1;
StringBuilder ans = new StringBuilder();
int count = 0;
while (t-- > 0) {
int n = s.nextInt();
int a[] = new int[n];
dp=new int[n][n];
for (int i = 0; i < n; i++) {
a[i]=s.nextInt();
}
f=new ArrayList<>();
u=new ArrayList<>();
for( int i=0; i<n; i++) Arrays.fill(dp[i],-1);
ans.append(solve(n, a)).append("\n");
}
System.out.println(ans.toString());
}
static class Scanner {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Scanner() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Scanner(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 norm(long a, long MOD) {
return ((a % MOD) + MOD) % MOD;
}
public static long msub(long a, long b, long MOD) {
return norm(norm(a, MOD) - norm(b, MOD), MOD);
}
public static long madd(long a, long b, long MOD) {
return norm(norm(a, MOD) + norm(b, MOD), MOD);
}
public static long mMul(long a, long b, long MOD) {
return norm(norm(a, MOD) * norm(b, MOD), MOD);
}
public static long mDiv(long a, long b, long MOD) {
return norm(norm(a, MOD) / norm(b, MOD), MOD);
}
}
|
//package Div_2B_Problems;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.ArrayList;
public class Armchairs {
static ArrayList<Integer> one;
static ArrayList<Integer> zero;
public static void main(String args[]) {
FastScanner fs=new FastScanner();
int n=fs.nextInt();
int []arr=new int[n];
one=new ArrayList<>();
zero=new ArrayList<>();
for(int i=0;i<arr.length;i++) {
arr[i]=fs.nextInt();
if(arr[i]==1)
one.add(i);
else zero.add(i);
}
int [][]dp=new int[arr.length][arr.length];
for(int i=0;i<arr.length;i++)
Arrays.fill(dp[i], -1);
System.out.println(dfs(dp,0,0));
}
public static int dfs(int [][]dp,int i,int j) {
//System.out.println(i+" "+j);
if(i>=one.size())
return 0;
if(j>=zero.size())
return (int)(1e9);
if(dp[i][j]!=-1)
return dp[i][j];
dp[i][j]=Math.min(Math.abs(one.get(i)-zero.get(j))+dfs(dp,i+1,j+1), dfs(dp,i,j+1));
return dp[i][j];
}
private static int[] readArray(int n) {
// TODO Auto-generated method stub
return null;
}
static final Random random=new Random();
static void ruffleSort(int[] a) {
int n=a.length;//shuffle, then sort
for (int i=0; i<n; i++) {
int oi=random.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
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());
}
}
}
| 0 |
Non-plagiarised
|
9c55bc1b
|
c9da41af
|
import java.util.*;
import java.io.*;
public class Main {
static MyScanner sc;
static PrintWriter out;
static {
sc = new MyScanner();
out = new PrintWriter(System.out);
}
public static void bfs(Node[] g, int[] ans) {
Arrays.fill(ans, -1);
boolean[] visited = new boolean[g.length];
Queue<Integer> q = new LinkedList<>();
int s = 0;
for(int i = 0; i < g.length; i++) {
if(g[i].l.size() == 1) {
s = i;
break;
}
}
q.add(s);
int curr = 2;
while(!q.isEmpty()) {
int u = q.poll();
if(visited[u])
continue;
visited[u] = true;
for(Edge edge : g[u].l) {
if(!visited[edge.v]) {
ans[edge.id] = curr;
q.add(edge.v);
if(curr == 2) curr = 3;
else curr = 2;
}
}
}
}
public static void solve() {
int n = sc.nextInt();
Node[] a = new Node[n];
for(int i = 0; i < n; i++)
a[i] = new Node();
for(int i = 0; i < n - 1; i++) {
int u = sc.nextInt() - 1;
int v = sc.nextInt() - 1;
a[u].l.add(new Edge(v, i));
a[v].l.add(new Edge(u, i));
}
for(Node node : a) {
if(node.l.size() > 2) {
out.println(-1);
return;
}
}
int[] ans = new int[n - 1];
bfs(a, ans);
for(int i = 0; i < n - 1; i++)
out.print(ans[i] + " ");
out.println();
}
public static void main(String[] args) {
int t = sc.nextInt();
while(t-- > 0)
solve();
out.flush();
}
}
class Edge {
int v, id;
Edge(int a, int b) {
v = a;
id = b;
}
}
class Node {
ArrayList<Edge> l;
Node() {
l = new ArrayList<>();
}
}
class MyScanner {
BufferedReader br;
StringTokenizer tok;
MyScanner() {
try { br = new BufferedReader(new InputStreamReader(System.in)); }
catch(Exception e) { System.out.println(e); }
tok = new StringTokenizer("");
}
public String next() {
try {
while(!tok.hasMoreTokens()) tok = new StringTokenizer(br.readLine());
}
catch(Exception e) { System.out.println(e); }
return tok.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
|
import java.util.*;
import java.lang.*;
import java.io.*;
public class Main {
static {
try {
System.setIn(new FileInputStream("input.txt"));
System.setOut(new PrintStream(new FileOutputStream("output.txt")));
} catch (Exception e) {}
}
void solve() {
int n = in.nextInt();
ArrayList<Edge>[] graph = new ArrayList[n + 1];
for (int i = 0; i < n; i++) {
graph[i] = new ArrayList<Edge>();
}
for (int i = 0; i < n - 1; i++) {
int u = in.nextInt();
int v = in.nextInt();
v--; u--;
graph[u].add(new Edge(v, i));
graph[v].add(new Edge(u, i));
}
int[] res = new int[n - 1];
for (int i = 0; i < n; i++) {
if (graph[i].size() > 2) {
out.append("-1\n");
return;
}
}
int start = -1;
for (int i = 0; i < n; i++) {
if (graph[i].size() == 1) {
start = i;
break;
}
}
int currNode = start;
int prevNode = -1;
int weight = 2;
while (true) {
ArrayList<Edge> edges = graph[currNode];
Edge next = edges.get(0);
if (next.node == prevNode) {
if (edges.size() == 1) {
break;
}
next = edges.get(1);
}
res[next.index] = weight;
weight = 5 - weight;
prevNode = currNode;
currNode = next.node;
}
for (int i = 0; i < n - 1; i++) {
out.append(res[i] + " ");
}
out.append("\n");
}
public static void main (String[] args) {
// Its Not Over Untill I Win - Syed Mizbahuddin
Main sol = new Main();
int t = 1;
t = in.nextInt();
while (t-- != 0) {
sol.solve();
}
System.out.print(out);
}
<T> void println(T[] s) {
System.out.println(Arrays.toString(s));
}
<T> void println(T s) {
System.out.println(s);
}
void print(int s) {
System.out.print(s);
}
void println(int s) {
System.out.println(s);
}
void println(int[] a) {
println(Arrays.toString(a));
}
int[] array(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
return a;
}
int[] array1(int n) {
int[] a = new int[n + 1];
for (int i = 1; i <= n; i++) {
a[i] = in.nextInt();
}
return a;
}
static FastReader in;
static StringBuffer out;
final int MAX;
final int MIN;
int mod ;
Main() {
in = new FastReader();
out = new StringBuffer();
MAX = Integer.MAX_VALUE;
MIN = Integer.MIN_VALUE;
mod = (int)1e9 + 7;
}
}
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;
}
}
class Edge {
int node, index;
Edge(int node, int index) {
this.node = node;
this.index = index;
}
}
| 0 |
Non-plagiarised
|
0ee2f8f1
|
587307f2
|
import java.util.*;
public class Main{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int T=sc.nextInt();
while(T-->0){
int n=sc.nextInt();
int arr[]=new int[n];
int min=Integer.MAX_VALUE;int max=Integer.MIN_VALUE;
for(int i=0;i<n;i++){
arr[i]=sc.nextInt();
min=Math.min(arr[i],min);
max=Math.max(arr[i],max);
}
while(min<=max){
int mid=min+(max-min)/2;
if(helper(arr,mid))
min=mid+1;
else max=mid-1;
}
System.out.println(min-1);
}
}
public static boolean helper(int arr[],int min){
int tmp[]=Arrays.copyOf(arr,arr.length);
for(int i=arr.length-1;i>=2;i--){
if(tmp[i]<min)
return false;
int d=(Math.min(arr[i],tmp[i]-min))/3;
tmp[i-1]+=d;
tmp[i-2]+=d*2;
}
return tmp[1]>=min && tmp[0]>=min;
}
}
|
import java.util.*;
public class Main{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int T=sc.nextInt();
while(T-->0){
int n=sc.nextInt();
int arr[]=new int[n];
int min=Integer.MAX_VALUE;int max=Integer.MIN_VALUE;
for(int i=0;i<n;i++){
arr[i]=sc.nextInt();
min=Math.min(arr[i],min);
max=Math.max(arr[i],max);
}
while(min<=max){
int mid=min+(max-min)/2;
if(helper(arr,mid))
min=mid+1;
else max=mid-1;
}
System.out.println(min-1);
}
}
public static boolean helper(int arr[],int min){
int tmp[]=Arrays.copyOf(arr,arr.length);
for(int i=arr.length-1;i>=2;i--){
if(tmp[i]<min)
return false;
int d=(Math.min(arr[i],tmp[i]-min))/3;
tmp[i-1]+=d;
tmp[i-2]+=d*2;
}
return tmp[1]>=min && tmp[0]>=min;
}
}
| 1 |
Plagiarised
|
0f3a2acf
|
dba80ad4
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Practice {
static int[][] vals;
static ArrayList<ArrayList<Integer>> adjList;
static long[][] ans;
public static void main(String[] args) throws IOException {
BufferedReader bu=new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(bu.readLine());
while (t-- > 0) {
Integer n = Integer.parseInt(bu.readLine());
vals = new int[2][n];
adjList = new ArrayList<>();
for(int i=0;i<n;i++){
String st[]=bu.readLine().split(" ");
vals[0][i] = Integer.parseInt(st[0]);
vals[1][i] = Integer.parseInt(st[1]);
adjList.add(new ArrayList<>());
}
for(int i=0;i<n-1;i++){
String st[]=bu.readLine().split(" ");
int source = Integer.parseInt(st[0]);; int dest = Integer.parseInt(st[1]);;
adjList.get(source-1).add(dest-1);
adjList.get(dest-1).add(source-1);
}
ans = new long[2][n];
DFS(0, adjList, -1, ans, vals);
System.out.println(Math.max(ans[0][0], ans[1][0]));
}
}
private static void DFS(Integer current, ArrayList<ArrayList<Integer>> adjList, Integer prev, long[][] ans, int[][] vals) {
ans[0][current] = 0L; ans[1][current] = 0L;
for(Integer node: adjList.get(current)){
if(node.equals(prev)) continue;
DFS(node, adjList, current, ans, vals);
ans[0][current] += Math.max(ans[0][node] + Math.abs(vals[0][current] - vals[0][node]), ans[1][node] + Math.abs(vals[0][current] - vals[1][node]));
ans[1][current] += Math.max(ans[0][node] + Math.abs(vals[1][current] - vals[0][node]) , ans[1][node] + Math.abs(vals[1][current] - vals[1][node]));
}
}
}
|
import java.util.*;
import static java.lang.Math.*;
import java.io.*;
public class S {
public static void main(String args[])throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int test = Integer.parseInt(br.readLine());
while(test > 0){
test--;
int n = Integer.parseInt(br.readLine());
int a[][] = new int[n][2];
for(int i = 0; i < n; i++){
StringTokenizer st = new StringTokenizer(br.readLine());
a[i][0] = Integer.parseInt(st.nextToken());
a[i][1] = Integer.parseInt(st.nextToken());
}
Map<Integer, List<Integer>> g = new HashMap<Integer, List<Integer>>();
for(int i = 0; i < n-1; i++){
StringTokenizer st = new StringTokenizer(br.readLine());
int u = Integer.parseInt(st.nextToken());
int v = Integer.parseInt(st.nextToken());
u--;
v--;
if(!g.containsKey(u))g.put(u, new ArrayList<Integer>());
g.get(u).add(v);
if(!g.containsKey(v))g.put(v, new ArrayList<Integer>());
g.get(v).add(u);
}
solve(n, a, g);
//System.out.println(s + " " + tar);
//StringTokenizer st = new StringTokenizer(br.readLine());
//int n = Integer.parseInt(st.nextToken());
//int l = Integer.parseInt(st.nextToken());
//st = new StringTokenizer(br.readLine());
//int a[] = new int[n];
//for(int i = 0; i < n; i++){
// a[i] = Integer.parseInt(st.nextToken());
//}
}
}
public static void solve(int n, int a[][], Map<Integer, List<Integer>> g){
Map<Integer, long[]> dp = new HashMap<Integer, long[]>();
boolean visited[] = new boolean[n];
long ans = 0;
visited[0] = true;
long part[] = dfs(a, g, 0, visited, dp);
ans = Math.max(part[0], part[1]);
System.out.println(ans);
}
public static long[] dfs(int a[][], Map<Integer, List<Integer>> g, int node, boolean visited[], Map<Integer, long[]> dp){
if(dp.containsKey(node)){
return dp.get(node);
}
List<Integer> children = g.get(node);
if(children == null)return new long[]{0, 0};
long ansL = 0;
long ansR = 0;
for(int child : children){
if(!visited[child]){
visited[child] = true;
long sol[] = dfs(a, g, child, visited, dp);
ansL += Math.max(sol[0] + Math.abs(a[node][0] - a[child][0]), sol[1] + Math.abs(a[node][0] - a[child][1]));
ansR += Math.max(sol[0] + Math.abs(a[node][1] - a[child][0]), sol[1] + Math.abs(a[node][1] - a[child][1]));
}
}
long ans[] = new long[]{ansL, ansR};
dp.put(node, ans);
return ans;
}
public static int gcd(int a, int b){
if(b == 0)return a;
return gcd(b, a%b);
}
}
| 0 |
Non-plagiarised
|
0fd5b95a
|
41e72d4f
|
//package codeforces;
import java.io.PrintWriter;
import java.util.*;
public class codeforces {
static int dp[][]=new int[5001][5001];
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
PrintWriter out=new PrintWriter(System.out);
int t=1;
for(int tt=0;tt<t;tt++) {
int n=s.nextInt();
int a[]=new int[n];
ArrayList<Integer> z=new ArrayList<>();
ArrayList<Integer> o=new ArrayList<>();
for(int i=0;i<n;i++) {
a[i]=s.nextInt();
if(a[i]==1) {
o.add(i);
}else {
z.add(i);
}
}
for(int i=0;i<5001;i++) {
Arrays.fill(dp[i], -1);
}
System.out.println(sol(0,0,z,o));
}
out.close();
s.close();
}
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 sortcol(int a[][],int c) {
Arrays.sort(a, (x, y) -> {
if (x[c] != y[c]) return(int)( x[c] - y[c]);
return (int)-(x[1]+x[2] - y[1]-y[2]);
});
}
static int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
public static int sol(int i,int j,ArrayList<Integer> z,ArrayList<Integer> o) {
if(j==o.size()) {
return 0;
}
int h=z.size()-i;
int l=o.size()-j;
if(i==z.size()) {
return 10000000;
}
if(dp[i][j]!=-1) {
//System.out.println(i+" "+j);
return dp[i][j];
}
int ans1=sol(i+1,j,z,o);
int ans2=sol(i+1,j+1,z,o)+Math.abs(z.get(i)-o.get(j));
dp[i][j]=Math.min(ans1, ans2);
return dp[i][j];
}
}
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.StringTokenizer;
public class ProblemD {
public static void main(String[] args) throws IOException {
final int INF = 20000000;
InputStream in = System.in;
InputReader scan = new InputReader(in);
int n = scan.nextInt();
int occ = 0;
List<Integer> occPos = new ArrayList<>();
HashSet<Integer> occPosSet = new HashSet<>();
for(int i=1;i<=n;i++) {
int num = scan.nextInt();
if(num==1) {
occ++;
occPos.add(i);
occPosSet.add(i);
}
}
int[][] dp = new int[n+1][occ+1];
for(int i=0;i<=n;i++) {
for(int j=0;j<=occ;j++) {
dp[i][j] = 20000000;
}
}
for(int i=1;i<=n;i++) {
int k=1;
for(int pos: occPos) {
if(occPosSet.contains(i)) {
dp[i][k] = dp[i-1][k];
} else {
dp[i][k] = Math.min(dp[i-1][k], dp[i-1][k-1]+Math.abs(pos-i));
if(k==1) dp[i][k]=Math.min(dp[i][k],Math.abs(pos-i));
}
k++;
}
}
if(dp[n][occ]==INF) {
System.out.println(0);
} else {
System.out.println(dp[n][occ]);
}
}
static class InputReader {
BufferedReader br;
StringTokenizer st;
InputReader(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| 0 |
Non-plagiarised
|
11c2ab99
|
259c1ea4
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
FastScanner fs=new FastScanner();
int T=fs.nextInt();
PrintWriter out=new PrintWriter(System.out);
for (int tt=0; tt<T; tt++) {
int n=fs.nextInt(), k=fs.nextInt();
int[] positions=fs.readArray(k), temps=fs.readArray(k);
int[] forced=new int[n];
Arrays.fill(forced, Integer.MAX_VALUE/2);
for (int i=0; i<k; i++) forced[positions[i]-1]=temps[i];
for (int i=1; i<n; i++)
forced[i]=Math.min(forced[i], forced[i-1]+1);
for (int i=n-2; i>=0; i--)
forced[i]=Math.min(forced[i], forced[i+1]+1);
for (int i=0; i<n; i++) out.print(forced[i]+" ");
out.println();
}
out.close();
}
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 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());
}
}
}
|
import java.util.Arrays;
import java.util.Scanner;
public class E {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int test = scn.nextInt();
while (test-- > 0) {
int nrLands = scn.nextInt();
int[] toRightLands = new int[nrLands];
Arrays.fill(toRightLands, (int) (1e9 + 1e8));
int[] toLeftLands = new int[nrLands];
Arrays.fill(toLeftLands, (int) (1e9 + 1e8));
int nrAcs = scn.nextInt();
AC[] acs = new AC[nrAcs];
for (int i = 0; i < nrAcs; i++) {
acs[i] = new AC();
acs[i].myPos = scn.nextInt() - 1;
}
for (int i = 0; i < nrAcs; i++) {
acs[i].myTemp = scn.nextInt();
}
Arrays.sort(acs);
int nextAc = 1;
AC lastChosen = acs[0];
for (int i = lastChosen.myPos; i < nrLands; i++) {
if (nextAc < acs.length && i == acs[nextAc].myPos) {
if (acs[nextAc].myTemp < lastChosen.myTemp + i - lastChosen.myPos) {
lastChosen = acs[nextAc];
}
nextAc++;
}
toRightLands[i] = lastChosen.myTemp + i - lastChosen.myPos;
}
int nextAc1 = acs.length - 2;
AC lastChosen1 = acs[acs.length - 1];
for (int i = lastChosen1.myPos; i >= 0; i--) {
if (nextAc1 >= 0 && i == acs[nextAc1].myPos) {
if (acs[nextAc1].myTemp < lastChosen1.myTemp - i + lastChosen1.myPos) {
lastChosen1 = acs[nextAc1];
}
nextAc1--;
}
toLeftLands[i] = lastChosen1.myTemp - i + lastChosen1.myPos;
}
for (int i = 0; i < nrLands; i++) {
System.out.print(Integer.min(toLeftLands[i], toRightLands[i]) + " ");
}
System.out.println();
}
}
static class AC implements Comparable<AC> {
int myPos, myTemp;
@Override
public int compareTo(AC o) {
return Integer.compare(myPos, o.myPos);
}
}
}
| 0 |
Non-plagiarised
|
7bc92b7f
|
9028caf7
|
import java.util.*;
import java.io.*;
public class Main{
public static void main(String[] args) throws java.io.IOException {
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
int[] arr=new int[n];
int[][] dp=new int[n][n];
int[][] min=new int[n][n];
ArrayList<Integer> ones=new ArrayList<>();
ArrayList<Integer> zero=new ArrayList<>();
for(int i=0;i<n;++i) {
arr[i] = sc.nextInt();
if(arr[i]==1)
ones.add(i);
else
zero.add(i);
}
for(int i=0;i<n;++i)
for(int j=0;j<n;++j) {
min[i][j] = Integer.MAX_VALUE;
dp[i][j] = Integer.MAX_VALUE;
}
int len=ones.size();
int zlen=zero.size();
int minn=0;
for(int i=0;i<len;++i)
{
int cur = ones.get(i);
for(int j=i;j<zlen;j++)
{
int curz = zero.get(j);
int cost = Math.abs(cur-curz);
if(i!=0 && curz-1>=0)
{
cost+=min[i-1][curz-1];
}
dp[i][curz]=cost;
}
minn=Integer.MAX_VALUE;
for(int j=0;j<n;++j)
{
if(dp[i][j]<minn)
minn=dp[i][j];
min[i][j]=minn;
}
}
System.out.println(minn);
}
}
// 1 0 1 1 0 0 1
|
import java.io.*;
import java.util.*;
public class Main {
public static void main(String args[])
{
FastReader input=new FastReader();
PrintWriter out=new PrintWriter(System.out);
int T=1;
while(T-->0)
{
int n=input.nextInt();
int a[]=new int[n];
ArrayList<Integer> list=new ArrayList<>();
ArrayList<Integer> space=new ArrayList<>();
for(int i=0;i<n;i++)
{
a[i]=input.nextInt();
if(a[i]==1)
{
list.add(i);
}
else
{
space.add(i);
}
}
int pre[]=new int[space.size()];
for(int i=0;i<list.size();i++)
{
if(i==0)
{
int min=Integer.MAX_VALUE;
for(int j=0;j<space.size();j++)
{
pre[j]=Math.abs(list.get(i)-space.get(j));
min=Math.min(min,pre[j]);
pre[j]=min;
}
}
else
{
int arr[]=new int[space.size()];
for(int j=0;j<i;j++)
{
arr[j]=Integer.MAX_VALUE;
}
int min=Integer.MAX_VALUE;
for(int j=i;j<space.size();j++)
{
int v=Math.abs(list.get(i)-space.get(j));
v+=pre[j-1];
arr[j]=v;
min=Math.min(min,v);
arr[j]=min;
}
for(int j=0;j<space.size();j++)
{
pre[j]=arr[j];
}
}
}
out.println(pre[space.size()-1]);
}
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());
}
String nextLine()
{
String str="";
try
{
str=br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
}
| 0 |
Non-plagiarised
|
67996c4c
|
7bc92b7f
|
import java.util.*;
import java.io.*;
public class code{
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
public static int GCD(int a, int b)
{
if (b == 0)
return a;
return GCD(b, a % b);
}
public static void main(String[] arg) throws IOException{
//Reader in=new Reader();
Scanner in=new Scanner(System.in);
int n=in.nextInt();
int[] arr=new int[n];
ArrayList<Integer> zero=new ArrayList<Integer>();
ArrayList<Integer> one=new ArrayList<Integer>();
for(int i=0;i<n;i++){
arr[i]=in.nextInt();
if(arr[i]==0) zero.add(i);
else one.add(i);
}
if(one.size()==0) {
System.out.println(0);
}
else{
int[][] dp=new int[one.size()][zero.size()];
for(int i=0;i<one.size();i++){
for(int j=0;j<zero.size();j++){
if(i==0 && j==0) dp[i][j]=Math.abs(one.get(i)-zero.get(j));
else if(j==0) dp[i][j]=Integer.MAX_VALUE/2;
else if(i==0) dp[i][j]=Math.min(dp[i][j-1],Math.abs(one.get(i)-zero.get(j)));
else{
dp[i][j]=Math.min(dp[i][j-1],dp[i-1][j-1]+Math.abs(one.get(i)-zero.get(j)));
}
}
}
System.out.println(dp[one.size()-1][zero.size()-1]);
}
}
}
|
import java.util.*;
import java.io.*;
public class Main{
public static void main(String[] args) throws java.io.IOException {
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
int[] arr=new int[n];
int[][] dp=new int[n][n];
int[][] min=new int[n][n];
ArrayList<Integer> ones=new ArrayList<>();
ArrayList<Integer> zero=new ArrayList<>();
for(int i=0;i<n;++i) {
arr[i] = sc.nextInt();
if(arr[i]==1)
ones.add(i);
else
zero.add(i);
}
for(int i=0;i<n;++i)
for(int j=0;j<n;++j) {
min[i][j] = Integer.MAX_VALUE;
dp[i][j] = Integer.MAX_VALUE;
}
int len=ones.size();
int zlen=zero.size();
int minn=0;
for(int i=0;i<len;++i)
{
int cur = ones.get(i);
for(int j=i;j<zlen;j++)
{
int curz = zero.get(j);
int cost = Math.abs(cur-curz);
if(i!=0 && curz-1>=0)
{
cost+=min[i-1][curz-1];
}
dp[i][curz]=cost;
}
minn=Integer.MAX_VALUE;
for(int j=0;j<n;++j)
{
if(dp[i][j]<minn)
minn=dp[i][j];
min[i][j]=minn;
}
}
System.out.println(minn);
}
}
// 1 0 1 1 0 0 1
| 0 |
Non-plagiarised
|
722e318f
|
c9159d9c
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
public class TaskB {
static long mod = 1000000007;
static FastScanner scanner;
static final StringBuilder result = new StringBuilder();
public static void main(String[] args) {
// 2 : 1000000000
scanner = new FastScanner();
int T = scanner.nextInt();
for (int t = 0; t < T; t++) {
solve(t + 1);
result.append("\n");
}
System.out.println(result);
}
static void solve(int t) {
int n = scanner.nextInt();
int[] a = scanner.nextIntArray(n);
String s = scanner.nextToken();
List<Integer> blue = new ArrayList<>();
List<Integer> red = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (s.charAt(i) == 'B') {
blue.add(a[i]);
} else {
red.add(a[i]);
}
}
Collections.sort(blue);
Collections.sort(red);
for (int i = 0; i < blue.size(); i++) {
if (blue.get(i) < i + 1) {
result.append("NO");
return;
}
}
for (int i = 0; i < red.size(); i++) {
if (red.get(i) > i + 1 + blue.size()) {
result.append("NO");
return;
}
}
result.append("YES");
}
static class WithIdx implements Comparable<WithIdx> {
int val, idx;
public WithIdx(int val, int idx) {
this.val = val;
this.idx = idx;
}
@Override
public int compareTo(WithIdx o) {
if (val == o.val) {
return Integer.compare(idx, o.idx);
}
return Integer.compare(val, o.val);
}
}
public static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String nextToken() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return st.nextToken();
}
String nextLine() {
try {
return br.readLine();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException();
}
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
int[] nextIntArray(int n) {
int[] res = new int[n];
for (int i = 0; i < n; i++) res[i] = nextInt();
return res;
}
long[] nextLongArray(int n) {
long[] res = new long[n];
for (int i = 0; i < n; i++) res[i] = nextLong();
return res;
}
String[] nextStringArray(int n) {
String[] res = new String[n];
for (int i = 0; i < n; i++) res[i] = nextToken();
return res;
}
}
static class PrefixSums {
long[] sums;
public PrefixSums(long[] sums) {
this.sums = sums;
}
public long sum(int fromInclusive, int toExclusive) {
if (fromInclusive > toExclusive) throw new IllegalArgumentException("Wrong value");
return sums[toExclusive] - sums[fromInclusive];
}
public static PrefixSums of(int[] ar) {
long[] sums = new long[ar.length + 1];
for (int i = 1; i <= ar.length; i++) {
sums[i] = sums[i - 1] + ar[i - 1];
}
return new PrefixSums(sums);
}
public static PrefixSums of(long[] ar) {
long[] sums = new long[ar.length + 1];
for (int i = 1; i <= ar.length; i++) {
sums[i] = sums[i - 1] + ar[i - 1];
}
return new PrefixSums(sums);
}
}
static class ADUtils {
static void sort(int[] ar) {
Random rnd = ThreadLocalRandom.current();
for (int i = ar.length - 1; i > 0; i--) {
int index = rnd.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
Arrays.sort(ar);
}
static void reverse(int[] arr) {
int last = arr.length / 2;
for (int i = 0; i < last; i++) {
int tmp = arr[i];
arr[i] = arr[arr.length - 1 - i];
arr[arr.length - 1 - i] = tmp;
}
}
static void sort(long[] ar) {
Random rnd = ThreadLocalRandom.current();
for (int i = ar.length - 1; i > 0; i--) {
int index = rnd.nextInt(i + 1);
// Simple swap
long a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
Arrays.sort(ar);
}
}
static class MathUtils {
static long[] FIRST_PRIMES = {
2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
73, 79, 83, 89, 97, 101, 103, 107, 109, 113,
127, 131, 137, 139, 149, 151, 157, 163, 167, 173,
179, 181, 191, 193, 197, 199, 211, 223, 227, 229,
233, 239, 241, 251, 257, 263, 269, 271, 277, 281,
283, 293, 307, 311, 313, 317, 331, 337, 347, 349,
353, 359, 367, 373, 379, 383, 389, 397, 401, 409,
419, 421, 431, 433, 439, 443, 449, 457, 461, 463,
467, 479, 487, 491, 499, 503, 509, 521, 523, 541,
547, 557, 563, 569, 571, 577, 587, 593, 599, 601,
607, 613, 617, 619, 631, 641, 643, 647, 653, 659,
661, 673, 677, 683, 691, 701, 709, 719, 727, 733,
739, 743, 751, 757, 761, 769, 773, 787, 797, 809,
811, 821, 823, 827, 829, 839, 853, 857, 859, 863,
877, 881, 883, 887, 907, 911, 919, 929, 937, 941,
947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013,
1019, 1021, 1031, 1033, 1039, 1049, 1051};
static long[] primes(int to) {
long[] all = new long[to + 1];
long[] primes = new long[to + 1];
all[1] = 1;
int primesLength = 0;
for (int i = 2; i <= to; i++) {
if (all[i] == 0) {
primes[primesLength++] = i;
all[i] = i;
}
for (int j = 0; j < primesLength && i * primes[j] <= to && all[i] >= primes[j];
j++) {
all[(int) (i * primes[j])] = primes[j];
}
}
return Arrays.copyOf(primes, primesLength);
}
static long modpow(long b, long e, long m) {
long result = 1;
while (e > 0) {
if ((e & 1) == 1) {
/* multiply in this bit's contribution while using modulus to keep
* result small */
result = (result * b) % m;
}
b = (b * b) % m;
e >>= 1;
}
return result;
}
static long submod(long x, long y, long m) {
return (x - y + m) % m;
}
static long modInverse(long a, long m) {
long g = gcdF(a, m);
if (g != 1) {
throw new IllegalArgumentException("Inverse doesn't exist");
} else {
// If a and m are relatively prime, then modulo
// inverse is a^(m-2) mode m
return modpow(a, m - 2, m);
}
}
static public long gcdF(long a, long b) {
while (b != 0) {
long na = b;
long nb = a % b;
a = na;
b = nb;
}
return a;
}
}
}
/*
5
3 2 3 8 8
2 8 5 10 1
*/
|
import java.util.*;
public class SolutionB {
public static long gcd(long a, long b){
if(b==0){
return a;
}
return gcd(b, a%b);
}
public static long gcdSum(long b){
long a = 0;
long temp = b;
while(temp!=0){
a = a + temp%10;
temp = temp/10;
}
return gcd(a,b);
}
public static class Pair{
Long a;
Long b;
public Pair(Long a, Long b) {
this.a = a;
this.b = b;
}
}
public static long factorial (long n){
if(n==0)
return 1;
else if(n==1)
return n;
return n * factorial(n-1);
}
public static long lcm (long n){
if(n<3)
return n;
return lcmForBig(n,n-1);
}
private static long lcmForBig(long n, long l) {
if(l==1)
return n;
n = (n * l) / gcd(n, l);
return lcmForBig(n, l-1);
}
public static void main(String[] args){
Scanner s = new Scanner(System.in);
int t = s.nextInt();
for(int i =0;i<t;i++) {
int n = s.nextInt();
int arr [] = new int[n];
ArrayList<Integer> blue = new ArrayList<>();
ArrayList<Integer> red = new ArrayList<>();
for(int j=0;j<n;j++){
int num = s.nextInt();
arr[j]=num;
}
String color = s.next();
for(int j=0;j<n;j++){
if(color.charAt(j)=='B'){
blue.add(arr[j]);
}
else{
red.add(arr[j]);
}
}
Collections.sort(blue);
String ans = "YES";
int counter = 0;
for(int j=0;j<blue.size();j++){
int current = blue.get(j);
if (current<1){
ans="NO";
break;
}
if(current>counter){
counter++;
}
else{
ans="NO";
break;
}
}
if(ans=="NO"){
System.out.println(ans);
}
else{
int tempCounter = n+1;
Collections.sort(red);
for(int j=red.size()-1;j>=0;j--){
int current = red.get(j);
if(current>=tempCounter){
ans="NO";
break;
}
else{
tempCounter--;
}
}
if(tempCounter-counter!=1)
System.out.println("NO");
else
System.out.println(ans);
}
}
return;
}
}
| 0 |
Non-plagiarised
|
1dab88fb
|
f59d9b6e
|
import java.util.*;
public class Main
{
static class Edge{
public int node;
public int index;
public Edge(int n, int i){
node=n;
index=i;
}
}
static Scanner sc=new Scanner(System.in);
public static void main(String[] args) {
int test=sc.nextInt();
while(test-->0){
solve();
}
}
static void solve(){
int n=sc.nextInt();
ArrayList<ArrayList<Edge>> graph= new ArrayList<ArrayList<Edge>>();
for(int i=0;i<n;i++){
graph.add(new ArrayList<>());
}
for (int i = 0; i < n - 1; i++) {
int u = sc.nextInt();
int v = sc.nextInt();
u--; v--;
graph.get(u).add(new Edge(v, i));
graph.get(v).add(new Edge(u, i));
}
int start = 0;
for (int i = 0; i < n; i++) {
if (graph.get(i).size() > 2) {
System.out.println("-1");
return;
} else if (graph.get(i).size() == 1) {
start = i;
}
}
int[] weight = new int[n - 1];
int prevNode = -1;
int curNode = start;
int curWeight = 2;
while (true) {
ArrayList<Edge> edges = graph.get(curNode);
Edge next = edges.get(0);
if (next.node == prevNode) {
if (edges.size() == 1) {
break;
} else {
next = edges.get(1);
}
}
weight[next.index] = curWeight;
prevNode = curNode;
curNode = next.node;
curWeight = 5 - curWeight;
}
for (int i = 0; i < n - 1; i++) {
System.out.print(weight[i]);
System.out.print(" ");
}
System.out.println();
}
}
|
/* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Codechef{
public static class Edge{
int node;
int index;
Edge(int node, int index){
this.node = node;
this.index = index;
}
}
static Scanner scn = new Scanner(System.in);
public static void main (String[] args) throws java.lang.Exception{
int t = scn.nextInt();
while(t-->0){
solve();
}
}
public static void solve(){
int n = scn.nextInt();
ArrayList<Edge>[]graph = new ArrayList[n];
for(int i = 0; i < n; i++){
graph[i] = new ArrayList<>();
}
for(int i = 0; i < n - 1; i++){
int u = scn.nextInt() - 1;
int v = scn.nextInt() - 1;
graph[u].add(new Edge(v, i));
graph[v].add(new Edge(u, i));
}
int start = 0;
for(int i = 0; i < n; i++){
if(graph[i].size() > 2){
System.out.println("-1");
return;
}else if(graph[i].size() == 1){
start = i;
}
}
int[]weight = new int[n - 1];
int prevNode = -1, curNode = start, curWeight = 2;
while(true){
ArrayList<Edge>edges = graph[curNode];
Edge next = edges.get(0);
if(next.node == prevNode){
if(edges.size() == 1){
break;
}else{
next = edges.get(1);
}
}
weight[next.index] = curWeight;
prevNode = curNode;
curNode = next.node;
curWeight = 5 - curWeight;
}
for(int i = 0; i < n - 1; i++){
System.out.print(weight[i]);
System.out.print(" ");
}
System.out.println();
}
}
| 1 |
Plagiarised
|
0588b869
|
11373c16
|
import java.util.*;
import java.io.*;
public class Solution
{
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 final long mod=(long)1e9+7;
public static long pow(long a,int p)
{
long res=1;
while(p>0)
{
if(p%2==1)
{
p--;
res*=a;
res%=mod;
}
else
{
a*=a;
a%=mod;
p/=2;
}
}
return res;
}
static class Pair
{
int u,v,w;
Pair(int u,int v,int w)
{
this.u=u;
this.v=v;
this.w=w;
}
}
/*static class Pair implements Comparable<Pair>
{
int v,l;
Pair(int v,int l)
{
this.v=v;
this.l=l;
}
public int compareTo(Pair p)
{
return l-p.l;
}
}*/
static int gcd(int a,int b)
{
if(b%a==0)
return a;
return gcd(b%a,a);
}
public static void dfs(int u,int dist[],int sub[],int mxv[],int par[],ArrayList<Integer> edge[])
{
sub[u]=1;
for(int v:edge[u])
{
if(dist[v]==-1)
{
par[v]=u;
dist[v]=dist[u]+1;
dfs(v,dist,sub,mxv,par,edge);
if(sub[v]+1>sub[u])
{
sub[u]=sub[v]+1;
mxv[u]=v;
}
}
}
}
public static void main(String args[])throws Exception
{
FastReader fs=new FastReader();
PrintWriter pw=new PrintWriter(System.out);
//int tc=fs.nextInt();
int n=fs.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++)
a[i]=fs.nextInt();
ArrayList<Integer> o=new ArrayList<>();
ArrayList<Integer> z=new ArrayList<>();
for(int i=0;i<n;i++)
{
if(a[i]==1)o.add(i);
else z.add(i);
}
int ans[][]=new int[o.size()+1][z.size()+1];
for(int i=1;i<=o.size();i++)
{
for(int j=i;j<=z.size();j++)
{
if(i==j)ans[i][j]=ans[i-1][j-1]+(int)Math.abs(o.get(i-1)-z.get(j-1));
else
ans[i][j]=Math.min(ans[i][j-1],ans[i-1][j-1]+(int)Math.abs(o.get(i-1)-z.get(j-1)));
}
}
pw.println(ans[o.size()][z.size()]);
pw.flush();
pw.close();
}
}
|
/* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Codechef
{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 void main (String[] args) throws java.lang.Exception
{
FastReader scan = new FastReader();
PrintWriter pw = new PrintWriter(System.out);
int n = scan.nextInt();
ArrayList<Integer> a = new ArrayList<>();
ArrayList<Integer> b = new ArrayList<>();
for(int i=0;i<n;i++){
int x = scan.nextInt();
if(x==1)
a.add(i);
else
b.add(i);
}
int x = a.size();
if(x==0){
pw.println(0);
pw.flush();
return;
}
int y = b.size();
int dp[][] = new int[x][y];
int min = Integer.MAX_VALUE;
for(int i=0;i<y;i++){
min = Math.min(Math.abs(a.get(0) - b.get(i)),min);
dp[0][i] = min;
}
for(int i=1;i<x;i++){
min = Integer.MAX_VALUE;
for(int j=i;j<y;j++){
min = Math.min(Math.abs(a.get(i)-b.get(j))+dp[i-1][j-1],min);
dp[i][j] = min;
}
}
pw.println(dp[x-1][y-1]);
pw.flush();
}
}
| 0 |
Non-plagiarised
|
ca3128ab
|
e270e909
|
import java.io.*;
import java.math.*;
import java.util.*;
public class test {
static class Pair{
long x;
long y;
Pair(long x,long y){
this.x = x;
this.y = y;
}
}
static class Compare {
void compare(Pair arr[], int n)
{
// Comparator to sort the pair according to second element
Arrays.sort(arr, new Comparator<Pair>() {
@Override public int compare(Pair p1, Pair p2)
{
if(p1.x!=p2.x) {
return (int)(p1.x - p2.x);
}
else {
return (int)(p1.y - p2.y);
}
}
});
// for (int i = 0; i < n; i++) {
// System.out.print(arr[i].x + " " + arr[i].y + " ");
// }
// System.out.println();
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner()
{
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public static void main(String args[]) throws Exception {
Scanner sc = new Scanner();
StringBuilder res = new StringBuilder();
int tc = sc.nextInt();
while(tc-->0) {
int n = sc.nextInt();
long c[] = new long[n];
for(int i=0;i<n;i++) {
c[i] = sc.nextLong();
}
long min_odd = Integer.MAX_VALUE;
long min_even = Integer.MAX_VALUE;
long ans = Long.MAX_VALUE;
long sum = 0;
int cnt1 = n;
int cnt2 = n;
for(int i = 0; i < n; i++){
sum += c[i];
if(i % 2 == 0){
cnt1--;
min_odd = Math.min(min_odd, c[i]);
}
else{
cnt2--;
min_even = Math.min(min_even, c[i]);
}
if(i > 0){
long temp = sum + (min_odd * cnt1) + (min_even * cnt2);
ans = Math.min(ans, temp);
}
}
System.out.println(ans);
}
System.out.println(res);
}
}
|
import java.io.*;
import java.util.*;
public class GFG {
public static class Pair{
long first;
long second;
Pair(long first,long second){
this.first = first;
this.second = second;
}
}
public static int gcd(int a, int b)
{
// if b=0, a is the GCD
if (b == 0)
return a;
// call the gcd() method recursively by
// replacing a with b and b with
// modulus(a,b) as long as b != 0
else
return gcd(b, a % b);
}
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-- > 0){
int n = sc.nextInt();
long pre = 0,ans = Long.MAX_VALUE;
long[] arr = new long[n];
PriorityQueue<Long> epq = new PriorityQueue<>();
PriorityQueue<Long> opq = new PriorityQueue<>();
for(int i=0;i<n;i++)
{
arr[i] = sc.nextLong();
if(i%2==0)
epq.add(arr[i]);
else
opq.add(arr[i]);
pre+=arr[i];
if(i>0)
ans = Math.min(ans,pre+(n-epq.size())*epq.peek()+(n-opq.size())*opq.peek());
}
System.out.println(ans);
}
}
}
| 0 |
Non-plagiarised
|
bd65846f
|
d018b49f
|
import java.lang.*;
import java.util.*;
import java.io.*;
public class Main {
static void deal(int[] arr,int n) {
int m1 = 0;
int m2 = 0;
for(int i=0;i<n;i++) {
if(arr[i]==1) {
m1 ++;
} else {
m2 ++;
}
}
if(m1 ==0) {
System.out.println(0);
return;
}
int[] arr1 = new int[m1];
int[] arr2 = new int[m2];
int index1 = 0;
int index2 = 0;
for(int i=0;i<n;i++) {
if(arr[i] == 1) {
arr1[index1] = i;
index1++;
} else {
arr2[index2] = i;
index2++;
}
}
int[][] dp = new int[m2][m1];
dp[0][0] = Math.abs(arr1[0]-arr2[0]);
for(int i=0;i<m1;i++) {
if(i>0) dp[i][i] = dp[i-1][i-1] + Math.abs(arr1[i]-arr2[i]);
for(int j=i+1;j<m2;j++) {
if(i>0) {
dp[j][i] = Math.min(dp[j-1][i],dp[j-1][i-1]+Math.abs(arr2[j]-arr1[i]));
} else {
dp[j][i] = Math.min(dp[j-1][i],Math.abs(arr2[j]-arr1[i]));
}
}
}
System.out.println(dp[m2-1][m1-1]);
}
public static void main(String[] args) {
MyScanner scanner = new MyScanner();
int n = scanner.nextInt();
int[] arr = new int[n];
for(int i=0;i<n;i++) {
arr[i] = scanner.nextInt();
}
deal(arr,n);
}
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;
}
}
}
|
/* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Codechef {
static long dp[][];
public static void main(String[] args) throws java.lang.Exception {
FastReader in = new FastReader(System.in);
StringBuilder sb = new StringBuilder();
int t = 1;
//t = in.nextInt();
while (t > 0) {
--t;
int n = in.nextInt();
int arr[] = new int[n];
List<Integer> ones = new ArrayList<Integer>();
List<Integer> zero = new ArrayList<>();
for(int i = 0;i<n;i++)
{
int a = in.nextInt();
if(a == 1)
ones.add(i);
else
zero.add(i);
}
if(ones.size() == 0) {
sb.append(0+"\n");
continue;
}
dp = new long[ones.size()][zero.size()];
for(int i = 0;i<ones.size();i++)
Arrays.fill(dp[i], -1);
sb.append(findans(ones, zero, ones.size()-1, zero.size()-1));
}
System.out.print(sb);
}
static long findans(List<Integer> ones,List<Integer> zero,int x,int y)
{
if(x < 0)
return 0;
if(y<0)
return Integer.MAX_VALUE;
if(dp[x][y]!=-1)
return dp[x][y];
return dp[x][y] = Math.min(findans(ones, zero, x, y-1),findans(ones, zero, x-1, y-1) + (long)Math.abs(ones.get(x)-zero.get(y)));
}
static long gcd(long a, long b) {
if (a == 0)
return b;
else
return gcd(b % a, a);
}
static long lcm(long a, long b) {
return (a / gcd(a, b)) * b;
}
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);
}
}
class FastReader {
byte[] buf = new byte[2048];
int index, total;
InputStream in;
FastReader(InputStream is) {
in = is;
}
int scan() throws IOException {
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0) {
return -1;
}
}
return buf[index++];
}
String next() throws IOException {
int c;
for (c = scan(); c <= 32; c = scan())
;
StringBuilder sb = new StringBuilder();
for (; c > 32; c = scan()) {
sb.append((char) c);
}
return sb.toString();
}
String nextLine() throws IOException {
int c;
for (c = scan(); c <= 32; c = scan())
;
StringBuilder sb = new StringBuilder();
for (; c != 10 && c != 13; c = scan()) {
sb.append((char) c);
}
return sb.toString();
}
char nextChar() throws IOException {
int c;
for (c = scan(); c <= 32; c = scan())
;
return (char) c;
}
int nextInt() throws IOException {
int c, val = 0;
for (c = scan(); c <= 32; c = scan())
;
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
long nextLong() throws IOException {
int c;
long val = 0;
for (c = scan(); c <= 32; c = scan())
;
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
}
| 0 |
Non-plagiarised
|
fc7dfa16
|
fe94ee2f
|
import java.util.*;
import java.io.*;
public class C {
static class Scan {
private byte[] buf=new byte[1024];
private int index;
private InputStream in;
private int total;
public Scan()
{
in=System.in;
}
public int scan()throws IOException
{
if(total<0)
throw new InputMismatchException();
if(index>=total)
{
index=0;
total=in.read(buf);
if(total<=0)
return -1;
}
return buf[index++];
}
public int scanInt()throws IOException
{
int integer=0;
int n=scan();
while(isWhiteSpace(n))
n=scan();
int neg=1;
if(n=='-')
{
neg=-1;
n=scan();
}
while(!isWhiteSpace(n))
{
if(n>='0'&&n<='9')
{
integer*=10;
integer+=n-'0';
n=scan();
}
else throw new InputMismatchException();
}
return neg*integer;
}
public double scanDouble()throws IOException
{
double doub=0;
int n=scan();
while(isWhiteSpace(n))
n=scan();
int neg=1;
if(n=='-')
{
neg=-1;
n=scan();
}
while(!isWhiteSpace(n)&&n!='.')
{
if(n>='0'&&n<='9')
{
doub*=10;
doub+=n-'0';
n=scan();
}
else throw new InputMismatchException();
}
if(n=='.')
{
n=scan();
double temp=1;
while(!isWhiteSpace(n))
{
if(n>='0'&&n<='9')
{
temp/=10;
doub+=(n-'0')*temp;
n=scan();
}
else throw new InputMismatchException();
}
}
return doub*neg;
}
public String scanString()throws IOException
{
StringBuilder sb=new StringBuilder();
int n=scan();
while(isWhiteSpace(n))
n=scan();
while(!isWhiteSpace(n))
{
sb.append((char)n);
n=scan();
}
return sb.toString();
}
private boolean isWhiteSpace(int n)
{
if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1)
return true;
return false;
}
}
public static void sort(int arr[],int l,int r) { //sort(arr,0,n-1);
if(l==r) {
return;
}
int mid=(l+r)/2;
sort(arr,l,mid);
sort(arr,mid+1,r);
merge(arr,l,mid,mid+1,r);
}
public static void merge(int arr[],int l1,int r1,int l2,int r2) {
int tmp[]=new int[r2-l1+1];
int indx1=l1,indx2=l2;
//sorting the two halves using a tmp array
for(int i=0;i<tmp.length;i++) {
if(indx1>r1) {
tmp[i]=arr[indx2];
indx2++;
continue;
}
if(indx2>r2) {
tmp[i]=arr[indx1];
indx1++;
continue;
}
if(arr[indx1]<arr[indx2]) {
tmp[i]=arr[indx1];
indx1++;
continue;
}
tmp[i]=arr[indx2];
indx2++;
}
//Copying the elements of tmp into the main array
for(int i=0,j=l1;i<tmp.length;i++,j++) {
arr[j]=tmp[i];
}
}
public static void sort(long arr[],int l,int r) { //sort(arr,0,n-1);
if(l==r) {
return;
}
int mid=(l+r)/2;
sort(arr,l,mid);
sort(arr,mid+1,r);
merge(arr,l,mid,mid+1,r);
}
public static void merge(long arr[],int l1,int r1,int l2,int r2) {
long tmp[]=new long[r2-l1+1];
int indx1=l1,indx2=l2;
//sorting the two halves using a tmp array
for(int i=0;i<tmp.length;i++) {
if(indx1>r1) {
tmp[i]=arr[indx2];
indx2++;
continue;
}
if(indx2>r2) {
tmp[i]=arr[indx1];
indx1++;
continue;
}
if(arr[indx1]<arr[indx2]) {
tmp[i]=arr[indx1];
indx1++;
continue;
}
tmp[i]=arr[indx2];
indx2++;
}
//Copying the elements of tmp into the main array
for(int i=0,j=l1;i<tmp.length;i++,j++) {
arr[j]=tmp[i];
}
}
static int n;
static long arr[];
public static void main(String args[]) throws IOException {
Scan input=new Scan();
StringBuilder ans=new StringBuilder("");
int test=input.scanInt();
for(int tt=1;tt<=test;tt++) {
n=input.scanInt();
arr=new long[n];
for(int i=0;i<n;i++) {
arr[i]=input.scanInt();
}
ans.append(solve()+"\n");
}
System.out.println(ans);
}
public static long solve() {
long ans=Long.MAX_VALUE;
long r_min=Long.MAX_VALUE,u_min=Long.MAX_VALUE;
long r_rem=n,u_rem=n,sum=0;
for(int i=0;i<n;i++) {
if(i%2==0) {
r_min=Math.min(r_min,arr[i]);
r_rem--;
}
else {
u_min=Math.min(u_min,arr[i]);
u_rem--;
}
sum+=arr[i];
if(i==0) {
continue;
}
ans=Math.min(ans,sum+(r_rem*r_min)+(u_rem*u_min));
}
r_min=Long.MAX_VALUE;
u_min=Long.MAX_VALUE;
r_rem=n;
u_rem=n;
sum=0;
for(int i=0;i<n;i++) {
if(i%2==1) {
r_min=Math.min(r_min,arr[i]);
r_rem--;
}
else {
u_min=Math.min(u_min,arr[i]);
u_rem--;
}
sum+=arr[i];
if(i==0) {
continue;
}
ans=Math.min(ans,sum+(r_rem*r_min)+(u_rem*u_min));
}
return ans;
}
}
|
import java.util.*;
import java.io.*;
public class C {
static class Scan {
private byte[] buf=new byte[1024];
private int index;
private InputStream in;
private int total;
public Scan()
{
in=System.in;
}
public int scan()throws IOException
{
if(total<0)
throw new InputMismatchException();
if(index>=total)
{
index=0;
total=in.read(buf);
if(total<=0)
return -1;
}
return buf[index++];
}
public int scanInt()throws IOException
{
int integer=0;
int n=scan();
while(isWhiteSpace(n))
n=scan();
int neg=1;
if(n=='-')
{
neg=-1;
n=scan();
}
while(!isWhiteSpace(n))
{
if(n>='0'&&n<='9')
{
integer*=10;
integer+=n-'0';
n=scan();
}
else throw new InputMismatchException();
}
return neg*integer;
}
public double scanDouble()throws IOException
{
double doub=0;
int n=scan();
while(isWhiteSpace(n))
n=scan();
int neg=1;
if(n=='-')
{
neg=-1;
n=scan();
}
while(!isWhiteSpace(n)&&n!='.')
{
if(n>='0'&&n<='9')
{
doub*=10;
doub+=n-'0';
n=scan();
}
else throw new InputMismatchException();
}
if(n=='.')
{
n=scan();
double temp=1;
while(!isWhiteSpace(n))
{
if(n>='0'&&n<='9')
{
temp/=10;
doub+=(n-'0')*temp;
n=scan();
}
else throw new InputMismatchException();
}
}
return doub*neg;
}
public String scanString()throws IOException
{
StringBuilder sb=new StringBuilder();
int n=scan();
while(isWhiteSpace(n))
n=scan();
while(!isWhiteSpace(n))
{
sb.append((char)n);
n=scan();
}
return sb.toString();
}
private boolean isWhiteSpace(int n)
{
if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1)
return true;
return false;
}
}
public static void sort(int arr[],int l,int r) { //sort(arr,0,n-1);
if(l==r) {
return;
}
int mid=(l+r)/2;
sort(arr,l,mid);
sort(arr,mid+1,r);
merge(arr,l,mid,mid+1,r);
}
public static void merge(int arr[],int l1,int r1,int l2,int r2) {
int tmp[]=new int[r2-l1+1];
int indx1=l1,indx2=l2;
//sorting the two halves using a tmp array
for(int i=0;i<tmp.length;i++) {
if(indx1>r1) {
tmp[i]=arr[indx2];
indx2++;
continue;
}
if(indx2>r2) {
tmp[i]=arr[indx1];
indx1++;
continue;
}
if(arr[indx1]<arr[indx2]) {
tmp[i]=arr[indx1];
indx1++;
continue;
}
tmp[i]=arr[indx2];
indx2++;
}
//Copying the elements of tmp into the main array
for(int i=0,j=l1;i<tmp.length;i++,j++) {
arr[j]=tmp[i];
}
}
public static void sort(long arr[],int l,int r) { //sort(arr,0,n-1);
if(l==r) {
return;
}
int mid=(l+r)/2;
sort(arr,l,mid);
sort(arr,mid+1,r);
merge(arr,l,mid,mid+1,r);
}
public static void merge(long arr[],int l1,int r1,int l2,int r2) {
long tmp[]=new long[r2-l1+1];
int indx1=l1,indx2=l2;
//sorting the two halves using a tmp array
for(int i=0;i<tmp.length;i++) {
if(indx1>r1) {
tmp[i]=arr[indx2];
indx2++;
continue;
}
if(indx2>r2) {
tmp[i]=arr[indx1];
indx1++;
continue;
}
if(arr[indx1]<arr[indx2]) {
tmp[i]=arr[indx1];
indx1++;
continue;
}
tmp[i]=arr[indx2];
indx2++;
}
//Copying the elements of tmp into the main array
for(int i=0,j=l1;i<tmp.length;i++,j++) {
arr[j]=tmp[i];
}
}
static int n;
static long arr[];
public static void main(String args[]) throws IOException {
Scan input=new Scan();
StringBuilder ans=new StringBuilder("");
int test=input.scanInt();
for(int tt=1;tt<=test;tt++) {
n=input.scanInt();
arr=new long[n];
for(int i=0;i<n;i++) {
arr[i]=input.scanInt();
}
ans.append(solve()+"\n");
}
System.out.println(ans);
}
public static long solve() {
long ans=Long.MAX_VALUE;
long r_min=Long.MAX_VALUE,u_min=Long.MAX_VALUE;
long r_rem=n,u_rem=n,sum=0;
for(int i=0;i<n;i++) {
if(i%2==0) {
r_min=Math.min(r_min,arr[i]);
r_rem--;
}
else {
u_min=Math.min(u_min,arr[i]);
u_rem--;
}
sum+=arr[i];
if(i==0) {
continue;
}
ans=Math.min(ans,sum+(r_rem*r_min)+(u_rem*u_min));
}
r_min=Long.MAX_VALUE;
u_min=Long.MAX_VALUE;
r_rem=n;
u_rem=n;
sum=0;
for(int i=0;i<n;i++) {
if(i%2==1) {
r_min=Math.min(r_min,arr[i]);
r_rem--;
}
else {
u_min=Math.min(u_min,arr[i]);
u_rem--;
}
sum+=arr[i];
if(i==0) {
continue;
}
ans=Math.min(ans,sum+(r_rem*r_min)+(u_rem*u_min));
}
return ans;
}
}
| 1 |
Plagiarised
|
548ffb07
|
921b6e4a
|
import java.io.*;
import java.util.*;
public class D_Java {
public static final int MOD = 998244353;
public static int mul(int a, int b) {
return (int)((long)a * (long)b % MOD);
}
int[] f;
int[] rf;
public int C(int n, int k) {
return (k < 0 || k > n) ? 0 : mul(f[n], mul(rf[n-k], rf[k]));
}
public static int pow(int a, int n) {
int res = 1;
while (n != 0) {
if ((n & 1) == 1) {
res = mul(res, a);
}
a = mul(a, a);
n >>= 1;
}
return res;
}
static void shuffleArray(int[] a) {
Random rnd = new Random();
for (int i = a.length-1; i > 0; i--) {
int index = rnd.nextInt(i + 1);
int tmp = a[index];
a[index] = a[i];
a[i] = tmp;
}
}
public static int inv(int a) {
return pow(a, MOD-2);
}
public void doIt() throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tok = new StringTokenizer(in.readLine());
int n = Integer.parseInt(tok.nextToken());
int k = Integer.parseInt(tok.nextToken());
f = new int[n+42];
rf = new int[n+42];
f[0] = rf[0] = 1;
for (int i = 1; i < f.length; ++i) {
f[i] = mul(f[i-1], i);
rf[i] = mul(rf[i-1], inv(i));
}
int[] events = new int[2*n];
for (int i = 0; i < n; ++i) {
tok = new StringTokenizer(in.readLine());
int le = Integer.parseInt(tok.nextToken());
int ri = Integer.parseInt(tok.nextToken());
events[i] = le*2;
events[i + n] = ri*2 + 1;
}
shuffleArray(events);
Arrays.sort(events);
int ans = 0;
int balance = 0;
for (int r = 0; r < 2*n;) {
int l = r;
while (r < 2*n && events[l] == events[r]) {
++r;
}
int added = r - l;
if (events[l] % 2 == 0) {
// Open event
ans += C(balance + added, k);
if (ans >= MOD) ans -= MOD;
ans += MOD - C(balance, k);
if (ans >= MOD) ans -= MOD;
balance += added;
} else {
// Close event
balance -= added;
}
}
in.close();
System.out.println(ans);
}
public static void main(String[] args) throws IOException {
(new D_Java()).doIt();
}
}
|
import java.io.*;
import java.util.*;
public class D_Java {
public static final int MOD = 998244353;
public static int mul(int a, int b) {
return (int)((long)a * (long)b % MOD);
}
int[] f;
int[] rf;
public int C(int n, int k) {
return (k < 0 || k > n) ? 0 : mul(f[n], mul(rf[n-k], rf[k]));
}
public static int pow(int a, int n) {
int res = 1;
while (n != 0) {
if ((n & 1) == 1) {
res = mul(res, a);
}
a = mul(a, a);
n >>= 1;
}
return res;
}
static void shuffleArray(int[] a) {
Random rnd = new Random();
for (int i = a.length-1; i > 0; i--) {
int index = rnd.nextInt(i + 1);
int tmp = a[index];
a[index] = a[i];
a[i] = tmp;
}
}
public static int inv(int a) {
return pow(a, MOD-2);
}
public void doIt() throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tok = new StringTokenizer(in.readLine());
int n = Integer.parseInt(tok.nextToken());
int k = Integer.parseInt(tok.nextToken());
f = new int[n+42];
rf = new int[n+42];
f[0] = rf[0] = 1;
for (int i = 1; i < f.length; ++i) {
f[i] = mul(f[i-1], i);
rf[i] = mul(rf[i-1], inv(i));
}
int[] events = new int[2*n];
for (int i = 0; i < n; ++i) {
tok = new StringTokenizer(in.readLine());
int le = Integer.parseInt(tok.nextToken());
int ri = Integer.parseInt(tok.nextToken());
events[i] = le*2;
events[i + n] = ri*2 + 1;
}
shuffleArray(events);
Arrays.sort(events);
int ans = 0;
int balance = 0;
for (int r = 0; r < 2*n;) {
int l = r;
while (r < 2*n && events[l] == events[r]) {
++r;
}
int added = r - l;
if (events[l] % 2 == 0) {
// Open event
ans += C(balance + added, k);
if (ans >= MOD) ans -= MOD;
ans += MOD - C(balance, k);
if (ans >= MOD) ans -= MOD;
balance += added;
} else {
// Close event
balance -= added;
}
}
in.close();
System.out.println(ans);
}
public static void main(String[] args) throws IOException {
(new D_Java()).doIt();
}
}
| 1 |
Plagiarised
|
11373c16
|
d8e4eb5e
|
/* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Codechef
{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 void main (String[] args) throws java.lang.Exception
{
FastReader scan = new FastReader();
PrintWriter pw = new PrintWriter(System.out);
int n = scan.nextInt();
ArrayList<Integer> a = new ArrayList<>();
ArrayList<Integer> b = new ArrayList<>();
for(int i=0;i<n;i++){
int x = scan.nextInt();
if(x==1)
a.add(i);
else
b.add(i);
}
int x = a.size();
if(x==0){
pw.println(0);
pw.flush();
return;
}
int y = b.size();
int dp[][] = new int[x][y];
int min = Integer.MAX_VALUE;
for(int i=0;i<y;i++){
min = Math.min(Math.abs(a.get(0) - b.get(i)),min);
dp[0][i] = min;
}
for(int i=1;i<x;i++){
min = Integer.MAX_VALUE;
for(int j=i;j<y;j++){
min = Math.min(Math.abs(a.get(i)-b.get(j))+dp[i-1][j-1],min);
dp[i][j] = min;
}
}
pw.println(dp[x-1][y-1]);
pw.flush();
}
}
|
import java.io.*;
import java.util.*;
public class E {
public static void main(String[] args) throws NumberFormatException, IOException {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int cnt = n;
boolean[] non = new boolean[n];
StringTokenizer st = new StringTokenizer(br.readLine());
for(int i = 0; i < n; i++) {
if(Integer.parseInt(st.nextToken()) == 0) {
non[i] = true;
cnt--;
}
}
int x = 0;
int y = 0;
int[] location = new int[cnt];
int[] rlocation = new int[n-cnt];
for(int i = 0; i < n; i++) {
if(!non[i]) {
location[x] = i;
x++;
}else{
rlocation[y] = i;
y++;
}
}
int[][] dp = new int[(n-cnt)+1][cnt+1];
Arrays.fill(dp[0], 100000000);
dp[0][0] = 0;
for(int i = 0; i < n-cnt; i++) {
//System.out.println("HIT");
if(i < (n-cnt))
Arrays.fill(dp[i+1], 100000000);
for(int j = 0; j < cnt; j++) {
if(i < (n-cnt)) {
dp[i+1][j] = Math.min(dp[i+1][j], dp[i][j]);
dp[i+1][j+1] = Math.min(dp[i+1][j+1], dp[i][j] + Math.abs(rlocation[i] - location[j]));
//System.out.println(dp[i+1][j+1] + " " + dp[i][j] + " " + j + " " + rlocation[i] + " " + location[j]);
}
}
}
int min = Integer.MAX_VALUE;
for(int i = 0; i < (n-cnt)+1; i++) {
min = Math.min(dp[i][cnt], min);
}
System.out.println(min);
}
}
| 0 |
Non-plagiarised
|
99bc7da3
|
ced4639e
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class Codeforces {
static int mod =1000000007;
static Set<Integer> set;
public static void main(String[] args) throws Exception {
PrintWriter out=new PrintWriter(System.out);
FastScanner fs=new FastScanner();
int t=fs.nextInt();
while(t-->0) {
int n=fs.nextInt();
int arr[]=new int[n];
// set=new HashSet<>();
for(int i=0;i<n;i++) {
arr[i]=Math.abs(fs.nextInt());
// set.add(arr[i]);
}
// sort(arr);
// for(int i=0;i<n;i++) System.out.print(arr[i]+" ");
// System.out.println();
// if(set.size()<n||set.contains(0)) {
// System.out.println("YES");
// continue;
// }
boolean f=false;
for(int i=0;i<n;i++) {
boolean cur=recur(0,i,arr,0);
if(cur) {
f=true;
break;
}
}
if(f) System.out.println("YES");
else System.out.println("NO");
}
out.close();
}
static boolean recur(int pos,int ind,int arr[],int sum) {
if(pos==ind) return recur(pos+1,ind,arr,sum);
if(sum==arr[ind]) return true;
if(pos==arr.length) {
return false;
}
if(recur(pos+1,ind,arr,sum+arr[pos])) return true;
if(recur(pos+1,ind,arr,sum)) return true;
if(recur(pos+1,ind,arr,sum-arr[pos])) return true;
return false;
}
static long gcd(long a,long b) {
if(b==0) return a;
return gcd(b,a%b);
}
static long nck(int n,int k) {
if(k>n) return 0;
long res=1;
res*=fact(n);
res%=mod;
res*=modInv(fact(k));
res%=mod;
res*=modInv(fact(n-k));
res%=mod;
return res;
}
static long fact(long n) {
long res=1;
for(int i=2;i<=n;i++) {
res*=i;
res%=mod;
}
return res;
}
static long pow(long a,long b) {
long res=1;
while(b!=0) {
if((b&1)!=0) {
res*=a;
res%=mod;
}
a*=a;
a%=mod;
b=b>>1;
}
return res;
}
static long modInv(long n) {
return pow(n,mod-2);
}
static void sort(int[] a) {
//suffle
int n=a.length;
Random r=new Random();
for (int i=0; i<a.length; i++) {
int oi=r.nextInt(n);
int temp=a[i];
a[i]=a[oi];
a[oi]=temp;
}
//then sort
Arrays.sort(a);
}
// Use this to input code since it is faster than a Scanner
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());
}
}
}
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class Main {
public static boolean find(int[] a) {
int n = a.length;
for (int i = 1; i < Math.pow(3, n); i++) {
int sum = 0;
int x = i;
for (int j = 0; j < n; j++) {
int r = x % 3;
if (r == 1) sum += a[j];
else if (r ==2) sum -= a[j];
x /= 3;
}
if (sum == 0) return true;
}
return false;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
int t = Integer.parseInt(br.readLine());
for (int i = 0; i < t; i++) {
int n = Integer.parseInt(br.readLine());
int[] a = new int[n];
String[] s = br.readLine().trim().split("\\s+");
for (int j = 0; j < n; j++) {
a[j] = Integer.parseInt(s[j]);
}
boolean res = find(a);
if (res) pw.println("YES");
else pw.println("NO");
}
pw.flush();
}
}
| 0 |
Non-plagiarised
|
034030f3
|
9e4ddc38
|
import java.util.*;
import java.io.*;
public class D_1525 {
static int INF = (int)1e9;
static int n, m;
static int[] full, free;
static int[][] memo;
public static int dp(int i, int j) {
if(i == n)
return 0;
if(j == m)
return INF;
if(memo[i][j] != -1)
return memo[i][j];
return memo[i][j] = Math.min(dp(i, j + 1), Math.abs(free[j] - full[i]) + dp(i + 1, j + 1));
}
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int l = sc.nextInt();
int[] array = sc.nextIntArray(l);
n = 0;
for(int i = 0; i < l; i++)
if(array[i] == 1)
n++;
m = l - n;
full = new int[n];
free = new int[m];
int ind1 = 0, ind2 = 0;
for(int i = 0; i < l; i++)
if(array[i] == 0)
free[ind2++] = i;
else
full[ind1++] = i;
memo = new int[n][m];
for(int[] i : memo)
Arrays.fill(i, -1);
pw.println(dp(0, 0));
pw.flush();
}
public static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public Scanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public int[] nextIntArray(int n) throws IOException {
int[] array = new int[n];
for (int i = 0; i < n; i++)
array[i] = nextInt();
return array;
}
public Integer[] nextIntegerArray(int n) throws IOException {
Integer[] array = new Integer[n];
for (int i = 0; i < n; i++)
array[i] = new Integer(nextInt());
return array;
}
public long[] nextLongArray(int n) throws IOException {
long[] array = new long[n];
for (int i = 0; i < n; i++)
array[i] = nextLong();
return array;
}
public double[] nextDoubleArray(int n) throws IOException {
double[] array = new double[n];
for (int i = 0; i < n; i++)
array[i] = nextDouble();
return array;
}
public static int[] shuffle(int[] a) {
int n = a.length;
Random rand = new Random();
for (int i = 0; i < n; i++) {
int tmpIdx = rand.nextInt(n);
int tmp = a[i];
a[i] = a[tmpIdx];
a[tmpIdx] = tmp;
}
return a;
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
}
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Try2{
public static void main(String[] args) throws IOException {
FastScanner fs = new FastScanner();
// int t =fs.nextInt();
int t=1;
while (t-- > 0) {
int n = fs.nextInt();
int a[] = new int[n];
int countOne = 0;
ArrayList<Integer> aa = new ArrayList<Integer>();
for(int i =0;i<n;i++) {
a[i] =fs.nextInt();
if(a[i]==1) {
countOne++;
aa.add(i);
}
}
int dp[][] = new int[n+1][countOne+1];
for(int i =0 ;i<=n;i++) {
for(int j =0 ;j<=countOne;j++) {
dp[i][j] = Integer.MAX_VALUE;
}
}
dp[0][0] =0;
for(int i =0 ;i<n;i++) {
for(int j =0 ;j<countOne+1;j++) {
if(dp[i][j]==Integer.MAX_VALUE) continue;
dp[i+1][j] = Math.min(dp[i][j], dp[i+1][j]);
if(j<countOne && a[i]==0) {
dp[i+1][j+1]=Math.min(dp[i][j]+Math.abs(aa.get(j)-i),dp[i+1][j+1]);
}
}
}
System.out.println(dp[n][countOne]);
}
}
static final Random random = new Random();
static void ruffleSort(int[] a) {
int n = a.length;// shuffle, then sort
for (int i = 0; i < n; i++) {
int oi = random.nextInt(n), temp = a[oi];
a[oi] = a[i];
a[i] = temp;
}
Arrays.sort(a);
}
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
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());
}
}
}
| 0 |
Non-plagiarised
|
1c8bb204
|
7d7cf9a7
|
import javax.print.DocFlavor;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class BST {
static class pair implements Comparable{
int high;
int idx;
pair(int x , int y){
high = x;
idx = y;
}
public String toString(){
return high + " " + idx;
}
@Override
public int compareTo(Object o) {
pair p = (pair)o;
return high-p.high;
}
}
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
while (t-->0){
int n = Integer.parseInt(br.readLine());
long [] arr = new long[n];
StringTokenizer st = new StringTokenizer(br.readLine());
for (int i = 0; i < n; i++) {
long tmp = Long.parseLong(st.nextToken());
arr[i] = tmp;
}
int h = 1;
int v = 1;
long minHor = arr[0];
long minVir = arr[1];
long sum0 = arr[0];
long sum1 = arr[1];
long total = (arr[0] + arr[1])*n;
for (int i = 2; i < n; i++) {
if(i%2==0){
h++;
sum0 += arr[i];
minHor = Math.min(arr[i] , minHor);
total = Math.min(total , minHor*(n-h+1)+(sum0-minHor)+minVir*(n-v+1)+(sum1-minVir));
}else {
v++;
sum1 += arr[i];
minVir = Math.min(arr[i] , minVir);
total = Math.min(total , minHor*(n-h+1)+(sum0-minHor)+minVir*(n-v+1)+(sum1-minVir));
}
}
System.out.println(total);
}
}
}
|
import java.util.*;
import java.io.*;
import java.math.*;
public class Coder {
static int n;
static long c[];
static StringBuilder str = new StringBuilder("");
static void solve() {
long mne=c[0];
long mno=c[1];
long ans=(c[0]+c[1])*n;
long se=c[0];
long so=c[1];
long ecnt=1,ocnt=1;
for(int i=2;i<n;i++){
if(i%2==0){mne=Math.min(mne, c[i]);se+=c[i];ecnt++;}
else{mno=Math.min(mno, c[i]);so+=c[i];ocnt++;}
ans=Math.min(ans, se+mne*(n-ecnt)+so+mno*(n-ocnt));
}
str.append(ans).append("\n");
}
public static void main(String[] args) throws java.lang.Exception {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
int q = Integer.parseInt(bf.readLine().trim());
while(q-->0) {
n=Integer.parseInt(bf.readLine().trim());
c=new long[n];
String s[]=bf.readLine().trim().split("\\s+");
for(int i=0;i<n;i++) c[i]=Long.parseLong(s[i]);
solve();
}
System.out.print(str);
}
}
| 0 |
Non-plagiarised
|
3a12e509
|
e812ee0b
|
import java.io.*;
import java.util.*;
public class Practice
{
// static final long mod=7420738134811L;
static int mod=1000000007;
static final int size=501;
static FastReader sc=new FastReader(System.in);
// static Reader sc=new Reader();
static PrintWriter out=new PrintWriter(System.out);
static long[] factorialNumInverse;
static long[] naturalNumInverse;
static int[] sp;
static long[] fact;
static ArrayList<Integer> pr;
public static void main(String[] args) throws IOException
{
// System.setIn(new FileInputStream("input.txt"));
// System.setOut(new PrintStream("output.txt"));
// factorial(mod);
// InverseofNumber(mod);
// InverseofFactorial(mod);
// make_seive();
int t=1;
t=sc.nextInt();
while(t-->0)
solve();
out.close();
out.flush();
}
static void solve() throws IOException
{
int n=sc.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++)
arr[i]=sc.nextInt();
String s=sc.next();
ArrayList<Integer> blue=new ArrayList<Integer>();
ArrayList<Integer> red=new ArrayList<Integer>();
for(int i=0;i<n;i++)
{
if(s.charAt(i)=='B')
blue.add(arr[i]);
else
red.add(arr[i]);
}
Collections.sort(blue);
Collections.sort(red);
for(int i=0;i<blue.size();i++)
{
if(blue.get(i)<i+1)
{
out.println("NO");
return;
}
}
for(int i=0;i<red.size();i++)
{
if(red.get(i)>i+1+blue.size())
{
out.println("NO");
return;
}
}
out.println("YES");
}
static class Pair implements Cloneable, Comparable<Pair>
{
int x,y;
Pair(int a,int b)
{
this.x=a;
this.y=b;
}
@Override
public boolean equals(Object obj)
{
if(obj instanceof Pair)
{
Pair p=(Pair)obj;
return p.x==this.x && p.y==this.y;
}
return false;
}
@Override
public int hashCode()
{
return Math.abs(x)+500*Math.abs(y);
}
@Override
public String toString()
{
return "("+x+" "+y+")";
}
@Override
protected Pair clone() throws CloneNotSupportedException {
return new Pair(this.x,this.y);
}
@Override
public int compareTo(Pair a)
{
int t= this.x-a.x;
if(t!=0)
return t;
else
return this.y-a.y;
}
public void swap()
{
this.y=this.y+this.x;
this.x=this.y-this.x;
this.y=this.y-this.x;
}
}
static class Tuple implements Cloneable, Comparable<Tuple>
{
int x,y,z;
Tuple(int a,int b,int c)
{
this.x=a;
this.y=b;
this.z=c;
}
public boolean equals(Object obj)
{
if(obj instanceof Tuple)
{
Tuple p=(Tuple)obj;
return p.x==this.x && p.y==this.y && p.z==this.z;
}
return false;
}
@Override
public int hashCode()
{
return (this.x+501*this.y);
}
@Override
public String toString()
{
return "("+x+","+y+","+z+")";
}
@Override
protected Tuple clone() throws CloneNotSupportedException {
return new Tuple(this.x,this.y,this.z);
}
@Override
public int compareTo(Tuple a)
{
int x=this.z-a.z;
if(x!=0)
return x;
int X= this.x-a.x;
if(X!=0)
return X;
return a.y-this.y;
}
}
static void arraySort(int arr[])
{
ArrayList<Integer> a=new ArrayList<Integer>();
for (int i = 0; i < arr.length; i++) {
a.add(arr[i]);
}
Collections.sort(a);
for (int i = 0; i < arr.length; i++) {
arr[i]=a.get(i);
}
}
static void arraySort(long arr[])
{
ArrayList<Long> a=new ArrayList<Long>();
for (int i = 0; i < arr.length; i++) {
a.add(arr[i]);
}
Collections.sort(a);
for (int i = 0; i < arr.length; i++) {
arr[i]=a.get(i);
}
}
static HashSet<Integer> primeFactors(int n)
{
HashSet<Integer> ans=new HashSet<Integer>();
if(n%2==0)
{
ans.add(2);
while((n&1)==0)
n=n>>1;
}
for(int i=3;i*i<=n;i+=2)
{
if(n%i==0)
{
ans.add(i);
while(n%i==0)
n=n/i;
}
}
if(n!=1)
ans.add(n);
return ans;
}
static void make_seive()
{
sp=new int[size];
pr=new ArrayList<Integer>();
for (int i=2; i<size; ++i) {
if (sp[i] == 0) {
sp[i] = i;
pr.add(i);
}
for (int j=0; j<(int)pr.size() && pr.get(j)<=sp[i] && i*pr.get(j)<size; ++j)
sp[i * pr.get(j)] = pr.get(j);
}
}
public static void InverseofNumber(int p)
{
naturalNumInverse=new long[size];
naturalNumInverse[0] = naturalNumInverse[1] = 1;
for(int i = 2; i < size; i++)
naturalNumInverse[i] = naturalNumInverse[p % i] * (long)(p - p / i) % p;
}
// Function to precompute inverse of factorials
public static void InverseofFactorial(int p)
{
factorialNumInverse=new long[size];
factorialNumInverse[0] = factorialNumInverse[1] = 1;
// pre-compute inverse of natural numbers
for(int i = 2; i < size; i++)
factorialNumInverse[i] = (naturalNumInverse[i] * factorialNumInverse[i - 1]) % p;
}
// Function to calculate factorial of 1 to 200001
public static void factorial(int p)
{
fact=new long[size];
fact[0] = 1;
for(int i = 1; i < size; i++)
fact[i] = (fact[i - 1] * (long)i) % p;
}
// Function to return nCr % p in O(1) time
public static long Binomial(int N, int R)
{
if(R<0)
return 1;
// n C r = n!*inverse(r!)*inverse((n-r)!)
long ans = ((fact[N] * factorialNumInverse[R]) % mod * factorialNumInverse[N - R]) % mod;
return ans;
}
static int findXOR(int x) //from 0 to x
{
if(x<0)
return 0;
if(x%4==0)
return x;
if(x%4==1)
return 1;
if(x%4==2)
return x+1;
return 0;
}
static boolean isPrime(long x)
{
if(x==1)
return false;
if(x<=3)
return true;
if(x%2==0 || x%3==0)
return false;
for(int i=5;i<=Math.sqrt(x);i+=2)
if(x%i==0)
return false;
return true;
}
static long gcd(long a,long b)
{
return (b==0)?a:gcd(b,a%b);
}
static int gcd(int a,int b)
{
return (b==0)?a:gcd(b,a%b);
}
static class Node
{
int vertex;
HashSet<Edge> adj;
int taxC,taxD;
Node(int ver)
{
vertex=ver;
taxD=0;
taxC=0;
adj=new HashSet<Edge>();
}
@Override
public String toString()
{
return vertex+" ";
}
}
static class Edge
{
Node to;
int cost;
Edge(Node t,int c)
{
this.to=t;
this.cost=c;
}
@Override
public String toString() {
return "("+to.vertex+","+cost+") ";
}
}
static long power(long x, long y)
{
if(x<=0)
return 1;
long res = 1;
x = x % mod;
if (x == 0)
return 0;
while (y > 0)
{
if ((y & 1) != 0)
res = (res * x) % mod;
y = y >> 1; // y = y/2
x = (x * x) % mod;
}
return res;
}
static long binomialCoeff(long n, long k)
{
if(n<k)
return 0;
long res = 1;
// if(k>n)
// return 0;
// Since C(n, k) = C(n, n-k)
if (k > n - k)
k = n - k;
// Calculate value of
// [n * (n-1) *---* (n-k+1)] / [k * (k-1) *----* 1]
for (long i = 0; i < k; ++i) {
res *= (n - i);
res /= (i + 1);
}
return res;
}
static class FastReader
{
byte[] buf = new byte[2048];
int index, total;
InputStream in;
FastReader(InputStream is)
{
in = is;
}
int scan() throws IOException
{
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0) {
return -1;
}
}
return buf[index++];
}
String next() throws IOException
{
int c;
for (c = scan(); c <= 32; c = scan());
StringBuilder sb = new StringBuilder();
for (; c > 32; c = scan()) {
sb.append((char) c);
}
return sb.toString();
}
int nextInt() throws IOException
{
int c, val = 0;
for (c = scan(); c <= 32; c = scan());
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
long nextLong() throws IOException
{
int c;
long val = 0;
for (c = scan(); c <= 32; c = scan());
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
}
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(
new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
if (cnt != 0) {
break;
}
else {
continue;
}
}
buf[cnt++] = (byte)c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0,
BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
public void printarray(int arr[])
{
for (int i = 0; i < arr.length; i++)
System.out.print(arr[i]+" ");
System.out.println();
}
}
}
|
import java.util.*;
import java.util.concurrent.Exchanger;
public class Codeforces {
static int[] mass = new int[200_001];
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
StringBuilder stringBuilder = new StringBuilder();
int t = scanner.nextInt();
for (int z =0 ; z < t ; ++z) {
solve(scanner, stringBuilder);
}
System.out.print(stringBuilder);
}
private static void solve(Scanner scanner, StringBuilder stringBuilder) {
int n = scanner.nextInt();
for (int i = 0 ; i < n ; ++i) {
mass[i] = scanner.nextInt();
}
String colors = scanner.next();
List<Integer> red = new ArrayList<>(n);
List<Integer> blue = new ArrayList<>(n);
for (int i = 0 ; i < n ; ++i) {
if(colors.charAt(i) == 'R') red.add(mass[i]);
else blue.add(mass[i]);
}
red.sort(Comparator.reverseOrder());
blue.sort(Comparator.naturalOrder());
int creatd = 0;
int upper = n;
int down = 1;
for (Integer integer : red) {
if (integer > upper) {
stringBuilder.append("NO\n");
return;
} else {
creatd++;
upper--;
}
}
for (Integer integer : blue) {
if (integer < down) {
stringBuilder.append("NO\n");
return;
} else {
creatd++;
down++;
}
}
if (creatd == n) stringBuilder.append("YES\n");
else stringBuilder.append("NO\n");
}
}
| 0 |
Non-plagiarised
|
94b3b86d
|
efe594c3
|
import java.io.*;
import java.util.*;
public class D
{
public static ArrayList<Integer> adj[];
public static int node;
public static int dist = 0;
public static void main(String[] args) throws IOException
{
FastScanner sc = new FastScanner();
int T = sc.nextInt();
PrintWriter out = new PrintWriter(System.out);
for(int t = 0; t < T; t++){
int N = sc.nextInt();
int a = sc.nextInt(); int b = sc.nextInt();
int da = sc.nextInt(); int db = sc.nextInt();
adj = new ArrayList[N+1];
for(int i = 0; i <= N; i++){
adj[i] = new ArrayList<Integer>();
}
for(int i = 0; i < N-1; i++){
int v = sc.nextInt();
int u = sc.nextInt();
adj[v].add(u);
adj[u].add(v);
}
if(db > 2*da){
dfs1(a, 0, b, 0);
if(dist <= da){
out.println("Alice");
}
else{
node = 0;
dist = 0;
dfs(1, 0, 0);
dfs(node, 0, 0);
if(dist > 2*da){
out.println("Bob");
}
else{
out.println("Alice");
}
}
}
else{
out.println("Alice");
}
}
out.close();
}
public static void dfs1(int a, int p, int b, int d){
if(a == b){
dist = d;
}
for(int next : adj[a]){
if(next != p){
dfs1(next, a, b, d+1);
}
}
}
public static void dfs(int i, int p, int d){
if(d > dist){
node = i;
dist = d;
}
for(int next : adj[i]){
if(next != p){
dfs(next, i, d+1);
}
}
}
static class FastScanner {
private int BS = 1 << 16;
private char NC = (char) 0;
private byte[] buf = new byte[BS];
private int bId = 0, size = 0;
private char c = NC;
private double cnt = 1;
private BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
} catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
private char getChar() {
while (bId == size) {
try {
size = in.read(buf);
} catch (Exception e) {
return NC;
}
if (size == -1)
return NC;
bId = 0;
}
return (char) buf[bId++];
}
public int nextInt() {
return (int) nextLong();
}
public int[] nextInts(int N) {
int[] res = new int[N];
for (int i = 0; i < N; i++) {
res[i] = (int) nextLong();
}
return res;
}
public long[] nextLongs(int N) {
long[] res = new long[N];
for (int i = 0; i < N; i++) {
res[i] = nextLong();
}
return res;
}
public long nextLong() {
cnt = 1;
boolean neg = false;
if (c == NC) c = getChar();
for (; (c < '0' || c > '9'); c = getChar()) {
if (c == '-') neg = true;
}
long res = 0;
for (; c >= '0' && c <= '9'; c = getChar()) {
res = (res << 3) + (res << 1) + c - '0';
cnt *= 10;
}
return neg ? -res : res;
}
public double nextDouble() {
double cur = nextLong();
return c != '.' ? cur : cur + nextLong() / cnt;
}
public double[] nextDoubles(int N) {
double[] res = new double[N];
for (int i = 0; i < N; i++) {
res[i] = nextDouble();
}
return res;
}
public String next() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c > 32) {
res.append(c);
c = getChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c != '\n') {
res.append(c);
c = getChar();
}
return res.toString();
}
public boolean hasNext() {
if (c > 32)
return true;
while (true) {
c = getChar();
if (c == NC)
return false;
else if (c > 32)
return true;
}
}
}
static void ASSERT(boolean assertion, String message) {
if (!assertion) throw new AssertionError(message);
}
}
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.StringTokenizer;
public class problemD {
static ArrayList<Integer>[] adj;
static boolean found = false;
static int[] D = new int[212345];
private static void solve() throws Exception {
int n = fs.nextInt();
int a = fs.nextInt();
int b = fs.nextInt();
int da = fs.nextInt();
int db = fs.nextInt();
adj = new ArrayList[n+1];
for (int i = 0 ; i <= n ; i ++ ) adj[i] = new ArrayList<Integer>();
for (int i = 0 ; i < n-1; i ++ ) {
int u = fs.nextInt();
int v = fs.nextInt();
adj[u].add(v);
adj[v].add(u);
}
found = false;
dfs(a, 0, 0, da, b);
if (found) {
out.println("Alice");
return;
}
dfs(b,0,0);
int maxD = -1;
int node = -1;
for (int i = 1; i <= n; i ++ ) {
if (D[i] > maxD) {
maxD = D[i];
node = i;
}
}
dfs(node, 0, 0);
maxD = -1;
for (int i = 1; i <= n; i ++ ) {
if (D[i] > maxD) {
maxD = D[i];
}
}
boolean bob = db > da * 2 && maxD > da * 2;
out.println(bob ? "Bob" : "Alice");
}
private static void dfs(int node, int parent, int dist) {
D[node] = dist;
for (int x: adj[node]) {
if (x != parent) {
dfs(x, node, dist+1);
}
}
}
private static void dfs(int node, int parent, int dist, int da, int b) {
if (node == b) { found = true; return; }
for (int x: adj[node]) {
if (x != parent) {
if (dist+1 <= da) {
dfs(x, node, dist + 1, da, b);
}
}
}
}
private static FastScanner fs = new FastScanner();
private static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) throws Exception {
int T = 1;
T = fs.nextInt();
for (int t = 0; t < T; t++) {
solve();
}
out.close();
}
static void debug(Object... O) {
System.err.print("DEBUG ");
System.err.println(Arrays.deepToString(O));
}
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());
}
String nextString() {
return next();
}
}
}
| 0 |
Non-plagiarised
|
624b8db5
|
90f01508
|
//created by Whiplash99
import java.io.*;
import java.util.*;
public class C
{
private static ArrayDeque<Integer>[] edge;
private static HashMap<String,Integer> map;
private static String getHash(int u, int v)
{
if(u>v)
{
int tmp=u;
u=v;
v=tmp;
}
return u+" "+v;
}
private static void DFS(int u, int p, int[] ans, int val)
{
for(int v:edge[u])
{
if(v==p) continue;
ans[map.get(getHash(u,v))]=val;
DFS(v,u,ans,5-val);
val=5-val;
}
}
public static void main(String[] args) throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int i,N;
int T=Integer.parseInt(br.readLine().trim());
StringBuilder sb=new StringBuilder();
while (T-->0)
{
N=Integer.parseInt(br.readLine().trim());
edge=new ArrayDeque[N];
for(i=0;i<N;i++) edge[i]=new ArrayDeque<>();
map=new HashMap<>();
int[] ans=new int[N-1];
int[] deg=new int[N];
for(i=0;i<N-1;i++)
{
String[] s=br.readLine().trim().split(" ");
int u=Integer.parseInt(s[0])-1;
int v=Integer.parseInt(s[1])-1;
edge[u].add(v); edge[v].add(u);
deg[u]++; deg[v]++;
map.put(getHash(u,v),i);
}
for(i=0;i<N;i++) if(deg[i]>2) break;
if(i<N)
{
sb.append(-1).append("\n");
continue;
}
DFS(0,0,ans,2);
for(int x:ans) sb.append(x).append(" ");
sb.append("\n");
}
System.out.println(sb);
}
}
|
// import java.io.DataInputStream;
// import java.io.FileInputStream;
// import java.io.IOException;
import java.io.*;
import java.util.*;
public class one
{
static Scanner sc=new Scanner(System.in);
boolean prime[];
static int prev=-1;
static int dp[][];
public static int[] input(int size){
int arr[]=new int[size];
for(int i=0;i<size;i++)
arr[i]=sc.nextInt();
return arr;
}
public static void main(String[] args) {
//int testcase=1;
int testcase=sc.nextInt();
//System.out.println("HI");
while(testcase-->0){
// int x=sc.nextInt();
// int y=sc.nextInt();
//String str[]=new String[size];
solve();
System.out.println();
}
}
public static void solve(){
HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
int size=sc.nextInt();
int arr[][]=new int[size-1][2];
for(int i=0;i<size-1;i++){
arr[i][0]=sc.nextInt();
arr[i][1]=sc.nextInt();
}
for(int x[]:arr){
map.put(x[0],map.getOrDefault(x[0], 0)+1);
map.put(x[1],map.getOrDefault(x[1], 0)+1);
if(map.get(x[0])>2||map.get(x[1])>2){
System.out.println(-1);
return;
}
}
List<List<Integer>> adj=new ArrayList<>();
for(int i=0;i<=size;i++)
adj.add(new ArrayList<Integer>());
for(int x[]:arr){
adj.get(x[0]).add(x[1]);
adj.get(x[1]).add(x[0]);
}
//System.out.println(adj);
int vist[]=new int[size+1];
HashMap<String,Integer> ans=new HashMap<String,Integer>();
for(int i=1;i<=size;i++){
if(vist[i]==0){
dfs(i,vist,adj,ans,2);
}
}
//System.out.println(ans);
for(int x[]:arr){
//System.out.print(map.get(x[0]));
int a=Math.min(x[0],x[1]);
int b=Math.max(x[0],x[1]);
String s=a+" "+b;
System.out.print(ans.get(s)+" ");
}
// map=new HashMap<Integer,Integer>();
// for(int x[]:arr){
// if(map.containsKey(x[0])){
// int val=13-map.get(x[0]);
// map.put(x[1],val);
// System.out.print(val+" ");
// }else if(map.containsKey(x[1])){
// int val=13-map.get(x[1]);
// map.put(x[0],val);
// System.out.print(val+" ");
// }else{
// System.out.print(2+" ");
// map.put(x[0],2);
// map.put(x[1],2);
// }
// }
}
public static void dfs(int node,int vist[],List<List<Integer>> adj,HashMap<String,Integer> ans,int val){
vist[node]=1;
for(int i:adj.get(node)){
if(vist[i]==1)
continue;
int x=Math.min(i, node);
int y=Math.max(i, node);
ans.put(x+" "+y,val);
dfs(i,vist,adj,ans,5-val);
val=5-val;
}
}
}
| 0 |
Non-plagiarised
|
3d06b643
|
f6ca6fc8
|
import java.io.*;
import java.util.*;
public class ArmChairs {
public static int solution(int n, int[] arr) {
ArrayList<Integer> one = new ArrayList<Integer>();
ArrayList<Integer> zero = new ArrayList<Integer>();
for (int i = 0; i < n; i++) {
if (arr[i] == 1) {
one.add(i);
} else {
zero.add(i);
}
}
int[][] dp = new int[one.size() + 1][zero.size() + 1];
for (int i = 1; i <= one.size(); i++) {
dp[i][i] = dp[i - 1][i - 1] + Math.abs(one.get(i - 1) - zero.get(i - 1));
for (int j = i + 1; j <= zero.size(); j++) {
dp[i][j] = Math.min(dp[i][j - 1], dp[i - 1][j - 1] + Math.abs(one.get(i - 1) - zero.get(j - 1)));
}
}
return dp[one.size()][zero.size()];
}
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out));
int n = Integer.parseInt(br.readLine());
String[] s = br.readLine().split(" ");
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(s[i]);
}
log.write(Integer.toString(solution(n, arr)) + "\n");
log.flush();
}
}
|
import java.util.*;
import java.io.*;
public class D {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n = sc.nextInt();
ArrayList<Integer> o=new ArrayList<Integer>();
ArrayList<Integer> e=new ArrayList<Integer>();
for(int i=1;i<=n;i++){
int x=sc.nextInt();
if(x==1)o.add(i);
else e.add(i);
}
int dp[][]=new int[o.size()+1][e.size()+1];
for(int i=1;i<=o.size();i++){
dp[i][i]=dp[i-1][i-1]+Math.abs(o.get(i-1)-e.get(i-1));
for(int j=i+1;j<=e.size();j++){
dp[i][j]=Math.min(dp[i][j-1],dp[i-1][j-1]+Math.abs(o.get(i-1)-e.get(j-1)));
}
}
System.out.println(dp[o.size()][e.size()]);
}
}
| 1 |
Plagiarised
|
464a03b8
|
f0ede32a
|
import java.util.*;
public class Soltion{
public static void main(String []args){
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-->0){
int n = sc.nextInt();
Integer[] arr = new Integer[n];
for(int i=0;i<n;i++){
arr[i] = sc.nextInt();
}
String s = sc.next();
List<Integer> blue = new ArrayList<>();
List<Integer> red = new ArrayList<>();
for(int i=0;i<s.length();i++){
if(s.charAt(i)=='B'){
blue.add(arr[i]);
}
else{
red.add(arr[i]);
}
}
Collections.sort(blue);
Collections.sort(red);
int p=1,q=n;
boolean flag = true;
for(int i=red.size()-1;i>=0;i--){
if(red.get(i)>q){
flag = false;
break;
}
q--;
}
for(int i=0;i<blue.size();i++){
if(blue.get(i)<p){
flag = false;
break;
}
p++;
}
System.out.println(flag? "Yes" : "No");
}
}
}
|
import java.util.*;
public class Soltion{
public static void main(String []args){
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-->0){
int n = sc.nextInt();
Integer[] arr = new Integer[n];
for(int i=0;i<n;i++){
arr[i] = sc.nextInt();
}
String s = sc.next();
List<Integer> blue = new ArrayList<>();
List<Integer> red = new ArrayList<>();
for(int i=0;i<s.length();i++){
if(s.charAt(i)=='B'){
blue.add(arr[i]);
}
else{
red.add(arr[i]);
}
}
Collections.sort(blue);
Collections.sort(red);
int p=1,q=n;
boolean flag = true;
for(int i=red.size()-1;i>=0;i--){
if(red.get(i)>q){
flag = false;
break;
}
q--;
}
for(int i=0;i<blue.size();i++){
if(blue.get(i)<p){
flag = false;
break;
}
p++;
}
System.out.println(flag? "Yes" : "No");
}
}
}
| 1 |
Plagiarised
|
680ba922
|
90dc2b20
|
import java.util.*;
import java.io.*;
public class Solution
{
static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(
new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
if (cnt != 0) {
break;
}
else {
continue;
}
}
buf[cnt++] = (byte)c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0,
BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
static int parent(int a , int p[])
{
if(a == p[a])
return a;
return p[a] = parent(p[a],p);
}
static void union(int a , int b , int p[] , int size[])
{
a = parent(a,p);
b = parent(b,p);
if(a == b)
return;
if(size[a] < size[b])
{
int temp = a;
a = b;
b = temp;
}
p[b] = a;
size[a] += size[b];
}
static long getSum(int index , long BITree[])
{
long sum = 0; // Iniialize result
// index in BITree[] is 1 more than
// the index in arr[]
// index = index + 1;
// Traverse ancestors of BITree[index]
while(index>0)
{
// Add current element of BITree
// to sum
sum += BITree[index];
// Move index to parent node in
// getSum View
index -= index & (-index);
}
return sum;
}
// Updates a node in Binary Index Tree (BITree)
// at given index in BITree. The given value
// 'val' is added to BITree[i] and all of
// its ancestors in tree.
public static void updateBIT(int n, int index,
long val , long BITree[])
{
// index in BITree[] is 1 more than
// the index in arr[]
// index = index + 1;
// Traverse all ancestors and add 'val'
while(index <= n)
{
// Add 'val' to current node of BIT Tree
BITree[index] += val;
// Update index to that of parent
// in update View
index += index & (-index);
}
}
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static int dp[][];
static int f(int pos , int take , int arr[])
{
if(pos == -1)
{
if(take == 0)
return 0;
return -10000000;
}
if(dp[pos][take] != -1)
return dp[pos][take];
if(pos+1-take == arr[pos])
dp[pos][take] = Math.max(dp[pos][take],1 + f(pos-1,take,arr));
dp[pos][take] = Math.max(dp[pos][take],f(pos-1,take,arr));
if(take > 0)
dp[pos][take] = Math.max(dp[pos][take],f(pos-1,take-1,arr));
return dp[pos][take];
}
public static void main(String []args) throws IOException
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-- > 0)
{
int n = sc.nextInt();
sc.nextLine();
String a = sc.nextLine();
String b = sc.nextLine();
int same = 0 , zo = 0 , oz = 0 , oo = 0 , zz = 0;
for(int i = 0 ; i < n ; i++)
{
if(a.charAt(i) == '0' && b.charAt(i) == '1')
oz++;
else if(a.charAt(i) == '1' && b.charAt(i) == '0')
zo++;
else if(a.charAt(i) == '1' && b.charAt(i) == '1')
oo++;
else
zz++;
}
if(oz == zo || (zz == oo-1))
{
int mx = Integer.MAX_VALUE;
if(oz == zo)
mx = Math.min(mx,2*oz);
if(oo-1 == zz)
mx = Math.min(mx,zz+oo);
System.out.println(mx);
}
else
{
System.out.println(-1);
}
}
}
}
|
import java.util.*;
import java.io.*;
public class C1615{
static FastScanner fs = null;
public static void main(String[] args) {
fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int t = fs.nextInt();
while (t-->0) {
int n = fs.nextInt();
String a = fs.next();
String b = fs.next();
char ch1[] = a.toCharArray();
char ch2[] = b.toCharArray();
int c00 = 0;
int c01 = 0;
int c10 = 0;
int c11 = 0;
for(int i=0;i<n;i++){
if(ch1[i]=='0'){
if(ch2[i]=='0'){
c00+=1;
}
else{
c01+=1;
}
}
else{
if(ch2[i]=='0'){
c10+=1;
}
else{
c11+=1;
}
}
}
int ans = -1;
if((c11-c00)==1 || c10==c01){
int s1 = (int)1e7;
int s2 = (int)1e7;
if((c11-c00)==1){
s1 = c11+c00;
}
if(c10==c01)
s2 = c10+c01;
ans = Math.min(s1,s2);
}
out.println(ans);
}
out.close();
}
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 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());
}
}
}
| 0 |
Non-plagiarised
|
67241a76
|
8a39dbf5
|
import java.util.*;
import java.io.*;
public class CodeForces {
public void run() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int q = Integer.parseInt(br.readLine());
while (q-- > 0){
br.readLine();
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int k = Integer.parseInt(st.nextToken());
int[] a = new int[k];
int[] t = new int[k];
long[] L = new long[n];
long[] R = new long[n];
for (int i = 0; i < n; i++) {
L[i] = Integer.MAX_VALUE;
R[i] = Integer.MAX_VALUE;
}
st = new StringTokenizer(br.readLine());
StringTokenizer st1 = new StringTokenizer(br.readLine());
for (int i = 0; i < k; i++) {
a[i] = Integer.parseInt(st.nextToken());
t[i] = Integer.parseInt(st1.nextToken());
L[a[i] - 1] = t[i];
R[a[i] - 1] = t[i];
}
for (int i = 1; i < n; i++) {
L[i] = Math.min(L[i-1] + 1, L[i]);
}
for (int i = n - 2; i >= 0; i--) {
R[i] = Math.min(R[i], R[i + 1] + 1);
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
long tmp = Math.min(L[i], R[i]);
sb.append(tmp);
sb.append(" ");
}
System.out.println(sb.toString().trim());
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new CodeForces().run();
}
}
|
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 Codeforces {
public static void main(String[] args) throws java.lang.Exception {
/* your code goes here */
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(buf.readLine());
StringBuilder sb = new StringBuilder();
for (int i = 0; i < t; i++) {
String st=buf.readLine();
String st1[]=(buf.readLine()).split(" ");
int n=Integer.parseInt(st1[0]);
int k=Integer.parseInt(st1[1]);
int a[]=new int[k];
int temp[]=new int[k];
long arr[]=new long[n];
String st2[]=(buf.readLine()).split(" ");
String st3[]=(buf.readLine()).split(" ");
for(int j=0;j<k;j++)
{
a[j]=Integer.parseInt(st2[j]);
temp[j]=Integer.parseInt(st3[j]);
}
for(int j=0;j<k;j++)
{
arr[a[j]-1]=temp[j];
}
long min=Integer.MAX_VALUE;
long left[]=new long[n];
long right[]=new long[n];
if(arr[0]==0)
left[0]=min;
else
left[0]=arr[0];
for(int j=1;j<n;j++)
{
if(arr[j]==0)
{
left[j]=left[j-1]+1;
}
else
{
left[j]=Math.min(left[j-1]+1,arr[j]);
}
}
if(arr[n-1]==0)
right[n-1]=min;
else
right[n-1]=arr[n-1];
for(int j=n-2;j>=0;j--)
{
if(arr[j]==0)
{
right[j]=right[j+1]+1;
}
else
{
right[j]=Math.min(right[j+1]+1,arr[j]);
}
}
for(int j=0;j<n;j++)
{
arr[j]=Math.min(left[j],right[j]);
sb.append(arr[j]+" ");
}
sb.append("\n");
}
System.out.println(sb);
}
}
| 0 |
Non-plagiarised
|
1c90c367
|
f0801d53
|
/*
/$$$$$ /$$$$$$ /$$ /$$ /$$$$$$
|__ $$ /$$__ $$ |$$ |$$ /$$__ $$
| $$| $$ \ $$| $$|$$| $$ \ $$
| $$| $$$$$$$$| $$ / $$/| $$$$$$$$
/ $$ | $$| $$__ $$ \ $$ $$/ | $$__ $$
| $$ | $$| $$ | $$ \ $$$/ | $$ | $$
| $$$$$$/| $$ | $$ \ $/ | $$ | $$
\______/ |__/ |__/ \_/ |__/ |__/
/$$$$$$$ /$$$$$$$ /$$$$$$ /$$$$$$ /$$$$$$$ /$$$$$$ /$$ /$$ /$$ /$$ /$$$$$$$$ /$$$$$$$
| $$__ $$| $$__ $$ /$$__ $$ /$$__ $$| $$__ $$ /$$__ $$| $$$ /$$$| $$$ /$$$| $$_____/| $$__ $$
| $$ \ $$| $$ \ $$| $$ \ $$| $$ \__/| $$ \ $$| $$ \ $$| $$$$ /$$$$| $$$$ /$$$$| $$ | $$ \ $$
| $$$$$$$/| $$$$$$$/| $$ | $$| $$ /$$$$| $$$$$$$/| $$$$$$$$| $$ $$/$$ $$| $$ $$/$$ $$| $$$$$ | $$$$$$$/
| $$____/ | $$__ $$| $$ | $$| $$|_ $$| $$__ $$| $$__ $$| $$ $$$| $$| $$ $$$| $$| $$__/ | $$__ $$
| $$ | $$ \ $$| $$ | $$| $$ \ $$| $$ \ $$| $$ | $$| $$\ $ | $$| $$\ $ | $$| $$ | $$ \ $$
| $$ | $$ | $$| $$$$$$/| $$$$$$/| $$ | $$| $$ | $$| $$ \/ | $$| $$ \/ | $$| $$$$$$$$| $$ | $$
|__/ |__/ |__/ \______/ \______/ |__/ |__/|__/ |__/|__/ |__/|__/ |__/|________/|__/ |__/
*/
import java.io.BufferedReader;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.io.*;
public class abc {
static PrintWriter pw;
static long x = 1, y = 1;
/*
* static long inv[]=new long[1000001]; static long dp[]=new long[1000001];
*/
/// MAIN FUNCTION///
public static void main(String[] args) throws Exception {
FastReader sc = new FastReader();
pw = new PrintWriter(System.out);
// use arraylist as it uses the concept of dynamic table(amortized analysis)
// Arrays.stream(array).forEach(a -> Arrays.fill(a, 0));
/* List<Integer> l1 = new ArrayList<Integer>(); */
// Random rand = new Random();
int tst = sc.nextInt();
while(tst-->0) {
int n=sc.nextInt();
int app[]=new int[n];
int h[]=new int[n];
for(int i=0;i<n;i++)
{
app[i]=sc.nextInt();
}
for(int i=0;i<n;i++)
{
h[i]=sc.nextInt();
}
long man = 0;
long last = app[n - 1] - h[n - 1] + 1;
int end = n-1;
for (int i = n-2; i >=0; i--) {
if(app[i]>=last) {
last = Math.min(last,app[i] - h[i] + 1);
}
else {
long s = app[end]-last+1;
man += (s*(s+1))/2;
end = i;
last = app[i] - h[i] + 1;;
}
}
long s = app[end]-last+1;
man += (s*(s+1))/2;
pw.println(man);
}
pw.flush();
}
public static long eculidean_gcd(long a, long b) {
if (a == 0) {
x = 0;
y = 1;
return b;
}
long ans = eculidean_gcd(b % a, a);
long x1 = x;
x = y - (b / a) * x;
y = x1;
return ans;
}
public static int sum(int n) {
int sum = 1;
if (n == 0)
return 0;
while (n != 0) {
sum = sum * n;
n = n - 1;
}
return sum;
}
public static boolean isLsbOne(int n) {
if ((n & 1) != 0)
return true;
return false;
}
public static pair helper(int arr[], int start, int end, int k, pair dp[][]) {
if (start >= end) {
if (start == end)
return (new pair(arr[start], 0));
else
return (new pair(0, 0));
}
if (dp[start][end].x != -1 && dp[start][end].y != -1) {
return dp[start][end];
}
pair ans = new pair(0, Integer.MAX_VALUE);
for (int i = start; i < end; i++) {
pair x1 = helper(arr, start, i, k, dp);
pair x2 = helper(arr, i + 1, end, k, dp);
long tip = k * (x1.x + x2.x) + x1.y + x2.y;
if (tip < ans.y)
ans = new pair(x1.x + x2.x, tip);
}
return dp[start][end] = ans;
}
public static void debugger() {
Random rand = new Random();
int tst = (int) (Math.abs(rand.nextInt()) % 2 + 1);
pw.println(tst);
while (tst-- > 0) {
int n = (int) (Math.abs(rand.nextInt()) % 5 + 1);
pw.println(n);
for (int i = 0; i < n; i++) {
pw.print((int) (Math.abs(rand.nextInt()) % 6 + 1) + " ");
}
pw.println();
}
}
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 int LowerBound(long a[], long 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 void recursion(int n) {
if (n == 1) {
pw.print(n + " ");
return;
}
// pw.print(n+" "); gives us n to 1
recursion(n - 1);
// pw.print(n+" "); gives us 1 to n
}
// ch.charAt(i)+"" converts into a char sequence
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;
}
/* CREATED BY ME */
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;
}
}
public static long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
public static boolean isPrime(long n) {
if (n == 2)
return true;
long i = 2;
while (i * i <= n) {
if (n % i == 0)
return false;
i++;
}
return true;
}
static int ceil(int x, int y) {
return (x % y == 0 ? x / y : (x / y + 1));
}
static long ceil(long x, long y) {
return (x % y == 0 ? x / y : (x / y + 1));
}
static double max(double x, double y) {
return Math.max(x, y);
}
static int min(int x, int y) {
return Math.min(x, y);
}
static int abs(int x) {
return Math.abs(x);
}
static long abs(long x) {
return Math.abs(x);
}
static int log2(int N) {
int result = (int) (Math.log(N) / Math.log(2));
return result;
}
static long max(long x, long y) {
return Math.max(x, y);
}
static long min(long x, long y) {
return Math.min(x, y);
}
public static class pair {
long x;
long y;
public pair(long a, long b) {
x = a;
y = b;
}
}
public static class Comp implements Comparator<pair> {
public int compare(pair a, pair b) {
long ans = a.x - b.x;
if (ans > 0)
return 1;
if (ans < 0)
return -1;
return 0;
}
}
// modular exponentiation
public static long fastExpo(long a, int n, int mod) {
if (n == 0)
return 1;
else {
if ((n & 1) == 1) {
long x = fastExpo(a, n / 2, mod);
return (((a * x) % mod) * x) % mod;
} else {
long x = fastExpo(a, n / 2, mod);
return (((x % mod) * (x % mod)) % mod) % mod;
}
}
}
public static long modInverse(long n, int p) {
return fastExpo(n, p - 2, p);
}
/*
* public static void extract(ArrayList<Integer> ar, int k, int d) { int c = 0;
* for (int i = 1; i < k; i++) { int x = 0; boolean dm = false; while (x > 0) {
* long dig = x % 10; x = x / 10; if (dig == d) { dm = true; break; } } if (dm)
* ar.add(i); } }
*/
public static int[] prefixfuntion(String s) {
int n = s.length();
int z[] = new int[n];
for (int i = 1; i < n; i++) {
int j = z[i - 1];
while (j > 0 && s.charAt(i) != s.charAt(j))
j = z[j - 1];
if (s.charAt(i) == s.charAt(j))
j++;
z[i] = j;
}
return z;
}
// counts the set(1) bit of a number
public static long countSetBitsUtil(long x) {
if (x <= 0)
return 0;
return (x % 2 == 0 ? 0 : 1) + countSetBitsUtil(x / 2);
}
//tells whether a particular index has which bit of a number
public static int getIthBitsUtil(int x, int y) {
return (x & (1 << y)) != 0 ? 1 : 0;
}
public static void swaper(long x, long y) {
x = x ^ y;
y = y ^ x;
x = x ^ y;
}
public static double decimalPlaces(double sum) {
DecimalFormat df = new DecimalFormat("#.00");
String angleFormated = df.format(sum);
double fin = Double.parseDouble(angleFormated);
return fin;
}
//use collections.swap for swapping
static boolean isSubSequence(String str1, String str2, int m, int n) {
int j = 0;
for (int i = 0; i < n && j < m; i++)
if (str1.charAt(j) == str2.charAt(i))
j++;
return (j == m);
}
static long sum(long n) {
long s2 = 0, max = -1, min = 10;
while (n > 0) {
s2 = (n % 10);
min = min(s2, min);
max = max(s2, max);
n = n / 10;
}
return max * min;
}
static long pow(long base, long power) {
if (power == 0) {
return 1;
}
long result = pow(base, power / 2);
if (power % 2 == 1) {
return result * result * base;
}
return result * result;
}
// return the hash value of a string
static long compute_hash(String s) {
long val = 0;
long p = 31;
long mod = (long) (1000000007);
long pow = 1;
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
val = (val + (int) (ch - 'a' + 1) * pow) % mod;
pow = (pow * p) % mod;
}
return val;
}
}
|
import java.util.*;
import java.io.*;
public class hmm {
static Scanner sc = new Scanner(System.in);
static PrintWriter pw = new PrintWriter(System.out);
public static void main(String[] args) throws Exception {
int t =sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
int []k = sc.nextIntArray(n);
int h[]=sc.nextIntArray(n);
long mana = 0;
pair cur = new pair(k[n-1]-h[n-1]+1,k[n-1]);
for(int i=n-1;i>=0;i--) {
int s = k[i];
int start = s-h[i]+1;
if(s>=cur.x) {
cur.x = Math.min(start, cur.x);
}
else {
long x = cur.y - cur.x +1;
mana += x*(x+1)/2;
cur.x = start;
cur.y = s;
}
}
long x = cur.y - cur.x +1;
mana += x*(x+1)/2;
pw.println(mana);
}
pw.close();
}
// -------------- stuff ------------------------------
static class pair {
int x ;
int y;
public pair(int n,int c) {
x= n;
y = c;
}
}
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 int[] nextIntArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
}
}
| 1 |
Plagiarised
|
2b2d3b84
|
aaccc000
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;
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
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args)
{
FastReader in = new FastReader();
int t=in.nextInt();
while(t-->0)
{
int n=in.nextInt();
int k=in.nextInt();
int a[]=new int[k];
int ans[]=new int[n];
int tem[]=new int[k];
for(int i=0;i<k;i++)
a[i]=in.nextInt();
for(int i=0;i<k;i++)
tem[i]=in.nextInt();
long c[]=new long[n];
long l[]=new long[n];
long r[]=new long[n];
Arrays.fill(c,Integer.MAX_VALUE);
Arrays.fill(l, Integer.MAX_VALUE);
Arrays.fill(r,Integer.MAX_VALUE);
long p=Integer.MAX_VALUE;
for(int i=0;i<k;i++)
c[a[i]-1]=tem[i];
for(int i=0;i<n;i++)
{
p=Math.min(p+1,c[i]);
l[i]=p;
}
p=Integer.MAX_VALUE;
for(int i=n-1;i>=0;i--)
{
p=Math.min(p+1,c[i]);
r[i]=p;
}
for(int i=0;i<n;i++)
System.out.print(Math.min(l[i],r[i])+" ");
System.out.println();
}
}
}
|
import java.io.*;
import java.util.*;
public class GFG {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-- > 0){
int n = sc.nextInt();
int k = sc.nextInt();
int[] a = new int[k];
int[] temp = new int[k];
for(int i=0;i<k;i++){
a[i] = sc.nextInt();
}
for(int i=0;i<k;i++){
temp[i] = sc.nextInt();
}
long[] c = new long[n];
Arrays.fill(c,Integer.MAX_VALUE);
for(int i=0;i<k;i++){
c[a[i]-1] = temp[i];
}
long p = Integer.MAX_VALUE;
long[] left = new long[n];
for(int i=0;i<n;i++){
p = (p+1<c[i])?p+1:c[i];
left[i] = p;
}
p = Integer.MAX_VALUE;
long[] right = new long[n];
for(int i=n-1;i>=0;i--){
p = (p+1<c[i])?p+1:c[i];
right[i] = p;
}
for(int i=0;i<n;i++){
long kl = (left[i]>right[i])?right[i]:left[i];
System.out.print(kl+" ");
}
System.out.println();
}
}
}
| 1 |
Plagiarised
|
487c9f62
|
54488276
|
import java.io.*;
import java.util.*;
public class C {
public static void main(String[] args) {
scan = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out));
int t = scan.nextInt();
while (t-->0){
solve();
}
out.close();
}
static void solve() {
int n = scan.nextInt();
int[][] words = new int[n][6];
for (int i = 0; i < n; i++) {
String input = scan.next();
words[i][0] = input.length();
for (int j = 0; j < input.length(); j++) {
words[i][input.charAt(j)-96]++;
}
for (int j = 1; j <= 5; j++) {
words[i][j] = words[i][0] - 2*words[i][j];
}
}
int maxCounter = 0;
for (int i = 1; i <= 5; i++) {
int[] arr = new int[n];
for (int j = 0; j < n; j++) {
arr[j] = words[j][i];
}
shuffleArray(arr);
Arrays.sort(arr);
int sum = 0;
int counter = 0;
while (counter < n && sum + arr[counter] < 0){
sum += arr[counter];
counter++;
}
maxCounter = Math.max(maxCounter, counter);
}
out.println(maxCounter);
}
private static void shuffleArray(int[] array)
{
int index, temp;
Random random = new Random();
for (int i = array.length - 1; i > 0; i--)
{
index = random.nextInt(i + 1);
temp = array[index];
array[index] = array[i];
array[i] = temp;
}
}
public static MyScanner scan;
public static PrintWriter out;
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;
}
}
}
|
import java.io.*;
import java.util.*;
public class C {
static int n;
public static void main (String[] args) throws IOException {
Kattio io = new Kattio();
int t = io.nextInt();
for (int ii=0; ii<t; ii++) {
n = io.nextInt();
String[] arr = new String[n];
for (int i=0; i<n; i++) {
String str = io.next();
arr[i] = str;
}
char[] chars = new char[]{'a','b','c','d','e'};
int ans = -1;
for (int i=0; i<5; i++) {
ans = Math.max(ans, solve(arr, chars[i]));
}
System.out.println(ans);
}
}
static int solve(String[] arr, char c) {
//System.out.println("Comparing based on " + c);
Arrays.sort(arr, new Comp(c));
int good = 0;
int total = 0;
int ret = 0;
for (int i=0; i<n; i++) {
//System.out.println(good + " " + total);
for (int j=0; j<arr[i].length(); j++) {
if (arr[i].charAt(j) == c) good++;
}
total += arr[i].length();
if (2 * good > total) {
ret++;
} else {
return ret;
}
}
return ret;
}
static class Comp implements Comparator<String> {
char c;
public Comp (char c) {
this.c = c;
}
public int compare(String a, String b) {
double cnt1 = 0;
double cnt2 = 0;
for (int i=0; i<a.length(); i++) {
if (a.charAt(i) == c) {
cnt1++;
}
}
for (int i=0; i<b.length(); i++) {
if (b.charAt(i) == c) {
cnt2++;
}
}
//higher ratio is better
return -Double.compare(cnt1 - (a.length() - cnt1), cnt2 - (b.length() - cnt2));
}
}
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()); }
}
}
| 0 |
Non-plagiarised
|
0b04b41e
|
4da08761
|
import java.io.BufferedReader;
import java.io.*;
import java.util.*;
public class josph {
static BufferedReader br;
static long mod = 1000000000 + 7;
static HashSet<Integer> p = new HashSet<>();
static boolean debug =true;
// Arrays.sort(time , (a1,a2) -> (a1[0]-a2[0])); 2d array sort lamda
public static void main(String[] args) throws Exception {
br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pr = new PrintWriter(System.out);
int tc = 1;
tc= cinI();
while(tc-->0){
int n =cinI();
String[] a= new String[n];
int[][] f =new int[10][n];
for(int i=0;i<n;i++){
a[i]=cin();
char[] x = a[i].toCharArray();
for(char c:x){
int index = c-'a';
f[index][i]+=1;
}
for(int j=0;j<10;j++){
int rem =x.length-f[j][i];
f[j][i]-=rem;
}
}
int max=0;
for(int j=0;j<10;j++){
Arrays.sort(f[j]);
int cnt=0;
int sum=0;
for(int i=n-1;i>=0;i--){
sum+=f[j][i];
if(sum>0){
cnt+=1;
}
else{
break;
}
}
max=max(max,cnt);
}
System.out.println(max);
}
}
public static <E> void print(String var ,E e){
if(debug==true){
System.out.println(var +" "+e);
}
}
private static long[] sort(long[] e){
ArrayList<Long> x=new ArrayList<>();
for(long c:e){
x.add(c);
}
Collections.sort(x);
long[] y = new long[e.length];
for(int i=0;i<x.size();i++){
y[i]=x.get(i);
}
return y;
}
public static void printDp(long[][] dp) {
int n = dp.length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < dp[0].length; j++) {
System.out.print(dp[i][j] + " ");
}
System.out.println();
}
}
private static long gcd(long a, long b) {
if (a == 0)
return b;
if (b == 0)
return a;
// base case
if (a == b)
return a;
// a is greater
if (a > b)
return gcd(a % b, b);
return gcd(a, b % a);
}
public static long min(long a, long b) {
return Math.min(a, b);
}
public static int min(int a, int b) {
return Math.min(a, b);
}
public static void sieve() {
int[] pf = new int[100000000 + 1];
//0 prime //1 not prime
pf[0] = 1;
pf[1] = 1;
for (int j = 2; j <= 10000; j++) {
if (pf[j] == 0) {
p.add(j);
for (int k = j * j; k < pf.length; k += j) {
pf[k] = 1;
}
}
}
}
public static int[] readArray(int n, int x, int z) throws Exception {
int[] arr = new int[n];
String[] ar = cinA();
for (int i = x; i < n + x; i++) {
arr[i] = getI(ar[i - x]);
}
return arr;
}
public static long[] readArray(int n, int x) throws Exception {
long[] arr = new long[n];
String[] ar = cinA();
for (int i = x; i < n + x; i++) {
arr[i] = getL(ar[i - x]);
}
return arr;
}
public static void arrinit(String[] a, long[] b) throws Exception {
for (int i = 0; i < a.length; i++) {
b[i] = Long.parseLong(a[i]);
}
}
public static HashSet<Integer>[] Graph(int n, int edge, int directed) throws Exception {
HashSet<Integer>[] tree = new HashSet[n];
for (int j = 0; j < edge; j++) {
String[] uv = cinA();
int u = getI(uv[0]);
int v = getI(uv[1]);
if (directed == 0) {
tree[v].add(u);
}
tree[u].add(v);
}
return tree;
}
public static void arrinit(String[] a, int[] b) throws Exception {
for (int i = 0; i < a.length; i++) {
b[i] = Integer.parseInt(a[i]);
}
}
static double findRoots(int a, int b, int c) {
// If a is 0, then equation is not
//quadratic, but linear
int d = b * b - 4 * a * c;
double sqrt_val = Math.sqrt(Math.abs(d));
// System.out.println("Roots are real and different \n");
return Math.max((double) (-b + sqrt_val) / (2 * a),
(double) (-b - sqrt_val) / (2 * a));
}
public static String cin() throws Exception {
return br.readLine();
}
public static String[] cinA() throws Exception {
return br.readLine().split(" ");
}
public static String[] cinA(int x) throws Exception {
return br.readLine().split("");
}
public static String ToString(Long x) {
return Long.toBinaryString(x);
}
public static void cout(String s) {
System.out.println(s);
}
public static Integer cinI() throws Exception {
return Integer.parseInt(br.readLine());
}
public static int getI(String s) throws Exception {
return Integer.parseInt(s);
}
public static long getL(String s) throws Exception {
return Long.parseLong(s);
}
public static long max(long a, long b) {
return Math.max(a, b);
}
public static int max(int a, int b) {
return Math.max(a, b);
}
public static void coutI(int x) {
System.out.println(String.valueOf(x));
}
public static void coutI(long x) {
System.out.println(String.valueOf(x));
}
public static Long cinL() throws Exception {
return Long.parseLong(br.readLine());
}
public static void arrInit(String[] arr, int[] arr1) throws Exception {
for (int i = 0; i < arr.length; i++) {
arr1[i] = getI(arr[i]);
}
}
}
|
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Solution {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Main solver = new Main();
boolean multipleTC = true;
int testCount = multipleTC ? Integer.parseInt(in.next()) : 1;
for (int i = 1; i <= testCount; i++)
solver.solve(in, out, i);
out.close();
}
static class Main {
PrintWriter out;
InputReader in;
public void solve(InputReader in, PrintWriter out, int test) {
this.out = out;
this.in = in;
int n = ni();
String[] arr = new String[n];
int[][] freq = new int[n][5];
int[][] rem = new int[n][5];
for(int i = 0; i < n; i++){
arr[i] = n();
for(int j = 0; j < arr[i].length(); j++)
freq[i][arr[i].charAt(j) - 'a']++;
for(int j = 0; j < 5; j++)
rem[i][j] = arr[i].length() - freq[i][j];
}
int ans = 0;
for(int i = 0; i < 5; i++){
int[] vals = new int[n];
for(int j = 0; j < n; j++)
vals[j] = freq[j][i] - rem[j][i];
Arrays.sort(vals);
int sum = 0, x = 0;
for(int j = n - 1; j >= 0; j--){
if(sum + vals[j] > 0){
x++;
sum += vals[j];
} else {
break;
}
}
if(x > ans) {
ans = x;
}
}
pn(ans);
}
int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
String n(){
return in.next();
}
int ni() {
return in.nextInt();
}
long nl() {
return in.nextLong();
}
void pn(long zx) {
out.println(zx);
}
void pn(String sz) {
out.println(sz);
}
void pn(double dx){
out.println(dx);
}
class Tuple {
long x;
long y;
Tuple(long a, long b) {
x = a;
y = b;
}
}
}
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 long nextLong() {
return Long.parseLong(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;
}
}
}
| 0 |
Non-plagiarised
|
28820c82
|
8637bb90
|
import java.util.*;
import java.io.*;
import java.math.*;
import java.lang.*;
public class MinimumGridPath {
static int mod = 1000000007;
public 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 void main(String[] args) throws Exception {
Reader scn = new Reader();
PrintWriter pw = new PrintWriter(System.out);
int t = scn.nextInt();
outer : while(t-->0){
int n = scn.nextInt();
long[] arr = new long[n];
for(int i=0; i<n; i++){
arr[i] = scn.nextInt();
}
long ans = Long.MAX_VALUE;
int k = 2;
long oddSum = arr[0];
long evenSum = 0;
long oddMin = arr[0];
long evenMin = Long.MAX_VALUE;
long oddCount = 1;
long evenCount = 0;
while(k <= n){
if(k % 2 == 1){
oddSum += arr[k-1];
oddCount++;
oddMin = Math.min(oddMin, arr[k-1]);
}else{
evenSum += arr[k-1];
evenCount++;
evenMin = Math.min(evenMin, arr[k-1]);
}
long sum = oddSum - oddMin + oddMin*(n - oddCount + 1) + evenSum - evenMin + evenMin*(n - evenCount + 1);
ans = Math.min(ans, sum);
k++;
}
pw.println(ans);
}
pw.close();
}
public static class Pair{
long x;
long y;
Pair(long x, long y){
this.x = x;
this.y = y;
}
}
private static void sort(int[] arr) {
List<Integer> list = new ArrayList<>();
for (int i=0; i<arr.length; i++){
list.add(arr[i]);
}
Collections.sort(list); // collections.sort uses nlogn in backend
for (int i = 0; i < arr.length; i++){
arr[i] = list.get(i);
}
}
private static void sort(long[] arr) {
List<Long> list = new ArrayList<>();
for(int i=0; i<arr.length; i++){
list.add(arr[i]);
}
Collections.sort(list); // collections.sort uses nlogn in backend
for (int i = 0; i < arr.length; i++){
arr[i] = list.get(i);
}
}
private static int lowerBound(int[] arr, int x){
int n = arr.length, si = 0, ei = n - 1;
while(si <= ei){
int mid = si + (ei - si)/2;
if(arr[mid] == x){
if(mid-1 >= 0 && arr[mid-1] == arr[mid]){
ei = mid-1;
}else{
return mid;
}
}else if(arr[mid] > x){
ei = mid - 1;
}else{
si = mid+1;
}
}
return si;
}
private static int upperBound(int[] arr, int x){
int n = arr.length, si = 0, ei = n - 1;
while(si <= ei){
int mid = si + (ei - si)/2;
if(arr[mid] == x){
if(mid+1 < n && arr[mid+1] == arr[mid]){
si = mid+1;
}else{
return mid + 1;
}
}else if(arr[mid] > x){
ei = mid - 1;
}else{
si = mid+1;
}
}
return si;
}
private static int upperBound(ArrayList<Integer> list, int x){
int n = list.size(), si = 0, ei = n - 1;
while(si <= ei){
int mid = si + (ei - si)/2;
if(list.get(mid) == x){
if(mid+1 < n && list.get(mid+1) == list.get(mid)){
si = mid+1;
}else{
return mid + 1;
}
}else if(list.get(mid) > x){
ei = mid - 1;
}else{
si = mid+1;
}
}
return si;
}
// (x^y)%p in O(logy)
private static long power(long x, long y){
long res = 1;
x = x % mod;
while(y > 0){
if ((y & 1) == 1){
res = (res * x) % mod;
}
y = y >> 1;
x = (x * x) % mod;
}
return res;
}
public static boolean nextPermutation(int[] arr) {
if(arr == null || arr.length <= 1){
return false;
}
int last = arr.length-2;
while(last >= 0){
if(arr[last] < arr[last+1]){
break;
}
last--;
}
if (last < 0){
return false;
}
if(last >= 0){
int nextGreater = arr.length-1;
for(int i=arr.length-1; i>last; i--){
if(arr[i] > arr[last]){
nextGreater = i;
break;
}
}
swap(arr, last, nextGreater);
}
reverse(arr, last+1, arr.length-1);
return true;
}
private static void swap(int[] arr, int i, int j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
private static void reverse(int[] arr, int i, int j){
while(i < j){
swap(arr, i++, j--);
}
}
// TC- O(logmax(a,b))
private static int gcd(int a, int b) {
if(a == 0){
return b;
}
return gcd(b%a, a);
}
private static long gcd(long a, long b) {
if(a == 0L){
return b;
}
return gcd(b%a, a);
}
private static long lcm(long a, long b) {
return a / gcd(a, b) * b;
}
// TC- O(logmax(a,b))
private static int lcm(int a, int b) {
return a / gcd(a, b) * b;
}
private static long inv(long x){
return power(x, mod - 2);
}
private static long summation(long n){
return (n * (n + 1L)) >> 1;
}
}
|
import java.util.*;
import java.awt.Point;
import java.io.*;
import java.math.BigInteger;
public class Solutions {
static int MAX=Integer.MAX_VALUE;
static int MIN=Integer.MIN_VALUE;
//static ArrayList<ArrayList<Integer>>list=new ArrayList<ArrayList<Integer>>();
static FastScanner scr=new FastScanner();
static PrintStream out=new PrintStream(System.out);
public static void main(String []args) {
int T=scr.nextInt();
t:for(int tt=0;tt<T;tt++) {
int n=scr.nextInt();
int []a=scr.readArray(n);
long min[]=new long[2];
long sum[]=new long[2];
sum [0]=a[0];
sum [1]=0;
min[0]=a[0];
min[1]=MAX;
long ans=Long.MAX_VALUE;
for(int i=1;i<n;i++) {
min[i%2]=Math.min(min[i%2],a[i]);
sum[i%2]+=a[i];
int odd=(i+2)/2;
int even=(i+1)/2;
ans=Math.min(ans,sum[0]+((n-odd)*min[0])+sum[1]+((n-even)*min[1]));
}
out.println(ans);
}
}
static long modPow(long base,long exp,long mod) {
if(exp==0) {
return 1;
}
if(exp%2==0) {
long res=(modPow(base,exp/2,mod));
return (res*res)%mod;
}
return (base*modPow(base,exp-1,mod))%mod;
}
static long gcd(long a,long b) {
if(b==0) {
return a;
}
return gcd(b,a%b);
}
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[] sort(int a[]) {
Arrays.sort(a);
return a;
}
int []reverse(int a[]){
int b[]=new int[a.length];
int index=0;
for(int i=a.length-1;i>=0;i--) {
b[index]=a[i];
}
return b;
}
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[] 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());
}
}
}
class triplet{
int x;
int y;
int z;
triplet(int fisrt,int second,int third){
this.x=fisrt;
this.y=second;
this.z=third;
}
}
class pair{
int x=0;
int y=0;
pair(int first,int second){
this.x=first;
this.y=second;
}
}
| 0 |
Non-plagiarised
|
11c2ab99
|
e6a6e318
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
FastScanner fs=new FastScanner();
int T=fs.nextInt();
PrintWriter out=new PrintWriter(System.out);
for (int tt=0; tt<T; tt++) {
int n=fs.nextInt(), k=fs.nextInt();
int[] positions=fs.readArray(k), temps=fs.readArray(k);
int[] forced=new int[n];
Arrays.fill(forced, Integer.MAX_VALUE/2);
for (int i=0; i<k; i++) forced[positions[i]-1]=temps[i];
for (int i=1; i<n; i++)
forced[i]=Math.min(forced[i], forced[i-1]+1);
for (int i=n-2; i>=0; i--)
forced[i]=Math.min(forced[i], forced[i+1]+1);
for (int i=0; i<n; i++) out.print(forced[i]+" ");
out.println();
}
out.close();
}
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 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());
}
}
}
|
//package codeforces;
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class solution {
public static void main(String args[]) throws java.lang.Exception{
FastScanner s=new FastScanner();
PrintWriter out=new PrintWriter(System.out);
int t=s.nextInt();
for(int tt=0;tt<t;tt++) {
int n=s.nextInt(), k=s.nextInt();
int[] a=s.readArray(k), temp=s.readArray(k);
long[] ans=new long[n];
Arrays.fill(ans, Integer.MAX_VALUE);
for (int i=0; i<k; i++) {
ans[a[i]-1]=temp[i];
}
for (int i=1; i<n; i++) {
ans[i]=Math.min(ans[i],ans[i-1]+1);
}
for (int i=n-2; i>=0; i--) {
ans[i]=Math.min(ans[i],ans[i+1]+1);
}
for (int i=0; i<n; i++) {
out.print(ans[i]+" ");
}
out.println();
}
out.close();
}
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 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 int gcd(int a, int b){
if (b == 0)
return a;
return gcd(b, a % b);
}
static void sortcol(int a[][],int c) {
Arrays.sort(a, (x, y) -> {
if(x[c]>y[c]) {
return 1;
}else {
return -1;
}
});
}
public static void printb(boolean ans) {
if(ans) {
System.out.println("Yes");
}else {
System.out.println("No");
}
}
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();
}
double nextDouble() {
return Double.parseDouble(next());
}
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());
}
}
static class Pair implements Comparable<Pair>{
int a , b;
Pair(int x , int y){
a=x;
b=y;
}
public int compareTo(Pair o) {
return a != o.a ? a - o.a : b - o.b;
}
}
}
| 1 |
Plagiarised
|
584b0e9e
|
c9159d9c
|
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.SortedSet;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
public class D_Round_753_Div3 {
public static int MOD = 1000000007;
static int[][] dp;
public static void main(String[] args) throws FileNotFoundException {
// PrintWriter out = new PrintWriter(new FileOutputStream(new File(
// "output.txt")));
PrintWriter out = new PrintWriter(System.out);
Scanner in = new Scanner();
int T = in.nextInt();
for (int z = 0; z < T; z++) {
int n = in.nextInt();
int[] data = new int[n];
for (int i = 0; i < n; i++) {
data[i] = in.nextInt();
}
String line = in.next();
ArrayList<Integer> blue = new ArrayList<>();
ArrayList<Integer> red = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (line.charAt(i) == 'B') {
blue.add(data[i]);
} else {
red.add(data[i]);
}
}
Collections.sort(blue);
Collections.sort(red);
int st = 1;
boolean ok = true;
for (int i : blue) {
if (i < st) {
ok = false;
break;
}
st++;
}
if (ok) {
for (int i : red) {
if (i > st) {
ok = false;
break;
}
st++;
}
}
out.println(ok ? "Yes" : "No");
}
out.close();
}
static int find(int v, int[] u) {
if (v == u[v]) {
return v;
}
return u[v] = find(u[v], u);
}
static int abs(int a) {
return a < 0 ? -a : a;
}
public static int[] KMP(String val) {
int i = 0;
int j = -1;
int[] result = new int[val.length() + 1];
result[0] = -1;
while (i < val.length()) {
while (j >= 0 && val.charAt(j) != val.charAt(i)) {
j = result[j];
}
j++;
i++;
result[i] = j;
}
return result;
}
public static boolean nextPer(int[] data) {
int i = data.length - 1;
while (i > 0 && data[i] < data[i - 1]) {
i--;
}
if (i == 0) {
return false;
}
int j = data.length - 1;
while (data[j] < data[i - 1]) {
j--;
}
int temp = data[i - 1];
data[i - 1] = data[j];
data[j] = temp;
Arrays.sort(data, i, data.length);
return true;
}
public static int digit(long n) {
int result = 0;
while (n > 0) {
n /= 10;
result++;
}
return result;
}
public static double dist(long a, long b, long x, long y) {
double val = (b - a) * (b - a) + (x - y) * (x - y);
val = Math.sqrt(val);
double other = x * x + a * a;
other = Math.sqrt(other);
return val + other;
}
public static class Point {
int x;
int y;
public Point(int start, int end) {
this.x = start;
this.y = end;
}
public String toString() {
return x + " " + y;
}
}
public static class FT {
long[] data;
FT(int n) {
data = new long[n];
}
public void update(int index, long value) {
while (index < data.length) {
data[index] += value;
data[index] %= MOD;
index += (index & (-index));
}
}
public long get(int index) {
long result = 0;
while (index > 0) {
result += data[index];
result %= MOD;
index -= (index & (-index));
}
return result;
}
}
public static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
public static long pow(long a, int b) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long val = pow(a, b / 2);
if (b % 2 == 0) {
return (val * val);
} else {
return (val * ((val * a)));
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() throws FileNotFoundException {
// System.setOut(new PrintStream(new BufferedOutputStream(System.out), true));
br = new BufferedReader(new InputStreamReader(System.in));
//br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt"))));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
throw new RuntimeException();
}
}
return st.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
st = null;
try {
return br.readLine();
} catch (Exception e) {
throw new RuntimeException();
}
}
public boolean endLine() {
try {
String next = br.readLine();
while (next != null && next.trim().isEmpty()) {
next = br.readLine();
}
if (next == null) {
return true;
}
st = new StringTokenizer(next);
return st.hasMoreTokens();
} catch (Exception e) {
throw new RuntimeException();
}
}
}
}
|
import java.util.*;
public class SolutionB {
public static long gcd(long a, long b){
if(b==0){
return a;
}
return gcd(b, a%b);
}
public static long gcdSum(long b){
long a = 0;
long temp = b;
while(temp!=0){
a = a + temp%10;
temp = temp/10;
}
return gcd(a,b);
}
public static class Pair{
Long a;
Long b;
public Pair(Long a, Long b) {
this.a = a;
this.b = b;
}
}
public static long factorial (long n){
if(n==0)
return 1;
else if(n==1)
return n;
return n * factorial(n-1);
}
public static long lcm (long n){
if(n<3)
return n;
return lcmForBig(n,n-1);
}
private static long lcmForBig(long n, long l) {
if(l==1)
return n;
n = (n * l) / gcd(n, l);
return lcmForBig(n, l-1);
}
public static void main(String[] args){
Scanner s = new Scanner(System.in);
int t = s.nextInt();
for(int i =0;i<t;i++) {
int n = s.nextInt();
int arr [] = new int[n];
ArrayList<Integer> blue = new ArrayList<>();
ArrayList<Integer> red = new ArrayList<>();
for(int j=0;j<n;j++){
int num = s.nextInt();
arr[j]=num;
}
String color = s.next();
for(int j=0;j<n;j++){
if(color.charAt(j)=='B'){
blue.add(arr[j]);
}
else{
red.add(arr[j]);
}
}
Collections.sort(blue);
String ans = "YES";
int counter = 0;
for(int j=0;j<blue.size();j++){
int current = blue.get(j);
if (current<1){
ans="NO";
break;
}
if(current>counter){
counter++;
}
else{
ans="NO";
break;
}
}
if(ans=="NO"){
System.out.println(ans);
}
else{
int tempCounter = n+1;
Collections.sort(red);
for(int j=red.size()-1;j>=0;j--){
int current = red.get(j);
if(current>=tempCounter){
ans="NO";
break;
}
else{
tempCounter--;
}
}
if(tempCounter-counter!=1)
System.out.println("NO");
else
System.out.println(ans);
}
}
return;
}
}
| 0 |
Non-plagiarised
|
3e1442a3
|
d0e27497
|
import java.util.*;
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
// long mod = 1_000_000_007L;
// long mod = 998_244_353L;
int t = sc.nextInt();
for ( int zzz=0; zzz<t; zzz++ ) {
int n = sc.nextInt();
HashMap<Integer, HashSet<Integer>> adj = new HashMap<>();
HashMap<HashSet<Integer>, Integer> inv = new HashMap<>();
boolean f = false;
for ( int i=0; i<n-1; i++ ) {
int u = sc.nextInt();
int v = sc.nextInt();
if ( adj.containsKey(u) ) {
HashSet<Integer> s = adj.get(u);
if ( s.size()>1 ) f = true;
s.add(v);
adj.put(u, s);
} else {
HashSet<Integer> s = new HashSet<>();
s.add(v);
adj.put(u, s);
}
if ( adj.containsKey(v) ) {
HashSet<Integer> s = adj.get(v);
if ( s.size()>1 ) f = true;
s.add(u);
adj.put(v, s);
} else {
HashSet<Integer> s = new HashSet<>();
s.add(u);
adj.put(v, s);
}
HashSet<Integer> si = new HashSet<>();
si.add(u);
si.add(v);
inv.put(si, i);
}
if ( f ) {
System.out.println(-1);
continue;
}
String[] ans = new String[n-1];
boolean g = false;
ArrayDeque<Integer> q = new ArrayDeque<>();
q.addLast(1);
boolean[] seen = new boolean[n+1];
while ( q.size()>0 ) {
int v = q.removeLast();
seen[v] = true;
HashSet<Integer> s = adj.get(v);
for ( int e : s ) {
if ( seen[e] ) continue;
HashSet<Integer> st = new HashSet<>();
st.add(v);
st.add(e);
int pos = inv.get(st);
if ( g ) {
ans[pos] = "3";
} else {
ans[pos] = "2";
}
g = !g;
q.addLast(e);
break;
}
}
g = true;
q.addLast(1);
while ( q.size()>0 ) {
int v = q.removeLast();
seen[v] = true;
HashSet<Integer> s = adj.get(v);
for ( int e : s ) {
if ( seen[e] ) continue;
HashSet<Integer> st = new HashSet<>();
st.add(v);
st.add(e);
int pos = inv.get(st);
if ( g ) {
ans[pos] = "3";
} else {
ans[pos] = "2";
}
g = !g;
q.addLast(e);
break;
}
}
System.out.println(String.join(" ", ans));
}
}
}
|
import java.util.*;
import java.io.*;
public class Main {
static FastScanner sc = new FastScanner(System.in);
static PrintWriter pw = new PrintWriter(System.out);
static StringBuilder sb = new StringBuilder();
static long mod = (long) 1e9 + 7;
public static void main(String[] args) throws Exception {
int t = sc.nextInt();
for(int i = 0; i < t; i++) solve();
pw.flush();
}
static ArrayList<ArrayList<int[]>> map;
static int[] ans;
public static void solve() {
sb.setLength(0);
int n = sc.nextInt();
ans = new int[n-1];
map = new ArrayList<>();
for(int i = 0; i < n; i++){
map.add(new ArrayList<>());
}
int[] cnt = new int[n];
for(int i = 0; i < n-1; i++){
int[] e = sc.nextIntArray(2);
e[0]--;
e[1]--;
cnt[e[0]]++;
cnt[e[1]]++;
//edge.add(e);
map.get(e[0]).add(new int[]{e[1],i});
map.get(e[1]).add(new int[]{e[0],i});
}
for(int i = 0; i < n; i++){
if(cnt[i] > 2){
pw.println(-1);
return;
}
}
for(int i = 0; i < n; i++){
if(cnt[i] == 1){
ArrayDeque<int[]> dq = new ArrayDeque<>();
boolean[] used = new boolean[n];
used[i] = true;
dq.add(new int[]{i,0});
while(dq.size() > 0){
int[] now = dq.poll();
int u = now[0];
int c = now[1];
//System.err.println(u + " " + c + " "+ map.get(u).size());
for(int[] next : map.get(u)){
int v = next[0];
int ei = next[1];
//System.err.println(u + " " + v + " " + c + " " + ei);
if(!used[v]){
used[v] = true;
//System.err.println(u + " " + v + " " + c);
ans[ei] = c % 2 == 0 ? 3 : 2;
dq.add(new int[]{v,c+1});
}
}
}
for(int v : ans){
if(v == 0){
pw.println(-1);
return;
}
sb.append(v).append(" ");
}
pw.println(sb.toString().trim());
return;
}
}
pw.println(-1);
}
static class GeekInteger {
public static void save_sort(int[] array) {
shuffle(array);
Arrays.sort(array);
}
public static int[] shuffle(int[] array) {
int n = array.length;
Random random = new Random();
for (int i = 0, j; i < n; i++) {
j = i + random.nextInt(n - i);
int randomElement = array[j];
array[j] = array[i];
array[i] = randomElement;
}
return array;
}
public static void save_sort(long[] array) {
shuffle(array);
Arrays.sort(array);
}
public static long[] shuffle(long[] array) {
int n = array.length;
Random random = new Random();
for (int i = 0, j; i < n; i++) {
j = i + random.nextInt(n - i);
long randomElement = array[j];
array[j] = array[i];
array[i] = randomElement;
}
return array;
}
}
}
class FastScanner {
private BufferedReader reader = null;
private StringTokenizer tokenizer = null;
public FastScanner(InputStream in) {
reader = new BufferedReader(new InputStreamReader(in));
tokenizer = null;
}
public FastScanner(FileReader in) {
reader = new BufferedReader(in);
tokenizer = null;
}
public String next() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public String nextLine() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken("\n");
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String[] nextArray(int n) {
String[] a = new String[n];
for (int i = 0; i < n; i++)
a[i] = next();
return a;
}
public int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
}
| 0 |
Non-plagiarised
|
4241f473
|
4685c420
|
import java.io.*;
import java.util.*;
public class C {
public static void main(String[] args)throws IOException {
FastScanner scan = new FastScanner();
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out));
int t = scan.nextInt();
for(int tt = 0;tt<t;tt++) {
int n = scan.nextInt();
ArrayList<String> arr = new ArrayList<>();
for(int i = 0;i<n;i++) arr.add(scan.next());
int max = -1;
for(int cases = 0;cases<5;cases++) {
ArrayList<Integer> list = new ArrayList<>();
char ch = (char)('a'+cases);
for(int i = 0;i<n;i++) {
String s = arr.get(i);
int countch = 0, countTotal = 0;
for(int j = 0;j<s.length();j++) {
if(s.charAt(j)==ch) countch++;
else countTotal++;
}
list.add(countch-countTotal);
}
Collections.sort(list);
int sum = 0, count = 0;
for(int i = n-1;i>=0;i--) {
sum+=list.get(i);
if(sum>0) count++;
else break;
}
max = Math.max(max, count);
}
output.write(max+"\n");
}
output.flush();
}
public static int[] sort(int arr[]) {
List<Integer> list = new ArrayList<>();
for(int i:arr)
list.add(i);
Collections.sort(list);
for(int i = 0;i<list.size();i++) {
arr[i] = list.get(i);
}
return arr;
}
public static int gcd(int a, int b) {
if(a == 0) return b;
return gcd(b%a, 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());
}
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());
}
}
}
|
// package Div3_734;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
public class ProblemC {
public static void main(String[] args)throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringBuilder print=new StringBuilder();
int test=Integer.parseInt(br.readLine());
while(test--!=0){
int n=Integer.parseInt(br.readLine());
ArrayList<Story> stories[]=new ArrayList[5];
for(int i=0;i<5;i++){
stories[i]=new ArrayList<>();
}
for(int i=1;i<=n;i++){
char c[]=br.readLine().toCharArray();
int freq[]=new int[5];
for(int j=0;j<c.length;j++){
freq[c[j]-97]++;
}
for(int j=0;j<5;j++){
stories[j].add(new Story(freq[j],c.length-freq[j]));
}
}
for(int i=0;i<5;i++){
Collections.sort(stories[i]);
}
int max=0;
for(int i=0;i<5;i++){
int def=0;
int count=0;
for(Story story:stories[i]){
int diff=story.diff;
if(def+diff<=0){
break;
}
else{
def+=diff;
count++;
}
}
max=Math.max(max,count);
}
print.append(max+"\n");
}
System.out.print(print);
}
}
class Story implements Comparable<Story>{
int x,y,diff;
public Story(int x,int y){
this.x=x;
this.y=y;
this.diff=this.x-this.y;
}
@Override
public int compareTo(Story o) {
return -this.diff+o.diff;
}
}
| 0 |
Non-plagiarised
|
2120328e
|
b790ef12
|
/***** ---> :) Vijender Srivastava (: <--- *****/
import java.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
static FastReader sc =new FastReader();
static PrintWriter out=new PrintWriter(System.out);
static int mod=10000007;
static StringBuilder sb=new StringBuilder();
/* start */
public static void main(String [] args)
{
int t = i();
while(t-->0)
{
int n = i();
int a[] = input(n);
char c[] = inputC();
ArrayList<Integer> b = new ArrayList<>();
ArrayList<Integer> r = new ArrayList<>();
for(int i=0;i<n;i++)
{
if(c[i]=='R')
r.add(a[i]);
else
b.add(a[i]);
}
Collections.sort(b);
Collections.sort(r,Collections.reverseOrder());
boolean is = true;
int cnt = 1;
for(int i=0;i<b.size();i++)
{
if(b.get(i)<cnt)
{
is = false;
break;
}
cnt++;
}
for(int i=0;i<r.size();i++)
{
if(r.get(i)>n-i)
{
is = false;
break;
}
}
out.println(is==true?"YES":"NO");
}
out.close();
}
/* end */
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 int i() {
return sc.nextInt();
}
static String s() {
return sc.next();
}
static long l() {
return sc.nextLong();
}
static char[] inputC()
{
String s = sc.nextLine();
return s.toCharArray();
}
static int[] input(int n) {
int A[]=new int[n];
for(int i=0;i<n;i++) {
A[i]=sc.nextInt();
}
return A;
}
static long[] inputL(int n) {
long A[]=new long[n];
for(int i=0;i<n;i++) {
A[i]=sc.nextLong();
}
return A;
}
static long[] putL(long a[]) {
long A[]=new long[a.length];
for(int i=0;i<a.length;i++) {
A[i]=a[i];
}
return A;
}
static String[] inputS(int n) {
String A[]=new String[n];
for(int i=0;i<n;i++) {
A[i]=sc.next();
}
return A;
}
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static String reverse(String s) {
StringBuffer p=new StringBuffer(s);
p.reverse();
return p.toString();
}
static int min(int a,int b) {
return Math.min(a, b);
}
static int min(int a,int b,int c) {
return Math.min(a, Math.min(b, c));
}
static int min(int a,int b,int c,int d) {
return Math.min(a, Math.min(b, Math.min(c, d)));
}
static int max(int a,int b) {
return Math.max(a, b);
}
static int max(int a,int b,int c) {
return Math.max(a, Math.max(b, c));
}
static int max(int a,int b,int c,int d) {
return Math.max(a, Math.max(b, Math.max(c, d)));
}
static long min(long a,long b) {
return Math.min(a, b);
}
static long min(long a,long b,long c) {
return Math.min(a, Math.min(b, c));
}
static long min(long a,long b,long c,long d) {
return Math.min(a, Math.min(b, Math.min(c, d)));
}
static long max(long a,long b) {
return Math.max(a, b);
}
static long max(long a,long b,long c) {
return Math.max(a, Math.max(b, c));
}
static long max(long a,long b,long c,long d) {
return Math.max(a, Math.max(b, Math.max(c, d)));
}
static long sum(int A[]) {
long sum=0;
for(int i : A) {
sum+=i;
}
return sum;
}
static long sum(long A[]) {
long sum=0;
for(long i : A) {
sum+=i;
}
return sum;
}
static void print(int A[]) {
for(int i : A) {
System.out.print(i+" ");
}
System.out.println();
}
static void print(long A[]) {
for(long i : A) {
System.out.print(i+" ");
}
System.out.println();
}
static long mod(long x) {
return ((x%mod + mod)%mod);
}
static long power(long x, long y)
{
if(y==0)
return 1;
if(x==0)
return 0;
long res = 1;
while (y > 0) {
if (y % 2 == 1)
res = (res * x) ;
y = y >> 1;
x = (x * x);
}
return res;
}
static boolean prime(int n)
{
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
double sq=Math.sqrt(n);
for (int i = 5; i <= sq; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static boolean prime(long n)
{
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
double sq=Math.sqrt(n);
for (int i = 5; i <= sq; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
//pair class
private static class Pair implements Comparable<Pair> {
int first, second;
public Pair(int f, int s) {
first = f;
second = s;
}
@Override
public int compareTo(Pair p) {
if (first > p.first)
return 1;
else if (first < p.first)
return -1;
else {
if (second > p.second)
return 1;
else if (second < p.second)
return -1;
else
return 0;
}
}
}
}
|
import java.io.*;
import java.util.*;
public class Main {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args) {
FastReader obj = new FastReader();
PrintWriter out = new PrintWriter(System.out);
int l = obj.nextInt();
while (l-- != 0) {
int n = obj.nextInt();
int[] num = new int[n];
for (int i = 0; i < n; i++) num[i] = obj.nextInt();
Vector<Integer> red = new Vector<>();
Vector<Integer> blue = new Vector<>();
String s = obj.next();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == 'R') red.add(num[i]);
else blue.add(num[i]);
}
Collections.sort(blue);
Collections.sort(red);
int c = 1, f = 0;
for (int i = 0; i < blue.size(); i++) {
if (blue.get(i) < c) {
f = 1;
break;
}
c++;
}
for (int i = 0; i < red.size(); i++) {
if (red.get(i) > c) {
f = 1;
break;
}
c++;
}
if (f == 0) out.println("YES");
else out.println("NO");
}
out.flush();
}
}
| 1 |
Plagiarised
|
8535bdf7
|
e86eb5b0
|
import java.util.*;
import java.io.*;
import java.lang.*;
public class Problem {
public static void dfs(int u, int parent, ArrayList<ArrayList<Integer>> graph,long[][] dp,Pair[] arr)
{
ArrayList<Integer> adja=graph.get(u);
for(int i=0;i<adja.size();i++)
{
int adja_ele=adja.get(i);
if(adja_ele!=parent)
{
dfs(adja_ele, u,graph,dp,arr);
long res1=Math.max(Math.abs(arr[u].getL()-arr[adja_ele].getL())+dp[adja_ele][0],Math.abs(arr[u].getL()-arr[adja_ele].getR())+dp[adja_ele][1]);
long res2=Math.max(Math.abs(arr[u].getR()-arr[adja_ele].getL())+dp[adja_ele][0],Math.abs(arr[u].getR()-arr[adja_ele].getR())+dp[adja_ele][1]);
dp[u][0]+=res1;
dp[u][1]+=res2;
// System.out.println(u+" "+adja_ele+" "+res1+" "+res2);
}
}
}
public static void main(String[] args) throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int t =Integer.parseInt(br.readLine());
while(t-- >0)
{
int n =Integer.parseInt(br.readLine().trim());
Pair[] arr=new Pair[n+1];
for(int i=1;i<n+1;i++) {
String[] sa=br.readLine().trim().split(" ");
int l=Integer.parseInt(sa[0]);
int r=Integer.parseInt(sa[1]);
Pair p=new Pair(l,r);
arr[i]=p;
}
ArrayList<ArrayList<Integer>> graph=new ArrayList<ArrayList<Integer>>(n+1);
for(int i=0;i<n+1;i++)
{
graph.add(new ArrayList<Integer>());
}
for(int i=0;i<n-1;i++)
{
String[] sa=br.readLine().trim().split(" ");
int u=Integer.parseInt(sa[0]);
int v=Integer.parseInt(sa[1]);
graph.get(u).add(v);
graph.get(v).add(u);
}
long[][] dp=new long[n+1][2];
dfs(1,0,graph,dp,arr);
// for(int i=0;i<dp.length;i++)
// {
// System.out.println(dp[i][0]+" "+dp[i][1]);
// }
System.out.println(Math.max(dp[1][0],dp[1][1]));
}
}
}
class Pair
{
private int l;
private int r;
public Pair(int l, int r) {
this.l = l;
this.r = r;
}
public int getL() {
return l;
}
public void setL(int l) {
this.l = l;
}
public int getR() {
return r;
}
public void setR(int r) {
this.r = r;
}
}
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class Exam1 {
/*
1. Time complexity: O(t*n*logn).
2. Space complexity: O(n).
2. n*t < 10^8 , it should be finished in the time constraint.
*/
static int[] l, r;
static List<Integer>[] adj;
static Long[][] a;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
int t = Integer.parseInt(s);
while (t-- > 0) {
s = br.readLine();
int n = Integer.parseInt(s);
l = new int[n];
r = new int[n];
for (int i = 0; i < n; i++) {
s = br.readLine();
String[] num = s.split(" ");
l[i] = Integer.parseInt(num[0]);
r[i] = Integer.parseInt(num[1]);
}
adj = new ArrayList[n];
for (int i = 0; i < n; i++) adj[i] = new ArrayList<>();
for (int i = 1; i < n; i++) {
s = br.readLine();
String[] num = s.split(" ");
int u = Integer.parseInt(num[0]) - 1, v = Integer.parseInt(num[1]) - 1;
adj[u].add(v);
adj[v].add(u);
}
a = new Long[n][2];
dfs(0, 0);
System.out.println(Math.max(a[0][0], a[0][1]));
}
}
private static void dfs(int cur, int fa) {
a[cur][0] = a[cur][1] = 0L;
for (int i = 0; i < adj[cur].size(); i++) {
int p = adj[cur].get(i);
if (p == fa) continue;
dfs(p, cur);
a[cur][0] += Math.max(a[p][0] + Math.abs(l[cur] - l[p]), a[p][1] + Math.abs(l[cur] - r[p]));
a[cur][1] += Math.max(a[p][0] + Math.abs(r[cur] - l[p]), a[p][1] + Math.abs(r[cur] - r[p]));
}
}
}
| 0 |
Non-plagiarised
|
5756162d
|
808f7516
|
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Main {
static int MOD = 1000000007;
// After writing solution, quick scan for:
// array out of bounds
// special cases e.g. n=1?
//
// Big numbers arithmetic bugs:
// int overflow
// sorting, or taking max, after MOD
void solve() throws IOException {
int n = ri();
int[] h = ril(n);
List<List<Integer>> adj = new ArrayList<>(n);
for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
int[] nextGe = new int[n];
nextGe[n-1] = n;
for (int i = n-2; i >= 0; i--) {
int j = i+1;
while (j != n && h[j] < h[i]) j = nextGe[j];
nextGe[i] = j;
}
int[] nextLe = new int[n];
nextLe[n-1] = n;
for (int i = n-2; i >= 0; i--) {
int j = i+1;
while (j != n && h[j] > h[i]) j = nextLe[j];
nextLe[i] = j;
}
int[] prevGe = new int[n];
prevGe[0] = -1;
for (int i = 1; i < n; i++) {
int j = i-1;
while (j != -1 && h[j] < h[i]) j = prevGe[j];
prevGe[i] = j;
}
int[] prevLe = new int[n];
prevLe[0] = -1;
for (int i = 1; i < n; i++) {
int j = i-1;
while (j != -1 && h[j] > h[i]) j = prevLe[j];
prevLe[i] = j;
}
for (int i = 0; i < n; i++) {
if (prevLe[i] != -1) adj.get(prevLe[i]).add(i);
if (prevGe[i] != -1) adj.get(prevGe[i]).add(i);
if (nextLe[i] != n) adj.get(i).add(nextLe[i]);
if (nextGe[i] != n) adj.get(i).add(nextGe[i]);
}
int dist = 0;
Deque<Integer> q = new ArrayDeque<>();
boolean[] visited = new boolean[n];
q.addLast(0);
visited[0] = true;
while (!q.isEmpty()) {
int sz = q.size();
for (int i = 0; i < sz; i++) {
int u = q.removeFirst();
if (u == n-1) {
q.clear();
break;
}
for (int v : adj.get(u)) {
if (!visited[v]) {
visited[v] = true;
q.addLast(v);
}
}
}
dist++;
}
pw.println(dist-1);
}
// Template code below
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
public static void main(String[] args) throws IOException {
Main m = new Main();
m.solve();
m.close();
}
void close() throws IOException {
pw.flush();
pw.close();
br.close();
}
int ri() throws IOException {
return Integer.parseInt(br.readLine());
}
long rl() throws IOException {
return Long.parseLong(br.readLine());
}
int[] ril(int n) throws IOException {
int[] nums = new int[n];
int c = 0;
for (int i = 0; i < n; i++) {
int sign = 1;
c = br.read();
int x = 0;
if (c == '-') {
sign = -1;
c = br.read();
}
while (c >= '0' && c <= '9') {
x = x * 10 + c - '0';
c = br.read();
}
nums[i] = x * sign;
}
while (c != '\n' && c != -1) c = br.read();
return nums;
}
long[] rll(int n) throws IOException {
long[] nums = new long[n];
int c = 0;
for (int i = 0; i < n; i++) {
int sign = 1;
c = br.read();
long x = 0;
if (c == '-') {
sign = -1;
c = br.read();
}
while (c >= '0' && c <= '9') {
x = x * 10 + c - '0';
c = br.read();
}
nums[i] = x * sign;
}
while (c != '\n' && c != -1) c = br.read();
return nums;
}
int[] rkil() throws IOException {
int sign = 1;
int c = br.read();
int x = 0;
if (c == '-') {
sign = -1;
c = br.read();
}
while (c >= '0' && c <= '9') {
x = x * 10 + c - '0';
c = br.read();
}
return ril(x);
}
long[] rkll() throws IOException {
int sign = 1;
int c = br.read();
int x = 0;
if (c == '-') {
sign = -1;
c = br.read();
}
while (c >= '0' && c <= '9') {
x = x * 10 + c - '0';
c = br.read();
}
return rll(x);
}
char[] rs() throws IOException {
return br.readLine().toCharArray();
}
void sort(int[] A) {
Random r = new Random();
for (int i = A.length-1; i > 0; i--) {
int j = r.nextInt(i+1);
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
Arrays.sort(A);
}
}
|
import java.util.*;
import java.io.*;
public class EdD {
public static void main(String[] args) throws Exception{
int num = 998244353;
// TODO Auto-generated method stub
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
// String input1 = bf.readLine().trim();
// String input2 = bf.readLine().trim();
int n = Integer.parseInt(bf.readLine());
int[] array = new int[n];
StringTokenizer st = new StringTokenizer(bf.readLine());
for(int j = 0;j<n;j++){
array[j] = Integer.parseInt(st.nextToken());
}
Map<Integer, Set<Integer>> mp = new HashMap<Integer, Set<Integer>>();
for(int j =0;j<n;j++)
mp.put(j, new HashSet<Integer>());
int[] nextge = new int[n];
int[] nextle = new int[n];
int[] prevge = new int[n];
int[] prevle = new int[n];
nextge[n-1] = -1;
nextle[n-1] = -1;
prevge[0] = -1;
prevle[0] = -1;
for(int j = n-2;j>=0;j--){
if (array[j+1] < array[j]){
nextle[j] = j+1;
mp.get(j).add(j+1);
int temp = j+1;
while(temp!= -1 && array[temp] < array[j])
temp = nextge[temp];
nextge[j] = temp;
if (temp!= -1)
mp.get(j).add(temp);
}
else if (array[j+1] > array[j]){
nextge[j] = j+1;
mp.get(j).add(j+1);
int temp = j+1;
while(temp!= -1 && array[temp] > array[j])
temp = nextle[temp];
nextle[j] = temp;
if (temp!= -1)
mp.get(j).add(temp);
}
else{
nextge[j] = j+1;
mp.get(j).add(j+1);
nextle[j] = j+1;
mp.get(j).add(j+1);
}
}
for(int j = 1;j<n;j++){
if (array[j] < array[j-1]){
prevge[j] = j-1;
mp.get(j-1).add(j);
int temp = j-1;
while(temp!= -1 && array[temp] > array[j])
temp = prevle[temp];
prevle[j] = temp;
if (temp!= -1)
mp.get(temp).add(j);
}
else if (array[j] > array[j-1]){
prevle[j] = j-1;
mp.get(j-1).add(j);
int temp = j-1;
while(temp!= -1 && array[temp] < array[j])
temp = prevge[temp];
prevge[j] = temp;
if (temp!= -1)
mp.get(temp).add(j);
}
else{
prevge[j] = j-1;
prevle[j] = j-1;
mp.get(j-1).add(j);
}
}
int[] depth = new int[n+1];
Set<Integer> seen = new HashSet<Integer>();
Queue<Integer> bfs = new LinkedList<Integer>();
bfs.add(0);
seen.add(0);
while(!bfs.isEmpty()){
int v = bfs.remove();
for(int child : mp.get(v)){
if (!seen.contains(child)){
bfs.add(child);
seen.add(child);
depth[child] = depth[v]+1;
}
}
}
out.println(depth[n-1]);
out.close();
}
}
//StringJoiner sj = new StringJoiner(" ");
//sj.add(strings)
//sj.toString() gives string of those stuff w spaces or whatever that sequence is
| 0 |
Non-plagiarised
|
317a209c
|
9ab3c0e1
|
import java.io.*;
import java.util.*;
public class D_Java {
public static final int MOD = 998244353;
public static int mul(int a, int b) {
return (int)((long)a * (long)b % MOD);
}
int[] f;
int[] rf;
public int C(int n, int k) {
return (k < 0 || k > n) ? 0 : mul(f[n], mul(rf[n-k], rf[k]));
}
public static int pow(int a, int n) {
int res = 1;
while (n != 0) {
if ((n & 1) == 1) {
res = mul(res, a);
}
a = mul(a, a);
n >>= 1;
}
return res;
}
static void shuffleArray(int[] a) {
Random rnd = new Random();
for (int i = a.length-1; i > 0; i--) {
int index = rnd.nextInt(i + 1);
int tmp = a[index];
a[index] = a[i];
a[i] = tmp;
}
}
public static int inv(int a) {
return pow(a, MOD-2);
}
public void doIt() throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tok = new StringTokenizer(in.readLine());
int n = Integer.parseInt(tok.nextToken());
int k = Integer.parseInt(tok.nextToken());
f = new int[n+42];
rf = new int[n+42];
f[0] = rf[0] = 1;
for (int i = 1; i < f.length; ++i) {
f[i] = mul(f[i-1], i);
rf[i] = mul(rf[i-1], inv(i));
}
int[] events = new int[2*n];
for (int i = 0; i < n; ++i) {
tok = new StringTokenizer(in.readLine());
int le = Integer.parseInt(tok.nextToken());
int ri = Integer.parseInt(tok.nextToken());
events[i] = le*2;
events[i + n] = ri*2 + 1;
}
shuffleArray(events);
Arrays.sort(events);
int ans = 0;
int balance = 0;
for (int r = 0; r < 2*n;) {
int l = r;
while (r < 2*n && events[l] == events[r]) {
++r;
}
int added = r - l;
if (events[l] % 2 == 0) {
// Open event
ans += C(balance + added, k);
if (ans >= MOD) ans -= MOD;
ans += MOD - C(balance, k);
if (ans >= MOD) ans -= MOD;
balance += added;
} else {
// Close event
balance -= added;
}
}
in.close();
System.out.println(ans);
}
public static void main(String[] args) throws IOException {
(new D_Java()).doIt();
}
}
|
//package CF672;
/**
* @version 1.0
* @Package_Name: CF672
* @Author: Redorain
* @Date: 2020/9/25 8:47
*/
import java.util.*;
public class d {
public static Scanner sc = new Scanner(System.in);
public static final int MOD = 998244353;
int []f; int [] lf;
public static int mul(int a, int b) {
return (int)((long)a * (long)b % MOD);
}
public static int ksm(int a, int n) {
int ans = 1;
while(n > 0) {
if((n & 1) == 1)
ans = mul(a, ans);
a = mul(a, a);
n >>= 1;
}
return ans;
}
public int C(int n, int k) {
return (k < 0 || k > n) ? 0 : mul(f[n], mul(lf[n - k], lf[k]));
}
public static int inv(int a) {
return ksm(a, MOD - 2);
}
public void solve() {
int n = sc.nextInt();
int k = sc.nextInt();
f = new int[n + 42];
lf = new int[n + 42];
f[0] = lf[0] = 1;
for(int i = 1; i < f.length; i++) {
f[i] = mul(f[i - 1], i);
lf[i] = mul(lf[i - 1], inv(i));
}
int[] events = new int[2 * n];
for(int i = 0; i < n; i++) {
int le = sc.nextInt();
int ri = sc.nextInt();
events[i] = le * 2;
events[i + n] = ri * 2 + 1;
}
Arrays.sort(events);
int ans = 0, balance = 0;
for(int r = 0; r < 2 * n;) {
int l = r;
while(r < 2 * n && events[l] == events[r]) ++r;
int added = r - l;
if(events[l] % 2 == 0) {
ans += C(balance + added, k);
if(ans >= MOD) ans -= MOD;
ans += MOD - C(balance, k);
if(ans >= MOD) ans -= MOD;
balance += added;
}
else balance -= added;
}
sc.close();
System.out.println(ans);
}
public static void main(String[] args) {
(new d()).solve();
}
}
| 1 |
Plagiarised
|
38b356b7
|
c77654b8
|
import java.awt.*;
import java.io.*;
import java.util.*;
public class Main {
static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
static StringBuilder str = new StringBuilder();
public static void main(String[] args) throws NumberFormatException, IOException {
int t = Integer.parseInt(reader.readLine());
while (t-- > 0) {
solve();
}
printRes();
}
public static void printRes() {
System.out.println(str);
}
public static void solve() throws IOException {
int n = Integer.parseInt(reader.readLine());
String[] s = reader.readLine().split(" ");
int[] nums = new int[n];
for (int i = 0; i < n; i++) {
nums[i] = Integer.parseInt(s[i]);
}
int i = 0;
if (n % 2 == 1) {
if (nums[1] + nums[2] != 0) {
str.append(-(nums[1] + nums[2]) + " " + nums[0] + " " + nums[0] + " ");
} else if (nums[0] + nums[2] != 0) {
str.append(nums[1] + " " + -(nums[0] + nums[2]) + " " + nums[1] + " ");
} else {
str.append(nums[2] + " " + nums[2] + " " + -(nums[0] + nums[1]) + " ");
}
i = 3;
}
for (; i < n; i+=2) {
if (nums[i] > 0 && nums[i+1] > 0) {
str.append(nums[i+1] + " " + (-nums[i]) + " ");
} else if (nums[i] < 0 && nums[i+1] < 0) {
str.append(nums[i+1] + " " + Math.abs(nums[i]) + " ");
} else {
str.append(Math.abs(nums[i+1]) + " " + Math.abs(nums[i]) + " ");
}
}
str.append("\n");
}
}
|
import java.io.PrintWriter;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int tc = sc.nextInt();
while(tc-->0){
int n = sc.nextInt();
int[] arr = new int[n]; for(int i = 0; i<n; i++)arr[i] = sc.nextInt();
if(n % 2 == 0){
for(int i = 0; i<n; i+=2){
pw.print((-arr[i + 1]) + " " + arr[i] + " ");
}
pw.println();
}else{
if(arr[0] + arr[1] != 0) pw.print(arr[2] + " " + arr[2] + " " + (-(arr[0] + arr[1])) + " ");
else if(arr[0] + arr[2] != 0)pw.println(arr[1] + " " + (-(arr[0] + arr[2]))+" " + arr[1]);
else pw.println(-(arr[1] + arr[2]) + " " + arr[0]+" " + arr[0]);
for(int i = 3; i<n; i+=2){
pw.print((-arr[i + 1]) + " " + arr[i] + " ");
}
pw.println();
}
}
pw.flush();
}
}
| 0 |
Non-plagiarised
|
1500a4fa
|
d7a8434f
|
import java.io.*;
import java.util.*;
public class GFG {
public static void main (String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0){
int n=sc.nextInt();
String a=sc.next();
String b=sc.next();
int i;
int zero=0,one=0;
int x=0,y=0,x1=0,y1=0;
for(i=0;i<n;i++){
if(a.charAt(i)=='0')
zero++;
else
one++;
}
if(one==0){
if(a.equals(b))
System.out.println("0");
else
System.out.println("-1");
}
else{
int same=0,diff=0;
for(i=0;i<n;i++){
if(a.charAt(i)==b.charAt(i)){
same++;
x++;
if(a.charAt(i)=='1'){
x1++;
}
}
else{
diff++;
y++;
if(a.charAt(i)=='1'){
y1++;
}
}
}
int ans=Integer.MAX_VALUE;
if(x%2!=0&&(x+1)/2==x1){
ans=x;
}
if(y%2==0&&(y/2)==y1){
ans=Math.min(ans,y);
}
if(ans==Integer.MAX_VALUE){
System.out.println("-1");
}else{
System.out.println(ans);
}
}
}
}
}
|
import java.util.*;
import java.io.*;
public class C {
public static void main(String[] args) {
FastScanner sc = new FastScanner();
int T = sc.nextInt();
while(T-->0) {
int n = sc.nextInt();
char[] s = new char[n];
char[] t = new char[n];
s = sc.next().toCharArray();
t = sc.next().toCharArray();
int a = 0, b = 0, c = 0, d = 0;
for(int i = 0; i < n; i++) {
if(s[i] == '0' && t[i] == '0') a++;
if(s[i] == '1' && t[i] == '0') b++;
if(s[i] == '0' && t[i] == '1') c++;
if(s[i] == '1' && t[i] == '1') d++;
}
int res = Integer.MAX_VALUE;
if(b == c || b+1 == c) {
if((b + c) % 2 == 0) {
res = Math.min(res, b + c);
}
}
if(a == d || a+1 == d) {
if((a + d) % 2 == 1) {
res = Math.min(res, a + d);
}
}
if(res == Integer.MAX_VALUE) System.out.println(-1);
else System.out.println(res);
}
}
static class FastScanner {
public BufferedReader reader;
public StringTokenizer tokenizer;
public FastScanner() {
reader = new BufferedReader(new InputStreamReader(System.in), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
try {
return reader.readLine();
} catch(IOException e) {
throw new RuntimeException(e);
}
}
}
}
| 0 |
Non-plagiarised
|
25597bcb
|
5fcbdd19
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class PhoenixAndTowers { // Template for CF
public static class ListComparator implements Comparator<List<Integer>> {
@Override
public int compare(List<Integer> l1, List<Integer> l2) {
for (int i = 0; i < l1.size(); ++i) {
if (l1.get(i).compareTo(l2.get(i)) != 0) {
return l1.get(i).compareTo(l2.get(i));
}
}
return 0;
}
}
public static class Pair {
int first;
int second;
public Pair(int first, int second) {
this.first = first;
this.second = second;
}
public int getFirst() {
return first;
}
public int getSecond() {
return second;
}
public void setFirst(int a) {
first = a;
}
@Override
public String toString() {
return first + " " + second;
}
}
public static void main(String[] args) throws IOException {
// Check for int overflow!!!!
// Should you use a long to store the sum or smthn?
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int T = Integer.parseInt(f.readLine());
for (int i = 0; i < T; i++) {
StringTokenizer st = new StringTokenizer(f.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
int x = Integer.parseInt(st.nextToken());
st = new StringTokenizer(f.readLine());
List<Integer> list = new ArrayList<>();
for (int j = 0; j < n; j++) {
int a = Integer.parseInt(st.nextToken());
list.add(a);
}
ArrayList<Integer> copy = new ArrayList<>(list);
Collections.sort(list);
TreeSet<List<Integer>> set = new TreeSet<>(new ListComparator());
for (int j = 1; j <= m; j++) {
List<Integer> temp = new ArrayList<>();
temp.add(0);
temp.add(j);
set.add(temp);
// System.out.println(temp);
}
// System.out.println(set);
Map<Integer, LinkedList<Integer>> map = new HashMap<>();
for (int j = n - 1; j >= 0; j--) {
if (map.containsKey(list.get(j))) {
map.get(list.get(j)).addLast(set.first().get(1));
} else {
map.put(list.get(j), new LinkedList<>());
map.get(list.get(j)).addLast(set.first().get(1));
}
List<Integer> temp = new ArrayList<>();
temp.add(set.first().get(0) + list.get(j));
temp.add(set.pollFirst().get(1));
set.add(temp);
}
// System.out.println(set);
if (set.last().get(0) - set.first().get(0) > x) {
out.println("NO");
} else {
out.println("YES");
for (int j = 0; j < n; j++) {
out.print(map.get(copy.get(j)).pollFirst() + " ");
}
out.println();
}
}
out.close();
}
}
|
import java.io.*;
import java.util.*;
public class C {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int t = in.nextInt();
for (int t1 = 0; t1 < t; t1++) {
int n = in.nextInt(), m = in.nextInt(), x = in.nextInt();
ArrayList<Pair> list = new ArrayList<>();
for (int i = 1; i <= n; i++) list.add(new Pair(in.nextInt(), i));
pw.println(solve(list, n, m, x));
}
pw.close();
}
static StringBuilder solve(ArrayList<Pair> arr, int n, int m, int x) {
Stack<Pair> stack = new Stack<>();
HashMap<Integer, Integer> map = new HashMap<>();
PriorityQueue<Pair> pq = new PriorityQueue<>();
Collections.sort(arr);
for (int i = m; i < n; i++) stack.push(arr.get(i));
for (int i = 0, j = 1; i < m; i++, j++) {
Pair p = arr.get(i);
pq.add(new Pair(p.f, j));
map.put(p.s, j);
}
while (!stack.isEmpty()) {
Pair val = stack.pop();
Pair p = pq.remove();
map.put(val.s, p.s);
pq.add(new Pair(p.f + val.f, p.s));
}
// debug(pq);
int min = pq.remove().f;
while (!pq.isEmpty()) {
int val = pq.remove().f;
if ((val - min) > x) return new StringBuilder().append("NO");
}
StringBuilder sb = new StringBuilder();
sb.append("YES\n");
for (int i = 1; i <= n; i++) {
sb.append(map.get(i) + " ");
}
return sb;
}
static class Pair implements Comparable<Pair> {
int f, s;
Pair(int f, int s) {
this.f = f;
this.s = s;
}
@Override
public int compareTo(Pair p) {
return Integer.compare(this.f, p.f);
}
@Override
public String toString() {
return f + " " + s;
}
}
static void debug(Object... obj) {
System.err.println(Arrays.deepToString(obj));
}
}
| 0 |
Non-plagiarised
|
c48673a6
|
ebed1250
|
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class C {
public static void main(String[] args) {
new C().solve(System.in, System.out);
}
public void solve(InputStream in, OutputStream out) {
InputReader inputReader = new InputReader(in);
PrintWriter writer = new PrintWriter(new BufferedOutputStream(out));
int t = inputReader.nextInt();
for (int t1 = 0; t1 < t; t1++) {
int n = inputReader.nextInt();
List<Long> c = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
c.add(inputReader.nextLong());
}
writer.println(solve(n, c));
}
writer.close();
}
public long solve(int n, List<Long> c) {
long[] minEven = new long[n];
long[] minOdd = new long[n];
long[] sumOdd = new long[n];
long[] sumEven = new long[n];
minEven[0] = Long.MAX_VALUE;
minOdd[0] = Long.MAX_VALUE;
for (int i = 0; i < n; i++) {
if (i > 0) {
minEven[i] = minEven[i - 1];
minOdd[i] = minOdd[i - 1];
sumOdd[i] = sumOdd[i - 1];
sumEven[i] = sumEven[i - 1];
}
if (i % 2 == 0) {
minEven[i] = Math.min(minEven[i], c.get(i));
sumEven[i] += c.get(i);
} else {
minOdd[i] = Math.min(minOdd[i], c.get(i));
sumOdd[i] += c.get(i);
}
}
long best = Long.MAX_VALUE;
for (int k = 1; k < n; k++) {
int countOdd = (k + 1) / 2;
int countEven = (k + 1) / 2;
if (k % 2 == 0) {
countEven++;
}
long oddResult = minOdd[k] * (n - countOdd) + sumOdd[k];
long evenResult = minEven[k] * (n - countEven) + sumEven[k];
long current = oddResult + evenResult;
best = Math.min(best, current);
}
return best;
}
private static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
|
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
public class Main {
private static void run() throws IOException {
int n = in.nextInt();
long[] c = new long[n];
for (int i = 0; i < n; i++) {
c[i] = in.nextInt();
}
long ans = (c[0] + c[1]) * n;
long sum = c[0] + c[1];
long[] min = {c[0], c[1]};
for (int i = 2; i < n; i++) {
sum += c[i];
int index = i % 2;
min[index] = Math.min(min[index], c[i]);
int[] times = new int[2];
times[index] = n - (i / 2 + 1);
times[index ^ 1] = n - ((i - 1) / 2 + 1);
ans = Math.min(ans, sum + min[0] * times[0] + min[1] * times[1]);
}
out.println(ans);
}
public static void main(String[] args) throws IOException {
in = new Reader();
out = new PrintWriter(new OutputStreamWriter(System.out));
int t = in.nextInt();
for (int i = 0; i < t; i++) {
run();
}
out.flush();
in.close();
out.close();
}
private static int gcd(int a, int b) {
if (a == 0 || b == 0)
return 0;
while (b != 0) {
int tmp;
tmp = a % b;
a = b;
b = tmp;
}
return a;
}
static final long mod = 1000000007;
static long pow_mod(long a, long b) {
long result = 1;
while (b != 0) {
if ((b & 1) != 0) result = (result * a) % mod;
a = (a * a) % mod;
b >>= 1;
}
return result;
}
private static long multiplied_mod(long... longs) {
long ans = 1;
for (long now : longs) {
ans = (ans * now) % mod;
}
return ans;
}
@SuppressWarnings("FieldCanBeLocal")
private static Reader in;
private static PrintWriter out;
private static void print_array(int[] array) {
for (int now : array) {
out.print(now);
out.print(' ');
}
out.println();
}
private static void print_array(long[] array) {
for (long now : array) {
out.print(now);
out.print(' ');
}
out.println();
}
static class Reader {
private static final int BUFFER_SIZE = 1 << 16;
private final DataInputStream din;
private final byte[] buffer;
private int bufferPointer, bytesRead;
Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
final byte[] buf = new byte[1024]; // 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 nextSign() throws IOException {
byte c = read();
while ('+' != c && '-' != c) {
c = read();
}
return '+' == c ? 0 : 1;
}
private static boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
public int skip() throws IOException {
int b;
// noinspection ALL
while ((b = read()) != -1 && isSpaceChar(b)) {
;
}
return b;
}
public char nc() throws IOException {
return (char) skip();
}
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();
}
}
}
| 0 |
Non-plagiarised
|
00f79486
|
fb312dc6
|
/* In_The_Name_Of_Allah_The_Merciful */
import java.util.*;
import java.io.*;
public class Main
{
class Pair implements Comparable<Pair>{
int f,s;
Pair(int x,int y){
f=x;
s=y;
}
@Override
public int compareTo(Pair a) {
if(a.f!=this.f)return Integer.compare(f,a.f);
else return Integer.compare(s,a.s);
}
}
PrintWriter out;
FastReader sc;
long[] m1= {(long)(1e9+7),998244353};
long mod=m1[1];
long maxlong=Long.MAX_VALUE;
long minlong=Long.MIN_VALUE;
StringBuilder sb;
/******************************************************************************************
*****************************************************************************************/
public void sol() {
int n=ni();
int[] ar=new int[n];
for(int i=0;i<n;i++)ar[i]=ni();
char[] s=rl();
PriorityQueue<Integer> red=new PriorityQueue<>(Collections.reverseOrder()),blue=new PriorityQueue<>();
for(int i=0;i<n;i++) {
if(s[i]=='R')red.add(ar[i]);
else blue.add(ar[i]);
}
int a=n;
while(red.size()>0) {
if(red.poll()>a) {
no();return;
}a--;
}a=1;
while(blue.size()>0) {
if(blue.poll()<a) {
no();return;
}a++;
}yes();
}
public static void main(String[] args)
{
Main g=new Main();
g.out=new PrintWriter(System.out);
g.sc=new FastReader();
int t=1;
t=g.ni();
while(t-->0)
g.sol();
g.out.flush();
}
/****************************************************************************************
*****************************************************************************************/
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 int ni(){
return sc.nextInt();
}public long nl(){
return sc.nextLong();
}public double nd(){
return sc.nextDouble();
}public char[] rl(){
return sc.nextLine().toCharArray();
}public String rl1(){
return sc.nextLine();
}
public void pl(Object s){
out.println(s);
}
public void pr(Object s){
out.print(s);
}public String next(){
return sc.next();
}public long abs(long x){
return Math.abs(x);
}
public int abs(int x){
return Math.abs(x);
}
public double abs(double x){
return Math.abs(x);
}public long min(long x,long y){
return (long)Math.min(x,y);
}
public int min(int x,int y){
return (int)Math.min(x,y);
}
public double min(double x,double y){
return Math.min(x,y);
}public long gcd(long a, long b) {
if (a == 0)
return b;
return gcd(b % a, a);
}public long lcm(long a, long b) {
return (a / gcd(a, b)) * b;
}
void sort1(int[] a) {
ArrayList<Integer> l = new ArrayList<>();
for (int i : a) {
l.add(i);
}
Collections.sort(l,Collections.reverseOrder());
for (int i = 0; i < a.length; i++) {
a[i] = l.get(i);
}
}
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);
}
}void sort(char[] a) {
ArrayList<Character> l = new ArrayList<>();
for (char i : a) {
l.add(i);
}
Collections.sort(l);
for (int i = 0; i < a.length; i++) {
a[i] = l.get(i);
}
}void sort1(char[] a) {
ArrayList<Character> l = new ArrayList<>();
for (char i : a) {
l.add(i);
}
Collections.sort(l,Collections.reverseOrder());
for (int i = 0; i < a.length; i++) {
a[i] = l.get(i);
}
}
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);
}
}void sort1(long[] a) {
ArrayList<Long> l = new ArrayList<>();
for (long i : a) {
l.add(i);
}
Collections.sort(l,Collections.reverseOrder());
for (int i = 0; i < a.length; i++) {
a[i] = l.get(i);
}
}
void sort(double[] a) {
ArrayList<Double> l = new ArrayList<>();
for (double i : a) {
l.add(i);
}
Collections.sort(l);
for (int i = 0; i < a.length; i++) {
a[i] = l.get(i);
}
}long pow(long a,long b){
if(b==0){
return 1;
}long p=pow(a,b/2);
if(b%2==0) return mMultiplication(p,p)%mod;
else return (mMultiplication(mMultiplication(p,p),a))%mod;
}
int swap(int a,int b){
return a;
}long swap(long a,long b){
return a;
}double swap(double a,double b){
return a;
}
boolean isPowerOfTwo (int x)
{
return x!=0 && ((x&(x-1)) == 0);
}boolean isPowerOfTwo (long x)
{
return x!=0 && ((x&(x-1)) == 0);
}public long max(long x,long y){
return (long)Math.max(x,y);
}
public int max(int x,int y){
return (int)Math.max(x,y);
}
public double max(double x,double y){
return Math.max(x,y);
}long sqrt(long x){
return (long)Math.sqrt(x);
}int sqrt(int x){
return (int)Math.sqrt(x);
}void input(int[] ar,int n){
for(int i=0;i<n;i++)ar[i]=ni();
}void input(long[] ar,int n){
for(int i=0;i<n;i++)ar[i]=nl();
}void fill(int[] ar,int k){
Arrays.fill(ar,k);
}void yes(){
pl("YES");
}void no(){
pl("NO");
}
long c2(long n) {
return (n*(n-1))/2;
}
long[] sieve(int n)
{
long[] k=new long[n+1];
boolean[] pr=new boolean[n+1];
for(int i=1;i<=n;i++){
k[i]=i;
pr[i]=true;
}for(int i=2;i<=n;i++){
if(pr[i]){
for(int j=i+i;j<=n;j+=i){
pr[j]=false;
if(k[j]==j){
k[j]=i;
}
}
}
}return k;
}
int strSmall(int[] arr, int target)
{
int start = 0, end = arr.length-1;
int ans = -1;
while (start <= end) {
int mid = (start + end) / 2;
if (arr[mid] >= target) {
end = mid - 1;
}
else {
ans = mid;
start = mid + 1;
}
}
return ans;
} int strSmall(ArrayList<Integer> arr, int target)
{
int start = 0, end = arr.size()-1;
int ans = -1;
while (start <= end) {
int mid = (start + end) / 2;
if (arr.get(mid) > target) {
start = mid + 1;
ans=start;
}
else {
end = mid - 1;
}
}
return ans;
}long mMultiplication(long a,long b)
{
long res = 0;
a %= mod;
while (b > 0)
{
if ((b & 1) > 0)
{
res = (res + a) % mod;
}
a = (2 * a) % mod;
b >>= 1;
}
return res;
}long nCr(int n, int r ,long p)
{
if (n<r)
return 0;
if (r == 0)
return 1;
long[] fac = new long[n + 1];
fac[0] = 1;
for (int i = 1; i <= n; i++)
fac[i] = fac[i - 1] * i %p;
return (fac[n] * modInverse(fac[r], p)
% p * modInverse(fac[n - r], p)
% p)
% p;
}long power(long x, long y, long p)
{
long res = 1;
x = x % p;
while (y > 0) {
if (y % 2 == 1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}long modInverse(long n, long p)
{
return power(n, p - 2, p);
}
int[][] floydWarshall(int graph[][],int INF,int V)
{
int dist[][] = new int[V][V];
int i, j, k;
for (i = 0; i < V; i++)
for (j = 0; j < V; j++)
dist[i][j] = graph[i][j];
for (k = 0; k < V; k++)
{
for (i = 0; i < V; i++)
{
for (j = 0; j < V; j++)
{
if (dist[i][k] + dist[k][j] < dist[i][j])
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}return dist;
}
class minque {
Deque<Long> q;
minque(){
q=new ArrayDeque<Long>();
}public void add(long p){
while(!q.isEmpty()&&q.peekLast()>p)q.pollLast();
q.addLast(p);
}public void remove(long p) {
if(!q.isEmpty()&&q.getFirst()==p)q.removeFirst();
}public long min() {
return q.getFirst();
}
}
int find(subset[] subsets, int i)
{
if (subsets[i].parent != i)
subsets[i].parent
= find(subsets, subsets[i].parent);
return subsets[i].parent;
}void Union(subset[] subsets, int x, int y)
{
int xroot = find(subsets, x);
int yroot = find(subsets, y);
if (subsets[xroot].rank < subsets[yroot].rank) {
subsets[xroot].parent = yroot;
}
else if (subsets[yroot].rank < subsets[xroot].rank) {
subsets[yroot].parent = xroot;
}
else {
subsets[xroot].parent = yroot;
subsets[yroot].rank++;
}
}class subset
{
int parent;
int rank;
}
}
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.StringTokenizer;
public class D {
static class Pair{
int val;
char c;
Pair(int a,char b){
this.val=a;
this.c=b;
}
}
public static void main(String[] args)
{
FastScanner sc=new FastScanner();
int t=sc.nextInt();
PrintWriter pw=new PrintWriter(System.out);
while(t-->0) {
int n=sc.nextInt();
int[] a=sc.readArray(n);
char[] s=sc.next().toCharArray();
boolean ok=true;
ArrayList<Integer> blues=new ArrayList<>();
ArrayList<Integer> reds=new ArrayList<>();
for(int i=0;i<n;i++){
if(s[i]=='B'){
blues.add(a[i]);
} else {
reds.add(a[i]);
}
}
Collections.sort(blues);
Collections.sort(reds);
for(int i=0;i<blues.size();i++){
if(blues.get(i)<(i+1)){
ok=false;
break;
}
}
int start=blues.size()+1;
for(int i=0;i<reds.size();i++){
if(reds.get(i)>(start++)){
ok=false;
break;
}
}
if(ok){
pw.println("YES");
} else {
pw.println("NO");
}
}
pw.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[] 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());
}
}
}
| 0 |
Non-plagiarised
|
3ef54b1a
|
bac616ee
|
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
FastIO fio = new FastIO();
int t = fio.nextInt();
for (int i = 0; i < t; i++) {
int n = fio.nextInt();
ArrayList<ArrayList<Tuple>> adjList = new ArrayList<>();
for (int j = 0; j < n; j++) {
adjList.add(new ArrayList<>());
}
for (int j = 0; j < n - 1; j++) {
int u = fio.nextInt() - 1;
int v = fio.nextInt() - 1;
adjList.get(u).add(new Tuple(v, j));
adjList.get(v).add(new Tuple(u, j));
}
boolean possible = true;
for (ArrayList<Tuple> neighbours : adjList) {
if (neighbours.size() > 2) {
possible = false;
break;
}
}
if (!possible) {
fio.println(-1);
continue;
}
int[] assignments = new int[n - 1];
boolean[] visited = new boolean[n];
visited[0] = true;
Queue<Integer> queue = new LinkedList<>();
queue.offer(0);
while (!queue.isEmpty()) {
int u = queue.poll();
List<Tuple> neighbors = adjList.get(u);
for (int j = 0; j < neighbors.size(); j++) {
Tuple tt = neighbors.get(j);
int pi = j;
if (neighbors.size() == 2 && visited[neighbors.get(1 - j).v]) {
pi = 1 - assignments[neighbors.get(1 - j).num];
}
if (!visited[tt.v]) {
assignments[tt.num] = pi;
visited[tt.v] = true;
queue.offer(tt.v);
}
}
}
for (int j = 0; j < n - 1; j++) {
if (j > 0) {
fio.print(" ");
}
fio.print(assignments[j] == 0 ? 2 : 3);
}
fio.println();
}
fio.close();
}
}
class Tuple {
int v, num;
Tuple(int v, int num) {
this.v = v;
this.num = num;
}
}
class State {
int u;
int i;
State(int u, int i) {
this.u = u;
this.i = i;
}
}
/**
* Fast I/O
* @source https://www.geeksforgeeks.org/fast-io-in-java-in-competitive-programming/
*/
class FastIO extends PrintWriter
{
BufferedReader br;
StringTokenizer st;
public FastIO()
{
super(new BufferedOutputStream(System.out));
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;
}
}
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class NotAssigning {
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;
}
}
static class Pair {
int a, b;
public Pair(int a, int b) {
this.a = a;
this.b = b;
}
}
static boolean vis[];
public static void dfs(ArrayList<ArrayList<Pair>> t, int cur, boolean mode, int[] w) {
vis[cur] = true;
for (Pair p : t.get(cur)) {
if (!vis[p.a]) {
if (mode) {
w[p.b] = 3;
}
else {
w[p.b] = 2;
}
dfs(t, p.a, !mode, w);
}
}
}
public static void solve(int n, int[] u, int[] v) {
ArrayList<ArrayList<Pair>> t = new ArrayList<ArrayList<Pair>>(n);
for (int i=0; i<n; i++) {
t.add(new ArrayList<Pair>());
}
for (int i=0; i<n-1; i++) {
t.get(u[i]).add(new Pair(v[i], i));
t.get(v[i]).add(new Pair(u[i], i));
}
int start = 0;
for (int i=0; i<n; i++) {
if (t.get(i).size() > 2) {
System.out.println("-1");
return;
}
if (t.get(i).size() == 1) {
start = i;
}
}
vis = new boolean[n];
int[] w = new int[n-1];
dfs(t, start, false, w);
StringBuilder ans = new StringBuilder();
for (int i=0; i<n-1; i++) {
ans.append(w[i]).append(" ");
}
System.out.println(ans);
}
public static void main(String[] args) {
FastReader in = new FastReader();
int t = in.nextInt();
while (t-- > 0) {
int n = in.nextInt();
int[] u = new int[n-1];
int[] v = new int[n-1];
for (int i=0; i<n-1; i++) {
u[i] = in.nextInt()-1;
v[i] = in.nextInt()-1;
}
solve(n, u, v);
}
}
}
| 0 |
Non-plagiarised
|
2bbf754b
|
d9199dfd
|
import java.util.*;
/**
__ __
( _) ( _)
/ / \\ / /\_\_
/ / \\ / / | \ \
/ / \\ / / |\ \ \
/ / , \ , / / /| \ \
/ / |\_ /| / / / \ \_\
/ / |\/ _ '_| \ / / / \ \\
| / |/ 0 \0\ / | | \ \\
| |\| \_\_ / / | \ \\
| | |/ \.\ o\o) / \ | \\
\ | /\\`v-v / | | \\
| \/ /_| \\_| / | | \ \\
| | /__/_ `-` / _____ | | \ \\
\| [__] \_/ |_________ \ | \ ()
/ [___] ( \ \ |\ | | //
| [___] |\| \| / |/
/| [____] \ |/\ / / ||
( \ [____ / ) _\ \ \ \| | ||
\ \ [_____| / / __/ \ / / //
| \ [_____/ / / \ | \/ //
| / '----| /=\____ _/ | / //
__ / / | / ___/ _/\ \ | ||
(/-(/-\) / \ (/\/\)/ | / | /
(/\/\) / / //
_________/ / /
\____________/ (
*/
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-- >0) {
int n=sc.nextInt();
int[] arr=new int[n];
for(int i=0;i<n;i++) {
arr[i]=sc.nextInt();
}
String str=sc.next();
ArrayList<Pair> plist=new ArrayList<>();
for(int i=0;i<n;i++) {
char ch=str.charAt(i);
plist.add(new Pair(arr[i],ch));
}
//B-reduce
//R-increse
Collections.sort(plist);
int counter=1;
boolean flag=false;
for(int i=0;i<plist.size();i++) {
int val=plist.get(i).number;
int clr=plist.get(i).color;
if(clr=='B') {
if(val<counter) {
flag=true;
break;
}
}
else {
if(val>counter) {
flag=true;
break;
}
}
counter++;
}
System.out.println(flag?"NO":"YES");
}
}
public static class Pair implements Comparable<Pair>{
int number;
char color;
Pair(int number,char color){
this.number=number;
this.color=color;
}
@Override
public int compareTo(Pair o) {
if(o.color==this.color) {
return this.number-o.number;
}
else {
return this.color-o.color;
}
}
public String toString() {
return number+"-"+color+".";
}
}
}
|
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Scanner;
public class Simple{
public static void main(String args[]){
//System.out.println("Hello Java");
Scanner s = new Scanner(System.in);
int t = s.nextInt();
while (t>0){
int n = s.nextInt();
int arr[] = new int[n];
for(int i=0;i<n;i++){
arr[i] = s.nextInt();
}
String str = s.next();
//Arrays.sort(arr);
ArrayList<Integer> blue = new ArrayList<>();
ArrayList<Integer> red = new ArrayList<>();
for(int i=0;i<n;i++){
if(str.charAt(i)=='R'){
red.add(arr[i]);
}
else{
blue.add(arr[i]);
}
}
Collections.sort(red);
Collections.sort(blue);
int start =1;
boolean bool =true;
for(int i=0;i<blue.size();i++){
if(blue.get(i)<start){
bool = false;
break;
}
start++;
}
if(!bool){
System.out.println("NO");
}
else{
for(int i=0;i<red.size();i++){
if(red.get(i)>start){
bool = false;
break;
}
start++;
}
if(bool){
System.out.println("YES");
}
else{
System.out.println("NO");
}
}
t--;
}
s.close();
}
}
| 0 |
Non-plagiarised
|
808f7516
|
9ebe348d
|
import java.util.*;
import java.io.*;
public class EdD {
public static void main(String[] args) throws Exception{
int num = 998244353;
// TODO Auto-generated method stub
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
// String input1 = bf.readLine().trim();
// String input2 = bf.readLine().trim();
int n = Integer.parseInt(bf.readLine());
int[] array = new int[n];
StringTokenizer st = new StringTokenizer(bf.readLine());
for(int j = 0;j<n;j++){
array[j] = Integer.parseInt(st.nextToken());
}
Map<Integer, Set<Integer>> mp = new HashMap<Integer, Set<Integer>>();
for(int j =0;j<n;j++)
mp.put(j, new HashSet<Integer>());
int[] nextge = new int[n];
int[] nextle = new int[n];
int[] prevge = new int[n];
int[] prevle = new int[n];
nextge[n-1] = -1;
nextle[n-1] = -1;
prevge[0] = -1;
prevle[0] = -1;
for(int j = n-2;j>=0;j--){
if (array[j+1] < array[j]){
nextle[j] = j+1;
mp.get(j).add(j+1);
int temp = j+1;
while(temp!= -1 && array[temp] < array[j])
temp = nextge[temp];
nextge[j] = temp;
if (temp!= -1)
mp.get(j).add(temp);
}
else if (array[j+1] > array[j]){
nextge[j] = j+1;
mp.get(j).add(j+1);
int temp = j+1;
while(temp!= -1 && array[temp] > array[j])
temp = nextle[temp];
nextle[j] = temp;
if (temp!= -1)
mp.get(j).add(temp);
}
else{
nextge[j] = j+1;
mp.get(j).add(j+1);
nextle[j] = j+1;
mp.get(j).add(j+1);
}
}
for(int j = 1;j<n;j++){
if (array[j] < array[j-1]){
prevge[j] = j-1;
mp.get(j-1).add(j);
int temp = j-1;
while(temp!= -1 && array[temp] > array[j])
temp = prevle[temp];
prevle[j] = temp;
if (temp!= -1)
mp.get(temp).add(j);
}
else if (array[j] > array[j-1]){
prevle[j] = j-1;
mp.get(j-1).add(j);
int temp = j-1;
while(temp!= -1 && array[temp] < array[j])
temp = prevge[temp];
prevge[j] = temp;
if (temp!= -1)
mp.get(temp).add(j);
}
else{
prevge[j] = j-1;
prevle[j] = j-1;
mp.get(j-1).add(j);
}
}
int[] depth = new int[n+1];
Set<Integer> seen = new HashSet<Integer>();
Queue<Integer> bfs = new LinkedList<Integer>();
bfs.add(0);
seen.add(0);
while(!bfs.isEmpty()){
int v = bfs.remove();
for(int child : mp.get(v)){
if (!seen.contains(child)){
bfs.add(child);
seen.add(child);
depth[child] = depth[v]+1;
}
}
}
out.println(depth[n-1]);
out.close();
}
}
//StringJoiner sj = new StringJoiner(" ");
//sj.add(strings)
//sj.toString() gives string of those stuff w spaces or whatever that sequence is
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.TreeSet;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int N = in.nextInt();
int[] h = new int[N];
int[] hsort = new int[N];
HashMap<Integer, Integer> condense = new HashMap<>();
for (int i = 0; i < N; i++) {
h[i] = in.nextInt();
hsort[i] = h[i];
}
ArrayUtils.sort(hsort);
int timer = 0;
int[] t = new int[N];
for (int i = 0; i < N; i++) {
if (!condense.containsKey(hsort[i])) {
condense.put(hsort[i], timer++);
t[timer - 1]++;
} else {
t[condense.get(hsort[i])]++;
}
}
int[][] heights = new int[timer][];
for (int i = 0; i < timer; i++) {
heights[i] = new int[t[i]];
t[i] = 0;
}
for (int i = 0; i < N; i++) {
h[i] = condense.get(h[i]);
heights[h[i]][t[h[i]]++] = i;
}
TreeSet<Integer> cur = new TreeSet<>();
ArrayList<Integer>[] to = new ArrayList[N];
for (int i = 0; i < N; i++) {
to[i] = new ArrayList<>();
if (i != N - 1) {
to[i].add(i + 1);
}
}
int low = N + 1;
int high = -1;
for (int i = 0; i < timer; i++) {
for (int e : heights[i]) {
cur.add(e);
low = Math.min(low, e);
high = Math.max(high, e);
}
for (int e : heights[i]) {
if (low < e) {
to[cur.lower(e)].add(e);
}
if (high > e) {
to[e].add(cur.higher(e));
}
}
}
cur.clear();
low = N + 1;
high = -1;
for (int i = timer - 1; i >= 0; i--) {
for (int e : heights[i]) {
cur.add(e);
low = Math.min(low, e);
high = Math.max(high, e);
}
for (int e : heights[i]) {
if (low < e) {
to[cur.lower(e)].add(e);
}
if (high > e) {
to[e].add(cur.higher(e));
}
}
}
long[] dp = new long[N];
Arrays.fill(dp, (int) (1e8));
dp[0] = 0;
for (int i = 0; i < N; i++) {
for (int toa : to[i]) {
dp[toa] = Math.min(dp[toa], dp[i] + 1);
}
}
out.println(dp[N - 1]);
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
static class ArrayUtils {
public static void shuffle(int[] arr) {
for (int i = 0; i < arr.length; i++) {
int rand = (int) (Math.random() * (i + 1));
swap(arr, i, rand);
}
}
public static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static void sort(int[] arr) {
shuffle(arr);
Arrays.sort(arr);
//get rid of quicksort cases
}
}
}
| 0 |
Non-plagiarised
|
3d06b643
|
db7f80a5
|
import java.io.*;
import java.util.*;
public class ArmChairs {
public static int solution(int n, int[] arr) {
ArrayList<Integer> one = new ArrayList<Integer>();
ArrayList<Integer> zero = new ArrayList<Integer>();
for (int i = 0; i < n; i++) {
if (arr[i] == 1) {
one.add(i);
} else {
zero.add(i);
}
}
int[][] dp = new int[one.size() + 1][zero.size() + 1];
for (int i = 1; i <= one.size(); i++) {
dp[i][i] = dp[i - 1][i - 1] + Math.abs(one.get(i - 1) - zero.get(i - 1));
for (int j = i + 1; j <= zero.size(); j++) {
dp[i][j] = Math.min(dp[i][j - 1], dp[i - 1][j - 1] + Math.abs(one.get(i - 1) - zero.get(j - 1)));
}
}
return dp[one.size()][zero.size()];
}
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out));
int n = Integer.parseInt(br.readLine());
String[] s = br.readLine().split(" ");
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(s[i]);
}
log.write(Integer.toString(solution(n, arr)) + "\n");
log.flush();
}
}
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class CodeForces {
public static void main(String[] args) throws IOException {
reader input = new reader();
PrintWriter output = new PrintWriter(System.out);
//BufferedReader bf = new BufferedReader(new FileReader("input.txt"));
//PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
//StringTokenizer stk = new StringTokenizer(bf.readLine());
//int n=Integer.parseInt(stk.nextToken());
int n=input.nextInt();
ArrayList<Integer>seated=new ArrayList<>();
ArrayList<Integer>empty=new ArrayList<>();
for(int i=0;i<n;i++){
int x=input.nextInt();
if(x==1)
seated.add(i);
else
empty.add(i);
}
if(seated.size()==0)
output.println(0);
else{
output.println(helper(seated,empty));
}
output.close();
}
public static long helper(ArrayList<Integer>seated,ArrayList<Integer>empty){
long dp[][]=new long[seated.size()+1][empty.size()+1];
for(int i=1;i<= seated.size();i++){
dp[i][i]=dp[i-1][i-1]+Math.abs(seated.get(i-1)-empty.get(i-1));
for(int j=i+1;j<= empty.size();j++){
dp[i][j]=Math.min(dp[i][j-1],dp[i-1][j-1]+Math.abs(seated.get(i-1)-empty.get(j-1)));
}
}
return dp[seated.size()][empty.size()];
}
public static int GCD(int a,int b){
if(a==0)
return b;
else
return GCD(b%a,a);
}
public static boolean isPrime(long num){
if(num==1)
return false;
else if(num==2||num==3)
return true;
else if(num%2==0||num%3==0)
return false;
else{
for(long i=5;i*i<=num;i+=6){
if(num%i==0||num%(i+2)==0)
return false;
}
}
return true;
}
public static void mergesort(long arr[],int start,int end){//start and end must be indexes
if(start<end) {
int mid=(start+end)/2;
mergesort(arr,start,mid);
mergesort(arr, mid+1, end);
merge(arr, start,mid,end);
}
}
public static void merge(long arr[],int start,int mid,int end){
int lsize=mid-start+1,rsize=end-mid;
long l[]=new long[lsize],r[]=new long[rsize];
for(int i=start;i<=mid;i++){
l[i-start]=arr[i];
}
for(int i=mid+1;i<=end;i++){
r[i-mid-1]=arr[i];
}
int i=0,j=0,k=start;
while(i<lsize&&j<rsize){
if(l[i]<=r[j]){
arr[k++]=l[i++];
}else{
arr[k++]=r[j++];
}
}
while(i<lsize)
arr[k++]=l[i++];
while(j<rsize)
arr[k++]=r[j++];
}
}
class Pair{
int a,b;
Pair(int a,int b){
this.a=a;
this.b=b;
}
}
class Edge{
int src,dest,weight;
Edge(int src,int dest,int weight){
this.src=src;
this.dest=dest;
this.weight=weight;
}
}
class TempEdge{
int vertex;
long distance;
TempEdge(int vertex,long distance){
this.vertex=vertex;
this.distance=distance;
}
}
//Undirected Graph
class UGraph{
ArrayList<ArrayList<Edge>>graph;
int vertex;
UGraph(int vertex){
this.vertex=vertex;
graph=new ArrayList<>();
for(int i=0;i<vertex;i++){
graph.add(new ArrayList<>());
}
}
void addEdge(int u,int v){
graph.get(u).add(new Edge(u,v,0));
graph.get(v).add(new Edge(v,u,0));
}
void addEdge(int u,int v,int weight){
graph.get(u).add(new Edge(u,v,weight));
graph.get(v).add(new Edge(v,u,weight));
}
ArrayList<Integer> BFS(int source){
boolean visited[]=new boolean[vertex];
ArrayList<Integer>ans=new ArrayList<>();
LinkedList<Integer>q=new LinkedList<>();
q.add(source);
visited[source]=true;
while(!q.isEmpty()){
int x=q.removeFirst();
ans.add(x);
for(Edge i:graph.get(x)){
if(!visited[i.dest]){
q.add(i.dest);
visited[i.dest]=true;
}
}
}
return ans;
}
ArrayList<Integer> BFS(){//O(V+E)
boolean visited[]=new boolean[vertex];
ArrayList<Integer>ans=new ArrayList<>();
for(int i=0;i<vertex;i++){
if(!visited[i]){
ArrayList<Integer>temp=BFS(i);
for(int j:temp)
ans.add(j);
}
}
return ans;
}
int connectedComponentsBFS(){
boolean visited[]=new boolean[vertex];
int count=0;
for(int i=0;i<vertex;i++){
if(!visited[i]){
count++;
BFS(i);
}
}
return count;
}
void DFS(int source){
boolean visited[]=new boolean[vertex];
DFSHelper(source,visited);
System.out.println();
}
void DFS(){//O(V+E)
boolean visited[]=new boolean[vertex];
for(int i=0;i<vertex;i++){
if(!visited[i]){
DFSHelper(i,visited);
System.out.println();
}
}
}
void DFSHelper(int source,boolean visited[]){
visited[source]=true;
System.out.print(source+" ");
for(Edge i:graph.get(source)){
if(!visited[i.dest]){
DFSHelper(i.dest,visited);
}
}
}
boolean detectCycleDFS(){//O(V+E)
boolean visited[]=new boolean[vertex];
for (int i=0;i<vertex;i++){
if(!visited[i]){
if(detectCycleDFSHelper(i,-1,visited))
return true;
}
}
return false;
}
boolean detectCycleDFSHelper(int source,int parent,boolean visited[]){
visited[source]=true;
for(Edge i:graph.get(source)){
if(!visited[i.dest]){
if(detectCycleDFSHelper(i.dest,source,visited))
return true;
}
if(i.dest!=parent)
return true;
}
return false;
}
boolean detectCycleBFS(){//O(V+E)
boolean visited[]=new boolean[vertex];
for (int i=0;i<vertex;i++){
if(!visited[i]){
if(detectCycleBFSHelper(i,visited))
return true;
}
}
return false;
}
boolean detectCycleBFSHelper(int source,boolean visited[]){
int parent[]=new int[vertex];
Arrays.fill(parent,-1);
LinkedList<Integer>q=new LinkedList<>();
q.add(source);
visited[source]=true;
while(!q.isEmpty()){
int x=q.removeFirst();
for(Edge i:graph.get(x)){
if(!visited[i.dest]){
q.add(i.dest);
visited[i.dest]=true;
parent[i.dest]=x;
}
else{
if(parent[x]!=i.dest)
return true;
}
}
}
return false;
}
int primsMST(){
boolean MST[]=new boolean[vertex];
TempEdge distarr[]=new TempEdge[vertex];//MST edge stores least distance of a vertex to the MST
for(int i=0;i<vertex;i++) {
distarr[i] = new TempEdge(i, Integer.MAX_VALUE);
}
distarr[0].distance=0;
// Use TreeSet instead of PriorityQueue as the remove function of the PQ is O(n) in java
TreeSet<TempEdge>q=new TreeSet<>((a,b)->(int)(a.distance-b.distance));
for(int i=0;i<vertex;i++) {
q.add(distarr[i]);
}
int ans=0;
while(!q.isEmpty()){
TempEdge x=q.pollFirst();
ans+=x.distance;
MST[x.vertex]=true;//Adding in MST
for(Edge i:graph.get(x.vertex)){
if(!MST[i.dest]){//Vertex not present in MST
if(distarr[i.dest].distance>i.weight){//Updating smallest distance from MST vertices to i.dest
q.remove(distarr[i.dest]);
distarr[i.dest].distance=i.weight;
q.add(distarr[i.dest]);
}
}
}
}
return ans;
}
long [] dikstra(int source){
long ans[]=new long[vertex];
boolean visited[]=new boolean[vertex];
Arrays.fill(ans,Integer.MAX_VALUE);
ans[source]=0;
//TreeSet may be used as done in prims if removal is required
PriorityQueue<TempEdge>pq=new PriorityQueue<>((a,b)-> (int) (a.distance-b.distance));
int count=0;
pq.add(new TempEdge(source,ans[source]));
while(count!=vertex-1){//On doing vertex-1 times, last vertex is automatically finalised
TempEdge x= pq.poll();
if(!visited[x.vertex]){
visited[x.vertex]=true;
count++;
for(Edge i:graph.get(x.vertex)){
/*Checking visited is not necessary as the won't affect the distance in any case
but will affect the heap*/
if(!visited[i.dest] && ans[i.dest]>ans[x.vertex]+i.weight){
ans[i.dest]=ans[x.vertex]+i.weight;
pq.add(new TempEdge(i.dest,ans[i.dest]));
}
}
}
}
return ans;
}
long[] bellmanford(int source){
long ans[]=new long[vertex];
ans[source]=0;
for(int i=0;i<vertex-1;i++){//Considering paths of length 1 to paths of length (v-1) from source
for(int j=0;j<vertex;j++){
for(Edge k:graph.get(j)){
if(ans[k.dest]>ans[k.src]+ans[k.weight])
ans[k.dest]=ans[k.src]+ans[k.weight];
}
}
}
return ans;
}
}
//Directed non-weighted Graph
class DGraph{
ArrayList<ArrayList<Edge>>graph;
int vertex;
DGraph(int vertex){
this.vertex=vertex;
graph=new ArrayList<>();
for(int i=0;i<vertex;i++){
graph.add(new ArrayList<>());
}
}
void addEdge(int src,int dest){
graph.get(src).add(new Edge(src,dest,0));
}
void addEdge(int src,int dest,int weight){
graph.get(src).add(new Edge(src,dest,weight));
}
boolean detectCycleDFS(){
boolean visited[]=new boolean[vertex];
boolean recst[]=new boolean[vertex];
for(int i=0;i<vertex;i++){
if(!visited[i]){
if(detectCycleDFSHelper(i,visited,recst))
return true;
}
}
return false;
}
boolean detectCycleDFSHelper(int index,boolean visited[],boolean recst[]){
visited[index]=true;
recst[index]=true;
for(Edge i:graph.get(index)){
if(!visited[i.dest]){
if(detectCycleDFSHelper(i.dest,visited,recst))
return true;
}else{
if(recst[i.dest])//Back edge present
return true;
}
}
recst[index]=false;
return false;
}
ArrayList<Integer> topologicalSortingBFS(){//Kahn's Algorithm which is valid only for directed acyclic graphs
ArrayList<Integer>ans=new ArrayList<>();
int indegree[]=new int[vertex];
for(int i=0;i<vertex;i++){
for(Edge j:graph.get(i)){
indegree[j.dest]++;
}
}
LinkedList<Integer>q=new LinkedList<>();
for(int i=0;i<vertex;i++){
if(indegree[i]==0)
q.add(i);
}
while(!q.isEmpty()){
int i=q.removeFirst();
ans.add(i);
for(Edge x:graph.get(i)){
if(--indegree[x.dest]==0){
q.add(x.dest);
}
}
}
return ans;
}
boolean detectCycleTopologicalSort(){
int count=0;
int indegree[]=new int[vertex];
for(int i=0;i<vertex;i++){
for(Edge j:graph.get(i)){
indegree[j.dest]++;
}
}
LinkedList<Integer>q=new LinkedList<>();
for(int i=0;i<vertex;i++){
if(indegree[i]==0)
q.add(i);
}
while(!q.isEmpty()){
int i=q.removeFirst();
count++;
for(Edge x:graph.get(i)){
if(--indegree[x.dest]==0){
q.add(x.dest);
}
}
}
return (count!=vertex);
}
ArrayList<Integer> topologicalSortingDFS(){
boolean visited[]=new boolean[vertex];
ArrayDeque<Integer>recst=new ArrayDeque<>();
for(int i=0;i<vertex;i++){
if(!visited[i]){
topologicalSortingDFSHelper(i,visited,recst);
}
}
ArrayList<Integer>ans=new ArrayList<>();
while(!recst.isEmpty())
ans.add(recst.pop());
return ans;
}
void topologicalSortingDFSHelper(int index,boolean visited[],ArrayDeque<Integer>recst){
visited[index]=true;
for(Edge i:graph.get(index)){
if(!visited[i.dest])
topologicalSortingDFSHelper(i.dest,visited,recst);
}
recst.push(index);
}
ArrayList<ArrayList<Integer>> stronglyConnectedComponentsKosaraju(){
ArrayList<Integer>sortedbyendtime=topologicalSortingDFS();
ArrayList<ArrayList<Edge>>transposegraph=new ArrayList<>();
for(int i=0;i<vertex;i++){
transposegraph.add(new ArrayList<>());
}
for(int i=0;i<vertex;i++){
for(Edge j:graph.get(i)){
transposegraph.get(j.dest).add(new Edge(j.dest,j.src, j.weight));
}
}
ArrayList<ArrayList<Integer>>ans=new ArrayList<>();
boolean visited[]=new boolean[vertex];
for(int i:sortedbyendtime){
if(!visited[i]){
ArrayList<Integer>curr=DFSTopologicalSort(i,transposegraph,visited);
ans.add(curr);
}
}
return ans;
}
ArrayList<Integer> DFSTopologicalSort(int source,ArrayList<ArrayList<Edge>>graph,boolean visited[]){
ArrayList<Integer> ans=new ArrayList<>();
DFSTopologicalSortHelper(source,graph,visited,ans);
return ans;
}
void DFSTopologicalSortHelper(int source,ArrayList<ArrayList<Edge>>graph,boolean visited[],ArrayList<Integer> ans) {
visited[source]=true;
ans.add(source);
for(Edge i:graph.get(source)){
if(!visited[i.dest])
DFSTopologicalSortHelper(i.dest,graph,visited,ans);
}
}
long[] bellmanford(int source){
long ans[]=new long[vertex];
ans[source]=0;
for(int i=0;i<vertex-1;i++){//Considering paths of length 1 to paths of length (v-1) from source
for(int j=0;j<vertex;j++){
for(Edge k:graph.get(j)){
if(ans[k.dest]>ans[k.src]+ans[k.weight])
ans[k.dest]=ans[k.src]+ans[k.weight];
}
}
}
return ans;
}
}
class reader {
BufferedReader br;
StringTokenizer st;
public reader() {
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
public int[] nextIntArray(int arraySize) {
int array[] = new int[arraySize];
for (int i = 0; i < arraySize; i++) {
array[i] = nextInt();
}
return array;
}
public long[] nextLongArray(int arraySize) {
long array[] = new long[arraySize];
for (int i = 0; i < arraySize; i++) {
array[i] = nextLong();
}
return array;
}
}
| 1 |
Plagiarised
|
34b9ed7f
|
8311f375
|
import java.io.*;
import java.util.*;
public class q3 {
public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// public static long mod = 1000000007;
public static void solve() throws Exception {
String[] parts = br.readLine().split(" ");
int n = Integer.parseInt(parts[0]);
int[] arr = new int[n + 1];
boolean[] vis = new boolean[n + 1];
for(int i = 1;i <= n;i++){
if(vis[i]) continue;
ArrayList<Integer> list = new ArrayList<>();
while(true){
System.out.println("? " + i);
int val = Integer.parseInt(br.readLine());
vis[val] = true;
list.add(val);
if(list.size() > 1 && val == list.get(0)) break;
}
for(int j = 0;j < list.size() - 1;j++) arr[list.get(j)] = list.get(j + 1);
// arr[list.get(list.size() - 1)] = list.get(0);
}
System.out.print("! ");
StringBuilder ans = new StringBuilder();
for(int i = 1;i <= n;i++) ans.append(arr[i]).append(" ");
System.out.println(ans);
}
public static void main(String[] args) throws Exception {
int tests = Integer.parseInt(br.readLine());
for (int test = 1; test <= tests; test++) {
solve();
}
}
// public static ArrayList<Integer> primes;
// public static void seive(int n){
// primes = new ArrayList<>();
// boolean[] arr = new boolean[n + 1];
// Arrays.fill(arr,true);
//
// for(int i = 2;i * i <= n;i++){
// if(arr[i]) {
// for (int j = i * i; j <= n; j += i) {
// arr[j] = false;
// }
// }
// }
// for(int i = 2;i <= n;i++) if(arr[i]) primes.add(i);
// }
// public static void sort(int[] arr){
// ArrayList<Integer> temp = new ArrayList<>();
// for(int val : arr) temp.add(val);
//
// Collections.sort(temp);
//
// for(int i = 0;i < arr.length;i++) arr[i] = temp.get(i);
// }
// public static void sort(long[] arr){
// ArrayList<Long> temp = new ArrayList<>();
// for(long val : arr) temp.add(val);
//
// Collections.sort(temp);
//
// for(int i = 0;i < arr.length;i++) arr[i] = temp.get(i);
// }
//
// public static long power(long a,long b,long mod){
// if(b == 0) return 1;
//
// long p = power(a,b / 2,mod);
// p = (p * p) % mod;
//
// if(b % 2 == 1) return (p * a) % mod;
// return p;
// }
// public static long modDivide(long a,long b,long mod){
// return ((a % mod) * (power(b,mod - 2,mod) % mod)) % mod;
// }
//
// public static int GCD(int a,int b){
// return b == 0 ? a : GCD(b,a % b);
// }
// public static long GCD(long a,long b){
// return b == 0 ? a : GCD(b,a % b);
// }
//
// public static int LCM(int a,int b){
// return a * b / GCD(a,b);
// }
// public static long LCM(long a,long b){
// return a * b / GCD(a,b);
// }
}
|
import java.io.*;
import java.util.*;
public class q3 {
public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// public static long mod = 1000000007;
public static void solve() throws Exception {
String[] parts = br.readLine().split(" ");
int n = Integer.parseInt(parts[0]);
int[] arr = new int[n + 1];
boolean[] vis = new boolean[n + 1];
for(int i = 1;i <= n;i++){
if(vis[i]) continue;
ArrayList<Integer> list = new ArrayList<>();
while(true){
System.out.println("? " + i);
int val = Integer.parseInt(br.readLine());
vis[val] = true;
list.add(val);
if(list.size() > 1 && val == list.get(0)) break;
}
for(int j = 0;j < list.size() - 1;j++) arr[list.get(j)] = list.get(j + 1);
}
System.out.print("! ");
StringBuilder ans = new StringBuilder();
for(int i = 1;i <= n;i++) ans.append(arr[i]).append(" ");
System.out.println(ans);
}
public static void main(String[] args) throws Exception {
int tests = Integer.parseInt(br.readLine());
for (int test = 1; test <= tests; test++) {
solve();
}
}
}
| 1 |
Plagiarised
|
45f5632f
|
5dc1f7b3
|
import java.io.*;
import java.util.*;
public class A{
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Task solver = new Task();
solver.solve(in, out);
out.close();
}
// main solver
static class Task{
double eps= 0.00000001;
static final int MAXN = 10000001;
// stores smallest prime factor for every number
static int spf[] = new int[MAXN];
Map<Integer,Set<Integer>> dp= new HashMap<>();
// Calculating SPF (Smallest Prime Factor) for every
// number till MAXN.
// Time Complexity : O(nloglogn)
public void sieve()
{
spf[1] = 1;
for (int i=2; i<MAXN; i++)
// marking smallest prime factor for every
// number to be itself.
spf[i] = i;
// separately marking spf for every even
// number as 2
for (int i=4; i<MAXN; i+=2)
spf[i] = 2;
for (int i=3; i*i<MAXN; i++)
{
// checking if i is prime
if (spf[i] == i)
{
// marking SPF for all numbers divisible by i
for (int j=i*i; j<MAXN; j+=i)
// marking spf[j] if it is not
// previously marked
if (spf[j]==j)
spf[j] = i;
}
}
}
// A O(log n) function returning primefactorization
// by dividing by smallest prime factor at every step
public Set<Integer> getFactorization(int x)
{
if(dp.containsKey(x)) return dp.get(x);
Set<Integer> ret = new HashSet<>();
while (x != 1)
{
if(spf[x]!=2) ret.add(spf[x]);
x = x / spf[x];
}
dp.put(x,ret);
return ret;
}
// function to find first index >= x
public int lowerIndex(List<Integer> arr, int n, int x)
{
int l = 0, h = n - 1;
while (l <= h)
{
int mid = (l + h) / 2;
if (arr.get(mid) >= x)
h = mid - 1;
else
l = mid + 1;
}
return l;
}
// function to find last index <= y
public int upperIndex(List<Integer> arr, int n, int y)
{
int l = 0, h = n - 1;
while (l <= h)
{
int mid = (l + h) / 2;
if (arr.get(mid) <= y)
l = mid + 1;
else
h = mid - 1;
}
return h;
}
// function to count elements within given range
public int countInRange(List<Integer> arr, int n, int x, int y)
{
// initialize result
int count = 0;
count = upperIndex(arr, n, y) -
lowerIndex(arr, n, x) + 1;
return count;
}
ArrayList<Integer>A = new ArrayList<>();
ArrayList<Integer>B = new ArrayList<>();
ArrayList<List<Integer>> L = new ArrayList<List<Integer>>();
public void solve(InputReader in, PrintWriter out) {
int n= in.nextInt();
int[] A= new int[n];
final int INF= 1000000000;
List<Integer> pos= new ArrayList<>();
for (int i = 0; i < n; i++){
A[i]= in.nextInt();
if (A[i] == 1) pos.add(i);
}
int cnt = pos.size();
int[][] dp= new int[cnt][n+1];
for(int[] temp: dp) Arrays.fill(temp,INF);
if (cnt == 0){
out.println(0);
return;
}
for (int i = n - 1; i >= 0; i--){
dp[cnt - 1][i] = dp[cnt - 1][i + 1];
if (A[i] != 1){
dp[cnt - 1][i] = Math.min(dp[cnt - 1][i], Math.abs(i - pos.get(pos.size()-1)));
}
}
for (int i = cnt - 2; i >= 0; i--){
for (int j = n - 1; j >= 0; j--){
dp[i][j] = dp[i][j + 1];
if (A[j] != 1){
dp[i][j] = Math.min(dp[i][j], Math.abs(j - pos.get(i)) + dp[i + 1][j + 1]);
}
}
}
out.println(dp[0][0]);
}
void backtrack(PrintWriter out, int i, List<Integer> considered, int used, int sum, int cur, int g){
if (used == considered.size()){
int percentage = (cur * 100) / sum;
if (percentage >= g){
considered.add(percentage);
L.add(considered);
}
return;
}
if (i == B.size()){
return;
}
for (int j = i; j < B.size(); j++){
List<Integer> au = new ArrayList<>(considered);
au.add(j + 1);
backtrack(out, j + 1, au, used, sum, cur + B.get(j), g);
}
}
public int _gcd(int a, int b)
{
if(b == 0) {
return a;
}
else {
return _gcd(b, a % b);
}
}
}
static class Tuple implements Comparable<Tuple>{
int x, y, z;
public Tuple(int x, int y, int z){
this.x= x;
this.y= y;
this.z=z;
}
@Override
public int compareTo(Tuple o){
return this.x-o.x;
}
}
static class Pair implements Comparable<Pair>{
public int x;
public int y;
public Pair(int x, int y){
this.x= x;
this.y= y;
}
@Override
public int compareTo(Pair o) {
return this.x-o.x;
}
}
// fast input reader class;
static class InputReader {
BufferedReader br;
StringTokenizer st;
public InputReader(InputStream stream) {
br = new BufferedReader(new InputStreamReader(stream));
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
String line = null;
try {
line = br.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
if (line == null) {
return null;
}
st = new StringTokenizer(line);
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public double nextDouble(){
return Double.parseDouble(nextToken());
}
public long nextLong(){
return Long.parseLong(nextToken());
}
}
}
|
import java.io.*;
import java.util.*;
public class D {
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 List<Integer> o1, o0;
static int[][] dp;
static int solve(int i, int j) {
if (i >= dp.length) return 0;
if (j >= dp[0].length) return Integer.MAX_VALUE/10;
if (dp[i][j] == -1) {
dp[i][j] = Integer.min(solve(i,j+1), solve(i+1,j+1) + Math.abs(o1.get(i)-o0.get(j)));
}
return dp[i][j];
}
public static void readInput() throws IOException {
// br = new BufferedReader(new FileReader(".in"));
// out = new PrintWriter(new FileWriter(".out"));
int n;
n = Integer.parseInt(br.readLine());
int[] a= new int[n];
StringTokenizer st = new StringTokenizer(br.readLine());
o1 = new ArrayList<Integer>();
o0 = new ArrayList<Integer>();
for (int i = 0; i < n; i++) {
a[i] = Integer.parseInt(st.nextToken());
if (a[i] == 1) o1.add(i);
else o0.add(i);
}
if (o1.size() == 0) {
out.println(0);
return;
}
dp = new int[o1.size()][o0.size()];
for (int[] x: dp) Arrays.fill(x, -1);
out.println(solve(0,0));
}
}
| 0 |
Non-plagiarised
|
54eb12ca
|
949502c2
|
import java.io.*;
import java.util.*;
public class huge implements Runnable
{
private boolean console=false;
ArrayList<Integer> adj[]; int maxi,maxc; int dis[];
int vis[];
Queue<Integer> q;
public void solve()
{
int i;
int n=in.ni(); maxi=0; maxc=0;
int a=in.ni()-1,b=in.ni()-1;
int da=in.ni(); int db=in.ni();
adj=new ArrayList[n];
for(i=0;i<n;i++)
adj[i]=new ArrayList();
for(i=0;i<n-1;i++)
{
int u=in.ni()-1; int v=in.ni()-1;
adj[u].add(v); adj[v].add(u);
}
maxc=maxi=0;
vis=new int[n]; int cur=-1; dfs(1,cur);
Arrays.fill(vis,0);
cur=-1; maxc=0; dfs(maxi,cur);
int d=(maxc);
int ans=1;
if(db<=2*da||2*da>=d||da>=db)
ans=0;
q= new LinkedList();
vis=new int[n];
q.add(a);
dis=new int[n];
dis[a]=0; int cu=0;
while(!q.isEmpty()||vis[b]==0)
{
int v=q.poll();
vis[v]=1;
bfs(v);
}
if(dis[b]<=da)
ans=0;
if(ans==1)
out.println("Bob");
else
out.println("Alice");
}
public void bfs(int v)
{
for(int node:adj[v])
{
if(vis[node]==0)
{
q.add(node);
dis[node]=dis[v]+1;
}
}
}
public void dfs(int v,int cur)
{
cur++;
if(cur>maxc)
{
maxc=cur; maxi=v;
}
vis[v]=1;
for(int node:adj[v])
{
if(vis[node]==0)
dfs(node,cur);
}
}
@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 huge().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();}
}
}
|
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import static java.lang.System.out;
import java.util.*;
import java.io.*;
import java.math.*;
public class Template {
static int mod = 1000000007;
public static void main(String[] args) {
FastScanner sc = new FastScanner();
int yo = sc.nextInt();
while (yo-- > 0) {
int n = sc.nextInt();
int a = sc.nextInt()-1;
int b = sc.nextInt()-1;
int da = sc.nextInt();
int db = sc.nextInt();
List<List<Integer>> list = new ArrayList<>();
for(int i = 0; i < n; i++) list.add(new ArrayList<>());
for(int i = 0; i < n-1; i++){
int x = sc.nextInt()-1;
int y = sc.nextInt()-1;
list.get(x).add(y);
list.get(y).add(x);
}
for(int i = 0; i <= n; i++) depth[i] = 0;
diam = 0;
dfs(a,-1,list);
if(2 * da >= min(diam, db) || depth[b] <= da){
out.println("Alice");
}
else {
out.println("Bob");
}
}
}
static int[] depth = new int[200001];
static int diam = 0;
static int dfs(int x, int p, List<List<Integer>> list) {
int len = 0;
List<Integer> ne = list.get(x);
for(int y : ne) {
if(y != p) {
depth[y] = depth[x] + 1;
int cur = 1 + dfs(y, x,list);
diam = max(diam, cur + len);
len = max(len, cur);
}
}
return len;
}
public static class Pair {
int x;
int y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
public static void sort(int[] arr) {
ArrayList<Integer> ls = new ArrayList<Integer>();
for (int x : arr)
ls.add(x);
Collections.sort(ls);
for (int i = 0; i < arr.length; i++)
arr[i] = ls.get(i);
}
public static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static boolean[] sieve(int N) {
boolean[] sieve = new boolean[N + 1];
for (int i = 2; i <= N; i++)
sieve[i] = true;
for (int i = 2; i <= N; i++) {
if (sieve[i]) {
for (int j = 2 * i; j <= N; j += i) {
sieve[j] = false;
}
}
}
return sieve;
}
public static long power(long x, long y, long p) {
long res = 1L;
x = x % p;
while (y > 0) {
if ((y & 1) == 1)
res = (res * x) % p;
y >>= 1;
x = (x * x) % p;
}
return res;
}
public static void print(int[] arr) {
//for debugging only
for (int x : arr)
out.print(x + " ");
out.println();
}
static class FastScanner {
private int BS = 1 << 16;
private char NC = (char) 0;
private byte[] buf = new byte[BS];
private int bId = 0, size = 0;
private char c = NC;
private double cnt = 1;
private BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
} catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
private char getChar() {
while (bId == size) {
try {
size = in.read(buf);
} catch (Exception e) {
return NC;
}
if (size == -1)
return NC;
bId = 0;
}
return (char) buf[bId++];
}
public int nextInt() {
return (int) nextLong();
}
public int[] readInts(int N) {
int[] res = new int[N];
for (int i = 0; i < N; i++) {
res[i] = (int) nextLong();
}
return res;
}
public long[] readLongs(int N) {
long[] res = new long[N];
for (int i = 0; i < N; i++) {
res[i] = nextLong();
}
return res;
}
public long nextLong() {
cnt = 1;
boolean neg = false;
if (c == NC)
c = getChar();
for (; (c < '0' || c > '9'); c = getChar()) {
if (c == '-')
neg = true;
}
long res = 0;
for (; c >= '0' && c <= '9'; c = getChar()) {
res = (res << 3) + (res << 1) + c - '0';
cnt *= 10;
}
return neg ? -res : res;
}
public double nextDouble() {
double cur = nextLong();
return c != '.' ? cur : cur + nextLong() / cnt;
}
public double[] readDoubles(int N) {
double[] res = new double[N];
for (int i = 0; i < N; i++) {
res[i] = nextDouble();
}
return res;
}
public String next() {
StringBuilder res = new StringBuilder();
while (c <= 32)
c = getChar();
while (c > 32) {
res.append(c);
c = getChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while (c <= 32)
c = getChar();
while (c != '\n') {
res.append(c);
c = getChar();
}
return res.toString();
}
public boolean hasNext() {
if (c > 32)
return true;
while (true) {
c = getChar();
if (c == NC)
return false;
else if (c > 32)
return true;
}
}
}
// For Input.txt and Output.txt
// FileInputStream in = new FileInputStream("input.txt");
// FileOutputStream out = new FileOutputStream("output.txt");
// PrintWriter pw = new PrintWriter(out);
// Scanner sc = new Scanner(in);
}
| 0 |
Non-plagiarised
|
d55c238c
|
ebce9e39
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class First {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
//int a = 1;
int t;
t = in.nextInt();
//t = 1;
while (t > 0) {
//out.print("Case #"+(a++)+": ");
solver.call(in,out);
t--;
}
out.close();
}
static class TaskA {
public void call(InputReader in, PrintWriter out) {
int n, m, x;
n = in.nextInt();
m = in.nextInt();
x = in.nextInt();
int[] arr = new int[n];
answer[] array = new answer[n];
int[] ar = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
array[i] = new answer(arr[i],i);
}
long[] ans = new long[m];
Arrays.sort(array);
int a = 0 , b = 0;
while(true){
for (int i = 0; i < m; i++) {
ar[b] = i+1;
b++;
if(b==n){
break;
}
}
if(b==n){
break;
}
for (int i = m-1; i >= 0; i--) {
ar[b] = i+1;
b++;
if(b==n){
break;
}
}
if(b==n){
break;
}
}
for (int i = 0; i < n; i++) {
ans[ar[i]-1] += array[i].a;
}
for (int i = 0; i < m-1; i++) {
if(Math.abs(ans[i]- ans[i+1])>x){
out.println("NO");
return;
}
}
out.println("YES");
int[] answer = new int[n];
for (int i = 0; i < n; i++) {
answer[array[i].b] = ar[i];
}
for (int i = 0; i < n; i++) {
out.print(answer[i]+" ");
}
out.println();
}
}
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static int lcm(int a, int b)
{
return (a / gcd(a, b)) * b;
}
static class answer implements Comparable<answer>{
int a;
int b;
public answer(int a, int b) {
this.a = a;
this.b = b;
}
@Override
public int compareTo(answer o) {
return o.a - this.a;
}
@Override
public boolean equals(Object o){
if(o instanceof answer){
answer c = (answer)o;
return a == c.a && b == c.b;
}
return false;
}
}
static class answer1 implements Comparable<answer1>{
int a, b, c;
public answer1(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
@Override
public int compareTo(answer1 o) {
if(o.c==this.c){
return this.a - o.a;
}
return o.c - this.c;
}
}
static long gcd(long a, long b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static void sort(long[] a) {
ArrayList<Long> l=new ArrayList<>();
for (Long i:a) l.add(i);
l.sort(Collections.reverseOrder());
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static final Random random=new Random();
static void shuffleSort(int[] a) {
int n=a.length;
for (int i=0; i<n; i++) {
int oi=random.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong(){
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
}
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class First {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
//int a = 1;
int t;
t = in.nextInt();
//t = 1;
while (t > 0) {
//out.print("Case #"+(a++)+": ");
solver.call(in,out);
t--;
}
out.close();
}
static class TaskA {
public void call(InputReader in, PrintWriter out) {
int n, m, x;
n = in.nextInt();
m = in.nextInt();
x = in.nextInt();
int[] arr = new int[n];
answer[] array = new answer[n];
int[] ar = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
array[i] = new answer(arr[i],i);
}
long[] ans = new long[m];
Arrays.sort(array);
int a = 0 , b = 0;
while(true){
for (int i = 0; i < m; i++) {
ar[b] = i+1;
b++;
if(b==n){
break;
}
}
if(b==n){
break;
}
for (int i = m-1; i >= 0; i--) {
ar[b] = i+1;
b++;
if(b==n){
break;
}
}
if(b==n){
break;
}
}
for (int i = 0; i < n; i++) {
ans[ar[i]-1] += array[i].a;
}
for (int i = 0; i < m-1; i++) {
if(Math.abs(ans[i]- ans[i+1])>x){
out.println("NO");
return;
}
}
out.println("YES");
int[] answer = new int[n];
for (int i = 0; i < n; i++) {
answer[array[i].b] = ar[i];
}
for (int i = 0; i < n; i++) {
out.print(answer[i]+" ");
}
out.println();
}
}
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static int lcm(int a, int b)
{
return (a / gcd(a, b)) * b;
}
static class answer implements Comparable<answer>{
int a;
int b;
public answer(int a, int b) {
this.a = a;
this.b = b;
}
@Override
public int compareTo(answer o) {
return o.a - this.a;
}
@Override
public boolean equals(Object o){
if(o instanceof answer){
answer c = (answer)o;
return a == c.a && b == c.b;
}
return false;
}
}
static class answer1 implements Comparable<answer1>{
int a, b, c;
public answer1(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
@Override
public int compareTo(answer1 o) {
if(o.c==this.c){
return this.a - o.a;
}
return o.c - this.c;
}
}
static long gcd(long a, long b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static void sort(long[] a) {
ArrayList<Long> l=new ArrayList<>();
for (Long i:a) l.add(i);
l.sort(Collections.reverseOrder());
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static final Random random=new Random();
static void shuffleSort(int[] a) {
int n=a.length;
for (int i=0; i<n; i++) {
int oi=random.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong(){
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
}
| 1 |
Plagiarised
|
b2590225
|
fdcbdf85
|
//package com.company;
import java.util.*;
public class P3 {
public static class tower implements Comparable<tower>{
ArrayList<Integer> index;
int size;
tower(){
size = 0;
index = new ArrayList<>();
}
@Override
public int compareTo(tower a) {
if(this.size > a.size) {
return 1;
} else if (this.size < a.size) {
return -1;
} else {
return 0;
}
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
while(t>0){
t--;
int n = scan.nextInt();
int m = scan.nextInt();
int x = scan.nextInt();
ArrayList<Integer> arr = new ArrayList<>();
HashMap<Integer,Integer> map = new HashMap<>();
for(int i = 0;i<n;i++){
arr.add(scan.nextInt());
map.put(i, arr.get(i));
}
System.out.println("YES");
PriorityQueue<tower> towers = new PriorityQueue<>();
for(int i = 0;i<m;i++){
tower curr = new tower();
towers.add(curr);
}
for(int i = 0;i<n;i++){
tower curr = towers.poll();
curr.size += arr.get(i);
curr.index.add(i);
towers.add(curr);
}
int[] ans = new int[n];
int count = 1;
while(towers.size() > 0){
tower curr = towers.poll();
for(Integer p : curr.index){
ans[p] = count;
}
count++;
}
for(int i = 0;i<n;i++){
System.out.print(ans[i] +" ");
}
System.out.println();
}
}
}
|
import java.io.*;
import java.util.*;
import java.lang.*;
public class B{
public static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
static long MOD = (long) (1e9 + 7);
// static long MOD = 998244353;
static long MOD2 = MOD * MOD;
static FastReader sc = new FastReader();
static int pInf = Integer.MAX_VALUE;
static int nInf = Integer.MIN_VALUE;
static long ded = (long)(1e17)+9;
public static void main(String[] args) throws Exception {
int test = 1;
test = sc.nextInt();
for (int i = 1; i <= test; i++){
// out.print("Case #"+i+": ");
solve();
}
out.flush();
out.close();
}
static void solve(){
int n = sc.nextInt();
int m = sc.nextInt();
int diff = sc.nextInt();
ArrayList<Pair> A = new ArrayList<>();
for(int i= 0; i < n; i++){
int x = sc.nextInt();
A.add(new Pair(x,i));
}
int[] sum = new int[m];
int[] ans = new int[n];
Collections.sort(A);
for(int i= 0; i < n; i++){
int idx = i%m;
sum[idx] += A.get(i).x;
ans[A.get(i).y] = idx+1;
}
ruffleSort(sum);
if(Math.abs(sum[0]-sum[sum.length-1])>diff){
out.println("NO");
return;
}
out.println("YES");
for(int i = 0; i < n; i++){
out.print(ans[i]+" ");
}
out.println();
}
static class Pair implements Comparable<Pair> {
int x;
int y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Pair o){
if(this.x==o.x){
return -1*(o.y-this.y);
}
return this.x-o.x;
}
@Override
public String toString() {
return "Pair{" + "x=" + x + ", y=" + y + '}';
}
public boolean equals(Pair o){
return this.x==o.x&&this.y==o.y;
}
}
public static long mul(long a, long b) {
return ((a % MOD) * (b % MOD)) % MOD;
}
public static long add(long a, long b) {
return ((a % MOD) + (b % MOD)) % MOD;
}
public static long c2(long n) {
if ((n & 1) == 0) {
return mul(n / 2, n - 1);
} else {
return mul(n, (n - 1) / 2);
}
}
//Shuffle Sort
static final Random random = new Random();
static void ruffleSort(int[] a) {
int n = a.length;//shuffle, then sort
for (int i = 0; i < n; i++) {
int oi = random.nextInt(n); int temp= a[oi];
a[oi] = a[i];
a[i] = temp;
}
Arrays.sort(a);
}
//Brian Kernighans Algorithm
static long countSetBits(long n) {
if (n == 0) return 0;
return 1 + countSetBits(n & (n - 1));
}
//Euclidean Algorithm
static long gcd(long A, long B) {
if (B == 0) return A;
return gcd(B, A % B);
}
//Modular Exponentiation
static long fastExpo(long x, long n) {
if (n == 0) return 1;
if ((n & 1) == 0) return fastExpo((x * x) % MOD, n / 2) % MOD;
return ((x % MOD) * fastExpo((x * x) % MOD, (n - 1) / 2)) % MOD;
}
//AKS Algorithm
static boolean isPrime(long n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
for (int i = 5; i <= Math.sqrt(n); i += 6)
if (n % i == 0 || n % (i + 2) == 0) return false;
return true;
}
public static long modinv(long x) {
return modpow(x, MOD - 2);
}
public static long modpow(long a, long b) {
if (b == 0) {
return 1;
}
long x = modpow(a, b / 2);
x = (x * x) % MOD;
if (b % 2 == 1) {
return (x * a) % MOD;
}
return x;
}
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;
}
}
}
| 0 |
Non-plagiarised
|
8d9871a9
|
e431de28
|
import java.util.*;
public class Main {
static Scanner scan = new Scanner(System.in);
static int[] readArray(int[] x) {
for(int i=0; i<x.length; ++i) x[i] = scan.nextInt();
return x;
}
static long[] readArray(long[] x) {
for(int i=0; i<x.length; ++i) x[i] = scan.nextLong();
return x;
}
public static void go() {
}
public static void main(String[] args) {
int t = scan.nextInt();
for(int it=0; it<t; ++it) {
int n = scan.nextInt();
long[] aa = readArray(new long[n]);
long minEven = aa[0];
long minOdd = aa[1];
long sum = aa[0]+aa[1];
long best = n*minEven + n*minOdd;
int numOdd = 1;
int numEven = 1;
for(int i=2; i<n; ++i) {
if(i%2 == 0) {
minEven = Math.min(aa[i], minEven);
numEven++;
}else {
minOdd = Math.min(aa[i], minOdd);
numOdd++;
}
sum += aa[i];
long score = sum;
score += minEven*(n-numEven);
score += minOdd*(n-numOdd);
best = Math.min(best, score);
}
System.out.println(best);
}
}
}
|
import java.io.*;
import java.lang.*;
import java.util.*;
public class MinGridPath {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner s=new Scanner(System.in);
int t=s.nextInt();
while(t-->0){
int n = s.nextInt();
long[] aa =new long[n];
for(int i=0;i<n;i++)
aa[i]=s.nextLong();
long minEven = aa[0];
long minOdd = aa[1];
long sum = aa[0]+aa[1];
long best = n*minEven + n*minOdd;
int numOdd = 1;
int numEven = 1;
for(int i=2; i<n; ++i) {
if(i%2 == 0) {
minEven = Math.min(aa[i], minEven);
numEven++;
}else {
minOdd = Math.min(aa[i], minOdd);
numOdd++;
}
sum += aa[i];
long score = sum;
score += minEven*(n-numEven);
score += minOdd*(n-numOdd);
best = Math.min(best, score);
}
System.out.println(best);
}
}
}
| 1 |
Plagiarised
|
6a47e491
|
f2cf6a74
|
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class InterestingStory {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
while (t-- > 0) {
int n = scan.nextInt();
String[] a = new String[n];
for (int i = 0; i < n; i++) {
a[i] = scan.next();
}
int res = -1;
int[] st = new int[n];
for (int i = 0; i < n; i++) {
String s = a[i];
int c = 0;
for (int j = 0; j < s.length(); j++) {
if (s.charAt(j) == 'a') {
++c;
}
}
st[i] = ((s.length() - c) - c);
}
sort(st);
long sum = 0;
int count = 0;
for (int i = 0; i < n; i++) {
if (st[i] + sum >= 0) {
break;
}
sum += st[i];
++count;
}
res = Math.max(res, count);
for (int i = 0; i < n; i++) {
String s = a[i];
int c = 0;
for (int j = 0; j < s.length(); j++) {
if (s.charAt(j) == 'b') {
++c;
}
}
st[i] = ((s.length() - c) - c);
}
sort(st);
sum = 0;
count = 0;
for (int i = 0; i < n; i++) {
if (st[i] + sum >= 0) {
break;
}
sum += st[i];
++count;
}
res = Math.max(res, count);
for (int i = 0; i < n; i++) {
String s = a[i];
int c = 0;
for (int j = 0; j < s.length(); j++) {
if (s.charAt(j) == 'c') {
++c;
}
}
st[i] = ((s.length() - c) - c);
}
sort(st);
sum = 0;
count = 0;
for (int i = 0; i < n; i++) {
if (st[i] + sum >= 0) {
break;
}
sum += st[i];
++count;
}
res = Math.max(res, count);
for (int i = 0; i < n; i++) {
String s = a[i];
int c = 0;
for (int j = 0; j < s.length(); j++) {
if (s.charAt(j) == 'd') {
++c;
}
}
st[i] = ((s.length() - c) - c);
}
sort(st);
sum = 0;
count = 0;
for (int i = 0; i < n; i++) {
if (st[i] + sum >= 0) {
break;
}
sum += st[i];
++count;
}
res = Math.max(res, count);
for (int i = 0; i < n; i++) {
String s = a[i];
int c = 0;
for (int j = 0; j < s.length(); j++) {
if (s.charAt(j) == 'e') {
++c;
}
}
st[i] = ((s.length() - c) - c);
}
sort(st);
sum = 0;
count = 0;
for (int i = 0; i < n; i++) {
if (st[i] + sum >= 0) {
break;
}
sum += st[i];
++count;
}
res = Math.max(res, count);
System.out.println(res);
}
}
static final Random random = new Random();
static void sort(int[] a) {
int n = a.length;//shuffle, then sort
for (int i = 0; i < n; i++) {
int oi = random.nextInt(n), temp = a[oi];
a[oi] = a[i];
a[i] = temp;
}
Arrays.sort(a);
}
}
|
import java.util.*;
public class shivam{
public static int diff(String str, char ch){
int cnt=0;
for(int i=0;i<str.length();i++){
if(ch==str.charAt(i)){
cnt++;
}
}
return cnt-(str.length()-cnt);
}
public static int process(char ch,int n,String []arr){
int[]a=new int[n];
for(int i=0;i<n;i++){
a[i]=diff(arr[i],ch);
}
Arrays.sort(a);
int max=0;
int sum=0;
for(int i=n-1;i>=0;i--){
sum+=a[i];
if(sum>0){
max++;
}
else{
break;
}
}
return max;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int k=sc.nextInt();
while(k-->0){
int n=sc.nextInt();
String []arr=new String[n];
for(int i=0;i<n;i++){
arr[i]=sc.next();
}
int a=process('a',n,arr);
int b=process('b',n,arr);
int c=process('c',n,arr);
int d=process('d',n,arr);
int e=process('e',n,arr);
System.out.println(Math.max(a,Math.max(b,Math.max(c,Math.max(d,e)))));
}
}
}
| 0 |
Non-plagiarised
|
3dd65549
|
90dc2b20
|
import java.util.*;
import java.io.*;
public class codeforces {
public static void main(String[] args) throws Exception {
int t=sc.nextInt();
while(t-->0) {
int n=sc.nextInt();
char[] a=sc.next().toCharArray();
char[] b=sc.next().toCharArray();
int e0=0;
int e1=0;
int o0=0;
int o1=0;
for(int i=0;i<n;i++) {
if(a[i]!=b[i]) {
if(a[i]=='1') {
e1++;
}else {
e0++;
}
}else {
if(a[i]=='1') {
o1++;
}else {
o0++;
}
}
}
int ans=Integer.MAX_VALUE;
if(e1==e0) {
ans=Math.min(ans, e1+e0);
}
if(o1==o0+1) {
ans=Math.min(ans, o1+o0);
}
// pw.println(e0+" "+e1+" "+o0+" "+o1);
pw.println(ans==Integer.MAX_VALUE?-1:ans);
}
pw.close();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public long[] nextlongArray(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public Long[] nextLongArray(int n) throws IOException {
Long[] a = new Long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public int[] nextIntArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public Integer[] nextIntegerArray(int n) throws IOException {
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public boolean ready() throws IOException {
return br.ready();
}
}
static class pair implements Comparable<pair> {
long x;
long y;
public pair(long x, long y) {
this.x = x;
this.y = y;
}
public String toString() {
return x + " " + y;
}
public boolean equals(Object o) {
if (o instanceof pair) {
pair p = (pair) o;
return p.x == x && p.y == y;
}
return false;
}
public int hashCode() {
return new Long(x).hashCode() * 31 + new Long(y).hashCode();
}
public int compareTo(pair other) {
if (this.x == other.x) {
return Long.compare(this.y, other.y);
}
return Long.compare(this.x, other.x);
}
}
static class tuble implements Comparable<tuble> {
int x;
int y;
int z;
public tuble(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
public String toString() {
return x + " " + y + " " + z;
}
public int compareTo(tuble other) {
if (this.x == other.x) {
if (this.y == other.y) {
return this.z - other.z;
}
return this.y - other.y;
} else {
return this.x - other.x;
}
}
}
static long mod = 1000000007;
static Random rn = new Random();
static Scanner sc = new Scanner(System.in);
static PrintWriter pw = new PrintWriter(System.out);
}
|
import java.util.*;
import java.io.*;
public class C1615{
static FastScanner fs = null;
public static void main(String[] args) {
fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int t = fs.nextInt();
while (t-->0) {
int n = fs.nextInt();
String a = fs.next();
String b = fs.next();
char ch1[] = a.toCharArray();
char ch2[] = b.toCharArray();
int c00 = 0;
int c01 = 0;
int c10 = 0;
int c11 = 0;
for(int i=0;i<n;i++){
if(ch1[i]=='0'){
if(ch2[i]=='0'){
c00+=1;
}
else{
c01+=1;
}
}
else{
if(ch2[i]=='0'){
c10+=1;
}
else{
c11+=1;
}
}
}
int ans = -1;
if((c11-c00)==1 || c10==c01){
int s1 = (int)1e7;
int s2 = (int)1e7;
if((c11-c00)==1){
s1 = c11+c00;
}
if(c10==c01)
s2 = c10+c01;
ans = Math.min(s1,s2);
}
out.println(ans);
}
out.close();
}
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 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());
}
}
}
| 0 |
Non-plagiarised
|
3088ca9c
|
6f393cfe
|
import java.util.*;
import java.io.*;
public class MyClass {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t>0)
{
int n = sc.nextInt();
sc.nextLine();
String [] str = new String[n];
int res = 0;
for(int i=0;i<n;i++)
{
str[i]=sc.nextLine();
}
int [][] freq = new int [n][5];
for(int i=0;i<n;i++)
{
for(int j=0;j<str[i].length();j++)
{
int k = str[i].charAt(j)-'a';
freq[i][k]++;
}
}
for(int i=0;i<5;i++)
{
int [] arr = new int[n];
for(int j=0;j<n;j++)
{
int pos = freq[j][i];
int sum=0;
for(int k = 0;k<5;k++)
{
sum+=freq[j][k];
}
sum-=pos;
arr[j]=(pos-sum);
}
Arrays.sort(arr);
// int p = n-1;
int count=0;
int sum=0;
for(int p=n-1;p>=0;p--)
{
sum+=arr[p];
if(sum>0)
{
count++;
}
else
{
break;
}
}
res=Math.max(count , res);
}
System.out.println(res);
t--;
}
}
}
|
import java.io.*;
import java.util.*;
public class C {
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
try{
int t = Integer.parseInt(br.readLine());
while(t-->0){
int n = Integer.parseInt(br.readLine());
int lst[][] = new int[n][5];
for(int i=0; i<n; i++){
String s = br.readLine();
for(int j=0; j<s.length(); j++){
lst[i][s.charAt(j)-'a']++;
}
}
int fans = Integer.MIN_VALUE;
for(int i=0; i<5; i++){
int val[] = new int[n];
for(int k=0; k<n; k++){
int sum = 0;
for(int j=0; j<5; j++){
if(i==j){
sum += lst[k][j];
}else{
sum -= lst[k][j];
}
}
val[k] = sum;
}
Arrays.sort(val);
int sum = 0;
int ans = 0;
for(int x = n-1; x>=0; x--){
sum+=val[x];
if(sum>0){
ans++;
}else{
break;
}
}
fans = Math.max(fans, ans);
}
bw.write(fans+"\n");
}
bw.flush();
}catch(Exception e){
return;
}
}
}
| 1 |
Plagiarised
|
b790ef12
|
ff34fab2
|
import java.io.*;
import java.util.*;
public class Main {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args) {
FastReader obj = new FastReader();
PrintWriter out = new PrintWriter(System.out);
int l = obj.nextInt();
while (l-- != 0) {
int n = obj.nextInt();
int[] num = new int[n];
for (int i = 0; i < n; i++) num[i] = obj.nextInt();
Vector<Integer> red = new Vector<>();
Vector<Integer> blue = new Vector<>();
String s = obj.next();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == 'R') red.add(num[i]);
else blue.add(num[i]);
}
Collections.sort(blue);
Collections.sort(red);
int c = 1, f = 0;
for (int i = 0; i < blue.size(); i++) {
if (blue.get(i) < c) {
f = 1;
break;
}
c++;
}
for (int i = 0; i < red.size(); i++) {
if (red.get(i) > c) {
f = 1;
break;
}
c++;
}
if (f == 0) out.println("YES");
else out.println("NO");
}
out.flush();
}
}
|
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
import java.io.*;
public class Div2 {
private 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;
}
}
public static String solution(int [] arr, int n, String st)
{
ArrayList<Integer> red = new ArrayList<>();
ArrayList<Integer> blue = new ArrayList<>();
for(int i = 0; i<n; i++)
{
if(st.charAt(i)=='R')
red.add(arr[i]);
else
blue.add(arr[i]);
}
Collections.sort(red);
Collections.sort(blue);
int cb = 1;
for(int j = 0; j<blue.size(); j++)
{
if(blue.get(j)<cb)
return "NO";
cb++;
}
int cr = n;
for(int j = red.size()-1; j>=0; j--)
{
if(red.get(j)>cr)
return "NO";
cr--;
}
return "YES";
}
private static PrintWriter out = new PrintWriter(System.out);
public static void main (String[] args)
{
MyScanner s = new MyScanner();
int t = s.nextInt();
for(int j = 0; j<t ; j++)
{
int n = s.nextInt();
int[] arr = new int[n];
for(int i =0; i<n; i++)
arr[i] = s.nextInt();
String st = s.next();
out.println(solution(arr,n, st));
}
out.flush();
out.close();
}
}
| 0 |
Non-plagiarised
|
07749c65
|
2bbf754b
|
import java.io.*;
import java.util.*;
public class Nov1P4 {
public static void main(String[] args) {
MyScanner sc = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out));
long o = sc.nextInt();
for(long i = 0; i < o; i++)
{
int n = sc.nextInt();
long[] m = new long[n];
for(int j = 0; j < n; j++)
{
m[j] = sc.nextLong();
}
String str = sc.nextLine();
ArrayList<Long> a = new ArrayList<Long>();
ArrayList<Long> b = new ArrayList<Long>();
for(int j = 0; j < n; j++)
{
if(str.charAt(j) == 'B')
{
b.add(m[j]);
}
else
{
a.add(m[j]);
}
}
Collections.sort(a);
Collections.sort(b);
boolean tf = true;
for(int j = 0; j < b.size(); j++)
{
if(b.get(j) < (j+1) && tf)
{
out.println("NO");
tf = false;
}
}
for(int j = 0; j < a.size(); j++)
{
if(a.get(j) > j+1+b.size() && tf)
{
out.println("NO");
tf = false;
}
}
if(tf)
out.println("YES");
}
// Start writing your solution here. -------------------------------------
/*
int n = sc.nextInt(); // read input as integer
long k = sc.nextLong(); // read input as long
double d = sc.nextDouble(); // read input as double
String str = sc.next(); // read input as String
String s = sc.nextLine(); // read whole line as String
int result = 3*n;
out.println(result); // print via PrintWriter
*/
// Stop writing your solution here. -------------------------------------
out.close();
}
//-----------PrintWriter for faster output---------------------------------
public static PrintWriter out;
//-----------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;
}
}
//--------------------------------------------------------
}
|
import java.util.*;
/**
__ __
( _) ( _)
/ / \\ / /\_\_
/ / \\ / / | \ \
/ / \\ / / |\ \ \
/ / , \ , / / /| \ \
/ / |\_ /| / / / \ \_\
/ / |\/ _ '_| \ / / / \ \\
| / |/ 0 \0\ / | | \ \\
| |\| \_\_ / / | \ \\
| | |/ \.\ o\o) / \ | \\
\ | /\\`v-v / | | \\
| \/ /_| \\_| / | | \ \\
| | /__/_ `-` / _____ | | \ \\
\| [__] \_/ |_________ \ | \ ()
/ [___] ( \ \ |\ | | //
| [___] |\| \| / |/
/| [____] \ |/\ / / ||
( \ [____ / ) _\ \ \ \| | ||
\ \ [_____| / / __/ \ / / //
| \ [_____/ / / \ | \/ //
| / '----| /=\____ _/ | / //
__ / / | / ___/ _/\ \ | ||
(/-(/-\) / \ (/\/\)/ | / | /
(/\/\) / / //
_________/ / /
\____________/ (
*/
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-- >0) {
int n=sc.nextInt();
int[] arr=new int[n];
for(int i=0;i<n;i++) {
arr[i]=sc.nextInt();
}
String str=sc.next();
ArrayList<Pair> plist=new ArrayList<>();
for(int i=0;i<n;i++) {
char ch=str.charAt(i);
plist.add(new Pair(arr[i],ch));
}
//B-reduce
//R-increse
Collections.sort(plist);
int counter=1;
boolean flag=false;
for(int i=0;i<plist.size();i++) {
int val=plist.get(i).number;
int clr=plist.get(i).color;
if(clr=='B') {
if(val<counter) {
flag=true;
break;
}
}
else {
if(val>counter) {
flag=true;
break;
}
}
counter++;
}
System.out.println(flag?"NO":"YES");
}
}
public static class Pair implements Comparable<Pair>{
int number;
char color;
Pair(int number,char color){
this.number=number;
this.color=color;
}
@Override
public int compareTo(Pair o) {
if(o.color==this.color) {
return this.number-o.number;
}
else {
return this.color-o.color;
}
}
public String toString() {
return number+"-"+color+".";
}
}
}
| 0 |
Non-plagiarised
|
464ad4dd
|
9291ca83
|
import java.io.*;
import java.util.*;
public class Solution{
public static int in = 0, count=0;
static class comparator implements Comparator<int[]>{
public int compare(int[] arr1 ,int[] arr2){
int gain1 =0, gain2=0;
for(int i:arr1) gain1+=i;
for(int i:arr2) gain2+=i;
if((gain1-2*arr1[in])>(gain2-2*arr2[in]))
return 1;
else if((gain1-2*arr1[in])==(gain2-2*arr2[in])) {
count++;
return 0;
}
return -1;
}
}
public static int solve(ArrayList<int[]> al, int[] total){
ArrayList<int[]> c = (ArrayList<int[]>) al.clone();
java.util.Collections.sort(c, new comparator());
int i= al.size()-1;
int sum=0; for(int ii:total) sum+=ii;
int check = total[in];
sum-=check;
for(; i>=0; i--){
if(check>sum) return i+1;
else{
int newSum=0; for(int ii:c.get(i)) newSum+=ii;
newSum-=c.get(i)[in];
sum-=newSum;
check-=c.get(i)[in];
}
}
return 0;
}
public static void main (String[] args) throws java.lang.Exception {
FastReader sc = new FastReader();
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
int testCase = sc.nextInt();
while (testCase-->0){
int n = sc.nextInt();
String[] strArr = new String[n];
for(int i=0; i<n; i++) {
strArr[i]=sc.nextLine();
}
int[] total = new int[5];
ArrayList<int[]> al = new ArrayList<>();
for(int i=0; i<n; i++){
int[] arr= new int[5];
for(int j=0; j<strArr[i].length(); j++){
arr[strArr[i].charAt(j)-'a']++;
}
for(int j=0; j<5; j++){
total[j]+=arr[j];
}
al.add(arr);
}
int ans = Integer.MIN_VALUE;
for(int i=0; i<5; i++) {
in = i;
ans = Math.max(solve(al, total), ans);
count=0;
}
System.out.println(ans);
}
}
// Fast Reader Class
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; }
}
}
|
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
public class Practice {
static HashMap<String, Integer> map = new HashMap<>();
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-->0) {
int n = sc.nextInt();
int[][] occurances = new int[5][n];
for(int i=0;i<n;i++){
String s = sc.next();
int[] count = new int[5];
int len = s.length();
for(int j=0;j<s.length();j++){
count[s.charAt(j)-'a']++;
}
for(int j=0;j<5;j++){
occurances[j][i] = count[j] - (len-count[j]);
}
}
int ans = 0;
for(int i=0;i<5;i++){
Arrays.sort(occurances[i]);
int tmpAns = 0; int tmpSum=0;
for(int j=n-1;j>=0;j--){
tmpSum+=occurances[i][j];
if(tmpSum>0) tmpAns++;
else break;
}
ans = Math.max(ans, tmpAns);
}
System.out.println(ans);
}
}
}
| 0 |
Non-plagiarised
|
35bb6075
|
42fe7dd0
|
/*
COLLECTIONS FRAMEWORK TUTORIAL
* HashMap
.add(key, value)
.get(key)
.containsKey(key) : true/false
.size()
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
static final long M = 1000000007;
// use main for only io
public static void main(String args[]) {
FastReader io = new FastReader();
new Solver().solve(io);
}
}
//class Pair{
// int key;String value;
//
// public Pair(int key, String value){
// this.key = key;
// this.value = value;
// }
//}
class SparseTable{
int dp[][] = new int[300005][20];
int log[] = new int[300005];
public SparseTable(long a[], int n){
for(int i =0;i<n;i++)dp[i][0] = i;
for(int i = 1;i < 20;i++){
for(int j = 0;j + (1 << i) < n;j++){
if(a[dp[j][i-1]] < a[dp[j + (1 << (i-1))][i-1]]){
dp[j][i] = dp[j][i-1];
}
else{
dp[j][i] = dp[j + (1 << (i - 1))][i-1];
}
}
}
log[1] = 0;
for(int i = 2;i <= n;i++){
log[i] = log[i/2] + 1;
}
}
int getMin(int L, int R, long a[]){
if(L > R)return 0;
int j = log[R - L + 1];
if(a[dp[L][j]] < a[dp[R - (1 << j) + 1][j]])return dp[L][j];
return dp[R-(1 << j) + 1][j];
}
}
class Solver {
static final int M = 998244353;
void solve(FastReader io) {
int t = io.nextInt();
while(t-- > 0){
int n = io.nextInt();
String s[] = new String[n];
for(int i = 0;i < n;i++)s[i] = io.nextLine();
int ans = 0;
for(int i = 0;i < 5;i++){
int count[] = new int[n];
for(int j = 0;j < n;j++){
int freq = 0;
for(int k = 0;k < s[j].length();k++){
// System.out.println(s[j].charAt(k) - 'a');
if((s[j].charAt(k) - 'a') == i){
freq++;
}
}
// System.out.println(i + " " + freq);
count[j] = 2*freq - s[j].length();
}
Arrays.sort(count);
// for(int it : count)System.out.print(it + " ");
// System.out.println();
int curr = 0;
int j = n - 1;
for(;j >= 0 && (curr + count[j] > 0);j--){
curr += count[j];
}
ans = Math.max(ans, n - j - 1);
}
System.out.println(ans);
}
}
// returns the first key greater than or equal to val
int lower_bound(int a[], int val) {
int low = 0, high = a.length - 1, ret = -1;
while (low <= high) {
int mid = (low + high) / 2;
if (a[mid] < val) low = mid + 1;
else {
ret = mid;
high = mid - 1;
}
}
return ret;
}
// returns the first key strictly greater than val
int upper_bound(int a[], int val) {
int low = 0, high = a.length - 1, ret = -1;
while (low <= high) {
int mid = (low + high) / 2;
if (a[mid] <= val) low = mid + 1;
else {
ret = mid;
high = mid - 1;
}
}
return ret;
}
long modexp(long n, int m) {
if (m == 0)
return 1;
else if (m == 1)
return n;
else {
long p = modexp(n, m / 2);
if (m % 2 == 1)
return (((p * p) % M) * n) % M;
else
return (p * p) % M;
}
}
long exp(long n, long m) {
if (m == 0)
return 1;
if (m == 1)
return n;
long p = exp(n, m / 2);
if (m % 2 == 1)
return p * p * n;
else
return p * p;
}
long gcd(long a, long b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
long inv(long n) {
return modexp(n, M - 2);
}
long lcm(long a, long b) {
return a * b / gcd(a, b);
}
long factorial(long fact[], int n) {
fact[0] = 1;
fact[1] = 1;
long prod = 1;
for (int i = 2; i <= n; i++) {
prod = (prod * i) % M;
fact[i] = prod;
}
return prod;
}
boolean isPrime(long n) {
for (int i = 2; i * i <= n; i++) {
if (n % i == 0)
return false;
}
return true;
}
}
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;
}
}
|
import java.util.*;
public class Solution {
static Scanner sc=new Scanner(System.in);
public static void main(String args[]) {
int t=sc.nextInt();
outer:while(t-->0){
int n=sc.nextInt();
int[][] ct=new int[n][5];
int[] len=new int[n];
for (int i=0;i<n;i++) {
String s=sc.next();
len[i]=s.length();
for(char c:s.toCharArray()){
ct[i][c-'a']++;
}
}
int mx=0;
for (int i=0;i<5;i++) {
int[] diff=new int[n];
for (int j=0;j<n;j++) {
diff[j]=ct[j][i]-(len[j]-ct[j][i]);
}
Arrays.sort(diff);
int sum=0,inc=0;
for(int j=n-1;j>=0;j--){
sum+=diff[j];
if (sum>0) {
inc++;
}else {
break;
}
}
mx=Math.max(mx,inc);
}
System.out.println(mx);
}
}
}
| 0 |
Non-plagiarised
|
2e404969
|
597195ee
|
import java.util.*;
import java.lang.*;
import java.io.*;
public class Codechef {
static long fans[] = new long[200001];
static long inv[] = new long[200001];
static long mod = 1000000007;
static void init() {
fans[0] = 1;
inv[0] = 1;
fans[1] = 1;
inv[1] = 1;
for (int i = 2; i < 200001; i++) {
fans[i] = ((long) i * fans[i - 1]) % mod;
inv[i] = power(fans[i], mod - 2);
}
}
static long ncr(int n, int r) {
return (((fans[n] * inv[n - r]) % mod) * (inv[r])) % mod;
}
public static void main(String[] args) throws java.lang.Exception {
FastReader in = new FastReader(System.in);
StringBuilder sb = new StringBuilder();
int t = 1;
t = in.nextInt();
while (t > 0) {
--t;
int n = in.nextInt();
long time[] = generateArray(in, n);
long hp[] = generateArray(in, n);
int s = 0;
long ans = 0;
while(s<time.length)
{
long l = time[s] - hp[s];
long r = time[s];
for(int i = s+1;i<n;i++)
{
if(time[i]-hp[i]<=l)
{
l = time[i]-hp[i];
r = time[i];
}
else if(time[i]-hp[i]<r)
{
r = time[i];
}
}
while(s<n && time[s]>=l && time[s]<=r)
{
++s;
}
long temp = r - l;
ans += (temp*(temp+1))/2;
}
sb.append(ans+"\n");
}
System.out.print(sb);
}
static long power(long x, long y) {
long res = 1; // Initialize result
while (y > 0) {
// If y is odd, multiply x with result
if ((y & 1) != 0)
res = ((res % mod) * (x % mod)) % mod;
// y must be even now
y = y >> 1; // y = y/2
x = ((x % mod) * (x % mod)) % mod; // Change x to x^2
}
return res;
}
static long[] generateArray(FastReader in, int n) throws IOException {
long arr[] = new long[n];
for (int i = 0; i < n; i++)
arr[i] = in.nextLong();
return arr;
}
static long[][] generatematrix(FastReader in, int n, int m) throws IOException {
long arr[][] = new long[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
arr[i][j] = in.nextLong();
}
}
return arr;
}
static long gcd(long a, long b) {
if (a == 0)
return b;
else
return gcd(b % a, a);
}
static long lcm(long a, long b) {
return (a / gcd(a, b)) * b;
}
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);
}
}
class FastReader {
byte[] buf = new byte[2048];
int index, total;
InputStream in;
FastReader(InputStream is) {
in = is;
}
int scan() throws IOException {
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0) {
return -1;
}
}
return buf[index++];
}
String next() throws IOException {
int c;
for (c = scan(); c <= 32; c = scan())
;
StringBuilder sb = new StringBuilder();
for (; c > 32; c = scan()) {
sb.append((char) c);
}
return sb.toString();
}
String nextLine() throws IOException {
int c;
for (c = scan(); c <= 32; c = scan())
;
StringBuilder sb = new StringBuilder();
for (; c != 10 && c != 13; c = scan()) {
sb.append((char) c);
}
return sb.toString();
}
char nextChar() throws IOException {
int c;
for (c = scan(); c <= 32; c = scan())
;
return (char) c;
}
int nextInt() throws IOException {
int c, val = 0;
for (c = scan(); c <= 32; c = scan())
;
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
long nextLong() throws IOException {
int c;
long val = 0;
for (c = scan(); c <= 32; c = scan())
;
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
}
|
import java.io.*;
import java.util.Arrays;
import java.util.StringTokenizer;
public class C_MonstersAndSpells_1700 {
public static void main(String[] args) {
MyScanner sc = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out));
int t = sc.nextInt();
while(t-->0) {
int n = sc.nextInt();
int[] times = new int[n];
int[] health = new int[n];
for(int i = 0; i < n; i++) {
times[i] = sc.nextInt();
}
for(int i = 0; i < n; i++) {
health[i] = sc.nextInt();
}
Point[] points = new Point[n];
for(int i = 0; i < n; i++) {
points[i] = new Point(times[i]-health[i], times[i]);
}
Arrays.sort(points);
long ans = 0;
for(int i = 0; i < n; i++) {
int j = i+1;
int latestTime = points[i].time;
while(j < n && points[j].startBy < latestTime) {
latestTime = Math.max(latestTime, times[j]);
j++;
}
long length = latestTime-points[i].startBy;
ans += (length*(length + 1))/2;
i = j - 1;
}
System.out.println(ans);
}
out.close();
}
static class Point implements Comparable<Point> {
Integer startBy;
Integer time;
Point(int startBy, int time) {
this.startBy = startBy;
this.time = time;
}
@Override
public int compareTo(Point o) {
return this.startBy.compareTo(o.startBy);
}
}
public static PrintWriter out;
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 class Pair {
public int x,y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
}
| 0 |
Non-plagiarised
|
04df7bb8
|
1ea771ea
|
import java.math.BigInteger;
import java.sql.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Scanner;
import java.util.Set;
import java.util.Stack;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
public class Main {
static HashMap<Integer,Boolean>map;
static long dp[][];
static boolean flag;
static HashSet<Long>hs;
static long mod=(long)(1e9+7);
public static void main(String[] args) {
StringBuilder ans=new StringBuilder();
FastReader sc=new FastReader();
int t=sc.nextInt();
while(t-->0) {
int n=sc.nextInt();
//int n=sb.length();
int k=sc.nextInt();
long L[]=new long[n];
long R[]=new long[n];
int a[]=new int[k];
int temp[]=new int[k];
for(int i=0;i<k;i++)
a[i]=sc.nextInt();
for(int i=0;i<k;i++)
temp[i]=sc.nextInt();
int c[]=new int [n];
Arrays.fill(c, Integer.MAX_VALUE);
for(int i=0;i<k;i++)
c[a[i]-1]=temp[i];
long p=Integer.MAX_VALUE;
for(int i=0;i<n;i++)
{
p=Math.min(p+1, c[i]);
L[i]=p;
}
p=Integer.MAX_VALUE;
for(int i=n-1;i>=0;i--)
{
p=Math.min(p+1, c[i]);
R[i]=p;
}
for(int i=0;i<n;i++)
{
ans.append(Math.min(L[i], R[i])+" ");
}
ans.append("\n");
}
System.out.println(ans);
}
static class Sparse{
int log[];
long sparse[][];
Sparse(int n){
log=new int [n+1];
for(int i=1;i<n+1;i++)
{
log[i]=log[i/2]+1;
}
sparse=new long[n][18];
}
}
static long solve(String X,String Y,int n,int m,int M){
if(m==0&&n==0)return 0;
// if(m==1&&X.charAt(n-1)!='u')return Integer.MIN_VALUE;
if(n==0||m==0)return Integer.MIN_VALUE;
if(dp[n][m]!=-1)return dp[n][m];
if(Y.charAt(m-1)==X.charAt(n-1))
{
// else if(n==1)return Integer.MAX_VALUE;
return dp[n][m]=1+ Math.max(solve (X,Y,n-1,m,M),solve (X,Y,n-1,m-1,M));
}
else{
return dp[n][m]= solve(X,Y,n-1,m,M);
}
}
static long solve(long [][]g,int n,int m,boolean visited [][]) {
if(n==0||m==0)return 0;
visited[n][m]=true;
long ans=g[n-1][m-1]+Math.max(solve(g, n, m-1, visited),solve(g, n-1, m, visited));
visited[n][m]=false;
return ans;
}
static boolean isP(long x,long n,long m) {
return (x^n)<=m;
}
static class pair{
int n;int i;
pair(int n,int i){
this.n=n;
this.i=i;
}
}
static long solve(char g[][],int n,int m) {
if(n==0||m==0)return 0;
if(n==1&&m==1)return 1;
if(g[n-1][m-1]=='#')return 0;
if(dp[n][m]!=-1)return dp[n][m];
return dp[n][m]= (solve(g, n-1, m)%mod+solve(g, n, m-1)%mod)%mod;
}
static int solve (int v,ArrayList<ArrayList<Integer>>adj,int d[],boolean visited[]) {
visited[v]=true;
for(int u:adj.get(v)) {
if(!visited[u])
{
solve(u, adj, d, visited);
}
d[v]=Math.max(1+d[u], d[v]);
}
return d[v];
}
static class colors{
int c;int n;
public colors(int c,int n) {
// TODO Auto-generated constructor stub
this.c=c;
this.n=n;
}
}
static int CeilIndex(long A[], int l, int r, long key)
{
while (r - l > 1) {
int m = l + (r - l) / 2;
if (A[m] >= key)
r = m;
else
l = m;
}
return r;
}
static int CeilIndexd(long A[], int l, int r, long key)
{
while (r - l > 1) {
int m = l + (r - l) / 2;
if (-1*A[m] >= key)
r = m;
else
l = m;
}
return r;
}
static void solve(ArrayList<Long>A,long bd) {
if(bd>(long)1e9)return;
// if(hs.contains(bd))return;
//A.add(bd);
hs.add(bd);
A.add(bd*10);
A.add(bd*10+1);
// hs.add(bd*10);
//hs.add(bd*10+1);
solve(A,bd*10);
solve(A,bd*10+1);
}
static boolean isPrime(int 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 long lcm(long a, long b)
{
return ((a / gcd(a, b))%mod * b%mod)%mod;
}
static long gcd(long a,long b)
{
if (a == 0)
return b%mod;
return (gcd(b % a, a))%mod;
}
//System.out.println(count);
static void dfs(int v,boolean visited[],ArrayList<ArrayList<Integer>>adj,int div[],int t)
{
visited[v]=true;
div[v]=t+1;
for(int u:adj.get(v)) {
if(!visited[u]) {
dfs(u,visited,adj,div,(t+1)%2);
}
}
}
static class Helper{
int a;int b;int t;
public Helper(int a,int b) {
// TODO Auto-generated constructor stub
this.a=a;
this.b=b;
}
}
// System.out.println(max);
//System.out.println(ans.toString());
//main(
static void solvedfs(ArrayList<ArrayList<Integer>>adj,int n,int v,int subt[],int subtAns[],boolean []visited) {
int count=1;
int ans=0;
visited[v]=true;
for(int u:adj.get(v)) {
if(!visited[u])
{
//System.out.println(v+" "+subt[v]+" "+n);
subtAns[u]=Math.max(subtAns[u], subt[v]-subtAns[u]);
solvedfs(adj, n, u, subt, subtAns, visited);
}
}
}
static int dfs(ArrayList<ArrayList<Integer>>adj,int v,int subt[],int subtAns[],boolean []visited) {
int count=0;
int ans=0;
visited[v]=true;
for(int u:adj.get(v)) {
if(!visited[u])
{
count+=ans;
ans=Math.max(dfs(adj,u,subt,subtAns,visited),ans);
}
}
subt[v]=count;
subtAns[v]=ans;
return ans+1;
}
static int solve(ArrayList<ArrayList<Integer>>adj,int node,ArrayList<Integer>A)
{
if(adj.get(node).size()==0)return 1;
int count=0;
for(int v:adj.get(node)) {
count+=solve(adj,v,A);
}
A.set(node,count);
return count+1;
}
static void dfs(String[]building,int i,int j,int n,int m, boolean visited[][]) {
visited[i][j]=true;
if(isValid(building,i+1,j,n,m,visited))
{ visited[i+1][j]=true;
dfs(building,i+1,j,n,m,visited);
}
if(isValid(building,i-1,j,n,m,visited))
{
visited[i-1][j]=true;
dfs(building,i-1,j,n,m,visited);
}
if(isValid(building,i,j+1,n,m,visited))
{visited[i][j+1]=true;
dfs(building,i,j+1,n,m,visited);
}
if(isValid(building,i,j-1,n,m,visited))
{visited[i][j-1]=true;
dfs(building,i,j-1,n,m,visited);
}
}
static boolean isValid(String[]building,int i,int j,int n,int m, boolean visited[][])
{
if(i==-1||j==-1||i==n||j==m||visited[i][j]||building[i].charAt(j)=='#')
return false;
return true;
}
static void compute(boolean sieve[],int n) {
for(int i=2;i<=n;i++) {
if(sieve[i])continue;
for(int j=2*i;j<n;j+=i)
{
sieve[j]=true;
}
}
}
static void computeHs(boolean sieve[]) {
int n=(int)(1e9-1e7+1);
for(int i=1;i<n;i++) {
if(sieve[i])continue;
for(int j=2*i;j<n;j+=i)
{
sieve[j]=true;
}
}
}
static boolean isValid(StringBuilder s,int w) {
if(w>s.length())return false;
HashSet<Character>hs=new HashSet<Character>();
int a[]=new int[3];
for(int i=0;i<w;i++) {
++a[s.charAt(i)-49];
}
if(a[0]>0&&a[1]>0&&a[2]>0)return true;
int start=0;
int end=w;
while(end!=s.length()) {
--a[s.charAt(start)-49];
++a[s.charAt(end)-49];
start++;
end++;
if(a[0]>0&&a[1]>0&&a[2]>0)return true;
}
return false;
}
static int find(int parent[],int i) {
if(parent[i]==-1)return i;
return parent[i]=find(parent,parent[i]);
}
static void union(int parent[],int rank[],int s1,int s2) {
if(rank[s1]>=rank[s2]) {
parent[s2]=s1;
rank[s1]+=rank[s2];
}
else {
parent[s1]=s2;
rank[s2]+=rank[s1];
}
}
static int solve(String S,int K) {
if(K<=0)return 0;
if(S.charAt(K-1)!=S.charAt(K))
return 1+solve(S,K-1);
else return solve(S,K-1);
}
static boolean isValid(int g[][],int r,int c,int n,int m,boolean visited[][],int s) {
if(r==-1||r==n||c==-1||c==m||visited[r][c]||g[r][c]!=s)return false;
return true;
}
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;
}
}
}
|
import java.io.*;
import java.util.*;
public class CODECHEF {
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();
}
String nextLine() throws IOException {
int c;
for (c = scan(); c <= 32; c = scan())
;
StringBuilder sb = new StringBuilder();
for (; c != 10 && c != 13; c = scan()) {
sb.append((char) c);
}
return sb.toString();
}
char nextChar() throws IOException {
int c;
for (c = scan(); c <= 32; c = scan())
;
return (char) c;
}
int nextInt() throws IOException {
int c, val = 0;
for (c = scan(); c <= 32; c = scan())
;
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
long nextLong() throws IOException {
int c;
long val = 0;
for (c = scan(); c <= 32; c = scan())
;
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
}
static long MOD=1000000000;
static class Pair{
long a;
int b;
Pair(long i,int j){
a=i;
b=j;
}
}
static long[] solve(int[] pos,long[] arr,int n,int k){
long[] ans=new long[n];
long[] left=new long[n];
long[] right=new long[n];
long min=Integer.MAX_VALUE;
for(int i=0;i<n;i++){
min=Math.min(min+1,arr[i]);
left[i]=min;
}
min=Integer.MAX_VALUE;
for(int i=n-1;i>=0;i--){
min=Math.min(min+1,arr[i]);
right[i]=min;
}
for(int i=0;i<n;i++){
ans[i]=Math.min(left[i],right[i]);
}
return ans;
}
public static void main(String[] args) throws java.lang.Exception {
FastReader fs=new FastReader(System.in);
// StringBuilder sb=new StringBuilder();
// PrintWriter out=new PrintWriter(System.out);
int t=fs.nextInt();
while (t-->0){
int n=fs.nextInt();
int k=fs.nextInt();
int[] pos=new int[k];
for(int i=0;i<k;i++)
pos[i]=fs.nextInt()-1;
long[] temp=new long[n];
int ptr=0;
Arrays.fill(temp,Integer.MAX_VALUE);
for(int i=0;i<k;i++)
temp[pos[ptr++]]=fs.nextLong();
long[] ans=solve(pos,temp,n,k);
for(int i=0;i<n;i++)
System.out.print(ans[i]+" ");
System.out.println();
}
//out.close;
}
}
| 1 |
Plagiarised
|
36f1b52a
|
558df7d4
|
/*
"Everything in the universe is balanced. Every disappointment
you face in life will be balanced by something good for you!
Keep going, never give up."
*/
import java.util.*;
import java.lang.*;
import java.io.*;
public class Solution {
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();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
int[] res = new int[n];
if (n % 2 == 0) {
for (int i = 1; i < n; i += 2) {
res[i] = arr[i - 1];
res[i - 1] = -arr[i];
}
}else {
for (int i = 4; i < n; i += 2) {
res[i] = arr[i - 1];
res[i - 1] = -arr[i];
}
if (arr[0] + arr[1] != 0) {
res[0] = -arr[2];
res[1] = -arr[2];
res[2] = arr[0] + arr[1];
}else if (arr[0] + arr[2] != 0) {
res[0] = -arr[1];
res[2] = -arr[1];
res[1] = arr[0] + arr[2];
}else {
res[1] = -arr[0];
res[2] = -arr[0];
res[0] = arr[1] + arr[2];
}
}
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 str;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (str == null || !str.hasMoreElements())
{
try
{
str = new StringTokenizer(br.readLine());
}
catch (IOException end)
{
end.printStackTrace();
}
}
return str.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException end)
{
end.printStackTrace();
}
return str;
}
}
}
|
import java.io.*;
import java.util.*;
public class Pupsen {
public static void main(String[] args) throws Exception {
FastIO in = new FastIO();
int t = in.nextInt();
for (int tc=0; tc<t; tc++) {
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];
if (n%2==0) {
for (int i=0; i<n-1; i+=2) {
b[i] = -a[i+1];
b[i+1] = a[i];
}
for (int i=0; i<n; i++) System.out.print(b[i]+" ");
}
else {
if (a[0]+a[1]!=0) {
b[0] = -a[2];
b[1] = -a[2];
b[2] = a[0]+a[1];
}
else if (a[0]+a[2]!=0) {
b[0] = -a[1];
b[2] = -a[1];
b[1] = a[0]+a[2];
}
else {
b[1] = -a[0];
b[2] = -a[0];
b[0] = a[1]+a[2];
}
for (int i=3; i<n-1; i+=2) {
b[i] = -a[i+1];
b[i+1] = a[i];
}
for (int i=0; i<n; i++) System.out.print(b[i]+" ");
}
System.out.println();
}
}
static class FastIO {
BufferedReader br;
StringTokenizer st;
PrintWriter pr;
public FastIO() throws IOException
{
br = new BufferedReader(new InputStreamReader(System.in));
}
public String next() throws IOException
{
while (st == null || !st.hasMoreElements()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
public int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); }
public long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); }
public double nextDouble() throws NumberFormatException, IOException
{
return Double.parseDouble(next());
}
public String nextLine() throws IOException
{
String str = br.readLine();
return str;
}
}
}
| 1 |
Plagiarised
|
46e9aed4
|
ee4f7b06
|
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public final class Solution {
public static void main(String[] args) throws Exception {
Reader sc = new Reader();
BufferedWriter op = new BufferedWriter(new OutputStreamWriter(System.out));
int n=sc.nextInt();
ArrayList<Integer> fill= new ArrayList<Integer>();
ArrayList<Integer> unfilled= new ArrayList<>();
for(int i=0;i<n;i++){
int x =sc.nextInt();
if(x==1){
fill.add(i);
}else{
unfilled.add(i);
}
}
Collections.sort(fill);
Collections.sort(unfilled);
long[][] dp =new long[fill.size()+1][unfilled.size()+1];
for(int i=0;i<fill.size()+1;i++){
for(int j=0;j<unfilled.size()+1;j++){
dp[i][j]=Integer.MAX_VALUE;
}
}
for(int i=0;i<unfilled.size()+1;i++){
dp[0][i]=0;
}
// for(int j=0;j<fill.size()+1;j++){
// dp[j][0]=0;
// }
for(int i=1;i<fill.size()+1;i++){
for(int j=1;j<unfilled.size()+1;j++){
dp[i][j]=Math.min(dp[i][j-1],dp[i-1][j-1]+Math.abs(fill.get(i-1)-unfilled.get(j-1)));
}
}
System.out.println(dp[fill.size()][unfilled.size()]);
// for(int i=0;i<fill.size()+1;i++){
// for(int j=0;j<unfilled.size()+1;j++)
// {
// System.out.print(dp[i][j]+" ");
// }
// System.out.println();
// }
}
}
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();
}
}
|
import java.io.*;
import java.util.*;
import java.lang.Math;
public class Main {
static PrintWriter pw;
static Scanner sc;
static StringBuilder ans;
static long mod = 1000000000+7;
static void pn(final Object arg) {
pw.print(arg);
pw.flush();
}
/*-------------- for input in an value ---------------------*/
static int ni() { return sc.nextInt(); }
static long nl() { return sc.nextLong(); }
static double nd() { return sc.nextDouble(); }
static String ns() { return sc.next(); }
static void ap(int arg) { ans.append(arg); }
static void ap(long arg) { ans.append(arg); }
static void ap(String arg) { ans.append(arg); }
static void ap(StringBuilder arg) { ans.append(arg); }
/*-------------- for input in an array ---------------------*/
static void inputIntegerArray(int arr[]){
for(int i=0; i<arr.length; i++)arr[i] = ni();
}
static void inputLongArray(long arr[]){
for(int i=0; i<arr.length; i++)arr[i] = nl();
}
static void inputStringArray(String arr[]){
for(int i=0; i<arr.length; i++)arr[i] = ns();
}
static void inputDoubleArray(double arr[]){
for(int i=0; i<arr.length; i++)arr[i] = nd();
}
/*-------------- File vs Input ---------------------*/
static void runFile() throws Exception {
sc = new Scanner(new FileReader("input.txt"));
pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
}
static void runIo() throws Exception {
pw =new PrintWriter(System.out);
sc = new Scanner(System.in);
}
static void swap(int a, int b) {
int t = a;
a = b;
b = t;
}
static boolean isPowerOfTwo (long x) { return x!=0 && ((x&(x-1)) == 0);}
static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); }
static int countDigit(long n){return (int)Math.floor(Math.log10(n) + 1);}
static boolean isPrime(int n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static boolean sv[] = new boolean[1000002];
static void seive() {
//true -> not prime
// false->prime
sv[0] = sv[1] = true;
sv[2] = false;
for(int i = 0; i< sv.length; i++) {
if( !sv[i] && (long)i*(long)i < sv.length ) {
for ( int j = i*i; j<sv.length ; j += i ) {
sv[j] = true;
}
}
}
}
static long binpow( long a, long b) {
long res = 1;
while (b > 0) {
if ( (b & 1) > 0){
res = (res * a)%mod;
}
a = (a * a)%mod;
b >>= 1;
}
return res;
}
static long factorial(long n) {
long res = 1, i;
for (i = 2; i <= n; i++){
res = ((res%mod) * (i%mod))%mod;
}
return res;
}
static class Pair {
int idx;
int v;
Pair(int idx, int v){
this.idx = idx;
this.v = v;
}
}
public static void main(String[] args) throws Exception {
// runFile();
runIo();
int t;
t = 1;
// t = sc.nextInt();
ans = new StringBuilder();
while( t-- > 0 ) {
solve();
}
pn(ans+"");
}
static int N ;
static int M ;
static ArrayList<Integer> f;
static ArrayList<Integer> e;
static long dp[][];
static long find(int i, int j ) {
if( i == N ) return 0;
if( j == M ) return Integer.MAX_VALUE;
if (dp[i][j] != -1 )
return dp[i][j];
return dp[i][j] = Math.min( find(i, j+1), Math.abs(f.get(i)-e.get(j)) + find(i+1, j+1) );
}
public static void solve() {
int n = ni();
f = new ArrayList();
e = new ArrayList();
for(int i = 0; i<n; i++) {
int v = ni();
if( v == 0 ) {
e.add(i);
}
else
f.add(i);
}
N = f.size();
M = e.size();
dp = new long[N][M];
for(int i = 0; i<N; i++)
Arrays.fill(dp[i], -1);
ap(find(0, 0)+"\n");
}
}
// 0 1 2 3 4 5 6 7
// 1 1 0 0 0 1 0 0
// 1s -> { 0, 1, 5 }
// 0s -> { 2, 3, 6, 7 }
| 0 |
Non-plagiarised
|
9756f13a
|
ea899386
|
import java.util.*;
import java.io.*;
public class PhoenixAndTowers {
public static void main(String [] args) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
int t = Integer.parseInt(in.readLine());
for (int test = 0; test < t; test++){
String [] data = in.readLine().split(" ");
int n = Integer.parseInt(data[0]);
int m = Integer.parseInt(data[1]);
int x = Integer.parseInt(data[2]);
data = in.readLine().split(" ");
intPair [] blocks = new intPair[n];
for (int i = 0; i < n; i++){
blocks[i] = new intPair(i, Integer.parseInt(data[i]));
}
Arrays.sort(blocks);
TreeSet<intPair> towers = new TreeSet<>();
// intPair [] towers = new intPair[m];
for (int i = 0; i < m; i++){
// towers[i] = new intPair(i+1, 0);
towers.add(new intPair(i+1, 0));
}
int [] newIdx = new int[n];
for (int i = n - 1; i >= 0; i--){
//Arrays.sort(towers);
intPair low = towers.pollFirst();
//towers[0].value += blocks[i].value;
low.value += blocks[i].value;
newIdx[blocks[i].idx] = low.idx;
towers.add(low);
}
int min = n*x;
int max = 0;
for (intPair tower : towers){
if (tower.value < min){
min = tower.value;
}
if (tower.value > max){
max = tower.value;
}
}
if (max - min <= x){
out.write("YES\n");
for (int i = 0; i < n; i++){
if (i != 0){
out.write(" " + newIdx[i]);
}else {
out.write("" + newIdx[i]);
}
}
out.write("\n");
} else {
out.write("NO\n");
}
}
out.close();
}
static class intPair implements Comparable<intPair>{
int idx;
int value;
intPair(int idx, int value){
this.idx = idx;
this.value = value;
}
@Override
public int compareTo(PhoenixAndTowers.intPair o) {
return this.value != o.value? this.value - o.value: this.idx - o.idx;
}
}
}
|
import java.io.*;
import java.util.*;
public class Codeforces {
public static class Tower implements Comparable<Tower>{
int val;
int index;
public Tower(int ind, int v) {
val = v;
index = ind;
}
@Override
public int compareTo(Tower o) {
return Integer.compare(val, o.val);
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int cases = Integer.parseInt(br.readLine());
while(cases-- > 0) {
String[] str = br.readLine().split(" ");
int n = Integer.parseInt(str[0]);
int m = Integer.parseInt(str[1]);
int x = Integer.parseInt(str[2]);
int[] h = new int[n];
str = br.readLine().split(" ");
for(int i=0; i<n; i++) {
h[i] = Integer.parseInt(str[i]);
}
PriorityQueue<Tower> q = new PriorityQueue<>(m);
int[] ans = new int[n];
for(int i=0; i<m; i++) {
q.add(new Tower(i, h[i]));
ans[i] = i;
}
for(int i=m; i<n; i++) {
Tower lowest = q.poll();
lowest.val += h[i];
ans[i] = lowest.index;
q.add(lowest);
}
System.out.println("YES");
for(int i=0; i<n; i++) {
System.out.print((ans[i]+1) + " ");
}
System.out.println();
}
}
}
| 0 |
Non-plagiarised
|
6db218a2
|
8ad1ad84
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.InputMismatchException;
import java.util.*;
import java.io.*;
import java.lang.*;
public class Main{
public static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars==-1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
}
catch (IOException e) {
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
public int nextInt() {
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if(c<'0'||c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static long gcd(long a, long b){
if (a == 0)
return b;
return gcd(b % a, a);
}
static long lcm(long a, long b) {
return (a*b)/gcd(a, b);
}
public static void sortbyColumn(int arr[][], int col)
{
Arrays.sort(arr, new Comparator<int[]>() {
@Override
public int compare(final int[] entry1,
final int[] entry2) {
if (entry1[col] > entry2[col])
return 1;
else
return -1;
}
});
}
static long func(long a[],int size,int s){
long max1=a[s];
long maxc=a[s];
for(int i=s+1;i<size;i++){
maxc=Math.max(a[i],maxc+a[i]);
max1=Math.max(maxc,max1);
}
return max1;
}
public static class Pair<U extends Comparable<U>, V extends Comparable<V>> implements Comparable<Pair<U, V>> {
public U x;
public V y;
public Pair(U x, V y) {
this.x = x;
this.y = y;
}
public int hashCode() {
return (x == null ? 0 : x.hashCode() * 31) + (y == null ? 0 : y.hashCode());
}
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Pair<U, V> p = (Pair<U, V>) o;
return (x == null ? p.x == null : x.equals(p.x)) && (y == null ? p.y == null : y.equals(p.y));
}
public int compareTo(Pair<U, V> b) {
int cmpU = x.compareTo(b.x);
return cmpU != 0 ? cmpU : y.compareTo(b.y);
}
public String toString() {
return String.format("(%s, %s)", x.toString(), y.toString());
}
}
static class MultiSet<U extends Comparable<U>> {
public int sz = 0;
public TreeMap<U, Integer> t;
public MultiSet() {
t = new TreeMap<>();
}
public void add(U x) {
t.put(x, t.getOrDefault(x, 0) + 1);
sz++;
}
public void remove(U x) {
if (t.get(x) == 1) t.remove(x);
else t.put(x, t.get(x) - 1);
sz--;
}
}
static void shuffle(long[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
long temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
static long myceil(long a, long b){
return (a+b-1)/b;
}
static long C(long n,long r){
long count=0,temp=n;
long ans=1;
long num=n-r+1,div=1;
while(num<=n){
ans*=num;
//ans+=MOD;
ans%=MOD;
ans*=mypow(div,MOD-2);
//ans+=MOD;
ans%=MOD;
num++;
div++;
}
ans+=MOD;
return ans%MOD;
}
static long fact(long a){
long i,ans=1;
for(i=1;i<=a;i++){
ans*=i;
ans%=MOD;
}
return ans%=MOD;
}
static void sieve(int n){
is_sieve[0]=1;
is_sieve[1]=1;
int i,j,k;
for(i=2;i<n;i++){
if(is_sieve[i]==0){
sieve[i]=i;
tr.add(i);
for(j=i*i;j<n;j+=i){
if(j>n||j<0){
break;
}
is_sieve[j]=1;
sieve[j]=i;
}
}
}
}
// static void calc(int n){
// int i,j;
// dp[n-1]=0;
// if(n>1)
// dp[n-2]=1;
// for(i=n-3;i>=0;i--){
// long ind=n-i-1;
// dp[i]=((ind*(long)mypow(10,ind-1))%MOD+dp[i+1])%MOD;
// }
// }
static long mypow(long x,long y){
long temp;
if( y == 0)
return 1;
temp = mypow(x, y/2);
if (y%2 == 0)
return (temp*temp)%MOD;
else
return ((x*temp)%MOD*(temp)%MOD)%MOD;
}
static long dist[],dp[][],left[],right[];
static int visited[],isit[];
static ArrayList<Pair<Integer,Pair<Long,Long>>> adj[],li;
//static int dp[][][];
static int MOD=1000000007;
static char ch[];
static int[] sieve,is_sieve;
static TreeSet<Integer> tr;
static long mat[][];
static void dfs(int node,int par, Pair<Long,Long> p[]){
for(Pair<Integer,Pair<Long,Long>> pp:adj[node]){
if(pp.x!=par){
//sum+=Math.abs(selected[node]-selected[pp.x]);
dfs(pp.x,node,p);
//System.out.println(node+" "+pp.x);
long x=Math.abs(p[node].x-p[pp.x].x);
long y=Math.abs(p[node].x-p[pp.x].y);
long z=Math.abs(p[node].y-p[pp.x].x);
long w=Math.abs(p[node].y-p[pp.x].y);
left[node]+=Math.max(x+left[pp.x],y+right[pp.x]);
right[node]+=Math.max(z+left[pp.x],w+right[pp.x]);
}
}
}
public static void main(String args[]){
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter w = new PrintWriter(outputStream);
int t,i,j,tno=0,tte;
t=in.nextInt();
//t=1;
//tte=t;
while(t-->0){
//sum=0;
int n=in.nextInt();
adj=new ArrayList[n+1];
left=new long[n+1];
right=new long[n+1];
visited=new int[n+1];
for(i=0;i<n+1;i++){
adj[i]=new ArrayList<>();
}
Pair<Long,Long> p[]=new Pair[n+1];
for(i=1;i<=n;i++){
p[i]=new Pair<>(in.nextLong(),in.nextLong());
}
for(i=0;i<n-1;i++){
int u,v;
u=in.nextInt();
v=in.nextInt();
adj[u].add(new Pair<>(v,p[v]));
adj[v].add(new Pair<>(u,p[u]));
}
dfs(1,-1,p);
// for(i=0;i<n+1;i++){
// w.print(selected[i]+" ");
// }
// w.println();
w.println((long)Math.max(left[1],right[1]));
}
w.close();
}
}
|
import java.io.*;
import java.util.*;
import java.math.*;
import java.math.BigInteger;
//import javafx.util.*;
public final class B
{
static PrintWriter out = new PrintWriter(System.out);
static StringBuilder ans=new StringBuilder();
static FastReader in=new FastReader();
static ArrayList<Integer> g[];
static long mod=(long)(1e9+7);
static int D1[],D2[],par[];
static boolean set[];
static int value[];
static long INF=Long.MAX_VALUE;
static int N,M;
static long L[],R[],dp[][];
static int s=1;
public static void main(String args[])throws IOException
{
int T=i();
outer:while(T-->0)
{
int N=i();
setGraph(N);
for(int i=1; i<=N; i++)
{
L[i]=l();
R[i]=l();
}
for(int i=1; i<N; i++)
{
int a=i(),b=i();
g[a].add(b);
g[b].add(a);
}
f(1,-1);
out.println(Math.max(dp[0][1], dp[1][1]));
}
out.close();
//print(L);
//print(R);
//print(dp[0]);
//print(dp[1]);
}
static void f(int n,int p)
{
for(int c:g[n])
{
if(c!=p)
{
f(c,n);
long a=dp[0][c]+Math.abs(L[c]-L[n]);
long b=dp[1][c]+Math.abs(R[c]-L[n]);
dp[0][n]+=Math.max(a, b);
a=dp[0][c]+Math.abs(L[c]-R[n]);
b=dp[1][c]+Math.abs(R[c]-R[n]);
dp[1][n]+=Math.max(a, b);
}
}
}
static boolean isPalin(char X[])
{
int l=0,r=X.length-1;
while(l<=r)
{
if(X[l]!=X[r])return false;
l++;
r--;
}
return true;
}
static boolean isSorted(int A[])
{
int N=A.length;
for(int i=0; i<N-1; i++)
{
if(A[i]>A[i+1])return false;
}
return true;
}
static int f1(int x,ArrayList<Integer> A)
{
int l=-1,r=A.size();
while(r-l>1)
{
int m=(l+r)/2;
int a=A.get(m);
if(a<x)l=m;
else r=m;
}
return l;
}
static int ask(int t,int i,int j,int x)
{
System.out.println("? "+t+" "+i+" "+j+" "+x);
return i();
}
static int ask(int a)
{
System.out.println("? 1 "+a);
return i();
}
static int f(int st,int end,int d)
{
if(st>end)return 0;
int a=0,b=0,c=0;
if(d>1)a=f(st+d-1,end,d-1);
b=f(st+d,end,d);
c=f(st+d+1,end,d+1);
return value[st]+max(a,b,c);
}
static int max(int a,int b,int c)
{
return Math.max(a, Math.max(c, b));
}
static int value(char X[],char Y[])
{
int c=0;
for(int i=0; i<7; i++)
{
if(Y[i]=='1' && X[i]=='0')return -1;
if(X[i]=='1' && Y[i]=='0')c++;
}
return c;
}
static boolean isValid(int i,int j)
{
if(i<0 || i>=N)return false;
if(j<0 || j>=M)return false;
return true;
}
static long fact(long N)
{
long num=1L;
while(N>=1)
{
num=((num%mod)*(N%mod))%mod;
N--;
}
return num;
}
static boolean reverse(long A[],int l,int r)
{
while(l<r)
{
long t=A[l];
A[l]=A[r];
A[r]=t;
l++;
r--;
}
if(isSorted(A))return true;
else return false;
}
static boolean isSorted(long A[])
{
for(int i=1; i<A.length; i++)if(A[i]<A[i-1])return false;
return true;
}
static boolean isPalindrome(char X[],int l,int r)
{
while(l<r)
{
if(X[l]!=X[r])return false;
l++; r--;
}
return true;
}
static long min(long a,long b,long c)
{
return Math.min(a, Math.min(c, b));
}
static void print(int a)
{
System.out.println("! "+a);
}
static int ask(int a,int b)
{
System.out.println("? "+a+" "+b);
return i();
}
static int find(int a)
{
if(par[a]<0)return a;
return par[a]=find(par[a]);
}
static void union(int a,int b)
{
a=find(a);
b=find(b);
if(a!=b)
{
par[a]+=par[b]; //transfers the size
par[b]=a; //changes the parent
}
}
static void swap(char A[],int a,int b)
{
char ch=A[a];
A[a]=A[b];
A[b]=ch;
}
static void sort(long[] a) //check for long
{
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 setGraph(int N)
{
g=new ArrayList[N+1];
dp=new long[2][N+1];
L=new long[N+1];
R=new long[N+1];
for(int i=0; i<=N; i++)
{
g[i]=new ArrayList<Integer>();
}
}
static long pow(long a,long b)
{
long mod=1000000007;
long pow=1;
long x=a;
while(b!=0)
{
if((b&1)!=0)pow=(pow*x)%mod;
x=(x*x)%mod;
b/=2;
}
return pow;
}
static long toggleBits(long x)//one's complement || Toggle bits
{
int n=(int)(Math.floor(Math.log(x)/Math.log(2)))+1;
return ((1<<n)-1)^x;
}
static int countBits(long a)
{
return (int)(Math.log(a)/Math.log(2)+1);
}
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 boolean isPrime(long N)
{
if (N<=1) return false;
if (N<=3) return true;
if (N%2 == 0 || N%3 == 0) return false;
for (int i=5; i*i<=N; i=i+6)
if (N%i == 0 || N%(i+2) == 0)
return false;
return true;
}
static long GCD(long a,long b)
{
if(b==0)
{
return a;
}
else return GCD(b,a%b );
}
//Debugging Functions Starts
static void print(char A[])
{
for(char c:A)System.out.print(c+" ");
System.out.println();
}
static void print(boolean A[])
{
for(boolean c:A)System.out.print(c+" ");
System.out.println();
}
static void print(int A[])
{
for(int a:A)System.out.print(a+" ");
System.out.println();
}
static void print(long A[])
{
for(long i:A)System.out.print(i+ " ");
System.out.println();
}
static void print(ArrayList<Integer> A)
{
for(int a:A)System.out.print(a+" ");
System.out.println();
}
//Debugging Functions END
//----------------------
//IO FUNCTIONS STARTS
static HashMap<Integer,Integer> Hash(int A[])
{
HashMap<Integer,Integer> mp=new HashMap<>();
for(int a:A)
{
int f=mp.getOrDefault(a,0)+1;
mp.put(a, f);
}
return mp;
}
static int i()
{
return in.nextInt();
}
static long l()
{
return in.nextLong();
}
static int[] input(int N){
int A[]=new int[N];
for(int i=0; i<N; i++)
{
A[i]=in.nextInt();
}
return A;
}
static long[] inputLong(int N) {
long A[]=new long[N];
for(int i=0; i<A.length; i++)A[i]=in.nextLong();
return A;
}
//IO FUNCTIONS END
}
class node implements Comparable<node>
{
int x,index; boolean right;
node(int x,boolean right,int index)
{
this.x=x;
this.right=right;
this.index=index;
}
public int compareTo(node X)
{
return this.x-X.x;
}
}
//Code For FastReader
//Code For FastReader
//Code For FastReader
//Code For FastReader
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());
}
//gey
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str="";
try
{
str=br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
| 0 |
Non-plagiarised
|
51019113
|
bf85ab7b
|
import java.io.*;
import java.math.*;
import java.util.*;
public class test {
static class Pair{
long x;
long y;
Pair(long x,long y){
this.x = x;
this.y = y;
}
}
static class Compare {
void compare(Pair arr[], int n)
{
// Comparator to sort the pair according to second element
Arrays.sort(arr, new Comparator<Pair>() {
@Override public int compare(Pair p1, Pair p2)
{
if(p1.x!=p2.x) {
return (int)(p1.x - p2.x);
}
else {
return (int)(p1.y - p2.y);
}
}
});
// for (int i = 0; i < n; i++) {
// System.out.print(arr[i].x + " " + arr[i].y + " ");
// }
// System.out.println();
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner()
{
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static void dfs(int cur , int prnt , ArrayList<Integer> graph[],long dp[][],Pair p[]) {
for(int i : graph[cur]) {
if(i!=prnt) {
dfs(i,cur,graph,dp,p);
dp[cur][0] += Math.max(Math.abs(p[cur].x - p[i].x)+ dp[i][0], Math.abs(p[cur].x - p[i].y)+dp[i][1]);
dp[cur][1] += Math.max(Math.abs(p[cur].y -p[i].x) + dp[i][0], Math.abs(p[cur].y - p[i].y)+dp[i][1]);
}
}
}
public static void main(String args[]) throws Exception {
Scanner sc = new Scanner();
StringBuffer res = new StringBuffer();
int tc = sc.nextInt();
while(tc-->0) {
int n = sc.nextInt();
Pair p[] = new Pair[n+1];
for(int i=1;i<=n;i++) {
p[i] = new Pair(0,0);
p[i].x = sc.nextLong();
p[i].y = sc.nextLong();
}
ArrayList<Integer> graph[] = new ArrayList[n+1];
for(int i=0;i<n+1;i++) {
graph[i] = new ArrayList<>();
}
for(int i=0;i<n-1;i++) {
int u = sc.nextInt();
int v = sc.nextInt();
graph[u].add(v);
graph[v].add(u);
}
long dp[][] = new long[n+1][2];
dfs(1,0,graph,dp,p);
System.out.println(Math.max(dp[1][0], dp[1][1]));
}
System.out.println(res);
}
}
|
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class ParsasHumongousTree {
public static void main(String args[]) throws IOException {
Reader scan = new Reader();
StringBuilder sb = new StringBuilder();
int t = scan.nextInt();
while (t-- > 0) {
int n = scan.nextInt();
int[] l = new int[n + 1];
int[] r = new int[n + 1];
for (int i = 1; i <= n; i++) {
l[i] = scan.nextInt();
r[i] = scan.nextInt();
}
Graph g = new Graph(n);
for (int i = 0; i < n - 1; i++) {
g.addEdge(scan.nextInt(), scan.nextInt());
}
sb.append(g.dfs(l, r) + "\n");
}
System.out.println(sb);
}
}
class Graph {
ArrayList<Integer>[] node;
int n;
int c = 0;
boolean[] vis;
Graph(int s) {
n = s + 1;
vis = new boolean[n + 1];
node = new ArrayList[n + 1];
for (int i = 0; i < n + 1; i++) {
node[i] = new ArrayList<>();
}
}
void addEdge(int u, int v) {
node[u].add(v);
node[v].add(u);
if (node[u].size() == 1) {
c = u;
}
if (node[v].size() == 1) {
c = v;
}
}
void cleanVisArray() {
for (int i = 0; i < n + 1; i++) {
vis[i] = false;
}
}
long dfs(int[] l, int[] r) {
cleanVisArray();
long[][] dp = new long[n][2];
dfsMain(1, dp, l, r);
return Math.max(dp[1][0], dp[1][1]);
}
void dfsMain(int v, long[][] dp, int[] l, int[] r) {
vis[v] = true;
for (int i : node[v]) {
if (!vis[i]) {
dfsMain(i, dp, l, r);
dp[v][0] += Math.max(Math.abs(l[v] - l[i]) + dp[i][0], Math.abs(l[v] - r[i]) + dp[i][1]);
dp[v][1] += Math.max(Math.abs(r[v] - l[i]) + dp[i][0], Math.abs(r[v] - r[i]) + dp[i][1]);
}
}
}
}
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();
}
}
| 0 |
Non-plagiarised
|
e2fe9d7d
|
ece1820d
|
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.SortedSet;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
public class C_Edu_Round_120 {
public static long MOD = 998244353;
static int[] dp;
public static void main(String[] args) throws FileNotFoundException {
// PrintWriter out = new PrintWriter(new FileOutputStream(new File(
// "output.txt")));
PrintWriter out = new PrintWriter(System.out);
Scanner in = new Scanner();
int T = in.nextInt();
//System.out.println(cal(1608737403, 1000000000) - 923456789987654321L);
for (int z = 0; z < T; z++) {
int n = in.nextInt();
long k = in.nextLong();
long[] data = new long[n];
long total = 0;
PriorityQueue<Integer> q = new PriorityQueue<>();
for (int i = 0; i < n; i++) {
q.add(in.nextInt());
}
for (int i = 0; i < n; i++) {
data[i] = q.poll();
total += data[i];
}
Arrays.sort(data);
long result = Long.max(0, total - k);
long cur = 0;
int num = 0;
for (int i = n - 1; i > 0 && total > k + cur; i--) {
num++;
cur += data[i] - data[0];
long left = Long.max(0, total - cur - k);
left /= (num + 1);
if (total - cur - (left * (num + 1)) > k) {
left++;
}
//System.out.println(num + " " + left + " " + cur + " " + total);
result = Long.min(result, left + num);
}
out.println(result);
}
out.close();
}
static long cal(long msg, long k) {
if (msg <= k) {
return msg * (msg + 1L) / 2L;
}
long re = k * (k + 1L) / 2L;
long left = 2 * k - 1 - msg;
long other = (k - 1) * k / 2;
other -= left * (left + 1) / 2;
//System.out.println(other);
return re + other;
}
static long cal2(long msg, long k) {
if (msg <= k) {
return BigInteger.valueOf(msg).multiply(BigInteger.valueOf(msg + 1)).shiftRight(1).longValue();
}
BigInteger re = BigInteger.valueOf(k).multiply(BigInteger.valueOf(k + 1)).shiftRight(1);
long left = 2 * k - 1 - msg;
BigInteger other = BigInteger.valueOf(k).multiply(BigInteger.valueOf(k - 1)).shiftRight(1);
other = other.subtract(BigInteger.valueOf(left).multiply(BigInteger.valueOf(left + 1)).shiftRight(1));
return re.add(other).longValue();
}
static int find(int index, int[] u) {
if (u[index] != index) {
return u[index] = find(u[index], u);
}
return index;
}
static int abs(int a) {
return a < 0 ? -a : a;
}
public static int[] KMP(String val) {
int i = 0;
int j = -1;
int[] result = new int[val.length() + 1];
result[0] = -1;
while (i < val.length()) {
while (j >= 0 && val.charAt(j) != val.charAt(i)) {
j = result[j];
}
j++;
i++;
result[i] = j;
}
return result;
}
public static boolean nextPer(int[] data) {
int i = data.length - 1;
while (i > 0 && data[i] < data[i - 1]) {
i--;
}
if (i == 0) {
return false;
}
int j = data.length - 1;
while (data[j] < data[i - 1]) {
j--;
}
int temp = data[i - 1];
data[i - 1] = data[j];
data[j] = temp;
Arrays.sort(data, i, data.length);
return true;
}
public static int digit(long n) {
int result = 0;
while (n > 0) {
n /= 10;
result++;
}
return result;
}
public static double dist(long a, long b, long x, long y) {
double val = (b - a) * (b - a) + (x - y) * (x - y);
val = Math.sqrt(val);
double other = x * x + a * a;
other = Math.sqrt(other);
return val + other;
}
public static class Point {
int x;
int y;
public Point(int start, int end) {
this.x = start;
this.y = end;
}
public String toString() {
return x + " " + y;
}
}
public static class FT {
long[] data;
FT(int n) {
data = new long[n];
}
public void update(int index, long value) {
while (index < data.length) {
data[index] += value;
index += (index & (-index));
}
}
public long get(int index) {
long result = 0;
while (index > 0) {
result += data[index];
index -= (index & (-index));
}
return result;
}
}
public static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
public static long pow(long a, int b) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long val = pow(a, b / 2);
if (b % 2 == 0) {
return (val * val) % MOD;
} else {
return (val * ((val * a) % MOD)) % MOD;
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() throws FileNotFoundException {
// System.setOut(new PrintStream(new BufferedOutputStream(System.out), true));
br = new BufferedReader(new InputStreamReader(System.in));
//br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt"))));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
throw new RuntimeException();
}
}
return st.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
st = null;
try {
return br.readLine();
} catch (Exception e) {
throw new RuntimeException();
}
}
public boolean endLine() {
try {
String next = br.readLine();
while (next != null && next.trim().isEmpty()) {
next = br.readLine();
}
if (next == null) {
return true;
}
st = new StringTokenizer(next);
return st.hasMoreTokens();
} catch (Exception e) {
throw new RuntimeException();
}
}
}
}
|
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
public class a729 {
public static void main(String[] args) throws IOException {
// try {
BufferedWriter out = new BufferedWriter(
new OutputStreamWriter(System.out));
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
PrintWriter pt = new PrintWriter(System.out);
FastReader sc = new FastReader();
int t = sc.nextInt();
for(int o = 0 ; o<t;o++){
int n = sc.nextInt();
long k = sc.nextLong();
long[] arr = new long[n];
for(int i = 0 ; i<n;i++) {
arr[i] = sc.nextLong();
}
shuffleArray(arr);
Arrays.sort(arr);
long[] psum = new long[n+1];
for(int i = 1; i<=n;i++){
psum[i] = psum[i-1] + arr[i-1];
}
if(n==1) {
long val = arr[0]-k;
val = Math.max(0, val);
System.out.println(val);
continue;
}
if(k>=psum[n]) {
System.out.println(0);
continue;
}
long ans = Integer.MAX_VALUE;
long x = 0;
long a1 = arr[0];
for(int y = 0 ; y<n;y++) {
long val = psum[n-y] + y*a1 - k;
// if(val<0) {
// continue;
// }
x = val/(y+1);
if(val%(y+1)!=0 && val>0) {
x++;
}
// if(x<0) {
// continue;
// }
ans = Math.min(ans, Math.max(x, 0) + y);
}
ans = Math.max(ans, 0);
System.out.println(ans);
}
// }catch(Exception e) {
// return;
// }
}
//------------------------------------------------------------------------------------------------------------------------------------------------
static int cntDivisors(int n)
{
int cnt = 0;
for (int i=1; i<=Math.sqrt(n); i++)
{
if (n%i==0)
{
if (n/i == i)
cnt++;
else
cnt+=2;
}
}
return cnt;
}
public static long findgcd(long[] arr,int v) {
int n = arr.length;
long g = arr[v];
for(int i = v ; i<n;i+=2) {
g = gcd(g, arr[i]);
}
return g;
}
public static int count(long x) {
int a = 0;
while(x>0) {
x/=2;
a++;
}
return a;
}
public static long ncr(long[] fac, int n , int r , long m) {
return fac[n]*(modInverse(fac[r], m))%m *(modInverse(fac[n-r], m))%m;
}
public static void build(int [][] seg,char []arr,int idx, int lo , int hi) {
if(lo == hi) {
// seg[idx] = arr[lo];
seg[idx][(int)arr[lo]-'a'] = 1;
return;
}
int mid = (lo + hi)/2;
build(seg,arr,2*idx+1, lo, mid);
build(seg,arr,idx*2+2, mid +1, hi);
//seg[idx] = Math.min(seg[2*idx+1],seg[2*idx+2]);
for(int i = 0 ; i<27;i++) {
seg[idx][i] = seg[2*idx+1][i] + seg[2*idx + 2][i];
}
}
//for f/inding minimum in range
public static void query(int[][]seg,int[]ans,int idx , int lo , int hi , int l , int r) {
if(lo>=l && hi<=r) {
for(int i = 0 ; i<27;i++) {
ans[i]+= seg[idx][i];
}
return ;
}
if(hi<l || lo>r) {
return;
}
int mid = (lo + hi)/2;
query(seg,ans,idx*2 +1, lo, mid, l, r);
query(seg,ans,idx*2 + 2, mid + 1, hi, l, r);
//return Math.min(left, right);
}
//// for sum
//
public static void update(int[][]seg,char[]arr,int idx, int lo , int hi , int node , char val) {
if(lo == hi) {
// seg[idx] += val;
seg[idx][val-'a']++;
seg[idx][arr[node]-'a']--;
}else {
int mid = (lo + hi )/2;
if(node<=mid && node>=lo) {
update(seg,arr, idx * 2 +1, lo, mid, node, val);
}else {
update(seg,arr, idx*2 + 2, mid + 1, hi, node, val);
}
//seg[idx] = seg[idx*2 + 1] + seg[idx*2 + 2];
for(int i = 0 ; i<27;i++) {
seg[idx][i] = seg[2*idx+1][i] + seg[2*idx + 2][i];
}
}
}
public static int lower_bound(int array[], int low, int high, int key){
// Base Case
if (low > high) {
return low;
}
// Find the middle index
int mid = low + (high - low) / 2;
// If key is lesser than or equal to
// array[mid] , then search
// in left subarray
if (key <= array[mid]) {
return lower_bound(array, low,
mid - 1, key);
}
// If key is greater than array[mid],
// then find in right subarray
return lower_bound(array, mid + 1, high,
key);
}
public static int upper_bound(int arr[], int low,
int high, int key){
// Base Case
if (low > high || low == arr.length)
return low;
// Find the value of middle index
int mid = low + (high - low) / 2;
// If key is greater than or equal
// to array[mid], then find in
// right subarray
if (key >= arr[mid]) {
return upper_bound(arr, mid + 1, high,
key);
}
// If key is less than array[mid],
// then find in left subarray
return upper_bound(arr, low, mid - 1,
key);
}
// -----------------------------------------------------------------------------------------------------------------------------------------------
public static long gcd(long a, long b){
if (a == 0)
return b;
return gcd(b % a, a);
}
//--------------------------------------------------------------------------------------------------------------------------------------------------------
public static long modInverse(long a, long m){
long m0 = m;
long y = 0, x = 1;
if (m == 1)
return 0;
while (a > 1) {
// q is quotient
long q = a / m;
long t = m;
// m is remainder now, process
// same as Euclid's algo
m = a % m;
a = t;
t = y;
// Update x and y
y = x - q * y;
x = t;
}
// Make x positive
if (x < 0)
x += m0;
return x;
}
//-----------------------------------------------------------------------------------------------------------------------------------
//segment tree
//for finding minimum in range
// public static void build(int [] seg,int []arr,int idx, int lo , int hi) {
// if(lo == hi) {
// seg[idx] = arr[lo];
// return;
// }
// int mid = (lo + hi)/2;
// build(seg,arr,2*idx+1, lo, mid);
// build(seg,arr,idx*2+2, mid +1, hi);
// seg[idx] = Math.min(seg[2*idx+1],seg[2*idx+2]);
// }
////for finding minimum in range
//public static int query(int[]seg,int idx , int lo , int hi , int l , int r) {
// if(lo>=l && hi<=r) {
// return seg[idx];
// }
// if(hi<l || lo>r) {
// return Integer.MAX_VALUE;
// }
// int mid = (lo + hi)/2;
// int left = query(seg,idx*2 +1, lo, mid, l, r);
// int right = query(seg,idx*2 + 2, mid + 1, hi, l, r);
// return Math.min(left, right);
//}
// // for sum
//
//public static void update(int[]seg,int idx, int lo , int hi , int node , int val) {
// if(lo == hi) {
// seg[idx] += val;
// }else {
//int mid = (lo + hi )/2;
//if(node<=mid && node>=lo) {
// update(seg, idx * 2 +1, lo, mid, node, val);
//}else {
// update(seg, idx*2 + 2, mid + 1, hi, node, val);
//}
//seg[idx] = seg[idx*2 + 1] + seg[idx*2 + 2];
//
//}
//}
//---------------------------------------------------------------------------------------------------------------------------------------
static void shuffleArray(long[] ar)
{
// If running on Java 6 or older, use `new Random()` on RHS here
Random rnd = ThreadLocalRandom.current();
for (int i = ar.length - 1; i > 0; i--)
{
int index = rnd.nextInt(i + 1);
// Simple swap
long a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
}
//-----------------------------------------------------------------------------------------------------------------------------------------------------------
}
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;
}
}
//------------------------------------------------------------------------------------------------------------------------------------------------------------
class SegmentTree{
int n;
public SegmentTree(int[] arr,int n) {
this.arr = arr;
this.n = n;
}
int[] arr = new int[n];
// int n = arr.length;
int[] seg = new int[4*n];
void build(int idx, int lo , int hi) {
if(lo == hi) {
seg[idx] = arr[lo];
return;
}
int mid = (lo + hi)/2;
build(2*idx+1, lo, mid);
build(idx*2+2, mid +1, hi);
seg[idx] = Math.min(seg[2*idx+1],seg[2*idx+2]);
}
int query(int idx , int lo , int hi , int l , int r) {
if(lo<=l && hi>=r) {
return seg[idx];
}
if(hi<l || lo>r) {
return Integer.MAX_VALUE;
}
int mid = (lo + hi)/2;
int left = query(idx*2 +1, lo, mid, l, r);
int right = query(idx*2 + 2, mid + 1, hi, l, r);
return Math.min(left, right);
}
}
//-----------------------------------------------------------------------------------------------------------------------------------------------------------
class coup{
char a;
int b;
public coup(char a , int b) {
this.a = a;
this.b = b;
}
}
class trip{
int a , b, c;
public trip(int a , int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
}
| 0 |
Non-plagiarised
|
51d857bc
|
63118334
|
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Round659 {
static int rec = 0;
static int X[] = { -1, 0, 0, 1 };
static int Y[] = { 0, -1, 1, 0 };
static long mod = 1000000007;
static int last=0;
static int maxDepth=0;
static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null)
return;
din.close();
}
}
public static long[] initArray(int n, Reader scan) throws IOException {
long arr[] = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = scan.nextLong();
}
return arr;
}
public static long sum(long arr[]) {
long sum = 0;
for (long i : arr) {
sum += (long) i;
}
return sum;
}
public static long max(long arr[]) {
long max = Long.MIN_VALUE;
for (long i : arr) {
max = Math.max(i, max);
}
return max;
}
public static long min(long arr[]) {
long min = Long.MAX_VALUE;
for (long i : arr) {
min = Math.min(i, min);
}
return min;
}
public static List<Integer>[] initAdjacency(int n, int e, Reader scan, boolean type) throws IOException {
List<Integer> adj[] = new ArrayList[n + 1];
for (int i = 0; i < e; i++) {
int u = scan.nextInt();
int v = scan.nextInt();
if (adj[u] == null)
adj[u] = new ArrayList<>();
if (type && adj[v] == null)
adj[v] = new ArrayList<>();
adj[u].add(v);
if (type)
adj[v].add(u);
}
return adj;
}
public static void main(String[] args) throws IOException {
Reader scan = new Reader();
// Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
while (t-- > 0) {
D(scan);
}
}
public static void D(Reader scan) throws IOException {
int n=scan.nextInt();
int a=scan.nextInt();
int b=scan.nextInt();
int da=scan.nextInt();
int db=scan.nextInt();
List<Integer> adj[]=initAdjacency(n, n-1, scan, true);
int d= dist(a, 0, adj, b);
if(d<=da) {
System.out.println("Alice");
return;
}
if(db<=2*da) {
System.out.println("Alice");
return;
}
MyPair far1= farthest(1, 0, adj);
MyPair far2=farthest(far1.weight, 0, adj);
int diameter= far2.value-1;
if(diameter<=2*da) {
System.out.println("Alice");
}else {
System.out.println("Bob");
}
// int val=d-2*a;
//
// if(val>0) {
// System.out.println("Bob");
// return;
// }
//
// int dep=0;
// for(Integer x: adj[a]) {
// if(x==last) continue;
//
// dep=Math.max(getDepth(x, a, adj), dep);
// }
//
// if(dep>=val) {
// System.out.println("Bob");
// }else {
// System.out.println("Alice");
// }
}
public static MyPair farthest(int i, int parent, List<Integer> adj[]) {
int dist=0;
int node= i;
for(Integer x: adj[i]) {
if(x==parent) continue;
MyPair recAns= farthest(x, i, adj);
if(recAns.value>dist) {
dist= recAns.value;
node= recAns.weight;
}
}
return new MyPair(dist+1, node);
}
public static int getDepth(int i, int parent, List<Integer> adj[]) {
int max=0;
for(Integer x: adj[i]) {
if(x==parent) continue;
max=Math.max(max, getDepth(x, i, adj));
}
return max+1;
}
public static int dist(int i, int parent, List<Integer> adj[], int target) {
if(i==target) return 0;
for(Integer x: adj[i]) {
if(x==parent) continue;
int recAns= dist(x, i, adj, target);
if(recAns!=-1) {
last=x;
return recAns+1;
}
}
return -1;
}
public static void C(int n, String s, int k) {
char arr[]= s.toCharArray();
for(int i=0;i<n;i++) {
if(i+k>=n) break;
if(arr[i]=='0'&&arr[i+k]=='1') {
System.out.println("NO");
return;
}
if(arr[i]=='1'&&arr[i+k]=='0') {
System.out.println("NO");
return;
}
if(arr[i]=='0'||arr[i]=='1') {
if(arr[i+k]=='?') {
arr[i+k]=arr[i];
}
continue;
}
if(arr[i+k]=='0'||arr[i+k]=='1') {
if(arr[i]=='?') {
arr[i]=arr[i+k];
}
continue;
}
}
int c0[]=new int[n];
int c1[]=new int[n];
int last0=0;
int last1=0;
for(int i=0;i<n;i++) {
if(arr[i]=='0') {
last0++;
}else if(arr[i]=='1'){
last1++;
}
c0[i]=last0;
c1[i]=last1;
}
for(int i=k-1;i<n;i++) {
int count0= c0[i]- ((i-k<0)?0: c0[i-k]);
int count1= c1[i]- ((i-k<0)?0: c1[i-k]);
if(count0>k/2||count1>k/2) {
System.out.println("NO");
return;
}
}
System.out.println("YES");
}
public static void A(int n, long arr[]) {
for(int i=n-1;i>=0;i--) {
System.out.print(arr[i]+" ");
}
System.out.println();
}
public static void B(int n, long arr[]) {
for(int i=1;i<n;i++) {
if(arr[i-1]>0) {
arr[i]+= arr[i-1];
arr[i-1]=0;
}
}
// System.out.println(Arrays.toString(arr));
long ans=0;
for(Long x: arr) {
if(x<0) ans+= -x;
}
System.out.println(ans);
}
}
class MyPair {
int value;
int weight;
public MyPair(int value, int w) {
this.value = value;
weight = w;
}
}
|
import java.util.*;
import java.io.*;
public class MyClass
{
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
static class Pair implements Comparable<Pair>
{
int f,s;
Pair(int f,int s)
{
this.f=f;
this.s=s;
}
public int compareTo(Pair p)
{
return this.f-p.f;
}
}
static ArrayList<Integer> edge[];
public static void main(String args[])
{
FastReader fs=new FastReader();
PrintWriter pw=new PrintWriter(System.out);
int tc=fs.nextInt();
while(tc-->0)
{
int n=fs.nextInt();
int a=fs.nextInt();
int b=fs.nextInt();
int da=fs.nextInt();
int db=fs.nextInt();
edge=new ArrayList[n+1];
for(int i=1;i<=n;i++)
edge[i]=new ArrayList<>();
for(int i=1;i<n;i++)
{
int u=fs.nextInt();
int v=fs.nextInt();
edge[u].add(v);
edge[v].add(u);
}
int dist[]=new int[n+1];
Arrays.fill(dist,-1);
dist[a]=0;
Queue<Integer> queue=new LinkedList<>();
queue.add(a);
while(!queue.isEmpty())
{
int node=queue.poll();
for(int v:edge[node])
{
if(dist[v]==-1)
{
dist[v]=dist[node]+1;
queue.add(v);
}
}
}
if(dist[b]<=da)
{
pw.println("Alice");
continue;
}
int mx=0,mxvert=1;
for(int i=1;i<=n;i++)
{
if(dist[i]>mx)
{
mx=dist[i];
mxvert=i;
}
}
Arrays.fill(dist,-1);
dist[mxvert]=0;
queue.add(mxvert);
while(!queue.isEmpty())
{
int node=queue.poll();
for(int v:edge[node])
{
if(dist[v]==-1)
{
dist[v]=dist[node]+1;
queue.add(v);
}
}
}
for(int i=1;i<=n;i++)
mx=Math.max(mx,dist[i]);
db=Math.min(db,mx);
if(db>2*da)
pw.println("Bob");
else
pw.println("Alice");
}
pw.flush();
pw.close();
}
}
| 0 |
Non-plagiarised
|
3b498a39
|
9028caf7
|
/*
* HI THERE! (:
*
* CREATED BY : NAITIK V
*
* JAI HIND
*
*/
import java.util.*;
import java.io.*;
import java.math.*;
public class Main
{
static FastReader sc=new FastReader();
static long dp[][];
static int mod=1000000007;
static int max;
public static void main(String[] args)
{
PrintWriter out=new PrintWriter(System.out);
//StringBuffer sb=new StringBuffer("");
int ttt=1;
//ttt =i();
outer :while (ttt-- > 0)
{
int n=i();
int A[]=input(n);
dp=new long[n+1][n+1];
for(int i=0;i<=n;i++) {
Arrays.fill(dp[i],-1);
}
ArrayList<Integer> l=new ArrayList<Integer>();
ArrayList<Integer> m=new ArrayList<Integer>();
for(int i=0;i<n;i++) {
if(A[i]==0) {
l.add(i+1);
}
else {
m.add(i+1);
}
}
A=new int[m.size()];
int B[]=new int[l.size()];
for(int i=0;i<l.size();i++) {
B[i]=l.get(i);
}
for(int i=0;i<m.size();i++) {
A[i]=m.get(i);
}
n=m.size();
int o=l.size();
System.out.println(go(A,B,0,0,n,o));
}
//System.out.println(sb.toString());
out.close();
//CHECK FOR N=1 //CHECK FOR M=0
//CHECK FOR N=1 //CHECK FOR M=0
//CHECK FOR N=1
//CHECK FOR N=1
//CHECK FOR N=1
}
private static long go(int[] A, int[] B, int i, int j, int n, int m) {
if(i==n)
return 0;
if(j==m)
return Integer.MAX_VALUE;
if(dp[i][j]!=-1)
return dp[i][j];
long op1=go(A, B, i+1, j+1, n, m)+Math.abs(A[i]-B[j]);
long op2=go(A, B, i, j+1, n, m);
return dp[i][j]=Math.min(op1, op2);
}
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) {
if(this.x>o.x)
return 1;
else if(this.x<o.x)
return -1;
else {
if(this.y>o.y)
return 1;
else if(this.y<o.y)
return -1;
else
return 0;
}
}
/* FOR TREE MAP PAIR USE */
// public int compareTo(Pair o) {
// if (x > o.x) {
// return 1;
// }
// if (x < o.x) {
// return -1;
// }
// if (y > o.y) {
// return 1;
// }
// if (y < o.y) {
// return -1;
// }
// return 0;
// }
}
static int[] input(int n) {
int A[]=new int[n];
for(int i=0;i<n;i++) {
A[i]=sc.nextInt();
}
return A;
}
static long[] inputL(int n) {
long A[]=new long[n];
for(int i=0;i<n;i++) {
A[i]=sc.nextLong();
}
return A;
}
static String[] inputS(int n) {
String A[]=new String[n];
for(int i=0;i<n;i++) {
A[i]=sc.next();
}
return A;
}
static long sum(int A[]) {
long sum=0;
for(int i : A) {
sum+=i;
}
return sum;
}
static long sum(long A[]) {
long sum=0;
for(long i : A) {
sum+=i;
}
return sum;
}
static void reverse(long A[]) {
int n=A.length;
long B[]=new long[n];
for(int i=0;i<n;i++) {
B[i]=A[n-i-1];
}
for(int i=0;i<n;i++)
A[i]=B[i];
}
static void reverse(int A[]) {
int n=A.length;
int B[]=new int[n];
for(int i=0;i<n;i++) {
B[i]=A[n-i-1];
}
for(int i=0;i<n;i++)
A[i]=B[i];
}
static void input(int A[],int B[]) {
for(int i=0;i<A.length;i++) {
A[i]=sc.nextInt();
B[i]=sc.nextInt();
}
}
static int[][] input(int n,int m){
int A[][]=new int[n][m];
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
A[i][j]=i();
}
}
return A;
}
static char[][] charinput(int n,int m){
char A[][]=new char[n][m];
for(int i=0;i<n;i++) {
String s=s();
for(int j=0;j<m;j++) {
A[i][j]=s.charAt(j);
}
}
return A;
}
static int max(int A[]) {
int max=Integer.MIN_VALUE;
for(int i=0;i<A.length;i++) {
max=Math.max(max, A[i]);
}
return max;
}
static int min(int A[]) {
int min=Integer.MAX_VALUE;
for(int i=0;i<A.length;i++) {
min=Math.min(min, A[i]);
}
return min;
}
static long max(long A[]) {
long max=Long.MIN_VALUE;
for(int i=0;i<A.length;i++) {
max=Math.max(max, A[i]);
}
return max;
}
static long min(long A[]) {
long min=Long.MAX_VALUE;
for(int i=0;i<A.length;i++) {
min=Math.min(min, A[i]);
}
return min;
}
static long [] prefix(long A[]) {
long p[]=new long[A.length];
p[0]=A[0];
for(int i=1;i<A.length;i++)
p[i]=p[i-1]+A[i];
return p;
}
static long [] prefix(int A[]) {
long p[]=new long[A.length];
p[0]=A[0];
for(int i=1;i<A.length;i++)
p[i]=p[i-1]+A[i];
return p;
}
static long [] suffix(long A[]) {
long p[]=new long[A.length];
p[A.length-1]=A[A.length-1];
for(int i=A.length-2;i>=0;i--)
p[i]=p[i+1]+A[i];
return p;
}
static long [] suffix(int A[]) {
long p[]=new long[A.length];
p[A.length-1]=A[A.length-1];
for(int i=A.length-2;i>=0;i--)
p[i]=p[i+1]+A[i];
return p;
}
static long power(long x, long y, long p)
{
if(y==0)
return 1;
if(x==0)
return 0;
long res = 1;
x = x % p;
while (y > 0) {
if (y % 2 == 1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
static void print(int A[]) {
for(int i : A) {
System.out.print(i+" ");
}
System.out.println();
}
static void print(long A[]) {
for(long i : A) {
System.out.print(i+" ");
}
System.out.println();
}
static long mod(long x) {
return ((x%mod + mod)%mod);
}
static String reverse(String s) {
StringBuffer p=new StringBuffer(s);
p.reverse();
return p.toString();
}
static int i() {
return sc.nextInt();
}
static String s() {
return sc.next();
}
static long l() {
return sc.nextLong();
}
static void sort(int[] A){
int n = A.length;
Random rnd = new Random();
for(int i=0; i<n; ++i){
int tmp = A[i];
int randomPos = i + rnd.nextInt(n-i);
A[i] = A[randomPos];
A[randomPos] = tmp;
}
Arrays.sort(A);
}
static void sort(long[] A){
int n = A.length;
Random rnd = new Random();
for(int i=0; i<n; ++i){
long tmp = A[i];
int randomPos = i + rnd.nextInt(n-i);
A[i] = A[randomPos];
A[randomPos] = tmp;
}
Arrays.sort(A);
}
static String sort(String s) {
Character ch[]=new Character[s.length()];
for(int i=0;i<s.length();i++) {
ch[i]=s.charAt(i);
}
Arrays.sort(ch);
StringBuffer st=new StringBuffer("");
for(int i=0;i<s.length();i++) {
st.append(ch[i]);
}
return st.toString();
}
static HashMap<Integer,Integer> hash(int A[]){
HashMap<Integer,Integer> map=new HashMap<Integer, Integer>();
for(int i : A) {
if(map.containsKey(i)) {
map.put(i, map.get(i)+1);
}
else {
map.put(i, 1);
}
}
return map;
}
static TreeMap<Integer,Integer> tree(int A[]){
TreeMap<Integer,Integer> map=new TreeMap<Integer, Integer>();
for(int i : A) {
if(map.containsKey(i)) {
map.put(i, map.get(i)+1);
}
else {
map.put(i, 1);
}
}
return map;
}
static boolean prime(int n)
{
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
double sq=Math.sqrt(n);
for (int i = 5; i <= sq; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static boolean prime(long n)
{
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
double sq=Math.sqrt(n);
for (int i = 5; i <= sq; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
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;
}
}
}
|
import java.io.*;
import java.util.*;
public class Main {
public static void main(String args[])
{
FastReader input=new FastReader();
PrintWriter out=new PrintWriter(System.out);
int T=1;
while(T-->0)
{
int n=input.nextInt();
int a[]=new int[n];
ArrayList<Integer> list=new ArrayList<>();
ArrayList<Integer> space=new ArrayList<>();
for(int i=0;i<n;i++)
{
a[i]=input.nextInt();
if(a[i]==1)
{
list.add(i);
}
else
{
space.add(i);
}
}
int pre[]=new int[space.size()];
for(int i=0;i<list.size();i++)
{
if(i==0)
{
int min=Integer.MAX_VALUE;
for(int j=0;j<space.size();j++)
{
pre[j]=Math.abs(list.get(i)-space.get(j));
min=Math.min(min,pre[j]);
pre[j]=min;
}
}
else
{
int arr[]=new int[space.size()];
for(int j=0;j<i;j++)
{
arr[j]=Integer.MAX_VALUE;
}
int min=Integer.MAX_VALUE;
for(int j=i;j<space.size();j++)
{
int v=Math.abs(list.get(i)-space.get(j));
v+=pre[j-1];
arr[j]=v;
min=Math.min(min,v);
arr[j]=min;
}
for(int j=0;j<space.size();j++)
{
pre[j]=arr[j];
}
}
}
out.println(pre[space.size()-1]);
}
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());
}
String nextLine()
{
String str="";
try
{
str=br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
}
| 0 |
Non-plagiarised
|
49e94e7e
|
d7a8434f
|
import java.io.BufferedReader;
import java.io.IOException;
import java.lang.*;
import java.io.InputStreamReader;
import static java.lang.Math.*;
import static java.lang.System.out;
import java.util.*;
import java.io.File;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.math.BigInteger;
public class Main {
/* 10^(7) = 1s.
* ceilVal = (a+b-1) / b */
static final int mod = 1000000007;
static final long temp = 998244353;
static final long MOD = 1000000007;
static final long M = (long)1e9+7;
static class Pair implements Comparable<Pair>
{
int first, second;
public Pair(int first, int second)
{
this.first = first;
this.second = second;
}
public int compareTo(Pair ob)
{
return (int)(first - ob.first);
}
}
static class Tuple implements Comparable<Tuple>
{
int first, second,third;
public Tuple(int first, int second, int third)
{
this.first = first;
this.second = second;
this.third = third;
}
public int compareTo(Tuple o)
{
return (int)(o.third - this.third);
}
}
public static class DSU
{
int[] parent;
int[] rank; //Size of the trees is used as the rank
public DSU(int n)
{
parent = new int[n];
rank = new int[n];
Arrays.fill(parent, -1);
Arrays.fill(rank, 1);
}
public int find(int i) //finding through path compression
{
return parent[i] < 0 ? i : (parent[i] = find(parent[i]));
}
public boolean union(int a, int b) //Union Find by Rank
{
a = find(a);
b = find(b);
if(a == b) return false; //if they are already connected we exit by returning false.
// if a's parent is less than b's parent
if(rank[a] < rank[b])
{
//then move a under b
parent[a] = b;
}
//else if rank of j's parent is less than i's parent
else if(rank[a] > rank[b])
{
//then move b under a
parent[b] = a;
}
//if both have the same rank.
else
{
//move a under b (it doesnt matter if its the other way around.
parent[b] = a;
rank[a] = 1 + rank[a];
}
return true;
}
}
static class Reader
{
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) throws IOException {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long[] longReadArray(int n) throws IOException {
long[] a=new long[n];
for (int i=0; i<n; i++) a[i]=nextLong();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
public static int gcd(int a, int b)
{
if(b == 0)
return a;
else
return gcd(b,a%b);
}
public static long lcm(long a, long b)
{
return (a / LongGCD(a, b)) * b;
}
public static long LongGCD(long a, long b)
{
if(b == 0)
return a;
else
return LongGCD(b,a%b);
}
public static long LongLCM(long a, long b)
{
return (a / LongGCD(a, b)) * b;
}
//Count the number of coprime's upto N
public static long phi(long n) //euler totient/phi function
{
long ans = n;
// for(long i = 2;i*i<=n;i++)
// {
// if(n%i == 0)
// {
// while(n%i == 0) n/=i;
// ans -= (ans/i);
// }
// }
//
// if(n > 1)
// {
// ans -= (ans/n);
// }
for(long i = 2;i<=n;i++)
{
if(isPrime(i))
{
ans -= (ans/i);
}
}
return ans;
}
public static long fastPow(long x, long n)
{
if(n == 0)
return 1;
else if(n%2 == 0)
return fastPow(x*x,n/2);
else
return x*fastPow(x*x,(n-1)/2);
}
public static long modPow(long x, long y, long p)
{
long res = 1;
x = x % p;
while (y > 0) {
if (y % 2 == 1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
static long modInverse(long n, long p)
{
return modPow(n, p - 2, p);
}
// Returns nCr % p using Fermat's little theorem.
public static long nCrModP(long n, long r,long p)
{
if (n<r)
return 0;
if (r == 0)
return 1;
long[] fac = new long[(int)(n) + 1];
fac[0] = 1;
for (int i = 1; i <= n; i++)
fac[i] = fac[i - 1] * i % p;
return (fac[(int)(n)] * modInverse(fac[(int)(r)], p)
% p * modInverse(fac[(int)(n - r)], p)
% p)
% p;
}
public static long fact(long n)
{
long[] fac = new long[(int)(n) + 1];
fac[0] = 1;
for (long i = 1; i <= n; i++)
fac[(int)(i)] = fac[(int)(i - 1)] * i;
return fac[(int)(n)];
}
public static long nCr(long n, long k)
{
long ans = 1;
for(long i = 0;i<k;i++)
{
ans *= (n-i);
ans /= (i+1);
}
return ans;
}
//Modular Operations for Addition and Multiplication.
public static long perfomMod(long x)
{
return ((x%M + M)%M);
}
public static long addMod(long a, long b)
{
return perfomMod(perfomMod(a)+perfomMod(b));
}
public static long subMod(long a, long b)
{
return perfomMod(perfomMod(a)-perfomMod(b));
}
public static long mulMod(long a, long b)
{
return perfomMod(perfomMod(a)*perfomMod(b));
}
public static boolean isPrime(long n)
{
if(n == 1)
{
return false;
}
//check only for sqrt of the number as the divisors
//keep repeating so only half of them are required. So,sqrt.
for(int i = 2;i*i<=n;i++)
{
if(n%i == 0)
{
return false;
}
}
return true;
}
public static List<Integer> SieveList(int n)
{
boolean prime[] = new boolean[(int)(n+1)];
Arrays.fill(prime, true);
List<Integer> l = new ArrayList<>();
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 p = 2; p<=n; p++)
{
if (prime[p] == true)
{
l.add(p);
}
}
return l;
}
public static int countDivisors(int x)
{
int c = 0;
for(int i = 1;i*i<=x;i++)
{
if(x%i == 0)
{
if(x/i != i)
{
c+=2;
}
else
{
c++;
}
}
}
return c;
}
public static long log2(long n)
{
long ans = (long)(log(n)/log(2));
return ans;
}
public static boolean isPow2(long n)
{
return (n != 0 && ((n & (n-1))) == 0);
}
public static boolean isSq(int x)
{
long s = (long)Math.round(Math.sqrt(x));
return s*s==x;
}
/*
*
* >= <=
0 1 2 3 4 5 6 7
5 5 5 6 6 6 7 7
lower_bound for 6 at index 3 (>=)
upper_bound for 6 at index 6(To get six reduce by one) (<=)
*/
public static int LowerBound(int a[], int x)
{
int l=-1,r=a.length;
while(l+1<r)
{
int m=(l+r)>>>1;
if(a[m]>=x) r=m;
else l=m;
}
return r;
}
public static int UpperBound(long a[], long x)
{
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;
}
public static void Sort(long[] a)
{
List<Long> l = new ArrayList<>();
for (long i : a) l.add(i);
Collections.sort(l);
// Collections.reverse(l); //Use to Sort decreasingly
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
public static void ssort(char[] a)
{
List<Character> l = new ArrayList<>();
for (char i : a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
public static void main(String[] args) throws Exception
{
Reader sc = new Reader();
PrintWriter fout = new PrintWriter(System.out);
int tt = sc.nextInt();
while(tt-- > 0)
{
int n = sc.nextInt();
char[] a = sc.next().toCharArray(), b = sc.next().toCharArray();
int c00 = 0, c01 = 0, c10 = 0, c11 = 0;
for(int i = 0;i<n;i++)
{
if(a[i] == '0' && b[i] == '0')
{
c00++;
}
else if(a[i] == '0' && b[i] == '1')
{
c01++;
}
else if(a[i] == '1' && b[i] == '0')
{
c10++;
}
else if(a[i] == '1' && b[i] == '1')
{
c11++;
}
}
int ans = mod;
if(c01 == c10) ans = min(ans, c01 + c10);
if(c11 == c00 + 1) ans = min(ans, c11 + c00);
fout.println((ans == mod) ? -1 : ans);
}
fout.close();
}
}
|
import java.util.*;
import java.io.*;
public class C {
public static void main(String[] args) {
FastScanner sc = new FastScanner();
int T = sc.nextInt();
while(T-->0) {
int n = sc.nextInt();
char[] s = new char[n];
char[] t = new char[n];
s = sc.next().toCharArray();
t = sc.next().toCharArray();
int a = 0, b = 0, c = 0, d = 0;
for(int i = 0; i < n; i++) {
if(s[i] == '0' && t[i] == '0') a++;
if(s[i] == '1' && t[i] == '0') b++;
if(s[i] == '0' && t[i] == '1') c++;
if(s[i] == '1' && t[i] == '1') d++;
}
int res = Integer.MAX_VALUE;
if(b == c || b+1 == c) {
if((b + c) % 2 == 0) {
res = Math.min(res, b + c);
}
}
if(a == d || a+1 == d) {
if((a + d) % 2 == 1) {
res = Math.min(res, a + d);
}
}
if(res == Integer.MAX_VALUE) System.out.println(-1);
else System.out.println(res);
}
}
static class FastScanner {
public BufferedReader reader;
public StringTokenizer tokenizer;
public FastScanner() {
reader = new BufferedReader(new InputStreamReader(System.in), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
try {
return reader.readLine();
} catch(IOException e) {
throw new RuntimeException(e);
}
}
}
}
| 0 |
Non-plagiarised
|
ca8f11a4
|
e185bce5
|
import java.util.*;
import java.util.stream.Collectors;
import java.io.*;
import java.math.*;
public class GR18_C2 {
public static FastScanner sc;
public static StringBuilder sb ;public static int MOD= 1000000007;
public 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) {}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
String nextLine() throws IOException {
return br.readLine();
}
}
public static void solve(int t) throws IOException {
int n=sc.nextInt();
String a=sc.next();
String b=sc.next();
int _00=0;
int _01=0;
int _10=0;
int _11=0;
for(int i=0;i<n;i++) {
if(a.charAt(i)=='0' && b.charAt(i)=='0') _00++;
if(a.charAt(i)=='0' && b.charAt(i)=='1') _01++;
if(a.charAt(i)=='1' && b.charAt(i)=='0') _10++;
if(a.charAt(i)=='1' && b.charAt(i)=='1') _11++;
}
int ans=Integer.MAX_VALUE;
// All _01 and _10 can be converted to _11 and _00 by swapping and this requires to operations
if(_01==_10) {
ans=Math.min(ans, _10*2);
}
// By performing one operation, we get _01==_10 and then even operations can be done.
// Possible when _11=_00 and one additional _11 for odd operation
if(_00+1==_11) {
ans=Math.min(ans, (_11-1)*2+1);
}
if(ans==Integer.MAX_VALUE) sb.append(-1).append('\n');
else sb.append(ans).append('\n');
}
public static void main(String[] args) throws IOException {
sb = new StringBuilder("");
sc = new FastScanner();
int t=sc.nextInt();
for(int i=1;i<=t;i++){
solve(i);
}
System.out.println(sb);
}
}
|
import java.util.*;
import java.io.*;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
public class Main {
private static FS sc = new FS();
private static class FS {
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) {}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
}
private static class extra {
static int[] intArr(int size) {
int[] a = new int[size];
for(int i = 0; i < size; i++) a[i] = sc.nextInt();
return a;
}
static long[] longArr(int size) {
Scanner scc = new Scanner(System.in);
long[] a = new long[size];
for(int i = 0; i < size; i++) a[i] = sc.nextLong();
return a;
}
static long intSum(int[] a) {
long sum = 0;
for(int i = 0; i < a.length; i++) {
sum += a[i];
}
return sum;
}
static long longSum(long[] a) {
long sum = 0;
for(int i = 0; i < a.length; i++) {
sum += a[i];
}
return sum;
}
static LinkedList[] graphD(int vertices, int edges) {
LinkedList<Integer>[] temp = new LinkedList[vertices+1];
for(int i = 0; i <= vertices; i++) temp[i] = new LinkedList<>();
for(int i = 0; i < edges; i++) {
int x = sc.nextInt();
int y = sc.nextInt();
temp[x].add(y);
}
return temp;
}
static LinkedList[] graphUD(int vertices, int edges) {
LinkedList<Integer>[] temp = new LinkedList[vertices+1];
for(int i = 0; i <= vertices; i++) temp[i] = new LinkedList<>();
for(int i = 0; i < edges; i++) {
int x = sc.nextInt();
int y = sc.nextInt();
temp[x].add(y);
temp[y].add(x);
}
return temp;
}
static void printG(LinkedList[] temp) { for(LinkedList<Integer> aa:temp) System.out.println(aa); }
static long cal(long val, long pow, long mod) {
if(pow == 0) return 1;
long res = cal(val, pow/2, mod);
long ret = (res*res)%mod;
if(pow%2 == 0) return ret;
return (val*ret)%mod;
}
static long gcd(long a, long b) { return b == 0 ? a:gcd(b, a%b); }
}
static int mod = (int) 1e9;
static LinkedList<Integer>[] temp, idx;
static long inf = (long) Long.MAX_VALUE;
// static long inf = Long.MAX_VALUE;
// static int max;
public static void main(String[] args) {
int t = sc.nextInt();
// int t = 1;
StringBuilder ret = new StringBuilder();
while(t-- > 0) {
int n = sc.nextInt();
String a = sc.next(), b = sc.next();
int _00 = 0, _01 = 0, _10 = 0, _11 = 0;
for(int i = 0; i < n; i++) {
if(a.charAt(i) == '0' && b.charAt(i) == '0') _00++;
if(a.charAt(i) == '0' && b.charAt(i) == '1') _01++;
if(a.charAt(i) == '1' && b.charAt(i) == '0') _10++;
if(a.charAt(i) == '1' && b.charAt(i) == '1') _11++;
}
int ans = Integer.MAX_VALUE;
if(_10 == _01) ans = _01 + _10;
if(_10 > 0) {
int n00 = _10 - 1;
int n01 = _11;
int n10 = _00 + 1;
int n11 = _01;
if (n01 == n10) {
ans = Math.min(ans, 1 + n01 + n10);
}
}
if(_11 > 0) {
int n00 = _10;
int n01 = _11 - 1;
int n10 = _00;
int n11 = _01 + 1;
if (n01 == n10) {
ans = Math.min(ans, 1 + n01 + n10);
}
}
ret.append(ans == Integer.MAX_VALUE ? -1 : ans);
ret.append("\n");
}
System.out.println(ret);
}
}
| 0 |
Non-plagiarised
|
81fb6415
|
fb69b3b4
|
import java.math.BigInteger;
import java.util.*;
import java.io.*;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
public class CodeForces {
public void run() throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
next : while (t-- > 0) {
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
long k = Long.parseLong(st.nextToken());
Long[] a = new Long[n];
st = new StringTokenizer(br.readLine());
for (int i = 0; i < n; i++) {
a[i] = Long.parseLong(st.nextToken());
}
Arrays.sort(a);
long ans = Long.MAX_VALUE;
long[] lsum = new long[n + 1];
for (int i = 0; i < n; i++) {
lsum[i + 1] = lsum[i] + a[i];
}
for (long y = 0; y < n; y++) {
long x = 0;
if ((k - lsum[n - (int)y] + a[0]) >= 0) {
x = (k - lsum[n - (int)y] + a[0]) / (y + 1);
} else {
if ((k - lsum[n - (int)y] + a[0]) % (y + 1) == 0) {
x = (k - lsum[n - (int)y] + a[0]) / (y + 1);
} else {
x = (k - lsum[n - (int)y] + a[0]) / (y + 1) - 1;
}
}
x = a[0] - x;
ans = Math.min(ans, Math.max(0, x) + y);
}
System.out.println(ans);
}
}
public static void main(String[] args) throws Exception {
new CodeForces().run();
}
}
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
public static long floor(long a, long b) {
long res = a / b;
while(res * b > a) res--;
return res;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
while (t-- > 0) {
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
long k = Long.parseLong(st.nextToken());
st = new StringTokenizer(br.readLine());
Long[] p = new Long[n];
for(int i = 0 ;i<n;i++) {
p[i] = Long.parseLong(st.nextToken());
}
Arrays.sort(p);
long[] sums = new long[n+1];
for(int i=0;i<n;i++) sums[i+1] = sums[i] + p[i];
long ans = Long.MAX_VALUE;
for(int y=0;y<n;y++) {
long x = p[0] - floor(k - sums[n-y] + p[0], y+1);
ans = Math.min(Math.max(x, 0) + y, ans);
}
System.out.println(ans);
}
}
}
| 0 |
Non-plagiarised
|
77d22fc3
|
d3528b2a
|
import java.io.*;
import java.util.*;
public class A {
//--------------------------INPUT READER---------------------------------//
static class fs {
public BufferedReader br;
StringTokenizer st = new StringTokenizer("");
public fs() { this(System.in); }
public fs(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
String next() {
while (!st.hasMoreTokens()) {
try { st = new StringTokenizer(br.readLine()); }
catch (IOException e) { e.printStackTrace(); }
}
return st.nextToken();
}
int ni() { return Integer.parseInt(next()); }
long nl() { return Long.parseLong(next()); }
double nd() { return Double.parseDouble(next()); }
String ns() { return next(); }
int[] na(long nn) {
int n = (int) nn;
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = ni();
return a;
}
long[] nal(long nn) {
int n = (int) nn;
long[] l = new long[n];
for(int i = 0; i < n; i++) l[i] = nl();
return l;
}
}
//-----------------------------------------------------------------------//
static int t = 0;
//---------------------------PRINTER-------------------------------------//
static class Printer {
static PrintWriter w;
public Printer() {this(System.out);}
public Printer(OutputStream os) {
w = new PrintWriter(os);
}
public void p(int i) {w.println(i);}
public void p(long l) {w.println(l);}
public void p(double d) {w.println(d);}
public void p(String s) { w.println(s);}
public void pr(int i) {w.print(i);}
public void pr(long l) {w.print(l);}
public void pr(double d) {w.print(d);}
public void pr(String s) { w.print(s);}
public void pl() {w.println();}
public void close() {w.close();}
}
//-----------------------------------------------------------------------//
//--------------------------VARIABLES------------------------------------//
static fs sc = new fs();
static OutputStream outputStream = System.out;
static Printer w = new Printer(outputStream);
static long lma = Long.MAX_VALUE, lmi = Long.MIN_VALUE;
static long ima = Integer.MAX_VALUE, imi = Integer.MIN_VALUE;
static long mod = 1000000007;
//-----------------------------------------------------------------------//
//--------------------------ADMIN_MODE-----------------------------------//
private static void ADMIN_MODE() throws IOException {
if (System.getProperty("ONLINE_JUDGE") == null) {
w = new Printer(new FileOutputStream("output.txt"));
sc = new fs(new FileInputStream("input.txt"));
}
}
//-----------------------------------------------------------------------//
static int tt = 0;
//----------------------------START--------------------------------------//
public static void main(String[] args)
throws IOException {
ADMIN_MODE();
t = sc.ni();while(t-->0) {
tt++;
solve();
}
w.close();
}
static void solve() throws IOException {
int n = sc.ni();
String s1 = sc.ns();
String s2 = sc.ns();
char[] strr = s1.toCharArray();
char[] strr2 = s2.toCharArray();
HashSet<Integer> lia = new HashSet<>(), lib = new HashSet<>();
for(int i = 0; i < n; i++) {
if(strr[i]=='1') lia.add(i);
else lib.add(i);
}
HashSet<Integer> liaa = new HashSet<>();
for(int i = 0; i < n; i++) {
if(strr2[i]=='1') liaa.add(i);
}
if(!(lia.size() == liaa.size() || lib.size()+1 == liaa.size())) {
w.p(-1);
return;
}
int ac = 0, bc = 0;
for(int i: lia) {
if(liaa.contains(i)) ac++;
}
bc = liaa.size()-ac;
if(lia.size() == liaa.size() && lia.size() == ac) {
w.p(0);
return;
}
int nac = lia.size()-ac;
int nbc = lib.size()-bc;
long ansa = ac != 0 && (ac-1 == nbc)? Math.abs(ac-1+nbc): ima;
long ansb = nac != 0 && (nac-1 == bc-1)? Math.abs(nac-1+bc): ima;
if(ansa == ima && ansb == ima) {
w.p(-1);
return;
}
w.p(Math.min(ansa, ansb)+1);
}
}
|
import java.io.*;
import java.util.*;
public class A {
//--------------------------INPUT READER---------------------------------//
static class fs {
public BufferedReader br;
StringTokenizer st = new StringTokenizer("");
public fs() { this(System.in); }
public fs(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
String next() {
while (!st.hasMoreTokens()) {
try { st = new StringTokenizer(br.readLine()); }
catch (IOException e) { e.printStackTrace(); }
}
return st.nextToken();
}
int ni() { return Integer.parseInt(next()); }
long nl() { return Long.parseLong(next()); }
double nd() { return Double.parseDouble(next()); }
String ns() { return next(); }
int[] na(long nn) {
int n = (int) nn;
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = ni();
return a;
}
long[] nal(long nn) {
int n = (int) nn;
long[] l = new long[n];
for(int i = 0; i < n; i++) l[i] = nl();
return l;
}
}
//-----------------------------------------------------------------------//
static int t = 0;
//---------------------------PRINTER-------------------------------------//
static class Printer {
static PrintWriter w;
public Printer() {this(System.out);}
public Printer(OutputStream os) {
w = new PrintWriter(os);
}
public void p(int i) {w.println(i);}
public void p(long l) {w.println(l);}
public void p(double d) {w.println(d);}
public void p(String s) { w.println(s);}
public void pr(int i) {w.print(i);}
public void pr(long l) {w.print(l);}
public void pr(double d) {w.print(d);}
public void pr(String s) { w.print(s);}
public void pl() {w.println();}
public void close() {w.close();}
}
//-----------------------------------------------------------------------//
//--------------------------VARIABLES------------------------------------//
static fs sc = new fs();
static OutputStream outputStream = System.out;
static Printer w = new Printer(outputStream);
static long lma = Long.MAX_VALUE, lmi = Long.MIN_VALUE;
static long ima = Integer.MAX_VALUE, imi = Integer.MIN_VALUE;
static long mod = 1000000007;
//-----------------------------------------------------------------------//
//--------------------------ADMIN_MODE-----------------------------------//
private static void ADMIN_MODE() throws IOException {
if (System.getProperty("ONLINE_JUDGE") == null) {
w = new Printer(new FileOutputStream("output.txt"));
sc = new fs(new FileInputStream("input.txt"));
}
}
//-----------------------------------------------------------------------//
static int tt = 0;
//----------------------------START--------------------------------------//
public static void main(String[] args)
throws IOException {
ADMIN_MODE();
t = sc.ni();while(t-->0) {
tt++;
solve();
}
w.close();
}
static void solve() throws IOException {
int n = sc.ni();
String s1 = sc.ns();
String s2 = sc.ns();
char[] strr = s1.toCharArray();
char[] strr2 = s2.toCharArray();
HashSet<Integer> lia = new HashSet<>(), lib = new HashSet<>();
for(int i = 0; i < n; i++) {
if(strr[i]=='1') lia.add(i);
else lib.add(i);
}
HashSet<Integer> liaa = new HashSet<>();
for(int i = 0; i < n; i++) {
if(strr2[i]=='1') liaa.add(i);
}
if(!(lia.size() == liaa.size() || lib.size()+1 == liaa.size())) {
w.p(-1);
return;
}
int ac = 0, bc = 0;
for(int i: lia) {
if(liaa.contains(i)) ac++;
}
bc = liaa.size()-ac;
if(lia.size() == liaa.size() && lia.size() == ac) {
w.p(0);
return;
}
int nac = lia.size()-ac;
int nbc = lib.size()-bc;
long ansa = ac != 0 && (ac-1 == nbc)? Math.abs(ac-1+nbc): ima;
long ansb = nac != 0 && (nac-1 == bc-1)? Math.abs(nac-1+bc): ima;
if(ansa == ima && ansb == ima) {
w.p(-1);
return;
}
w.p(Math.min(ansa, ansb)+1);
}
}
| 1 |
Plagiarised
|
8f31b279
|
d2f74dfc
|
import java.util.*;
import java.io.*;
public class JavaTract
{
static class Pair implements Comparable<Pair>{
int first;
int second;
Pair(int x,int y){
this.first=x;
this.second=y;
}
@Override
public int compareTo(Pair x){
return this.first-x.first;
}
}
public static void main (String[] args)
{
Scanner scan=new Scanner(System.in);
int t=scan.nextInt();
while(t-->0){
int n=scan.nextInt();
int m=scan.nextInt();
int x=scan.nextInt();
int[]arr=new int[n];
for(int i=0;i<n;i++){
arr[i]=scan.nextInt();
}
// TreeSet<Pair> set = new TreeSet<>();
Queue<Pair> set = new PriorityQueue<>();
for(int i=1;i<=m;i++){
set.add(new Pair(0,i));
}
System.out.println("YES");
for(int i=0;i<n;i++){
Pair temp=set.poll();
int first = temp.first;
int second = temp.second;
System.out.print(second+" ");
set.add(new Pair(first+arr[i],second));
}
System.out.println();
}
}
}
|
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t--!=0){
int n=sc.nextInt();
int m=sc.nextInt();
int x=sc.nextInt();
int[] a=new int[n];
int[] c=new int[n];
Map<Integer,Stack<Integer>> mp=new HashMap<>();
for(int i=0;i<n;i++){
a[i]=sc.nextInt();
//c[i]=a[i];
if(mp.containsKey(a[i])){
Stack<Integer> l=mp.get(a[i]);
l.push(i);
mp.put(a[i],l);
}
else{
Stack<Integer> l=new Stack<>();
l.push(i);
mp.put(a[i],l);
}
}
Arrays.sort(a);
int[] b=new int[n];
int cn=1;
for(int i=0;i<n;i++){
cn=cn%m;
Stack<Integer> li=mp.get(a[i]);
if(!li.isEmpty()){
int val=li.peek();
b[val]=cn+1;
c[i]+=a[i];
li.pop();
mp.put(a[i],li);
}
cn++;
}
int mv=c[0]-c[n-1];
if(Math.abs(mv)>x) System.out.println("NO");
else {
System.out.println("YES");
for(int i=0;i<n;i++){
System.out.print(b[i]+" ");
}
System.out.println();
}
}
}
}
| 0 |
Non-plagiarised
|
2120328e
|
464a03b8
|
/***** ---> :) Vijender Srivastava (: <--- *****/
import java.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
static FastReader sc =new FastReader();
static PrintWriter out=new PrintWriter(System.out);
static int mod=10000007;
static StringBuilder sb=new StringBuilder();
/* start */
public static void main(String [] args)
{
int t = i();
while(t-->0)
{
int n = i();
int a[] = input(n);
char c[] = inputC();
ArrayList<Integer> b = new ArrayList<>();
ArrayList<Integer> r = new ArrayList<>();
for(int i=0;i<n;i++)
{
if(c[i]=='R')
r.add(a[i]);
else
b.add(a[i]);
}
Collections.sort(b);
Collections.sort(r,Collections.reverseOrder());
boolean is = true;
int cnt = 1;
for(int i=0;i<b.size();i++)
{
if(b.get(i)<cnt)
{
is = false;
break;
}
cnt++;
}
for(int i=0;i<r.size();i++)
{
if(r.get(i)>n-i)
{
is = false;
break;
}
}
out.println(is==true?"YES":"NO");
}
out.close();
}
/* end */
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 int i() {
return sc.nextInt();
}
static String s() {
return sc.next();
}
static long l() {
return sc.nextLong();
}
static char[] inputC()
{
String s = sc.nextLine();
return s.toCharArray();
}
static int[] input(int n) {
int A[]=new int[n];
for(int i=0;i<n;i++) {
A[i]=sc.nextInt();
}
return A;
}
static long[] inputL(int n) {
long A[]=new long[n];
for(int i=0;i<n;i++) {
A[i]=sc.nextLong();
}
return A;
}
static long[] putL(long a[]) {
long A[]=new long[a.length];
for(int i=0;i<a.length;i++) {
A[i]=a[i];
}
return A;
}
static String[] inputS(int n) {
String A[]=new String[n];
for(int i=0;i<n;i++) {
A[i]=sc.next();
}
return A;
}
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static String reverse(String s) {
StringBuffer p=new StringBuffer(s);
p.reverse();
return p.toString();
}
static int min(int a,int b) {
return Math.min(a, b);
}
static int min(int a,int b,int c) {
return Math.min(a, Math.min(b, c));
}
static int min(int a,int b,int c,int d) {
return Math.min(a, Math.min(b, Math.min(c, d)));
}
static int max(int a,int b) {
return Math.max(a, b);
}
static int max(int a,int b,int c) {
return Math.max(a, Math.max(b, c));
}
static int max(int a,int b,int c,int d) {
return Math.max(a, Math.max(b, Math.max(c, d)));
}
static long min(long a,long b) {
return Math.min(a, b);
}
static long min(long a,long b,long c) {
return Math.min(a, Math.min(b, c));
}
static long min(long a,long b,long c,long d) {
return Math.min(a, Math.min(b, Math.min(c, d)));
}
static long max(long a,long b) {
return Math.max(a, b);
}
static long max(long a,long b,long c) {
return Math.max(a, Math.max(b, c));
}
static long max(long a,long b,long c,long d) {
return Math.max(a, Math.max(b, Math.max(c, d)));
}
static long sum(int A[]) {
long sum=0;
for(int i : A) {
sum+=i;
}
return sum;
}
static long sum(long A[]) {
long sum=0;
for(long i : A) {
sum+=i;
}
return sum;
}
static void print(int A[]) {
for(int i : A) {
System.out.print(i+" ");
}
System.out.println();
}
static void print(long A[]) {
for(long i : A) {
System.out.print(i+" ");
}
System.out.println();
}
static long mod(long x) {
return ((x%mod + mod)%mod);
}
static long power(long x, long y)
{
if(y==0)
return 1;
if(x==0)
return 0;
long res = 1;
while (y > 0) {
if (y % 2 == 1)
res = (res * x) ;
y = y >> 1;
x = (x * x);
}
return res;
}
static boolean prime(int n)
{
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
double sq=Math.sqrt(n);
for (int i = 5; i <= sq; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static boolean prime(long n)
{
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
double sq=Math.sqrt(n);
for (int i = 5; i <= sq; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
//pair class
private static class Pair implements Comparable<Pair> {
int first, second;
public Pair(int f, int s) {
first = f;
second = s;
}
@Override
public int compareTo(Pair p) {
if (first > p.first)
return 1;
else if (first < p.first)
return -1;
else {
if (second > p.second)
return 1;
else if (second < p.second)
return -1;
else
return 0;
}
}
}
}
|
import java.util.*;
public class Soltion{
public static void main(String []args){
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-->0){
int n = sc.nextInt();
Integer[] arr = new Integer[n];
for(int i=0;i<n;i++){
arr[i] = sc.nextInt();
}
String s = sc.next();
List<Integer> blue = new ArrayList<>();
List<Integer> red = new ArrayList<>();
for(int i=0;i<s.length();i++){
if(s.charAt(i)=='B'){
blue.add(arr[i]);
}
else{
red.add(arr[i]);
}
}
Collections.sort(blue);
Collections.sort(red);
int p=1,q=n;
boolean flag = true;
for(int i=red.size()-1;i>=0;i--){
if(red.get(i)>q){
flag = false;
break;
}
q--;
}
for(int i=0;i<blue.size();i++){
if(blue.get(i)<p){
flag = false;
break;
}
p++;
}
System.out.println(flag? "Yes" : "No");
}
}
}
| 1 |
Plagiarised
|
69b2fd22
|
d221162a
|
import java.io.*;
import java.util.*;
public class Main {
public static void main(String args[])
{
FastReader input=new FastReader();
PrintWriter out=new PrintWriter(System.out);
int T=1;
while(T-->0)
{
int n=input.nextInt();
int a[]=new int[n];
ArrayList<Integer> list=new ArrayList<>();
ArrayList<Integer> space=new ArrayList<>();
for(int i=0;i<n;i++)
{
a[i]=input.nextInt();
if(a[i]==1)
{
list.add(i);
}
else
{
space.add(i);
}
}
int pre[]=new int[space.size()];
for(int i=0;i<list.size();i++)
{
if(i==0)
{
int min=Integer.MAX_VALUE;
for(int j=0;j<space.size();j++)
{
pre[j]=Math.abs(list.get(i)-space.get(j));
min=Math.min(min,pre[j]);
pre[j]=min;
}
}
else
{
int arr[]=new int[space.size()];
for(int j=0;j<i;j++)
{
arr[j]=Integer.MAX_VALUE;
}
int min=Integer.MAX_VALUE;
for(int j=i;j<space.size();j++)
{
int v=Math.abs(list.get(i)-space.get(j));
v+=pre[j-1];
arr[j]=v;
min=Math.min(min,v);
arr[j]=min;
}
for(int j=0;j<space.size();j++)
{
pre[j]=arr[j];
}
}
}
out.println(pre[space.size()-1]);
}
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());
}
String nextLine()
{
String str="";
try
{
str=br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
}
|
import java.util.*;
import java.io.*;
public class Main2 {
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 long mod = 998244353;
// static Scanner sc = new Scanner(System.in);
static FastReader sc = new FastReader();
static PrintWriter out = new PrintWriter(System.out);
public static void main (String[] args) {
int t = 1;
// t = sc.nextInt();
z : while(t-->0) {
int n = sc.nextInt();
int a[] = new int[n];
for(int i=0;i<n;i++) a[i] = sc.nextInt();
List<Integer> a1 = new ArrayList<>();
ArrayList<Integer> a2 = new ArrayList<>();
for (int i = 0; i < n; i++) {
if(a[i] == 0) a1.add(i);
else a2.add(i);
}
long dp[][] = new long[n+1][n+1];
for (int i = 0; i <= n; i++) {
Arrays.fill(dp[i],-1);
}
out.write(find(0,0,a1,a2,dp)+"\n");
}
out.close();
}
private static long find(int i, int j, List<Integer> a1, ArrayList<Integer> a2, long[][] dp) {
if(j == a2.size()) return 0;
int req = a2.size()-j;
int ava = a1.size()-i;
if(ava<req) return Integer.MAX_VALUE/2;
if(dp[i][j] != -1) return dp[i][j];
long ans1 = find(i+1,j,a1,a2,dp);
long ans2 = Math.abs(a1.get(i)-a2.get(j)) + find(i+1,j+1,a1,a2,dp);
return dp[i][j] = Math.min(ans1, ans2);
}
}
| 0 |
Non-plagiarised
|
2e1109d7
|
e7000ac2
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.InputStream;
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
DArmchairs solver = new DArmchairs();
solver.solve(1, in, out);
out.close();
}
static class DArmchairs {
ArrayList<Integer>[] arr;
long[][] dp;
public void solve(int testNumber, FastReader in, PrintWriter out) {
int n = in.nextInt();
int[] a = in.readArray(n);
int mx = 5001;
dp = new long[mx][mx];
for (int i = 0; i < mx; ++i) {
Arrays.fill(dp[i], -1);
}
arr = new ArrayList[2];
for (int i = 0; i < 2; ++i) {
arr[i] = new ArrayList<>();
}
for (int i = 0; i < n; ++i) {
arr[a[i]].add(i);
}
out.println(go(0, 0));
}
long go(int i, int j) {
if (i == arr[1].size()) return 0;
if (j == arr[0].size()) return (long) 1e9;
if (dp[i][j] != -1) return dp[i][j];
long pick = Math.abs(arr[0].get(j) - arr[1].get(i)) + go(i + 1, j + 1);
long leave = go(i, j + 1);
dp[i][j] = Math.min(leave, pick);
return dp[i][j];
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private FastReader.SpaceCharFilter filter;
public FastReader(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 c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int[] readArray(int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++) array[i] = nextInt();
return array;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.InputStream;
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
DArmchairs solver = new DArmchairs();
solver.solve(1, in, out);
out.close();
}
static class DArmchairs {
ArrayList<Integer>[] arr;
long[][] dp;
public void solve(int testNumber, FastReader in, PrintWriter out) {
int n = in.nextInt();
int[] a = in.readArray(n);
int mx = 5001;
dp = new long[mx][mx];
for (int i = 0; i < mx; ++i) {
Arrays.fill(dp[i], -1);
}
arr = new ArrayList[2];
for (int i = 0; i < 2; ++i) {
arr[i] = new ArrayList<>();
}
for (int i = 0; i < n; ++i) {
arr[a[i]].add(i);
}
out.println(go(0, 0));
}
long go(int i, int j) {
if (i == arr[1].size()) return 0;
if (j == arr[0].size()) return (long) 1e9;
if (dp[i][j] != -1) return dp[i][j];
long pick = Math.abs(arr[0].get(j) - arr[1].get(i)) + go(i + 1, j + 1);
long leave = go(i, j + 1);
dp[i][j] = Math.min(leave, pick);
return dp[i][j];
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private FastReader.SpaceCharFilter filter;
public FastReader(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 c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int[] readArray(int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++) array[i] = nextInt();
return array;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| 1 |
Plagiarised
|
a8f7c8b7
|
c1638a45
|
import java.util.Scanner;
public class Menorah {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
char initial[] = sc.next().toCharArray();
char desired[] = sc.next().toCharArray();
int lit1 = 0, lit2 = 0;
int ans = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
if (initial[i] == '1') {
++lit1;
}
if (desired[i] == '1') {
++lit2;
}
}
if (lit1 == lit2) {
int count = 0;
for (int i = 0; i < n; i++) {
if (initial[i] != desired[i]) {
++count;
}
}
ans = Math.min(count, ans);
}
if (lit2 == (n - lit1 + 1)) {
int count = 0;
for (int i = 0; i < n; i++) {
if (initial[i] == desired[i]) {
++count;
}
}
ans = Math.min(ans, count);
}
if (ans == Integer.MAX_VALUE) {
System.out.println(-1);
} else {
System.out.println(ans);
}
}
}
}
|
import java.io.*;
import java.util.*;
public class qC {
public static void main(String[] args)throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
while(T-- > 0) {
int N = Integer.parseInt(br.readLine());
char[] curr = br.readLine().toCharArray();
char[] sol = br.readLine().toCharArray();
// int oddP = 0;
// int evenP = 0;
// int even1 = 0;
// int odd1 = 0;
// int even0 = 0;
// int odd0 = 0;
// boolean alreadySolved = true;
// for(int i = 0;i < N;i++) {
// if(curr[i] == sol[i]) {
// evenP++;
// if(curr[i] == '1') even1++;
// else even0++;
// }
// else {
// oddP++;
// if(curr[i] == '1') odd1++;
// else odd0++;
// alreadySolved = false;
// }
// }
//
// if(alreadySolved) {
// System.out.println(0);
// continue;
// }
// int minSwaps = Integer.MAX_VALUE;
// if(N % 2 == 1) {
// if(evenP % 2 == 1 && Math.abs(odd1 - odd0) <= 1 && odd1 > 0 && odd0 > 0) {
// minSwaps = Math.min(minSwaps, oddP);
// }
// if(oddP % 2 == 0 && Math.abs(even1 - even0) <= 1 && even1 > 0 && even1 > 0) {
// minSwaps = Math.min(minSwaps, evenP);
// }
// }
// else {
// if(evenP % 2 == 0 && Math.abs(odd1 - odd0) <= 1 && odd1 > 0 && odd0 > 0) {
// minSwaps = Math.min(minSwaps, oddP);
// }
// if(oddP % 2 == 1 && Math.abs(even1 - even0) <= 1 && even1 > 0 && even1 > 0) {
// minSwaps = Math.min(minSwaps, evenP);
// }
// }
// System.out.println((minSwaps == Integer.MAX_VALUE) ? -1: minSwaps);
int curr1 = 0;
int sol1 = 0;
int mismatch = 0;
for(int i = 0;i < N;i++) {
if(curr[i] == '1') curr1++;
if(sol[i] == '1') sol1++;
if(curr[i] != sol[i]) mismatch++;
}
int minAns = Integer.MAX_VALUE;
//even operations
if(curr1 == sol1 && mismatch % 2 == 0) {
minAns = Math.min(mismatch, minAns);
}
//odd operations
for(int i = 0;i < N;i++) {
if(curr[i] == '1') {
int tempcurr1 = N - curr1 + 1;
int tempmismatch;
if(sol[i] == '0') {
tempmismatch = N - mismatch;
}
else {
tempmismatch = N - mismatch - 1;
}
if(tempcurr1 == sol1 && tempmismatch % 2 == 0) {
minAns = Math.min(minAns, tempmismatch + 1);
}
}
}
System.out.println((minAns == Integer.MAX_VALUE) ? -1 : minAns);
}
}
}
| 0 |
Non-plagiarised
|
7011024d
|
e6b7a899
|
import java.util.*;
public class D {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
ArrayList<Integer> occupied = new ArrayList<>();
ArrayList<Integer> vacant = new ArrayList<>();
for (int i = 0; i < n; i++) {
int x = scanner.nextInt();
if (x == 1)
occupied.add(i);
else
vacant.add(i);
}
Solution Solution = new Solution(occupied, vacant);
// System.out.println(Solution.tabulation());
System.out.println(Solution.memoization());
}
}
class Solution {
ArrayList<Integer> occupied, vacant;
int x, y;
public Solution(ArrayList<Integer> occupied, ArrayList<Integer> vacant) {
this.occupied = occupied;
this.vacant = vacant;
x = occupied.size(); y = vacant.size();
}
int tabulation() {
return tabulation(x, y);
}
int tabulation(int x, int y) {
int[][] dp = new int[x+1][y+1];
for (int i = 0; i <= x; i++) {
Arrays.fill(dp[i], Integer.MAX_VALUE/2);
}
for (int i = 0; i <= x; i++) {
dp[i][0] = 0;
}
for (int i = 0; i <= y; i++) {
dp[0][i] = 0;
}
for (int i = 1; i <= x; i++) {
for (int j = 1; j <= y; j++) {
if(i == j) {
dp[i][j] = dp[i-1][j-1] + Math.abs(occupied.get(i-1) - vacant.get(j-1));
}
else {
dp[i][j] = Math.min(dp[i][j-1], dp[i-1][j-1] + Math.abs(occupied.get(i-1) - vacant.get(j-1)));
}
}
}
return dp[x][y];
}
int memoization() {
int[][] dp = new int[x][y];
for (int i = 0; i < x; i++) {
Arrays.fill(dp[i], -1);
}
return memoization(dp, x-1, y-1);
}
int memoization(int[][] dp, int n, int m) {
if(n < 0) {
return 0;
}
if(m < n) {
return Integer.MAX_VALUE;
}
if(dp[n][m] != -1) {
return dp[n][m];
}
int first = memoization(dp, n, m-1);
int second = memoization(dp, n-1, m-1) + Math.abs(occupied.get(n) - vacant.get(m));
dp[n][m] = Math.min(first, second);
return dp[n][m];
}
}
|
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 long ans=0;
//static ArrayList<Integer> ans=new ArrayList<>();
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);
ArrayList<Integer> a1 = new ArrayList<Integer>();
ArrayList<Integer> a2 = new ArrayList<Integer>();
for (int i = 0; i < A.length; i++) {
if (A[i]==0) {
a1.add(i);
}else {
a2.add(i);
}
}
int[][] dp = new int[a1.size()+1][a2.size()+1];
for (int i = 0; i < dp.length; i++) {
Arrays.fill(dp[i], Integer.MAX_VALUE/2);
}
dp[0][0] = 0;
for (int i = 1; i <= a1.size() ; i++) {
int pos1 = a1.get(i-1);
for (int j = 0; j <= a2.size(); j++) {
dp[i][j] = dp[i-1][j];
if (j-1>=0) {
int pos2 = a2.get(j-1);
dp[i][j] = Math.min(dp[i][j], dp[i-1][j-1] + Math.abs(pos1-pos2));
}
}
}
System.out.println(dp[a1.size()][a2.size()]);
}
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;
}
}
}
| 0 |
Non-plagiarised
|
7011024d
|
eea69e7f
|
import java.util.*;
public class D {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
ArrayList<Integer> occupied = new ArrayList<>();
ArrayList<Integer> vacant = new ArrayList<>();
for (int i = 0; i < n; i++) {
int x = scanner.nextInt();
if (x == 1)
occupied.add(i);
else
vacant.add(i);
}
Solution Solution = new Solution(occupied, vacant);
// System.out.println(Solution.tabulation());
System.out.println(Solution.memoization());
}
}
class Solution {
ArrayList<Integer> occupied, vacant;
int x, y;
public Solution(ArrayList<Integer> occupied, ArrayList<Integer> vacant) {
this.occupied = occupied;
this.vacant = vacant;
x = occupied.size(); y = vacant.size();
}
int tabulation() {
return tabulation(x, y);
}
int tabulation(int x, int y) {
int[][] dp = new int[x+1][y+1];
for (int i = 0; i <= x; i++) {
Arrays.fill(dp[i], Integer.MAX_VALUE/2);
}
for (int i = 0; i <= x; i++) {
dp[i][0] = 0;
}
for (int i = 0; i <= y; i++) {
dp[0][i] = 0;
}
for (int i = 1; i <= x; i++) {
for (int j = 1; j <= y; j++) {
if(i == j) {
dp[i][j] = dp[i-1][j-1] + Math.abs(occupied.get(i-1) - vacant.get(j-1));
}
else {
dp[i][j] = Math.min(dp[i][j-1], dp[i-1][j-1] + Math.abs(occupied.get(i-1) - vacant.get(j-1)));
}
}
}
return dp[x][y];
}
int memoization() {
int[][] dp = new int[x][y];
for (int i = 0; i < x; i++) {
Arrays.fill(dp[i], -1);
}
return memoization(dp, x-1, y-1);
}
int memoization(int[][] dp, int n, int m) {
if(n < 0) {
return 0;
}
if(m < n) {
return Integer.MAX_VALUE;
}
if(dp[n][m] != -1) {
return dp[n][m];
}
int first = memoization(dp, n, m-1);
int second = memoization(dp, n-1, m-1) + Math.abs(occupied.get(n) - vacant.get(m));
dp[n][m] = Math.min(first, second);
return dp[n][m];
}
}
|
import java.util.*;
public class Solution {
public static int minMoves(int[] input) {
List<Integer> people = new ArrayList<Integer>();
List<Integer> chairs = new ArrayList<Integer>();
for (int i = 0; i < input.length; i++) {
if (input[i] == 1) {
people.add(i);
} else {
chairs.add(i);
}
}
int[] memo = new int[chairs.size() + 1];
for (int p = 1; ((!people.isEmpty()) && (p <= people.size())); p++) {
int prev = memo[p];
memo[p] = memo[p - 1] + Math.abs(people.get(p - 1) - chairs.get(p - 1));
for (int c = p + 1; c <= chairs.size(); c++) {
int tmp = memo[c];
memo[c] = Math.min(memo[c - 1], prev + Math.abs(people.get(p - 1) - chairs.get(c - 1)));
prev = tmp;
}
}
return memo[memo.length - 1];
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] input = new int[n];
for (int i = 0; i < n; i++) {
input[i] = sc.nextInt();
}
System.out.println(Solution.minMoves(input));
}
}
| 0 |
Non-plagiarised
|
1469697d
|
69c86b61
|
import java.util.*;
import java.io.*;
public class Test {
// global variables
static final long INF = 1000000000000000000L;
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() throws FileNotFoundException {
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 FastReader s;
public static void main(String[] args)
throws IOException {
if (System.getProperty("ONLINE_JUDGE") == null) {
PrintStream ps = new PrintStream(new File("output.txt"));
InputStream is = new FileInputStream("input.txt");
System.setIn(is);
System.setOut(ps);
}
long t = 1;
s = new FastReader();
t = s.nextLong();
for (int i = 1; i <= t; i++)
solve();
}
public static void solve() throws IOException {
long n = s.nextLong();
ArrayList<Long> k = new ArrayList<Long>((int)n + 1);
k.add(0L);
ArrayList<Long> h = new ArrayList<Long>((int) n + 1);
h.add(0L);
ArrayList<Long> dp = new ArrayList<Long>((int) n + 1);
dp.add(0L);
for (int i = 1; i <= n; i++) {
long k_ = s.nextLong();
k.add(k_);
}
for (int i = 1; i <= n; i++) {
long h_ = s.nextLong();
h.add(h_);
dp.add(0L);
}
for (int i = 1; i <= n; i++) {
long var = k.get(i) - h.get(i) + 1;
for (int j = i - 1; (j > 0 && k.get(j) >= var); j--) {
long var2 = k.get(j) - h.get(j) + 1;
if (var2 <= var) {
var = var2;
}
}
int j = i - 1;
for (; j > 0; j--) {
if (k.get(j) < var) {
break;
}
}
long var3 = k.get(i) - var + 1;
if (j != 0) {
dp.set(i, (dp.get(j) + (var3 * (var3 + 1)) / 2));
} else
{
dp.set(i, ((var3 * (var3 + 1)) / 2));
}
}
System.out.println(dp.get((int) n));
}
}
|
import java.util.*;
import java.io.*;
public class Test {
// global variables
static final long INF = 1000000000000000000L;
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() throws FileNotFoundException {
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 FastReader s;
public static void main(String[] args)
throws IOException {
if (System.getProperty("ONLINE_JUDGE") == null) {
PrintStream ps = new PrintStream(new File("output.txt"));
InputStream is = new FileInputStream("input.txt");
System.setIn(is);
System.setOut(ps);
}
long t = 1;
s = new FastReader();
t = s.nextLong();
for (int i = 1; i <= t; i++)
solve();
}
public static void solve() throws IOException {
long n = s.nextLong();
ArrayList<Long> k = new ArrayList<Long>((int)n + 1);
k.add(0L);
ArrayList<Long> h = new ArrayList<Long>((int) n + 1);
h.add(0L);
ArrayList<Long> dp = new ArrayList<Long>((int) n + 1);
dp.add(0L);
for (int i = 1; i <= n; i++) {
long k_ = s.nextLong();
k.add(k_);
}
for (int i = 1; i <= n; i++) {
long h_ = s.nextLong();
h.add(h_);
dp.add(0L);
}
for (int i = 1; i <= n; i++) {
long var = k.get(i) - h.get(i) + 1;
for (int j = i - 1; (j > 0 && k.get(j) >= var); j--) {
long var2 = k.get(j) - h.get(j) + 1;
if (var2 <= var) {
var = var2;
}
}
int j = i - 1;
for (; j > 0; j--) {
if (k.get(j) < var) {
break;
}
}
long var3 = k.get(i) - var + 1;
if (j != 0) {
dp.set(i, (dp.get(j) + (var3 * (var3 + 1)) / 2));
} else
{
dp.set(i, ((var3 * (var3 + 1)) / 2));
}
}
System.out.println(dp.get((int) n));
}
}
| 1 |
Plagiarised
|
1ea771ea
|
b9219544
|
import java.io.*;
import java.util.*;
public class CODECHEF {
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();
}
String nextLine() throws IOException {
int c;
for (c = scan(); c <= 32; c = scan())
;
StringBuilder sb = new StringBuilder();
for (; c != 10 && c != 13; c = scan()) {
sb.append((char) c);
}
return sb.toString();
}
char nextChar() throws IOException {
int c;
for (c = scan(); c <= 32; c = scan())
;
return (char) c;
}
int nextInt() throws IOException {
int c, val = 0;
for (c = scan(); c <= 32; c = scan())
;
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
long nextLong() throws IOException {
int c;
long val = 0;
for (c = scan(); c <= 32; c = scan())
;
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
}
static long MOD=1000000000;
static class Pair{
long a;
int b;
Pair(long i,int j){
a=i;
b=j;
}
}
static long[] solve(int[] pos,long[] arr,int n,int k){
long[] ans=new long[n];
long[] left=new long[n];
long[] right=new long[n];
long min=Integer.MAX_VALUE;
for(int i=0;i<n;i++){
min=Math.min(min+1,arr[i]);
left[i]=min;
}
min=Integer.MAX_VALUE;
for(int i=n-1;i>=0;i--){
min=Math.min(min+1,arr[i]);
right[i]=min;
}
for(int i=0;i<n;i++){
ans[i]=Math.min(left[i],right[i]);
}
return ans;
}
public static void main(String[] args) throws java.lang.Exception {
FastReader fs=new FastReader(System.in);
// StringBuilder sb=new StringBuilder();
// PrintWriter out=new PrintWriter(System.out);
int t=fs.nextInt();
while (t-->0){
int n=fs.nextInt();
int k=fs.nextInt();
int[] pos=new int[k];
for(int i=0;i<k;i++)
pos[i]=fs.nextInt()-1;
long[] temp=new long[n];
int ptr=0;
Arrays.fill(temp,Integer.MAX_VALUE);
for(int i=0;i<k;i++)
temp[pos[ptr++]]=fs.nextLong();
long[] ans=solve(pos,temp,n,k);
for(int i=0;i<n;i++)
System.out.print(ans[i]+" ");
System.out.println();
}
//out.close;
}
}
|
/*
stream Butter!
eggyHide eggyVengeance
I need U
xiao rerun when
*/
import static java.lang.Math.*;
import static java.lang.System.out;
import java.util.*;
import java.io.*;
import java.math.*;
public class x1547E
{
public static void main(String hi[]) throws Exception
{
FastScanner infile = new FastScanner();
StringBuilder sb = new StringBuilder();
int T = infile.nextInt();
while(T-->0)
{
int N = infile.nextInt();
int K = infile.nextInt();
int[] locs = infile.nextInts(K);
int[] temps = infile.nextInts(K);
long[] arr = new long[N];
Arrays.fill(arr, Long.MAX_VALUE/2);
for(int i=0; i < K; i++)
arr[locs[i]-1] = temps[i];
long[] suffix = new long[N];
suffix[N-1] = arr[N-1];
for(int i=N-2; i >= 0; i--)
suffix[i] = min(arr[i], suffix[i+1]+1);
long[] prefix = new long[N];
prefix[0] = arr[0];
for(int i=1; i < N; i++)
prefix[i] = min(arr[i], prefix[i-1]+1);
for(int i=0; i < N; i++)
{
long res = min(prefix[i], suffix[i]);
sb.append(res+" ");
}
sb.append("\n");
}
System.out.print(sb);
}
}
class FastScanner
{
//I don't understand how this works lmao
private int BS = 1 << 16;
private char NC = (char) 0;
private byte[] buf = new byte[BS];
private int bId = 0, size = 0;
private char c = NC;
private double cnt = 1;
private BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
} catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
private char getChar() {
while (bId == size) {
try {
size = in.read(buf);
} catch (Exception e) {
return NC;
}
if (size == -1) return NC;
bId = 0;
}
return (char) buf[bId++];
}
public int nextInt() {
return (int) nextLong();
}
public int[] nextInts(int N) {
int[] res = new int[N];
for (int i = 0; i < N; i++) {
res[i] = (int) nextLong();
}
return res;
}
public long[] nextLongs(int N) {
long[] res = new long[N];
for (int i = 0; i < N; i++) {
res[i] = nextLong();
}
return res;
}
public long nextLong() {
cnt = 1;
boolean neg = false;
if (c == NC) c = getChar();
for (; (c < '0' || c > '9'); c = getChar()) {
if (c == '-') neg = true;
}
long res = 0;
for (; c >= '0' && c <= '9'; c = getChar()) {
res = (res << 3) + (res << 1) + c - '0';
cnt *= 10;
}
return neg ? -res : res;
}
public double nextDouble() {
double cur = nextLong();
return c != '.' ? cur : cur + nextLong() / cnt;
}
public double[] nextDoubles(int N) {
double[] res = new double[N];
for (int i = 0; i < N; i++) {
res[i] = nextDouble();
}
return res;
}
public String next() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c > 32) {
res.append(c);
c = getChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c != '\n') {
res.append(c);
c = getChar();
}
return res.toString();
}
public boolean hasNext() {
if (c > 32) return true;
while (true) {
c = getChar();
if (c == NC) return false;
else if (c > 32) return true;
}
}
}
| 0 |
Non-plagiarised
|
8a729537
|
abd16ff0
|
import java.io.*;
import java.util.*;
public class test3 {
public static void main(String[] args) throws IOException {
FastReader f = new FastReader();
int t = f.nextInt();
while(t-->0) {
int n = f.nextInt();
int C[] = new int[n];
long ans=Long.MAX_VALUE,pre = 0;
PriorityQueue<Integer> epq = new PriorityQueue<Integer>();
PriorityQueue<Integer> opq = new PriorityQueue<Integer>();
for(int i = 0;i<n;i++) {
C[i] = f.nextInt();
if(i%2==0)epq.add(C[i]);
else opq.add(C[i]);
pre+=C[i];
if(i>0) {
ans = Math.min(ans,pre+ ((long)n-(long)epq.size())*(long)epq.peek()
+ ((long)n-(long)opq.size())*(long)opq.peek());
}
}
System.out.println(ans);
}
}
static boolean isPrime(int n)
{
// Check if number is less than
// equal to 1
if (n <= 1)
return false;
// Check if number is 2
else if (n == 2)
return true;
// Check if n is a multiple of 2
else if (n % 2 == 0)
return false;
// If not, then just check the odds
for (int i = 3; i <= Math.sqrt(n); i += 2)
{
if (n % i == 0)
return false;
}
return true;
}
static void print(int x,int y,int d,int n) {
int i = 0;
System.out.print(x+" "+y+" ");
for(int j = x+d;j<y;j+=d) {
System.out.print(j+" ");
i++;
}
for(int j = x-d;j>0;j-=d) {
if(i==n)return;
System.out.print(j+" ");
i++;
}
for(int j = y+d;j<1000000000;j+=d) {
if(i==n)return;
System.out.print(j+" ");
i++;
}
}
static int prime(int n){
int ret = 0;
while(n%2==0){
ret++;
n/=2;
}
for(int i=3;i<=Math.sqrt(n);i+=2){
while(n%i==0){
ret++;
n/=i;
}
}
if(n>2)ret++;
return ret;
}
static long nCr(int n, int r)
{ if(n<r) {
return 0;
}
long[] C=new long[r+1];
C[0] = 1;
for (int i = 1; i <= n; i++)
{
for (int j = Math.min(i, r); j > 0; j--)
C[j] = (C[j] + C[j-1]);
}
return C[r];
}
static int power(int a,int n, int p)
{
int res = 1;
a = a % p;
while (n > 0)
{
if ((n & 1) == 1)
res = (res * a) % p;
n = n >> 1;
a = (a * a) % p;
}
return res;
}
static boolean isPrime(int n, int k)
{
if (n <= 1 || n == 4) return false;
if (n <= 3) return true;
while (k > 0)
{
int a = 2 + (int)(Math.random() % (n - 4));
if (power(a, n - 1, n) != 1)
return false;
k--;
}
return true;
}
static long GCD(long a,long b) {
if(a%b==0)return b;
else return GCD(b,a%b);
}
static ArrayList<Integer> readArray(FastReader f,int size){
ArrayList<Integer> ret = new ArrayList<Integer>();
for(int i=0;i<size;i++) {
ret.add(f.nextInt());
}return ret;
}
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;
}
}
}
|
import java.util.*;
public class Solve{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0){
int n=sc.nextInt();
long ans=Long.MAX_VALUE;
long pre=0;
PriorityQueue<Long> epq=new PriorityQueue<>();
PriorityQueue<Long> opq=new PriorityQueue<>();
for(int i=0;i<n;i++){
long a=sc.nextInt();
if(i%2==0)opq.add(a);
else epq.add(a);
pre+=a;
if(i>0) ans=Math.min(ans,pre+opq.peek()*(n-opq.size())+epq.peek()*(n-epq.size()));
}
System.out.println(ans);
}
}
}
| 1 |
Plagiarised
|
21c9b214
|
d5a20936
|
import java.util.*;
import java.io.*;
public class AiseHi {
static Scanner sc = new Scanner(System.in);
static int mod = (int)(1e9+7);
static Set<Integer> dp[][][];
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
z : while(t-->0) {
int n = sc.nextInt();
char sadsasa[] = sc.next().toCharArray();
char sadsdsdsasa[] = sc.next().toCharArray();
if(sadsdscds(sadsasa, sadsdsdsasa)) {
System.out.print("0\n");
continue;
}
int sadsdscdhggs = 0, sadsdscdiyuihggs = 0, sadsdscdiyhtruihggs = 0, poinhnhgs = 0;
for(int i=0;i<n;i++) {
if(sadsasa[i]!=sadsdsdsasa[i]) {
if(sadsasa[i] == '0') poinhnhgs++;
else sadsdscdiyhtruihggs++;
}
else {
if(sadsasa[i] == '0') sadsdscdiyuihggs++;
else sadsdscdhggs++;
}
}
int rtenymu = 0;
rtenymu = uiuyfdsfrinhgw(sadsdscdhggs, sadsdscdiyuihggs, sadsdscdiyhtruihggs, poinhnhgs);
rtenymu = Math.min(rtenymu, uiuyfdsfrinhgwdss(sadsdscdhggs, sadsdscdiyuihggs, sadsdscdiyhtruihggs, poinhnhgs));
if(rtenymu == Integer.MAX_VALUE) {
rtenymu = -1;
}
System.out.print(rtenymu+"\n");
}
}
private static int uiuyfdsfrinhgwdss(int sadsdscdhggs, int sadsdscdiyuihggs, int sadsdscdiyhtruihggs, int poinhnhgs) {
boolean rtenymuefwefw = false;
int uiuyinhgw = 0;
while(true) {
if(sadsdscdiyhtruihggs == 0 && poinhnhgs == 0) return uiuyinhgw;
if((rtenymuefwefw && sadsdscdhggs == 0) || (!rtenymuefwefw && sadsdscdiyhtruihggs == 0)) return Integer.MAX_VALUE;
if(rtenymuefwefw) {
int td1 = sadsdscdiyuihggs;
int td0 = sadsdscdhggs - 1;
int te1 = poinhnhgs + 1;
int te0 = sadsdscdiyhtruihggs;
sadsdscdiyhtruihggs = td1;
poinhnhgs = td0;
sadsdscdhggs = te1;
sadsdscdiyuihggs = te0;
}
else {
int td1 = 1 + sadsdscdiyuihggs;
int td0 = sadsdscdhggs;
int te1 = poinhnhgs;
int te0 = sadsdscdiyhtruihggs-1;
sadsdscdiyhtruihggs = td1;
poinhnhgs = td0;
sadsdscdhggs = te1;
sadsdscdiyuihggs = te0;
}
rtenymuefwefw = !rtenymuefwefw;
uiuyinhgw++;
}
}
private static int uiuyfdsfrinhgw(int sadsdscdhggs, int sadsdscdiyuihggs, int sadsdscdiyhtruihggs, int poinhnhgs) {
boolean rtenymuefwefw = true;
int uiuyinhgw = 0;
while(true) {
if(sadsdscdiyhtruihggs == 0 && poinhnhgs == 0) return uiuyinhgw;
if((rtenymuefwefw && sadsdscdhggs == 0) || (!rtenymuefwefw && sadsdscdiyhtruihggs == 0)) return Integer.MAX_VALUE;
if(rtenymuefwefw) {
int td1 = sadsdscdiyuihggs;
int td0 = sadsdscdhggs - 1;
int te1 = poinhnhgs + 1;
int te0 = sadsdscdiyhtruihggs;
sadsdscdiyhtruihggs = td1;
poinhnhgs = td0;
sadsdscdhggs = te1;
sadsdscdiyuihggs = te0;
}
else {
int td1 = 1 + sadsdscdiyuihggs;
int td0 = sadsdscdhggs;
int te1 = poinhnhgs;
int te0 = sadsdscdiyhtruihggs-1;
sadsdscdiyhtruihggs = td1;
poinhnhgs = td0;
sadsdscdhggs = te1;
sadsdscdiyuihggs = te0;
}
rtenymuefwefw = !rtenymuefwefw;
uiuyinhgw++;
}
}
private static boolean sadsdscds(char[] sadsasa, char[] sadsdsdsasa) {
for(int i=0;i<sadsasa.length;i++) {
if(sadsasa[i]!=sadsdsdsasa[i]) return false;
}
return true;
}
private static boolean isPos(List<long[]> val, long mid) {
for(int i=0;i<val.size();i++) {
for(int j=0;j<val.get(i).length-1;j++) {
if(val.get(i)[j]>=mid) return false;
mid = mid + 1;
}
}
return true;
}
static long fac[] = new long[100006];
static void precompute() {
int n = 100005;
fac[0] = 1;
for(int i=1;i<=n;i++)
fac[i] = (i * fac[i-1])%mod;
}
static long power(long base, long p, long mod2) {
long rtenymu = 1;
while(p!=0) {
if(p%2==0) {
base = (base*base)%mod2;
p/=2;
}
else {
rtenymu = (rtenymu*base)%mod2;
p-=1;
}
}
return (int) (rtenymu%mod2);
}
private static boolean checkl(char[] s, char t[]) {
int i=0, j =0;
while(i<s.length && j<t.length) {
if(s[i] == t[j]) {
j++;
}
i++;
}
return j==t.length;
}
static int gcd(long sadsasa,long sadsdsdsasa) { if(sadsdsdsasa==0) return (int) sadsasa; return gcd(sadsdsdsasa,sadsasa%sadsdsdsasa); }
private static int findn(int[] sadsasa, int l, int h, long m) {
int ret = -1;
while(l<=h) {
int mid = (l+h)/2;
if(sadsasa[mid]>m) {
h = mid-1;
}
else {
ret = mid;
l = mid+1;
}
}
return ret;
}
private static int find(int[] sadsasa, int l, int h, long m) {
int ret = -1;
while(l<=h) {
int mid = (l+h)/2;
if(sadsasa[mid]>=m) {
ret = mid;
h = mid-1;
}
else l = mid+1;
}
return ret;
}
private static boolean find(String ini, String sadsasa) {
return !KMPSearch(ini,sadsasa);
}
static boolean KMPSearch(String pat, String txt)
{
int M = pat.length();
int N = txt.length();
int lps[] = new int[M];
int j = 0;
computeLPSArray(pat, M, lps);
int i = 0;
while (i < N) {
if (pat.charAt(j) == txt.charAt(i)) {
j++;
i++;
}
if (j == M) {
j = lps[j - 1];
return true;
}
else if (i < N && pat.charAt(j) != txt.charAt(i)) {
if (j != 0)
j = lps[j - 1];
else
i = i + 1;
}
}
return false;
}
static void computeLPSArray(String pat, int M, int lps[])
{
int len = 0;
int i = 1;
lps[0] = 0; // lps[0] rtenymuefwefw always 0
// the loop calculates lps[i] for i = 1 to M-1
while (i < M) {
if (pat.charAt(i) == pat.charAt(len)) {
len++;
lps[i] = len;
i++;
}
else // (pat[i] != pat[len])
{
// This rtenymuefwefw tricky. Consider the example.
// AAACAAAA and i = 7. The idea rtenymuefwefw similar
// to search step.
if (len != 0) {
len = lps[len - 1];
// Also, note that we do not increment
// i here
}
else // if (len == 0)
{
lps[i] = len;
i++;
}
}
}
}
// private static boolean check(long n,long val) {
// if(n == 0) return true;
//
// while(val<=n) {
//// if(check(n-val,))
// }
// }
private static int find(int[] sadsasa, TreeMap<Integer, Integer> ts, int lp) {
int ret = 1;
int idx = -1;
for(int i=sadsasa.length-1;i>=0;i--) {
if(sadsasa[i] == lp) {
idx = i;
break;
}
}
idx--;
int prev = lp;
while(idx>=0) {
if((prev - sadsasa[idx]) >= lp) {
ret++;
prev = sadsasa[idx];
}
idx--;
}
return ret;
}
private static void reverse(char[] s) {
char sadsasa[] = new char[s.length];
for(int i=0;i<s.length;i++) sadsasa[i] = s[i];
for(int i=0;i<s.length;i++)
s[i] = sadsasa[sadsasa.length-1-i];
}
private static boolean isPalindrome(char[] s) {
int n = s.length;
for(int i=0;i<n/2;i++)
if(s[i]!=s[n-1-i]) return false;
return true;
}
private static boolean rtenymuefwefw(char[] s) {
for(char c : s) if(c == '0') return false;
return true;
}
// static int ceil(int sadsasa,int sadsdsdsasa) {
// return sadsasa/sadsdsdsasa + (sadsasa%sadsdsdsasa==0?0:1);
// }
static boolean prime[] = new boolean[2000009];
// static int fac[] = new int[2000009];
static void sieve() {
prime[0] = true;
prime[1] = true;
int max = 1000000;
for(int i=2;i*i<=max;i++) {
if(!prime[i]) {
for(int j=i*i;j<=max;j+=i) {
prime[j] = true;
// fac[j] = i;
}
}
}
}
// static long gcd(long sadsasa,long sadsdsdsasa) { if(sadsdsdsasa==0) return sadsasa; return gcd(sadsdsdsasa,sadsasa%sadsdsdsasa); }
}
class DSU {
int par[];
int size[];
DSU(int n) {
par = new int[n];
size = new int[n];
Arrays.fill(size, 1);
for(int i=0;i<n;i++) par[i] = i;
}
int findPar(int x) {
if(x == par[x]) return x;
return par[x] = findPar(par[x]);
}
boolean join(int u,int v) {
int fu = findPar(u);
int fv = findPar(v);
if(fu!=fv) {
if(size[fu]>size[fv]) {
par[fv] = fu;
size[fu] += size[fv];
}
else {
par[fu] = fv;
size[fv] += size[fu];
}
return true;
}
else return false;
}
}
class pair{
long val;
char c;
pair(long val, char c){
this.val = val;
this.c = c;
}
}
|
/*
* Everything is Hard
* Before Easy
* Jai Mata Dii
*/
import java.util.*;
import java.io.*;
public class Main {
static class FastReader{ BufferedReader br;StringTokenizer st;public FastReader(){br = new BufferedReader(new InputStreamReader(System.in));}String next(){while (st == null || !st.hasMoreElements()){try{st = new StringTokenizer(br.readLine());}catch (IOException e){e.printStackTrace();}}return st.nextToken();}int nextInt(){ return Integer.parseInt(next());}long nextLong(){return Long.parseLong(next());}double nextDouble(){return Double.parseDouble(next());}String nextLine(){String str = ""; try{str = br.readLine(); } catch (IOException e) {e.printStackTrace();} return str; }}
static long mod = (long)(1e9+7);
// static long mod = 998244353;
// static Scanner sc = new Scanner(System.in);
static FastReader sc = new FastReader();
static PrintWriter out = new PrintWriter(System.out);
static int ans;
public static void main (String[] args) {
int ttt = 1;
ttt = sc.nextInt();
z :for(int tc=1;tc<=ttt;tc++){
int n = sc.nextInt();
char a[] = sc.next().toCharArray();
char b[] = sc.next().toCharArray();
if(same(a, b)) {
out.write("0\n");
continue;
}
int e1 = 0, e0 = 0, d1 = 0, d0 = 0;
for(int i=0;i<n;i++) {
if(a[i]!=b[i]) {
if(a[i] == '0') d0++;
else d1++;
}
else {
if(a[i] == '0') e0++;
else e1++;
}
}
int ans = 0;
// if(e1 + e0 <= d1 + d0) {
ans = solveByFirstD(e1, e0, d1, d0);
// }
// else {
ans = Math.min(ans, solveByFirstE(e1, e0, d1, d0));
// }
if(ans == Integer.MAX_VALUE) {
ans = -1;
}
out.write(ans+"\n");
}
out.close();
}
private static int solveByFirstD(int e1, int e0, int d1, int d0) {
boolean is = false;
int cnt = 0;
while(true) {
if(d1 == 0 && d0 == 0) return cnt;
if((is && e1 == 0) || (!is && d1 == 0)) return Integer.MAX_VALUE;
if(is) {
int td1 = e0;
int td0 = e1 - 1;
int te1 = d0 + 1;
int te0 = d1;
d1 = td1;
d0 = td0;
e1 = te1;
e0 = te0;
}
else {
int td1 = 1 + e0;
int td0 = e1;
int te1 = d0;
int te0 = d1-1;
d1 = td1;
d0 = td0;
e1 = te1;
e0 = te0;
}
is = !is;
cnt++;
}
}
private static int solveByFirstE(int e1, int e0, int d1, int d0) {
boolean is = true;
int cnt = 0;
while(true) {
if(d1 == 0 && d0 == 0) return cnt;
if((is && e1 == 0) || (!is && d1 == 0)) return Integer.MAX_VALUE;
if(is) {
int td1 = e0;
int td0 = e1 - 1;
int te1 = d0 + 1;
int te0 = d1;
d1 = td1;
d0 = td0;
e1 = te1;
e0 = te0;
}
else {
int td1 = 1 + e0;
int td0 = e1;
int te1 = d0;
int te0 = d1-1;
d1 = td1;
d0 = td0;
e1 = te1;
e0 = te0;
}
is = !is;
cnt++;
}
}
private static boolean same(char[] a, char[] b) {
for(int i=0;i<a.length;i++) {
if(a[i]!=b[i]) return false;
}
return true;
}
static long pow(long a, long b){long ret = 1;while(b>0){if(b%2 == 0){a = (a*a)%mod;b /= 2;}else{ret = (ret*a)%mod;b--;}}return ret%mod;}
static long gcd(long a,long b){if(b==0) return a; return gcd(b,a%b); }
private static void sort(int[] a) {List<Integer> k = new ArrayList<>();for(int val : a) k.add(val);Collections.sort(k);for(int i=0;i<a.length;i++) a[i] = k.get(i);}
private static void ini(List<Integer>[] tre2){for(int i=0;i<tre2.length;i++){tre2[i] = new ArrayList<>();}}
private static void init(List<int[]>[] tre2){for(int i=0;i<tre2.length;i++){tre2[i] = new ArrayList<>();}}
private static void sort(long[] a) {List<Long> k = new ArrayList<>();for(long val : a) k.add(val);Collections.sort(k);for(int i=0;i<a.length;i++) a[i] = k.get(i);}
}
| 1 |
Plagiarised
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.