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 | 5b88c777cd01b3e919ce009ced252aa7 | train_001.jsonl | 1405774800 | Jzzhu is the president of country A. There are n cities numbered from 1 to n in his country. City 1 is the capital of A. Also there are m roads connecting the cities. One can go from city ui to vi (and vise versa) using the i-th road, the length of this road is xi. Finally, there are k train routes in the country. One can use the i-th train route to go from capital of the country to city si (and vise versa), the length of this route is yi.Jzzhu doesn't want to waste the money of the country, so he is going to close some of the train routes. Please tell Jzzhu the maximum number of the train routes which can be closed under the following condition: the length of the shortest path from every city to the capital mustn't change. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class trains{
static ArrayList<edge>[] ady;
static ArrayList<edge>[] ady2;
static int n;
static int l;
static long[] dist;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] input = br.readLine().split(" ");
n = Integer.parseInt(input[0]);int m = Integer.parseInt(input[1]);int k=Integer.parseInt(input[2]);
ady = new ArrayList[n];
ady2 = new ArrayList[n];
dist = new long[n];
ArrayList<edge> trains = new ArrayList<edge>();
for(int i=0;i<n;i++){
ady[i]=new ArrayList<edge>();
ady2[i]=new ArrayList<edge>();
}
for(int i=0;i<m;i++){
input=br.readLine().split(" ");
int in = Integer.parseInt(input[0])-1;
int out = Integer.parseInt(input[1])-1;
int w = Integer.parseInt(input[2]);
ady[in].add(new edge(out,w));
ady[out].add(new edge(in,w));
}
for(int i=0;i<k;i++){
input=br.readLine().split(" ");
int out = Integer.parseInt(input[0])-1;
int w = Integer.parseInt(input[1]);
edge route = new edge(out,w);
ady[0].add(route);
ady[out].add(new edge(0,w));
trains.add(route);
}
dj(0);
int indegree[] = new int[n];
for(int i =0;i<n;i++){
for(edge e:ady[i]){
if(e.w+dist[i]==dist[e.out]){
indegree[e.out]++;
ady2[i].add(new edge(e.out,e.w));
}
}
}
// for(int i=0;i<n;i++){
// for(edge e:ady2[i]){
// System.out.print(" "+ e.out +" " +e.w);
// }
// System.out.println("");
// }
int total = 0;
for(edge e:trains){
if (e.w>dist[e.out]){
total++;
}
else if(indegree[e.out]>1) {
total++;
indegree[e.out]--;
}
}
System.out.println(total);
}
static void dj(int nodo){
IndexMinPQ<Integer> p = new IndexMinPQ<Integer>(n);
for(int i=0;i<n;i++) dist[i]=Integer.MAX_VALUE;
dist[nodo]=0;
p.insert(nodo,0);
while(!p.isEmpty()){
int u = p.delMin();
for(edge e : ady[u]){
int v = e.out;
int w = e.w;
if(dist[u]+w<dist[v]){
dist[v]=dist[u]+w;
if (!p.contains(v)){
p.insert(v,(int)dist[v]);
}
else{
p.decreaseKey(v, (int)dist[v]);
}
}
}
}
}
static class edge{
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + out;
result = prime * result + w;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
edge other = (edge) obj;
if (out != other.out)
return false;
if (w != other.w)
return false;
return true;
}
int out,w;
edge(int out,int w){
this.out=out;
this.w=w;
}
}
}
/**
* The <tt>IndexMinPQ</tt> class represents an indexed priority queue of generic keys.
* It supports the usual <em>insert</em> and <em>delete-the-minimum</em>
* operations, along with <em>delete</em> and <em>change-the-key</em>
* methods. In order to let the client refer to keys on the priority queue,
* an integer between 0 and maxN-1 is associated with each key—the client
* uses this integer to specify which key to delete or change.
* It also supports methods for peeking at the minimum key,
* testing if the priority queue is empty, and iterating through
* the keys.
* <p>
* This implementation uses a binary heap along with an array to associate
* keys with integers in the given range.
* The <em>insert</em>, <em>delete-the-minimum</em>, <em>delete</em>,
* <em>change-key</em>, <em>decrease-key</em>, and <em>increase-key</em>
* operations take logarithmic time.
* The <em>is-empty</em>, <em>size</em>, <em>min-index</em>, <em>min-key</em>, and <em>key-of</em>
* operations take constant time.
* Construction takes time proportional to the specified capacity.
* <p>
* For additional documentation, see <a href="http://algs4.cs.princeton.edu/24pq">Section 2.4</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*
* @param <Key> the generic type of key on this priority queue
*/
class IndexMinPQ<Key extends Comparable<Key>> implements Iterable<Integer> {
private int maxN; // maximum number of elements on PQ
private int N; // number of elements on PQ
private int[] pq; // binary heap using 1-based indexing
private int[] qp; // inverse of pq - qp[pq[i]] = pq[qp[i]] = i
private Key[] keys; // keys[i] = priority of i
/**
* Initializes an empty indexed priority queue with indices between <tt>0</tt>
* and <tt>maxN - 1</tt>.
* @param maxN the keys on this priority queue are index from <tt>0</tt>
* <tt>maxN - 1</tt>
* @throws IllegalArgumentException if <tt>maxN</tt> < <tt>0</tt>
*/
public IndexMinPQ(int maxN) {
if (maxN < 0) throw new IllegalArgumentException();
this.maxN = maxN;
keys = (Key[]) new Comparable[maxN + 1]; // make this of length maxN??
pq = new int[maxN + 1];
qp = new int[maxN + 1]; // make this of length maxN??
for (int i = 0; i <= maxN; i++)
qp[i] = -1;
}
/**
* Returns true if this priority queue is empty.
*
* @return <tt>true</tt> if this priority queue is empty;
* <tt>false</tt> otherwise
*/
public boolean isEmpty() {
return N == 0;
}
/**
* Is <tt>i</tt> an index on this priority queue?
*
* @param i an index
* @return <tt>true</tt> if <tt>i</tt> is an index on this priority queue;
* <tt>false</tt> otherwise
* @throws IndexOutOfBoundsException unless 0 ≤ <tt>i</tt> < <tt>maxN</tt>
*/
public boolean contains(int i) {
if (i < 0 || i >= maxN) throw new IndexOutOfBoundsException();
return qp[i] != -1;
}
/**
* Returns the number of keys on this priority queue.
*
* @return the number of keys on this priority queue
*/
public int size() {
return N;
}
/**
* Associates key with index <tt>i</tt>.
*
* @param i an index
* @param key the key to associate with index <tt>i</tt>
* @throws IndexOutOfBoundsException unless 0 ≤ <tt>i</tt> < <tt>maxN</tt>
* @throws IllegalArgumentException if there already is an item associated
* with index <tt>i</tt>
*/
public void insert(int i, Key key) {
if (i < 0 || i >= maxN) throw new IndexOutOfBoundsException();
if (contains(i)) throw new IllegalArgumentException("index is already in the priority queue");
N++;
qp[i] = N;
pq[N] = i;
keys[i] = key;
swim(N);
}
/**
* Returns an index associated with a minimum key.
*
* @return an index associated with a minimum key
* @throws NoSuchElementException if this priority queue is empty
*/
public int minIndex() {
if (N == 0) throw new NoSuchElementException("Priority queue underflow");
return pq[1];
}
/**
* Returns a minimum key.
*
* @return a minimum key
* @throws NoSuchElementException if this priority queue is empty
*/
public Key minKey() {
if (N == 0) throw new NoSuchElementException("Priority queue underflow");
return keys[pq[1]];
}
/**
* Removes a minimum key and returns its associated index.
* @return an index associated with a minimum key
* @throws NoSuchElementException if this priority queue is empty
*/
public int delMin() {
if (N == 0) throw new NoSuchElementException("Priority queue underflow");
int min = pq[1];
exch(1, N--);
sink(1);
qp[min] = -1; // delete
keys[pq[N+1]] = null; // to help with garbage collection
pq[N+1] = -1; // not needed
return min;
}
/**
* Returns the key associated with index <tt>i</tt>.
*
* @param i the index of the key to return
* @return the key associated with index <tt>i</tt>
* @throws IndexOutOfBoundsException unless 0 ≤ <tt>i</tt> < <tt>maxN</tt>
* @throws NoSuchElementException no key is associated with index <tt>i</tt>
*/
public Key keyOf(int i) {
if (i < 0 || i >= maxN) throw new IndexOutOfBoundsException();
if (!contains(i)) throw new NoSuchElementException("index is not in the priority queue");
else return keys[i];
}
/**
* Change the key associated with index <tt>i</tt> to the specified value.
*
* @param i the index of the key to change
* @param key change the key assocated with index <tt>i</tt> to this key
* @throws IndexOutOfBoundsException unless 0 ≤ <tt>i</tt> < <tt>maxN</tt>
* @deprecated Replaced by changeKey()
*/
@Deprecated public void change(int i, Key key) {
changeKey(i, key);
}
/**
* Change the key associated with index <tt>i</tt> to the specified value.
*
* @param i the index of the key to change
* @param key change the key assocated with index <tt>i</tt> to this key
* @throws IndexOutOfBoundsException unless 0 ≤ <tt>i</tt> < <tt>maxN</tt>
* @throws NoSuchElementException no key is associated with index <tt>i</tt>
*/
public void changeKey(int i, Key key) {
if (i < 0 || i >= maxN) throw new IndexOutOfBoundsException();
if (!contains(i)) throw new NoSuchElementException("index is not in the priority queue");
keys[i] = key;
swim(qp[i]);
sink(qp[i]);
}
/**
* Decrease the key associated with index <tt>i</tt> to the specified value.
*
* @param i the index of the key to decrease
* @param key decrease the key assocated with index <tt>i</tt> to this key
* @throws IndexOutOfBoundsException unless 0 ≤ <tt>i</tt> < <tt>maxN</tt>
* @throws IllegalArgumentException if key ≥ key associated with index <tt>i</tt>
* @throws NoSuchElementException no key is associated with index <tt>i</tt>
*/
public void decreaseKey(int i, Key key) {
if (i < 0 || i >= maxN) throw new IndexOutOfBoundsException();
if (!contains(i)) throw new NoSuchElementException("index is not in the priority queue");
if (keys[i].compareTo(key) <= 0)
throw new IllegalArgumentException("Calling decreaseKey() with given argument would not strictly decrease the key");
keys[i] = key;
swim(qp[i]);
}
/**
* Increase the key associated with index <tt>i</tt> to the specified value.
*
* @param i the index of the key to increase
* @param key increase the key assocated with index <tt>i</tt> to this key
* @throws IndexOutOfBoundsException unless 0 ≤ <tt>i</tt> < <tt>maxN</tt>
* @throws IllegalArgumentException if key ≤ key associated with index <tt>i</tt>
* @throws NoSuchElementException no key is associated with index <tt>i</tt>
*/
public void increaseKey(int i, Key key) {
if (i < 0 || i >= maxN) throw new IndexOutOfBoundsException();
if (!contains(i)) throw new NoSuchElementException("index is not in the priority queue");
if (keys[i].compareTo(key) >= 0)
throw new IllegalArgumentException("Calling increaseKey() with given argument would not strictly increase the key");
keys[i] = key;
sink(qp[i]);
}
/**
* Remove the key associated with index <tt>i</tt>.
*
* @param i the index of the key to remove
* @throws IndexOutOfBoundsException unless 0 ≤ <tt>i</tt> < <tt>maxN</tt>
* @throws NoSuchElementException no key is associated with index <t>i</tt>
*/
public void delete(int i) {
if (i < 0 || i >= maxN) throw new IndexOutOfBoundsException();
if (!contains(i)) throw new NoSuchElementException("index is not in the priority queue");
int index = qp[i];
exch(index, N--);
swim(index);
sink(index);
keys[i] = null;
qp[i] = -1;
}
/***************************************************************************
* General helper functions.
***************************************************************************/
private boolean greater(int i, int j) {
return keys[pq[i]].compareTo(keys[pq[j]]) > 0;
}
private void exch(int i, int j) {
int swap = pq[i];
pq[i] = pq[j];
pq[j] = swap;
qp[pq[i]] = i;
qp[pq[j]] = j;
}
/***************************************************************************
* Heap helper functions.
***************************************************************************/
private void swim(int k) {
while (k > 1 && greater(k/2, k)) {
exch(k, k/2);
k = k/2;
}
}
private void sink(int k) {
while (2*k <= N) {
int j = 2*k;
if (j < N && greater(j, j+1)) j++;
if (!greater(k, j)) break;
exch(k, j);
k = j;
}
}
/***************************************************************************
* Iterators.
***************************************************************************/
/**
* Returns an iterator that iterates over the keys on the
* priority queue in ascending order.
* The iterator doesn't implement <tt>remove()</tt> since it's optional.
*
* @return an iterator that iterates over the keys in ascending order
*/
public Iterator<Integer> iterator() { return new HeapIterator(); }
private class HeapIterator implements Iterator<Integer> {
// create a new pq
private IndexMinPQ<Key> copy;
// add all elements to copy of heap
// takes linear time since already in heap order so no keys move
public HeapIterator() {
copy = new IndexMinPQ<Key>(pq.length - 1);
for (int i = 1; i <= N; i++)
copy.insert(pq[i], keys[pq[i]]);
}
public boolean hasNext() { return !copy.isEmpty(); }
public void remove() { throw new UnsupportedOperationException(); }
public Integer next() {
if (!hasNext()) throw new NoSuchElementException();
return copy.delMin();
}
}
}
| Java | ["5 5 3\n1 2 1\n2 3 2\n1 3 3\n3 4 4\n1 5 5\n3 5\n4 5\n5 5", "2 2 3\n1 2 2\n2 1 3\n2 1\n2 2\n2 3"] | 2 seconds | ["2", "2"] | null | Java 7 | standard input | [
"graphs",
"greedy",
"shortest paths"
] | 03d6b61be6ca0ac9dd8259458f41da59 | The first line contains three integers n, m, k (2 ≤ n ≤ 105; 1 ≤ m ≤ 3·105; 1 ≤ k ≤ 105). Each of the next m lines contains three integers ui, vi, xi (1 ≤ ui, vi ≤ n; ui ≠ vi; 1 ≤ xi ≤ 109). Each of the next k lines contains two integers si and yi (2 ≤ si ≤ n; 1 ≤ yi ≤ 109). It is guaranteed that there is at least one way from every city to the capital. Note, that there can be multiple roads between two cities. Also, there can be multiple routes going to the same city from the capital. | 2,000 | Output a single integer representing the maximum number of the train routes which can be closed. | standard output | |
PASSED | 5f5091a8e39856481908f4be4cb0da86 | train_001.jsonl | 1405774800 | Jzzhu is the president of country A. There are n cities numbered from 1 to n in his country. City 1 is the capital of A. Also there are m roads connecting the cities. One can go from city ui to vi (and vise versa) using the i-th road, the length of this road is xi. Finally, there are k train routes in the country. One can use the i-th train route to go from capital of the country to city si (and vise versa), the length of this route is yi.Jzzhu doesn't want to waste the money of the country, so he is going to close some of the train routes. Please tell Jzzhu the maximum number of the train routes which can be closed under the following condition: the length of the shortest path from every city to the capital mustn't change. | 256 megabytes | import java.io.IOException;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.ArrayList;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.TreeSet;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author George Marcus
*/
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);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
private static final long INF = (long) 1e17;
public void solve(int testNumber, InputReader in, PrintWriter out) {
int N = in.nextInt();
int M = in.nextInt();
int K = in.nextInt();
ArrayList<Edge>[] G = new ArrayList[N];
for (int i = 0; i < N; i++) {
G[i] = new ArrayList<Edge>();
}
for (int i = 0; i < M; i++) {
int a = in.nextInt();
int b = in.nextInt();
int c = in.nextInt();
a--; b--;
G[a].add(new Edge(b, c));
G[b].add(new Edge(a, c));
}
int[] minTrain = new int[N];
Arrays.fill(minTrain, Integer.MAX_VALUE);
int[] numTrains = new int[N];
for (int i = 0; i < K; i++) {
int a = in.nextInt();
int b = in.nextInt();
a--;
minTrain[a] = Math.min(minTrain[a], b);
numTrains[a]++;
}
long ans = computeDistances(G, minTrain, numTrains);
out.println(ans);
}
private int computeDistances(ArrayList<Edge>[] G, int[] minTrain, int[] numTrains) {
int N = G.length;
boolean[] changed = new boolean[N];
long[] D = new long[N];
Arrays.fill(D, INF);
TreeSet<Edge> S = new TreeSet<Edge>();
D[0] = 0;
S.add(new Edge(0, 0));
for (int i = 0; i < N; i++) {
if (numTrains[i] > 0) {
D[i] = minTrain[i];
S.add(new Edge(i, D[i]));
}
}
int ret = 0;
while (!S.isEmpty()) {
Edge top = S.first();
S.remove(top);
int p = top.to;
long dist = top.cost;
if (dist > D[p]) {
continue;
}
if (numTrains[p] > 0) {
if (changed[p]) {
ret += numTrains[p];
}
else {
ret += numTrains[p] - 1;
}
}
for (Edge e : G[p]) {
if (D[p] + e.cost < D[e.to]) {
D[e.to] = D[p] + e.cost;
S.add(new Edge(e.to, D[e.to]));
changed[e.to] = true;
}
else if (D[p] + e.cost == D[e.to]) {
changed[e.to] = true;
}
}
}
return ret;
}
private class Edge implements Comparable<Edge> {
public int to;
public long cost;
private Edge(int to, long cost) {
this.to = to;
this.cost = cost;
}
public int compareTo(Edge e) {
if (cost != e.cost) {
return cost < e.cost ? -1 : 1;
}
if (to != e.to) {
return to < e.to ? -1 : 1;
}
return 0;
}
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
return Integer.parseInt(nextString());
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuffer res = new StringBuffer();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
| Java | ["5 5 3\n1 2 1\n2 3 2\n1 3 3\n3 4 4\n1 5 5\n3 5\n4 5\n5 5", "2 2 3\n1 2 2\n2 1 3\n2 1\n2 2\n2 3"] | 2 seconds | ["2", "2"] | null | Java 7 | standard input | [
"graphs",
"greedy",
"shortest paths"
] | 03d6b61be6ca0ac9dd8259458f41da59 | The first line contains three integers n, m, k (2 ≤ n ≤ 105; 1 ≤ m ≤ 3·105; 1 ≤ k ≤ 105). Each of the next m lines contains three integers ui, vi, xi (1 ≤ ui, vi ≤ n; ui ≠ vi; 1 ≤ xi ≤ 109). Each of the next k lines contains two integers si and yi (2 ≤ si ≤ n; 1 ≤ yi ≤ 109). It is guaranteed that there is at least one way from every city to the capital. Note, that there can be multiple roads between two cities. Also, there can be multiple routes going to the same city from the capital. | 2,000 | Output a single integer representing the maximum number of the train routes which can be closed. | standard output | |
PASSED | 23c86f90b14baf11b33ff8a1752e171e | train_001.jsonl | 1405774800 | Jzzhu is the president of country A. There are n cities numbered from 1 to n in his country. City 1 is the capital of A. Also there are m roads connecting the cities. One can go from city ui to vi (and vise versa) using the i-th road, the length of this road is xi. Finally, there are k train routes in the country. One can use the i-th train route to go from capital of the country to city si (and vise versa), the length of this route is yi.Jzzhu doesn't want to waste the money of the country, so he is going to close some of the train routes. Please tell Jzzhu the maximum number of the train routes which can be closed under the following condition: the length of the shortest path from every city to the capital mustn't change. | 256 megabytes | import static java.lang.Math.*;
import java.io.*;
import java.util.*;
public class A {
BufferedReader in;
PrintWriter out;
StringTokenizer st;
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(in.readLine());
} catch(Exception e) {}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
boolean bit(int m, int i) {
return (m & (1 << i)) > 0;
}
int n, x, y, c, m, k;
ArrayList<Pair>[] g;
long inf = 10000000000000000L;
TreeSet<Pair> pq;
long[] d;
int ans=0, ptr=0;
Pair[] r;
public void dj() {
m: while (pq.size()>0) {
while (ptr < k && pq.first().y > r[ptr].y) {
if (d[r[ptr].x] > r[ptr].y) {
d[r[ptr].x] = r[ptr].y;
pq.add(new Pair(r[ptr].x, r[ptr].y));
ptr++;
ans++;
continue m;
} else ptr++;
}
Pair cur = pq.pollFirst();
if (d[cur.x] != cur.y) continue;
for (Pair nx : g[cur.x]) if (d[cur.x] + nx.y < d[nx.x]) {
Pair f = new Pair(nx.x, d[nx.x]);
//if (pq.contains(f)) pq.remove(f);
d[nx.x] = d[cur.x] + nx.y;
pq.add(new Pair(nx.x, d[nx.x]));
}
}
}
public void run() {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
n = nextInt();
m = nextInt();
k = nextInt();
g = new ArrayList[n];
for (int i=0; i<n; i++) g[i] = new ArrayList<Pair>();
for (int i=0; i<m; i++) {
int a = nextInt() - 1;
int b = nextInt() - 1;
int c = nextInt();
g[a].add(new Pair(b, c));
g[b].add(new Pair(a, c));
}
pq = new TreeSet<Pair>();
d = new long[n];
for (int i=0; i<n; i++) d[i] = inf;
pq.add(new Pair(0, 0));
d[0] =0;
r = new Pair[k];
for (int i=0; i<k; i++) {
r[i] = new Pair(nextInt() - 1, nextInt());
}
Random rn = new Random();
for (int i=2; i<k; i++) {
int j = abs(rn.nextInt()) % i;
Pair w = r[i];
r[i] = r[j];
r[j] = w;
}
Arrays.sort(r);
dj();
out.println(k-ans);
out.close();
}
class Pair implements Comparable<Pair> {
int x;
long y;
public Pair(int x, long y) {
this.x=x;
this.y=y;
}
public int compareTo(Pair o) {
if (y != o.y) return sign(y - o.y);
return x - o.x;
}
}
int sign(long x) {
if (x < 0) return -1;
if (x > 0) return 1;
return 0;
}
public static void main(String[] args) throws Exception {
new A().run();
}
} | Java | ["5 5 3\n1 2 1\n2 3 2\n1 3 3\n3 4 4\n1 5 5\n3 5\n4 5\n5 5", "2 2 3\n1 2 2\n2 1 3\n2 1\n2 2\n2 3"] | 2 seconds | ["2", "2"] | null | Java 7 | standard input | [
"graphs",
"greedy",
"shortest paths"
] | 03d6b61be6ca0ac9dd8259458f41da59 | The first line contains three integers n, m, k (2 ≤ n ≤ 105; 1 ≤ m ≤ 3·105; 1 ≤ k ≤ 105). Each of the next m lines contains three integers ui, vi, xi (1 ≤ ui, vi ≤ n; ui ≠ vi; 1 ≤ xi ≤ 109). Each of the next k lines contains two integers si and yi (2 ≤ si ≤ n; 1 ≤ yi ≤ 109). It is guaranteed that there is at least one way from every city to the capital. Note, that there can be multiple roads between two cities. Also, there can be multiple routes going to the same city from the capital. | 2,000 | Output a single integer representing the maximum number of the train routes which can be closed. | standard output | |
PASSED | 415194dd3f57427f31199896e6af2255 | train_001.jsonl | 1405774800 | Jzzhu is the president of country A. There are n cities numbered from 1 to n in his country. City 1 is the capital of A. Also there are m roads connecting the cities. One can go from city ui to vi (and vise versa) using the i-th road, the length of this road is xi. Finally, there are k train routes in the country. One can use the i-th train route to go from capital of the country to city si (and vise versa), the length of this route is yi.Jzzhu doesn't want to waste the money of the country, so he is going to close some of the train routes. Please tell Jzzhu the maximum number of the train routes which can be closed under the following condition: the length of the shortest path from every city to the capital mustn't change. | 256 megabytes | /*
ID: govind.3, GhpS, govindpatel
LANG: JAVA
TASK: Main
*/
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Main {
/**
* Min segment Tree takes the minimum number at the root
*/
class MinSegmentTree {
/**
* root: Tree root, balance: input array, rl,rr:
* rl=0,rr=inputArray.length-1 minTree:segment Tree
*/
private void initMinTree(int root, int rl, int rr, int[] balance, int[] minTree) {
if (rl == rr) {
minTree[root] = balance[rl];
return;
}
int rm = (rl + rr) / 2;
initMinTree(root * 2 + 1, rl, rm, balance, minTree);
initMinTree(root * 2 + 2, rm + 1, rr, balance, minTree);
minTree[root] = Math.min(minTree[root * 2 + 1], minTree[root * 2 + 2]);
}
/**
* minTree:segment tree root:0 rl:0,rr:inputarray.length-1
* l=queryleft-1(If 1 based index),r = queryright(1-based)
*/
private int getMin(int[] minTree, int root, int rl, int rr, int l, int r) {
//l = query left-1, r = query right
if (l > r) {
return Integer.MAX_VALUE;
}
if (l == rl && r == rr) {
return minTree[root];
}
int rm = (rl + rr) / 2;
return Math.min(getMin(minTree, root * 2 + 1, rl, rm, l, Math.min(r, rm)),
getMin(minTree, root * 2 + 2, rm + 1, rr, Math.max(rm + 1, l), r));
}
}
//dsu next operation
int[] next;
private int next(int i) {
if (next[i] == i) {
return i;
}
return next[i] = next(next[i]);
}
//segment tree...
private void set(int[] t, int ind, int val) {
ind += (t.length / 2);
t[ind] = val;
int curr = 0;
while (ind > 1) {
ind >>= 1;
if (curr == 0) {
t[ind] = t[ind * 2] | t[ind * 2 + 1];
} else {
t[ind] = t[ind * 2] ^ t[2 * ind + 1];
}
curr ^= 1;
}
}
//Binary Index tree
class FenwickTree {
int[] ft;
int N;
FenwickTree(int n) {
this.N = n;
ft = new int[N];
}
private int lowbit(int x) {
return x & (-x);
}
void update(int pos, int val) {
while (pos < N) {
ft[pos] += val;
pos |= pos + 1;//0-index
}
}
int sum(int pos) {
int sum = 0;
while (pos >= 0) {
sum += ft[pos];
pos = (pos & (pos + 1)) - 1;
}
return sum;
}
int rangeSum(int left, int right) {
return sum(right) - sum(left - 1);
}
}
/**
* BINARY SEARCH IN FENWICK TREE: l=1, r=N(length), at=sumRequired,
* letter=TreeIndex(if there are many ft), ft=arrays of FT
*/
private int binarySearch(int l, int r, int at, int letter, FenwickTree[] ft) {
while (r - l > 0) {
int mid = (l + r) / 2;
int sum = ft[letter].sum(mid);
if (sum < at) {
l = mid + 1;
} else {
r = mid;
}
}
return l;
}
private int[] compress(int[] a) {
int[] b = new int[a.length];
for (int i = 0; i < a.length; i++) {
b[i] = a[i];
}
Arrays.sort(b);
int m = 0;
for (int i = 0; i < b.length;) {
int j = i;
while (j < b.length && b[j] == b[i]) {
j++;
}
b[m++] = b[i];
i = j;
}
for (int i = 0; i < a.length; i++) {
a[i] = Arrays.binarySearch(b, 0, m, a[i]);
}
return a;
}
class Dijkstra {
class Edge implements Comparable<Edge> {
int to;
long weight;
Edge(int t, long w) {
to = t;
weight = w;
}
public int compareTo(Edge other) {
return (int) Math.signum(weight - other.weight);
}
}
public static final long INF = (long) 1e17;
private ArrayList<Edge> adj[];
private int nodes;
private long[] dist;
private int[] prev;
private boolean[] visited;
public Dijkstra(int n) {
nodes = n;
adj = new ArrayList[nodes];
dist = new long[nodes];
prev = new int[nodes];
visited = new boolean[nodes];
for (int i = 0; i < nodes; i++) {
adj[i] = new ArrayList<Edge>();
dist[i] = INF;
prev[i] = -1;
}
}
public void add(int u, int v, long cost) {
adj[u].add(new Edge(v, cost));
}
public void dist() {
//src vertex = 0;
dist[0] = 0;
Queue<Edge> q = new PriorityQueue<Edge>();
q.add(new Edge(0, 0));
while (!q.isEmpty()) {
Edge e = q.poll();
int ind = e.to;
if (visited[ind]) {
continue;
}
visited[ind] = true;
for (Edge edge : adj[ind]) {
long newDistance = e.weight + edge.weight;
if (newDistance < dist[edge.to]) {
dist[edge.to] = newDistance;
prev[edge.to] = ind;
q.add(new Edge(edge.to, dist[edge.to]));
}
}
}
}
public ArrayList<Integer> getPrevList(int last) {
ArrayList<Integer> al = new ArrayList<Integer>();
while (last != -1) {
al.add(last);
last = prev[last];
}
return al;
}
public int[] getPrev() {
return prev;
}
public long[] getDistance() {
return dist;
}
public boolean[] getVisited() {
return visited;
}
}
class Edge implements Comparable<Edge> {
int to;
long dist;
Edge(int t, long d) {
to = t;
dist = d;
}
public int compareTo(Edge other) {
return Long.compare(dist, other.dist);
}
}
private void solve() throws IOException {
int N = nextInt();
int M = nextInt();
int K = nextInt();
ArrayList<Edge>[] g = new ArrayList[N];
ArrayList<Edge>[] g2 = new ArrayList[N];
long[] dist = new long[N];
boolean[] visited = new boolean[N];
for (int i = 0; i < N; i++) {
g[i] = new ArrayList<Edge>();
g2[i] = new ArrayList<Edge>();
dist[i] = Long.MAX_VALUE;
}
for (int i = 0; i < M; i++) {
int f = nextInt() - 1;
int t = nextInt() - 1;
long w = nextLong();
g[f].add(new Edge(t, w));
g[t].add(new Edge(f, w));
}
for (int i = 0; i < K; i++) {
int t = nextInt() - 1;
long w = nextLong();
g[0].add(new Edge(t, w));
g2[t].add(new Edge(0, w));
}
PriorityQueue<Edge> pq = new PriorityQueue<Edge>();
dist[0] = 0;
pq.add(new Edge(0, 0));
int ans = 0;
while (!pq.isEmpty()) {
Edge e = pq.poll();
int to = e.to;
if (visited[to]) {
continue;
}
visited[to] = true;
long currDist = Long.MAX_VALUE;
for (Edge ee : g[to]) {
if (dist[ee.to] != Long.MAX_VALUE) {
currDist = Math.min(dist[ee.to] + ee.dist, currDist);
}
}
if (currDist == dist[to] || to == 0) {
ans += g2[to].size();
} else {
ans += g2[to].size() - 1;
}
for (Edge ee : g[to]) {
if (dist[ee.to] > dist[to] + ee.dist) {
dist[ee.to] = dist[to] + ee.dist;
pq.add(new Edge(ee.to, dist[ee.to]));
}
}
}
out.println(ans);
}
boolean isSorted(ArrayList<Integer> al) {
int size = al.size();
for (int i = 1; i < size - 2; i++) {
if (al.get(i) > al.get(i + 1)) {
return false;
}
}
return true;
}
/**
* SHUFFLE: shuffle the array 'a' of size 'N'
*/
private void shuffle(int[] a, int N) {
for (int i = 0; i < N; i++) {
int r = i + (int) ((N - i) * Math.random());
int t = a[i];
a[i] = a[r];
a[r] = t;
}
}
/**
* TEMPLATE-STUFF: main method, run method - ( fileIO and stdIO ) and
* various methods for input like nextInt, nextLong, nextToken and
* nextDouble with some declarations.
*/
/**
* For solution to the problem ... see the solve method
*/
public static void main(String[] args) {
new Main().run();
}
public void run() {
try {
in = new BufferedReader(new FileReader("D-large.in"));
out = new PrintWriter(new BufferedWriter(new FileWriter("Main.out")));
tok = null;
solve();
in.close();
out.close();
System.exit(0);
} catch (IOException e) {//(FileNotFoundException e) {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new OutputStreamWriter(System.out));
tok = null;
solve();
in.close();
out.close();
System.exit(0);
} catch (IOException ex) {
System.out.println(ex.getMessage());
System.exit(0);
}
}
}
private String nextToken() throws IOException {
while (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
private int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
private long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
private double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
BufferedReader in;
StringTokenizer tok;
PrintWriter out;
}
| Java | ["5 5 3\n1 2 1\n2 3 2\n1 3 3\n3 4 4\n1 5 5\n3 5\n4 5\n5 5", "2 2 3\n1 2 2\n2 1 3\n2 1\n2 2\n2 3"] | 2 seconds | ["2", "2"] | null | Java 7 | standard input | [
"graphs",
"greedy",
"shortest paths"
] | 03d6b61be6ca0ac9dd8259458f41da59 | The first line contains three integers n, m, k (2 ≤ n ≤ 105; 1 ≤ m ≤ 3·105; 1 ≤ k ≤ 105). Each of the next m lines contains three integers ui, vi, xi (1 ≤ ui, vi ≤ n; ui ≠ vi; 1 ≤ xi ≤ 109). Each of the next k lines contains two integers si and yi (2 ≤ si ≤ n; 1 ≤ yi ≤ 109). It is guaranteed that there is at least one way from every city to the capital. Note, that there can be multiple roads between two cities. Also, there can be multiple routes going to the same city from the capital. | 2,000 | Output a single integer representing the maximum number of the train routes which can be closed. | standard output | |
PASSED | cd5bf8cbd74f8a2dd4326d8fe004f493 | train_001.jsonl | 1405774800 | Jzzhu is the president of country A. There are n cities numbered from 1 to n in his country. City 1 is the capital of A. Also there are m roads connecting the cities. One can go from city ui to vi (and vise versa) using the i-th road, the length of this road is xi. Finally, there are k train routes in the country. One can use the i-th train route to go from capital of the country to city si (and vise versa), the length of this route is yi.Jzzhu doesn't want to waste the money of the country, so he is going to close some of the train routes. Please tell Jzzhu the maximum number of the train routes which can be closed under the following condition: the length of the shortest path from every city to the capital mustn't change. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
public class B {
private static final long INF = 1000000000000000l;
public int solve(int n, int m, int k, List<Edge> edgeList, int[][] routes) {
Map<Integer, List<Edge>> edgeMap = new HashMap<Integer, List<Edge>>();
for (Edge edge : edgeList) {
if (!edgeMap.containsKey(edge.from))
edgeMap.put(edge.from, new ArrayList<Edge>());
edgeMap.get(edge.from).add(edge);
}
List<Edge> elist0 = edgeMap.get(0);
if (elist0==null)
edgeMap.put(0, elist0=new ArrayList<Edge>());
for (int i=0; i<k; i++) {
List<Edge> elist = edgeMap.get(routes[i][0]);
if (elist==null)
edgeMap.put(routes[i][0], elist=new ArrayList<Edge>());
elist.add(new Edge(routes[i][0], 0, routes[i][1], i));
elist0.add(new Edge(0, routes[i][0], routes[i][1], i));
}
int res = k;
long[] dist = new long[n];
boolean[] visited = new boolean[n];
boolean[] f = new boolean[n];
Arrays.fill(dist, INF);
PriorityQueue<Vertex> que = new PriorityQueue<Vertex>();
que.add(new Vertex(0, 0));
dist[0] = 0;
while (que.size()>0) {
Vertex v = que.poll();
if (visited[v.v])
continue;
visited[v.v] = true;
if (v.route>=0)
res--;
if (edgeMap.containsKey(v.v))
for (Edge edge : edgeMap.get(v.v))
if (dist[v.v]+edge.cost<dist[edge.to]) {
dist[edge.to] = dist[v.v]+edge.cost;
que.add(new Vertex(edge.to, dist[edge.to], edge.route));
if (edge.route>=0)
f[edge.to] = true;
} else if (f[edge.to] && dist[v.v]+edge.cost==dist[edge.to] && edge.route==-1)
que.add(new Vertex(edge.to, dist[edge.to], edge.route));
}
return res;
}
private static class Edge {
private int from, to;
private int cost;
private int route = -1;
private Edge(int from, int to, int cost) {
this.from = from;
this.to = to;
this.cost = cost;
}
private Edge(int from, int to, int cost, int route) {
this.from = from;
this.to = to;
this.cost = cost;
this.route = route;
}
}
private class Vertex implements Comparable<Vertex> {
private int v;
private long cost;
private int route = -1;
private Vertex(int v, long cost) {
this.v = v;
this.cost = cost;
}
private Vertex(int v, long cost, int route) {
this.v = v;
this.cost = cost;
this.route = route;
}
public int compareTo(Vertex v) {
if (this.cost<v.cost)
return -1;
else if (this.cost>v.cost)
return 1;
else if (this.route==-1 && v.route>=0)
return -1;
else if (this.route>=0 && v.route==-1)
return 1;
return 0;
}
}
public static void main(String args[]) throws IOException {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
String[] split = line.split(" ");
int n = Integer.parseInt(split[0]);
int m = Integer.parseInt(split[1]);
int k = Integer.parseInt(split[2]);
List<Edge> edgeList = new ArrayList<>();
for (int i=0; i<m; i++) {
line = br.readLine();
split = line.split(" ");
int u = Integer.parseInt(split[0])-1;
int v = Integer.parseInt(split[1])-1;
int x = Integer.parseInt(split[2]);
edgeList.add(new Edge(u, v, x));
edgeList.add(new Edge(v, u, x));
}
int[][] routes = new int[k][2];
for (int j=0; j<k; j++) {
line = br.readLine();
split = line.split(" ");
routes[j][0] = Integer.parseInt(split[0])-1;
routes[j][1] = Integer.parseInt(split[1]);
}
int res = new B().solve(n, m, k, edgeList, routes);
System.out.println(res);
} finally {
if (br!=null)
br.close();
}
}
} | Java | ["5 5 3\n1 2 1\n2 3 2\n1 3 3\n3 4 4\n1 5 5\n3 5\n4 5\n5 5", "2 2 3\n1 2 2\n2 1 3\n2 1\n2 2\n2 3"] | 2 seconds | ["2", "2"] | null | Java 7 | standard input | [
"graphs",
"greedy",
"shortest paths"
] | 03d6b61be6ca0ac9dd8259458f41da59 | The first line contains three integers n, m, k (2 ≤ n ≤ 105; 1 ≤ m ≤ 3·105; 1 ≤ k ≤ 105). Each of the next m lines contains three integers ui, vi, xi (1 ≤ ui, vi ≤ n; ui ≠ vi; 1 ≤ xi ≤ 109). Each of the next k lines contains two integers si and yi (2 ≤ si ≤ n; 1 ≤ yi ≤ 109). It is guaranteed that there is at least one way from every city to the capital. Note, that there can be multiple roads between two cities. Also, there can be multiple routes going to the same city from the capital. | 2,000 | Output a single integer representing the maximum number of the train routes which can be closed. | standard output | |
PASSED | 2180304e09cd4ba5e45bfaa5feccf2d0 | train_001.jsonl | 1405774800 | Jzzhu is the president of country A. There are n cities numbered from 1 to n in his country. City 1 is the capital of A. Also there are m roads connecting the cities. One can go from city ui to vi (and vise versa) using the i-th road, the length of this road is xi. Finally, there are k train routes in the country. One can use the i-th train route to go from capital of the country to city si (and vise versa), the length of this route is yi.Jzzhu doesn't want to waste the money of the country, so he is going to close some of the train routes. Please tell Jzzhu the maximum number of the train routes which can be closed under the following condition: the length of the shortest path from every city to the capital mustn't change. | 256 megabytes | import java.io.*;
import java.math.*;
import java.util.*;
public class Main{
FastScanner in;
PrintWriter out;
public class Edge {
int to;
long w;
public Edge(int to, long w) {
this.to = to;
this.w = w;
}
}
public class myStruct implements Comparable<myStruct> {
int v;
long dV;
public myStruct(int v, long dV) {
this.v = v;
this.dV = dV;
}
public int compareTo(myStruct o) {
if (o.dV < dV)
return 1;
if (o.dV > dV)
return -1;
if (o.v > v)
return 1;
if (o.v < v)
return -1;
return 0;
}
}
ArrayList<Edge>[] list;
long[] dist;
int[] from;
long[] W;
int[] C;
boolean[] used;
public void dj(int v, int n) {
dist[v] = 0;
TreeSet<myStruct> set = new TreeSet<>();
set.add(new myStruct(v, 0));
for (int i = 0; i < n; i++) {
while (!set.isEmpty() && used[set.first().v]) {
set.remove(set.first());
}
if (set.isEmpty()) break;
myStruct tmp = set.first();
set.remove(tmp);
v = tmp.v;
long d = dist[v];
used[v] = true;
for (Edge to : list[v])
if (!used[to.to]) {
if (dist[to.to] < d + to.w) continue;
if (dist[to.to] == d + to.w)
C[to.to]++;
else {
C[to.to] = 1;
dist[to.to] = d + to.w;
from[to.to] = v;
W[to.to] = to.w;
}
set.add(new myStruct(to.to, dist[to.to]));
}
}
}
public void solve()
{
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
list = new ArrayList[n];
for (int i = 0; i < n; i++) {
list[i] = new ArrayList<>();
}
for (int i = 0; i < m; i++) {
int a = in.nextInt()-1;
int b = in.nextInt()-1;
int w = in.nextInt();
list[a].add(new Edge(b, w));
list[b].add(new Edge(a, w));
}
int[] train = new int[n];
int[] cnt = new int[n];
for (int i = 0; i < n; i++) {
train[i] = (int)1e9+1;
cnt[i] = 0;
}
for (int i = 0; i < k; i++) {
int s = in.nextInt()-1;
int w = in.nextInt();
cnt[s]++;
train[s] = Math.min(train[s], w);
}
for (int i = 0; i < n; i++)
if (train[i] < (int)1e9+1) {
list[0].add(new Edge(i, train[i]));
list[i].add(new Edge(0, train[i]));
}
dist = new long[n];
from = new int[n];
W = new long[n];
C = new int[n];
used = new boolean[n];
for (int i = 0; i < n; i++) {
dist[i] = (long)1e18+1;
from[i] = -1;
W[i] = dist[i];
C[i] = 0;
used[i] = false;
}
dj(0, n);
//for (int i = 0; i < n; i++) {
// out.print(dist[i] + " ");
//}
//out.println();
int ans = k;
for (int i = 0; i < n; i++)
if (train[i] < (int)1e9+1) {
if (from[i] == 0 && W[i] == train[i] && C[i] == 1)
ans--;
}
out.println(ans);
}
public void run()
{
in = new FastScanner();
out = new PrintWriter(System.out);
solve();
out.close();
}
public static void main(String[] args) {
new Main().run();
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
} | Java | ["5 5 3\n1 2 1\n2 3 2\n1 3 3\n3 4 4\n1 5 5\n3 5\n4 5\n5 5", "2 2 3\n1 2 2\n2 1 3\n2 1\n2 2\n2 3"] | 2 seconds | ["2", "2"] | null | Java 7 | standard input | [
"graphs",
"greedy",
"shortest paths"
] | 03d6b61be6ca0ac9dd8259458f41da59 | The first line contains three integers n, m, k (2 ≤ n ≤ 105; 1 ≤ m ≤ 3·105; 1 ≤ k ≤ 105). Each of the next m lines contains three integers ui, vi, xi (1 ≤ ui, vi ≤ n; ui ≠ vi; 1 ≤ xi ≤ 109). Each of the next k lines contains two integers si and yi (2 ≤ si ≤ n; 1 ≤ yi ≤ 109). It is guaranteed that there is at least one way from every city to the capital. Note, that there can be multiple roads between two cities. Also, there can be multiple routes going to the same city from the capital. | 2,000 | Output a single integer representing the maximum number of the train routes which can be closed. | standard output | |
PASSED | 02b3ec41311288e21d1a0c6a44058e0a | train_001.jsonl | 1405774800 | Jzzhu is the president of country A. There are n cities numbered from 1 to n in his country. City 1 is the capital of A. Also there are m roads connecting the cities. One can go from city ui to vi (and vise versa) using the i-th road, the length of this road is xi. Finally, there are k train routes in the country. One can use the i-th train route to go from capital of the country to city si (and vise versa), the length of this route is yi.Jzzhu doesn't want to waste the money of the country, so he is going to close some of the train routes. Please tell Jzzhu the maximum number of the train routes which can be closed under the following condition: the length of the shortest path from every city to the capital mustn't change. | 256 megabytes | //package CF;
import java.util.*;
import java.io.*;
public class CFD_257 {
static long[] dis = new long[500010] ;
static boolean[] parent = new boolean[500010] ;
static boolean[] vis = new boolean[100010];
static int n,m,k,sol=0;
static long OO = 1000000000000000L ;
static HashSet<Integer> hash = new HashSet<Integer>();
static ArrayList<ArrayList<Pair>> adj = new ArrayList<ArrayList<Pair>>();
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out));
StringTokenizer st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
m = Integer.parseInt(st.nextToken());
k = Integer.parseInt(st.nextToken());
for (int i = 0; i <= n; i++)
adj.add(new ArrayList<Pair>());
int a,b,w;
for (int i = 0; i < m; i++) {
st = new StringTokenizer(br.readLine());
a = Integer.parseInt(st.nextToken());
b = Integer.parseInt(st.nextToken());
w = Integer.parseInt(st.nextToken());
adj.get(a).add(new Pair(b,w,false));
adj.get(b).add(new Pair(a,w,false));
}
for (int i = 0; i < k; i++) {
st = new StringTokenizer(br.readLine());
b = Integer.parseInt(st.nextToken());
w = Integer.parseInt(st.nextToken());
adj.get(1).add(new Pair(b,w,true));
}
dijkestra();
for (int i = 2; i <= n; i++)
if(parent[i]) sol++;
pw.println(k-sol);
pw.close();
br.close();
}
static void dijkestra()
{
Arrays.fill(dis, OO);
dis[1] = 0; // source
PriorityQueue<Pair> q = new PriorityQueue<Pair>();
q.add(new Pair(1,0,false));
Pair cur ;
while(!q.isEmpty())
{
cur = q.poll();
if(vis[cur.a]) continue ;
vis[cur.a] = true ;
for (Pair pair : adj.get(cur.a)) {
long dist = pair.b+cur.b;
if(dist<=dis[pair.a])
{
if(dist<dis[pair.a])
parent[pair.a] = pair.train ;
else if(dist == dis[pair.a] && !pair.train)
parent[pair.a] = false;
dis[pair.a] = dist ;
q.add(new Pair(pair.a,dist,pair.train));
}
}
}
}
public static class Pair implements Comparable<Pair>
{
int a;
long b;
boolean train ;
Pair(int a,long b, boolean t)
{
this.a = a;
this.b = b;
train = t;
}
public int compareTo(Pair o)
{
if(this.b==o.b){
if(!(this.train^o.train))
return 0;
else if(this.train)
return 1;
else return -1;
}
long ret = this.b - o.b ;
return ret>0 ?1:-1;
}
}
}
| Java | ["5 5 3\n1 2 1\n2 3 2\n1 3 3\n3 4 4\n1 5 5\n3 5\n4 5\n5 5", "2 2 3\n1 2 2\n2 1 3\n2 1\n2 2\n2 3"] | 2 seconds | ["2", "2"] | null | Java 7 | standard input | [
"graphs",
"greedy",
"shortest paths"
] | 03d6b61be6ca0ac9dd8259458f41da59 | The first line contains three integers n, m, k (2 ≤ n ≤ 105; 1 ≤ m ≤ 3·105; 1 ≤ k ≤ 105). Each of the next m lines contains three integers ui, vi, xi (1 ≤ ui, vi ≤ n; ui ≠ vi; 1 ≤ xi ≤ 109). Each of the next k lines contains two integers si and yi (2 ≤ si ≤ n; 1 ≤ yi ≤ 109). It is guaranteed that there is at least one way from every city to the capital. Note, that there can be multiple roads between two cities. Also, there can be multiple routes going to the same city from the capital. | 2,000 | Output a single integer representing the maximum number of the train routes which can be closed. | standard output | |
PASSED | 18044f9ef0c72c4aa58552f063997eb5 | train_001.jsonl | 1386943200 | There are n kangaroos with pockets. Each kangaroo has a size (integer number). A kangaroo can go into another kangaroo's pocket if and only if the size of kangaroo who hold the kangaroo is at least twice as large as the size of kangaroo who is held.Each kangaroo can hold at most one kangaroo, and the kangaroo who is held by another kangaroo cannot hold any kangaroos.The kangaroo who is held by another kangaroo cannot be visible from outside. Please, find a plan of holding kangaroos with the minimal number of kangaroos who is visible. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class C {
static BufferedReader in;
static StringTokenizer st;
static PrintWriter out;
public static void main(String[] args) throws IOException {
begin();
solve();
end();
}
private static void end() {
out.close();
}
private static void solve() throws IOException {
int n = nextInt();
int []arr = new int [n];
for (int i = 0; i < arr.length; i++) {
arr[i] = nextInt();
}
Arrays.sort(arr);
int ans = n;
int right = n/2;
for (int i = 0; i < n/2; i++) {
boolean f = false;
for (int j = right; j < n; j++) {
if (arr[i]*2 <= arr[j]){
ans--;
right = ++j;
f = true;
break;
}
}
if (!f) break;
}
System.out.println(ans);
}
private static long nextLong() throws IOException {
return Long.parseLong(next());
}
private static void writeln(Object t) {
out.println(t);
}
private static void write(Object t) {
out.print(t);
}
private static int nextInt() throws IOException {
return Integer.parseInt(next());
}
private static String next() throws IOException {
while (!st.hasMoreElements())
st = new StringTokenizer(in.readLine());
return st.nextToken();
}
private static void begin() {
out = new PrintWriter(new OutputStreamWriter(System.out));
st = new StringTokenizer("");
in = new BufferedReader(new InputStreamReader(System.in));
}
}
| Java | ["8\n2\n5\n7\n6\n9\n8\n4\n2", "8\n9\n1\n6\n2\n6\n5\n8\n3"] | 1 second | ["5", "5"] | null | Java 7 | standard input | [
"two pointers",
"sortings",
"greedy"
] | 361f65484d86051fa9ff013f5e8c9154 | The first line contains a single integer — n (1 ≤ n ≤ 5·105). Each of the next n lines contains an integer si — the size of the i-th kangaroo (1 ≤ si ≤ 105). | 1,600 | Output a single integer — the optimal number of visible kangaroos. | standard output | |
PASSED | 3e4fb727c990ec0faf1a1a08c5195186 | train_001.jsonl | 1386943200 | There are n kangaroos with pockets. Each kangaroo has a size (integer number). A kangaroo can go into another kangaroo's pocket if and only if the size of kangaroo who hold the kangaroo is at least twice as large as the size of kangaroo who is held.Each kangaroo can hold at most one kangaroo, and the kangaroo who is held by another kangaroo cannot hold any kangaroos.The kangaroo who is held by another kangaroo cannot be visible from outside. Please, find a plan of holding kangaroos with the minimal number of kangaroos who is visible. | 256 megabytes | import static java.util.Arrays.deepToString;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main {
static void solve() throws Exception {
int n = nextInt();
int[] a = new int[n];
for(int i = 0; i < n; i++) {
a[i] = nextInt();
}
Arrays.sort(a);
int cnt = 0;
int p1 = (n % 2 == 0) ? n / 2 - 1 : n / 2;
int p2 = n - 1;
int x = p1;
while(true) {
if(p1 < 0 || p2 == x) {
break;
}
if(a[p2] >= a[p1] * 2 && cnt + 1 <= n / 2) {
p1--;
p2--;
cnt++;
continue;
}
while(p1 >= 0 && a[p2] < a[p1] * 2) {
p1--;
}
}
out.println(n - cnt);
}
static BufferedReader br;
static StringTokenizer tokenizer;
static PrintWriter out;
static void debug(Object... a) {
System.err.println(deepToString(a));
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static String next() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
String line = br.readLine();
if (line == null) {
return null;
}
tokenizer = new StringTokenizer(line);
}
return tokenizer.nextToken();
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public static void main(String[] args) {
try {
File file = new File("stupid_rmq.in");
InputStream input = System.in;
OutputStream output = System.out;
if (file.canRead()) {
input = (new FileInputStream(file));
output = (new PrintStream("stupid_rmq.out"));
}
br = new BufferedReader(new InputStreamReader(input));
out = new PrintWriter(output);
solve();
out.close();
br.close();
} catch (Throwable e) {
e.printStackTrace();
System.exit(1);
}
}
} | Java | ["8\n2\n5\n7\n6\n9\n8\n4\n2", "8\n9\n1\n6\n2\n6\n5\n8\n3"] | 1 second | ["5", "5"] | null | Java 7 | standard input | [
"two pointers",
"sortings",
"greedy"
] | 361f65484d86051fa9ff013f5e8c9154 | The first line contains a single integer — n (1 ≤ n ≤ 5·105). Each of the next n lines contains an integer si — the size of the i-th kangaroo (1 ≤ si ≤ 105). | 1,600 | Output a single integer — the optimal number of visible kangaroos. | standard output | |
PASSED | 0fed5485f9eaaccd433d4a3059455951 | train_001.jsonl | 1386943200 | There are n kangaroos with pockets. Each kangaroo has a size (integer number). A kangaroo can go into another kangaroo's pocket if and only if the size of kangaroo who hold the kangaroo is at least twice as large as the size of kangaroo who is held.Each kangaroo can hold at most one kangaroo, and the kangaroo who is held by another kangaroo cannot hold any kangaroos.The kangaroo who is held by another kangaroo cannot be visible from outside. Please, find a plan of holding kangaroos with the minimal number of kangaroos who is visible. | 256 megabytes | import java.util.Arrays;
import java.util.Scanner;
public class C_219 {
static int[] s;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
s= new int[n];
for(int i = 0; i < n; i++){
s[i] = in.nextInt();
}
Arrays.sort(s);
//System.out.println(Arrays.toString(s));
int hi = n;
int lo = (n+1)/2;
while(lo < hi){
int mid = (hi+lo)/2;
//System.out.println("mid="+mid);
if(possible(mid)){
hi = mid;
//System.out.println("pos");
} else{
lo = mid+1;
//System.out.println("not pos");
}
}
System.out.println(hi);
}
private static boolean possible(int visible) {
int hidden = s.length-visible;
int n = s.length;
for(int i = 0; i < hidden; i++){
if(2*s[i] > s[n-hidden+i]){
return false;
} else {
//System.out.println(2*s[i] +" <= "+ s[n-hidden+i]);
}
}
return true;
}
}
| Java | ["8\n2\n5\n7\n6\n9\n8\n4\n2", "8\n9\n1\n6\n2\n6\n5\n8\n3"] | 1 second | ["5", "5"] | null | Java 7 | standard input | [
"two pointers",
"sortings",
"greedy"
] | 361f65484d86051fa9ff013f5e8c9154 | The first line contains a single integer — n (1 ≤ n ≤ 5·105). Each of the next n lines contains an integer si — the size of the i-th kangaroo (1 ≤ si ≤ 105). | 1,600 | Output a single integer — the optimal number of visible kangaroos. | standard output | |
PASSED | a71544529d5d9c855ed7a736679e48c6 | train_001.jsonl | 1386943200 | There are n kangaroos with pockets. Each kangaroo has a size (integer number). A kangaroo can go into another kangaroo's pocket if and only if the size of kangaroo who hold the kangaroo is at least twice as large as the size of kangaroo who is held.Each kangaroo can hold at most one kangaroo, and the kangaroo who is held by another kangaroo cannot hold any kangaroos.The kangaroo who is held by another kangaroo cannot be visible from outside. Please, find a plan of holding kangaroos with the minimal number of kangaroos who is visible. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {public static void main(String[] args) throws Exception {new Solve();}}
class Solve { public Solve() throws Exception {solve();}
static BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st = new StringTokenizer("");
void solve() throws Exception {
int n = NI();
List <Integer> a = new ArrayList<Integer>(n);
while(n-->0)
a.add(NI());
Collections.sort(a);
int bigI = a.size() - 1, smallS = a.get(bigI) >> 1, smallI = a.size() / 2 - 1, beg = 0, end = bigI >> 1, res = a.size(), t;
while (smallI >= 0 && a.get(smallI) > smallS)
smallI--;
// while (end - beg > 1) {
// smallI = beg + ((end - beg) >> 1);
// if (a.get(smallI) > smallS)
// end = --smallI;
// else
// beg = ++smallI;
// }
t = smallI;
while(smallI >= 0 && bigI > t) {
while (smallI >= 0 && a.get(bigI) >> 1 < a.get(smallI))
smallI--;
if (smallI >= 0) {
res--;
bigI--;
smallI--;
}
}
System.out.println(res);
}
class Pair {
}
int min(int i1, int i2) {return i1 < i2 ? i1 : i2;}
long min(long i1, long i2) {return i1 < i2 ? i1 : i2;}
int max(int i1, int i2) {return i1 > i2 ? i1 : i2;}
long max(long i1, long i2) {return i1 > i2 ? i1 : i2;}
public String NS() throws Exception {
while (!st.hasMoreTokens()) st = new StringTokenizer(stdin.readLine());
return st.nextToken();}
public int NI() throws Exception {return Integer.parseInt(NS());}
public long NL() throws Exception {return Long.parseLong(NS());}
int abs(int x) {return x < 0 ? -x : x;}
} | Java | ["8\n2\n5\n7\n6\n9\n8\n4\n2", "8\n9\n1\n6\n2\n6\n5\n8\n3"] | 1 second | ["5", "5"] | null | Java 7 | standard input | [
"two pointers",
"sortings",
"greedy"
] | 361f65484d86051fa9ff013f5e8c9154 | The first line contains a single integer — n (1 ≤ n ≤ 5·105). Each of the next n lines contains an integer si — the size of the i-th kangaroo (1 ≤ si ≤ 105). | 1,600 | Output a single integer — the optimal number of visible kangaroos. | standard output | |
PASSED | ac5cfd1b2c3ed0de0251a0c6a3d9efc5 | train_001.jsonl | 1386943200 | There are n kangaroos with pockets. Each kangaroo has a size (integer number). A kangaroo can go into another kangaroo's pocket if and only if the size of kangaroo who hold the kangaroo is at least twice as large as the size of kangaroo who is held.Each kangaroo can hold at most one kangaroo, and the kangaroo who is held by another kangaroo cannot hold any kangaroos.The kangaroo who is held by another kangaroo cannot be visible from outside. Please, find a plan of holding kangaroos with the minimal number of kangaroos who is visible. | 256 megabytes | //package C;
import java.util.Arrays;
import java.util.Scanner;
public class C {
void run() {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int [] l = new int[n+1];
for(int a=1;a<=n;a++) l[a] = sc.nextInt();
int j = n;
int ans = 0;
Arrays.sort(l);
for(int i = n/2;i>=1&&j>n/2;i--){
if(l[i]*2<=l[j]){
ans++;
j--;
}
}
System.out.println(n-ans);
}
void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
public static void main(String[] args) {
new C().run();
}
}
| Java | ["8\n2\n5\n7\n6\n9\n8\n4\n2", "8\n9\n1\n6\n2\n6\n5\n8\n3"] | 1 second | ["5", "5"] | null | Java 7 | standard input | [
"two pointers",
"sortings",
"greedy"
] | 361f65484d86051fa9ff013f5e8c9154 | The first line contains a single integer — n (1 ≤ n ≤ 5·105). Each of the next n lines contains an integer si — the size of the i-th kangaroo (1 ≤ si ≤ 105). | 1,600 | Output a single integer — the optimal number of visible kangaroos. | standard output | |
PASSED | e232398f478aefe712d24c2b04062f4f | train_001.jsonl | 1456506900 | Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if the sequence consists of at least two elements f0 and f1 are arbitrary fn + 2 = fn + 1 + fn for all n ≥ 0. You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence. | 512 megabytes | import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class MainD {
MyScanner sc = new MyScanner();
Scanner sc2 = new Scanner(System.in);
long start = System.currentTimeMillis();
long fin = System.currentTimeMillis();
final int MOD = 1000000007;
int[] dx = { 1, 0, 0, -1 };
int[] dy = { 0, 1, -1, 0 };
void run() {
int n = sc.nextInt();
int[] a = new int[n];
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
Map<Integer, Map<Integer, Integer>> cash = new HashMap<Integer, Map<Integer, Integer>>();
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
map.put(a[i], map.containsKey(a[i]) ? map.get(a[i]) + 1 : 1);
}
int longest = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j) continue;
if (cash.containsKey(a[i]) && cash.get(a[i]).containsKey(a[j])) continue;
Map<Integer, Integer> use = new HashMap<Integer, Integer>();
int step = 2;
int pre1 = a[i];
int pre2 = a[j];
int next = pre1 + pre2;
use.put(pre1, 1);
use.put(pre2, 1);
while (true) {
if (!map.containsKey(next) || (use.containsKey(next) && map.get(next) - use.get(next) <= 0)) {
break;
}
use.put(next, use.containsKey(next) ? use.get(next) + 1 : 1);
if (pre1 == 0 && pre2 == 0) {
step += map.get(0) - 2;
break;
}
step++;
int tmp = pre2;
pre1 = pre2;
pre2 = next;
next += tmp;
}
if (cash.containsKey(a[i])) {
Map<Integer, Integer> tmp = cash.get(a[i]);
tmp.put(a[j], step);
cash.put(a[i], tmp);
} else {
Map<Integer, Integer> tmp = new HashMap<Integer, Integer>();
tmp.put(a[j], step);
cash.put(a[i], tmp);
}
longest = Math.max(longest, step);
}
}
System.out.println(longest);
}
public static void main(String[] args) {
new MainD().run();
}
void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
void debug2(long[][] array) {
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j]);
}
System.out.println();
}
}
boolean inner(int h, int w, int limH, int limW) {
return 0 <= h && h < limH && 0 <= w && w < limW;
}
void swap(char[] x, int a, int b) {
char tmp = x[a];
x[a] = x[b];
x[b] = tmp;
}
// find minimum i (k <= a[i])
int lower_bound(int a[], int k) {
int l = -1;
int r = a.length;
while (r - l > 1) {
int mid = (l + r) / 2;
if (k <= a[mid])
r = mid;
else
l = mid;
}
// r = l + 1
return r;
}
// find minimum i (k < a[i])
int upper_bound(int a[], int k) {
int l = -1;
int r = a.length;
while (r - l > 1) {
int mid = (l + r) / 2;
if (k < a[mid])
r = mid;
else
l = mid;
}
// r = l + 1
return r;
}
int gcd(int a, int b) {
return a % b == 0 ? b : gcd(b, a % b);
}
int lcm(int a, int b) {
return a * b / gcd(a, b);
}
boolean palindrome(String s) {
for (int i = 0; i < s.length() / 2; i++) {
if (s.charAt(i) != s.charAt(s.length() - 1 - i)) {
return false;
}
}
return true;
}
class MyScanner {
int nextInt() {
try {
int c = System.in.read();
while (c != '-' && (c < '0' || '9' < c))
c = System.in.read();
if (c == '-')
return -nextInt();
int res = 0;
do {
res *= 10;
res += c - '0';
c = System.in.read();
} while ('0' <= c && c <= '9');
return res;
} catch (Exception e) {
return -1;
}
}
double nextDouble() {
return Double.parseDouble(next());
}
long nextLong() {
return Long.parseLong(next());
}
String next() {
try {
StringBuilder res = new StringBuilder("");
int c = System.in.read();
while (Character.isWhitespace(c))
c = System.in.read();
do {
res.append((char) c);
} while (!Character.isWhitespace(c = System.in.read()));
return res.toString();
} catch (Exception e) {
return null;
}
}
int[] nextIntArray(int n) {
int[] in = new int[n];
for (int i = 0; i < n; i++) {
in[i] = nextInt();
}
return in;
}
int[][] nextInt2dArray(int n, int m) {
int[][] in = new int[n][m];
for (int i = 0; i < n; i++) {
in[i] = nextIntArray(m);
}
return in;
}
double[] nextDoubleArray(int n) {
double[] in = new double[n];
for (int i = 0; i < n; i++) {
in[i] = nextDouble();
}
return in;
}
long[] nextLongArray(int n) {
long[] in = new long[n];
for (int i = 0; i < n; i++) {
in[i] = nextLong();
}
return in;
}
char[][] nextCharField(int n, int m) {
char[][] in = new char[n][m];
for (int i = 0; i < n; i++) {
String s = sc.next();
for (int j = 0; j < m; j++) {
in[i][j] = s.charAt(j);
}
}
return in;
}
}
} | Java | ["3\n1 2 -1", "5\n28 35 7 14 21"] | 3 seconds | ["3", "4"] | NoteIn the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.In the second sample, the optimal way to rearrange elements is , , , , 28. | Java 7 | standard input | [
"dp",
"hashing",
"math",
"implementation",
"brute force"
] | 98348af1203460b3f69239d3e8f635b9 | The first line of the input contains a single integer n (2 ≤ n ≤ 1000) — the length of the sequence ai. The second line contains n integers a1, a2, ..., an (|ai| ≤ 109). | 2,000 | Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement. | standard output | |
PASSED | 71727ea0c16991da713fe411343261a2 | train_001.jsonl | 1456506900 | Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if the sequence consists of at least two elements f0 and f1 are arbitrary fn + 2 = fn + 1 + fn for all n ≥ 0. You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence. | 512 megabytes | import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class MainD {
Scanner sc = new Scanner(System.in);
void run() {
int n = sc.nextInt();
int[] a = new int[n];
int M = 1000000000;
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
Set<Long> cash = new HashSet<Long>();
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
map.put(a[i], map.containsKey(a[i]) ? map.get(a[i]) + 1 : 1);
}
int longest = Math.max(2, map.containsKey(0) ? map.get(0) : 0);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j || (a[i] == 0) && a[j] == 0) continue;
if (cash.contains(a[i] + (1L * a[j] * M))) continue;
Map<Integer, Integer> use = new HashMap<Integer, Integer>();
int step = 2;
int pre1 = a[i];
int pre2 = a[j];
int next = pre1 + pre2;
use.put(pre1, 1);
use.put(pre2, 1);
while (true) {
if (!map.containsKey(next) || (use.containsKey(next) && map.get(next) - use.get(next) <= 0)) {
break;
}
use.put(next, use.containsKey(next) ? use.get(next) + 1 : 1);
step++;
int tmp = pre2;
pre1 = pre2;
pre2 = next;
next += tmp;
}
cash.add(a[i] + (1L * a[j] * M));
longest = Math.max(longest, step);
}
}
System.out.println(longest);
}
public static void main(String[] args) {
new MainD().run();
}
} | Java | ["3\n1 2 -1", "5\n28 35 7 14 21"] | 3 seconds | ["3", "4"] | NoteIn the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.In the second sample, the optimal way to rearrange elements is , , , , 28. | Java 7 | standard input | [
"dp",
"hashing",
"math",
"implementation",
"brute force"
] | 98348af1203460b3f69239d3e8f635b9 | The first line of the input contains a single integer n (2 ≤ n ≤ 1000) — the length of the sequence ai. The second line contains n integers a1, a2, ..., an (|ai| ≤ 109). | 2,000 | Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement. | standard output | |
PASSED | d2d6fe3feec75ff1a947e12bf0c8ba4c | train_001.jsonl | 1456506900 | Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if the sequence consists of at least two elements f0 and f1 are arbitrary fn + 2 = fn + 1 + fn for all n ≥ 0. You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence. | 512 megabytes | import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class MainD {
MyScanner sc = new MyScanner();
Scanner sc2 = new Scanner(System.in);
long start = System.currentTimeMillis();
long fin = System.currentTimeMillis();
final int MOD = 1000000007;
int[] dx = { 1, 0, 0, -1 };
int[] dy = { 0, 1, -1, 0 };
void run() {
int n = sc.nextInt();
int[] a = new int[n];
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
Set<Long> cash = new HashSet<Long>();
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
map.put(a[i], map.containsKey(a[i]) ? map.get(a[i]) + 1 : 1);
}
int longest = Math.max(2, map.containsKey(0) ? map.get(0) : 0);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j || (a[i] == 0) && a[j] == 0) continue;
if (cash.contains(a[i] + (1L * a[j] * MOD))) continue;
Map<Integer, Integer> use = new HashMap<Integer, Integer>();
int step = 2;
int pre1 = a[i];
int pre2 = a[j];
int next = pre1 + pre2;
use.put(pre1, 1);
use.put(pre2, 1);
while (true) {
if (!map.containsKey(next) || (use.containsKey(next) && map.get(next) - use.get(next) <= 0)) {
break;
}
use.put(next, use.containsKey(next) ? use.get(next) + 1 : 1);
step++;
int tmp = pre2;
pre1 = pre2;
pre2 = next;
next += tmp;
}
cash.add(a[i] + (1L * a[j] * MOD));
longest = Math.max(longest, step);
}
}
System.out.println(longest);
}
public static void main(String[] args) {
new MainD().run();
}
void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
void debug2(long[][] array) {
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j]);
}
System.out.println();
}
}
boolean inner(int h, int w, int limH, int limW) {
return 0 <= h && h < limH && 0 <= w && w < limW;
}
void swap(char[] x, int a, int b) {
char tmp = x[a];
x[a] = x[b];
x[b] = tmp;
}
// find minimum i (k <= a[i])
int lower_bound(int a[], int k) {
int l = -1;
int r = a.length;
while (r - l > 1) {
int mid = (l + r) / 2;
if (k <= a[mid])
r = mid;
else
l = mid;
}
// r = l + 1
return r;
}
// find minimum i (k < a[i])
int upper_bound(int a[], int k) {
int l = -1;
int r = a.length;
while (r - l > 1) {
int mid = (l + r) / 2;
if (k < a[mid])
r = mid;
else
l = mid;
}
// r = l + 1
return r;
}
int gcd(int a, int b) {
return a % b == 0 ? b : gcd(b, a % b);
}
int lcm(int a, int b) {
return a * b / gcd(a, b);
}
boolean palindrome(String s) {
for (int i = 0; i < s.length() / 2; i++) {
if (s.charAt(i) != s.charAt(s.length() - 1 - i)) {
return false;
}
}
return true;
}
class MyScanner {
int nextInt() {
try {
int c = System.in.read();
while (c != '-' && (c < '0' || '9' < c))
c = System.in.read();
if (c == '-')
return -nextInt();
int res = 0;
do {
res *= 10;
res += c - '0';
c = System.in.read();
} while ('0' <= c && c <= '9');
return res;
} catch (Exception e) {
return -1;
}
}
double nextDouble() {
return Double.parseDouble(next());
}
long nextLong() {
return Long.parseLong(next());
}
String next() {
try {
StringBuilder res = new StringBuilder("");
int c = System.in.read();
while (Character.isWhitespace(c))
c = System.in.read();
do {
res.append((char) c);
} while (!Character.isWhitespace(c = System.in.read()));
return res.toString();
} catch (Exception e) {
return null;
}
}
int[] nextIntArray(int n) {
int[] in = new int[n];
for (int i = 0; i < n; i++) {
in[i] = nextInt();
}
return in;
}
int[][] nextInt2dArray(int n, int m) {
int[][] in = new int[n][m];
for (int i = 0; i < n; i++) {
in[i] = nextIntArray(m);
}
return in;
}
double[] nextDoubleArray(int n) {
double[] in = new double[n];
for (int i = 0; i < n; i++) {
in[i] = nextDouble();
}
return in;
}
long[] nextLongArray(int n) {
long[] in = new long[n];
for (int i = 0; i < n; i++) {
in[i] = nextLong();
}
return in;
}
char[][] nextCharField(int n, int m) {
char[][] in = new char[n][m];
for (int i = 0; i < n; i++) {
String s = sc.next();
for (int j = 0; j < m; j++) {
in[i][j] = s.charAt(j);
}
}
return in;
}
}
} | Java | ["3\n1 2 -1", "5\n28 35 7 14 21"] | 3 seconds | ["3", "4"] | NoteIn the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.In the second sample, the optimal way to rearrange elements is , , , , 28. | Java 7 | standard input | [
"dp",
"hashing",
"math",
"implementation",
"brute force"
] | 98348af1203460b3f69239d3e8f635b9 | The first line of the input contains a single integer n (2 ≤ n ≤ 1000) — the length of the sequence ai. The second line contains n integers a1, a2, ..., an (|ai| ≤ 109). | 2,000 | Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement. | standard output | |
PASSED | df48ac6fdb801470a003dad5c03c34fe | train_001.jsonl | 1456506900 | Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if the sequence consists of at least two elements f0 and f1 are arbitrary fn + 2 = fn + 1 + fn for all n ≥ 0. You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence. | 512 megabytes | import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class MainD {
Scanner sc = new Scanner(System.in);
void run() {
int n = sc.nextInt();
int[] a = new int[n];
int M = 1000000000;
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
Set<Long> cash = new HashSet<Long>();
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
map.put(a[i], map.containsKey(a[i]) ? map.get(a[i]) + 1 : 1);
}
int longest = Math.max(2, map.containsKey(0) ? map.get(0) : 0);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j || (a[i] == 0) && a[j] == 0) continue;
if (cash.contains(a[i] + (1L * a[j] * M))) continue;
Map<Integer, Integer> use = new HashMap<Integer, Integer>();
int step = 2;
int pre1 = a[i];
int pre2 = a[j];
int next = pre1 + pre2;
use.put(pre1, 1);
use.put(pre2, 1);
while (true) {
if (!map.containsKey(next) || (use.containsKey(next) && map.get(next) - use.get(next) <= 0)) {
break;
}
use.put(next, use.containsKey(next) ? use.get(next) + 1 : 1);
step++;
int tmp = pre2;
pre1 = pre2;
pre2 = next;
next += tmp;
}
cash.add(a[i] + (1L * a[j] * M));
longest = Math.max(longest, step);
}
}
System.out.println(longest);
}
public static void main(String[] args) {
new MainD().run();
}
} | Java | ["3\n1 2 -1", "5\n28 35 7 14 21"] | 3 seconds | ["3", "4"] | NoteIn the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.In the second sample, the optimal way to rearrange elements is , , , , 28. | Java 7 | standard input | [
"dp",
"hashing",
"math",
"implementation",
"brute force"
] | 98348af1203460b3f69239d3e8f635b9 | The first line of the input contains a single integer n (2 ≤ n ≤ 1000) — the length of the sequence ai. The second line contains n integers a1, a2, ..., an (|ai| ≤ 109). | 2,000 | Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement. | standard output | |
PASSED | 97cb1b71ca5ce8d9be758cff590d5132 | train_001.jsonl | 1456506900 | Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if the sequence consists of at least two elements f0 and f1 are arbitrary fn + 2 = fn + 1 + fn for all n ≥ 0. You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence. | 512 megabytes | import java.io.*;
import java.util.*;
public class d {
public static void main(String[] args) throws IOException {
input.init(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = input.nextInt();
int[] as = new int[n];
long oo = (long)2e9+7;
for(int i = 0; i<n; i++) as[i] = input.nextInt();
HashSet<Long> used = new HashSet<Long>();
HashMap<Integer, Integer> fs = new HashMap<Integer, Integer>();
HashMap<Integer, Integer> seq = new HashMap<Integer, Integer>();
for(int i = 0; i<n; i++)
{
fs.put(as[i], fs.containsKey(as[i]) ? (1+fs.get(as[i])) : 1);
seq.put(as[i], 0);
}
int res = 0;
for(int i = 0; i<n; i++)
for(int j = 0; j<n; j++)
{
if(i == j) continue;
long key = as[i]*oo + as[j];
if(used.contains(key)) continue;
used.add(key);
int cur = 2;
seq.put(as[i], 1);
seq.put(as[j], as[i] == as[j] ? 2 : 1);
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(as[i]);
list.add(as[j]);
int a = as[i], b = as[j];
while(true)
{
//System.out.println(a+" "+b);
key = a*oo+b;
used.add(key);
if(Math.abs(a+b) > 1e9) break;
int next = a+b;
if(fs.containsKey(next) && fs.get(next) > seq.get(next))
{
list.add(next);
seq.put(next, seq.get(next)+1);
cur++;
a = b;
b = next;
}
else break;
}
for(int x : list) seq.put(x, 0);
res = Math.max(res, cur);
}
out.println(res);
out.close();
}
public static class input {
static BufferedReader reader;
static StringTokenizer tokenizer;
static void init(InputStream input) {
reader = new BufferedReader(new InputStreamReader(input));
tokenizer = new StringTokenizer("");
}
static String next() throws IOException {
while (!tokenizer.hasMoreTokens())
tokenizer = new StringTokenizer(reader.readLine());
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
}
}
| Java | ["3\n1 2 -1", "5\n28 35 7 14 21"] | 3 seconds | ["3", "4"] | NoteIn the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.In the second sample, the optimal way to rearrange elements is , , , , 28. | Java 7 | standard input | [
"dp",
"hashing",
"math",
"implementation",
"brute force"
] | 98348af1203460b3f69239d3e8f635b9 | The first line of the input contains a single integer n (2 ≤ n ≤ 1000) — the length of the sequence ai. The second line contains n integers a1, a2, ..., an (|ai| ≤ 109). | 2,000 | Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement. | standard output | |
PASSED | b698280213e06a053c640c14975bcc65 | train_001.jsonl | 1456506900 | Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if the sequence consists of at least two elements f0 and f1 are arbitrary fn + 2 = fn + 1 + fn for all n ≥ 0. You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence. | 512 megabytes | import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
long CC = (long)1e10 + 7;
int n = stdin.nextInt();
long[] a = new long[n];
HashSet<Long> set = new HashSet<>();
HashMap<Long, Integer> map = new HashMap<>();
for (int i = 0; i < n; i++) {
a[i] = stdin.nextLong();
map.put(a[i], map.containsKey(a[i]) ? map.get(a[i]) + 1 : 1);
}
int ans = 2;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
if (i == j) continue;
long KEY = CC * a[i] + a[j];
if (set.contains(KEY)) continue;
set.add(KEY);
long a1 = a[i];
long a2 = a[j];
map.put(a[i], map.get(a[i]) - 1);
map.put(a[j], map.get(a[j]) - 1);
int tmp = 2;
for(;;) {
long a3 = a1 + a2;
if (map.containsKey(a3) && map.get(a3) > 0) {
tmp++;
map.put(a3, map.get(a3) - 1);
a1 = a2;
a2 = a3;
} else
break;
}
ans = Math.max(ans, tmp);
a1 = a[i];
a2 = a[j];
map.put(a[i], map.get(a[i]) + 1);
map.put(a[j], map.get(a[j]) + 1);
for (int k = 2; k < tmp; k++) {
long a3 = a1 + a2;
map.put(a3, map.get(a3) + 1);
a1 = a2;
a2 = a3;
}
}
System.out.println(ans);
}
}
| Java | ["3\n1 2 -1", "5\n28 35 7 14 21"] | 3 seconds | ["3", "4"] | NoteIn the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.In the second sample, the optimal way to rearrange elements is , , , , 28. | Java 7 | standard input | [
"dp",
"hashing",
"math",
"implementation",
"brute force"
] | 98348af1203460b3f69239d3e8f635b9 | The first line of the input contains a single integer n (2 ≤ n ≤ 1000) — the length of the sequence ai. The second line contains n integers a1, a2, ..., an (|ai| ≤ 109). | 2,000 | Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement. | standard output | |
PASSED | 9307a405896d3c4becbd4d3f51356813 | train_001.jsonl | 1456506900 | Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if the sequence consists of at least two elements f0 and f1 are arbitrary fn + 2 = fn + 1 + fn for all n ≥ 0. You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence. | 512 megabytes | import java.io.*;
import java.util.*;
public class D {
FastScanner in;
PrintWriter out;
void solve() {
int n = in.nextInt();
long[] a = new long[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
int ans = 0;
Set<Long> vis = new HashSet<>();
Map<Long, Integer> multiset = new HashMap<>();
for (int i = 0; i < n; i++) {
if (!multiset.containsKey(a[i])) {
multiset.put(a[i], 0);
}
multiset.put(a[i], multiset.get(a[i]) + 1);
}
long MAX = (long) 1e10;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j) {
continue;
}
long mask = 1L * MAX * a[i] + a[j];
if (vis.contains(mask)) {
continue;
}
vis.add(mask);
int cur = 2;
add(multiset, a[i], -1);
add(multiset, a[j], -1);
long a1 = a[i], a2 = a[j];
while (true) {
long a3 = a1 + a2;
if (multiset.containsKey(a3) && multiset.get(a3) > 0) {
cur++;
add(multiset, a3, -1);
a1 = a2;
a2 = a3;
} else {
break;
}
}
ans = Math.max(ans, cur);
a1 = a[i];
a2 = a[j];
add(multiset, a1, 1);
add(multiset, a2, 1);
for (int t = 2; t < cur; t++) {
long a3 = a1 + a2;
add(multiset, a3, 1);
a1 = a2;
a2 = a3;
}
}
}
out.println(ans);
}
private void add(Map<Long, Integer> multiset, long i, int delta) {
multiset.put(i, multiset.get(i) + delta);
}
void runIO() {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
solve();
out.close();
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f));
}
String next() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
boolean hasMoreTokens() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return false;
st = new StringTokenizer(s);
}
return true;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
public static void main(String[] args) {
new D().runIO();
}
} | Java | ["3\n1 2 -1", "5\n28 35 7 14 21"] | 3 seconds | ["3", "4"] | NoteIn the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.In the second sample, the optimal way to rearrange elements is , , , , 28. | Java 7 | standard input | [
"dp",
"hashing",
"math",
"implementation",
"brute force"
] | 98348af1203460b3f69239d3e8f635b9 | The first line of the input contains a single integer n (2 ≤ n ≤ 1000) — the length of the sequence ai. The second line contains n integers a1, a2, ..., an (|ai| ≤ 109). | 2,000 | Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement. | standard output | |
PASSED | aedd65f9d74aef5922ad592842c6da6f | train_001.jsonl | 1456506900 | Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if the sequence consists of at least two elements f0 and f1 are arbitrary fn + 2 = fn + 1 + fn for all n ≥ 0. You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence. | 512 megabytes | //package fibonacci;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
public class Test {
/**
* @param args
*/
static int[] filter(int t[], int size) {
int i = 0, res[] = new int[size];
for (int v : t) {
if (i >= size)
break;
res[i++] = v;
}
return res;
}
static void alnaser() {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Integer a[] = new Integer[n];
int neg=0;
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
if(a[i]<0)
neg++;
}
Arrays.sort(a);
for (int i : a)
System.out.print(i + ",");
System.out.println();
if(neg>0)
Arrays.sort(a, 0, neg, Collections.reverseOrder());
// Arrays.sort(a);
for (int i : a)
System.out.print(i + ",");
System.out.println();
List<int[]> list = new ArrayList<>();
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n; j++) {
if (i != j) {
int i1 = 2, inc = 0, tab[] = new int[n];
tab[0] = a[i];
tab[1] = a[j];
while (inc < n) {
if (tab[i1 - 2] + tab[i1 - 1] != a[inc]) {
inc++;
continue;
}
tab[i1++] = a[inc++];
}
// for(int x:tab)
// System.out.print(x+",");
// System.out.println();
list.add(filter(tab, i1));
}
}
}
int max = 0;
for (int[] t : list) {
if (max < t.length)
max = t.length;
// for (int i : t) {
// System.out.print(i + ",");
// }
// System.out.println();
}
System.out.println(max);
}
public static void main(String[] args) {
solve();
//alnaser();
}
static int[] remove(int[] a) {
ArrayList<Integer> res = new ArrayList<>();
for (int x : a) {
int sz = res.size();
if (sz >= 3 && res.get(sz - 1) == x && res.get(sz - 2) == x
&& res.get(sz - 3) == x) {
continue;
}
res.add(x);
}
int[] result = new int[res.size()];
for (int i = 0; i < result.length; i++) {
result[i] = res.get(i);
}
return result;
}
static void solve() {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
Arrays.sort(a);
int cnt0 = 0;
for (int i = 0; i < n; i++) {
if (a[i] == 0) {
cnt0++;
}
}
int res = Math.max(cnt0, 2);
a = remove(a);
n = a.length;
int[][] go = new int[n][n];
for (int i = 0; i < n; i++) {
int it = 0;
for (int j = 0; j < n; j++) {
int need = a[i] + a[j];
while (it < n && a[it] < need) {
it++;
}
go[i][j] = it;
}
}
// for (int i[] : go) {
// for (int j : i) {
// System.out.format("%3d", j);
// }
// System.out.println();
// }
int[] lastTime = new int[n];
int time = 0;
for (int f = 0; f < n; f++) {
for (int s = 0; s < n; s++) {
if (f != s && (a[f] != 0 || a[s] != 0)) {
time++;
lastTime[f] = time;
lastTime[s] = time;
int c1 = f, c2 = s;
int sz = 2;
while (true) {
int ne = go[c1][c2];
int need = a[c1] + a[c2];
while (ne < n && a[ne] == need && lastTime[ne] == time) {
ne++;
}
if (ne < n && a[ne] == need && lastTime[ne] < time) {
c1 = c2;
c2 = ne;
lastTime[ne] = time;
sz++;
} else {
break;
}
}
res = Math.max(res, sz);
}
}
}
System.out.println(res);
}
}
| Java | ["3\n1 2 -1", "5\n28 35 7 14 21"] | 3 seconds | ["3", "4"] | NoteIn the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.In the second sample, the optimal way to rearrange elements is , , , , 28. | Java 7 | standard input | [
"dp",
"hashing",
"math",
"implementation",
"brute force"
] | 98348af1203460b3f69239d3e8f635b9 | The first line of the input contains a single integer n (2 ≤ n ≤ 1000) — the length of the sequence ai. The second line contains n integers a1, a2, ..., an (|ai| ≤ 109). | 2,000 | Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement. | standard output | |
PASSED | 34f637420f531d00e82f162ced14396f | train_001.jsonl | 1456506900 | Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if the sequence consists of at least two elements f0 and f1 are arbitrary fn + 2 = fn + 1 + fn for all n ≥ 0. You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence. | 512 megabytes | import java.io.*;
import java.util.*;
public class Solution {
private BufferedReader in;
private StringTokenizer line;
private PrintWriter out;
private static final int mm = 1000000007;
public void solve() throws IOException {
int n = nextInt();
int[] a = nextIntArray(n);
Arrays.sort(a);
HashMap<Integer, Integer> b = new HashMap<>();
for (int i = 0; i < n; ) {
int j = i;
while (i < n && a[i] == a[j]) {
i++;
}
b.put(a[j], i - j);
}
int res = 2;
if (b.containsKey(0)) {
res = Math.max(res, b.get(0));
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i != j && !(a[i] == 0 && a[j] == 0)) {
int first = a[i];
int second = a[j];
HashMap<Integer, Integer> c = new HashMap<>();
addAndComp(b, c, first);
addAndComp(b, c, second);
int r = 2;
while (true) {
if (addAndComp(b, c, first + second)) {
r++;
int t = first + second;
first = second;
second = t;
} else {
break;
}
}
res = Math.max(res, r);
}
}
}
out.println(res);
}
private boolean remove(HashMap<Integer, Integer> a, Integer i) {
Integer c = a.get(i);
if (c == null) return false;
if (c > 1) {
a.put(i, c - 1);
} else {
a.remove(i);
}
return true;
}
private boolean addAndComp(HashMap<Integer, Integer> b, HashMap<Integer, Integer> c, Integer i) {
Integer cnt = c.get(i);
if (cnt == null) {
cnt = 1;
} else {
cnt++;
}
c.put(i, cnt);
Integer cnt2 = b.get(i);
if (cnt2 == null) {
return false;
}
return cnt <= cnt2;
}
public static void main(String[] args) throws IOException {
new Solution().run(args);
}
public void run(String[] args) throws IOException {
if (args.length > 0 && "DEBUG_MODE".equals(args[0])) {
in = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt")));
} else {
in = new BufferedReader(new InputStreamReader(System.in));
}
out = new PrintWriter(System.out);
// out = new PrintWriter("output.txt");
// int t = nextInt();
int t = 1;
for (int i = 0; i < t; i++) {
// out.print("Case #" + (i + 1) + ": ");
solve();
}
in.close();
out.flush();
out.close();
}
private int[] nextIntArray(int n) throws IOException {
int[] res = new int[n];
for (int i = 0; i < n; i++) {
res[i] = nextInt();
}
return res;
}
private long[] nextLongArray(int n) throws IOException {
long[] res = new long[n];
for (int i = 0; i < n; i++) {
res[i] = nextInt();
}
return res;
}
private int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
private long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
private double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
private String nextToken() throws IOException {
while (line == null || !line.hasMoreTokens()) {
line = new StringTokenizer(in.readLine());
}
return line.nextToken();
}
private static class Pii {
private int key;
private int value;
public Pii(int key, int value) {
this.key = key;
this.value = value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pii pii = (Pii) o;
if (key != pii.key) return false;
return value == pii.value;
}
@Override
public int hashCode() {
int result = key;
result = 31 * result + value;
return result;
}
}
private static class Pair<K, V> {
private K key;
private V value;
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair<?, ?> pair = (Pair<?, ?>) o;
if (key != null ? !key.equals(pair.key) : pair.key != null) return false;
return !(value != null ? !value.equals(pair.value) : pair.value != null);
}
@Override
public int hashCode() {
int result = key != null ? key.hashCode() : 0;
result = 31 * result + (value != null ? value.hashCode() : 0);
return result;
}
}
} | Java | ["3\n1 2 -1", "5\n28 35 7 14 21"] | 3 seconds | ["3", "4"] | NoteIn the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.In the second sample, the optimal way to rearrange elements is , , , , 28. | Java 7 | standard input | [
"dp",
"hashing",
"math",
"implementation",
"brute force"
] | 98348af1203460b3f69239d3e8f635b9 | The first line of the input contains a single integer n (2 ≤ n ≤ 1000) — the length of the sequence ai. The second line contains n integers a1, a2, ..., an (|ai| ≤ 109). | 2,000 | Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement. | standard output | |
PASSED | db0b39f0a63cfbe011213d49e7315f2d | train_001.jsonl | 1456506900 | Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if the sequence consists of at least two elements f0 and f1 are arbitrary fn + 2 = fn + 1 + fn for all n ≥ 0. You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence. | 512 megabytes | import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.io.*;
import java.util.*;
public class ManthanD
{
private static StringTokenizer st;
public static void nextLine(BufferedReader br) throws IOException
{
st = new StringTokenizer(br.readLine());
}
public static int nextInt()
{
return Integer.parseInt(st.nextToken());
}
public static String next()
{
return st.nextToken();
}
public static long nextLong()
{
return Long.parseLong(st.nextToken());
}
public static double nextDouble()
{
return Double.parseDouble(st.nextToken());
}
static long[] a;
static HashMap<Long, Integer> map;
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
nextLine(br);
int n = nextInt();
nextLine(br);
a = new long[n];
map = new HashMap<Long, Integer>();
int zeros = 0;
for (int i = 0; i < n; i++)
{
a[i] = nextLong();
if (!map.containsKey(a[i]))
{
map.put(a[i], 1);
}
else
{
map.put(a[i], map.get(a[i]) + 1);
}
if (a[i] == 0)
{
zeros++;
}
}
int best = 0;
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (a[i] == 0 && a[j] == 0)
{
best = Math.max(best, zeros);
continue;
}
best = Math.max(best, test(a[i], a[j]));
best = Math.max(best, test(a[j], a[i]));
}
}
System.out.println(best);
}
static int test(long a, long b)
{
long c = a + b;
int ans = 2;
HashMap<Long, Integer> map2 = new HashMap<Long, Integer>();
map2.put(a, 1);
if (a != b)
{
map2.put(b, 1);
}
else
{
map2.put(a, 2);
}
while (Math.abs(c) < 1000000001)
{
Integer count = map.get(c);
if (count == null)
{
break;
}
Integer count2 = map2.get(c);
if (count2 == null)
{
map2.put(c, 1);
}
else
{
if (count2 >= count)
{
break;
}
map2.put(c, count2 + 1);
}
long d = b + c;
b = c;
c = d;
ans++;
}
return ans;
}
} | Java | ["3\n1 2 -1", "5\n28 35 7 14 21"] | 3 seconds | ["3", "4"] | NoteIn the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.In the second sample, the optimal way to rearrange elements is , , , , 28. | Java 7 | standard input | [
"dp",
"hashing",
"math",
"implementation",
"brute force"
] | 98348af1203460b3f69239d3e8f635b9 | The first line of the input contains a single integer n (2 ≤ n ≤ 1000) — the length of the sequence ai. The second line contains n integers a1, a2, ..., an (|ai| ≤ 109). | 2,000 | Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement. | standard output | |
PASSED | b0a55b8ff29d5681924c2a0b22b3c9af | train_001.jsonl | 1456506900 | Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if the sequence consists of at least two elements f0 and f1 are arbitrary fn + 2 = fn + 1 + fn for all n ≥ 0. You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence. | 512 megabytes | import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Vector;
public class D {
class Pair {
int a, b;
public Pair(int a, int b) {
this.a = a;
this.b = b;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Pair))
return false;
Pair p = (Pair)o;
return a == p.a && b == p.b;
}
@Override
public int hashCode() {
return a * 10003 + b;
}
}
public static final boolean DEBUG = false;
String filename = "";
Scanner sc;
PrintWriter pw;
public void debug(Object o) {
if (DEBUG) {
int ln = Thread.currentThread().getStackTrace()[2].getLineNumber();
String fn = Thread.currentThread().getStackTrace()[2].getFileName();
System.out.println("(" + fn + ":" + ln + "): " + o);
}
}
public void pln(Object o) {
System.out.println(o);
}
int n;
HashMap<Integer, Integer> h;
HashSet<Pair> set = new HashSet<Pair>();
int[] v;
Vector<Integer> sol = new Vector<Integer>();
int simulate(int a, int b) {
Pair pair = new Pair(a, b);
if (set.contains(pair)) {
return 0;
}
set.add(pair);
if (!h.containsKey(a + b)) {
return 2;
}
sol.clear();
sol.add(a); sol.add(b);
h.put(a, h.get(a) - 1);
h.put(b, h.get(b) - 1);
int crt = 2;
while (true) {
int c = a + b;
Integer nr = h.get(c);
if (nr != null && nr != 0) {
crt++;
a = b;
b = c;
h.put(c, nr - 1);
sol.add(c);
} else {
break;
}
}
for (int val: sol) {
h.put(val, h.get(val) + 1);
}
return crt;
}
public void solve() {
n = sc.nextInt();
h = new HashMap<Integer, Integer>();
v = new int[n];
int numZeros = 0;
for (int i = 0; i < n; i++) {
v[i] = sc.nextInt();
Integer n = h.get(v[i]);
if (n == null) n = 0;
h.put(v[i], n + 1);
if (v[i] == 0) numZeros++;
}
int result = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j) continue;
if ((v[i] > 0 && v[j] > 0)
|| (v[i] < 0 && v[j] < 0)) {
if (h.containsKey(v[j] - v[i])) {
continue;
}
}
if (v[i] == 0 && v[j] == 0) {
if (numZeros > result) {
result = numZeros;
}
continue;
}
int crt = simulate(v[i], v[j]);
if (crt > result) {
result = crt;
}
}
}
pw.println(result);
}
public void run() throws FileNotFoundException {
if (filename.isEmpty()) {
sc = new Scanner(System.in);
pw = new PrintWriter(System.out);
} else {
sc = new Scanner(new File(filename + ".in"));
pw = new PrintWriter(new File(filename + ".out"));
}
solve();
pw.close();
sc.close();
}
public static void main(String[] args) {
D t = new D();
try {
t.run();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
} | Java | ["3\n1 2 -1", "5\n28 35 7 14 21"] | 3 seconds | ["3", "4"] | NoteIn the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.In the second sample, the optimal way to rearrange elements is , , , , 28. | Java 7 | standard input | [
"dp",
"hashing",
"math",
"implementation",
"brute force"
] | 98348af1203460b3f69239d3e8f635b9 | The first line of the input contains a single integer n (2 ≤ n ≤ 1000) — the length of the sequence ai. The second line contains n integers a1, a2, ..., an (|ai| ≤ 109). | 2,000 | Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement. | standard output | |
PASSED | f96964a30ed179650f13d00de9c57e31 | train_001.jsonl | 1456506900 | Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if the sequence consists of at least two elements f0 and f1 are arbitrary fn + 2 = fn + 1 + fn for all n ≥ 0. You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence. | 512 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map.Entry;
import java.util.Random;
import java.util.TreeMap;
public class D {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
long arr[] = new long[n];
String[] parts = br.readLine().split(" ");
for (int i = 0; i < n; i++) {
arr[i] = Long.parseLong(parts[i]);
}
int res = 0;
HashMap<Long, Integer> map = new HashMap<Long, Integer>();
for (int i = 0; i < n; i++) {
if (!map.containsKey(arr[i]))
map.put(arr[i], 0);
map.put(arr[i], map.get(arr[i]) + 1);
}
boolean zeroCase = false;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j)
continue;
long number1 = arr[i];
long number2 = arr[j];
int counter = 2;
if (number1==0 && number2==0 && zeroCase==true)
break;
if (number1==0 && number2==0)
zeroCase=true;
HashMap<Long, Integer> newMap = new HashMap<Long, Integer>();
if (number1 == number2)
newMap.put(number1, 2);
else {
newMap.put(number1, 1);
newMap.put(number2, 1);
}
while (true) {
long newNumber = number1 + number2;
// System.out.println(newNumber);
Integer upperBound = map.get(newNumber);
if (upperBound == null) {
break;
}
// System.out.println(upperBound);
int tek = 0;
if (newMap.containsKey(newNumber))
tek = newMap.get(newNumber);
tek++;
if (tek > upperBound)
break;
// System.out.println(tek);
newMap.put(newNumber, tek);
number1 = number2;
number2 = newNumber;
counter++;
}
// System.out.println(i+" "+j+" "+counter);
res = Math.max(res, counter);
}
}
System.out.println(res);
}
}
| Java | ["3\n1 2 -1", "5\n28 35 7 14 21"] | 3 seconds | ["3", "4"] | NoteIn the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.In the second sample, the optimal way to rearrange elements is , , , , 28. | Java 7 | standard input | [
"dp",
"hashing",
"math",
"implementation",
"brute force"
] | 98348af1203460b3f69239d3e8f635b9 | The first line of the input contains a single integer n (2 ≤ n ≤ 1000) — the length of the sequence ai. The second line contains n integers a1, a2, ..., an (|ai| ≤ 109). | 2,000 | Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement. | standard output | |
PASSED | c7f1e2f1c9a2f849cb5b55e698f1e3e7 | train_001.jsonl | 1456506900 | Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if the sequence consists of at least two elements f0 and f1 are arbitrary fn + 2 = fn + 1 + fn for all n ≥ 0. You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence. | 512 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.StringTokenizer;
public class D {
public static void main(String [] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
StringTokenizer tokenizer = new StringTokenizer(br.readLine());
long [] a = new long[N];
HashMap<Long, Integer> map = new HashMap<Long, Integer>();
for(int i=0; i<N; i++) {
a[i] = Long.parseLong(tokenizer.nextToken());
Integer val = map.get(a[i]);
if(null == val) val = 0;
++val;
map.put(a[i], val);
}
int sol = 2;
boolean zeroZero = false;
for(int i=0; i<N; ++i) {
for(int j=0; j<N; ++j) {
if(i == j) continue;
if(zeroZero && a[i] == a[j] && a[j] == 0) {
continue;
}
if(a[i] == a[j] && a[i] == 0) {
zeroZero = true;
}
int counter = 2;
long lastPlayer = a[i];
long currVal = a[i] + a[j];
HashMap<Long, Integer> currMap = new HashMap<Long, Integer>();
currMap.put(a[i], 1);
if(a[i] == a[j])
currMap.put(a[j],2);
else
currMap.put(a[j], 1);
while(true) {
Integer numTimes = map.get(currVal);
if(null == numTimes) {
break;
}
Integer currNumTimes = currMap.get(currVal);
if(null == currNumTimes)
currNumTimes = 0;
//System.out.println("currNumTimes: " + currNumTimes + " numTimes: " + numTimes);
if(currNumTimes >= numTimes) break;
currMap.put(currVal, 1 + currNumTimes);
long temp = currVal;
currVal+= lastPlayer;
lastPlayer = temp;
++counter;
}
//System.out.println("counter: " + counter);
sol = Math.max(counter, sol);
}
}
System.out.println(sol);
}
} | Java | ["3\n1 2 -1", "5\n28 35 7 14 21"] | 3 seconds | ["3", "4"] | NoteIn the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.In the second sample, the optimal way to rearrange elements is , , , , 28. | Java 7 | standard input | [
"dp",
"hashing",
"math",
"implementation",
"brute force"
] | 98348af1203460b3f69239d3e8f635b9 | The first line of the input contains a single integer n (2 ≤ n ≤ 1000) — the length of the sequence ai. The second line contains n integers a1, a2, ..., an (|ai| ≤ 109). | 2,000 | Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement. | standard output | |
PASSED | 53089de5e22d3ba2ee97fabf4021504d | train_001.jsonl | 1456506900 | Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if the sequence consists of at least two elements f0 and f1 are arbitrary fn + 2 = fn + 1 + fn for all n ≥ 0. You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence. | 512 megabytes | import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.Map.Entry;
import java.util.Queue;
import java.util.Random;
import java.util.Set;
import java.util.SortedSet;
import java.util.Stack;
import java.util.TreeMap;
import java.util.TreeSet;
public class Main
{
/********************************************** a list of common variables **********************************************/
private MyScanner scan = new MyScanner();
private PrintWriter out = new PrintWriter(System.out);
private final long INF = Long.MAX_VALUE;
private final double PI = Math.acos(-1.0);
private final int SIZEN = (int)(1e5);
private final int MOD = (int)(1e9 + 7);
private final int[] DX = {0, 1, 0, -1}, DY = {-1, 0, 1, 0};
private ArrayList<Integer>[] edge;
public void foo()
{
int n = scan.nextInt();
long[] a = new long[n];
HashMap<Long, Integer> hm = new HashMap<Long, Integer>();
int sum0 = 0;
for(int i = 0;i < n;++i)
{
a[i] = scan.nextLong();
hm.put(a[i], hm.containsKey(a[i]) ? hm.get(a[i]) + 1 : 1);
if(0 == a[i]) ++sum0;
}
HashSet<Long> p = new HashSet<Long>();
int ans = sum0;
for(int i = 0;i < n;++i)
{
for(int j = 0;j < n;++j)
{
if(i != j && !(0 == a[i] && 0 == a[j]))
{
long key = 2000000001L * (a[i] + 1000000000) + a[j] + 1000000000;
if(p.contains(key)) continue;
p.add(key);
int cnt = 2;
long x = a[i], y = a[j], z = x + y;
HashMap<Long, Integer> hmNew = new HashMap<Long, Integer>();
hmNew.put(x, hmNew.containsKey(x) ? hmNew.get(x) + 1 : 1);
hmNew.put(y, hmNew.containsKey(y) ? hmNew.get(y) + 1 : 1);
while(hm.containsKey(z) && (!hmNew.containsKey(z) || hmNew.get(z) + 1 <= hm.get(z)))
{
hmNew.put(z, hmNew.containsKey(z) ? hmNew.get(z) + 1 : 1);
x = y;
y = z;
z = x + y;
++cnt;
}
ans = Math.max(ans, cnt);
}
}
}
out.println(ans);
}
public static void main(String[] args)
{
Main m = new Main();
m.foo();
m.out.close();
}
/********************************************** a list of common algorithms **********************************************/
/**
* 1---Get greatest common divisor
* @param a : first number
* @param b : second number
* @return greatest common divisor
*/
public long gcd(long a, long b)
{
return 0 == b ? a : gcd(b, a % b);
}
/**
* 2---Get the distance from a point to a line
* @param x1 the x coordinate of one endpoint of the line
* @param y1 the y coordinate of one endpoint of the line
* @param x2 the x coordinate of the other endpoint of the line
* @param y2 the y coordinate of the other endpoint of the line
* @param x the x coordinate of the point
* @param y the x coordinate of the point
* @return the distance from a point to a line
*/
public double getDist(long x1, long y1, long x2, long y2, long x, long y)
{
long a = y2 - y1;
long b = x1 - x2;
long c = y1 * (x2 - x1) - x1 * (y2 - y1);
return Math.abs(a * x + b * y + c) / Math.sqrt(a * a + b * b);
}
/**
* 3---Get the distance from one point to a segment (not a line)
* @param x1 the x coordinate of one endpoint of the segment
* @param y1 the y coordinate of one endpoint of the segment
* @param x2 the x coordinate of the other endpoint of the segment
* @param y2 the y coordinate of the other endpoint of the segment
* @param x the x coordinate of the point
* @param y the y coordinate of the point
* @return the distance from one point to a segment (not a line)
*/
public double ptToSeg(long x1, long y1, long x2, long y2, long x, long y)
{
double cross = (x2 - x1) * (x - x1) + (y2 - y1) * (y - y1);
if(cross <= 0)
{
return (x - x1) * (x - x1) + (y - y1) * (y - y1);
}
double d = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
if(cross >= d)
{
return (x - x2) * (x - x2) + (y - y2) * (y - y2);
}
double r = cross / d;
double px = x1 + (x2 - x1) * r;
double py = y1 + (y2 - y1) * r;
return (x - px) * (x - px) + (y - py) * (y - py);
}
/**
* 4---KMP match, i.e. kmpMatch("abcd", "bcd") = 1, kmpMatch("abcd", "bfcd") = -1.
* @param t: String to match.
* @param p: String to be matched.
* @return if can match, first index; otherwise -1.
*/
public int kmpMatch(char[] t, char[] p)
{
int n = t.length;
int m = p.length;
int[] next = new int[m + 1];
next[0] = -1;
int j = -1;
for(int i = 1;i < m;++i)
{
while(j >= 0 && p[i] != p[j + 1])
{
j = next[j];
}
if(p[i] == p[j + 1])
{
++j;
}
next[i] = j;
}
j = -1;
for(int i = 0;i < n;++i)
{
while(j >= 0 && t[i] != p[j + 1])
{
j = next[j];
}
if(t[i] == p[j + 1])
{
++j;
}
if(j == m - 1)
{
return i - m + 1;
}
}
return -1;
}
class MyScanner
{
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
BufferedInputStream bis = new BufferedInputStream(System.in);
public int read()
{
if (-1 == numChars)
{
throw new InputMismatchException();
}
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = bis.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if (numChars <= 0)
{
return -1;
}
}
return buf[curChar++];
}
public int nextInt()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if (c < '0' || c > '9')
{
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public 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 & 15;
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 & 15) * m;
c = read();
}
}
return res * sgn;
}
public String next()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private boolean isSpaceChar(int c)
{
return ' ' == c || '\n' == c || '\r' == c || '\t' == c || -1 == c;
}
}
} | Java | ["3\n1 2 -1", "5\n28 35 7 14 21"] | 3 seconds | ["3", "4"] | NoteIn the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.In the second sample, the optimal way to rearrange elements is , , , , 28. | Java 7 | standard input | [
"dp",
"hashing",
"math",
"implementation",
"brute force"
] | 98348af1203460b3f69239d3e8f635b9 | The first line of the input contains a single integer n (2 ≤ n ≤ 1000) — the length of the sequence ai. The second line contains n integers a1, a2, ..., an (|ai| ≤ 109). | 2,000 | Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement. | standard output | |
PASSED | d3cffb2fce2d19ebd3373346c083fce0 | train_001.jsonl | 1397749200 | A boy named Gena really wants to get to the "Russian Code Cup" finals, or at least get a t-shirt. But the offered problems are too complex, so he made an arrangement with his n friends that they will solve the problems for him.The participants are offered m problems on the contest. For each friend, Gena knows what problems he can solve. But Gena's friends won't agree to help Gena for nothing: the i-th friend asks Gena xi rubles for his help in solving all the problems he can. Also, the friend agreed to write a code for Gena only if Gena's computer is connected to at least ki monitors, each monitor costs b rubles.Gena is careful with money, so he wants to spend as little money as possible to solve all the problems. Help Gena, tell him how to spend the smallest possible amount of money. Initially, there's no monitors connected to Gena's computer. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Comparator;
import java.util.StringTokenizer;
public class a {
public static final long oo = (long)2e18;
public static void main(String[] args) throws IOException {
FastScanner in = new FastScanner(System.in);
int n = in.nextInt(), m = in.nextInt();
long b = in.nextLong();
Friend[] fs = new Friend[n];
for(int i=0;i<n;i++) {
fs[i] = new Friend();
fs[i].x = in.nextLong();
fs[i].k = in.nextLong();
int mi = in.nextInt();
for(int j=0;j<mi;j++) {
fs[i].mask |= 1 << (in.nextInt()-1);
}
}
Arrays.sort(fs, Comparator.comparing(f -> f.k));
long[] memo = new long[1<<m];
long ans = oo;
Arrays.fill(memo, oo);
memo[0] = 0;
int M = (1 << m) - 1;
for(int i=0;i<n;i++) {
long cx = fs[i].x, ck = fs[i].k * b;
int cm = fs[i].mask;
for(int mask=M;mask>=0;mask--) {
long cost = memo[mask] + cx;
if(cost >= ans)
continue;
int nmask = cm | mask;
memo[nmask] = Math.min(memo[nmask], cost);
}
ans = Math.min(ans, memo[M] + ck);
}
System.out.println(ans == oo ? -1 : ans);
}
static class Friend {
long x,k;
int mask;
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream i) {
br = new BufferedReader(new InputStreamReader(i));
st = null;
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
if (st == null) {
st = new StringTokenizer(br.readLine());
}
String line = st.nextToken("\n");
st = null;
return line;
}
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 | ["2 2 1\n100 1 1\n2\n100 2 1\n1", "3 2 5\n100 1 1\n1\n100 1 1\n2\n200 1 2\n1 2", "1 2 1\n1 1 1\n1"] | 1 second | ["202", "205", "-1"] | null | Java 8 | standard input | [
"dp",
"sortings",
"bitmasks"
] | bc5b2d1413efcaddbf3bf1d905000159 | The first line contains three integers n, m and b (1 ≤ n ≤ 100; 1 ≤ m ≤ 20; 1 ≤ b ≤ 109) — the number of Gena's friends, the number of problems and the cost of a single monitor. The following 2n lines describe the friends. Lines number 2i and (2i + 1) contain the information about the i-th friend. The 2i-th line contains three integers xi, ki and mi (1 ≤ xi ≤ 109; 1 ≤ ki ≤ 109; 1 ≤ mi ≤ m) — the desired amount of money, monitors and the number of problems the friend can solve. The (2i + 1)-th line contains mi distinct positive integers — the numbers of problems that the i-th friend can solve. The problems are numbered from 1 to m. | 1,900 | Print the minimum amount of money Gena needs to spend to solve all the problems. Or print -1, if this cannot be achieved. | standard output | |
PASSED | 48f015351579bdb6819be90312201171 | train_001.jsonl | 1397749200 | A boy named Gena really wants to get to the "Russian Code Cup" finals, or at least get a t-shirt. But the offered problems are too complex, so he made an arrangement with his n friends that they will solve the problems for him.The participants are offered m problems on the contest. For each friend, Gena knows what problems he can solve. But Gena's friends won't agree to help Gena for nothing: the i-th friend asks Gena xi rubles for his help in solving all the problems he can. Also, the friend agreed to write a code for Gena only if Gena's computer is connected to at least ki monitors, each monitor costs b rubles.Gena is careful with money, so he wants to spend as little money as possible to solve all the problems. Help Gena, tell him how to spend the smallest possible amount of money. Initially, there's no monitors connected to Gena's computer. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Comparator;
import java.util.StringTokenizer;
public class a {
public static final long oo = (long)2e18;
public static void main(String[] args) throws IOException {
FastScanner in = new FastScanner(System.in);
int n = in.nextInt(), m = in.nextInt();
long b = in.nextLong();
Friend[] fs = new Friend[n];
for(int i=0;i<n;i++) {
fs[i] = new Friend();
fs[i].x = in.nextLong();
fs[i].k = in.nextLong();
int mi = in.nextInt();
for(int j=0;j<mi;j++) {
fs[i].mask |= 1 << (in.nextInt()-1);
}
}
Arrays.sort(fs, Comparator.comparing(f -> f.k));
long[] memo = new long[1<<m];
long ans = oo;
Arrays.fill(memo, oo);
memo[0] = 0;
int M = (1 << m) - 1;
for(int i=0;i<n;i++) {
long cx = fs[i].x;
int cm = fs[i].mask;
for(int mask=M;mask>=0;mask--) {
long cur = memo[mask] + cx;
if(cur < memo[cm|mask])
memo[cm|mask] = cur;
}
long cur = fs[i].k * b + memo[M];
if(cur < ans)
ans = cur;
}
System.out.println(ans == oo ? -1 : ans);
}
static class Friend {
long x,k;
int mask;
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream i) {
br = new BufferedReader(new InputStreamReader(i));
st = null;
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
if (st == null) {
st = new StringTokenizer(br.readLine());
}
String line = st.nextToken("\n");
st = null;
return line;
}
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 | ["2 2 1\n100 1 1\n2\n100 2 1\n1", "3 2 5\n100 1 1\n1\n100 1 1\n2\n200 1 2\n1 2", "1 2 1\n1 1 1\n1"] | 1 second | ["202", "205", "-1"] | null | Java 8 | standard input | [
"dp",
"sortings",
"bitmasks"
] | bc5b2d1413efcaddbf3bf1d905000159 | The first line contains three integers n, m and b (1 ≤ n ≤ 100; 1 ≤ m ≤ 20; 1 ≤ b ≤ 109) — the number of Gena's friends, the number of problems and the cost of a single monitor. The following 2n lines describe the friends. Lines number 2i and (2i + 1) contain the information about the i-th friend. The 2i-th line contains three integers xi, ki and mi (1 ≤ xi ≤ 109; 1 ≤ ki ≤ 109; 1 ≤ mi ≤ m) — the desired amount of money, monitors and the number of problems the friend can solve. The (2i + 1)-th line contains mi distinct positive integers — the numbers of problems that the i-th friend can solve. The problems are numbered from 1 to m. | 1,900 | Print the minimum amount of money Gena needs to spend to solve all the problems. Or print -1, if this cannot be achieved. | standard output | |
PASSED | b6eaf9b3739a8a3fa96249c6f7734f33 | train_001.jsonl | 1397749200 | A boy named Gena really wants to get to the "Russian Code Cup" finals, or at least get a t-shirt. But the offered problems are too complex, so he made an arrangement with his n friends that they will solve the problems for him.The participants are offered m problems on the contest. For each friend, Gena knows what problems he can solve. But Gena's friends won't agree to help Gena for nothing: the i-th friend asks Gena xi rubles for his help in solving all the problems he can. Also, the friend agreed to write a code for Gena only if Gena's computer is connected to at least ki monitors, each monitor costs b rubles.Gena is careful with money, so he wants to spend as little money as possible to solve all the problems. Help Gena, tell him how to spend the smallest possible amount of money. Initially, there's no monitors connected to Gena's computer. | 256 megabytes | import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class a {
public static final long oo = (long)2e18;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt(), m = in.nextInt();
long b = in.nextLong();
Friend[] fs = new Friend[n];
for(int i=0;i<n;i++) {
fs[i] = new Friend();
fs[i].x = in.nextLong();
fs[i].k = in.nextLong();
int mi = in.nextInt();
for(int j=0;j<mi;j++) {
fs[i].mask |= 1 << (in.nextInt()-1);
}
}
Arrays.sort(fs, Comparator.comparing(f -> f.k));
long[] memo = new long[1<<m];
long ans = oo;
Arrays.fill(memo, oo);
memo[0] = 0;
int M = (1 << m) - 1;
for(int i=0;i<n;i++) {
long cx = fs[i].x, ck = fs[i].k * b;
int cm = fs[i].mask;
for(int mask=M;mask>=0;mask--) {
long cost = memo[mask] + cx;
if(cost >= ans)
continue;
int nmask = cm | mask;
memo[nmask] = Math.min(memo[nmask], cost);
}
ans = Math.min(ans, memo[M] + ck);
}
System.out.println(ans == oo ? -1 : ans);
}
static class Friend {
long x,k;
int mask;
}
}
| Java | ["2 2 1\n100 1 1\n2\n100 2 1\n1", "3 2 5\n100 1 1\n1\n100 1 1\n2\n200 1 2\n1 2", "1 2 1\n1 1 1\n1"] | 1 second | ["202", "205", "-1"] | null | Java 8 | standard input | [
"dp",
"sortings",
"bitmasks"
] | bc5b2d1413efcaddbf3bf1d905000159 | The first line contains three integers n, m and b (1 ≤ n ≤ 100; 1 ≤ m ≤ 20; 1 ≤ b ≤ 109) — the number of Gena's friends, the number of problems and the cost of a single monitor. The following 2n lines describe the friends. Lines number 2i and (2i + 1) contain the information about the i-th friend. The 2i-th line contains three integers xi, ki and mi (1 ≤ xi ≤ 109; 1 ≤ ki ≤ 109; 1 ≤ mi ≤ m) — the desired amount of money, monitors and the number of problems the friend can solve. The (2i + 1)-th line contains mi distinct positive integers — the numbers of problems that the i-th friend can solve. The problems are numbered from 1 to m. | 1,900 | Print the minimum amount of money Gena needs to spend to solve all the problems. Or print -1, if this cannot be achieved. | standard output | |
PASSED | 2ae807d9a98b56e490e0ef6f477ff6b6 | train_001.jsonl | 1397749200 | A boy named Gena really wants to get to the "Russian Code Cup" finals, or at least get a t-shirt. But the offered problems are too complex, so he made an arrangement with his n friends that they will solve the problems for him.The participants are offered m problems on the contest. For each friend, Gena knows what problems he can solve. But Gena's friends won't agree to help Gena for nothing: the i-th friend asks Gena xi rubles for his help in solving all the problems he can. Also, the friend agreed to write a code for Gena only if Gena's computer is connected to at least ki monitors, each monitor costs b rubles.Gena is careful with money, so he wants to spend as little money as possible to solve all the problems. Help Gena, tell him how to spend the smallest possible amount of money. Initially, there's no monitors connected to Gena's computer. | 256 megabytes | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.Arrays;
import java.util.Comparator;
import java.util.InputMismatchException;
import java.util.StringTokenizer;
public class a {
public static final long oo = (long)2e18;
public static void main(String[] args) throws IOException {
InputReader in = new InputReader(System.in);
OutputWriter out = new OutputWriter(System.out);
int n = in.nextInt(), m = in.nextInt();
long b = in.nextLong();
Friend[] fs = new Friend[n];
for(int i=0;i<n;i++) {
fs[i] = new Friend();
fs[i].x = in.nextLong();
fs[i].k = in.nextLong();
int mi = in.nextInt();
for(int j=0;j<mi;j++) {
fs[i].mask |= 1 << (in.nextInt()-1);
}
}
Arrays.sort(fs, Comparator.comparing(f -> f.k));
long[] memo = new long[1<<m];
long ans = oo;
Arrays.fill(memo, oo);
memo[0] = 0;
int M = (1 << m) - 1;
for(int i=0;i<n;i++) {
long cx = fs[i].x;
int cm = fs[i].mask;
for(int mask=M;mask>=0;mask--) {
long cur = memo[mask] + cx;
int nm = cm|mask;
if(cur < memo[nm])
memo[nm] = cur;
}
long cur = fs[i].k * b + memo[M];
if(cur < ans)
ans = cur;
}
out.printLine(ans == oo ? -1 : ans);
out.close();
}
static class Friend {
long x,k;
int mask;
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream i) {
br = new BufferedReader(new InputStreamReader(i));
st = null;
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
if (st == null) {
st = new StringTokenizer(br.readLine());
}
String line = st.nextToken("\n");
st = null;
return line;
}
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());
}
}
}
class InputReader {
private InputStream stream;
private byte[] buffer = new byte[10000];
private int cur;
private int count;
public InputReader(InputStream stream) {
this.stream = stream;
}
public static boolean isSpace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int read() {
if (count == -1) {
throw new InputMismatchException();
}
try {
if (cur >= count) {
cur = 0;
count = stream.read(buffer);
if (count <= 0)
return -1;
}
} catch (IOException e) {
throw new InputMismatchException();
}
return buffer[cur++];
}
public int readSkipSpace() {
int c;
do {
c = read();
} while (isSpace(c));
return c;
}
public int nextInt() {
int sgn = 1;
int c = readSkipSpace();
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res = res * 10 + c - '0';
c = read();
} while (!isSpace(c));
res *= sgn;
return res;
}
public long nextLong() {
long sgn = 1;
int c = readSkipSpace();
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res = res * 10L + (long)(c - '0');
c = read();
} while (!isSpace(c));
res *= sgn;
return res;
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
} | Java | ["2 2 1\n100 1 1\n2\n100 2 1\n1", "3 2 5\n100 1 1\n1\n100 1 1\n2\n200 1 2\n1 2", "1 2 1\n1 1 1\n1"] | 1 second | ["202", "205", "-1"] | null | Java 8 | standard input | [
"dp",
"sortings",
"bitmasks"
] | bc5b2d1413efcaddbf3bf1d905000159 | The first line contains three integers n, m and b (1 ≤ n ≤ 100; 1 ≤ m ≤ 20; 1 ≤ b ≤ 109) — the number of Gena's friends, the number of problems and the cost of a single monitor. The following 2n lines describe the friends. Lines number 2i and (2i + 1) contain the information about the i-th friend. The 2i-th line contains three integers xi, ki and mi (1 ≤ xi ≤ 109; 1 ≤ ki ≤ 109; 1 ≤ mi ≤ m) — the desired amount of money, monitors and the number of problems the friend can solve. The (2i + 1)-th line contains mi distinct positive integers — the numbers of problems that the i-th friend can solve. The problems are numbered from 1 to m. | 1,900 | Print the minimum amount of money Gena needs to spend to solve all the problems. Or print -1, if this cannot be achieved. | standard output | |
PASSED | 9fdabb80fa994b5f2ec4ac7c9559fbb5 | train_001.jsonl | 1397749200 | A boy named Gena really wants to get to the "Russian Code Cup" finals, or at least get a t-shirt. But the offered problems are too complex, so he made an arrangement with his n friends that they will solve the problems for him.The participants are offered m problems on the contest. For each friend, Gena knows what problems he can solve. But Gena's friends won't agree to help Gena for nothing: the i-th friend asks Gena xi rubles for his help in solving all the problems he can. Also, the friend agreed to write a code for Gena only if Gena's computer is connected to at least ki monitors, each monitor costs b rubles.Gena is careful with money, so he wants to spend as little money as possible to solve all the problems. Help Gena, tell him how to spend the smallest possible amount of money. Initially, there's no monitors connected to Gena's computer. | 256 megabytes | import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class a {
public static final long oo = (long)2e18;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt(), m = in.nextInt();
long b = in.nextLong();
Friend[] fs = new Friend[n];
for(int i=0;i<n;i++) {
fs[i] = new Friend();
fs[i].x = in.nextLong();
fs[i].k = in.nextLong();
int mi = in.nextInt();
for(int j=0;j<mi;j++) {
fs[i].mask |= 1 << (in.nextInt()-1);
}
}
Arrays.sort(fs, Comparator.comparing(f -> f.k));
long[] memo = new long[1<<m];
long ans = oo;
Arrays.fill(memo, oo);
memo[0] = 0;
int M = (1 << m) - 1;
for(int i=0;i<n;i++) {
long cx = fs[i].x, ck = fs[i].k * b;
int cm = fs[i].mask;
for(int mask=M;mask>=0;mask--) {
long cost = memo[mask] + cx;
if(cost >= ans)
continue;
int nmask = cm | mask;
if(nmask == (1<<m)-1)
ans = Math.min(ans, cost + ck);
else
memo[nmask] = Math.min(memo[nmask], cost);
}
}
System.out.println(ans == oo ? -1 : ans);
}
static class Friend {
long x,k;
int mask;
}
}
| Java | ["2 2 1\n100 1 1\n2\n100 2 1\n1", "3 2 5\n100 1 1\n1\n100 1 1\n2\n200 1 2\n1 2", "1 2 1\n1 1 1\n1"] | 1 second | ["202", "205", "-1"] | null | Java 8 | standard input | [
"dp",
"sortings",
"bitmasks"
] | bc5b2d1413efcaddbf3bf1d905000159 | The first line contains three integers n, m and b (1 ≤ n ≤ 100; 1 ≤ m ≤ 20; 1 ≤ b ≤ 109) — the number of Gena's friends, the number of problems and the cost of a single monitor. The following 2n lines describe the friends. Lines number 2i and (2i + 1) contain the information about the i-th friend. The 2i-th line contains three integers xi, ki and mi (1 ≤ xi ≤ 109; 1 ≤ ki ≤ 109; 1 ≤ mi ≤ m) — the desired amount of money, monitors and the number of problems the friend can solve. The (2i + 1)-th line contains mi distinct positive integers — the numbers of problems that the i-th friend can solve. The problems are numbered from 1 to m. | 1,900 | Print the minimum amount of money Gena needs to spend to solve all the problems. Or print -1, if this cannot be achieved. | standard output | |
PASSED | db4fd49906aa55dd4fc2ec38a0528201 | train_001.jsonl | 1397749200 | A boy named Gena really wants to get to the "Russian Code Cup" finals, or at least get a t-shirt. But the offered problems are too complex, so he made an arrangement with his n friends that they will solve the problems for him.The participants are offered m problems on the contest. For each friend, Gena knows what problems he can solve. But Gena's friends won't agree to help Gena for nothing: the i-th friend asks Gena xi rubles for his help in solving all the problems he can. Also, the friend agreed to write a code for Gena only if Gena's computer is connected to at least ki monitors, each monitor costs b rubles.Gena is careful with money, so he wants to spend as little money as possible to solve all the problems. Help Gena, tell him how to spend the smallest possible amount of money. Initially, there's no monitors connected to Gena's computer. | 256 megabytes | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.Arrays;
import java.util.Comparator;
import java.util.InputMismatchException;
import java.util.StringTokenizer;
public class a {
public static final long oo = (long)2e18;
public static void main(String[] args) throws IOException {
InputReader in = new InputReader(System.in);
OutputWriter out = new OutputWriter(System.out);
int n = in.nextInt(), m = in.nextInt();
long b = in.nextLong();
Friend[] fs = new Friend[n];
for(int i=0;i<n;i++) {
fs[i] = new Friend();
fs[i].x = in.nextLong();
fs[i].k = in.nextLong();
int mi = in.nextInt();
for(int j=0;j<mi;j++) {
fs[i].mask |= 1 << (in.nextInt()-1);
}
}
Arrays.sort(fs, Comparator.comparing(f -> f.k));
long[] memo = new long[1<<m];
long ans = oo;
Arrays.fill(memo, oo);
memo[0] = 0;
int M = (1 << m) - 1;
for(int i=0;i<n;i++) {
long cx = fs[i].x;
int cm = fs[i].mask;
for(int mask=0;mask<memo.length;mask++) {
long cur = memo[mask] + cx;
int nm = cm|mask;
if(cur < memo[nm])
memo[nm] = cur;
}
long cur = fs[i].k * b + memo[M];
if(cur < ans)
ans = cur;
}
if(ans >= oo)
ans = -1;
out.printLine(ans);
out.close();
}
static class Friend {
long x,k;
int mask;
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream i) {
br = new BufferedReader(new InputStreamReader(i));
st = null;
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
if (st == null) {
st = new StringTokenizer(br.readLine());
}
String line = st.nextToken("\n");
st = null;
return line;
}
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());
}
}
}
class InputReader {
private InputStream stream;
private byte[] buffer = new byte[10000];
private int cur;
private int count;
public InputReader(InputStream stream) {
this.stream = stream;
}
public static boolean isSpace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int read() {
if (count == -1) {
throw new InputMismatchException();
}
try {
if (cur >= count) {
cur = 0;
count = stream.read(buffer);
if (count <= 0)
return -1;
}
} catch (IOException e) {
throw new InputMismatchException();
}
return buffer[cur++];
}
public int readSkipSpace() {
int c;
do {
c = read();
} while (isSpace(c));
return c;
}
public int nextInt() {
int sgn = 1;
int c = readSkipSpace();
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res = res * 10 + c - '0';
c = read();
} while (!isSpace(c));
res *= sgn;
return res;
}
public long nextLong() {
long sgn = 1;
int c = readSkipSpace();
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res = res * 10L + (long)(c - '0');
c = read();
} while (!isSpace(c));
res *= sgn;
return res;
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
} | Java | ["2 2 1\n100 1 1\n2\n100 2 1\n1", "3 2 5\n100 1 1\n1\n100 1 1\n2\n200 1 2\n1 2", "1 2 1\n1 1 1\n1"] | 1 second | ["202", "205", "-1"] | null | Java 8 | standard input | [
"dp",
"sortings",
"bitmasks"
] | bc5b2d1413efcaddbf3bf1d905000159 | The first line contains three integers n, m and b (1 ≤ n ≤ 100; 1 ≤ m ≤ 20; 1 ≤ b ≤ 109) — the number of Gena's friends, the number of problems and the cost of a single monitor. The following 2n lines describe the friends. Lines number 2i and (2i + 1) contain the information about the i-th friend. The 2i-th line contains three integers xi, ki and mi (1 ≤ xi ≤ 109; 1 ≤ ki ≤ 109; 1 ≤ mi ≤ m) — the desired amount of money, monitors and the number of problems the friend can solve. The (2i + 1)-th line contains mi distinct positive integers — the numbers of problems that the i-th friend can solve. The problems are numbered from 1 to m. | 1,900 | Print the minimum amount of money Gena needs to spend to solve all the problems. Or print -1, if this cannot be achieved. | standard output | |
PASSED | 6f3556f2dca620a7b9421ef169b9620e | train_001.jsonl | 1397749200 | A boy named Gena really wants to get to the "Russian Code Cup" finals, or at least get a t-shirt. But the offered problems are too complex, so he made an arrangement with his n friends that they will solve the problems for him.The participants are offered m problems on the contest. For each friend, Gena knows what problems he can solve. But Gena's friends won't agree to help Gena for nothing: the i-th friend asks Gena xi rubles for his help in solving all the problems he can. Also, the friend agreed to write a code for Gena only if Gena's computer is connected to at least ki monitors, each monitor costs b rubles.Gena is careful with money, so he wants to spend as little money as possible to solve all the problems. Help Gena, tell him how to spend the smallest possible amount of money. Initially, there's no monitors connected to Gena's computer. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Comparator;
import java.util.StringTokenizer;
public class a {
public static final long oo = (long)2e18;
public static void main(String[] args) throws IOException {
FastScanner in = new FastScanner(System.in);
int n = in.nextInt(), m = in.nextInt();
long b = in.nextLong();
Friend[] fs = new Friend[n];
for(int i=0;i<n;i++) {
fs[i] = new Friend();
fs[i].x = in.nextLong();
fs[i].k = in.nextLong();
int mi = in.nextInt();
for(int j=0;j<mi;j++) {
fs[i].mask |= 1 << (in.nextInt()-1);
}
}
Arrays.sort(fs, Comparator.comparing(f -> f.k));
long[] memo = new long[1<<m];
long ans = oo;
Arrays.fill(memo, oo);
memo[0] = 0;
int M = (1 << m) - 1;
for(int i=0;i<n;i++) {
long cx = fs[i].x;
int cm = fs[i].mask;
for(int mask=M;mask>=0;mask--) {
long cur = memo[mask] + cx;
int nm = cm|mask;
if(cur < memo[nm])
memo[nm] = cur;
}
long cur = fs[i].k * b + memo[M];
if(cur < ans)
ans = cur;
}
System.out.println(ans == oo ? -1 : ans);
}
static class Friend {
long x,k;
int mask;
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream i) {
br = new BufferedReader(new InputStreamReader(i));
st = null;
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
if (st == null) {
st = new StringTokenizer(br.readLine());
}
String line = st.nextToken("\n");
st = null;
return line;
}
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 | ["2 2 1\n100 1 1\n2\n100 2 1\n1", "3 2 5\n100 1 1\n1\n100 1 1\n2\n200 1 2\n1 2", "1 2 1\n1 1 1\n1"] | 1 second | ["202", "205", "-1"] | null | Java 8 | standard input | [
"dp",
"sortings",
"bitmasks"
] | bc5b2d1413efcaddbf3bf1d905000159 | The first line contains three integers n, m and b (1 ≤ n ≤ 100; 1 ≤ m ≤ 20; 1 ≤ b ≤ 109) — the number of Gena's friends, the number of problems and the cost of a single monitor. The following 2n lines describe the friends. Lines number 2i and (2i + 1) contain the information about the i-th friend. The 2i-th line contains three integers xi, ki and mi (1 ≤ xi ≤ 109; 1 ≤ ki ≤ 109; 1 ≤ mi ≤ m) — the desired amount of money, monitors and the number of problems the friend can solve. The (2i + 1)-th line contains mi distinct positive integers — the numbers of problems that the i-th friend can solve. The problems are numbered from 1 to m. | 1,900 | Print the minimum amount of money Gena needs to spend to solve all the problems. Or print -1, if this cannot be achieved. | standard output | |
PASSED | 8485f1fad5a5fff2230b1d62c3807c0c | train_001.jsonl | 1397749200 | A boy named Gena really wants to get to the "Russian Code Cup" finals, or at least get a t-shirt. But the offered problems are too complex, so he made an arrangement with his n friends that they will solve the problems for him.The participants are offered m problems on the contest. For each friend, Gena knows what problems he can solve. But Gena's friends won't agree to help Gena for nothing: the i-th friend asks Gena xi rubles for his help in solving all the problems he can. Also, the friend agreed to write a code for Gena only if Gena's computer is connected to at least ki monitors, each monitor costs b rubles.Gena is careful with money, so he wants to spend as little money as possible to solve all the problems. Help Gena, tell him how to spend the smallest possible amount of money. Initially, there's no monitors connected to Gena's computer. | 256 megabytes | import java.util.List;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.util.ArrayList;
import java.util.Comparator;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.Collections;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
static final long inf = (long)(2E18);
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int m = in.nextInt();
long b = in.nextLong();
long[] d = new long[1 << m];
Arrays.fill(d, inf);
d[0] = 0;
ArrayList<Entry> entries = new ArrayList<Entry>();
for (int i = 0; i < n; ++i) {
long cost = in.nextLong();
long cnt = in.nextLong();
int mc = in.nextInt();
int mask = 0;
for (int j = 0; j < mc; ++j)
mask |= (1 << (in.nextInt() - 1));
entries.add(new Entry(cost, cnt, mask));
}
Collections.sort(entries, new Comparator<Entry>() {
@Override
public int compare(Entry entry1, Entry entry2) {
return Long.valueOf(entry1.cnt).compareTo(entry2.cnt);
}
});
long res = inf;
for (int i = 0; i < n; ++i) {
int mask = entries.get(i).mask;
long cost = entries.get(i).money;
for (int j = 0; j < d.length; ++j) {
long val = d[j] + cost;
if (d[j | mask] > val) d[j | mask] = val;
}
long cur = b * entries.get(i).cnt + d[(1 << m) - 1];
if (cur < res) res = cur;
}
if (res >= inf) res = -1;
out.printLine(res);
}
static class Entry {
long money, cnt;
int mask;
Entry(long money, long cnt, int mask) {
this.money = money;
this.cnt = cnt;
this.mask = mask;
}
}
}
class InputReader {
private InputStream stream;
private byte[] buffer = new byte[10000];
private int cur;
private int count;
public InputReader(InputStream stream) {
this.stream = stream;
}
public static boolean isSpace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int read() {
if (count == -1) {
throw new InputMismatchException();
}
try {
if (cur >= count) {
cur = 0;
count = stream.read(buffer);
if (count <= 0)
return -1;
}
} catch (IOException e) {
throw new InputMismatchException();
}
return buffer[cur++];
}
public int readSkipSpace() {
int c;
do {
c = read();
} while (isSpace(c));
return c;
}
public int nextInt() {
int sgn = 1;
int c = readSkipSpace();
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res = res * 10 + c - '0';
c = read();
} while (!isSpace(c));
res *= sgn;
return res;
}
public long nextLong() {
long sgn = 1;
int c = readSkipSpace();
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res = res * 10L + (long)(c - '0');
c = read();
} while (!isSpace(c));
res *= sgn;
return res;
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
} | Java | ["2 2 1\n100 1 1\n2\n100 2 1\n1", "3 2 5\n100 1 1\n1\n100 1 1\n2\n200 1 2\n1 2", "1 2 1\n1 1 1\n1"] | 1 second | ["202", "205", "-1"] | null | Java 8 | standard input | [
"dp",
"sortings",
"bitmasks"
] | bc5b2d1413efcaddbf3bf1d905000159 | The first line contains three integers n, m and b (1 ≤ n ≤ 100; 1 ≤ m ≤ 20; 1 ≤ b ≤ 109) — the number of Gena's friends, the number of problems and the cost of a single monitor. The following 2n lines describe the friends. Lines number 2i and (2i + 1) contain the information about the i-th friend. The 2i-th line contains three integers xi, ki and mi (1 ≤ xi ≤ 109; 1 ≤ ki ≤ 109; 1 ≤ mi ≤ m) — the desired amount of money, monitors and the number of problems the friend can solve. The (2i + 1)-th line contains mi distinct positive integers — the numbers of problems that the i-th friend can solve. The problems are numbered from 1 to m. | 1,900 | Print the minimum amount of money Gena needs to spend to solve all the problems. Or print -1, if this cannot be achieved. | standard output | |
PASSED | 16910a36263bad66f0fbdf74bbb6decf | train_001.jsonl | 1397749200 | A boy named Gena really wants to get to the "Russian Code Cup" finals, or at least get a t-shirt. But the offered problems are too complex, so he made an arrangement with his n friends that they will solve the problems for him.The participants are offered m problems on the contest. For each friend, Gena knows what problems he can solve. But Gena's friends won't agree to help Gena for nothing: the i-th friend asks Gena xi rubles for his help in solving all the problems he can. Also, the friend agreed to write a code for Gena only if Gena's computer is connected to at least ki monitors, each monitor costs b rubles.Gena is careful with money, so he wants to spend as little money as possible to solve all the problems. Help Gena, tell him how to spend the smallest possible amount of money. Initially, there's no monitors connected to Gena's computer. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class CunningGena
{
static int[] can, cost;
static Pair[] monitor;
static int n, m, b;
static long inf = (long) 2l * 1000000 * 1000000 * 1000000;
public static void main(String[] args) throws IOException
{
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
b = sc.nextInt();
can = new int[n];
cost = new int[n];
monitor = new Pair[n];
long[] base = new long[n];
for (int i = 0; i < n; i++)
{
cost[i] = sc.nextInt();
monitor[i] = new Pair(i, sc.nextInt());
int mi = sc.nextInt();
int msk = 0;
for (int j = 0; j < mi; j++)
msk |= (1 << (sc.nextInt() - 1));
can[i] = msk;
base[i] = cost[i] + 1l * monitor[i].m * b;
}
Arrays.sort(monitor);
dp = new long[2][(1<<m)+1];
int p = 0;
Arrays.fill(dp[p], inf);
for (int ind = n - 1; ind >= 0; ind--)
{
p = 1-p;
for (int msk = (1 << m) - 1; msk >= 0; msk--)
{
int k = monitor[ind].ind;
long ans = dp[1-p][msk];
int nwMsk = msk | can[k];
if (nwMsk == (1 << m) - 1)
ans = Math.min(ans, base[k]);
else
ans = Math.min(ans, cost[k] + dp[1-p][nwMsk]);
dp[p][msk] = ans;
}
}
System.out.println(dp[p][0] >= inf ? -1 : dp[p][0]);
}
static long[][] dp;
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s)
{
br = new BufferedReader(new InputStreamReader(s));
}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException
{
return Integer.parseInt(next());
}
public long nextLong() throws IOException
{
return Long.parseLong(next());
}
public String nextLine() throws IOException
{
return br.readLine();
}
public boolean ready() throws IOException
{
return br.ready();
}
}
static class Pair implements Comparable<Pair>
{
int ind, m;
public Pair(int i, int m)
{
ind = i;
this.m = m;
}
public int compareTo(Pair arg0)
{
return m - arg0.m;
}
}
}
| Java | ["2 2 1\n100 1 1\n2\n100 2 1\n1", "3 2 5\n100 1 1\n1\n100 1 1\n2\n200 1 2\n1 2", "1 2 1\n1 1 1\n1"] | 1 second | ["202", "205", "-1"] | null | Java 8 | standard input | [
"dp",
"sortings",
"bitmasks"
] | bc5b2d1413efcaddbf3bf1d905000159 | The first line contains three integers n, m and b (1 ≤ n ≤ 100; 1 ≤ m ≤ 20; 1 ≤ b ≤ 109) — the number of Gena's friends, the number of problems and the cost of a single monitor. The following 2n lines describe the friends. Lines number 2i and (2i + 1) contain the information about the i-th friend. The 2i-th line contains three integers xi, ki and mi (1 ≤ xi ≤ 109; 1 ≤ ki ≤ 109; 1 ≤ mi ≤ m) — the desired amount of money, monitors and the number of problems the friend can solve. The (2i + 1)-th line contains mi distinct positive integers — the numbers of problems that the i-th friend can solve. The problems are numbered from 1 to m. | 1,900 | Print the minimum amount of money Gena needs to spend to solve all the problems. Or print -1, if this cannot be achieved. | standard output | |
PASSED | 7419b40f1c6b4f0aa3b20d2a73459e83 | train_001.jsonl | 1397749200 | A boy named Gena really wants to get to the "Russian Code Cup" finals, or at least get a t-shirt. But the offered problems are too complex, so he made an arrangement with his n friends that they will solve the problems for him.The participants are offered m problems on the contest. For each friend, Gena knows what problems he can solve. But Gena's friends won't agree to help Gena for nothing: the i-th friend asks Gena xi rubles for his help in solving all the problems he can. Also, the friend agreed to write a code for Gena only if Gena's computer is connected to at least ki monitors, each monitor costs b rubles.Gena is careful with money, so he wants to spend as little money as possible to solve all the problems. Help Gena, tell him how to spend the smallest possible amount of money. Initially, there's no monitors connected to Gena's computer. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class CunningGena
{
static int[] can, cost;
static Pair[] monitor;
static int n, m, b;
static long inf = (long) 2l * 1000000 * 1000000 * 1000000;
public static void main(String[] args) throws IOException
{
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
b = sc.nextInt();
can = new int[n];
cost = new int[n];
monitor = new Pair[n];
long[] base = new long[n];
for (int i = 0; i < n; i++)
{
cost[i] = sc.nextInt();
monitor[i] = new Pair(i, sc.nextInt());
int mi = sc.nextInt();
int msk = 0;
for (int j = 0; j < mi; j++)
msk |= (1 << (sc.nextInt() - 1));
can[i] = msk;
base[i] = cost[i] + 1l * monitor[i].m * b;
}
Arrays.sort(monitor);
dp = new long[2][(1 << m) + 1];
int p = 0;
Arrays.fill(dp[p], inf);
for (int ind = n - 1; ind >= 0; ind--)
{
p = 1 - p;
for (int msk = (1 << m) - 1; msk >= 0; msk--)
{
int k = monitor[ind].ind;
long ans = inf;
ans = Math.min(ans, dp[1 - p][msk]);
int nwMsk = msk | can[k];
if (nwMsk == (1 << m) - 1)
ans = Math.min(ans, base[k]);
else
ans = Math.min(ans, cost[k] + dp[1 - p][nwMsk]);
dp[p][msk] = ans;
}
}
System.out.println(dp[p][0] >= inf ? -1 : dp[p][0]);
}
static long[][] dp;
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s)
{
br = new BufferedReader(new InputStreamReader(s));
}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException
{
return Integer.parseInt(next());
}
public long nextLong() throws IOException
{
return Long.parseLong(next());
}
public String nextLine() throws IOException
{
return br.readLine();
}
public boolean ready() throws IOException
{
return br.ready();
}
}
static class Pair implements Comparable<Pair>
{
int ind, m;
public Pair(int i, int m)
{
ind = i;
this.m = m;
}
public int compareTo(Pair arg0)
{
return m - arg0.m;
}
}
}
| Java | ["2 2 1\n100 1 1\n2\n100 2 1\n1", "3 2 5\n100 1 1\n1\n100 1 1\n2\n200 1 2\n1 2", "1 2 1\n1 1 1\n1"] | 1 second | ["202", "205", "-1"] | null | Java 8 | standard input | [
"dp",
"sortings",
"bitmasks"
] | bc5b2d1413efcaddbf3bf1d905000159 | The first line contains three integers n, m and b (1 ≤ n ≤ 100; 1 ≤ m ≤ 20; 1 ≤ b ≤ 109) — the number of Gena's friends, the number of problems and the cost of a single monitor. The following 2n lines describe the friends. Lines number 2i and (2i + 1) contain the information about the i-th friend. The 2i-th line contains three integers xi, ki and mi (1 ≤ xi ≤ 109; 1 ≤ ki ≤ 109; 1 ≤ mi ≤ m) — the desired amount of money, monitors and the number of problems the friend can solve. The (2i + 1)-th line contains mi distinct positive integers — the numbers of problems that the i-th friend can solve. The problems are numbered from 1 to m. | 1,900 | Print the minimum amount of money Gena needs to spend to solve all the problems. Or print -1, if this cannot be achieved. | standard output | |
PASSED | 9c75c1ca39cfb18631f9f14e499851ad | train_001.jsonl | 1397749200 | A boy named Gena really wants to get to the "Russian Code Cup" finals, or at least get a t-shirt. But the offered problems are too complex, so he made an arrangement with his n friends that they will solve the problems for him.The participants are offered m problems on the contest. For each friend, Gena knows what problems he can solve. But Gena's friends won't agree to help Gena for nothing: the i-th friend asks Gena xi rubles for his help in solving all the problems he can. Also, the friend agreed to write a code for Gena only if Gena's computer is connected to at least ki monitors, each monitor costs b rubles.Gena is careful with money, so he wants to spend as little money as possible to solve all the problems. Help Gena, tell him how to spend the smallest possible amount of money. Initially, there's no monitors connected to Gena's computer. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Comparator;
import java.util.StringTokenizer;
public class CunningGena
{
static int[] can, cost;
static int[] monitor;
static int n, m, b;
static long inf = (long) 2l * 1000000 * 1000000 * 1000000;
public static void main(String[] args) throws IOException
{
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
b = sc.nextInt();
can = new int[n];
cost = new int[n];
monitor = new int[n];
Integer [] indices = new Integer[n];
long[] base = new long[n];
for (int i = 0; i < n; i++)
{
cost[i] = sc.nextInt();
indices[i] = i;
monitor[i] = sc.nextInt();
int mi = sc.nextInt();
int msk = 0;
for (int j = 0; j < mi; j++)
msk |= (1 << (sc.nextInt() - 1));
can[i] = msk;
base[i] = cost[i] + 1l * monitor[i] * b;
}
Arrays.sort(indices, new cmp());
dp = new long[2][(1 << m) + 1];
int p = 0;
Arrays.fill(dp[p], inf);
for (int ind = n - 1; ind >= 0; ind--)
{
p = 1 - p;
for (int msk = (1 << m) - 1; msk >= 0; msk--)
{
int k = indices[ind];
long ans = dp[1 - p][msk];
int nwMsk = msk | can[k];
if (nwMsk == (1 << m) - 1)
ans = Math.min(ans, base[k]);
else
ans = Math.min(ans, cost[k] + dp[1 - p][nwMsk]);
dp[p][msk] = ans;
}
}
System.out.println(dp[p][0] >= inf ? -1 : dp[p][0]);
}
static long[][] dp;
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s)
{
br = new BufferedReader(new InputStreamReader(s));
}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException
{
return Integer.parseInt(next());
}
public long nextLong() throws IOException
{
return Long.parseLong(next());
}
public String nextLine() throws IOException
{
return br.readLine();
}
public boolean ready() throws IOException
{
return br.ready();
}
}
static class cmp implements Comparator<Integer>
{
public int compare(Integer a, Integer b)
{
return monitor[a] - monitor[b];
}
}
}
| Java | ["2 2 1\n100 1 1\n2\n100 2 1\n1", "3 2 5\n100 1 1\n1\n100 1 1\n2\n200 1 2\n1 2", "1 2 1\n1 1 1\n1"] | 1 second | ["202", "205", "-1"] | null | Java 8 | standard input | [
"dp",
"sortings",
"bitmasks"
] | bc5b2d1413efcaddbf3bf1d905000159 | The first line contains three integers n, m and b (1 ≤ n ≤ 100; 1 ≤ m ≤ 20; 1 ≤ b ≤ 109) — the number of Gena's friends, the number of problems and the cost of a single monitor. The following 2n lines describe the friends. Lines number 2i and (2i + 1) contain the information about the i-th friend. The 2i-th line contains three integers xi, ki and mi (1 ≤ xi ≤ 109; 1 ≤ ki ≤ 109; 1 ≤ mi ≤ m) — the desired amount of money, monitors and the number of problems the friend can solve. The (2i + 1)-th line contains mi distinct positive integers — the numbers of problems that the i-th friend can solve. The problems are numbered from 1 to m. | 1,900 | Print the minimum amount of money Gena needs to spend to solve all the problems. Or print -1, if this cannot be achieved. | standard output | |
PASSED | bdf9ca75611df187f9b7acf7a27fc641 | train_001.jsonl | 1397749200 | A boy named Gena really wants to get to the "Russian Code Cup" finals, or at least get a t-shirt. But the offered problems are too complex, so he made an arrangement with his n friends that they will solve the problems for him.The participants are offered m problems on the contest. For each friend, Gena knows what problems he can solve. But Gena's friends won't agree to help Gena for nothing: the i-th friend asks Gena xi rubles for his help in solving all the problems he can. Also, the friend agreed to write a code for Gena only if Gena's computer is connected to at least ki monitors, each monitor costs b rubles.Gena is careful with money, so he wants to spend as little money as possible to solve all the problems. Help Gena, tell him how to spend the smallest possible amount of money. Initially, there's no monitors connected to Gena's computer. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class CunningGena
{
static int[] can, cost;
static Pair[] monitor;
static int n, m, b;
static long inf = (long) 2l * 1000000 * 1000000 * 1000000;
public static void main(String[] args) throws IOException
{
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
b = sc.nextInt();
can = new int[n];
cost = new int[n];
monitor = new Pair[n];
long[] base = new long[n];
for (int i = 0; i < n; i++)
{
cost[i] = sc.nextInt();
monitor[i] = new Pair(i, sc.nextInt());
int mi = sc.nextInt();
int msk = 0;
for (int j = 0; j < mi; j++)
msk |= (1 << (sc.nextInt() - 1));
can[i] = msk;
base[i] = cost[i] + 1l * monitor[i].m * b;
}
Arrays.sort(monitor);
dp = new long[2][(1 << m) + 1];
int p = 0;
Arrays.fill(dp[p], inf);
for (int ind = n - 1; ind >= 0; ind--)
{
p = 1 - p;
for (int msk = (1 << m) - 1; msk >= 0; msk--)
{
int k = monitor[ind].ind;
long ans = dp[1 - p][msk];
int nwMsk = msk | can[k];
if (nwMsk == (1 << m) - 1)
ans = Math.min(ans, base[k]);
else
ans = Math.min(ans, cost[k] + dp[1 - p][nwMsk]);
dp[p][msk] = ans;
}
}
System.out.println(dp[p][0] >= inf ? -1 : dp[p][0]);
}
static long[][] dp;
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s)
{
br = new BufferedReader(new InputStreamReader(s));
}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException
{
return Integer.parseInt(next());
}
public long nextLong() throws IOException
{
return Long.parseLong(next());
}
public String nextLine() throws IOException
{
return br.readLine();
}
public boolean ready() throws IOException
{
return br.ready();
}
}
static class Pair implements Comparable<Pair>
{
int ind, m;
public Pair(int i, int m)
{
ind = i;
this.m = m;
}
public int compareTo(Pair arg0)
{
return m - arg0.m;
}
}
}
| Java | ["2 2 1\n100 1 1\n2\n100 2 1\n1", "3 2 5\n100 1 1\n1\n100 1 1\n2\n200 1 2\n1 2", "1 2 1\n1 1 1\n1"] | 1 second | ["202", "205", "-1"] | null | Java 8 | standard input | [
"dp",
"sortings",
"bitmasks"
] | bc5b2d1413efcaddbf3bf1d905000159 | The first line contains three integers n, m and b (1 ≤ n ≤ 100; 1 ≤ m ≤ 20; 1 ≤ b ≤ 109) — the number of Gena's friends, the number of problems and the cost of a single monitor. The following 2n lines describe the friends. Lines number 2i and (2i + 1) contain the information about the i-th friend. The 2i-th line contains three integers xi, ki and mi (1 ≤ xi ≤ 109; 1 ≤ ki ≤ 109; 1 ≤ mi ≤ m) — the desired amount of money, monitors and the number of problems the friend can solve. The (2i + 1)-th line contains mi distinct positive integers — the numbers of problems that the i-th friend can solve. The problems are numbered from 1 to m. | 1,900 | Print the minimum amount of money Gena needs to spend to solve all the problems. Or print -1, if this cannot be achieved. | standard output | |
PASSED | dac52b17bd99a18c6cef65675db749d1 | train_001.jsonl | 1397749200 | A boy named Gena really wants to get to the "Russian Code Cup" finals, or at least get a t-shirt. But the offered problems are too complex, so he made an arrangement with his n friends that they will solve the problems for him.The participants are offered m problems on the contest. For each friend, Gena knows what problems he can solve. But Gena's friends won't agree to help Gena for nothing: the i-th friend asks Gena xi rubles for his help in solving all the problems he can. Also, the friend agreed to write a code for Gena only if Gena's computer is connected to at least ki monitors, each monitor costs b rubles.Gena is careful with money, so he wants to spend as little money as possible to solve all the problems. Help Gena, tell him how to spend the smallest possible amount of money. Initially, there's no monitors connected to Gena's computer. | 256 megabytes | import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.util.Arrays.fill;
import static java.util.Arrays.sort;
public class Main{
void run(){
Locale.setDefault(Locale.US);
boolean my;
try {
my = System.getProperty("MY_LOCAL") != null;
} catch (Exception e) {
my = false;
}
try{
err = System.err;
if( my ){
sc = new FastScanner(new BufferedReader(new FileReader("input.txt")));
// sc = new FastScanner(new BufferedReader(new FileReader("C:\\myTest.txt")));
out = new PrintWriter (new FileWriter("output.txt"));
}
else {
sc = new FastScanner( new BufferedReader(new InputStreamReader(System.in)) );
out = new PrintWriter( new OutputStreamWriter(System.out));
}
// out = new PrintWriter(new OutputStreamWriter(System.out));
}catch(Exception e){
MLE();
}
if( my )
tBeg = System.currentTimeMillis();
solve();
// check();
if( my )
err.println( "TIME: " + (System.currentTimeMillis() - tBeg ) / 1e3 );
exit(0);
}
void exit( int val ){
err.flush();
out.flush();
System.exit(val);
}
double tBeg;
FastScanner sc;
PrintWriter out;
PrintStream err;
class FastScanner{
StringTokenizer st;
BufferedReader br;
FastScanner( BufferedReader _br ){
br = _br;
}
String readLine(){
try {
return br.readLine();
} catch (IOException e) {
return null;
}
}
String next(){
while( st==null || !st.hasMoreElements() )
st = new StringTokenizer(readLine());
return st.nextToken();
}
int nextInt(){ return Integer.parseInt(next()); }
long nextLong(){ return Long.parseLong(next()); }
double nextDouble(){ return Double.parseDouble(next()); }
}
void MLE(){
int[][] arr = new int[1024*1024][]; for( int i = 0; i < 1024*1024; ++i ) arr[i] = new int[1024*1024];
}
void MLE( boolean doNotMLE ){ if( !doNotMLE ) MLE(); }
void TLE(){
for(;;);
}
public static void main(String[] args) {
new Main().run();
// new Thread( null, new Runnable() {
// @Override
// public void run() {
// new Main().run();
// }
// }, "Lolka", 256_000_000L ).run();
}
////////////////////////////////////////////////////////////////
class Item{
int cost, monik, msk;
}
final long inf = Long.MAX_VALUE;
int cntMan, cntProblems;
long costMonik;
Item[] arr;
long[] dp;
void solve(){
cntMan = sc.nextInt();
cntProblems = sc.nextInt();
costMonik = sc.nextInt();
arr = new Item[cntMan];
for (int i = 0; i < cntMan; i++) {
arr[i] = new Item();
arr[i].cost = sc.nextInt();
arr[i].monik = sc.nextInt();
int cnt = sc.nextInt();
for (int j = 0; j < cnt; j++) {
arr[i].msk |= 1 << (sc.nextInt()-1);
}
}
sort(arr, (a, b) -> Integer.compare(a.monik, b.monik));
dp = new long[1<<cntProblems];
fill( dp, inf );
dp[0] = 0;
long ans = inf;
for (Item cur : arr) {
int curMsk = cur.msk;
long curCost = cur.cost;
for (int msk = 0; msk < (1<<cntProblems); msk++) {
if( dp[msk] == inf ) continue;
dp[msk | curMsk] = min( dp[msk | curMsk], dp[msk] + curCost );
}
if( dp[(1<<cntProblems)-1] != inf )
ans = min( ans, dp[(1<<cntProblems)-1] + 1L * cur.monik * costMonik );
}
if( ans == inf ) ans = -1;
out.println( ans );
}
}
| Java | ["2 2 1\n100 1 1\n2\n100 2 1\n1", "3 2 5\n100 1 1\n1\n100 1 1\n2\n200 1 2\n1 2", "1 2 1\n1 1 1\n1"] | 1 second | ["202", "205", "-1"] | null | Java 8 | standard input | [
"dp",
"sortings",
"bitmasks"
] | bc5b2d1413efcaddbf3bf1d905000159 | The first line contains three integers n, m and b (1 ≤ n ≤ 100; 1 ≤ m ≤ 20; 1 ≤ b ≤ 109) — the number of Gena's friends, the number of problems and the cost of a single monitor. The following 2n lines describe the friends. Lines number 2i and (2i + 1) contain the information about the i-th friend. The 2i-th line contains three integers xi, ki and mi (1 ≤ xi ≤ 109; 1 ≤ ki ≤ 109; 1 ≤ mi ≤ m) — the desired amount of money, monitors and the number of problems the friend can solve. The (2i + 1)-th line contains mi distinct positive integers — the numbers of problems that the i-th friend can solve. The problems are numbered from 1 to m. | 1,900 | Print the minimum amount of money Gena needs to spend to solve all the problems. Or print -1, if this cannot be achieved. | standard output | |
PASSED | 72b2c5d95b1058df5ee238398b71cde0 | train_001.jsonl | 1397749200 | A boy named Gena really wants to get to the "Russian Code Cup" finals, or at least get a t-shirt. But the offered problems are too complex, so he made an arrangement with his n friends that they will solve the problems for him.The participants are offered m problems on the contest. For each friend, Gena knows what problems he can solve. But Gena's friends won't agree to help Gena for nothing: the i-th friend asks Gena xi rubles for his help in solving all the problems he can. Also, the friend agreed to write a code for Gena only if Gena's computer is connected to at least ki monitors, each monitor costs b rubles.Gena is careful with money, so he wants to spend as little money as possible to solve all the problems. Help Gena, tell him how to spend the smallest possible amount of money. Initially, there's no monitors connected to Gena's computer. | 256 megabytes | import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.util.Arrays.fill;
import static java.util.Arrays.sort;
public class Main{
void run(){
Locale.setDefault(Locale.US);
boolean my;
try {
my = System.getProperty("MY_LOCAL") != null;
} catch (Exception e) {
my = false;
}
try{
err = System.err;
if( my ){
sc = new FastScanner(new BufferedReader(new FileReader("input.txt")));
// sc = new FastScanner(new BufferedReader(new FileReader("C:\\myTest.txt")));
out = new PrintWriter (new FileWriter("output.txt"));
}
else {
sc = new FastScanner( new BufferedReader(new InputStreamReader(System.in)) );
out = new PrintWriter( new OutputStreamWriter(System.out));
}
// out = new PrintWriter(new OutputStreamWriter(System.out));
}catch(Exception e){
MLE();
}
if( my )
tBeg = System.currentTimeMillis();
solve();
// check();
if( my )
err.println( "TIME: " + (System.currentTimeMillis() - tBeg ) / 1e3 );
exit(0);
}
void exit( int val ){
err.flush();
out.flush();
System.exit(val);
}
double tBeg;
FastScanner sc;
PrintWriter out;
PrintStream err;
class FastScanner{
StringTokenizer st;
BufferedReader br;
FastScanner( BufferedReader _br ){
br = _br;
}
String readLine(){
try {
return br.readLine();
} catch (IOException e) {
return null;
}
}
String next(){
while( st==null || !st.hasMoreElements() )
st = new StringTokenizer(readLine());
return st.nextToken();
}
int nextInt(){ return Integer.parseInt(next()); }
long nextLong(){ return Long.parseLong(next()); }
double nextDouble(){ return Double.parseDouble(next()); }
}
void MLE(){
int[][] arr = new int[1024*1024][]; for( int i = 0; i < 1024*1024; ++i ) arr[i] = new int[1024*1024];
}
void MLE( boolean doNotMLE ){ if( !doNotMLE ) MLE(); }
void TLE(){
for(;;);
}
public static void main(String[] args) {
new Main().run();
// new Thread( null, new Runnable() {
// @Override
// public void run() {
// new Main().run();
// }
// }, "Lolka", 256_000_000L ).run();
}
////////////////////////////////////////////////////////////////
class Item{
int cost, monik, msk;
}
final long inf = Long.MAX_VALUE/2;
int cntMan, cntProblems;
long costMonik;
Item[] arr;
long[] dp;
void solve(){
cntMan = sc.nextInt();
cntProblems = sc.nextInt();
costMonik = sc.nextInt();
arr = new Item[cntMan];
for (int i = 0; i < cntMan; i++) {
arr[i] = new Item();
arr[i].cost = sc.nextInt();
arr[i].monik = sc.nextInt();
int cnt = sc.nextInt();
for (int j = 0; j < cnt; j++) {
arr[i].msk |= 1 << (sc.nextInt()-1);
}
}
sort(arr, (a, b) -> Integer.compare(a.monik, b.monik));
dp = new long[1<<cntProblems];
fill( dp, inf );
dp[0] = 0;
long ans = inf;
for (Item cur : arr) {
int curMsk = cur.msk;
long curCost = cur.cost;
for (int msk = 0; msk < (1<<cntProblems); msk++) {
if( dp[msk] == inf ) continue;
dp[msk | curMsk] = min( dp[msk | curMsk], dp[msk] + curCost );
}
ans = min( ans, dp[(1<<cntProblems)-1] + 1L * cur.monik * costMonik );
}
if( ans == inf ) ans = -1;
out.println( ans );
}
}
| Java | ["2 2 1\n100 1 1\n2\n100 2 1\n1", "3 2 5\n100 1 1\n1\n100 1 1\n2\n200 1 2\n1 2", "1 2 1\n1 1 1\n1"] | 1 second | ["202", "205", "-1"] | null | Java 8 | standard input | [
"dp",
"sortings",
"bitmasks"
] | bc5b2d1413efcaddbf3bf1d905000159 | The first line contains three integers n, m and b (1 ≤ n ≤ 100; 1 ≤ m ≤ 20; 1 ≤ b ≤ 109) — the number of Gena's friends, the number of problems and the cost of a single monitor. The following 2n lines describe the friends. Lines number 2i and (2i + 1) contain the information about the i-th friend. The 2i-th line contains three integers xi, ki and mi (1 ≤ xi ≤ 109; 1 ≤ ki ≤ 109; 1 ≤ mi ≤ m) — the desired amount of money, monitors and the number of problems the friend can solve. The (2i + 1)-th line contains mi distinct positive integers — the numbers of problems that the i-th friend can solve. The problems are numbered from 1 to m. | 1,900 | Print the minimum amount of money Gena needs to spend to solve all the problems. Or print -1, if this cannot be achieved. | standard output | |
PASSED | 0435ceac752075a765faba9f5a01c6a9 | train_001.jsonl | 1397749200 | A boy named Gena really wants to get to the "Russian Code Cup" finals, or at least get a t-shirt. But the offered problems are too complex, so he made an arrangement with his n friends that they will solve the problems for him.The participants are offered m problems on the contest. For each friend, Gena knows what problems he can solve. But Gena's friends won't agree to help Gena for nothing: the i-th friend asks Gena xi rubles for his help in solving all the problems he can. Also, the friend agreed to write a code for Gena only if Gena's computer is connected to at least ki monitors, each monitor costs b rubles.Gena is careful with money, so he wants to spend as little money as possible to solve all the problems. Help Gena, tell him how to spend the smallest possible amount of money. Initially, there's no monitors connected to Gena's computer. | 256 megabytes | // practice with rainboy
import java.io.*;
import java.util.*;
public class CF418B extends PrintWriter {
CF418B() { super(System.out, true); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF418B o = new CF418B(); o.main(); o.flush();
}
static final long INF = 0x3f3f3f3f3f3f3f3fL;
void main() {
int n = sc.nextInt();
int m = sc.nextInt();
int c = sc.nextInt();
int[] xx = new int[n];
int[] kk = new int[n];
int[] bb = new int[n];
Integer[] ii = new Integer[n];
for (int i = 0; i < n; i++) {
xx[i] = sc.nextInt();
kk[i] = sc.nextInt();
int mi = sc.nextInt();
int b = 0;
while (mi-- > 0) {
int p = sc.nextInt() - 1;
b |= 1 << p;
}
bb[i] = b;
ii[i] = i;
}
Arrays.sort(ii, (i, j) -> kk[i] - kk[j]);
long[] dp = new long[1 << m];
Arrays.fill(dp, INF);
dp[0] = 0;
long ans = INF;
for (int h = 0; h < n; h++) {
int i = ii[h];
int x = xx[i], b = bb[i];
for (int a = 0; a < 1 << m; a++)
if (dp[a] != -1) {
int a_ = a | b;
long x_ = dp[a] + x;
if (dp[a_] == -1 || dp[a_] > x_)
dp[a_] = x_;
}
long x_ = dp[(1 << m) - 1];
if (x_ == INF)
continue;
x_ += (long) kk[i] * c;
if (ans > x_)
ans = x_;
}
println(ans == INF ? -1 : ans);
}
}
| Java | ["2 2 1\n100 1 1\n2\n100 2 1\n1", "3 2 5\n100 1 1\n1\n100 1 1\n2\n200 1 2\n1 2", "1 2 1\n1 1 1\n1"] | 1 second | ["202", "205", "-1"] | null | Java 8 | standard input | [
"dp",
"sortings",
"bitmasks"
] | bc5b2d1413efcaddbf3bf1d905000159 | The first line contains three integers n, m and b (1 ≤ n ≤ 100; 1 ≤ m ≤ 20; 1 ≤ b ≤ 109) — the number of Gena's friends, the number of problems and the cost of a single monitor. The following 2n lines describe the friends. Lines number 2i and (2i + 1) contain the information about the i-th friend. The 2i-th line contains three integers xi, ki and mi (1 ≤ xi ≤ 109; 1 ≤ ki ≤ 109; 1 ≤ mi ≤ m) — the desired amount of money, monitors and the number of problems the friend can solve. The (2i + 1)-th line contains mi distinct positive integers — the numbers of problems that the i-th friend can solve. The problems are numbered from 1 to m. | 1,900 | Print the minimum amount of money Gena needs to spend to solve all the problems. Or print -1, if this cannot be achieved. | standard output | |
PASSED | c47b47b8f44408ac11c989a0e801019c | train_001.jsonl | 1397749200 | A boy named Gena really wants to get to the "Russian Code Cup" finals, or at least get a t-shirt. But the offered problems are too complex, so he made an arrangement with his n friends that they will solve the problems for him.The participants are offered m problems on the contest. For each friend, Gena knows what problems he can solve. But Gena's friends won't agree to help Gena for nothing: the i-th friend asks Gena xi rubles for his help in solving all the problems he can. Also, the friend agreed to write a code for Gena only if Gena's computer is connected to at least ki monitors, each monitor costs b rubles.Gena is careful with money, so he wants to spend as little money as possible to solve all the problems. Help Gena, tell him how to spend the smallest possible amount of money. Initially, there's no monitors connected to Gena's computer. | 256 megabytes | import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
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);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
static class Friend implements Comparable<Friend> {
int x, k, mask;
Friend(int x, int k, int mask) {
this.x = x;
this.k = k;
this.mask = mask;
}
public int compareTo(Friend o) {
return k - o.k;
}
}
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
int b = in.nextInt();
Friend[] friends = new Friend[n];
for (int i = 0; i < n; i++) {
int x = in.nextInt();
int k = in.nextInt();
int mi = in.nextInt();
int mask = 0;
for (int j = 0; j < mi; j++) {
int t = in.nextInt();
mask |= 1 << (t - 1);
}
friends[i] = new Friend(x, k, mask);
}
Arrays.sort(friends);
long[] dp = new long[1 << m];
Arrays.fill(dp, Long.MAX_VALUE);
dp[0] = 0;
long res = Long.MAX_VALUE;
for (Friend friend : friends) {
for (int j = 0; j < dp.length; j++) {
if (dp[j] != Long.MAX_VALUE)
dp[j | friend.mask] = Math.min(dp[j | friend.mask], dp[j] + friend.x);
}
if (dp[dp.length - 1] != Long.MAX_VALUE)
res = Math.min(res, dp[dp.length - 1] + friend.k * (long) b);
}
out.println(res == Long.MAX_VALUE ? -1 : res);
}
}
class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
}
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 | ["2 2 1\n100 1 1\n2\n100 2 1\n1", "3 2 5\n100 1 1\n1\n100 1 1\n2\n200 1 2\n1 2", "1 2 1\n1 1 1\n1"] | 1 second | ["202", "205", "-1"] | null | Java 8 | standard input | [
"dp",
"sortings",
"bitmasks"
] | bc5b2d1413efcaddbf3bf1d905000159 | The first line contains three integers n, m and b (1 ≤ n ≤ 100; 1 ≤ m ≤ 20; 1 ≤ b ≤ 109) — the number of Gena's friends, the number of problems and the cost of a single monitor. The following 2n lines describe the friends. Lines number 2i and (2i + 1) contain the information about the i-th friend. The 2i-th line contains three integers xi, ki and mi (1 ≤ xi ≤ 109; 1 ≤ ki ≤ 109; 1 ≤ mi ≤ m) — the desired amount of money, monitors and the number of problems the friend can solve. The (2i + 1)-th line contains mi distinct positive integers — the numbers of problems that the i-th friend can solve. The problems are numbered from 1 to m. | 1,900 | Print the minimum amount of money Gena needs to spend to solve all the problems. Or print -1, if this cannot be achieved. | standard output | |
PASSED | f2fe1f1eebe3f0e01443bb7f087086c8 | train_001.jsonl | 1397749200 | A boy named Gena really wants to get to the "Russian Code Cup" finals, or at least get a t-shirt. But the offered problems are too complex, so he made an arrangement with his n friends that they will solve the problems for him.The participants are offered m problems on the contest. For each friend, Gena knows what problems he can solve. But Gena's friends won't agree to help Gena for nothing: the i-th friend asks Gena xi rubles for his help in solving all the problems he can. Also, the friend agreed to write a code for Gena only if Gena's computer is connected to at least ki monitors, each monitor costs b rubles.Gena is careful with money, so he wants to spend as little money as possible to solve all the problems. Help Gena, tell him how to spend the smallest possible amount of money. Initially, there's no monitors connected to Gena's computer. | 256 megabytes | import java.io.*;
import java.util.*;
public class A {
static long []memo;
static long INF=(long)1e18;
static ArrayList<Integer>[]adj;
static long dp(int msk) {
if(msk==0)
return 0;
if(memo[msk]!=-1)
return memo[msk];
long ans=INF;
int idx=log[msk&-msk];
for(int solve:adj[idx]) {
int newMsk=msk&(~msks[solve]);
ans=Math.min(ans, dp(newMsk)+x[solve]);
}
return memo[msk]=ans;
}
static int []log,msks,x,k;
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner();
PrintWriter out = new PrintWriter(System.out);
int n=sc.nextInt(),m=sc.nextInt(),b=sc.nextInt();
x=new int [n];
Integer[]indices=new Integer[n];
memo=new long [1<<m];
k=new int [n];
log=new int [1<<m];
log[1]=0;
for(int i=0;i<m;i++)
log[1<<i]=i;
adj=new ArrayList[m];
for(int i=0;i<m;i++)
adj[i]=new ArrayList();
msks=new int [n];
int all=0;
for(int i=0;i<n;i++) {
indices[i]=i;
x[i]=sc.nextInt();
k[i]=sc.nextInt();
int M=sc.nextInt(),msk=0;
while(M-->0) {
int a=sc.nextInt()-1;
msk|=1<<a;
}
msks[i]=msk;
all|=msk;
}
Arrays.sort(indices,Comparator.comparingInt(i->k[i]));
if(all+1!=1<<m) {
System.out.println(-1);
return;
}
long ans=2*INF;
for(int i=0;i<n;i++) {
for(int j=i;j<n && k[indices[j]]==k[indices[i]];j++) {
int idx=indices[j];
int msk=msks[idx];
while(msk>0) {
int x=msk&-msk;
msk-=x;
adj[log[x]].add(idx);
}
i=j;
}
Arrays.fill(memo, -1);
long dp=dp(all);
if(dp<INF) {
ans=Math.min(ans, b*1L*k[indices[i]]+dp);
}
}
out.println(ans);
out.close();
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
Scanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
Scanner(String fileName) throws FileNotFoundException {
br = new BufferedReader(new FileReader(fileName));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
String nextLine() throws IOException {
return br.readLine();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(next());
}
double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(next());
}
boolean ready() throws IOException {
return br.ready();
}
}
} | Java | ["2 2 1\n100 1 1\n2\n100 2 1\n1", "3 2 5\n100 1 1\n1\n100 1 1\n2\n200 1 2\n1 2", "1 2 1\n1 1 1\n1"] | 1 second | ["202", "205", "-1"] | null | Java 8 | standard input | [
"dp",
"sortings",
"bitmasks"
] | bc5b2d1413efcaddbf3bf1d905000159 | The first line contains three integers n, m and b (1 ≤ n ≤ 100; 1 ≤ m ≤ 20; 1 ≤ b ≤ 109) — the number of Gena's friends, the number of problems and the cost of a single monitor. The following 2n lines describe the friends. Lines number 2i and (2i + 1) contain the information about the i-th friend. The 2i-th line contains three integers xi, ki and mi (1 ≤ xi ≤ 109; 1 ≤ ki ≤ 109; 1 ≤ mi ≤ m) — the desired amount of money, monitors and the number of problems the friend can solve. The (2i + 1)-th line contains mi distinct positive integers — the numbers of problems that the i-th friend can solve. The problems are numbered from 1 to m. | 1,900 | Print the minimum amount of money Gena needs to spend to solve all the problems. Or print -1, if this cannot be achieved. | standard output | |
PASSED | 7765d6ced1bb4169f1bba02fac9b9a92 | train_001.jsonl | 1397749200 | A boy named Gena really wants to get to the "Russian Code Cup" finals, or at least get a t-shirt. But the offered problems are too complex, so he made an arrangement with his n friends that they will solve the problems for him.The participants are offered m problems on the contest. For each friend, Gena knows what problems he can solve. But Gena's friends won't agree to help Gena for nothing: the i-th friend asks Gena xi rubles for his help in solving all the problems he can. Also, the friend agreed to write a code for Gena only if Gena's computer is connected to at least ki monitors, each monitor costs b rubles.Gena is careful with money, so he wants to spend as little money as possible to solve all the problems. Help Gena, tell him how to spend the smallest possible amount of money. Initially, there's no monitors connected to Gena's computer. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class Main {
static BufferedReader in;
static PrintWriter out;
static StringTokenizer tok;
static void solve() throws Exception {
int n = nextInt();
int m = nextInt();
int b = nextInt();
Friend[] a = new Friend[n];
for (int i = 0; i < n; i++) {
a[i] = new Friend(nextInt(), nextInt(), 0);
int cnt = nextInt();
for (int j = 0; j < cnt; j++) {
a[i].mask |= 1 << (nextInt()-1);
}
}
Arrays.sort(a);
long[] dp = new long[1<<m];
dp[0] = 0;
for (int i = 1; i < (1<<m); i++) {
dp[i] = Long.MAX_VALUE;
}
long res = Long.MAX_VALUE;
for (int i = 0; i < n; i++) {
for (int j = (1<<m)-1; j >= 0; j--) {
if (dp[j] != Long.MAX_VALUE) {
int j2 = j | a[i].mask;
dp[j2] = Math.min(dp[j] + a[i].x, dp[j2]);
}
}
if (dp[(1<<m)-1] != Long.MAX_VALUE) {
res = Math.min(dp[(1<<m)-1] + (long)a[i].k * b, res);
}
}
if (res == Long.MAX_VALUE) {
out.println("-1");
} else {
out.println(res);
}
}
static class Friend implements Comparable<Friend>{
int x, k, mask;
Friend(int x, int k, int mask) {
this.x = x;
this.k = k;
this.mask = mask;
}
public int compareTo(Friend other) {
return Integer.compare(this.k, other.k);
}
}
static int sqr(int x) {
return x*x;
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
static BigInteger nextBigInteger() throws IOException {
return new BigInteger(next());
}
static String next() throws IOException {
while (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
static String nextLine() throws IOException {
tok = new StringTokenizer("");
return in.readLine();
}
static boolean hasNext() throws IOException {
while (tok == null || !tok.hasMoreTokens()) {
String s = in.readLine();
if (s == null) {
return false;
}
tok = new StringTokenizer(s);
}
return true;
}
public static void main(String args[]) {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new OutputStreamWriter(System.out));
//in = new BufferedReader(new FileReader("1.in"));
//out = new PrintWriter(new FileWriter("1.out"));
solve();
in.close();
out.close();
} catch (Throwable e) {
e.printStackTrace();
java.lang.System.exit(1);
}
}
} | Java | ["2 2 1\n100 1 1\n2\n100 2 1\n1", "3 2 5\n100 1 1\n1\n100 1 1\n2\n200 1 2\n1 2", "1 2 1\n1 1 1\n1"] | 1 second | ["202", "205", "-1"] | null | Java 8 | standard input | [
"dp",
"sortings",
"bitmasks"
] | bc5b2d1413efcaddbf3bf1d905000159 | The first line contains three integers n, m and b (1 ≤ n ≤ 100; 1 ≤ m ≤ 20; 1 ≤ b ≤ 109) — the number of Gena's friends, the number of problems and the cost of a single monitor. The following 2n lines describe the friends. Lines number 2i and (2i + 1) contain the information about the i-th friend. The 2i-th line contains three integers xi, ki and mi (1 ≤ xi ≤ 109; 1 ≤ ki ≤ 109; 1 ≤ mi ≤ m) — the desired amount of money, monitors and the number of problems the friend can solve. The (2i + 1)-th line contains mi distinct positive integers — the numbers of problems that the i-th friend can solve. The problems are numbered from 1 to m. | 1,900 | Print the minimum amount of money Gena needs to spend to solve all the problems. Or print -1, if this cannot be achieved. | standard output | |
PASSED | b033a8e929ba9f985377457739ada55a | train_001.jsonl | 1397749200 | A boy named Gena really wants to get to the "Russian Code Cup" finals, or at least get a t-shirt. But the offered problems are too complex, so he made an arrangement with his n friends that they will solve the problems for him.The participants are offered m problems on the contest. For each friend, Gena knows what problems he can solve. But Gena's friends won't agree to help Gena for nothing: the i-th friend asks Gena xi rubles for his help in solving all the problems he can. Also, the friend agreed to write a code for Gena only if Gena's computer is connected to at least ki monitors, each monitor costs b rubles.Gena is careful with money, so he wants to spend as little money as possible to solve all the problems. Help Gena, tell him how to spend the smallest possible amount of money. Initially, there's no monitors connected to Gena's computer. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class CunningGena {
static int n, m;
static long b;
static Friend[] friends;
static long[] dp;
static class Friend implements Comparable<Friend> {
int x, k, p, mask;
public Friend(int xx, int kk, int pp) {
x = xx;
k = kk;
p = pp;
}
@Override
public int compareTo(Friend arg0) {
return k - arg0.k;
}
}
public static void main(String[] args) {
InputReader r = new InputReader(System.in);
n = r.nextInt();
m = r.nextInt();
b = r.nextInt();
friends = new Friend[n];
for (int i = 0; i < n; i++) {
friends[i] = new Friend(r.nextInt(), r.nextInt(), r.nextInt());
for (int j = 0; j < friends[i].p; j++) {
int p = r.nextInt() - 1;
friends[i].mask |= (1 << p);
}
}
Arrays.sort(friends);
dp = new long[1 << m];
long res = Long.MAX_VALUE / 2;
Arrays.fill(dp, res);
dp[0] = 0L;
for (int i = 0; i < n; i++) {
int mask = friends[i].mask;
for (int j = 0; j < 1 << m; j++) {
dp[j | mask] = Math.min(dp[j | mask], dp[j] + friends[i].x);
}
res = Math.min(res, b * friends[i].k + dp[(1 << m) - 1]);
}
System.out.println(res >= Long.MAX_VALUE / 2 ? -1 : res);
}
static class InputReader {
private BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public InputReader(FileReader stream) {
reader = new BufferedReader(stream);
tokenizer = null;
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return 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 | ["2 2 1\n100 1 1\n2\n100 2 1\n1", "3 2 5\n100 1 1\n1\n100 1 1\n2\n200 1 2\n1 2", "1 2 1\n1 1 1\n1"] | 1 second | ["202", "205", "-1"] | null | Java 6 | standard input | [
"dp",
"sortings",
"bitmasks"
] | bc5b2d1413efcaddbf3bf1d905000159 | The first line contains three integers n, m and b (1 ≤ n ≤ 100; 1 ≤ m ≤ 20; 1 ≤ b ≤ 109) — the number of Gena's friends, the number of problems and the cost of a single monitor. The following 2n lines describe the friends. Lines number 2i and (2i + 1) contain the information about the i-th friend. The 2i-th line contains three integers xi, ki and mi (1 ≤ xi ≤ 109; 1 ≤ ki ≤ 109; 1 ≤ mi ≤ m) — the desired amount of money, monitors and the number of problems the friend can solve. The (2i + 1)-th line contains mi distinct positive integers — the numbers of problems that the i-th friend can solve. The problems are numbered from 1 to m. | 1,900 | Print the minimum amount of money Gena needs to spend to solve all the problems. Or print -1, if this cannot be achieved. | standard output | |
PASSED | 81d9ea70e6cc208b4d6f98d05892fd54 | train_001.jsonl | 1397749200 | A boy named Gena really wants to get to the "Russian Code Cup" finals, or at least get a t-shirt. But the offered problems are too complex, so he made an arrangement with his n friends that they will solve the problems for him.The participants are offered m problems on the contest. For each friend, Gena knows what problems he can solve. But Gena's friends won't agree to help Gena for nothing: the i-th friend asks Gena xi rubles for his help in solving all the problems he can. Also, the friend agreed to write a code for Gena only if Gena's computer is connected to at least ki monitors, each monitor costs b rubles.Gena is careful with money, so he wants to spend as little money as possible to solve all the problems. Help Gena, tell him how to spend the smallest possible amount of money. Initially, there's no monitors connected to Gena's computer. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class B {
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter out;
public void solve() throws IOException {
int N = nextInt();
int M = nextInt();
long B = nextLong();
int max = 1 << M;
int[][] friends = new int[N][];
for (int i = 0; i < N; i++) {
int X = nextInt();
int K = nextInt();
int MM = nextInt();
int mask = 0;
for (int j = 0; j < MM; j++) {
int Q = nextInt() - 1;
mask |= (1 << Q);
}
friends[i] = new int[] {X, K, mask};
}
Arrays.sort(friends, new Comparator<int[]>() {
@Override
public int compare(int[] a, int[] b) {
return a[1] < b[1]? -1: 1;
}
});
long[] dp = new long[max];
Arrays.fill(dp, -1);
dp[0] = 0;
int UNDEF = -1;
long ans = Long.MAX_VALUE;
int cur_monitors = 0;
for (int n = 0; n < N; n++) {
if (dp[max-1] != UNDEF) {
ans = Math.min(ans, dp[max-1]);
}
if (friends[n][1] > cur_monitors) {
long extra = (friends[n][1] - cur_monitors) * B;
for (int i = 0; i < max; i++) {
if (dp[i] != UNDEF) {
dp[i] += extra;
}
}
cur_monitors = friends[n][1];
}
for (int i = 0; i < max; i++) {
if (dp[i] != UNDEF) {
int mask = (i | friends[n][2]);
if (dp[mask] == UNDEF || dp[mask] > dp[i] + friends[n][0]) {
dp[mask] = dp[i] + friends[n][0];
}
}
}
}
if (dp[max-1] != UNDEF) {
ans = Math.min(ans, dp[max-1]);
}
if (ans == Long.MAX_VALUE) {
out.println(-1);
} else {
out.println(ans);
}
}
/**
* @param args
*/
public static void main(String[] args) {
new B().run();
}
public void run() {
try {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
out = new PrintWriter(System.out);
solve();
reader.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
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 nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
}
| Java | ["2 2 1\n100 1 1\n2\n100 2 1\n1", "3 2 5\n100 1 1\n1\n100 1 1\n2\n200 1 2\n1 2", "1 2 1\n1 1 1\n1"] | 1 second | ["202", "205", "-1"] | null | Java 6 | standard input | [
"dp",
"sortings",
"bitmasks"
] | bc5b2d1413efcaddbf3bf1d905000159 | The first line contains three integers n, m and b (1 ≤ n ≤ 100; 1 ≤ m ≤ 20; 1 ≤ b ≤ 109) — the number of Gena's friends, the number of problems and the cost of a single monitor. The following 2n lines describe the friends. Lines number 2i and (2i + 1) contain the information about the i-th friend. The 2i-th line contains three integers xi, ki and mi (1 ≤ xi ≤ 109; 1 ≤ ki ≤ 109; 1 ≤ mi ≤ m) — the desired amount of money, monitors and the number of problems the friend can solve. The (2i + 1)-th line contains mi distinct positive integers — the numbers of problems that the i-th friend can solve. The problems are numbered from 1 to m. | 1,900 | Print the minimum amount of money Gena needs to spend to solve all the problems. Or print -1, if this cannot be achieved. | standard output | |
PASSED | f5ddbd72af85f3b7f7694b4df60e3c0a | train_001.jsonl | 1397749200 | A boy named Gena really wants to get to the "Russian Code Cup" finals, or at least get a t-shirt. But the offered problems are too complex, so he made an arrangement with his n friends that they will solve the problems for him.The participants are offered m problems on the contest. For each friend, Gena knows what problems he can solve. But Gena's friends won't agree to help Gena for nothing: the i-th friend asks Gena xi rubles for his help in solving all the problems he can. Also, the friend agreed to write a code for Gena only if Gena's computer is connected to at least ki monitors, each monitor costs b rubles.Gena is careful with money, so he wants to spend as little money as possible to solve all the problems. Help Gena, tell him how to spend the smallest possible amount of money. Initially, there's no monitors connected to Gena's computer. | 256 megabytes | import java.util.* ;
import java.io.* ;
import java.util.regex.* ;
import java.text.* ;
import java.math.* ;
public class Main {
public static void main( String[] args ) {
InputStream isObj ;
OutputStream osObj ;
InputReader irObj ;
PrintWriter pwObj ;
String inputFileName , outputFileName ;
File fObj1 , fObj2 ;
int T , ind ;
boolean hasMoreInput , hasTestCases ;
ProblemSolver psObj ;
//only variable to be changed here is hasTestCases and osObj(optional for file output)
hasTestCases = ProblemSolver.HAS_TEST_CASES ;
isObj = System.in ;
osObj = System.out ;
inputFileName = ProblemSolver.INPUT_FILE_NAME ;
outputFileName = ProblemSolver.OUTPUT_FILE_NAME ;
try {
fObj1 = new File( System.getProperty( "user.dir" ).toString() + "\\" + inputFileName ) ;
fObj2 = new File( System.getProperty( "user.dir" ).toString() + "\\" + outputFileName ) ;
if( fObj1.exists() == false ) {
fObj1 = new File( System.getProperty( "user.dir" ).toString() + "\\src\\" + inputFileName ) ;
fObj2 = new File( System.getProperty( "user.dir" ).toString() + "\\src\\" + outputFileName ) ;
}
isObj = new FileInputStream( fObj1 ) ;
if( ProblemSolver.DO_OUTPUT_TO_FILE == true ) {
osObj = new FileOutputStream( fObj2 ) ;
}
}
catch( Exception ex ) {
ex.printStackTrace() ;
isObj = System.in ;
osObj = System.out ;
}
irObj = new InputReader( isObj ) ;
pwObj = new PrintWriter( osObj ) ;
try {
psObj = new ProblemSolver() ;
if( hasTestCases == true ) {
//for input with test cases
T = irObj.nextInt() ;
for( ind = 1 ; ind <= T ; ind++ ) {
psObj.clearPerCase() ;
psObj.getInput( irObj ) ;
psObj.solveCase( pwObj ) ;
}
}
else {
//for end of file input
for( ind = 1 ; ; ind++ ) {
psObj.clearPerCase() ;
hasMoreInput = psObj.getInput( irObj ) ;
if( hasMoreInput == false ) {
break ;
}
psObj.solveCase( pwObj ) ;
}
}
pwObj.flush() ;
isObj.close() ;
osObj.close() ;
}
catch( Exception ex ) {
ex.printStackTrace() ;
throw new RuntimeException( ex ) ;
}
finally {
pwObj.close() ;
}
}
}
class ProblemSolver {
public static final boolean HAS_TEST_CASES = false ;
public static final String INPUT_FILE_NAME = "test.in" ;
public static final String OUTPUT_FILE_NAME = "out.txt" ;
public static final boolean DO_OUTPUT_TO_FILE = false ;
public void solveCase( PrintWriter pwObj ) {
int i , j , a , mask , b , c , lim , nwMask , abc ;
int[] drr ;
long res , lo , hi , mi , cost ;
res = Long.MAX_VALUE ;
lim = 1 << this.m ;
Arrays.sort( this.nrr , 0 , this.n ) ;
for( i = 0 ; i < this.lim1 ; i++ ) {
this.lrr[ i ] = Long.MAX_VALUE ;
this.brr[ i ] = 0 ;
}
this.lrr[ 0 ] = 0 ;
this.brr[ 0 ] = 1 ;
for( i = 0 ; i < this.n ; i++ ) {
mask = 0 ;
drr = this.nrr[ i ].getArr() ;
cost = this.nrr[ i ].getM() ;
for( j = 0 ; j < this.nrr[ i ].getM() ; j++ ) {
a = drr[ j ] - 1 ;
mask |= ( 1 << a ) ;
}
for( j = 0 ; j < lim ; j++ ) {
if( this.brr[ j ] == 1 ) {
nwMask = j | mask ;
this.lrr[ nwMask ] = Math.min( this.lrr[ nwMask ] , ( ( long ) this.lrr[ j ] ) + ( ( long ) this.nrr[ i ].getX() ) ) ;
this.brr[ nwMask ] = 1 ;
}
}
if( this.brr[ lim - 1 ] == 1 ) {
res = Math.min( res , this.lrr[ lim - 1 ] + ( ( long ) this.nrr[ i ].getK() * ( long ) this.b ) ) ;
}
}
if( res == Long.MAX_VALUE ) {
res = -1 ;
}
pwObj.println( res ) ;
}
private void init() {
//default values
this.lim1 = 1100010 ;
this.lim2 = 110 ;
this.cc = 1 ;
this.ind = 0 ;
this.declareArrays() ;
this.fillAllArrays() ;
}
public boolean getInput( InputReader irObj ) {
int i , j , x , y , z ;
try {
this.n = irObj.nextInt() ;
}
catch( Exception ex ) {
return false ;
}
this.m = irObj.nextInt() ;
this.b = irObj.nextInt() ;
for( i = 0 ; i < this.n ; i++ ) {
x = irObj.nextInt() ;
y = irObj.nextInt() ;
z = irObj.nextInt() ;
this.crr[ i ] = z ;
int[] drr ;
drr = new int[ 25 ] ;
for( j = 0 ; j < z ; j++ ) {
drr[ j ] = irObj.nextInt() ;
}
this.nrr[ i ] = new Node( x , y , z , drr ) ;
}
return true ;
}
private int lim1 , lim2 , cn , ind , cc , n , m , b ;
private String[] srr ;
private int[] arr , brr , crr ;
private Node[] nrr ;
private long[] lrr ;
private int[][] memo , done ;
private ArrayList< Integer >[] adj_list ;
public void clearPerCase() {
this.incrementInd() ;
this.incrementCc() ;
this.n = 0 ;
this.cn = 0 ;
}
private void declareArrays() {
//array declarations
this.arr = new int[ this.lim1 ] ;
this.brr = new int[ this.lim1 ] ;
this.crr = new int[ this.lim1 ] ;
this.lrr = new long[ this.lim1 ] ;
this.srr = new String[ this.lim1 ] ;
this.nrr = new Node[ this.lim1 ] ;
this.memo = new int[ this.lim2 ][ this.lim2 ] ;
this.done = new int[ this.lim2 ][ this.lim2 ] ;
this.adj_list = new ArrayList[ this.lim1 ] ;
}
private void fillAllArrays() {
int i ;
//array initiations
Arrays.fill( this.arr , 0 ) ;
Arrays.fill( this.brr , 0 ) ;
Arrays.fill( this.crr , 0 ) ;
Arrays.fill( this.lrr , 0 ) ;
for( int zrr[] : this.memo ) {
Arrays.fill( zrr , -1 ) ;
}
for( int zrr[] : this.done ) {
Arrays.fill( zrr , 0 ) ;
}
for( i = 0 ; i < this.lim1 ; i++ ) {
this.srr[ i ] = new String( "" ) ;
this.adj_list[ i ] = new ArrayList< Integer >() ;
}
}
private void incrementInd() {
this.ind++ ;
}
public void setCn( int c ) {
this.cn = c ;
}
public void incrementCn() {
this.cn++ ;
}
public void incrementCc() {
this.cc++ ;
}
public int getCn() {
return this.cn ;
}
public ProblemSolver() {
this.init() ;
}
}
class Node implements Comparable< Node > {
private int x , k , m ;
private int[] arr ;
private Node() {
}
public Node( int xParam , int kParam , int mParam , int[] arrParam ) {
this.x = xParam ;
this.k = kParam ;
this.m = mParam ;
this.arr = arrParam ;
}
public void setArr( int[] arrParam ) {
this.arr = arrParam ;
}
public int[] getArr() {
return this.arr ;
}
public int getM() {
return this.m ;
}
public int getX() {
return this.x ;
}
public int getK() {
return this.k ;
}
public int compareTo( Node nParam ) {
return this.getK() - nParam.getK() ;
}
}
class InputReader {
private BufferedReader reader ;
private StringTokenizer tokenizer ;
public InputReader( InputStream stream ) {
this.reader = new BufferedReader( new InputStreamReader( stream ) ) ;
this.tokenizer = null ;
}
private String next( int fl ) {
while( this.tokenizer == null || ! this.tokenizer.hasMoreTokens() ) {
try {
this.tokenizer = new StringTokenizer( this.reader.readLine() ) ;
}
catch( IOException e ) {
throw new RuntimeException( e ) ;
}
}
String s ;
s = "" ;
if( fl == 1 ) {
s = this.tokenizer.nextToken() ;
}
return s ;
}
public String nextLine() {
this.next( 0 ) ;
int fl ;
String line ;
line = "" ;
fl = 0 ;
if( this.tokenizer != null ) {
while( this.tokenizer.hasMoreTokens() ) {
if( fl == 1 ) {
line += " " ;
}
fl = 1 ;
line += this.tokenizer.nextToken() ;
}
}
return line ;
}
public int nextInt() {
return Integer.parseInt( this.next( 1 ) ) ;
}
public long nextLong() {
return Long.parseLong( this.next( 1 ) ) ;
}
public double nextDouble() {
return Double.parseDouble( this.next( 1 ) ) ;
}
public String nextString() {
return this.next( 1 ) ;
}
} | Java | ["2 2 1\n100 1 1\n2\n100 2 1\n1", "3 2 5\n100 1 1\n1\n100 1 1\n2\n200 1 2\n1 2", "1 2 1\n1 1 1\n1"] | 1 second | ["202", "205", "-1"] | null | Java 6 | standard input | [
"dp",
"sortings",
"bitmasks"
] | bc5b2d1413efcaddbf3bf1d905000159 | The first line contains three integers n, m and b (1 ≤ n ≤ 100; 1 ≤ m ≤ 20; 1 ≤ b ≤ 109) — the number of Gena's friends, the number of problems and the cost of a single monitor. The following 2n lines describe the friends. Lines number 2i and (2i + 1) contain the information about the i-th friend. The 2i-th line contains three integers xi, ki and mi (1 ≤ xi ≤ 109; 1 ≤ ki ≤ 109; 1 ≤ mi ≤ m) — the desired amount of money, monitors and the number of problems the friend can solve. The (2i + 1)-th line contains mi distinct positive integers — the numbers of problems that the i-th friend can solve. The problems are numbered from 1 to m. | 1,900 | Print the minimum amount of money Gena needs to spend to solve all the problems. Or print -1, if this cannot be achieved. | standard output | |
PASSED | 65cc09a3dee6d38c3d17861731db09dd | train_001.jsonl | 1397749200 | A boy named Gena really wants to get to the "Russian Code Cup" finals, or at least get a t-shirt. But the offered problems are too complex, so he made an arrangement with his n friends that they will solve the problems for him.The participants are offered m problems on the contest. For each friend, Gena knows what problems he can solve. But Gena's friends won't agree to help Gena for nothing: the i-th friend asks Gena xi rubles for his help in solving all the problems he can. Also, the friend agreed to write a code for Gena only if Gena's computer is connected to at least ki monitors, each monitor costs b rubles.Gena is careful with money, so he wants to spend as little money as possible to solve all the problems. Help Gena, tell him how to spend the smallest possible amount of money. Initially, there's no monitors connected to Gena's computer. | 256 megabytes | import java.io.*;
import java.util.*;
import java.lang.reflect.*;
public class Main {
static long CURRENT_TIME_NANO = System.nanoTime();
public static void main(String[] args) throws Exception {
int n = next();
int m = next();
long b = nextl();
long[] x = new long[n];
long[] k = new long[n];
int[] can = new int[n];
for (int i = 0; i < n; i++) {
x[i] = nextl();
k[i] = nextl();
int kol = next();
for (int j = 0; j < kol; j++) can[i] |= 1 << (next() - 1);
}
long inf = Long.MAX_VALUE;
long answ = inf;
long[] best = new long[1 << m];
Arrays.fill(best, inf);
best[0] = 0;
long[] num = new long[n];
for (int i = 0; i < n; i++) num[i] = k[i] * 1000000L + i;
Arrays.sort(num);
for (int i = 0; i < n; i++) num[i] %= 1000000;
for (long ii : num) {
int i = (int)ii;
for (int mask = 0; mask < (1 << m); mask++)
if (best[mask] < inf)
best[mask | can[i]] = Math.min(best[mask] + x[i], best[mask | can[i]]);
if (best[(1 << m) - 1] < inf)
answ = Math.min(answ, b * k[i] + best[(1 << m) - 1]);
}
out.println(answ == inf ? -1 : answ);
out.close();
}
static void printtime() {System.out.println((System.nanoTime() - CURRENT_TIME_NANO)*1e-9);}
static void nexttime() {printtime(); CURRENT_TIME_NANO = System.nanoTime();}
static PrintWriter out = new PrintWriter(System.out);
static BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer in = new StringTokenizer("");
static String nextToken() throws Exception {
if (!in.hasMoreTokens()) in = new StringTokenizer(bufferedreader.readLine());
return in.nextToken();
}
static int next() throws Exception {return Integer.parseInt(nextToken());};
static int[] next(int n) throws Exception {
int[] x = new int[n];
for (int i = 0; i < n; i++) x[i] = next();
return x;
}
static int[][] next(int n, int m) throws Exception {
int[][] x = new int[n][];
for (int i = 0; i < n; i++) x[i] = next(m);
return x;
}
static long nextl() throws Exception {return Long.parseLong(nextToken());};
static long[] nextl(int n) throws Exception {
long[] x = new long[n];
for (int i = 0; i < n; i++) x[i] = nextl();
return x;
}
static long[][] nextl(int n, int m) throws Exception {
long[][] x = new long[n][];
for (int i = 0; i < n; i++) x[i] = nextl(m);
return x;
}
static double nextd() throws Exception {return Double.parseDouble(nextToken());};
static double[] nextd(int n) throws Exception {
double[] x = new double[n];
for (int i = 0; i < n; i++) x[i] = nextd();
return x;
}
static double[][] nextd(int n, int m) throws Exception {
double[][] x = new double[n][];
for (int i = 0; i < n; i++) x[i] = nextd(m);
return x;
}
static String nextline() throws Exception {
in = new StringTokenizer("");
return bufferedreader.readLine();
}
static void sout(long x) {System.out.println(x);}
static void sout(String s) {System.out.println(s);}
static void sout(int[] x) {for (int xx : x) System.out.print(xx + " "); System.out.println();}
static void sout(long[] x) {for (long xx : x) System.out.print(xx + " "); System.out.println();}
static void sout(int[][] x) {for (int[] xx : x) sout(xx); System.out.println();}
static void sout(long[][] x) {for (long[] xx : x) sout(xx); System.out.println();}
} | Java | ["2 2 1\n100 1 1\n2\n100 2 1\n1", "3 2 5\n100 1 1\n1\n100 1 1\n2\n200 1 2\n1 2", "1 2 1\n1 1 1\n1"] | 1 second | ["202", "205", "-1"] | null | Java 6 | standard input | [
"dp",
"sortings",
"bitmasks"
] | bc5b2d1413efcaddbf3bf1d905000159 | The first line contains three integers n, m and b (1 ≤ n ≤ 100; 1 ≤ m ≤ 20; 1 ≤ b ≤ 109) — the number of Gena's friends, the number of problems and the cost of a single monitor. The following 2n lines describe the friends. Lines number 2i and (2i + 1) contain the information about the i-th friend. The 2i-th line contains three integers xi, ki and mi (1 ≤ xi ≤ 109; 1 ≤ ki ≤ 109; 1 ≤ mi ≤ m) — the desired amount of money, monitors and the number of problems the friend can solve. The (2i + 1)-th line contains mi distinct positive integers — the numbers of problems that the i-th friend can solve. The problems are numbered from 1 to m. | 1,900 | Print the minimum amount of money Gena needs to spend to solve all the problems. Or print -1, if this cannot be achieved. | standard output | |
PASSED | 3335a66d1cd381bd34c49dd6de805d39 | train_001.jsonl | 1599918300 | This is an interactive problem.There is an unknown integer $$$x$$$ ($$$1\le x\le n$$$). You want to find $$$x$$$.At first, you have a set of integers $$$\{1, 2, \ldots, n\}$$$. You can perform the following operations no more than $$$10000$$$ times: A $$$a$$$: find how many numbers are multiples of $$$a$$$ in the current set. B $$$a$$$: find how many numbers are multiples of $$$a$$$ in this set, and then delete all multiples of $$$a$$$, but $$$x$$$ will never be deleted (even if it is a multiple of $$$a$$$). In this operation, $$$a$$$ must be greater than $$$1$$$. C $$$a$$$: it means that you know that $$$x=a$$$. This operation can be only performed once. Remember that in the operation of type B $$$a>1$$$ must hold.Write a program, that will find the value of $$$x$$$. | 512 megabytes | //package Codeforces.Round670Div2;
import java.util.*;
public class E {
static ArrayList<Integer> primes;
/*static class Checker
{
int n;
int guess;
boolean finishedflag;
ArrayList<Integer> arr;
int gcount;
Checker(int n, int guess)
{
this.n = n;
this.finishedflag = false;
this.guess = guess;
this.gcount = 0;
arr = new ArrayList<>(n+1);
for(int i=0;i<=n;i++)
{
arr.add(i);
}
}
public int println(char c, int a)
{
gcount++;
if(gcount>10000)
{
System.out.println("Too many queries");
System.exit(0);
}
if(finishedflag)
{
System.out.println("Output wrong in ");
System.exit(0);
}
//System.out.println(c+" "+a);
if(c == 'A')
{
int counter = 0;
for(int i=a;i<=n;i+=a)
{
if(arr.get(i)!=0)
counter++;
}
return counter;
}
else if(c == 'B')
{
int counter = 0;
for(int i=a;i<=n;i+=a)
{
if(arr.get(i)!=0) {
counter++;
}
if(arr.get(i)!=0 && arr.get(i)!=this.guess)
{
arr.set(i, 0);
}
}
return counter;
}
else
{
if(a==guess) {
//System.out.println("Correct Guess. " + a);
return 0;
}
else
{
System.out.println("Wrong Guess. "+a+" "+this.guess+" "+this.n);
System.exit(0);
}
finishedflag = true;
return 0;
}
}
}*/
public static void preComputePrimes(int n)
{
int[] parr = new int[n+1];
for(int i=0;i<=n;i++)
{
parr[i] = i;
}
parr[0] = 1;
for(int i=2;i<=n;i++)
{
if(parr[i]==1)
continue;
for(int j=2*i;j<=n;j+=i)
{
parr[j] = 1;
}
}
for(int i=0;i<=n;i++)
{
if(parr[i]!=1)
primes.add(i);
}
}
/*public static void main(String[] args)
{
int t = 10000;
while(t-->0)
{
int n = (int) (Math.random()*100000+1);
int g = (int) (Math.random()*n+1);
maind(n, g);
if(t%100 == 0)
System.out.println(10000-t);
}
System.out.println("Correctly Guessed all test cases");
}*/
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
//Checker chk = new Checker(n, g);
int n = sc.nextInt();
int input;
primes = new ArrayList<>();
preComputePrimes(n);
int numberOfPrimes = primes.size();
int sqrt = (int) Math.sqrt(n);
int smallPrimes=0;
for(int i: primes)
{
if(i>sqrt)
break;
//input = chk.println('B', i);
System.out.println("B "+ i);
System.out.flush();
input = sc.nextInt();
smallPrimes++;
}
int bigPrimes = numberOfPrimes-smallPrimes;
//input = chk.println('A', 1);
System.out.println("A 1");
System.out.flush();
input = sc.nextInt();
input -= 1;
int ans = 1;
if(input-bigPrimes==1)
{
//Compute for small primes
ArrayList<Integer> primeFactor = new ArrayList<>();
for(int ind=0;ind<smallPrimes;ind++)
{
int i = primes.get(ind);
System.out.println("A "+i);
System.out.flush();
int k = sc.nextInt();
//int k = chk.println('A', i);
if(k==1)
primeFactor.add(i);
}
for(int i: primeFactor)
{
int counter = 1;
while(true) {
if((i*counter) > n)
break;
//int k = chk.println('A', (i*counter));
System.out.println("A "+(i*counter));
System.out.flush();
int k = sc.nextInt();
counter = counter*i;
if(k==0)
break;
else ans *= i;
}
}
/*System.out.println("C "+ans);
System.out.flush();*/
//int k = chk.println('C', ans);
}
int start = smallPrimes;
int bsize = 100;
int prevCount = input;
while(true)
{
//System.out.println(start+" "+primes.get(start));
if(start+bsize>=primes.size())
{
for(int i=start;i<primes.size();i++)
{
int pf = primes.get(i);
//input = chk.println('B', pf);
System.out.println("B "+pf);
System.out.flush();
input = sc.nextInt();
//input = chk.println('A', pf);
System.out.println("A "+pf);
System.out.flush();
input = sc.nextInt();
if(input==1)
{
System.out.println("C "+(pf*ans));
System.out.flush();
System.exit(0);
//int k = chk.println('C', (pf*ans));
return;
}
}
break;
}
int segcount = 0;
for(int i=start;i<start+bsize;i++)
{
int pf = primes.get(i);
System.out.println("B "+pf);
System.out.flush();
input = sc.nextInt();
//input = chk.println('B', pf);
segcount += input;
}
System.out.println("A 1");
System.out.flush();
input = sc.nextInt();
//input = chk.println('A', 1);
input -= 1;
int store = input;
if(input+segcount != prevCount)
{
for(int i=start;i<start+bsize;i++)
{
int pf = primes.get(i);
System.out.println("A "+pf);
System.out.flush();
input = sc.nextInt();
//input = chk.println('A', pf);
if(input==1)
{
System.out.println("C "+(pf*ans));
System.out.flush();
System.exit(0);
//input = chk.println('C', (pf*ans));
return;
}
}
break;
}
start += bsize;
prevCount = store;
}
System.out.println("C "+ans);
System.out.flush();
//chk.println('C', ans);
}
} | Java | ["10\n\n2\n\n4\n\n0"] | 1 second | ["B 4\n\nA 2\n\nA 8\n\nC 4"] | NoteNote that to make the sample more clear, we added extra empty lines. You shouldn't print any extra empty lines during the interaction process.In the first test $$$n=10$$$ and $$$x=4$$$.Initially the set is: $$$\{1,2,3,4,5,6,7,8,9,10\}$$$.In the first operation, you ask how many numbers are multiples of $$$4$$$ and delete them. The answer is $$$2$$$ because there are two numbers divisible by $$$4$$$: $$$\{4,8\}$$$. $$$8$$$ will be deleted but $$$4$$$ won't, because the number $$$x$$$ will never be deleted. Now the set is $$$\{1,2,3,4,5,6,7,9,10\}$$$.In the second operation, you ask how many numbers are multiples of $$$2$$$. The answer is $$$4$$$ because there are four numbers divisible by $$$2$$$: $$$\{2,4,6,10\}$$$.In the third operation, you ask how many numbers are multiples of $$$8$$$. The answer is $$$0$$$ because there isn't any number divisible by $$$8$$$ in the current set.In the fourth operation, you know that $$$x=4$$$, which is the right answer. | Java 11 | standard input | [
"interactive",
"number theory",
"math"
] | 513480a6c7a715e237c3a63805208039 | The first line contains one integer $$$n$$$ ($$$1\le n\le 10^5$$$). The remaining parts of the input will be given throughout the interaction process. | 2,600 | null | standard output | |
PASSED | a0e91105106b8b650c38f1e9c993adab | train_001.jsonl | 1599918300 | This is an interactive problem.There is an unknown integer $$$x$$$ ($$$1\le x\le n$$$). You want to find $$$x$$$.At first, you have a set of integers $$$\{1, 2, \ldots, n\}$$$. You can perform the following operations no more than $$$10000$$$ times: A $$$a$$$: find how many numbers are multiples of $$$a$$$ in the current set. B $$$a$$$: find how many numbers are multiples of $$$a$$$ in this set, and then delete all multiples of $$$a$$$, but $$$x$$$ will never be deleted (even if it is a multiple of $$$a$$$). In this operation, $$$a$$$ must be greater than $$$1$$$. C $$$a$$$: it means that you know that $$$x=a$$$. This operation can be only performed once. Remember that in the operation of type B $$$a>1$$$ must hold.Write a program, that will find the value of $$$x$$$. | 512 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class cf1406e {
public static void main(String[] args) throws IOException {
int n = ri(), div[] = new int[n + 1], sqrt = (int) sqrt(n);
List<Integer> primes = new ArrayList<>();
for (int i = 2; i <= n; ++i) {
if (div[i] == 0){
primes.add(div[i] = i);
int j = i;
while ((j += i) <= n) {
div[j] = i;
}
}
}
Map<Integer, Integer> prime_factorization = new HashMap<>();
int remain = n, step = 0;
boolean found = false;
int i;
out: for (i = primes.size() - 1; i >= 0 && primes.get(i) > sqrt; --i) {
int p = primes.get(i), qry = qryb(p);
remain -= qry;
if (++step == 100) {
if (remain < qrya(1)) {
for (int j = i + step - 1; j >= i; --j) {
if (qrya(primes.get(j)) > 0) {
prime_factorization.put(primes.get(j), 1);
found = true;
break out;
}
}
}
step = 0;
}
}
if (!found) {
if (remain < qrya(1)) {
for (int j = i + step; j > i; --j) {
if (qrya(primes.get(j)) > 0) {
prime_factorization.put(primes.get(j), 1);
break;
}
}
}
}
while (i >= 0 && primes.get(i) > sqrt) {
--i;
}
while (i >= 0) {
int p = primes.get(i), qry = p;
qryb(qry);
int mx = log(p, n), put = 0;
for (int l = 1, r = mx; l <= r; ) {
int m = l + (r - l) / 2;
if (qrya(powi(p, m)) > 0) {
put = m;
l = m + 1;
} else {
r = m - 1;
}
}
if (put > 0) {
prime_factorization.put(p, put);
}
--i;
}
int ans = 1;
for (int key : prime_factorization.keySet()) {
for (int j = 0; j < prime_factorization.get(key); ++j) {
ans *= key;
}
}
pr("C ");
prln(ans);
close();
}
static int qrya(int x) throws IOException {
pr("A ");
prln(x);
flush();
return ri();
}
static int qryb(int x) throws IOException {
pr("B ");
prln(x);
flush();
return ri();
}
static int log(int x, int n) {
int ans = 0;
while (n >= x) {
n /= x;
++ans;
}
return ans;
}
static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out));
static StringTokenizer input;
static Random __rand = new Random();
// references
// IBIG = 1e9 + 7
// IMAX ~= 2e9
// LMAX ~= 9e18
// constants
static final int IBIG = 1000000007;
static final int IMAX = 2147483647;
static final int IMIN = -2147483648;
static final long LMAX = 9223372036854775807L;
static final long LMIN = -9223372036854775808L;
// math util
static int minof(int a, int b, int c) {return min(a, min(b, c));}
static int minof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;}
static long minof(long a, long b, long c) {return min(a, min(b, c));}
static long minof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;}
static int maxof(int a, int b, int c) {return max(a, max(b, c));}
static int maxof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;}
static long maxof(long a, long b, long c) {return max(a, max(b, c));}
static long maxof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;}
static int powi(int a, int b) {if (a == 0) return 0; int ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static long powl(long a, int b) {if (a == 0) return 0; long ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static int fli(double d) {return (int) d;}
static int cei(double d) {return (int) ceil(d);}
static long fll(double d) {return (long) d;}
static long cel(double d) {return (long) ceil(d);}
static int gcf(int a, int b) {return b == 0 ? a : gcf(b, a % b);}
static long gcf(long a, long b) {return b == 0 ? a : gcf(b, a % b);}
static int lcm(int a, int b) {return a * b / gcf(a, b);}
static long lcm(long a, long b) {return a * b / gcf(a, b);}
static int randInt(int min, int max) {return __rand.nextInt(max - min + 1) + min;}
static long mix(long x) {x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31);}
// array util
static void reverse(int[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(long[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(double[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(char[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void shuffle(int[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void shuffle(long[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void shuffle(double[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void rsort(int[] a) {shuffle(a); sort(a);}
static void rsort(long[] a) {shuffle(a); sort(a);}
static void rsort(double[] a) {shuffle(a); sort(a);}
static int[] copy(int[] a) {int[] ans = new int[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static long[] copy(long[] a) {long[] ans = new long[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static double[] copy(double[] a) {double[] ans = new double[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static char[] copy(char[] a) {char[] ans = new char[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
// input
static void r() throws IOException {input = new StringTokenizer(rline());}
static int ri() throws IOException {return Integer.parseInt(rline());}
static long rl() throws IOException {return Long.parseLong(rline());}
static double rd() throws IOException {return Double.parseDouble(rline());}
static int[] ria(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni(); return a;}
static int[] riam1(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni() - 1; return a;}
static long[] rla(int n) throws IOException {long[] a = new long[n]; r(); for (int i = 0; i < n; ++i) a[i] = nl(); return a;}
static double[] rda(int n) throws IOException {double[] a = new double[n]; r(); for (int i = 0; i < n; ++i) a[i] = nd(); return a;}
static char[] rcha() throws IOException {return rline().toCharArray();}
static String rline() throws IOException {return __in.readLine();}
static String n() {return input.nextToken();}
static int rni() throws IOException {r(); return ni();}
static int ni() {return Integer.parseInt(n());}
static long rnl() throws IOException {r(); return nl();}
static long nl() {return Long.parseLong(n());}
static double rnd() throws IOException {r(); return nd();}
static double nd() {return Double.parseDouble(n());}
// output
static void pr(int i) {__out.print(i);}
static void prln(int i) {__out.println(i);}
static void pr(long l) {__out.print(l);}
static void prln(long l) {__out.println(l);}
static void pr(double d) {__out.print(d);}
static void prln(double d) {__out.println(d);}
static void pr(char c) {__out.print(c);}
static void prln(char c) {__out.println(c);}
static void pr(char[] s) {__out.print(new String(s));}
static void prln(char[] s) {__out.println(new String(s));}
static void pr(String s) {__out.print(s);}
static void prln(String s) {__out.println(s);}
static void pr(Object o) {__out.print(o);}
static void prln(Object o) {__out.println(o);}
static void prln() {__out.println();}
static void pryes() {prln("yes");}
static void pry() {prln("Yes");}
static void prY() {prln("YES");}
static void prno() {prln("no");}
static void prn() {prln("No");}
static void prN() {prln("NO");}
static boolean pryesno(boolean b) {prln(b ? "yes" : "no"); return b;};
static boolean pryn(boolean b) {prln(b ? "Yes" : "No"); return b;}
static boolean prYN(boolean b) {prln(b ? "YES" : "NO"); return b;}
static void prln(int... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();}
static void prln(long... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();}
static void prln(double... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();}
static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for (int i = 0; i < n; pr(iter.next()), pr(' '), ++i); if (n >= 0) prln(iter.next()); else prln();}
static void h() {prln("hlfd"); flush();}
static void flush() {__out.flush();}
static void close() {__out.close();}
} | Java | ["10\n\n2\n\n4\n\n0"] | 1 second | ["B 4\n\nA 2\n\nA 8\n\nC 4"] | NoteNote that to make the sample more clear, we added extra empty lines. You shouldn't print any extra empty lines during the interaction process.In the first test $$$n=10$$$ and $$$x=4$$$.Initially the set is: $$$\{1,2,3,4,5,6,7,8,9,10\}$$$.In the first operation, you ask how many numbers are multiples of $$$4$$$ and delete them. The answer is $$$2$$$ because there are two numbers divisible by $$$4$$$: $$$\{4,8\}$$$. $$$8$$$ will be deleted but $$$4$$$ won't, because the number $$$x$$$ will never be deleted. Now the set is $$$\{1,2,3,4,5,6,7,9,10\}$$$.In the second operation, you ask how many numbers are multiples of $$$2$$$. The answer is $$$4$$$ because there are four numbers divisible by $$$2$$$: $$$\{2,4,6,10\}$$$.In the third operation, you ask how many numbers are multiples of $$$8$$$. The answer is $$$0$$$ because there isn't any number divisible by $$$8$$$ in the current set.In the fourth operation, you know that $$$x=4$$$, which is the right answer. | Java 11 | standard input | [
"interactive",
"number theory",
"math"
] | 513480a6c7a715e237c3a63805208039 | The first line contains one integer $$$n$$$ ($$$1\le n\le 10^5$$$). The remaining parts of the input will be given throughout the interaction process. | 2,600 | null | standard output | |
PASSED | 38278f064a1b66a4fd28764488d8ccac | train_001.jsonl | 1599918300 | This is an interactive problem.There is an unknown integer $$$x$$$ ($$$1\le x\le n$$$). You want to find $$$x$$$.At first, you have a set of integers $$$\{1, 2, \ldots, n\}$$$. You can perform the following operations no more than $$$10000$$$ times: A $$$a$$$: find how many numbers are multiples of $$$a$$$ in the current set. B $$$a$$$: find how many numbers are multiples of $$$a$$$ in this set, and then delete all multiples of $$$a$$$, but $$$x$$$ will never be deleted (even if it is a multiple of $$$a$$$). In this operation, $$$a$$$ must be greater than $$$1$$$. C $$$a$$$: it means that you know that $$$x=a$$$. This operation can be only performed once. Remember that in the operation of type B $$$a>1$$$ must hold.Write a program, that will find the value of $$$x$$$. | 512 megabytes | import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.Flushable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.StringTokenizer;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
static class TaskAdapter implements Runnable {
@Override
public void run() {
long startTime = System.currentTimeMillis();
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Input in = new Input(inputStream);
Output out = new Output(outputStream);
EDeletingNumbers solver = new EDeletingNumbers();
solver.solve(1, in, out);
out.close();
System.err.println(System.currentTimeMillis()-startTime+"ms");
}
}
public static void main(String[] args) throws Exception {
Thread thread = new Thread(null, new TaskAdapter(), "", 1<<28);
thread.start();
thread.join();
}
static class EDeletingNumbers {
public EDeletingNumbers() {
}
public void solve(int kase, InputReader in, Output pw) {
int n = in.nextInt(), cnt = 0;
ArrayList<Integer> primes = Utilities.sieve(Math.max(316, n));
primes = new ArrayList<>(primes.subList(65, primes.size()));
int block = 98, size = n, ans = 1;
loop:
for(int i = 0; i<primes.size(); i += 98) {
int end = Math.min(primes.size(), i+98), cblock = 0;
for(int j = i; j<end; j++) {
cblock += n/primes.get(j);
pw.println("B "+(primes.get(j)));
cnt++;
}
pw.println("A 1");
pw.flush();
cnt++;
for(int j = i; j<end; j++) {
in.nextInt();
}
int response = in.nextInt();
if(response!=size-cblock) {
for(int j = i; j<end; j++) {
pw.println("A "+(primes.get(j)));
cnt++;
pw.flush();
response = in.nextInt();
if(response==1) {
ans = primes.get(j);
break loop;
}
}
}else {
size -= cblock;
}
}
primes = Utilities.sieve(316);
for(int p: primes) {
if(p>n) {
break;
}
pw.println("B "+p);
pw.println("A "+p);
cnt += 2;
pw.flush();
in.nextInt();
int response = in.nextInt();
if(response==1) {
long pow = p*p;
for(int i = 2; i<=18&&pow<=n; i++) {
pw.println("A "+pow);
cnt++;
pw.flush();
response = in.nextInt();
if(response==0) {
break;
}
pow *= p;
}
pow /= p;
ans *= pow;
}
}
Utilities.Debug.dbg(cnt);
pw.println("C "+ans);
cnt++;
pw.flush();
}
}
static class Input implements InputReader {
BufferedReader br;
StringTokenizer st;
public Input(InputStream is) {
this(is, 1<<20);
}
public Input(InputStream is, int bs) {
br = new BufferedReader(new InputStreamReader(is), bs);
st = new StringTokenizer("");
}
public boolean hasNext() {
try {
while(st==null||!st.hasMoreTokens()) {
String s = br.readLine();
if(s==null) {
return false;
}
st = new StringTokenizer(s);
}
return true;
}catch(Exception e) {
return false;
}
}
public String next() {
if(!hasNext()) {
throw new InputMismatchException();
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
static class Output implements Closeable, Flushable {
public StringBuilder sb;
public OutputStream os;
public int BUFFER_SIZE;
public String lineSeparator;
public Output(OutputStream os) {
this(os, 1<<16);
}
public Output(OutputStream os, int bs) {
BUFFER_SIZE = bs;
sb = new StringBuilder(BUFFER_SIZE);
this.os = new BufferedOutputStream(os, 1<<17);
lineSeparator = System.lineSeparator();
}
public void println(String s) {
sb.append(s);
println();
if(sb.length()>BUFFER_SIZE >> 1) {
flushToBuffer();
}
}
public void println() {
sb.append(lineSeparator);
}
private void flushToBuffer() {
try {
os.write(sb.toString().getBytes());
}catch(IOException e) {
e.printStackTrace();
}
sb = new StringBuilder(BUFFER_SIZE);
}
public void flush() {
try {
flushToBuffer();
os.flush();
}catch(IOException e) {
e.printStackTrace();
}
}
public void close() {
flush();
try {
os.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
static interface InputReader {
int nextInt();
}
static class Utilities {
public static ArrayList<Integer> sieve(int n) {
ArrayList<Integer> ans = new ArrayList<>();
boolean[] prime = new boolean[n+1];
Arrays.fill(prime, true);
for(int i = 2; i<=n; i++) {
if(prime[i]) {
ans.add(i);
}
if((long) i*i>n) {
continue;
}
for(int j = i*i; j<=n; j += i) {
prime[j] = false;
}
}
return ans;
}
public static class Debug {
public static final boolean LOCAL = System.getProperty("ONLINE_JUDGE")==null;
private static <T> String ts(T t) {
if(t==null) {
return "null";
}
try {
return ts((Iterable) t);
}catch(ClassCastException e) {
if(t instanceof int[]) {
String s = Arrays.toString((int[]) t);
return "{"+s.substring(1, s.length()-1)+"}";
}else if(t instanceof long[]) {
String s = Arrays.toString((long[]) t);
return "{"+s.substring(1, s.length()-1)+"}";
}else if(t instanceof char[]) {
String s = Arrays.toString((char[]) t);
return "{"+s.substring(1, s.length()-1)+"}";
}else if(t instanceof double[]) {
String s = Arrays.toString((double[]) t);
return "{"+s.substring(1, s.length()-1)+"}";
}else if(t instanceof boolean[]) {
String s = Arrays.toString((boolean[]) t);
return "{"+s.substring(1, s.length()-1)+"}";
}
try {
return ts((Object[]) t);
}catch(ClassCastException e1) {
return t.toString();
}
}
}
private static <T> String ts(T[] arr) {
StringBuilder ret = new StringBuilder();
ret.append("{");
boolean first = true;
for(T t: arr) {
if(!first) {
ret.append(", ");
}
first = false;
ret.append(ts(t));
}
ret.append("}");
return ret.toString();
}
private static <T> String ts(Iterable<T> iter) {
StringBuilder ret = new StringBuilder();
ret.append("{");
boolean first = true;
for(T t: iter) {
if(!first) {
ret.append(", ");
}
first = false;
ret.append(ts(t));
}
ret.append("}");
return ret.toString();
}
public static void dbg(Object... o) {
if(LOCAL) {
System.err.print("Line #"+Thread.currentThread().getStackTrace()[2].getLineNumber()+": [");
for(int i = 0; i<o.length; i++) {
if(i!=0) {
System.err.print(", ");
}
System.err.print(ts(o[i]));
}
System.err.println("]");
}
}
}
}
}
| Java | ["10\n\n2\n\n4\n\n0"] | 1 second | ["B 4\n\nA 2\n\nA 8\n\nC 4"] | NoteNote that to make the sample more clear, we added extra empty lines. You shouldn't print any extra empty lines during the interaction process.In the first test $$$n=10$$$ and $$$x=4$$$.Initially the set is: $$$\{1,2,3,4,5,6,7,8,9,10\}$$$.In the first operation, you ask how many numbers are multiples of $$$4$$$ and delete them. The answer is $$$2$$$ because there are two numbers divisible by $$$4$$$: $$$\{4,8\}$$$. $$$8$$$ will be deleted but $$$4$$$ won't, because the number $$$x$$$ will never be deleted. Now the set is $$$\{1,2,3,4,5,6,7,9,10\}$$$.In the second operation, you ask how many numbers are multiples of $$$2$$$. The answer is $$$4$$$ because there are four numbers divisible by $$$2$$$: $$$\{2,4,6,10\}$$$.In the third operation, you ask how many numbers are multiples of $$$8$$$. The answer is $$$0$$$ because there isn't any number divisible by $$$8$$$ in the current set.In the fourth operation, you know that $$$x=4$$$, which is the right answer. | Java 11 | standard input | [
"interactive",
"number theory",
"math"
] | 513480a6c7a715e237c3a63805208039 | The first line contains one integer $$$n$$$ ($$$1\le n\le 10^5$$$). The remaining parts of the input will be given throughout the interaction process. | 2,600 | null | standard output | |
PASSED | 5f41e8613b5e1c2362e1367fa92b0e81 | train_001.jsonl | 1599918300 | This is an interactive problem.There is an unknown integer $$$x$$$ ($$$1\le x\le n$$$). You want to find $$$x$$$.At first, you have a set of integers $$$\{1, 2, \ldots, n\}$$$. You can perform the following operations no more than $$$10000$$$ times: A $$$a$$$: find how many numbers are multiples of $$$a$$$ in the current set. B $$$a$$$: find how many numbers are multiples of $$$a$$$ in this set, and then delete all multiples of $$$a$$$, but $$$x$$$ will never be deleted (even if it is a multiple of $$$a$$$). In this operation, $$$a$$$ must be greater than $$$1$$$. C $$$a$$$: it means that you know that $$$x=a$$$. This operation can be only performed once. Remember that in the operation of type B $$$a>1$$$ must hold.Write a program, that will find the value of $$$x$$$. | 512 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.StringTokenizer;
public class problemE {
static final int MAXN = 1_000_00;
static ArrayList<Integer> primes = new ArrayList<>();
private static void getPrimes() {
boolean[] dp = new boolean[MAXN];
Arrays.fill(dp, true);
for (int i = 2; i < MAXN; i ++ ) {
if (dp[i]) {
primes.add(i);
for (long j = (long)i*i; j < MAXN; j += i ) {
dp[(int) j] = false;
}
}
}
}
static HashSet<Integer> hs = new HashSet<>();
private static void solve() throws Exception {
getPrimes();
int n = fs.nextInt();
if (manual) {
for (int i = 1; i <= n; i ++ ) hs.add(i);
}
long ans = 1;
for (int p : primes) {
if (p <= 317 && p <= n) {
query('B', p);
int curr = p;
while (curr <= n) {
int res = query('A', curr);
if (res > 0) {
curr *= p;
ans *= p;
} else {
break ;
}
}
} else {
break;
}
}
int bucketSize = 100;
int expectedSize = query('A', 1);
ArrayList<Integer> lastQueries = new ArrayList<>(bucketSize);
for (int p : primes) {
if (p > 317 && p <= n) {
int expectedDeletes = query('B', p);
lastQueries.add(p);
expectedSize -= expectedDeletes;
if (lastQueries.size() == bucketSize) {
int gotSize = query('A', 1);
if (gotSize == expectedSize) {
lastQueries = new ArrayList<>(bucketSize);
} else {
break;
}
}
}
}
for (int p : lastQueries) {
int res = query('A', p);
if (res > 0) {
ans *= p;
}
}
System.out.println("C " + ans);
System.out.flush();
}
static boolean manual = false;
static int choosen = 99874;
static int totalQueries = 0;
private static int query(char type, int val) {
System.out.println(type + " " + val);
System.out.flush();
totalQueries++;
return manual ? answer(type, val) : fs.nextInt();
}
private static int answer(char type, int val) {
if (type == 'A') {
int count = 0 ;
for (int x : hs) if (x % val == 0) count++;
if (val == 49937) debug("answer", type, val, count);
return count;
} else if (type == 'B') {
ArrayList<Integer> toRemove = new ArrayList<>();
for (int x : hs) if (x % val == 0) toRemove.add(x);
for (int x: toRemove) hs.remove(x);
hs.add(choosen);
if (val == 49937) debug("answer", type, val, toRemove);
return toRemove.size();
}
return 0;
}
private static FastScanner fs = new FastScanner();
private static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) throws Exception {
int T = 1;
for (int t = 0; t < T; t++) {
solve();
}
out.close();
}
static void debug(Object... O) {
System.err.print("DEBUG ");
System.err.println(Arrays.deepToString(O));
}
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextString() {
return next();
}
}
}
| Java | ["10\n\n2\n\n4\n\n0"] | 1 second | ["B 4\n\nA 2\n\nA 8\n\nC 4"] | NoteNote that to make the sample more clear, we added extra empty lines. You shouldn't print any extra empty lines during the interaction process.In the first test $$$n=10$$$ and $$$x=4$$$.Initially the set is: $$$\{1,2,3,4,5,6,7,8,9,10\}$$$.In the first operation, you ask how many numbers are multiples of $$$4$$$ and delete them. The answer is $$$2$$$ because there are two numbers divisible by $$$4$$$: $$$\{4,8\}$$$. $$$8$$$ will be deleted but $$$4$$$ won't, because the number $$$x$$$ will never be deleted. Now the set is $$$\{1,2,3,4,5,6,7,9,10\}$$$.In the second operation, you ask how many numbers are multiples of $$$2$$$. The answer is $$$4$$$ because there are four numbers divisible by $$$2$$$: $$$\{2,4,6,10\}$$$.In the third operation, you ask how many numbers are multiples of $$$8$$$. The answer is $$$0$$$ because there isn't any number divisible by $$$8$$$ in the current set.In the fourth operation, you know that $$$x=4$$$, which is the right answer. | Java 11 | standard input | [
"interactive",
"number theory",
"math"
] | 513480a6c7a715e237c3a63805208039 | The first line contains one integer $$$n$$$ ($$$1\le n\le 10^5$$$). The remaining parts of the input will be given throughout the interaction process. | 2,600 | null | standard output | |
PASSED | 50085779aa0eed08fd8cf5dc8e2836b4 | train_001.jsonl | 1397749200 | One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.The appointed Judge was the most experienced member — Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table. | 256 megabytes | import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author @thnkndblv
*/
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);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
}
class TaskC {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int k = in.nextInt();
if ( 2 * k > (n - 1) ) out.println( -1 );
else {
boolean[][] done = new boolean[n + 1][n + 1];
out.println( n * k );
for (int i = 1; i <= n; i++) {
for (int j = 1, count = 0; j <= n && count < k; j++) if ( i != j && !done[j][i] ) {
count++;
out.println(i + " " + j);
done[i][j] = true;
}
}
}
}
}
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 | ["3 1"] | 1 second | ["3\n1 2\n2 3\n3 1"] | null | Java 7 | standard input | [
"constructive algorithms",
"implementation",
"graphs"
] | 14570079152bbf6c439bfceef9816f7e | The first line contains two integers — n and k (1 ≤ n, k ≤ 1000). | 1,400 | In the first line print an integer m — number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n. If a tournir that meets the conditions of the problem does not exist, then print -1. | standard output | |
PASSED | 4580c289d25029da7efc35e82d6b1638 | train_001.jsonl | 1397749200 | One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.The appointed Judge was the most experienced member — Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table. | 256 megabytes | import java.io.*;
import java.util.*;
public final class football
{
static BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
static FastScanner sc=new FastScanner(br);
static PrintWriter out=new PrintWriter(System.out);
public static void main(String args[]) throws Exception
{
int n=sc.nextInt(),k=sc.nextInt();
boolean ans=true,v[][]=new boolean[n+1][n+1];
for(int i=1;i<=n;i++)
{
int cnt=0;
for(int j=1;j<=n;j++)
{
if(i!=j)
{
if(cnt==k)
{
break;
}
if(!v[j][i])
{
cnt++;
v[i][j]=true;
}
}
}
if(cnt<k)
{
ans=false;
break;
}
}
if(ans)
{
out.println(n*k);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if(v[i][j])
{
out.println(i+" "+j);
}
}
}
}
else
{
out.println(-1);
}
out.close();
}
}
class Pair
{
int l,r;
public Pair(int l,int r)
{
this.l=l;
this.r=r;
}
}
class FastScanner
{
BufferedReader in;
StringTokenizer st;
public FastScanner(BufferedReader in) {
this.in = in;
}
public String nextToken() throws Exception {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
public String next() throws Exception {
return nextToken().toString();
}
public int nextInt() throws Exception {
return Integer.parseInt(nextToken());
}
public long nextLong() throws Exception {
return Long.parseLong(nextToken());
}
public double nextDouble() throws Exception {
return Double.parseDouble(nextToken());
}
} | Java | ["3 1"] | 1 second | ["3\n1 2\n2 3\n3 1"] | null | Java 7 | standard input | [
"constructive algorithms",
"implementation",
"graphs"
] | 14570079152bbf6c439bfceef9816f7e | The first line contains two integers — n and k (1 ≤ n, k ≤ 1000). | 1,400 | In the first line print an integer m — number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n. If a tournir that meets the conditions of the problem does not exist, then print -1. | standard output | |
PASSED | b054d30dd2512399cf460946241f6233 | train_001.jsonl | 1397749200 | One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.The appointed Judge was the most experienced member — Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
import static java.util.Arrays.*;
import static java.lang.Math.*;
import static java.util.Collections.*;
import static java.lang.System.out;
public class Main {
static boolean LOCAL = System.getSecurityManager() == null;
Scanner in = new Scanner(System.in);
void run() {
while (in.hasNext())
solve();
}
private void solve() {
int n = in.nextInt(), k = in.nextInt();
if (k > (n - 1) / 2) {
out.println(-1);
return ;
}
StringBuilder sb = new StringBuilder();
sb.append(n * k);
sb.append(System.lineSeparator());
boolean[][] vis = new boolean[n + 1][n + 1];
for (int i = 0; i <= n; i++) vis[i][i] = true;
for (int i = 1; i <= n; i++) {
for (int j = 1, c = 0; c < k; j++) {
if (!vis[i][j]) {
vis[j][i] = vis[i][j] = true;
c++;
// out.println(i + " " + j);
sb.append(i);
sb.append(' ');
sb.append(j);
sb.append(System.lineSeparator());
}
}
}
out.print(sb);
}
void debug(Object... os) {
System.err.println(deepToString(os));
}
public static void main(String[] args) {
if (LOCAL) {
try {
System.setIn(new FileInputStream("./../in"));
} catch (IOException e) {
LOCAL = false;
}
}
long start = System.nanoTime();
new Main().run();
if (LOCAL)
System.err.printf("[Time %.6fs]%n",
(System.nanoTime() - start) * 1e-9);
}
}
class Scanner {
BufferedReader br;
StringTokenizer st;
Scanner(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
eat("");
}
private void eat(String string) {
st = new StringTokenizer(string);
}
String nextLine() {
try {
return br.readLine();
} catch (IOException e) {
return null;
}
}
boolean hasNext() {
while (!st.hasMoreTokens()) {
String s = nextLine();
if (s == null)
return false;
eat(s);
}
return true;
}
String next() {
hasNext();
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
} | Java | ["3 1"] | 1 second | ["3\n1 2\n2 3\n3 1"] | null | Java 7 | standard input | [
"constructive algorithms",
"implementation",
"graphs"
] | 14570079152bbf6c439bfceef9816f7e | The first line contains two integers — n and k (1 ≤ n, k ≤ 1000). | 1,400 | In the first line print an integer m — number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n. If a tournir that meets the conditions of the problem does not exist, then print -1. | standard output | |
PASSED | 83783b8c4420caa1bc399f060de6076a | train_001.jsonl | 1397749200 | One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.The appointed Judge was the most experienced member — Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
import static java.util.Arrays.*;
import static java.lang.Math.*;
import static java.util.Collections.*;
public class Main {
static boolean LOCAL = System.getSecurityManager() == null;
Scanner in = new Scanner(System.in);
static PrintWriter out = new PrintWriter(System.out);
void run() {
while (in.hasNext())
solve();
}
private void solve() {
int n = in.nextInt(), k = in.nextInt();
if (k > (n - 1) / 2) {
out.println(-1);
return ;
}
out.println(n * k);
boolean[][] vis = new boolean[n + 1][n + 1];
for (int i = 0; i <= n; i++) vis[i][i] = true;
for (int i = 1; i <= n; i++) {
for (int j = 1, c = 0; c < k; j++) {
if (!vis[i][j]) {
vis[j][i] = vis[i][j] = true;
c++;
out.println(i + " " + j);
}
}
}
}
void debug(Object... os) {
System.err.println(deepToString(os));
}
public static void main(String[] args) {
if (LOCAL) {
try {
System.setIn(new FileInputStream("./../in"));
} catch (IOException e) {
LOCAL = false;
}
}
long start = System.nanoTime();
new Main().run();
out.close();
if (LOCAL)
System.err.printf("[Time %.6fs]%n",
(System.nanoTime() - start) * 1e-9);
}
}
class Scanner {
BufferedReader br;
StringTokenizer st;
Scanner(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
eat("");
}
private void eat(String string) {
st = new StringTokenizer(string);
}
String nextLine() {
try {
return br.readLine();
} catch (IOException e) {
return null;
}
}
boolean hasNext() {
while (!st.hasMoreTokens()) {
String s = nextLine();
if (s == null)
return false;
eat(s);
}
return true;
}
String next() {
hasNext();
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
} | Java | ["3 1"] | 1 second | ["3\n1 2\n2 3\n3 1"] | null | Java 7 | standard input | [
"constructive algorithms",
"implementation",
"graphs"
] | 14570079152bbf6c439bfceef9816f7e | The first line contains two integers — n and k (1 ≤ n, k ≤ 1000). | 1,400 | In the first line print an integer m — number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n. If a tournir that meets the conditions of the problem does not exist, then print -1. | standard output | |
PASSED | 17f29f438f9164897815bfc7ecf79389 | train_001.jsonl | 1397749200 | One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.The appointed Judge was the most experienced member — Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table. | 256 megabytes | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Locale;
import java.util.StringTokenizer;
public class RCC_A {
static StringTokenizer st;
static BufferedReader br;
static PrintWriter pw;
public static void main(String[] args) throws IOException {
Locale.setDefault(Locale.US);
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
System.out)));
int n = nextInt(), k = nextInt();
if ((n - 1) / 2 >= k) {
pw.println(n * k);
for (int i = 1; i <= n; i++) {
int h = i;
for (int j = 1; j <= k; j++) {
h++;
if (h > n)
h = 1;
pw.println(i + " " + h);
}
}
} else {
System.out.println(-1);
}
pw.close();
}
private static int nextInt() throws IOException {
return Integer.parseInt(next());
}
private static long nextLong() throws IOException {
return Long.parseLong(next());
}
private static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
private static String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
}
| Java | ["3 1"] | 1 second | ["3\n1 2\n2 3\n3 1"] | null | Java 7 | standard input | [
"constructive algorithms",
"implementation",
"graphs"
] | 14570079152bbf6c439bfceef9816f7e | The first line contains two integers — n and k (1 ≤ n, k ≤ 1000). | 1,400 | In the first line print an integer m — number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n. If a tournir that meets the conditions of the problem does not exist, then print -1. | standard output | |
PASSED | 7509e92272ad0d49257fc0deee828f4a | train_001.jsonl | 1397749200 | One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.The appointed Judge was the most experienced member — Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Exercise3 implements Runnable {
static BufferedReader in;
static PrintWriter out;
static StringTokenizer st;
private void solve() throws IOException {
int teamsCount = nextInt();
int wins = nextInt();
int sumWins = (teamsCount * teamsCount - teamsCount) / 2;
if (sumWins < wins * teamsCount) {
out.print(-1);
} else {
out.println(wins * teamsCount);
for (int i = 0; i < teamsCount; i++) {
for (int j = 0; j < wins; j++) {
int nextTeam = i + j + 2;
if (nextTeam > teamsCount) {
nextTeam = nextTeam % teamsCount;
}
out.println((i + 1) + " " + nextTeam);
}
}
}
}
public static void main(String[] args) {
new Exercise3().run();
}
@Override
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
} catch (IOException e) {
e.printStackTrace(System.err);
System.exit(1);
}
}
private String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String line = in.readLine();
if (line == null) {
return null;
}
st = new StringTokenizer(line);
}
return st.nextToken();
}
private int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
private long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
private double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
}
| Java | ["3 1"] | 1 second | ["3\n1 2\n2 3\n3 1"] | null | Java 7 | standard input | [
"constructive algorithms",
"implementation",
"graphs"
] | 14570079152bbf6c439bfceef9816f7e | The first line contains two integers — n and k (1 ≤ n, k ≤ 1000). | 1,400 | In the first line print an integer m — number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n. If a tournir that meets the conditions of the problem does not exist, then print -1. | standard output | |
PASSED | b0906b0f7939e16ab34a90e7e50c942c | train_001.jsonl | 1397749200 | One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.The appointed Judge was the most experienced member — Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table. | 256 megabytes | import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Formatter;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Set;
import java.util.SortedSet;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class Main
{
private static BufferedReader in;
private static BufferedWriter out;
private static int n;
private static int k;
public static void main(String... args) throws IOException
{
// streams
boolean file = false;
if (file)
in = new BufferedReader(new FileReader("input.txt"));
else
in = new BufferedReader(new InputStreamReader(System.in));
out = new BufferedWriter(new OutputStreamWriter(System.out));
// out = new BufferedWriter(new FileWriter("output.txt"));
StringTokenizer tok;
// read params
tok = new StringTokenizer(in.readLine());
n =Integer.parseInt(tok.nextToken());
k =Integer.parseInt(tok.nextToken());
// solve
solve();
out.flush();
}
private static void solve() throws IOException
{
// check we can make those k
int maxEdges = n * (n-1) / 2;
int maxGames = (maxEdges / n) * n;
if (k*n > maxGames )
{
out.write("-1\n");
return;
}
// output
out.write(k*n + "\n");
for (int g = 1; g <= k; g++)
{
for (int i = 1; i <= n; i++)
{
int a = i;
int b = i + g;
if (b > n)
b-= n;
out.write(a + " " + b + "\n");
}
}
}
}
| Java | ["3 1"] | 1 second | ["3\n1 2\n2 3\n3 1"] | null | Java 7 | standard input | [
"constructive algorithms",
"implementation",
"graphs"
] | 14570079152bbf6c439bfceef9816f7e | The first line contains two integers — n and k (1 ≤ n, k ≤ 1000). | 1,400 | In the first line print an integer m — number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n. If a tournir that meets the conditions of the problem does not exist, then print -1. | standard output | |
PASSED | e29b6ce3293a6254a7e11dd847202192 | train_001.jsonl | 1397749200 | One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.The appointed Judge was the most experienced member — Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table. | 256 megabytes | import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class C {
public static void main(String[] args) throws IOException {
Scanner scan = new Scanner(System.in);
PrintWriter wrt = new PrintWriter(System.out);
int n = scan.nextInt();
int k = scan.nextInt();
if(2*k + 1 > n){
System.out.println(-1);
return;
}
int m = n * k;
wrt.println(m);
for (int i = 0; i < n; i++){
for (int j = 0; j < k; j++){
wrt.println((i + 1) + " " + ((j + i + 1) % n + 1));
}
}
wrt.flush();
}
}
| Java | ["3 1"] | 1 second | ["3\n1 2\n2 3\n3 1"] | null | Java 7 | standard input | [
"constructive algorithms",
"implementation",
"graphs"
] | 14570079152bbf6c439bfceef9816f7e | The first line contains two integers — n and k (1 ≤ n, k ≤ 1000). | 1,400 | In the first line print an integer m — number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n. If a tournir that meets the conditions of the problem does not exist, then print -1. | standard output | |
PASSED | 591e68b209cf570b1dc3a89f1b09e786 | train_001.jsonl | 1397749200 | One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.The appointed Judge was the most experienced member — Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table. | 256 megabytes | import java.io.*;
import java.math.BigInteger;
import java.util.*;
import java.util.Map.Entry;
public class Main {
public static void main(String[] args) throws IOException {
(new Main()).solve();
}
public Main() {
}
MyReader in = new MyReader();
PrintWriter out = new PrintWriter(System.out);
void solve() throws IOException {
//BufferedReader in = new BufferedReader(new
//InputStreamReader(System.in));
//Scanner in = new Scanner(System.in);
Locale.setDefault(Locale.US);
//Scanner in = new Scanner(new FileReader("input.in"));
//PrintWriter out = new PrintWriter("output.txt");
int n = in.nextInt();
int k = in.nextInt();
int m = n * k;
if (m > n * (n - 1) / 2) {
out.println(-1);
} else {
out.println(m);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= k; j++) {
int t = i + j;
if (t > n) {
t -= n;
}
out.print(i);
out.print(' ');
out.println(t);
}
}
}
out.close();
}
class MyReader {
private BufferedReader in;
String[] parsed;
int index = 0;
public MyReader() {
in = new BufferedReader(new InputStreamReader(System.in));
}
public int nextInt() throws NumberFormatException, IOException {
if (parsed == null || parsed.length == index) {
read();
}
return Integer.parseInt(parsed[index++]);
}
public long nextLong() throws NumberFormatException, IOException {
if (parsed == null || parsed.length == index) {
read();
}
return Long.parseLong(parsed[index++]);
}
public double nextDouble() throws NumberFormatException, IOException {
if (parsed == null || parsed.length == index) {
read();
}
return Double.parseDouble(parsed[index++]);
}
public String nextString() throws IOException {
if (parsed == null || parsed.length == index) {
read();
}
return parsed[index++];
}
private void read() throws IOException {
parsed = in.readLine().split(" ");
index = 0;
}
public String readLine() throws IOException {
return in.readLine();
}
public int read(char[] cbuf) throws IOException {
return in.read(cbuf);
}
}
}; | Java | ["3 1"] | 1 second | ["3\n1 2\n2 3\n3 1"] | null | Java 7 | standard input | [
"constructive algorithms",
"implementation",
"graphs"
] | 14570079152bbf6c439bfceef9816f7e | The first line contains two integers — n and k (1 ≤ n, k ≤ 1000). | 1,400 | In the first line print an integer m — number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n. If a tournir that meets the conditions of the problem does not exist, then print -1. | standard output | |
PASSED | 9455e7bfdb5fc09aea8c22d6b915567f | train_001.jsonl | 1560090900 | You are given an undirected unweighted connected graph consisting of $$$n$$$ vertices and $$$m$$$ edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.Your task is to choose at most $$$\lfloor\frac{n}{2}\rfloor$$$ vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices.It is guaranteed that the answer exists. If there are multiple answers, you can print any.You will be given multiple independent queries to answer. | 256 megabytes | import java.util.*;
import java.io.*;
public class coverit {
public static void main(String[] args) {
FastScanner sc = new FastScanner();
PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out));
int n = sc.nextInt();
while(n-->0) {
int x = sc.nextInt();
int y = sc.nextInt();
graph g = new graph(x);
while(y-->0) {
g.addEdge(sc.nextInt()-1, sc.nextInt()-1);
}
g.bfs(1);
int c=0;
for(int i=0;i<x;i++) {
c+=g.d[i]%2;
}
if(c<x-c) {
pw.println(c);
for(int i=0;i<g.d.length;i++) {
if(g.d[i]%2==1)pw.print(i+1+" ");
}
pw.println();
}
else {
pw.println(x-c);
for(int i=0;i<g.d.length;i++) {
if(g.d[i]%2==0)pw.print(i+1+" ");
}
pw.println();
}
}
pw.close();
}
}
class graph{
int vertexct;
ArrayList<Integer> adjlist[];
int[] d;
public graph(int vertexct) {
this.vertexct=vertexct;
adjlist= new ArrayList[vertexct];
for(int i=0;i<vertexct;i++) {
adjlist[i]=new ArrayList<Integer>();
}
}
public void addEdge(int start, int to) {
adjlist[start].add(to);
adjlist[to].add(start);
}
public void bfs(int n) {
Queue<Integer> need = new LinkedList<Integer>();
boolean visited[] = new boolean[vertexct];
need.add(0);
d = new int[vertexct];
Arrays.fill(d, -1);
d[0]=0;
int temp=0;
while(!need.isEmpty()) {
temp=need.poll();
for(int x : adjlist[temp]) {
if(d[x]==-1) {
need.add(x);
d[x]=d[temp]^1;
}
}
}
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(String s) {
try {
br = new BufferedReader(new FileReader(s));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String nextToken() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
} | Java | ["2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4\n6 8\n2 5\n5 4\n4 3\n4 1\n1 3\n2 3\n2 6\n5 6"] | 2 seconds | ["2\n1 3\n3\n4 3 6"] | NoteIn the first query any vertex or any pair of vertices will suffice. Note that you don't have to minimize the number of chosen vertices. In the second query two vertices can be enough (vertices $$$2$$$ and $$$4$$$) but three is also ok. | Java 8 | standard input | [
"graphs",
"shortest paths",
"dsu",
"dfs and similar",
"trees"
] | c343e6a298c12cb1257aecf823f2ead0 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^5$$$) — the number of queries. Then $$$t$$$ queries follow. The first line of each query contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n - 1 \le m \le min(2 \cdot 10^5, \frac{n(n-1)}{2})$$$) — the number of vertices and the number of edges, respectively. The following $$$m$$$ lines denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no self-loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the list of edges, and for each pair ($$$v_i, u_i$$$) the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that $$$\sum m \le 2 \cdot 10^5$$$ over all queries. | 1,700 | For each query print two lines. In the first line print $$$k$$$ ($$$1 \le \lfloor\frac{n}{2}\rfloor$$$) — the number of chosen vertices. In the second line print $$$k$$$ distinct integers $$$c_1, c_2, \dots, c_k$$$ in any order, where $$$c_i$$$ is the index of the $$$i$$$-th chosen vertex. It is guaranteed that the answer exists. If there are multiple answers, you can print any. | standard output | |
PASSED | 1d5abac5b8a8469e54441c392d91fc71 | train_001.jsonl | 1560090900 | You are given an undirected unweighted connected graph consisting of $$$n$$$ vertices and $$$m$$$ edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.Your task is to choose at most $$$\lfloor\frac{n}{2}\rfloor$$$ vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices.It is guaranteed that the answer exists. If there are multiple answers, you can print any.You will be given multiple independent queries to answer. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(in.readLine());
PrintWriter out = new PrintWriter(System.out);
for (int test = 0; test < t; test++) {
StringTokenizer st = new StringTokenizer(in.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
ArrayList<Integer>[] adj = new ArrayList[n+1];
for (int i = 0; i <= n; i++) {
adj[i] = new ArrayList<>();
}
for (int i = 0; i < m; i++) {
st = new StringTokenizer(in.readLine());
int u = Integer.parseInt(st.nextToken());
int v = Integer.parseInt(st.nextToken());
adj[u].add(v);
adj[v].add(u);
}
int[] dist = new int[n+1];
boolean[] vis = new boolean[n+1];
vis[1] = true;
dist[1] = 0;
Queue<Integer> queue = new LinkedList<>();
queue.offer(1);
while (!queue.isEmpty()) {
int node = queue.poll();
for (int v : adj[node]) {
if (!vis[v]) {
queue.offer(v);
dist[v] = dist[node] + 1;
vis[v] = true;
}
}
}
int odd = 0;
int even = 0;
for (int i = 1; i <= n; i++) {
if (dist[i] % 2 == 0) {
even++;
} else {
odd++;
}
}
int donate = n/2;
boolean[] chosen = new boolean[n+1];
for (int i = 1; i <= n; i++) {
if (dist[i] % 2 == 0 && even <= odd && donate > 0) {
chosen[i] = true;
donate--;
}
if (dist[i] % 2 == 1 && odd < even && donate > 0) {
chosen[i] = true;
donate--;
}
}
int res = 0;
int[] a = new int[n+1];
for (int i = 1; i <= n; i++) {
if (chosen[i]) {
a[res] = i;
res++;
}
}
out.println(res);
for (int i = 0; i < res; i++) {
if (i > 0) {
out.print(' ');
}
out.print(a[i]);
}
out.print('\n');
}
out.close();
}
}
/*
*/ | Java | ["2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4\n6 8\n2 5\n5 4\n4 3\n4 1\n1 3\n2 3\n2 6\n5 6"] | 2 seconds | ["2\n1 3\n3\n4 3 6"] | NoteIn the first query any vertex or any pair of vertices will suffice. Note that you don't have to minimize the number of chosen vertices. In the second query two vertices can be enough (vertices $$$2$$$ and $$$4$$$) but three is also ok. | Java 8 | standard input | [
"graphs",
"shortest paths",
"dsu",
"dfs and similar",
"trees"
] | c343e6a298c12cb1257aecf823f2ead0 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^5$$$) — the number of queries. Then $$$t$$$ queries follow. The first line of each query contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n - 1 \le m \le min(2 \cdot 10^5, \frac{n(n-1)}{2})$$$) — the number of vertices and the number of edges, respectively. The following $$$m$$$ lines denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no self-loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the list of edges, and for each pair ($$$v_i, u_i$$$) the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that $$$\sum m \le 2 \cdot 10^5$$$ over all queries. | 1,700 | For each query print two lines. In the first line print $$$k$$$ ($$$1 \le \lfloor\frac{n}{2}\rfloor$$$) — the number of chosen vertices. In the second line print $$$k$$$ distinct integers $$$c_1, c_2, \dots, c_k$$$ in any order, where $$$c_i$$$ is the index of the $$$i$$$-th chosen vertex. It is guaranteed that the answer exists. If there are multiple answers, you can print any. | standard output | |
PASSED | 200bb2d8d9ea3a81c1951d0e4b397f40 | train_001.jsonl | 1560090900 | You are given an undirected unweighted connected graph consisting of $$$n$$$ vertices and $$$m$$$ edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.Your task is to choose at most $$$\lfloor\frac{n}{2}\rfloor$$$ vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices.It is guaranteed that the answer exists. If there are multiple answers, you can print any.You will be given multiple independent queries to answer. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
Reader in = new Reader();
int t = in.nextInt();
PrintWriter out = new PrintWriter(System.out);
for (int test = 0; test < t; test++) {
int nodes = in.nextInt();
int edges = in.nextInt();
HashMap<Integer, ArrayList<Integer>> adj = new HashMap<>();
for (int i = 0; i < edges; i++) {
int u = in.nextInt();
int v = in.nextInt();
connect(u, v, adj);
connect(v, u, adj);
}
Queue<Integer> queue = new LinkedList<>();
boolean[] vis = new boolean[nodes+1];
int[] dist = new int[nodes+1];
queue.offer(1);
int oddNodes = 0;
int evenNodes = 0;
while (!queue.isEmpty()) {
int node = queue.poll();
if (adj.containsKey(node)) {
for (int y : adj.get(node)) {
if (!vis[y]) {
queue.offer(y);
dist[y] = dist[node]+1;
vis[y] = true;
}
}
}
vis[node] = true;
if (dist[node] % 2 == 0) {
evenNodes++;
} else {
oddNodes++;
}
}
if (evenNodes < oddNodes) {
out.println(evenNodes);
for (int i = 1; i <= nodes; i++) {
if (dist[i] % 2 == 0) {
out.print(i + " ");
}
}
out.print("\n");
} else {
out.println(oddNodes);
for (int i = 1; i <= nodes; i++) {
if (dist[i] % 2 != 0) {
out.print(i + " ");
}
}
out.print("\n");
}
}
out.close();
}
static void connect(int x, int y, HashMap<Integer, ArrayList<Integer>> adj) {
if (adj.containsKey(x)) {
ArrayList<Integer> list = adj.get(x);
list.add(y);
adj.put(x, list);
} else {
ArrayList<Integer> list = new ArrayList<>();
list.add(y);
adj.put(x, list);
}
}
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 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;
}
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++];
}
}
}
/*
*/
/*
*/ | Java | ["2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4\n6 8\n2 5\n5 4\n4 3\n4 1\n1 3\n2 3\n2 6\n5 6"] | 2 seconds | ["2\n1 3\n3\n4 3 6"] | NoteIn the first query any vertex or any pair of vertices will suffice. Note that you don't have to minimize the number of chosen vertices. In the second query two vertices can be enough (vertices $$$2$$$ and $$$4$$$) but three is also ok. | Java 8 | standard input | [
"graphs",
"shortest paths",
"dsu",
"dfs and similar",
"trees"
] | c343e6a298c12cb1257aecf823f2ead0 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^5$$$) — the number of queries. Then $$$t$$$ queries follow. The first line of each query contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n - 1 \le m \le min(2 \cdot 10^5, \frac{n(n-1)}{2})$$$) — the number of vertices and the number of edges, respectively. The following $$$m$$$ lines denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no self-loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the list of edges, and for each pair ($$$v_i, u_i$$$) the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that $$$\sum m \le 2 \cdot 10^5$$$ over all queries. | 1,700 | For each query print two lines. In the first line print $$$k$$$ ($$$1 \le \lfloor\frac{n}{2}\rfloor$$$) — the number of chosen vertices. In the second line print $$$k$$$ distinct integers $$$c_1, c_2, \dots, c_k$$$ in any order, where $$$c_i$$$ is the index of the $$$i$$$-th chosen vertex. It is guaranteed that the answer exists. If there are multiple answers, you can print any. | standard output | |
PASSED | 274d0178adea9abf4ce3488fd505e778 | train_001.jsonl | 1560090900 | You are given an undirected unweighted connected graph consisting of $$$n$$$ vertices and $$$m$$$ edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.Your task is to choose at most $$$\lfloor\frac{n}{2}\rfloor$$$ vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices.It is guaranteed that the answer exists. If there are multiple answers, you can print any.You will be given multiple independent queries to answer. | 256 megabytes | /*
*created by Kraken on 05-05-2020 at 12:40
*/
//package com.kraken.cf.practice;
import java.util.*;
import java.io.*;
public class E1176 {
private static ArrayList<ArrayList<Integer>> graph;
private static int n, m, o, e;
private static boolean[] vis;
private static int[] dis;
private static StringBuilder odd, even;
private static void bfs(int vertex) {
o = 0;
e = 0;
odd = new StringBuilder();
even = new StringBuilder();
dis[vertex] = 0;
vis[vertex] = true;
Queue<Integer> q = new LinkedList<>();
q.add(vertex);
while (!q.isEmpty()) {
int curr = q.poll();
if ((dis[curr] & 1) == 0) {
e++;
even.append(curr + " ");
} else {
o++;
odd.append(curr + " ");
}
for (int i : graph.get(curr)) {
if (!vis[i]) {
dis[i] = dis[curr] + 1;
q.add(i);
vis[i] = true;
}
}
}
}
public static void main(String[] args) {
FastReader sc = new FastReader();
int t = sc.nextInt();
while (t-- > 0) {
n = sc.nextInt(); m = sc.nextInt();
vis = new boolean[n + 1];
graph = new ArrayList<>();
dis = new int[n + 1];
for (int i = 0; i <= n; i++) graph.add(new ArrayList<>());
for (int i = 0; i < m; i++) {
int u = sc.nextInt(), v = sc.nextInt();
graph.get(u).add(v);
graph.get(v).add(u);
}
bfs(1);
if (o < e)
System.out.println(o + "\n" + odd);
else
System.out.println(e + "\n" + even);
}
}
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\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4\n6 8\n2 5\n5 4\n4 3\n4 1\n1 3\n2 3\n2 6\n5 6"] | 2 seconds | ["2\n1 3\n3\n4 3 6"] | NoteIn the first query any vertex or any pair of vertices will suffice. Note that you don't have to minimize the number of chosen vertices. In the second query two vertices can be enough (vertices $$$2$$$ and $$$4$$$) but three is also ok. | Java 8 | standard input | [
"graphs",
"shortest paths",
"dsu",
"dfs and similar",
"trees"
] | c343e6a298c12cb1257aecf823f2ead0 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^5$$$) — the number of queries. Then $$$t$$$ queries follow. The first line of each query contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n - 1 \le m \le min(2 \cdot 10^5, \frac{n(n-1)}{2})$$$) — the number of vertices and the number of edges, respectively. The following $$$m$$$ lines denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no self-loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the list of edges, and for each pair ($$$v_i, u_i$$$) the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that $$$\sum m \le 2 \cdot 10^5$$$ over all queries. | 1,700 | For each query print two lines. In the first line print $$$k$$$ ($$$1 \le \lfloor\frac{n}{2}\rfloor$$$) — the number of chosen vertices. In the second line print $$$k$$$ distinct integers $$$c_1, c_2, \dots, c_k$$$ in any order, where $$$c_i$$$ is the index of the $$$i$$$-th chosen vertex. It is guaranteed that the answer exists. If there are multiple answers, you can print any. | standard output | |
PASSED | 79ef5002560686b10ed1fb2bbc25222b | train_001.jsonl | 1560090900 | You are given an undirected unweighted connected graph consisting of $$$n$$$ vertices and $$$m$$$ edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.Your task is to choose at most $$$\lfloor\frac{n}{2}\rfloor$$$ vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices.It is guaranteed that the answer exists. If there are multiple answers, you can print any.You will be given multiple independent queries to answer. | 256 megabytes | import static java.util.Arrays.* ;
import static java.lang.Math.* ;
import java.util.*;
import java.io.*;
public class A {
int [][] adjList ;
void main() throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int TC = sc.nextInt() ;
while(TC -->0) {
int n = sc.nextInt() , m = sc.nextInt();
adjList = new int[n][];
int[] deg = new int[n], x = new int[m], y = new int[m];
for (int i = 0; i < m; i++) {
deg[x[i] = sc.nextInt() - 1]++;
deg[y[i] = sc.nextInt() - 1]++;
}
for (int u = 0; u < n; u++)
adjList[u] = new int[deg[u]];
for (int i = 0; i < m; i++) {
adjList[x[i]][--deg[x[i]]] = y[i];
adjList[y[i]][--deg[y[i]]] = x[i];
}
Queue<Integer> q = new LinkedList<>();
int c[] = new int[n];
fill(c, -1);
c[0] = 0 ;
q.add(0);
while (!q.isEmpty()) {
int u = q.poll();
for (int v : adjList[u])
if (c[v] == -1) {
c[v] = c[u] ^ 1;
q.add(v);
}
}
int cnt = 0;
for (int z : c) cnt += z;
if (cnt <= n / 2) {
out.println(cnt);
for (int u = 0; u < n; u++)
if (c[u] == 1)
out.print(u + 1 +" ");
}
else {
out.println(n - cnt);
for (int u = 0; u < n; u++)
if (c[u] == 0)
out.print(u + 1 +" ");
}
out.println();
}
out.flush();
out.close();
}
class Scanner
{
BufferedReader br;
StringTokenizer st;
Scanner(InputStream in)
{
br = new BufferedReader(new InputStreamReader(System.in));
}
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()); }
long nextLong() throws Exception { return Long.parseLong(next()); }
double nextDouble() throws Exception { return Double.parseDouble(next());}
}
public static void main (String [] args) throws Exception {(new A()).main();}
} | Java | ["2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4\n6 8\n2 5\n5 4\n4 3\n4 1\n1 3\n2 3\n2 6\n5 6"] | 2 seconds | ["2\n1 3\n3\n4 3 6"] | NoteIn the first query any vertex or any pair of vertices will suffice. Note that you don't have to minimize the number of chosen vertices. In the second query two vertices can be enough (vertices $$$2$$$ and $$$4$$$) but three is also ok. | Java 8 | standard input | [
"graphs",
"shortest paths",
"dsu",
"dfs and similar",
"trees"
] | c343e6a298c12cb1257aecf823f2ead0 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^5$$$) — the number of queries. Then $$$t$$$ queries follow. The first line of each query contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n - 1 \le m \le min(2 \cdot 10^5, \frac{n(n-1)}{2})$$$) — the number of vertices and the number of edges, respectively. The following $$$m$$$ lines denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no self-loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the list of edges, and for each pair ($$$v_i, u_i$$$) the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that $$$\sum m \le 2 \cdot 10^5$$$ over all queries. | 1,700 | For each query print two lines. In the first line print $$$k$$$ ($$$1 \le \lfloor\frac{n}{2}\rfloor$$$) — the number of chosen vertices. In the second line print $$$k$$$ distinct integers $$$c_1, c_2, \dots, c_k$$$ in any order, where $$$c_i$$$ is the index of the $$$i$$$-th chosen vertex. It is guaranteed that the answer exists. If there are multiple answers, you can print any. | standard output | |
PASSED | cb1c8e3a4616adb6ab793c219d76acd5 | train_001.jsonl | 1560090900 | You are given an undirected unweighted connected graph consisting of $$$n$$$ vertices and $$$m$$$ edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.Your task is to choose at most $$$\lfloor\frac{n}{2}\rfloor$$$ vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices.It is guaranteed that the answer exists. If there are multiple answers, you can print any.You will be given multiple independent queries to answer. | 256 megabytes | import static java.util.Arrays.* ;
import static java.lang.Math.* ;
import java.util.*;
import java.io.*;
public class A {
int [][] adjList ;
void main() throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int TC = sc.nextInt() ;
StringBuilder st = new StringBuilder() ;
int[] q = new int [1 << 20];
while(TC -->0) {
int n = sc.nextInt() , m = sc.nextInt();
adjList = new int[n][];
int[] deg = new int[n], x = new int[m], y = new int[m];
for (int i = 0; i < m; i++) {
deg[x[i] = sc.nextInt() - 1]++;
deg[y[i] = sc.nextInt() - 1]++;
}
for (int u = 0; u < n; u++)
adjList[u] = new int[deg[u]];
for (int i = 0; i < m; i++) {
adjList[x[i]][--deg[x[i]]] = y[i];
adjList[y[i]][--deg[y[i]]] = x[i];
}
int c[] = new int[n];
fill(c, -1);
int qh = 0 , qt = 0 ;
c[q[qt++] = 0] = 0 ;
while (qh != qt) {
int u = q[qh++];
for (int v : adjList[u])
if (c[v] == -1)
c[q[qt++] = v] = c[u] ^ 1;
}
int cnt = 0;
for (int z : c) cnt += z;
if (cnt <= n / 2) {
st.append(cnt).append('\n');
for (int u = 0; u < n; u++)
if (c[u] == 1)
st.append(u + 1).append(" ");
}
else {
st.append(n - cnt).append('\n');
for (int u = 0; u < n; u++)
if (c[u] == 0)
st.append(u + 1).append(" ");
}
st.append('\n') ;
}
out.print(st);
out.flush();
out.close();
}
class Scanner
{
BufferedReader br;
StringTokenizer st;
Scanner(InputStream in)
{
br = new BufferedReader(new InputStreamReader(System.in));
}
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()); }
long nextLong() throws Exception { return Long.parseLong(next()); }
double nextDouble() throws Exception { return Double.parseDouble(next());}
}
public static void main (String [] args) throws Exception {(new A()).main();}
} | Java | ["2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4\n6 8\n2 5\n5 4\n4 3\n4 1\n1 3\n2 3\n2 6\n5 6"] | 2 seconds | ["2\n1 3\n3\n4 3 6"] | NoteIn the first query any vertex or any pair of vertices will suffice. Note that you don't have to minimize the number of chosen vertices. In the second query two vertices can be enough (vertices $$$2$$$ and $$$4$$$) but three is also ok. | Java 8 | standard input | [
"graphs",
"shortest paths",
"dsu",
"dfs and similar",
"trees"
] | c343e6a298c12cb1257aecf823f2ead0 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^5$$$) — the number of queries. Then $$$t$$$ queries follow. The first line of each query contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n - 1 \le m \le min(2 \cdot 10^5, \frac{n(n-1)}{2})$$$) — the number of vertices and the number of edges, respectively. The following $$$m$$$ lines denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no self-loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the list of edges, and for each pair ($$$v_i, u_i$$$) the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that $$$\sum m \le 2 \cdot 10^5$$$ over all queries. | 1,700 | For each query print two lines. In the first line print $$$k$$$ ($$$1 \le \lfloor\frac{n}{2}\rfloor$$$) — the number of chosen vertices. In the second line print $$$k$$$ distinct integers $$$c_1, c_2, \dots, c_k$$$ in any order, where $$$c_i$$$ is the index of the $$$i$$$-th chosen vertex. It is guaranteed that the answer exists. If there are multiple answers, you can print any. | standard output | |
PASSED | 4bfb8a2c7ada71af7a9aace2ebb49e97 | train_001.jsonl | 1560090900 | You are given an undirected unweighted connected graph consisting of $$$n$$$ vertices and $$$m$$$ edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.Your task is to choose at most $$$\lfloor\frac{n}{2}\rfloor$$$ vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices.It is guaranteed that the answer exists. If there are multiple answers, you can print any.You will be given multiple independent queries to answer. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
public class E1176 {
private static class Node {
long h;
HashMap<Integer,Long> edges = new HashMap<Integer,Long>();
Node(long h) {
this.h = h;
}
}
private static void bfs(Node[] G,int s,int[] order) {
LinkedList<Integer> Q = new LinkedList<Integer>();
int n = G.length;
boolean[] visited = new boolean[n];
Q.add(s);
visited[s] = true;
order[s]=0;
while(!Q.isEmpty()) {
int c = Q.poll();
for(Map.Entry<Integer, Long> e : G[c].edges.entrySet()) {
if(e.getValue()==0) continue;
int v = e.getKey();
if(!visited[v]) {
Q.add(v);
visited[v]=true;
order[v] = (order[c]+1)%2;
}
}
}
}
public static void main(String[] args) throws Exception {
// BufferedReader br = new BufferedReader(new FileReader("F:/books/input.txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Integer Q = Integer.parseInt(br.readLine());
StringBuilder SB = new StringBuilder();
for(int q=0;q<Q;q++) {
String[] s1 = br.readLine().split(" ");
Integer n = Integer.parseInt(s1[0]);
Integer m = Integer.parseInt(s1[1]);
Node[] G = new Node[n+1];
for (int i = 1; i <= n; i++) {
G[i] = new Node(i);
}
for (int i = 0; i < m; i++) {
String[] s2 = br.readLine().split(" ");
Integer u = Integer.parseInt(s2[0]);
Integer v = Integer.parseInt(s2[1]);
G[u].edges.put(v, 1l);
G[v].edges.put(u, 1l);
}
int[] res = new int[n+1];
bfs(G,1,res);
StringBuilder sb1 = new StringBuilder();
StringBuilder sb2 = new StringBuilder();
int cnt1=0,cnt2=0;
for(int i=1;i<=n;i++)
if(res[i]==0) {
cnt1++;
sb1.append(i+" ");
}
else {
sb2.append(i+" ");
cnt2++;
}
StringBuilder sb = (cnt1>cnt2)?sb2:sb1;
SB.append(Math.min(cnt1, cnt2)+"\n");
SB.append(sb+"\n");
}
System.out.println(SB.toString());
}
}
| Java | ["2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4\n6 8\n2 5\n5 4\n4 3\n4 1\n1 3\n2 3\n2 6\n5 6"] | 2 seconds | ["2\n1 3\n3\n4 3 6"] | NoteIn the first query any vertex or any pair of vertices will suffice. Note that you don't have to minimize the number of chosen vertices. In the second query two vertices can be enough (vertices $$$2$$$ and $$$4$$$) but three is also ok. | Java 8 | standard input | [
"graphs",
"shortest paths",
"dsu",
"dfs and similar",
"trees"
] | c343e6a298c12cb1257aecf823f2ead0 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^5$$$) — the number of queries. Then $$$t$$$ queries follow. The first line of each query contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n - 1 \le m \le min(2 \cdot 10^5, \frac{n(n-1)}{2})$$$) — the number of vertices and the number of edges, respectively. The following $$$m$$$ lines denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no self-loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the list of edges, and for each pair ($$$v_i, u_i$$$) the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that $$$\sum m \le 2 \cdot 10^5$$$ over all queries. | 1,700 | For each query print two lines. In the first line print $$$k$$$ ($$$1 \le \lfloor\frac{n}{2}\rfloor$$$) — the number of chosen vertices. In the second line print $$$k$$$ distinct integers $$$c_1, c_2, \dots, c_k$$$ in any order, where $$$c_i$$$ is the index of the $$$i$$$-th chosen vertex. It is guaranteed that the answer exists. If there are multiple answers, you can print any. | standard output | |
PASSED | 879a1a127bbd67f7f52ae123ad610853 | train_001.jsonl | 1560090900 | You are given an undirected unweighted connected graph consisting of $$$n$$$ vertices and $$$m$$$ edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.Your task is to choose at most $$$\lfloor\frac{n}{2}\rfloor$$$ vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices.It is guaranteed that the answer exists. If there are multiple answers, you can print any.You will be given multiple independent queries to answer. | 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 int mod = 1_000_000_007;
static int[] di = {1, 0, 0, -1};
static int[] dj = {0, -1, 1, 0};
static int M = 100005;
static double EPS = 1e-5;
public static void main(String[] args) throws IOException {
int t = in.nextInt();
while(t --> 0) {
int n = in.nextInt();
int m = in.nextInt();
ArrayList<Integer>[] adj = new ArrayList[n];
for(int i = 0; i < n; ++i)
adj[i] = new ArrayList<Integer>();
for(int i = 0; i < m; ++i) {
int u = in.nextInt() - 1;
int v = in.nextInt() - 1;
adj[u].add(v);
adj[v].add(u);
}
int[] color = new int[n];
Queue<Integer> q = new ArrayDeque<Integer>();
q.add(0);
while(!q.isEmpty()) {
int u = q.poll();
for(int v : adj[u]) {
if(color[v] == 0) {
color[v] = color[u] == 1 ? 2 : 1;
q.add(v);
}
}
}
int cnt1 = 0, cnt2 = 0;
for(int i = 0; i < n; ++i) {
if(color[i] == 1)
cnt1++;
else
cnt2++;
}
int select, cnt;
if(cnt1 > cnt2) {
select = 2;
cnt = cnt2;
}
else {
select = 1;
cnt = cnt1;
}
out.println(cnt);
for(int i = 0; i < n; ++i) {
if(color[i] == select) {
out.print(i+1 + " ");
}
}
out.println();
}
out.close();
}
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;
char[] a;
int[] seg;
int DEFAULT_VALUE = 0;
public SegmentTree(char[] 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) {
int x = a[i] - 'a';
return seg[node] = (1<<x);
}
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;
int x = a[i] - 'a';
return seg[node] = (1<<x);
}
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 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(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 | ["2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4\n6 8\n2 5\n5 4\n4 3\n4 1\n1 3\n2 3\n2 6\n5 6"] | 2 seconds | ["2\n1 3\n3\n4 3 6"] | NoteIn the first query any vertex or any pair of vertices will suffice. Note that you don't have to minimize the number of chosen vertices. In the second query two vertices can be enough (vertices $$$2$$$ and $$$4$$$) but three is also ok. | Java 8 | standard input | [
"graphs",
"shortest paths",
"dsu",
"dfs and similar",
"trees"
] | c343e6a298c12cb1257aecf823f2ead0 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^5$$$) — the number of queries. Then $$$t$$$ queries follow. The first line of each query contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n - 1 \le m \le min(2 \cdot 10^5, \frac{n(n-1)}{2})$$$) — the number of vertices and the number of edges, respectively. The following $$$m$$$ lines denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no self-loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the list of edges, and for each pair ($$$v_i, u_i$$$) the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that $$$\sum m \le 2 \cdot 10^5$$$ over all queries. | 1,700 | For each query print two lines. In the first line print $$$k$$$ ($$$1 \le \lfloor\frac{n}{2}\rfloor$$$) — the number of chosen vertices. In the second line print $$$k$$$ distinct integers $$$c_1, c_2, \dots, c_k$$$ in any order, where $$$c_i$$$ is the index of the $$$i$$$-th chosen vertex. It is guaranteed that the answer exists. If there are multiple answers, you can print any. | standard output | |
PASSED | adac171e8ece81ffec5ead4eed0d648b | train_001.jsonl | 1560090900 | You are given an undirected unweighted connected graph consisting of $$$n$$$ vertices and $$$m$$$ edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.Your task is to choose at most $$$\lfloor\frac{n}{2}\rfloor$$$ vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices.It is guaranteed that the answer exists. If there are multiple answers, you can print any.You will be given multiple independent queries to answer. | 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 int mod = 1_000_000_007;
static int[] di = {1, 0, 0, -1};
static int[] dj = {0, -1, 1, 0};
static int M = 100005;
static double EPS = 1e-5;
public static void main(String[] args) throws IOException {
int t = in.nextInt();
while(t --> 0) {
int n = in.nextInt();
int m = in.nextInt();
ArrayList<Integer>[] adj = new ArrayList[n];
for(int i = 0; i < n; ++i)
adj[i] = new ArrayList<Integer>();
for(int i = 0; i < m; ++i) {
int u = in.nextInt() - 1;
int v = in.nextInt() - 1;
adj[u].add(v);
adj[v].add(u);
}
int[] color = new int[n];
Queue<Integer> q = new ArrayDeque<Integer>();
q.add(0);
color[0] = 1;
while(!q.isEmpty()) {
int u = q.poll();
for(int v : adj[u]) {
if(color[v] == 0) {
color[v] = color[u] == 1 ? 2 : 1;
q.add(v);
}
}
}
int cnt1 = 0, cnt2 = 0;
for(int i = 0; i < n; ++i) {
if(color[i] == 1)
cnt1++;
else
cnt2++;
}
int select, cnt;
if(cnt1 > cnt2) {
select = 2;
cnt = cnt2;
}
else {
select = 1;
cnt = cnt1;
}
out.println(cnt);
for(int i = 0; i < n; ++i) {
if(color[i] == select) {
out.print(i+1 + " ");
}
}
out.println();
}
out.close();
}
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;
char[] a;
int[] seg;
int DEFAULT_VALUE = 0;
public SegmentTree(char[] 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) {
int x = a[i] - 'a';
return seg[node] = (1<<x);
}
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;
int x = a[i] - 'a';
return seg[node] = (1<<x);
}
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 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(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 | ["2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4\n6 8\n2 5\n5 4\n4 3\n4 1\n1 3\n2 3\n2 6\n5 6"] | 2 seconds | ["2\n1 3\n3\n4 3 6"] | NoteIn the first query any vertex or any pair of vertices will suffice. Note that you don't have to minimize the number of chosen vertices. In the second query two vertices can be enough (vertices $$$2$$$ and $$$4$$$) but three is also ok. | Java 8 | standard input | [
"graphs",
"shortest paths",
"dsu",
"dfs and similar",
"trees"
] | c343e6a298c12cb1257aecf823f2ead0 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^5$$$) — the number of queries. Then $$$t$$$ queries follow. The first line of each query contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n - 1 \le m \le min(2 \cdot 10^5, \frac{n(n-1)}{2})$$$) — the number of vertices and the number of edges, respectively. The following $$$m$$$ lines denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no self-loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the list of edges, and for each pair ($$$v_i, u_i$$$) the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that $$$\sum m \le 2 \cdot 10^5$$$ over all queries. | 1,700 | For each query print two lines. In the first line print $$$k$$$ ($$$1 \le \lfloor\frac{n}{2}\rfloor$$$) — the number of chosen vertices. In the second line print $$$k$$$ distinct integers $$$c_1, c_2, \dots, c_k$$$ in any order, where $$$c_i$$$ is the index of the $$$i$$$-th chosen vertex. It is guaranteed that the answer exists. If there are multiple answers, you can print any. | standard output | |
PASSED | de9844c8dc20ef6c45250b7ffa69c88e | train_001.jsonl | 1560090900 | You are given an undirected unweighted connected graph consisting of $$$n$$$ vertices and $$$m$$$ edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.Your task is to choose at most $$$\lfloor\frac{n}{2}\rfloor$$$ vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices.It is guaranteed that the answer exists. If there are multiple answers, you can print any.You will be given multiple independent queries to answer. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
public class Codechef
{ static PrintWriter out=new PrintWriter(System.out);static FastScanner in = new FastScanner(System.in);static class FastScanner {BufferedReader br;StringTokenizer stok;FastScanner(InputStream is) {br = new BufferedReader(new InputStreamReader(is));}
String next() throws IOException {while (stok == null || !stok.hasMoreTokens()) {String s = br.readLine();if (s == null) {return null;}
stok = new StringTokenizer(s);}return stok.nextToken();}
int ni() throws IOException {return Integer.parseInt(next());}long nl() throws IOException {return Long.parseLong(next());}double nd() throws IOException {return Double.parseDouble(next());}char nc() throws IOException {return (char) (br.read());}String ns() throws IOException {return br.readLine();}
int[] nia(int n) throws IOException{int a[] = new int[n];for (int i = 0; i < n; i++)a[i] = ni();return a;}long[] nla(int n) throws IOException {long a[] = new long[n];for (int i = 0; i < n; i++)a[i] = nl();return a;}
double[] nda(int n)throws IOException {double a[] = new double[n];for (int i = 0; i < n; i++)a[i] = nd();return a;}int [][] imat(int n,int m) throws IOException{int mat[][]=new int[n][m];for(int i=0;i<n;i++){for(int j=0;j<m;j++)mat[i][j]=ni();}return mat;}
}
static long mod=(long)1e9+7;
static ArrayList<Integer> arr[];
static ArrayList<Integer> temp1,temp2;
static boolean visited[];
public static void main (String[] args) throws java.lang.Exception
{ int i,j;
HashMap<Integer,Integer> hm=new HashMap<Integer,Integer>();
/* if(hm.containsKey(z))
hm.put(z,hm.get(z)+1);
else
hm.put(z,1);
*/
//ArrayList<Integer> arr=new ArrayList<Integer>();
HashSet<Integer> set=new HashSet<Integer>();
PriorityQueue<Integer> pq=new PriorityQueue<Integer>();
int t=in.ni();
while(t--!=0)
{ int n=in.ni();
arr=new ArrayList[n+1];
for(i=0;i<=n;i++)
arr[i]=new ArrayList<Integer>();
visited=new boolean[n+1];
temp1=new ArrayList<Integer>();
temp2=new ArrayList<Integer>();
Queue<Integer> q=new LinkedList<Integer>();
int m=in.ni();
for(i=0;i<m;i++)
{ int p=in.ni();
int x=in.ni();
arr[p].add(x);
arr[x].add(p);
}
q.add(1);
int h[]=new int[n+1];
h[1]=1;
while(q.size()!=0)
{ int z=q.poll();
visited[z]=true;
for(int c:arr[z])
if(!visited[c])
{ q.add(c);
visited[c]=true;
h[c]=h[z]+1;
}
}
for(i=1;i<=n;i++)
{ if(h[i]%2==0)
temp1.add(i);
else
temp2.add(i);
}
if(temp1.size()<=n/2)
{ out.println(temp1.size());
for(int c:temp1)
out.print(c+" ");
}
else
{ out.println(temp2.size());
for(int c:temp2)
out.print(c+" ");
}
out.println();
}
out.close();
}
static void dfs(int a)
{ if(visited[a])
return;
visited[a]=true;
for(int c:arr[a])
dfs(c);
//temp.add(a);
}
static class pair implements Comparable<pair>{
int x, y;
public pair(int x, int y){this.x = x; this.y = y;}
@Override
public int compareTo(pair arg0)
{ if(x<arg0.x) return -1;
else if(x==arg0.x)
{ if(y<arg0.y) return -1;
else if(y>arg0.y) return 1;
else return 0;
}
else return 1;
}
}
static long gcd(long a,long b)
{ if(b==0)
return a;
return gcd(b,a%b);
}
static long exponent(long a,long n)
{ long ans=1;
while(n!=0)
{ if(n%2==1)
ans=(ans*a)%mod;
a=(a*a)%mod;
n=n>>1;
}
return ans;
}
static int binarySearch(int a[], int item, int low, int high)
{ if (high <= low)
return (item > a[low])? (low + 1): low;
int mid = (low + high)/2;
if(item == a[mid])
return mid+1;
if(item > a[mid])
return binarySearch(a, item, mid+1, high);
return binarySearch(a, item, low, mid-1);
}
static void merge(int arr[], int l, int m, int r) {
int n1 = m - l + 1; int n2 = r - m; int L[] = new int [n1]; int R[] = new int [n2];
for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; int i = 0, j = 0; int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else{ arr[k] = R[j]; j++; } k++; } while (i < n1){ arr[k] = L[i]; i++; k++; } while (j < n2) { arr[k] = R[j]; j++; k++; }
}
static void Sort(int arr[], int l, int r) {if (l < r) { int m = (l+r)/2; Sort(arr, l, m); Sort(arr , m+1, r); merge(arr, l, m, r); } }
static void sort(int a[])
{Sort(a,0,a.length-1);}
} | Java | ["2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4\n6 8\n2 5\n5 4\n4 3\n4 1\n1 3\n2 3\n2 6\n5 6"] | 2 seconds | ["2\n1 3\n3\n4 3 6"] | NoteIn the first query any vertex or any pair of vertices will suffice. Note that you don't have to minimize the number of chosen vertices. In the second query two vertices can be enough (vertices $$$2$$$ and $$$4$$$) but three is also ok. | Java 8 | standard input | [
"graphs",
"shortest paths",
"dsu",
"dfs and similar",
"trees"
] | c343e6a298c12cb1257aecf823f2ead0 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^5$$$) — the number of queries. Then $$$t$$$ queries follow. The first line of each query contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n - 1 \le m \le min(2 \cdot 10^5, \frac{n(n-1)}{2})$$$) — the number of vertices and the number of edges, respectively. The following $$$m$$$ lines denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no self-loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the list of edges, and for each pair ($$$v_i, u_i$$$) the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that $$$\sum m \le 2 \cdot 10^5$$$ over all queries. | 1,700 | For each query print two lines. In the first line print $$$k$$$ ($$$1 \le \lfloor\frac{n}{2}\rfloor$$$) — the number of chosen vertices. In the second line print $$$k$$$ distinct integers $$$c_1, c_2, \dots, c_k$$$ in any order, where $$$c_i$$$ is the index of the $$$i$$$-th chosen vertex. It is guaranteed that the answer exists. If there are multiple answers, you can print any. | standard output | |
PASSED | f08a4248968bbae80b4c0c37734d9130 | train_001.jsonl | 1560090900 | You are given an undirected unweighted connected graph consisting of $$$n$$$ vertices and $$$m$$$ edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.Your task is to choose at most $$$\lfloor\frac{n}{2}\rfloor$$$ vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices.It is guaranteed that the answer exists. If there are multiple answers, you can print any.You will be given multiple independent queries to answer. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.BigInteger;
public class cf1 {
static long mod = (long)1e9 + 7;
static long mod1 = 998244353;
static FastScanner f;
static PrintWriter pw = new PrintWriter(System.out);
static Scanner S = new Scanner(System.in);
static long x0; static long y0;
static int inf = (int)(1e9) + 5;
static long iinf = (long)(1e18);
static double eps = (double)1e-4;
static int color[];
static boolean vis[];
static HashMap<Integer , ArrayList<Integer>> g;
static void dfs(int src) {
vis[src] = true;
for (Integer node : g.get(src)) {
if (!vis[node]) {
color[node] = 1 - color[src];
dfs(node);
}
}
}
static void solve()throws IOException {
int n = f.ni(); int m = f.ni();
g = new HashMap<>();
vis = new boolean[n + 1];
color = new int[n + 1];
for (int i = 1; i <= n; ++i) {
g.put(i , new ArrayList<Integer>());
}
for (int i = 1; i <= m; ++i) {
int u = f.ni(); int v = f.ni();
g.get(u).add(v);
g.get(v).add(u);
}
dfs(1);
int cnt0 = 0 , cnt1 = 0;
for (int i = 1; i <= n; ++i) {
if (color[i] == 1) ++cnt1;
else ++cnt0;
}
if (cnt0 < cnt1) {
pn(cnt0);
for (int i = 1; i <= n; ++i) {
if (color[i] == 0) p(i + " ");
}
}
else {
pn(cnt1);
for (int i = 1; i <= n; ++i) {
if (color[i] == 1) p(i + " ");
//pn("color for " + i + " " + color[i]);
}
}
pn("");
}
public static void main(String[] args)throws NumberFormatException , IOException {
init();
boolean tc = true;
int t = tc ? f.ni() : 1;
while(t --> 0) solve();
pw.flush();
pw.close();
}
/******************************END OF MAIN PROGRAM*******************************************/
public static void init()throws IOException{if(System.getProperty("ONLINE_JUDGE")==null){f=new FastScanner("");}else{f=new FastScanner(System.in);}}
public static class FastScanner {
BufferedReader br;StringTokenizer st;
FastScanner(InputStream stream){try{br=new BufferedReader(new InputStreamReader(stream));}catch(Exception e){e.printStackTrace();}}
FastScanner(String str){try{br=new BufferedReader(new FileReader("!a.txt"));}catch(Exception e){e.printStackTrace();}}
String next(){while(st==null||!st.hasMoreTokens()){try{st=new StringTokenizer(br.readLine());}catch(IOException e){e.printStackTrace();}}return st.nextToken();}
String nextLine()throws IOException{return br.readLine();}int ni(){return Integer.parseInt(next());}long nl(){return Long.parseLong(next());}double nd(){return Double.parseDouble(next());}
}
public static void pn(Object o){pw.println(o);}
public static void p(Object o){pw.print(o);}
public static void pni(Object o){pw.println(o);pw.flush();}
static int gcd(int a,int b){if(b==0)return a;else{return gcd(b,a%b);}}
static long gcd(long a,long b){if(b==0l)return a;else{return gcd(b,a%b);}}
static long lcm(long a,long b){return (a*b/gcd(a,b));}
static long exgcd(long a,long b){if(b==0){x0=1;y0=0;return a;}long temp=exgcd(b,a%b);long t=x0;x0=y0;y0=t-a/b*y0;return temp;}
static long pow(long a,long b){long res=1;while(b>0){if((b&1)==1)res=res*a;b>>=1;a=a*a;}return res;}
static long mpow(long a,long b){long res=1;while(b>0l){if((b&1)==1l)res=((res%mod)*(a%mod))%mod;b>>=1l;a=((a%mod)*(a%mod))%mod;}return res;}
static long mul(long a , long b){return ((a%mod)*(b%mod)%mod);}
static long adp(long a , long b){return ((a%mod)+(b%mod)%mod);}
static int log2(int x){return (int)(Math.log(x)/Math.log(2));}
static boolean isPrime(long n){if(n<=1)return false;if(n<=3)return true;if(n%2==0||n%3==0)return false;for(long i=5;i*i<=n;i=i+6)if(n%i==0||n%(i+2)==0)return false;return true;}
static boolean isPrime(int n){if(n<=1)return false;if(n<=3)return true;if(n%2==0||n%3==0)return false;for(int i=5;i*i<=n;i=i+6)if(n%i==0||n%(i+2)==0)return false;return true;}
static HashSet<Long> factors(long n){HashSet<Long> hs=new HashSet<Long>();for(long i=1;i<=(long)Math.sqrt(n);i++){if(n%i==0){hs.add(i);hs.add(n/i);}}return hs;}
static HashSet<Integer> factors(int n){HashSet<Integer> hs=new HashSet<Integer>();for(int i=1;i<=(int)Math.sqrt(n);i++){if(n%i==0){hs.add(i);hs.add(n/i);}}return hs;}
static HashSet<Long> pf(long n){HashSet<Long> ff=factors(n);HashSet<Long> res=new HashSet<Long>();for(Long i:ff)if(isPrime(i))res.add(i);return res;}
static HashSet<Integer> pf(int n){HashSet<Integer> ff=factors(n);HashSet<Integer> res=new HashSet<Integer>();for(Integer i:ff)if(isPrime(i))res.add(i);return res;}
static int[] inpint(int n){int arr[]=new int[n+1];for(int i=1;i<=n;++i){arr[i]=f.ni();}return arr;}
static long[] inplong(int n){long arr[] = new long[n+1];for(int i=1;i<=n;++i){arr[i]=f.nl();}return arr;}
static boolean ise(int x){return ((x&1)==0);}static boolean ise(long x){return ((x&1)==0);}
static int gnv(char c){return Character.getNumericValue(c);}//No. of integers less than equal to i in ub
static int log(long x){return x==1?0:(1+log(x/2));} static int log(int x){return x==1?0:(1+log(x/2));}
static int upperbound(int a[],int i){int lo=0,hi=a.length-1,mid=0;int count=0;while(lo<=hi){mid=(lo+hi)/2;if(a[mid]<=i){count=mid+1;lo=mid+1;}else hi=mid-1;}return count;}
static void sort(int[] a){ArrayList<Integer> l=new ArrayList<>();for(int i:a)l.add(i);Collections.sort(l);for(int i=0;i<a.length;++i)a[i]=l.get(i);}
static void sort(long[] a){ArrayList<Long> l=new ArrayList<>();for(long i:a)l.add(i);Collections.sort(l);for(int i=0;i<a.length;++i)a[i]=l.get(i);}
static void sort(ArrayList<Integer> a){Collections.sort(a);}//!Precompute fact in ncr()!
static int nextPowerOf2(int n){int count=0;if(n>0&&(n&(n-1))==0)return n;while(n!=0){n>>=1;count += 1;}return 1<<count;}
} | Java | ["2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4\n6 8\n2 5\n5 4\n4 3\n4 1\n1 3\n2 3\n2 6\n5 6"] | 2 seconds | ["2\n1 3\n3\n4 3 6"] | NoteIn the first query any vertex or any pair of vertices will suffice. Note that you don't have to minimize the number of chosen vertices. In the second query two vertices can be enough (vertices $$$2$$$ and $$$4$$$) but three is also ok. | Java 8 | standard input | [
"graphs",
"shortest paths",
"dsu",
"dfs and similar",
"trees"
] | c343e6a298c12cb1257aecf823f2ead0 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^5$$$) — the number of queries. Then $$$t$$$ queries follow. The first line of each query contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n - 1 \le m \le min(2 \cdot 10^5, \frac{n(n-1)}{2})$$$) — the number of vertices and the number of edges, respectively. The following $$$m$$$ lines denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no self-loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the list of edges, and for each pair ($$$v_i, u_i$$$) the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that $$$\sum m \le 2 \cdot 10^5$$$ over all queries. | 1,700 | For each query print two lines. In the first line print $$$k$$$ ($$$1 \le \lfloor\frac{n}{2}\rfloor$$$) — the number of chosen vertices. In the second line print $$$k$$$ distinct integers $$$c_1, c_2, \dots, c_k$$$ in any order, where $$$c_i$$$ is the index of the $$$i$$$-th chosen vertex. It is guaranteed that the answer exists. If there are multiple answers, you can print any. | standard output | |
PASSED | ac0cc879c7bdec49805d76b4fa7a1d64 | train_001.jsonl | 1560090900 | You are given an undirected unweighted connected graph consisting of $$$n$$$ vertices and $$$m$$$ edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.Your task is to choose at most $$$\lfloor\frac{n}{2}\rfloor$$$ vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices.It is guaranteed that the answer exists. If there are multiple answers, you can print any.You will be given multiple independent queries to answer. | 256 megabytes | import java.io.*;
import java.util.*;
public class codeforces {
public static void main(String[] args) throws IOException {
BufferedReader scan = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
int t = Integer.parseInt(scan.readLine());
for (int j = 0; j < t; j++) {
StringTokenizer st = new StringTokenizer(scan.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
ArrayList<Integer> graph[] = new ArrayList[n];
for (int i = 0; i < n; i++) graph[i] = new ArrayList<>();
for (int i = 0; i < m; i++) {
st = new StringTokenizer(scan.readLine());
int u = Integer.parseInt(st.nextToken()) - 1;
int v = Integer.parseInt(st.nextToken()) - 1;
graph[u].add(v);
graph[v].add(u);
}
TreeSet<Integer> set = new TreeSet<>();
set.add(0);
boolean used[] = new boolean[n];
int dist[] = new int[n];
while (!set.isEmpty()) {
int v = set.pollFirst();
used[v] = true;
for (int u : graph[v]) {
if (!used[u]) {
dist[u] = dist[v] + 1;
set.add(u);
}
}
}
ArrayList<Integer> even = new ArrayList<>();
ArrayList<Integer> odd = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (dist[i] % 2 == 0) even.add(i + 1);
else odd.add(i + 1);
}
if (even.size() < odd.size()) {
out.write(even.size() + "\n");
for (int v : even) out.write(v + " ");
out.write("\n");
} else {
out.write(odd.size() + "\n");
for (int v : odd) out.write(v + " ");
out.write("\n");
}
}
out.close();
}
} | Java | ["2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4\n6 8\n2 5\n5 4\n4 3\n4 1\n1 3\n2 3\n2 6\n5 6"] | 2 seconds | ["2\n1 3\n3\n4 3 6"] | NoteIn the first query any vertex or any pair of vertices will suffice. Note that you don't have to minimize the number of chosen vertices. In the second query two vertices can be enough (vertices $$$2$$$ and $$$4$$$) but three is also ok. | Java 8 | standard input | [
"graphs",
"shortest paths",
"dsu",
"dfs and similar",
"trees"
] | c343e6a298c12cb1257aecf823f2ead0 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^5$$$) — the number of queries. Then $$$t$$$ queries follow. The first line of each query contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n - 1 \le m \le min(2 \cdot 10^5, \frac{n(n-1)}{2})$$$) — the number of vertices and the number of edges, respectively. The following $$$m$$$ lines denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no self-loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the list of edges, and for each pair ($$$v_i, u_i$$$) the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that $$$\sum m \le 2 \cdot 10^5$$$ over all queries. | 1,700 | For each query print two lines. In the first line print $$$k$$$ ($$$1 \le \lfloor\frac{n}{2}\rfloor$$$) — the number of chosen vertices. In the second line print $$$k$$$ distinct integers $$$c_1, c_2, \dots, c_k$$$ in any order, where $$$c_i$$$ is the index of the $$$i$$$-th chosen vertex. It is guaranteed that the answer exists. If there are multiple answers, you can print any. | standard output | |
PASSED | 384b9f2cccce1de555e8114aa80f4d0c | train_001.jsonl | 1560090900 | You are given an undirected unweighted connected graph consisting of $$$n$$$ vertices and $$$m$$$ edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.Your task is to choose at most $$$\lfloor\frac{n}{2}\rfloor$$$ vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices.It is guaranteed that the answer exists. If there are multiple answers, you can print any.You will be given multiple independent queries to answer. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class round565d3e {
private static StringBuilder sb;
public static void main(String args[]) {
FastScanner in = new FastScanner(System.in);
sb = new StringBuilder();
int t = in.nextInt();
for (int i = 0; i < t; i++) {
int n = in.nextInt();
int m = in.nextInt();
Graph g = new Graph(n);
for (int j = 0; j < m; j++) {
int a = in.nextInt()-1;
int b = in.nextInt()-1;
g.addEdge(a, b);
}
g.DFS(0);
}
System.out.println(sb);
//in.close();
}
// ======================================================================================
// =============================== Reference Code =======================================
// ======================================================================================
// This class represents an undirected graph using adjacency list
static class Graph
{
private int V; // No. of vertices
// Array of lists for Adjacency List Representation
private LinkedList<Integer> adj[];
// Constructor
Graph(int v)
{
V = v;
adj = new LinkedList[v];
for (int i=0; i<v; ++i)
adj[i] = new LinkedList();
}
//Function to add an edge into the graph
void addEdge(int v, int w)
{
adj[v].add(w); // Add w to v's list.
adj[w].add(v); //Graph is undirected
}
// A function used by DFS
void DFSUtil(int v,boolean visited[], boolean colors[])
{
// Mark the current node as visited and print it
visited[v] = true;
//System.out.print(v+" ");
// Recur for all the vertices adjacent to this vertex
Iterator<Integer> i = adj[v].listIterator();
while (i.hasNext())
{
int n = i.next();
if (!visited[n]) {
colors[n] = colors[v] ? false : true;
DFSUtil(n, visited, colors);
}
}
}
// The function to do DFS traversal. It uses recursive DFSUtil()
void DFS(int v)
{
// Mark all the vertices as not visited(set as
// false by default in java)
boolean visited[] = new boolean[V];
boolean colors[] = new boolean[V];
// Call the recursive helper function to print DFS traversal
DFSUtil(v, visited, colors);
ArrayList<Integer> odds = new ArrayList<>();
ArrayList<Integer> evens = new ArrayList<>();
for (int i = 0; i < V; i++) {
if (colors[i]) {
odds.add(i);
}
else evens.add(i);
}
if (odds.size() < evens.size()) {
sb.append(odds.size() + "\n");
//System.out.println(odds.size());
for (Integer elem : odds) {
sb.append((elem+1)+" ");
//System.out.print((elem+1) + " ");
}
}
else {
sb.append(evens.size() + "\n");
//System.out.println(evens.size());
for (Integer elem : evens) {
sb.append((elem+1)+" ");
//System.out.print((elem+1) + " ");
}
}
//System.out.println();
sb.append("\n");
}
}
// Binary search for number greater than or equal to target
// returns -1 if number not found
private static int bin_gteq(int[] a, int key) {
int low = 0;
int high = a.length;
int max_limit = high;
while (low < high) {
int mid = low + (high - low) / 2;
if (a[mid] < key) {
low = mid + 1;
} else
high = mid;
}
return high == max_limit ? -1 : high;
}
public static int gcd(int a, int b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
static class Tuple<X, Y> {
public final X x;
public final Y y;
public Tuple(X x, Y y) {
this.x = x;
this.y = y;
}
public String toString() {
return "(" + x + "," + y + ")";
}
}
static class Tuple3<X, Y, Z> {
public final X x;
public final Y y;
public final Z z;
public Tuple3(X x, Y y, Z z) {
this.x = x;
this.y = y;
this.z = z;
}
public String toString() {
return "(" + x + "," + y + "," + z + ")";
}
}
static Tuple3<Integer, Integer, Integer> gcdExtended(int a, int b, int x, int y) {
// Base Case
if (a == 0) {
x = 0;
y = 1;
return new Tuple3(0, 1, b);
}
int x1 = 1, y1 = 1; // To store results of recursive call
Tuple3<Integer, Integer, Integer> tuple = gcdExtended(b % a, a, x1, y1);
int gcd = tuple.z;
x1 = tuple.x;
y1 = tuple.y;
// Update x and y using results of recursive
// call
x = y1 - (b / a) * x1;
y = x1;
return new Tuple3(x, y, gcd);
}
// Returns modulo inverse of a
// with respect to m using extended
// Euclid Algorithm. Refer below post for details:
// https://www.geeksforgeeks.org/multiplicative-inverse-under-modulo-m/
static int inv(int a, int m) {
int m0 = m, t, q;
int x0 = 0, x1 = 1;
if (m == 1)
return 0;
// Apply extended Euclid Algorithm
while (a > 1) {
// q is quotient
q = a / m;
t = m;
// m is remainder now, process
// same as euclid's algo
m = a % m;
a = t;
t = x0;
x0 = x1 - q * x0;
x1 = t;
}
// Make x1 positive
if (x1 < 0)
x1 += m0;
return x1;
}
// k is size of num[] and rem[].
// Returns the smallest number
// x such that:
// x % num[0] = rem[0],
// x % num[1] = rem[1],
// ..................
// x % num[k-2] = rem[k-1]
// Assumption: Numbers in num[] are pairwise
// coprime (gcd for every pair is 1)
static int findMinX(int num[], int rem[], int k) {
// Compute product of all numbers
int prod = 1;
for (int i = 0; i < k; i++)
prod *= num[i];
// Initialize result
int result = 0;
// Apply above formula
for (int i = 0; i < k; i++) {
int pp = prod / num[i];
result += rem[i] * inv(pp, num[i]) * pp;
}
return result % prod;
}
/**
* Source: Matt Fontaine
*/
static class FastScanner {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int chars;
public FastScanner(InputStream stream) {
this.stream = stream;
}
int read() {
if (chars == -1)
throw new InputMismatchException();
if (curChar >= chars) {
curChar = 0;
try {
chars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (chars <= 0)
return -1;
}
return buf[curChar++];
}
boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
boolean isEndline(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String next() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = read();
while (isEndline(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndline(c));
return res.toString();
}
}
} | Java | ["2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4\n6 8\n2 5\n5 4\n4 3\n4 1\n1 3\n2 3\n2 6\n5 6"] | 2 seconds | ["2\n1 3\n3\n4 3 6"] | NoteIn the first query any vertex or any pair of vertices will suffice. Note that you don't have to minimize the number of chosen vertices. In the second query two vertices can be enough (vertices $$$2$$$ and $$$4$$$) but three is also ok. | Java 8 | standard input | [
"graphs",
"shortest paths",
"dsu",
"dfs and similar",
"trees"
] | c343e6a298c12cb1257aecf823f2ead0 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^5$$$) — the number of queries. Then $$$t$$$ queries follow. The first line of each query contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n - 1 \le m \le min(2 \cdot 10^5, \frac{n(n-1)}{2})$$$) — the number of vertices and the number of edges, respectively. The following $$$m$$$ lines denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no self-loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the list of edges, and for each pair ($$$v_i, u_i$$$) the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that $$$\sum m \le 2 \cdot 10^5$$$ over all queries. | 1,700 | For each query print two lines. In the first line print $$$k$$$ ($$$1 \le \lfloor\frac{n}{2}\rfloor$$$) — the number of chosen vertices. In the second line print $$$k$$$ distinct integers $$$c_1, c_2, \dots, c_k$$$ in any order, where $$$c_i$$$ is the index of the $$$i$$$-th chosen vertex. It is guaranteed that the answer exists. If there are multiple answers, you can print any. | standard output | |
PASSED | b30b8990edd255aed65490566dba7aa9 | train_001.jsonl | 1560090900 | You are given an undirected unweighted connected graph consisting of $$$n$$$ vertices and $$$m$$$ edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.Your task is to choose at most $$$\lfloor\frac{n}{2}\rfloor$$$ vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices.It is guaranteed that the answer exists. If there are multiple answers, you can print any.You will be given multiple independent queries to answer. | 256 megabytes | import java.io.*;
import java.util.*;
public class Solution {
//-----------PrintWriter for faster output---------------------------------
public static PrintWriter out;
//-----------MyScanner class for faster input----------
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
//--------------------------------------------------------
static class Node {
int index;
int color = -1;
List<Node> neighbour = new ArrayList<>();
public Node(int index) {
this.index = index;
}
}
public static void main(String[] args) throws Exception {
MyScanner scan = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out));
int tc = scan.nextInt();
for (int ttc = 0; ttc < tc; ttc++) {
int nodeCount = scan.nextInt();
Node[] nodes = new Node[nodeCount];
for (int i = 0; i < nodeCount; i++) {
nodes[i] = new Node(i);
}
int edgeCount = scan.nextInt();
int[] edges = new int[edgeCount];
for (int i = 0; i < edges.length; i++) {
int a = scan.nextInt();
int b = scan.nextInt();
nodes[a - 1].neighbour.add(nodes[b - 1]);
nodes[b - 1].neighbour.add(nodes[a - 1]);
}
List<Node> v1 = new ArrayList<>();
List<Node> v2 = new ArrayList<>();
boolean[] used = new boolean[nodes.length];
List<Node> openList = new ArrayList<>();
openList.add(nodes[0]);
nodes[0].color = 0;
used[nodes[0].index] = true;
int index = 0;
while (index < openList.size()) {
Node node = openList.get(index);
if (node.color == 1) {
v2.add(node);
} else if (node.color == 0) {
v1.add(node);
}
for (int i = 0; i < node.neighbour.size(); i++) {
if (used[node.neighbour.get(i).index]) continue;
used[node.neighbour.get(i).index] = true;
node.neighbour.get(i).color = 1 - node.color;
openList.add(node.neighbour.get(i));
}
index++;
}
if (v1.size() < v2.size()) {
out.println(v1.size());
for (Node n : v1) {
out.println(n.index + 1);
}
} else {
out.println(v2.size());
for (Node n : v2) {
out.println(n.index + 1);
}
}
}
out.close();
}
} | Java | ["2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4\n6 8\n2 5\n5 4\n4 3\n4 1\n1 3\n2 3\n2 6\n5 6"] | 2 seconds | ["2\n1 3\n3\n4 3 6"] | NoteIn the first query any vertex or any pair of vertices will suffice. Note that you don't have to minimize the number of chosen vertices. In the second query two vertices can be enough (vertices $$$2$$$ and $$$4$$$) but three is also ok. | Java 8 | standard input | [
"graphs",
"shortest paths",
"dsu",
"dfs and similar",
"trees"
] | c343e6a298c12cb1257aecf823f2ead0 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^5$$$) — the number of queries. Then $$$t$$$ queries follow. The first line of each query contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n - 1 \le m \le min(2 \cdot 10^5, \frac{n(n-1)}{2})$$$) — the number of vertices and the number of edges, respectively. The following $$$m$$$ lines denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no self-loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the list of edges, and for each pair ($$$v_i, u_i$$$) the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that $$$\sum m \le 2 \cdot 10^5$$$ over all queries. | 1,700 | For each query print two lines. In the first line print $$$k$$$ ($$$1 \le \lfloor\frac{n}{2}\rfloor$$$) — the number of chosen vertices. In the second line print $$$k$$$ distinct integers $$$c_1, c_2, \dots, c_k$$$ in any order, where $$$c_i$$$ is the index of the $$$i$$$-th chosen vertex. It is guaranteed that the answer exists. If there are multiple answers, you can print any. | standard output | |
PASSED | df02079c20dc0facf88d8ce623a5210f | train_001.jsonl | 1560090900 | You are given an undirected unweighted connected graph consisting of $$$n$$$ vertices and $$$m$$$ edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.Your task is to choose at most $$$\lfloor\frac{n}{2}\rfloor$$$ vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices.It is guaranteed that the answer exists. If there are multiple answers, you can print any.You will be given multiple independent queries to answer. | 256 megabytes | import java.util.*;
public class Solution {
static class Node {
int index;
int color = -1;
List<Node> neighbour = new ArrayList<>();
public Node(int index) {
this.index = index;
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
StringBuilder sb = new StringBuilder();
int tc = scan.nextInt();
for (int ttc = 0; ttc < tc; ttc++) {
int nodeCount = scan.nextInt();
Node[] nodes = new Node[nodeCount];
for (int i = 0; i < nodeCount; i++) {
nodes[i] = new Node(i);
}
int edgeCount = scan.nextInt();
int[] edges = new int[edgeCount];
for (int i = 0; i < edges.length; i++) {
int a = scan.nextInt();
int b = scan.nextInt();
nodes[a - 1].neighbour.add(nodes[b - 1]);
nodes[b - 1].neighbour.add(nodes[a - 1]);
}
List<Node> v1 = new ArrayList<>();
List<Node> v2 = new ArrayList<>();
boolean[] used = new boolean[nodes.length];
List<Node> openList = new ArrayList<>();
openList.add(nodes[0]);
nodes[0].color = 0;
used[nodes[0].index] = true;
int index = 0;
while (index < openList.size()) {
Node node = openList.get(index);
if (node.color == 1) {
v2.add(node);
} else if (node.color == 0) {
v1.add(node);
}
for (int i = 0; i < node.neighbour.size(); i++) {
if (used[node.neighbour.get(i).index]) continue;
used[node.neighbour.get(i).index] = true;
node.neighbour.get(i).color = 1 - node.color;
openList.add(node.neighbour.get(i));
}
index++;
}
if (v1.size() < v2.size()) {
sb.append(v1.size());
for (Node n : v1) {
sb.append(" ");
sb.append(n.index + 1);
}
sb.append('\n');
} else {
sb.append(v2.size());
for (Node n : v2) {
sb.append(" ");
sb.append(n.index + 1);
}
sb.append('\n');
}
}
System.out.println(sb.toString());
}
} | Java | ["2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4\n6 8\n2 5\n5 4\n4 3\n4 1\n1 3\n2 3\n2 6\n5 6"] | 2 seconds | ["2\n1 3\n3\n4 3 6"] | NoteIn the first query any vertex or any pair of vertices will suffice. Note that you don't have to minimize the number of chosen vertices. In the second query two vertices can be enough (vertices $$$2$$$ and $$$4$$$) but three is also ok. | Java 8 | standard input | [
"graphs",
"shortest paths",
"dsu",
"dfs and similar",
"trees"
] | c343e6a298c12cb1257aecf823f2ead0 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^5$$$) — the number of queries. Then $$$t$$$ queries follow. The first line of each query contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n - 1 \le m \le min(2 \cdot 10^5, \frac{n(n-1)}{2})$$$) — the number of vertices and the number of edges, respectively. The following $$$m$$$ lines denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no self-loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the list of edges, and for each pair ($$$v_i, u_i$$$) the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that $$$\sum m \le 2 \cdot 10^5$$$ over all queries. | 1,700 | For each query print two lines. In the first line print $$$k$$$ ($$$1 \le \lfloor\frac{n}{2}\rfloor$$$) — the number of chosen vertices. In the second line print $$$k$$$ distinct integers $$$c_1, c_2, \dots, c_k$$$ in any order, where $$$c_i$$$ is the index of the $$$i$$$-th chosen vertex. It is guaranteed that the answer exists. If there are multiple answers, you can print any. | standard output | |
PASSED | 837802c742df8e9984467e837ae50032 | train_001.jsonl | 1560090900 | You are given an undirected unweighted connected graph consisting of $$$n$$$ vertices and $$$m$$$ edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.Your task is to choose at most $$$\lfloor\frac{n}{2}\rfloor$$$ vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices.It is guaranteed that the answer exists. If there are multiple answers, you can print any.You will be given multiple independent queries to answer. | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.Queue;
public class E565 {
public static void main(String[] args) {
FastScanner in = new FastScanner(System.in);
int T = in.nextInt();
StringBuilder sb = new StringBuilder();
for(int t = 0; t < T; t++) {
int N = in.nextInt();
int M = in.nextInt();
int[][] edges = new int[M][2];
for(int i = 0; i < M; i++) {
edges[i] = new int[] {in.nextInt()-1, in.nextInt()-1};
}
boolean[] visited = new boolean[M];
UF uf = new UF(N);
int index = 0;
while(uf.count > 1) {
if(!uf.connected(edges[index][0], edges[index][1])) {
visited[index] = true;
uf.union(edges[index][0], edges[index][1]);
}
index++;
}
ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
for(int i = 0; i < N; i++) {
adj.add(new ArrayList<>());
}
for(int i = 0; i < M; i++) {
if(visited[i]) {
int u = edges[i][0];
int v = edges[i][1];
adj.get(u).add(v);
adj.get(v).add(u);
}
}
int root = 0;
visited = new boolean[N];
int[] levels = new int[N];
Arrays.fill(levels, Integer.MAX_VALUE);
while(adj.get(root).size() == 0)
root++;
levels[root] = 0;
Queue<Integer> q = new LinkedList<>();
q.add(root);
while(!q.isEmpty()) {
int node = q.poll();
if(visited[node])
continue;
visited[node] = true;
for(int i : adj.get(node)) {
levels[i] = Math.min(levels[node] + 1, levels[i]);
q.add(i);
}
}
ArrayList<Integer> evens = new ArrayList<>();
ArrayList<Integer> odds = new ArrayList<>();
for(int i = 0; i < levels.length; i++) {
if((levels[i] & 1) == 0) {
evens.add(i);
}
else {
odds.add(i);
}
}
ArrayList<Integer> shorter = (evens.size() <= odds.size()) ? evens : odds;
sb.append(shorter.size());
sb.append("\n");
for(int i = 0; i < shorter.size(); i++) {
sb.append(1 + shorter.get(i));
if(i != shorter.size()-1)
sb.append(" ");
}
sb.append("\n");
}
System.out.print(sb.toString());
}
/*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
static class UF {
private int[] parent; // parent[i] = parent of i
private byte[] rank; // rank[i] = rank of subtree rooted at i (never more than 31)
private int count; // number of components
/**
* Initializes an empty union�find data structure with {@code n} sites
* {@code 0} through {@code n-1}. Each site is initially in its own
* component.
*
* @param n the number of sites
* @throws IllegalArgumentException if {@code n < 0}
*/
public UF(int n) {
if (n < 0) throw new IllegalArgumentException();
count = n;
parent = new int[n];
rank = new byte[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
rank[i] = 0;
}
}
/**
* Returns the component identifier for the component containing site {@code p}.
*
* @param p the integer representing one site
* @return the component identifier for the component containing site {@code p}
* @throws IllegalArgumentException unless {@code 0 <= p < n}
*/
public int find(int p) {
validate(p);
while (p != parent[p]) {
parent[p] = parent[parent[p]]; // path compression by halving
p = parent[p];
}
return p;
}
/**
* Returns the number of components.
*
* @return the number of components (between {@code 1} and {@code n})
*/
public int count() {
return count;
}
/**
* Returns true if the the two sites are in the same component.
*
* @param p the integer representing one site
* @param q the integer representing the other site
* @return {@code true} if the two sites {@code p} and {@code q} are in the same component;
* {@code false} otherwise
* @throws IllegalArgumentException unless
* both {@code 0 <= p < n} and {@code 0 <= q < n}
*/
public boolean connected(int p, int q) {
return find(p) == find(q);
}
/**
* Merges the component containing site {@code p} with the
* the component containing site {@code q}.
*
* @param p the integer representing one site
* @param q the integer representing the other site
* @throws IllegalArgumentException unless
* both {@code 0 <= p < n} and {@code 0 <= q < n}
*/
public void union(int p, int q) {
int rootP = find(p);
int rootQ = find(q);
if (rootP == rootQ) return;
// make root of smaller rank point to root of larger rank
if (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ;
else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP;
else {
parent[rootQ] = rootP;
rank[rootP]++;
}
count--;
}
// validate that p is a valid index
private void validate(int p) {
int n = parent.length;
if (p < 0 || p >= n) {
throw new IllegalArgumentException("index " + p + " is not between 0 and " + (n-1));
}
}
}
/**
* Source: Matt Fontaine
*/
static class FastScanner {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int chars;
public FastScanner(InputStream stream) {
this.stream = stream;
}
int read() {
if (chars == -1)
throw new InputMismatchException();
if (curChar >= chars) {
curChar = 0;
try {
chars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (chars <= 0)
return -1;
}
return buf[curChar++];
}
boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
boolean isEndline(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String next() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = read();
while (isEndline(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndline(c));
return res.toString();
}
}
}
/*
2
4 6
1 2
1 3
1 4
2 3
2 4
3 4
6 8
2 5
5 4
4 3
4 1
1 3
2 3
2 6
5 6
outputCopy
2
1 3
3
4 3 6
1
5 6
1 2
1 3
1 4
2 3
3 4
4 5
2
1 5
*/ | Java | ["2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4\n6 8\n2 5\n5 4\n4 3\n4 1\n1 3\n2 3\n2 6\n5 6"] | 2 seconds | ["2\n1 3\n3\n4 3 6"] | NoteIn the first query any vertex or any pair of vertices will suffice. Note that you don't have to minimize the number of chosen vertices. In the second query two vertices can be enough (vertices $$$2$$$ and $$$4$$$) but three is also ok. | Java 8 | standard input | [
"graphs",
"shortest paths",
"dsu",
"dfs and similar",
"trees"
] | c343e6a298c12cb1257aecf823f2ead0 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^5$$$) — the number of queries. Then $$$t$$$ queries follow. The first line of each query contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n - 1 \le m \le min(2 \cdot 10^5, \frac{n(n-1)}{2})$$$) — the number of vertices and the number of edges, respectively. The following $$$m$$$ lines denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no self-loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the list of edges, and for each pair ($$$v_i, u_i$$$) the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that $$$\sum m \le 2 \cdot 10^5$$$ over all queries. | 1,700 | For each query print two lines. In the first line print $$$k$$$ ($$$1 \le \lfloor\frac{n}{2}\rfloor$$$) — the number of chosen vertices. In the second line print $$$k$$$ distinct integers $$$c_1, c_2, \dots, c_k$$$ in any order, where $$$c_i$$$ is the index of the $$$i$$$-th chosen vertex. It is guaranteed that the answer exists. If there are multiple answers, you can print any. | standard output | |
PASSED | a1f59aa0a1d68e867b90776f292a8081 | train_001.jsonl | 1560090900 | You are given an undirected unweighted connected graph consisting of $$$n$$$ vertices and $$$m$$$ edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.Your task is to choose at most $$$\lfloor\frac{n}{2}\rfloor$$$ vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices.It is guaranteed that the answer exists. If there are multiple answers, you can print any.You will be given multiple independent queries to answer. | 256 megabytes | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.StringTokenizer;
public class TaskD {
public static void main(String[] args) throws IOException {
//Scanner s = new Scanner(System.in);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st = new StringTokenizer(br.readLine());
int q = Integer.parseInt(st.nextToken());
while(q > 0) {
st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
int max = n/2;
int[] nodes = new int[n];
int count = 0;
for(int i=0;i<m;i++) {
st = new StringTokenizer(br.readLine());
int nodeA = Integer.parseInt(st.nextToken())-1;
int nodeB = Integer.parseInt(st.nextToken())-1;
if(nodes[nodeA] == 0 && nodes[nodeB] == 0) {
nodes[nodeA] = 1;
nodes[nodeB] = 2;
count++;
} else if(nodes[nodeA] == 0 && nodes[nodeB] != 0) {
if(nodes[nodeB] == 1) {
nodes[nodeA] = 2;
} else {
nodes[nodeA] = 1;
count++;
}
} else if(nodes[nodeA] != 0 && nodes[nodeB] == 0) {
if(nodes[nodeA] == 1) {
nodes[nodeB] = 2;
} else {
nodes[nodeB] = 1;
count++;
}
}
}
int remColor = 0;
if(count <= max) {
remColor = 1;
} else {
remColor = 2;
count = n - count;
}
out.write(count + "\n");
for(int i=0;i<n;i++) {
if(nodes[i] == remColor) {
out.write((i+1) + " ");
}
}
out.write("\n");
out.flush();
//print(nodes);
q--;
}
}
public static void print(int[] arr) {
System.out.println();
for(int i=0;i<arr.length;i++) {
System.out.print(arr[i] + " ");
}
}
}
| Java | ["2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4\n6 8\n2 5\n5 4\n4 3\n4 1\n1 3\n2 3\n2 6\n5 6"] | 2 seconds | ["2\n1 3\n3\n4 3 6"] | NoteIn the first query any vertex or any pair of vertices will suffice. Note that you don't have to minimize the number of chosen vertices. In the second query two vertices can be enough (vertices $$$2$$$ and $$$4$$$) but three is also ok. | Java 8 | standard input | [
"graphs",
"shortest paths",
"dsu",
"dfs and similar",
"trees"
] | c343e6a298c12cb1257aecf823f2ead0 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^5$$$) — the number of queries. Then $$$t$$$ queries follow. The first line of each query contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n - 1 \le m \le min(2 \cdot 10^5, \frac{n(n-1)}{2})$$$) — the number of vertices and the number of edges, respectively. The following $$$m$$$ lines denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no self-loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the list of edges, and for each pair ($$$v_i, u_i$$$) the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that $$$\sum m \le 2 \cdot 10^5$$$ over all queries. | 1,700 | For each query print two lines. In the first line print $$$k$$$ ($$$1 \le \lfloor\frac{n}{2}\rfloor$$$) — the number of chosen vertices. In the second line print $$$k$$$ distinct integers $$$c_1, c_2, \dots, c_k$$$ in any order, where $$$c_i$$$ is the index of the $$$i$$$-th chosen vertex. It is guaranteed that the answer exists. If there are multiple answers, you can print any. | standard output | |
PASSED | 226a2ca4d9c5866dc0d26db93489861e | train_001.jsonl | 1560090900 | You are given an undirected unweighted connected graph consisting of $$$n$$$ vertices and $$$m$$$ edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.Your task is to choose at most $$$\lfloor\frac{n}{2}\rfloor$$$ vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices.It is guaranteed that the answer exists. If there are multiple answers, you can print any.You will be given multiple independent queries to answer. | 256 megabytes | import java.util.*;
import javax.lang.model.util.ElementScanner6;
import java.io.*;
public class Main{
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader inp = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Solver solver = new Solver();
solver.solve(inp, out);
out.close();
}
static class Solver {
class Node implements Comparable<Node>{
int i;
long c;
Node(int i,long c)
{
this.i=i;
this.c=c;
}
public int compareTo(Node n)
{
if(this.c==n.c)
{
return Integer.compare(this.i, n.i);
}
return Long.compare(this.c, n.c);
}
}
public boolean done(int[] sp,int[] par)
{
int root;
root=findSet(sp[0],par);
for(int i=1;i<sp.length;i++)
{
if(root!=findSet(sp[i], par))
return false;
}
return true;
}
public int findSet(int i,int[] par)
{
int x =i;
boolean flag =false;
while(par[i]>=0)
{
flag = true;
i=par[i];
}
if(flag)
par[x]=i;
return i;
}
public void unionSet(int i,int j,int[] par)
{
int x = findSet(i, par);
int y = findSet(j, par);
if(x<y)
{
par[y]=x;
}
else
{
par[x]=y;
}
}
public long pow(long a, long b, long MOD) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long val = pow(a, b / 2, MOD);
if (b % 2 == 0) {
return val * val % MOD;
} else {
return val * (val * a % MOD) % MOD;
}
}
public void minPrimeFactor(int n,int[] s)
{
boolean prime[] = new boolean[n+1];
Arrays.fill(prime, true);
s[1]=1;
s[2]=2;
for(int i=4;i<=n;i+=2)
{
prime[i]=false;
s[i]=2;
}
for(int i=3;i<=n;i+=2)
{
if(prime[i])
{
s[i]=i;
for(int j=2*i;j<=n;j+=i)
{
prime[j]=false;
s[j]=i;
}
}
}
}
// public void findAllPrime(int n,ArrayList<Node> al,int s[])
// {
// int curr = s[n];
// int cnt = 1;
// while(n>1)
// {
// n/=s[n];
// if(curr==s[n])
// {
// cnt++;
// continue;
// }
// Node n1 = new Node(curr,cnt);
// al.add(n1);
// curr=s[n];
// cnt=1;
// }
// }
public int binarySearch(int n,int k)
{
int left=1;
int right=100000000+5;
int ans=0;
while(left<=right)
{
int mid = (left+right)/2;
if(n/mid>=k)
{
left = mid+1;
ans=mid;
}
else
{
right=mid-1;
}
}
return ans;
}
public boolean checkPallindrom(String s)
{
char ch[] = s.toCharArray();
for(int i=0;i<s.length()/2;i++)
{
if(ch[i]!=ch[s.length()-1-i])
return false;
}
return true;
}
public void dfs_util(ArrayList<Integer>[] al,boolean vis[],int x,int g,int arr[],int[] count)
{
vis[x] = true;
count[0]++;
arr[x]=g;
// System.out.println("x "+x);
for(int i=0;i<al[x].size();i++)
{
if(!vis[al[x].get(i)])
{
// System.out.println("s.size "+s.size());
dfs_util(al, vis, al[x].get(i),g,arr,count);
}
}
return ;
}
public void dfs(ArrayList<Integer>[] al,int arr[],int arr1[])
{
boolean vis[] = new boolean[al.length];
int g =0;
int count[]= new int[1];
for(int i=0;i<al.length;i++)
{
if(!vis[i])
{
count[0]=0;
dfs_util(al,vis,i,g,arr,count);
arr1[g]=count[0];
g++;
}
}
}
public void remove(ArrayList<Integer>[] al,int x)
{
for(int i=0;i<al.length;i++)
{
for(int j=0;j<al[i].size();j++)
{
if(al[i].get(j)==x)
al[i].remove(j);
}
}
}
public long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
public void printDivisors(long n,ArrayList<Long> al)
{
// Note that this loop runs till square root
for (long i=2; i<=Math.sqrt(n); i++)
{
if (n%i==0)
{
// If divisors are equal, print only one
if (n/i == i)
{
al.add(i);
}
else // Otherwise print both
{
al.add(i);
al.add(n/i);
}
}
}
}
public static long constructSegment(long seg[],long arr[], int low,int high,int pos)
{
if(low==high)
{
seg[pos] = arr[low];
return seg[pos];
}
int mid = (low+high)/2;
long t1=constructSegment(seg, arr,low , mid,(2*pos)+1);
long t2=constructSegment(seg,arr,mid+1,high,(2*pos)+2);
seg[pos] = t1+t2;
return seg[pos];
}
public static long querySegment(long seg[],int low,int high,int qlow, int qhigh,int pos)
{
if(qlow<=low&&qhigh>=high)
{
return seg[pos];
}
else if(qlow>high||qhigh<low )
{
return 0;
}
else{
long ans=0;
int mid=(low+high)/2;
ans+=querySegment(seg,low , mid, qlow, qhigh, (2*pos)+1);
ans+=querySegment(seg, mid+1, high, qlow, qhigh, (2*pos)+2);
return ans;
}
}
public static int lcs( char[] X, char[] Y, int m, int n )
{
if (m == 0 || n == 0)
return 0;
if (X[m-1] == Y[n-1])
return 1 + lcs(X, Y, m-1, n-1);
else
return Integer.max(lcs(X, Y, m, n-1), lcs(X, Y, m-1, n));
}
public static long recursion(long start,long end,long cnt[],int a, int b)
{
long min=0;
long count=0;
int ans1=-1;
int ans2=-1;
int l=0;
int r=cnt.length-1;
while(l<=r)
{
int mid=(l+r)/2;
if(cnt[mid]>=start)
{
ans1=mid;
r=mid-1;
}
else
{
l=mid+1;
}
}
l=0;
r=cnt.length-1;
while(l<=r)
{
int mid=(l+r)/2;
if(cnt[mid]<=end)
{
ans2=mid;
l=mid+1;
}
else
{
r=mid-1;
}
}
if(ans1==-1||ans2==-1||ans2<ans1)
{
// System.out.println("min1 "+min);
min=a;
return a;
}
else
{
min=b*(end-start+1)*(ans2-ans1+1);
}
if(start==end)
{
// System.out.println("min "+min);
return min;
}
long mid = (end+start)/2;
min = Long.min(min,recursion(start, mid, cnt, a, b)+recursion(mid+1, end, cnt, a, b));
// System.out.println("min "+min);
return min;
}
private void solve(InputReader inp, PrintWriter out1) {
int t =inp.nextInt();
for(int k=0;k<t;k++)
{
int n = inp.nextInt();
int m =inp.nextInt();
ArrayList<Integer> al[] = new ArrayList[n];
for(int i=0;i<n;i++)
{
al[i] = new ArrayList<Integer>();
}
for(int i=0;i<m;i++)
{
int x = inp.nextInt();
int y = inp.nextInt();
al[x-1].add(y-1);
al[y-1].add(x-1);
}
boolean vis[] = new boolean[n];
Queue<Integer> q = new LinkedList<Integer>();
int count[] = new int[2];
int ar[] = new int[n];
q.add(0);
ar[0]=0;
while(!q.isEmpty())
{
int x=q.remove();
for(int i=0;i<al[x].size();i++)
{
if(!vis[al[x].get(i)])
{
q.add(al[x].get(i));
ar[al[x].get(i)]=1^ar[x];
vis[al[x].get(i)]=true;
}
}
}
for(int i=0;i<n;i++)
{
count[ar[i]]++;
}
ArrayList<Integer> ans = new ArrayList<Integer>();
if(count[0]<count[1])
{
for(int i=0;i<n;i++)
{
if(ar[i]==0)
{
ans.add(i+1);
}
}
}
else
{
for(int i=0;i<n;i++)
{
if(ar[i]==1)
{
ans.add(i+1);
}
}
}
out1.println(Math.min(count[0],count[1]));
for(int i=0;i<ans.size();i++)
{
out1.print(ans.get(i)+" ");
}
out1.println();
}
}
}
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();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
class ele{
long value;
long i;
boolean flag;
public ele(long value,long i)
{
this.value = value;
this.i=i;
this.flag = false;
}
} | Java | ["2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4\n6 8\n2 5\n5 4\n4 3\n4 1\n1 3\n2 3\n2 6\n5 6"] | 2 seconds | ["2\n1 3\n3\n4 3 6"] | NoteIn the first query any vertex or any pair of vertices will suffice. Note that you don't have to minimize the number of chosen vertices. In the second query two vertices can be enough (vertices $$$2$$$ and $$$4$$$) but three is also ok. | Java 8 | standard input | [
"graphs",
"shortest paths",
"dsu",
"dfs and similar",
"trees"
] | c343e6a298c12cb1257aecf823f2ead0 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^5$$$) — the number of queries. Then $$$t$$$ queries follow. The first line of each query contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n - 1 \le m \le min(2 \cdot 10^5, \frac{n(n-1)}{2})$$$) — the number of vertices and the number of edges, respectively. The following $$$m$$$ lines denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no self-loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the list of edges, and for each pair ($$$v_i, u_i$$$) the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that $$$\sum m \le 2 \cdot 10^5$$$ over all queries. | 1,700 | For each query print two lines. In the first line print $$$k$$$ ($$$1 \le \lfloor\frac{n}{2}\rfloor$$$) — the number of chosen vertices. In the second line print $$$k$$$ distinct integers $$$c_1, c_2, \dots, c_k$$$ in any order, where $$$c_i$$$ is the index of the $$$i$$$-th chosen vertex. It is guaranteed that the answer exists. If there are multiple answers, you can print any. | standard output | |
PASSED | 1df8e47b51935b6a95f87ba303392160 | train_001.jsonl | 1560090900 | You are given an undirected unweighted connected graph consisting of $$$n$$$ vertices and $$$m$$$ edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.Your task is to choose at most $$$\lfloor\frac{n}{2}\rfloor$$$ vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices.It is guaranteed that the answer exists. If there are multiple answers, you can print any.You will be given multiple independent queries to answer. | 256 megabytes | import java.util.*;
import javax.lang.model.util.ElementScanner6;
import java.io.*;
public class Main{
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader inp = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Solver solver = new Solver();
solver.solve(inp, out);
out.close();
}
static class Solver {
class Node implements Comparable<Node>{
int i;
long c;
Node(int i,long c)
{
this.i=i;
this.c=c;
}
public int compareTo(Node n)
{
if(this.c==n.c)
{
return Integer.compare(this.i, n.i);
}
return Long.compare(this.c, n.c);
}
}
public boolean done(int[] sp,int[] par)
{
int root;
root=findSet(sp[0],par);
for(int i=1;i<sp.length;i++)
{
if(root!=findSet(sp[i], par))
return false;
}
return true;
}
public int findSet(int i,int[] par)
{
int x =i;
boolean flag =false;
while(par[i]>=0)
{
flag = true;
i=par[i];
}
if(flag)
par[x]=i;
return i;
}
public void unionSet(int i,int j,int[] par)
{
int x = findSet(i, par);
int y = findSet(j, par);
if(x<y)
{
par[y]=x;
}
else
{
par[x]=y;
}
}
public long pow(long a, long b, long MOD) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long val = pow(a, b / 2, MOD);
if (b % 2 == 0) {
return val * val % MOD;
} else {
return val * (val * a % MOD) % MOD;
}
}
public void minPrimeFactor(int n,int[] s)
{
boolean prime[] = new boolean[n+1];
Arrays.fill(prime, true);
s[1]=1;
s[2]=2;
for(int i=4;i<=n;i+=2)
{
prime[i]=false;
s[i]=2;
}
for(int i=3;i<=n;i+=2)
{
if(prime[i])
{
s[i]=i;
for(int j=2*i;j<=n;j+=i)
{
prime[j]=false;
s[j]=i;
}
}
}
}
// public void findAllPrime(int n,ArrayList<Node> al,int s[])
// {
// int curr = s[n];
// int cnt = 1;
// while(n>1)
// {
// n/=s[n];
// if(curr==s[n])
// {
// cnt++;
// continue;
// }
// Node n1 = new Node(curr,cnt);
// al.add(n1);
// curr=s[n];
// cnt=1;
// }
// }
public int binarySearch(int n,int k)
{
int left=1;
int right=100000000+5;
int ans=0;
while(left<=right)
{
int mid = (left+right)/2;
if(n/mid>=k)
{
left = mid+1;
ans=mid;
}
else
{
right=mid-1;
}
}
return ans;
}
public boolean checkPallindrom(String s)
{
char ch[] = s.toCharArray();
for(int i=0;i<s.length()/2;i++)
{
if(ch[i]!=ch[s.length()-1-i])
return false;
}
return true;
}
public void dfs_util(ArrayList<Integer>[] al,boolean vis[],int x,int lvl[],ArrayList<Integer>[] a)
{
vis[x] = true;
// System.out.println("x "+x);
for(int i=0;i<al[x].size();i++)
{
if(!vis[al[x].get(i)])
{
// System.out.println("s.size "+s.size());
lvl[al[x].get(i)]=1^lvl[x];
a[lvl[al[x].get(i)]].add(al[x].get(i));
dfs_util(al, vis, al[x].get(i),lvl,a);
}
}
return ;
}
public void dfs(ArrayList<Integer>[] al, int lvl[],ArrayList<Integer>[] a)
{
boolean vis[] = new boolean[al.length];
int g =0;
for(int i=0;i<al.length;i++)
{
if(!vis[i])
{
lvl[i]=0;
a[lvl[i]].add(i);
dfs_util(al,vis,i,lvl,a);
}
}
}
public void remove(ArrayList<Integer>[] al,int x)
{
for(int i=0;i<al.length;i++)
{
for(int j=0;j<al[i].size();j++)
{
if(al[i].get(j)==x)
al[i].remove(j);
}
}
}
public long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
public void printDivisors(long n,ArrayList<Long> al)
{
// Note that this loop runs till square root
for (long i=2; i<=Math.sqrt(n); i++)
{
if (n%i==0)
{
// If divisors are equal, print only one
if (n/i == i)
{
al.add(i);
}
else // Otherwise print both
{
al.add(i);
al.add(n/i);
}
}
}
}
public static long constructSegment(long seg[],long arr[], int low,int high,int pos)
{
if(low==high)
{
seg[pos] = arr[low];
return seg[pos];
}
int mid = (low+high)/2;
long t1=constructSegment(seg, arr,low , mid,(2*pos)+1);
long t2=constructSegment(seg,arr,mid+1,high,(2*pos)+2);
seg[pos] = t1+t2;
return seg[pos];
}
public static long querySegment(long seg[],int low,int high,int qlow, int qhigh,int pos)
{
if(qlow<=low&&qhigh>=high)
{
return seg[pos];
}
else if(qlow>high||qhigh<low )
{
return 0;
}
else{
long ans=0;
int mid=(low+high)/2;
ans+=querySegment(seg,low , mid, qlow, qhigh, (2*pos)+1);
ans+=querySegment(seg, mid+1, high, qlow, qhigh, (2*pos)+2);
return ans;
}
}
public static int lcs( char[] X, char[] Y, int m, int n )
{
if (m == 0 || n == 0)
return 0;
if (X[m-1] == Y[n-1])
return 1 + lcs(X, Y, m-1, n-1);
else
return Integer.max(lcs(X, Y, m, n-1), lcs(X, Y, m-1, n));
}
public static long recursion(long start,long end,long cnt[],int a, int b)
{
long min=0;
long count=0;
int ans1=-1;
int ans2=-1;
int l=0;
int r=cnt.length-1;
while(l<=r)
{
int mid=(l+r)/2;
if(cnt[mid]>=start)
{
ans1=mid;
r=mid-1;
}
else
{
l=mid+1;
}
}
l=0;
r=cnt.length-1;
while(l<=r)
{
int mid=(l+r)/2;
if(cnt[mid]<=end)
{
ans2=mid;
l=mid+1;
}
else
{
r=mid-1;
}
}
if(ans1==-1||ans2==-1||ans2<ans1)
{
// System.out.println("min1 "+min);
min=a;
return a;
}
else
{
min=b*(end-start+1)*(ans2-ans1+1);
}
if(start==end)
{
// System.out.println("min "+min);
return min;
}
long mid = (end+start)/2;
min = Long.min(min,recursion(start, mid, cnt, a, b)+recursion(mid+1, end, cnt, a, b));
// System.out.println("min "+min);
return min;
}
private void solve(InputReader inp, PrintWriter out1) {
int t =inp.nextInt();
for(int k=0;k<t;k++)
{
int n =inp.nextInt();
int m =inp.nextInt();
ArrayList<Integer> al[] = new ArrayList[n];
for(int i=0;i<n;i++)
{
al[i] = new ArrayList<Integer>();
}
for(int i=0;i<m;i++)
{
int x=inp.nextInt();
int y =inp.nextInt();
al[x-1].add(y-1);
al[y-1].add(x-1);
}
int lvl[] = new int[n];
ArrayList<Integer> a[] = new ArrayList[2];
a[0] = new ArrayList<Integer>();
a[1] = new ArrayList<Integer>();
dfs(al,lvl,a);
if(a[0].size()<=a[1].size())
{
out1.println(a[0].size());
for(int i=0;i<a[0].size();i++)
{
out1.print((a[0].get(i)+1)+" ");
}
out1.println();
}
else
{
out1.println(a[1].size());
for(int i=0;i<a[1].size();i++)
{
out1.print((a[1].get(i)+1)+" ");
}
out1.println();
}
}
}
}
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();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
class ele{
long value;
long i;
boolean flag;
public ele(long value,long i)
{
this.value = value;
this.i=i;
this.flag = false;
}
} | Java | ["2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4\n6 8\n2 5\n5 4\n4 3\n4 1\n1 3\n2 3\n2 6\n5 6"] | 2 seconds | ["2\n1 3\n3\n4 3 6"] | NoteIn the first query any vertex or any pair of vertices will suffice. Note that you don't have to minimize the number of chosen vertices. In the second query two vertices can be enough (vertices $$$2$$$ and $$$4$$$) but three is also ok. | Java 8 | standard input | [
"graphs",
"shortest paths",
"dsu",
"dfs and similar",
"trees"
] | c343e6a298c12cb1257aecf823f2ead0 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^5$$$) — the number of queries. Then $$$t$$$ queries follow. The first line of each query contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n - 1 \le m \le min(2 \cdot 10^5, \frac{n(n-1)}{2})$$$) — the number of vertices and the number of edges, respectively. The following $$$m$$$ lines denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no self-loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the list of edges, and for each pair ($$$v_i, u_i$$$) the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that $$$\sum m \le 2 \cdot 10^5$$$ over all queries. | 1,700 | For each query print two lines. In the first line print $$$k$$$ ($$$1 \le \lfloor\frac{n}{2}\rfloor$$$) — the number of chosen vertices. In the second line print $$$k$$$ distinct integers $$$c_1, c_2, \dots, c_k$$$ in any order, where $$$c_i$$$ is the index of the $$$i$$$-th chosen vertex. It is guaranteed that the answer exists. If there are multiple answers, you can print any. | standard output | |
PASSED | b4dbec687628fb6600e08c00f9f150d1 | train_001.jsonl | 1560090900 | You are given an undirected unweighted connected graph consisting of $$$n$$$ vertices and $$$m$$$ edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.Your task is to choose at most $$$\lfloor\frac{n}{2}\rfloor$$$ vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices.It is guaranteed that the answer exists. If there are multiple answers, you can print any.You will be given multiple independent queries to answer. | 256 megabytes | import java.util.Scanner;
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
int n = stdin.nextInt();
StringBuilder builder = new StringBuilder();
for(int i = 0; i < n; i++)
{
test(stdin, builder);
}
//test(stdin);
System.out.println(builder);
stdin.close();
}
public static StringBuilder test(Scanner stdin, StringBuilder builder)
{
int n = stdin.nextInt();
int m = stdin.nextInt();
TreeSet<Integer>[] graph = new TreeSet[n];
int deg[] = new int[n];
for(int i = 0; i < n; i++)
{
graph[i] = new TreeSet();
}
for(int i = 0; i < m; i++)
{
int a = stdin.nextInt() - 1;
int b = stdin.nextInt() - 1;
if(!graph[a].contains(b))
{
graph[a].add(b);
graph[b].add(a);
}
}
dfs(graph, deg, 0, 1);
int count = 0;
for(int i = 0; i < n; i++)
{
if(deg[i] == 1)
{
count++;
}
}
int toSearch = 1;
if(count > n/2)
{
count = n - count;
toSearch = -1;
}
builder.append(count + "\n");
for(int i = 0; i < n; i++)
{
if(deg[i] == toSearch)
{
builder.append((i + 1) + " ");
}
}
builder.append("\n");
return builder;
}
public static void dfs(TreeSet<Integer>[] graph, int[] deg, int vertice, int color)
{
if(deg[vertice] == 0)
{
deg[vertice] = color;
for (Integer i : graph[vertice]) {
dfs(graph, deg, i, -color);
}
}
}
} | Java | ["2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4\n6 8\n2 5\n5 4\n4 3\n4 1\n1 3\n2 3\n2 6\n5 6"] | 2 seconds | ["2\n1 3\n3\n4 3 6"] | NoteIn the first query any vertex or any pair of vertices will suffice. Note that you don't have to minimize the number of chosen vertices. In the second query two vertices can be enough (vertices $$$2$$$ and $$$4$$$) but three is also ok. | Java 8 | standard input | [
"graphs",
"shortest paths",
"dsu",
"dfs and similar",
"trees"
] | c343e6a298c12cb1257aecf823f2ead0 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^5$$$) — the number of queries. Then $$$t$$$ queries follow. The first line of each query contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n - 1 \le m \le min(2 \cdot 10^5, \frac{n(n-1)}{2})$$$) — the number of vertices and the number of edges, respectively. The following $$$m$$$ lines denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no self-loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the list of edges, and for each pair ($$$v_i, u_i$$$) the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that $$$\sum m \le 2 \cdot 10^5$$$ over all queries. | 1,700 | For each query print two lines. In the first line print $$$k$$$ ($$$1 \le \lfloor\frac{n}{2}\rfloor$$$) — the number of chosen vertices. In the second line print $$$k$$$ distinct integers $$$c_1, c_2, \dots, c_k$$$ in any order, where $$$c_i$$$ is the index of the $$$i$$$-th chosen vertex. It is guaranteed that the answer exists. If there are multiple answers, you can print any. | standard output | |
PASSED | 17527c8b6cd8537abf85da86990f5320 | train_001.jsonl | 1560090900 | You are given an undirected unweighted connected graph consisting of $$$n$$$ vertices and $$$m$$$ edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.Your task is to choose at most $$$\lfloor\frac{n}{2}\rfloor$$$ vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices.It is guaranteed that the answer exists. If there are multiple answers, you can print any.You will be given multiple independent queries to answer. | 256 megabytes | import java.util.LinkedList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder();
Scanner stdin = new Scanner(System.in);
int n = stdin.nextInt();
for(int i = 0; i < n; i++)
{
test(stdin, builder);
}
System.out.println(builder);
stdin.close();
}
public static void test(Scanner stdin, StringBuilder builder)
{
int n = stdin.nextInt();
int m = stdin.nextInt();
LinkedList<Integer>[] graph = new LinkedList[n];
int colors[] = new int[n];
for(int i = 0; i < n; i++)
{
graph[i] = new LinkedList<>();
}
for(int i = 0; i < m; i++)
{
int a = stdin.nextInt() - 1;
int b = stdin.nextInt() - 1;
graph[a].add(b);
graph[b].add(a);
}
dfs(graph, colors, 0, 1);
int count = 0;
for(int i = 0; i < n; i++)
{
if(colors[i] == 1)
{
count++;
}
}
int colored = 1;
if(count > n/2)
{
count = n - count;
colored = -1;
}
builder.append(count + "\n");
for(int i = 0; i < n; i++)
{
if(colors[i] == colored)
{
builder.append((i + 1) + " ");
}
}
builder.append("\n");
}
public static void dfs(LinkedList<Integer>[] graph, int[] colors, int vertice, int color)
{
if(colors[vertice] == 0)
{
colors[vertice] = color;
for (Integer i : graph[vertice]) {
dfs(graph, colors, i, -color);
}
}
}
} | Java | ["2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4\n6 8\n2 5\n5 4\n4 3\n4 1\n1 3\n2 3\n2 6\n5 6"] | 2 seconds | ["2\n1 3\n3\n4 3 6"] | NoteIn the first query any vertex or any pair of vertices will suffice. Note that you don't have to minimize the number of chosen vertices. In the second query two vertices can be enough (vertices $$$2$$$ and $$$4$$$) but three is also ok. | Java 8 | standard input | [
"graphs",
"shortest paths",
"dsu",
"dfs and similar",
"trees"
] | c343e6a298c12cb1257aecf823f2ead0 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^5$$$) — the number of queries. Then $$$t$$$ queries follow. The first line of each query contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n - 1 \le m \le min(2 \cdot 10^5, \frac{n(n-1)}{2})$$$) — the number of vertices and the number of edges, respectively. The following $$$m$$$ lines denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no self-loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the list of edges, and for each pair ($$$v_i, u_i$$$) the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that $$$\sum m \le 2 \cdot 10^5$$$ over all queries. | 1,700 | For each query print two lines. In the first line print $$$k$$$ ($$$1 \le \lfloor\frac{n}{2}\rfloor$$$) — the number of chosen vertices. In the second line print $$$k$$$ distinct integers $$$c_1, c_2, \dots, c_k$$$ in any order, where $$$c_i$$$ is the index of the $$$i$$$-th chosen vertex. It is guaranteed that the answer exists. If there are multiple answers, you can print any. | standard output | |
PASSED | 297964006c8d3c4c9bad84b59427a549 | train_001.jsonl | 1560090900 | You are given an undirected unweighted connected graph consisting of $$$n$$$ vertices and $$$m$$$ edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.Your task is to choose at most $$$\lfloor\frac{n}{2}\rfloor$$$ vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices.It is guaranteed that the answer exists. If there are multiple answers, you can print any.You will be given multiple independent queries to answer. | 256 megabytes | import java.util.LinkedList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder();
Scanner stdin = new Scanner(System.in);
int n = stdin.nextInt();
for(int i = 0; i < n; i++)
{
test(stdin, builder);
}
System.out.println(builder);
stdin.close();
}
public static void test(Scanner stdin, StringBuilder builder)
{
int n = stdin.nextInt();
int m = stdin.nextInt();
LinkedList<Integer>[] graph = new LinkedList[n];
int colors[] = new int[n];
for(int i = 0; i < n; i++)
{
graph[i] = new LinkedList<>();
}
for(int i = 0; i < m; i++)
{
int a = stdin.nextInt() - 1;
int b = stdin.nextInt() - 1;
graph[a].add(b);
graph[b].add(a);
}
int count = dfs(graph, colors, 0, 1);
int colored = 1;
if(count > n/2)
{
count = n - count;
colored = -1;
}
builder.append(count + "\n");
for(int i = 0; i < n; i++)
{
if(colors[i] == colored)
{
builder.append((i + 1) + " ");
}
}
builder.append("\n");
}
public static int dfs(LinkedList<Integer>[] graph, int[] colors, int vertice, int color)
{
int count = 0;
if(colors[vertice] == 0)
{
if(color == 1)
{
count++;
}
colors[vertice] = color;
for (Integer i : graph[vertice]) {
count += dfs(graph, colors, i, -color);
}
}
return count;
}
} | Java | ["2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4\n6 8\n2 5\n5 4\n4 3\n4 1\n1 3\n2 3\n2 6\n5 6"] | 2 seconds | ["2\n1 3\n3\n4 3 6"] | NoteIn the first query any vertex or any pair of vertices will suffice. Note that you don't have to minimize the number of chosen vertices. In the second query two vertices can be enough (vertices $$$2$$$ and $$$4$$$) but three is also ok. | Java 8 | standard input | [
"graphs",
"shortest paths",
"dsu",
"dfs and similar",
"trees"
] | c343e6a298c12cb1257aecf823f2ead0 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^5$$$) — the number of queries. Then $$$t$$$ queries follow. The first line of each query contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n - 1 \le m \le min(2 \cdot 10^5, \frac{n(n-1)}{2})$$$) — the number of vertices and the number of edges, respectively. The following $$$m$$$ lines denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no self-loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the list of edges, and for each pair ($$$v_i, u_i$$$) the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that $$$\sum m \le 2 \cdot 10^5$$$ over all queries. | 1,700 | For each query print two lines. In the first line print $$$k$$$ ($$$1 \le \lfloor\frac{n}{2}\rfloor$$$) — the number of chosen vertices. In the second line print $$$k$$$ distinct integers $$$c_1, c_2, \dots, c_k$$$ in any order, where $$$c_i$$$ is the index of the $$$i$$$-th chosen vertex. It is guaranteed that the answer exists. If there are multiple answers, you can print any. | standard output | |
PASSED | f4fcca1880db3c28803c56903e293333 | train_001.jsonl | 1560090900 | You are given an undirected unweighted connected graph consisting of $$$n$$$ vertices and $$$m$$$ edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.Your task is to choose at most $$$\lfloor\frac{n}{2}\rfloor$$$ vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices.It is guaranteed that the answer exists. If there are multiple answers, you can print any.You will be given multiple independent queries to answer. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Collection;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Queue;
import java.util.LinkedList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Ribhav
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
ECoverIt solver = new ECoverIt();
solver.solve(1, in, out);
out.close();
}
static class ECoverIt {
public void solve(int testNumber, FastReader s, PrintWriter out) {
int t = s.nextInt();
while (t-- > 0) {
int n = s.nextInt();
int m = s.nextInt();
HashMap<Integer, ArrayList<Integer>> map = new HashMap<>();
for (int i = 0; i < m; i++) {
int src = s.nextInt() - 1;
int dest = s.nextInt() - 1;
ArrayList<Integer> list = map.getOrDefault(src, new ArrayList<>());
list.add(dest);
map.put(src, list);
list = map.getOrDefault(dest, new ArrayList<>());
list.add(src);
map.put(dest, list);
}
Queue<Integer> q = new LinkedList<>();
q.add(0);
boolean[] visited = new boolean[n];
HashSet<Integer> blue = new HashSet<>();
HashSet<Integer> red = new HashSet<>();
red.add(0);
visited[0] = true;
while (!q.isEmpty()) {
int curr = q.poll();
ArrayList<Integer> list = map.getOrDefault(curr, new ArrayList<>());
if (red.contains(curr)) {
for (int num : list) {
if (!visited[num]) {
blue.add(num);
q.add(num);
visited[num] = true;
}
}
} else {
for (int num : list) {
if (!visited[num]) {
if (!blue.contains(num) && !blue.contains(num)) {
red.add(num);
q.add(num);
visited[num] = true;
}
}
}
}
}
HashSet<Integer> graph;
if (red.size() > blue.size()) {
graph = blue;
} else {
graph = red;
}
// out.println(graph.size());
StringBuilder ans = new StringBuilder();
ans.append(graph.size()).append("\n");
Iterator<Integer> iter = graph.iterator();
while (iter.hasNext()) {
int curr = iter.next();
ans.append(curr + 1).append(" ");
}
out.println(ans);
}
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private FastReader.SpaceCharFilter filter;
public FastReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return 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);
}
}
}
| Java | ["2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4\n6 8\n2 5\n5 4\n4 3\n4 1\n1 3\n2 3\n2 6\n5 6"] | 2 seconds | ["2\n1 3\n3\n4 3 6"] | NoteIn the first query any vertex or any pair of vertices will suffice. Note that you don't have to minimize the number of chosen vertices. In the second query two vertices can be enough (vertices $$$2$$$ and $$$4$$$) but three is also ok. | Java 8 | standard input | [
"graphs",
"shortest paths",
"dsu",
"dfs and similar",
"trees"
] | c343e6a298c12cb1257aecf823f2ead0 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^5$$$) — the number of queries. Then $$$t$$$ queries follow. The first line of each query contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n - 1 \le m \le min(2 \cdot 10^5, \frac{n(n-1)}{2})$$$) — the number of vertices and the number of edges, respectively. The following $$$m$$$ lines denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no self-loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the list of edges, and for each pair ($$$v_i, u_i$$$) the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that $$$\sum m \le 2 \cdot 10^5$$$ over all queries. | 1,700 | For each query print two lines. In the first line print $$$k$$$ ($$$1 \le \lfloor\frac{n}{2}\rfloor$$$) — the number of chosen vertices. In the second line print $$$k$$$ distinct integers $$$c_1, c_2, \dots, c_k$$$ in any order, where $$$c_i$$$ is the index of the $$$i$$$-th chosen vertex. It is guaranteed that the answer exists. If there are multiple answers, you can print any. | standard output | |
PASSED | ecb5006fd43f2e2ef32cc7fbf0bd09e9 | train_001.jsonl | 1560090900 | You are given an undirected unweighted connected graph consisting of $$$n$$$ vertices and $$$m$$$ edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.Your task is to choose at most $$$\lfloor\frac{n}{2}\rfloor$$$ vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices.It is guaranteed that the answer exists. If there are multiple answers, you can print any.You will be given multiple independent queries to answer. | 256 megabytes | import javax.swing.event.TreeSelectionEvent;
import java.io.*;
import java.util.*;
public class Main {
static long gcd(long a, long b) {
return a == 0 ? b : gcd(b, b % a);
}
static long binpow(long a, int n) {
return n == 1 ? a : (n & 1) == 0 ? binpow(a, n / 2) * binpow(a, n / 2) : a * binpow(a, n - 1);
}
static long lcm(long a, long b) {
return a * b / gcd(a, b);
}
static ArrayList<Integer> g[];
public static void main(String[] args) throws IOException {
FastScanner in = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
// FastScanner in = new FastScanner("search.in");
//PrintWriter out = new PrintWriter("search.out");
int t = in.nextInt();
while (t-- > 0) {
int n = in.nextInt();
int m = in.nextInt();
g = new ArrayList[n];
for (int i = 0; i < n; i++)
g[i] = new ArrayList<>();
for (int i = 0; i < m; i++) {
int v = in.nextInt() - 1;
int u = in.nextInt() - 1;
g[v].add(u);
g[u].add(v);
}
Queue<Integer> bfs = new ArrayDeque<>();
int dist[] = new int[n];
for (int i = 1; i < n; i++) {
dist[i] = -1;
}
bfs.add(0);
while (!bfs.isEmpty()) {
int v = bfs.poll();
for (Integer to : g[v])
if (dist[to] == -1) {
dist[to] = dist[v] + 1;
bfs.add(to);
}
}
int sum[] = new int[2];
for (int i = 0; i < n; i++) {
sum[dist[i] & 1]++;
}
int ans = 0;
if(sum[0] == sum[1]){
for (int i = 0; i < n; i++) {
if((dist[i]&1)==0)ans++;
}
out.println(ans);
for (int i = 0; i < n; i++) {
if((dist[i] & 1) == 0)out.print(i+1+" ");
}
out.println();
continue;
}
for (int i = 0; i < n; i++) {
if (sum[dist[i] & 1] < sum[(dist[i] + 1) & 1]) ans++;
}
out.println(ans);
for (int i = 0; i < n; i++) {
if (sum[dist[i] & 1] < sum[(dist[i] + 1) & 1]) out.print(i + 1 + " ");
}
out.println();
}
out.close();
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st = new StringTokenizer("");
public FastScanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public FastScanner(String s) throws FileNotFoundException {
br = new BufferedReader(new FileReader(new File(s)));
}
public String next() throws IOException {
if (!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 double nextDouble() throws IOException {
return Double.parseDouble(next());
}
} | Java | ["2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4\n6 8\n2 5\n5 4\n4 3\n4 1\n1 3\n2 3\n2 6\n5 6"] | 2 seconds | ["2\n1 3\n3\n4 3 6"] | NoteIn the first query any vertex or any pair of vertices will suffice. Note that you don't have to minimize the number of chosen vertices. In the second query two vertices can be enough (vertices $$$2$$$ and $$$4$$$) but three is also ok. | Java 8 | standard input | [
"graphs",
"shortest paths",
"dsu",
"dfs and similar",
"trees"
] | c343e6a298c12cb1257aecf823f2ead0 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^5$$$) — the number of queries. Then $$$t$$$ queries follow. The first line of each query contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n - 1 \le m \le min(2 \cdot 10^5, \frac{n(n-1)}{2})$$$) — the number of vertices and the number of edges, respectively. The following $$$m$$$ lines denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no self-loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the list of edges, and for each pair ($$$v_i, u_i$$$) the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that $$$\sum m \le 2 \cdot 10^5$$$ over all queries. | 1,700 | For each query print two lines. In the first line print $$$k$$$ ($$$1 \le \lfloor\frac{n}{2}\rfloor$$$) — the number of chosen vertices. In the second line print $$$k$$$ distinct integers $$$c_1, c_2, \dots, c_k$$$ in any order, where $$$c_i$$$ is the index of the $$$i$$$-th chosen vertex. It is guaranteed that the answer exists. If there are multiple answers, you can print any. | standard output | |
PASSED | 4606ae74806a6b492999aca1a4159dc8 | train_001.jsonl | 1364916600 | Little penguin Polo adores integer segments, that is, pairs of integers [l; r] (l ≤ r). He has a set that consists of n integer segments: [l1; r1], [l2; r2], ..., [ln; rn]. We know that no two segments of this set intersect. In one move Polo can either widen any segment of the set 1 unit to the left or 1 unit to the right, that is transform [l; r] to either segment [l - 1; r], or to segment [l; r + 1].The value of a set of segments that consists of n segments [l1; r1], [l2; r2], ..., [ln; rn] is the number of integers x, such that there is integer j, for which the following inequality holds, lj ≤ x ≤ rj.Find the minimum number of moves needed to make the value of the set of Polo's segments divisible by k. | 256 megabytes | import java.io.*;
import java.util.*;
/*
* @author: Ramanqul
* */
public class Main {
private static boolean USE_TEST_CASES = false;
private static void solve(MyScanner in, PrintWriter out) {
int n = in.nextInt();
int k = in.nextInt();
int a[][] = new int[n][2];
for (int i=0;i<n;i++) {
a[i][0] = in.nextInt();
a[i][1] = in.nextInt();
}
long sum = 0;
for (int i=0;i<n;i++) {
int x = a[i][1] - a[i][0] + 1;
sum += x;
}
long d = sum % k;
long ans = (k-sum%k)%k;
out.println(ans);
}
public static void main(String[] args) {
MyScanner sc = new MyScanner();
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
int t = 1;
if (USE_TEST_CASES) {
t = sc.nextInt();
}
for (int i=0;i<t;i++) {
solve(sc, out);
}
out.close();
}
private static class Pair<A,B> {
public A first;
public B second;
public Pair(A first, B second) {
this.first = first;
this.second = second;
}
}
private static class Triple<A,B,C> {
public A first;
public B second;
public C third;
public Triple(A first, B second, C third) {
this.first = first;
this.second = second;
this.third = third;
}
}
private static class H {
public static void readArray(MyScanner in, int a[], int n) {
for (int i=0;i<n;i++) {
a[i] = in.nextInt();
}
}
public static boolean isUnique(int ... nums) {
Set<Integer> s = new HashSet<>();
for (int i:nums) {
if (s.contains(i)) {
return false;
}
s.add(i);
}
return true;
}
public static Pair<Integer, Integer>[] readIntPairs(MyScanner in, int n) {
Pair[] pairs = new Pair[n];
for (int i=0;i<n;i++) {
int x = in.nextInt();
int y = in.nextInt();
pairs[i] = new Pair<Integer, Integer>(x, y);
}
return pairs;
}
public static List<Integer> dfs(int start, List<Integer>[] adj) {
boolean v[] = new boolean[adj.length+1];
List<Integer> res = new ArrayList<>();
Stack<Integer> st = new Stack<>();
st.push(start);
while (!st.isEmpty()) {
int x = st.pop();
if (!v[x]) {
res.add(x);
boolean allVisited = true;
for (int e: adj[x]) {
if (!v[e]) {
st.push(e);
allVisited = false;
}
}
if (allVisited) {
break;
}
v[x] = true;
} else {
break;
}
}
return res;
}
public static long gcd(long a, long b) {
if (a == 0) {
return b;
}
return gcd(b%a, a);
}
public static long lcm(long a, long b) {
return (a * b) / gcd(a,b);
}
}
private static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public MyScanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
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 3\n1 2\n3 4", "3 7\n1 2\n3 3\n4 7"] | 2 seconds | ["2", "0"] | null | Java 8 | standard input | [
"implementation",
"brute force"
] | 3a93a6f78b41cbb43c616f20beee288d | The first line contains two integers n and k (1 ≤ n, k ≤ 105). Each of the following n lines contain a segment as a pair of integers li and ri ( - 105 ≤ li ≤ ri ≤ 105), separated by a space. It is guaranteed that no two segments intersect. In other words, for any two integers i, j (1 ≤ i < j ≤ n) the following inequality holds, min(ri, rj) < max(li, lj). | 1,100 | In a single line print a single integer — the answer to the problem. | standard output | |
PASSED | 84b5efe3e03d1a42c568d74fc5a5e37d | train_001.jsonl | 1364916600 | Little penguin Polo adores integer segments, that is, pairs of integers [l; r] (l ≤ r). He has a set that consists of n integer segments: [l1; r1], [l2; r2], ..., [ln; rn]. We know that no two segments of this set intersect. In one move Polo can either widen any segment of the set 1 unit to the left or 1 unit to the right, that is transform [l; r] to either segment [l - 1; r], or to segment [l; r + 1].The value of a set of segments that consists of n segments [l1; r1], [l2; r2], ..., [ln; rn] is the number of integers x, such that there is integer j, for which the following inequality holds, lj ≤ x ≤ rj.Find the minimum number of moves needed to make the value of the set of Polo's segments divisible by k. | 256 megabytes | import java.util.Scanner;
public class JavaApplication2 {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int n=reader.nextInt();
int k=reader.nextInt();
int total=0;
for(int i=0;i<n;i++){
int min=reader.nextInt();
int max=reader.nextInt();
total+=max-min+1;
}
if(total%k==0)
System.out.println("0");
else
System.out.println(k-(total%k));
}} | Java | ["2 3\n1 2\n3 4", "3 7\n1 2\n3 3\n4 7"] | 2 seconds | ["2", "0"] | null | Java 8 | standard input | [
"implementation",
"brute force"
] | 3a93a6f78b41cbb43c616f20beee288d | The first line contains two integers n and k (1 ≤ n, k ≤ 105). Each of the following n lines contain a segment as a pair of integers li and ri ( - 105 ≤ li ≤ ri ≤ 105), separated by a space. It is guaranteed that no two segments intersect. In other words, for any two integers i, j (1 ≤ i < j ≤ n) the following inequality holds, min(ri, rj) < max(li, lj). | 1,100 | In a single line print a single integer — the answer to the problem. | standard output | |
PASSED | f447b7a51a65bb2af6f610b58c09dcff | train_001.jsonl | 1364916600 | Little penguin Polo adores integer segments, that is, pairs of integers [l; r] (l ≤ r). He has a set that consists of n integer segments: [l1; r1], [l2; r2], ..., [ln; rn]. We know that no two segments of this set intersect. In one move Polo can either widen any segment of the set 1 unit to the left or 1 unit to the right, that is transform [l; r] to either segment [l - 1; r], or to segment [l; r + 1].The value of a set of segments that consists of n segments [l1; r1], [l2; r2], ..., [ln; rn] is the number of integers x, such that there is integer j, for which the following inequality holds, lj ≤ x ≤ rj.Find the minimum number of moves needed to make the value of the set of Polo's segments divisible by k. | 256 megabytes |
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(), k = sc.nextInt();
int sum = 0;
for(int i = 0 ; i < n; i++)
sum += -(sc.nextInt() - sc.nextInt()) + 1;
System.out.println((k - sum%k) % k);
sc.close();
}
}
| Java | ["2 3\n1 2\n3 4", "3 7\n1 2\n3 3\n4 7"] | 2 seconds | ["2", "0"] | null | Java 8 | standard input | [
"implementation",
"brute force"
] | 3a93a6f78b41cbb43c616f20beee288d | The first line contains two integers n and k (1 ≤ n, k ≤ 105). Each of the following n lines contain a segment as a pair of integers li and ri ( - 105 ≤ li ≤ ri ≤ 105), separated by a space. It is guaranteed that no two segments intersect. In other words, for any two integers i, j (1 ≤ i < j ≤ n) the following inequality holds, min(ri, rj) < max(li, lj). | 1,100 | In a single line print a single integer — the answer to the problem. | standard output | |
PASSED | d0670904c225c150e17e32cd2471e3ce | train_001.jsonl | 1364916600 | Little penguin Polo adores integer segments, that is, pairs of integers [l; r] (l ≤ r). He has a set that consists of n integer segments: [l1; r1], [l2; r2], ..., [ln; rn]. We know that no two segments of this set intersect. In one move Polo can either widen any segment of the set 1 unit to the left or 1 unit to the right, that is transform [l; r] to either segment [l - 1; r], or to segment [l; r + 1].The value of a set of segments that consists of n segments [l1; r1], [l2; r2], ..., [ln; rn] is the number of integers x, such that there is integer j, for which the following inequality holds, lj ≤ x ≤ rj.Find the minimum number of moves needed to make the value of the set of Polo's segments divisible by k. | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int k = in.nextInt();
int covered = 0;
for(int i=0;i<n;i++){
int l = in.nextInt();
int r = in.nextInt();
covered += (r - l +1);
}
int reminder = covered % k;
if(reminder == 0){
System.out.println(0);
}else{
System.out.println(k-reminder);
}
}
} | Java | ["2 3\n1 2\n3 4", "3 7\n1 2\n3 3\n4 7"] | 2 seconds | ["2", "0"] | null | Java 8 | standard input | [
"implementation",
"brute force"
] | 3a93a6f78b41cbb43c616f20beee288d | The first line contains two integers n and k (1 ≤ n, k ≤ 105). Each of the following n lines contain a segment as a pair of integers li and ri ( - 105 ≤ li ≤ ri ≤ 105), separated by a space. It is guaranteed that no two segments intersect. In other words, for any two integers i, j (1 ≤ i < j ≤ n) the following inequality holds, min(ri, rj) < max(li, lj). | 1,100 | In a single line print a single integer — the answer to the problem. | standard output | |
PASSED | 8f278d2c56694626c5e586b0e8da0640 | train_001.jsonl | 1364916600 | Little penguin Polo adores integer segments, that is, pairs of integers [l; r] (l ≤ r). He has a set that consists of n integer segments: [l1; r1], [l2; r2], ..., [ln; rn]. We know that no two segments of this set intersect. In one move Polo can either widen any segment of the set 1 unit to the left or 1 unit to the right, that is transform [l; r] to either segment [l - 1; r], or to segment [l; r + 1].The value of a set of segments that consists of n segments [l1; r1], [l2; r2], ..., [ln; rn] is the number of integers x, such that there is integer j, for which the following inequality holds, lj ≤ x ≤ rj.Find the minimum number of moves needed to make the value of the set of Polo's segments divisible by k. | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int k = s.nextInt();
int sum = 0;
while(n-- > 0) {
int l = s.nextInt();
int r = s.nextInt();
sum += (r - l) + 1;
}
int res = k - (sum % k);
if(res == k) {
System.out.println(0);
} else {
System.out.println(res);
}
}
}
| Java | ["2 3\n1 2\n3 4", "3 7\n1 2\n3 3\n4 7"] | 2 seconds | ["2", "0"] | null | Java 8 | standard input | [
"implementation",
"brute force"
] | 3a93a6f78b41cbb43c616f20beee288d | The first line contains two integers n and k (1 ≤ n, k ≤ 105). Each of the following n lines contain a segment as a pair of integers li and ri ( - 105 ≤ li ≤ ri ≤ 105), separated by a space. It is guaranteed that no two segments intersect. In other words, for any two integers i, j (1 ≤ i < j ≤ n) the following inequality holds, min(ri, rj) < max(li, lj). | 1,100 | In a single line print a single integer — the answer to the problem. | standard output | |
PASSED | 5a9098b0b25d70c812a9665b910b1b2a | train_001.jsonl | 1364916600 | Little penguin Polo adores integer segments, that is, pairs of integers [l; r] (l ≤ r). He has a set that consists of n integer segments: [l1; r1], [l2; r2], ..., [ln; rn]. We know that no two segments of this set intersect. In one move Polo can either widen any segment of the set 1 unit to the left or 1 unit to the right, that is transform [l; r] to either segment [l - 1; r], or to segment [l; r + 1].The value of a set of segments that consists of n segments [l1; r1], [l2; r2], ..., [ln; rn] is the number of integers x, such that there is integer j, for which the following inequality holds, lj ≤ x ≤ rj.Find the minimum number of moves needed to make the value of the set of Polo's segments divisible by k. | 256 megabytes | import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int k = scan.nextInt();
int o = 5%2;
int c = 0;
for (int i = 0; i < n; i++) {
int n1 = scan.nextInt();
int n2 = scan.nextInt();
c += Math.abs(n1 - n2)+1;
}
c %= k;
if(c != 0) {
c = k - c;
}
System.out.println(c);
scan.close();
}
}
| Java | ["2 3\n1 2\n3 4", "3 7\n1 2\n3 3\n4 7"] | 2 seconds | ["2", "0"] | null | Java 8 | standard input | [
"implementation",
"brute force"
] | 3a93a6f78b41cbb43c616f20beee288d | The first line contains two integers n and k (1 ≤ n, k ≤ 105). Each of the following n lines contain a segment as a pair of integers li and ri ( - 105 ≤ li ≤ ri ≤ 105), separated by a space. It is guaranteed that no two segments intersect. In other words, for any two integers i, j (1 ≤ i < j ≤ n) the following inequality holds, min(ri, rj) < max(li, lj). | 1,100 | In a single line print a single integer — the answer to the problem. | standard output | |
PASSED | 769531b7ab7ccde457e8cf523586d788 | train_001.jsonl | 1364916600 | Little penguin Polo adores integer segments, that is, pairs of integers [l; r] (l ≤ r). He has a set that consists of n integer segments: [l1; r1], [l2; r2], ..., [ln; rn]. We know that no two segments of this set intersect. In one move Polo can either widen any segment of the set 1 unit to the left or 1 unit to the right, that is transform [l; r] to either segment [l - 1; r], or to segment [l; r + 1].The value of a set of segments that consists of n segments [l1; r1], [l2; r2], ..., [ln; rn] is the number of integers x, such that there is integer j, for which the following inequality holds, lj ≤ x ≤ rj.Find the minimum number of moves needed to make the value of the set of Polo's segments divisible by k. | 256 megabytes | import java.util.Scanner;
public class PenguinSegments {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int k = scanner.nextInt();
int covered = 0;
for (int i = 0; i < n; i++) {
int start = scanner.nextInt();
int end = scanner.nextInt();
covered += (end - start + 1);
}
System.out.println((k - (covered % k)) % k);
}
}
| Java | ["2 3\n1 2\n3 4", "3 7\n1 2\n3 3\n4 7"] | 2 seconds | ["2", "0"] | null | Java 8 | standard input | [
"implementation",
"brute force"
] | 3a93a6f78b41cbb43c616f20beee288d | The first line contains two integers n and k (1 ≤ n, k ≤ 105). Each of the following n lines contain a segment as a pair of integers li and ri ( - 105 ≤ li ≤ ri ≤ 105), separated by a space. It is guaranteed that no two segments intersect. In other words, for any two integers i, j (1 ≤ i < j ≤ n) the following inequality holds, min(ri, rj) < max(li, lj). | 1,100 | In a single line print a single integer — the answer to the problem. | standard output | |
PASSED | 1f823632f5e3f1cb259510387d67c7cc | train_001.jsonl | 1364916600 | Little penguin Polo adores integer segments, that is, pairs of integers [l; r] (l ≤ r). He has a set that consists of n integer segments: [l1; r1], [l2; r2], ..., [ln; rn]. We know that no two segments of this set intersect. In one move Polo can either widen any segment of the set 1 unit to the left or 1 unit to the right, that is transform [l; r] to either segment [l - 1; r], or to segment [l; r + 1].The value of a set of segments that consists of n segments [l1; r1], [l2; r2], ..., [ln; rn] is the number of integers x, such that there is integer j, for which the following inequality holds, lj ≤ x ≤ rj.Find the minimum number of moves needed to make the value of the set of Polo's segments divisible by k. | 256 megabytes |
import java.io.*;
import java.util.StringTokenizer;
public class Sol {
static FastReader reader = new FastReader();
/**
* ####
* .#..
* ####
* ....
*/
public static void main(String[] args) {
int n = reader.nextInt();
int k = reader.nextInt();
int sum = 0;
for (int i = 0; i < n; i++) {
sum += Math.abs(reader.nextInt() - reader.nextInt()) + 1;
}
// StdOut.println(sum);
sum %= k;
if (sum == 0) System.out.println(0);
else
System.out.println(k - (sum % k));
}
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 3\n1 2\n3 4", "3 7\n1 2\n3 3\n4 7"] | 2 seconds | ["2", "0"] | null | Java 8 | standard input | [
"implementation",
"brute force"
] | 3a93a6f78b41cbb43c616f20beee288d | The first line contains two integers n and k (1 ≤ n, k ≤ 105). Each of the following n lines contain a segment as a pair of integers li and ri ( - 105 ≤ li ≤ ri ≤ 105), separated by a space. It is guaranteed that no two segments intersect. In other words, for any two integers i, j (1 ≤ i < j ≤ n) the following inequality holds, min(ri, rj) < max(li, lj). | 1,100 | In a single line print a single integer — the answer to the problem. | standard output | |
PASSED | 963e80d023de14a1974457b98e5fe65c | train_001.jsonl | 1364916600 | Little penguin Polo adores integer segments, that is, pairs of integers [l; r] (l ≤ r). He has a set that consists of n integer segments: [l1; r1], [l2; r2], ..., [ln; rn]. We know that no two segments of this set intersect. In one move Polo can either widen any segment of the set 1 unit to the left or 1 unit to the right, that is transform [l; r] to either segment [l - 1; r], or to segment [l; r + 1].The value of a set of segments that consists of n segments [l1; r1], [l2; r2], ..., [ln; rn] is the number of integers x, such that there is integer j, for which the following inequality holds, lj ≤ x ≤ rj.Find the minimum number of moves needed to make the value of the set of Polo's segments divisible by k. | 256 megabytes | import java.io.BufferedReader;
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.Collections;
import java.util.Deque;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
public class Main {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
StringBuilder sb = new StringBuilder();
int n = sc.nextInt() , k = sc.nextInt();
long num = 0;
while (n -- > 0) {
int l = sc.nextInt() , r = sc.nextInt();
num += (r - l + 1);
}
System.out.println(k - (num % k) == k ? 0 : k - (num % k));
out.flush();
out.close();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
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();
}
public boolean nextEmpty() throws IOException
{
String s = nextLine();
st = new StringTokenizer(s);
return s.isEmpty();
}
}
} | Java | ["2 3\n1 2\n3 4", "3 7\n1 2\n3 3\n4 7"] | 2 seconds | ["2", "0"] | null | Java 8 | standard input | [
"implementation",
"brute force"
] | 3a93a6f78b41cbb43c616f20beee288d | The first line contains two integers n and k (1 ≤ n, k ≤ 105). Each of the following n lines contain a segment as a pair of integers li and ri ( - 105 ≤ li ≤ ri ≤ 105), separated by a space. It is guaranteed that no two segments intersect. In other words, for any two integers i, j (1 ≤ i < j ≤ n) the following inequality holds, min(ri, rj) < max(li, lj). | 1,100 | In a single line print a single integer — the answer to the problem. | standard output | |
PASSED | 7e444f00b7592fd9869dfbcead8c3fe0 | train_001.jsonl | 1364916600 | Little penguin Polo adores integer segments, that is, pairs of integers [l; r] (l ≤ r). He has a set that consists of n integer segments: [l1; r1], [l2; r2], ..., [ln; rn]. We know that no two segments of this set intersect. In one move Polo can either widen any segment of the set 1 unit to the left or 1 unit to the right, that is transform [l; r] to either segment [l - 1; r], or to segment [l; r + 1].The value of a set of segments that consists of n segments [l1; r1], [l2; r2], ..., [ln; rn] is the number of integers x, such that there is integer j, for which the following inequality holds, lj ≤ x ≤ rj.Find the minimum number of moves needed to make the value of the set of Polo's segments divisible by k. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public final class Solution
{
public static void main(String[] args)
{
Reader input = new Reader();
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
int n = input.nextInt(), k = input.nextInt() , a , b;
long numbers = 0;
for(int i = 0 ; i < n ; i++)
{
a = input.nextInt();
b = input.nextInt();
numbers += b - a + 1;
}
if(numbers % k == 0)
out.println(0);
else
out.println((numbers / k + 1) * k - numbers);
out.close();
}
public static class Reader
{
BufferedReader br;
StringTokenizer st;
public Reader()
{
br = new BufferedReader(new InputStreamReader(System.in));
}
public String next()
{
try
{
if(st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
}
catch(IOException ex)
{
ex.printStackTrace();
System.exit(1);
}
return st.nextToken();
}
public int nextInt()
{
return Integer.parseInt(next());
}
public double nextDouble()
{
return Double.parseDouble(next());
}
public long nextLong()
{
return Long.parseLong(next());
}
public String nextLine()
{
try
{
return br.readLine();
}
catch(IOException ex)
{
ex.printStackTrace();
System.exit(1);
}
return "";
}
}
} | Java | ["2 3\n1 2\n3 4", "3 7\n1 2\n3 3\n4 7"] | 2 seconds | ["2", "0"] | null | Java 8 | standard input | [
"implementation",
"brute force"
] | 3a93a6f78b41cbb43c616f20beee288d | The first line contains two integers n and k (1 ≤ n, k ≤ 105). Each of the following n lines contain a segment as a pair of integers li and ri ( - 105 ≤ li ≤ ri ≤ 105), separated by a space. It is guaranteed that no two segments intersect. In other words, for any two integers i, j (1 ≤ i < j ≤ n) the following inequality holds, min(ri, rj) < max(li, lj). | 1,100 | In a single line print a single integer — the answer to the problem. | standard output | |
PASSED | 7938b118a4ed96a4e861ce9c06121e75 | train_001.jsonl | 1364916600 | Little penguin Polo adores integer segments, that is, pairs of integers [l; r] (l ≤ r). He has a set that consists of n integer segments: [l1; r1], [l2; r2], ..., [ln; rn]. We know that no two segments of this set intersect. In one move Polo can either widen any segment of the set 1 unit to the left or 1 unit to the right, that is transform [l; r] to either segment [l - 1; r], or to segment [l; r + 1].The value of a set of segments that consists of n segments [l1; r1], [l2; r2], ..., [ln; rn] is the number of integers x, such that there is integer j, for which the following inequality holds, lj ≤ x ≤ rj.Find the minimum number of moves needed to make the value of the set of Polo's segments divisible by k. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public final class Solution
{
public static void main(String[] args)
{
Reader input = new Reader();
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
int n = input.nextInt(), k = input.nextInt() , a , b;
long numbers = 0;
for(int i = 0 ; i < n ; i++)
{
a = input.nextInt();
b = input.nextInt();
numbers += b - a + 1;
}
if(numbers % k == 0)
out.println(0);
else
out.println((numbers / k + 1) * k - numbers);
out.close();
}
public static class Reader
{
BufferedReader br;
StringTokenizer st;
public Reader()
{
br = new BufferedReader(new InputStreamReader(System.in));
}
public String next()
{
try
{
if(st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
}
catch(IOException ex)
{
ex.printStackTrace();
System.exit(1);
}
return st.nextToken();
}
public int nextInt()
{
return Integer.parseInt(next());
}
public double nextDouble()
{
return Double.parseDouble(next());
}
public long nextLong()
{
return Long.parseLong(next());
}
public String nextLine()
{
try
{
return br.readLine();
}
catch(IOException ex)
{
ex.printStackTrace();
System.exit(1);
}
return "";
}
}
} | Java | ["2 3\n1 2\n3 4", "3 7\n1 2\n3 3\n4 7"] | 2 seconds | ["2", "0"] | null | Java 8 | standard input | [
"implementation",
"brute force"
] | 3a93a6f78b41cbb43c616f20beee288d | The first line contains two integers n and k (1 ≤ n, k ≤ 105). Each of the following n lines contain a segment as a pair of integers li and ri ( - 105 ≤ li ≤ ri ≤ 105), separated by a space. It is guaranteed that no two segments intersect. In other words, for any two integers i, j (1 ≤ i < j ≤ n) the following inequality holds, min(ri, rj) < max(li, lj). | 1,100 | In a single line print a single integer — the answer to the problem. | standard output | |
PASSED | c851ee163ba1f8f20b9a2e32e4b215ba | train_001.jsonl | 1364916600 | Little penguin Polo adores integer segments, that is, pairs of integers [l; r] (l ≤ r). He has a set that consists of n integer segments: [l1; r1], [l2; r2], ..., [ln; rn]. We know that no two segments of this set intersect. In one move Polo can either widen any segment of the set 1 unit to the left or 1 unit to the right, that is transform [l; r] to either segment [l - 1; r], or to segment [l; r + 1].The value of a set of segments that consists of n segments [l1; r1], [l2; r2], ..., [ln; rn] is the number of integers x, such that there is integer j, for which the following inequality holds, lj ≤ x ≤ rj.Find the minimum number of moves needed to make the value of the set of Polo's segments divisible by k. | 256 megabytes | import java.util.*;
public class PolothePenguinandSegments {
public static void main(String[] args) {
Scanner in= new Scanner(System.in);
int n=in.nextInt();
int k=in.nextInt();
int[] arr=new int[2*n];
int nint=0;
for(int i=0;i<arr.length;i+=2) {
int l=in.nextInt();
int r=in.nextInt();
nint+=(r-l+1);
arr[i]=l;
arr[i+1]=r;
}
int x = 0;
int x1=nint-nint%k;
int x2=nint+(k-nint%k);
x=(k-nint%k)%k;
System.out.println(x);
}
}
| Java | ["2 3\n1 2\n3 4", "3 7\n1 2\n3 3\n4 7"] | 2 seconds | ["2", "0"] | null | Java 8 | standard input | [
"implementation",
"brute force"
] | 3a93a6f78b41cbb43c616f20beee288d | The first line contains two integers n and k (1 ≤ n, k ≤ 105). Each of the following n lines contain a segment as a pair of integers li and ri ( - 105 ≤ li ≤ ri ≤ 105), separated by a space. It is guaranteed that no two segments intersect. In other words, for any two integers i, j (1 ≤ i < j ≤ n) the following inequality holds, min(ri, rj) < max(li, lj). | 1,100 | In a single line print a single integer — the answer to the problem. | standard output | |
PASSED | 92d942bf7f9e42ac6d3d3a1d833cc477 | train_001.jsonl | 1364916600 | Little penguin Polo adores integer segments, that is, pairs of integers [l; r] (l ≤ r). He has a set that consists of n integer segments: [l1; r1], [l2; r2], ..., [ln; rn]. We know that no two segments of this set intersect. In one move Polo can either widen any segment of the set 1 unit to the left or 1 unit to the right, that is transform [l; r] to either segment [l - 1; r], or to segment [l; r + 1].The value of a set of segments that consists of n segments [l1; r1], [l2; r2], ..., [ln; rn] is the number of integers x, such that there is integer j, for which the following inequality holds, lj ≤ x ≤ rj.Find the minimum number of moves needed to make the value of the set of Polo's segments divisible by k. | 256 megabytes |
//package polo.the.penguin.and.segments;
import java.util.Scanner;
public class PoloThePenguinAndSegments {
private static int count=0, numberBetween,j = 0;
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int n=in.nextInt();
int k=in.nextInt();
for (int i = 0; i < n; i++) {
int x=in.nextInt();
int y=in.nextInt();
PoloThePenguinAndSegments p=new PoloThePenguinAndSegments();
numberBetween = p.numberBetween(x,y);
}
if(numberBetween%k==0)
{
System.out.println(j); }
else
{
/* while(numberBetween%k!=0)
{
numberBetween++;
j++;
}*/
for (; numberBetween%k!=0; j++) {
numberBetween++;
}
System.out.println(j);
}
}
private int numberBetween (int x, int y){
while( x<=y) {
count++;
x++;
}
return count;}
}
| Java | ["2 3\n1 2\n3 4", "3 7\n1 2\n3 3\n4 7"] | 2 seconds | ["2", "0"] | null | Java 8 | standard input | [
"implementation",
"brute force"
] | 3a93a6f78b41cbb43c616f20beee288d | The first line contains two integers n and k (1 ≤ n, k ≤ 105). Each of the following n lines contain a segment as a pair of integers li and ri ( - 105 ≤ li ≤ ri ≤ 105), separated by a space. It is guaranteed that no two segments intersect. In other words, for any two integers i, j (1 ≤ i < j ≤ n) the following inequality holds, min(ri, rj) < max(li, lj). | 1,100 | In a single line print a single integer — the answer to the problem. | standard output | |
PASSED | 5aefbfdb905eeb9b01542042495ac319 | train_001.jsonl | 1364916600 | Little penguin Polo adores integer segments, that is, pairs of integers [l; r] (l ≤ r). He has a set that consists of n integer segments: [l1; r1], [l2; r2], ..., [ln; rn]. We know that no two segments of this set intersect. In one move Polo can either widen any segment of the set 1 unit to the left or 1 unit to the right, that is transform [l; r] to either segment [l - 1; r], or to segment [l; r + 1].The value of a set of segments that consists of n segments [l1; r1], [l2; r2], ..., [ln; rn] is the number of integers x, such that there is integer j, for which the following inequality holds, lj ≤ x ≤ rj.Find the minimum number of moves needed to make the value of the set of Polo's segments divisible by k. | 256 megabytes |
//package polo.the.penguin.and.segments;
import java.util.Scanner;
public class PoloThePenguinAndSegments {
private static int count=0, numberBetween,j = 0;
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int n=in.nextInt();
int k=in.nextInt();
for (int i = 0; i < n; i++) {
int x=in.nextInt();
int y=in.nextInt();
PoloThePenguinAndSegments p=new PoloThePenguinAndSegments();
numberBetween = p.numberBetween(x,y);
}
if(numberBetween%k==0)
{
System.out.println(j); }
else
{
for (; numberBetween%k!=0; j++) {
numberBetween++;
}
System.out.println(j);
}
}
private int numberBetween (int x, int y){
while( x<=y) {
count++;
x++;
}
return count;}
}
| Java | ["2 3\n1 2\n3 4", "3 7\n1 2\n3 3\n4 7"] | 2 seconds | ["2", "0"] | null | Java 8 | standard input | [
"implementation",
"brute force"
] | 3a93a6f78b41cbb43c616f20beee288d | The first line contains two integers n and k (1 ≤ n, k ≤ 105). Each of the following n lines contain a segment as a pair of integers li and ri ( - 105 ≤ li ≤ ri ≤ 105), separated by a space. It is guaranteed that no two segments intersect. In other words, for any two integers i, j (1 ≤ i < j ≤ n) the following inequality holds, min(ri, rj) < max(li, lj). | 1,100 | In a single line print a single integer — the answer to the problem. | standard output | |
PASSED | 98fddab8a8dbab658a8c32c79b771c0f | train_001.jsonl | 1364916600 | Little penguin Polo adores integer segments, that is, pairs of integers [l; r] (l ≤ r). He has a set that consists of n integer segments: [l1; r1], [l2; r2], ..., [ln; rn]. We know that no two segments of this set intersect. In one move Polo can either widen any segment of the set 1 unit to the left or 1 unit to the right, that is transform [l; r] to either segment [l - 1; r], or to segment [l; r + 1].The value of a set of segments that consists of n segments [l1; r1], [l2; r2], ..., [ln; rn] is the number of integers x, such that there is integer j, for which the following inequality holds, lj ≤ x ≤ rj.Find the minimum number of moves needed to make the value of the set of Polo's segments divisible by k. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStreamReader;
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);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int k = in.nextInt();
long sum = 0;
for (int i = 0; i < n; i++) sum += 1 - in.nextInt() + in.nextInt();
if (sum % k == 0) out.println(0);
else out.println(k - sum % k);
}
}
static class InputReader {
private StringTokenizer tokenizer;
private BufferedReader reader;
public InputReader(InputStream inputStream) {
reader = new BufferedReader(new InputStreamReader(inputStream));
}
private void fillTokenizer() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public String next() {
fillTokenizer();
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["2 3\n1 2\n3 4", "3 7\n1 2\n3 3\n4 7"] | 2 seconds | ["2", "0"] | null | Java 8 | standard input | [
"implementation",
"brute force"
] | 3a93a6f78b41cbb43c616f20beee288d | The first line contains two integers n and k (1 ≤ n, k ≤ 105). Each of the following n lines contain a segment as a pair of integers li and ri ( - 105 ≤ li ≤ ri ≤ 105), separated by a space. It is guaranteed that no two segments intersect. In other words, for any two integers i, j (1 ≤ i < j ≤ n) the following inequality holds, min(ri, rj) < max(li, lj). | 1,100 | In a single line print a single integer — the answer to the problem. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.