exec_outcome stringclasses 1 value | code_uid stringlengths 32 32 | file_name stringclasses 111 values | prob_desc_created_at stringlengths 10 10 | prob_desc_description stringlengths 63 3.8k | prob_desc_memory_limit stringclasses 18 values | source_code stringlengths 117 65.5k | lang_cluster stringclasses 1 value | prob_desc_sample_inputs stringlengths 2 802 | prob_desc_time_limit stringclasses 27 values | prob_desc_sample_outputs stringlengths 2 796 | prob_desc_notes stringlengths 4 3k ⌀ | lang stringclasses 5 values | prob_desc_input_from stringclasses 3 values | tags listlengths 0 11 | src_uid stringlengths 32 32 | prob_desc_input_spec stringlengths 28 2.37k ⌀ | difficulty int64 -1 3.5k ⌀ | prob_desc_output_spec stringlengths 17 1.47k ⌀ | prob_desc_output_to stringclasses 3 values | hidden_unit_tests stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PASSED | 9c561f9b843245f9e8b4f17d75339382 | train_003.jsonl | 1470323700 | Little Mishka enjoys programming. Since her birthday has just passed, her friends decided to present her with array of non-negative integers a1, a2, ..., an of n elements!Mishka loved the array and she instantly decided to determine its beauty value, but she is too little and can't process large arrays. Right because of that she invited you to visit her and asked you to process m queries.Each query is processed in the following way: Two integers l and r (1 ≤ l ≤ r ≤ n) are specified — bounds of query segment. Integers, presented in array segment [l, r] (in sequence of integers al, al + 1, ..., ar) even number of times, are written down. XOR-sum of written down integers is calculated, and this value is the answer for a query. Formally, if integers written down in point 2 are x1, x2, ..., xk, then Mishka wants to know the value , where — operator of exclusive bitwise OR. Since only the little bears know the definition of array beauty, all you are to do is to answer each of queries presented. | 256 megabytes |
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import static java.util.Comparator.comparingInt;
public class MishkaAndInterestingSum implements Closeable {
private InputReader in = new InputReader(System.in);
private PrintWriter out = new PrintWriter(System.out);
private final int MAX = 1000000;
public void solve() {
int n = in.ni();
int[] x = new int[n + 1];
for (int i = 1; i <= n; i++) {
x[i] = in.ni();
}
int[] prefix = new int[n + 1];
for (int i = 1; i <= n; i++) {
prefix[i] = prefix[i - 1] ^ x[i];
}
int q = in.ni();
List<Query> queries = new ArrayList<>();
for (int i = 0; i < q; i++) {
queries.add(new Query(i, in.ni(), in.ni()));
}
queries.sort(comparingInt(a -> a.right));
int idx = 0;
int[] result = new int[q];
Map<Integer, Integer> lastSeen = new HashMap<>();
FenwickTree tree = new FenwickTree();
for (int i = 1; i <= n; i++) {
if (idx == q) break;
int value = x[i];
int seen = lastSeen.getOrDefault(value, -1);
if (seen != -1) {
tree.update(seen, value);
}
lastSeen.put(value, i);
tree.update(i, value);
while (idx < q && queries.get(idx).right == i) {
Query query = queries.get(idx);
result[query.idx] = prefix[query.right] ^ prefix[query.left - 1] ^ tree.query(query.left, query.right);
idx++;
}
}
for (int ans : result) {
out.println(ans);
}
}
private class Query {
private int idx, left, right;
private Query(int idx, int left, int right) {
this.idx = idx;
this.left = left;
this.right = right;
}
}
private class FenwickTree {
private int[] tree = new int[MAX + 1];
public void update(int idx, int delta) {
for (; idx <= MAX; idx += (idx & -idx)) {
tree[idx] ^= delta;
}
}
public int query(int left, int right) {
return query(right) ^ query(left - 1);
}
public int query(int idx) {
int result = 0;
for (; idx > 0; idx -= (idx & -idx)) {
result ^= tree[idx];
}
return result;
}
}
@Override
public void close() throws IOException {
in.close();
out.close();
}
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 ni() {
return Integer.parseInt(next());
}
public long nl() {
return Long.parseLong(next());
}
public void close() throws IOException {
reader.close();
}
}
public static void main(String[] args) throws IOException {
try (MishkaAndInterestingSum instance = new MishkaAndInterestingSum()) {
instance.solve();
}
}
}
| Java | ["3\n3 7 8\n1\n1 3", "7\n1 2 1 3 3 2 3\n5\n4 7\n4 5\n1 3\n1 7\n1 5"] | 3.5 seconds | ["0", "0\n3\n1\n3\n2"] | NoteIn the second sample:There is no integers in the segment of the first query, presented even number of times in the segment — the answer is 0.In the second query there is only integer 3 is presented even number of times — the answer is 3.In the third query only integer 1 is written down — the answer is 1.In the fourth query all array elements are considered. Only 1 and 2 are presented there even number of times. The answer is .In the fifth query 1 and 3 are written down. The answer is . | Java 8 | standard input | [
"data structures"
] | 6fe09ae0980bbc59230290c7ac0bc7c3 | The first line of the input contains single integer n (1 ≤ n ≤ 1 000 000) — the number of elements in the array. The second line of the input contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — array elements. The third line of the input contains single integer m (1 ≤ m ≤ 1 000 000) — the number of queries. Each of the next m lines describes corresponding query by a pair of integers l and r (1 ≤ l ≤ r ≤ n) — the bounds of query segment. | 2,100 | Print m non-negative integers — the answers for the queries in the order they appear in the input. | standard output | |
PASSED | 8541af9edd00a5d6cab9d3bed68a3260 | train_003.jsonl | 1470323700 | Little Mishka enjoys programming. Since her birthday has just passed, her friends decided to present her with array of non-negative integers a1, a2, ..., an of n elements!Mishka loved the array and she instantly decided to determine its beauty value, but she is too little and can't process large arrays. Right because of that she invited you to visit her and asked you to process m queries.Each query is processed in the following way: Two integers l and r (1 ≤ l ≤ r ≤ n) are specified — bounds of query segment. Integers, presented in array segment [l, r] (in sequence of integers al, al + 1, ..., ar) even number of times, are written down. XOR-sum of written down integers is calculated, and this value is the answer for a query. Formally, if integers written down in point 2 are x1, x2, ..., xk, then Mishka wants to know the value , where — operator of exclusive bitwise OR. Since only the little bears know the definition of array beauty, all you are to do is to answer each of queries presented. | 256 megabytes | import java.util.*;
import java.io.*;
public class MishkaandInterestingsum
{
/************************ SOLUTION STARTS HERE ***********************/
static int BIT[];
static int N;
static void update(int idx,int val){
for(;idx <= N;idx += (idx & ((~idx) + 1)))
BIT[idx] ^= val;
}
static int xorSum(int idx){
int xor_sum = 0;
for(;idx > 0;idx -= (idx & ((~idx) + 1)))
xor_sum ^= BIT[idx];
return xor_sum;
}
static int xorSum(int L , int R){
return xorSum(L - 1) ^ xorSum(R);
}
static class Pair {
int index , L;
Pair(int index , int L){
this.index = index;
this.L = L;
}
}
private static void solve(FastScanner s1, PrintWriter out){
N = s1.nextInt();
BIT = new int[N + 1];
int arr[] = s1.nextIntArrayOneBased(N);
int prefixXor[] = new int[N + 1];
HashMap<Integer,Integer> last = new HashMap<>();
for(int i=1;i<=N;i++)
prefixXor[i] = arr[i] ^ prefixXor[i - 1];
int Q = s1.nextInt();
HashMap<Integer, ArrayList<Pair>> query = new HashMap<>();
for(int i=0;i<Q;i++){
int L = s1.nextInt();
int R = s1.nextInt();
ArrayList<Pair> arl = query.get(R);
if(arl == null)
arl = new ArrayList<>();
arl.add(new Pair(i, L));
query.put(R, arl);
}
int ans[] = new int[Q];
for(int i=1;i<=N;i++){
if(last.containsKey(arr[i]))
update(last.get(arr[i]), arr[i]);
update(i, arr[i]);
last.put(arr[i], i);
if(query.containsKey(i)){
for(Pair p: query.get(i))
ans[p.index] = prefixXor[i] ^ prefixXor[p.L - 1] ^ xorSum(p.L, i);
}
}
for(int a:ans)
out.println(a);
}
/************************ SOLUTION ENDS HERE ************************/
/************************ TEMPLATE STARTS HERE *********************/
public static void main(String []args) throws IOException {
FastScanner in = new FastScanner(System.in);
PrintWriter out =
new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), false);
solve(in, out);
in.close();
out.close();
}
static class FastScanner{
BufferedReader reader;
StringTokenizer st;
FastScanner(InputStream stream){reader=new BufferedReader(new InputStreamReader(stream));st=null;}
String next()
{while(st == null || !st.hasMoreTokens()){try{String line = reader.readLine();if(line == null){return null;}
st = new StringTokenizer(line);}catch (Exception e){throw new RuntimeException();}}return st.nextToken();}
String nextLine() {String s=null;try{s=reader.readLine();}catch(IOException e){e.printStackTrace();}return s;}
int nextInt() {return Integer.parseInt(next());}
long nextLong() {return Long.parseLong(next());}
double nextDouble(){return Double.parseDouble(next());}
char nextChar() {return next().charAt(0);}
int[] nextIntArray(int n) {int[] arr= new int[n]; int i=0;while(i<n){arr[i++]=nextInt();} return arr;}
long[] nextLongArray(int n) {long[]arr= new long[n]; int i=0;while(i<n){arr[i++]=nextLong();} return arr;}
int[] nextIntArrayOneBased(int n) {int[] arr= new int[n+1]; int i=1;while(i<=n){arr[i++]=nextInt();} return arr;}
long[] nextLongArrayOneBased(int n){long[]arr= new long[n+1];int i=1;while(i<=n){arr[i++]=nextLong();}return arr;}
void close(){try{reader.close();}catch(IOException e){e.printStackTrace();}}
}
/************************ TEMPLATE ENDS HERE ************************/
} | Java | ["3\n3 7 8\n1\n1 3", "7\n1 2 1 3 3 2 3\n5\n4 7\n4 5\n1 3\n1 7\n1 5"] | 3.5 seconds | ["0", "0\n3\n1\n3\n2"] | NoteIn the second sample:There is no integers in the segment of the first query, presented even number of times in the segment — the answer is 0.In the second query there is only integer 3 is presented even number of times — the answer is 3.In the third query only integer 1 is written down — the answer is 1.In the fourth query all array elements are considered. Only 1 and 2 are presented there even number of times. The answer is .In the fifth query 1 and 3 are written down. The answer is . | Java 8 | standard input | [
"data structures"
] | 6fe09ae0980bbc59230290c7ac0bc7c3 | The first line of the input contains single integer n (1 ≤ n ≤ 1 000 000) — the number of elements in the array. The second line of the input contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — array elements. The third line of the input contains single integer m (1 ≤ m ≤ 1 000 000) — the number of queries. Each of the next m lines describes corresponding query by a pair of integers l and r (1 ≤ l ≤ r ≤ n) — the bounds of query segment. | 2,100 | Print m non-negative integers — the answers for the queries in the order they appear in the input. | standard output | |
PASSED | 2b5b2820345ad5181d2d468ebf7b5d23 | train_003.jsonl | 1470323700 | Little Mishka enjoys programming. Since her birthday has just passed, her friends decided to present her with array of non-negative integers a1, a2, ..., an of n elements!Mishka loved the array and she instantly decided to determine its beauty value, but she is too little and can't process large arrays. Right because of that she invited you to visit her and asked you to process m queries.Each query is processed in the following way: Two integers l and r (1 ≤ l ≤ r ≤ n) are specified — bounds of query segment. Integers, presented in array segment [l, r] (in sequence of integers al, al + 1, ..., ar) even number of times, are written down. XOR-sum of written down integers is calculated, and this value is the answer for a query. Formally, if integers written down in point 2 are x1, x2, ..., xk, then Mishka wants to know the value , where — operator of exclusive bitwise OR. Since only the little bears know the definition of array beauty, all you are to do is to answer each of queries presented. | 256 megabytes | // package codeforces.cf3xx.cf365.div2;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.Map;
/**
* Created by hama_du on 2016/08/06.
*/
public class D {
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
int[] a = in.nextInts(n);
long[] imos = new long[n+1];
for (int i = 0; i < n ; i++) {
imos[i+1] = imos[i] ^ a[i];
}
int[] ra = new int[n];
Map<Integer,Integer> lmap = new HashMap<>();
for (int i = 0; i < a.length; i++) {
if (lmap.containsKey(a[i])) {
ra[i] = lmap.get(a[i]);
continue;
}
ra[i] = lmap.size();
lmap.put(a[i], lmap.size());
}
int m = in.nextInt();
int[][] q = new int[m][3];
for (int i = 0; i < m ; i++) {
for (int j = 0; j < 2 ; j++) {
q[i][j] = in.nextInt();
}
q[i][0]--;
q[i][2] = i;
}
Arrays.sort(q, (o1, o2) -> o1[1] - o2[1]);
BIT bit = new BIT(1000010);
int[] last = new int[1000010];
long[] ans = new long[m];
Arrays.fill(last, -1);
int head = 0;
for (int i = 0; i < m ; i++) {
while (head < q[i][1]) {
int ni = ra[head];
if (last[ni] != -1) {
bit.set(last[ni]+1, 0);
}
last[ni] = head;
bit.set(last[ni]+1, a[head]);
head++;
}
ans[q[i][2]] = bit.range(q[i][0]+1, q[i][1]) ^ imos[q[i][1]] ^ imos[q[i][0]];
}
for (int i = 0; i < m ; i++) {
out.println(ans[i]);
}
out.flush();
}
static class BIT {
long N;
long[] data;
BIT(int n) {
N = n;
data = new long[n+1];
}
long sum(int i) {
long s = 0;
while (i > 0) {
s ^= data[i];
i -= i & (-i);
}
return s;
}
long range(int i, int j) {
return sum(j) ^ sum(i-1);
}
void set(int i, long x) {
add(i, x^range(i, i));
}
void add(int i, long x) {
while (i <= N) {
data[i] ^= x;
i += i & (-i);
}
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
private int[] nextInts(int n) {
int[] ret = new int[n];
for (int i = 0; i < n; i++) {
ret[i] = nextInt();
}
return ret;
}
private int[][] nextIntTable(int n, int m) {
int[][] ret = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
ret[i][j] = nextInt();
}
}
return ret;
}
private long[] nextLongs(int n) {
long[] ret = new long[n];
for (int i = 0; i < n; i++) {
ret[i] = nextLong();
}
return ret;
}
private long[][] nextLongTable(int n, int m) {
long[][] ret = new long[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
ret[i][j] = nextLong();
}
}
return ret;
}
private double[] nextDoubles(int n) {
double[] ret = new double[n];
for (int i = 0; i < n; i++) {
ret[i] = nextDouble();
}
return ret;
}
private int next() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public char nextChar() {
int c = next();
while (isSpaceChar(c))
c = next();
if ('a' <= c && c <= 'z') {
return (char) c;
}
if ('A' <= c && c <= 'Z') {
return (char) c;
}
throw new InputMismatchException();
}
public String nextToken() {
int c = next();
while (isSpaceChar(c))
c = next();
StringBuilder res = new StringBuilder();
do {
res.append((char) c);
c = next();
} while (!isSpaceChar(c));
return res.toString();
}
public int nextInt() {
int c = next();
while (isSpaceChar(c))
c = next();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = next();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c-'0';
c = next();
} while (!isSpaceChar(c));
return res*sgn;
}
public long nextLong() {
int c = next();
while (isSpaceChar(c))
c = next();
long sgn = 1;
if (c == '-') {
sgn = -1;
c = next();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c-'0';
c = next();
} while (!isSpaceChar(c));
return res*sgn;
}
public double nextDouble() {
return Double.valueOf(nextToken());
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static void debug(Object... o) {
System.err.println(Arrays.deepToString(o));
}
}
| Java | ["3\n3 7 8\n1\n1 3", "7\n1 2 1 3 3 2 3\n5\n4 7\n4 5\n1 3\n1 7\n1 5"] | 3.5 seconds | ["0", "0\n3\n1\n3\n2"] | NoteIn the second sample:There is no integers in the segment of the first query, presented even number of times in the segment — the answer is 0.In the second query there is only integer 3 is presented even number of times — the answer is 3.In the third query only integer 1 is written down — the answer is 1.In the fourth query all array elements are considered. Only 1 and 2 are presented there even number of times. The answer is .In the fifth query 1 and 3 are written down. The answer is . | Java 8 | standard input | [
"data structures"
] | 6fe09ae0980bbc59230290c7ac0bc7c3 | The first line of the input contains single integer n (1 ≤ n ≤ 1 000 000) — the number of elements in the array. The second line of the input contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — array elements. The third line of the input contains single integer m (1 ≤ m ≤ 1 000 000) — the number of queries. Each of the next m lines describes corresponding query by a pair of integers l and r (1 ≤ l ≤ r ≤ n) — the bounds of query segment. | 2,100 | Print m non-negative integers — the answers for the queries in the order they appear in the input. | standard output | |
PASSED | 306a31f9cfa02cb1b4cb5d66457bbf9a | train_003.jsonl | 1470323700 | Little Mishka enjoys programming. Since her birthday has just passed, her friends decided to present her with array of non-negative integers a1, a2, ..., an of n elements!Mishka loved the array and she instantly decided to determine its beauty value, but she is too little and can't process large arrays. Right because of that she invited you to visit her and asked you to process m queries.Each query is processed in the following way: Two integers l and r (1 ≤ l ≤ r ≤ n) are specified — bounds of query segment. Integers, presented in array segment [l, r] (in sequence of integers al, al + 1, ..., ar) even number of times, are written down. XOR-sum of written down integers is calculated, and this value is the answer for a query. Formally, if integers written down in point 2 are x1, x2, ..., xk, then Mishka wants to know the value , where — operator of exclusive bitwise OR. Since only the little bears know the definition of array beauty, all you are to do is to answer each of queries presented. | 256 megabytes | //package round365;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.InputMismatchException;
public class D {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni();
int[] a = na(n);
int[] b = shrink(a);
int[] prev = new int[n];
int[] time = new int[n+1];
Arrays.fill(time, -1);
for(int i = 0;i < n;i++){
prev[i] = time[b[i]];
time[b[i]] = i;
}
int[] cum = new int[n+1];
for(int i = 0;i < n;i++){
cum[i+1] = cum[i] ^ a[i];
}
int Q = ni();
int[][] qs = new int[Q][];
for(int i = 0;i < Q;i++){
qs[i] = new int[]{ni()-1, ni()-1, i};
}
Arrays.sort(qs, new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
return a[1] - b[1];
}
});
int p = 0;
int[] rets = new int[Q];
int[] ft = new int[n+3];
for(int i = 0;i < n;i++){
if(prev[i] >= 0){
addFenwick(ft, prev[i]+1, a[i]);
}else{
addFenwick(ft, 0, a[i]);
}
addFenwick(ft, i+1, a[i]);
while(p < Q && qs[p][1] <= i){
int all = sumFenwick(ft, qs[p][0]);
int odd = cum[qs[p][1]+1]^cum[qs[p][0]];
rets[qs[p][2]] = all^odd;
p++;
}
}
for(int v : rets){
out.println(v);
}
}
public static int[] shrink(int[] a) {
int n = a.length;
long[] b = new long[n];
for (int i = 0; i < n; i++)
b[i] = (long) a[i] << 32 | i;
Arrays.sort(b);
int[] ret = new int[n];
int p = 0;
for (int i = 0; i < n; i++) {
if (i > 0 && (b[i] ^ b[i - 1]) >> 32 != 0)
p++;
ret[(int) b[i]] = p;
}
return ret;
}
public static int sumFenwick(int[] ft, int i) {
int sum = 0;
for (i++; i > 0; i -= i & -i)
sum ^= ft[i];
return sum;
}
public static void addFenwick(int[] ft, int i, int v) {
if (v == 0 || i < 0)
return;
int n = ft.length;
for (i++; i < n; i += i & -i)
ft[i] ^= v;
}
public static int[] restoreFenwick(int[] ft) {
int n = ft.length - 1;
int[] ret = new int[n];
for (int i = 0; i < n; i++)
ret[i] = sumFenwick(ft, i);
for (int i = n - 1; i >= 1; i--)
ret[i] -= ret[i - 1];
return ret;
}
void run() throws Exception
{
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new D().run(); }
private byte[] inbuf = new byte[1024];
private int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
| Java | ["3\n3 7 8\n1\n1 3", "7\n1 2 1 3 3 2 3\n5\n4 7\n4 5\n1 3\n1 7\n1 5"] | 3.5 seconds | ["0", "0\n3\n1\n3\n2"] | NoteIn the second sample:There is no integers in the segment of the first query, presented even number of times in the segment — the answer is 0.In the second query there is only integer 3 is presented even number of times — the answer is 3.In the third query only integer 1 is written down — the answer is 1.In the fourth query all array elements are considered. Only 1 and 2 are presented there even number of times. The answer is .In the fifth query 1 and 3 are written down. The answer is . | Java 8 | standard input | [
"data structures"
] | 6fe09ae0980bbc59230290c7ac0bc7c3 | The first line of the input contains single integer n (1 ≤ n ≤ 1 000 000) — the number of elements in the array. The second line of the input contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — array elements. The third line of the input contains single integer m (1 ≤ m ≤ 1 000 000) — the number of queries. Each of the next m lines describes corresponding query by a pair of integers l and r (1 ≤ l ≤ r ≤ n) — the bounds of query segment. | 2,100 | Print m non-negative integers — the answers for the queries in the order they appear in the input. | standard output | |
PASSED | 77860d8fa91d7b5678f6825668cc5da0 | train_003.jsonl | 1470323700 | Little Mishka enjoys programming. Since her birthday has just passed, her friends decided to present her with array of non-negative integers a1, a2, ..., an of n elements!Mishka loved the array and she instantly decided to determine its beauty value, but she is too little and can't process large arrays. Right because of that she invited you to visit her and asked you to process m queries.Each query is processed in the following way: Two integers l and r (1 ≤ l ≤ r ≤ n) are specified — bounds of query segment. Integers, presented in array segment [l, r] (in sequence of integers al, al + 1, ..., ar) even number of times, are written down. XOR-sum of written down integers is calculated, and this value is the answer for a query. Formally, if integers written down in point 2 are x1, x2, ..., xk, then Mishka wants to know the value , where — operator of exclusive bitwise OR. Since only the little bears know the definition of array beauty, all you are to do is to answer each of queries presented. | 256 megabytes | import java.io.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.StringTokenizer;
public class D703 {
private static int[] segmentTree;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
StringTokenizer st;
int n = Integer.parseInt(br.readLine());
int pow = (int) (Math.ceil(Math.log(n) / Math.log(2)) + 1.0);
segmentTree = new int[(int) Math.pow(2.0, pow)];
int[] num = new int[n];
int[] xor = new int[n + 1];
st = new StringTokenizer(br.readLine());
for (int i = 0; i < n; i++) {
num[i] = Integer.parseInt(st.nextToken());
xor[i + 1] = xor[i] ^ num[i];
}
int m = Integer.parseInt(br.readLine());
Query[] queries = new Query[m];
for (int i = 0; i < m; i++) {
st = new StringTokenizer(br.readLine());
queries[i] = new Query(
i,
Integer.parseInt(st.nextToken()),
Integer.parseInt(st.nextToken())
);
}
Arrays.sort(queries, (q1, q2) -> q1.r == q2.r ? q1.l - q2.l: q1.r - q2.r);
int[] ans = new int[m];
HashMap<Integer, Integer> previousOccurrence = new HashMap<>();
for (int i = 0, q = 0; i < n; i++) {
if (previousOccurrence.containsKey(num[i])) {
updateTree(previousOccurrence.get(num[i]), 0, 0, n - 1, 0);
}
previousOccurrence.put(num[i], i);
updateTree(i, num[i], 0, n - 1, 0);
while (q < m && queries[q].r == i + 1) {
int val = xor[queries[q].r] ^ xor[queries[q].l - 1];
val ^= queryTree(queries[q].l - 1, queries[q].r - 1, 0, n - 1, 0);
ans[queries[q].i] = val;
q++;
}
}
for (int i = 0; i < m; i++) {
out.println(ans[i]);
}
out.close();
}
private static int queryTree(int start, int end, int low, int high, int level) {
if (end < low || start > high) {
return 0;
}
if (start <= low && end >= high) {
return segmentTree[level];
}
int mid = (low + high) / 2;
int left = queryTree(start, end, low, mid, 2 * level + 1);
int right = queryTree(start, end, mid + 1, high, 2 * level + 2);
return left ^ right;
}
private static void updateTree(int pos, int num, int low, int high, int level) {
if (low == high) {
segmentTree[level] = num;
return;
}
int mid = (low + high) / 2;
if (pos >= low && pos <= mid) {
updateTree(pos, num, low, mid, 2 * level + 1);
}
if (pos > mid && pos <= high) {
updateTree(pos, num, mid + 1, high, 2 * level + 2);
}
segmentTree[level] = segmentTree[2 * level + 1] ^ segmentTree[2 * level + 2];
}
private static class Query {
int i;
int l;
int r;
Query(int i, int l, int r) {
this.i = i;
this.l = l;
this.r = r;
}
}
}
| Java | ["3\n3 7 8\n1\n1 3", "7\n1 2 1 3 3 2 3\n5\n4 7\n4 5\n1 3\n1 7\n1 5"] | 3.5 seconds | ["0", "0\n3\n1\n3\n2"] | NoteIn the second sample:There is no integers in the segment of the first query, presented even number of times in the segment — the answer is 0.In the second query there is only integer 3 is presented even number of times — the answer is 3.In the third query only integer 1 is written down — the answer is 1.In the fourth query all array elements are considered. Only 1 and 2 are presented there even number of times. The answer is .In the fifth query 1 and 3 are written down. The answer is . | Java 8 | standard input | [
"data structures"
] | 6fe09ae0980bbc59230290c7ac0bc7c3 | The first line of the input contains single integer n (1 ≤ n ≤ 1 000 000) — the number of elements in the array. The second line of the input contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — array elements. The third line of the input contains single integer m (1 ≤ m ≤ 1 000 000) — the number of queries. Each of the next m lines describes corresponding query by a pair of integers l and r (1 ≤ l ≤ r ≤ n) — the bounds of query segment. | 2,100 | Print m non-negative integers — the answers for the queries in the order they appear in the input. | standard output | |
PASSED | f1c2ffb2a6833fafd284b8831f598217 | train_003.jsonl | 1470323700 | Little Mishka enjoys programming. Since her birthday has just passed, her friends decided to present her with array of non-negative integers a1, a2, ..., an of n elements!Mishka loved the array and she instantly decided to determine its beauty value, but she is too little and can't process large arrays. Right because of that she invited you to visit her and asked you to process m queries.Each query is processed in the following way: Two integers l and r (1 ≤ l ≤ r ≤ n) are specified — bounds of query segment. Integers, presented in array segment [l, r] (in sequence of integers al, al + 1, ..., ar) even number of times, are written down. XOR-sum of written down integers is calculated, and this value is the answer for a query. Formally, if integers written down in point 2 are x1, x2, ..., xk, then Mishka wants to know the value , where — operator of exclusive bitwise OR. Since only the little bears know the definition of array beauty, all you are to do is to answer each of queries presented. | 256 megabytes | import static java.lang.Math.*;
import static java.util.Arrays.*;
import java.util.*;
import java.io.*;
public class Main {
void solve() {
int N = sc.nextInt();
int[] a = sc.nextIntArray(N);
int[] sum = new int[N+1];
for (int i = 0; i < N; i++) {
sum[i+1] = sum[i] ^ a[i];
}
int Q = sc.nextInt();
int[] ans = new int[Q];
Range[] qs = new Range[Q];
for (int q = 0; q < Q; q++) {
int l = sc.nextInt() - 1;
int r = sc.nextInt() - 1;
qs[q] = new Range(q, l, r);
}
a = normalize2(a);
sort(qs);
int qid = 0;
BIT bit = new BIT(N);
int[] last = new int[N];
fill(last, -1);
for (int i = 0; i < N; i++) {
if (last[a[i]] != -1) {
bit.add(last[a[i]], orgIndex[a[i]]);
}
last[a[i]] = i;
bit.add(i, orgIndex[a[i]]);
for (; qid < Q && qs[qid].b == i; qid++) {
Range q = qs[qid];
ans[q.id] = bit.range(q.a-1) ^ bit.range(q.b) ^ sum[q.a] ^ sum[q.b+1];
}
}
for (int i = 0; i < Q; i++)
out.println(ans[i]);
}
public class BIT {
int n;
int[] vs;
public BIT(int n) {
this.n = n;
vs = new int[n+1];
}
void add(int idx, int val) {
for (int x = idx + 1; x <= n; x += x & -x) vs[x] ^= val;
}
int range(int idx) {
int sum = 0;
for (int x = idx + 1; x > 0; x -= x & -x) sum ^= vs[x];
return sum;
}
}
int[] orgIndex;
public int[] normalize2(int[] v) {
int[] res = new int[v.length];
int[][] t = new int[v.length][2];
for (int i = 0; i < v.length; i++) {
t[i][0] = v[i];
t[i][1] = i;
}
Arrays.sort(t, 0, t.length, new Comparator<int[]>(){
public int compare(int[] a, int[] b){
if (a[0] != b[0]) return a[0] < b[0] ? -1 : 1;
return 0;
}
});
orgIndex = new int[v.length];
int r = 0;
for (int i = 0; i < v.length; i++) {
r += (i > 0 && t[i - 1][0] != t[i][0]) ? 1 : 0;
res[(int)t[i][1]] = r;
orgIndex[r] = t[i][0];
}
orgIndex = Arrays.copyOf(orgIndex, r+1);
return res;
}
static class Range implements Comparable<Range> {
int id;
int a, b;
Range(int id, int a, int b) {
this.id = id;
this.a = a;
this.b = b;
}
@Override
public int compareTo(Range o) {
return Integer.compare(b, o.b);
}
@Override
public String toString() {
return String.format("id=%d : [%d,%d);", id, a, b);
}
}
static void tr(Object... os) { System.err.println(deepToString(os)); }
static void tr(int[][] as) { for (int[] a : as) tr(a); }
void print(int[] a) {
if (a.length > 0) out.print(a[0]);
for (int i = 1; i < a.length; i++) out.print(" " + a[i]);
out.println();
}
public static void main(String[] args) throws Exception {
new Main().run();
}
MyScanner sc = null;
PrintWriter out = null;
public void run() throws Exception {
sc = new MyScanner(System.in);
out = new PrintWriter(System.out);
for (;sc.hasNext();) {
solve();
out.flush();
}
out.close();
}
class MyScanner {
String line;
BufferedReader reader;
StringTokenizer tokenizer;
public MyScanner(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public void eat() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
line = reader.readLine();
if (line == null) {
tokenizer = null;
return;
}
tokenizer = new StringTokenizer(line);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
public String next() {
eat();
return tokenizer.nextToken();
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public boolean hasNext() {
eat();
return (tokenizer != null && tokenizer.hasMoreElements());
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
}
} | Java | ["3\n3 7 8\n1\n1 3", "7\n1 2 1 3 3 2 3\n5\n4 7\n4 5\n1 3\n1 7\n1 5"] | 3.5 seconds | ["0", "0\n3\n1\n3\n2"] | NoteIn the second sample:There is no integers in the segment of the first query, presented even number of times in the segment — the answer is 0.In the second query there is only integer 3 is presented even number of times — the answer is 3.In the third query only integer 1 is written down — the answer is 1.In the fourth query all array elements are considered. Only 1 and 2 are presented there even number of times. The answer is .In the fifth query 1 and 3 are written down. The answer is . | Java 8 | standard input | [
"data structures"
] | 6fe09ae0980bbc59230290c7ac0bc7c3 | The first line of the input contains single integer n (1 ≤ n ≤ 1 000 000) — the number of elements in the array. The second line of the input contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — array elements. The third line of the input contains single integer m (1 ≤ m ≤ 1 000 000) — the number of queries. Each of the next m lines describes corresponding query by a pair of integers l and r (1 ≤ l ≤ r ≤ n) — the bounds of query segment. | 2,100 | Print m non-negative integers — the answers for the queries in the order they appear in the input. | standard output | |
PASSED | 40dd433c6e19793b7cdc16df14d81299 | train_003.jsonl | 1470323700 | Little Mishka enjoys programming. Since her birthday has just passed, her friends decided to present her with array of non-negative integers a1, a2, ..., an of n elements!Mishka loved the array and she instantly decided to determine its beauty value, but she is too little and can't process large arrays. Right because of that she invited you to visit her and asked you to process m queries.Each query is processed in the following way: Two integers l and r (1 ≤ l ≤ r ≤ n) are specified — bounds of query segment. Integers, presented in array segment [l, r] (in sequence of integers al, al + 1, ..., ar) even number of times, are written down. XOR-sum of written down integers is calculated, and this value is the answer for a query. Formally, if integers written down in point 2 are x1, x2, ..., xk, then Mishka wants to know the value , where — operator of exclusive bitwise OR. Since only the little bears know the definition of array beauty, all you are to do is to answer each of queries presented. | 256 megabytes | import java.io.IOException;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.InputMismatchException;
public class MishkaAndInterestingSum {
public static void main(String[] args) {
FasterScanner sc = new FasterScanner();
int N = sc.nextInt();
int[] A = sc.nextIntArray(N, 1);
int M = sc.nextInt();
Query[] Q = new Query[M];
for (int i = 0; i < M; i++) {
int L = sc.nextInt();
int R = sc.nextInt();
Q[i] = new Query(i, L, R);
}
int[] S = new int[N + 1];
for (int i = 1; i <= N; i++) {
S[i] = A[i] ^ S[i - 1];
}
Arrays.sort(Q, new Comparator<Query>() {
public int compare(Query q1, Query q2) {
return Integer.compare(q1.R, q2.R);
}
});
int q = 0;
int[] ans = new int[M];
HashMap<Integer, Integer> last = new HashMap<Integer, Integer>();
SegmentTree st = new SegmentTree(N + 1);
for (int i = 1; i <= N; i++) {
if (last.containsKey(A[i])) {
st.insert(last.get(A[i]), 0);
}
last.put(A[i], i);
st.insert(i, A[i]);
while (q < M && Q[q].R == i) {
int aXor = S[Q[q].R] ^ S[Q[q].L - 1];
int dXor = st.getRange(Q[q].L, Q[q].R);
ans[Q[q].index] = aXor ^ dXor;
q++;
}
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < M; i++) {
sb.append(ans[i] + "\n");
}
System.out.print(sb.toString());
}
public static class Query {
public int index;
public int L, R;
public Query(int idx, int left, int rite) {
this.index = idx;
this.L = left;
this.R = rite;
}
}
public static class SegmentTree {
public SegmentTreeNode[] leaves;
public SegmentTreeNode root;
public SegmentTree(int n) {
this.leaves = new SegmentTreeNode[n];
this.root = new SegmentTreeNode(this, null, 0, n - 1);
}
// modify the data-type of this segment tree
public SegmentTree(int[] vals) {
this(vals.length);
for (int i = 0; i < vals.length; i++) {
this.insert(i, vals[i]);
}
}
// modify the data-type of this segment tree
public void insert(int idx, int v) {
this.leaves[idx].setAndUpdate(v);
}
// modify the data-type of this segment tree
public int get(int idx) {
return this.leaves[idx].val;
}
// modify the data-type of this segment tree
public int getRange(int lower, int upper) {
return this.root.getRange(lower, upper);
}
private static class SegmentTreeNode {
public int L;
public int R;
// modify the data-type of this segment tree
public int val;
public SegmentTree tree;
public SegmentTreeNode parent;
public SegmentTreeNode left;
public SegmentTreeNode rite;
public SegmentTreeNode(SegmentTree t, SegmentTreeNode p, int lower, int upper) {
this.tree = t;
this.parent = p;
this.L = lower;
this.R = upper;
if (lower == upper) {
this.tree.leaves[lower] = this;
} else {
int mid = (lower + upper) / 2;
this.left = new SegmentTreeNode(tree, this, lower, mid);
this.rite = new SegmentTreeNode(tree, this, mid + 1, upper);
}
}
// modify the data-type of this segment tree
public void setAndUpdate(int v) {
this.val = v;
this.update();
}
// modify the function (i.e. max, min, sum, etc.) in this method
public void update() {
if (this.left != null && this.rite != null) {
this.val = this.left.val ^ this.rite.val;
} else if (this.left != null) {
this.val = this.left.val;
} else if (this.rite != null) {
this.val = this.rite.val;
}
if (this.parent != null) {
this.parent.update();
}
}
// modify the function & the default return value in this method
public int getRange(int lower, int upper) {
if (this.L >= lower && this.R <= upper) {
return this.val;
} else if (this.L > upper || this.R < lower) {
// modify the default value here (if it's not found)
return 0;
} else {
// modify the function that this Segment Tree uses
return this.left.getRange(lower, upper) ^ this.rite.getRange(lower, upper);
}
}
}
}
public static class FasterScanner {
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = System.in.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long 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 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 int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
public int[] nextIntArray(int n, int offset) {
int[] arr = new int[n + offset];
for (int i = 0; i < n; i++) {
arr[i + offset] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
public long[] nextLongArray(int n, int offset) {
long[] arr = new long[n + offset];
for (int i = 0; i < n; i++) {
arr[i + offset] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
} | Java | ["3\n3 7 8\n1\n1 3", "7\n1 2 1 3 3 2 3\n5\n4 7\n4 5\n1 3\n1 7\n1 5"] | 3.5 seconds | ["0", "0\n3\n1\n3\n2"] | NoteIn the second sample:There is no integers in the segment of the first query, presented even number of times in the segment — the answer is 0.In the second query there is only integer 3 is presented even number of times — the answer is 3.In the third query only integer 1 is written down — the answer is 1.In the fourth query all array elements are considered. Only 1 and 2 are presented there even number of times. The answer is .In the fifth query 1 and 3 are written down. The answer is . | Java 8 | standard input | [
"data structures"
] | 6fe09ae0980bbc59230290c7ac0bc7c3 | The first line of the input contains single integer n (1 ≤ n ≤ 1 000 000) — the number of elements in the array. The second line of the input contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — array elements. The third line of the input contains single integer m (1 ≤ m ≤ 1 000 000) — the number of queries. Each of the next m lines describes corresponding query by a pair of integers l and r (1 ≤ l ≤ r ≤ n) — the bounds of query segment. | 2,100 | Print m non-negative integers — the answers for the queries in the order they appear in the input. | standard output | |
PASSED | 82f32fc5d0f92155455acee454f09431 | train_003.jsonl | 1470323700 | Little Mishka enjoys programming. Since her birthday has just passed, her friends decided to present her with array of non-negative integers a1, a2, ..., an of n elements!Mishka loved the array and she instantly decided to determine its beauty value, but she is too little and can't process large arrays. Right because of that she invited you to visit her and asked you to process m queries.Each query is processed in the following way: Two integers l and r (1 ≤ l ≤ r ≤ n) are specified — bounds of query segment. Integers, presented in array segment [l, r] (in sequence of integers al, al + 1, ..., ar) even number of times, are written down. XOR-sum of written down integers is calculated, and this value is the answer for a query. Formally, if integers written down in point 2 are x1, x2, ..., xk, then Mishka wants to know the value , where — operator of exclusive bitwise OR. Since only the little bears know the definition of array beauty, all you are to do is to answer each of queries presented. | 256 megabytes | import java.io.IOException;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.InputMismatchException;
public class MishkaAndInterestingSum {
public static void main(String[] args) {
FasterScanner sc = new FasterScanner();
int N = sc.nextInt();
long[] A = sc.nextLongArray(N, 1);
int M = sc.nextInt();
Query[] Q = new Query[M];
for (int i = 0; i < M; i++) {
int L = sc.nextInt();
int R = sc.nextInt();
Q[i] = new Query(i, L, R);
}
long[] S = new long[N + 1];
for (int i = 1; i <= N; i++) {
S[i] = A[i] ^ S[i - 1];
}
Arrays.sort(Q, new Comparator<Query>() {
public int compare(Query q1, Query q2) {
return Integer.compare(q1.R, q2.R);
}
});
int q = 0;
long[] ans = new long[M];
HashMap<Long, Integer> last = new HashMap<Long, Integer>();
SegmentTree st = new SegmentTree(N + 1);
for (int i = 1; i <= N; i++) {
if (last.containsKey(A[i])) {
st.insert(last.get(A[i]), 0);
}
last.put(A[i], i);
st.insert(i, A[i]);
while (q < M && Q[q].R == i) {
long aXor = S[Q[q].R] ^ S[Q[q].L - 1];
long dXor = st.get(Q[q].L, Q[q].R);
ans[Q[q].index] = aXor ^ dXor;
q++;
}
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < M; i++) {
sb.append(ans[i] + "\n");
}
System.out.print(sb.toString());
}
public static class Query {
public int index;
public int L, R;
public Query(int idx, int left, int rite) {
this.index = idx;
this.L = left;
this.R = rite;
}
}
public static class SegmentTree {
public SegmentTreeNode[] leaves;
public SegmentTreeNode root;
public SegmentTree(int n) {
this.leaves = new SegmentTreeNode[n];
this.root = new SegmentTreeNode(this, null, 0, n - 1);
}
// modify the data-type of this segment tree
public SegmentTree(long[] vals) {
this(vals.length);
for (int i = 0; i < vals.length; i++) {
this.insert(i, vals[i]);
}
}
// modify the data-type of this segment tree
public void insert(int idx, long v) {
this.leaves[idx].setAndUpdate(v);
}
// modify the data-type of this segment tree
public long get(int idx) {
return this.leaves[idx].val;
}
// modify the data-type of this segment tree
public long get(int lower, int upper) {
return this.root.getRange(lower, upper);
}
private static class SegmentTreeNode {
public int L;
public int R;
// modify the data-type of this segment tree
public long val;
public SegmentTree tree;
public SegmentTreeNode parent;
public SegmentTreeNode left;
public SegmentTreeNode rite;
public SegmentTreeNode(SegmentTree t, SegmentTreeNode p, int lower, int upper) {
this.tree = t;
this.parent = p;
this.L = lower;
this.R = upper;
if (lower == upper) {
this.tree.leaves[lower] = this;
} else {
int mid = (lower + upper) / 2;
this.left = new SegmentTreeNode(tree, this, lower, mid);
this.rite = new SegmentTreeNode(tree, this, mid + 1, upper);
}
}
// modify the data-type of this segment tree
public void setAndUpdate(long v) {
this.val = v;
this.update();
}
// modify the function (i.e. max, min, sum, etc.) in this method
public void update() {
if (this.left != null && this.rite != null) {
this.val = this.left.val ^ this.rite.val;
} else if (this.left != null) {
this.val = this.left.val;
} else if (this.rite != null) {
this.val = this.rite.val;
}
if (this.parent != null) {
this.parent.update();
}
}
// modify the function & the default return value in this method
public long getRange(int lower, int upper) {
if (this.L >= lower && this.R <= upper) {
return this.val;
} else if (this.L > upper || this.R < lower) {
// modify the default value here (if it's not found)
return 0;
} else {
// modify the function that this Segment Tree uses
return this.left.getRange(lower, upper) ^ this.rite.getRange(lower, upper);
}
}
}
}
public static class FasterScanner {
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = System.in.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long 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 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 int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
public int[] nextIntArray(int n, int offset) {
int[] arr = new int[n + offset];
for (int i = 0; i < n; i++) {
arr[i + offset] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
public long[] nextLongArray(int n, int offset) {
long[] arr = new long[n + offset];
for (int i = 0; i < n; i++) {
arr[i + offset] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
} | Java | ["3\n3 7 8\n1\n1 3", "7\n1 2 1 3 3 2 3\n5\n4 7\n4 5\n1 3\n1 7\n1 5"] | 3.5 seconds | ["0", "0\n3\n1\n3\n2"] | NoteIn the second sample:There is no integers in the segment of the first query, presented even number of times in the segment — the answer is 0.In the second query there is only integer 3 is presented even number of times — the answer is 3.In the third query only integer 1 is written down — the answer is 1.In the fourth query all array elements are considered. Only 1 and 2 are presented there even number of times. The answer is .In the fifth query 1 and 3 are written down. The answer is . | Java 8 | standard input | [
"data structures"
] | 6fe09ae0980bbc59230290c7ac0bc7c3 | The first line of the input contains single integer n (1 ≤ n ≤ 1 000 000) — the number of elements in the array. The second line of the input contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — array elements. The third line of the input contains single integer m (1 ≤ m ≤ 1 000 000) — the number of queries. Each of the next m lines describes corresponding query by a pair of integers l and r (1 ≤ l ≤ r ≤ n) — the bounds of query segment. | 2,100 | Print m non-negative integers — the answers for the queries in the order they appear in the input. | standard output | |
PASSED | 56ce8326f2615a3efecb1666b0ccd1e6 | train_003.jsonl | 1470323700 | Little Mishka enjoys programming. Since her birthday has just passed, her friends decided to present her with array of non-negative integers a1, a2, ..., an of n elements!Mishka loved the array and she instantly decided to determine its beauty value, but she is too little and can't process large arrays. Right because of that she invited you to visit her and asked you to process m queries.Each query is processed in the following way: Two integers l and r (1 ≤ l ≤ r ≤ n) are specified — bounds of query segment. Integers, presented in array segment [l, r] (in sequence of integers al, al + 1, ..., ar) even number of times, are written down. XOR-sum of written down integers is calculated, and this value is the answer for a query. Formally, if integers written down in point 2 are x1, x2, ..., xk, then Mishka wants to know the value , where — operator of exclusive bitwise OR. Since only the little bears know the definition of array beauty, all you are to do is to answer each of queries presented. | 256 megabytes | import java.io.IOException;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.InputMismatchException;
public class MishkaAndInterestingSum {
public static void main(String[] args) {
FasterScanner sc = new FasterScanner();
int N = sc.nextInt();
int[] A = sc.nextIntArray(N, 1);
int M = sc.nextInt();
Query[] Q = new Query[M];
for (int i = 0; i < M; i++) {
int L = sc.nextInt();
int R = sc.nextInt();
Q[i] = new Query(i, L, R);
}
int[] S = new int[N + 1];
for (int i = 1; i <= N; i++) {
S[i] = A[i] ^ S[i - 1];
}
Arrays.sort(Q, new Comparator<Query>() {
public int compare(Query q1, Query q2) {
return Integer.compare(q1.R, q2.R);
}
});
int q = 0;
int[] ans = new int[M];
HashMap<Integer, Integer> last = new HashMap<Integer, Integer>();
FenwickTree ft = new FenwickTree(N + 1);
for (int i = 1; i <= N; i++) {
if (last.containsKey(A[i])) {
ft.change(last.get(A[i]), A[i]);
}
last.put(A[i], i);
ft.change(i, A[i]);
while (q < M && Q[q].R == i) {
int aXor = S[Q[q].R] ^ S[Q[q].L - 1];
int dXor = ft.queryRange(Q[q].L, Q[q].R);
ans[Q[q].index] = aXor ^ dXor;
q++;
}
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < M; i++) {
sb.append(ans[i] + "\n");
}
System.out.print(sb.toString());
}
public static class Query {
public int index;
public int L, R;
public Query(int idx, int left, int rite) {
this.index = idx;
this.L = left;
this.R = rite;
}
}
public static class FenwickTree {
int[] data;
public FenwickTree(int n) {
data = new int[n];
}
public void change(int i, int k) {
while (i < data.length) {
data[i] ^= k;
i += (i & -i);
}
}
public int query(int i) {
int ans = 0;
while (i > 0) {
ans ^= data[i];
i -= (i & -i);
}
return ans;
}
public int queryRange(int i, int j) {
return query(j) ^ query(i - 1);
}
}
public static class FasterScanner {
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = System.in.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long 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 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 int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
public int[] nextIntArray(int n, int offset) {
int[] arr = new int[n + offset];
for (int i = 0; i < n; i++) {
arr[i + offset] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
public long[] nextLongArray(int n, int offset) {
long[] arr = new long[n + offset];
for (int i = 0; i < n; i++) {
arr[i + offset] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
} | Java | ["3\n3 7 8\n1\n1 3", "7\n1 2 1 3 3 2 3\n5\n4 7\n4 5\n1 3\n1 7\n1 5"] | 3.5 seconds | ["0", "0\n3\n1\n3\n2"] | NoteIn the second sample:There is no integers in the segment of the first query, presented even number of times in the segment — the answer is 0.In the second query there is only integer 3 is presented even number of times — the answer is 3.In the third query only integer 1 is written down — the answer is 1.In the fourth query all array elements are considered. Only 1 and 2 are presented there even number of times. The answer is .In the fifth query 1 and 3 are written down. The answer is . | Java 8 | standard input | [
"data structures"
] | 6fe09ae0980bbc59230290c7ac0bc7c3 | The first line of the input contains single integer n (1 ≤ n ≤ 1 000 000) — the number of elements in the array. The second line of the input contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — array elements. The third line of the input contains single integer m (1 ≤ m ≤ 1 000 000) — the number of queries. Each of the next m lines describes corresponding query by a pair of integers l and r (1 ≤ l ≤ r ≤ n) — the bounds of query segment. | 2,100 | Print m non-negative integers — the answers for the queries in the order they appear in the input. | standard output | |
PASSED | 30b24a17cefcfaea7b2daee046444f0a | train_003.jsonl | 1470323700 | Little Mishka enjoys programming. Since her birthday has just passed, her friends decided to present her with array of non-negative integers a1, a2, ..., an of n elements!Mishka loved the array and she instantly decided to determine its beauty value, but she is too little and can't process large arrays. Right because of that she invited you to visit her and asked you to process m queries.Each query is processed in the following way: Two integers l and r (1 ≤ l ≤ r ≤ n) are specified — bounds of query segment. Integers, presented in array segment [l, r] (in sequence of integers al, al + 1, ..., ar) even number of times, are written down. XOR-sum of written down integers is calculated, and this value is the answer for a query. Formally, if integers written down in point 2 are x1, x2, ..., xk, then Mishka wants to know the value , where — operator of exclusive bitwise OR. Since only the little bears know the definition of array beauty, all you are to do is to answer each of queries presented. | 256 megabytes | import java.io.IOException;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.InputMismatchException;
public class MishkaAndInterestingSum {
public static void main(String[] args) {
FasterScanner sc = new FasterScanner();
int N = sc.nextInt();
long[] A = sc.nextLongArray(N, 1);
int M = sc.nextInt();
Query[] Q = new Query[M];
for (int i = 0; i < M; i++) {
int L = sc.nextInt();
int R = sc.nextInt();
Q[i] = new Query(i, L, R);
}
long[] S = new long[N + 1];
for (int i = 1; i <= N; i++) {
S[i] = A[i] ^ S[i - 1];
}
Arrays.sort(Q, new Comparator<Query>() {
public int compare(Query q1, Query q2) {
return Integer.compare(q1.R, q2.R);
}
});
int q = 0;
long[] ans = new long[M];
HashMap<Long, Integer> last = new HashMap<Long, Integer>();
SegmentTreeArray st = new SegmentTreeArray(findPow(N));
for (int i = 1; i <= N; i++) {
if (last.containsKey(A[i])) {
st.insert(last.get(A[i]), 0);
}
last.put(A[i], i);
st.insert(i, A[i]);
while (q < M && Q[q].R == i) {
long aXor = S[Q[q].R] ^ S[Q[q].L - 1];
long dXor = st.getRange(Q[q].L, Q[q].R);
ans[Q[q].index] = aXor ^ dXor;
q++;
}
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < M; i++) {
sb.append(ans[i] + "\n");
}
System.out.print(sb.toString());
}
public static int findPow(int val) {
int L = 0, R = 30;
int good = R;
while (L <= R) {
int M = (L + R) / 2;
if ((1 << M) > val) {
good = M;
R = M - 1;
} else {
L = M + 1;
}
}
return good;
}
public static class Query {
public int index;
public int L, R;
public Query(int idx, int left, int rite) {
this.index = idx;
this.L = left;
this.R = rite;
}
}
/**
* Implementation of Segment Tree based on perfect binary tree indexed on an array
*/
public static class SegmentTreeArray {
public int[] left;
public int[] rite;
public long[] values;
private final int LAYERS;
public SegmentTreeArray(int layers) {
int len = (1 << (layers + 1)) - 1;
left = new int[len];
rite = new int[len];
values = new long[len];
LAYERS = layers;
setLayer(0, 0, (1 << layers) - 1);
}
private void setLayer(int idx, int lower, int upper) {
this.left[idx] = lower;
this.rite[idx] = upper;
if (lower != upper) {
int mid = (lower + upper) / 2;
setLayer(getLeftChild(idx), lower, mid);
setLayer(getRiteChild(idx), mid + 1, upper);
}
}
public void insert(int idx, long val) {
int pos = getActualIdx(this.LAYERS, idx);
this.values[pos] = val;
if (idx > 0) {
this.update(getParentIdx(pos));
}
}
private void update(int idx) {
int idxL = getLeftChild(idx);
int idxR = getRiteChild(idx);
this.values[idx] = this.values[idxL] ^ this.values[idxR];
if (idx > 0) {
this.update(getParentIdx(idx));
}
}
public long get(int idx) {
int pos = getActualIdx(this.LAYERS, idx);
return this.values[pos];
}
public long getRange(int lower, int upper) {
return getRangeHelper(0, lower, upper);
}
private long getRangeHelper(int idx, int lower, int upper) {
if (this.left[idx] >= lower && this.rite[idx] <= upper) {
return this.values[idx];
} else if (this.left[idx] > upper || this.rite[idx] < lower) {
return 0;
} else {
return getRangeHelper(getLeftChild(idx), lower, upper) ^ getRangeHelper(getRiteChild(idx), lower, upper);
}
}
public static int getActualIdx(int layer, int idx) {
return (1 << layer) - 1 + idx;
}
private static int getParentIdx(int idx) {
return (idx - 1) / 2;
}
private static int getLeftChild(int idx) {
return 2 * idx + 1;
}
private static int getRiteChild(int idx) {
return 2 * idx + 2;
}
}
public static class FasterScanner {
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = System.in.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long 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 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 int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
public int[] nextIntArray(int n, int offset) {
int[] arr = new int[n + offset];
for (int i = 0; i < n; i++) {
arr[i + offset] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
public long[] nextLongArray(int n, int offset) {
long[] arr = new long[n + offset];
for (int i = 0; i < n; i++) {
arr[i + offset] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
} | Java | ["3\n3 7 8\n1\n1 3", "7\n1 2 1 3 3 2 3\n5\n4 7\n4 5\n1 3\n1 7\n1 5"] | 3.5 seconds | ["0", "0\n3\n1\n3\n2"] | NoteIn the second sample:There is no integers in the segment of the first query, presented even number of times in the segment — the answer is 0.In the second query there is only integer 3 is presented even number of times — the answer is 3.In the third query only integer 1 is written down — the answer is 1.In the fourth query all array elements are considered. Only 1 and 2 are presented there even number of times. The answer is .In the fifth query 1 and 3 are written down. The answer is . | Java 8 | standard input | [
"data structures"
] | 6fe09ae0980bbc59230290c7ac0bc7c3 | The first line of the input contains single integer n (1 ≤ n ≤ 1 000 000) — the number of elements in the array. The second line of the input contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — array elements. The third line of the input contains single integer m (1 ≤ m ≤ 1 000 000) — the number of queries. Each of the next m lines describes corresponding query by a pair of integers l and r (1 ≤ l ≤ r ≤ n) — the bounds of query segment. | 2,100 | Print m non-negative integers — the answers for the queries in the order they appear in the input. | standard output | |
PASSED | 738c45b690db64b8ce06ffb00402c997 | train_003.jsonl | 1470323700 | Little Mishka enjoys programming. Since her birthday has just passed, her friends decided to present her with array of non-negative integers a1, a2, ..., an of n elements!Mishka loved the array and she instantly decided to determine its beauty value, but she is too little and can't process large arrays. Right because of that she invited you to visit her and asked you to process m queries.Each query is processed in the following way: Two integers l and r (1 ≤ l ≤ r ≤ n) are specified — bounds of query segment. Integers, presented in array segment [l, r] (in sequence of integers al, al + 1, ..., ar) even number of times, are written down. XOR-sum of written down integers is calculated, and this value is the answer for a query. Formally, if integers written down in point 2 are x1, x2, ..., xk, then Mishka wants to know the value , where — operator of exclusive bitwise OR. Since only the little bears know the definition of array beauty, all you are to do is to answer each of queries presented. | 256 megabytes | import java.io.IOException;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.InputMismatchException;
public class MishkaAndInterestingSum {
public static void main(String[] args) {
FasterScanner sc = new FasterScanner();
int N = sc.nextInt();
int[] A = sc.nextIntArray(N, 1);
int M = sc.nextInt();
Query[] Q = new Query[M];
for (int i = 0; i < M; i++) {
int L = sc.nextInt();
int R = sc.nextInt();
Q[i] = new Query(i, L, R);
}
int[] S = new int[N + 1];
for (int i = 1; i <= N; i++) {
S[i] = A[i] ^ S[i - 1];
}
Arrays.sort(Q, new Comparator<Query>() {
public int compare(Query q1, Query q2) {
return Integer.compare(q1.R, q2.R);
}
});
int q = 0;
int[] ans = new int[M];
HashMap<Integer, Integer> last = new HashMap<Integer, Integer>();
SegmentTreeArray st = new SegmentTreeArray(findPow(N));
for (int i = 1; i <= N; i++) {
if (last.containsKey(A[i])) {
st.insert(last.get(A[i]), 0);
}
last.put(A[i], i);
st.insert(i, A[i]);
while (q < M && Q[q].R == i) {
int aXor = S[Q[q].R] ^ S[Q[q].L - 1];
int dXor = st.getRange(Q[q].L, Q[q].R);
ans[Q[q].index] = aXor ^ dXor;
q++;
}
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < M; i++) {
sb.append(ans[i] + "\n");
}
System.out.print(sb.toString());
}
public static int findPow(int val) {
int L = 0, R = 30;
int good = R;
while (L <= R) {
int M = (L + R) / 2;
if ((1 << M) > val) {
good = M;
R = M - 1;
} else {
L = M + 1;
}
}
return good;
}
public static class Query {
public int index;
public int L, R;
public Query(int idx, int left, int rite) {
this.index = idx;
this.L = left;
this.R = rite;
}
}
/**
* Implementation of Segment Tree based on perfect binary tree indexed on an array
*/
public static class SegmentTreeArray {
public int[] left;
public int[] rite;
public int[] values;
private final int LAYERS;
public SegmentTreeArray(int layers) {
int len = (1 << (layers + 1)) - 1;
left = new int[len];
rite = new int[len];
values = new int[len];
LAYERS = layers;
setLayer(0, 0, (1 << layers) - 1);
}
private void setLayer(int idx, int lower, int upper) {
this.left[idx] = lower;
this.rite[idx] = upper;
if (lower != upper) {
int mid = (lower + upper) / 2;
setLayer(getLeftChild(idx), lower, mid);
setLayer(getRiteChild(idx), mid + 1, upper);
}
}
public void insert(int idx, int val) {
int pos = getActualIdx(this.LAYERS, idx);
this.values[pos] = val;
if (idx > 0) {
this.update(getParentIdx(pos));
}
}
private void update(int idx) {
int idxL = getLeftChild(idx);
int idxR = getRiteChild(idx);
this.values[idx] = this.values[idxL] ^ this.values[idxR];
if (idx > 0) {
this.update(getParentIdx(idx));
}
}
public int get(int idx) {
int pos = getActualIdx(this.LAYERS, idx);
return this.values[pos];
}
public int getRange(int lower, int upper) {
return getRangeHelper(0, lower, upper);
}
private int getRangeHelper(int idx, int lower, int upper) {
if (this.left[idx] >= lower && this.rite[idx] <= upper) {
return this.values[idx];
} else if (this.left[idx] > upper || this.rite[idx] < lower) {
return 0;
} else {
return getRangeHelper(getLeftChild(idx), lower, upper) ^ getRangeHelper(getRiteChild(idx), lower, upper);
}
}
public static int getActualIdx(int layer, int idx) {
return (1 << layer) - 1 + idx;
}
private static int getParentIdx(int idx) {
return (idx - 1) / 2;
}
private static int getLeftChild(int idx) {
return 2 * idx + 1;
}
private static int getRiteChild(int idx) {
return 2 * idx + 2;
}
}
public static class FasterScanner {
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = System.in.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long 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 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 int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
public int[] nextIntArray(int n, int offset) {
int[] arr = new int[n + offset];
for (int i = 0; i < n; i++) {
arr[i + offset] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
public long[] nextLongArray(int n, int offset) {
long[] arr = new long[n + offset];
for (int i = 0; i < n; i++) {
arr[i + offset] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
} | Java | ["3\n3 7 8\n1\n1 3", "7\n1 2 1 3 3 2 3\n5\n4 7\n4 5\n1 3\n1 7\n1 5"] | 3.5 seconds | ["0", "0\n3\n1\n3\n2"] | NoteIn the second sample:There is no integers in the segment of the first query, presented even number of times in the segment — the answer is 0.In the second query there is only integer 3 is presented even number of times — the answer is 3.In the third query only integer 1 is written down — the answer is 1.In the fourth query all array elements are considered. Only 1 and 2 are presented there even number of times. The answer is .In the fifth query 1 and 3 are written down. The answer is . | Java 8 | standard input | [
"data structures"
] | 6fe09ae0980bbc59230290c7ac0bc7c3 | The first line of the input contains single integer n (1 ≤ n ≤ 1 000 000) — the number of elements in the array. The second line of the input contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — array elements. The third line of the input contains single integer m (1 ≤ m ≤ 1 000 000) — the number of queries. Each of the next m lines describes corresponding query by a pair of integers l and r (1 ≤ l ≤ r ≤ n) — the bounds of query segment. | 2,100 | Print m non-negative integers — the answers for the queries in the order they appear in the input. | standard output | |
PASSED | a68306f3709128802b45496c4be4bfd9 | train_003.jsonl | 1470323700 | Little Mishka enjoys programming. Since her birthday has just passed, her friends decided to present her with array of non-negative integers a1, a2, ..., an of n elements!Mishka loved the array and she instantly decided to determine its beauty value, but she is too little and can't process large arrays. Right because of that she invited you to visit her and asked you to process m queries.Each query is processed in the following way: Two integers l and r (1 ≤ l ≤ r ≤ n) are specified — bounds of query segment. Integers, presented in array segment [l, r] (in sequence of integers al, al + 1, ..., ar) even number of times, are written down. XOR-sum of written down integers is calculated, and this value is the answer for a query. Formally, if integers written down in point 2 are x1, x2, ..., xk, then Mishka wants to know the value , where — operator of exclusive bitwise OR. Since only the little bears know the definition of array beauty, all you are to do is to answer each of queries presented. | 256 megabytes | import java.io.*;
import java.util.*;
import java.util.stream.IntStream;
/**
* 703D
*/
public class MishkaSum {
// static class Profiler {
// List<String> mLabels = new ArrayList<>();
// List<Long> mTime = new ArrayList<>();
//
// String current;
// long started;
//
// void start(String what) {
// stop();
// current = what;
// started = System.nanoTime();
// }
//
// void stop() {
// if (current == null) {
// return;
// }
// long now = System.nanoTime();
// mLabels.add(current);
// mTime.add((now - started) / 1000000);
// current = null;
// }
//
// void dump() {
// stop();
// for (int i = 0; i < mLabels.size(); i++) {
// System.err.println(mLabels.get(i) + ": " + mTime.get(i));
// }
// }
// }
static class GovnoHash {
private final static int N = 7785571;
private final static int R = -1;
private static final int STEP = 1;
int keys[] = new int[N];
int values[] = new int[N];
void put(int key, int value) {
int idx = key % N;
while (keys[idx] != 0 && keys[idx] != key && keys[idx] != R) {
idx = (idx + STEP) % N;
}
keys[idx] = key;
values[idx] = value;
}
int get(int key) {
int idx = key % N;
while (keys[idx] != key && keys[idx] != 0) {
idx = (idx + STEP) % N;
}
return keys[idx] == key ? values[idx] : -1;
}
}
static class SegTree {
final int st[];
final int a[];
int n;
SegTree(int n) {
this.n = n;
this.a = new int[n];
this.st = new int[Integer.highestOneBit(n - 1) * 2];
}
void update(int pos, int val) {
update(pos, val ^ a[pos], 0, 0, n - 1);
a[pos] = val;
}
private void update(int pos, int delta, int i, int l, int r) {
if (l < r) {
st[i] ^= delta;
int b = (l + r) / 2;
if (pos <= b) {
update(pos, delta, i * 2 + 1, l, b);
} else {
update(pos, delta, i * 2 + 2, b+1, r);
}
}
}
int query(int from, int to) {
return query(from, to, 0, 0, n - 1);
}
private int query(int from, int to, int i, int l, int r) {
if (l == r) {
return a[l];
}
if (l >= from && r <= to) {
return st[i];
}
int b = (l + r) / 2;
int res = 0;
if (from <= b) {
res ^= query(from, to, 2*i + 1, l, b);
}
if (to >= b+1) {
res ^= query(from, to, 2*i + 2, b+1, r);
}
return res;
}
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader(InputStream stream) {
br = new BufferedReader(new
InputStreamReader(stream));
}
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());
}
}
public static void main(String args[]) {
int n;
//Profiler p = new Profiler();
//p.start("input");
FastReader sc = new FastReader(System.in);
n = sc.nextInt();
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
int nq = sc.nextInt();
int f[] = new int[nq];
int t[] = new int[nq];
int qRes[] = new int[nq];
for (int i = 0; i < nq; i++) {
f[i] = sc.nextInt() - 1;
t[i] = sc.nextInt() - 1;
}
//p.start("sort");
int q[] = IntStream.range(0, nq)
.boxed()
.sorted(Comparator.comparingInt(l -> t[l]))
.mapToInt(x -> x)
.toArray();
//p.start("xor");
int partXor[] = new int[n];
partXor[0] = a[0];
for (int i = 1; i < n; i++) {
partXor[i] = partXor[i - 1] ^ a[i];
}
//p.start("main run");
SegTree st = new SegTree(n);
//HashMap<Integer, Integer> last = new HashMap<>();
GovnoHash last = new GovnoHash();
int qPos = 0;
for (int i = 0; i < n; i++) {
int prev = last.get(a[i]); //getOrDefault(a[i], -1);
if (prev >= 0) {
st.update(prev, 0);
}
st.update(i, a[i]);
last.put(a[i], i);
while (qPos < nq && t[q[qPos]] < i) {
qPos++;
}
while (qPos < nq && t[q[qPos]] == i) {
int qi = q[qPos];
int uniq = st.query(f[qi], t[qi]);
int total = partXor[t[qi]] ^ (f[qi] > 0 ? partXor[f[qi] - 1] : 0);
qRes[qi] = uniq ^ total;
qPos++;
}
}
//p.start("output");
try (OutputStream out = new BufferedOutputStream(System.out)) {
byte nl[] = "\n".getBytes();
for (int i = 0; i < nq; i++) {
out.write(String.valueOf(qRes[i]).getBytes());
out.write(nl);
}
// System.out.println(qRes[i]);
} catch (IOException e) {
e.printStackTrace();
}
//p.dump();
}
}
| Java | ["3\n3 7 8\n1\n1 3", "7\n1 2 1 3 3 2 3\n5\n4 7\n4 5\n1 3\n1 7\n1 5"] | 3.5 seconds | ["0", "0\n3\n1\n3\n2"] | NoteIn the second sample:There is no integers in the segment of the first query, presented even number of times in the segment — the answer is 0.In the second query there is only integer 3 is presented even number of times — the answer is 3.In the third query only integer 1 is written down — the answer is 1.In the fourth query all array elements are considered. Only 1 and 2 are presented there even number of times. The answer is .In the fifth query 1 and 3 are written down. The answer is . | Java 8 | standard input | [
"data structures"
] | 6fe09ae0980bbc59230290c7ac0bc7c3 | The first line of the input contains single integer n (1 ≤ n ≤ 1 000 000) — the number of elements in the array. The second line of the input contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — array elements. The third line of the input contains single integer m (1 ≤ m ≤ 1 000 000) — the number of queries. Each of the next m lines describes corresponding query by a pair of integers l and r (1 ≤ l ≤ r ≤ n) — the bounds of query segment. | 2,100 | Print m non-negative integers — the answers for the queries in the order they appear in the input. | standard output | |
PASSED | 0f988a247687eab236809cd50cd4c645 | train_003.jsonl | 1470323700 | Little Mishka enjoys programming. Since her birthday has just passed, her friends decided to present her with array of non-negative integers a1, a2, ..., an of n elements!Mishka loved the array and she instantly decided to determine its beauty value, but she is too little and can't process large arrays. Right because of that she invited you to visit her and asked you to process m queries.Each query is processed in the following way: Two integers l and r (1 ≤ l ≤ r ≤ n) are specified — bounds of query segment. Integers, presented in array segment [l, r] (in sequence of integers al, al + 1, ..., ar) even number of times, are written down. XOR-sum of written down integers is calculated, and this value is the answer for a query. Formally, if integers written down in point 2 are x1, x2, ..., xk, then Mishka wants to know the value , where — operator of exclusive bitwise OR. Since only the little bears know the definition of array beauty, all you are to do is to answer each of queries presented. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class Main {
void solve() throws IOException {
int n = ni();
int[] a = nia(n);
int m = ni();
Pair[] p = new Pair[m];
for (int i = 0; i < m; i++) {
int l = ni() - 1;
int r = ni() - 1;
p[i] = new Pair(i, l, r);
}
Arrays.sort(p);
int[] sum = new int[n + 1];
for (int i = 1; i <= n; i++) {
sum[i] = sum[i - 1] ^ a[i - 1];
}
int[] ans = new int[m];
int idx = 0;
HashMap<Integer, Integer> map = new HashMap<>();
BIT bit = new BIT(n);
for (int i = 0; i < m; i++) {
while (idx <= p[i].y) {
if (map.containsKey(a[idx])) {
bit.add(map.get(a[idx]), a[idx]);
}
bit.add(idx + 1, a[idx]);
map.put(a[idx], idx + 1);
idx++;
}
int tmp = sum[p[i].y + 1] ^ sum[p[i].x];
tmp ^= bit.sum(p[i].y + 1);
if (p[i].x > 0) tmp ^= bit.sum(p[i].x);
ans[p[i].i] = tmp;
}
for (int i = 0; i < m; i++) {
out.println(ans[i]);
}
}
public class Pair implements Comparable<Pair> {
int i, x, y;
Pair(int i, int x, int y) {
this.i = i;
this.x = x;
this.y = y;
}
public int compareTo(Pair p) {
return y - p.y;
}
}
class BIT {
int n;
int[] bit;
BIT(int n) {
this.n = n;
bit = new int[n + 1];
}
int sum(int i) {
int s = 0;
while (i > 0) {
s ^= bit[i];
i -= i & -i;
}
return s;
}
void add(int i, int x) {
while (i <= n) {
bit[i] ^= x;
i += i & -i;
}
}
}
String ns() throws IOException {
while (!tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine(), " ");
}
return tok.nextToken();
}
int ni() throws IOException {
return Integer.parseInt(ns());
}
long nl() throws IOException {
return Long.parseLong(ns());
}
double nd() throws IOException {
return Double.parseDouble(ns());
}
String[] nsa(int n) throws IOException {
String[] res = new String[n];
for (int i = 0; i < n; i++) {
res[i] = ns();
}
return res;
}
int[] nia(int n) throws IOException {
int[] res = new int[n];
for (int i = 0; i < n; i++) {
res[i] = ni();
}
return res;
}
long[] nla(int n) throws IOException {
long[] res = new long[n];
for (int i = 0; i < n; i++) {
res[i] = nl();
}
return res;
}
static BufferedReader in;
static PrintWriter out;
static StringTokenizer tok;
public static void main(String[] args) throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
tok = new StringTokenizer("");
Main main = new Main();
main.solve();
out.close();
}
} | Java | ["3\n3 7 8\n1\n1 3", "7\n1 2 1 3 3 2 3\n5\n4 7\n4 5\n1 3\n1 7\n1 5"] | 3.5 seconds | ["0", "0\n3\n1\n3\n2"] | NoteIn the second sample:There is no integers in the segment of the first query, presented even number of times in the segment — the answer is 0.In the second query there is only integer 3 is presented even number of times — the answer is 3.In the third query only integer 1 is written down — the answer is 1.In the fourth query all array elements are considered. Only 1 and 2 are presented there even number of times. The answer is .In the fifth query 1 and 3 are written down. The answer is . | Java 8 | standard input | [
"data structures"
] | 6fe09ae0980bbc59230290c7ac0bc7c3 | The first line of the input contains single integer n (1 ≤ n ≤ 1 000 000) — the number of elements in the array. The second line of the input contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — array elements. The third line of the input contains single integer m (1 ≤ m ≤ 1 000 000) — the number of queries. Each of the next m lines describes corresponding query by a pair of integers l and r (1 ≤ l ≤ r ≤ n) — the bounds of query segment. | 2,100 | Print m non-negative integers — the answers for the queries in the order they appear in the input. | standard output | |
PASSED | 593096b1c3864901b94702c0613e92af | train_003.jsonl | 1470323700 | Little Mishka enjoys programming. Since her birthday has just passed, her friends decided to present her with array of non-negative integers a1, a2, ..., an of n elements!Mishka loved the array and she instantly decided to determine its beauty value, but she is too little and can't process large arrays. Right because of that she invited you to visit her and asked you to process m queries.Each query is processed in the following way: Two integers l and r (1 ≤ l ≤ r ≤ n) are specified — bounds of query segment. Integers, presented in array segment [l, r] (in sequence of integers al, al + 1, ..., ar) even number of times, are written down. XOR-sum of written down integers is calculated, and this value is the answer for a query. Formally, if integers written down in point 2 are x1, x2, ..., xk, then Mishka wants to know the value , where — operator of exclusive bitwise OR. Since only the little bears know the definition of array beauty, all you are to do is to answer each of queries presented. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Task.solve(in, out);
out.close();
}
private static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
}
private static class Task {
private static class Query implements Comparable<Query> {
int x, y;
int initialPos;
Query(int x, int y, int i) {
this.x = x;
this.y = y;
this.initialPos = i;
}
@Override
public int compareTo(Query second) {
int temp = y - second.y;
if (temp == 0)
return x - second.x;
return y - second.y;
}
@Override
public String toString() {
return x + " " + y;
}
}
private static Query[] queries;
private static int[] elem;
private static int[] aib;
private static int[] xorSum;
private static int[] answers;
private static Map<Integer, Integer> map = new HashMap<>();
private static int lsb(int x) {
return x & (-x);
}
private static void update(int pos, int val) {
for (int i = pos; i < aib.length; i += lsb(i)) {
aib[i] ^= val;
}
}
private static int sum(int pos) {
int sum = 0;
for (int i = pos; i > 0; i -= lsb(i)) {
sum ^= aib[i];
}
return sum;
}
static void solve(InputReader in, PrintWriter out) {
int n = in.nextInt();
elem = new int[n + 1];
aib = new int[n + 1];
xorSum = new int[n + 1];
for (int i = 1; i <= n; i++) {
elem[i] = in.nextInt();
xorSum[i] = xorSum[i - 1] ^ elem[i];
}
int m = in.nextInt();
queries = new Query[m];
answers = new int[m];
for (int i = 0; i < m; i++) {
int x = in.nextInt();
int y = in.nextInt();
queries[i] = new Query(x, y, i);
}
Arrays.sort(queries);
for (int i = 0, last = 0; i < queries.length; i++) {
int y = queries[i].y;
int x = queries[i].x;
while (last < y) {
last++;
Integer old = map.get(elem[last]);
if (old != null) {
update(old, elem[last]);
}
update(last, elem[last]);
map.put(elem[last], last);
}
answers[queries[i].initialPos] = xorSum[y] ^ xorSum[x - 1] ^ sum(y) ^ sum(x - 1);
}
for (int answer : answers) {
out.println(answer);
}
}
}
}
| Java | ["3\n3 7 8\n1\n1 3", "7\n1 2 1 3 3 2 3\n5\n4 7\n4 5\n1 3\n1 7\n1 5"] | 3.5 seconds | ["0", "0\n3\n1\n3\n2"] | NoteIn the second sample:There is no integers in the segment of the first query, presented even number of times in the segment — the answer is 0.In the second query there is only integer 3 is presented even number of times — the answer is 3.In the third query only integer 1 is written down — the answer is 1.In the fourth query all array elements are considered. Only 1 and 2 are presented there even number of times. The answer is .In the fifth query 1 and 3 are written down. The answer is . | Java 8 | standard input | [
"data structures"
] | 6fe09ae0980bbc59230290c7ac0bc7c3 | The first line of the input contains single integer n (1 ≤ n ≤ 1 000 000) — the number of elements in the array. The second line of the input contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — array elements. The third line of the input contains single integer m (1 ≤ m ≤ 1 000 000) — the number of queries. Each of the next m lines describes corresponding query by a pair of integers l and r (1 ≤ l ≤ r ≤ n) — the bounds of query segment. | 2,100 | Print m non-negative integers — the answers for the queries in the order they appear in the input. | standard output | |
PASSED | 14405bb7a1e91335228ca68add8b1f04 | train_003.jsonl | 1470323700 | Little Mishka enjoys programming. Since her birthday has just passed, her friends decided to present her with array of non-negative integers a1, a2, ..., an of n elements!Mishka loved the array and she instantly decided to determine its beauty value, but she is too little and can't process large arrays. Right because of that she invited you to visit her and asked you to process m queries.Each query is processed in the following way: Two integers l and r (1 ≤ l ≤ r ≤ n) are specified — bounds of query segment. Integers, presented in array segment [l, r] (in sequence of integers al, al + 1, ..., ar) even number of times, are written down. XOR-sum of written down integers is calculated, and this value is the answer for a query. Formally, if integers written down in point 2 are x1, x2, ..., xk, then Mishka wants to know the value , where — operator of exclusive bitwise OR. Since only the little bears know the definition of array beauty, all you are to do is to answer each of queries presented. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Task.solve(in, out);
out.close();
}
private static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
}
private static class Task {
private static class Query implements Comparable<Query> {
int x, y;
int initialPos;
Query(int x, int y, int i) {
this.x = x;
this.y = y;
this.initialPos = i;
}
@Override
public int compareTo(Query second) {
return y - second.y;
}
@Override
public String toString() {
return x + " " + y;
}
}
private static Query[] queries;
private static int[] elem;
private static int[] aib;
private static int[] xorSum;
private static int[] answers;
private static Map<Integer, Integer> map = new HashMap<>();
private static int lsb(int x) {
return x & (-x);
}
private static void update(int pos, int val) {
for (int i = pos; i < aib.length; i += lsb(i)) {
aib[i] ^= val;
}
}
private static int sum(int pos) {
int sum = 0;
for (int i = pos; i > 0; i -= lsb(i)) {
sum ^= aib[i];
}
return sum;
}
static void solve(InputReader in, PrintWriter out) {
int n = in.nextInt();
elem = new int[n + 1];
aib = new int[n + 1];
xorSum = new int[n + 1];
for (int i = 1; i <= n; i++) {
elem[i] = in.nextInt();
xorSum[i] = xorSum[i - 1] ^ elem[i];
}
int m = in.nextInt();
queries = new Query[m];
answers = new int[m];
for (int i = 0; i < m; i++) {
int x = in.nextInt();
int y = in.nextInt();
queries[i] = new Query(x, y, i);
}
Arrays.sort(queries);
for (int i = 0, last = 0; i < queries.length; i++) {
int y = queries[i].y;
int x = queries[i].x;
while (last < y) {
last++;
Integer old = map.get(elem[last]);
if (old != null) {
update(old, elem[last]);
}
update(last, elem[last]);
map.put(elem[last], last);
}
answers[queries[i].initialPos] = xorSum[y] ^ xorSum[x - 1] ^ sum(y) ^ sum(x - 1);
}
for (int answer : answers) {
out.println(answer);
}
}
}
}
| Java | ["3\n3 7 8\n1\n1 3", "7\n1 2 1 3 3 2 3\n5\n4 7\n4 5\n1 3\n1 7\n1 5"] | 3.5 seconds | ["0", "0\n3\n1\n3\n2"] | NoteIn the second sample:There is no integers in the segment of the first query, presented even number of times in the segment — the answer is 0.In the second query there is only integer 3 is presented even number of times — the answer is 3.In the third query only integer 1 is written down — the answer is 1.In the fourth query all array elements are considered. Only 1 and 2 are presented there even number of times. The answer is .In the fifth query 1 and 3 are written down. The answer is . | Java 8 | standard input | [
"data structures"
] | 6fe09ae0980bbc59230290c7ac0bc7c3 | The first line of the input contains single integer n (1 ≤ n ≤ 1 000 000) — the number of elements in the array. The second line of the input contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — array elements. The third line of the input contains single integer m (1 ≤ m ≤ 1 000 000) — the number of queries. Each of the next m lines describes corresponding query by a pair of integers l and r (1 ≤ l ≤ r ≤ n) — the bounds of query segment. | 2,100 | Print m non-negative integers — the answers for the queries in the order they appear in the input. | standard output | |
PASSED | 16b589a37e212d9f3e780cfa5d109ab3 | train_003.jsonl | 1470323700 | Little Mishka enjoys programming. Since her birthday has just passed, her friends decided to present her with array of non-negative integers a1, a2, ..., an of n elements!Mishka loved the array and she instantly decided to determine its beauty value, but she is too little and can't process large arrays. Right because of that she invited you to visit her and asked you to process m queries.Each query is processed in the following way: Two integers l and r (1 ≤ l ≤ r ≤ n) are specified — bounds of query segment. Integers, presented in array segment [l, r] (in sequence of integers al, al + 1, ..., ar) even number of times, are written down. XOR-sum of written down integers is calculated, and this value is the answer for a query. Formally, if integers written down in point 2 are x1, x2, ..., xk, then Mishka wants to know the value , where — operator of exclusive bitwise OR. Since only the little bears know the definition of array beauty, all you are to do is to answer each of queries presented. | 256 megabytes | import java.awt.*;
import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.List;
import static java.lang.Math.max;
import static java.lang.Math.min;
public class ProblemD implements Runnable{
private final static Random rnd = new Random();
// SOLUTION!!!
// HACK ME PLEASE IF YOU CAN!!!
// PLEASE!!!
// PLEASE!!!
// PLEASE!!!
private void solve() {
int n = readInt();
int[] array = readIntArray(n);
int[] prefXors = new int[n + 1];
for (int i = 0; i < n; ++i) {
prefXors[i + 1] = (prefXors[i] ^ array[i]);
}
int[] next = new int[n];
Map<Integer, Integer> leftestIndexes = new HashMap<>();
for (int index = n - 1; index >= 0; --index) {
int value = array[index];
Integer nextIndex = leftestIndexes.get(value);
if (null == nextIndex) {
nextIndex = -1;
}
next[index] = nextIndex;
leftestIndexes.put(value, index);
}
FenwickTree tree = new FenwickTree(n);
for (Map.Entry<Integer, Integer> leftestEntries : leftestIndexes.entrySet()) {
tree.update(leftestEntries.getValue(), leftestEntries.getKey());
}
final int queriesCount = readInt();
List<Point>[] queries = new List[n];
for (int index = 0; index < n; ++index) {
queries[index] = new ArrayList<>();
}
for (int queryIndex = 0; queryIndex < queriesCount; ++queryIndex) {
int left = readInt() - 1;
int right = readInt() - 1;
queries[left].add(new Point(right, queryIndex));
}
int[] answers = new int[queriesCount];
for (int left = 0; left < n; ++left) {
if (left > 0) {
int removed = array[left - 1];
tree.update(left - 1, removed);
int nextIndex = next[left - 1];
if (-1 != nextIndex) {
tree.update(nextIndex, removed);
}
}
for (Point query : queries[left]) {
int right = query.x;
int queryIndex = query.y;
int totalXor = (prefXors[right + 1] ^ prefXors[left]);
int uniqueXor = tree.get(right);
answers[queryIndex] = (totalXor ^ uniqueXor);
}
}
for (int answer : answers) {
out.println(answer);
}
}
private static class FenwickTree {
int[] tree;
FenwickTree(int size) {
this.tree = new int[size];
}
int get(int right) {
int xor = 0;
for (int index = right; index >= 0; index &= (index + 1), --index) {
xor ^= tree[index];
}
return xor;
}
void update(int index, int delta) {
for (int cur = index; cur < tree.length; cur |= (cur + 1)) {
tree[cur] ^= delta;
}
}
}
/////////////////////////////////////////////////////////////////////
private final static boolean FIRST_INPUT_STRING = false;
private final static boolean MULTIPLE_TESTS = true;
private final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
private final static int MAX_STACK_SIZE = 128;
/////////////////////////////////////////////////////////////////////
public void run(){
try{
timeBegin = System.currentTimeMillis();
Locale.setDefault(Locale.US);
init();
if (ONLINE_JUDGE) {
solve();
} else {
do {
try {
solve();
out.println();
} catch (NumberFormatException e) {
break;
} catch (NullPointerException e) {
if (FIRST_INPUT_STRING) break;
else throw e;
}
} while (MULTIPLE_TESTS);
}
out.close();
time();
}catch (Exception e){
e.printStackTrace(System.err);
System.exit(-1);
}
}
/////////////////////////////////////////////////////////////////////
private BufferedReader in;
private OutputWriter out;
private StringTokenizer tok = new StringTokenizer("");
public static void main(String[] args){
new Thread(null, new ProblemD(), "", MAX_STACK_SIZE * (1L << 20)).start();
}
/////////////////////////////////////////////////////////////////////
private void init() throws FileNotFoundException{
Locale.setDefault(Locale.US);
if (ONLINE_JUDGE){
in = new BufferedReader(new InputStreamReader(System.in));
out = new OutputWriter(System.out);
}else{
in = new BufferedReader(new FileReader("input.txt"));
out = new OutputWriter("output.txt");
}
}
////////////////////////////////////////////////////////////////
private long timeBegin;
private void time(){
long timeEnd = System.currentTimeMillis();
System.err.println("Time = " + (timeEnd - timeBegin));
}
private void debug(Object... objects){
if (ONLINE_JUDGE){
for (Object o: objects){
System.err.println(o.toString());
}
}
}
/////////////////////////////////////////////////////////////////////
private String delim = " ";
private String readLine() {
try {
return in.readLine();
} catch (IOException e) {
throw new RuntimeIOException(e);
}
}
private String readString() {
try {
while(!tok.hasMoreTokens()){
tok = new StringTokenizer(readLine());
}
return tok.nextToken(delim);
} catch (NullPointerException e) {
return null;
}
}
/////////////////////////////////////////////////////////////////
private final char NOT_A_SYMBOL = '\0';
private char readChar() {
try {
int intValue = in.read();
if (intValue == -1){
return NOT_A_SYMBOL;
}
return (char) intValue;
} catch (IOException e) {
throw new RuntimeIOException(e);
}
}
private char[] readCharArray() {
return readLine().toCharArray();
}
private char[][] readCharField(int rowsCount) {
char[][] field = new char[rowsCount][];
for (int row = 0; row < rowsCount; ++row) {
field[row] = readCharArray();
}
return field;
}
/////////////////////////////////////////////////////////////////
private int readInt() {
return Integer.parseInt(readString());
}
private int[] readIntArray(int size) {
int[] array = new int[size];
for (int index = 0; index < size; ++index){
array[index] = readInt();
}
return array;
}
private int[] readSortedIntArray(int size) {
Integer[] array = new Integer[size];
for (int index = 0; index < size; ++index) {
array[index] = readInt();
}
Arrays.sort(array);
int[] sortedArray = new int[size];
for (int index = 0; index < size; ++index) {
sortedArray[index] = array[index];
}
return sortedArray;
}
private int[] readIntArrayWithDecrease(int size) {
int[] array = readIntArray(size);
for (int i = 0; i < size; ++i) {
array[i]--;
}
return array;
}
///////////////////////////////////////////////////////////////////
private int[][] readIntMatrix(int rowsCount, int columnsCount) {
int[][] matrix = new int[rowsCount][];
for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) {
matrix[rowIndex] = readIntArray(columnsCount);
}
return matrix;
}
private int[][] readIntMatrixWithDecrease(int rowsCount, int columnsCount) {
int[][] matrix = new int[rowsCount][];
for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) {
matrix[rowIndex] = readIntArrayWithDecrease(columnsCount);
}
return matrix;
}
///////////////////////////////////////////////////////////////////
private long readLong() {
return Long.parseLong(readString());
}
private long[] readLongArray(int size) {
long[] array = new long[size];
for (int index = 0; index < size; ++index){
array[index] = readLong();
}
return array;
}
////////////////////////////////////////////////////////////////////
private double readDouble() {
return Double.parseDouble(readString());
}
private double[] readDoubleArray(int size) {
double[] array = new double[size];
for (int index = 0; index < size; ++index){
array[index] = readDouble();
}
return array;
}
////////////////////////////////////////////////////////////////////
private BigInteger readBigInteger() {
return new BigInteger(readString());
}
private BigDecimal readBigDecimal() {
return new BigDecimal(readString());
}
/////////////////////////////////////////////////////////////////////
private Point readPoint() {
int x = readInt();
int y = readInt();
return new Point(x, y);
}
private Point[] readPointArray(int size) {
Point[] array = new Point[size];
for (int index = 0; index < size; ++index){
array[index] = readPoint();
}
return array;
}
/////////////////////////////////////////////////////////////////////
private List<Integer>[] readGraph(int vertexNumber, int edgeNumber) {
@SuppressWarnings("unchecked")
List<Integer>[] graph = new List[vertexNumber];
for (int index = 0; index < vertexNumber; ++index){
graph[index] = new ArrayList<Integer>();
}
while (edgeNumber-- > 0){
int from = readInt() - 1;
int to = readInt() - 1;
graph[from].add(to);
graph[to].add(from);
}
return graph;
}
/////////////////////////////////////////////////////////////////////
private static class IntIndexPair {
static Comparator<IntIndexPair> increaseComparator = new Comparator<ProblemD.IntIndexPair>() {
@Override
public int compare(ProblemD.IntIndexPair indexPair1, ProblemD.IntIndexPair indexPair2) {
int value1 = indexPair1.value;
int value2 = indexPair2.value;
if (value1 != value2) return value1 - value2;
int index1 = indexPair1.index;
int index2 = indexPair2.index;
return index1 - index2;
}
};
static Comparator<IntIndexPair> decreaseComparator = new Comparator<ProblemD.IntIndexPair>() {
@Override
public int compare(ProblemD.IntIndexPair indexPair1, ProblemD.IntIndexPair indexPair2) {
int value1 = indexPair1.value;
int value2 = indexPair2.value;
if (value1 != value2) return -(value1 - value2);
int index1 = indexPair1.index;
int index2 = indexPair2.index;
return index1 - index2;
}
};
int value, index;
IntIndexPair(int value, int index) {
super();
this.value = value;
this.index = index;
}
int getRealIndex() {
return index + 1;
}
}
private IntIndexPair[] readIntIndexArray(int size) {
IntIndexPair[] array = new IntIndexPair[size];
for (int index = 0; index < size; ++index) {
array[index] = new IntIndexPair(readInt(), index);
}
return array;
}
/////////////////////////////////////////////////////////////////////
private static class OutputWriter extends PrintWriter {
final int DEFAULT_PRECISION = 12;
private int precision;
private String format, formatWithSpace;
{
precision = DEFAULT_PRECISION;
format = createFormat(precision);
formatWithSpace = format + " ";
}
OutputWriter(OutputStream out) {
super(out);
}
OutputWriter(String fileName) throws FileNotFoundException {
super(fileName);
}
int getPrecision() {
return precision;
}
void setPrecision(int precision) {
precision = max(0, precision);
this.precision = precision;
format = createFormat(precision);
formatWithSpace = format + " ";
}
String createFormat(int precision){
return "%." + precision + "f";
}
@Override
public void print(double d){
printf(format, d);
}
void printWithSpace(double d){
printf(formatWithSpace, d);
}
void printAll(double...d){
for (int i = 0; i < d.length - 1; ++i){
printWithSpace(d[i]);
}
print(d[d.length - 1]);
}
@Override
public void println(double d){
printlnAll(d);
}
void printlnAll(double... d){
printAll(d);
println();
}
}
/////////////////////////////////////////////////////////////////////
private static class RuntimeIOException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = -6463830523020118289L;
RuntimeIOException(Throwable cause) {
super(cause);
}
}
/////////////////////////////////////////////////////////////////////
//////////////// Some useful constants and functions ////////////////
/////////////////////////////////////////////////////////////////////
private static final int[][] steps = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
private static final int[][] steps8 = {
{-1, 0}, {1, 0}, {0, -1}, {0, 1},
{-1, -1}, {1, 1}, {1, -1}, {-1, 1}
};
private static boolean checkCell(int row, int rowsCount, int column, int columnsCount) {
return checkIndex(row, rowsCount) && checkIndex(column, columnsCount);
}
private static boolean checkIndex(int index, int lim){
return (0 <= index && index < lim);
}
/////////////////////////////////////////////////////////////////////
private static boolean checkBit(int mask, int bit){
return (mask & (1 << bit)) != 0;
}
/////////////////////////////////////////////////////////////////////
private static long getSum(int[] array) {
long sum = 0;
for (int value: array) {
sum += value;
}
return sum;
}
private static Point getMinMax(int[] array) {
int min = array[0];
int max = array[0];
for (int index = 0, size = array.length; index < size; ++index, ++index) {
int value = array[index];
if (index == size - 1) {
min = min(min, value);
max = max(max, value);
} else {
int otherValue = array[index + 1];
if (value <= otherValue) {
min = min(min, value);
max = max(max, otherValue);
} else {
min = min(min, otherValue);
max = max(max, value);
}
}
}
return new Point(min, max);
}
/////////////////////////////////////////////////////////////////////
private static int[] getPrimes(int n) {
boolean[] used = new boolean[n];
used[0] = used[1] = true;
int size = 0;
for (int i = 2; i < n; ++i) {
if (!used[i]) {
++size;
for (int j = 2 * i; j < n; j += i) {
used[j] = true;
}
}
}
int[] primes = new int[size];
for (int i = 0, cur = 0; i < n; ++i) {
if (!used[i]) {
primes[cur++] = i;
}
}
return primes;
}
/////////////////////////////////////////////////////////////////////
private static long lcm(long a, long b) {
return a / gcd(a, b) * b;
}
private static long gcd(long a, long b) {
return (a == 0 ? b : gcd(b % a, a));
}
/////////////////////////////////////////////////////////////////////
private static class IdMap<KeyType> extends HashMap<KeyType, Integer> {
/**
*
*/
private static final long serialVersionUID = -3793737771950984481L;
public IdMap() {
super();
}
int getId(KeyType key) {
Integer id = super.get(key);
if (id == null) {
super.put(key, id = size());
}
return id;
}
}
}
| Java | ["3\n3 7 8\n1\n1 3", "7\n1 2 1 3 3 2 3\n5\n4 7\n4 5\n1 3\n1 7\n1 5"] | 3.5 seconds | ["0", "0\n3\n1\n3\n2"] | NoteIn the second sample:There is no integers in the segment of the first query, presented even number of times in the segment — the answer is 0.In the second query there is only integer 3 is presented even number of times — the answer is 3.In the third query only integer 1 is written down — the answer is 1.In the fourth query all array elements are considered. Only 1 and 2 are presented there even number of times. The answer is .In the fifth query 1 and 3 are written down. The answer is . | Java 8 | standard input | [
"data structures"
] | 6fe09ae0980bbc59230290c7ac0bc7c3 | The first line of the input contains single integer n (1 ≤ n ≤ 1 000 000) — the number of elements in the array. The second line of the input contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — array elements. The third line of the input contains single integer m (1 ≤ m ≤ 1 000 000) — the number of queries. Each of the next m lines describes corresponding query by a pair of integers l and r (1 ≤ l ≤ r ≤ n) — the bounds of query segment. | 2,100 | Print m non-negative integers — the answers for the queries in the order they appear in the input. | standard output | |
PASSED | 0f030f3fff33f0561af2a4457aff605f | train_003.jsonl | 1470323700 | Little Mishka enjoys programming. Since her birthday has just passed, her friends decided to present her with array of non-negative integers a1, a2, ..., an of n elements!Mishka loved the array and she instantly decided to determine its beauty value, but she is too little and can't process large arrays. Right because of that she invited you to visit her and asked you to process m queries.Each query is processed in the following way: Two integers l and r (1 ≤ l ≤ r ≤ n) are specified — bounds of query segment. Integers, presented in array segment [l, r] (in sequence of integers al, al + 1, ..., ar) even number of times, are written down. XOR-sum of written down integers is calculated, and this value is the answer for a query. Formally, if integers written down in point 2 are x1, x2, ..., xk, then Mishka wants to know the value , where — operator of exclusive bitwise OR. Since only the little bears know the definition of array beauty, all you are to do is to answer each of queries presented. | 256 megabytes | import java.awt.*;
import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.List;
import static java.lang.Math.max;
import static java.lang.Math.min;
public class ProblemD implements Runnable{
private final static Random rnd = new Random();
// SOLUTION!!!
// HACK ME PLEASE IF YOU CAN!!!
// PLEASE!!!
// PLEASE!!!
// PLEASE!!!
private void solve() {
int n = readInt();
int[] array = readIntArray(n);
final int queriesCount = readInt();
class Query {
int left, right, index;
public Query(int left, int right, int index) {
this.left = left;
this.right = right;
this.index = index;
}
}
Query[] queries = new Query[queriesCount];
for (int queryIndex = 0; queryIndex < queriesCount; ++queryIndex) {
int left = readInt() - 1;
int right = readInt() - 1;
queries[queryIndex] = new Query(left, right, queryIndex);
}
Arrays.sort(queries, Comparator.comparingInt(a -> a.right));
int[] prefXors = new int[n + 1];
for (int i = 0; i < n; ++i) {
prefXors[i + 1] = (prefXors[i] ^ array[i]);
}
Map<Integer, Integer> lasts = new HashMap<>();
FenwickTree tree = new FenwickTree(n);
int[] answers = new int[queriesCount];
for (int right = 0, queryIndex = 0; right < n; ++right) {
int value = array[right];
int last = lasts.getOrDefault(value, -1);
if (last >= 0) {
tree.update(last, value);
}
tree.update(right, value);
lasts.put(value, right);
for (; queryIndex < queriesCount && queries[queryIndex].right == right;
++queryIndex) {
Query query = queries[queryIndex];
int left = query.left, index = query.index;
int segmentXor = prefXors[right + 1] ^ prefXors[left];
int uniqueXor = tree.get(left, right);
answers[index] = segmentXor ^ uniqueXor;
}
}
for (int answer : answers) {
out.println(answer);
}
}
private static class FenwickTree {
int size;
int[] tree;
FenwickTree(int n) {
this.size = n + 1;
this.tree = new int[size];
}
int get(int start, int end) {
return get(end) ^ get(start - 1);
}
int get(int index) {
++index;
int xor = 0;
for (; index > 0; index -= index & -index) {
xor ^= tree[index];
}
return xor;
}
void update(int index, int delta) {
++index;
for (; index < tree.length; index += index & -index) {
tree[index] ^= delta;
}
}
}
/////////////////////////////////////////////////////////////////////
private final static boolean FIRST_INPUT_STRING = false;
private final static boolean MULTIPLE_TESTS = true;
private final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
private final static boolean OPTIMIZE_READ_NUMBERS = false;
private final static int MAX_STACK_SIZE = 128;
/////////////////////////////////////////////////////////////////////
public void run(){
try{
timeBegin = System.currentTimeMillis();
Locale.setDefault(Locale.US);
init();
if (ONLINE_JUDGE) {
solve();
} else {
do {
try {
solve();
out.println();
out.flush();
} catch (NumberFormatException e) {
break;
} catch (NullPointerException e) {
if (FIRST_INPUT_STRING) break;
else throw e;
}
} while (MULTIPLE_TESTS);
}
out.close();
time();
}catch (Exception e){
e.printStackTrace(System.err);
System.exit(-1);
}
}
/////////////////////////////////////////////////////////////////////
private BufferedReader in;
private OutputWriter out;
private StringTokenizer tok = new StringTokenizer("");
public static void main(String[] args){
new Thread(null, new ProblemD(), "", MAX_STACK_SIZE * (1L << 20)).start();
}
/////////////////////////////////////////////////////////////////////
private void init() throws FileNotFoundException{
Locale.setDefault(Locale.US);
if (ONLINE_JUDGE){
in = new BufferedReader(new InputStreamReader(System.in));
out = new OutputWriter(System.out);
}else{
in = new BufferedReader(new FileReader("input.txt"));
out = new OutputWriter("output.txt");
}
}
////////////////////////////////////////////////////////////////
private long timeBegin;
private void time(){
long timeEnd = System.currentTimeMillis();
System.err.println("Time = " + (timeEnd - timeBegin));
}
private void debug(Object... objects){
if (ONLINE_JUDGE){
for (Object o: objects){
System.err.println(o.toString());
}
}
}
/////////////////////////////////////////////////////////////////////
private String delim = " ";
private String readLine() {
try {
return in.readLine();
} catch (IOException e) {
throw new RuntimeIOException(e);
}
}
private String readString() {
try {
while(!tok.hasMoreTokens()){
tok = new StringTokenizer(readLine());
}
return tok.nextToken(delim);
} catch (NullPointerException e) {
return null;
}
}
/////////////////////////////////////////////////////////////////
private final char NOT_A_SYMBOL = '\0';
private char readChar() {
try {
int intValue = in.read();
if (intValue == -1){
return NOT_A_SYMBOL;
}
return (char) intValue;
} catch (IOException e) {
throw new RuntimeIOException(e);
}
}
private char[] readCharArray() {
return readLine().toCharArray();
}
private char[][] readCharField(int rowsCount) {
char[][] field = new char[rowsCount][];
for (int row = 0; row < rowsCount; ++row) {
field[row] = readCharArray();
}
return field;
}
/////////////////////////////////////////////////////////////////
private int readInt() {
if (!OPTIMIZE_READ_NUMBERS) {
return Integer.parseInt(readString());
} else {
return (int) optimizedReadLong();
}
}
private long optimizedReadLong() {
int sign = 1;
long result = 0;
boolean started = false;
while (true) {
try {
int j = in.read();
if (-1 == j) {
if (started) return sign * result;
throw new NumberFormatException();
}
if (j == '-') {
if (started) throw new NumberFormatException();
sign = -sign;
}
if ('0' <= j && j <= '9') {
result = result * 10 + j - '0';
started = true;
} else if (started) {
return sign * result;
}
} catch (IOException e) {
throw new RuntimeIOException(e);
}
}
}
private int[] readIntArray(int size) {
int[] array = new int[size];
for (int index = 0; index < size; ++index){
array[index] = readInt();
}
return array;
}
private int[] readSortedIntArray(int size) {
Integer[] array = new Integer[size];
for (int index = 0; index < size; ++index) {
array[index] = readInt();
}
Arrays.sort(array);
int[] sortedArray = new int[size];
for (int index = 0; index < size; ++index) {
sortedArray[index] = array[index];
}
return sortedArray;
}
private int[] readIntArrayWithDecrease(int size) {
int[] array = readIntArray(size);
for (int i = 0; i < size; ++i) {
array[i]--;
}
return array;
}
///////////////////////////////////////////////////////////////////
private int[][] readIntMatrix(int rowsCount, int columnsCount) {
int[][] matrix = new int[rowsCount][];
for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) {
matrix[rowIndex] = readIntArray(columnsCount);
}
return matrix;
}
private int[][] readIntMatrixWithDecrease(int rowsCount, int columnsCount) {
int[][] matrix = new int[rowsCount][];
for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) {
matrix[rowIndex] = readIntArrayWithDecrease(columnsCount);
}
return matrix;
}
///////////////////////////////////////////////////////////////////
private long readLong() {
return Long.parseLong(readString());
}
private long[] readLongArray(int size) {
long[] array = new long[size];
for (int index = 0; index < size; ++index){
array[index] = readLong();
}
return array;
}
////////////////////////////////////////////////////////////////////
private double readDouble() {
return Double.parseDouble(readString());
}
private double[] readDoubleArray(int size) {
double[] array = new double[size];
for (int index = 0; index < size; ++index){
array[index] = readDouble();
}
return array;
}
////////////////////////////////////////////////////////////////////
private BigInteger readBigInteger() {
return new BigInteger(readString());
}
private BigDecimal readBigDecimal() {
return new BigDecimal(readString());
}
/////////////////////////////////////////////////////////////////////
private Point readPoint() {
int x = readInt();
int y = readInt();
return new Point(x, y);
}
private Point[] readPointArray(int size) {
Point[] array = new Point[size];
for (int index = 0; index < size; ++index){
array[index] = readPoint();
}
return array;
}
/////////////////////////////////////////////////////////////////////
private List<Integer>[] readGraph(int vertexNumber, int edgeNumber) {
@SuppressWarnings("unchecked")
List<Integer>[] graph = new List[vertexNumber];
for (int index = 0; index < vertexNumber; ++index){
graph[index] = new ArrayList<Integer>();
}
while (edgeNumber-- > 0){
int from = readInt() - 1;
int to = readInt() - 1;
graph[from].add(to);
graph[to].add(from);
}
return graph;
}
/////////////////////////////////////////////////////////////////////
private static class IntIndexPair {
static Comparator<IntIndexPair> increaseComparator = new Comparator<ProblemD.IntIndexPair>() {
@Override
public int compare(ProblemD.IntIndexPair indexPair1, ProblemD.IntIndexPair indexPair2) {
int value1 = indexPair1.value;
int value2 = indexPair2.value;
if (value1 != value2) return value1 - value2;
int index1 = indexPair1.index;
int index2 = indexPair2.index;
return index1 - index2;
}
};
static Comparator<IntIndexPair> decreaseComparator = new Comparator<ProblemD.IntIndexPair>() {
@Override
public int compare(ProblemD.IntIndexPair indexPair1, ProblemD.IntIndexPair indexPair2) {
int value1 = indexPair1.value;
int value2 = indexPair2.value;
if (value1 != value2) return -(value1 - value2);
int index1 = indexPair1.index;
int index2 = indexPair2.index;
return index1 - index2;
}
};
int value, index;
IntIndexPair(int value, int index) {
super();
this.value = value;
this.index = index;
}
int getRealIndex() {
return index + 1;
}
}
private IntIndexPair[] readIntIndexArray(int size) {
IntIndexPair[] array = new IntIndexPair[size];
for (int index = 0; index < size; ++index) {
array[index] = new IntIndexPair(readInt(), index);
}
return array;
}
/////////////////////////////////////////////////////////////////////
private static class OutputWriter extends PrintWriter {
final int DEFAULT_PRECISION = 12;
private int precision;
private String format, formatWithSpace;
{
precision = DEFAULT_PRECISION;
format = createFormat(precision);
formatWithSpace = format + " ";
}
OutputWriter(OutputStream out) {
super(out);
}
OutputWriter(String fileName) throws FileNotFoundException {
super(fileName);
}
int getPrecision() {
return precision;
}
void setPrecision(int precision) {
precision = max(0, precision);
this.precision = precision;
format = createFormat(precision);
formatWithSpace = format + " ";
}
String createFormat(int precision){
return "%." + precision + "f";
}
@Override
public void print(double d){
printf(format, d);
}
void printWithSpace(double d){
printf(formatWithSpace, d);
}
void printAll(double...d){
for (int i = 0; i < d.length - 1; ++i){
printWithSpace(d[i]);
}
print(d[d.length - 1]);
}
@Override
public void println(double d){
printlnAll(d);
}
void printlnAll(double... d){
printAll(d);
println();
}
}
/////////////////////////////////////////////////////////////////////
private static class RuntimeIOException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = -6463830523020118289L;
RuntimeIOException(Throwable cause) {
super(cause);
}
}
/////////////////////////////////////////////////////////////////////
//////////////// Some useful constants and functions ////////////////
/////////////////////////////////////////////////////////////////////
private static final int[][] steps = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
private static final int[][] steps8 = {
{-1, 0}, {1, 0}, {0, -1}, {0, 1},
{-1, -1}, {1, 1}, {1, -1}, {-1, 1}
};
private static boolean checkCell(int row, int rowsCount, int column, int columnsCount) {
return checkIndex(row, rowsCount) && checkIndex(column, columnsCount);
}
private static boolean checkIndex(int index, int lim){
return (0 <= index && index < lim);
}
/////////////////////////////////////////////////////////////////////
private static boolean checkBit(int mask, int bit){
return (mask & (1 << bit)) != 0;
}
/////////////////////////////////////////////////////////////////////
private static long getSum(int[] array) {
long sum = 0;
for (int value: array) {
sum += value;
}
return sum;
}
private static Point getMinMax(int[] array) {
int min = array[0];
int max = array[0];
for (int index = 0, size = array.length; index < size; ++index, ++index) {
int value = array[index];
if (index == size - 1) {
min = min(min, value);
max = max(max, value);
} else {
int otherValue = array[index + 1];
if (value <= otherValue) {
min = min(min, value);
max = max(max, otherValue);
} else {
min = min(min, otherValue);
max = max(max, value);
}
}
}
return new Point(min, max);
}
/////////////////////////////////////////////////////////////////////
private static int[] getPrimes(int n) {
boolean[] used = new boolean[n];
used[0] = used[1] = true;
int size = 0;
for (int i = 2; i < n; ++i) {
if (!used[i]) {
++size;
for (int j = 2 * i; j < n; j += i) {
used[j] = true;
}
}
}
int[] primes = new int[size];
for (int i = 0, cur = 0; i < n; ++i) {
if (!used[i]) {
primes[cur++] = i;
}
}
return primes;
}
/////////////////////////////////////////////////////////////////////
private static long lcm(long a, long b) {
return a / gcd(a, b) * b;
}
private static long gcd(long a, long b) {
return (a == 0 ? b : gcd(b % a, a));
}
/////////////////////////////////////////////////////////////////////
private static class IdMap<KeyType> extends HashMap<KeyType, Integer> {
/**
*
*/
private static final long serialVersionUID = -3793737771950984481L;
public IdMap() {
super();
}
int getId(KeyType key) {
Integer id = super.get(key);
if (id == null) {
super.put(key, id = size());
}
return id;
}
}
} | Java | ["3\n3 7 8\n1\n1 3", "7\n1 2 1 3 3 2 3\n5\n4 7\n4 5\n1 3\n1 7\n1 5"] | 3.5 seconds | ["0", "0\n3\n1\n3\n2"] | NoteIn the second sample:There is no integers in the segment of the first query, presented even number of times in the segment — the answer is 0.In the second query there is only integer 3 is presented even number of times — the answer is 3.In the third query only integer 1 is written down — the answer is 1.In the fourth query all array elements are considered. Only 1 and 2 are presented there even number of times. The answer is .In the fifth query 1 and 3 are written down. The answer is . | Java 8 | standard input | [
"data structures"
] | 6fe09ae0980bbc59230290c7ac0bc7c3 | The first line of the input contains single integer n (1 ≤ n ≤ 1 000 000) — the number of elements in the array. The second line of the input contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — array elements. The third line of the input contains single integer m (1 ≤ m ≤ 1 000 000) — the number of queries. Each of the next m lines describes corresponding query by a pair of integers l and r (1 ≤ l ≤ r ≤ n) — the bounds of query segment. | 2,100 | Print m non-negative integers — the answers for the queries in the order they appear in the input. | standard output | |
PASSED | 7c6d3e8e9b6b025d35dbe9aa9f8c8101 | train_003.jsonl | 1470323700 | Little Mishka enjoys programming. Since her birthday has just passed, her friends decided to present her with array of non-negative integers a1, a2, ..., an of n elements!Mishka loved the array and she instantly decided to determine its beauty value, but she is too little and can't process large arrays. Right because of that she invited you to visit her and asked you to process m queries.Each query is processed in the following way: Two integers l and r (1 ≤ l ≤ r ≤ n) are specified — bounds of query segment. Integers, presented in array segment [l, r] (in sequence of integers al, al + 1, ..., ar) even number of times, are written down. XOR-sum of written down integers is calculated, and this value is the answer for a query. Formally, if integers written down in point 2 are x1, x2, ..., xk, then Mishka wants to know the value , where — operator of exclusive bitwise OR. Since only the little bears know the definition of array beauty, all you are to do is to answer each of queries presented. | 256 megabytes | import java.awt.*;
import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.List;
import static java.lang.Math.max;
import static java.lang.Math.min;
public class ProblemD implements Runnable{
private final static Random rnd = new Random();
// SOLUTION!!!
// HACK ME PLEASE IF YOU CAN!!!
// PLEASE!!!
// PLEASE!!!
// PLEASE!!!
private void solve() {
int n = readInt();
int[] array = readIntArray(n);
final int queriesCount = readInt();
List<Point>[] queries = new List[n];
for (int index = 0; index < n; ++index) {
queries[index] = new ArrayList<>(0);
}
for (int queryIndex = 0; queryIndex < queriesCount; ++queryIndex) {
int left = readInt() - 1;
int right = readInt() - 1;
queries[right].add(new Point(left, queryIndex));
}
int[] prefXors = new int[n + 1];
for (int i = 0; i < n; ++i) {
prefXors[i + 1] = (prefXors[i] ^ array[i]);
}
Map<Integer, Integer> lasts = new HashMap<>();
FenwickTree tree = new FenwickTree(n);
int[] answers = new int[queriesCount];
for (int right = 0; right < n; ++right) {
int value = array[right];
int last = lasts.getOrDefault(value, -1);
if (last >= 0) {
tree.update(last, value);
}
tree.update(right, value);
lasts.put(value, right);
for (Point query : queries[right]) {
int left = query.x, index = query.y;
int segmentXor = prefXors[right + 1] ^ prefXors[left];
int uniqueXor = tree.get(left, right);
answers[index] = segmentXor ^ uniqueXor;
}
}
for (int answer : answers) {
out.println(answer);
}
}
private static class FenwickTree {
int size;
int[] tree;
FenwickTree(int n) {
this.size = n + 1;
this.tree = new int[size];
}
int get(int start, int end) {
return get(end) ^ get(start - 1);
}
int get(int index) {
++index;
int xor = 0;
for (; index > 0; index -= index & -index) {
xor ^= tree[index];
}
return xor;
}
void update(int index, int delta) {
++index;
for (; index < tree.length; index += index & -index) {
tree[index] ^= delta;
}
}
}
/////////////////////////////////////////////////////////////////////
private final static boolean FIRST_INPUT_STRING = false;
private final static boolean MULTIPLE_TESTS = true;
private final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
private final static boolean OPTIMIZE_READ_NUMBERS = false;
private final static int MAX_STACK_SIZE = 128;
/////////////////////////////////////////////////////////////////////
public void run(){
try{
timeBegin = System.currentTimeMillis();
Locale.setDefault(Locale.US);
init();
if (ONLINE_JUDGE) {
solve();
} else {
do {
try {
solve();
out.println();
out.flush();
} catch (NumberFormatException e) {
break;
} catch (NullPointerException e) {
if (FIRST_INPUT_STRING) break;
else throw e;
}
} while (MULTIPLE_TESTS);
}
out.close();
time();
}catch (Exception e){
e.printStackTrace(System.err);
System.exit(-1);
}
}
/////////////////////////////////////////////////////////////////////
private BufferedReader in;
private OutputWriter out;
private StringTokenizer tok = new StringTokenizer("");
public static void main(String[] args){
new Thread(null, new ProblemD(), "", MAX_STACK_SIZE * (1L << 20)).start();
}
/////////////////////////////////////////////////////////////////////
private void init() throws FileNotFoundException{
Locale.setDefault(Locale.US);
if (ONLINE_JUDGE){
in = new BufferedReader(new InputStreamReader(System.in));
out = new OutputWriter(System.out);
}else{
in = new BufferedReader(new FileReader("input.txt"));
out = new OutputWriter("output.txt");
}
}
////////////////////////////////////////////////////////////////
private long timeBegin;
private void time(){
long timeEnd = System.currentTimeMillis();
System.err.println("Time = " + (timeEnd - timeBegin));
}
private void debug(Object... objects){
if (ONLINE_JUDGE){
for (Object o: objects){
System.err.println(o.toString());
}
}
}
/////////////////////////////////////////////////////////////////////
private String delim = " ";
private String readLine() {
try {
return in.readLine();
} catch (IOException e) {
throw new RuntimeIOException(e);
}
}
private String readString() {
try {
while(!tok.hasMoreTokens()){
tok = new StringTokenizer(readLine());
}
return tok.nextToken(delim);
} catch (NullPointerException e) {
return null;
}
}
/////////////////////////////////////////////////////////////////
private final char NOT_A_SYMBOL = '\0';
private char readChar() {
try {
int intValue = in.read();
if (intValue == -1){
return NOT_A_SYMBOL;
}
return (char) intValue;
} catch (IOException e) {
throw new RuntimeIOException(e);
}
}
private char[] readCharArray() {
return readLine().toCharArray();
}
private char[][] readCharField(int rowsCount) {
char[][] field = new char[rowsCount][];
for (int row = 0; row < rowsCount; ++row) {
field[row] = readCharArray();
}
return field;
}
/////////////////////////////////////////////////////////////////
private int readInt() {
if (!OPTIMIZE_READ_NUMBERS) {
return Integer.parseInt(readString());
} else {
return (int) optimizedReadLong();
}
}
private long optimizedReadLong() {
int sign = 1;
long result = 0;
boolean started = false;
while (true) {
try {
int j = in.read();
if (-1 == j) {
if (started) return sign * result;
throw new NumberFormatException();
}
if (j == '-') {
if (started) throw new NumberFormatException();
sign = -sign;
}
if ('0' <= j && j <= '9') {
result = result * 10 + j - '0';
started = true;
} else if (started) {
return sign * result;
}
} catch (IOException e) {
throw new RuntimeIOException(e);
}
}
}
private int[] readIntArray(int size) {
int[] array = new int[size];
for (int index = 0; index < size; ++index){
array[index] = readInt();
}
return array;
}
private int[] readSortedIntArray(int size) {
Integer[] array = new Integer[size];
for (int index = 0; index < size; ++index) {
array[index] = readInt();
}
Arrays.sort(array);
int[] sortedArray = new int[size];
for (int index = 0; index < size; ++index) {
sortedArray[index] = array[index];
}
return sortedArray;
}
private int[] readIntArrayWithDecrease(int size) {
int[] array = readIntArray(size);
for (int i = 0; i < size; ++i) {
array[i]--;
}
return array;
}
///////////////////////////////////////////////////////////////////
private int[][] readIntMatrix(int rowsCount, int columnsCount) {
int[][] matrix = new int[rowsCount][];
for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) {
matrix[rowIndex] = readIntArray(columnsCount);
}
return matrix;
}
private int[][] readIntMatrixWithDecrease(int rowsCount, int columnsCount) {
int[][] matrix = new int[rowsCount][];
for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) {
matrix[rowIndex] = readIntArrayWithDecrease(columnsCount);
}
return matrix;
}
///////////////////////////////////////////////////////////////////
private long readLong() {
return Long.parseLong(readString());
}
private long[] readLongArray(int size) {
long[] array = new long[size];
for (int index = 0; index < size; ++index){
array[index] = readLong();
}
return array;
}
////////////////////////////////////////////////////////////////////
private double readDouble() {
return Double.parseDouble(readString());
}
private double[] readDoubleArray(int size) {
double[] array = new double[size];
for (int index = 0; index < size; ++index){
array[index] = readDouble();
}
return array;
}
////////////////////////////////////////////////////////////////////
private BigInteger readBigInteger() {
return new BigInteger(readString());
}
private BigDecimal readBigDecimal() {
return new BigDecimal(readString());
}
/////////////////////////////////////////////////////////////////////
private Point readPoint() {
int x = readInt();
int y = readInt();
return new Point(x, y);
}
private Point[] readPointArray(int size) {
Point[] array = new Point[size];
for (int index = 0; index < size; ++index){
array[index] = readPoint();
}
return array;
}
/////////////////////////////////////////////////////////////////////
private List<Integer>[] readGraph(int vertexNumber, int edgeNumber) {
@SuppressWarnings("unchecked")
List<Integer>[] graph = new List[vertexNumber];
for (int index = 0; index < vertexNumber; ++index){
graph[index] = new ArrayList<Integer>();
}
while (edgeNumber-- > 0){
int from = readInt() - 1;
int to = readInt() - 1;
graph[from].add(to);
graph[to].add(from);
}
return graph;
}
/////////////////////////////////////////////////////////////////////
private static class IntIndexPair {
static Comparator<IntIndexPair> increaseComparator = new Comparator<ProblemD.IntIndexPair>() {
@Override
public int compare(ProblemD.IntIndexPair indexPair1, ProblemD.IntIndexPair indexPair2) {
int value1 = indexPair1.value;
int value2 = indexPair2.value;
if (value1 != value2) return value1 - value2;
int index1 = indexPair1.index;
int index2 = indexPair2.index;
return index1 - index2;
}
};
static Comparator<IntIndexPair> decreaseComparator = new Comparator<ProblemD.IntIndexPair>() {
@Override
public int compare(ProblemD.IntIndexPair indexPair1, ProblemD.IntIndexPair indexPair2) {
int value1 = indexPair1.value;
int value2 = indexPair2.value;
if (value1 != value2) return -(value1 - value2);
int index1 = indexPair1.index;
int index2 = indexPair2.index;
return index1 - index2;
}
};
int value, index;
IntIndexPair(int value, int index) {
super();
this.value = value;
this.index = index;
}
int getRealIndex() {
return index + 1;
}
}
private IntIndexPair[] readIntIndexArray(int size) {
IntIndexPair[] array = new IntIndexPair[size];
for (int index = 0; index < size; ++index) {
array[index] = new IntIndexPair(readInt(), index);
}
return array;
}
/////////////////////////////////////////////////////////////////////
private static class OutputWriter extends PrintWriter {
final int DEFAULT_PRECISION = 12;
private int precision;
private String format, formatWithSpace;
{
precision = DEFAULT_PRECISION;
format = createFormat(precision);
formatWithSpace = format + " ";
}
OutputWriter(OutputStream out) {
super(out);
}
OutputWriter(String fileName) throws FileNotFoundException {
super(fileName);
}
int getPrecision() {
return precision;
}
void setPrecision(int precision) {
precision = max(0, precision);
this.precision = precision;
format = createFormat(precision);
formatWithSpace = format + " ";
}
String createFormat(int precision){
return "%." + precision + "f";
}
@Override
public void print(double d){
printf(format, d);
}
void printWithSpace(double d){
printf(formatWithSpace, d);
}
void printAll(double...d){
for (int i = 0; i < d.length - 1; ++i){
printWithSpace(d[i]);
}
print(d[d.length - 1]);
}
@Override
public void println(double d){
printlnAll(d);
}
void printlnAll(double... d){
printAll(d);
println();
}
}
/////////////////////////////////////////////////////////////////////
private static class RuntimeIOException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = -6463830523020118289L;
RuntimeIOException(Throwable cause) {
super(cause);
}
}
/////////////////////////////////////////////////////////////////////
//////////////// Some useful constants and functions ////////////////
/////////////////////////////////////////////////////////////////////
private static final int[][] steps = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
private static final int[][] steps8 = {
{-1, 0}, {1, 0}, {0, -1}, {0, 1},
{-1, -1}, {1, 1}, {1, -1}, {-1, 1}
};
private static boolean checkCell(int row, int rowsCount, int column, int columnsCount) {
return checkIndex(row, rowsCount) && checkIndex(column, columnsCount);
}
private static boolean checkIndex(int index, int lim){
return (0 <= index && index < lim);
}
/////////////////////////////////////////////////////////////////////
private static boolean checkBit(int mask, int bit){
return (mask & (1 << bit)) != 0;
}
/////////////////////////////////////////////////////////////////////
private static long getSum(int[] array) {
long sum = 0;
for (int value: array) {
sum += value;
}
return sum;
}
private static Point getMinMax(int[] array) {
int min = array[0];
int max = array[0];
for (int index = 0, size = array.length; index < size; ++index, ++index) {
int value = array[index];
if (index == size - 1) {
min = min(min, value);
max = max(max, value);
} else {
int otherValue = array[index + 1];
if (value <= otherValue) {
min = min(min, value);
max = max(max, otherValue);
} else {
min = min(min, otherValue);
max = max(max, value);
}
}
}
return new Point(min, max);
}
/////////////////////////////////////////////////////////////////////
private static int[] getPrimes(int n) {
boolean[] used = new boolean[n];
used[0] = used[1] = true;
int size = 0;
for (int i = 2; i < n; ++i) {
if (!used[i]) {
++size;
for (int j = 2 * i; j < n; j += i) {
used[j] = true;
}
}
}
int[] primes = new int[size];
for (int i = 0, cur = 0; i < n; ++i) {
if (!used[i]) {
primes[cur++] = i;
}
}
return primes;
}
/////////////////////////////////////////////////////////////////////
private static long lcm(long a, long b) {
return a / gcd(a, b) * b;
}
private static long gcd(long a, long b) {
return (a == 0 ? b : gcd(b % a, a));
}
/////////////////////////////////////////////////////////////////////
private static class IdMap<KeyType> extends HashMap<KeyType, Integer> {
/**
*
*/
private static final long serialVersionUID = -3793737771950984481L;
public IdMap() {
super();
}
int getId(KeyType key) {
Integer id = super.get(key);
if (id == null) {
super.put(key, id = size());
}
return id;
}
}
} | Java | ["3\n3 7 8\n1\n1 3", "7\n1 2 1 3 3 2 3\n5\n4 7\n4 5\n1 3\n1 7\n1 5"] | 3.5 seconds | ["0", "0\n3\n1\n3\n2"] | NoteIn the second sample:There is no integers in the segment of the first query, presented even number of times in the segment — the answer is 0.In the second query there is only integer 3 is presented even number of times — the answer is 3.In the third query only integer 1 is written down — the answer is 1.In the fourth query all array elements are considered. Only 1 and 2 are presented there even number of times. The answer is .In the fifth query 1 and 3 are written down. The answer is . | Java 8 | standard input | [
"data structures"
] | 6fe09ae0980bbc59230290c7ac0bc7c3 | The first line of the input contains single integer n (1 ≤ n ≤ 1 000 000) — the number of elements in the array. The second line of the input contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — array elements. The third line of the input contains single integer m (1 ≤ m ≤ 1 000 000) — the number of queries. Each of the next m lines describes corresponding query by a pair of integers l and r (1 ≤ l ≤ r ≤ n) — the bounds of query segment. | 2,100 | Print m non-negative integers — the answers for the queries in the order they appear in the input. | standard output | |
PASSED | d887cd4033993f5e2f0cc36262fd09eb | train_003.jsonl | 1470323700 | Little Mishka enjoys programming. Since her birthday has just passed, her friends decided to present her with array of non-negative integers a1, a2, ..., an of n elements!Mishka loved the array and she instantly decided to determine its beauty value, but she is too little and can't process large arrays. Right because of that she invited you to visit her and asked you to process m queries.Each query is processed in the following way: Two integers l and r (1 ≤ l ≤ r ≤ n) are specified — bounds of query segment. Integers, presented in array segment [l, r] (in sequence of integers al, al + 1, ..., ar) even number of times, are written down. XOR-sum of written down integers is calculated, and this value is the answer for a query. Formally, if integers written down in point 2 are x1, x2, ..., xk, then Mishka wants to know the value , where — operator of exclusive bitwise OR. Since only the little bears know the definition of array beauty, all you are to do is to answer each of queries presented. | 256 megabytes | /*
Keep solving problems.
*/
import java.util.*;
import java.io.*;
public class CFA {
BufferedReader br;
PrintWriter out;
StringTokenizer st;
boolean eof;
private static final long MOD = 1000L * 1000L * 1000L + 7;
private static final int[] dx = {0, -1, 0, 1};
private static final int[] dy = {1, 0, -1, 0};
private static final String yes = "Yes";
private static final String no = "No";
int n;
class Query implements Comparable<Query> {
int idx;
int start;
int end;
public Query(int idx, int start, int end) {
this.idx = idx;
this.start = start;
this.end = end;
}
@Override
public int compareTo(Query o) {
if (end != o.end) {
return Integer.compare(end, o.end);
}
return Integer.compare(start, o.start);
}
@Override
public String toString() {
return idx + " " + start + " " + end;
}
}
Query[] queries;
int[] arr;
int m;
int tree[];
int[] pref;
/**
* Increment elements at queryIndex with value
*/
void update_tree(int node, int nodeStartIndex, int nodeEndIndex, int queryIndex, int value) {
if(nodeStartIndex > nodeEndIndex || nodeStartIndex > queryIndex || nodeEndIndex < queryIndex) // Current segment is not within range [i, j]
return;
if(nodeStartIndex == nodeEndIndex) { // Segment is fully within range
tree[node] = value;
return;
}
update_tree(node * 2, nodeStartIndex, (nodeStartIndex + nodeEndIndex) / 2, queryIndex, value); // Updating left child
update_tree(node * 2 + 1, 1 + (nodeStartIndex + nodeEndIndex) / 2, nodeEndIndex, queryIndex, value); // Updating right child
tree[node] = tree[node * 2] ^ tree[node * 2 + 1]; // Updating root
}
/**
* Query tree to get max element value within range [queryStartIndex, queryEndIndex]
*/
int query_tree(int node, int nodeStartIndex, int nodeEndIndex, int queryStartIndex, int queryEndIndex) {
if(nodeStartIndex > nodeEndIndex || nodeStartIndex > queryEndIndex || nodeEndIndex < queryStartIndex) {
return 0; // Out of range!!! change if necessary
}
if(nodeStartIndex >= queryStartIndex && nodeEndIndex <= queryEndIndex) {// Current segment is totally within range [i, j]
return tree[node];
}
int q1 = query_tree(node * 2, nodeStartIndex, (nodeStartIndex + nodeEndIndex) / 2, queryStartIndex, queryEndIndex); // Query left child
int q2 = query_tree(1 + node * 2, 1 + (nodeStartIndex + nodeEndIndex) / 2, nodeEndIndex, queryStartIndex, queryEndIndex); // Query right child
return q1 ^ q2;
}
void solve() throws IOException {
n = nextInt();
arr = nextIntArr(n);
m = nextInt();
queries = new Query[m];
for (int i = 0; i < m; i++) {
int start = nextInt() - 1;
int end = nextInt() - 1;
queries[i] = new Query(i, start, end);
}
pref = new int[1 + n];
for (int i = 1; i <= n; i++) {
pref[i] = arr[i - 1] ^ pref[i - 1];
}
Arrays.sort(queries);
int[] res = new int[m];
tree = new int[5 * n];
Map<Integer, Integer> prev = new HashMap<>();
int end = 0;
for (int i = 0; i < m; i++) {
while (end <= queries[i].end) {
if (prev.containsKey(arr[end])) {
int prevIndex = prev.get(arr[end]);
update_tree(1, 0, n - 1, prevIndex, 0);
}
prev.put(arr[end], end);
update_tree(1, 0, n - 1, end, arr[end]);
end++;
}
int val = query_tree(1, 0, n - 1, queries[i].start, queries[i].end);
int extra = pref[queries[i].end + 1] ^ pref[queries[i].start];
res[queries[i].idx] = val ^ extra;
}
for (int v : res) {
outln(v);
}
}
void shuffle(int[] a) {
int n = a.length;
for(int i = 0; i < n; i++) {
int r = i + (int) (Math.random() * (n - i));
int tmp = a[i];
a[i] = a[r];
a[r] = tmp;
}
}
long gcd(long a, long b) {
while(a != 0 && b != 0) {
long c = b;
b = a % b;
a = c;
}
return a + b;
}
private void outln(Object o) {
out.println(o);
}
private void out(Object o) {
out.print(o);
}
private void formatPrint(double val) {
outln(String.format("%.9f%n", val));
}
public CFA() throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
}
public static void main(String[] args) throws IOException {
new CFA();
}
public long[] nextLongArr(int n) throws IOException{
long[] res = new long[n];
for(int i = 0; i < n; i++)
res[i] = nextLong();
return res;
}
public int[] nextIntArr(int n) throws IOException {
int[] res = new int[n];
for(int i = 0; i < n; i++)
res[i] = nextInt();
return res;
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
eof = true;
return null;
}
}
return st.nextToken();
}
public String nextString() {
try {
return br.readLine();
} catch (IOException e) {
eof = true;
return null;
}
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
} | Java | ["3\n3 7 8\n1\n1 3", "7\n1 2 1 3 3 2 3\n5\n4 7\n4 5\n1 3\n1 7\n1 5"] | 3.5 seconds | ["0", "0\n3\n1\n3\n2"] | NoteIn the second sample:There is no integers in the segment of the first query, presented even number of times in the segment — the answer is 0.In the second query there is only integer 3 is presented even number of times — the answer is 3.In the third query only integer 1 is written down — the answer is 1.In the fourth query all array elements are considered. Only 1 and 2 are presented there even number of times. The answer is .In the fifth query 1 and 3 are written down. The answer is . | Java 8 | standard input | [
"data structures"
] | 6fe09ae0980bbc59230290c7ac0bc7c3 | The first line of the input contains single integer n (1 ≤ n ≤ 1 000 000) — the number of elements in the array. The second line of the input contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — array elements. The third line of the input contains single integer m (1 ≤ m ≤ 1 000 000) — the number of queries. Each of the next m lines describes corresponding query by a pair of integers l and r (1 ≤ l ≤ r ≤ n) — the bounds of query segment. | 2,100 | Print m non-negative integers — the answers for the queries in the order they appear in the input. | standard output | |
PASSED | abc2b7439d9a37e87996c215cd6b6556 | train_003.jsonl | 1470323700 | Little Mishka enjoys programming. Since her birthday has just passed, her friends decided to present her with array of non-negative integers a1, a2, ..., an of n elements!Mishka loved the array and she instantly decided to determine its beauty value, but she is too little and can't process large arrays. Right because of that she invited you to visit her and asked you to process m queries.Each query is processed in the following way: Two integers l and r (1 ≤ l ≤ r ≤ n) are specified — bounds of query segment. Integers, presented in array segment [l, r] (in sequence of integers al, al + 1, ..., ar) even number of times, are written down. XOR-sum of written down integers is calculated, and this value is the answer for a query. Formally, if integers written down in point 2 are x1, x2, ..., xk, then Mishka wants to know the value , where — operator of exclusive bitwise OR. Since only the little bears know the definition of array beauty, all you are to do is to answer each of queries presented. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
public class Main {
static ArrayList<Integer> adj[];
static int k;
static int[] a;
static int b[];
static int m;
static class Pair implements Comparable<Pair> {
int a;
int b;
public Pair(int c,int l) {
a = c;
b = l;
}
@Override
public int compareTo(Pair o) {
if(o.a==this.a)
return this.b-o.b;
return this.a-o.a;
}
}
static ArrayList<Pair> adjlist[];
// static char c[];
static long mod = (long) (1e9+7);
static int V;
static long INF = (long) 1E16;
static int n;
static char c[];
static Pair p[];
static int grid[][];
static Scanner sc = new Scanner(System.in);
static PrintWriter out = new PrintWriter(System.out);
static long div[];
public static void main(String args[]) throws Exception {
int n=sc.nextInt();
int a[]=new int[n];
int sum[]=new int[n];
for (int i = 0; i < a.length; i++) {
a[i]=sc.nextInt();
}
sum[0]=a[0];
for (int i =1; i < sum.length; i++) {
sum[i]=a[i]^sum[i-1];
}
int m=sc.nextInt();
FenwickTree ft=new FenwickTree(n);
Query q[]=new Query[m];
for (int i = 0; i < q.length; i++) {
q[i]=new Query(sc.nextInt()-1,sc.nextInt()-1,i);
}
Arrays.sort(q);
int ans[]=new int[m];
int curr=0;
HashMap<Integer,Integer> last=new HashMap<>();
for (int i = 0; i < ans.length; i++) {
int l=q[i].left;
int r=q[i].right;
while(curr<=r) {
int prev=last.getOrDefault(a[curr],-1);
if(prev!=-1) {
ft.point_update(prev,a[curr]);
}
ft.point_update(curr+1,a[curr]);
last.put(a[curr],curr+1);
curr++;
}
if(l>0)
ans[q[i].idx]=(int) (sum[r]^sum[l-1]^ft.rsq(r+1)^ft.rsq(l));
else
ans[q[i].idx]=(int)(sum[r]^ft.rsq(r+1));
//System.out.println(l+" "+r+" "+ans[q[i].idx]+" "+(sum[r]^sum[l-1])+" "+ft.rsq(l+1,r+1));
}
for(int x:ans) {
out.println(x);
}
out.flush();
}
static int s;
static class Query implements Comparable<Query>
{
// length of a block , s = sqrt(n)
int left, right, idx;
int block;
Query(int a, int b, int c)
{
left = a; right = b; idx = c;
//block=left/s;
}
public int compareTo(Query q)
{
return right-q.right;
}
}
static void dfs(int u) {
vis[u]=true;
for(int v:adj[u]) {
if(!vis[v]) {
dfs(v);
}
}
}
static int[] compreessarray(int c[]) {
int b[]=new int[c.length];
for (int i = 0; i < b.length; i++) {
b[i]=c[i];
}
sortarray(c);
TreeMap<Integer,Integer> map=new TreeMap<>();
int id=0;
for (int i = 0; i < c.length; i++) {
if(!map.containsKey(c[i]))
id++;
map.put(c[i],map.getOrDefault(c[i],id));
}
int idx=0;
for (int i = 0; i < c.length; i++) {
joke.put(b[i],map.get(b[i]));
b[i]=map.get(b[i]);
}
return b;
}
static TreeMap<Integer,Integer> joke=new TreeMap<>();
static int div4[];
static long [] reversearray(long a[]) {
for (int i = 0; i <a.length/2; i++) {
long temp=a[i];
a[i]=a[a.length-i-1];
a[a.length-i-1]=temp;
}
return a;
}
static int [] reversearray(int a[]) {
for (int i = 0; i <=a.length/2; i++) {
int temp=a[i];
a[i]=a[a.length-i-1];
a[a.length-i-1]=temp;
}
return a;
}
static class SegmentTree { // 1-based DS, OOP
int N; //the number of elements in the array as a power of 2 (i.e. after padding)
long[] array, sTree, lazy;
long max[];
SegmentTree(long[] in)
{
array = in; N = in.length - 1;
sTree = new long[N<<1]; //no. of nodes = 2*N - 1, we add one to cross out index zero
lazy = new long[N<<1];
max=new long[N<<1];
build(1,1,N);
}
void build(int node, int b, int e) // O(n)
{
if(b == e) {
sTree[node] = array[b];
max[node]=array[b];
}
else
{
int mid = b + e >> 1;
build(node<<1,b,mid);
build(node<<1|1,mid+1,e);
sTree[node] = sTree[node<<1]+sTree[node<<1|1];
max[node]=Math.max(max[node<<1],max[node<<1|1]);
}
}
void update_point(int index, int val) // O(log n)
{
index += N - 1;
sTree[index] += val;
while(index>1)
{
index >>= 1;
sTree[index] = sTree[index<<1] + sTree[index<<1|1];
}
}
void update_range(int i, int j, int val) // O(log n)
{
update_range(1,1,N,i,j,val);
}
void update_range(int node, int b, int e, int i, int j, int val)
{
if(i > e || j < b||max[node]==1||max[node]==2)
return;
if(b==e)
{
sTree[node]=div[(int) sTree[node]];
max[node]=sTree[node];
}
else
{
int mid = b + e >> 1;
// propagate(node, b, mid, e);
update_range(node<<1,b,mid,i,j,val);
update_range(node<<1|1,mid+1,e,i,j,val);
sTree[node] = sTree[node<<1] + sTree[node<<1|1];
max[node]=Math.max(max[node<<1],max[node<<1|1]);
}
}
// void propagate(int node, int b, int mid, int e)
// {
// lazy[node<<1] += lazy[node];
// lazy[node<<1|1] += lazy[node];
// sTree[node<<1] += (mid-b+1)*lazy[node];
// sTree[node<<1|1] += (e-mid)*lazy[node];
// lazy[node] = 0;
// }
long query(int i, int j)
{
return query(1,1,N,i,j);
}
long query(int node, int b, int e, int i, int j) // O(log n)
{
if(i>e || j <b)
return 0;
if(b>= i && e <= j)
return sTree[node];
int mid = b + e >> 1;
// propagate(node, b, mid, e);
long q1 = query(node<<1,b,mid,i,j);
long q2 = query(node<<1|1,mid+1,e,i,j);
return q1+q2;
}
}
static TreeSet<Integer> ts=new TreeSet();
static HashMap<Integer, Integer> compress(int a[]) {
ts = new TreeSet<>();
HashMap<Integer, Integer> hm = new HashMap<>();
for (int x : a)
ts.add(x);
for (int x : ts) {
hm.put(x, hm.size() + 1);
}
return hm;
}
static class FenwickTree { // one-based DS
int n;
long[] ft;
FenwickTree(int size) { n = size; ft = new long[n+1]; }
long rsq(int b) //O(log n)
{
long sum = 0;
while(b>0) { sum ^= ft[b];;
b -= b & -b;
} //min?
return sum;
}
long rsq(int a, int b) { return rsq(b)^rsq(a); }
/**
* @param k
* @param l
*/
void point_update(int k, long l) //O(log n), update = increment
{
while(k<=n) { ft[k]^=l; k += k & -k;
}
}
}
static ArrayList<Integer> euler=new ArrayList<>();
static long total;
static TreeMap<Integer,Integer> map1;
static int zz;
//static int dp(int idx,int left,int state) {
//if(idx>=k-((zz-left)*2)||idx+1==n) {
// return 0;
//}
//if(memo[idx][left][state]!=-1) {
// return memo[idx][left][state];
//}
//int ans=a[idx+1]+dp(idx+1,left,0);
//if(left>0&&state==0&&idx>0) {
// ans=Math.max(ans,a[idx-1]+dp(idx-1,left-1,1));
//}
//return memo[idx][left][state]=ans;
//}21
static HashMap<Integer,Integer> map;
static int maxa=0;
static int ff=123123;
static int[][] memo;
static long modmod=998244353;
static int dx[]= {1,-1,0,0};
static int dy[]= {0,0,1,-1};
static class BBOOK implements Comparable<BBOOK>{
int t;
int alice;
int bob;
public BBOOK(int x,int y,int z) {
t=x;
alice=y;
bob=z;
}
@Override
public int compareTo(BBOOK o) {
return this.t-o.t;
}
}
private static long lcm(long a2, long b2) {
return (a2*b2)/gcd(a2,b2);
}
static class Edge implements Comparable<Edge>
{
int node;long cost ; long time;
Edge(int a, long b,long c) { node = a; cost = b; time=c; }
public int compareTo(Edge e){ return Long.compare(time,e.time); }
}
static void sieve(int N) // O(N log log N)
{
isComposite = new int[N+1];
isComposite[0] = isComposite[1] = 1; // 0 indicates a prime number
primes = new ArrayList<Integer>();
for (int i = 2; i <= N; ++i) //can loop till i*i <= N if primes array is not needed O(N log log sqrt(N))
if (isComposite[i] == 0) //can loop in 2 and odd integers for slightly better performance
{
primes.add(i);
if(1l * i * i <= N)
for (int j = i * i; j <= N; j += i) // j = i * 2 will not affect performance too much, may alter in modified sieve
isComposite[j] = 1;
}
}
static TreeSet<Integer> factors;
static TreeSet<Integer> primeFactors(int N) // O(sqrt(N) / ln sqrt(N))
{
factors = new TreeSet<Integer>(); //take abs(N) in case of -ve integers
int idx = 0, p = primes.get(idx);
while(1l*p * p <= N)
{
while(N % p == 0) { factors.add(p); N /= p; }
p = primes.get(++idx);
}
if(N != 1) // last prime factor may be > sqrt(N)
factors.add(N); // for integers whose largest prime factor has a power of 1
return factors;
}
static class UnionFind {
int[] p, rank, setSize;
int numSets;
long max[];
long largest=0;
public UnionFind(int N) {
p = new int[numSets = N];
rank = new int[N];
setSize = new int[N];
max=new long[N];
for (int i = 0; i < N; i++) {
p[i] = i;
setSize[i] = 1;
}
largest=0;
}
public int findSet(int i) {
return p[i] == i ? i : (p[i] = findSet(p[i]));
}
public void addmax(int i,int val) {
max[i]=val;
largest=Math.max(largest,max[i]);
}
public boolean isSameSet(int i, int j) {
return findSet(i) == findSet(j);
}
public void unionSet(int i, int j) {
if (isSameSet(i, j))
return;
numSets--;
int x = findSet(i), y = findSet(j);
if (rank[x] > rank[y]) {
p[y] = x;
setSize[x] += setSize[y];
max[x]+=max[y];
} else {
p[x] = y;
setSize[y] += setSize[x];
if (rank[x] == rank[y])
rank[y]++;
max[y]+=max[x];
}
largest=Math.max(max[x],largest);
largest=Math.max(max[y],largest);
}
public int numDisjointSets() {
return numSets;
}
public int sizeOfSet(int i) {
return setSize[findSet(i)];
}
}
static class Quad implements Comparable<Quad> {
int u;
int v;
char state;
int turns;
public Quad(int i, int j, char c, int k) {
u = i;
v = j;
state = c;
turns = k;
}
public int compareTo(Quad e) {
return (int) (turns - e.turns);
}
}
static long manhatandistance(long x, long x2, long y, long y2) {
return Math.abs(x - x2) + Math.abs(y - y2);
}
static long fib[];
static long fib(int n) {
if (n == 1 || n == 0) {
return 1;
}
if (fib[n] != -1) {
return fib[n];
} else
return fib[n] = ((fib(n - 2) % mod + fib(n - 1) % mod) % mod);
}
static class Point implements Comparable<Point>{
long x, y;
Point(long counth, long counts) {
x = counth;
y = counts;
}
@Override
public int compareTo(Point p )
{
return Long.compare(p.y*1l*x, p.x*1l*y);
}
}
static TreeSet<Long> primeFactors(long N) // O(sqrt(N) / ln sqrt(N))
{
TreeSet<Long> factors = new TreeSet<Long>(); // take abs(N) in case of -ve integers
int idx = 0, p = primes.get(idx);
while (p * p <= N) {
while (N % p == 0) {
factors.add((long) p);
N /= p;
}
if (primes.size() > idx + 1)
p = primes.get(++idx);
else
break;
}
if (N != 1) // last prime factor may be > sqrt(N)
factors.add(N); // for integers whose largest prime factor has a power of 1
return factors;
}
static boolean visited[];
/**
* static int bfs(int s) { Queue<Integer> q = new LinkedList<Integer>();
* q.add(s); int count=0; int maxcost=0; int dist[]=new int[n]; dist[s]=0;
* while(!q.isEmpty()) {
*
* int u = q.remove(); if(dist[u]==k) { break; } for(Pair v: adj[u]) {
* maxcost=Math.max(maxcost, v.cost);
*
*
*
* if(!visited[v.v]) {
*
* visited[v.v]=true; q.add(v.v); dist[v.v]=dist[u]+1; maxcost=Math.max(maxcost,
* v.cost); } }
*
* } return maxcost; }
**/
static boolean[] vis2;
static boolean f2 = false;
static long[][] matMul(long[][] a2, long[][] b, int p, int q, int r) // C(p x r) = A(p x q) x (q x r) -- O(p x q x
// r)
{
long[][] C = new long[p][r];
for (int i = 0; i < p; ++i) {
for (int j = 0; j < r; ++j) {
for (int k = 0; k < q; ++k) {
C[i][j] = (C[i][j] + (a2[i][k] % mod * b[k][j] % mod)) % mod;
C[i][j] %= mod;
}
}
}
return C;
}
public static int[] schuffle(int[] a2) {
for (int i = 0; i < a2.length; i++) {
int x = (int) (Math.random() * a2.length);
int temp = a2[x];
a2[x] = a2[i];
a2[i] = temp;
}
return a2;
}
static boolean vis[];
static HashSet<Integer> set = new HashSet<Integer>();
static long modPow(long ways, long count, long mod) // O(log e)
{
ways %= mod;
long res = 1;
while (count > 0) {
if ((count & 1) == 1)
res = (res * ways) % mod;
ways = (ways * ways) % mod;
count >>= 1;
}
return res % mod;
}
static long gcd(long l, long o) {
if (o == 0) {
return l;
}
return gcd(o, l % o);
}
static int[] isComposite;
static int[] valid;
static ArrayList<Integer> primes;
static ArrayList<Integer> l1;
static TreeSet<Integer> primus = new TreeSet<Integer>();
static void sieveLinear(int N)
{
int[] lp = new int[N + 1]; //lp[i] = least prime divisor of i
for(int i = 2; i <= N; ++i)
{
if(lp[i] == 0)
{
primus.add(i);
lp[i] = i;
}
int curLP = lp[i];
for(int p: primus)
if(p > curLP || p * i > N)
break;
else
lp[p * i] = i;
}
}
public static long[] schuffle(long[] a2) {
for (int i = 0; i < a2.length; i++) {
int x = (int) (Math.random() * a2.length);
long temp = a2[x];
a2[x] = a2[i];
a2[i] = temp;
}
return a2;
}
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 boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
public int[] nxtArr(int n) throws IOException {
int[] ans = new int[n];
for (int i = 0; i < n; i++)
ans[i] = nextInt();
return ans;
}
}
public static int[] sortarray(int a[]) {
schuffle(a);
Arrays.sort(a);
return a;
}
public static long[] sortarray(long a[]) {
schuffle(a);
Arrays.sort(a);
return a;
}
} | Java | ["3\n3 7 8\n1\n1 3", "7\n1 2 1 3 3 2 3\n5\n4 7\n4 5\n1 3\n1 7\n1 5"] | 3.5 seconds | ["0", "0\n3\n1\n3\n2"] | NoteIn the second sample:There is no integers in the segment of the first query, presented even number of times in the segment — the answer is 0.In the second query there is only integer 3 is presented even number of times — the answer is 3.In the third query only integer 1 is written down — the answer is 1.In the fourth query all array elements are considered. Only 1 and 2 are presented there even number of times. The answer is .In the fifth query 1 and 3 are written down. The answer is . | Java 8 | standard input | [
"data structures"
] | 6fe09ae0980bbc59230290c7ac0bc7c3 | The first line of the input contains single integer n (1 ≤ n ≤ 1 000 000) — the number of elements in the array. The second line of the input contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — array elements. The third line of the input contains single integer m (1 ≤ m ≤ 1 000 000) — the number of queries. Each of the next m lines describes corresponding query by a pair of integers l and r (1 ≤ l ≤ r ≤ n) — the bounds of query segment. | 2,100 | Print m non-negative integers — the answers for the queries in the order they appear in the input. | standard output | |
PASSED | fa9f7a4dc8c811dae1b7af8c74f46e7a | train_003.jsonl | 1335614400 | In ABBYY a wonderful Smart Beaver lives. This time, he began to study history. When he read about the Roman Empire, he became interested in the life of merchants.The Roman Empire consisted of n cities numbered from 1 to n. It also had m bidirectional roads numbered from 1 to m. Each road connected two different cities. Any two cities were connected by no more than one road.We say that there is a path between cities c1 and c2 if there exists a finite sequence of cities t1, t2, ..., tp (p ≥ 1) such that: t1 = c1 tp = c2 for any i (1 ≤ i < p), cities ti and ti + 1 are connected by a road We know that there existed a path between any two cities in the Roman Empire.In the Empire k merchants lived numbered from 1 to k. For each merchant we know a pair of numbers si and li, where si is the number of the city where this merchant's warehouse is, and li is the number of the city where his shop is. The shop and the warehouse could be located in different cities, so the merchants had to deliver goods from the warehouse to the shop.Let's call a road important for the merchant if its destruction threatens to ruin the merchant, that is, without this road there is no path from the merchant's warehouse to his shop. Merchants in the Roman Empire are very greedy, so each merchant pays a tax (1 dinar) only for those roads which are important for him. In other words, each merchant pays di dinars of tax, where di (di ≥ 0) is the number of roads important for the i-th merchant.The tax collection day came in the Empire. The Smart Beaver from ABBYY is very curious by nature, so he decided to count how many dinars each merchant had paid that day. And now he needs your help. | 256 megabytes | /**
* Created with IntelliJ IDEA.
* User: Zakhar_Voit
* Date: 28.04.12
* Time: 22:10
*/
import java.io.*;
import java.util.*;
import static java.lang.System.exit;
public class B {
BufferedReader in;
PrintWriter out;
StringTokenizer st = new StringTokenizer("");
final int INF = (int)2e9;
int n, m, k, timer;
boolean[][] g, bridge;
boolean[] used;
int[] a, b, ans, fup, tin, d;
void init() {
}
void read() throws IOException {
n = nextInt();
m = nextInt();
g = new boolean[n][n];
bridge = new boolean[n][n];
a = new int[m];
b = new int[m];
fup = new int[n];
tin = new int[n];
for (int i = 0; i < m; i++) {
int a = nextInt() - 1, b = nextInt() - 1;
g[a][b] = g[b][a] = true;
this.a[i] = a;
this.b[i] = b;
}
k = nextInt();
ans = new int[k];
}
void solve() throws IOException {
find_bridges();
for (int i = 0; i < k; i++) {
ans[i] = ford_bellman(nextInt() - 1, nextInt() - 1);
}
}
void write() {
for (int i = 0; i < k; i++) out.println(ans[i]);
}
void dfs (int v, int p) {
used[v] = true;
tin[v] = fup[v] = timer++;
for (int to = 0; to < n; to++) {
if (!g[v][to] || to == p) continue;
if (used[to])
fup[v] = Math.min (fup[v], tin[to]);
else {
dfs (to, v);
fup[v] = Math.min (fup[v], fup[to]);
if (fup[to] > tin[v])
bridge[v][to] = bridge[to][v] = true;
}
}
}
void find_bridges() {
timer = 0;
used = new boolean[n];
for (int i=0; i<n; ++i)
if (!used[i])
dfs (i, -1);
}
int ford_bellman(int v, int to) {
d = new int[n];
for (int i = 0; i < n; i++) d[i] = INF;
d[v] = 0;
for (int i=0; i<=n-1; ++i) {
for (int j=0; j<m; ++j)
if (d[a[j]] < INF)
d[b[j]] = Math.min (d[b[j]], d[a[j]] + (bridge[a[j]][b[j]] ? 1 : 0));
for (int j=0; j<m; ++j)
if (d[b[j]] < INF)
d[a[j]] = Math.min (d[a[j]], d[b[j]] + (bridge[b[j]][a[j]] ? 1 : 0));
}
return d[to];
}
public void run() throws IOException {
openIO();
init();
read();
solve();
write();
out.close();
}
static public void main(String[] args) throws IOException {
new Thread(null, new Runnable() {
public void run() {
try {
new B().run();
} catch (Throwable e) {
e.printStackTrace();
exit(999);
}
}
}, "1", 1 << 23).start();
}
public void openIO() throws IOException {
if (new File("input.txt").exists()) {
System.setIn(new FileInputStream("input.txt"));
out = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
} else {
out = new PrintWriter(System.out);
}
in = new BufferedReader(new InputStreamReader(System.in));
}
String nextToken() throws IOException {
while (!st.hasMoreTokens())
st = new StringTokenizer(in.readLine());
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextLine() throws IOException {
st = new StringTokenizer("");
return in.readLine();
}
boolean EOF() throws IOException {
while (!st.hasMoreTokens()) {
String s = in.readLine();
if (s == null)
return true;
st = new StringTokenizer(s);
}
return false;
}
} | Java | ["7 8\n1 2\n2 3\n3 4\n4 5\n5 6\n5 7\n3 5\n4 7\n4\n1 5\n2 4\n2 6\n4 7"] | 2 seconds | ["2\n1\n2\n0"] | NoteThe given sample is illustrated in the figure below. Let's describe the result for the first merchant. The merchant's warehouse is located in city 1 and his shop is in city 5. Let us note that if either road, (1, 2) or (2, 3) is destroyed, there won't be any path between cities 1 and 5 anymore. If any other road is destroyed, the path will be preserved. That's why for the given merchant the answer is 2. | Java 7 | standard input | [] | 184314d3aa83d48b71a95ae4b48de457 | The first input line contains two integers n and m, separated by a space, n is the number of cities, and m is the number of roads in the empire. The following m lines contain pairs of integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi), separated by a space — the numbers of cities connected by the i-th road. It is guaranteed that any two cities are connected by no more than one road and that there exists a path between any two cities in the Roman Empire. The next line contains a single integer k — the number of merchants in the empire. The following k lines contain pairs of integers si, li (1 ≤ si, li ≤ n), separated by a space, — si is the number of the city in which the warehouse of the i-th merchant is located, and li is the number of the city in which the shop of the i-th merchant is located. The input limitations for getting 20 points are: 1 ≤ n ≤ 200 1 ≤ m ≤ 200 1 ≤ k ≤ 200 The input limitations for getting 50 points are: 1 ≤ n ≤ 2000 1 ≤ m ≤ 2000 1 ≤ k ≤ 2000 The input limitations for getting 100 points are: 1 ≤ n ≤ 105 1 ≤ m ≤ 105 1 ≤ k ≤ 105 | 1,600 | Print exactly k lines, the i-th line should contain a single integer di — the number of dinars that the i-th merchant paid. | standard output | |
PASSED | c49e78080f3b5fc9d7775bb8729d9d4d | train_003.jsonl | 1335614400 | In ABBYY a wonderful Smart Beaver lives. This time, he began to study history. When he read about the Roman Empire, he became interested in the life of merchants.The Roman Empire consisted of n cities numbered from 1 to n. It also had m bidirectional roads numbered from 1 to m. Each road connected two different cities. Any two cities were connected by no more than one road.We say that there is a path between cities c1 and c2 if there exists a finite sequence of cities t1, t2, ..., tp (p ≥ 1) such that: t1 = c1 tp = c2 for any i (1 ≤ i < p), cities ti and ti + 1 are connected by a road We know that there existed a path between any two cities in the Roman Empire.In the Empire k merchants lived numbered from 1 to k. For each merchant we know a pair of numbers si and li, where si is the number of the city where this merchant's warehouse is, and li is the number of the city where his shop is. The shop and the warehouse could be located in different cities, so the merchants had to deliver goods from the warehouse to the shop.Let's call a road important for the merchant if its destruction threatens to ruin the merchant, that is, without this road there is no path from the merchant's warehouse to his shop. Merchants in the Roman Empire are very greedy, so each merchant pays a tax (1 dinar) only for those roads which are important for him. In other words, each merchant pays di dinars of tax, where di (di ≥ 0) is the number of roads important for the i-th merchant.The tax collection day came in the Empire. The Smart Beaver from ABBYY is very curious by nature, so he decided to count how many dinars each merchant had paid that day. And now he needs your help. | 256 megabytes | import static java.util.Arrays.deepToString;
import java.io.*;
import java.math.*;
import java.util.*;
public class B {
static ArrayList<Integer> cl = new ArrayList<>(), cr = new ArrayList<>();
static boolean[] used;
static int timer = 0;
static int[] tin, fup;
static ArrayList<Integer>[] g;
static Set<Long> bset = new HashSet<Long>();
static void bridge(int u, int v) {
bset.add(((long) u << 32) + v);
bset.add(((long) v << 32) + u);
}
static void dfs(int v, int p) {
used[v] = true;
tin[v] = fup[v] = timer++;
for (int to : g[v]) {
if (to == p)
continue;
if (used[to])
fup[v] = Math.min(fup[v], tin[to]);
else {
dfs(to, v);
fup[v] = Math.min(fup[v], fup[to]);
if (fup[to] > tin[v])
bridge(v, to);
}
}
}
static int color = 0;
static int[] vc;
static void color(int v, int c) {
used[v] = true;
vc[v] = c;
for (int w : g[v]) {
if (used[w])
continue;
if (bset.contains(((long) v << 32) + w)) {
color++;
cl.add(c);
cr.add(color);
color(w, color);
} else {
color(w, c);
}
}
}
static int[] tout;
static int[][] up;
static int[] h;
static int l;
static void dfs_lca(int v, int p, int cur_h, TreeSet<Integer>[] g) {
tin[v] = ++timer;
up[v][0] = p;
h[v] = cur_h;
for (int i = 1; i <= l; ++i)
up[v][i] = up[up[v][i - 1]][i - 1];
for (int to : g[v]) {
if (to != p)
dfs_lca(to, v, cur_h + 1, g);
}
tout[v] = ++timer;
}
static boolean upper(int a, int b) {
return tin[a] <= tin[b] && tout[a] >= tout[b];
}
static int lca(int a, int b) {
if (upper(a, b))
return a;
if (upper(b, a))
return b;
for (int i = l; i >= 0; --i)
if (!upper(up[a][i], b))
a = up[a][i];
return up[a][0];
}
static void solve() {
int n = nextInt(), m = nextInt();
g = new ArrayList[n];
for (int i = 0; i < n; i++) {
g[i] = new ArrayList<>(0);
}
for (int i = 0; i < m; i++) {
int a = nextInt() - 1, b = nextInt() - 1;
g[a].add(b);
g[b].add(a);
}
used = new boolean[n];
tin = new int[n];
fup = new int[n];
for (int i = 0; i < n; i++) {
if (!used[i]) {
dfs(i, -1);
}
}
vc = new int[n];
used = new boolean[n];
for (int i = 0; i < n; i++) {
if (!used[i]) {
color(i, color);
}
}
color++;
TreeSet<Integer>[] tree = new TreeSet[color];
for (int i = 0; i < color; i++) {
tree[i] = new TreeSet<>();
}
for (int i = 0; i < cl.size(); i++) {
int u = cl.get(i), v = cr.get(i);
tree[u].add(v);
tree[v].add(u);
}
timer = 0;
l = 1;
while ((1 << l) <= color)
++l;
up = new int[color][l + 1];
tout = new int[color];
h = new int[color];
dfs_lca(0, 0, 0, tree);
int k = nextInt();
for (int i = 0; i < k; i++) {
int u = nextInt() - 1, v = nextInt() - 1;
int cu = vc[u], cv = vc[v];
int lc = lca(cu, cv);
int res = h[cu] + h[cv] - 2 * h[lc];
writer.println(res);
}
}
public static void main(String[] args) throws Exception {
reader = new BufferedReader(new InputStreamReader(System.in));
writer = new PrintWriter(System.out);
setTime();
solve();
printTime();
printMemory();
writer.close();
}
static BufferedReader reader;
static PrintWriter writer;
static StringTokenizer tok = new StringTokenizer("");
static long systemTime;
static void debug(Object... o) {
System.err.println(deepToString(o));
}
static void setTime() {
systemTime = System.currentTimeMillis();
}
static void printTime() {
System.err.println("Time consumed: " + (System.currentTimeMillis() - systemTime));
}
static void printMemory() {
System.err.println("Memory consumed: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1000 + "kb");
}
static String next() {
while (!tok.hasMoreTokens()) {
String w = null;
try {
w = reader.readLine();
} catch (Exception e) {
e.printStackTrace();
}
if (w == null)
return null;
tok = new StringTokenizer(w);
}
return tok.nextToken();
}
static int nextInt() {
return Integer.parseInt(next());
}
static long nextLong() {
return Long.parseLong(next());
}
static double nextDouble() {
return Double.parseDouble(next());
}
static BigInteger nextBigInteger() {
return new BigInteger(next());
}
} | Java | ["7 8\n1 2\n2 3\n3 4\n4 5\n5 6\n5 7\n3 5\n4 7\n4\n1 5\n2 4\n2 6\n4 7"] | 2 seconds | ["2\n1\n2\n0"] | NoteThe given sample is illustrated in the figure below. Let's describe the result for the first merchant. The merchant's warehouse is located in city 1 and his shop is in city 5. Let us note that if either road, (1, 2) or (2, 3) is destroyed, there won't be any path between cities 1 and 5 anymore. If any other road is destroyed, the path will be preserved. That's why for the given merchant the answer is 2. | Java 7 | standard input | [] | 184314d3aa83d48b71a95ae4b48de457 | The first input line contains two integers n and m, separated by a space, n is the number of cities, and m is the number of roads in the empire. The following m lines contain pairs of integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi), separated by a space — the numbers of cities connected by the i-th road. It is guaranteed that any two cities are connected by no more than one road and that there exists a path between any two cities in the Roman Empire. The next line contains a single integer k — the number of merchants in the empire. The following k lines contain pairs of integers si, li (1 ≤ si, li ≤ n), separated by a space, — si is the number of the city in which the warehouse of the i-th merchant is located, and li is the number of the city in which the shop of the i-th merchant is located. The input limitations for getting 20 points are: 1 ≤ n ≤ 200 1 ≤ m ≤ 200 1 ≤ k ≤ 200 The input limitations for getting 50 points are: 1 ≤ n ≤ 2000 1 ≤ m ≤ 2000 1 ≤ k ≤ 2000 The input limitations for getting 100 points are: 1 ≤ n ≤ 105 1 ≤ m ≤ 105 1 ≤ k ≤ 105 | 1,600 | Print exactly k lines, the i-th line should contain a single integer di — the number of dinars that the i-th merchant paid. | standard output | |
PASSED | 14220029d5b120bacfd2632e44e5bb28 | train_003.jsonl | 1335614400 | In ABBYY a wonderful Smart Beaver lives. This time, he began to study history. When he read about the Roman Empire, he became interested in the life of merchants.The Roman Empire consisted of n cities numbered from 1 to n. It also had m bidirectional roads numbered from 1 to m. Each road connected two different cities. Any two cities were connected by no more than one road.We say that there is a path between cities c1 and c2 if there exists a finite sequence of cities t1, t2, ..., tp (p ≥ 1) such that: t1 = c1 tp = c2 for any i (1 ≤ i < p), cities ti and ti + 1 are connected by a road We know that there existed a path between any two cities in the Roman Empire.In the Empire k merchants lived numbered from 1 to k. For each merchant we know a pair of numbers si and li, where si is the number of the city where this merchant's warehouse is, and li is the number of the city where his shop is. The shop and the warehouse could be located in different cities, so the merchants had to deliver goods from the warehouse to the shop.Let's call a road important for the merchant if its destruction threatens to ruin the merchant, that is, without this road there is no path from the merchant's warehouse to his shop. Merchants in the Roman Empire are very greedy, so each merchant pays a tax (1 dinar) only for those roads which are important for him. In other words, each merchant pays di dinars of tax, where di (di ≥ 0) is the number of roads important for the i-th merchant.The tax collection day came in the Empire. The Smart Beaver from ABBYY is very curious by nature, so he decided to count how many dinars each merchant had paid that day. And now he needs your help. | 256 megabytes | import java.util.*;
import java.io.*;
public class Solution {
FastScanner in;
PrintWriter out;
int N, M, K, co = 0;
compa[] xx;
boolean[] used;
city[] g;
class city {
ArrayList<Integer> roads;
ArrayList<Integer> bridges;
int comp;
}
class compa {
ArrayList<Integer> r;
ArrayList<Integer> g;
int id;
}
void IS_BRIDGE(int v, int to) {
g[v].bridges.add(to);
g[to].bridges.add(v);
}
int timer;
int[] tin;
int[] fup;
void dfs (int v, int p) {
used[v] = true;
tin[v] = fup[v] = timer++;
for (int i = 0; i < g[v].roads.size(); ++i) {
int to = g[v].roads.get(i);
if (to == p) continue;
if (used[to])
fup[v] = Math.min(fup[v], tin[to]);
else {
dfs (to, v);
fup[v] = Math.min (fup[v], fup[to]);
if (fup[to] > tin[v])
IS_BRIDGE(v,to);
}
}
}
void dfs2 (int v, int co) {
g[v].comp = co;
for (int i = 0; i < g[v].roads.size(); i++) {
int to = g[v].roads.get(i);
if (g[to].comp == 0) {
g[to].comp = co;
dfs2(to, co);
}
}
}
void dfs3 (int v, int id) {
xx[v].id = id;
for (int i = 0; i < xx[v].r.size(); i++) {
int to = xx[v].r.get(i);
if (xx[to].id == 0) {
xx[v].g.add(to);
dfs3(to, id + 1);
}
}
}
//
int l;
int[] tin2;
int[] tout2;
int timer2;
int[][] up2;
void dfs4 (int v, int p) {
tin2[v] = ++timer2;
up2[v][0] = p;
for (int i=1; i<=l; ++i)
up2[v][i] = up2[up2[v][i-1]][i-1];
for (int i=0; i<xx[v].g.size(); ++i) {
int to = xx[v].g.get(i);
if (to != p)
dfs4 (to, v);
}
tout2[v] = ++timer2;
}
boolean upper2 (int a, int b) {
return tin2[a] <= tin2[b] && tout2[a] >= tout2[b];
}
int lca (int a, int b) {
if (upper2 (a, b)) return a;
if (upper2 (b, a)) return b;
for (int i = l; i>=0; --i)
if (! upper2 (up2[a][i], b))
a = up2[a][i];
return up2[a][0];
}
//
public void solve() throws IOException {
N = in.nextInt();
g = new city[N];
used = new boolean[N];
tin = new int[N];
fup = new int[N];
for (int i = 0; i < N; i++) {
g[i] = new city();
g[i].roads = new ArrayList<Integer>();
g[i].bridges = new ArrayList<Integer>();
}
M = in.nextInt();
for (int i = 0; i < M; i++) {
int x = in.nextInt();
int y = in.nextInt();
g[x - 1].roads.add(y - 1);
g[y - 1].roads.add(x - 1);
}
for (int i = 0; i < N; ++i)
used[i] = false;
timer = 0;
for (int i=0; i < N; ++i)
if (!used[i])
dfs (i, -1);
for (int i = 0; i < N; i++) {
int[] tmp = new int[g[i].bridges.size()];
for (int j = 0; j < g[i].bridges.size(); j++)
tmp[j] = g[i].bridges.get(j);
Arrays.sort(tmp);
g[i].bridges = new ArrayList<Integer>();
for (int j = 0; j < tmp.length; j++)
g[i].bridges.add(tmp[j]);
tmp = new int[g[i].roads.size()];
for (int j = 0; j < g[i].roads.size(); j++)
tmp[j] = g[i].roads.get(j);
Arrays.sort(tmp);
int uk = 0;
g[i].roads = new ArrayList<Integer>();
for (int j = 0; j < tmp.length; j++) {
while (uk != g[i].bridges.size() && g[i].bridges.get(uk) < tmp[j]) uk++;
if (uk == g[i].bridges.size() || (int)g[i].bridges.get(uk) != tmp[j])
g[i].roads.add(tmp[j]);
}
}
for (int i = 0; i < N; i++) {
if (g[i].comp == 0) {
++co;
dfs2(i, co);
}
}
xx = new compa[co];
for (int i = 0; i < co; i++) {
xx[i] = new compa();
xx[i].r = new ArrayList<Integer>();
xx[i].g = new ArrayList<Integer>();
}
for (int i = 0; i < N; i++) {
int c = g[i].comp - 1;
for (int j = 0; j < g[i].bridges.size(); j++) {
int to = g[g[i].bridges.get(j)].comp - 1;
xx[c].r.add(to);
}
}
int from = 0;
for (int i = 0; i < co; i++) {
if (xx[i].r.size() <= 1) {
dfs3(i, 1);
from = i;
break;
}
}
int n = xx.length;
tin2 = new int[n];
tout2 = new int[n];
up2 = new int[n][];
l = 1;
while ((1<<l) <= n) ++l;
for (int i=0; i<n; ++i) up2[i] = new int[l + 1];
dfs4 (from, from);
K = in.nextInt();
for (int i = 0; i < K; i++) {
int x = in.nextInt();
int y = in.nextInt();
int c1 = g[x - 1].comp - 1;
int c2 = g[y - 1].comp - 1;
int lc = lca(c1, c2);
int res = (xx[c1].id - xx[lc].id) + (xx[c2].id - xx[lc].id);
out.println(res);
}
}
public void run() {
try {
//in = new FastScanner(new File("input.txt"));
//out = new PrintWriter(new File("output.txt"));
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f));
}
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());
}
}
public static void main(String[] arg) {
new Solution().run();
}
} | Java | ["7 8\n1 2\n2 3\n3 4\n4 5\n5 6\n5 7\n3 5\n4 7\n4\n1 5\n2 4\n2 6\n4 7"] | 2 seconds | ["2\n1\n2\n0"] | NoteThe given sample is illustrated in the figure below. Let's describe the result for the first merchant. The merchant's warehouse is located in city 1 and his shop is in city 5. Let us note that if either road, (1, 2) or (2, 3) is destroyed, there won't be any path between cities 1 and 5 anymore. If any other road is destroyed, the path will be preserved. That's why for the given merchant the answer is 2. | Java 7 | standard input | [] | 184314d3aa83d48b71a95ae4b48de457 | The first input line contains two integers n and m, separated by a space, n is the number of cities, and m is the number of roads in the empire. The following m lines contain pairs of integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi), separated by a space — the numbers of cities connected by the i-th road. It is guaranteed that any two cities are connected by no more than one road and that there exists a path between any two cities in the Roman Empire. The next line contains a single integer k — the number of merchants in the empire. The following k lines contain pairs of integers si, li (1 ≤ si, li ≤ n), separated by a space, — si is the number of the city in which the warehouse of the i-th merchant is located, and li is the number of the city in which the shop of the i-th merchant is located. The input limitations for getting 20 points are: 1 ≤ n ≤ 200 1 ≤ m ≤ 200 1 ≤ k ≤ 200 The input limitations for getting 50 points are: 1 ≤ n ≤ 2000 1 ≤ m ≤ 2000 1 ≤ k ≤ 2000 The input limitations for getting 100 points are: 1 ≤ n ≤ 105 1 ≤ m ≤ 105 1 ≤ k ≤ 105 | 1,600 | Print exactly k lines, the i-th line should contain a single integer di — the number of dinars that the i-th merchant paid. | standard output | |
PASSED | 1c58f5e819fcbcf49503fff5ec90d272 | train_003.jsonl | 1335614400 | In ABBYY a wonderful Smart Beaver lives. This time, he began to study history. When he read about the Roman Empire, he became interested in the life of merchants.The Roman Empire consisted of n cities numbered from 1 to n. It also had m bidirectional roads numbered from 1 to m. Each road connected two different cities. Any two cities were connected by no more than one road.We say that there is a path between cities c1 and c2 if there exists a finite sequence of cities t1, t2, ..., tp (p ≥ 1) such that: t1 = c1 tp = c2 for any i (1 ≤ i < p), cities ti and ti + 1 are connected by a road We know that there existed a path between any two cities in the Roman Empire.In the Empire k merchants lived numbered from 1 to k. For each merchant we know a pair of numbers si and li, where si is the number of the city where this merchant's warehouse is, and li is the number of the city where his shop is. The shop and the warehouse could be located in different cities, so the merchants had to deliver goods from the warehouse to the shop.Let's call a road important for the merchant if its destruction threatens to ruin the merchant, that is, without this road there is no path from the merchant's warehouse to his shop. Merchants in the Roman Empire are very greedy, so each merchant pays a tax (1 dinar) only for those roads which are important for him. In other words, each merchant pays di dinars of tax, where di (di ≥ 0) is the number of roads important for the i-th merchant.The tax collection day came in the Empire. The Smart Beaver from ABBYY is very curious by nature, so he decided to count how many dinars each merchant had paid that day. And now he needs your help. | 256 megabytes | import java.io.*;
import java.util.*;
public class cf178b {
public static void main(String[] args) {
FastIO in = new FastIO(), out = in;
int n = in.nextInt();
int m = in.nextInt();
int[] a = new int[m];
int[] b = new int[m];
Graph g = new Graph(n);
for(int i=0; i<m; i++) {
a[i] = in.nextInt()-1;
b[i] = in.nextInt()-1;
g.add(a[i], b[i]);
}
DFSLowLink dfs = new DFSLowLink(g);
DisjointSet ds = new DisjointSet(n);
HashSet<Integer> bridges = new HashSet<Integer>();
for(int x : dfs.bridges) bridges.add(x);
for(int i=0; i<m; i++)
if(!bridges.contains(i)) {
ds.union(a[i], b[i]);
}
LinkCutTree lct = new LinkCutTree(n);
for(int i=0; i<n; i++)
lct.pathUpdate(i, i, 1);
for(int x : bridges) {
lct.link(ds.find(a[x]), ds.find(b[x]));
}
int k = in.nextInt();
for(int i=0; i<k; i++) {
int x = in.nextInt()-1;
int y = in.nextInt()-1;
out.println(lct.pathAggregate(ds.find(x),ds.find(y))-1);
}
out.close();
}
static class LinkCutTree {
int[] l, r, p, pp, val, sum, carry, size, flip;
int NULL;
public LinkCutTree(int n) {
Arrays.fill(l = new int[n + 1], NULL = n);
Arrays.fill(r = new int[n + 1], NULL);
Arrays.fill(p = new int[n + 1], NULL);
Arrays.fill(pp = new int[n + 1], NULL);
Arrays.fill(size = new int[n + 1], 1);
val = new int[n + 1];
sum = new int[n + 1];
carry = new int[n + 1];
flip = new int[n + 1];
size[NULL] = 0;
}
public int access(int x) {
if (r[splay(x)] != NULL)
r[pp[r[x]] = x] = p[r[x]] = NULL;
for (int w = x; update(w) >= 0 && splay(w = pp[x]) != NULL; splay(r[p[x] = w] = x))
if (r[w] != NULL)
p[r[pp[r[w]] = w]] = NULL;
return x;
}
public void makeroot(int x) {
access(x);
flip[x] ^= 1;
push(x);
}
public int findroot(int x) {
for (access(x); l[x] != NULL; x = l[x])
;
return access(x);
}
public int pathAggregate(int x) {
return sum[access(x)];
}
public int pathAggregate(int x, int y) {
int z = lca(x, y);
int ans = val[z];
if (z != x)
ans += sum[x];
if (z != y)
ans += sum[y];
return ans;
}
public void cut(int x) {
l[x] = p[l[access(x)]] = NULL;
}
public void link(int x, int y) {
makeroot(x);
l[p[access(y)] = access(x)] = y;
}
public void pathUpdate(int x, int y, int c) {
int z = lca(x, y);
if (x != z)
carry[x] += c;
if (y != z)
carry[y] += c;
val[z] += c;
}
public int splay(int x) {
for (push(x); p[x] != NULL; lift(x))
if (l[l[p[p[x]]]] == x || r[r[p[p[x]]]] == x)
lift(p[x]);
else lift(x);
return x;
}
void push(int x) {
if (flip[x] == 1) {
int tmp = l[x];
l[x] = r[x];
r[x] = tmp;
flip[x] ^= 1;
flip[l[x]] ^= 1;
flip[r[x]] ^= 1;
}
val[x] += carry[x];
carry[l[x]] += carry[x];
carry[r[x]] += carry[x];
carry[x] = 0;
}
int update(int x) {
if (x == NULL)
return x;
size[x] = size[l[x]] + size[r[x]] + 1;
sum[x] = val[x] + sum[l[x]] + sum[r[x]] + carry[x] * size[x];
return x;
}
public int lca(int x, int y) {
access(x);
access(y);
splay(x);
return access(pp[x] == NULL ? x : pp[x]);
}
void lift(int x) {
if (p[x] == NULL)
return;
push(p[x]);
push(x);
pp[x] = pp[p[x]];
pp[p[x]] = NULL;
int[] a = l, b = r;
if (r[p[x]] == x) {
a = r;
b = l;
}
a[p[x]] = b[x];
b[x] = p[x];
p[x] = p[p[x]];
if (p[x] != NULL)
if (a[p[x]] == b[x])
a[p[x]] = x;
else b[p[x]] = x;
if (a[b[x]] != NULL)
p[a[b[x]]] = b[x];
update(p[update(b[x])] = x);
}
}
static class DisjointSet {
int[] p, r;
DisjointSet(int s) {
p = new int[s];
r = new int[s];
for(int i=0; i<s; i++)
p[i] = i;
}
void union(int x, int y) {
int a = find(x);
int b = find(y);
if(a==b) return;
if(r[a] == r[b])
r[p[b]=a]++;
else
p[a]=p[b]=r[a]<r[b]?b:a;
}
int find(int x) {
return p[x]=p[x]==x?x:find(p[x]);
}
}
static class DFSLowLink {
ArrayList<ArrayList<Integer>> comps;
ArrayList<Integer> bridges;
boolean[] art, used;
int[] stk, low, pre;
Graph g;
int cnt;
DFSLowLink(Graph gg) {
g=gg; cnt=0;
comps = new ArrayList<ArrayList<Integer>>();
bridges = new ArrayList<Integer>();
Arrays.fill(low=new int[g.N], -1);
Arrays.fill(pre=new int[g.N], -1);
used = new boolean[g.M+1];
art = new boolean[g.N];
stk = new int[g.M+2];
for(int i=0; i<g.N; i++)
if(pre[i] == -1) {
used[g.M] = false;
dfs(i,i,g.M);
if(stk[0] > 1)
makeComp(g.M);
stk[0]=0;
}
}
int dfs(int i, int p, int id) {
if(!used[id]) used[stk[++stk[0]] = id] = true;
if(pre[i] != -1) return low[p] = Math.min(low[p],pre[i]);
boolean hasPath = false; low[i] = pre[i] = cnt++;
for(Edge e : g.adj[i]) if(e.id != id && dfs(e.j,i,e.id) < 0) {
low[i] = Math.min(low[i],low[e.j]);
if(low[e.j] == pre[e.j]) bridges.add(e.id);
if(i != p ? low[e.j] >= pre[i] : hasPath) {
art[i] = true;
makeComp(e.id).add(stk[stk[0]--]);
}
hasPath=true;
}
return -1;
}
ArrayList<Integer> makeComp (int id) {
ArrayList<Integer> comp = new ArrayList<Integer>();
while(stk[stk[0]] != id) comp.add(stk[stk[0]--]);
comps.add(comp);
return comp;
}
}
static class Graph {
int N,M;
ArrayList<Edge>[] adj;
Graph(int n) {
adj = new ArrayList[N=n];
for(int i=0; i<N; i++)
adj[i] = new ArrayList<Edge>();
}
void add(int i, int j) {
adj[i].add(new Edge(j,M));
adj[j].add(new Edge(i,M++));
}
}
static class Edge {
int j, id;
Edge(int jj, int ii) {
j=jj; id=ii;
}
}
static class FastIO extends PrintWriter {
BufferedReader br;
StringTokenizer st;
public FastIO() {
this(System.in, System.out);
}
public FastIO(InputStream in, OutputStream out) {
super(new BufferedWriter(new OutputStreamWriter(out)));
br = new BufferedReader(new InputStreamReader(in));
scanLine();
}
public void scanLine() {
try {
st = new StringTokenizer(br.readLine().trim());
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
public int numTokens() {
if (!st.hasMoreTokens()) {
scanLine();
return numTokens();
}
return st.countTokens();
}
public String next() {
if (!st.hasMoreTokens()) {
scanLine();
return next();
}
return st.nextToken();
}
public double nextDouble() {
return Double.parseDouble(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["7 8\n1 2\n2 3\n3 4\n4 5\n5 6\n5 7\n3 5\n4 7\n4\n1 5\n2 4\n2 6\n4 7"] | 2 seconds | ["2\n1\n2\n0"] | NoteThe given sample is illustrated in the figure below. Let's describe the result for the first merchant. The merchant's warehouse is located in city 1 and his shop is in city 5. Let us note that if either road, (1, 2) or (2, 3) is destroyed, there won't be any path between cities 1 and 5 anymore. If any other road is destroyed, the path will be preserved. That's why for the given merchant the answer is 2. | Java 7 | standard input | [] | 184314d3aa83d48b71a95ae4b48de457 | The first input line contains two integers n and m, separated by a space, n is the number of cities, and m is the number of roads in the empire. The following m lines contain pairs of integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi), separated by a space — the numbers of cities connected by the i-th road. It is guaranteed that any two cities are connected by no more than one road and that there exists a path between any two cities in the Roman Empire. The next line contains a single integer k — the number of merchants in the empire. The following k lines contain pairs of integers si, li (1 ≤ si, li ≤ n), separated by a space, — si is the number of the city in which the warehouse of the i-th merchant is located, and li is the number of the city in which the shop of the i-th merchant is located. The input limitations for getting 20 points are: 1 ≤ n ≤ 200 1 ≤ m ≤ 200 1 ≤ k ≤ 200 The input limitations for getting 50 points are: 1 ≤ n ≤ 2000 1 ≤ m ≤ 2000 1 ≤ k ≤ 2000 The input limitations for getting 100 points are: 1 ≤ n ≤ 105 1 ≤ m ≤ 105 1 ≤ k ≤ 105 | 1,600 | Print exactly k lines, the i-th line should contain a single integer di — the number of dinars that the i-th merchant paid. | standard output | |
PASSED | 5ad959acd2f754117150b71a6323e46c | train_003.jsonl | 1335614400 | In ABBYY a wonderful Smart Beaver lives. This time, he began to study history. When he read about the Roman Empire, he became interested in the life of merchants.The Roman Empire consisted of n cities numbered from 1 to n. It also had m bidirectional roads numbered from 1 to m. Each road connected two different cities. Any two cities were connected by no more than one road.We say that there is a path between cities c1 and c2 if there exists a finite sequence of cities t1, t2, ..., tp (p ≥ 1) such that: t1 = c1 tp = c2 for any i (1 ≤ i < p), cities ti and ti + 1 are connected by a road We know that there existed a path between any two cities in the Roman Empire.In the Empire k merchants lived numbered from 1 to k. For each merchant we know a pair of numbers si and li, where si is the number of the city where this merchant's warehouse is, and li is the number of the city where his shop is. The shop and the warehouse could be located in different cities, so the merchants had to deliver goods from the warehouse to the shop.Let's call a road important for the merchant if its destruction threatens to ruin the merchant, that is, without this road there is no path from the merchant's warehouse to his shop. Merchants in the Roman Empire are very greedy, so each merchant pays a tax (1 dinar) only for those roads which are important for him. In other words, each merchant pays di dinars of tax, where di (di ≥ 0) is the number of roads important for the i-th merchant.The tax collection day came in the Empire. The Smart Beaver from ABBYY is very curious by nature, so he decided to count how many dinars each merchant had paid that day. And now he needs your help. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class Solution {
BufferedReader in;
PrintWriter out;
StringTokenizer st;
String nextToken() throws Exception {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
int nextInt() throws Exception {
return Integer.parseInt(nextToken());
}
class Edge {
int b, e;
Edge next;
boolean isBr;
Edge ss;
Edge(int q, int w, Edge qq) {
b = q; e = w; next = qq;
isBr = false; ss = null;
}
}
Edge[] v;
Edge[] v2;
int[] tin;
int[] t;
boolean[] was;
int[] comp;
int countercomp = 0;
int counter = 1;
void dfs(int q) {
was[q] = true;
comp[q] = countercomp;
for (Edge r = v[q]; r != null; r = r.next) if (!r.isBr) {
if (!was[r.e]) {
dfs(r.e);
}
}
}
void bridges(int q, Edge rr) {
tin[q] = counter++;
was[q] = true;
t[q] = tin[q];
for (Edge r = v[q]; r != null; r = r.next) if (rr == null || rr.ss != r) {
if (was[r.e]) {
t[q] = Math.min(t[q], tin[r.e]);
} else {
bridges(r.e, r);
t[q] = Math.min(t[q], t[r.e]);
}
}
if (rr != null) {
if (t[q] == tin[q]) {
rr.isBr = true;
rr.ss.isBr = true;
}
}
}
void addedge(int a, int b) {
v[a] = new Edge(a, b, v[a]);
v[b] = new Edge(b, a, v[b]);
v[a].ss = v[b];
v[b].ss = v[a];
}
int[] h;
class SegTree {
int C = 1 << 18;
int[] a;
int cnt = 0;
SegTree() {
a = new int[2 * C];
Arrays.fill(a, Integer.MAX_VALUE / 2);
}
void add(int q) {
a[C + cnt++] = q;
}
void fin() {
for (int i = C - 1; i >= 1; i--) {
a[i] = Math.min(a[i * 2], a[i * 2 + 1]);
}
}
int minn(int q, int w) {
return min1(C + Math.min(q, w), C + Math.max(q, w));
}
int min1(int q, int w) {
if (q == w) return a[q];
if (q + 1 == w) return Math.min(a[q], a[w]);
int res = min1((q + 1) / 2, (w - 1) / 2);
if (q % 2 == 1) res = Math.min(res, a[q]);
if (w % 2 == 0) res = Math.min(res, a[w]);
return res;
}
}
SegTree str;
int[] lcaf;
void dfseuh(int q, int hh) {
h[q] = hh;
if (lcaf[q] == -1) lcaf[q] = str.cnt;
str.add(hh);
for (Edge r = v2[q]; r != null; r = r.next) {
if (h[r.e] == -1) {
dfseuh(r.e, hh + 1);
str.add(hh);
}
}
}
int lca(int a, int b) {
return str.minn(lcaf[a], lcaf[b]);
}
void solve() throws Exception {
int n = nextInt();
int m = nextInt();
v = new Edge[n];
tin = new int[n];
t = new int[n];
was = new boolean[n];
comp = new int[n];
for (int i = 0; i < m; i++) {
addedge(nextInt() - 1, nextInt() - 1);
}
bridges(0, null);
Arrays.fill(was, false);
for (int i = 0; i < n; i++) {
if (!was[i]) {
dfs(i);
countercomp++;
}
}
v2 = new Edge[countercomp];
for (int i = 0; i < n; i++) {
for (Edge r = v[i]; r != null; r = r.next) {
if (r.isBr) {
v2[comp[r.b]] = new Edge(comp[r.b], comp[r.e], v2[comp[r.b]]);
}
}
}
h = new int[countercomp];
lcaf = new int[countercomp];
Arrays.fill(h, -1);
Arrays.fill(lcaf, -1);
str = new SegTree();
dfseuh(0, 0);
str.fin();
int k = nextInt();
for (int i = 0; i < k; i++) {
int a = comp[nextInt() - 1];
int b = comp[nextInt() - 1];
if (a == b) out.println(0); else {
int lc = lca(a, b);
out.println(h[a] + h[b] - 2 * lc);
}
}
}
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
} finally {
out.close();
}
}
public static void main(String[] args) {
new Solution().run();
}
}
| Java | ["7 8\n1 2\n2 3\n3 4\n4 5\n5 6\n5 7\n3 5\n4 7\n4\n1 5\n2 4\n2 6\n4 7"] | 2 seconds | ["2\n1\n2\n0"] | NoteThe given sample is illustrated in the figure below. Let's describe the result for the first merchant. The merchant's warehouse is located in city 1 and his shop is in city 5. Let us note that if either road, (1, 2) or (2, 3) is destroyed, there won't be any path between cities 1 and 5 anymore. If any other road is destroyed, the path will be preserved. That's why for the given merchant the answer is 2. | Java 7 | standard input | [] | 184314d3aa83d48b71a95ae4b48de457 | The first input line contains two integers n and m, separated by a space, n is the number of cities, and m is the number of roads in the empire. The following m lines contain pairs of integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi), separated by a space — the numbers of cities connected by the i-th road. It is guaranteed that any two cities are connected by no more than one road and that there exists a path between any two cities in the Roman Empire. The next line contains a single integer k — the number of merchants in the empire. The following k lines contain pairs of integers si, li (1 ≤ si, li ≤ n), separated by a space, — si is the number of the city in which the warehouse of the i-th merchant is located, and li is the number of the city in which the shop of the i-th merchant is located. The input limitations for getting 20 points are: 1 ≤ n ≤ 200 1 ≤ m ≤ 200 1 ≤ k ≤ 200 The input limitations for getting 50 points are: 1 ≤ n ≤ 2000 1 ≤ m ≤ 2000 1 ≤ k ≤ 2000 The input limitations for getting 100 points are: 1 ≤ n ≤ 105 1 ≤ m ≤ 105 1 ≤ k ≤ 105 | 1,600 | Print exactly k lines, the i-th line should contain a single integer di — the number of dinars that the i-th merchant paid. | standard output | |
PASSED | eb833c9abd7313a5c60396ac3854f016 | train_003.jsonl | 1572873300 | There are $$$n$$$ students at your university. The programming skill of the $$$i$$$-th student is $$$a_i$$$. As a coach, you want to divide them into teams to prepare them for the upcoming ICPC finals. Just imagine how good this university is if it has $$$2 \cdot 10^5$$$ students ready for the finals!Each team should consist of at least three students. Each student should belong to exactly one team. The diversity of a team is the difference between the maximum programming skill of some student that belongs to this team and the minimum programming skill of some student that belongs to this team (in other words, if the team consists of $$$k$$$ students with programming skills $$$a[i_1], a[i_2], \dots, a[i_k]$$$, then the diversity of this team is $$$\max\limits_{j=1}^{k} a[i_j] - \min\limits_{j=1}^{k} a[i_j]$$$).The total diversity is the sum of diversities of all teams formed.Your task is to minimize the total diversity of the division of students and find the optimal way to divide the students. | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.InputMismatchException;
import java.util.NoSuchElementException;
import java.util.function.BinaryOperator;
public class Main {
static PrintWriter out;
static InputReader ir;
static void solve() {
int n = ir.nextInt();
long[][] a = new long[n][2];
for (int i = 0; i < n; i++) {
a[i][0] = ir.nextLong();
a[i][1] = i;
}
Arrays.sort(a, new Comparator<long[]>() {
public int compare(long[] A, long[] B) {
return Long.compare(A[0], B[0]);
}
});
BinaryOperator<Long> f = (A, B) -> Math.min(A, B);
SegmentTree st = new SegmentTree(n, f, 1L << 60);
st.update(n - 3, 1L << 60);
st.update(n - 2, 1L << 60);
st.update(n - 1, a[n - 1][0]);
long[] dp = new long[n + 1];
dp[n - 2] = dp[n - 1] = 1L << 60;
for (int i = n - 3; i >= 0; i--) {
dp[i] = st.query(i + 2, n) - a[i][0];
if (i != 0)
st.update(i - 1, a[i - 1][0] + dp[i]);
else {
out.print(dp[0] + " ");
int k = 1;
int[] div = new int[n];
for (int j = 0; j < n; j++) {
int pre = j;
div[(int) a[j++][1]] = k;
div[(int) a[j++][1]] = k;
while (j < n && dp[pre] + a[pre][0] != a[j][0] + dp[j + 1]) {
div[(int) a[j][1]] = k;
j++;
}
if (j < n)
div[(int) a[j][1]] = k++;
}
out.println(k - 1);
for (int j = 0; j < n; j++)
out.print(div[j] + " ");
out.println();
return;
}
}
}
static class SegmentTree {
BinaryOperator<Long> f;
int n;
long[] seg;
long e;
public SegmentTree(int nn, BinaryOperator<Long> f, long e) {
this.f = f;
this.e = e;
n = 1;
while (n < nn)
n <<= 1;
seg = new long[n * 2 - 1];
Arrays.fill(seg, e);
}
public SegmentTree(long[] a, BinaryOperator<Long> f, long e) {
this.f = f;
this.e = e;
n = 1;
while (n < a.length)
n <<= 1;
seg = new long[n * 2 - 1];
Arrays.fill(seg, e);
for (int i = 0; i < a.length; i++)
seg[i + n - 1] = a[i];
for (int i = n - 2; i >= 0; i--)
seg[i] = f.apply(seg[i * 2 + 1], seg[i * 2 + 2]);
}
public long query(int l, int r) {
return query(l, r, 0, 0, n);
}
private long query(int a, int b, int k, int l, int r) {
if (a <= l && r <= b)
return seg[k];
if (r <= a || b <= l)
return e;
long vl = query(a, b, k * 2 + 1, l, (l + r) / 2);
long vr = query(a, b, k * 2 + 2, (l + r) / 2, r);
return f.apply(vl, vr);
}
void update(int i, long x) {
i += n - 1;
seg[i] = x;
while (i > 0) {
i = (i - 1) / 2;
seg[i] = f.apply(seg[i * 2 + 1], seg[i * 2 + 2]);
}
}
}
public static void main(String[] args) {
ir = new InputReader(System.in);
out = new PrintWriter(System.out);
solve();
out.flush();
}
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 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;
}
}
static void tr(Object... o) {
out.println(Arrays.deepToString(o));
}
} | Java | ["5\n1 1 3 4 2", "6\n1 5 12 13 2 15", "10\n1 2 5 129 185 581 1041 1909 1580 8150"] | 2 seconds | ["3 1\n1 1 1 1 1", "7 2\n2 2 1 1 2 1", "7486 3\n3 3 3 2 2 2 2 1 1 1"] | NoteIn the first example, there is only one team with skills $$$[1, 1, 2, 3, 4]$$$ so the answer is $$$3$$$. It can be shown that you cannot achieve a better answer.In the second example, there are two teams with skills $$$[1, 2, 5]$$$ and $$$[12, 13, 15]$$$ so the answer is $$$4 + 3 = 7$$$.In the third example, there are three teams with skills $$$[1, 2, 5]$$$, $$$[129, 185, 581, 1041]$$$ and $$$[1580, 1909, 8150]$$$ so the answer is $$$4 + 912 + 6570 = 7486$$$. | Java 8 | standard input | [
"dp",
"sortings",
"greedy"
] | 9ff029199394c3fa4ced7c65b2827b6c | The first line of the input contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of students. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the programming skill of the $$$i$$$-th student. | 2,000 | In the first line print two integers $$$res$$$ and $$$k$$$ — the minimum total diversity of the division of students and the number of teams in your division, correspondingly. In the second line print $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le k$$$), where $$$t_i$$$ is the number of team to which the $$$i$$$-th student belong. If there are multiple answers, you can print any. Note that you don't need to minimize the number of teams. Each team should consist of at least three students. | standard output | |
PASSED | b471e31c384fe75298486a423ce31603 | train_003.jsonl | 1572873300 | There are $$$n$$$ students at your university. The programming skill of the $$$i$$$-th student is $$$a_i$$$. As a coach, you want to divide them into teams to prepare them for the upcoming ICPC finals. Just imagine how good this university is if it has $$$2 \cdot 10^5$$$ students ready for the finals!Each team should consist of at least three students. Each student should belong to exactly one team. The diversity of a team is the difference between the maximum programming skill of some student that belongs to this team and the minimum programming skill of some student that belongs to this team (in other words, if the team consists of $$$k$$$ students with programming skills $$$a[i_1], a[i_2], \dots, a[i_k]$$$, then the diversity of this team is $$$\max\limits_{j=1}^{k} a[i_j] - \min\limits_{j=1}^{k} a[i_j]$$$).The total diversity is the sum of diversities of all teams formed.Your task is to minimize the total diversity of the division of students and find the optimal way to divide the students. | 256 megabytes |
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.InputMismatchException;
public class E {
private static int n;
private static long[] dp;
private int[][] b;
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
n = in.nextInt();
int[][] b = new int[n][];
for(int i=0; i<n; i++) {
b[i] = new int[] {i, in.nextInt()};
}
Arrays.sort(b, new Comparator<int[]>() {
public int compare(int[] p, int[] q) {
return p[1]-q[1];
}
});
dp = new long[n+1];
dp[n-1] = b[n-1][1];
for(int i=n-2; i>=0; i--) {
long ans = (long)1e16;
if (i+3<=n-1) {
ans = Math.min(b[i][1]-b[i+1][1]+dp[i+3], ans);
}
ans = Math.min(dp[i+1], ans);
dp[i] = ans;
}
w.write(-1*b[0][1]+dp[2]+" ");
int last = 0;
int[] ans = new int[n];
int count = 1;
int i = 2;
while(i<n-1) {
if (dp[i]==dp[i+1]) {
i++;
} else {
for(int j=last; j<=i; j++) {
ans[b[j][0]] = count;
}
count++;
last = i+1;
i+=3;
}
}
if (i==n-1) {
for(int j=last; j<=n-1; j++) {
ans[b[j][0]] = count;
}
}
w.write(count+"\n");
for(int x: ans) {
w.write(x+" ");
}
w.write("\n");
w.close();
}
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
public InputReader(InputStream st) {
this.stream = st;
}
public int read() {
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 = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
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 {
res *= 10;
res += c - '0';
c = read();
} 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 = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
}
//1 1 2 3 4
| Java | ["5\n1 1 3 4 2", "6\n1 5 12 13 2 15", "10\n1 2 5 129 185 581 1041 1909 1580 8150"] | 2 seconds | ["3 1\n1 1 1 1 1", "7 2\n2 2 1 1 2 1", "7486 3\n3 3 3 2 2 2 2 1 1 1"] | NoteIn the first example, there is only one team with skills $$$[1, 1, 2, 3, 4]$$$ so the answer is $$$3$$$. It can be shown that you cannot achieve a better answer.In the second example, there are two teams with skills $$$[1, 2, 5]$$$ and $$$[12, 13, 15]$$$ so the answer is $$$4 + 3 = 7$$$.In the third example, there are three teams with skills $$$[1, 2, 5]$$$, $$$[129, 185, 581, 1041]$$$ and $$$[1580, 1909, 8150]$$$ so the answer is $$$4 + 912 + 6570 = 7486$$$. | Java 8 | standard input | [
"dp",
"sortings",
"greedy"
] | 9ff029199394c3fa4ced7c65b2827b6c | The first line of the input contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of students. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the programming skill of the $$$i$$$-th student. | 2,000 | In the first line print two integers $$$res$$$ and $$$k$$$ — the minimum total diversity of the division of students and the number of teams in your division, correspondingly. In the second line print $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le k$$$), where $$$t_i$$$ is the number of team to which the $$$i$$$-th student belong. If there are multiple answers, you can print any. Note that you don't need to minimize the number of teams. Each team should consist of at least three students. | standard output | |
PASSED | 039192026aaa298ff1f27bfd21588866 | train_003.jsonl | 1572873300 | There are $$$n$$$ students at your university. The programming skill of the $$$i$$$-th student is $$$a_i$$$. As a coach, you want to divide them into teams to prepare them for the upcoming ICPC finals. Just imagine how good this university is if it has $$$2 \cdot 10^5$$$ students ready for the finals!Each team should consist of at least three students. Each student should belong to exactly one team. The diversity of a team is the difference between the maximum programming skill of some student that belongs to this team and the minimum programming skill of some student that belongs to this team (in other words, if the team consists of $$$k$$$ students with programming skills $$$a[i_1], a[i_2], \dots, a[i_k]$$$, then the diversity of this team is $$$\max\limits_{j=1}^{k} a[i_j] - \min\limits_{j=1}^{k} a[i_j]$$$).The total diversity is the sum of diversities of all teams formed.Your task is to minimize the total diversity of the division of students and find the optimal way to divide the students. | 256 megabytes | import java.io.*;
import java.util.*;
public class CF598E {
private static final long MAX_VALUE = 10L * 200000L * 1000000000L;
private static int n;
private static Member[] members;
private static long[] dp = new long[200005];
private static int[] path = new int[200005];
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
n = Integer.parseInt(br.readLine());
members = new Member[n];
String[] inputs = br.readLine().split(" ");
for (int ii = 0; ii < n; ii++) {
members[ii] = new Member(ii, Long.parseLong(inputs[ii]));
}
Arrays.sort(members, new Comparator<Member>() {
public int compare(Member m1, Member m2) {
return Long.compare(m1.skill, m2.skill);
}
});
Arrays.fill(dp, -1);
Arrays.fill(path, -1);
long res = solve(0);
int currentTeam = 1;
int ii = path[0];
for (int jj = 0; jj < n; jj++) {
if (ii != -1 && jj < ii) {
members[jj].team = currentTeam;
} else {
members[jj].team = ++currentTeam;
ii = path[ii];
}
}
Arrays.sort(members, new Comparator<Member>() {
public int compare(Member m1, Member m2) {
return Integer.compare(m1.id, m2.id);
}
});
System.out.println(res + " " + currentTeam);
for (int jj = 0; jj < n; jj++) {
System.out.printf("%d%c", members[jj].team, (jj == n-1) ? '\n' : ' ');
}
}
private static long solve(int ii) {
if (ii == n) dp[ii] = 0L;
else if (ii+2 >= n) dp[ii] = MAX_VALUE;
if (dp[ii] > -1) return dp[ii];
dp[ii] = MAX_VALUE;
int nextii = -1;
for (int jj = ii+3; jj <= Math.min(ii+5, n); jj++) {
long res = members[jj-1].skill - members[ii].skill + solve(jj);
if (res < dp[ii]) {
dp[ii] = res;
nextii = jj;
}
}
path[ii] = nextii;
return dp[ii];
}
private static class Member {
public int id;
public long skill;
public int team;
public Member(int id, long skill) {
this.id = id;
this.skill = skill;
}
}
}
| Java | ["5\n1 1 3 4 2", "6\n1 5 12 13 2 15", "10\n1 2 5 129 185 581 1041 1909 1580 8150"] | 2 seconds | ["3 1\n1 1 1 1 1", "7 2\n2 2 1 1 2 1", "7486 3\n3 3 3 2 2 2 2 1 1 1"] | NoteIn the first example, there is only one team with skills $$$[1, 1, 2, 3, 4]$$$ so the answer is $$$3$$$. It can be shown that you cannot achieve a better answer.In the second example, there are two teams with skills $$$[1, 2, 5]$$$ and $$$[12, 13, 15]$$$ so the answer is $$$4 + 3 = 7$$$.In the third example, there are three teams with skills $$$[1, 2, 5]$$$, $$$[129, 185, 581, 1041]$$$ and $$$[1580, 1909, 8150]$$$ so the answer is $$$4 + 912 + 6570 = 7486$$$. | Java 8 | standard input | [
"dp",
"sortings",
"greedy"
] | 9ff029199394c3fa4ced7c65b2827b6c | The first line of the input contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of students. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the programming skill of the $$$i$$$-th student. | 2,000 | In the first line print two integers $$$res$$$ and $$$k$$$ — the minimum total diversity of the division of students and the number of teams in your division, correspondingly. In the second line print $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le k$$$), where $$$t_i$$$ is the number of team to which the $$$i$$$-th student belong. If there are multiple answers, you can print any. Note that you don't need to minimize the number of teams. Each team should consist of at least three students. | standard output | |
PASSED | 13104b0aee9b500477c64d2d8fb96b69 | train_003.jsonl | 1572873300 | There are $$$n$$$ students at your university. The programming skill of the $$$i$$$-th student is $$$a_i$$$. As a coach, you want to divide them into teams to prepare them for the upcoming ICPC finals. Just imagine how good this university is if it has $$$2 \cdot 10^5$$$ students ready for the finals!Each team should consist of at least three students. Each student should belong to exactly one team. The diversity of a team is the difference between the maximum programming skill of some student that belongs to this team and the minimum programming skill of some student that belongs to this team (in other words, if the team consists of $$$k$$$ students with programming skills $$$a[i_1], a[i_2], \dots, a[i_k]$$$, then the diversity of this team is $$$\max\limits_{j=1}^{k} a[i_j] - \min\limits_{j=1}^{k} a[i_j]$$$).The total diversity is the sum of diversities of all teams formed.Your task is to minimize the total diversity of the division of students and find the optimal way to divide the students. | 256 megabytes | import java.io.*;
import java.util.*;
@SuppressWarnings("unused")
public class Main {
private FastScanner in;
private PrintWriter out;
final int MOD = (int)1e9+7;
long ceil(long a, long b){return (a + b - 1) / b;}
long gcd(long a, long b){return b == 0 ? a : gcd(b, a % b);}
long lcm(long a, long b){return a / gcd(a, b) * b; /*オーバーフローに注意*/}
void solve() {
int n = in.nextInt();
int[][] a = new int[n+1][2];
for(int i = 1; i <= n; i++){
a[i][0] = in.nextInt();
a[i][1] = i;
}
Arrays.sort(a, (e1, e2)->Integer.compare(e1[0], e2[0]));
long[] dp = new long[n+1];
int[] pre = new int[n+1];
Arrays.fill(dp, Long.MAX_VALUE / 2);
dp[0] = 0;
pre[0] = 0;
for(int i = 3; i <= n; i++){
long min = Long.MAX_VALUE;
int idx = -1;
for(int j = i-3; j >= i-5; j--){
if(j <= 2 && j != 0) continue;
long num = dp[j] + a[i][0] - a[j+1][0];
if(min > num){
min = num;
idx = j;
}
}
dp[i] = min;
pre[i] = idx;
}
int idx = n, cnt = 0;
while(true){
//out.println(dp[idx] + " " + pre[idx]);
cnt++;
for(int i = idx; i > pre[idx]; i--) a[i][0] = cnt;
idx = pre[idx];
if(idx == 0) break;
}
Arrays.sort(a, (e1, e2)->Integer.compare(e1[1], e2[1]));
out.println(dp[n] + " " + cnt);
for(int i = 1; i <= n; i++) out.print(a[i][0] + " ");
out.println();
}
//end solve
public static void main(String[] args) {
new Main().m();
}
private void m() {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
/*
try {
String path = "output.txt";
out = new PrintWriter(new BufferedWriter(new FileWriter(new File(path))));
}catch (IOException e){
e.printStackTrace();
}
*/
solve();
out.flush();
in.close();
out.close();
}
static class FastScanner {
private Reader input;
public FastScanner() {this(System.in);}
public FastScanner(InputStream stream) {this.input = new BufferedReader(new InputStreamReader(stream));}
public void close() {
try {
this.input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public int nextInt() {return (int) nextLong();}
public long nextLong() {
try {
int sign = 1;
int b = input.read();
while ((b < '0' || '9' < b) && b != '-' && b != '+') {
b = input.read();
}
if (b == '-') {
sign = -1;
b = input.read();
} else if (b == '+') {
b = input.read();
}
long ret = b - '0';
while (true) {
b = input.read();
if (b < '0' || '9' < b) return ret * sign;
ret *= 10;
ret += b - '0';
}
} catch (IOException e) {
e.printStackTrace();
return -1;
}
}
public double nextDouble() {
try {
double sign = 1;
int b = input.read();
while ((b < '0' || '9' < b) && b != '-' && b != '+') {
b = input.read();
}
if (b == '-') {
sign = -1;
b = input.read();
} else if (b == '+') {
b = input.read();
}
double ret = b - '0';
while (true) {
b = input.read();
if (b < '0' || '9' < b) break;
ret *= 10;
ret += b - '0';
}
if (b != '.') return sign * ret;
double div = 1;
b = input.read();
while ('0' <= b && b <= '9') {
ret *= 10;
ret += b - '0';
div *= 10;
b = input.read();
}
return sign * ret / div;
} catch (IOException e) {
e.printStackTrace();
return Double.NaN;
}
}
public char nextChar() {
try {
int b = input.read();
while (Character.isWhitespace(b)) {
b = input.read();
}
return (char) b;
} catch (IOException e) {
e.printStackTrace();
return 0;
}
}
public String nextStr() {
try {
StringBuilder sb = new StringBuilder();
int b = input.read();
while (Character.isWhitespace(b)) {
b = input.read();
}
while (b != -1 && !Character.isWhitespace(b)) {
sb.append((char) b);
b = input.read();
}
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
public int[] nextIntArray(int n) {
int[] res = new int[n];
for (int i = 0; i < n; i++) {
res[i] = nextInt();
}
return res;
}
public int[] nextIntArrayDec(int n) {
int[] res = new int[n];
for (int i = 0; i < n; i++) {
res[i] = nextInt() - 1;
}
return res;
}
public int[] nextIntArray1Index(int n) {
int[] res = new int[n + 1];
for (int i = 0; i < n; i++) {
res[i + 1] = nextInt();
}
return res;
}
public long[] nextLongArray(int n) {
long[] res = new long[n];
for (int i = 0; i < n; i++) {
res[i] = nextLong();
}
return res;
}
public long[] nextLongArrayDec(int n) {
long[] res = new long[n];
for (int i = 0; i < n; i++) {
res[i] = nextLong() - 1;
}
return res;
}
public long[] nextLongArray1Index(int n) {
long[] res = new long[n + 1];
for (int i = 0; i < n; i++) {
res[i + 1] = nextLong();
}
return res;
}
public double[] nextDoubleArray(int n) {
double[] res = new double[n];
for (int i = 0; i < n; i++) {
res[i] = nextDouble();
}
return res;
}
}
} | Java | ["5\n1 1 3 4 2", "6\n1 5 12 13 2 15", "10\n1 2 5 129 185 581 1041 1909 1580 8150"] | 2 seconds | ["3 1\n1 1 1 1 1", "7 2\n2 2 1 1 2 1", "7486 3\n3 3 3 2 2 2 2 1 1 1"] | NoteIn the first example, there is only one team with skills $$$[1, 1, 2, 3, 4]$$$ so the answer is $$$3$$$. It can be shown that you cannot achieve a better answer.In the second example, there are two teams with skills $$$[1, 2, 5]$$$ and $$$[12, 13, 15]$$$ so the answer is $$$4 + 3 = 7$$$.In the third example, there are three teams with skills $$$[1, 2, 5]$$$, $$$[129, 185, 581, 1041]$$$ and $$$[1580, 1909, 8150]$$$ so the answer is $$$4 + 912 + 6570 = 7486$$$. | Java 8 | standard input | [
"dp",
"sortings",
"greedy"
] | 9ff029199394c3fa4ced7c65b2827b6c | The first line of the input contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of students. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the programming skill of the $$$i$$$-th student. | 2,000 | In the first line print two integers $$$res$$$ and $$$k$$$ — the minimum total diversity of the division of students and the number of teams in your division, correspondingly. In the second line print $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le k$$$), where $$$t_i$$$ is the number of team to which the $$$i$$$-th student belong. If there are multiple answers, you can print any. Note that you don't need to minimize the number of teams. Each team should consist of at least three students. | standard output | |
PASSED | 51e2396ec0d8ac07ceb0b8f090dfc46c | train_003.jsonl | 1572873300 | There are $$$n$$$ students at your university. The programming skill of the $$$i$$$-th student is $$$a_i$$$. As a coach, you want to divide them into teams to prepare them for the upcoming ICPC finals. Just imagine how good this university is if it has $$$2 \cdot 10^5$$$ students ready for the finals!Each team should consist of at least three students. Each student should belong to exactly one team. The diversity of a team is the difference between the maximum programming skill of some student that belongs to this team and the minimum programming skill of some student that belongs to this team (in other words, if the team consists of $$$k$$$ students with programming skills $$$a[i_1], a[i_2], \dots, a[i_k]$$$, then the diversity of this team is $$$\max\limits_{j=1}^{k} a[i_j] - \min\limits_{j=1}^{k} a[i_j]$$$).The total diversity is the sum of diversities of all teams formed.Your task is to minimize the total diversity of the division of students and find the optimal way to divide the students. | 256 megabytes | import java.io.*;
import java.util.*;
@SuppressWarnings("unused")
public class Main {
private FastScanner in;
private PrintWriter out;
final int MOD = (int)1e9+7;
long ceil(long a, long b){return (a + b - 1) / b;}
long gcd(long a, long b){return b == 0 ? a : gcd(b, a % b);}
long lcm(long a, long b){return a / gcd(a, b) * b; /*オーバーフローに注意*/}
void solve() {
int n = in.nextInt();
int[][] a = new int[n+1][2];
for(int i = 1; i <= n; i++){
a[i][0] = in.nextInt();
a[i][1] = i;
}
Arrays.sort(a, (e1, e2)->Integer.compare(e1[0], e2[0]));
SegmentTree seg = new SegmentTree(n+1);
long[] dp = new long[n+1];
int[] pre = new int[n+1];
Arrays.fill(dp, Long.MAX_VALUE / 2);
dp[0] = 0;
pre[0] = 0;
seg.setPoint(0, dp[0] - a[1][0]);
for(int i = 3; i <= n; i++){
SegmentTree.Node res = seg.getSegment(0, i-2);
dp[i] = res.value + a[i][0];
pre[i] = res.index;
if(i < n) seg.setPoint(i, dp[i] - a[i+1][0]);
/*
for(int j = 0; j <= i-3; j++){
dp[i] = Math.min(dp[i], dp[j] + a[i] - a[j+1]);
}
*/
}
int idx = n, cnt = 0;
while(true){
//out.println(dp[idx] + " " + pre[idx]);
cnt++;
for(int i = idx; i > pre[idx]; i--) a[i][0] = cnt;
idx = pre[idx];
if(idx == 0) break;
}
Arrays.sort(a, (e1, e2)->Integer.compare(e1[1], e2[1]));
out.println(dp[n] + " " + cnt);
for(int i = 1; i <= n; i++) out.print(a[i][0] + " ");
out.println();
}
//end solve
class SegmentTree{
public class Node implements Comparable<Node>{
long value;
int index;
public Node(long c, int i){
value = c; index = i;
}
@Override
public int compareTo(Node o) {
return this.value != o.value ? Long.compare(this.value, o.value) : Integer.compare(this.index, o.index);
}
}
int n;
Node[] node;
/*二項演算で使える単位元*/
private long e = Integer.MAX_VALUE;
//private long e = 0;
/*結合律が成り立つ、要素同士の二項演算*/
private Node f(Node e1, Node e2){
//区間最小値、同じ値なら小さいindexを返す
return e1.compareTo(e2) <= 0 ? e1 : e2;
}
/*要素更新用の演算(可換でなくてもよい)*/
private long g(long nodeVal, long val){
return val; //更新
}
/* 単位元で初期化 */
public SegmentTree(int sz){
n = 1;
while(n < sz) n *= 2;
node = new Node[2*n];
for(int i = 0; i < node.length; i++) node[i] = new Node(e, 0);
for(int i = 0; i < sz; i++) {
node[i + n].value = e;
node[i + n].index = i;
}
for(int i = n-1; i > 0; i--) {
node[i] = f(node[2 * i + 0], node[2 * i + 1]);
}
}
/* 元配列vでセグメント木を初期化 */
public SegmentTree(long[] v){
n = 1;
while(n < v.length) n *= 2;
node = new Node[2*n];
for(int i = 0; i < v.length; i++) {
node[i + n].value = v[i];
node[i + n].index = i;
}
for(int i = n-1; i > 0; i--) {
node[i] = f(node[2 * i + 0], node[2 * i + 1]);
}
}
public Node getPoint(int x){
return new Node(node[x + n].value, node[x + n].index);
}
/* 0-indexed:xの要素をg(node[x], val)に更新 */
public void setPoint(int x, long val){
x += n;
node[x].value = g(node[x].value, val);
while(x > 1){
x = x / 2;
node[x] = f(node[2*x+0], node[2*x+1]);
}
}
/* 指定した区間[L,R)の区間演算の結果を求めるクエリ */
public Node getSegment(int L, int R){
L += n;
R += n;
Node resL = new Node(e, 0), resR = new Node(e, 0);
while (L < R) {
if ((L & 1) != 0){
resL = f(resL, node[L]);
L++;
}
if ((R & 1) != 0){
--R;
resR = f(resR, node[R]);
}
L >>= 1;
R >>= 1;
}
Node res = f(resL, resR);
return new Node(res.value, res.index);
}
}
public static void main(String[] args) {
new Main().m();
}
private void m() {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
/*
try {
String path = "output.txt";
out = new PrintWriter(new BufferedWriter(new FileWriter(new File(path))));
}catch (IOException e){
e.printStackTrace();
}
*/
solve();
out.flush();
in.close();
out.close();
}
static class FastScanner {
private Reader input;
public FastScanner() {this(System.in);}
public FastScanner(InputStream stream) {this.input = new BufferedReader(new InputStreamReader(stream));}
public void close() {
try {
this.input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public int nextInt() {return (int) nextLong();}
public long nextLong() {
try {
int sign = 1;
int b = input.read();
while ((b < '0' || '9' < b) && b != '-' && b != '+') {
b = input.read();
}
if (b == '-') {
sign = -1;
b = input.read();
} else if (b == '+') {
b = input.read();
}
long ret = b - '0';
while (true) {
b = input.read();
if (b < '0' || '9' < b) return ret * sign;
ret *= 10;
ret += b - '0';
}
} catch (IOException e) {
e.printStackTrace();
return -1;
}
}
public double nextDouble() {
try {
double sign = 1;
int b = input.read();
while ((b < '0' || '9' < b) && b != '-' && b != '+') {
b = input.read();
}
if (b == '-') {
sign = -1;
b = input.read();
} else if (b == '+') {
b = input.read();
}
double ret = b - '0';
while (true) {
b = input.read();
if (b < '0' || '9' < b) break;
ret *= 10;
ret += b - '0';
}
if (b != '.') return sign * ret;
double div = 1;
b = input.read();
while ('0' <= b && b <= '9') {
ret *= 10;
ret += b - '0';
div *= 10;
b = input.read();
}
return sign * ret / div;
} catch (IOException e) {
e.printStackTrace();
return Double.NaN;
}
}
public char nextChar() {
try {
int b = input.read();
while (Character.isWhitespace(b)) {
b = input.read();
}
return (char) b;
} catch (IOException e) {
e.printStackTrace();
return 0;
}
}
public String nextStr() {
try {
StringBuilder sb = new StringBuilder();
int b = input.read();
while (Character.isWhitespace(b)) {
b = input.read();
}
while (b != -1 && !Character.isWhitespace(b)) {
sb.append((char) b);
b = input.read();
}
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
public int[] nextIntArray(int n) {
int[] res = new int[n];
for (int i = 0; i < n; i++) {
res[i] = nextInt();
}
return res;
}
public int[] nextIntArrayDec(int n) {
int[] res = new int[n];
for (int i = 0; i < n; i++) {
res[i] = nextInt() - 1;
}
return res;
}
public int[] nextIntArray1Index(int n) {
int[] res = new int[n + 1];
for (int i = 0; i < n; i++) {
res[i + 1] = nextInt();
}
return res;
}
public long[] nextLongArray(int n) {
long[] res = new long[n];
for (int i = 0; i < n; i++) {
res[i] = nextLong();
}
return res;
}
public long[] nextLongArrayDec(int n) {
long[] res = new long[n];
for (int i = 0; i < n; i++) {
res[i] = nextLong() - 1;
}
return res;
}
public long[] nextLongArray1Index(int n) {
long[] res = new long[n + 1];
for (int i = 0; i < n; i++) {
res[i + 1] = nextLong();
}
return res;
}
public double[] nextDoubleArray(int n) {
double[] res = new double[n];
for (int i = 0; i < n; i++) {
res[i] = nextDouble();
}
return res;
}
}
} | Java | ["5\n1 1 3 4 2", "6\n1 5 12 13 2 15", "10\n1 2 5 129 185 581 1041 1909 1580 8150"] | 2 seconds | ["3 1\n1 1 1 1 1", "7 2\n2 2 1 1 2 1", "7486 3\n3 3 3 2 2 2 2 1 1 1"] | NoteIn the first example, there is only one team with skills $$$[1, 1, 2, 3, 4]$$$ so the answer is $$$3$$$. It can be shown that you cannot achieve a better answer.In the second example, there are two teams with skills $$$[1, 2, 5]$$$ and $$$[12, 13, 15]$$$ so the answer is $$$4 + 3 = 7$$$.In the third example, there are three teams with skills $$$[1, 2, 5]$$$, $$$[129, 185, 581, 1041]$$$ and $$$[1580, 1909, 8150]$$$ so the answer is $$$4 + 912 + 6570 = 7486$$$. | Java 8 | standard input | [
"dp",
"sortings",
"greedy"
] | 9ff029199394c3fa4ced7c65b2827b6c | The first line of the input contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of students. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the programming skill of the $$$i$$$-th student. | 2,000 | In the first line print two integers $$$res$$$ and $$$k$$$ — the minimum total diversity of the division of students and the number of teams in your division, correspondingly. In the second line print $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le k$$$), where $$$t_i$$$ is the number of team to which the $$$i$$$-th student belong. If there are multiple answers, you can print any. Note that you don't need to minimize the number of teams. Each team should consist of at least three students. | standard output | |
PASSED | 4616bddf7092bae6a5ae4ad96623681f | train_003.jsonl | 1572873300 | There are $$$n$$$ students at your university. The programming skill of the $$$i$$$-th student is $$$a_i$$$. As a coach, you want to divide them into teams to prepare them for the upcoming ICPC finals. Just imagine how good this university is if it has $$$2 \cdot 10^5$$$ students ready for the finals!Each team should consist of at least three students. Each student should belong to exactly one team. The diversity of a team is the difference between the maximum programming skill of some student that belongs to this team and the minimum programming skill of some student that belongs to this team (in other words, if the team consists of $$$k$$$ students with programming skills $$$a[i_1], a[i_2], \dots, a[i_k]$$$, then the diversity of this team is $$$\max\limits_{j=1}^{k} a[i_j] - \min\limits_{j=1}^{k} a[i_j]$$$).The total diversity is the sum of diversities of all teams formed.Your task is to minimize the total diversity of the division of students and find the optimal way to divide the students. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
public static int log(int x){
int c =0;
while(x>0){
x/=2;
c++;
}
c--;
return c;
}
static int pow(int a, int b){
int l =1;
for(int i=0; i<b; i++){
l*=a;
}
return l;
}
static int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static int lcm(int a, int b)
{
return (a*b)/gcd(a, b);
}
static int claculate(int n)
{
// calculate 2^(n+1)
int sum = (1 << (n + 1));
return sum - 1;
}
static class pair implements Comparable<pair>{
int x;
int y;
public pair(int x, int y){
this.x=x;
this.y=y;
}
public int compareTo(pair p){
return x-p.x;
}
}
static pair [] arr ;
static int dp[];
static int res[];
public static int solve(int idx){
if(idx>=arr.length){
return 0;
}
if(dp[idx]!=-1){
return dp[idx];
}
int take1;int take2;int take3;
if(idx+3<=arr.length)
take1 = solve(idx+3)+arr[idx+2].x-arr[idx].x;
else take1 =(int) 1e9;
if(idx+4<=arr.length)
take2 = solve(idx+4)+arr[idx+3].x-arr[idx].x;
else take2 =(int) 1e9;
if(idx+5<=arr.length)
take3 = solve(idx+5)+arr[idx+4].x-arr[idx].x;
else take3 =(int) 1e9;
return dp[idx] = Math.min(take1,Math.min(take2,take3));
}
public static void trace(int idx,int num){
if(idx+3<=arr.length&&dp[idx]==solve(idx+3)+arr[idx+2].x-arr[idx].x){
for(int i=idx;i<=idx+2; i++ ){
res[i] = num;
}
trace(idx+3,++num);
}
else if(idx+4<=arr.length&&dp[idx]==solve(idx+4)+arr[idx+3].x-arr[idx].x){
for(int i=idx;i<=idx+3; i++ ){
res[i] = num;
}
trace(idx+4,++num);
}
else if(idx+5<=arr.length&&dp[idx]==solve(idx+5)+arr[idx+4].x-arr[idx].x){
for(int i=idx;i<=idx+4; i++ ){
res[i] = num;
}
trace(idx+5,++num);
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
// String s = br.readLine();
// char[] arr=s.toCharArray();
// ArrayList<Integer> arrl = new ArrayList<Integer>();
// TreeSet<Integer> ts1 = new TreeSet<Integer>();
// HashSet<Integer> h = new HashSet<Integer>();
// HashMap<Integer, Integer> map= new HashMap<>();
// PriorityQueue<String> pQueue = new PriorityQueue<String>();
// LinkedList<String> object = new LinkedList<String>();
// StringBuilder str = new StringBuilder();
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
arr = new pair[n];
st = new StringTokenizer(br.readLine());
for(int i=0; i<n; i++){
int x = Integer.parseInt(st.nextToken());
arr[i] = new pair(x,i);
}
Arrays.sort(arr);
dp = new int[n];
Arrays.fill(dp,-1);
int ans =solve(0);
res = new int [n];
trace(0,1);
int max = res[n-1];
// Arrays.sort(arr,(a,b)->a.y-b.y);
out.println(ans+" "+ max);
int [] res2 = new int[n];
for(int i=0; i<n; i++) {res2[arr[i].y]=res[i];}
for(int i=0; i<n; i++){
out.print(res2[i]+" ");
}
out.println();
out.flush();
}
} | Java | ["5\n1 1 3 4 2", "6\n1 5 12 13 2 15", "10\n1 2 5 129 185 581 1041 1909 1580 8150"] | 2 seconds | ["3 1\n1 1 1 1 1", "7 2\n2 2 1 1 2 1", "7486 3\n3 3 3 2 2 2 2 1 1 1"] | NoteIn the first example, there is only one team with skills $$$[1, 1, 2, 3, 4]$$$ so the answer is $$$3$$$. It can be shown that you cannot achieve a better answer.In the second example, there are two teams with skills $$$[1, 2, 5]$$$ and $$$[12, 13, 15]$$$ so the answer is $$$4 + 3 = 7$$$.In the third example, there are three teams with skills $$$[1, 2, 5]$$$, $$$[129, 185, 581, 1041]$$$ and $$$[1580, 1909, 8150]$$$ so the answer is $$$4 + 912 + 6570 = 7486$$$. | Java 8 | standard input | [
"dp",
"sortings",
"greedy"
] | 9ff029199394c3fa4ced7c65b2827b6c | The first line of the input contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of students. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the programming skill of the $$$i$$$-th student. | 2,000 | In the first line print two integers $$$res$$$ and $$$k$$$ — the minimum total diversity of the division of students and the number of teams in your division, correspondingly. In the second line print $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le k$$$), where $$$t_i$$$ is the number of team to which the $$$i$$$-th student belong. If there are multiple answers, you can print any. Note that you don't need to minimize the number of teams. Each team should consist of at least three students. | standard output | |
PASSED | fb0c858a9eeb3bc20e5f34cd2d7f8be1 | train_003.jsonl | 1572873300 | There are $$$n$$$ students at your university. The programming skill of the $$$i$$$-th student is $$$a_i$$$. As a coach, you want to divide them into teams to prepare them for the upcoming ICPC finals. Just imagine how good this university is if it has $$$2 \cdot 10^5$$$ students ready for the finals!Each team should consist of at least three students. Each student should belong to exactly one team. The diversity of a team is the difference between the maximum programming skill of some student that belongs to this team and the minimum programming skill of some student that belongs to this team (in other words, if the team consists of $$$k$$$ students with programming skills $$$a[i_1], a[i_2], \dots, a[i_k]$$$, then the diversity of this team is $$$\max\limits_{j=1}^{k} a[i_j] - \min\limits_{j=1}^{k} a[i_j]$$$).The total diversity is the sum of diversities of all teams formed.Your task is to minimize the total diversity of the division of students and find the optimal way to divide the students. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
static InputReader in = new InputReader(System.in);
static PrintWriter out = new PrintWriter(System.out);
// static int oo = (int)1e9;
static long oo = (long)1e15;
static int mod = 1_000_000_007;
static int[] di = {1, 0, 0, -1};
static int[] dj = {0, -1, 1, 0};
static int M = 5005;
static double EPS = 1e-5;
public static void main(String[] args) throws IOException {
int n = in.nextInt();
Pair[] p = new Pair[n];
for(int i = 0; i < n; ++i) {
p[i] = new Pair(in.nextInt(), i);
}
shuffle(p);
Arrays.parallelSort(p);
long[] dp = new long[n];
Arrays.fill(dp, oo);
for(int i = 2; i < n; ++i) {
for(int j = i - 2, b = i - 4; j >= 0 && j >= b; --j) {
dp[i] = Math.min(dp[i], p[i].first - p[j].first + (j == 0 ? 0 : dp[j-1]) );
}
}
int[] ans = new int[n];
int team = 0;
for(int i = n-1; i >= 0; ) {
for(int j = i - 2, b = i - 4; j >= 0 && j >= b; --j) {
if(dp[i] == p[i].first - p[j].first + (j == 0 ? 0 : dp[j-1])) {
team++;
for(int k = j; k <= i; ++k)
ans[p[k].second] = team;
i = j - 1;
break;
}
}
}
System.out.println(dp[n-1] + " " + team);
for(int x : ans)
System.out.print(x + " ");
out.close();
}
static int solve(int[] a, int[] next, int i, int j) {
if(i >= j)
return 0;
int k = next[i];
if(k > j)
return solve(a, next, i+1, j) + 1;
return solve(a, next, i+1, k-1) + 1 + solve(a, next, k, j);
}
static boolean inside(int i, int j, int n, int m) {
return i >= 0 && i < n && j >= 0 && j < m;
}
static long pow(long a, long n, long mod) {
if(n == 0)
return 1;
if(n % 2 == 1)
return a * pow(a, n-1, mod) % mod;
long x = pow(a, n / 2, mod);
return x * x % mod;
}
static class SegmentTree {
int n;
int[] a;
int[] seg;
int DEFAULT_VALUE = 0;
public SegmentTree(int[] a, int n) {
super();
this.a = a;
this.n = n;
seg = new int[n * 4 + 1];
build(1, 0, n-1);
}
private int build(int node, int i, int j) {
if(i == j) {
return seg[node] = a[i];
}
int first = build(node * 2, i, (i+j) / 2);
int second = build(node * 2 + 1, (i+j) / 2 + 1, j);
return seg[node] = combine(first, second);
}
int update(int k, char value) {
return update(1, 0, n-1, k, value);
}
private int update(int node, int i, int j, int k, char value) {
if(k < i || k > j)
return seg[node];
if(i == j && j == k) {
a[k] = value;
return seg[node] = value;
}
int m = (i + j) / 2;
int first = update(node * 2, i, m, k, value);
int second = update(node * 2 + 1, m + 1, j, k, value);
return seg[node] = combine(first, second);
}
int query(int l, int r) {
return query(1, 0, n-1, l, r);
}
private int query(int node, int i, int j, int l, int r) {
if(l <= i && j <= r)
return seg[node];
if(j < l || i > r)
return DEFAULT_VALUE;
int m = (i + j) / 2;
int first = query(node * 2, i, m, l, r);
int second = query(node * 2 + 1, m+1, j, l, r);
return combine(first, second);
}
private int combine(int a, int b) {
return Math.max(a, b);
}
}
static class DisjointSet {
int n;
int[] g;
int[] h;
public DisjointSet(int n) {
super();
this.n = n;
g = new int[n];
h = new int[n];
for(int i = 0; i < n; ++i) {
g[i] = i;
h[i] = 1;
}
}
int find(int x) {
if(g[x] == x)
return x;
return g[x] = find(g[x]);
}
void union(int x, int y) {
x = find(x); y = find(y);
if(x == y)
return;
if(h[x] >= h[y]) {
g[y] = x;
if(h[x] == h[y])
h[x]++;
}
else {
g[x] = y;
}
}
}
static int[] getPi(char[] a) {
int m = a.length;
int j = 0;
int[] pi = new int[m];
for(int i = 1; i < m; ++i) {
while(j > 0 && a[i] != a[j])
j = pi[j-1];
if(a[i] == a[j]) {
pi[i] = j + 1;
j++;
}
}
return pi;
}
static long lcm(long a, long b) {
return a * b / gcd(a, b);
}
static boolean nextPermutation(int[] a) {
for(int i = a.length - 2; i >= 0; --i) {
if(a[i] < a[i+1]) {
for(int j = a.length - 1; ; --j) {
if(a[i] < a[j]) {
int t = a[i];
a[i] = a[j];
a[j] = t;
for(i++, j = a.length - 1; i < j; ++i, --j) {
t = a[i];
a[i] = a[j];
a[j] = t;
}
return true;
}
}
}
}
return false;
}
static void shuffle(Object[] a) {
Random r = new Random();
for(int i = a.length - 1; i > 0; --i) {
int si = r.nextInt(i);
Object t = a[si];
a[si] = a[i];
a[i] = t;
}
}
static void shuffle(int[] a) {
Random r = new Random();
for(int i = a.length - 1; i > 0; --i) {
int si = r.nextInt(i);
int t = a[si];
a[si] = a[i];
a[i] = t;
}
}
static void shuffle(long[] a) {
Random r = new Random();
for(int i = a.length - 1; i > 0; --i) {
int si = r.nextInt(i);
long t = a[si];
a[si] = a[i];
a[i] = t;
}
}
static int lower_bound(int[] a, int n, int k) {
int s = 0;
int e = n;
int m;
while (e - s > 0) {
m = (s + e) / 2;
if (a[m] < k)
s = m + 1;
else
e = m;
}
return e;
}
static int lower_bound(long[] a, int n, long k) {
int s = 0;
int e = n;
int m;
while (e - s > 0) {
m = (s + e) / 2;
if (a[m] < k)
s = m + 1;
else
e = m;
}
return e;
}
static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
static long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
static class Pair implements Comparable<Pair> {
int first, second;
public Pair(int first, int second) {
super();
this.first = first;
this.second = second;
}
@Override
public int compareTo(Pair o) {
return this.first != o.first ? this.first - o.first : this.second - o.second;
}
// @Override
// public int compareTo(Pair o) {
// return this.first != o.first ? o.first - this.first : o.second - this.second;
// }
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + first;
result = prime * result + second;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Pair other = (Pair) obj;
if (first != other.first)
return false;
if (second != other.second)
return false;
return true;
}
}
}
class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
public InputReader(InputStream st) {
this.stream = st;
}
public int read() {
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 = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
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 {
res *= 10;
res += c - '0';
c = read();
} 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 = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
} | Java | ["5\n1 1 3 4 2", "6\n1 5 12 13 2 15", "10\n1 2 5 129 185 581 1041 1909 1580 8150"] | 2 seconds | ["3 1\n1 1 1 1 1", "7 2\n2 2 1 1 2 1", "7486 3\n3 3 3 2 2 2 2 1 1 1"] | NoteIn the first example, there is only one team with skills $$$[1, 1, 2, 3, 4]$$$ so the answer is $$$3$$$. It can be shown that you cannot achieve a better answer.In the second example, there are two teams with skills $$$[1, 2, 5]$$$ and $$$[12, 13, 15]$$$ so the answer is $$$4 + 3 = 7$$$.In the third example, there are three teams with skills $$$[1, 2, 5]$$$, $$$[129, 185, 581, 1041]$$$ and $$$[1580, 1909, 8150]$$$ so the answer is $$$4 + 912 + 6570 = 7486$$$. | Java 8 | standard input | [
"dp",
"sortings",
"greedy"
] | 9ff029199394c3fa4ced7c65b2827b6c | The first line of the input contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of students. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the programming skill of the $$$i$$$-th student. | 2,000 | In the first line print two integers $$$res$$$ and $$$k$$$ — the minimum total diversity of the division of students and the number of teams in your division, correspondingly. In the second line print $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le k$$$), where $$$t_i$$$ is the number of team to which the $$$i$$$-th student belong. If there are multiple answers, you can print any. Note that you don't need to minimize the number of teams. Each team should consist of at least three students. | standard output | |
PASSED | 1f7543fca02f1dd49bea523eab69594b | train_003.jsonl | 1572873300 | There are $$$n$$$ students at your university. The programming skill of the $$$i$$$-th student is $$$a_i$$$. As a coach, you want to divide them into teams to prepare them for the upcoming ICPC finals. Just imagine how good this university is if it has $$$2 \cdot 10^5$$$ students ready for the finals!Each team should consist of at least three students. Each student should belong to exactly one team. The diversity of a team is the difference between the maximum programming skill of some student that belongs to this team and the minimum programming skill of some student that belongs to this team (in other words, if the team consists of $$$k$$$ students with programming skills $$$a[i_1], a[i_2], \dots, a[i_k]$$$, then the diversity of this team is $$$\max\limits_{j=1}^{k} a[i_j] - \min\limits_{j=1}^{k} a[i_j]$$$).The total diversity is the sum of diversities of all teams formed.Your task is to minimize the total diversity of the division of students and find the optimal way to divide the students. | 256 megabytes | import java.util.*;
import java.io.*;
public class A
{
public static void main(String ar[]) throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(br.readLine());
String s1[]=br.readLine().split(" ");
Integer a1[][]=new Integer[n][2];
Integer a[]=new Integer[n];
for(int i=0;i<n;i++)
{ a[i]=Integer.parseInt(s1[i]); a1[i][0]=a[i]; a1[i][1]=i; }
Arrays.sort(a);
Arrays.sort(a1,new Comparator<Integer[]>(){
public int compare(final Integer f1[],final Integer f2[])
{
return f1[0].compareTo(f2[0]);
}
});
long dp[][]=new long[n+1][6];
int b[][]=new int[n+1][6];
for(int i=1;i<=n;i++)
{
for(int j=0;j<=5;j++)
{
dp[i][j]=Long.MAX_VALUE;
b[i][j]=Integer.MAX_VALUE;
}
}
for(int i=2;i<n;i++)
{
long min=Long.MAX_VALUE;
if(i>=2)
{
int min1=-1;
for(int j=3;j<=5;j++)
{
if(min>dp[i-2][j])
{ min=dp[i-2][j]; min1=b[i-2][j]; }
}
if(min!=Long.MAX_VALUE)
{
dp[i+1][3]=min+a[i]-a[i-2];
b[i+1][3]=1+min1;
}
}
if(i>=3)
{
min=Long.MAX_VALUE;
int min1=-1;
for(int j=3;j<=5;j++)
{
if(min>dp[i-3][j])
{ min=dp[i-3][j]; min1=b[i-3][j]; }
}
if(min!=Long.MAX_VALUE)
{
dp[i+1][4]=min+a[i]-a[i-3];
b[i+1][4]=1+min1;
}
}
if(i>=4)
{
min=Long.MAX_VALUE;
int min1=-1;
for(int j=3;j<=5;j++)
{
if(min>dp[i-4][j])
{ min=dp[i-4][j]; min1=b[i-4][j]; }
}
if(min!=Long.MAX_VALUE)
{
dp[i+1][5]=min+a[i]-a[i-4];
b[i+1][5]=1+min1;
}
}
}
int p=0;
long min=Math.min(dp[n][3],dp[n][4]);
min=Math.min(min,dp[n][5]);
if(min==dp[n][3])
{ p=b[n][3]; }
else if(min==dp[n][4])
{ p=b[n][4]; }
else
{ p=b[n][5]; }
System.out.println(min+" "+p);
int d[]=new int[n];
int u=n;
while(u>=1)
{
min=Math.min(dp[u][3],dp[u][4]);
min=Math.min(min,dp[u][5]);
int t=0;
if(min==dp[u][3])
{ t=3; }
else if(min==dp[u][4])
{ t=4; }
else
{ t=5; }
int v=u;
while(v>=1 && v>u-t)
{ d[a1[v-1][1]]=p; v--; }
p--;
u=v;
}
StringBuffer sb=new StringBuffer();
for(int i=0;i<n;i++)
sb.append(d[i]).append(" ");
System.out.println(sb);
}
} | Java | ["5\n1 1 3 4 2", "6\n1 5 12 13 2 15", "10\n1 2 5 129 185 581 1041 1909 1580 8150"] | 2 seconds | ["3 1\n1 1 1 1 1", "7 2\n2 2 1 1 2 1", "7486 3\n3 3 3 2 2 2 2 1 1 1"] | NoteIn the first example, there is only one team with skills $$$[1, 1, 2, 3, 4]$$$ so the answer is $$$3$$$. It can be shown that you cannot achieve a better answer.In the second example, there are two teams with skills $$$[1, 2, 5]$$$ and $$$[12, 13, 15]$$$ so the answer is $$$4 + 3 = 7$$$.In the third example, there are three teams with skills $$$[1, 2, 5]$$$, $$$[129, 185, 581, 1041]$$$ and $$$[1580, 1909, 8150]$$$ so the answer is $$$4 + 912 + 6570 = 7486$$$. | Java 8 | standard input | [
"dp",
"sortings",
"greedy"
] | 9ff029199394c3fa4ced7c65b2827b6c | The first line of the input contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of students. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the programming skill of the $$$i$$$-th student. | 2,000 | In the first line print two integers $$$res$$$ and $$$k$$$ — the minimum total diversity of the division of students and the number of teams in your division, correspondingly. In the second line print $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le k$$$), where $$$t_i$$$ is the number of team to which the $$$i$$$-th student belong. If there are multiple answers, you can print any. Note that you don't need to minimize the number of teams. Each team should consist of at least three students. | standard output | |
PASSED | 3f004bae909721cc05093d465b29485c | train_003.jsonl | 1572873300 | There are $$$n$$$ students at your university. The programming skill of the $$$i$$$-th student is $$$a_i$$$. As a coach, you want to divide them into teams to prepare them for the upcoming ICPC finals. Just imagine how good this university is if it has $$$2 \cdot 10^5$$$ students ready for the finals!Each team should consist of at least three students. Each student should belong to exactly one team. The diversity of a team is the difference between the maximum programming skill of some student that belongs to this team and the minimum programming skill of some student that belongs to this team (in other words, if the team consists of $$$k$$$ students with programming skills $$$a[i_1], a[i_2], \dots, a[i_k]$$$, then the diversity of this team is $$$\max\limits_{j=1}^{k} a[i_j] - \min\limits_{j=1}^{k} a[i_j]$$$).The total diversity is the sum of diversities of all teams formed.Your task is to minimize the total diversity of the division of students and find the optimal way to divide the students. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author htvu
*/
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);
EYetAnotherDivisionIntoTeams solver = new EYetAnotherDivisionIntoTeams();
solver.solve(1, in, out);
out.close();
}
static class EYetAnotherDivisionIntoTeams {
Pair.LongPair[] a;
long[] dp;
int[] pre;
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
a = new Pair.LongPair[n + 1];
for (int i = 1; i <= n; ++i)
a[i] = new Pair.LongPair(in.nextLong(), (long) i);
Arrays.sort(a, 1, n + 1);
dp = new long[n + 1];
pre = new int[n + 1];
long INF = (long) 1e9 * n;
Arrays.fill(dp, INF);
dp[0] = 0;
for (int i = 3; i <= n; ++i) {
imin(i, i - 3);
if (i >= 4)
imin(i, i - 4);
if (i >= 5)
imin(i, i - 5);
}
int cur = n, numTeam = 0;
int[] team = new int[n + 1];
while (cur > 0) {
numTeam++;
int prev = pre[cur];
for (int i = prev + 1; i <= cur; ++i) {
team[a[i].second.intValue()] = numTeam;
}
cur = prev;
}
out.println(dp[n] + " " + numTeam);
for (int i = 1; i <= n; ++i)
out.print(team[i] + " ");
}
void imin(int i, int j) {
if (dp[i] > dp[j] + a[i].first - a[j + 1].first) {
dp[i] = dp[j] + a[i].first - a[j + 1].first;
pre[i] = j;
}
}
}
static class Pair<A extends Comparable<A>, B extends Comparable<B>> implements Comparable<Pair<A, B>> {
public A first;
public B second;
public Pair(A a, B b) {
this.first = a;
this.second = b;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair<?, ?> pair = (Pair<?, ?>) o;
return first.equals(pair.first) &&
second.equals(pair.second);
}
public int hashCode() {
return (first == null ? 0 : first.hashCode()) ^
(second == null ? 0 : second.hashCode());
}
public String toString() {
return "{" + first + "," + second + '}';
}
public int compareTo(Pair<A, B> o) {
int c = first.compareTo(o.first);
if (c != 0) return c;
return second.compareTo(o.second);
}
public static class LongPair extends Pair<Long, Long> {
public LongPair(Long aLong, Long aLong2) {
super(aLong, aLong2);
}
}
}
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());
}
}
}
| Java | ["5\n1 1 3 4 2", "6\n1 5 12 13 2 15", "10\n1 2 5 129 185 581 1041 1909 1580 8150"] | 2 seconds | ["3 1\n1 1 1 1 1", "7 2\n2 2 1 1 2 1", "7486 3\n3 3 3 2 2 2 2 1 1 1"] | NoteIn the first example, there is only one team with skills $$$[1, 1, 2, 3, 4]$$$ so the answer is $$$3$$$. It can be shown that you cannot achieve a better answer.In the second example, there are two teams with skills $$$[1, 2, 5]$$$ and $$$[12, 13, 15]$$$ so the answer is $$$4 + 3 = 7$$$.In the third example, there are three teams with skills $$$[1, 2, 5]$$$, $$$[129, 185, 581, 1041]$$$ and $$$[1580, 1909, 8150]$$$ so the answer is $$$4 + 912 + 6570 = 7486$$$. | Java 8 | standard input | [
"dp",
"sortings",
"greedy"
] | 9ff029199394c3fa4ced7c65b2827b6c | The first line of the input contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of students. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the programming skill of the $$$i$$$-th student. | 2,000 | In the first line print two integers $$$res$$$ and $$$k$$$ — the minimum total diversity of the division of students and the number of teams in your division, correspondingly. In the second line print $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le k$$$), where $$$t_i$$$ is the number of team to which the $$$i$$$-th student belong. If there are multiple answers, you can print any. Note that you don't need to minimize the number of teams. Each team should consist of at least three students. | standard output | |
PASSED | d5d5a301a7b8bf87ae91ab8ab1d12bd4 | train_003.jsonl | 1572873300 | There are $$$n$$$ students at your university. The programming skill of the $$$i$$$-th student is $$$a_i$$$. As a coach, you want to divide them into teams to prepare them for the upcoming ICPC finals. Just imagine how good this university is if it has $$$2 \cdot 10^5$$$ students ready for the finals!Each team should consist of at least three students. Each student should belong to exactly one team. The diversity of a team is the difference between the maximum programming skill of some student that belongs to this team and the minimum programming skill of some student that belongs to this team (in other words, if the team consists of $$$k$$$ students with programming skills $$$a[i_1], a[i_2], \dots, a[i_k]$$$, then the diversity of this team is $$$\max\limits_{j=1}^{k} a[i_j] - \min\limits_{j=1}^{k} a[i_j]$$$).The total diversity is the sum of diversities of all teams formed.Your task is to minimize the total diversity of the division of students and find the optimal way to divide the students. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.util.Comparator;
import java.util.Collections;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskE solver = new TaskE();
solver.solve(1, in, out);
out.close();
}
static class TaskE {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int N = in.nextInt();
int[] dp = new int[N];
int[] diff = new int[N];
ArrayList<Student> arr = new ArrayList<>();
long sum = 0;
for (int i = 0; i < N; i++) {
arr.add(new Student(i, in.nextInt()));
}
Collections.sort(arr, new Comparator<Student>() {
public int compare(Student student, Student t1) {
return Integer.compare(student.c, t1.c);
}
});
for (int i = 1; i < N; i++) {
diff[i] = arr.get(i).c - arr.get(i - 1).c;
}
sum = arr.get(arr.size() - 1).c - arr.get(0).c;
dp[0] = 0;
dp[1] = 0;
dp[2] = 0;
ArrayList<Integer>[] store = new ArrayList[N];
store[0] = new ArrayList<>();
store[1] = new ArrayList<>();
store[2] = new ArrayList<>();
store[0].add(0);
store[1].add(0);
store[2].add(0);
int[] par = new int[N];
int[] at = new int[N];
for (int i = 3; i <= N - 3; i++) {
if (dp[i - 1] > dp[i - 3] + diff[i]) {
dp[i] = dp[i - 1];
at[i] = at[i - 1];
par[i] = par[i - 1];
// store[i] = (ArrayList<Integer>) store[i-1].clone();
} else {
// store[i] = store[i - 3];
// store[i].add(i);
dp[i] = dp[i - 3] + diff[i];
at[i] = i;
par[i] = i - 3;
}
}
int[] res = new int[N];
int last = N;
int u = at[N - 3];
int id = 1;
while (true) {
for (int i = u; i < last; i++) {
res[arr.get(i).id] = id;
}
if (u == par[u]) {
break;
}
last = u;
u = at[par[u]];
id++;
}
out.println(sum - dp[N - 3] + " " + id);
for (int val : res) {
out.print(val + " ");
}
}
class Student {
int id;
int c;
Student(int id, int c) {
this.id = id;
this.c = c;
}
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["5\n1 1 3 4 2", "6\n1 5 12 13 2 15", "10\n1 2 5 129 185 581 1041 1909 1580 8150"] | 2 seconds | ["3 1\n1 1 1 1 1", "7 2\n2 2 1 1 2 1", "7486 3\n3 3 3 2 2 2 2 1 1 1"] | NoteIn the first example, there is only one team with skills $$$[1, 1, 2, 3, 4]$$$ so the answer is $$$3$$$. It can be shown that you cannot achieve a better answer.In the second example, there are two teams with skills $$$[1, 2, 5]$$$ and $$$[12, 13, 15]$$$ so the answer is $$$4 + 3 = 7$$$.In the third example, there are three teams with skills $$$[1, 2, 5]$$$, $$$[129, 185, 581, 1041]$$$ and $$$[1580, 1909, 8150]$$$ so the answer is $$$4 + 912 + 6570 = 7486$$$. | Java 8 | standard input | [
"dp",
"sortings",
"greedy"
] | 9ff029199394c3fa4ced7c65b2827b6c | The first line of the input contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of students. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the programming skill of the $$$i$$$-th student. | 2,000 | In the first line print two integers $$$res$$$ and $$$k$$$ — the minimum total diversity of the division of students and the number of teams in your division, correspondingly. In the second line print $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le k$$$), where $$$t_i$$$ is the number of team to which the $$$i$$$-th student belong. If there are multiple answers, you can print any. Note that you don't need to minimize the number of teams. Each team should consist of at least three students. | standard output | |
PASSED | 5ecffe7dd49acff384b79609150c8fa1 | train_003.jsonl | 1572873300 | There are $$$n$$$ students at your university. The programming skill of the $$$i$$$-th student is $$$a_i$$$. As a coach, you want to divide them into teams to prepare them for the upcoming ICPC finals. Just imagine how good this university is if it has $$$2 \cdot 10^5$$$ students ready for the finals!Each team should consist of at least three students. Each student should belong to exactly one team. The diversity of a team is the difference between the maximum programming skill of some student that belongs to this team and the minimum programming skill of some student that belongs to this team (in other words, if the team consists of $$$k$$$ students with programming skills $$$a[i_1], a[i_2], \dots, a[i_k]$$$, then the diversity of this team is $$$\max\limits_{j=1}^{k} a[i_j] - \min\limits_{j=1}^{k} a[i_j]$$$).The total diversity is the sum of diversities of all teams formed.Your task is to minimize the total diversity of the division of students and find the optimal way to divide the students. | 256 megabytes | import java.awt.event.MouseAdapter;
import java.io.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
new Main().run();
}
static int groups = 0;
static int[] fa;
static int[] sz;
static void init1(int n) {
groups = n;
fa = new int[n];
for (int i = 1; i < n; ++i) {
fa[i] = i;
}
sz = new int[n];
Arrays.fill(sz, 1);
}
static int root(int p) {
while (p != fa[p]) {
fa[p] = fa[fa[p]];
p = fa[p];
}
return p;
}
static void combine(int p, int q) {
int i = root(p);
int j = root(q);
if (i == j) {
return;
}
fa[i] = j;
if (sz[i] < sz[j]) {
fa[i] = j;
sz[j] += sz[i];
} else {
fa[j] = i;
sz[i] += sz[j];
}
groups--;
}
public static String roundS(double result, int scale) {
String fmt = String.format("%%.%df", scale);
return String.format(fmt, result);
}
int[] unique(int a[]) {
int p = 1;
for (int i = 1; i < a.length; ++i) {
if (a[i] != a[i - 1]) {
a[p++] = a[i];
}
}
return Arrays.copyOf(a, p);
}
public static int bigger(long[] a, long key) {
return bigger(a, 0, a.length, key);
}
public static int bigger(long[] a, int lo, int hi,
long key) {
while (lo < hi) {
int mid = (lo + hi) >>> 1;
if (a[mid] > key) {
hi = mid;
} else {
lo = mid + 1;
}
}
return lo;
}
static int h[];
static int to[];
static int ne[];
static int m = 0;
public static void addEdge(int u, int v, int w) {
to[++m] = v;
ne[m] = h[u];
h[u] = m;
}
int w[];
int cc = 0;
void add(int u, int v, int ww) {
to[++cc] = u;
w[cc] = ww;
ne[cc] = h[v];
h[v] = cc;
to[++cc] = v;
w[cc] = ww;
ne[cc] = h[u];
h[u] = cc;
}
// List<int[]> li = new ArrayList<>();
//
// void go(int j){
// d[j] = l[j] = ++N;
// int cd = 0;
// for(int i=h[j];i!=0;i= ne[i]){
// int v= to[i];
// if(d[v]==0){
// fa[v] = j;
// cd++;
// go(v);
// l[j] = Math.min(l[j],l[v]);
// if(d[j]<=l[v]){
// cut[j] = true;
// }
// if(d[j]<l[v]){
// int ma = Math.max(j,v);
// int mi = Math.min(j,v);
// li.add(new int[]{mi,ma});
// }
// }else if(fa[j]!=v){
// l[j] = Math.min(l[j],d[v]);
// }
// }
// if(fa[j]==-1&&cd==1){
// cut[j] = false;
// }
// if (l[j] == d[j]) {
// while(p>0){
// mk[stk[p-1]] = id;
// }
// id++;
// }
// }
// int mk[];
// int id= 0;
// int l[];
// boolean cut[];
// int p = 0;
// int d[];int N = 0;
// int stk[];
static class S {
int l = 0;
int r = 0;
int miss = 0;
int cnt = 0;
int c = 0;
public S(int l, int r) {
this.l = l;
this.r = r;
}
}
static S a[];
static int[] o;
static void init11(int[] f) {
o = f;
int len = o.length;
a = new S[len * 4];
build1(1, 0, len - 1);
}
static void build1(int num, int l, int r) {
S cur = new S(l, r);
if (l == r) {
cur.c = o[l];
a[num] = cur;
return;
} else {
int m = (l + r) >> 1;
int le = num << 1;
int ri = le | 1;
build1(le, l, m);
build1(ri, m + 1, r);
a[num] = cur;
pushup(num, le, ri);
}
}
static int query1(int num, int l, int r) {
if (a[num].l >= l && a[num].r <= r) {
return a[num].c;
} else {
int m = (a[num].l + a[num].r) >> 1;
int le = num << 1;
int ri = le | 1;
int mi = -1;
if (r > m) {
int res = query1(ri, l, r);
mi = Math.max(mi, res);
}
if (l <= m) {
int res = query1(le, l, r);
mi = Math.max(mi, res);
}
return mi;
}
}
static void pushup(int num, int le, int ri) {
a[num].c = Math.max(a[le].c, a[ri].c);
}
// int root[] = new int[10000];
//
// void dfs(int j) {
//
// clr[j] = 1;
//
// for (int i = h[j]; i != 0; i = ne[i]) {
// int v = to[i];
// dfs(v);
// }
// for (Object go : qr[j]) {
// int g = (int) go;
// int id1 = qs[g][0];
// int id2 = qs[g][1];
// int ck;
// if (id1 == j) {
// ck = id2;
// } else {
// ck = id1;
// }
//
// if (clr[ck] == 0) {
// continue;
// } else if (clr[ck] == 1) {
// qs[g][2] = ck;
// } else {
// qs[g][2] = root(ck);
// }
// }
// root[j] = fa[j];
//
// clr[j] = 2;
// }
int clr[];
List[] qr;
int qs[][];
int rr = 100;
LinkedList<Integer> cao;
void df(int n,LinkedList<Integer> li){
int sz = li.size();
if(sz>=rr||sz>=11) return;
int v = li.getLast();
if(v==n){
cao = new LinkedList<>(li);
rr = sz;
return;
}
List<Integer> res = new ArrayList<>(li);
Collections.reverse(res);
for(int u:res){
for(int vv:res){
if(u+vv>v&&u+vv<=n){
li.addLast(u+vv);
df(n,li);
li.removeLast();
}else if(u+vv>n){break;}
}
}
}
Random rd = new Random(1274873);
static long mul(long a, long b, long p)
{
long res=0,base=a;
while(b>0)
{
if((b&1L)>0)
res=(res+base)%p;
base=(base+base)%p;
b>>=1;
}
return res;
}
static long mod_pow(long k,long n,long p){
long res = 1L;
long temp = k%p;
while(n!=0L){
if((n&1L)==1L){
res = mul(res,temp,p);
}
temp = mul(temp,temp,p);
n = n>>1L;
}
return res%p;
}
long gen(long x){
while(true) {
long f = rd.nextLong()%x;
if (f >=1 &&f<=x-1) {
return f;
}
}
}
boolean robin_miller(long x){
if(x==1) return false;
if(x==2) return true;
if(x==3) return true;
if((x&1)==0) return false;
long y = x%6;
if(y==1||y==5){
long ck = x-1;
while((ck&1)==0) ck>>>=1;
long as[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37};
for(int i=0;i<as.length;++i){
long a = as[i];
long ck1= ck;
a = mod_pow(a,ck1,x);
while(ck1<x){
y = mod_pow(a,2, x);
if (y == 1 && a != 1 && a != x - 1)
return false;
a = y;
ck1 = ck1<<1;
}
if (a != 1)
return false;
}
return true;
}else{
return false;
}
}
long inv(long a, long MOD) {
//return fpow(a, MOD-2, MOD);
return a==1?1:(long )(MOD-MOD/a)*inv(MOD%a, MOD)%MOD;
}
long C(long n,long m, long MOD) {
if(m+m>n)m=n-m;
long up=1,down=1;
for(long i=0;i<m;i++)
{
up=up*(n-i)%MOD;
down=down*(i+1)%MOD;
}
return up*inv(down, MOD)%MOD;
}
// int g[][] = {{1,2,3},{0,3,4},{0,3},{0,1,2,4},{1,3}};
// int res= 0;
// void go(int i,int a[],int x[],boolean ck[]){
// if(i==5){
// int an = 0;
// for(int j=0;i<5;++j){
// int id = a[j];
// if(ct[id]>3) continue;
// int all =0;
// for(int g:g[id]){
// all |= a[g];
// }
// if(all&(gz[id])==gz[id]){
// an++;
// }
// }
// if(an>res){
// res = an;
// }
// return;
// }
// for(int j=0;j<5;++j){
// if(!ck[j]){
// ck[j] = true;
// a[i] = x[j];
// go(i+1,a,x,ck);
// ck[j] = false;
// }
// }
//
//
// }
// x = r[0], y = r[1] , gcd(x,y) = r[2]
public static long[] ex_gcd(long a,long b){
if(b==0) {
return new long[]{1,0,a};
}
long []r = ex_gcd(b,a%b);
return new long[]{r[1], r[0]-(a/b)*r[1], r[2]};
}
void chinese_rm(long m[],long r[]){
long res[] = ex_gcd(m[0],m[1]);
long rm = r[1]-r[0];
if(rm%res[2]==0){
}
}
// void go(int i,int c,int cl[]){
// cl[i] = c;
// for(int j=h[i];j!=-1;j=ne[j]){
// int v = to[j];
// if(cl[v]==0){
// go(v,-c,cl);
// }
// }
//
// }
int go(int rt,int h[],int ne[],int to[],int pa){
int all = 3010;
for(int i=h[rt];i!=-1;i=ne[i]){
int v = to[i];
if(v==pa) continue;
int ma = 0;
for(int j=h[rt];j!=-1;j=ne[j]) {
int u = to[j];
if(u==pa) continue;
if(u!=v){
int r = 1 + go(u,h,ne,to,rt);
ma = Math.max(ma,r);
}
}
all = Math.min(all,ma);
}
if(all==3010||all==0) return 1;
return all;
}
boolean next_perm(int[] a){
int len = a.length;
for(int i=len-2,j = 0;i>=0;--i){
if(a[i]<a[i+1]){
j = len-1;
for(;a[j]<=a[i];--j);
int p = a[j];
a[j] = a[i];
a[i] = p;
j = i+1;
for(int ed = len-1;j<ed;--ed) {
p = a[ed];
a[ed] = a[j];
a[j++] = p;
}
return true;
}
}
return false;
}
boolean ok = false;
void ck(int[] d,int l,String a,String b,String c,int n,boolean chose[],int add){
if(ok) return;
if(l==-1){
if(add==0) {
for (int u : d) {
print(u + " ");
}
ok = true;
}
return;
}
int i1 = a.charAt(l)-'A';
int i2 = b.charAt(l)-'A';
int i3 = c.charAt(l)-'A';
if(d[i1]==-1&&d[i2]==-1) {
if(i1==i2){
for (int i = n-1; i >=0; --i) {
if (chose[i]) continue;
int s = (i + i + add);
int w = s % n;
if (d[i3] != -1 && d[i3] != w) continue;
if (chose[w] && d[i3] != w) continue;
if (w == i && i3 != i2) continue;
boolean hsw = d[i3]==w;
chose[w] = true;
chose[i] = true;
d[i1] = i; d[i2] = i; d[i3] = w;
int nadd = s/n;
ck(d, l-1,a,b,c,n,chose,nadd);
d[i1] = -1;
d[i2] = -1;
if(!hsw) {
d[i3] = -1;
chose[w] = false;
}
chose[i] = false;
}
}else {
for (int i = n-1; i >=0; --i) {
if (chose[i]) continue;
chose[i] = true;
d[i1] = i;
for (int j = n-1; j >=0; --j) {
if (chose[j]) continue;
int s = (i + j + add);
int w = s % n;
if (d[i3] != -1 && d[i3] != w) continue;
if (chose[w] && d[i3] != w) continue;
if (w == j && i3 != i2) continue;
if (w == i && i3 != i1) continue;
boolean hsw = d[i3] == w;
chose[w] = true;
chose[j] = true;
d[i2] = j;
d[i3] = w;
int nadd = s / n;
ck(d, l - 1, a, b, c, n, chose, nadd);
d[i2] = -1;
if (!hsw) {
d[i3] = -1;
chose[w] = false;
}
chose[j] = false;
}
chose[i] = false;
d[i1] = -1;
}
}
}else if(d[i1]==-1){
if(d[i3]==-1) {
for (int i = n - 1; i >= 0; --i) {
if (chose[i]) continue;
int s = (i + d[i2] + add);
int w = s % n;
if (d[i3] != -1 && d[i3] != w) continue;
if (chose[w] && d[i3] != w) continue;
if (w == i && i3 != i1) continue;
if (w == d[i2] && i3 != i2) continue;
boolean hsw = d[i3] == w;
chose[i] = true;
chose[w] = false;
d[i1] = i;
d[i3] = w;
int nadd = s / n;
ck(d, l - 1, a, b, c, n, chose, nadd);
d[i1] = -1;
if (!hsw) {
d[i3] = -1;
chose[w] = false;
}
chose[i] = false;
}
}else{
int s = d[i3]-add-d[i2];
int nadd = 0;
if(s<0){
s += n;
nadd = 1;
}
if(chose[s]) return;
chose[s] = true;
d[i1] = s;
ck(d, l - 1, a, b, c, n, chose, nadd);
chose[s] = false;
d[i1] = -1;
}
}else if(d[i2]==-1){
if(d[i3]==-1) {
for (int i = n - 1; i >= 0; --i) {
if (chose[i]) continue;
int s = (i + d[i1] + add);
int w = s % n;
// if (d[i3] != -1 && d[i3] != w) continue;
if (chose[w] && d[i3] != w) continue;
if (w == i && i3 != i2) continue;
if (w == d[i1] && i3 != i1) continue;
boolean hsw = d[i3] == w;
chose[i] = true;
chose[w] = true;
d[i2] = i;
d[i3] = w;
int nadd = s / n;
ck(d, l - 1, a, b, c, n, chose, nadd);
d[i2] = -1;
if (!hsw) {
d[i3] = -1;
chose[w] = false;
}
chose[i] = false;
}
}else{
int s = d[i3]-add-d[i1];
int nadd = 0;
if(s<0){
s += n;
nadd = 1;
}
if(chose[s]) return;
chose[s] = true;
d[i2] = s;
ck(d, l - 1, a, b, c, n, chose, nadd);
chose[s] = false;
d[i2] = -1;
}
}else{
if(d[i3]==-1){
int w =(d[i1]+d[i2]+add);
int nadd = w/n;
w %= n;
if(w==d[i2]&&i3!=i2) return;
if(w==d[i1]&&i3!=i1) return;
if(chose[w]) return;
d[i3] = w;
chose[d[i3]] = true;
ck(d, l - 1, a, b, c, n, chose, nadd);
chose[d[i3]] = false;
d[i3] = -1;
}else{
int w = d[i1]+d[i2]+add;
int nadd = w/n;
if(d[i3]==w%n){
ck(d, l - 1, a, b, c, n, chose, nadd);
}else{
return;
}
}
}
}
void solve() {
int n = ni();
int a[][] = new int[n][2];
for(int i=0;i<n;++i){
a[i][0] = ni();
a[i][1] = i;
}
Arrays.sort(a,(x,y)->{
return x[0] - y[0];
});
long b[] = new long[n-1];
long s = 0;
for(int i=0;i<n-1;++i){
b[i] = a[i+1][0] - a[i][0];
s += b[i];
}
long dp[] = new long[n-1];
int last[] = new int[n-1];
Arrays.fill(last,-1);
int ma = -1;
int mxid = -1;
for(int i=2;i<n-3;++i){
dp[i] = b[i]+(mxid==-1?0:dp[mxid]);
last[i] =mxid;
// for(int j=0;j+2<i;++j){
// if( dp[i] < dp[j] + b[i]){
// dp[i] = dp[j] + b[i];
// last[i] = j;
// }
// }
if(ma==-1||dp[i]>dp[ma]){
ma = i;
}
if(i>=4&&(mxid==-1||dp[i-2]>dp[mxid])){
mxid = i-2;
}
}
long res = s-(ma==-1?0:dp[ma]);
int dui = 0;
boolean f[] = new boolean[n-1];
while(ma!=-1){
dui++;
f[ma] = true;
ma = last[ma];
}
println(res+" "+(dui+1));
int c = 1;
int e[] = new int[n];
for(int i=0;i<n-1;++i){
if(!f[i]){
e[a[i][1]] = c;
e[a[i+1][1]] = c;
}else{
c++;
}
}
for(int u:e){
print(u+" ");
}
// int n = ni();
// int p = ni();
//
// int h[] = new int[n+1];
// Arrays.fill(h,-1);
// int to[] = new int[2*n+5];
// int ne[] = new int[2*n+5];
// int ct = 0;
//
// for(int i=0;i<p;i++){
// int x = ni();
// int y = ni();
// to[ct] = x;
// ne[ct] = h[y];
// h[y] = ct++;
//
// to[ct] = y;
// ne[ct] = h[x];
// h[x] = ct++;
//
// }
//
// println(go(1,h,ne,to,-1));
// int n= ni();
// //int m = ni();
// int l = 2*n;
//
// String s[] = new String[2*n+1];
//
// long a[] = new long[2*n+1];
// for(int i=1;i<=n;++i){
// s[i] = ns();
// s[i+n] = s[i];
// a[i] = ni();
// a[i+n] = a[i];
// }
//
// long dp[][] = new long[l+1][l+1];
// long dp1[][] = new long[l+1][l+1];
//
// for(int i = l;i>=1;--i) {
//
// Arrays.fill(dp[i],-1000000000);
// Arrays.fill(dp1[i],1000000000);
// }
//
// for(int i = l;i>=1;--i) {
// dp[i][i] = a[i];
// dp1[i][i] = a[i];
// }
//
//
//
// for(int i = l;i>=1;--i) {
//
// for (int j = i+1; j <= l&&j-i+1<=n; ++j) {
//
//
// for(int e=i;e<j;++e){
// if(s[e+1].equals("t")){
// dp[i][j] = Math.max(dp[i][j], dp[i][e]+dp[e+1][j]);
// dp1[i][j] = Math.min(dp1[i][j], dp1[i][e]+dp1[e+1][j]);
// }else{
//
// long f[] = {dp[i][e]*dp[e+1][j],dp1[i][e]*dp1[e+1][j],dp[i][e]*dp1[e+1][j],dp1[i][e]*dp[e+1][j]};
//
// for(long u:f) {
// dp[i][j] = Math.max(dp[i][j], u);
// dp1[i][j] = Math.min(dp1[i][j], u);
// }
// }
//
//
// }
//
// }
// }
// long ma = -100000000;
// List<Integer> li = new ArrayList<>();
// for (int j = 1; j <= n; ++j) {
// if(dp[j][j+n-1]==ma){
// li.add(j);
// }else if(dp[j][j+n-1]>ma){
// ma = dp[j][j+n-1];
// li.clear();
// li.add(j);
// }
//
// }
// println(ma);
// for(int u:li){
// print(u+" ");
// }
// println();
// println(get(490));
// int num =1;
// while(true) {
// int n = ni();
// int m = ni();
// if(n==0&&m==0) break;
// int p[] = new int[n];
// int d[] = new int[n];
// for(int j=0;j<n;++j){
// p[j] = ni();
// d[j] = ni();
// }
// int dp[][] = new int[8001][22];
// int choose[][] = new int[8001][22];
//
// for(int v=0;v<=8000;++v){
// for(int u=0;u<=21;++u) {
// dp[v][u] = -100000;
// choose[v][u] =-1;
// }
// }
// dp[4000][0] = 0;
//
// for(int j=0;j<n;++j){
// for(int g = m-1 ;g>=0; --g){
// if(p[j] - d[j]>=0) {
// for (int v = 4000; v >= -4000; --v) {
// if (v + 4000 + p[j] - d[j] >= 0 && v + 4000 + p[j] - d[j] <= 8000 && dp[v + 4000][g] >= 0) {
// int ck1 = dp[v + 4000 + p[j] - d[j]][g + 1];
// if (ck1 < dp[v + 4000][g] + p[j] + d[j]) {
// dp[v + 4000 + p[j] - d[j]][g + 1] = dp[v + 4000][g] + p[j] + d[j];
// choose[v + 4000 + p[j] - d[j]][g + 1] = j;
// }
// }
//
// }
// }else{
// for (int v = -4000; v <= 4000; ++v) {
// if (v + 4000 + p[j] - d[j] >= 0 && v + 4000 + p[j] - d[j] <= 8000 && dp[v + 4000][g] >= 0) {
// int ck1 = dp[v + 4000 + p[j] - d[j]][g + 1];
// if (ck1 < dp[v + 4000][g] + p[j] + d[j]) {
// dp[v + 4000 + p[j] - d[j]][g + 1] = dp[v + 4000][g] + p[j] + d[j];
// choose[v + 4000 + p[j] - d[j]][g + 1] = j;
// }
// }
//
// }
//
//
//
//
//
// }
// }
// }
// int big = 0;
// int st = 0;
// boolean ok = false;
// for(int v=0;v<=4000;++v){
// int v1 = -v;
// if(dp[v+4000][m]>0){
// big = dp[v+4000][m];
// st = v+4000;
// ok = true;
// }
// if(dp[v1+4000][m]>0&&dp[v1+4000][m]>big){
// big = dp[v1+4000][m];
// st = v1+4000;
// ok = true;
// }
// if(ok){
// break;
// }
// }
// int f = 0;
// int s = 0;
// List<Integer> res = new ArrayList<>();
// while(choose[st][m]!=-1){
// int j = choose[st][m];
// res.add(j+1);
// f += p[j];
// s += d[j];
// st -= p[j]-d[j];
// m--;
// }
// Collections.sort(res);
// println("Jury #"+num);
// println("Best jury has value " + f + " for prosecution and value " + s + " for defence:");
// for(int u=0;u<res.size();++u){
// print(" ");
// print(res.get(u));
// }
// println();
// println();
// num++;
// }
// int n = ni();
// int m = ni();
//
// int dp[][] = new int[n][4];
//
// for(int i=0;i<n;++i){
// for(int j=0;j<m;++j){
// for(int c = 0;c<4;++c){
// if(c==0){
// dp[i][j][] =
// }
// }
// }
// }
}
static void pushdown(int num, int le, int ri) {
}
long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
InputStream is;
PrintWriter out;
void run() throws Exception {
is = System.in;
out = new PrintWriter(System.out);
solve();
out.flush();
}
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte() {
if (lenbuf == -1) throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0) return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b)) ;
return b;
}
private double nd() {
return Double.parseDouble(ns());
}
private char nc() {
return (char) skip();
}
private char ncc() {
int b = b = readByte();
return (char) b;
}
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private String nline() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!isSpaceChar(b) || b == ' ') {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[][] nm(int n, int m) {
char[][] a = new char[n][];
for (int i = 0; i < n; i++) a[i] = ns(m);
return a;
}
private int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = ni();
return a;
}
private long[] nal(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nl();
return a;
}
private int ni() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) {
}
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') num = (num << 3) + (num << 1) + (b - '0');
else return minus ? -num : num;
b = readByte();
}
}
private long nl() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) {
}
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') num = num * 10 + (b - '0');
else return minus ? -num : num;
b = readByte();
}
}
void print(Object obj) {
out.print(obj);
}
void println(Object obj) {
out.println(obj);
}
void println() {
out.println();
}
} | Java | ["5\n1 1 3 4 2", "6\n1 5 12 13 2 15", "10\n1 2 5 129 185 581 1041 1909 1580 8150"] | 2 seconds | ["3 1\n1 1 1 1 1", "7 2\n2 2 1 1 2 1", "7486 3\n3 3 3 2 2 2 2 1 1 1"] | NoteIn the first example, there is only one team with skills $$$[1, 1, 2, 3, 4]$$$ so the answer is $$$3$$$. It can be shown that you cannot achieve a better answer.In the second example, there are two teams with skills $$$[1, 2, 5]$$$ and $$$[12, 13, 15]$$$ so the answer is $$$4 + 3 = 7$$$.In the third example, there are three teams with skills $$$[1, 2, 5]$$$, $$$[129, 185, 581, 1041]$$$ and $$$[1580, 1909, 8150]$$$ so the answer is $$$4 + 912 + 6570 = 7486$$$. | Java 8 | standard input | [
"dp",
"sortings",
"greedy"
] | 9ff029199394c3fa4ced7c65b2827b6c | The first line of the input contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of students. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the programming skill of the $$$i$$$-th student. | 2,000 | In the first line print two integers $$$res$$$ and $$$k$$$ — the minimum total diversity of the division of students and the number of teams in your division, correspondingly. In the second line print $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le k$$$), where $$$t_i$$$ is the number of team to which the $$$i$$$-th student belong. If there are multiple answers, you can print any. Note that you don't need to minimize the number of teams. Each team should consist of at least three students. | standard output | |
PASSED | bd155df011a24ac922d964a76d06e494 | train_003.jsonl | 1572873300 | There are $$$n$$$ students at your university. The programming skill of the $$$i$$$-th student is $$$a_i$$$. As a coach, you want to divide them into teams to prepare them for the upcoming ICPC finals. Just imagine how good this university is if it has $$$2 \cdot 10^5$$$ students ready for the finals!Each team should consist of at least three students. Each student should belong to exactly one team. The diversity of a team is the difference between the maximum programming skill of some student that belongs to this team and the minimum programming skill of some student that belongs to this team (in other words, if the team consists of $$$k$$$ students with programming skills $$$a[i_1], a[i_2], \dots, a[i_k]$$$, then the diversity of this team is $$$\max\limits_{j=1}^{k} a[i_j] - \min\limits_{j=1}^{k} a[i_j]$$$).The total diversity is the sum of diversities of all teams formed.Your task is to minimize the total diversity of the division of students and find the optimal way to divide the students. | 256 megabytes | import java.util.*;
import java.io.*;
public class Solution{
public static Integer INT(String s) {
return Integer.parseInt(s);
}
public static Long LONG(String s) {
return Long.parseLong(s);
}
static int mod=1_000_000_007, oo=Integer.MAX_VALUE, _oo=Integer.MAX_VALUE;
//==================================================================================================================================================
public static void main(String args[]) throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); Scanner in=new Scanner(System.in); StringBuilder out=new StringBuilder();
int n=in.nextInt();
long a[][]=new long[n][5];
for(int i=0; i<n; i++) {
a[i][0]=i;
a[i][1]=in.nextLong();
}
Arrays.sort(a, (a1, a2)->(int)(a1[1]-a2[1]));
for(int i=0; i<n-1; i++)
a[i][2]=a[i][1]-a[i+1][1];
int prevmax=-1, max=-1;
for(int i=2; i<n-3; i++) {
if(i>=5 && (prevmax==-1 || a[i-3][2]<a[prevmax][2]))
prevmax=i-3;
if(prevmax!=-1) {
a[i][2]+=a[prevmax][2];
a[i][3]=prevmax;
}
else
a[i][3]=0;
if(max==-1 || a[i][2]<a[max][2])
max=i;
}
long value=a[n-1][1]-a[0][1];
if(max!=-1)
value+=a[max][2];
int k=1;
for(int i=n-1; i>=0; i--) {
if(i!=0 && i==max) {
max=(int)a[i][3];
k+=1;
}
a[i][4]=k;
}
int ans[]=new int[n];
for(int i=0; i<n; i++)
ans[(int)a[i][0]]=(int)a[i][4];
out.append(value+" "+k+"\n");
for(int item: ans)
out.append(item+" ");
System.out.print(out);
}
} | Java | ["5\n1 1 3 4 2", "6\n1 5 12 13 2 15", "10\n1 2 5 129 185 581 1041 1909 1580 8150"] | 2 seconds | ["3 1\n1 1 1 1 1", "7 2\n2 2 1 1 2 1", "7486 3\n3 3 3 2 2 2 2 1 1 1"] | NoteIn the first example, there is only one team with skills $$$[1, 1, 2, 3, 4]$$$ so the answer is $$$3$$$. It can be shown that you cannot achieve a better answer.In the second example, there are two teams with skills $$$[1, 2, 5]$$$ and $$$[12, 13, 15]$$$ so the answer is $$$4 + 3 = 7$$$.In the third example, there are three teams with skills $$$[1, 2, 5]$$$, $$$[129, 185, 581, 1041]$$$ and $$$[1580, 1909, 8150]$$$ so the answer is $$$4 + 912 + 6570 = 7486$$$. | Java 8 | standard input | [
"dp",
"sortings",
"greedy"
] | 9ff029199394c3fa4ced7c65b2827b6c | The first line of the input contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of students. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the programming skill of the $$$i$$$-th student. | 2,000 | In the first line print two integers $$$res$$$ and $$$k$$$ — the minimum total diversity of the division of students and the number of teams in your division, correspondingly. In the second line print $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le k$$$), where $$$t_i$$$ is the number of team to which the $$$i$$$-th student belong. If there are multiple answers, you can print any. Note that you don't need to minimize the number of teams. Each team should consist of at least three students. | standard output | |
PASSED | 687b5104abb8e96e24dd983be3a680c6 | train_003.jsonl | 1572873300 | There are $$$n$$$ students at your university. The programming skill of the $$$i$$$-th student is $$$a_i$$$. As a coach, you want to divide them into teams to prepare them for the upcoming ICPC finals. Just imagine how good this university is if it has $$$2 \cdot 10^5$$$ students ready for the finals!Each team should consist of at least three students. Each student should belong to exactly one team. The diversity of a team is the difference between the maximum programming skill of some student that belongs to this team and the minimum programming skill of some student that belongs to this team (in other words, if the team consists of $$$k$$$ students with programming skills $$$a[i_1], a[i_2], \dots, a[i_k]$$$, then the diversity of this team is $$$\max\limits_{j=1}^{k} a[i_j] - \min\limits_{j=1}^{k} a[i_j]$$$).The total diversity is the sum of diversities of all teams formed.Your task is to minimize the total diversity of the division of students and find the optimal way to divide the students. | 256 megabytes | import java.util.*;
import java.io.*;
import java.text.*;
public class E1256 {
static Pair[] arr;
static int[] trace;
static int[][] dp;
static int dp(int idx, int size) {
int max = 0;
if (idx == arr.length)
return dp[idx][size]= 0;
if (dp[idx][size] != -1)
return dp[idx][size];
if (idx + 2 < arr.length) {
max = Math.max(arr[idx].v - arr[idx - 1].v + dp(idx + 3, 3), max);
}
if (size < 7)
max = Math.max(dp(idx + 1, size + 1), max);
return dp[idx][size] = max;
}
static void trace(int idx,int size,int team) {
if(idx==arr.length)
return;
// if(idx<arr.length)System.out.println(dp[idx][size]+" "+(arr[idx]-arr[idx-1]+dp[idx+3][3]));
if(idx+2<arr.length && dp[idx][size]==(arr[idx].v-arr[idx-1].v+dp[idx+3][3]))
{
int cur = team+1;;
trace[idx]=cur;
trace[idx+1]=cur;
trace[idx+2]=cur;
trace(idx+3, 3, cur);
}else {
trace[idx]=team;
trace(idx+1, size+1, team);
}
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = sc.nextInt();
arr = new Pair[n];
for (int i = 0; i < arr.length; i++) {
arr[i] = new Pair(i, sc.nextInt());
}
Arrays.sort(arr,(a,b)->a.v-b.v);
dp = new int[n+3][8];
for (int[] x : dp)
Arrays.fill(x, -1);
int ans = arr[n - 1].v - arr[0].v - dp(3, 3);
trace = new int [n];
trace[0]=trace[1]=trace[2]=1;
trace(3, 3, 1);
pw.println(ans+" "+trace[n-1]);
for(int i=0;i<n;i++) {
arr[i].v=trace[i];
}
Arrays.sort(arr,(a,b)->a.idx-b.idx);
for(Pair p : arr)
pw.print(p.v+" ");
pw.println();
pw.close();
}
static class Pair{
int idx,v;
public Pair(int idx, int v) {
this.idx=idx;
this.v=v;
}
}
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 boolean ready() throws IOException {
return br.ready();
}
}
}
| Java | ["5\n1 1 3 4 2", "6\n1 5 12 13 2 15", "10\n1 2 5 129 185 581 1041 1909 1580 8150"] | 2 seconds | ["3 1\n1 1 1 1 1", "7 2\n2 2 1 1 2 1", "7486 3\n3 3 3 2 2 2 2 1 1 1"] | NoteIn the first example, there is only one team with skills $$$[1, 1, 2, 3, 4]$$$ so the answer is $$$3$$$. It can be shown that you cannot achieve a better answer.In the second example, there are two teams with skills $$$[1, 2, 5]$$$ and $$$[12, 13, 15]$$$ so the answer is $$$4 + 3 = 7$$$.In the third example, there are three teams with skills $$$[1, 2, 5]$$$, $$$[129, 185, 581, 1041]$$$ and $$$[1580, 1909, 8150]$$$ so the answer is $$$4 + 912 + 6570 = 7486$$$. | Java 8 | standard input | [
"dp",
"sortings",
"greedy"
] | 9ff029199394c3fa4ced7c65b2827b6c | The first line of the input contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of students. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the programming skill of the $$$i$$$-th student. | 2,000 | In the first line print two integers $$$res$$$ and $$$k$$$ — the minimum total diversity of the division of students and the number of teams in your division, correspondingly. In the second line print $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le k$$$), where $$$t_i$$$ is the number of team to which the $$$i$$$-th student belong. If there are multiple answers, you can print any. Note that you don't need to minimize the number of teams. Each team should consist of at least three students. | standard output | |
PASSED | 35f836760f86c56ab85cdda7f87a359d | train_003.jsonl | 1572873300 | There are $$$n$$$ students at your university. The programming skill of the $$$i$$$-th student is $$$a_i$$$. As a coach, you want to divide them into teams to prepare them for the upcoming ICPC finals. Just imagine how good this university is if it has $$$2 \cdot 10^5$$$ students ready for the finals!Each team should consist of at least three students. Each student should belong to exactly one team. The diversity of a team is the difference between the maximum programming skill of some student that belongs to this team and the minimum programming skill of some student that belongs to this team (in other words, if the team consists of $$$k$$$ students with programming skills $$$a[i_1], a[i_2], \dots, a[i_k]$$$, then the diversity of this team is $$$\max\limits_{j=1}^{k} a[i_j] - \min\limits_{j=1}^{k} a[i_j]$$$).The total diversity is the sum of diversities of all teams formed.Your task is to minimize the total diversity of the division of students and find the optimal way to divide the students. | 256 megabytes | import java.io.*;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main {
static final int UNCALC = -1;
static final long INF = (long) 1e15;
static long[][] memo;
static int n;
static Pair[] a;
static int teams;
static int[] ans;
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
n = sc.nextInt();
int[] b = sc.nextIntArray(n);
a = new Pair[n];
for (int i = 0; i < n; i++)
a[i] = new Pair(i, b[i]);
memo = new long[4][n];
for (long[] aa : memo)
Arrays.fill(aa, UNCALC);
Arrays.sort(a);
long best = dp(0, 0);
ans = new int[n];
trace(0, 0);
out.println(best + " " + teams);
for (int x : ans)
out.print(x + " ");
out.flush();
out.close();
}
static void trace(int cnt, int i) {
if (cnt > 3) cnt = 3;
if (i == n) return;
long best = dp(cnt, i);
if (cnt >= 2 && best == a[i].val + dp(0, i + 1)) {
ans[a[i].i] = teams;
trace(0, i + 1);
return;
}
if (cnt == 0) teams++;
ans[a[i].i] = teams;
trace(cnt + 1, i + 1);
}
static long dp(int cnt, int i) {
if (cnt > 3) cnt = 3;
if (i == n) return cnt == 0 ? 0 : INF;
if (memo[cnt][i] != UNCALC) return memo[cnt][i];
long best = (cnt == 0 ? -a[i].val : 0) + dp(cnt + 1, i + 1);
if (cnt >= 2) best = Math.min(best, a[i].val + dp(0, i + 1));
return memo[cnt][i] = best;
}
static class Pair implements Comparable<Pair> {
int i, val;
public Pair(int i, int val) {
this.i = i;
this.val = val;
}
@Override
public int compareTo(Pair o) {
return val - o.val;
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
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[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
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 Integer[] nextIntegerArray(int n) throws IOException {
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public double[] nextDoubleArray(int n) throws IOException {
double[] ans = new double[n];
for (int i = 0; i < n; i++)
ans[i] = nextDouble();
return ans;
}
public short nextShort() throws IOException {
return Short.parseShort(next());
}
}
} | Java | ["5\n1 1 3 4 2", "6\n1 5 12 13 2 15", "10\n1 2 5 129 185 581 1041 1909 1580 8150"] | 2 seconds | ["3 1\n1 1 1 1 1", "7 2\n2 2 1 1 2 1", "7486 3\n3 3 3 2 2 2 2 1 1 1"] | NoteIn the first example, there is only one team with skills $$$[1, 1, 2, 3, 4]$$$ so the answer is $$$3$$$. It can be shown that you cannot achieve a better answer.In the second example, there are two teams with skills $$$[1, 2, 5]$$$ and $$$[12, 13, 15]$$$ so the answer is $$$4 + 3 = 7$$$.In the third example, there are three teams with skills $$$[1, 2, 5]$$$, $$$[129, 185, 581, 1041]$$$ and $$$[1580, 1909, 8150]$$$ so the answer is $$$4 + 912 + 6570 = 7486$$$. | Java 8 | standard input | [
"dp",
"sortings",
"greedy"
] | 9ff029199394c3fa4ced7c65b2827b6c | The first line of the input contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of students. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the programming skill of the $$$i$$$-th student. | 2,000 | In the first line print two integers $$$res$$$ and $$$k$$$ — the minimum total diversity of the division of students and the number of teams in your division, correspondingly. In the second line print $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le k$$$), where $$$t_i$$$ is the number of team to which the $$$i$$$-th student belong. If there are multiple answers, you can print any. Note that you don't need to minimize the number of teams. Each team should consist of at least three students. | standard output | |
PASSED | 90bd2acecc567a031c888ef0fe1a4da3 | train_003.jsonl | 1572873300 | There are $$$n$$$ students at your university. The programming skill of the $$$i$$$-th student is $$$a_i$$$. As a coach, you want to divide them into teams to prepare them for the upcoming ICPC finals. Just imagine how good this university is if it has $$$2 \cdot 10^5$$$ students ready for the finals!Each team should consist of at least three students. Each student should belong to exactly one team. The diversity of a team is the difference between the maximum programming skill of some student that belongs to this team and the minimum programming skill of some student that belongs to this team (in other words, if the team consists of $$$k$$$ students with programming skills $$$a[i_1], a[i_2], \dots, a[i_k]$$$, then the diversity of this team is $$$\max\limits_{j=1}^{k} a[i_j] - \min\limits_{j=1}^{k} a[i_j]$$$).The total diversity is the sum of diversities of all teams formed.Your task is to minimize the total diversity of the division of students and find the optimal way to divide the students. | 256 megabytes | import java.math.*;
import java.io.*;
import java.util.*;
import java.awt.*;
public class CP {
public static void main(String[] args) throws Exception {
/*new Thread(null, new Runnable() {
@Override
public void run() {
try {
new Solver().solve();
} catch (Exception e) {
e.printStackTrace();
}
}
}, "Solver", 1l << 30).start();*/
new Solver().solve();
}
}
class Solver {
final Helper hp;
final int MAXN = 1000_006;
final long MOD = (long) 1e9 + 7;
Solver() {
hp = new Helper(MOD, MAXN);
hp.initIO(System.in, System.out);
}
void solve() throws Exception {
int i, j, k;
int N = hp.nextInt();
long[] A = hp.getLongArray(N);
if (N <= 5) {
System.out.println(hp.max(A) - hp.min(A));
System.out.println(1);
for (i = 0; i < N; ++i) System.out.print("1 ");
System.out.println();
return;
}
HashMap<Long, Stack<Integer>> map = new HashMap<>();
for (i = 0; i < N; ++i) {
map.putIfAbsent(A[i], new Stack<>());
map.get(A[i]).add(i);
}
hp.shuffle(A);
Arrays.sort(A);
TreeSet<long[]> pairs = new TreeSet<>((long[] a, long[] b) ->
a[0] == b[0] ? Long.compare(a[1], b[1]) : Long.compare(a[0], b[0]));
//System.out.println(Arrays.toString(A));
dp = new long[N + 1];
dp[0] = -A[0]; dp[1] = dp[2] = Long.MAX_VALUE;
for (i = 3; i <= N; ++i) {
pairs.add(new long[] {dp[i - 3], i - 3});
dp[i] = pairs.first()[0] + A[i - 1];
if (i < N) dp[i] -= A[i];
}
//System.out.println(Arrays.toString(dp));
BitSet sel = new BitSet();
int idx = N; sel.set(idx);
while (idx > 0) {
long temp = dp[idx] - A[idx - 1];
if (idx < N) temp += A[idx];
int prev = -7;
while (prev < 0) {
long[] p = pairs.floor(new long[] {temp, Integer.MAX_VALUE >> 2});
pairs.remove(p);
if (p[1] <= idx - 3) prev = (int) p[1];
}
if (dp[prev] != temp) System.exit(7 / 0);
sel.set(prev);
idx = prev;
}
int[] ans = new int[N];
for (k = i = 0; i < N; ++i) {
if (sel.get(i)) ++k;
ans[i] = k;
}
long sum = 0;
for (i = 1; i <= N; ++i) if (sel.get(i)) {
sum += A[i - 1] - A[sel.previousSetBit(i - 1)];
}
int[] assignCol = new int[N];
for (i = 0; i < N; ++i) {
assignCol[map.get(A[i]).pop()] = ans[i];
}
hp.println(sum);
hp.println(hp.max(assignCol));
hp.println(hp.joinElements(assignCol));
hp.flush();
}
long[] dp;
long search(int l, int r) {
long ret = Long.MAX_VALUE;
for (int i = l; i <= r; ++i) ret = Math.min(ret, dp[i]);
return ret;
}
}
class Helper {
final long MOD;
final int MAXN;
final Random rnd;
public Helper(long mod, int maxn) {
MOD = mod;
MAXN = maxn;
rnd = new Random();
}
public static int[] sieve;
public static ArrayList<Integer> primes;
public void setSieve() {
primes = new ArrayList<>();
sieve = new int[MAXN];
int i, j;
for (i = 2; i < MAXN; ++i)
if (sieve[i] == 0) {
primes.add(i);
for (j = i; j < MAXN; j += i) {
sieve[j] = i;
}
}
}
public static long[] factorial;
public void setFactorial() {
factorial = new long[MAXN];
factorial[0] = 1;
for (int i = 1; i < MAXN; ++i) factorial[i] = factorial[i - 1] * i % MOD;
}
public long getFactorial(int n) {
if (factorial == null) setFactorial();
return factorial[n];
}
public long ncr(int n, int r) {
if (r > n) return 0;
if (factorial == null) setFactorial();
long numerator = factorial[n];
long denominator = factorial[r] * factorial[n - r] % MOD;
return numerator * pow(denominator, MOD - 2, MOD) % MOD;
}
public long[] getLongArray(int size) throws Exception {
long[] ar = new long[size];
for (int i = 0; i < size; ++i) ar[i] = nextLong();
return ar;
}
public int[] getIntArray(int size) throws Exception {
int[] ar = new int[size];
for (int i = 0; i < size; ++i) ar[i] = nextInt();
return ar;
}
public String[] getStringArray(int size) throws Exception {
String[] ar = new String[size];
for (int i = 0; i < size; ++i) ar[i] = next();
return ar;
}
public String joinElements(long[] ar) {
StringBuilder sb = new StringBuilder();
for (long itr : ar) sb.append(itr).append(" ");
return sb.toString().trim();
}
public String joinElements(int[] ar) {
StringBuilder sb = new StringBuilder();
for (int itr : ar) sb.append(itr).append(" ");
return sb.toString().trim();
}
public String joinElements(String[] ar) {
StringBuilder sb = new StringBuilder();
for (String itr : ar) sb.append(itr).append(" ");
return sb.toString().trim();
}
public String joinElements(Object[] ar) {
StringBuilder sb = new StringBuilder();
for (Object itr : ar) sb.append(itr).append(" ");
return sb.toString().trim();
}
public long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
public int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
public long max(long[] ar) {
long ret = ar[0];
for (long itr : ar) ret = Math.max(ret, itr);
return ret;
}
public int max(int[] ar) {
int ret = ar[0];
for (int itr : ar) ret = Math.max(ret, itr);
return ret;
}
public long min(long[] ar) {
long ret = ar[0];
for (long itr : ar) ret = Math.min(ret, itr);
return ret;
}
public int min(int[] ar) {
int ret = ar[0];
for (int itr : ar) ret = Math.min(ret, itr);
return ret;
}
public long sum(long[] ar) {
long sum = 0;
for (long itr : ar) sum += itr;
return sum;
}
public long sum(int[] ar) {
long sum = 0;
for (int itr : ar) sum += itr;
return sum;
}
public void shuffle(int[] ar) {
int r;
for (int i = 0; i < ar.length; ++i) {
r = rnd.nextInt(ar.length);
if (r != i) {
ar[i] ^= ar[r];
ar[r] ^= ar[i];
ar[i] ^= ar[r];
}
}
}
public void shuffle(long[] ar) {
int r;
for (int i = 0; i < ar.length; ++i) {
r = rnd.nextInt(ar.length);
if (r != i) {
ar[i] ^= ar[r];
ar[r] ^= ar[i];
ar[i] ^= ar[r];
}
}
}
public long pow(long base, long exp, long MOD) {
base %= MOD;
long ret = 1;
while (exp > 0) {
if ((exp & 1) == 1) ret = ret * base % MOD;
base = base * base % MOD;
exp >>= 1;
}
return ret;
}
static byte[] buf = new byte[2048];
static int index, total;
static InputStream in;
static BufferedWriter bw;
public void initIO(InputStream is, OutputStream os) {
try {
in = is;
bw = new BufferedWriter(new OutputStreamWriter(os));
} catch (Exception e) {
}
}
public void initIO(String inputFile, String outputFile) {
try {
in = new FileInputStream(inputFile);
bw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outputFile)));
} catch (Exception e) {
}
}
private int scan() throws Exception {
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0)
return -1;
}
return buf[index++];
}
public String next() throws Exception {
int c;
for (c = scan(); c <= 32; c = scan()) ;
StringBuilder sb = new StringBuilder();
for (; c > 32; c = scan())
sb.append((char) c);
return sb.toString();
}
public int nextInt() throws Exception {
int c, val = 0;
for (c = scan(); c <= 32; c = scan()) ;
boolean neg = c == '-';
if (c == '-' || c == '+')
c = scan();
for (; c >= '0' && c <= '9'; c = scan())
val = (val << 3) + (val << 1) + (c & 15);
return neg ? -val : val;
}
public long nextLong() throws Exception {
int c;
long val = 0;
for (c = scan(); c <= 32; c = scan()) ;
boolean neg = c == '-';
if (c == '-' || c == '+')
c = scan();
for (; c >= '0' && c <= '9'; c = scan())
val = (val << 3) + (val << 1) + (c & 15);
return neg ? -val : val;
}
public void print(Object a) throws Exception {
bw.write(a.toString());
}
public void printsp(Object a) throws Exception {
print(a);
print(" ");
}
public void println() throws Exception {
bw.write("\n");
}
public void println(Object a) throws Exception {
print(a);
println();
}
public void flush() throws Exception {
bw.flush();
}
}
| Java | ["5\n1 1 3 4 2", "6\n1 5 12 13 2 15", "10\n1 2 5 129 185 581 1041 1909 1580 8150"] | 2 seconds | ["3 1\n1 1 1 1 1", "7 2\n2 2 1 1 2 1", "7486 3\n3 3 3 2 2 2 2 1 1 1"] | NoteIn the first example, there is only one team with skills $$$[1, 1, 2, 3, 4]$$$ so the answer is $$$3$$$. It can be shown that you cannot achieve a better answer.In the second example, there are two teams with skills $$$[1, 2, 5]$$$ and $$$[12, 13, 15]$$$ so the answer is $$$4 + 3 = 7$$$.In the third example, there are three teams with skills $$$[1, 2, 5]$$$, $$$[129, 185, 581, 1041]$$$ and $$$[1580, 1909, 8150]$$$ so the answer is $$$4 + 912 + 6570 = 7486$$$. | Java 8 | standard input | [
"dp",
"sortings",
"greedy"
] | 9ff029199394c3fa4ced7c65b2827b6c | The first line of the input contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of students. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the programming skill of the $$$i$$$-th student. | 2,000 | In the first line print two integers $$$res$$$ and $$$k$$$ — the minimum total diversity of the division of students and the number of teams in your division, correspondingly. In the second line print $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le k$$$), where $$$t_i$$$ is the number of team to which the $$$i$$$-th student belong. If there are multiple answers, you can print any. Note that you don't need to minimize the number of teams. Each team should consist of at least three students. | standard output | |
PASSED | 58d179a51f09441ceb7def647dccad89 | train_003.jsonl | 1572873300 | There are $$$n$$$ students at your university. The programming skill of the $$$i$$$-th student is $$$a_i$$$. As a coach, you want to divide them into teams to prepare them for the upcoming ICPC finals. Just imagine how good this university is if it has $$$2 \cdot 10^5$$$ students ready for the finals!Each team should consist of at least three students. Each student should belong to exactly one team. The diversity of a team is the difference between the maximum programming skill of some student that belongs to this team and the minimum programming skill of some student that belongs to this team (in other words, if the team consists of $$$k$$$ students with programming skills $$$a[i_1], a[i_2], \dots, a[i_k]$$$, then the diversity of this team is $$$\max\limits_{j=1}^{k} a[i_j] - \min\limits_{j=1}^{k} a[i_j]$$$).The total diversity is the sum of diversities of all teams formed.Your task is to minimize the total diversity of the division of students and find the optimal way to divide the students. | 256 megabytes | /**
* @author derrick20
*/
import java.io.*;
import java.util.*;
public class YetAnotherDivisionSimple implements Runnable {
public static void main(String[] args) throws Exception {
new Thread(null, new YetAnotherDivisionSimple(), ": )", 1 << 28).start();
}
public void run() {
FastScanner sc = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int N = sc.nextInt();
Pair[] a = new Pair[N + 1];
a[0] = new Pair(0, 0);
for (int i = 1; i <= N; i++) {
a[i] = new Pair(i, sc.nextInt());
}
Arrays.sort(a, Comparator.comparingLong(p -> p.val));
int[] prev = new int[N + 1];
long[] dp = new long[N + 1];
Arrays.fill(dp, oo);
dp[0] = 0;
for (int end = 3; end <= N; end++) {
for (int prevEnd = end - 3; prevEnd >= 0 && prevEnd >= end - 5; prevEnd--) {
long cost = a[end].val - a[prevEnd + 1].val + dp[prevEnd];
if (cost < dp[end]) {
dp[end] = cost;
prev[end] = prevEnd;
}
}
}
int[] team = new int[N + 1];
int t = 1;
int curr = N;
while (curr > 0) {
int next = prev[curr];
for (int j = curr; j > next; j--) {
team[a[j].idx] = t;
}
t++;
curr = next;
}
out.println(dp[N] + " " + (t - 1));
StringJoiner sj = new StringJoiner(" ");
for (int i = 1; i <= N; i++) {
sj.add(Integer.toString(team[i]));
}
out.println(sj.toString());
out.close();
}
static long oo = (long) 9e18;
static class Pair {
int idx; long val;
public Pair(int ii, long vv) {
idx = ii; val = vv;
}
public String toString() {
return "(" + idx + ", " + val + ")";
}
}
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);
}
static void ASSERT(boolean assertion) {
if (!assertion) throw new AssertionError();
}
} | Java | ["5\n1 1 3 4 2", "6\n1 5 12 13 2 15", "10\n1 2 5 129 185 581 1041 1909 1580 8150"] | 2 seconds | ["3 1\n1 1 1 1 1", "7 2\n2 2 1 1 2 1", "7486 3\n3 3 3 2 2 2 2 1 1 1"] | NoteIn the first example, there is only one team with skills $$$[1, 1, 2, 3, 4]$$$ so the answer is $$$3$$$. It can be shown that you cannot achieve a better answer.In the second example, there are two teams with skills $$$[1, 2, 5]$$$ and $$$[12, 13, 15]$$$ so the answer is $$$4 + 3 = 7$$$.In the third example, there are three teams with skills $$$[1, 2, 5]$$$, $$$[129, 185, 581, 1041]$$$ and $$$[1580, 1909, 8150]$$$ so the answer is $$$4 + 912 + 6570 = 7486$$$. | Java 8 | standard input | [
"dp",
"sortings",
"greedy"
] | 9ff029199394c3fa4ced7c65b2827b6c | The first line of the input contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of students. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the programming skill of the $$$i$$$-th student. | 2,000 | In the first line print two integers $$$res$$$ and $$$k$$$ — the minimum total diversity of the division of students and the number of teams in your division, correspondingly. In the second line print $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le k$$$), where $$$t_i$$$ is the number of team to which the $$$i$$$-th student belong. If there are multiple answers, you can print any. Note that you don't need to minimize the number of teams. Each team should consist of at least three students. | standard output | |
PASSED | 52a39966d8afc4588c984b226f9e8aee | train_003.jsonl | 1572873300 | There are $$$n$$$ students at your university. The programming skill of the $$$i$$$-th student is $$$a_i$$$. As a coach, you want to divide them into teams to prepare them for the upcoming ICPC finals. Just imagine how good this university is if it has $$$2 \cdot 10^5$$$ students ready for the finals!Each team should consist of at least three students. Each student should belong to exactly one team. The diversity of a team is the difference between the maximum programming skill of some student that belongs to this team and the minimum programming skill of some student that belongs to this team (in other words, if the team consists of $$$k$$$ students with programming skills $$$a[i_1], a[i_2], \dots, a[i_k]$$$, then the diversity of this team is $$$\max\limits_{j=1}^{k} a[i_j] - \min\limits_{j=1}^{k} a[i_j]$$$).The total diversity is the sum of diversities of all teams formed.Your task is to minimize the total diversity of the division of students and find the optimal way to divide the students. | 256 megabytes | /**
* @author derrick20
*/
import java.io.*;
import java.util.*;
public class YetAnotherDivisionIntoTeam implements Runnable {
public static void main(String[] args) throws Exception {
new Thread(null, new YetAnotherDivisionIntoTeam(), ": )", 1 << 28).start();
}
public void run() {
FastScanner sc = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int N = sc.nextInt();
Pair[] a = new Pair[N + 1];
a[0] = new Pair(0, 0);
for (int i = 1; i <= N; i++) {
a[i] = new Pair(i, sc.nextInt());
}
Arrays.sort(a, Comparator.comparingLong(p -> p.val));
SegmentTree dp = new SegmentTree(N + 1);
dp.update(0, -a[1].val);
dp.update(1, oo);
dp.update(2, oo);
int[] prev = new int[N + 1];
for (int i = 3; i <= N; i++) {
Pair prevPair = dp.query(0, i - 3);
// System.out.println("Prev: " + prevPair);
prev[i] = prevPair.idx;
dp.update(i, a[i].val + prevPair.val - (i != N ? a[i + 1].val : 0));
// dp.print();
}
int[] team = new int[N + 1];
int t = 1;
int curr = N;
while (curr > 0) {
int next = prev[curr];
for (int j = curr; j > next; j--) {
team[a[j].idx] = t;
}
t++;
curr = next;
}
out.println(dp.query(N, N).val + " " + (t - 1));
StringJoiner sj = new StringJoiner(" ");
for (int i = 1; i <= N; i++) {
sj.add(Integer.toString(team[i]));
}
out.println(sj.toString());
out.close();
}
static long oo = (long) 9e18;
static class Pair {
int idx; long val;
public Pair(int ii, long vv) {
idx = ii; val = vv;
}
public String toString() {
return "(" + idx + ", " + val + ")";
}
}
static class SegmentTree {
Pair[] tree;
int N;
public SegmentTree(int size) {
N = size;
tree = new Pair[4 * N + 1];
Arrays.setAll(tree, i -> new Pair(-1, oo));
}
public void print() {
StringJoiner sj = new StringJoiner(" ");
for (int i = 0; i <= N; i++) {
sj.add(query(i, i).toString());
}
System.out.println(sj);
}
public Pair query(int l, int r) {
return query(1, 0, N - 1, l, r);
}
public Pair query(int node, int sl, int sr, int l, int r) {
if (sr < l || r < sl) {
return new Pair(-1, oo);
} else if (l <= sl && sr <= r) {
return tree[node];
} else {
int mid = (sl + sr) / 2;
Pair left = query(2 * node, sl, mid, l, r);
Pair right = query(2 * node + 1, mid + 1, sr, l, r);
return left.val < right.val ? left : right;
}
}
public void update(int i, long val) {
update(1, 0, N - 1, i, val);
}
public void update(int node, int sl, int sr, int i, long val) {
if (sr < i || i < sl) return;
else if (i == sl && sr == i) {
tree[node] = new Pair(sl, val);
} else {
int mid = (sl + sr) / 2;
update(2 * node, sl, mid, i, val);
update(2 * node + 1, mid + 1, sr, i, val);
if (tree[2 * node].val < tree[2 * node + 1].val) {
tree[node] = tree[2 * node];
} else {
tree[node] = tree[2 * node + 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);
}
static void ASSERT(boolean assertion) {
if (!assertion) throw new AssertionError();
}
} | Java | ["5\n1 1 3 4 2", "6\n1 5 12 13 2 15", "10\n1 2 5 129 185 581 1041 1909 1580 8150"] | 2 seconds | ["3 1\n1 1 1 1 1", "7 2\n2 2 1 1 2 1", "7486 3\n3 3 3 2 2 2 2 1 1 1"] | NoteIn the first example, there is only one team with skills $$$[1, 1, 2, 3, 4]$$$ so the answer is $$$3$$$. It can be shown that you cannot achieve a better answer.In the second example, there are two teams with skills $$$[1, 2, 5]$$$ and $$$[12, 13, 15]$$$ so the answer is $$$4 + 3 = 7$$$.In the third example, there are three teams with skills $$$[1, 2, 5]$$$, $$$[129, 185, 581, 1041]$$$ and $$$[1580, 1909, 8150]$$$ so the answer is $$$4 + 912 + 6570 = 7486$$$. | Java 8 | standard input | [
"dp",
"sortings",
"greedy"
] | 9ff029199394c3fa4ced7c65b2827b6c | The first line of the input contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of students. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the programming skill of the $$$i$$$-th student. | 2,000 | In the first line print two integers $$$res$$$ and $$$k$$$ — the minimum total diversity of the division of students and the number of teams in your division, correspondingly. In the second line print $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le k$$$), where $$$t_i$$$ is the number of team to which the $$$i$$$-th student belong. If there are multiple answers, you can print any. Note that you don't need to minimize the number of teams. Each team should consist of at least three students. | standard output | |
PASSED | ee870fb11aa6cdfd40c48933ebc7c0a4 | train_003.jsonl | 1572873300 | There are $$$n$$$ students at your university. The programming skill of the $$$i$$$-th student is $$$a_i$$$. As a coach, you want to divide them into teams to prepare them for the upcoming ICPC finals. Just imagine how good this university is if it has $$$2 \cdot 10^5$$$ students ready for the finals!Each team should consist of at least three students. Each student should belong to exactly one team. The diversity of a team is the difference between the maximum programming skill of some student that belongs to this team and the minimum programming skill of some student that belongs to this team (in other words, if the team consists of $$$k$$$ students with programming skills $$$a[i_1], a[i_2], \dots, a[i_k]$$$, then the diversity of this team is $$$\max\limits_{j=1}^{k} a[i_j] - \min\limits_{j=1}^{k} a[i_j]$$$).The total diversity is the sum of diversities of all teams formed.Your task is to minimize the total diversity of the division of students and find the optimal way to divide the students. | 256 megabytes | import java.awt.Point;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class thing {
public static void main(String[] args) throws FileNotFoundException {
//Scanner in = new Scanner(new File("template.in"));
Scanner in = new Scanner(System.in);
int n = in.nextInt();
Point[] a = new Point[n];
for(int i = 0; i < n; i++) {
a[i] = new Point(i, in.nextInt());
}
Arrays.sort(a, new Comparator<Point>() {
public int compare(Point a, Point b) {
return Integer.compare(a.y, b.y);
}
});
int[] dp = new int[n];
Arrays.fill(dp, Integer.MAX_VALUE);
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for(int i = 0; i < 2; i++) {
min = Math.min(min, a[i].y);
max = Math.max(max, a[i].y);
}
for(int i = 2; i < 5; i++) {
min = Math.min(min, a[i].y);
max = Math.max(max, a[i].y);
dp[i] = max - min;
}
int[] end = new int[n];
for(int i = 5; i < n; i++) {
for(int j = 0; j < 3; j++) {
if(i-j-3 < 0) continue;
if(dp[i-j-3] == Integer.MAX_VALUE) continue;
int calc = dp[i-j-3] + a[i].y - a[i-j-2].y;
if(calc < dp[i]) {
dp[i] = calc;
end[i] = i-j-2;
}
}
}
int team[] = new int[n];
System.out.print(dp[n-1] + " ");
int t = 1;
for(int i = n; i != 0; i = end[i], t++) {
i--;
for(int j = i; j >= end[i]; j--) {
team[a[j].x] = t;
}
}
System.out.println(t-1);
for(int i = 0; i < n; i++) {
System.out.print(team[i] + " ");
}
}
}
| Java | ["5\n1 1 3 4 2", "6\n1 5 12 13 2 15", "10\n1 2 5 129 185 581 1041 1909 1580 8150"] | 2 seconds | ["3 1\n1 1 1 1 1", "7 2\n2 2 1 1 2 1", "7486 3\n3 3 3 2 2 2 2 1 1 1"] | NoteIn the first example, there is only one team with skills $$$[1, 1, 2, 3, 4]$$$ so the answer is $$$3$$$. It can be shown that you cannot achieve a better answer.In the second example, there are two teams with skills $$$[1, 2, 5]$$$ and $$$[12, 13, 15]$$$ so the answer is $$$4 + 3 = 7$$$.In the third example, there are three teams with skills $$$[1, 2, 5]$$$, $$$[129, 185, 581, 1041]$$$ and $$$[1580, 1909, 8150]$$$ so the answer is $$$4 + 912 + 6570 = 7486$$$. | Java 8 | standard input | [
"dp",
"sortings",
"greedy"
] | 9ff029199394c3fa4ced7c65b2827b6c | The first line of the input contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of students. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the programming skill of the $$$i$$$-th student. | 2,000 | In the first line print two integers $$$res$$$ and $$$k$$$ — the minimum total diversity of the division of students and the number of teams in your division, correspondingly. In the second line print $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le k$$$), where $$$t_i$$$ is the number of team to which the $$$i$$$-th student belong. If there are multiple answers, you can print any. Note that you don't need to minimize the number of teams. Each team should consist of at least three students. | standard output | |
PASSED | acf7d44b355d65f4bf8f6e3c45e94d1e | train_003.jsonl | 1572873300 | There are $$$n$$$ students at your university. The programming skill of the $$$i$$$-th student is $$$a_i$$$. As a coach, you want to divide them into teams to prepare them for the upcoming ICPC finals. Just imagine how good this university is if it has $$$2 \cdot 10^5$$$ students ready for the finals!Each team should consist of at least three students. Each student should belong to exactly one team. The diversity of a team is the difference between the maximum programming skill of some student that belongs to this team and the minimum programming skill of some student that belongs to this team (in other words, if the team consists of $$$k$$$ students with programming skills $$$a[i_1], a[i_2], \dots, a[i_k]$$$, then the diversity of this team is $$$\max\limits_{j=1}^{k} a[i_j] - \min\limits_{j=1}^{k} a[i_j]$$$).The total diversity is the sum of diversities of all teams formed.Your task is to minimize the total diversity of the division of students and find the optimal way to divide the students. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
private static void execute(ContestReader reader, PrintWriter out) {
int n = reader.nextInt();
int[] as = reader.nextIntArray(n);
for (String line : new Solver(n, as).solve()) {
out.println(line);
}
}
public static void main(String[] args) {
ContestReader reader = new ContestReader(System.in);
PrintWriter out = new PrintWriter(System.out);
execute(reader, out);
out.flush();
}
}
class Player implements Comparable<Player> {
final int index, skill;
public Player(int index, int skill) {
this.index = index;
this.skill = skill;
}
public int compareTo(Player player) {
return this.skill - player.skill;
}
}
class Solver {
private static final long INF = 1L << 58;
final int n;
final int[] as;
Solver (int n, int[] as) {
this.n = n;
this.as = as;
}
List<String> solve() {
Player[] players = new Player[n];
for (int i = 0; i < n; i++) {
players[i] = new Player(i, as[i]);
}
Algorithm.sort(players);
long[] dps = new long[n + 1];
int[] prevs = new int[n + 1];
dps[0] = 0;
dps[1] = INF;
dps[2] = INF;
for (int i = 3; i <= n; i++) {
dps[i] = INF;
for (int j = 3; j <= 5; j++) {
if (i - j < 0) {
continue;
}
if (dps[i] > dps[i - j] + players[i - 1].skill - players[i - j].skill) {
dps[i] = dps[i - j] + players[i - 1].skill - players[i - j].skill;
prevs[i] = i - j;
}
}
}
long minScore = dps[n];
int[] assignment = new int[n];
int prevIndex = n;
int teamId = 1;
while (prevIndex > 0) {
int nextPrevIndex = prevs[prevIndex];
for (int i = nextPrevIndex; i < prevIndex; i++) {
assignment[players[i].index] = teamId;
}
prevIndex = nextPrevIndex;
teamId++;
}
StringBuffer sb = new StringBuffer();
sb.append(assignment[0]);
for (int i = 1; i < n; i++) {
sb.append(" ");
sb.append(assignment[i]);
}
return Arrays.asList(
String.format("%d %d", minScore, teamId - 1),
sb.toString()
);
}
}
class ContestReader {
private BufferedReader reader;
private StringTokenizer tokenizer;
ContestReader(InputStream in) {
reader = new BufferedReader(new InputStreamReader(in));
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new java.util.StringTokenizer(reader.readLine());
} catch (Exception 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[] nextArray(int n) {
String[] array = new String[n];
for (int i = 0; i < n; i++) {
array[i] = next();
}
return array;
}
public int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = nextInt();
}
return array;
}
public long[] nextLongArray(int n) {
long[] array = new long[n];
for (int i = 0; i < n; i++) {
array[i] = nextLong();
}
return array;
}
public double[] nextDoubleArray(int n) {
double[] array = new double[n];
for (int i = 0; i < n; i++) {
array[i] = nextDouble();
}
return array;
}
public int[][] nextIntMatrix(int n, int m) {
int[][] matrix = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
matrix[i][j] = nextInt();
}
}
return matrix;
}
public long[][] nextLongMatrix(int n, int m) {
long[][] matrix = new long[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
matrix[i][j] = nextLong();
}
}
return matrix;
}
public double[][] nextDoubleMatrix(int n, int m) {
double[][] matrix = new double[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
matrix[i][j] = nextDouble();
}
}
return matrix;
}
}
class Algorithm {
private static void swap(Object[] list, int a, int b) {
Object tmp = list[a];
list[a] = list[b];
list[b] = tmp;
}
public static <T extends Comparable<? super T>> boolean nextPermutation(T[] ts) {
int rightMostAscendingOrderIndex = ts.length - 2;
while (rightMostAscendingOrderIndex >= 0 &&
ts[rightMostAscendingOrderIndex].compareTo(ts[rightMostAscendingOrderIndex + 1]) >= 0) {
rightMostAscendingOrderIndex--;
}
if (rightMostAscendingOrderIndex < 0) {
return false;
}
int rightMostGreatorIndex = ts.length - 1;
while (ts[rightMostAscendingOrderIndex].compareTo(ts[rightMostGreatorIndex]) >= 0) {
rightMostGreatorIndex--;
}
swap(ts, rightMostAscendingOrderIndex, rightMostGreatorIndex);
for (int i = 0; i < (ts.length - rightMostAscendingOrderIndex - 1) / 2; i++) {
swap(ts, rightMostAscendingOrderIndex + 1 + i, ts.length - 1 - i);
}
return true;
}
public static void shuffle(int[] array) {
Random random = new Random();
int n = array.length;
for (int i = 0; i < n; i++) {
int randomIndex = i + random.nextInt(n - i);
int temp = array[i];
array[i] = array[randomIndex];
array[randomIndex] = temp;
}
}
public static void shuffle(long[] array) {
Random random = new Random();
int n = array.length;
for (int i = 0; i < n; i++) {
int randomIndex = i + random.nextInt(n - i);
long temp = array[i];
array[i] = array[randomIndex];
array[randomIndex] = temp;
}
}
public static void shuffle(Object[] array) {
Random random = new Random();
int n = array.length;
for (int i = 0; i < n; i++) {
int randomIndex = i + random.nextInt(n - i);
Object temp = array[i];
array[i] = array[randomIndex];
array[randomIndex] = temp;
}
}
public static void sort(int[] array) {
shuffle(array);
Arrays.sort(array);
}
public static void sort(long[] array) {
shuffle(array);
Arrays.sort(array);
}
public static void sort(Object[] array) {
shuffle(array);
Arrays.sort(array);
}
}
| Java | ["5\n1 1 3 4 2", "6\n1 5 12 13 2 15", "10\n1 2 5 129 185 581 1041 1909 1580 8150"] | 2 seconds | ["3 1\n1 1 1 1 1", "7 2\n2 2 1 1 2 1", "7486 3\n3 3 3 2 2 2 2 1 1 1"] | NoteIn the first example, there is only one team with skills $$$[1, 1, 2, 3, 4]$$$ so the answer is $$$3$$$. It can be shown that you cannot achieve a better answer.In the second example, there are two teams with skills $$$[1, 2, 5]$$$ and $$$[12, 13, 15]$$$ so the answer is $$$4 + 3 = 7$$$.In the third example, there are three teams with skills $$$[1, 2, 5]$$$, $$$[129, 185, 581, 1041]$$$ and $$$[1580, 1909, 8150]$$$ so the answer is $$$4 + 912 + 6570 = 7486$$$. | Java 8 | standard input | [
"dp",
"sortings",
"greedy"
] | 9ff029199394c3fa4ced7c65b2827b6c | The first line of the input contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of students. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the programming skill of the $$$i$$$-th student. | 2,000 | In the first line print two integers $$$res$$$ and $$$k$$$ — the minimum total diversity of the division of students and the number of teams in your division, correspondingly. In the second line print $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le k$$$), where $$$t_i$$$ is the number of team to which the $$$i$$$-th student belong. If there are multiple answers, you can print any. Note that you don't need to minimize the number of teams. Each team should consist of at least three students. | standard output | |
PASSED | 7dc31c9bd6ff0c09b5e8e351d94400d5 | train_003.jsonl | 1572873300 | There are $$$n$$$ students at your university. The programming skill of the $$$i$$$-th student is $$$a_i$$$. As a coach, you want to divide them into teams to prepare them for the upcoming ICPC finals. Just imagine how good this university is if it has $$$2 \cdot 10^5$$$ students ready for the finals!Each team should consist of at least three students. Each student should belong to exactly one team. The diversity of a team is the difference between the maximum programming skill of some student that belongs to this team and the minimum programming skill of some student that belongs to this team (in other words, if the team consists of $$$k$$$ students with programming skills $$$a[i_1], a[i_2], \dots, a[i_k]$$$, then the diversity of this team is $$$\max\limits_{j=1}^{k} a[i_j] - \min\limits_{j=1}^{k} a[i_j]$$$).The total diversity is the sum of diversities of all teams formed.Your task is to minimize the total diversity of the division of students and find the optimal way to divide the students. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
EYetAnotherDivisionIntoTeams solver = new EYetAnotherDivisionIntoTeams();
solver.solve(1, in, out);
out.close();
}
static class EYetAnotherDivisionIntoTeams {
static EYetAnotherDivisionIntoTeams.Player[] arr;
static int n;
static long inf = (long) 1e10;
static Long[][] memo;
public long dp(int idx, int count) {
if (idx == n)
return 0;
if (idx + 3 > n)
return inf;
if (memo[count][idx] != null)
return memo[count][idx];
long take3 = inf, take4 = inf, take5 = inf;
int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
for (int i = idx; i < idx + 3; i++) {
min = Math.min(min, arr[i].skill);
max = Math.max(max, arr[i].skill);
}
take3 = max - min;
if (idx + 3 < n) {
min = Math.min(min, arr[idx + 3].skill);
max = Math.max(max, arr[idx + 3].skill);
take4 = max - min;
}
if (idx + 4 < n) {
min = Math.min(min, arr[idx + 4].skill);
max = Math.max(max, arr[idx + 4].skill);
take5 = max - min;
}
take3 += dp(idx + 3, 3);
take4 += dp(idx + 4, 4);
take5 += dp(idx + 5, 5);
return memo[count][idx] = Math.min(take3, Math.min(take4, take5));
}
public int trace(int idx, int count, int[] ans, int teamnum) {
if (idx == n)
return teamnum - 1;
long cur = dp(idx, count);
int min = (int) 1e9, max = (int) -1e9;
for (int i = idx; i < idx + 3; i++) {
min = Math.min(min, arr[i].skill);
max = Math.max(max, arr[i].skill);
}
long take3 = max - min;
for (int i = idx; i < idx + 3; i++)
ans[arr[i].idx] = teamnum;
if (cur == take3 + dp(idx + 3, 3)) {
return trace(idx + 3, 3, ans, teamnum + 1);
}
ans[arr[idx + 3].idx] = teamnum;
if (idx + 3 < n) {
min = Math.min(min, arr[idx + 3].skill);
max = Math.max(max, arr[idx + 3].skill);
long take4 = max - min;
if (cur == take4 + dp(idx + 4, 4))
return trace(idx + 4, 4, ans, teamnum + 1);
}
ans[arr[idx + 4].idx] = teamnum;
return trace(idx + 5, 5, ans, teamnum + 1);
}
public void solve(int testNumber, Scanner sc, PrintWriter pw) {
n = sc.nextInt();
arr = new EYetAnotherDivisionIntoTeams.Player[n];
memo = new Long[6][n];
for (int i = 0; i < n; i++)
arr[i] = new EYetAnotherDivisionIntoTeams.Player(sc.nextInt(), i);
int[] ans = new int[n];
Arrays.sort(arr);
pw.println(dp(0, 0) + " " + trace(0, 0, ans, 1));
for (int x : ans)
pw.print(x + " ");
}
static class Player implements Comparable<EYetAnotherDivisionIntoTeams.Player> {
int skill;
int idx;
public Player(int skill, int idx) {
this.idx = idx;
this.skill = skill;
}
public String toString() {
return skill + " " + idx;
}
public int compareTo(EYetAnotherDivisionIntoTeams.Player player) {
return skill - player.skill;
}
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["5\n1 1 3 4 2", "6\n1 5 12 13 2 15", "10\n1 2 5 129 185 581 1041 1909 1580 8150"] | 2 seconds | ["3 1\n1 1 1 1 1", "7 2\n2 2 1 1 2 1", "7486 3\n3 3 3 2 2 2 2 1 1 1"] | NoteIn the first example, there is only one team with skills $$$[1, 1, 2, 3, 4]$$$ so the answer is $$$3$$$. It can be shown that you cannot achieve a better answer.In the second example, there are two teams with skills $$$[1, 2, 5]$$$ and $$$[12, 13, 15]$$$ so the answer is $$$4 + 3 = 7$$$.In the third example, there are three teams with skills $$$[1, 2, 5]$$$, $$$[129, 185, 581, 1041]$$$ and $$$[1580, 1909, 8150]$$$ so the answer is $$$4 + 912 + 6570 = 7486$$$. | Java 8 | standard input | [
"dp",
"sortings",
"greedy"
] | 9ff029199394c3fa4ced7c65b2827b6c | The first line of the input contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of students. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the programming skill of the $$$i$$$-th student. | 2,000 | In the first line print two integers $$$res$$$ and $$$k$$$ — the minimum total diversity of the division of students and the number of teams in your division, correspondingly. In the second line print $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le k$$$), where $$$t_i$$$ is the number of team to which the $$$i$$$-th student belong. If there are multiple answers, you can print any. Note that you don't need to minimize the number of teams. Each team should consist of at least three students. | standard output | |
PASSED | f244e65c62c3d2dbce812551bd165ccb | train_003.jsonl | 1442939400 | When Kefa came to the restaurant and sat at a table, the waiter immediately brought him the menu. There were n dishes. Kefa knows that he needs exactly m dishes. But at that, he doesn't want to order the same dish twice to taste as many dishes as possible. Kefa knows that the i-th dish gives him ai units of satisfaction. But some dishes do not go well together and some dishes go very well together. Kefa set to himself k rules of eating food of the following type — if he eats dish x exactly before dish y (there should be no other dishes between x and y), then his satisfaction level raises by c. Of course, our parrot wants to get some maximal possible satisfaction from going to the restaurant. Help him in this hard task! | 256 megabytes | /*import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
public class KefaandDishes {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
new KefaandDishes().solve(in,out);
in.close();
out.close();
}
int N, M, K;
int[][] bonusPoints;
long[][] memo;
int[] satisfaction;
private void solve(Scanner in, PrintWriter out) {
N = in.nextInt();
M = in.nextInt();
K = in.nextInt();
satisfaction = new int[N];
for(int n=0; n<N; n++) {
satisfaction[n] = in.nextInt();
}
memo = new long[1<<N][N];
for(int i=0; i< 1<<N; i++) {
Arrays.fill(memo[i], -1);
}
bonusPoints = new int[N][N];
for(int k=0; k<K; k++) {
int x = in.nextInt()-1;
int y = in.nextInt()-1;
bonusPoints[x][y] = in.nextInt();
}
//System.out.println(Integer.toBinaryString((1<<N)-1));
// make sure 1<<N is IN PARENTHESIS below!
out.println(dp((1<<N)-1, -1));
}
final int oo = (int) 1e9;
private long dp(int mask, int curr) {
if(Integer.bitCount((1<<N)-1) - Integer.bitCount(mask) == M) {
//System.out.println("ans " + Integer.toBinaryString(mask) );
return 0;
}
if(curr != -1 && memo[mask][curr] != -1) return memo[mask][curr];
long best = -oo;
for(int next =0; next<N; next++) {
if(((1<<next) & mask) == 0) continue;
int toAdd = 0;
if(curr != -1) toAdd = bonusPoints[curr][next];
//System.out.println(Integer.toBinaryString(mask) + " " + next + " " + toAdd);
best = Math.max(best, toAdd + satisfaction[next] + dp(mask-(1<<next), next));
}
//System.out.println(best);
if(curr!=-1) memo[mask][curr] = best;
return best;
}
}*/
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
public class KefaandDishes {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
new KefaandDishes().solve(in,out);
in.close();
out.close();
}
int N, M, K;
int[][] bonusPoints;
long[][] memo;
int[] satisfaction;
private void solve(Scanner in, PrintWriter out) {
N = in.nextInt();
M = in.nextInt();
K = in.nextInt();
satisfaction = new int[N];
for(int n=0; n<N; n++) {
satisfaction[n] = in.nextInt();
}
memo = new long[N][1<<N];
for(int i=0; i<N; i++) {
Arrays.fill(memo[i], -1);
}
bonusPoints = new int[N][N];
for(int k=0; k<K; k++) {
int x = in.nextInt()-1;
int y = in.nextInt()-1;
bonusPoints[x][y] = in.nextInt();
}
//System.out.println(Integer.toBinaryString((1<<N)-1));
// make sure 1<<N is IN PARENTHESIS below!
out.println(dp((1<<N)-1, -1));
}
final int oo = (int) 1e9;
private long dp(int mask, int curr) {
if(Integer.bitCount((1<<N)-1) - Integer.bitCount(mask) == M) {
//System.out.println("ans " + Integer.toBinaryString(mask) );
return 0;
}
if(curr != -1 && memo[curr][mask] != -1) return memo[curr][mask];
long best = -oo;
for(int next =0; next<N; next++) {
if(((1<<next) & mask) == 0) continue;
int toAdd = 0;
if(curr != -1) toAdd = bonusPoints[curr][next];
//System.out.println(Integer.toBinaryString(mask) + " " + next + " " + toAdd);
best = Math.max(best, toAdd + satisfaction[next] + dp(mask-(1<<next), next));
}
//System.out.println(best);
if(curr!=-1) memo[curr][mask] = best;
return best;
}
}
| Java | ["2 2 1\n1 1\n2 1 1", "4 3 2\n1 2 3 4\n2 1 5\n3 4 2"] | 2 seconds | ["3", "12"] | NoteIn the first sample it is best to first eat the second dish, then the first one. Then we get one unit of satisfaction for each dish and plus one more for the rule.In the second test the fitting sequences of choice are 4 2 1 or 2 1 4. In both cases we get satisfaction 7 for dishes and also, if we fulfill rule 1, we get an additional satisfaction 5. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 5b881f1cd74b17358b954299c2742bdf | The first line of the input contains three space-separated numbers, n, m and k (1 ≤ m ≤ n ≤ 18, 0 ≤ k ≤ n * (n - 1)) — the number of dishes on the menu, the number of portions Kefa needs to eat to get full and the number of eating rules. The second line contains n space-separated numbers ai, (0 ≤ ai ≤ 109) — the satisfaction he gets from the i-th dish. Next k lines contain the rules. The i-th rule is described by the three numbers xi, yi and ci (1 ≤ xi, yi ≤ n, 0 ≤ ci ≤ 109). That means that if you eat dish xi right before dish yi, then the Kefa's satisfaction increases by ci. It is guaranteed that there are no such pairs of indexes i and j (1 ≤ i < j ≤ k), that xi = xj and yi = yj. | 1,800 | In the single line of the output print the maximum satisfaction that Kefa can get from going to the restaurant. | standard output | |
PASSED | b11359e38377f07e14e51c906017c441 | train_003.jsonl | 1442939400 | When Kefa came to the restaurant and sat at a table, the waiter immediately brought him the menu. There were n dishes. Kefa knows that he needs exactly m dishes. But at that, he doesn't want to order the same dish twice to taste as many dishes as possible. Kefa knows that the i-th dish gives him ai units of satisfaction. But some dishes do not go well together and some dishes go very well together. Kefa set to himself k rules of eating food of the following type — if he eats dish x exactly before dish y (there should be no other dishes between x and y), then his satisfaction level raises by c. Of course, our parrot wants to get some maximal possible satisfaction from going to the restaurant. Help him in this hard task! | 256 megabytes | import java.io.*;
import java.util.*;
public class Abc {
static int n, m, k;
static long a[];
static long dp[][];
static long raise[][];
public static void main(String[] args) throws Exception {
FastReader sc = new FastReader();
n = sc.nextInt();
m = sc.nextInt();
k = sc.nextInt();
a = new long[n];
long max1=0;
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
max1=Math.max(max1,a[i]);
}
if (m==1){
System.out.println(max1);
return;
}
raise = new long[n][n];
dp = new long[(1 << n)][n];
for (long ar[]:dp) {
Arrays.fill(ar, -1);
}
for (int i = 0; i < k; i++) {
int x = sc.nextInt()-1, y = sc.nextInt()-1, c = sc.nextInt();
raise[x][y] = c;
}
long max=0;
for (int i=0;i<n;i++){
for (int j=0;j<n;j++){
if (i==j)continue;
max=Math.max(a[i]+a[j]+raise[j][i]+dp((1<<i)+(1<<j),i),max);
}
}
System.out.println(max);
}
static long dp(int mask, int prev) {
if (cntBits(mask) == m) return 0;
if (dp[mask][prev] != -1) return dp[mask][prev];
dp[mask][prev] = 0;
for (int i = 0; i <n; i++) {
if ((mask & (1 << i)) != 0) continue;
dp[mask][prev] = Math.max(dp[mask][prev], a[i] + dp((mask | (1 << i)), i) + raise[prev][i]);
}
return dp[mask][prev];
}
static int cntBits(int x) {
int c = 0;
for (int i = 0; i < 30; i++) {
if ((x & (1 << i)) != 0) {
c++;
}
}
return c;
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["2 2 1\n1 1\n2 1 1", "4 3 2\n1 2 3 4\n2 1 5\n3 4 2"] | 2 seconds | ["3", "12"] | NoteIn the first sample it is best to first eat the second dish, then the first one. Then we get one unit of satisfaction for each dish and plus one more for the rule.In the second test the fitting sequences of choice are 4 2 1 or 2 1 4. In both cases we get satisfaction 7 for dishes and also, if we fulfill rule 1, we get an additional satisfaction 5. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 5b881f1cd74b17358b954299c2742bdf | The first line of the input contains three space-separated numbers, n, m and k (1 ≤ m ≤ n ≤ 18, 0 ≤ k ≤ n * (n - 1)) — the number of dishes on the menu, the number of portions Kefa needs to eat to get full and the number of eating rules. The second line contains n space-separated numbers ai, (0 ≤ ai ≤ 109) — the satisfaction he gets from the i-th dish. Next k lines contain the rules. The i-th rule is described by the three numbers xi, yi and ci (1 ≤ xi, yi ≤ n, 0 ≤ ci ≤ 109). That means that if you eat dish xi right before dish yi, then the Kefa's satisfaction increases by ci. It is guaranteed that there are no such pairs of indexes i and j (1 ≤ i < j ≤ k), that xi = xj and yi = yj. | 1,800 | In the single line of the output print the maximum satisfaction that Kefa can get from going to the restaurant. | standard output | |
PASSED | 72e2eaafa44b88daf74f86ee9bd169c4 | train_003.jsonl | 1442939400 | When Kefa came to the restaurant and sat at a table, the waiter immediately brought him the menu. There were n dishes. Kefa knows that he needs exactly m dishes. But at that, he doesn't want to order the same dish twice to taste as many dishes as possible. Kefa knows that the i-th dish gives him ai units of satisfaction. But some dishes do not go well together and some dishes go very well together. Kefa set to himself k rules of eating food of the following type — if he eats dish x exactly before dish y (there should be no other dishes between x and y), then his satisfaction level raises by c. Of course, our parrot wants to get some maximal possible satisfaction from going to the restaurant. Help him in this hard task! | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Kefa_And_Dishes {
static long [] nums;
static long [] [] bonus;
static int total;
static long [][] memo;
public static void main(String[] args)throws Throwable {
BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer(bf.readLine());
st.nextToken();
total=Integer.parseInt(st.nextToken());
int rules=Integer.parseInt(st.nextToken());
st=new StringTokenizer(bf.readLine());
nums =new long [st.countTokens()];
bonus=new long [st.countTokens()+1][st.countTokens()+1];
memo=new long [(1<<st.countTokens())+2][st.countTokens()+2];
for(int i=0;i<memo.length;i++)
Arrays.fill(memo[i], -1);
for(int i=0;st.hasMoreTokens();i++)
nums[i]=Integer.parseInt(st.nextToken());
while(rules-->0)
{
st=new StringTokenizer(bf.readLine());
int from=Integer.parseInt(st.nextToken());
int to=Integer.parseInt(st.nextToken());
bonus[from][to]=Integer.parseInt(st.nextToken());
}
System.out.println(solve(0,-1));
}
static long solve(int bit,int last)//can use need and last as bitmask where need is num of bits and last is last bit with 1 [int solve(int i,int need,int last)]
{
if(memo[bit][last+1]!=-1)
return memo[bit][last+1];
int need=total-Integer.bitCount(bit);
if(need==0)
return memo[bit][last+1]=0;
long ans=-1;
for(int i=0;i<nums.length;i++)
if((bit&(1<<i))==0)
ans=Math.max(ans, nums[i]+bonus[last+1][i+1]+solve(bit|(1<<i),i));
return memo[bit][last+1]=ans;
}
}
| Java | ["2 2 1\n1 1\n2 1 1", "4 3 2\n1 2 3 4\n2 1 5\n3 4 2"] | 2 seconds | ["3", "12"] | NoteIn the first sample it is best to first eat the second dish, then the first one. Then we get one unit of satisfaction for each dish and plus one more for the rule.In the second test the fitting sequences of choice are 4 2 1 or 2 1 4. In both cases we get satisfaction 7 for dishes and also, if we fulfill rule 1, we get an additional satisfaction 5. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 5b881f1cd74b17358b954299c2742bdf | The first line of the input contains three space-separated numbers, n, m and k (1 ≤ m ≤ n ≤ 18, 0 ≤ k ≤ n * (n - 1)) — the number of dishes on the menu, the number of portions Kefa needs to eat to get full and the number of eating rules. The second line contains n space-separated numbers ai, (0 ≤ ai ≤ 109) — the satisfaction he gets from the i-th dish. Next k lines contain the rules. The i-th rule is described by the three numbers xi, yi and ci (1 ≤ xi, yi ≤ n, 0 ≤ ci ≤ 109). That means that if you eat dish xi right before dish yi, then the Kefa's satisfaction increases by ci. It is guaranteed that there are no such pairs of indexes i and j (1 ≤ i < j ≤ k), that xi = xj and yi = yj. | 1,800 | In the single line of the output print the maximum satisfaction that Kefa can get from going to the restaurant. | standard output | |
PASSED | 147ef9a761c57eaf8c47e0b881822244 | train_003.jsonl | 1442939400 | When Kefa came to the restaurant and sat at a table, the waiter immediately brought him the menu. There were n dishes. Kefa knows that he needs exactly m dishes. But at that, he doesn't want to order the same dish twice to taste as many dishes as possible. Kefa knows that the i-th dish gives him ai units of satisfaction. But some dishes do not go well together and some dishes go very well together. Kefa set to himself k rules of eating food of the following type — if he eats dish x exactly before dish y (there should be no other dishes between x and y), then his satisfaction level raises by c. Of course, our parrot wants to get some maximal possible satisfaction from going to the restaurant. Help him in this hard task! | 256 megabytes | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.*;
import java.io.*;
public class codeforces
{
static class Student{
int x,y;//z;
Student(int x,int y){
this.x=x;
this.y=y;
//this.z=z;
}
}
static int prime[];
static void sieveOfEratosthenes(int n)
{
// Create a boolean array "prime[0..n]" and initialize
// all entries it as true. A value in prime[i] will
// finally be false if i is Not a prime, else true.
int pos=0;
prime= new int[n+1];
for(int p = 2; p*p <=n; p++)
{
// If prime[p] is not changed, then it is a prime
if(prime[p] == 0)
{
// Update all multiples of p
prime[p]=p;
for(int i = p*p; i <= n; i += p)
if(prime[i]==0)
prime[i] = p;
}
}
}
static class Sortbyroll implements Comparator<Student>
{
// Used for sorting in ascending order of
// roll number
public int compare(Student c, Student b)
{
return c.y-b.y;
}
}
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 Edge{
int a,b;
Edge(int a,int b){
this.a=a;
this.b=b;
}
}
static class Trie{
HashMap<Character,Trie>map;
int c;
Trie(){
map=new HashMap<>();
//z=null;
//o=null;
c=0;
}
}
//static long ans;
static int parent[];
static int rank[];
// static int b[][];
static int bo[][];
static int ho[][];
static int seg[];
//static int pos;
// static long mod=1000000007;
//static int dp[][];
static HashMap<String,Integer>map;
static PriorityQueue<Student>q=new PriorityQueue<>();
//static Stack<Integer>st;
// static ArrayList<Character>ans;
static ArrayList<ArrayList<Integer>>adj;
//static long ans;
static int pos;
static Trie root;
static long fac[];
static int gw,gb;
static long mod=(long)(998244353);
static int ans;
static void solve()throws IOException{
FastReader sc=new FastReader();
int n,m,k,i,j,k1,x,y,c;
long ans=0;
n=sc.nextInt();
m=sc.nextInt();
k1=sc.nextInt();
int a[]=new int[n];
for(i=0;i<n;i++)
a[i]=sc.nextInt();
//HashMap<String,Integer>map=new HashMap<>();
int c1[][]=new int[n][n];
for(i=0;i<k1;i++){
x=sc.nextInt()-1;
y=sc.nextInt()-1;
//map.put(y+" "+x,sc.nextInt());
c1[y][x]=sc.nextInt();
}
ArrayList<Student>arr=new ArrayList<>();
for(i=0;i<(int)Math.pow(2,n);i++){
c=0;
for(j=0;j<n;j++){
if((int)(((int)(1<<j))&i)!=0)
++c;
}
arr.add(new Student(i,c));
}
Collections.sort(arr,new Sortbyroll());
long dp[][]=new long[n][(int)Math.pow(2,n)];
long dp1[]=new long[n+1];
for(i=0;i<arr.size();i++){
// System.out.println(arr.get(i).x+" "+arr.get(i).y);
for(j=0;j<n;j++){
if((int)(((int)(1<<j))&arr.get(i).x)!=0){
y=arr.get(i).x^((int)(1<<j));
ans=0;
for(k=0;k<n;k++){
if((((int)(1<<k))&y)!=0){
ans=Math.max(ans,dp[k][y^((int)(1<<k))]+c1[j][k]);
}
}
ans+=(long)a[j];
dp[j][y]=ans;
dp1[arr.get(i).y]=Math.max(dp1[arr.get(i).y],ans);
}
}
}
System.out.println(dp1[m]);
}
static boolean isSafe(int x,int y,int b[][],String s[] ){
if(x>=0&&x<b.length&&y>=0&&y<b[0].length&&s[x].charAt(y)=='#'&&b[x][y]==0)
return true;
return false;
}
static void add(int x,int y,Queue<Integer>q,Queue<Integer>v,int b[][]){
q.add(x);
v.add(y);
b[x][y]=1;
}
static long nCr(long n, long r,
long p)
{
return (fac[(int)n]* modInverse(fac[(int)r], p)
% p * modInverse(fac[(int)(n-r)], p)
% p) % p;
}
//static int prime[];
//static int dp[];
public static void main(String[] args){
//long sum=0;
try {
codeforces.solve();
} catch (Exception e) {
e.printStackTrace();
}
}
static long modInverse(long n, long p)
{
return power(n, p-(long)2,p);
}
static long power(long x, long y, long p)
{
long res = 1; // Initialize result
x = x % p; // Update x if it is more than or
// equal to p
while (y > 0)
{
// If y is odd, multiply x with result
if (y %(long)2!=0)
res = (res*x) % p;
// y must be even now
y = y>>1; // y = y/2
x = (x*x) % p;
}
return res%p;
}
/*public static long power(long x,long a) {
if(a==0) return 1;
if(a%2==1)return (x*1L*power(x,a-1))%mod;
return (power((int)((x*1L*x)%mod),a/2))%mod;
}*/
static int find(int x)
{
// Finds the representative of the set
// that x is an element of
while(parent[x]!=x)
{
// if x is not the parent of itself
// Then x is not the representative of
// his set,
x=parent[x];
// so we recursively call Find on its parent
// and move i's node directly under the
// representative of this set
}
return x;
}
static void union(int x, int y)
{
// Find representatives of two sets
int xRoot = find(x), yRoot = find(y);
// Elements are in the same set, no need
// to unite anything.
if (xRoot == yRoot)
return;
// If x's rank is less than y's rank
if (rank[xRoot] < rank[yRoot])
// Then move x under y so that depth
// of tree remains less
parent[xRoot] = yRoot;
// Else if y's rank is less than x's rank
else if (rank[yRoot] < rank[xRoot])
// Then move y under x so that depth of
// tree remains less
parent[yRoot] = xRoot;
else // if ranks are the same
{
// Then move y under x (doesn't matter
// which one goes where)
parent[yRoot] = xRoot;
// And increment the the result tree's
// rank by 1
rank[xRoot] = rank[xRoot] + 1;
}
}
static long gcd(long a, long b)
{
if (a == 0){
//ans+=b;
return b;
}
return gcd(b % a, a);
}
} | Java | ["2 2 1\n1 1\n2 1 1", "4 3 2\n1 2 3 4\n2 1 5\n3 4 2"] | 2 seconds | ["3", "12"] | NoteIn the first sample it is best to first eat the second dish, then the first one. Then we get one unit of satisfaction for each dish and plus one more for the rule.In the second test the fitting sequences of choice are 4 2 1 or 2 1 4. In both cases we get satisfaction 7 for dishes and also, if we fulfill rule 1, we get an additional satisfaction 5. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 5b881f1cd74b17358b954299c2742bdf | The first line of the input contains three space-separated numbers, n, m and k (1 ≤ m ≤ n ≤ 18, 0 ≤ k ≤ n * (n - 1)) — the number of dishes on the menu, the number of portions Kefa needs to eat to get full and the number of eating rules. The second line contains n space-separated numbers ai, (0 ≤ ai ≤ 109) — the satisfaction he gets from the i-th dish. Next k lines contain the rules. The i-th rule is described by the three numbers xi, yi and ci (1 ≤ xi, yi ≤ n, 0 ≤ ci ≤ 109). That means that if you eat dish xi right before dish yi, then the Kefa's satisfaction increases by ci. It is guaranteed that there are no such pairs of indexes i and j (1 ≤ i < j ≤ k), that xi = xj and yi = yj. | 1,800 | In the single line of the output print the maximum satisfaction that Kefa can get from going to the restaurant. | standard output | |
PASSED | a67f53946c73a2230c2d849265d0fe79 | train_003.jsonl | 1442939400 | When Kefa came to the restaurant and sat at a table, the waiter immediately brought him the menu. There were n dishes. Kefa knows that he needs exactly m dishes. But at that, he doesn't want to order the same dish twice to taste as many dishes as possible. Kefa knows that the i-th dish gives him ai units of satisfaction. But some dishes do not go well together and some dishes go very well together. Kefa set to himself k rules of eating food of the following type — if he eats dish x exactly before dish y (there should be no other dishes between x and y), then his satisfaction level raises by c. Of course, our parrot wants to get some maximal possible satisfaction from going to the restaurant. Help him in this hard task! | 256 megabytes | import java.util.Scanner;
public class Bitmask {
static int arr[];
static int bonus [][];
static long dp[][];
static long res = -1;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(), m = sc.nextInt(), k = sc.nextInt();
arr = new int[n];
bonus = new int[n][n];
dp = new long[1 << n][n];
for(int i = 0; i<n; i++) {
arr[i] = sc.nextInt();
res = Math.max(res, arr[i]);
}
for(int i = 0; i<k; i++) {
int first = sc.nextInt();
int next = sc.nextInt();
int ext = sc.nextInt();
bonus[first-1][next-1] = ext;
}
for(int mask = 1; mask<(1 << n); mask++) {
int cnt = Integer.bitCount(mask);
int first = Right_most_setbit(mask);
if(cnt > m) continue;
if(cnt == 1) {
dp[mask][first] = arr[first];
continue;
}
for(int lst = 0; lst<n; lst++) {
dp[mask][lst] = -1000000000;
if(((1 << lst) & mask) != 0) {
for(int lst2=0; lst2 < n; lst2++) {
if(lst2 != lst && ((1 << lst2) & mask) != 0) {
dp[mask][lst] = Math.max(dp[mask][lst], dp[mask ^ (1 << lst)][lst2]+arr[lst]+bonus[lst2][lst]);
}
}
}
if(cnt == m) {
res = Math.max(res, dp[mask][lst]);
}
}
}
System.out.println(res);
}
static int Right_most_setbit(int num)
{
int pos = 0;
int INT_SIZE = 32;
// counting the position of first set bit
for (int i = 0; i < INT_SIZE; i++) {
if ((num & (1 << i)) == 0)
pos++;
else
break;
}
return pos;
}
}
| Java | ["2 2 1\n1 1\n2 1 1", "4 3 2\n1 2 3 4\n2 1 5\n3 4 2"] | 2 seconds | ["3", "12"] | NoteIn the first sample it is best to first eat the second dish, then the first one. Then we get one unit of satisfaction for each dish and plus one more for the rule.In the second test the fitting sequences of choice are 4 2 1 or 2 1 4. In both cases we get satisfaction 7 for dishes and also, if we fulfill rule 1, we get an additional satisfaction 5. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 5b881f1cd74b17358b954299c2742bdf | The first line of the input contains three space-separated numbers, n, m and k (1 ≤ m ≤ n ≤ 18, 0 ≤ k ≤ n * (n - 1)) — the number of dishes on the menu, the number of portions Kefa needs to eat to get full and the number of eating rules. The second line contains n space-separated numbers ai, (0 ≤ ai ≤ 109) — the satisfaction he gets from the i-th dish. Next k lines contain the rules. The i-th rule is described by the three numbers xi, yi and ci (1 ≤ xi, yi ≤ n, 0 ≤ ci ≤ 109). That means that if you eat dish xi right before dish yi, then the Kefa's satisfaction increases by ci. It is guaranteed that there are no such pairs of indexes i and j (1 ≤ i < j ≤ k), that xi = xj and yi = yj. | 1,800 | In the single line of the output print the maximum satisfaction that Kefa can get from going to the restaurant. | standard output | |
PASSED | fec1599d2587657eb77c97566e4e36b8 | train_003.jsonl | 1442939400 | When Kefa came to the restaurant and sat at a table, the waiter immediately brought him the menu. There were n dishes. Kefa knows that he needs exactly m dishes. But at that, he doesn't want to order the same dish twice to taste as many dishes as possible. Kefa knows that the i-th dish gives him ai units of satisfaction. But some dishes do not go well together and some dishes go very well together. Kefa set to himself k rules of eating food of the following type — if he eats dish x exactly before dish y (there should be no other dishes between x and y), then his satisfaction level raises by c. Of course, our parrot wants to get some maximal possible satisfaction from going to the restaurant. Help him in this hard task! | 256 megabytes | import java.awt.Point;
import java.io.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.*;
import java.util.Map.Entry;
public class Tests {
static Scanner in = new Scanner();
static PrintWriter out = new PrintWriter(System.out);
static int n, m, k;
static int A[], bouns[][];
static long memo[][];
public static void main(String[] test) throws NumberFormatException, IOException {
n = in.nextInt();
m = in.nextInt();
k = in.nextInt();
A = new int[n];
for (int i = 0; i < n; A[i++] = in.nextInt())
;
bouns = new int[n + 5][n + 5];
for (int i = 0; i < k; i++) {
int x = in.nextInt() - 1;
int y = in.nextInt() - 1;
bouns[x][y] = in.nextInt();
}
memo = new long[n + 5][(1 << n) + 5];
for (int i = 0; i < memo.length; i++) {
Arrays.fill(memo[i], -1);
}
out.println(dp(n, 0));
out.flush();
out.close();
}
static long dp(int last, int mask) {
if (Integer.bitCount(mask) == m) {
return 0;
}
if (memo[last][mask] != -1) {
return memo[last][mask];
}
long ret = 0L;
for (int dish = 0; dish < n; dish++) {
if (!isOn(mask, dish)) {
ret = Math.max(ret, 1L * dp(dish, setBit(mask, dish)) + A[dish] + bouns[last][dish]);
}
}
return memo[last][mask] = ret;
}
static int setBit(int S, int j) {
return S | (1 << j);
}
static boolean isOn(int S, int j) {
return (S & (1 << j)) != 0;
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
Scanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
Scanner(String file) throws FileNotFoundException {
br = new BufferedReader(new FileReader(file));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(next());
}
String nextLine() throws IOException {
return br.readLine();
}
long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(next());
}
public int[] nextIntArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
}
}
| Java | ["2 2 1\n1 1\n2 1 1", "4 3 2\n1 2 3 4\n2 1 5\n3 4 2"] | 2 seconds | ["3", "12"] | NoteIn the first sample it is best to first eat the second dish, then the first one. Then we get one unit of satisfaction for each dish and plus one more for the rule.In the second test the fitting sequences of choice are 4 2 1 or 2 1 4. In both cases we get satisfaction 7 for dishes and also, if we fulfill rule 1, we get an additional satisfaction 5. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 5b881f1cd74b17358b954299c2742bdf | The first line of the input contains three space-separated numbers, n, m and k (1 ≤ m ≤ n ≤ 18, 0 ≤ k ≤ n * (n - 1)) — the number of dishes on the menu, the number of portions Kefa needs to eat to get full and the number of eating rules. The second line contains n space-separated numbers ai, (0 ≤ ai ≤ 109) — the satisfaction he gets from the i-th dish. Next k lines contain the rules. The i-th rule is described by the three numbers xi, yi and ci (1 ≤ xi, yi ≤ n, 0 ≤ ci ≤ 109). That means that if you eat dish xi right before dish yi, then the Kefa's satisfaction increases by ci. It is guaranteed that there are no such pairs of indexes i and j (1 ≤ i < j ≤ k), that xi = xj and yi = yj. | 1,800 | In the single line of the output print the maximum satisfaction that Kefa can get from going to the restaurant. | standard output | |
PASSED | a3cbabeccecaed940017f9d2cc7f9905 | train_003.jsonl | 1442939400 | When Kefa came to the restaurant and sat at a table, the waiter immediately brought him the menu. There were n dishes. Kefa knows that he needs exactly m dishes. But at that, he doesn't want to order the same dish twice to taste as many dishes as possible. Kefa knows that the i-th dish gives him ai units of satisfaction. But some dishes do not go well together and some dishes go very well together. Kefa set to himself k rules of eating food of the following type — if he eats dish x exactly before dish y (there should be no other dishes between x and y), then his satisfaction level raises by c. Of course, our parrot wants to get some maximal possible satisfaction from going to the restaurant. Help him in this hard task! | 256 megabytes | import java.util.*;
import java.io.*;
public class Codeforces{
static int[][] satisfaction;
static int[] dishes;
static long[][] memo;
static int n, m;
static long INF = (long) -1e16;
static long dp(int msk, int last, int idx){
if(idx == m){
return 0;
}
if(memo[msk][last] != -1){
return memo[msk][last];
}
long max = INF;
for(int i = 0; i < n; i++){
if((msk & 1<<i) == 0){
max = Math.max(max, dishes[i] + (satisfaction[last][i] != -1 ? satisfaction[last][i] : 0) + dp(msk | 1<<i, i, idx + 1));
}
}
return memo[msk][last] = max;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
m = Integer.parseInt(st.nextToken());
int k = Integer.parseInt(st.nextToken());
dishes = new int[n];
st = new StringTokenizer(br.readLine());
for(int i = 0; i < n; i++){
dishes[i] = Integer.parseInt(st.nextToken());
}
satisfaction = new int[n + 1][n + 1];
for(int i = 0; i < satisfaction.length; i++){
Arrays.fill(satisfaction[i], -1);
}
for(int i = 0; i < k; i++){
st = new StringTokenizer(br.readLine());
int x = Integer.parseInt(st.nextToken()) - 1;
int y = Integer.parseInt(st.nextToken()) - 1;
satisfaction[x][y] = Integer.parseInt(st.nextToken());
}
memo = new long[1<<18][19];
for(int i = 0; i < memo.length; i++){
Arrays.fill(memo[i], -1);
}
System.out.println(dp(0, n, 0));
}
} | Java | ["2 2 1\n1 1\n2 1 1", "4 3 2\n1 2 3 4\n2 1 5\n3 4 2"] | 2 seconds | ["3", "12"] | NoteIn the first sample it is best to first eat the second dish, then the first one. Then we get one unit of satisfaction for each dish and plus one more for the rule.In the second test the fitting sequences of choice are 4 2 1 or 2 1 4. In both cases we get satisfaction 7 for dishes and also, if we fulfill rule 1, we get an additional satisfaction 5. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 5b881f1cd74b17358b954299c2742bdf | The first line of the input contains three space-separated numbers, n, m and k (1 ≤ m ≤ n ≤ 18, 0 ≤ k ≤ n * (n - 1)) — the number of dishes on the menu, the number of portions Kefa needs to eat to get full and the number of eating rules. The second line contains n space-separated numbers ai, (0 ≤ ai ≤ 109) — the satisfaction he gets from the i-th dish. Next k lines contain the rules. The i-th rule is described by the three numbers xi, yi and ci (1 ≤ xi, yi ≤ n, 0 ≤ ci ≤ 109). That means that if you eat dish xi right before dish yi, then the Kefa's satisfaction increases by ci. It is guaranteed that there are no such pairs of indexes i and j (1 ≤ i < j ≤ k), that xi = xj and yi = yj. | 1,800 | In the single line of the output print the maximum satisfaction that Kefa can get from going to the restaurant. | standard output | |
PASSED | b54602f6df0687fb79041ee1878b3847 | train_003.jsonl | 1442939400 | When Kefa came to the restaurant and sat at a table, the waiter immediately brought him the menu. There were n dishes. Kefa knows that he needs exactly m dishes. But at that, he doesn't want to order the same dish twice to taste as many dishes as possible. Kefa knows that the i-th dish gives him ai units of satisfaction. But some dishes do not go well together and some dishes go very well together. Kefa set to himself k rules of eating food of the following type — if he eats dish x exactly before dish y (there should be no other dishes between x and y), then his satisfaction level raises by c. Of course, our parrot wants to get some maximal possible satisfaction from going to the restaurant. Help him in this hard task! | 256 megabytes | import java.util.Scanner;
public class Bluda {
public static int getOnesAmount(int num) {
int res = 0;
while(num != 0) {
if(num % 2 != 0) ++res;
num = num / 2;
}
return res;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int allAmount = sc.nextInt();
int necAmount = sc.nextInt();
int rulesAmount = sc.nextInt();
long[] satis = new long[allAmount];
for(int i = 0; i < allAmount; ++i) {
satis[i] = sc.nextLong();
}
long[][] rules = new long[allAmount][allAmount];
for(int i = 0; i < rulesAmount; ++i) {
rules[sc.nextInt() - 1][sc.nextInt() - 1] = sc.nextLong();
}
int maxMask = (int) Math.pow(2, allAmount);
long[][] dynArr = new long[allAmount][maxMask];
long max = 0;
int mask = 1;
for(int i = 0; i < allAmount; i++, mask = mask << 1) {
dynArr[i][mask] = satis[i];
}
for(int pos = 1; pos < maxMask; ++pos) {
for(int i = 0; i < allAmount; ++i) {
if ((pos & (1 << i)) == 0) continue;
if (getOnesAmount(pos) > necAmount) continue;
int j = 0;
mask = 1;
while (j < allAmount) {
if ((pos & mask) == 0) {
dynArr[j][pos | mask] = Math.max(dynArr[j][pos | mask], dynArr[i][pos] + satis[j] + rules[i][j]);
}
++j;
mask = mask << 1;
}
}
}
for(int i = 0; i < allAmount; ++i) {
for(int pos = 0; pos < maxMask; ++pos) {
if(getOnesAmount(pos) == necAmount) max = Math.max(max, dynArr[i][pos]);
}
}
System.out.print(max);
}
} | Java | ["2 2 1\n1 1\n2 1 1", "4 3 2\n1 2 3 4\n2 1 5\n3 4 2"] | 2 seconds | ["3", "12"] | NoteIn the first sample it is best to first eat the second dish, then the first one. Then we get one unit of satisfaction for each dish and plus one more for the rule.In the second test the fitting sequences of choice are 4 2 1 or 2 1 4. In both cases we get satisfaction 7 for dishes and also, if we fulfill rule 1, we get an additional satisfaction 5. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 5b881f1cd74b17358b954299c2742bdf | The first line of the input contains three space-separated numbers, n, m and k (1 ≤ m ≤ n ≤ 18, 0 ≤ k ≤ n * (n - 1)) — the number of dishes on the menu, the number of portions Kefa needs to eat to get full and the number of eating rules. The second line contains n space-separated numbers ai, (0 ≤ ai ≤ 109) — the satisfaction he gets from the i-th dish. Next k lines contain the rules. The i-th rule is described by the three numbers xi, yi and ci (1 ≤ xi, yi ≤ n, 0 ≤ ci ≤ 109). That means that if you eat dish xi right before dish yi, then the Kefa's satisfaction increases by ci. It is guaranteed that there are no such pairs of indexes i and j (1 ≤ i < j ≤ k), that xi = xj and yi = yj. | 1,800 | In the single line of the output print the maximum satisfaction that Kefa can get from going to the restaurant. | standard output | |
PASSED | 7f8fd091185e8ebedb28bcfd48a8c244 | train_003.jsonl | 1442939400 | When Kefa came to the restaurant and sat at a table, the waiter immediately brought him the menu. There were n dishes. Kefa knows that he needs exactly m dishes. But at that, he doesn't want to order the same dish twice to taste as many dishes as possible. Kefa knows that the i-th dish gives him ai units of satisfaction. But some dishes do not go well together and some dishes go very well together. Kefa set to himself k rules of eating food of the following type — if he eats dish x exactly before dish y (there should be no other dishes between x and y), then his satisfaction level raises by c. Of course, our parrot wants to get some maximal possible satisfaction from going to the restaurant. Help him in this hard task! | 256 megabytes | import java.awt.List;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.StringTokenizer;
public class kefaanddishes {
static long memo[][];
static int dishes[][];
static int[] sat;
static int N, M;
static long dp(int lastidx, int mask) {
if (Integer.bitCount(mask)==M)
return 0;
if (memo[lastidx][mask] != -1)
return memo[lastidx][mask];
long max=(long)-1e9 ;
long take=0;
for(int i=0;i<N;i++) {
if((mask & (1<<i))==0) {
if(dishes[lastidx][i]>0) {
take=sat[i]+dishes[lastidx][i]+dp(i,((mask)|(1<<i)));
}
else {
take=sat[i]+dp(i,((mask)|(1<<i)));
}max=Math.max(max, take);
}
}
return memo[lastidx][mask] = max;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
int rules = Integer.parseInt(st.nextToken());
memo = new long[N+1][1<<N];
dishes = new int[N+1][N+1];
sat = new int[N];
st = new StringTokenizer(br.readLine());
for (int i = 0; i < N; i++)
sat[i] = Integer.parseInt(st.nextToken());
for (long[] arr : memo) {
Arrays.fill(arr, -1);
}
for (int[] arr : dishes) {
Arrays.fill(arr, -1);
}
while (rules-- > 0) {
st = new StringTokenizer(br.readLine());
int i = Integer.parseInt(st.nextToken()) - 1;
int j = Integer.parseInt(st.nextToken()) - 1;
dishes[i][j] = Integer.parseInt(st.nextToken());
}
System.out.println(dp(N,0));
}
}
| Java | ["2 2 1\n1 1\n2 1 1", "4 3 2\n1 2 3 4\n2 1 5\n3 4 2"] | 2 seconds | ["3", "12"] | NoteIn the first sample it is best to first eat the second dish, then the first one. Then we get one unit of satisfaction for each dish and plus one more for the rule.In the second test the fitting sequences of choice are 4 2 1 or 2 1 4. In both cases we get satisfaction 7 for dishes and also, if we fulfill rule 1, we get an additional satisfaction 5. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 5b881f1cd74b17358b954299c2742bdf | The first line of the input contains three space-separated numbers, n, m and k (1 ≤ m ≤ n ≤ 18, 0 ≤ k ≤ n * (n - 1)) — the number of dishes on the menu, the number of portions Kefa needs to eat to get full and the number of eating rules. The second line contains n space-separated numbers ai, (0 ≤ ai ≤ 109) — the satisfaction he gets from the i-th dish. Next k lines contain the rules. The i-th rule is described by the three numbers xi, yi and ci (1 ≤ xi, yi ≤ n, 0 ≤ ci ≤ 109). That means that if you eat dish xi right before dish yi, then the Kefa's satisfaction increases by ci. It is guaranteed that there are no such pairs of indexes i and j (1 ≤ i < j ≤ k), that xi = xj and yi = yj. | 1,800 | In the single line of the output print the maximum satisfaction that Kefa can get from going to the restaurant. | standard output | |
PASSED | 90696dba18b54c8e43c30b7d4e0a5b64 | train_003.jsonl | 1442939400 | When Kefa came to the restaurant and sat at a table, the waiter immediately brought him the menu. There were n dishes. Kefa knows that he needs exactly m dishes. But at that, he doesn't want to order the same dish twice to taste as many dishes as possible. Kefa knows that the i-th dish gives him ai units of satisfaction. But some dishes do not go well together and some dishes go very well together. Kefa set to himself k rules of eating food of the following type — if he eats dish x exactly before dish y (there should be no other dishes between x and y), then his satisfaction level raises by c. Of course, our parrot wants to get some maximal possible satisfaction from going to the restaurant. Help him in this hard task! | 256 megabytes | import java.util.Arrays;
import java.util.Scanner;
public class dishes {
static int []dish;
static int [][] pri;
static long [][]memo;
static int n,m;
static long dp(int mask,int next){
if(Integer.bitCount(mask)==m){
// System.out.println(Integer.bitCount(mask));
return 0;
}
if(memo[next][mask]!=-1)
return memo[next][mask];
long ans= (long) -1e9;
for(int i=0;i<n;i++){
long take2=0;
// long plus=0;
if((mask &(1<<i))==0){
take2=pri[next][i]+dish[i]+dp((mask|(1<<i)),i);
// System.out.println(take2);
ans=Math.max(ans, take2);
}
}
return memo[next][mask]=ans;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
m=sc.nextInt();
int k=sc.nextInt();
dish=new int[n];
pri=new int[n+1][n+1];
memo=new long[n+1][1<<n];
for(long []arr:memo)
Arrays.fill(arr, -1);
for(int i=0;i<n;i++)
dish[i]=sc.nextInt();
for(int i=0;i<k;i++){
int x=sc.nextInt()-1;
int y=sc.nextInt()-1;
int c=sc.nextInt();
pri[x][y]=c;
}
System.out.println(dp(0,n));
}
}
| Java | ["2 2 1\n1 1\n2 1 1", "4 3 2\n1 2 3 4\n2 1 5\n3 4 2"] | 2 seconds | ["3", "12"] | NoteIn the first sample it is best to first eat the second dish, then the first one. Then we get one unit of satisfaction for each dish and plus one more for the rule.In the second test the fitting sequences of choice are 4 2 1 or 2 1 4. In both cases we get satisfaction 7 for dishes and also, if we fulfill rule 1, we get an additional satisfaction 5. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 5b881f1cd74b17358b954299c2742bdf | The first line of the input contains three space-separated numbers, n, m and k (1 ≤ m ≤ n ≤ 18, 0 ≤ k ≤ n * (n - 1)) — the number of dishes on the menu, the number of portions Kefa needs to eat to get full and the number of eating rules. The second line contains n space-separated numbers ai, (0 ≤ ai ≤ 109) — the satisfaction he gets from the i-th dish. Next k lines contain the rules. The i-th rule is described by the three numbers xi, yi and ci (1 ≤ xi, yi ≤ n, 0 ≤ ci ≤ 109). That means that if you eat dish xi right before dish yi, then the Kefa's satisfaction increases by ci. It is guaranteed that there are no such pairs of indexes i and j (1 ≤ i < j ≤ k), that xi = xj and yi = yj. | 1,800 | In the single line of the output print the maximum satisfaction that Kefa can get from going to the restaurant. | standard output | |
PASSED | 1098e11a6adf3ef4a87d879bff96dd08 | train_003.jsonl | 1442939400 | When Kefa came to the restaurant and sat at a table, the waiter immediately brought him the menu. There were n dishes. Kefa knows that he needs exactly m dishes. But at that, he doesn't want to order the same dish twice to taste as many dishes as possible. Kefa knows that the i-th dish gives him ai units of satisfaction. But some dishes do not go well together and some dishes go very well together. Kefa set to himself k rules of eating food of the following type — if he eats dish x exactly before dish y (there should be no other dishes between x and y), then his satisfaction level raises by c. Of course, our parrot wants to get some maximal possible satisfaction from going to the restaurant. Help him in this hard task! | 256 megabytes | import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
import java.lang.*;
import static java.lang.Math.*;
public class Main implements Runnable {
public static void main(String[] args) {
new Thread(null, new Main(), "Check2", 1 << 28).start();// to increse stack size in java
}
void init(ArrayList <Integer> adj[], int n){
for(int i=0;i<=n;i++)adj[i]=new ArrayList<>();
}
static long mod = (long) (1e9+7);
public void run() {
InputReader in=new InputReader(System.in);
PrintWriter w=new PrintWriter(System.out);
int n=in.nextInt();
m=in.nextInt();
int k=in.nextInt();
long a[]=new long[n+1];
for(int i=1;i<=n;i++)a[i]=in.nextLong();
long v[][]=new long[n+1][n+1];
for(int i=0;i<k;i++){
int u=in.nextInt();
int vv=in.nextInt();
long c=in.nextLong();
v[u][vv]=c;
// v[vv][u]=c;
}
full=(1<<n)-1;
dp=new long[20][1<<20];
for(int i=0;i<20;i++)for(int j=0;j<dp[i].length;j++)dp[i][j]=-1;
long ans=0;
w.println(rec(0,0,a,v,0));
w.close();
}
int full;
long dp[][];
int m;
long dp2[][];
long rec(int i,int mask,long a[],long v[][],int prv){
if(i==m)return 0;
long ans=0;
if(dp[prv][mask]!=-1)return dp[prv][mask];
for(int j=1;j<a.length;j++){
if((mask&(1<<j))==0) {
ans=max(ans,rec(i+1,(mask|(1<<j)),a,v,j)+v[prv][j]+a[j]);
}
}
return dp[prv][mask]=ans;
}
class pair {
int a;
long b;
pair(int a,long b){
this.a=a;
this.b=b;
}
public boolean equals(Object obj) { // override equals method for object to remove tem from arraylist and sets etc.......
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
pair other = (pair) obj;
if (b!= other.b||a!=other.a)
return false;
return true;
}
}
static long modinv(long a,long b)
{
long p=power(b,mod-2);
p=a%mod*p%mod;
p%=mod;
return p;
}
static long power(long x,long y){
if(y==0)return 1%mod;
if(y==1)return x%mod;
long res=1;
x=x%mod;
while(y>0){
if((y%2)!=0){
res=(res*x)%mod;
}
y=y/2;
x=(x*x)%mod;
}
return res;
}
static long gcd(long a,long b){
if(b==0)return a;
return gcd(b,a%b);
}
static void sev(int a[],int n){
for(int i=2;i<=n;i++)a[i]=i;
for(int i=2;i<=n;i++){
if(a[i]!=0){
for(int j=2*i;j<=n;){
a[j]=0;
j=j+i;
}
}
}
}
static class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (numChars==-1)
throw new InputMismatchException();
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine()
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
public int nextInt()
{
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if(c<'0'||c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.')
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.')
{
c = read();
double m = 1;
while (!isSpaceChar(c))
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next()
{
return readString();
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["2 2 1\n1 1\n2 1 1", "4 3 2\n1 2 3 4\n2 1 5\n3 4 2"] | 2 seconds | ["3", "12"] | NoteIn the first sample it is best to first eat the second dish, then the first one. Then we get one unit of satisfaction for each dish and plus one more for the rule.In the second test the fitting sequences of choice are 4 2 1 or 2 1 4. In both cases we get satisfaction 7 for dishes and also, if we fulfill rule 1, we get an additional satisfaction 5. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 5b881f1cd74b17358b954299c2742bdf | The first line of the input contains three space-separated numbers, n, m and k (1 ≤ m ≤ n ≤ 18, 0 ≤ k ≤ n * (n - 1)) — the number of dishes on the menu, the number of portions Kefa needs to eat to get full and the number of eating rules. The second line contains n space-separated numbers ai, (0 ≤ ai ≤ 109) — the satisfaction he gets from the i-th dish. Next k lines contain the rules. The i-th rule is described by the three numbers xi, yi and ci (1 ≤ xi, yi ≤ n, 0 ≤ ci ≤ 109). That means that if you eat dish xi right before dish yi, then the Kefa's satisfaction increases by ci. It is guaranteed that there are no such pairs of indexes i and j (1 ≤ i < j ≤ k), that xi = xj and yi = yj. | 1,800 | In the single line of the output print the maximum satisfaction that Kefa can get from going to the restaurant. | standard output | |
PASSED | 98e7c840ef5d949222744ab280d71e01 | train_003.jsonl | 1442939400 | When Kefa came to the restaurant and sat at a table, the waiter immediately brought him the menu. There were n dishes. Kefa knows that he needs exactly m dishes. But at that, he doesn't want to order the same dish twice to taste as many dishes as possible. Kefa knows that the i-th dish gives him ai units of satisfaction. But some dishes do not go well together and some dishes go very well together. Kefa set to himself k rules of eating food of the following type — if he eats dish x exactly before dish y (there should be no other dishes between x and y), then his satisfaction level raises by c. Of course, our parrot wants to get some maximal possible satisfaction from going to the restaurant. Help him in this hard task! | 256 megabytes | import java.io.BufferedInputStream;
import java.util.Arrays;
import java.util.Scanner;
/*
mem[x][bitMask]
= The best satisfaction you can get from now on when you start with
dish 'x' and took dishes in 'bitMask' already.
*/
public class D {
static long[] sat;
static long[][] bonus;
static long[][] mem;
static long INF = -1L;
static int N, M;
public static void main(String[] args) {
final Scanner sc = new Scanner(new BufferedInputStream(System.in));
N = sc.nextInt();
M = sc.nextInt();
int K = sc.nextInt();
sat = new long[N];
bonus = new long[N][N];
mem = new long[N][1 << N];
for (int i = 0; i < N; i++)
sat[i] = sc.nextLong();
for (int i = 0; i < K; i++)
bonus[sc.nextInt() - 1][sc.nextInt() - 1] = sc.nextLong();
for (int i = 0; i < N; i++)
Arrays.fill(mem[i], INF);
long res = 0L;
for (int i = 0; i < N; i++)
res = Math.max(res, sat[i] + find(i, 1 << i, 1));
System.out.println(res);
}
public static long find(int curDish, int bitMask, int used) {
if (used == M) return 0;
if (mem[curDish][bitMask] == INF) {
mem[curDish][bitMask] = 0;
for (int nextDish = 0; nextDish < N; nextDish++) {
if ((bitMask & (1 << nextDish)) == 0) {
mem[curDish][bitMask] = Math.max(mem[curDish][bitMask],
sat[nextDish] + bonus[curDish][nextDish] +
find(nextDish, bitMask | (1 << nextDish), used + 1));
}
}
}
return mem[curDish][bitMask];
}
}
| Java | ["2 2 1\n1 1\n2 1 1", "4 3 2\n1 2 3 4\n2 1 5\n3 4 2"] | 2 seconds | ["3", "12"] | NoteIn the first sample it is best to first eat the second dish, then the first one. Then we get one unit of satisfaction for each dish and plus one more for the rule.In the second test the fitting sequences of choice are 4 2 1 or 2 1 4. In both cases we get satisfaction 7 for dishes and also, if we fulfill rule 1, we get an additional satisfaction 5. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 5b881f1cd74b17358b954299c2742bdf | The first line of the input contains three space-separated numbers, n, m and k (1 ≤ m ≤ n ≤ 18, 0 ≤ k ≤ n * (n - 1)) — the number of dishes on the menu, the number of portions Kefa needs to eat to get full and the number of eating rules. The second line contains n space-separated numbers ai, (0 ≤ ai ≤ 109) — the satisfaction he gets from the i-th dish. Next k lines contain the rules. The i-th rule is described by the three numbers xi, yi and ci (1 ≤ xi, yi ≤ n, 0 ≤ ci ≤ 109). That means that if you eat dish xi right before dish yi, then the Kefa's satisfaction increases by ci. It is guaranteed that there are no such pairs of indexes i and j (1 ≤ i < j ≤ k), that xi = xj and yi = yj. | 1,800 | In the single line of the output print the maximum satisfaction that Kefa can get from going to the restaurant. | standard output | |
PASSED | 2db7cc268a28e6653ec9f777e59daa83 | train_003.jsonl | 1442939400 | When Kefa came to the restaurant and sat at a table, the waiter immediately brought him the menu. There were n dishes. Kefa knows that he needs exactly m dishes. But at that, he doesn't want to order the same dish twice to taste as many dishes as possible. Kefa knows that the i-th dish gives him ai units of satisfaction. But some dishes do not go well together and some dishes go very well together. Kefa set to himself k rules of eating food of the following type — if he eats dish x exactly before dish y (there should be no other dishes between x and y), then his satisfaction level raises by c. Of course, our parrot wants to get some maximal possible satisfaction from going to the restaurant. Help him in this hard task! | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Artem Gilmudinov
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Reader in = new Reader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
long[][] dp;
public void solve(int testNumber, Reader in, PrintWriter out) {
int n, m, k;
n = in.ni();
m = in.ni();
k = in.ni();
dp = new long[n][1 << n];
long[] a = new long[n];
Helper.fillLongArray(in, a);
long[][] edges = new long[n][n];
for (int i = 0; i < k; i++) {
int x, y, c;
x = in.ni() - 1;
y = in.ni() - 1;
c = in.ni();
edges[x][y] = c;
}
int mask = 1 << n;
int[] cnt = new int[mask];
for (int i = 0; i < mask; i++) {
for (int j = 0; j < n; j++) {
if ((i & (1 << j)) != 0) {
cnt[i]++;
}
}
}
for (int i = 0; i < n; i++) {
Arrays.fill(dp[i], -1);
dp[i][1 << i] = a[i];
}
int u, v;
for (int i = 0; i < mask; i++) {
for (int j = 0; j < n; j++) {
u = 1 << j;
if ((i & u) == 0) {
continue;
}
for (int z = 0; z < n; z++) {
v = 1 << z;
if ((i & v) != 0 && dp[z][i ^ u] != -1) {
dp[j][i] = Math.max(dp[j][i], dp[z][i ^ u] + edges[z][j] + a[j]);
}
}
}
}
long ans = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < mask; j++) {
if (cnt[j] == m) {
ans = Math.max(dp[i][j], ans);
}
}
}
out.println(ans);
}
}
static class Reader {
private BufferedReader in;
private StringTokenizer st = new StringTokenizer("");
private String delim = " ";
public Reader(InputStream in) {
this.in = new BufferedReader(new InputStreamReader(in));
}
public String next() {
if (!st.hasMoreTokens()) {
st = new StringTokenizer(rl());
}
return st.nextToken(delim);
}
public String rl() {
try {
return in.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public int ni() {
return Integer.parseInt(next());
}
public long nl() {
return Long.parseLong(next());
}
}
static class Helper {
public static void fillLongArray(Reader in, long[] a) {
for (int i = 0; i < a.length; i++) {
a[i] = in.nl();
}
}
}
}
| Java | ["2 2 1\n1 1\n2 1 1", "4 3 2\n1 2 3 4\n2 1 5\n3 4 2"] | 2 seconds | ["3", "12"] | NoteIn the first sample it is best to first eat the second dish, then the first one. Then we get one unit of satisfaction for each dish and plus one more for the rule.In the second test the fitting sequences of choice are 4 2 1 or 2 1 4. In both cases we get satisfaction 7 for dishes and also, if we fulfill rule 1, we get an additional satisfaction 5. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 5b881f1cd74b17358b954299c2742bdf | The first line of the input contains three space-separated numbers, n, m and k (1 ≤ m ≤ n ≤ 18, 0 ≤ k ≤ n * (n - 1)) — the number of dishes on the menu, the number of portions Kefa needs to eat to get full and the number of eating rules. The second line contains n space-separated numbers ai, (0 ≤ ai ≤ 109) — the satisfaction he gets from the i-th dish. Next k lines contain the rules. The i-th rule is described by the three numbers xi, yi and ci (1 ≤ xi, yi ≤ n, 0 ≤ ci ≤ 109). That means that if you eat dish xi right before dish yi, then the Kefa's satisfaction increases by ci. It is guaranteed that there are no such pairs of indexes i and j (1 ≤ i < j ≤ k), that xi = xj and yi = yj. | 1,800 | In the single line of the output print the maximum satisfaction that Kefa can get from going to the restaurant. | standard output | |
PASSED | aace9ac8797025b30b96d6acb96a6edb | train_003.jsonl | 1442939400 | When Kefa came to the restaurant and sat at a table, the waiter immediately brought him the menu. There were n dishes. Kefa knows that he needs exactly m dishes. But at that, he doesn't want to order the same dish twice to taste as many dishes as possible. Kefa knows that the i-th dish gives him ai units of satisfaction. But some dishes do not go well together and some dishes go very well together. Kefa set to himself k rules of eating food of the following type — if he eats dish x exactly before dish y (there should be no other dishes between x and y), then his satisfaction level raises by c. Of course, our parrot wants to get some maximal possible satisfaction from going to the restaurant. Help him in this hard task! | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Morgrey
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.readInt(), m = in.readInt(), k = in.readInt();
int[] a = IOUtils.readIntArray(in, n);
int[][] b = new int[n][n];
long[][] dp = new long[1 << n][n];
for (int i = 0; i < k; i++) {
b[in.readInt() - 1][in.readInt() - 1] = in.readInt();
}
for (int i = 0; i < n; i++) {
dp[1 << i][i] = a[i];
}
for (int i = 0; i < 1 << n; i++) {
for (int j = 0; j < n; j++) {
if ((i & (1 << j)) != 0) {
int p = i ^ (1 << j);
for (int z = 0; z < n; z++) {
if ((p & (1 << z)) != 0) {
dp[i][j] = Math.max(dp[i][j], dp[p][z] + b[z][j] + a[j]);
}
}
}
}
}
long ans = 0;
for (int i = 0; i < 1 << n; i++) {
if (Integer.bitCount(i) == m) {
ans = Math.max(ans, ArrayUtils.maxElement(dp[i]));
}
}
out.printLine(ans);
}
}
static class IOUtils {
public static int[] readIntArray(InputReader in, int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = in.readInt();
return array;
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void printLine(long i) {
writer.println(i);
}
}
static class ArrayUtils {
public static long maxElement(long[] array) {
return array[maxPosition(array)];
}
public static int maxPosition(long[] array) {
return maxPosition(array, 0, array.length);
}
public static int maxPosition(long[] array, int from, int to) {
if (from >= to)
return -1;
long max = array[from];
int result = from;
for (int i = from + 1; i < to; i++) {
if (array[i] > max) {
max = array[i];
result = i;
}
}
return result;
}
}
}
| Java | ["2 2 1\n1 1\n2 1 1", "4 3 2\n1 2 3 4\n2 1 5\n3 4 2"] | 2 seconds | ["3", "12"] | NoteIn the first sample it is best to first eat the second dish, then the first one. Then we get one unit of satisfaction for each dish and plus one more for the rule.In the second test the fitting sequences of choice are 4 2 1 or 2 1 4. In both cases we get satisfaction 7 for dishes and also, if we fulfill rule 1, we get an additional satisfaction 5. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 5b881f1cd74b17358b954299c2742bdf | The first line of the input contains three space-separated numbers, n, m and k (1 ≤ m ≤ n ≤ 18, 0 ≤ k ≤ n * (n - 1)) — the number of dishes on the menu, the number of portions Kefa needs to eat to get full and the number of eating rules. The second line contains n space-separated numbers ai, (0 ≤ ai ≤ 109) — the satisfaction he gets from the i-th dish. Next k lines contain the rules. The i-th rule is described by the three numbers xi, yi and ci (1 ≤ xi, yi ≤ n, 0 ≤ ci ≤ 109). That means that if you eat dish xi right before dish yi, then the Kefa's satisfaction increases by ci. It is guaranteed that there are no such pairs of indexes i and j (1 ≤ i < j ≤ k), that xi = xj and yi = yj. | 1,800 | In the single line of the output print the maximum satisfaction that Kefa can get from going to the restaurant. | standard output | |
PASSED | 6759cb8b1a8b85188199c34d70fc462f | train_003.jsonl | 1442939400 | When Kefa came to the restaurant and sat at a table, the waiter immediately brought him the menu. There were n dishes. Kefa knows that he needs exactly m dishes. But at that, he doesn't want to order the same dish twice to taste as many dishes as possible. Kefa knows that the i-th dish gives him ai units of satisfaction. But some dishes do not go well together and some dishes go very well together. Kefa set to himself k rules of eating food of the following type — if he eats dish x exactly before dish y (there should be no other dishes between x and y), then his satisfaction level raises by c. Of course, our parrot wants to get some maximal possible satisfaction from going to the restaurant. Help him in this hard task! | 256 megabytes |
import java.io.PrintWriter;
import java.util.Scanner;
public class D {
static int n;
static int m;;
static int k;
static int sat[];
static int g[][];
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
n = in.nextInt();
m = in.nextInt();
k = in.nextInt();
sat = new int[n];
for (int i = 0; i < n; i++) {
sat[i] = in.nextInt();
}
g = new int[n][n];
for (int i = 0; i < k; i++) {
int x = in.nextInt()-1;
int y = in.nextInt()-1;
int c = in.nextInt();
g[x][y] = c;
}
in.close();
long best = 0;
dp = new long[n][1 << n];
for (int i = 0; i < n; i++) {
for (int k = 0; k < 1 << n; k++) {
dp[i][k] = -1;
}
}
for (int dish = 0; dish < n; dish++) {
best = Math.max(best, sat[dish] + find(dish, 1 << dish));
}
out.println(best);
out.close();
}
static long dp[][];
private static long find(int lastDish, int mask) {
int remainingDishes = m - Integer.bitCount(mask);
if (remainingDishes == 0) return 0;
long best = 0;
if (dp[lastDish][mask] != -1) return dp[lastDish][mask];
for (int i = 0; i < n; i++) {
if (((1 << i) & mask) == 0) {
best = Math.max(best, sat[i] + g[lastDish][i] + find(i, mask | (1 << i)));
}
}
return dp[lastDish][mask] = best;
}
}
| Java | ["2 2 1\n1 1\n2 1 1", "4 3 2\n1 2 3 4\n2 1 5\n3 4 2"] | 2 seconds | ["3", "12"] | NoteIn the first sample it is best to first eat the second dish, then the first one. Then we get one unit of satisfaction for each dish and plus one more for the rule.In the second test the fitting sequences of choice are 4 2 1 or 2 1 4. In both cases we get satisfaction 7 for dishes and also, if we fulfill rule 1, we get an additional satisfaction 5. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 5b881f1cd74b17358b954299c2742bdf | The first line of the input contains three space-separated numbers, n, m and k (1 ≤ m ≤ n ≤ 18, 0 ≤ k ≤ n * (n - 1)) — the number of dishes on the menu, the number of portions Kefa needs to eat to get full and the number of eating rules. The second line contains n space-separated numbers ai, (0 ≤ ai ≤ 109) — the satisfaction he gets from the i-th dish. Next k lines contain the rules. The i-th rule is described by the three numbers xi, yi and ci (1 ≤ xi, yi ≤ n, 0 ≤ ci ≤ 109). That means that if you eat dish xi right before dish yi, then the Kefa's satisfaction increases by ci. It is guaranteed that there are no such pairs of indexes i and j (1 ≤ i < j ≤ k), that xi = xj and yi = yj. | 1,800 | In the single line of the output print the maximum satisfaction that Kefa can get from going to the restaurant. | standard output | |
PASSED | 38060e0cb95882a573d013bb82adfb05 | train_003.jsonl | 1442939400 | When Kefa came to the restaurant and sat at a table, the waiter immediately brought him the menu. There were n dishes. Kefa knows that he needs exactly m dishes. But at that, he doesn't want to order the same dish twice to taste as many dishes as possible. Kefa knows that the i-th dish gives him ai units of satisfaction. But some dishes do not go well together and some dishes go very well together. Kefa set to himself k rules of eating food of the following type — if he eats dish x exactly before dish y (there should be no other dishes between x and y), then his satisfaction level raises by c. Of course, our parrot wants to get some maximal possible satisfaction from going to the restaurant. Help him in this hard task! | 256 megabytes | import javafx.scene.layout.Priority;
import java.io.*;
import java.util.*;
public class D {
static long[][] dp;
static Edge[][] adj;
static long[] a;
static int n, max;
public static void main(String[] args) {
FastScannerD fs = new FastScannerD();
PrintWriter out = new PrintWriter(System.out);
dp = new long[1 << 18][18];
for(int i = 0; i < dp.length; i++) Arrays.fill(dp[i], -1);
n = fs.nextInt(); max = fs.nextInt();
adj = new Edge[n+1][n+1];
int k = fs.nextInt();
a = new long[n];
for(int i = 0; i < n; i++) a[i] = fs.nextInt();
for(int i = 0; i < k; i++) {
int x = fs.nextInt()-1, y = fs.nextInt()-1;
long we = fs.nextInt();
adj[x][y] = new Edge(x, y, we);
}
long res = 0;
for(int i = 0; i < n; i++) {
res = Math.max(res, go(1 << i, i));
}
out.println(res);
out.close();
}
static long go(int mask, int at) {
if(Integer.bitCount(mask) == max) {
return a[at];
}
if(dp[mask][at] != -1) return dp[mask][at];
long res = 0;
for(int i = 0; i < n; i++) {
int result = mask & (1 << i);
if(result == 0) {
long add = 0;
if(adj[at][i] != null) add = adj[at][i].we;
res = Math.max(res, go(mask | (1 << i), i)+ add+ a[at]) ;
}
}
return dp[mask][at] = res;
}
}
class Edge {
long we, aV, bV;
int u, v;
public Edge(int a, int b, long w) {
u = a; v = b; we = w;
}
}
class FastScannerD {
BufferedReader br;
StringTokenizer st;
public FastScannerD() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer("");
} catch (Exception e) {
e.printStackTrace();
}
}
public String next() {
if (st.hasMoreTokens()) return st.nextToken();
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
e.printStackTrace();
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
String line = "";
try {
line = br.readLine();
} catch (Exception e) {
e.printStackTrace();
}
return line;
}
public Integer[] nextIntegerArray(int n) {
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
public int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
public char[] nextCharArray() {
return nextLine().toCharArray();
}
} | Java | ["2 2 1\n1 1\n2 1 1", "4 3 2\n1 2 3 4\n2 1 5\n3 4 2"] | 2 seconds | ["3", "12"] | NoteIn the first sample it is best to first eat the second dish, then the first one. Then we get one unit of satisfaction for each dish and plus one more for the rule.In the second test the fitting sequences of choice are 4 2 1 or 2 1 4. In both cases we get satisfaction 7 for dishes and also, if we fulfill rule 1, we get an additional satisfaction 5. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 5b881f1cd74b17358b954299c2742bdf | The first line of the input contains three space-separated numbers, n, m and k (1 ≤ m ≤ n ≤ 18, 0 ≤ k ≤ n * (n - 1)) — the number of dishes on the menu, the number of portions Kefa needs to eat to get full and the number of eating rules. The second line contains n space-separated numbers ai, (0 ≤ ai ≤ 109) — the satisfaction he gets from the i-th dish. Next k lines contain the rules. The i-th rule is described by the three numbers xi, yi and ci (1 ≤ xi, yi ≤ n, 0 ≤ ci ≤ 109). That means that if you eat dish xi right before dish yi, then the Kefa's satisfaction increases by ci. It is guaranteed that there are no such pairs of indexes i and j (1 ≤ i < j ≤ k), that xi = xj and yi = yj. | 1,800 | In the single line of the output print the maximum satisfaction that Kefa can get from going to the restaurant. | standard output | |
PASSED | 8e3824cb78e7facdd9a0cd44e60d80b6 | train_003.jsonl | 1442939400 | When Kefa came to the restaurant and sat at a table, the waiter immediately brought him the menu. There were n dishes. Kefa knows that he needs exactly m dishes. But at that, he doesn't want to order the same dish twice to taste as many dishes as possible. Kefa knows that the i-th dish gives him ai units of satisfaction. But some dishes do not go well together and some dishes go very well together. Kefa set to himself k rules of eating food of the following type — if he eats dish x exactly before dish y (there should be no other dishes between x and y), then his satisfaction level raises by c. Of course, our parrot wants to get some maximal possible satisfaction from going to the restaurant. Help him in this hard task! | 256 megabytes | import java.util.LinkedList;
import java.util.Scanner;
/**
* 状态压缩dp
* 少于1000次输入,用Scanner
*/
public class Main {
static int n,m,k;
static int[] a;
static int[][] val;
static long[][] dp;
static long max;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
k = sc.nextInt();
a = new int[20];
for(int i = 0; i < n; i++)
a[i] = sc.nextInt();
dp = new long[1000000][20];//最大有2^18种状态
val = new int[20][20];
for(int i = 0; i < k; i++){//全部从0-n-1计数
int x = sc.nextInt();
int y = sc.nextInt();
int c = sc.nextInt();
val[x-1][y-1] = c;
}
sc.close();
int end = 1<<n;
for(int st = 0; st < end; st++){
//对每一个状态st,找其之前的状态来做dp
if(cnt(st)>m)
continue;
for(int i = 0; i < n; i++){
if((st&(1<<i))>0){//若点了i
boolean has = false;
for(int j = 0; j < n; j++){
if(i!=j && (st&(1<<j))>0){//如果还点了j
dp[st][i] = Math.max(dp[st][i],
dp[st&(~(1<<i))][j]+val[j][i]+a[i]);
//和没有点i但是点了j的上一单进行dp推进
has = true;
}
}
if(!has){//只有点一单i,其他都没点
dp[st][i] = a[i];
}
}
max = Math.max(max, dp[st][i]);
}
}
System.out.println(max);
}
/*
private static void dfs(int st, int end, int dep) {
// TODO Auto-generated method stub
//dfs全排列
if(dep==0)
return;
for(int i = 0; i < n; i++){
if((st&(1<<i))==0){//表示没有选择第i个菜
dp[st|(1<<i)][i] = Math.max(dp[st|(1<<i)][i],
dp[st][end]+val[end][i]+a[i]);
//这里的dp[st][end]有可能不是最大值,所以错误!
//不应该用dfs
max = Math.max(max, dp[st|(1<<i)][i]);
dfs(st|(1<<i), i, dep-1);
}
}
}
*/
private static int cnt(int st) {
// TODO Auto-generated method stub
int res = 0;
while(st>0){
res+=st&1;
st>>=1;
}
return res;
}
}
| Java | ["2 2 1\n1 1\n2 1 1", "4 3 2\n1 2 3 4\n2 1 5\n3 4 2"] | 2 seconds | ["3", "12"] | NoteIn the first sample it is best to first eat the second dish, then the first one. Then we get one unit of satisfaction for each dish and plus one more for the rule.In the second test the fitting sequences of choice are 4 2 1 or 2 1 4. In both cases we get satisfaction 7 for dishes and also, if we fulfill rule 1, we get an additional satisfaction 5. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 5b881f1cd74b17358b954299c2742bdf | The first line of the input contains three space-separated numbers, n, m and k (1 ≤ m ≤ n ≤ 18, 0 ≤ k ≤ n * (n - 1)) — the number of dishes on the menu, the number of portions Kefa needs to eat to get full and the number of eating rules. The second line contains n space-separated numbers ai, (0 ≤ ai ≤ 109) — the satisfaction he gets from the i-th dish. Next k lines contain the rules. The i-th rule is described by the three numbers xi, yi and ci (1 ≤ xi, yi ≤ n, 0 ≤ ci ≤ 109). That means that if you eat dish xi right before dish yi, then the Kefa's satisfaction increases by ci. It is guaranteed that there are no such pairs of indexes i and j (1 ≤ i < j ≤ k), that xi = xj and yi = yj. | 1,800 | In the single line of the output print the maximum satisfaction that Kefa can get from going to the restaurant. | standard output | |
PASSED | bf4965cc24b061f1257084a4aeac372d | train_003.jsonl | 1442939400 | When Kefa came to the restaurant and sat at a table, the waiter immediately brought him the menu. There were n dishes. Kefa knows that he needs exactly m dishes. But at that, he doesn't want to order the same dish twice to taste as many dishes as possible. Kefa knows that the i-th dish gives him ai units of satisfaction. But some dishes do not go well together and some dishes go very well together. Kefa set to himself k rules of eating food of the following type — if he eats dish x exactly before dish y (there should be no other dishes between x and y), then his satisfaction level raises by c. Of course, our parrot wants to get some maximal possible satisfaction from going to the restaurant. Help him in this hard task! | 256 megabytes | import java.io.IOException;
import java.util.ArrayList;
import java.util.InputMismatchException;
public class KefaAndDishes {
public static void main(String[] args) {
FasterScanner sc = new FasterScanner();
int N = sc.nextInt();
int M = sc.nextInt();
int K = sc.nextInt();
long[] A = sc.nextLongArray(N);
final int S = (1 << N);
long[][] C = new long[N][N];
for (int i = 0; i < K; i++) {
int X = sc.nextInt() - 1;
int Y = sc.nextInt() - 1;
C[X][Y] = sc.nextLong();
}
IntList[] masks = new IntList[N + 1];
for (int i = 0; i <= N; i++) {
masks[i] = new IntList();
}
for (int i = 0; i < S; i++) {
int bits = Integer.bitCount(i);
masks[bits].add(i);
}
long[][] best = new long[N][S];
for (int i = 0; i < N; i++) {
best[i][1 << i] = A[i];
}
for (int t = 1; t < M; t++) {
for (int i = 0; i < N; i++) {
for (int m : masks[t]) {
if (getBit(m, i) > 0) {
for (int j = 0; j < N; j++) {
if (getBit(m, j) == 0) {
int b = setBit(m, j);
best[j][b] = Math.max(best[j][b], best[i][m] + A[j] + C[i][j]);
}
}
}
}
}
}
long sat = 0;
for (int i = 0; i < N; i++) {
for (int m : masks[M]) {
sat = Math.max(sat, best[i][m]);
}
}
System.out.println(sat);
}
/**
* Gets the specified bit (0 or 1) in the number.
*/
public static int getBit(int n, int b) {
return (1 & (n >> b));
}
/**
* Sets the specified bit to one in the number.
*/
public static int setBit(int n, int b) {
return ((1 << b) | n);
}
public static class IntList extends ArrayList<Integer> {
private static final long serialVersionUID = 8376426890995232292L;
}
public static class FasterScanner {
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = System.in.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long 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 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 int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
} | Java | ["2 2 1\n1 1\n2 1 1", "4 3 2\n1 2 3 4\n2 1 5\n3 4 2"] | 2 seconds | ["3", "12"] | NoteIn the first sample it is best to first eat the second dish, then the first one. Then we get one unit of satisfaction for each dish and plus one more for the rule.In the second test the fitting sequences of choice are 4 2 1 or 2 1 4. In both cases we get satisfaction 7 for dishes and also, if we fulfill rule 1, we get an additional satisfaction 5. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 5b881f1cd74b17358b954299c2742bdf | The first line of the input contains three space-separated numbers, n, m and k (1 ≤ m ≤ n ≤ 18, 0 ≤ k ≤ n * (n - 1)) — the number of dishes on the menu, the number of portions Kefa needs to eat to get full and the number of eating rules. The second line contains n space-separated numbers ai, (0 ≤ ai ≤ 109) — the satisfaction he gets from the i-th dish. Next k lines contain the rules. The i-th rule is described by the three numbers xi, yi and ci (1 ≤ xi, yi ≤ n, 0 ≤ ci ≤ 109). That means that if you eat dish xi right before dish yi, then the Kefa's satisfaction increases by ci. It is guaranteed that there are no such pairs of indexes i and j (1 ≤ i < j ≤ k), that xi = xj and yi = yj. | 1,800 | In the single line of the output print the maximum satisfaction that Kefa can get from going to the restaurant. | standard output | |
PASSED | cad5286a9977ae742282c418676b1ab8 | train_003.jsonl | 1442939400 | When Kefa came to the restaurant and sat at a table, the waiter immediately brought him the menu. There were n dishes. Kefa knows that he needs exactly m dishes. But at that, he doesn't want to order the same dish twice to taste as many dishes as possible. Kefa knows that the i-th dish gives him ai units of satisfaction. But some dishes do not go well together and some dishes go very well together. Kefa set to himself k rules of eating food of the following type — if he eats dish x exactly before dish y (there should be no other dishes between x and y), then his satisfaction level raises by c. Of course, our parrot wants to get some maximal possible satisfaction from going to the restaurant. Help him in this hard task! | 256 megabytes | /*
If you want to aim high, aim high
Don't let that studying and grades consume you
Just live life young
******************************
What do you think? What do you think?
1st on Billboard, what do you think of it
Next is a Grammy, what do you think of it
However you think, I’m sorry, but shit, I have no fucking interest
*******************************
Higher, higher, even higher, to the point you won’t even be able to see me
https://www.a2oj.com/Ladder16.html
*******************************
300IQ as writer = Sad!
*/
import java.util.*;
import java.io.*;
import java.math.*;
public class x580D
{
public static void main(String omkar[]) throws Exception
{
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int N = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
int K = Integer.parseInt(st.nextToken());
long[] arr = new long[N];
st = new StringTokenizer(infile.readLine());
for(int i=0; i < N; i++)
arr[i] = Long.parseLong(st.nextToken());
long[][] grid = new long[N][N];
for(int i=0; i < K; i++)
{
st = new StringTokenizer(infile.readLine());
int a = Integer.parseInt(st.nextToken())-1;
int b = Integer.parseInt(st.nextToken())-1;
int c = Integer.parseInt(st.nextToken());
grid[a][b] = c;
}
//dp[mask][prev] = max bingbongs with mask seen dishes, previous dish = prev
long[][] dp = new long[1<< N][N];
for(int b=0; b < N; b++)
dp[1<<b][b] = arr[b];
for(int mask=1; mask < (1<<N); mask++)
{
for(int b=0; b < N; b++)
if((mask&(1<<b)) == 0)
{
int submask = mask|(1<<b);
for(int prev=0; prev < N; prev++)
if(prev != b && (mask&(1<<prev)) > 0)
dp[submask][b] = Math.max(dp[submask][b], (long)arr[b]+dp[mask][prev]+grid[prev][b]);
}
}
long res = 0L;
for(int mask=0; mask < (1<<N); mask++)
if(Integer.bitCount(mask) == M)
for(int b=0; b < N; b++)
res = Math.max(res, dp[mask][b]);
System.out.println(res);
}
} | Java | ["2 2 1\n1 1\n2 1 1", "4 3 2\n1 2 3 4\n2 1 5\n3 4 2"] | 2 seconds | ["3", "12"] | NoteIn the first sample it is best to first eat the second dish, then the first one. Then we get one unit of satisfaction for each dish and plus one more for the rule.In the second test the fitting sequences of choice are 4 2 1 or 2 1 4. In both cases we get satisfaction 7 for dishes and also, if we fulfill rule 1, we get an additional satisfaction 5. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 5b881f1cd74b17358b954299c2742bdf | The first line of the input contains three space-separated numbers, n, m and k (1 ≤ m ≤ n ≤ 18, 0 ≤ k ≤ n * (n - 1)) — the number of dishes on the menu, the number of portions Kefa needs to eat to get full and the number of eating rules. The second line contains n space-separated numbers ai, (0 ≤ ai ≤ 109) — the satisfaction he gets from the i-th dish. Next k lines contain the rules. The i-th rule is described by the three numbers xi, yi and ci (1 ≤ xi, yi ≤ n, 0 ≤ ci ≤ 109). That means that if you eat dish xi right before dish yi, then the Kefa's satisfaction increases by ci. It is guaranteed that there are no such pairs of indexes i and j (1 ≤ i < j ≤ k), that xi = xj and yi = yj. | 1,800 | In the single line of the output print the maximum satisfaction that Kefa can get from going to the restaurant. | standard output | |
PASSED | 9d552a00e76a5fa7ae2b34e376f09d1c | train_003.jsonl | 1442939400 | When Kefa came to the restaurant and sat at a table, the waiter immediately brought him the menu. There were n dishes. Kefa knows that he needs exactly m dishes. But at that, he doesn't want to order the same dish twice to taste as many dishes as possible. Kefa knows that the i-th dish gives him ai units of satisfaction. But some dishes do not go well together and some dishes go very well together. Kefa set to himself k rules of eating food of the following type — if he eats dish x exactly before dish y (there should be no other dishes between x and y), then his satisfaction level raises by c. Of course, our parrot wants to get some maximal possible satisfaction from going to the restaurant. Help him in this hard task! | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.stream.IntStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author PloadyFree
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
private int n;
private int m;
private int k;
private int[] a;
private int[][] rules;
private long[][] dp;
public void solve(int testNumber, InputReader in, OutputWriter out) {
input(in);
for (int i = 0; i < n; i++)
dp[1 << i][i] = a[i];
for (int mask = 0; mask < 1 << n; mask++) {
for (int i = 0; i < n; i++) {
if (isSet(mask, i)) {
int prevMask = flipBit(mask, i);
for (int j = 0; j < n; j++) {
if (isSet(prevMask, j)) {
dp[mask][i] = Math.max(dp[mask][i], dp[prevMask][j] + a[i] + rules[j][i]);
}
}
}
}
}
IntStream.range(0, 1 << n)
.filter(i -> Integer.bitCount(i) == m)
.boxed()
.flatMapToLong(i -> Arrays.stream(dp[i]))
.max()
.ifPresent(out::print);
}
private int flipBit(int mask, int bit) {
return mask ^ (1 << bit);
}
private boolean isSet(int mask, int bit) {
return (mask & (1 << bit)) != 0;
}
private void input(InputReader in) {
n = in.readInt();
m = in.readInt();
k = in.readInt();
a = IOUtils.readIntArray(in, n);
rules = new int[n][n];
for (int i = 0; i < k; i++)
rules[in.readInt() - 1][in.readInt() - 1] = in.readInt();
dp = new long[1 << n][n];
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class IOUtils {
public static int[] readIntArray(InputReader in, int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = in.readInt();
return array;
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void print(long i) {
writer.print(i);
}
}
}
| Java | ["2 2 1\n1 1\n2 1 1", "4 3 2\n1 2 3 4\n2 1 5\n3 4 2"] | 2 seconds | ["3", "12"] | NoteIn the first sample it is best to first eat the second dish, then the first one. Then we get one unit of satisfaction for each dish and plus one more for the rule.In the second test the fitting sequences of choice are 4 2 1 or 2 1 4. In both cases we get satisfaction 7 for dishes and also, if we fulfill rule 1, we get an additional satisfaction 5. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 5b881f1cd74b17358b954299c2742bdf | The first line of the input contains three space-separated numbers, n, m and k (1 ≤ m ≤ n ≤ 18, 0 ≤ k ≤ n * (n - 1)) — the number of dishes on the menu, the number of portions Kefa needs to eat to get full and the number of eating rules. The second line contains n space-separated numbers ai, (0 ≤ ai ≤ 109) — the satisfaction he gets from the i-th dish. Next k lines contain the rules. The i-th rule is described by the three numbers xi, yi and ci (1 ≤ xi, yi ≤ n, 0 ≤ ci ≤ 109). That means that if you eat dish xi right before dish yi, then the Kefa's satisfaction increases by ci. It is guaranteed that there are no such pairs of indexes i and j (1 ≤ i < j ≤ k), that xi = xj and yi = yj. | 1,800 | In the single line of the output print the maximum satisfaction that Kefa can get from going to the restaurant. | standard output | |
PASSED | 2cd4f3e6f9b8d9734770626e297822e2 | train_003.jsonl | 1442939400 | When Kefa came to the restaurant and sat at a table, the waiter immediately brought him the menu. There were n dishes. Kefa knows that he needs exactly m dishes. But at that, he doesn't want to order the same dish twice to taste as many dishes as possible. Kefa knows that the i-th dish gives him ai units of satisfaction. But some dishes do not go well together and some dishes go very well together. Kefa set to himself k rules of eating food of the following type — if he eats dish x exactly before dish y (there should be no other dishes between x and y), then his satisfaction level raises by c. Of course, our parrot wants to get some maximal possible satisfaction from going to the restaurant. Help him in this hard task! | 256 megabytes | import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.io.*;
public class Kefa {
static int n;
static int[] dishSat;
static int[][] bonus;
static long[][]memo;
public static void main(String[] args) throws NumberFormatException, IOException, InterruptedException {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
n=sc.nextInt();
int m=sc.nextInt();
int k=sc.nextInt();
dishSat=sc.nextIntArr(n);
bonus=new int[n+1][n+1];
while(k-->0) {
int u=sc.nextInt();
int v=sc.nextInt();
int w=sc.nextInt();
bonus[u][v]=w;
}
memo=new long[1<<n][n+1];
for (long[] x : memo) {
Arrays.fill(x, -1);
}
System.out.println(dp(m,0,0));
}
static long dp(int remM,int done,int last) {
if(memo[done][last]!=-1)
return memo[done][last];
if(remM==0)
return memo[done][last]=0;
long ans=0;
for (int i = 0; i < n; i++) {
if(!check(i,done)) {
int newDone = set(i,done);
long cursat=0l+dishSat[i]+bonus[last][i+1];
ans=Math.max(ans,cursat+ dp(remM-1,newDone,i+1));
}
}
return memo[done][last]=ans;
}
private static int set(int i,int done) {
return (1<<i)^done;
}
private static boolean check(int i,int done) {
return ((1<<i)&done)!=0;
}
static void shuffleArray(int[] ar) {
// If running on Java 6 or older, use `new Random()` on RHS here
Random rnd = ThreadLocalRandom.current();
for (int i = ar.length - 1; i > 0; i--) {
int index = rnd.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
}
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 {
return Double.parseDouble(next());
}
public int[] nextIntArr(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < arr.length; i++)
arr[i] = nextInt();
return arr;
}
public boolean ready() throws IOException {
return br.ready();
}
}
} | Java | ["2 2 1\n1 1\n2 1 1", "4 3 2\n1 2 3 4\n2 1 5\n3 4 2"] | 2 seconds | ["3", "12"] | NoteIn the first sample it is best to first eat the second dish, then the first one. Then we get one unit of satisfaction for each dish and plus one more for the rule.In the second test the fitting sequences of choice are 4 2 1 or 2 1 4. In both cases we get satisfaction 7 for dishes and also, if we fulfill rule 1, we get an additional satisfaction 5. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 5b881f1cd74b17358b954299c2742bdf | The first line of the input contains three space-separated numbers, n, m and k (1 ≤ m ≤ n ≤ 18, 0 ≤ k ≤ n * (n - 1)) — the number of dishes on the menu, the number of portions Kefa needs to eat to get full and the number of eating rules. The second line contains n space-separated numbers ai, (0 ≤ ai ≤ 109) — the satisfaction he gets from the i-th dish. Next k lines contain the rules. The i-th rule is described by the three numbers xi, yi and ci (1 ≤ xi, yi ≤ n, 0 ≤ ci ≤ 109). That means that if you eat dish xi right before dish yi, then the Kefa's satisfaction increases by ci. It is guaranteed that there are no such pairs of indexes i and j (1 ≤ i < j ≤ k), that xi = xj and yi = yj. | 1,800 | In the single line of the output print the maximum satisfaction that Kefa can get from going to the restaurant. | standard output | |
PASSED | e6c4e0703a6265284a37a001e28c8618 | train_003.jsonl | 1442939400 | When Kefa came to the restaurant and sat at a table, the waiter immediately brought him the menu. There were n dishes. Kefa knows that he needs exactly m dishes. But at that, he doesn't want to order the same dish twice to taste as many dishes as possible. Kefa knows that the i-th dish gives him ai units of satisfaction. But some dishes do not go well together and some dishes go very well together. Kefa set to himself k rules of eating food of the following type — if he eats dish x exactly before dish y (there should be no other dishes between x and y), then his satisfaction level raises by c. Of course, our parrot wants to get some maximal possible satisfaction from going to the restaurant. Help him in this hard task! | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.io.BufferedReader;
public class Main{
static int[][] rules;
static int[] val;
static long[][] memo;
static int n;
static int k;
public static void main(String[] args) throws IOException, InterruptedException {
Scanner sc = new Scanner(System.in);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
n = sc.nextInt();
int m = sc.nextInt();
k = sc.nextInt();
val = new int[n];
for (int i = 0; i < n; i++)
val[i] = sc.nextInt();
memo = new long[n][1<<n];
for (long[] i : memo) {
Arrays.fill(i, -1);
}
rules = new int[n][n];
for (int i = 0; i < k; i++)
rules[sc.nextInt()-1][sc.nextInt()-1] = sc.nextInt();
long max = 0;
for (int i = 0; i < n; i++) {
max = Math.max(max,dp(i, 1<<(n-1-i), m-1) + val[i]);
}
out.println(max);
out.flush();
}
static long dp(int i,int mask,int rem) {
if (memo[i][mask] != -1) {
return memo[i][mask];
}
long max = 0;
long sum = 0;
for (int j = 0; j < n; j++) {
if ((mask & 1<<j) == 0 && rem > 0) {
max = Math.max(max, dp(n-1-j, mask | 1<< j, rem-1) + val[n-1-j] + rules[i][n-1-j]);
}
}
if (rem == 0) {
return memo[i][mask] = sum;
}
return memo[i][mask] = max;
}
}
class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
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 boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
} | Java | ["2 2 1\n1 1\n2 1 1", "4 3 2\n1 2 3 4\n2 1 5\n3 4 2"] | 2 seconds | ["3", "12"] | NoteIn the first sample it is best to first eat the second dish, then the first one. Then we get one unit of satisfaction for each dish and plus one more for the rule.In the second test the fitting sequences of choice are 4 2 1 or 2 1 4. In both cases we get satisfaction 7 for dishes and also, if we fulfill rule 1, we get an additional satisfaction 5. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 5b881f1cd74b17358b954299c2742bdf | The first line of the input contains three space-separated numbers, n, m and k (1 ≤ m ≤ n ≤ 18, 0 ≤ k ≤ n * (n - 1)) — the number of dishes on the menu, the number of portions Kefa needs to eat to get full and the number of eating rules. The second line contains n space-separated numbers ai, (0 ≤ ai ≤ 109) — the satisfaction he gets from the i-th dish. Next k lines contain the rules. The i-th rule is described by the three numbers xi, yi and ci (1 ≤ xi, yi ≤ n, 0 ≤ ci ≤ 109). That means that if you eat dish xi right before dish yi, then the Kefa's satisfaction increases by ci. It is guaranteed that there are no such pairs of indexes i and j (1 ≤ i < j ≤ k), that xi = xj and yi = yj. | 1,800 | In the single line of the output print the maximum satisfaction that Kefa can get from going to the restaurant. | standard output | |
PASSED | 0e18294d9e3ba21510de4ba09c3907ef | train_003.jsonl | 1442939400 | When Kefa came to the restaurant and sat at a table, the waiter immediately brought him the menu. There were n dishes. Kefa knows that he needs exactly m dishes. But at that, he doesn't want to order the same dish twice to taste as many dishes as possible. Kefa knows that the i-th dish gives him ai units of satisfaction. But some dishes do not go well together and some dishes go very well together. Kefa set to himself k rules of eating food of the following type — if he eats dish x exactly before dish y (there should be no other dishes between x and y), then his satisfaction level raises by c. Of course, our parrot wants to get some maximal possible satisfaction from going to the restaurant. Help him in this hard task! | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class KefaAndDishes {
static class STDIN {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
String next() throws Exception {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
int nextInt() throws Exception {
return Integer.parseInt(next());
}
}
static int n, m, k;
static long[][] dp, cost;
static int[] hap;
public static void main(String[] args)throws Exception {
STDIN scan = new STDIN();
n = scan.nextInt();
m = scan.nextInt();
k = scan.nextInt();
hap = new int[n];
dp = new long[1 << n][n + 1];
cost = new long[n + 1][n + 1];
for (int i = 0; i < n; i++) {
hap[i] = scan.nextInt();
}
for (long[] d : dp)
Arrays.fill(d, -1);
for (int i = 0; i < k; i++) {
int d1 = scan.nextInt() - 1, d2 = scan.nextInt() - 1, c = scan.nextInt();
cost[d1][d2] = c;
}
long ans = calc(0, n);
System.out.println(ans);
}
private static long calc(int mask, int prev) {
if (Integer.bitCount(mask) == m)
return 0;
if (dp[mask][prev] != -1) {
return dp[mask][prev];
}
for (int i = 0; i < n; i++) {
if (((mask >> i) & 1) == 0) {
dp[mask][prev] = Math.max(dp[mask][prev], hap[i] + 1L * cost[prev][i] + calc(mask | (1 << i), i));
}
}
return dp[mask][prev];
}
}
| Java | ["2 2 1\n1 1\n2 1 1", "4 3 2\n1 2 3 4\n2 1 5\n3 4 2"] | 2 seconds | ["3", "12"] | NoteIn the first sample it is best to first eat the second dish, then the first one. Then we get one unit of satisfaction for each dish and plus one more for the rule.In the second test the fitting sequences of choice are 4 2 1 or 2 1 4. In both cases we get satisfaction 7 for dishes and also, if we fulfill rule 1, we get an additional satisfaction 5. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 5b881f1cd74b17358b954299c2742bdf | The first line of the input contains three space-separated numbers, n, m and k (1 ≤ m ≤ n ≤ 18, 0 ≤ k ≤ n * (n - 1)) — the number of dishes on the menu, the number of portions Kefa needs to eat to get full and the number of eating rules. The second line contains n space-separated numbers ai, (0 ≤ ai ≤ 109) — the satisfaction he gets from the i-th dish. Next k lines contain the rules. The i-th rule is described by the three numbers xi, yi and ci (1 ≤ xi, yi ≤ n, 0 ≤ ci ≤ 109). That means that if you eat dish xi right before dish yi, then the Kefa's satisfaction increases by ci. It is guaranteed that there are no such pairs of indexes i and j (1 ≤ i < j ≤ k), that xi = xj and yi = yj. | 1,800 | In the single line of the output print the maximum satisfaction that Kefa can get from going to the restaurant. | standard output | |
PASSED | 1976c156e450e0d54e51b88d5dbf189d | train_003.jsonl | 1442939400 | When Kefa came to the restaurant and sat at a table, the waiter immediately brought him the menu. There were n dishes. Kefa knows that he needs exactly m dishes. But at that, he doesn't want to order the same dish twice to taste as many dishes as possible. Kefa knows that the i-th dish gives him ai units of satisfaction. But some dishes do not go well together and some dishes go very well together. Kefa set to himself k rules of eating food of the following type — if he eats dish x exactly before dish y (there should be no other dishes between x and y), then his satisfaction level raises by c. Of course, our parrot wants to get some maximal possible satisfaction from going to the restaurant. Help him in this hard task! | 256 megabytes | import java.util.Arrays;
import java.util.Scanner;
public class KefaAndDishes {
static int n, m, k;
static long[][] dp, cost;
static int[] hap;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
n = scan.nextInt();
m = scan.nextInt();
k = scan.nextInt();
hap = new int[n];
dp = new long[1 << n][n + 1];
cost = new long[n + 1][n + 1];
for (int i = 0; i < n; i++) {
hap[i] = scan.nextInt();
}
for (long[] d : dp)
Arrays.fill(d, -1);
for (int i = 0; i < k; i++) {
int d1 = scan.nextInt() - 1, d2 = scan.nextInt() - 1, c = scan.nextInt();
cost[d1][d2] = c;
}
long ans = calc(0, n);
System.out.println(ans);
}
private static long calc(int mask, int prev) {
if (ones(mask) == m)
return 0;
if (dp[mask][prev] != -1) {
return dp[mask][prev];
}
dp[mask][prev] = 0;
for (int i = 0; i < n; i++) {
if (!isSet(mask, i)) {
dp[mask][prev] = Math.max(dp[mask][prev], hap[i] + 1L * cost[prev][i] + calc(mask | (1 << i), i));
}
}
return dp[mask][prev];
}
private static boolean isSet(int mask, int i) {
return ((mask >> i) & 1) != 0;
}
static int ones(int n) {
return n == 0 ? 0 : n % 2 + ones(n >> 1);
}
}
| Java | ["2 2 1\n1 1\n2 1 1", "4 3 2\n1 2 3 4\n2 1 5\n3 4 2"] | 2 seconds | ["3", "12"] | NoteIn the first sample it is best to first eat the second dish, then the first one. Then we get one unit of satisfaction for each dish and plus one more for the rule.In the second test the fitting sequences of choice are 4 2 1 or 2 1 4. In both cases we get satisfaction 7 for dishes and also, if we fulfill rule 1, we get an additional satisfaction 5. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 5b881f1cd74b17358b954299c2742bdf | The first line of the input contains three space-separated numbers, n, m and k (1 ≤ m ≤ n ≤ 18, 0 ≤ k ≤ n * (n - 1)) — the number of dishes on the menu, the number of portions Kefa needs to eat to get full and the number of eating rules. The second line contains n space-separated numbers ai, (0 ≤ ai ≤ 109) — the satisfaction he gets from the i-th dish. Next k lines contain the rules. The i-th rule is described by the three numbers xi, yi and ci (1 ≤ xi, yi ≤ n, 0 ≤ ci ≤ 109). That means that if you eat dish xi right before dish yi, then the Kefa's satisfaction increases by ci. It is guaranteed that there are no such pairs of indexes i and j (1 ≤ i < j ≤ k), that xi = xj and yi = yj. | 1,800 | In the single line of the output print the maximum satisfaction that Kefa can get from going to the restaurant. | standard output | |
PASSED | da50612c1a29fa19da975c2eeef3fdb2 | train_003.jsonl | 1442939400 | When Kefa came to the restaurant and sat at a table, the waiter immediately brought him the menu. There were n dishes. Kefa knows that he needs exactly m dishes. But at that, he doesn't want to order the same dish twice to taste as many dishes as possible. Kefa knows that the i-th dish gives him ai units of satisfaction. But some dishes do not go well together and some dishes go very well together. Kefa set to himself k rules of eating food of the following type — if he eats dish x exactly before dish y (there should be no other dishes between x and y), then his satisfaction level raises by c. Of course, our parrot wants to get some maximal possible satisfaction from going to the restaurant. Help him in this hard task! | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class KefaAndDishes {
static class STDIN {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
String next() throws Exception {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
int nextInt() throws Exception {
return Integer.parseInt(next());
}
}
static int n, m, k;
static long[][] dp, cost;
static int[] hap;
public static void main(String[] args)throws Exception {
STDIN scan = new STDIN();
n = scan.nextInt();
m = scan.nextInt();
k = scan.nextInt();
hap = new int[n];
dp = new long[1 << n][n + 1];
cost = new long[n + 1][n + 1];
for (int i = 0; i < n; i++) {
hap[i] = scan.nextInt();
}
for (long[] d : dp)
Arrays.fill(d, -1);
for (int i = 0; i < k; i++) {
int d1 = scan.nextInt() - 1, d2 = scan.nextInt() - 1, c = scan.nextInt();
cost[d1][d2] = c;
}
long ans = calc(0, n);
System.out.println(ans);
}
private static long calc(int mask, int prev) {
if (ones(mask) == m)
return 0;
if (dp[mask][prev] != -1) {
return dp[mask][prev];
}
dp[mask][prev] = 0;
for (int i = 0; i < n; i++) {
if (!isSet(mask, i)) {
dp[mask][prev] = Math.max(dp[mask][prev], hap[i] + 1L * cost[prev][i] + calc(mask | (1 << i), i));
}
}
return dp[mask][prev];
}
private static boolean isSet(int mask, int i) {
return ((mask >> i) & 1) != 0;
}
static int ones(int n) {
return n == 0 ? 0 : n % 2 + ones(n >> 1);
}
}
| Java | ["2 2 1\n1 1\n2 1 1", "4 3 2\n1 2 3 4\n2 1 5\n3 4 2"] | 2 seconds | ["3", "12"] | NoteIn the first sample it is best to first eat the second dish, then the first one. Then we get one unit of satisfaction for each dish and plus one more for the rule.In the second test the fitting sequences of choice are 4 2 1 or 2 1 4. In both cases we get satisfaction 7 for dishes and also, if we fulfill rule 1, we get an additional satisfaction 5. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 5b881f1cd74b17358b954299c2742bdf | The first line of the input contains three space-separated numbers, n, m and k (1 ≤ m ≤ n ≤ 18, 0 ≤ k ≤ n * (n - 1)) — the number of dishes on the menu, the number of portions Kefa needs to eat to get full and the number of eating rules. The second line contains n space-separated numbers ai, (0 ≤ ai ≤ 109) — the satisfaction he gets from the i-th dish. Next k lines contain the rules. The i-th rule is described by the three numbers xi, yi and ci (1 ≤ xi, yi ≤ n, 0 ≤ ci ≤ 109). That means that if you eat dish xi right before dish yi, then the Kefa's satisfaction increases by ci. It is guaranteed that there are no such pairs of indexes i and j (1 ≤ i < j ≤ k), that xi = xj and yi = yj. | 1,800 | In the single line of the output print the maximum satisfaction that Kefa can get from going to the restaurant. | standard output | |
PASSED | caca7055c5750b9a4ee3f44ed603b17d | train_003.jsonl | 1442939400 | When Kefa came to the restaurant and sat at a table, the waiter immediately brought him the menu. There were n dishes. Kefa knows that he needs exactly m dishes. But at that, he doesn't want to order the same dish twice to taste as many dishes as possible. Kefa knows that the i-th dish gives him ai units of satisfaction. But some dishes do not go well together and some dishes go very well together. Kefa set to himself k rules of eating food of the following type — if he eats dish x exactly before dish y (there should be no other dishes between x and y), then his satisfaction level raises by c. Of course, our parrot wants to get some maximal possible satisfaction from going to the restaurant. Help him in this hard task! | 256 megabytes | import java.io.*;
import java.util.Arrays;
import java.util.StringTokenizer;
public class D580 {
static int m, n, k;
static int satis[][];
static int dishes[];
static long memo[][];
public static void main(String[] args) throws IOException, InterruptedException {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
m = sc.nextInt();
n = sc.nextInt();
k = sc.nextInt();
dishes = new int[m];
satis = new int[m + 1][m + 1];
memo = new long[m+1][(1 << m) + 1];
for (int i = 0; i < m; i++)
dishes[i] = sc.nextInt();
for (int i = 0; i < k; i++)
satis[sc.nextInt() - 1][sc.nextInt() - 1] = sc.nextInt();
for(int i=0;i<m+1;i++)
Arrays.fill(memo[i],-1);
pw.println(dp(m,0));
pw.flush();
}
static long dp(int idx, int bmask) {
if (Integer.bitCount(bmask) == n)
return 0;
if (memo[idx][bmask] != -1)
return memo[idx][bmask];
long ans = 0;
for (int i = 0; i < m; i++) {
if (((1 << i) & bmask) == 0) {
ans = Math.max(ans, satis[idx][i] + dishes[i] + dp(i, bmask | (1 << i)));
}
}
return memo[idx][bmask] = ans;
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
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 boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(4000);
}
}
}
| Java | ["2 2 1\n1 1\n2 1 1", "4 3 2\n1 2 3 4\n2 1 5\n3 4 2"] | 2 seconds | ["3", "12"] | NoteIn the first sample it is best to first eat the second dish, then the first one. Then we get one unit of satisfaction for each dish and plus one more for the rule.In the second test the fitting sequences of choice are 4 2 1 or 2 1 4. In both cases we get satisfaction 7 for dishes and also, if we fulfill rule 1, we get an additional satisfaction 5. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 5b881f1cd74b17358b954299c2742bdf | The first line of the input contains three space-separated numbers, n, m and k (1 ≤ m ≤ n ≤ 18, 0 ≤ k ≤ n * (n - 1)) — the number of dishes on the menu, the number of portions Kefa needs to eat to get full and the number of eating rules. The second line contains n space-separated numbers ai, (0 ≤ ai ≤ 109) — the satisfaction he gets from the i-th dish. Next k lines contain the rules. The i-th rule is described by the three numbers xi, yi and ci (1 ≤ xi, yi ≤ n, 0 ≤ ci ≤ 109). That means that if you eat dish xi right before dish yi, then the Kefa's satisfaction increases by ci. It is guaranteed that there are no such pairs of indexes i and j (1 ≤ i < j ≤ k), that xi = xj and yi = yj. | 1,800 | In the single line of the output print the maximum satisfaction that Kefa can get from going to the restaurant. | standard output | |
PASSED | 4815880ff04a6696166823a5fc0c2507 | train_003.jsonl | 1575038100 | One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of $$$n$$$ passwords — strings, consists of small Latin letters.Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords $$$a$$$ and $$$b$$$ as follows: two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a letter, that exists in both $$$a$$$ and $$$b$$$; two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a password $$$c$$$ from the list, which is equivalent to both $$$a$$$ and $$$b$$$. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
static ArrayList<Integer> adj_lst[];
static boolean vis[];
public static void main(String args[]){
Scanner input=new Scanner(System.in);
//No of nodes
int n=input.nextInt();
boolean arr[][]=new boolean[n][26];
for(int i=0;i<n;i++) {
String str=input.next();
for(int j=0;j<str.length();j++) {
arr[i][str.charAt(j)-97]=true;
}
}
adj_lst=new ArrayList[n];
vis=new boolean[adj_lst.length];
for(int i=0;i<adj_lst.length;i++) {
adj_lst[i]=new ArrayList<Integer>();
}
//No of edges
for(int i=0;i<26;i++) {
int first=-1;
for(int j=0;j<n;j++) {
if(arr[j][i]) {
first=j;
break;
}
}
if(first==-1) {
continue;
}
for(int j=first+1;j<n;j++) {
if(arr[j][i]) {
adj_lst[first].add(j);
adj_lst[j].add(first);
}
}
}
// for(int i=0;i<adj_lst.length;i++) {
// System.out.print(i+"->");
// for(int j=0;j<adj_lst[i].size();j++) {
// System.out.print(adj_lst[i].get(j)+" ");
// }
// System.out.println();
// }
int count=0;
for(int i=0;i<n;i++) {
if(!vis[i]) {
DFS(i);
count++;
}
}
System.out.println(count);
}
public static void DFS(int root) {
vis[root]=true;
for(int i=0;i<adj_lst[root].size();i++) {
if(!vis[adj_lst[root].get(i)]) {
DFS(adj_lst[root].get(i));
}
}
}
}
| Java | ["4\na\nb\nab\nd", "3\nab\nbc\nabc", "1\ncodeforces"] | 1 second | ["2", "1", "1"] | NoteIn the second example hacker need to use any of the passwords to access the system. | Java 11 | standard input | [
"dsu",
"dfs and similar",
"graphs"
] | 00db0111fd80ce1820da2af07a6cb8f1 | The first line contain integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — number of passwords in the list. Next $$$n$$$ lines contains passwords from the list – non-empty strings $$$s_i$$$, with length at most $$$50$$$ letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed $$$10^6$$$ letters. All of them consist only of lowercase Latin letters. | 1,500 | In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system. | standard output | |
PASSED | 45a4e871419cda6a1c98c30103bc9a56 | train_003.jsonl | 1575038100 | One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of $$$n$$$ passwords — strings, consists of small Latin letters.Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords $$$a$$$ and $$$b$$$ as follows: two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a letter, that exists in both $$$a$$$ and $$$b$$$; two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a password $$$c$$$ from the list, which is equivalent to both $$$a$$$ and $$$b$$$. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args){
InputStream inputstream;
OutputStream outputstream;
inputstream = System.in;
outputstream = System.out;
InputReader in = new InputReader(inputstream);
PrintWriter out = new PrintWriter(outputstream);
Task solver = new Task();
solver.solve(in,out);
out.close();
}
static class Task{
int n;
int[] idx = new int[26];
public void solve(InputReader in,PrintWriter out){
n = in.nextInt();
Arrays.fill(idx,-1);
Dsu dsu = new Dsu(n);
for(int i = 0;i < n;++i){
String s = in.nextLine();
for(int j = 0;j < s.length();++j){
char c = s.charAt(j);
if(idx[c - 'a'] == -1){
idx[c - 'a'] = i;
} else {
dsu.join(i,idx[c - 'a']);
}
}
}
int ans = 0;
for(int i = 0;i < n;++i){
ans += (i == dsu.findp(i) ? 1 : 0);
}
out.print(ans);
}
public class Dsu {
int[] par;
public Dsu(int _size){
par = new int[_size];
for(int i = 0;i < _size;++i){
par[i] = i;
}
}
int findp(int u){
return (par[u] == u ? par[u] : (par[u] = findp(par[u])));
}
void join(int u,int v){
par[findp(u)] = par[findp(v)];
}
}
}
static class InputReader{
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream){
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String next(){
while(tokenizer == null || !tokenizer.hasMoreTokens()){
try{
tokenizer = new StringTokenizer(reader.readLine());
} catch (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(){
String ret_str = "";
try {
ret_str = reader.readLine();
} catch (IOException e){
e.printStackTrace();
}
return ret_str;
}
}
}
| Java | ["4\na\nb\nab\nd", "3\nab\nbc\nabc", "1\ncodeforces"] | 1 second | ["2", "1", "1"] | NoteIn the second example hacker need to use any of the passwords to access the system. | Java 11 | standard input | [
"dsu",
"dfs and similar",
"graphs"
] | 00db0111fd80ce1820da2af07a6cb8f1 | The first line contain integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — number of passwords in the list. Next $$$n$$$ lines contains passwords from the list – non-empty strings $$$s_i$$$, with length at most $$$50$$$ letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed $$$10^6$$$ letters. All of them consist only of lowercase Latin letters. | 1,500 | In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system. | standard output | |
PASSED | b1675ad9c1736150b7d626ef4701a52e | train_003.jsonl | 1575038100 | One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of $$$n$$$ passwords — strings, consists of small Latin letters.Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords $$$a$$$ and $$$b$$$ as follows: two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a letter, that exists in both $$$a$$$ and $$$b$$$; two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a password $$$c$$$ from the list, which is equivalent to both $$$a$$$ and $$$b$$$. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system. | 256 megabytes | import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.Set;
public class SecretPasswords {
InputStream is;
PrintWriter pw;
String INPUT = "";
long L_INF = (1L << 60L);
void solve() {
int n=ni(), m;
String a[] = new String[n];
for (int i = 0; i < n; i++) {
a[i]=ns();
}
UnionFind uf = new UnionFind(26);
int check=0;
for (int i = 0; i < n; i++) {
for (int j = 1; j < a[i].length(); j++) {
uf.union(a[i].charAt(j)-'a',a[i].charAt(0)-'a');
}
}
Set<Integer> st = new HashSet<>();
for (int i = 0; i < n; i++) {
st.add(uf.root(a[i].charAt(0)-'a'));
}
pw.println(st.size());
}
static class UnionFind {
private int count; // num of components
private int id[]; // id[i] = root of i
private int rank[]; // rank[i] = size of subtree rooted at i (cant be more than 31)
private int numNodes[];
UnionFind(int n) {
count = n;
id = new int[n];
rank = new int[n];
numNodes = new int[n];
int i;
for (i = 0; i < n; i++) {
id[i] = i; // each tree is its own root
rank[i] = 0;
numNodes[i] = 1; // each tree has 1 node(itself) in the beginning
}
}
/**
* @return the root of the parameter p
*/
int root(int p) {
while (p != id[p]) {
id[p] = id[id[p]]; // path compression
p = id[p];
}
return p;
}
/**
* @return true if a and b belong to same subtree
*/
boolean find(int a, int b) {
if (root(a) == root(b))
return true;
return false;
}
/**
* union of subtree a with b according to rank
*/
int union(int a, int b) {
int root_a = root(a);
int root_b = root(b);
if(a==b && root_a==a)
return 1;
if (root_a == root_b)
return 0;
if (rank[root_a] > rank[root_b]) {
id[root_b] = root_a;
numNodes[root_a] += numNodes[root_b];
} else if (rank[root_b] > rank[root_a]) {
id[root_a] = root_b;
numNodes[root_b] += numNodes[root_a];
} else {
id[root_a] = root_b;
numNodes[root_b] += numNodes[root_a];
rank[root_b]++;
}
count--;
return 0;
}
/**
* @return number of components in tree
*/
int componentSize(int a) {
int root_a = root(a);
return numNodes[root_a];
}
int numOfComponents() {
return count;
}
}
void run() throws Exception {
// is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
is = System.in;
pw = new PrintWriter(System.out);
long s = System.currentTimeMillis();
// int t = ni();
// while (t-- > 0)
solve();
pw.flush();
tr(System.currentTimeMillis() - s + "ms");
}
public static void main(String[] args) throws Exception {
new SecretPasswords().run();
}
private byte[] inbuf = new byte[1024];
private int lenbuf = 0, ptrbuf = 0;
private int readByte() {
if (lenbuf == -1) throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0) return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b)) ;
return b;
}
private double nd() {
return Double.parseDouble(ns());
}
private char nc() {
return (char) skip();
}
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++) map[i] = ns(m);
return map;
}
private int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = ni();
return a;
}
private int ni() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private long nl() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) {
if (!oj) System.out.println(Arrays.deepToString(o));
}
}
| Java | ["4\na\nb\nab\nd", "3\nab\nbc\nabc", "1\ncodeforces"] | 1 second | ["2", "1", "1"] | NoteIn the second example hacker need to use any of the passwords to access the system. | Java 11 | standard input | [
"dsu",
"dfs and similar",
"graphs"
] | 00db0111fd80ce1820da2af07a6cb8f1 | The first line contain integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — number of passwords in the list. Next $$$n$$$ lines contains passwords from the list – non-empty strings $$$s_i$$$, with length at most $$$50$$$ letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed $$$10^6$$$ letters. All of them consist only of lowercase Latin letters. | 1,500 | In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system. | standard output | |
PASSED | bf39dceae93830096045107ecd706cd5 | train_003.jsonl | 1575038100 | One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of $$$n$$$ passwords — strings, consists of small Latin letters.Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords $$$a$$$ and $$$b$$$ as follows: two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a letter, that exists in both $$$a$$$ and $$$b$$$; two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a password $$$c$$$ from the list, which is equivalent to both $$$a$$$ and $$$b$$$. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system. | 256 megabytes | import java.io.*;
import java.util.*;
public class template {
public static void main(String[] args) throws IOException {
FastReader scan = new FastReader();
//PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("radio.out")));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
Task solver = new Task();
//int t = scan.nextInt();
int t = 1;
for(int i = 1; i <= t; i++) solver.solve(i, scan, out);
out.close();
}
static class Task {
public void solve(int testNumber, FastReader sc, PrintWriter pw) {
int n =sc.nextInt();
int check[] = new int[26];
int next = 1;
for(int i=0;i<n;i++){
String str = sc.nextLine();
boolean[] cont = new boolean[26];
for(char x : str.toCharArray()){
cont[x-'a']=true;
}
Set<Integer> group = new HashSet<Integer>();
for(int j=0;j<26;j++){
if(check[j]!=0&&cont[j]){
group.add(check[j]);
}
}
for(int j=0;j<26;j++){
if(group.contains(check[j])||cont[j]){
check[j]=next;
}
}
next++;
}
int out = 0;
Set<Integer> group = new HashSet<Integer>();
for(int i=0;i<26;i++){
if(check[i]!=0&&!group.contains(check[i])){
group.add(check[i]);
}
}
pw.println(group.size());
}
}
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 class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws FileNotFoundException {
br = new BufferedReader(new FileReader(new File(s)));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["4\na\nb\nab\nd", "3\nab\nbc\nabc", "1\ncodeforces"] | 1 second | ["2", "1", "1"] | NoteIn the second example hacker need to use any of the passwords to access the system. | Java 11 | standard input | [
"dsu",
"dfs and similar",
"graphs"
] | 00db0111fd80ce1820da2af07a6cb8f1 | The first line contain integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — number of passwords in the list. Next $$$n$$$ lines contains passwords from the list – non-empty strings $$$s_i$$$, with length at most $$$50$$$ letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed $$$10^6$$$ letters. All of them consist only of lowercase Latin letters. | 1,500 | In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system. | standard output | |
PASSED | 26150de986dea37848cab6cf4d13ab96 | train_003.jsonl | 1575038100 | One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of $$$n$$$ passwords — strings, consists of small Latin letters.Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords $$$a$$$ and $$$b$$$ as follows: two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a letter, that exists in both $$$a$$$ and $$$b$$$; two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a password $$$c$$$ from the list, which is equivalent to both $$$a$$$ and $$$b$$$. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system. | 256 megabytes |
import java.io.*;
import java.util.*;
import java.util.Map.Entry;
import javax.swing.text.InternationalFormatter;
import java.math.*;
public class temp1 {
public static PrintWriter out;
static int[] a;
static int[] b;
static StringBuilder sb = new StringBuilder();
static int ans = 0;
public static void main(String[] args) throws IOException {
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
ArrayList<String> p = new ArrayList<>();
HashSet<Integer>[] a = new HashSet[256];
for (int i = 0; i < 256; i++)
a[i] = new HashSet<>();
for (int i = 0; i < n; i++) {
String x = scn.next();
p.add(x);
for (char ch : x.toCharArray()) {
a[ch].add(i);
}
}
DSU d = new DSU(n);
for (int i = 0; i < 256; i++) {
if (a[i].size() != 0) {
ArrayList<Integer> st = new ArrayList<>();
for (int h : a[i])
st.add(h);
for (int j = 1; j < st.size(); j++)
d.merge(st.get(0), st.get(j));
}
}
System.out.println(d.connected);
}
private static class DSU {
int[] size;
int[] parent;
int connected;
public DSU(int n) {
size = new int[n + 1];
parent = new int[n + 1];
for (int i = 1; i <= n; i++) {
size[i] = 1;
parent[i] = i;
}
connected = n;
}
public int find(int v) {
if (v == parent[v])
return v;
parent[v] = find(parent[v]);
return parent[v];
}
public void merge(int u, int v){
int p1=find(u);
int p2=find(v);
if(p1 == p2)
return;
connected--;
if(size[p1]>size[p2]){
size[p1]+=size[p2];
parent[p2]=p1;
}
else{
size[p2]+=size[p1];
parent[p1]=p2;
}
}
}
// _________________________TEMPLATE_____________________________________________________________
// private static int gcd(int a, int b) {
// if(a== 0)
// return b;
//
// return gcd(b%a,a);
// }
// static class comp implements Comparator<pair> {
//
// @Override
// public int compare(pair o1, pair o2) {
// return o2.b - o1.b;
// }
//
// }
static class pair implements Comparable<pair> {
int u;
int v;
pair(int a, int b) {
u = a < b ? a : b;
v = a == u ? b : a;
}
@Override
public int compareTo(pair o) {
return (int) (this.v - o.u);
}
}
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[100000 + 1]; // 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 int[] nextIntArray(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) throws IOException {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
public int[][] nextInt2DArray(int m, int n) throws IOException {
int[][] arr = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++)
arr[i][j] = nextInt();
}
return arr;
}
}
} | Java | ["4\na\nb\nab\nd", "3\nab\nbc\nabc", "1\ncodeforces"] | 1 second | ["2", "1", "1"] | NoteIn the second example hacker need to use any of the passwords to access the system. | Java 11 | standard input | [
"dsu",
"dfs and similar",
"graphs"
] | 00db0111fd80ce1820da2af07a6cb8f1 | The first line contain integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — number of passwords in the list. Next $$$n$$$ lines contains passwords from the list – non-empty strings $$$s_i$$$, with length at most $$$50$$$ letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed $$$10^6$$$ letters. All of them consist only of lowercase Latin letters. | 1,500 | In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system. | standard output | |
PASSED | e8d7fdf9d6db4ee09ea372c6259649df | train_003.jsonl | 1575038100 | One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of $$$n$$$ passwords — strings, consists of small Latin letters.Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords $$$a$$$ and $$$b$$$ as follows: two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a letter, that exists in both $$$a$$$ and $$$b$$$; two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a password $$$c$$$ from the list, which is equivalent to both $$$a$$$ and $$$b$$$. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system. | 256 megabytes | import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
public class Main {
static final int INF = (int) (1e9 + 10);
static final int MOD = (int) (1e9 + 7);
// static final int N = (int) (4e5 + 5);
// static ArrayList<Integer>[] graph;
// static boolean visited[];
// static long size[];
public static void main(String[] args) throws NumberFormatException, IOException {
FastReader sc = new FastReader();
PrintWriter pr = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = sc.nextInt();
HashMap<String , Integer> map= new HashMap<>();
String [] str = new String [n];
for(int i =0 ; i < n; i++){
str [i] = sc.next();
// map.put(str[i], i);
}
Unionfind uf = new Unionfind(n);
for(int i =0; i < n; i++){
HashSet<Character> set = new HashSet<>();
String ref = str[i];
for(char ch : ref.toCharArray()){
set.add(ch);
}
for(int j = i+1 ; j < n ; j++){
if(uf.find(i) == uf.find(j)) break;
for(char cc : str[j].toCharArray()){
if(set.contains(cc)){
uf.union(i , j);
break;
}
}
}
}
pr.print(uf.count());
pr.flush();
pr.close();
}
public static class Unionfind{
private int count = 0;
private int[] parent , rank;
public Unionfind(int n ){
count = n;
parent =new int[n];
rank =new int[n];
for(int i = 0 ; i < n ; i++){
parent[i] = i;
}
}
public int find(int p){
while(p != parent[p]){
parent[p] = parent[parent[p]];
p = parent[p];
}
return p;
}
public void union(int p , int q){
int rootP = find(p);
int rootQ= find(q);
if(rootP == rootQ) return;
if(rank[rootQ] > rank[rootP]){
parent[rootP] = rootQ;
}else{
parent[rootQ] = rootP;
if(rank[rootP]== rank[rootQ]){
rank[rootP]++;
}
}
count--;
}
public int count(){
return count;
}
}
/*
* Template From Here
*/
private static boolean possible(long[] arr, int[] f, long mid, long k) {
long c = 0;
for (int i = 0; i < arr.length; i++) {
if ((arr[i] * f[f.length - i - 1]) > mid) {
c += (arr[i] - (mid / f[f.length - i - 1]));
}
}
// System.out.println(mid+" "+c);
if (c <= k)
return true;
return false;
}
public static int lowerBound(ArrayList<Integer> array, int length, long value) {
int low = 0;
int high = length;
while (low < high) {
final int mid = (low + high) / 2;
if (value <= array.get(mid)) {
high = mid;
} else {
low = mid + 1;
}
}
return low;
}
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 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[][] att, int col) {
// Using built-in sort function Arrays.sort
Arrays.sort(att, new Comparator<int[]>() {
@Override
// Compare values according to columns
public int compare(final int[] entry1, final int[] entry2) {
// To sort in descending order revert
// the '>' Operator
// if (entry1[col] > entry2[col])
// return 1;
// else //(entry1[col] >= entry2[col])
// return -1;
return new Integer(entry1[col]).compareTo(entry2[col]);
// return entry1[col].
}
}); // End of function call sort().
}
static class pair {
int V, I;
pair(int v, int i) {
V = v;
I = i;
}
}
public static int[] swap(int data[], int left, int right) {
int temp = data[left];
data[left] = data[right];
data[right] = temp;
return data;
}
public static int[] reverse(int data[], int left, int right) {
while (left < right) {
int temp = data[left];
data[left++] = data[right];
data[right--] = temp;
}
return data;
}
public static boolean findNextPermutation(int data[]) {
if (data.length <= 1)
return false;
int last = data.length - 2;
while (last >= 0) {
if (data[last] < data[last + 1]) {
break;
}
last--;
}
if (last < 0)
return false;
int nextGreater = data.length - 1;
for (int i = data.length - 1; i > last; i--) {
if (data[i] > data[last]) {
nextGreater = i;
break;
}
}
data = swap(data, nextGreater, last);
data = reverse(data, last + 1, data.length - 1);
return true;
}
static long nCr(long n, long r) {
if (n == r)
return 1;
return fact(n) / (fact(r) * fact(n - r));
}
static long fact(long n) {
long res = 1;
for (long i = 2; i <= n; i++)
res = res * i;
return res;
}
/*
* static boolean prime[] = new boolean[1000007];
*
* public static void sieveOfEratosthenes(int n) {
*
* for (int i = 0; i < n; i++) prime[i] = true; * for (int p = 2; p * p <=
* n; p++) { // If prime[p] is not changed, then it is a prime if (prime[p]
* == true) { // Update all multiples of p for (int i = p * p; i <= n; i +=
* p) prime[i] = false; } }
*
* // Print all prime numbers // for(int i = 2; i <= n; i++) // { //
* if(prime[i] == true) // System.out.print(i + " "); // } }
*/
static long power(long fac2, int y, int p) {
long res = 1;
fac2 = fac2 % p;
while (y > 0) {
if (y % 2 == 1)
res = (res * fac2) % p;
fac2 = (fac2 * fac2) % p;
}
return res;
}
static long modInverse(long fac2, int p) {
return power(fac2, p - 2, p);
}
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;
}
public static BigInteger lcmm(String a, String b) {
BigInteger s = new BigInteger(a);
BigInteger s1 = new BigInteger(b);
BigInteger mul = s.multiply(s1);
BigInteger gcd = s.gcd(s1);
BigInteger lcm = mul.divide(gcd);
return lcm;
}
} | Java | ["4\na\nb\nab\nd", "3\nab\nbc\nabc", "1\ncodeforces"] | 1 second | ["2", "1", "1"] | NoteIn the second example hacker need to use any of the passwords to access the system. | Java 11 | standard input | [
"dsu",
"dfs and similar",
"graphs"
] | 00db0111fd80ce1820da2af07a6cb8f1 | The first line contain integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — number of passwords in the list. Next $$$n$$$ lines contains passwords from the list – non-empty strings $$$s_i$$$, with length at most $$$50$$$ letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed $$$10^6$$$ letters. All of them consist only of lowercase Latin letters. | 1,500 | In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system. | standard output | |
PASSED | fcf7ba5dcb0259cd060746c28c2dbcde | train_003.jsonl | 1575038100 | One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of $$$n$$$ passwords — strings, consists of small Latin letters.Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords $$$a$$$ and $$$b$$$ as follows: two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a letter, that exists in both $$$a$$$ and $$$b$$$; two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a password $$$c$$$ from the list, which is equivalent to both $$$a$$$ and $$$b$$$. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Vector;
import java.util.Scanner;
import java.util.Stack;
import java.util.ArrayList;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Kraken7
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
private ArrayList<ArrayList<Integer>> graph = new ArrayList<>();
private boolean[] vis;
private void dfs(int vertex) {
vis[vertex] = true;
Stack<Integer> stack = new Stack<>();
stack.push(vertex);
while (!stack.isEmpty()) {
int curr = stack.pop();
for (int i : graph.get(curr)) {
if (vis[i])
continue;
vis[i] = true;
stack.push(i);
}
}
}
public void solve(int testNumber, Scanner in, PrintWriter out) {
int n = in.nextInt();
vis = new boolean[n + 27];
for (int i = 0; i <= n + 26; i++) {
graph.add(new ArrayList<>());
}
for (int i = 0; i < n; i++) {
char[] s = in.next().toCharArray();
for (char c : s) {
graph.get(c - 'a').add(i + 26);
graph.get(i + 26).add(c - 'a');
}
}
int cnt = 0;
for (int i = 26; i < n + 26; i++) {
if (vis[i])
continue;
cnt++;
dfs(i);
}
out.println(cnt);
}
}
}
| Java | ["4\na\nb\nab\nd", "3\nab\nbc\nabc", "1\ncodeforces"] | 1 second | ["2", "1", "1"] | NoteIn the second example hacker need to use any of the passwords to access the system. | Java 11 | standard input | [
"dsu",
"dfs and similar",
"graphs"
] | 00db0111fd80ce1820da2af07a6cb8f1 | The first line contain integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — number of passwords in the list. Next $$$n$$$ lines contains passwords from the list – non-empty strings $$$s_i$$$, with length at most $$$50$$$ letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed $$$10^6$$$ letters. All of them consist only of lowercase Latin letters. | 1,500 | In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system. | standard output | |
PASSED | 1614f999163bca8d5375ece255cf77b7 | train_003.jsonl | 1575038100 | One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of $$$n$$$ passwords — strings, consists of small Latin letters.Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords $$$a$$$ and $$$b$$$ as follows: two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a letter, that exists in both $$$a$$$ and $$$b$$$; two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a password $$$c$$$ from the list, which is equivalent to both $$$a$$$ and $$$b$$$. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class SecretPasswords {
public static class DSU{
int size = 0;
DSU par = null;
boolean counted = false;
}
public static DSU findSet(DSU dsu){
if(dsu == null)
return null;
if(dsu.par == null)
return dsu;
dsu.par = findSet(dsu.par);
return dsu.par;
}
public static void union(DSU dsu1, DSU dsu2){
DSU d1 = findSet(dsu1);
DSU d2 = findSet(dsu2);
if(d1 == d2)
return;
if(d1.size > d2.size){
d2.par = d1;
d1.size++;
}else{
d1.par = d2;
d2.size++;
}
}
static DSU[] dsuArr = new DSU[27];
static BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) throws IOException {
int n = Integer.parseInt(bf.readLine().trim());
for(int i = 0; i < n; i++){
String s = bf.readLine().trim();
for(int j = 0; j < s.length(); j++)
if(dsuArr[s.charAt(j)-'a'] == null){
dsuArr[s.charAt(j)-'a'] = new DSU();
}
for(int j = 0; j < s.length()-1; j++)
union(dsuArr[s.charAt(j)-'a'], dsuArr[s.charAt(j+1)-'a']);
}
int num = 0;
for(int j = 0; j < 27; j++){
if(dsuArr[j] == null)
continue;
DSU u = findSet(dsuArr[j]);
if(!u.counted){
num++;
u.counted = true;
}
}
bf.close();
System.out.println(num);
}
}
| Java | ["4\na\nb\nab\nd", "3\nab\nbc\nabc", "1\ncodeforces"] | 1 second | ["2", "1", "1"] | NoteIn the second example hacker need to use any of the passwords to access the system. | Java 11 | standard input | [
"dsu",
"dfs and similar",
"graphs"
] | 00db0111fd80ce1820da2af07a6cb8f1 | The first line contain integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — number of passwords in the list. Next $$$n$$$ lines contains passwords from the list – non-empty strings $$$s_i$$$, with length at most $$$50$$$ letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed $$$10^6$$$ letters. All of them consist only of lowercase Latin letters. | 1,500 | In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system. | standard output | |
PASSED | 031fd295680d00fa876e8e78d6bd9a5d | train_003.jsonl | 1575038100 | One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of $$$n$$$ passwords — strings, consists of small Latin letters.Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords $$$a$$$ and $$$b$$$ as follows: two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a letter, that exists in both $$$a$$$ and $$$b$$$; two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a password $$$c$$$ from the list, which is equivalent to both $$$a$$$ and $$$b$$$. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system. | 256 megabytes | import java.io.*;
import java.util.*;
import static java.util.Collections.*;
import static java.lang.Math.*;
@SuppressWarnings("unchecked")
public class D_Secret_Passwords {
public static PrintWriter out;
public static InputReader in;
public static int[] root, sizes;
public static void main(String[] args)throws IOException {
in = new InputReader(System.in);
out = new PrintWriter(System.out);
int n = in.nextInt();
root = new int[n];
sizes = new int[n];
initialize();
HashSet arr[] = new HashSet[n];
Arrays.setAll(arr, t->new HashSet<Integer>());
for(int t = 0; t < n; t++){
String s = in.next();
for(int i=0;i<s.length();i++){
arr[t].add(s.charAt(i)-'a');
}
}
for(int i=0;i<26;i++){
int ix = -1;
for(int j=0;j<n;j++){
HashSet<Integer> set = (HashSet<Integer>)arr[j];
if(!set.contains(i))
continue;
if(ix==-1)
ix = j;
// out.println("combining "+ix+" "+j);
union(ix,j);
}
}
HashSet<Integer> ans = new HashSet<Integer>();
for(int i=0;i<n;i++)
ans.add(find(i));
out.println(ans.size());
out.close();
}
public static void initialize()
{
int len=root.length;
for(int i=0;i<len;i++)
{
root[i]=i; sizes[i] = 1;
}
}
public static int find(int i)
{
while(i!=root[i])
{
root[i]=root[root[i]];
i=root[i];
}
return i;
}
public static void union(int a,int b)
{
int roota=find(a);
int rootb=find(b);
if(roota==rootb)
return;
else
{
if(sizes[roota]<sizes[rootb])
{
sizes[rootb]+=sizes[roota];
root[roota]=rootb;
}
else
{
sizes[roota]+=sizes[rootb];
root[rootb]=roota;
}
}
}
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());
}
}
} | Java | ["4\na\nb\nab\nd", "3\nab\nbc\nabc", "1\ncodeforces"] | 1 second | ["2", "1", "1"] | NoteIn the second example hacker need to use any of the passwords to access the system. | Java 11 | standard input | [
"dsu",
"dfs and similar",
"graphs"
] | 00db0111fd80ce1820da2af07a6cb8f1 | The first line contain integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — number of passwords in the list. Next $$$n$$$ lines contains passwords from the list – non-empty strings $$$s_i$$$, with length at most $$$50$$$ letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed $$$10^6$$$ letters. All of them consist only of lowercase Latin letters. | 1,500 | In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system. | standard output | |
PASSED | 15e8efc425082dd4a504951e49095121 | train_003.jsonl | 1575038100 | One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of $$$n$$$ passwords — strings, consists of small Latin letters.Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords $$$a$$$ and $$$b$$$ as follows: two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a letter, that exists in both $$$a$$$ and $$$b$$$; two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a password $$$c$$$ from the list, which is equivalent to both $$$a$$$ and $$$b$$$. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system. | 256 megabytes |
import java.util.*;import java.io.*;import java.math.*;
public class Main
{
static int find_par(int n){
if(par[n]==n)
return n;
return (par[n]=find_par(par[n]));
}
static void union(int a,int b){
int root1=find_par(a),root2=find_par(b);
if(root1==root2)
return;
if(sz[root1]<sz[root2]){
par[root1]=root2;
sz[root2]+=sz[root1];
}
else{
par[root2]=root1;
sz[root1]+=sz[root2];
}
}
static int par[];
static int sz[];
public static void process()throws IOException
{
int n=ni();
par=new int[30];
sz=new int[30];
for(int i=0;i<30;i++){ par[i]=i; sz[i]=1; }
HashSet<Integer> set = new HashSet<Integer>();
for(int i=1;i<=n;i++){
char arr[]=nln().toCharArray();
int fix=arr[0]-'a';set.add(fix);
for(int j=1;j<arr.length;j++){
set.add(arr[j]-'a');
union(fix,arr[j]-'a');
}
}
HashSet<Integer> res = new HashSet<Integer>();
for(Integer i : set){
int p=find_par(i);
res.add(p);
}
pn(res.size());
}
static AnotherReader sc;
static PrintWriter out;
public static void main(String[]args)throws IOException
{
out = new PrintWriter(System.out);
sc=new AnotherReader();
boolean oj = true;
oj = System.getProperty("ONLINE_JUDGE") != null;
if(!oj) sc=new AnotherReader(100);
long s = System.currentTimeMillis();
int t=1;
//t=ni();
while(t-->0)
process();
out.flush();
if(!oj)
System.out.println(System.currentTimeMillis()-s+"ms");
System.out.close();
}
static void pn(Object o){out.println(o);}
static void p(Object o){out.print(o);}
static void pni(Object o){out.println(o);System.out.flush();}
static int ni()throws IOException{return sc.nextInt();}
static long nl()throws IOException{return sc.nextLong();}
static double nd()throws IOException{return sc.nextDouble();}
static String nln()throws IOException{return sc.nextLine();}
static long gcd(long a, long b)throws IOException{return (b==0)?a:gcd(b,a%b);}
static int gcd(int a, int b)throws IOException{return (b==0)?a:gcd(b,a%b);}
static int bit(long n)throws IOException{return (n==0)?0:(1+bit(n&(n-1)));}
static boolean multipleTC=false;
static long mod=(long)1e9+7l;
static void r_sort(int arr[],int n){
Random r = new Random();
for (int i = n-1; i > 0; i--){
int j = r.nextInt(i+1);
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
Arrays.sort(arr);
}
static long mpow(long x, long n) {
if(n == 0)
return 1;
if(n % 2 == 0) {
long root = mpow(x, n / 2);
return root * root % mod;
}else {
return x * mpow(x, n - 1) % mod;
}
}
static long mcomb(long a, long b) {
if(b > a - b)
return mcomb(a, a - b);
long m = 1;
long d = 1;
long i;
for(i = 0; i < b; i++) {
m *= (a - i);
m %= mod;
d *= (i + 1);
d %= mod;
}
long ans = m * mpow(d, mod - 2) % mod;
return ans;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
static class AnotherReader{BufferedReader br; StringTokenizer st;
AnotherReader()throws FileNotFoundException{
br=new BufferedReader(new InputStreamReader(System.in));}
AnotherReader(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;}}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
} | Java | ["4\na\nb\nab\nd", "3\nab\nbc\nabc", "1\ncodeforces"] | 1 second | ["2", "1", "1"] | NoteIn the second example hacker need to use any of the passwords to access the system. | Java 11 | standard input | [
"dsu",
"dfs and similar",
"graphs"
] | 00db0111fd80ce1820da2af07a6cb8f1 | The first line contain integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — number of passwords in the list. Next $$$n$$$ lines contains passwords from the list – non-empty strings $$$s_i$$$, with length at most $$$50$$$ letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed $$$10^6$$$ letters. All of them consist only of lowercase Latin letters. | 1,500 | In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system. | standard output | |
PASSED | ddc8f541fa38fa018a2150e12e7ed1e6 | train_003.jsonl | 1575038100 | One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of $$$n$$$ passwords — strings, consists of small Latin letters.Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords $$$a$$$ and $$$b$$$ as follows: two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a letter, that exists in both $$$a$$$ and $$$b$$$; two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a password $$$c$$$ from the list, which is equivalent to both $$$a$$$ and $$$b$$$. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system. | 256 megabytes | import java.io.*;
import java.util.*;
public class CF1263D extends PrintWriter {
CF1263D() { super(System.out, true); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF1263D o = new CF1263D(); o.main(); o.flush();
}
static final int A = 26;
int[] dsu;
int find(int i) {
return dsu[i] < 0 ? i : (dsu[i] = find(dsu[i]));
}
void join(int i, int j) {
i = find(i);
j = find(j);
if (i == j)
return;
if (dsu[i] > dsu[j])
dsu[i] = j;
else {
if (dsu[i] == dsu[j])
dsu[i]--;
dsu[j] = i;
}
}
void main() {
dsu = new int[A]; Arrays.fill(dsu, -1);
boolean[] used = new boolean[A];
int n = sc.nextInt();
while (n-- > 0) {
byte[] cc = sc.next().getBytes();
int l = cc.length;
for (int i = 0; i < cc.length; i++) {
int a = cc[i] - 'a';
used[a] = true;
if (i > 0) {
int b = cc[i - 1] - 'a';
join(a, b);
}
}
}
int ans = 0;
for (int a = 0; a < A; a++)
if (used[a] && dsu[a] < 0)
ans++;
println(ans);
}
}
| Java | ["4\na\nb\nab\nd", "3\nab\nbc\nabc", "1\ncodeforces"] | 1 second | ["2", "1", "1"] | NoteIn the second example hacker need to use any of the passwords to access the system. | Java 11 | standard input | [
"dsu",
"dfs and similar",
"graphs"
] | 00db0111fd80ce1820da2af07a6cb8f1 | The first line contain integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — number of passwords in the list. Next $$$n$$$ lines contains passwords from the list – non-empty strings $$$s_i$$$, with length at most $$$50$$$ letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed $$$10^6$$$ letters. All of them consist only of lowercase Latin letters. | 1,500 | In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system. | standard output | |
PASSED | bebe7924b1f82f5fe2a36c1d2461dada | train_003.jsonl | 1575038100 | One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of $$$n$$$ passwords — strings, consists of small Latin letters.Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords $$$a$$$ and $$$b$$$ as follows: two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a letter, that exists in both $$$a$$$ and $$$b$$$; two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a password $$$c$$$ from the list, which is equivalent to both $$$a$$$ and $$$b$$$. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.*;
public class D{
static ArrayList<ArrayList<Integer>> g;
static ArrayList<Boolean> vis;
static void dfs(int i){
if (vis.get(i)) return;
vis.set(i, true);
for (int j : g.get(i))
dfs(j);
}
public static void main (String[] args){
IO io = new IO();
int n = io.nextInt();
g = new ArrayList<>(n + 30);
vis = new ArrayList<>(n + 30);
for (int i = 0; i < n+30; i++){
g.add(new ArrayList<>());
vis.add(false);
}
for (int i = 0; i < n; i++){
String s = io.next();
for (char c : s.toCharArray()){
int j = n + (c - 'a');
g.get(i).add(j);
g.get(j).add(i);
}
}
int ans = 0;
for (int i = 0; i < n; i++){
if (vis.get(i)) continue;
ans++;
dfs(i);
}
io.write(ans + "\n");
io.flush();
}
public static class IO {
String [] line;
int i;
InputStreamReader ir;
BufferedReader in;
OutputStreamWriter or;
BufferedWriter out;
IO(){
ir = new InputStreamReader(System.in);
in = new BufferedReader(ir);
or = new OutputStreamWriter(System.out);
out = new BufferedWriter(or);
}
String next(){
try{
if (line == null || i == line.length){
line = in.readLine().split(" ");
i = 0;
}
return line[i++];
}catch (Exception e){ return null; }
}
Integer nextInt(){
return Integer.valueOf(next());
}
Long nextLong(){
return Long.valueOf(next());
}
<T> void write(T t) {
try{
out.append(String.valueOf(t));
}catch (Exception e){}
}
public void flush(){
try{
out.flush();
}catch(IOException e){}
}
}
}
| Java | ["4\na\nb\nab\nd", "3\nab\nbc\nabc", "1\ncodeforces"] | 1 second | ["2", "1", "1"] | NoteIn the second example hacker need to use any of the passwords to access the system. | Java 11 | standard input | [
"dsu",
"dfs and similar",
"graphs"
] | 00db0111fd80ce1820da2af07a6cb8f1 | The first line contain integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — number of passwords in the list. Next $$$n$$$ lines contains passwords from the list – non-empty strings $$$s_i$$$, with length at most $$$50$$$ letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed $$$10^6$$$ letters. All of them consist only of lowercase Latin letters. | 1,500 | In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system. | standard output | |
PASSED | 8e251321b24fb1e77f1ec17eb7ac3630 | train_003.jsonl | 1575038100 | One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of $$$n$$$ passwords — strings, consists of small Latin letters.Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords $$$a$$$ and $$$b$$$ as follows: two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a letter, that exists in both $$$a$$$ and $$$b$$$; two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a password $$$c$$$ from the list, which is equivalent to both $$$a$$$ and $$$b$$$. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
MScanner sc = new MScanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n=sc.nextInt();
N=n+26;
p = new int[numSets = N];
rank = new int[N];
setSize = new int[N];
for (int i = 0; i < N; i++) { p[i] = i; setSize[i] = 1; }
for(int i=0;i<n;i++) {
//System.out.println(Arrays.toString(p));
boolean[]chars=new boolean[26];
char[]x=sc.nextLine().toCharArray();
for(int j=0;j<x.length;j++) {
int l=((int)x[j]-'a');
unionSet(i, n+l);
chars[l]=true;
}
for(int j=0;j<26;j++) {
if(chars[j]) {
for(int o=j+1;o<26;o++) {
if(chars[o])
unionSet(n+o, n+j);
}
}
}
}
HashSet<Integer>hs=new HashSet<Integer>();
for(int i=0;i<n;i++) {
hs.add(findSet(i));
}
pw.println(hs.size());
pw.flush();
}
static int[] p, rank, setSize;
static int numSets,N;
public static int findSet(int i) { return p[i] == i ? i : (p[i] = findSet(p[i])); }
public static boolean isSameSet(int i, int j) { return findSet(i) == findSet(j); }
public static void unionSet(int i, int j)
{
if (isSameSet(i, j))
return;
numSets--;
int x = findSet(i), y = findSet(j);
if(rank[x] > rank[y]) { p[y] = x; setSize[x] += setSize[y]; }
else
{ p[x] = y; setSize[y] += setSize[x];
if(rank[x] == rank[y]) rank[y]++;
}
}
static class MScanner {
StringTokenizer st;
BufferedReader br;
public MScanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public MScanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int[] takearr(int n) throws IOException {
int[] in = new int[n];
for (int i = 0; i < n; i++)
in[i] = nextInt();
return in;
}
public long[] takearrl(int n) throws IOException {
long[] in = new long[n];
for (int i = 0; i < n; i++)
in[i] = nextLong();
return in;
}
public Integer[] takearrobj(int n) throws IOException {
Integer[] in = new Integer[n];
for (int i = 0; i < n; i++)
in[i] = nextInt();
return in;
}
public Long[] takearrlobj(int n) throws IOException {
Long[] in = new Long[n];
for (int i = 0; i < n; i++)
in[i] = nextLong();
return in;
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public Long nextLong() throws IOException {
return Long.parseLong(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
} | Java | ["4\na\nb\nab\nd", "3\nab\nbc\nabc", "1\ncodeforces"] | 1 second | ["2", "1", "1"] | NoteIn the second example hacker need to use any of the passwords to access the system. | Java 11 | standard input | [
"dsu",
"dfs and similar",
"graphs"
] | 00db0111fd80ce1820da2af07a6cb8f1 | The first line contain integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — number of passwords in the list. Next $$$n$$$ lines contains passwords from the list – non-empty strings $$$s_i$$$, with length at most $$$50$$$ letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed $$$10^6$$$ letters. All of them consist only of lowercase Latin letters. | 1,500 | In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system. | standard output | |
PASSED | 6ca089d199e79280313d5db165cad72c | train_003.jsonl | 1575038100 | One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of $$$n$$$ passwords — strings, consists of small Latin letters.Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords $$$a$$$ and $$$b$$$ as follows: two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a letter, that exists in both $$$a$$$ and $$$b$$$; two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a password $$$c$$$ from the list, which is equivalent to both $$$a$$$ and $$$b$$$. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main{
public static void DFS(boolean vis[],int src,HashMap<Integer,HashSet<Integer>> link){
if(vis[src]==true){
return ;
}
vis[src]=true;
for(int i:link.get(src)){
DFS(vis,i,link);
}
}
public static void main(String []args)throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(System.out));
int t=Integer.parseInt(br.readLine());
boolean vis[]=new boolean[26];
HashMap<Integer,HashSet<Integer>> link=new HashMap();
for(int i=0;i<26;i++){
link.put(i,new HashSet<Integer>());
}
while(t>0){
String str=br.readLine();
vis[str.charAt(0)-'a']=true;
for(int i=1;i<str.length();i++){
int u=str.charAt(i-1)-'a';
int v=str.charAt(i)-'a';
link.get(u).add(v);
link.get(v).add(u);
vis[u]=true;
vis[v]=true;
}
t--;
}
int ans=0;
boolean arr[]=new boolean[26];
for(int i=0;i<26;i++){
if(vis[i] && !arr[i]){
DFS(arr,i,link);
ans++;
}
}
bw.write(ans+"\n");
bw.flush();
}
} | Java | ["4\na\nb\nab\nd", "3\nab\nbc\nabc", "1\ncodeforces"] | 1 second | ["2", "1", "1"] | NoteIn the second example hacker need to use any of the passwords to access the system. | Java 11 | standard input | [
"dsu",
"dfs and similar",
"graphs"
] | 00db0111fd80ce1820da2af07a6cb8f1 | The first line contain integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — number of passwords in the list. Next $$$n$$$ lines contains passwords from the list – non-empty strings $$$s_i$$$, with length at most $$$50$$$ letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed $$$10^6$$$ letters. All of them consist only of lowercase Latin letters. | 1,500 | In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system. | standard output | |
PASSED | aec87b7b6a7c4c344fc30b955ac9143e | train_003.jsonl | 1575038100 | One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of $$$n$$$ passwords — strings, consists of small Latin letters.Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords $$$a$$$ and $$$b$$$ as follows: two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a letter, that exists in both $$$a$$$ and $$$b$$$; two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a password $$$c$$$ from the list, which is equivalent to both $$$a$$$ and $$$b$$$. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system. | 256 megabytes | import java.util.*;
public class Main {
Scanner sc = new Scanner(System.in);
public Main() {
int n = sc.nextInt();
sc.nextLine();
UnionFind uf = new UnionFind(26);
boolean[] vis = new boolean[26];
for (int i = 0; i < n; i++) {
String s = sc.nextLine();
int len = s.length();
if (s.length() == 1) vis[s.charAt(0) - 'a'] = true;
else {
for (int j = 1; j < len; j++) {
int a = s.charAt(j - 1) - 'a';
int b = s.charAt(j) - 'a';
uf.union(a, b);
vis[a] = vis[b] = true;
}
}
}
HashSet<Integer> root = new HashSet<>();
for (int i = 0; i < 26; i++) {
if (vis[i]) root.add(uf.findRoot(i));
}
System.out.println(root.size());
}
public static void main(String[] args) {
Main uva = new Main();
}
class UnionFind {
int[] par;
public UnionFind(int n) {
par = new int[n + 1];
for (int i = 1; i <= n; i++) {
par[i] = i;
}
}
public int findRoot(int x) {
if (x == par[x]) return x;
return par[x] = findRoot(par[x]);
}
public boolean union(int x, int y) {
int rx = findRoot(x);
int ry = findRoot(y);
if (rx == ry) return false;
par[rx] = ry;
return true;
}
public boolean isSameSet(int x, int y) {
return findRoot(x) == findRoot(y);
}
}
} | Java | ["4\na\nb\nab\nd", "3\nab\nbc\nabc", "1\ncodeforces"] | 1 second | ["2", "1", "1"] | NoteIn the second example hacker need to use any of the passwords to access the system. | Java 11 | standard input | [
"dsu",
"dfs and similar",
"graphs"
] | 00db0111fd80ce1820da2af07a6cb8f1 | The first line contain integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — number of passwords in the list. Next $$$n$$$ lines contains passwords from the list – non-empty strings $$$s_i$$$, with length at most $$$50$$$ letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed $$$10^6$$$ letters. All of them consist only of lowercase Latin letters. | 1,500 | In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system. | standard output | |
PASSED | 0d07660eaf29f0b06d3d9240a71d2ee7 | train_003.jsonl | 1575038100 | One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of $$$n$$$ passwords — strings, consists of small Latin letters.Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords $$$a$$$ and $$$b$$$ as follows: two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a letter, that exists in both $$$a$$$ and $$$b$$$; two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a password $$$c$$$ from the list, which is equivalent to both $$$a$$$ and $$$b$$$. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class Hello {
static int []fa = new int[200100];
static int gf(int x) {
//return (x==fa[x])?x:fa[x] = gf(fa[x]);
if (x == fa[x]) {
return x;
}
fa[x] = gf(fa[x]);
return fa[x];
}
static ArrayList<Integer> adj[] = new ArrayList[26];
public static void main(String[] args) {
//try {
// FileInputStream fis = new FileInputStream("data.txt");
// System.setIn(fis);
//Scanner in = new Scanner(System.in);
FastReader in = new FastReader(System.in);
for (int i = 0; i < 26; i++) {
adj[i] = new ArrayList<Integer>();
}
int n = in.nextInt();
//System.out.print("n:"+n);
//System.out.print("m:"+m);
for (int i = 0;i < n;++i) {
String s = in.nextLine();
for (int j = 0;j < s.length();++j) {
char x = s.charAt(j);
int o = x - 'a';
adj[x - 'a'].add(i);
}
}
for (int z = 0;z < n;++z) fa[z] = z;
for (int i = 0;i < 26;++i) {
for (int z = 0;z < adj[i].size() - 1;++z) {
int i1 = adj[i].get(z);
int i2 = adj[i].get(z + 1);
fa[gf(i1)] = gf(i2);
}
}
int []sz = new int[n];
for (int z = 0;z < n;++z) sz[z] = 0;
for (int z = 0;z < n;++z) sz[gf(z)] += 1;
int cnt = 0;
for (int z = 0;z < n;++z) if (sz[z] != 0) cnt += 1;
System.out.println(cnt);
//} catch (FileNotFoundException e){
// System.out.println("error");
//}
}
}
class FastReader {
private boolean finished = false;
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private 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 peek() {
if (numChars == -1) {
return -1;
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c == ',') {
c = read();
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuilder buf = new StringBuilder();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r') {
buf.appendCodePoint(c);
}
c = read();
}
return buf.toString();
}
public String nextLine() {
String s = readLine0();
while (s.trim().length() == 0)
s = readLine0();
return s;
}
public String nextLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines) {
return nextLine();
} else {
return readLine0();
}
}
public BigInteger nextBigInteger() {
try {
return new BigInteger(nextString());
} catch (NumberFormatException e) {
throw new InputMismatchException();
}
}
public char nextCharacter() {
int c = read();
while (isSpaceChar(c))
c = read();
return (char) c;
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, nextInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, nextInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public boolean isExhausted() {
int value;
while (isSpaceChar(value = peek()) && value != -1)
read();
return value == -1;
}
public String next() {
return nextString();
}
public SpaceCharFilter getFilter() {
return filter;
}
public void setFilter(SpaceCharFilter filter) {
this.filter = filter;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
| Java | ["4\na\nb\nab\nd", "3\nab\nbc\nabc", "1\ncodeforces"] | 1 second | ["2", "1", "1"] | NoteIn the second example hacker need to use any of the passwords to access the system. | Java 11 | standard input | [
"dsu",
"dfs and similar",
"graphs"
] | 00db0111fd80ce1820da2af07a6cb8f1 | The first line contain integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — number of passwords in the list. Next $$$n$$$ lines contains passwords from the list – non-empty strings $$$s_i$$$, with length at most $$$50$$$ letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed $$$10^6$$$ letters. All of them consist only of lowercase Latin letters. | 1,500 | In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system. | standard output | |
PASSED | 246b1bfcd6fadd2468d49f6fbae187e6 | train_003.jsonl | 1575038100 | One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of $$$n$$$ passwords — strings, consists of small Latin letters.Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords $$$a$$$ and $$$b$$$ as follows: two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a letter, that exists in both $$$a$$$ and $$$b$$$; two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a password $$$c$$$ from the list, which is equivalent to both $$$a$$$ and $$$b$$$. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class CP{
public static OutputStream out=new BufferedOutputStream(System.out);
static Scanner sc=new Scanner(System.in);
static long mod=1000000007l;
static int INF=1000000;
//nl-->neew line; //l-->line; //arp-->array print; //arpnl-->array print new line
public static void nl(Object o) throws IOException{out.write((o+"\n").getBytes()); }
public static void l(Object o) throws IOException{out.write((o+"").getBytes());}
public static void arp(int[] o) throws IOException{for(int i=0;i<o.length;i++) out.write((o[i]+" ").getBytes()); out.write(("\n").getBytes());}
public static void arpnl(int[] o) throws IOException{for(int i=0;i<o.length;i++) out.write((o[i]+"\n").getBytes());}
public static void scanl(long[] a,int n) {for(int i=0;i<n;i++) a[i]=sc.nextLong();}
public static void scani(int[] a,int n) {for(int i=0;i<n;i++) a[i]=sc.nextInt();}
public static void scan2D(int[][] a,int n,int m) {for(int i=0;i<n;i++) for(int j=0;j<m;j++) a[i][j]=sc.nextInt();}
//
static long cnt;
static TreeSet<Integer> ans;
static int n,m;
static boolean[][] dp,vis;
static HashMap<Pair,Boolean> arrl;
static Stack<Integer> stk;
static Queue<Integer> queue;
public static void main(String[] args) throws IOException{
long sttm=System.currentTimeMillis();
long mod=1000000007l;
// int t=sc.nextInt();
int t=1;
while(t-->0){
int n=sc.nextInt();
int[][] g=new int[26][26];
boolean[] vis=new boolean[26];
Arrays.fill(vis,true);
for(int i=0;i<n;i++){
String s=sc.next();
vis[s.charAt(0)-'a']=false;
for(int j=1;j<s.length();j++){
if(s.charAt(j)!=s.charAt(0)){
g[s.charAt(0)-'a'][s.charAt(j)-'a']=1;
g[s.charAt(j)-'a'][s.charAt(0)-'a']=1;
}
vis[s.charAt(j)-'a']=false;
}
}
int cnt=0;
for(int i=0;i<26;i++){
if(vis[i]==false){
dfs(g,vis,i);
cnt++;
}
}
nl(cnt);
}
out.flush();
}
public static void dfs(int[][] g, boolean[] vis,int u){
vis[u]=true;
for(int i=0;i<26;i++){
if(g[i][u]==1 && vis[i]==false){
dfs(g,vis,i);
}
}
}
public static int binSearch(long sum, long[] a,int st,int nd){
if(st==nd) return st;
int mid=(st+nd+1)/2;
if(a[mid]<sum){
return binSearch(sum,a,mid,nd);
}
if(a[mid]==sum){
return -1;
}
else{
return binSearch(sum,a,st,mid-1);
}
}
}
class Pair{
int x,y;
Pair(int x,int y){
this.x=x;
this.y=y;
}
}
| Java | ["4\na\nb\nab\nd", "3\nab\nbc\nabc", "1\ncodeforces"] | 1 second | ["2", "1", "1"] | NoteIn the second example hacker need to use any of the passwords to access the system. | Java 11 | standard input | [
"dsu",
"dfs and similar",
"graphs"
] | 00db0111fd80ce1820da2af07a6cb8f1 | The first line contain integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — number of passwords in the list. Next $$$n$$$ lines contains passwords from the list – non-empty strings $$$s_i$$$, with length at most $$$50$$$ letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed $$$10^6$$$ letters. All of them consist only of lowercase Latin letters. | 1,500 | In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system. | standard output | |
PASSED | 2455ce3bbccca019fd12387fa30c2f5e | train_003.jsonl | 1575038100 | One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of $$$n$$$ passwords — strings, consists of small Latin letters.Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords $$$a$$$ and $$$b$$$ as follows: two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a letter, that exists in both $$$a$$$ and $$$b$$$; two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a password $$$c$$$ from the list, which is equivalent to both $$$a$$$ and $$$b$$$. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.TreeSet;
public class c {
static int[] tree;
static int[] size;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
size = new int[26];
tree = new int[26];
String[] strings = new String[n];
for (int a = 0; a < tree.length; a++) {
size[a] = 1;
tree[a] = a;
}
for (int a = 0; a < n; a++) {
String str = br.readLine();
char ch = str.charAt(0);
strings[a] = str;
for(int b = 1; b < str.length(); b ++)
join(ch - 'a', str.charAt(b) - 'a');
}
TreeSet<Integer> set = new TreeSet<>();
for(int a = 0; a < n; a ++){
set.add(getRoot(strings[a].charAt(0) - 'a'));
}
System.out.println(set.size());
}
public static void join(int v, int u) {
v = getRoot(v);
u = getRoot(u);
if(v == u)
return;
if (size[u] > size[v]) {
int t = v;
v = u;
u = t;
}
tree[u] = v;
size[v] += size[u];
}
public static int getRoot(int v) {
if (tree[v] == v)
return v;
return tree[v] = getRoot(tree[v]);
}
}
| Java | ["4\na\nb\nab\nd", "3\nab\nbc\nabc", "1\ncodeforces"] | 1 second | ["2", "1", "1"] | NoteIn the second example hacker need to use any of the passwords to access the system. | Java 11 | standard input | [
"dsu",
"dfs and similar",
"graphs"
] | 00db0111fd80ce1820da2af07a6cb8f1 | The first line contain integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — number of passwords in the list. Next $$$n$$$ lines contains passwords from the list – non-empty strings $$$s_i$$$, with length at most $$$50$$$ letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed $$$10^6$$$ letters. All of them consist only of lowercase Latin letters. | 1,500 | In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system. | standard output | |
PASSED | 6854de02e8af613c745de5e9bc2a3032 | train_003.jsonl | 1575038100 | One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of $$$n$$$ passwords — strings, consists of small Latin letters.Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords $$$a$$$ and $$$b$$$ as follows: two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a letter, that exists in both $$$a$$$ and $$$b$$$; two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a password $$$c$$$ from the list, which is equivalent to both $$$a$$$ and $$$b$$$. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system. | 256 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class cf1263d {
static BufferedReader __in;
static PrintWriter __out;
static StringTokenizer input;
public static void main(String[] args) throws IOException {
__in = new BufferedReader(new InputStreamReader(System.in));
__out = new PrintWriter(new OutputStreamWriter(System.out));
int n = ri();
DSU dsu = new DSU(n + 26);
for(int i = 0; i < n; ++i) {
char[] s = rcha();
for(char c : s) {
dsu.union(i + 26, c - 'a');
}
}
Set<Integer> ansS = new HashSet<>();
for(int i = 0; i < n; ++i) {
ansS.add(dsu.find(i + 26));
}
prln(ansS.size());
close();
}
static class DSU {
boolean init = true;
int n, par[], sz[];
DSU(int n_) {
n = n_;
par = new int[n];
sz = new int[n];
if(init) {
init();
} else {
fill(par, -1);
}
}
void make(int v) {
par[v] = v;
sz[v] = 1;
}
void init() {
for(int i = 0; i < n; ++i) {
make(i);
}
}
int find(int v) {
if(par[v] == -1) {
return -1;
} else if(v == par[v]) {
return v;
} else {
par[v] = find(par[v]);
return par[v];
}
}
void union(int u, int v) {
int a = find(u), b = find(v);
if(a != b) {
if(sz[a] < sz[b]) {
int swap = a;
a = b;
b = swap;
}
par[b] = a;
sz[a] += sz[b];
}
}
}
// references
// IBIG = 1e9 + 7
// IRAND ~= 3e8
// IMAX ~= 2e10
// LMAX ~= 9e18
// constants
static final int IBIG = 1000000007;
static final int IRAND = 327859546;
static final int IMAX = 2147483647;
static final int IMIN = -2147483648;
static final long LMAX = 9223372036854775807L;
static final long LMIN = -9223372036854775808L;
// util
static int minof(int a, int b, int c) {return min(a, min(b, c));}
static int minof(int... x) {return x.length == 1 ? x[0] : x.length == 2 ? min(x[0], x[1]) : min(x[0], minstarting(1, x));}
static int minstarting(int offset, int... x) {assert x.length > 2; return offset == x.length - 2 ? min(x[offset], x[offset + 1]) : min(x[offset], minstarting(offset + 1, x));}
static long minof(long a, long b, long c) {return min(a, min(b, c));}
static long minof(long... x) {return x.length == 1 ? x[0] : x.length == 2 ? min(x[0], x[1]) : min(x[0], minstarting(1, x));}
static long minstarting(int offset, long... x) {assert x.length > 2; return offset == x.length - 2 ? min(x[offset], x[offset + 1]) : min(x[offset], minstarting(offset + 1, x));}
static int maxof(int a, int b, int c) {return max(a, max(b, c));}
static int maxof(int... x) {return x.length == 1 ? x[0] : x.length == 2 ? max(x[0], x[1]) : max(x[0], maxstarting(1, x));}
static int maxstarting(int offset, int... x) {assert x.length > 2; return offset == x.length - 2 ? max(x[offset], x[offset + 1]) : max(x[offset], maxstarting(offset + 1, x));}
static long maxof(long a, long b, long c) {return max(a, max(b, c));}
static long maxof(long... x) {return x.length == 1 ? x[0] : x.length == 2 ? max(x[0], x[1]) : max(x[0], maxstarting(1, x));}
static long maxstarting(int offset, long... x) {assert x.length > 2; return offset == x.length - 2 ? max(x[offset], x[offset + 1]) : max(x[offset], maxstarting(offset + 1, x));}
static int powi(int a, int b) {if(a == 0) return 0; int ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static long powl(long a, int b) {if(a == 0) return 0; long ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static int floori(double d) {return (int)d;}
static int ceili(double d) {return (int)ceil(d);}
static long floorl(double d) {return (long)d;}
static long ceill(double d) {return (long)ceil(d);}
// input
static void r() throws IOException {input = new StringTokenizer(__in.readLine());}
static int ri() throws IOException {return Integer.parseInt(__in.readLine());}
static long rl() throws IOException {return Long.parseLong(__in.readLine());}
static int[] ria(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()); return a;}
static long[] rla(int n) throws IOException {long[] a = new long[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Long.parseLong(input.nextToken()); return a;}
static char[] rcha() throws IOException {return __in.readLine().toCharArray();}
static String rline() throws IOException {return __in.readLine();}
static int rni() throws IOException {input = new StringTokenizer(__in.readLine()); return Integer.parseInt(input.nextToken());}
static int ni() {return Integer.parseInt(input.nextToken());}
static long rnl() throws IOException {input = new StringTokenizer(__in.readLine()); return Long.parseLong(input.nextToken());}
static long nl() {return Long.parseLong(input.nextToken());}
// output
static void pr(int i) {__out.print(i);}
static void prln(int i) {__out.println(i);}
static void pr(long l) {__out.print(l);}
static void prln(long l) {__out.println(l);}
static void pr(double d) {__out.print(d);}
static void prln(double d) {__out.println(d);}
static void pr(char c) {__out.print(c);}
static void prln(char c) {__out.println(c);}
static void pr(char[] s) {__out.print(new String(s));}
static void prln(char[] s) {__out.println(new String(s));}
static void pr(String s) {__out.print(s);}
static void prln(String s) {__out.println(s);}
static void pr(Object o) {__out.print(o);}
static void prln(Object o) {__out.println(o);}
static void prln() {__out.println();}
static void pryes() {__out.println("yes");}
static void pry() {__out.println("Yes");}
static void prY() {__out.println("YES");}
static void prno() {__out.println("no");}
static void prn() {__out.println("No");}
static void prN() {__out.println("NO");}
static void pryesno(boolean b) {__out.println(b ? "yes" : "no");};
static void pryn(boolean b) {__out.println(b ? "Yes" : "No");}
static void prYN(boolean b) {__out.println(b ? "YES" : "NO");}
static void prln(int... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);}
static void prln(long... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);}
static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for(int i = 0; i < n; __out.print(iter.next()), __out.print(' '), ++i); __out.println(iter.next());}
static void flush() {__out.flush();}
static void close() {__out.close();}
} | Java | ["4\na\nb\nab\nd", "3\nab\nbc\nabc", "1\ncodeforces"] | 1 second | ["2", "1", "1"] | NoteIn the second example hacker need to use any of the passwords to access the system. | Java 11 | standard input | [
"dsu",
"dfs and similar",
"graphs"
] | 00db0111fd80ce1820da2af07a6cb8f1 | The first line contain integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — number of passwords in the list. Next $$$n$$$ lines contains passwords from the list – non-empty strings $$$s_i$$$, with length at most $$$50$$$ letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed $$$10^6$$$ letters. All of them consist only of lowercase Latin letters. | 1,500 | In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system. | standard output | |
PASSED | 84f8e440cf759e4565a29c6110c87dcd | train_003.jsonl | 1575038100 | One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of $$$n$$$ passwords — strings, consists of small Latin letters.Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords $$$a$$$ and $$$b$$$ as follows: two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a letter, that exists in both $$$a$$$ and $$$b$$$; two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a password $$$c$$$ from the list, which is equivalent to both $$$a$$$ and $$$b$$$. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system. | 256 megabytes | import java.util.*;
import java.io.*;
public class d {
public static PrintWriter out;
public static void main(String[] args) throws IOException {
FS sc = new FS(System.in);
out = new PrintWriter(new BufferedOutputStream(System.out));
int n = sc.nextInt();
DSU d = new DSU(26);
int[] found = new int[26];
for (int i=0;i<n;i++) {
char[] next = sc.next().toCharArray();
found[(int)(next[0] - 'a')] = 1;
for (int j=1;j<next.length;j++) {
found[(int)(next[j] - 'a')] = 1;
d.union((int)(next[j]-'a'), (int)(next[j-1]-'a'));
}
}
//d.print();
HashSet<Integer> sets = new HashSet<Integer>();
for (int i=0;i<26;i++) {
if (found[i] == 1)
sets.add(d.find(i));
}
out.println(sets.size());
out.close();
}
static class DSU {
int[] link;
int[] size;
public DSU(int n) {
size = new int[n];
link = new int[n];
Arrays.fill(size, 1);
for (int i=0;i<n;i++)
link[i] = i;
}
int find(int x) {
while (x != link[x]) x = link[x];
return x;
}
boolean same(int a, int b) {
return find(a) == find(b);
}
void print() {
for (int i=0;i<link.length;i++)
System.out.print(link[i] + " ");
System.out.println();
}
void union(int a, int b) {
a = find(a);
b = find(b);
if (size[a] < size[b]) {
int tmp = a;
a = b;
b = tmp;
}
size[a] += size[b];
link[b] = a;
}
}
static class FS {
BufferedReader br;
StringTokenizer st;
public FS(InputStream i) {
br = new BufferedReader(new InputStreamReader(i));
st = new StringTokenizer("");
}
public String next() throws IOException {
if(st.hasMoreTokens())
return st.nextToken();
else
st = new StringTokenizer(br.readLine());
return next();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
}
| Java | ["4\na\nb\nab\nd", "3\nab\nbc\nabc", "1\ncodeforces"] | 1 second | ["2", "1", "1"] | NoteIn the second example hacker need to use any of the passwords to access the system. | Java 11 | standard input | [
"dsu",
"dfs and similar",
"graphs"
] | 00db0111fd80ce1820da2af07a6cb8f1 | The first line contain integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — number of passwords in the list. Next $$$n$$$ lines contains passwords from the list – non-empty strings $$$s_i$$$, with length at most $$$50$$$ letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed $$$10^6$$$ letters. All of them consist only of lowercase Latin letters. | 1,500 | In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system. | standard output | |
PASSED | 8df13094f7d43bc9537ea859802dbc19 | train_003.jsonl | 1575038100 | One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of $$$n$$$ passwords — strings, consists of small Latin letters.Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords $$$a$$$ and $$$b$$$ as follows: two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a letter, that exists in both $$$a$$$ and $$$b$$$; two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a password $$$c$$$ from the list, which is equivalent to both $$$a$$$ and $$$b$$$. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
static final int MOD_PRIME = 1000000007;
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();
int i = 0;
int t = 1;
//t = in.nextInt();
for (; i < t; i++)
solver.solve(i, in, out);
out.close();
}
static class Task {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
String[] ar = new String[n];
for(int i = 0; i < n; i++) ar[i] = in.next();
HashSet<Integer> present = new HashSet<Integer>();
UnionSet set = new UnionSet(26);
for(int i = 0; i < n; i++) {
present.add(ar[i].charAt(0) - 'a');
for(int j = 0; j < ar[i].length() - 1; j++) {
present.add(ar[i].charAt(j+1) - 'a');
set.union(ar[i].charAt(j) - 'a', ar[i].charAt(j + 1) - 'a');
}
}
int ctr = 0;
for(int i = 0; i < 26; i++) {
if(present.contains(set.findParent(i))){
ctr++;
present.remove(set.findParent(i));
}
}
out.println(ctr);
}
}
// template code
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());
}
}
static long modexp(long a, long b, long p) {
// returns a to the power b mod p by modular exponentiation
long res = 1;
long mult = a % p;
while (b > 0) {
if (b % 2 == 1) {
res = (res * mult) % p;
}
b /= 2;
mult = (mult * mult) % p;
}
return res;
}
static double log(double arg, double base) {
// returns log of a base b, contains floating point errors, dont use for exact
// calculations.
if (base < 0 || base == 1) {
throw new ArithmeticException("base cant be 1 or negative");
}
if (arg < 0) {
throw new ArithmeticException("log of negative number undefined");
}
return Math.log10(arg) / Math.log10(base);
}
static int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
// scope for improvement
static ArrayList<Integer> sieveOfEratosthenes(int n) {
boolean[] check = new boolean[n + 1];
ArrayList<Integer> prime = new ArrayList<Integer>();
for (long i = 2; i <= n; i++) {
if (!check[(int) i]) {
prime.add((int) i);
for (long j = i * i; j <= n; j += i) {
check[(int) j] = true;
}
}
}
return prime;
}
static int modInverse(int a, int n) {
// returns inverse of a mod n by extended euclidean algorithm
int t = 0;
int newt = 1;
int r = n;
int newr = a;
int quotient;
int tempr, tempt;
while (newr != 0) {
quotient = r / newr;
tempt = newt;
tempr = newr;
newr = r - quotient * tempr;
newt = t - quotient * tempt;
t = tempt;
r = tempr;
}
if (r > 1) {
throw new ArithmeticException("inverse of " + a + " mod " + n + " does not exist");
} else {
if (t < 0) {
t += n;
}
return t;
}
}
static int primeModInverse(int a, int n) {
// returns inverse of a mod n by mod exponentiation, use only if n is prime
return (int) modexp(a, n - 2, n);
}
static void dfs(HashMap<Integer, ArrayList<Integer>> adj, Set<Integer> ans, Set<Integer> open,
HashMap<String, Integer> edge, boolean[] vis, int i) {
vis[i] = true;
open.add(i);
if (adj.get(i) != null) {
for (int k : adj.get(i)) {
if (!vis[k]) {
dfs(adj, ans, open, edge, vis, k);
} else if (open.contains(k)) {
ans.add(edge.get(String.valueOf(i) + " " + String.valueOf(k)));
}
}
}
open.remove(i);
}
}
class UnionSet {
int[] rank , parent;
int n;
UnionSet(int n){
//here n is the total number of elements , that is for 0 to n-1.
rank = new int[n];
parent = new int[n];
this.n = n;
makeSet();
}
void makeSet() {
for(int i = 0; i < n; i++) {
parent[i] = i;
rank[i] = 1;
}
}
int findParent(int x) {
if(parent[x] == x) {
return x;
}
int temp = findParent(parent[x]);
parent[x] = temp;
return temp;
}
void union(int x , int y) {
int xRoot = findParent(x);
int yRoot = findParent(y);
if(xRoot == yRoot) {
return;
}
if(rank[xRoot] == rank[yRoot]) {
parent[yRoot] = xRoot;
rank[xRoot]++;
return;
}
if(rank[xRoot] < rank[yRoot]) {
int temp = xRoot;
xRoot = yRoot;
yRoot = temp;
}
parent[yRoot] = xRoot;
}
}
| Java | ["4\na\nb\nab\nd", "3\nab\nbc\nabc", "1\ncodeforces"] | 1 second | ["2", "1", "1"] | NoteIn the second example hacker need to use any of the passwords to access the system. | Java 11 | standard input | [
"dsu",
"dfs and similar",
"graphs"
] | 00db0111fd80ce1820da2af07a6cb8f1 | The first line contain integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — number of passwords in the list. Next $$$n$$$ lines contains passwords from the list – non-empty strings $$$s_i$$$, with length at most $$$50$$$ letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed $$$10^6$$$ letters. All of them consist only of lowercase Latin letters. | 1,500 | In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system. | standard output | |
PASSED | b2f5faa0c206492274e6567b2903fc97 | train_003.jsonl | 1575038100 | One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of $$$n$$$ passwords — strings, consists of small Latin letters.Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords $$$a$$$ and $$$b$$$ as follows: two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a letter, that exists in both $$$a$$$ and $$$b$$$; two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a password $$$c$$$ from the list, which is equivalent to both $$$a$$$ and $$$b$$$. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system. | 256 megabytes | import java.util.* ;
public class firstjava
{
static ArrayList< ArrayList<Integer> > v = new ArrayList< ArrayList<Integer> > ( ) ;
static int[ ] visited = new int[ 26 ] ;
public static void main ( String[ ] args )
{
Scanner sc = new Scanner( System.in ) ;
int T = 1 ;
while( T -- != 0 )
{
int n = sc.nextInt( ) ;
sc.nextLine( ) ;
String[ ] s = new String[ n ] ;
Set < Integer > sett = new HashSet< Integer >( ) ;
for( int i = 0 ; i < 26 ; i ++ )
{
v.add( new ArrayList< Integer > ( ) ) ;
}
for( int i = 0 ; i < n ; i ++ )
{
s[ i ] = sc.nextLine( ) ;
int m = s[ i ].length( ) ;
for( int j = 0 ; j < m - 1 ; j ++ )
{
sett.add( s[ i ].charAt( j ) - 97 ) ;
v.get( s[ i ].charAt( j ) - 97 ).add( s[ i ].charAt( j + 1 ) - 97 ) ;
v.get( s[ i ].charAt( j + 1 ) - 97 ).add( s[ i ].charAt( j ) - 97 ) ;
}
sett.add( s[ i ].charAt( m - 1 ) - 97 ) ;
}
Arrays.fill( visited , 0 ) ;
int ct = 0 ;
int answer = sett.size( ) ;
for( Integer i : sett)
{
if( visited[ i ] == 0 )
{
dfs( i ) ;
ct ++ ;
}
}
System.out.println( Math.min( answer , ct ) ) ;
for( int i = 0 ; i < 26 ; i ++ )
{
v.get( i ).clear( ) ;
}
}
}
public static void dfs ( int i )
{
visited[ i ] = 1 ;
for( Integer j : v.get( i ) )
{
if( visited[ j ] == 0 )
{
dfs( j ) ;
}
}
}
} | Java | ["4\na\nb\nab\nd", "3\nab\nbc\nabc", "1\ncodeforces"] | 1 second | ["2", "1", "1"] | NoteIn the second example hacker need to use any of the passwords to access the system. | Java 11 | standard input | [
"dsu",
"dfs and similar",
"graphs"
] | 00db0111fd80ce1820da2af07a6cb8f1 | The first line contain integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — number of passwords in the list. Next $$$n$$$ lines contains passwords from the list – non-empty strings $$$s_i$$$, with length at most $$$50$$$ letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed $$$10^6$$$ letters. All of them consist only of lowercase Latin letters. | 1,500 | In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system. | standard output | |
PASSED | 61f1da6d96f7ad6f4048caab5769fa2c | train_003.jsonl | 1575038100 | One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of $$$n$$$ passwords — strings, consists of small Latin letters.Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords $$$a$$$ and $$$b$$$ as follows: two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a letter, that exists in both $$$a$$$ and $$$b$$$; two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a password $$$c$$$ from the list, which is equivalent to both $$$a$$$ and $$$b$$$. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system. | 256 megabytes | import java.util.Scanner;
import java.util.HashSet;
public class SecretPasswords {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int wCnt = s.nextInt();
int[] cand = new int[26];
int[] next = new int[26];
int[] tmp;
int candCnt = 0;
for (int i = 0; i < wCnt; i++) {
String cur = s.next();
int bm = 0;
for (int j = 0; j < cur.length(); j++) {
bm |= 1 << (cur.charAt(j) - 'a');
}
int nIdx = 0;
for (int j = 0; j < candCnt; j++) {
if ((cand[j] & bm) > 0) {
bm |= cand[j];
} else {
next[nIdx++] = cand[j];
}
}
next[nIdx++] = bm;
tmp = cand;
cand = next;
candCnt = nIdx;
next = tmp;
}
System.out.println(candCnt);
}
} | Java | ["4\na\nb\nab\nd", "3\nab\nbc\nabc", "1\ncodeforces"] | 1 second | ["2", "1", "1"] | NoteIn the second example hacker need to use any of the passwords to access the system. | Java 11 | standard input | [
"dsu",
"dfs and similar",
"graphs"
] | 00db0111fd80ce1820da2af07a6cb8f1 | The first line contain integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — number of passwords in the list. Next $$$n$$$ lines contains passwords from the list – non-empty strings $$$s_i$$$, with length at most $$$50$$$ letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed $$$10^6$$$ letters. All of them consist only of lowercase Latin letters. | 1,500 | In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system. | standard output | |
PASSED | 8e8f32f0f32616cbff5262ff8e28b3ae | train_003.jsonl | 1575038100 | One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of $$$n$$$ passwords — strings, consists of small Latin letters.Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords $$$a$$$ and $$$b$$$ as follows: two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a letter, that exists in both $$$a$$$ and $$$b$$$; two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a password $$$c$$$ from the list, which is equivalent to both $$$a$$$ and $$$b$$$. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system. | 256 megabytes | import java.util.HashSet;
import java.util.Scanner;
public class SecretPasswords {
static class Node{
Node parent = this;
int size = 1;
String s;
Node(String s){
this.s = s;
}
}
public static void main(String[] arg){
Scanner in = new Scanner(System.in);
int n = in.nextInt();
Node[] letters = new Node[26];
Node[] passwords = new Node[n];
for (int i = 0; i < 26; i++) {
letters[i] = new Node(Character.toString((char) ('a' + i)));
}
in.nextLine();
for (int i = 0; i < n; i++) {
String pass = in.nextLine();
passwords[i] = new Node(pass);
for (int j = 0; j < pass.length(); j++) {
union(letters[pass.charAt(j) - 'a'], passwords[i]);
}
}
HashSet<String> totalPass = new HashSet<>();
for (int i = 0; i < n; i++) {
totalPass.add(findParent(passwords[i]).s);
}
System.out.println(totalPass.size());
}
private static void union(Node a, Node b){
findParent(a); findParent(b);
if(a.parent.size < b.parent.size){
b.parent.size += a.parent.size;
a.parent.parent = b.parent;
}else{
a.parent.size += b.parent.size;
b.parent.parent = a.parent;
}
}
private static boolean find(Node a, Node b){
Node parentA = findParent(a);
Node parentB = findParent(b);
return parentA.equals(parentB);
}
private static Node findParent(Node a){
if(a.parent.equals(a)) return a;
a.parent = findParent(a.parent);
return a.parent;
}
}
| Java | ["4\na\nb\nab\nd", "3\nab\nbc\nabc", "1\ncodeforces"] | 1 second | ["2", "1", "1"] | NoteIn the second example hacker need to use any of the passwords to access the system. | Java 11 | standard input | [
"dsu",
"dfs and similar",
"graphs"
] | 00db0111fd80ce1820da2af07a6cb8f1 | The first line contain integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — number of passwords in the list. Next $$$n$$$ lines contains passwords from the list – non-empty strings $$$s_i$$$, with length at most $$$50$$$ letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed $$$10^6$$$ letters. All of them consist only of lowercase Latin letters. | 1,500 | In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system. | standard output | |
PASSED | 510c017f9ceb756aa9e153a62b870902 | train_003.jsonl | 1575038100 | One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of $$$n$$$ passwords — strings, consists of small Latin letters.Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords $$$a$$$ and $$$b$$$ as follows: two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a letter, that exists in both $$$a$$$ and $$$b$$$; two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a password $$$c$$$ from the list, which is equivalent to both $$$a$$$ and $$$b$$$. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system. | 256 megabytes | import java.util.ArrayList;
import java.util.Scanner;
public class D {
static boolean[] visited;
static ArrayList<Integer>[] adj;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String ref = "abcdefghijklmnopqrstuvwxyz";
adj= new ArrayList[26];
for(int i=0;i<26;i++) adj[i] = new ArrayList<>();
boolean[] put = new boolean[26];
int n = sc.nextInt();
for(int i=0;i<n;i++) {
String s = sc.next();
put[ref.indexOf(s.charAt(0))]= true;
for(int j=0;j<s.length()-1;j++) {
adj[ref.indexOf(s.charAt(j))].add(ref.indexOf(s.charAt(j+1)));
adj[ref.indexOf(s.charAt(j+1))].add(ref.indexOf(s.charAt(j)));
put[ref.indexOf(s.charAt(j+1))] = true;
}
}
int numComponents =0;
visited = new boolean[26];
for(int i=0;i<26;i++) {
if(!visited[i] && put[i]) {
numComponents++;
dfs(i);
}
}
System.out.println(numComponents);
}
static void dfs(int i) {
visited[i] = true;
for(int j : adj[i]) {
if(!visited[j]) {
dfs(j);
}
}
}
}
| Java | ["4\na\nb\nab\nd", "3\nab\nbc\nabc", "1\ncodeforces"] | 1 second | ["2", "1", "1"] | NoteIn the second example hacker need to use any of the passwords to access the system. | Java 11 | standard input | [
"dsu",
"dfs and similar",
"graphs"
] | 00db0111fd80ce1820da2af07a6cb8f1 | The first line contain integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — number of passwords in the list. Next $$$n$$$ lines contains passwords from the list – non-empty strings $$$s_i$$$, with length at most $$$50$$$ letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed $$$10^6$$$ letters. All of them consist only of lowercase Latin letters. | 1,500 | In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system. | standard output | |
PASSED | 8919276d08c3fb41ba8ccbe011dc679d | train_003.jsonl | 1575038100 | One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of $$$n$$$ passwords — strings, consists of small Latin letters.Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords $$$a$$$ and $$$b$$$ as follows: two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a letter, that exists in both $$$a$$$ and $$$b$$$; two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a password $$$c$$$ from the list, which is equivalent to both $$$a$$$ and $$$b$$$. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system. | 256 megabytes | /**
* sol1263D
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.*;
public class sol1263D {
public static String output = "";
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 sc= new FastReader();
try {
int t=1;
// t=sc.nextInt();
while (t-- >0) {
int n=sc.nextInt();
int[] occ = new int[26];
Arrays.fill(occ,-1);
DSU obj = new DSU(n);
for(int i=0;i<n;i++){
String s=sc.nextLine();
for(int j=0;j<s.length();j++){
int x = s.charAt(j)-'a';
if(occ[x]==-1){
occ[x]=i;
}else{
obj.union(i, occ[x]);
}
}
}
System.out.print(obj.numSets);
}
// sc.close();
} catch (Exception e) {
e.printStackTrace();
}
}
static class DSU {
int numSets;
int[] p, rank;
public DSU(int n) {
numSets = n;
p = new int[n];
rank = new int[n];
for(int i = 0; i<n; i++)
p[i] =i;
}
int findSet(int x) {
return p[x] == x ? x : (p[x] = findSet(p[x]));
}
void union(int x, int y) {
x = findSet(x);
y = findSet(y);
if (x == y)
return;
if (rank[x] > rank[y]) {
p[y] = x;
} else {
p[x] = y;
if (rank[x] == rank[y]) {
rank[y]++;
}
}
numSets--;
}
}
//Find the GCD of two numbers
public static int gcd(int a, int b) {
if (a < b) return gcd(b,a);
if (b == 0)
return a;
else
return gcd(b,a%b);
}
// LCM
public static int lcm(int a,int b){
int ans = (a*b)/gcd(a,b);
return ans;
}
//Fast exponentiation (x^y mod m)
public static long power(long x, long y, long m) {
if (y < 0) return 0L;
long ans = 1;
x %= m;
while (y > 0) {
if(y % 2 == 1)
ans = (ans * x) % m;
y /= 2;
x = (x * x) % m;
}
return ans;
}
}
| Java | ["4\na\nb\nab\nd", "3\nab\nbc\nabc", "1\ncodeforces"] | 1 second | ["2", "1", "1"] | NoteIn the second example hacker need to use any of the passwords to access the system. | Java 11 | standard input | [
"dsu",
"dfs and similar",
"graphs"
] | 00db0111fd80ce1820da2af07a6cb8f1 | The first line contain integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — number of passwords in the list. Next $$$n$$$ lines contains passwords from the list – non-empty strings $$$s_i$$$, with length at most $$$50$$$ letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed $$$10^6$$$ letters. All of them consist only of lowercase Latin letters. | 1,500 | In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system. | standard output | |
PASSED | 21baf7924be14b4f12a9aab40434891b | train_003.jsonl | 1575038100 | One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of $$$n$$$ passwords — strings, consists of small Latin letters.Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords $$$a$$$ and $$$b$$$ as follows: two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a letter, that exists in both $$$a$$$ and $$$b$$$; two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a password $$$c$$$ from the list, which is equivalent to both $$$a$$$ and $$$b$$$. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system. | 256 megabytes | import java.util.*;
import java.io.*;
public class D603
{
static ArrayList<Integer> [] adj;
static boolean []
visited; public static void main(String [] args)
{
MyScanner sc = new MyScanner();
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); Map<String, Integer> rep = new HashMap<>();
int n = sc.nextInt();
adj = new ArrayList[n+1];
for (int i = 1; i <= n; i++) adj[i] = new ArrayList<>();
for (int i = 1; i <= n; i++) {
String s = sc.next(); Set<String> processed = new HashSet<>();
for (int j = 0; j < s.length(); j++) {
if (processed.contains(s.substring(j, j+1))) continue;
if (rep.containsKey(s.substring(j, j+1))) {
int connect = rep.get(s.substring(j, j+1));
adj[i].add(connect);
adj[connect].add(i);
} else {
rep.put(s.substring(j, j+1), i);
}
processed.add(s.substring(j, j+1));
}
}
visited = new boolean[n+1]; int ans = 0;
for (int i = 1; i <= n; i++) {
if (!visited[i]) {
dfs(i); ans++;
}
}
out.println(ans);
out.close();
}
static void dfs(int start) {
visited[start] = true;
for (Integer next: adj[start]) {
if (!visited[next]) {
dfs(next);
}
}
}
//-----------MyScanner class for faster input----------
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["4\na\nb\nab\nd", "3\nab\nbc\nabc", "1\ncodeforces"] | 1 second | ["2", "1", "1"] | NoteIn the second example hacker need to use any of the passwords to access the system. | Java 11 | standard input | [
"dsu",
"dfs and similar",
"graphs"
] | 00db0111fd80ce1820da2af07a6cb8f1 | The first line contain integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — number of passwords in the list. Next $$$n$$$ lines contains passwords from the list – non-empty strings $$$s_i$$$, with length at most $$$50$$$ letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed $$$10^6$$$ letters. All of them consist only of lowercase Latin letters. | 1,500 | In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system. | standard output | |
PASSED | 399ac86b20986851f571459594f8f887 | train_003.jsonl | 1575038100 | One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of $$$n$$$ passwords — strings, consists of small Latin letters.Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords $$$a$$$ and $$$b$$$ as follows: two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a letter, that exists in both $$$a$$$ and $$$b$$$; two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a password $$$c$$$ from the list, which is equivalent to both $$$a$$$ and $$$b$$$. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system. | 256 megabytes | import java.util.*;
import java.io.*;
public class Sol {
public static int[] id, size;
public static int find(int p) {
while (p != id[p]) {
p = id[p];
}
return p;
}
public static void union(int p, int q) {
int rp = find(p);
int rq = find(q);
if (rp == rq) return;
if (size[rp] < size[rq]) {
id[rp] = rq;
size[rq] += size[rp];
}
else {
id[rq] = rp;
size[rp] += size[rq];
}
}
public static void main(String[] args) throws IOException {
BufferedReader f = (new BufferedReader(new InputStreamReader(System.in)));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int N = Integer.parseInt(f.readLine());
String[] strs = new String[N];
for (int i = 0; i < N; i++) strs[i] = f.readLine();
id = new int[26];
for (int i = 0; i < 26; i++) id[i] = i;
size = new int[26];
boolean[][] connected = new boolean[26][26];
HashSet<Integer> present = new HashSet<>();
for (int n = 0; n < 2; n++) {
for (int k = 0; k < N; k++) {
char[] s = strs[k].toCharArray();
for (int i = 0; i < s.length; i++) {
int a = s[i] - 'a';
present.add(a);
for (int j = i+1; j < s.length; j++) {
int b = s[j]-'a';
if (!connected[a][b]) union(a, b);
else connected[a][b] = true;
}
}
}
}
TreeSet<Integer> comp = new TreeSet<>();
for (int i = 0; i < 26; i++) {
if (present.contains(i)) comp.add(find(i));
}
out.println(comp.size());
f.close();
out.close();
}
}
| Java | ["4\na\nb\nab\nd", "3\nab\nbc\nabc", "1\ncodeforces"] | 1 second | ["2", "1", "1"] | NoteIn the second example hacker need to use any of the passwords to access the system. | Java 11 | standard input | [
"dsu",
"dfs and similar",
"graphs"
] | 00db0111fd80ce1820da2af07a6cb8f1 | The first line contain integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — number of passwords in the list. Next $$$n$$$ lines contains passwords from the list – non-empty strings $$$s_i$$$, with length at most $$$50$$$ letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed $$$10^6$$$ letters. All of them consist only of lowercase Latin letters. | 1,500 | In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system. | standard output | |
PASSED | 75f94b754d5ac30499d8476c6f8d2840 | train_003.jsonl | 1575038100 | One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of $$$n$$$ passwords — strings, consists of small Latin letters.Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords $$$a$$$ and $$$b$$$ as follows: two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a letter, that exists in both $$$a$$$ and $$$b$$$; two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a password $$$c$$$ from the list, which is equivalent to both $$$a$$$ and $$$b$$$. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int n = nextInt();
int arr[] = new int[26];
Arrays.fill(arr, -1);
int a[] = new int[n];
dsu d = new dsu(n);
for (int i = 0; i < n; i++) {
char[] b = next().toCharArray();
for (int j = 0; j < b.length; j++) {
if (arr[b[j] - 'a'] != -1) {
d.merge(i, arr[b[j] - 'a']);
}
arr[b[j] - 'a'] = i;
}
}
TreeSet<Integer> ts = new TreeSet<>();
for (int i = 0; i < n; i++) {
ts.add(d.get(i));
}
out.println(ts.size());
out.close();
}
static BufferedReader br;
static StringTokenizer st = new StringTokenizer("");
static String next() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
}
class dsu {
int n;
int[] p;
public dsu(int n) {
this.n = n;
p = new int[n];
for (int i = 0; i < n; i++) {
p[i] = i;
}
}
int get(int a) {
if (p[a] == a) return a;
return p[a] = get(p[a]);
}
void merge(int a, int b) {
a = get(a);
b = get(b);
if (a != b) {
p[b] = a;
}
}
} | Java | ["4\na\nb\nab\nd", "3\nab\nbc\nabc", "1\ncodeforces"] | 1 second | ["2", "1", "1"] | NoteIn the second example hacker need to use any of the passwords to access the system. | Java 11 | standard input | [
"dsu",
"dfs and similar",
"graphs"
] | 00db0111fd80ce1820da2af07a6cb8f1 | The first line contain integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — number of passwords in the list. Next $$$n$$$ lines contains passwords from the list – non-empty strings $$$s_i$$$, with length at most $$$50$$$ letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed $$$10^6$$$ letters. All of them consist only of lowercase Latin letters. | 1,500 | In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.