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
f9991ac4979222ed3714dd118754a9db
train_001.jsonl
1532938500
Pavel made a photo of his favourite stars in the sky. His camera takes a photo of all points of the sky that belong to some rectangle with sides parallel to the coordinate axes.Strictly speaking, it makes a photo of all points with coordinates $$$(x, y)$$$, such that $$$x_1 \leq x \leq x_2$$$ and $$$y_1 \leq y \leq y_2$$$, where $$$(x_1, y_1)$$$ and $$$(x_2, y_2)$$$ are coordinates of the left bottom and the right top corners of the rectangle being photographed. The area of this rectangle can be zero.After taking the photo, Pavel wrote down coordinates of $$$n$$$ of his favourite stars which appeared in the photo. These points are not necessarily distinct, there can be multiple stars in the same point of the sky.Pavel has lost his camera recently and wants to buy a similar one. Specifically, he wants to know the dimensions of the photo he took earlier. Unfortunately, the photo is also lost. His notes are also of not much help; numbers are written in random order all over his notepad, so it's impossible to tell which numbers specify coordinates of which points.Pavel asked you to help him to determine what are the possible dimensions of the photo according to his notes. As there are multiple possible answers, find the dimensions with the minimal possible area of the rectangle.
256 megabytes
//Code by Sounak, IIEST import java.io.*; import java.math.*; import java.util.*; import java.util.Arrays; public class Test1{ public static void main(String args[])throws IOException{ Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int a[]=new int[2*n]; int i,j; for(i=0;i<2*n;i++) a[i]=sc.nextInt(); Arrays.sort(a); long br=(long)a[n-1]-(long)a[0]; long ln=(long)a[2*n-1]-(long)a[n]; long res=br*ln; for(i=1;i<n;i++) { long p=(long)(a[2*n-1]-a[0])*(long)(a[n+i-1]-a[i]); res=Math.min(res,p); } System.out.println(res); } }
Java
["4\n4 1 3 2 3 2 1 3", "3\n5 8 5 5 7 5"]
1 second
["1", "0"]
NoteIn the first sample stars in Pavel's records can be $$$(1, 3)$$$, $$$(1, 3)$$$, $$$(2, 3)$$$, $$$(2, 4)$$$. In this case, the minimal area of the rectangle, which contains all these points is $$$1$$$ (rectangle with corners at $$$(1, 3)$$$ and $$$(2, 4)$$$).
Java 8
standard input
[ "implementation", "sortings", "brute force", "math" ]
cda1179c51fc69d2c64ee4707b97cbb3
The first line of the input contains an only integer $$$n$$$ ($$$1 \leq n \leq 100\,000$$$), the number of points in Pavel's records. The second line contains $$$2 \cdot n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{2 \cdot n}$$$ ($$$1 \leq a_i \leq 10^9$$$), coordinates, written by Pavel in some order.
1,500
Print the only integer, the minimal area of the rectangle which could have contained all points from Pavel's records.
standard output
PASSED
f03aa75ddc10e06bbbc65d2df0b76958
train_001.jsonl
1532938500
Pavel made a photo of his favourite stars in the sky. His camera takes a photo of all points of the sky that belong to some rectangle with sides parallel to the coordinate axes.Strictly speaking, it makes a photo of all points with coordinates $$$(x, y)$$$, such that $$$x_1 \leq x \leq x_2$$$ and $$$y_1 \leq y \leq y_2$$$, where $$$(x_1, y_1)$$$ and $$$(x_2, y_2)$$$ are coordinates of the left bottom and the right top corners of the rectangle being photographed. The area of this rectangle can be zero.After taking the photo, Pavel wrote down coordinates of $$$n$$$ of his favourite stars which appeared in the photo. These points are not necessarily distinct, there can be multiple stars in the same point of the sky.Pavel has lost his camera recently and wants to buy a similar one. Specifically, he wants to know the dimensions of the photo he took earlier. Unfortunately, the photo is also lost. His notes are also of not much help; numbers are written in random order all over his notepad, so it's impossible to tell which numbers specify coordinates of which points.Pavel asked you to help him to determine what are the possible dimensions of the photo according to his notes. As there are multiple possible answers, find the dimensions with the minimal possible area of the rectangle.
256 megabytes
import java.io.*; import java.util.Arrays; import java.util.StringTokenizer; public class Main { public static void main(String[] args) { FastReader fr = new FastReader(); OutputStream outputStream = System.out; PrintWriter out = new PrintWriter(outputStream); int n = fr.nextInt()*2; long[] a = new long[n]; for (int i = 0; i < n; i ++){ a[i] = fr.nextLong(); } Arrays.sort(a); long min = 2000000000; for (int i = 1; i < n / 2; i ++){ min = Math.min (min , Math.abs(a[i] - a[i + n / 2 - 1])); } out.print(Math.min(Math.abs(min*(a[0] - a[n-1])) , Math.abs((a[0] - a[n/2 - 1])*(a[n/2]-a[n-1])))); out.close(); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["4\n4 1 3 2 3 2 1 3", "3\n5 8 5 5 7 5"]
1 second
["1", "0"]
NoteIn the first sample stars in Pavel's records can be $$$(1, 3)$$$, $$$(1, 3)$$$, $$$(2, 3)$$$, $$$(2, 4)$$$. In this case, the minimal area of the rectangle, which contains all these points is $$$1$$$ (rectangle with corners at $$$(1, 3)$$$ and $$$(2, 4)$$$).
Java 8
standard input
[ "implementation", "sortings", "brute force", "math" ]
cda1179c51fc69d2c64ee4707b97cbb3
The first line of the input contains an only integer $$$n$$$ ($$$1 \leq n \leq 100\,000$$$), the number of points in Pavel's records. The second line contains $$$2 \cdot n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{2 \cdot n}$$$ ($$$1 \leq a_i \leq 10^9$$$), coordinates, written by Pavel in some order.
1,500
Print the only integer, the minimal area of the rectangle which could have contained all points from Pavel's records.
standard output
PASSED
b57443ba03055f2acc2e3d06565f8973
train_001.jsonl
1532938500
Pavel made a photo of his favourite stars in the sky. His camera takes a photo of all points of the sky that belong to some rectangle with sides parallel to the coordinate axes.Strictly speaking, it makes a photo of all points with coordinates $$$(x, y)$$$, such that $$$x_1 \leq x \leq x_2$$$ and $$$y_1 \leq y \leq y_2$$$, where $$$(x_1, y_1)$$$ and $$$(x_2, y_2)$$$ are coordinates of the left bottom and the right top corners of the rectangle being photographed. The area of this rectangle can be zero.After taking the photo, Pavel wrote down coordinates of $$$n$$$ of his favourite stars which appeared in the photo. These points are not necessarily distinct, there can be multiple stars in the same point of the sky.Pavel has lost his camera recently and wants to buy a similar one. Specifically, he wants to know the dimensions of the photo he took earlier. Unfortunately, the photo is also lost. His notes are also of not much help; numbers are written in random order all over his notepad, so it's impossible to tell which numbers specify coordinates of which points.Pavel asked you to help him to determine what are the possible dimensions of the photo according to his notes. As there are multiple possible answers, find the dimensions with the minimal possible area of the rectangle.
256 megabytes
import java.util.*; import java.io.*; import java.io.FileWriter; import java.math.BigInteger; // Solution public class Main { public static void main (String[] argv) { new Main(); } boolean test = false; final int[][] dirs8 = {{0,1}, {0,-1}, {-1,0}, {1,0}, {1,1},{1,-1},{-1,1},{-1,-1}}; final int[][] dirs4 = {{0,1}, {0,-1}, {-1,0}, {1,0}}; final int MOD = 998244353;//1000000007; int n_bit = 1; int[] bit; final int WALL = -1; final int EMPTY = -2; final int VISITED = 1; final int FULL = 2; public Main() { FastReader in = new FastReader(new BufferedReader(new InputStreamReader(System.in))); // FastReader in = new FastReader(new BufferedReader(new FileReader("Main.in"))); //int nt = in.nextInt(); int nt = 1; StringBuilder sb = new StringBuilder(); //long[] invs = new long[101]; //for (int i = 1; i <= 100; i++) invs[i] = inv(i); for (int it = 0; it < nt; it++) { int n = in.nextInt(); int n2 = n * 2; Integer[] a = new Integer[n2]; for (int i = 0; i < n2; i++) a[i] = in.nextInt(); Arrays.sort(a); long minArea = 1L * (a[n-1] - a[0]) * (a[n2-1] - a[n]); long dx = a[n2-1] - a[0]; for (int i = 1; i + n < n2; i++) { minArea = Math.min(minArea, dx *(a[i+n-1] - a[i])); } sb.append(minArea+"\n"); //sb.append(f(n) + "\n"); //System.out.println(); //String ans = new String(a); //sb.append(ans); } System.out.print(sb); } class DSU { int n; int[] par; int[] sz; int nGroup; public DSU(int n) { this.n = n; par = new int[n]; sz = new int[n]; for (int i = 0; i < n; i++){ par[i] = i; sz[i] = 1; } nGroup = n; } private boolean add(int p, int q) { int rp = find(p); int rq = find(q); if (rq == rp) return false; if (sz[rp] <= sz[rq]) { sz[rq] += sz[rp]; par[rp] = rq; }else { sz[rp] += sz[rq]; par[rq] = rp; } nGroup--; return true; } private int find(int p) { int r = p; while (par[r] != r) r = par[r]; while (r != p) { int t = par[p]; par[p] = r; p = t; } return r; } } private int[] build_z_function(String s) { int n = s.length(); int[] zfun = new int[n]; int l = -1, r = -1; for (int i = 1; i < n; i++) { // Set the start value if (i <= r) zfun[i] = Math.min(zfun[i-l], r - i + 1); while (i + zfun[i] < n && s.charAt(i + zfun[i]) == s.charAt(zfun[i])) zfun[i]++; if (i + zfun[i] - 1> r){ l = i; r = i + zfun[i] - 1; } } if (test) { System.out.println("Z-function of " + s); for (int i = 0; i < n; i++) System.out.print(zfun[i] + " "); System.out.println(); } return zfun; } private int query(int p) { int sum = 0; for (; p > 0; p -= (p & (-p))) { sum += bit[p]; } return sum; } private void add(int p, int val) { //System.out.println("add to BIT " + p); for (; p <= n_bit; p += (p & (-p))) { bit[p] += val; } } private List<Integer> getMinFactor(int sum) { List<Integer> factors = new ArrayList<>(); for (int sz = 2; sz <= sum / sz; sz++){ if (sum % sz == 0) { factors.add(sz); factors.add(sum / sz); } } if (factors.size() == 0) factors.add(sum); return factors; } /* Tree class */ class Tree { int V = 0; int root = 0; List<Integer>[] nbs; int[][] timeRange; int[] subTreeSize; int t; boolean dump = false; public Tree(int V, int root) { if (dump) System.out.println("build tree with size = " + V + ", root = " + root); this.V = V; this.root = root; nbs = new List[V]; subTreeSize = new int[V]; for (int i = 0; i < V; i++) nbs[i] = new ArrayList<>(); } public void doneInput() { dfsEuler(); } public void addEdge(int p, int q) { nbs[p].add(q); nbs[q].add(p); } private void dfsEuler() { timeRange = new int[V][2]; t = 1; dfs(root); } private void dfs(int node) { if (dump) System.out.println("dfs on node " + node + ", at time " + t); timeRange[node][0] = t; for (int next : nbs[node]) { if (timeRange[next][0] == 0) { ++t; dfs(next); } } timeRange[node][1] = t; subTreeSize[node] = t - timeRange[node][0] + 1; } public List<Integer> getNeighbors(int p) { return nbs[p]; } public int[] getSubTreeSize(){ return subTreeSize; } public int[][] getTimeRange() { if (dump){ for (int i = 0; i < V; i++){ System.out.println(i + ": " + timeRange[i][0] + " - " + timeRange[i][1]); } } return timeRange; } } /* segment tree */ class SegTree { int[] a; int[] tree; int[] treeMin; int[] treeMax; int[] lazy; int n; boolean dump = false; public SegTree(int n) { if (dump) System.out.println("create segTree with size " + n); this.n = n; treeMin = new int[n*4]; treeMax = new int[n*4]; lazy = new int[n*4]; } public SegTree(int n, int[] a) { this(n); this.a = a; buildTree(1, 0, n-1); } private void buildTree(int node, int lo, int hi) { if (lo == hi) { tree[node] = lo; return; } int m = (lo + hi) / 2; buildTree(node * 2, lo, m); buildTree(node * 2 + 1, m + 1, hi); pushUp(node, lo, hi); } private void pushUp(int node, int lo, int hi) { if (lo >= hi) return; // note that, if we need to call pushUp on a node, then lazy[node] must be zero. //the true value is the value + lazy treeMin[node] = Math.min(treeMin[node * 2] + lazy[node * 2], treeMin[node * 2 + 1] + lazy[node * 2 + 1]); treeMax[node] = Math.max(treeMax[node * 2] + lazy[node * 2], treeMax[node * 2 + 1] + lazy[node * 2 + 1]); // add combine fcn } private void pushDown(int node, int lo, int hi) { if (lazy[node] == 0) return; int lz = lazy[node]; lazy[node] = 0; treeMin[node] += lz; treeMax[node] += lz; if (lo == hi) return; int mid = (lo + hi) / 2; lazy[node * 2] += lz; lazy[node * 2 + 1] += lz; } public int rangeQueryMax(int fr, int to) { return rangeQueryMax(1, 0, n-1, fr, to); } public int rangeQueryMax(int node, int lo, int hi, int fr, int to) { if (lo == fr && hi == to) return treeMax[node] + lazy[node]; int mid = (lo + hi) / 2; pushDown(node, lo, hi); if (to <= mid) { return rangeQueryMax(node * 2, lo, mid, fr, to); }else if (fr > mid) return rangeQueryMax(node * 2 + 1, mid + 1, hi, fr, to); else { return Math.max(rangeQueryMax(node * 2, lo, mid, fr, mid), rangeQueryMax(node * 2 + 1, mid + 1, hi, mid + 1, to)); } } public int rangeQueryMin(int fr, int to) { return rangeQueryMin(1, 0, n-1, fr, to); } public int rangeQueryMin(int node, int lo, int hi, int fr, int to) { if (lo == fr && hi == to) return treeMin[node] + lazy[node]; int mid = (lo + hi) / 2; pushDown(node, lo, hi); if (to <= mid) { return rangeQueryMin(node * 2, lo, mid, fr, to); }else if (fr > mid) return rangeQueryMin(node * 2 + 1, mid + 1, hi, fr, to); else { return Math.min(rangeQueryMin(node * 2, lo, mid, fr, mid), rangeQueryMin(node * 2 + 1, mid + 1, hi, mid + 1, to)); } } public void rangeUpdate(int fr, int to, int delta){ rangeUpdate(1, 0, n-1, fr, to, delta); } public void rangeUpdate(int node, int lo, int hi, int fr, int to, int delta){ pushDown(node, lo, hi); if (fr == lo && to == hi) { lazy[node] = delta; return; } int m = (lo + hi) / 2; if (to <= m) rangeUpdate(node * 2, lo, m, fr, to, delta); else if (fr > m) rangeUpdate(node * 2 + 1, m + 1, hi, fr, to, delta); else { rangeUpdate(node * 2, lo, m, fr, m, delta); rangeUpdate(node * 2 + 1, m + 1, hi, m + 1, to, delta); } // re-set the in-variant pushUp(node, lo, hi); } public int query(int node, int lo, int hi, int fr, int to) { if (fr == lo && to == hi) return tree[node]; int m = (lo + hi) / 2; if (to <= m) return query(node * 2, lo, m, fr, to); else if (fr > m) return query(node * 2 + 1, m + 1, hi, fr, to); int lid = query(node * 2, lo, m, fr, m); int rid = query(node * 2 + 1, m + 1, hi, m + 1, to); return a[lid] >= a[rid] ? lid : rid; } } private long inv(long v) { return pow(v, MOD-2); } private long pow(long v, int p) { long ans = 1; while (p > 0) { if (p % 2 == 1) ans = ans * v % MOD; v = v * v % MOD; p = p / 2; } return ans; } private double dist(double x, double y, double xx, double yy) { return Math.sqrt((xx - x) * (xx - x) + (yy - y) * (yy - y)); } private int mod_add(int a, int b) { int v = a + b; if (v >= MOD) v -= MOD; return v; } private long overlap(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) { if (x1 > x3) return overlap(x3, y3, x4, y4, x1, y1, x2, y2); if (x3 > x2 || y4 < y1 || y3 > y2) return 0L; //(x3, ?, x2, ?) int yL = Math.max(y1, y3); int yH = Math.min(y2, y4); int xH = Math.min(x2, x4); return f(x3, yL, xH, yH); } //return #black cells in rectangle private long f(int x1, int y1, int x2, int y2) { long dx = 1L + x2 - x1; long dy = 1L + y2 - y1; if (dx % 2 == 0 || dy % 2 == 0 || (x1 + y1) % 2 == 0) return 1L * dx * dy / 2; return 1L * dx * dy / 2 + 1; } private int distM(int x, int y, int xx, int yy) { return abs(x - xx) + abs(y - yy); } private boolean less(int x, int y, int xx, int yy) { return x < xx || y > yy; } private int mul(int x, int y) { return (int)(1L * x * y % MOD); } private int nBit1(int v) { int v0 = v; int c = 0; while (v != 0) { ++c; v = v & (v - 1); } return c; } private long abs(long v) { return v > 0 ? v : -v; } private int abs(int v) { return v > 0 ? v : -v; } private int common(int v) { int c = 0; while (v != 1) { v = (v >>> 1); ++c; } return c; } private void reverse(char[] a, int i, int j) { while (i < j) { swap(a, i++, j--); } } private void swap(char[] a, int i, int j) { char t = a[i]; a[i] = a[j]; a[j] = t; } private int gcd(int x, int y) { if (y == 0) return x; return gcd(y, x % y); } private long gcd(long x, long y) { if (y == 0) return x; return gcd(y, x % y); } private int max(int a, int b) { return a > b ? a : b; } private long max(long a, long b) { return a > b ? a : b; } private int min(int a, int b) { return a > b ? b : a; } private long min(long a, long b) { return a > b ? b : a; } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader(BufferedReader in) { br = in; } String next() { while (st == null || !st.hasMoreElements()) { try { String line = br.readLine(); if (line == null || line.length() == 0) return ""; st = new StringTokenizer(line); } catch (IOException e) { return ""; //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) { return null; //e.printStackTrace(); } return str; } } }
Java
["4\n4 1 3 2 3 2 1 3", "3\n5 8 5 5 7 5"]
1 second
["1", "0"]
NoteIn the first sample stars in Pavel's records can be $$$(1, 3)$$$, $$$(1, 3)$$$, $$$(2, 3)$$$, $$$(2, 4)$$$. In this case, the minimal area of the rectangle, which contains all these points is $$$1$$$ (rectangle with corners at $$$(1, 3)$$$ and $$$(2, 4)$$$).
Java 8
standard input
[ "implementation", "sortings", "brute force", "math" ]
cda1179c51fc69d2c64ee4707b97cbb3
The first line of the input contains an only integer $$$n$$$ ($$$1 \leq n \leq 100\,000$$$), the number of points in Pavel's records. The second line contains $$$2 \cdot n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{2 \cdot n}$$$ ($$$1 \leq a_i \leq 10^9$$$), coordinates, written by Pavel in some order.
1,500
Print the only integer, the minimal area of the rectangle which could have contained all points from Pavel's records.
standard output
PASSED
53c9bc201566c018d9bf0679622229cd
train_001.jsonl
1532938500
Pavel made a photo of his favourite stars in the sky. His camera takes a photo of all points of the sky that belong to some rectangle with sides parallel to the coordinate axes.Strictly speaking, it makes a photo of all points with coordinates $$$(x, y)$$$, such that $$$x_1 \leq x \leq x_2$$$ and $$$y_1 \leq y \leq y_2$$$, where $$$(x_1, y_1)$$$ and $$$(x_2, y_2)$$$ are coordinates of the left bottom and the right top corners of the rectangle being photographed. The area of this rectangle can be zero.After taking the photo, Pavel wrote down coordinates of $$$n$$$ of his favourite stars which appeared in the photo. These points are not necessarily distinct, there can be multiple stars in the same point of the sky.Pavel has lost his camera recently and wants to buy a similar one. Specifically, he wants to know the dimensions of the photo he took earlier. Unfortunately, the photo is also lost. His notes are also of not much help; numbers are written in random order all over his notepad, so it's impossible to tell which numbers specify coordinates of which points.Pavel asked you to help him to determine what are the possible dimensions of the photo according to his notes. As there are multiple possible answers, find the dimensions with the minimal possible area of the rectangle.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; import java.io.IOException; import java.util.Random; import java.io.UncheckedIOException; import java.io.Closeable; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27); thread.start(); thread.join(); } static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastInput in = new FastInput(inputStream); FastOutput out = new FastOutput(outputStream); APhotoOfTheSky solver = new APhotoOfTheSky(); solver.solve(1, in, out); out.close(); } } static class APhotoOfTheSky { public void solve(int testNumber, FastInput in, FastOutput out) { int n = in.readInt(); long[] nums = new long[n * 2]; for (int i = 0; i < n * 2; i++) { nums[i] = in.readInt(); } Randomized.shuffle(nums); Arrays.sort(nums); long ans = (nums[n - 1] - nums[0]) * (nums[2 * n - 1] - nums[n]); for (int i = 0; i + n <= 2 * n; i++) { ans = Math.min(ans, (nums[2 * n - 1] - nums[0]) * (nums[i + n - 1] - nums[i])); } out.println(ans); } } static class FastOutput implements AutoCloseable, Closeable, Appendable { private StringBuilder cache = new StringBuilder(10 << 20); private final Writer os; public FastOutput append(CharSequence csq) { cache.append(csq); return this; } public FastOutput append(CharSequence csq, int start, int end) { cache.append(csq, start, end); return this; } public FastOutput(Writer os) { this.os = os; } public FastOutput(OutputStream os) { this(new OutputStreamWriter(os)); } public FastOutput append(char c) { cache.append(c); return this; } public FastOutput println(long c) { cache.append(c); println(); return this; } public FastOutput println() { cache.append(System.lineSeparator()); return this; } public FastOutput flush() { try { os.append(cache); os.flush(); cache.setLength(0); } catch (IOException e) { throw new UncheckedIOException(e); } return this; } public void close() { flush(); try { os.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } public String toString() { return cache.toString(); } } static class Randomized { private static Random random = new Random(0); public static void shuffle(long[] data) { shuffle(data, 0, data.length - 1); } public static void shuffle(long[] data, int from, int to) { to--; for (int i = from; i <= to; i++) { int s = nextInt(i, to); long tmp = data[i]; data[i] = data[s]; data[s] = tmp; } } public static int nextInt(int l, int r) { return random.nextInt(r - l + 1) + l; } } static class FastInput { private final InputStream is; private byte[] buf = new byte[1 << 20]; private int bufLen; private int bufOffset; private int next; public FastInput(InputStream is) { this.is = is; } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { bufLen = -1; } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public int readInt() { int sign = 1; skipBlank(); if (next == '+' || next == '-') { sign = next == '+' ? 1 : -1; next = read(); } int val = 0; if (sign == 1) { while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } } else { while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } } return val; } } }
Java
["4\n4 1 3 2 3 2 1 3", "3\n5 8 5 5 7 5"]
1 second
["1", "0"]
NoteIn the first sample stars in Pavel's records can be $$$(1, 3)$$$, $$$(1, 3)$$$, $$$(2, 3)$$$, $$$(2, 4)$$$. In this case, the minimal area of the rectangle, which contains all these points is $$$1$$$ (rectangle with corners at $$$(1, 3)$$$ and $$$(2, 4)$$$).
Java 8
standard input
[ "implementation", "sortings", "brute force", "math" ]
cda1179c51fc69d2c64ee4707b97cbb3
The first line of the input contains an only integer $$$n$$$ ($$$1 \leq n \leq 100\,000$$$), the number of points in Pavel's records. The second line contains $$$2 \cdot n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{2 \cdot n}$$$ ($$$1 \leq a_i \leq 10^9$$$), coordinates, written by Pavel in some order.
1,500
Print the only integer, the minimal area of the rectangle which could have contained all points from Pavel's records.
standard output
PASSED
d489f6fe13c969cd744780be012ba3a1
train_001.jsonl
1532938500
Pavel made a photo of his favourite stars in the sky. His camera takes a photo of all points of the sky that belong to some rectangle with sides parallel to the coordinate axes.Strictly speaking, it makes a photo of all points with coordinates $$$(x, y)$$$, such that $$$x_1 \leq x \leq x_2$$$ and $$$y_1 \leq y \leq y_2$$$, where $$$(x_1, y_1)$$$ and $$$(x_2, y_2)$$$ are coordinates of the left bottom and the right top corners of the rectangle being photographed. The area of this rectangle can be zero.After taking the photo, Pavel wrote down coordinates of $$$n$$$ of his favourite stars which appeared in the photo. These points are not necessarily distinct, there can be multiple stars in the same point of the sky.Pavel has lost his camera recently and wants to buy a similar one. Specifically, he wants to know the dimensions of the photo he took earlier. Unfortunately, the photo is also lost. His notes are also of not much help; numbers are written in random order all over his notepad, so it's impossible to tell which numbers specify coordinates of which points.Pavel asked you to help him to determine what are the possible dimensions of the photo according to his notes. As there are multiple possible answers, find the dimensions with the minimal possible area of the rectangle.
256 megabytes
import java.lang.reflect.Array; import java.util.Arrays; import java.util.Scanner; public class SkyPhoto { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] arr = new int[n*2]; for (int k = 0; k < 2*n; k++){ arr[k] = sc.nextInt(); } Arrays.sort(arr); int xmin = arr[0]; int xmax = arr[arr.length/2-1]; int ymin = arr[arr.length/2]; int ymax = arr[arr.length-1]; long print = (long)(xmax-xmin)*(long)(ymax-ymin); int width = arr[arr.length-1]-arr[0]; for (int k = 1; k <= arr.length/2; k++){ ymin = arr[k]; ymax = arr[k+arr.length/2-1]; print = Math.min((long)(ymax-ymin)*width,print); } System.out.print(print); } }
Java
["4\n4 1 3 2 3 2 1 3", "3\n5 8 5 5 7 5"]
1 second
["1", "0"]
NoteIn the first sample stars in Pavel's records can be $$$(1, 3)$$$, $$$(1, 3)$$$, $$$(2, 3)$$$, $$$(2, 4)$$$. In this case, the minimal area of the rectangle, which contains all these points is $$$1$$$ (rectangle with corners at $$$(1, 3)$$$ and $$$(2, 4)$$$).
Java 8
standard input
[ "implementation", "sortings", "brute force", "math" ]
cda1179c51fc69d2c64ee4707b97cbb3
The first line of the input contains an only integer $$$n$$$ ($$$1 \leq n \leq 100\,000$$$), the number of points in Pavel's records. The second line contains $$$2 \cdot n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{2 \cdot n}$$$ ($$$1 \leq a_i \leq 10^9$$$), coordinates, written by Pavel in some order.
1,500
Print the only integer, the minimal area of the rectangle which could have contained all points from Pavel's records.
standard output
PASSED
9ff29c53fa50f50f639d949ea3d2552e
train_001.jsonl
1532938500
Pavel made a photo of his favourite stars in the sky. His camera takes a photo of all points of the sky that belong to some rectangle with sides parallel to the coordinate axes.Strictly speaking, it makes a photo of all points with coordinates $$$(x, y)$$$, such that $$$x_1 \leq x \leq x_2$$$ and $$$y_1 \leq y \leq y_2$$$, where $$$(x_1, y_1)$$$ and $$$(x_2, y_2)$$$ are coordinates of the left bottom and the right top corners of the rectangle being photographed. The area of this rectangle can be zero.After taking the photo, Pavel wrote down coordinates of $$$n$$$ of his favourite stars which appeared in the photo. These points are not necessarily distinct, there can be multiple stars in the same point of the sky.Pavel has lost his camera recently and wants to buy a similar one. Specifically, he wants to know the dimensions of the photo he took earlier. Unfortunately, the photo is also lost. His notes are also of not much help; numbers are written in random order all over his notepad, so it's impossible to tell which numbers specify coordinates of which points.Pavel asked you to help him to determine what are the possible dimensions of the photo according to his notes. As there are multiple possible answers, find the dimensions with the minimal possible area of the rectangle.
256 megabytes
import java.util.*; import java.io.*; public class A { static final boolean stdin = true; static final String filename = ""; static FastScanner br; static PrintWriter pw; public static void main(String[] args) throws IOException { if (stdin) { br = new FastScanner(); pw = new PrintWriter(new OutputStreamWriter(System.out)); } else { br = new FastScanner(filename + ".in"); pw = new PrintWriter(new FileWriter(filename + ".out")); } Solver solver = new Solver(); solver.solve(br, pw); pw.close(); } static class Solver { static long mod = (long) (1e9); public void solve(FastScanner br, PrintWriter pw) throws IOException { int n = br.ni(); Long[] in = br.nLa(n * 2); Arrays.sort(in); long x1 = in[0], y1 = in[n], x2 = in[n - 1], y2 = in[n * 2 - 1]; long ans = (x2 - x1) * (y2 - y1); for (int i = 1; i < n; i++) { ans = Math.min(ans, (in[n * 2 - 1] - in[0]) * (in[i + n - 1] - in[i])); } pw.println(ans); } static long gcd(long a, long b) { if (a > b) return gcd(b, a); if (a == 0) return b; return gcd(b % a, a); } static long lcm(long a, long b) { return a * (b / gcd(a, b)); } static long pow(long a, long b) { if (b == 0) return 1L; long val = pow(a, b / 2); if (b % 2 == 0) return val * val % mod; else return val * val % mod * a % mod; } } static class Point implements Comparable<Point> { int a; int b; Point(int a, int b) { this.a = a; this.b = b; } @Override public int compareTo(Point o) { return this.a - o.a; } public boolean equals(Object obj) { if (obj instanceof Point) { Point other = (Point) obj; return a == other.a && b == other.b; } return false; } public int hashCode() { return 65536 * a + b + 4733 * 0; } } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } ArrayList<Integer>[] ng(int n, int e) { ArrayList<Integer>[] adj = new ArrayList[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<Integer>(); } for (int i = 0; i < e; i++) { int a = ni() - 1; int b = ni() - 1; adj[a].add(b); adj[b].add(a); } return adj; } Integer[] nIa(int n) { Integer[] arr = new Integer[n]; for (int i = 0; i < n; i++) { arr[i] = ni(); } return arr; } int[] nia(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = ni(); } return arr; } Long[] nLa(int n) { Long[] arr = new Long[n]; for (int i = 0; i < n; i++) { arr[i] = nl(); } return arr; } long[] nla(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nl(); } return arr; } String[] nsa(int n) { String[] arr = new String[n]; for (int i = 0; i < n; i++) { arr[i] = nt(); } return arr; } String nt() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int ni() { return Integer.parseInt(nt()); } long nl() { return Long.parseLong(nt()); } double nd() { return Double.parseDouble(nt()); } } }
Java
["4\n4 1 3 2 3 2 1 3", "3\n5 8 5 5 7 5"]
1 second
["1", "0"]
NoteIn the first sample stars in Pavel's records can be $$$(1, 3)$$$, $$$(1, 3)$$$, $$$(2, 3)$$$, $$$(2, 4)$$$. In this case, the minimal area of the rectangle, which contains all these points is $$$1$$$ (rectangle with corners at $$$(1, 3)$$$ and $$$(2, 4)$$$).
Java 8
standard input
[ "implementation", "sortings", "brute force", "math" ]
cda1179c51fc69d2c64ee4707b97cbb3
The first line of the input contains an only integer $$$n$$$ ($$$1 \leq n \leq 100\,000$$$), the number of points in Pavel's records. The second line contains $$$2 \cdot n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{2 \cdot n}$$$ ($$$1 \leq a_i \leq 10^9$$$), coordinates, written by Pavel in some order.
1,500
Print the only integer, the minimal area of the rectangle which could have contained all points from Pavel's records.
standard output
PASSED
aecdfc1c502e3a4b876c9bc34a4c067e
train_001.jsonl
1532938500
Pavel made a photo of his favourite stars in the sky. His camera takes a photo of all points of the sky that belong to some rectangle with sides parallel to the coordinate axes.Strictly speaking, it makes a photo of all points with coordinates $$$(x, y)$$$, such that $$$x_1 \leq x \leq x_2$$$ and $$$y_1 \leq y \leq y_2$$$, where $$$(x_1, y_1)$$$ and $$$(x_2, y_2)$$$ are coordinates of the left bottom and the right top corners of the rectangle being photographed. The area of this rectangle can be zero.After taking the photo, Pavel wrote down coordinates of $$$n$$$ of his favourite stars which appeared in the photo. These points are not necessarily distinct, there can be multiple stars in the same point of the sky.Pavel has lost his camera recently and wants to buy a similar one. Specifically, he wants to know the dimensions of the photo he took earlier. Unfortunately, the photo is also lost. His notes are also of not much help; numbers are written in random order all over his notepad, so it's impossible to tell which numbers specify coordinates of which points.Pavel asked you to help him to determine what are the possible dimensions of the photo according to his notes. As there are multiple possible answers, find the dimensions with the minimal possible area of the rectangle.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; import java.io.IOException; import java.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; MyScan in = new MyScan(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, MyScan in, PrintWriter out) { int n = in.nextInt(); int[] data = in.na(n * 2); Util.sort(data); long best = (data[n - 1] - data[0]) * 1L * (data[n + n - 1] - data[n]); for (int i = 1; i < n; i++) { best = Math.min(best, (data[i + n - 1] - data[i]) * 1L * (data[n + n - 1] - data[0])); } out.println(best); } } static class Util { public static void sort(int[] data) { Integer[] v = new Integer[data.length]; for (int s = 0; s < data.length; s++) { v[s] = data[s]; } Arrays.sort(v); for (int s = 0; s < data.length; s++) { data[s] = v[s]; } } } static class MyScan { private final InputStream in; private byte[] inbuf = new byte[1024]; public int lenbuf = 0; public int ptrbuf = 0; public MyScan(InputStream in) { this.in = in; } private int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = in.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } public int[] na(int n) { int[] k = new int[n]; for (int i = 0; i < n; i++) { k[i] = nextInt(); } return k; } public int nextInt() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } } }
Java
["4\n4 1 3 2 3 2 1 3", "3\n5 8 5 5 7 5"]
1 second
["1", "0"]
NoteIn the first sample stars in Pavel's records can be $$$(1, 3)$$$, $$$(1, 3)$$$, $$$(2, 3)$$$, $$$(2, 4)$$$. In this case, the minimal area of the rectangle, which contains all these points is $$$1$$$ (rectangle with corners at $$$(1, 3)$$$ and $$$(2, 4)$$$).
Java 8
standard input
[ "implementation", "sortings", "brute force", "math" ]
cda1179c51fc69d2c64ee4707b97cbb3
The first line of the input contains an only integer $$$n$$$ ($$$1 \leq n \leq 100\,000$$$), the number of points in Pavel's records. The second line contains $$$2 \cdot n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{2 \cdot n}$$$ ($$$1 \leq a_i \leq 10^9$$$), coordinates, written by Pavel in some order.
1,500
Print the only integer, the minimal area of the rectangle which could have contained all points from Pavel's records.
standard output
PASSED
0ff1a8564124e583d1fbfe1b589fe974
train_001.jsonl
1532938500
Pavel made a photo of his favourite stars in the sky. His camera takes a photo of all points of the sky that belong to some rectangle with sides parallel to the coordinate axes.Strictly speaking, it makes a photo of all points with coordinates $$$(x, y)$$$, such that $$$x_1 \leq x \leq x_2$$$ and $$$y_1 \leq y \leq y_2$$$, where $$$(x_1, y_1)$$$ and $$$(x_2, y_2)$$$ are coordinates of the left bottom and the right top corners of the rectangle being photographed. The area of this rectangle can be zero.After taking the photo, Pavel wrote down coordinates of $$$n$$$ of his favourite stars which appeared in the photo. These points are not necessarily distinct, there can be multiple stars in the same point of the sky.Pavel has lost his camera recently and wants to buy a similar one. Specifically, he wants to know the dimensions of the photo he took earlier. Unfortunately, the photo is also lost. His notes are also of not much help; numbers are written in random order all over his notepad, so it's impossible to tell which numbers specify coordinates of which points.Pavel asked you to help him to determine what are the possible dimensions of the photo according to his notes. As there are multiple possible answers, find the dimensions with the minimal possible area of the rectangle.
256 megabytes
import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Collections; public class A { public static void main(String[] args) { JS in = new JS(); int n = in.nextInt(); int N = 2*n; ArrayList<Long> list = new ArrayList<Long>(); for(int i = 0; i < 2*n; i++) list.add(in.nextLong()); Collections.sort(list); long best = Long.MAX_VALUE; if(n==1) { System.out.println(0); return; } for(int i = 0; i < N; i++) { int i1 = i; int i2 = (i+N/2-1)%N; int i3 = (i+N/2)%N; int i4 = (i+N/2+N/2-1)%N; long xlo,xhi,ylo,yhi; if(i2 > i1) { xlo = list.get(i); xhi = list.get(i2); } else { xlo = list.get(0); xhi = list.get(N-1); } if(i4 > i3) { ylo = list.get(i3); yhi = list.get(i4); } else { ylo = list.get(0); yhi = list.get(N-1); } long cur = Math.abs(xhi-xlo)*Math.abs(yhi-ylo); best = Math.min(best,cur); } System.out.println(best); } static void sort(int a[]) { sort2(a, 0, a.length-1); } static void sort2(int a[], int lo, int hi) { if(lo==hi) return; if(lo+1 == hi) { if(a[lo] > a[hi]) { int temp = a[lo]; a[lo]=a[hi]; a[hi]=temp; } } else { int mid = (lo+hi)/2; sort2(a,lo,mid); sort2(a,mid+1,hi); int temp[] = new int[hi-lo+1]; int l = lo; int r = mid+1; for(int i = lo; i <= hi; i++) { if(l==mid+1) temp[i-lo] = a[r++]; else if(r==hi+1) temp[i-lo]=a[l++]; else if(a[l] < a[r]) temp[i-lo]=a[l++]; else temp[i-lo]=a[r++]; } for(int i = lo; i <= hi; i++) a[i] = temp[i-lo]; } } static class JS{ public int BS = 1<<16; public char NC = (char)0; byte[] buf = new byte[BS]; int bId = 0, size = 0; char c = NC; double num = 1; BufferedInputStream in; public JS() { in = new BufferedInputStream(System.in, BS); } public JS(String s) throws FileNotFoundException { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } public char nextChar(){ while(bId==size) { try { size = in.read(buf); }catch(Exception e) { return NC; } if(size==-1)return NC; bId=0; } return (char)buf[bId++]; } public int nextInt() { return (int)nextLong(); } public long nextLong() { num=1; boolean neg = false; if(c==NC)c=nextChar(); for(;(c<'0' || c>'9'); c = nextChar()) { if(c=='-')neg=true; } long res = 0; for(; c>='0' && c <='9'; c=nextChar()) { res = (res<<3)+(res<<1)+c-'0'; num*=10; } return neg?-res:res; } public double nextDouble() { while(c!='.'&&c!='-'&&(c <'0' || c>'9')) c = nextChar(); boolean neg = c=='-'; if(neg)c=nextChar(); boolean fl = c=='.'; double cur = nextLong(); if(fl) return neg ? -cur/num : cur/num; if(c == '.') { double next = nextLong(); return neg ? -cur-next/num : cur+next/num; } else return neg ? -cur : cur; } public String next() { StringBuilder res = new StringBuilder(); while(c<=32)c=nextChar(); while(c>32) { res.append(c); c=nextChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while(c<=32)c=nextChar(); while(c!='\n') { res.append(c); c=nextChar(); } return res.toString(); } public boolean hasNext() { if(c>32)return true; while(true) { c=nextChar(); if(c==NC)return false; else if(c>32)return true; } } } }
Java
["4\n4 1 3 2 3 2 1 3", "3\n5 8 5 5 7 5"]
1 second
["1", "0"]
NoteIn the first sample stars in Pavel's records can be $$$(1, 3)$$$, $$$(1, 3)$$$, $$$(2, 3)$$$, $$$(2, 4)$$$. In this case, the minimal area of the rectangle, which contains all these points is $$$1$$$ (rectangle with corners at $$$(1, 3)$$$ and $$$(2, 4)$$$).
Java 8
standard input
[ "implementation", "sortings", "brute force", "math" ]
cda1179c51fc69d2c64ee4707b97cbb3
The first line of the input contains an only integer $$$n$$$ ($$$1 \leq n \leq 100\,000$$$), the number of points in Pavel's records. The second line contains $$$2 \cdot n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{2 \cdot n}$$$ ($$$1 \leq a_i \leq 10^9$$$), coordinates, written by Pavel in some order.
1,500
Print the only integer, the minimal area of the rectangle which could have contained all points from Pavel's records.
standard output
PASSED
3277b6d0324c764a63c8b189d2c8b15b
train_001.jsonl
1532938500
Pavel made a photo of his favourite stars in the sky. His camera takes a photo of all points of the sky that belong to some rectangle with sides parallel to the coordinate axes.Strictly speaking, it makes a photo of all points with coordinates $$$(x, y)$$$, such that $$$x_1 \leq x \leq x_2$$$ and $$$y_1 \leq y \leq y_2$$$, where $$$(x_1, y_1)$$$ and $$$(x_2, y_2)$$$ are coordinates of the left bottom and the right top corners of the rectangle being photographed. The area of this rectangle can be zero.After taking the photo, Pavel wrote down coordinates of $$$n$$$ of his favourite stars which appeared in the photo. These points are not necessarily distinct, there can be multiple stars in the same point of the sky.Pavel has lost his camera recently and wants to buy a similar one. Specifically, he wants to know the dimensions of the photo he took earlier. Unfortunately, the photo is also lost. His notes are also of not much help; numbers are written in random order all over his notepad, so it's impossible to tell which numbers specify coordinates of which points.Pavel asked you to help him to determine what are the possible dimensions of the photo according to his notes. As there are multiple possible answers, find the dimensions with the minimal possible area of the rectangle.
256 megabytes
import java.io.*; import java.util.*; public class A { public static void main(String[] args)throws Throwable { MyScanner sc=new MyScanner(); PrintWriter pw=new PrintWriter(System.out); int n=sc.nextInt(); Integer [] a=new Integer [2*n]; for(int i=0;i<2*n;i++) a[i]=sc.nextInt(); Arrays.sort(a); long x=a[n-1]-a[0],y=a[2*n-1]-a[n]; long ans=x*y; for(int i=1;i+n-1<2*n-1;i++){ ans=Math.min(ans,1L*(a[i+n-1]-a[i])*(a[2*n-1]-a[0])); } pw.println(ans); pw.flush(); pw.close(); } static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() {while (st == null || !st.hasMoreElements()) { try {st = new StringTokenizer(br.readLine());} catch (IOException e) {e.printStackTrace();}} return st.nextToken();} int nextInt() {return Integer.parseInt(next());} long nextLong() {return Long.parseLong(next());} double nextDouble() {return Double.parseDouble(next());} String nextLine(){String str = ""; try {str = br.readLine();} catch (IOException e) {e.printStackTrace();} return str;} } }
Java
["4\n4 1 3 2 3 2 1 3", "3\n5 8 5 5 7 5"]
1 second
["1", "0"]
NoteIn the first sample stars in Pavel's records can be $$$(1, 3)$$$, $$$(1, 3)$$$, $$$(2, 3)$$$, $$$(2, 4)$$$. In this case, the minimal area of the rectangle, which contains all these points is $$$1$$$ (rectangle with corners at $$$(1, 3)$$$ and $$$(2, 4)$$$).
Java 8
standard input
[ "implementation", "sortings", "brute force", "math" ]
cda1179c51fc69d2c64ee4707b97cbb3
The first line of the input contains an only integer $$$n$$$ ($$$1 \leq n \leq 100\,000$$$), the number of points in Pavel's records. The second line contains $$$2 \cdot n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{2 \cdot n}$$$ ($$$1 \leq a_i \leq 10^9$$$), coordinates, written by Pavel in some order.
1,500
Print the only integer, the minimal area of the rectangle which could have contained all points from Pavel's records.
standard output
PASSED
ff9a2aec540f900eea903d8d760c80d0
train_001.jsonl
1532938500
Pavel made a photo of his favourite stars in the sky. His camera takes a photo of all points of the sky that belong to some rectangle with sides parallel to the coordinate axes.Strictly speaking, it makes a photo of all points with coordinates $$$(x, y)$$$, such that $$$x_1 \leq x \leq x_2$$$ and $$$y_1 \leq y \leq y_2$$$, where $$$(x_1, y_1)$$$ and $$$(x_2, y_2)$$$ are coordinates of the left bottom and the right top corners of the rectangle being photographed. The area of this rectangle can be zero.After taking the photo, Pavel wrote down coordinates of $$$n$$$ of his favourite stars which appeared in the photo. These points are not necessarily distinct, there can be multiple stars in the same point of the sky.Pavel has lost his camera recently and wants to buy a similar one. Specifically, he wants to know the dimensions of the photo he took earlier. Unfortunately, the photo is also lost. His notes are also of not much help; numbers are written in random order all over his notepad, so it's impossible to tell which numbers specify coordinates of which points.Pavel asked you to help him to determine what are the possible dimensions of the photo according to his notes. As there are multiple possible answers, find the dimensions with the minimal possible area of the rectangle.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class HelloWorld{ public static void main(String []args)throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n=Integer.parseInt(br.readLine()); long a[]=new long[2*n]; StringTokenizer tk=new StringTokenizer(br.readLine()); for(int i=0;i<2*n;i++) a[i]=Long.parseLong(tk.nextToken()); Arrays.sort(a); long min=Long.MAX_VALUE; long x1=a[0]; long x2=a[n-1]; long y1=a[n]; long y2=a[(2*n)-1]; min=(long)Math.min(min,(x2-x1)*(y2-y1)); for(int i=1;i+n-1<2*n-1;i++) { min=(long)Math.min(min,(a[i+n-1]-a[i])*(a[2*n-1]-a[0])); } System.out.println(min); } }
Java
["4\n4 1 3 2 3 2 1 3", "3\n5 8 5 5 7 5"]
1 second
["1", "0"]
NoteIn the first sample stars in Pavel's records can be $$$(1, 3)$$$, $$$(1, 3)$$$, $$$(2, 3)$$$, $$$(2, 4)$$$. In this case, the minimal area of the rectangle, which contains all these points is $$$1$$$ (rectangle with corners at $$$(1, 3)$$$ and $$$(2, 4)$$$).
Java 8
standard input
[ "implementation", "sortings", "brute force", "math" ]
cda1179c51fc69d2c64ee4707b97cbb3
The first line of the input contains an only integer $$$n$$$ ($$$1 \leq n \leq 100\,000$$$), the number of points in Pavel's records. The second line contains $$$2 \cdot n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{2 \cdot n}$$$ ($$$1 \leq a_i \leq 10^9$$$), coordinates, written by Pavel in some order.
1,500
Print the only integer, the minimal area of the rectangle which could have contained all points from Pavel's records.
standard output
PASSED
8006aec54d0fbbdad4158652ebfbd282
train_001.jsonl
1532938500
Pavel made a photo of his favourite stars in the sky. His camera takes a photo of all points of the sky that belong to some rectangle with sides parallel to the coordinate axes.Strictly speaking, it makes a photo of all points with coordinates $$$(x, y)$$$, such that $$$x_1 \leq x \leq x_2$$$ and $$$y_1 \leq y \leq y_2$$$, where $$$(x_1, y_1)$$$ and $$$(x_2, y_2)$$$ are coordinates of the left bottom and the right top corners of the rectangle being photographed. The area of this rectangle can be zero.After taking the photo, Pavel wrote down coordinates of $$$n$$$ of his favourite stars which appeared in the photo. These points are not necessarily distinct, there can be multiple stars in the same point of the sky.Pavel has lost his camera recently and wants to buy a similar one. Specifically, he wants to know the dimensions of the photo he took earlier. Unfortunately, the photo is also lost. His notes are also of not much help; numbers are written in random order all over his notepad, so it's impossible to tell which numbers specify coordinates of which points.Pavel asked you to help him to determine what are the possible dimensions of the photo according to his notes. As there are multiple possible answers, find the dimensions with the minimal possible area of the rectangle.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class a{ static void solve(){ int n = ni(); long[] a = nla(2*n); Arrays.sort(a); long ans = (a[n-1]-a[0])*(a[2*n-1]-a[n]); for(int i=n+1;i<2*n;++i){ ans = Math.min(ans, (a[2*n-1]-a[0])*(a[i-1]-a[i-n])); } out.println(ans); } public static void main(String[] args){ solve(); out.flush(); } private static InputStream in = System.in; private static PrintWriter out = new PrintWriter(System.out); private static final byte[] buffer = new byte[1<<15]; private static int ptr = 0; private static int buflen = 0; private static boolean hasNextByte(){ if(ptr<buflen)return true; ptr = 0; try{ buflen = in.read(buffer); } catch (IOException e){ e.printStackTrace(); } return buflen>0; } private static int readByte(){ if(hasNextByte()) return buffer[ptr++]; else return -1;} private static boolean isSpaceChar(int c){ return !(33<=c && c<=126);} private static int skip(){int res; while((res=readByte())!=-1 && isSpaceChar(res)); return res;} private static double nd(){ return Double.parseDouble(ns()); } private static char nc(){ return (char)skip(); } private static String ns(){ StringBuilder sb = new StringBuilder(); for(int b=skip();!isSpaceChar(b);b=readByte())sb.append((char)b); return sb.toString(); } private static int[] nia(int n){ int[] res = new int[n]; for(int i=0;i<n;++i)res[i]=ni(); return res; } private static long[] nla(int n){ long[] res = new long[n]; for(int i=0;i<n;++i)res[i]=nl(); return res; } private static int ni(){ int res=0,b; boolean minus=false; while((b=readByte())!=-1 && !((b>='0'&&b<='9') || b=='-')); if(b=='-'){ minus=true; b=readByte(); } for(;'0'<=b&&b<='9';b=readByte())res=res*10+(b-'0'); return minus ? -res:res; } private static long nl(){ long res=0,b; boolean minus=false; while((b=readByte())!=-1 && !((b>='0'&&b<='9') || b=='-')); if(b=='-'){ minus=true; b=readByte(); } for(;'0'<=b&&b<='9';b=readByte())res=res*10+(b-'0'); return minus ? -res:res; } }
Java
["4\n4 1 3 2 3 2 1 3", "3\n5 8 5 5 7 5"]
1 second
["1", "0"]
NoteIn the first sample stars in Pavel's records can be $$$(1, 3)$$$, $$$(1, 3)$$$, $$$(2, 3)$$$, $$$(2, 4)$$$. In this case, the minimal area of the rectangle, which contains all these points is $$$1$$$ (rectangle with corners at $$$(1, 3)$$$ and $$$(2, 4)$$$).
Java 8
standard input
[ "implementation", "sortings", "brute force", "math" ]
cda1179c51fc69d2c64ee4707b97cbb3
The first line of the input contains an only integer $$$n$$$ ($$$1 \leq n \leq 100\,000$$$), the number of points in Pavel's records. The second line contains $$$2 \cdot n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{2 \cdot n}$$$ ($$$1 \leq a_i \leq 10^9$$$), coordinates, written by Pavel in some order.
1,500
Print the only integer, the minimal area of the rectangle which could have contained all points from Pavel's records.
standard output
PASSED
cef610ea1b05d61782ae69087a622384
train_001.jsonl
1495303500
Leha decided to move to a quiet town Vičkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to n computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on the same straight line, due to the reason that there is the only one straight street in Vičkopolis.Let's denote the coordinate system on this street. Besides let's number all the hacked computers with integers from 1 to n. So the i-th hacked computer is located at the point xi. Moreover the coordinates of all computers are distinct. Leha is determined to have a little rest after a hard week. Therefore he is going to invite his friend Noora to a restaurant. However the girl agrees to go on a date with the only one condition: Leha have to solve a simple task.Leha should calculate a sum of F(a) for all a, where a is a non-empty subset of the set, that consists of all hacked computers. Formally, let's denote A the set of all integers from 1 to n. Noora asks the hacker to find value of the expression . Here F(a) is calculated as the maximum among the distances between all pairs of computers from the set a. Formally, . Since the required sum can be quite large Noora asks to find it modulo 109 + 7.Though, Leha is too tired. Consequently he is not able to solve this task. Help the hacker to attend a date.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String args[]) throws IOException { Reader sc = new Reader(System.in); int n = sc.nextInt(); long[] a = new long[n]; long[] b = new long[n]; for (int i = 0; i < n; ++ i) { a[i] = sc.nextLong(); }; Long[] lol = new Long[n]; for (int i = 0; i < n; ++ i) { lol[i] = a[i]; } Arrays.sort(lol); for (int i = 0; i < n; ++ i) { a[i] = lol[i]; } long lines = 1; long ans = 0; long mod = 1000000007; for (int i = 1; i < n; ++ i) { b[i] = lines; lines = (lines * 2 + 1) % mod; } lines = 1; for (int i = 1; i < n; ++ i) { ans += ((a[n - i] - a[n - i - 1]) * lines) % mod * b[n - i] % mod; lines = (lines * 2 + 1) % mod; } System.out.println((ans) % mod); } } class Reader { private BufferedReader x; private StringTokenizer st; public Reader(InputStream in) { x = new BufferedReader(new InputStreamReader(in)); st = null; } public String nextString() throws IOException { while( st==null || !st.hasMoreTokens() ) st = new StringTokenizer(x.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(nextString()); } public long nextLong() throws IOException { return Long.parseLong(nextString()); } public double nextDouble() throws IOException { return Double.parseDouble(nextString()); } }
Java
["2\n4 7", "3\n4 3 1"]
2 seconds
["3", "9"]
NoteThere are three non-empty subsets in the first sample test:, and . The first and the second subset increase the sum by 0 and the third subset increases the sum by 7 - 4 = 3. In total the answer is 0 + 0 + 3 = 3.There are seven non-empty subsets in the second sample test. Among them only the following subsets increase the answer: , , , . In total the sum is (4 - 3) + (4 - 1) + (3 - 1) + (4 - 1) = 9.
Java 8
standard input
[ "implementation", "sortings", "math" ]
acff03fe274e819a74b5e9350a859471
The first line contains one integer n (1 ≤ n ≤ 3·105) denoting the number of hacked computers. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) denoting the coordinates of hacked computers. It is guaranteed that all xi are distinct.
1,500
Print a single integer — the required sum modulo 109 + 7.
standard output
PASSED
d55ed27a966c8831b6052bed26ed588f
train_001.jsonl
1495303500
Leha decided to move to a quiet town Vičkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to n computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on the same straight line, due to the reason that there is the only one straight street in Vičkopolis.Let's denote the coordinate system on this street. Besides let's number all the hacked computers with integers from 1 to n. So the i-th hacked computer is located at the point xi. Moreover the coordinates of all computers are distinct. Leha is determined to have a little rest after a hard week. Therefore he is going to invite his friend Noora to a restaurant. However the girl agrees to go on a date with the only one condition: Leha have to solve a simple task.Leha should calculate a sum of F(a) for all a, where a is a non-empty subset of the set, that consists of all hacked computers. Formally, let's denote A the set of all integers from 1 to n. Noora asks the hacker to find value of the expression . Here F(a) is calculated as the maximum among the distances between all pairs of computers from the set a. Formally, . Since the required sum can be quite large Noora asks to find it modulo 109 + 7.Though, Leha is too tired. Consequently he is not able to solve this task. Help the hacker to attend a date.
256 megabytes
import java.io.*; import java.util.*; public class Main { static class Task{ ////////////////// Solution ///////////////////////////////////// public void solve(InputReader in, PrintWriter out) throws Exception { int n = in.nextInt(); Integer[] a = new Integer[n]; long[] pow2 = new long[n+1]; pow2[0] = 1; long MOD = 1000000007; for (int i = 0; i < n; i++){ pow2[i+1] = (pow2[i]*2)%MOD; a[i] = in.nextInt(); } Arrays.sort(a, (b, c) -> c-b); long res = 0; for (int i = 0; i < n; i++){ res += (pow2[n-i-1]-pow2[i])*a[i]; res %= MOD; } res = (res+MOD)%MOD; out.println(res); } ////////////////////////////////////////////////////////////////////// } public static void main(String[] args) throws Exception{ InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task task = new Task(); task.solve(in, out); out.close(); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public Character nextChar(){ return next().charAt(0); } public String nextLine() throws IOException { return reader.readLine(); } public long nextLong(){ return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["2\n4 7", "3\n4 3 1"]
2 seconds
["3", "9"]
NoteThere are three non-empty subsets in the first sample test:, and . The first and the second subset increase the sum by 0 and the third subset increases the sum by 7 - 4 = 3. In total the answer is 0 + 0 + 3 = 3.There are seven non-empty subsets in the second sample test. Among them only the following subsets increase the answer: , , , . In total the sum is (4 - 3) + (4 - 1) + (3 - 1) + (4 - 1) = 9.
Java 8
standard input
[ "implementation", "sortings", "math" ]
acff03fe274e819a74b5e9350a859471
The first line contains one integer n (1 ≤ n ≤ 3·105) denoting the number of hacked computers. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) denoting the coordinates of hacked computers. It is guaranteed that all xi are distinct.
1,500
Print a single integer — the required sum modulo 109 + 7.
standard output
PASSED
c0c17cf20716b4c9da03727c15fa56c2
train_001.jsonl
1495303500
Leha decided to move to a quiet town Vičkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to n computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on the same straight line, due to the reason that there is the only one straight street in Vičkopolis.Let's denote the coordinate system on this street. Besides let's number all the hacked computers with integers from 1 to n. So the i-th hacked computer is located at the point xi. Moreover the coordinates of all computers are distinct. Leha is determined to have a little rest after a hard week. Therefore he is going to invite his friend Noora to a restaurant. However the girl agrees to go on a date with the only one condition: Leha have to solve a simple task.Leha should calculate a sum of F(a) for all a, where a is a non-empty subset of the set, that consists of all hacked computers. Formally, let's denote A the set of all integers from 1 to n. Noora asks the hacker to find value of the expression . Here F(a) is calculated as the maximum among the distances between all pairs of computers from the set a. Formally, . Since the required sum can be quite large Noora asks to find it modulo 109 + 7.Though, Leha is too tired. Consequently he is not able to solve this task. Help the hacker to attend a date.
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; /** * Created by jfuentes on 20.05.17. */ public class CodForceA { public static void main(String[] args) throws IOException { final long MOD = 1000000007L; FastScanner st = new FastScanner(System.in); int n = st.nextInt(); Integer[] nums = new Integer[n]; // long[] twoPower = new long[n]; // // twoPower[0] = 1; // for (int i = 1; i < n; i++) { // twoPower[i] = (2 * twoPower[i - 1]) % MOD; // } for (int i = 0; i < n; i++) { nums[i] = st.nextInt(); } Arrays.sort(nums); long right = 0, left = 0; long sol = 0; // for (int i = 0; i < n; i++) { // left = nums[i] * (twoPower[n - i - 1] - 1); // right = nums[i] * (twoPower[i] - 1); // // sol = (sol - left + right + MOD) % MOD; // } long p = 0, q = 0; for (int i = 0; i < n; i++) { p = (2 * p + nums[i]) % MOD; q = (2 * q + nums[n - i - 1]) % MOD; } sol = (q + MOD - p) % MOD; System.out.println(sol); } } class FastScanner { BufferedReader br; StringTokenizer tokenizer; FastScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } String nextLine() throws IOException { tokenizer = null; return br.readLine(); } String next() throws IOException { if (tokenizer == null || !tokenizer.hasMoreTokens()) { String line = br.readLine(); if (line == null) { return null; } tokenizer = new StringTokenizer(line); } return tokenizer.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } char nextChar() throws IOException { return next().charAt(0); } }
Java
["2\n4 7", "3\n4 3 1"]
2 seconds
["3", "9"]
NoteThere are three non-empty subsets in the first sample test:, and . The first and the second subset increase the sum by 0 and the third subset increases the sum by 7 - 4 = 3. In total the answer is 0 + 0 + 3 = 3.There are seven non-empty subsets in the second sample test. Among them only the following subsets increase the answer: , , , . In total the sum is (4 - 3) + (4 - 1) + (3 - 1) + (4 - 1) = 9.
Java 8
standard input
[ "implementation", "sortings", "math" ]
acff03fe274e819a74b5e9350a859471
The first line contains one integer n (1 ≤ n ≤ 3·105) denoting the number of hacked computers. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) denoting the coordinates of hacked computers. It is guaranteed that all xi are distinct.
1,500
Print a single integer — the required sum modulo 109 + 7.
standard output
PASSED
81b6707d8ca426065f72e8d91f7dca5e
train_001.jsonl
1495303500
Leha decided to move to a quiet town Vičkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to n computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on the same straight line, due to the reason that there is the only one straight street in Vičkopolis.Let's denote the coordinate system on this street. Besides let's number all the hacked computers with integers from 1 to n. So the i-th hacked computer is located at the point xi. Moreover the coordinates of all computers are distinct. Leha is determined to have a little rest after a hard week. Therefore he is going to invite his friend Noora to a restaurant. However the girl agrees to go on a date with the only one condition: Leha have to solve a simple task.Leha should calculate a sum of F(a) for all a, where a is a non-empty subset of the set, that consists of all hacked computers. Formally, let's denote A the set of all integers from 1 to n. Noora asks the hacker to find value of the expression . Here F(a) is calculated as the maximum among the distances between all pairs of computers from the set a. Formally, . Since the required sum can be quite large Noora asks to find it modulo 109 + 7.Though, Leha is too tired. Consequently he is not able to solve this task. Help the hacker to attend a date.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class Main { static FastScanner in; static PrintWriter out; static final int MOD = 1000000007; public static void main(String[] args) throws IOException { // Scanner in = new Scanner(new File("input.txt")); // Scanner in = new Scanner(System.in); // System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream("output.txt")), true)); out = new PrintWriter(System.out); in = new FastScanner(System.in); // in = new FastScanner("input.txt"); int n = in.nextInt(); Integer x[] = new Integer[n]; for (int i = 0; i < n; i++) { x[i] = in.nextInt(); } Arrays.sort(x); out.println(solve(x, n)); out.close(); } public static long solve(Integer[] x, int n) { long p = 0, q = 0; for (int i = 0; i < n; i++) { p = (2 * p + x[i]) % MOD; q = (2 * q + x[n - i - 1]) % MOD; } return (q + MOD - p) % MOD; } } class Pair { public int first; //first member of pair public int second; //second member of pair public Pair(int first, int second) { this.first = first; this.second = second; } public Pair() { } } class PairComparable implements Comparator<Pair> { @Override public int compare(Pair o1, Pair o2) { int first1 = o1.first * 2; int first2 = o2.first * 2; if (first1 > o1.second) { first1 = o1.second; } if (first2 > o2.second) { first2 = o2.second; } if (first1 - o1.first < first2 - o2.first) { return 1; } else if (first1 - o1.first > first2 - o2.first) { return -1; } else { return 0; } } } class FastScanner { BufferedReader br; StringTokenizer tokenizer; FastScanner(String fileName) throws FileNotFoundException { this(new FileInputStream(new File(fileName))); } FastScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } String nextLine() throws IOException { tokenizer = null; return br.readLine(); } String next() throws IOException { if (tokenizer == null || !tokenizer.hasMoreTokens()) { String line = br.readLine(); if (line == null) { return null; } tokenizer = new StringTokenizer(line); } return tokenizer.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } char nextChar() throws IOException { return next().charAt(0); } }
Java
["2\n4 7", "3\n4 3 1"]
2 seconds
["3", "9"]
NoteThere are three non-empty subsets in the first sample test:, and . The first and the second subset increase the sum by 0 and the third subset increases the sum by 7 - 4 = 3. In total the answer is 0 + 0 + 3 = 3.There are seven non-empty subsets in the second sample test. Among them only the following subsets increase the answer: , , , . In total the sum is (4 - 3) + (4 - 1) + (3 - 1) + (4 - 1) = 9.
Java 8
standard input
[ "implementation", "sortings", "math" ]
acff03fe274e819a74b5e9350a859471
The first line contains one integer n (1 ≤ n ≤ 3·105) denoting the number of hacked computers. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) denoting the coordinates of hacked computers. It is guaranteed that all xi are distinct.
1,500
Print a single integer — the required sum modulo 109 + 7.
standard output
PASSED
e4605b20c4041eb709c75d2b4690f484
train_001.jsonl
1495303500
Leha decided to move to a quiet town Vičkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to n computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on the same straight line, due to the reason that there is the only one straight street in Vičkopolis.Let's denote the coordinate system on this street. Besides let's number all the hacked computers with integers from 1 to n. So the i-th hacked computer is located at the point xi. Moreover the coordinates of all computers are distinct. Leha is determined to have a little rest after a hard week. Therefore he is going to invite his friend Noora to a restaurant. However the girl agrees to go on a date with the only one condition: Leha have to solve a simple task.Leha should calculate a sum of F(a) for all a, where a is a non-empty subset of the set, that consists of all hacked computers. Formally, let's denote A the set of all integers from 1 to n. Noora asks the hacker to find value of the expression . Here F(a) is calculated as the maximum among the distances between all pairs of computers from the set a. Formally, . Since the required sum can be quite large Noora asks to find it modulo 109 + 7.Though, Leha is too tired. Consequently he is not able to solve this task. Help the hacker to attend a date.
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.Collections; import java.util.StringTokenizer; public class C { static long MOD = (long) (1e9 + 7); static int N; static long initial; public static void main(String[] args) throws IOException { BufferedReader s = new BufferedReader(new InputStreamReader(System.in)); N = Integer.parseInt(s.readLine()); String numberString = s.readLine(); StringTokenizer st = new StringTokenizer(numberString, " "); initial = powmod(2, N) + 1; Long[] vals = new Long[N]; int ind = 0; while(st.hasMoreTokens()) vals[ind++] = Long.parseLong(st.nextToken()); ArrayList<Long> vv = new ArrayList<Long>(Arrays.asList(vals)); Collections.sort(vv); ind = 0; for(Long l : vv) vals[ind++] = l; long tot = 0; for (int i = 0; i < N - 1; i++) { tot += (vals[i + 1] - vals[i]) * getCoefficient(i); tot %= MOD; } System.out.println(tot); s.close(); } public static long getCoefficient(int i) { long cur = initial; cur -= powmod(2, N - i - 1); cur -= powmod(2, i + 1); cur %= MOD; cur = (cur + MOD) % MOD; return cur; } public static long powmod(long a, long b) { long ans = 1; while (b > 0) { if (b % 2 == 1) { ans = (ans % MOD) * (a % MOD); b--; } else { a = (a % MOD) * (a % MOD); b /= 2; } ans %= MOD; a %= MOD; } return ans; } }
Java
["2\n4 7", "3\n4 3 1"]
2 seconds
["3", "9"]
NoteThere are three non-empty subsets in the first sample test:, and . The first and the second subset increase the sum by 0 and the third subset increases the sum by 7 - 4 = 3. In total the answer is 0 + 0 + 3 = 3.There are seven non-empty subsets in the second sample test. Among them only the following subsets increase the answer: , , , . In total the sum is (4 - 3) + (4 - 1) + (3 - 1) + (4 - 1) = 9.
Java 8
standard input
[ "implementation", "sortings", "math" ]
acff03fe274e819a74b5e9350a859471
The first line contains one integer n (1 ≤ n ≤ 3·105) denoting the number of hacked computers. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) denoting the coordinates of hacked computers. It is guaranteed that all xi are distinct.
1,500
Print a single integer — the required sum modulo 109 + 7.
standard output
PASSED
b964091275335e6e675249af2ca3cc89
train_001.jsonl
1495303500
Leha decided to move to a quiet town Vičkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to n computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on the same straight line, due to the reason that there is the only one straight street in Vičkopolis.Let's denote the coordinate system on this street. Besides let's number all the hacked computers with integers from 1 to n. So the i-th hacked computer is located at the point xi. Moreover the coordinates of all computers are distinct. Leha is determined to have a little rest after a hard week. Therefore he is going to invite his friend Noora to a restaurant. However the girl agrees to go on a date with the only one condition: Leha have to solve a simple task.Leha should calculate a sum of F(a) for all a, where a is a non-empty subset of the set, that consists of all hacked computers. Formally, let's denote A the set of all integers from 1 to n. Noora asks the hacker to find value of the expression . Here F(a) is calculated as the maximum among the distances between all pairs of computers from the set a. Formally, . Since the required sum can be quite large Noora asks to find it modulo 109 + 7.Though, Leha is too tired. Consequently he is not able to solve this task. Help the hacker to attend a date.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.lang.reflect.Array; import java.util.Arrays; import java.util.Random; import java.util.StringTokenizer; public class Codeforces { static class Task { final int MOD = 1000000007; public void solve(FastScanner cin, PrintWriter cout) throws IOException{ int n = cin.nextInt(); int[] a = new int[n]; for(int i=0;i<n;i++) a[i] = cin.nextInt(); Utils.sort(a); int[] pre = new int[n+5]; pre[0] = 1; for(int i=1;i<=n;i++) pre[i] = 2 * pre[i-1] % MOD; long sum = 0; for(int i=0;i<n;i++) { long tmp = 1L * a[i] * ((pre[i] - pre[n-i-1] + MOD) % MOD) % MOD; sum = (sum + tmp) % MOD; } cout.println(sum); cout.close(); } } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); st = null; } 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 double nextDouble() throws IOException { return Double.parseDouble(next()); } } static class Utils{ private static void sort(int[] a){ Random rnd = new Random(); for(int i=0;i<a.length;i++){ int j = i + rnd.nextInt(a.length - i); int temp = a[j]; a[j] = a[i]; a[i] = temp; } Arrays.sort(a); } } public static void main(String[] args) throws IOException { InputStream is = System.in; OutputStream os = System.out; FastScanner in = new FastScanner(is); PrintWriter out = new PrintWriter(os); Task solver = new Task(); solver.solve(in, out); out.close(); } }
Java
["2\n4 7", "3\n4 3 1"]
2 seconds
["3", "9"]
NoteThere are three non-empty subsets in the first sample test:, and . The first and the second subset increase the sum by 0 and the third subset increases the sum by 7 - 4 = 3. In total the answer is 0 + 0 + 3 = 3.There are seven non-empty subsets in the second sample test. Among them only the following subsets increase the answer: , , , . In total the sum is (4 - 3) + (4 - 1) + (3 - 1) + (4 - 1) = 9.
Java 8
standard input
[ "implementation", "sortings", "math" ]
acff03fe274e819a74b5e9350a859471
The first line contains one integer n (1 ≤ n ≤ 3·105) denoting the number of hacked computers. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) denoting the coordinates of hacked computers. It is guaranteed that all xi are distinct.
1,500
Print a single integer — the required sum modulo 109 + 7.
standard output
PASSED
212cfd4628f435394b2c4169c0e57014
train_001.jsonl
1495303500
Leha decided to move to a quiet town Vičkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to n computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on the same straight line, due to the reason that there is the only one straight street in Vičkopolis.Let's denote the coordinate system on this street. Besides let's number all the hacked computers with integers from 1 to n. So the i-th hacked computer is located at the point xi. Moreover the coordinates of all computers are distinct. Leha is determined to have a little rest after a hard week. Therefore he is going to invite his friend Noora to a restaurant. However the girl agrees to go on a date with the only one condition: Leha have to solve a simple task.Leha should calculate a sum of F(a) for all a, where a is a non-empty subset of the set, that consists of all hacked computers. Formally, let's denote A the set of all integers from 1 to n. Noora asks the hacker to find value of the expression . Here F(a) is calculated as the maximum among the distances between all pairs of computers from the set a. Formally, . Since the required sum can be quite large Noora asks to find it modulo 109 + 7.Though, Leha is too tired. Consequently he is not able to solve this task. Help the hacker to attend a date.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.PriorityQueue; 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(); PriorityQueue<Integer> x = new PriorityQueue<>(); for (int i = 0; i < n; i++) x.add(in.nextInt()); int[] pow2val = new int[n + 1]; for (int i = 0, tmp = 1; i <= n; i++) { pow2val[i] = tmp; tmp = (tmp * 2) % 1_000_000_007; } long sum = 0; int pX = x.poll(); for (int i = 1; i < n; i++) { int cX = x.poll(); long left = (pow2val[i] + 1_000_000_006) % 1_000_000_007; long right = (pow2val[n - i] + 1_000_000_006) % 1_000_000_007; sum += ((cX - pX) * ((left * right) % 1_000_000_007)) % 1_000_000_007; sum %= 1_000_000_007; pX = cX; } out.println(sum); } } 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\n4 7", "3\n4 3 1"]
2 seconds
["3", "9"]
NoteThere are three non-empty subsets in the first sample test:, and . The first and the second subset increase the sum by 0 and the third subset increases the sum by 7 - 4 = 3. In total the answer is 0 + 0 + 3 = 3.There are seven non-empty subsets in the second sample test. Among them only the following subsets increase the answer: , , , . In total the sum is (4 - 3) + (4 - 1) + (3 - 1) + (4 - 1) = 9.
Java 8
standard input
[ "implementation", "sortings", "math" ]
acff03fe274e819a74b5e9350a859471
The first line contains one integer n (1 ≤ n ≤ 3·105) denoting the number of hacked computers. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) denoting the coordinates of hacked computers. It is guaranteed that all xi are distinct.
1,500
Print a single integer — the required sum modulo 109 + 7.
standard output
PASSED
f8aa3ffd645f90b4062d1bd8d51f7011
train_001.jsonl
1495303500
Leha decided to move to a quiet town Vičkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to n computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on the same straight line, due to the reason that there is the only one straight street in Vičkopolis.Let's denote the coordinate system on this street. Besides let's number all the hacked computers with integers from 1 to n. So the i-th hacked computer is located at the point xi. Moreover the coordinates of all computers are distinct. Leha is determined to have a little rest after a hard week. Therefore he is going to invite his friend Noora to a restaurant. However the girl agrees to go on a date with the only one condition: Leha have to solve a simple task.Leha should calculate a sum of F(a) for all a, where a is a non-empty subset of the set, that consists of all hacked computers. Formally, let's denote A the set of all integers from 1 to n. Noora asks the hacker to find value of the expression . Here F(a) is calculated as the maximum among the distances between all pairs of computers from the set a. Formally, . Since the required sum can be quite large Noora asks to find it modulo 109 + 7.Though, Leha is too tired. Consequently he is not able to solve this task. Help the hacker to attend a date.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; 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(); Integer[] x = new Integer[n]; for (int i = 0; i < n; i++) x[i] = in.nextInt(); int[] pow2val = new int[n + 1]; for (int i = 0, tmp = 1; i <= n; i++) { pow2val[i] = tmp; tmp = (tmp * 2) % 1_000_000_007; } Arrays.sort(x); long sum = 0; for (int i = 1; i < n; i++) { long left = (pow2val[i] + 1_000_000_006) % 1_000_000_007; long right = (pow2val[n - i] + 1_000_000_006) % 1_000_000_007; sum += ((x[i] - x[i - 1]) * ((left * right) % 1_000_000_007)) % 1_000_000_007; sum %= 1_000_000_007; } out.println(sum); } } 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\n4 7", "3\n4 3 1"]
2 seconds
["3", "9"]
NoteThere are three non-empty subsets in the first sample test:, and . The first and the second subset increase the sum by 0 and the third subset increases the sum by 7 - 4 = 3. In total the answer is 0 + 0 + 3 = 3.There are seven non-empty subsets in the second sample test. Among them only the following subsets increase the answer: , , , . In total the sum is (4 - 3) + (4 - 1) + (3 - 1) + (4 - 1) = 9.
Java 8
standard input
[ "implementation", "sortings", "math" ]
acff03fe274e819a74b5e9350a859471
The first line contains one integer n (1 ≤ n ≤ 3·105) denoting the number of hacked computers. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) denoting the coordinates of hacked computers. It is guaranteed that all xi are distinct.
1,500
Print a single integer — the required sum modulo 109 + 7.
standard output
PASSED
65ff8a1193349ffd44ede49979025674
train_001.jsonl
1495303500
Leha decided to move to a quiet town Vičkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to n computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on the same straight line, due to the reason that there is the only one straight street in Vičkopolis.Let's denote the coordinate system on this street. Besides let's number all the hacked computers with integers from 1 to n. So the i-th hacked computer is located at the point xi. Moreover the coordinates of all computers are distinct. Leha is determined to have a little rest after a hard week. Therefore he is going to invite his friend Noora to a restaurant. However the girl agrees to go on a date with the only one condition: Leha have to solve a simple task.Leha should calculate a sum of F(a) for all a, where a is a non-empty subset of the set, that consists of all hacked computers. Formally, let's denote A the set of all integers from 1 to n. Noora asks the hacker to find value of the expression . Here F(a) is calculated as the maximum among the distances between all pairs of computers from the set a. Formally, . Since the required sum can be quite large Noora asks to find it modulo 109 + 7.Though, Leha is too tired. Consequently he is not able to solve this task. Help the hacker to attend a date.
256 megabytes
import java.util.*; import java.io.*; import java.math.BigInteger; public class ProblemA { static long MOD = 1000000007; public static void main(String[] args) { FastScanner input = new FastScanner(); int n = input.nextInt(); int[] arr = input.readIntArray(n); shuffle(arr); Arrays.sort(arr); if(n == 1){ System.out.println(0); } else if(n == 2){ System.out.println(arr[1]-arr[0]); } else{ long start = arr[1]-arr[0]; long pow = 2; long total = start; for(int a = 2; a < n; a++){ start = start * 2; start %= MOD; pow *= 2; pow %= MOD; start += (pow-1)*(arr[a]-arr[a-1]); start %= MOD; total += start; total %= MOD; } total %= MOD; total += MOD; total %= MOD; System.out.println(total); } } static void shuffle(int[] arr) { Random rng = new Random(); int length = arr.length; for (int idx = 0; idx < arr.length; idx++) { int toSwap = idx + rng.nextInt(length-idx); int tmp = arr[idx]; arr[idx] = arr[toSwap]; arr[toSwap] = tmp; } } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(Reader in) { br = new BufferedReader(in); } public FastScanner() { this(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String readNextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] readIntArray(int n) { int[] a = new int[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextInt(); } return a; } long[] readLongArray(int n) { long[] a = new long[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextLong(); } return a; } } } // 1-4; 4x // 2-4; 2x // 3-4; 1x // 1-4; 8x // 2-4; 4x // 3-4; 2x // 4-4; 1x // // shift -
Java
["2\n4 7", "3\n4 3 1"]
2 seconds
["3", "9"]
NoteThere are three non-empty subsets in the first sample test:, and . The first and the second subset increase the sum by 0 and the third subset increases the sum by 7 - 4 = 3. In total the answer is 0 + 0 + 3 = 3.There are seven non-empty subsets in the second sample test. Among them only the following subsets increase the answer: , , , . In total the sum is (4 - 3) + (4 - 1) + (3 - 1) + (4 - 1) = 9.
Java 8
standard input
[ "implementation", "sortings", "math" ]
acff03fe274e819a74b5e9350a859471
The first line contains one integer n (1 ≤ n ≤ 3·105) denoting the number of hacked computers. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) denoting the coordinates of hacked computers. It is guaranteed that all xi are distinct.
1,500
Print a single integer — the required sum modulo 109 + 7.
standard output
PASSED
07bb8ecc799dbbc8be160d18941dd176
train_001.jsonl
1495303500
Leha decided to move to a quiet town Vičkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to n computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on the same straight line, due to the reason that there is the only one straight street in Vičkopolis.Let's denote the coordinate system on this street. Besides let's number all the hacked computers with integers from 1 to n. So the i-th hacked computer is located at the point xi. Moreover the coordinates of all computers are distinct. Leha is determined to have a little rest after a hard week. Therefore he is going to invite his friend Noora to a restaurant. However the girl agrees to go on a date with the only one condition: Leha have to solve a simple task.Leha should calculate a sum of F(a) for all a, where a is a non-empty subset of the set, that consists of all hacked computers. Formally, let's denote A the set of all integers from 1 to n. Noora asks the hacker to find value of the expression . Here F(a) is calculated as the maximum among the distances between all pairs of computers from the set a. Formally, . Since the required sum can be quite large Noora asks to find it modulo 109 + 7.Though, Leha is too tired. Consequently he is not able to solve this task. Help the hacker to attend a date.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.Iterator; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.NoSuchElementException; 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); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { final static int MOD = 1000 * 1000 * 1000 + 7; public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); long[] powers = new long[n]; powers[0] = 1; for (int i = 1; i < n; i++) powers[i] = (powers[i - 1] * 2) % MOD; int[] x = IOUtils.readIntArray(in, n); ArrayUtils.sort(x); int res = 0; for (int i = n - 1; i >= 0; i--) { int val = (int) ((powers[i] * x[i]) % MOD); res += val; if (res >= MOD) res -= MOD; } for (int i = 0; i < n; i++) { int val = (int) ((powers[n - i - 1] * x[i]) % MOD); res -= val; if (res < 0) res += MOD; } out.printLine(res); } } static class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = in.readInt(); } return array; } } static class ArrayUtils { public static int[] sort(int[] array) { return sort(array, IntComparator.DEFAULT); } public static int[] sort(int[] array, IntComparator comparator) { return sort(array, 0, array.length, comparator); } public static int[] sort(int[] array, int from, int to, IntComparator comparator) { if (from == 0 && to == array.length) { new IntArray(array).sort(comparator); } else { new IntArray(array).subList(from, to).sort(comparator); } return array; } } static abstract class IntAbstractStream implements IntStream { public String toString() { StringBuilder builder = new StringBuilder(); boolean first = true; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { if (first) { first = false; } else { builder.append(' '); } builder.append(it.value()); } return builder.toString(); } public boolean equals(Object o) { if (!(o instanceof IntStream)) { return false; } IntStream c = (IntStream) o; IntIterator it = intIterator(); IntIterator jt = c.intIterator(); while (it.isValid() && jt.isValid()) { if (it.value() != jt.value()) { return false; } it.advance(); jt.advance(); } return !it.isValid() && !jt.isValid(); } public int hashCode() { int result = 0; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { result *= 31; result += it.value(); } return result; } } static interface IntReversableCollection extends IntCollection { } static interface IntList extends IntReversableCollection { public abstract int get(int index); public abstract void set(int index, int value); public abstract void addAt(int index, int value); public abstract void removeAt(int index); default public void swap(int first, int second) { if (first == second) { return; } int temp = get(first); set(first, get(second)); set(second, temp); } default public IntIterator intIterator() { return new IntIterator() { private int at; private boolean removed; public int value() { if (removed) { throw new IllegalStateException(); } return get(at); } public boolean advance() { at++; removed = false; return isValid(); } public boolean isValid() { return !removed && at < size(); } public void remove() { removeAt(at); at--; removed = true; } }; } default public void add(int value) { addAt(size(), value); } default public IntList sort(IntComparator comparator) { Sorter.sort(this, comparator); return this; } default public IntList subList(final int from, final int to) { return new IntList() { private final int shift; private final int size; { if (from < 0 || from > to || to > IntList.this.size()) { throw new IndexOutOfBoundsException("from = " + from + ", to = " + to + ", size = " + size()); } shift = from; size = to - from; } public int size() { return size; } public int get(int at) { if (at < 0 || at >= size) { throw new IndexOutOfBoundsException("at = " + at + ", size = " + size()); } return IntList.this.get(at + shift); } public void addAt(int index, int value) { throw new UnsupportedOperationException(); } public void removeAt(int index) { throw new UnsupportedOperationException(); } public void set(int at, int value) { if (at < 0 || at >= size) { throw new IndexOutOfBoundsException("at = " + at + ", size = " + size()); } IntList.this.set(at + shift, value); } public IntList compute() { return new IntArrayList(this); } }; } } static interface IntIterator { public int value() throws NoSuchElementException; public boolean advance(); public boolean isValid(); } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void printLine(int i) { writer.println(i); } } static class IntArrayList extends IntAbstractStream implements IntList { private int size; private int[] data; public IntArrayList() { this(3); } public IntArrayList(int capacity) { data = new int[capacity]; } public IntArrayList(IntCollection c) { this(c.size()); addAll(c); } public IntArrayList(IntStream c) { this(); if (c instanceof IntCollection) { ensureCapacity(((IntCollection) c).size()); } addAll(c); } public IntArrayList(IntArrayList c) { size = c.size(); data = c.data.clone(); } public IntArrayList(int[] arr) { size = arr.length; data = arr.clone(); } public int size() { return size; } public int get(int at) { if (at >= size) { throw new IndexOutOfBoundsException("at = " + at + ", size = " + size); } return data[at]; } private void ensureCapacity(int capacity) { if (data.length >= capacity) { return; } capacity = Math.max(2 * data.length, capacity); data = Arrays.copyOf(data, capacity); } public void addAt(int index, int value) { ensureCapacity(size + 1); if (index > size || index < 0) { throw new IndexOutOfBoundsException("at = " + index + ", size = " + size); } if (index != size) { System.arraycopy(data, index, data, index + 1, size - index); } data[index] = value; size++; } public void removeAt(int index) { if (index >= size || index < 0) { throw new IndexOutOfBoundsException("at = " + index + ", size = " + size); } if (index != size - 1) { System.arraycopy(data, index + 1, data, index, size - index - 1); } size--; } public void set(int index, int value) { if (index >= size) { throw new IndexOutOfBoundsException("at = " + index + ", size = " + size); } data[index] = value; } } static class Sorter { private static final int INSERTION_THRESHOLD = 16; private Sorter() { } public static void sort(IntList list, IntComparator comparator) { quickSort(list, 0, list.size() - 1, (Integer.bitCount(Integer.highestOneBit(list.size()) - 1) * 5) >> 1, comparator); } private static void quickSort(IntList list, int from, int to, int remaining, IntComparator comparator) { if (to - from < INSERTION_THRESHOLD) { insertionSort(list, from, to, comparator); return; } if (remaining == 0) { heapSort(list, from, to, comparator); return; } remaining--; int pivotIndex = (from + to) >> 1; int pivot = list.get(pivotIndex); list.swap(pivotIndex, to); int storeIndex = from; int equalIndex = to; for (int i = from; i < equalIndex; i++) { int value = comparator.compare(list.get(i), pivot); if (value < 0) { list.swap(storeIndex++, i); } else if (value == 0) { list.swap(--equalIndex, i--); } } quickSort(list, from, storeIndex - 1, remaining, comparator); for (int i = equalIndex; i <= to; i++) { list.swap(storeIndex++, i); } quickSort(list, storeIndex, to, remaining, comparator); } private static void heapSort(IntList list, int from, int to, IntComparator comparator) { for (int i = (to + from - 1) >> 1; i >= from; i--) { siftDown(list, i, to, comparator, from); } for (int i = to; i > from; i--) { list.swap(from, i); siftDown(list, from, i - 1, comparator, from); } } private static void siftDown(IntList list, int start, int end, IntComparator comparator, int delta) { int value = list.get(start); while (true) { int child = ((start - delta) << 1) + 1 + delta; if (child > end) { return; } int childValue = list.get(child); if (child + 1 <= end) { int otherValue = list.get(child + 1); if (comparator.compare(otherValue, childValue) > 0) { child++; childValue = otherValue; } } if (comparator.compare(value, childValue) >= 0) { return; } list.swap(start, child); start = child; } } private static void insertionSort(IntList list, int from, int to, IntComparator comparator) { for (int i = from + 1; i <= to; i++) { int value = list.get(i); for (int j = i - 1; j >= from; j--) { if (comparator.compare(list.get(j), value) <= 0) { break; } list.swap(j, j + 1); } } } } static class IntArray extends IntAbstractStream implements IntList { private int[] data; public IntArray(int[] arr) { data = arr; } public int size() { return data.length; } public int get(int at) { return data[at]; } public void addAt(int index, int value) { throw new UnsupportedOperationException(); } public void removeAt(int index) { throw new UnsupportedOperationException(); } public void set(int index, int value) { data[index] = value; } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static interface IntCollection extends IntStream { public int size(); default public void add(int value) { throw new UnsupportedOperationException(); } default public IntCollection addAll(IntStream values) { for (IntIterator it = values.intIterator(); it.isValid(); it.advance()) { add(it.value()); } return this; } } static interface IntComparator { public static final IntComparator DEFAULT = (first, second) -> { if (first < second) { return -1; } if (first > second) { return 1; } return 0; }; public int compare(int first, int second); } static interface IntStream extends Iterable<Integer>, Comparable<IntStream> { public IntIterator intIterator(); default public Iterator<Integer> iterator() { return new Iterator<Integer>() { private IntIterator it = intIterator(); public boolean hasNext() { return it.isValid(); } public Integer next() { int result = it.value(); it.advance(); return result; } }; } default public int compareTo(IntStream c) { IntIterator it = intIterator(); IntIterator jt = c.intIterator(); while (it.isValid() && jt.isValid()) { int i = it.value(); int j = jt.value(); if (i < j) { return -1; } else if (i > j) { return 1; } it.advance(); jt.advance(); } if (it.isValid()) { return 1; } if (jt.isValid()) { return -1; } return 0; } } }
Java
["2\n4 7", "3\n4 3 1"]
2 seconds
["3", "9"]
NoteThere are three non-empty subsets in the first sample test:, and . The first and the second subset increase the sum by 0 and the third subset increases the sum by 7 - 4 = 3. In total the answer is 0 + 0 + 3 = 3.There are seven non-empty subsets in the second sample test. Among them only the following subsets increase the answer: , , , . In total the sum is (4 - 3) + (4 - 1) + (3 - 1) + (4 - 1) = 9.
Java 8
standard input
[ "implementation", "sortings", "math" ]
acff03fe274e819a74b5e9350a859471
The first line contains one integer n (1 ≤ n ≤ 3·105) denoting the number of hacked computers. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) denoting the coordinates of hacked computers. It is guaranteed that all xi are distinct.
1,500
Print a single integer — the required sum modulo 109 + 7.
standard output
PASSED
76cbd4e800b2f4749811c7d8fde62dad
train_001.jsonl
1495303500
Leha decided to move to a quiet town Vičkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to n computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on the same straight line, due to the reason that there is the only one straight street in Vičkopolis.Let's denote the coordinate system on this street. Besides let's number all the hacked computers with integers from 1 to n. So the i-th hacked computer is located at the point xi. Moreover the coordinates of all computers are distinct. Leha is determined to have a little rest after a hard week. Therefore he is going to invite his friend Noora to a restaurant. However the girl agrees to go on a date with the only one condition: Leha have to solve a simple task.Leha should calculate a sum of F(a) for all a, where a is a non-empty subset of the set, that consists of all hacked computers. Formally, let's denote A the set of all integers from 1 to n. Noora asks the hacker to find value of the expression . Here F(a) is calculated as the maximum among the distances between all pairs of computers from the set a. Formally, . Since the required sum can be quite large Noora asks to find it modulo 109 + 7.Though, Leha is too tired. Consequently he is not able to solve this task. Help the hacker to attend a date.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.Iterator; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.NoSuchElementException; 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); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { final static int MOD = 1000 * 1000 * 1000 + 7; public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); int[] x = IOUtils.readIntArray(in, n); ArrayUtils.sort(x); int res = 0; for (int i = n - 1; i >= 0; i--) { int val = (int) ((IntegerUtils.power(2, i, MOD) * x[i]) % MOD); res += val; if (res >= MOD) res -= MOD; } for (int i = 0; i < n; i++) { int val = (int) (((IntegerUtils.power(2, n - i - 1, MOD) * x[i]) % MOD)); res -= val; if (res < 0) res += MOD; } out.printLine(res); } } static class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = in.readInt(); } return array; } } static class IntArray extends IntAbstractStream implements IntList { private int[] data; public IntArray(int[] arr) { data = arr; } public int size() { return data.length; } public int get(int at) { return data[at]; } public void addAt(int index, int value) { throw new UnsupportedOperationException(); } public void removeAt(int index) { throw new UnsupportedOperationException(); } public void set(int index, int value) { data[index] = value; } } static abstract class IntAbstractStream implements IntStream { public String toString() { StringBuilder builder = new StringBuilder(); boolean first = true; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { if (first) { first = false; } else { builder.append(' '); } builder.append(it.value()); } return builder.toString(); } public boolean equals(Object o) { if (!(o instanceof IntStream)) { return false; } IntStream c = (IntStream) o; IntIterator it = intIterator(); IntIterator jt = c.intIterator(); while (it.isValid() && jt.isValid()) { if (it.value() != jt.value()) { return false; } it.advance(); jt.advance(); } return !it.isValid() && !jt.isValid(); } public int hashCode() { int result = 0; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { result *= 31; result += it.value(); } return result; } } static interface IntCollection extends IntStream { public int size(); default public void add(int value) { throw new UnsupportedOperationException(); } default public IntCollection addAll(IntStream values) { for (IntIterator it = values.intIterator(); it.isValid(); it.advance()) { add(it.value()); } return this; } } static class IntArrayList extends IntAbstractStream implements IntList { private int size; private int[] data; public IntArrayList() { this(3); } public IntArrayList(int capacity) { data = new int[capacity]; } public IntArrayList(IntCollection c) { this(c.size()); addAll(c); } public IntArrayList(IntStream c) { this(); if (c instanceof IntCollection) { ensureCapacity(((IntCollection) c).size()); } addAll(c); } public IntArrayList(IntArrayList c) { size = c.size(); data = c.data.clone(); } public IntArrayList(int[] arr) { size = arr.length; data = arr.clone(); } public int size() { return size; } public int get(int at) { if (at >= size) { throw new IndexOutOfBoundsException("at = " + at + ", size = " + size); } return data[at]; } private void ensureCapacity(int capacity) { if (data.length >= capacity) { return; } capacity = Math.max(2 * data.length, capacity); data = Arrays.copyOf(data, capacity); } public void addAt(int index, int value) { ensureCapacity(size + 1); if (index > size || index < 0) { throw new IndexOutOfBoundsException("at = " + index + ", size = " + size); } if (index != size) { System.arraycopy(data, index, data, index + 1, size - index); } data[index] = value; size++; } public void removeAt(int index) { if (index >= size || index < 0) { throw new IndexOutOfBoundsException("at = " + index + ", size = " + size); } if (index != size - 1) { System.arraycopy(data, index + 1, data, index, size - index - 1); } size--; } public void set(int index, int value) { if (index >= size) { throw new IndexOutOfBoundsException("at = " + index + ", size = " + size); } data[index] = value; } } static class ArrayUtils { public static int[] sort(int[] array) { return sort(array, IntComparator.DEFAULT); } public static int[] sort(int[] array, IntComparator comparator) { return sort(array, 0, array.length, comparator); } public static int[] sort(int[] array, int from, int to, IntComparator comparator) { if (from == 0 && to == array.length) { new IntArray(array).sort(comparator); } else { new IntArray(array).subList(from, to).sort(comparator); } return array; } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void printLine(int i) { writer.println(i); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class IntegerUtils { public static long power(long base, long exponent, long mod) { if (base >= mod) { base %= mod; } if (exponent == 0) { return 1 % mod; } long result = power(base, exponent >> 1, mod); result = result * result % mod; if ((exponent & 1) != 0) { result = result * base % mod; } return result; } } static class Sorter { private static final int INSERTION_THRESHOLD = 16; private Sorter() { } public static void sort(IntList list, IntComparator comparator) { quickSort(list, 0, list.size() - 1, (Integer.bitCount(Integer.highestOneBit(list.size()) - 1) * 5) >> 1, comparator); } private static void quickSort(IntList list, int from, int to, int remaining, IntComparator comparator) { if (to - from < INSERTION_THRESHOLD) { insertionSort(list, from, to, comparator); return; } if (remaining == 0) { heapSort(list, from, to, comparator); return; } remaining--; int pivotIndex = (from + to) >> 1; int pivot = list.get(pivotIndex); list.swap(pivotIndex, to); int storeIndex = from; int equalIndex = to; for (int i = from; i < equalIndex; i++) { int value = comparator.compare(list.get(i), pivot); if (value < 0) { list.swap(storeIndex++, i); } else if (value == 0) { list.swap(--equalIndex, i--); } } quickSort(list, from, storeIndex - 1, remaining, comparator); for (int i = equalIndex; i <= to; i++) { list.swap(storeIndex++, i); } quickSort(list, storeIndex, to, remaining, comparator); } private static void heapSort(IntList list, int from, int to, IntComparator comparator) { for (int i = (to + from - 1) >> 1; i >= from; i--) { siftDown(list, i, to, comparator, from); } for (int i = to; i > from; i--) { list.swap(from, i); siftDown(list, from, i - 1, comparator, from); } } private static void siftDown(IntList list, int start, int end, IntComparator comparator, int delta) { int value = list.get(start); while (true) { int child = ((start - delta) << 1) + 1 + delta; if (child > end) { return; } int childValue = list.get(child); if (child + 1 <= end) { int otherValue = list.get(child + 1); if (comparator.compare(otherValue, childValue) > 0) { child++; childValue = otherValue; } } if (comparator.compare(value, childValue) >= 0) { return; } list.swap(start, child); start = child; } } private static void insertionSort(IntList list, int from, int to, IntComparator comparator) { for (int i = from + 1; i <= to; i++) { int value = list.get(i); for (int j = i - 1; j >= from; j--) { if (comparator.compare(list.get(j), value) <= 0) { break; } list.swap(j, j + 1); } } } } static interface IntComparator { public static final IntComparator DEFAULT = (first, second) -> { if (first < second) { return -1; } if (first > second) { return 1; } return 0; }; public int compare(int first, int second); } static interface IntStream extends Iterable<Integer>, Comparable<IntStream> { public IntIterator intIterator(); default public Iterator<Integer> iterator() { return new Iterator<Integer>() { private IntIterator it = intIterator(); public boolean hasNext() { return it.isValid(); } public Integer next() { int result = it.value(); it.advance(); return result; } }; } default public int compareTo(IntStream c) { IntIterator it = intIterator(); IntIterator jt = c.intIterator(); while (it.isValid() && jt.isValid()) { int i = it.value(); int j = jt.value(); if (i < j) { return -1; } else if (i > j) { return 1; } it.advance(); jt.advance(); } if (it.isValid()) { return 1; } if (jt.isValid()) { return -1; } return 0; } } static interface IntIterator { public int value() throws NoSuchElementException; public boolean advance(); public boolean isValid(); } static interface IntReversableCollection extends IntCollection { } static interface IntList extends IntReversableCollection { public abstract int get(int index); public abstract void set(int index, int value); public abstract void addAt(int index, int value); public abstract void removeAt(int index); default public void swap(int first, int second) { if (first == second) { return; } int temp = get(first); set(first, get(second)); set(second, temp); } default public IntIterator intIterator() { return new IntIterator() { private int at; private boolean removed; public int value() { if (removed) { throw new IllegalStateException(); } return get(at); } public boolean advance() { at++; removed = false; return isValid(); } public boolean isValid() { return !removed && at < size(); } public void remove() { removeAt(at); at--; removed = true; } }; } default public void add(int value) { addAt(size(), value); } default public IntList sort(IntComparator comparator) { Sorter.sort(this, comparator); return this; } default public IntList subList(final int from, final int to) { return new IntList() { private final int shift; private final int size; { if (from < 0 || from > to || to > IntList.this.size()) { throw new IndexOutOfBoundsException("from = " + from + ", to = " + to + ", size = " + size()); } shift = from; size = to - from; } public int size() { return size; } public int get(int at) { if (at < 0 || at >= size) { throw new IndexOutOfBoundsException("at = " + at + ", size = " + size()); } return IntList.this.get(at + shift); } public void addAt(int index, int value) { throw new UnsupportedOperationException(); } public void removeAt(int index) { throw new UnsupportedOperationException(); } public void set(int at, int value) { if (at < 0 || at >= size) { throw new IndexOutOfBoundsException("at = " + at + ", size = " + size()); } IntList.this.set(at + shift, value); } public IntList compute() { return new IntArrayList(this); } }; } } }
Java
["2\n4 7", "3\n4 3 1"]
2 seconds
["3", "9"]
NoteThere are three non-empty subsets in the first sample test:, and . The first and the second subset increase the sum by 0 and the third subset increases the sum by 7 - 4 = 3. In total the answer is 0 + 0 + 3 = 3.There are seven non-empty subsets in the second sample test. Among them only the following subsets increase the answer: , , , . In total the sum is (4 - 3) + (4 - 1) + (3 - 1) + (4 - 1) = 9.
Java 8
standard input
[ "implementation", "sortings", "math" ]
acff03fe274e819a74b5e9350a859471
The first line contains one integer n (1 ≤ n ≤ 3·105) denoting the number of hacked computers. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) denoting the coordinates of hacked computers. It is guaranteed that all xi are distinct.
1,500
Print a single integer — the required sum modulo 109 + 7.
standard output
PASSED
7a6dbc38fb02e64b60f4cb0736e75e5b
train_001.jsonl
1495303500
Leha decided to move to a quiet town Vičkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to n computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on the same straight line, due to the reason that there is the only one straight street in Vičkopolis.Let's denote the coordinate system on this street. Besides let's number all the hacked computers with integers from 1 to n. So the i-th hacked computer is located at the point xi. Moreover the coordinates of all computers are distinct. Leha is determined to have a little rest after a hard week. Therefore he is going to invite his friend Noora to a restaurant. However the girl agrees to go on a date with the only one condition: Leha have to solve a simple task.Leha should calculate a sum of F(a) for all a, where a is a non-empty subset of the set, that consists of all hacked computers. Formally, let's denote A the set of all integers from 1 to n. Noora asks the hacker to find value of the expression . Here F(a) is calculated as the maximum among the distances between all pairs of computers from the set a. Formally, . Since the required sum can be quite large Noora asks to find it modulo 109 + 7.Though, Leha is too tired. Consequently he is not able to solve this task. Help the hacker to attend a date.
256 megabytes
import java.util.*; public class Code809A{ public static int MOD = 1000000007; public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] Tab = new int[n]; int[] Pow = new int[n]; Pow[0]=1; for(int i=1;i<n;i++)Pow[i]=(2*Pow[i-1])%MOD; //System.out.println("XXXXXXX"); Code809A sorter = new Code809A(n+1); for(int i=0;i<n;i++)sorter.insert(sc.nextInt()); for(int i=0;i<n;i++)Tab[i]=sorter.getAndRemove(); long res=0; int lim = (n-1)/2; for(int i=1;i<=lim;i++){ int f = Tab[i]-Tab[i-1] + Tab[n-i]-Tab[n-i-1]; long l = Pow[i]-1; long r = Pow[n-i]-1; long x = l*r%MOD; res=(res+(x*f)%MOD)%MOD; //System.out.println("New res="+res); } if(n%2==0){ int f = Tab[n/2]-Tab[n/2-1]; long lir = Pow[n/2]-1; long x = (lir*lir)%MOD; res=(res+(x*f)%MOD)%MOD; } System.out.println(res); } //public static void swap(int &a, int &b){ // int c=a; // a=b; // b=c; //} int[] heap; int hSize; Code809A(int x){ hSize=0; heap = new int[x]; } void repairUp(int x){ while(x>1) if(heap[x/2]>heap[x]){ //swap(heap[x], heap[x/2]); int sw = heap[x]; heap[x]=heap[x/2]; heap[x/2]=sw; x/=2; } else break; } void repairDown(int x){ int mV=heap[x], mP=x; if(x*2<=hSize && heap[x*2]<mV){ mP=x*2; mV=heap[mP]; } if(x*2+1<=hSize && heap[x*2+1]<mV){ mP=x*2+1; mV=heap[mP]; } if(mP!=x){ //swap(heap[x], heap[mP]); int sw = heap[x]; heap[x]=heap[mP]; heap[mP]=sw; repairDown(mP); } } void insert(int x){ heap[++hSize]=x; repairUp(hSize); } int getAndRemove(){ int r = heap[1]; heap[1]=heap[hSize--]; if(hSize>0)repairDown(1); return r; } }
Java
["2\n4 7", "3\n4 3 1"]
2 seconds
["3", "9"]
NoteThere are three non-empty subsets in the first sample test:, and . The first and the second subset increase the sum by 0 and the third subset increases the sum by 7 - 4 = 3. In total the answer is 0 + 0 + 3 = 3.There are seven non-empty subsets in the second sample test. Among them only the following subsets increase the answer: , , , . In total the sum is (4 - 3) + (4 - 1) + (3 - 1) + (4 - 1) = 9.
Java 8
standard input
[ "implementation", "sortings", "math" ]
acff03fe274e819a74b5e9350a859471
The first line contains one integer n (1 ≤ n ≤ 3·105) denoting the number of hacked computers. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) denoting the coordinates of hacked computers. It is guaranteed that all xi are distinct.
1,500
Print a single integer — the required sum modulo 109 + 7.
standard output
PASSED
127761930533f7a8cb3c9ee9e7632678
train_001.jsonl
1495303500
Leha decided to move to a quiet town Vičkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to n computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on the same straight line, due to the reason that there is the only one straight street in Vičkopolis.Let's denote the coordinate system on this street. Besides let's number all the hacked computers with integers from 1 to n. So the i-th hacked computer is located at the point xi. Moreover the coordinates of all computers are distinct. Leha is determined to have a little rest after a hard week. Therefore he is going to invite his friend Noora to a restaurant. However the girl agrees to go on a date with the only one condition: Leha have to solve a simple task.Leha should calculate a sum of F(a) for all a, where a is a non-empty subset of the set, that consists of all hacked computers. Formally, let's denote A the set of all integers from 1 to n. Noora asks the hacker to find value of the expression . Here F(a) is calculated as the maximum among the distances between all pairs of computers from the set a. Formally, . Since the required sum can be quite large Noora asks to find it modulo 109 + 7.Though, Leha is too tired. Consequently he is not able to solve this task. Help the hacker to attend a date.
256 megabytes
import java.util.*; import java.io.*; public class A { public static void main(String[] args) throws Exception { PrintWriter out = new PrintWriter(System.out); new A(new FastScanner(System.in), out); out.close(); } int MODO = 1_000_000_007; public A(FastScanner in, PrintWriter out) { int N = in.nextInt(); long[] pow2 = new long[N+1]; pow2[0] = 1; for (int i=1; i<N; i++) pow2[i] = (2 * pow2[i-1]) % MODO; int[] vs = new int[N]; for (int i=0; i<N; i++) vs[i] = in.nextInt(); for (int i=1; i<N; i++) { int j = (int)(i*Math.random()); int tmp = vs[i]; vs[i] = vs[j]; vs[j] = tmp; } Arrays.sort(vs); long sum = 0; for (int i=0; i<N; i++) { int numLeft = i; int numRight = N-i-1; sum -= (vs[i] * pow2[numRight]) % MODO; sum %= MODO; sum += MODO; sum %= MODO; sum += vs[i] * pow2[numLeft]; sum %= MODO; } out.println(sum); } } class FastScanner{ private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastScanner(InputStream stream) { this.stream = stream; } 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++]; } 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; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } 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(); } 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 7", "3\n4 3 1"]
2 seconds
["3", "9"]
NoteThere are three non-empty subsets in the first sample test:, and . The first and the second subset increase the sum by 0 and the third subset increases the sum by 7 - 4 = 3. In total the answer is 0 + 0 + 3 = 3.There are seven non-empty subsets in the second sample test. Among them only the following subsets increase the answer: , , , . In total the sum is (4 - 3) + (4 - 1) + (3 - 1) + (4 - 1) = 9.
Java 8
standard input
[ "implementation", "sortings", "math" ]
acff03fe274e819a74b5e9350a859471
The first line contains one integer n (1 ≤ n ≤ 3·105) denoting the number of hacked computers. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) denoting the coordinates of hacked computers. It is guaranteed that all xi are distinct.
1,500
Print a single integer — the required sum modulo 109 + 7.
standard output
PASSED
c084d56d8f5ac83f131ff3bc8f7803f5
train_001.jsonl
1495303500
Leha decided to move to a quiet town Vičkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to n computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on the same straight line, due to the reason that there is the only one straight street in Vičkopolis.Let's denote the coordinate system on this street. Besides let's number all the hacked computers with integers from 1 to n. So the i-th hacked computer is located at the point xi. Moreover the coordinates of all computers are distinct. Leha is determined to have a little rest after a hard week. Therefore he is going to invite his friend Noora to a restaurant. However the girl agrees to go on a date with the only one condition: Leha have to solve a simple task.Leha should calculate a sum of F(a) for all a, where a is a non-empty subset of the set, that consists of all hacked computers. Formally, let's denote A the set of all integers from 1 to n. Noora asks the hacker to find value of the expression . Here F(a) is calculated as the maximum among the distances between all pairs of computers from the set a. Formally, . Since the required sum can be quite large Noora asks to find it modulo 109 + 7.Though, Leha is too tired. Consequently he is not able to solve this task. Help the hacker to attend a date.
256 megabytes
import static java.lang.Integer.min; import static java.lang.System.out; import java.util.Arrays; import java.util.Comparator; import java.util.Scanner; import java.util.stream.IntStream; /* * N points on a line, coordinate 1 ≤ xi ≤ 10^9, 1 ≤ n ≤ 3·10^5 * a is none empty subset of A - all points * F(a) = max distance of any two points in a * Find sum of F(a) of all possible subsets */ // e.g N=3, X=1 3 4 // dist 1-3: subsets 1 3, 1 4, 1 3 4 // dist 3-4: subsets 1 4, 1 3 4, 3 4 //contest r415, 809A public class WantDate { static final int MOD=1000000007; // 10^9 + 7 static int power2[]=new int[300000+5]; static { power2[0]=1; for (int i=1; i< power2.length; i++) { power2[i] = (2 * power2[i-1])%MOD; } //out.println(Arrays.toString(power2)); } WantDate(int x[]) { x = sortIaR(x); //out.println(Arrays.toString(x)); long total=0; for (int i=0; i<x.length-1; i++) { long dist=x[i]-x[i+1]; dist = (dist * (power2[i+1]-1))%MOD; dist = (dist * (power2[x.length-i-1]-1))%MOD; total = (total+dist)%MOD; } out.println(total); } static long sum1(int x[], int i, int n) { long diff=x[i]-x[n]; int power=n-i-1; //out.println("diff="+diff+" power="+power); if (power==0) { return diff%MOD; } long total=0; while (power>0) { int p=min(power, 30); power -= p; diff *= (1<<p); total = (total+diff%MOD)%MOD; } //out.println("new total="+total); return total; } static void sum(int x[]) { x = sortIaR(x); int n=x.length-1; long total=0; for (int i=0; i<n; i++) { total =(total+sum1(x, i, n))%MOD; if (i==0) continue; total =(total+sum1(x, 0, i))%MOD; } out.println(total); } static void test() { new WantDate(new int[]{4, 7}); // 3 new WantDate(new int[]{400000000,100000000,300000000}); //900000000 new WantDate(new int[]{400000000,100000000,300000000,1}); // 999999979 new WantDate(new int[]{1, 2, 3, 4, 5}); // 66 new WantDate(new int[]{100000000, 200000000, 300000000, 400000000, 500000000}); //599999958 } static int[] sortIaR(int a[]) // sort int array reverse { return IntStream.of(a).boxed() .sorted(Comparator.reverseOrder()) .mapToInt(i->i).toArray(); } static int[] ria(int N) { // read int array int L[]=new int[N]; for (int i=0; i<N; i++) L[i]=sc.nextInt(); return L; } static Scanner sc = new Scanner(System.in); public static void main(String[] args) { new WantDate(ria(sc.nextInt())); } }
Java
["2\n4 7", "3\n4 3 1"]
2 seconds
["3", "9"]
NoteThere are three non-empty subsets in the first sample test:, and . The first and the second subset increase the sum by 0 and the third subset increases the sum by 7 - 4 = 3. In total the answer is 0 + 0 + 3 = 3.There are seven non-empty subsets in the second sample test. Among them only the following subsets increase the answer: , , , . In total the sum is (4 - 3) + (4 - 1) + (3 - 1) + (4 - 1) = 9.
Java 8
standard input
[ "implementation", "sortings", "math" ]
acff03fe274e819a74b5e9350a859471
The first line contains one integer n (1 ≤ n ≤ 3·105) denoting the number of hacked computers. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) denoting the coordinates of hacked computers. It is guaranteed that all xi are distinct.
1,500
Print a single integer — the required sum modulo 109 + 7.
standard output
PASSED
941191c3346b9df01b187d2561d4244b
train_001.jsonl
1495303500
Leha decided to move to a quiet town Vičkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to n computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on the same straight line, due to the reason that there is the only one straight street in Vičkopolis.Let's denote the coordinate system on this street. Besides let's number all the hacked computers with integers from 1 to n. So the i-th hacked computer is located at the point xi. Moreover the coordinates of all computers are distinct. Leha is determined to have a little rest after a hard week. Therefore he is going to invite his friend Noora to a restaurant. However the girl agrees to go on a date with the only one condition: Leha have to solve a simple task.Leha should calculate a sum of F(a) for all a, where a is a non-empty subset of the set, that consists of all hacked computers. Formally, let's denote A the set of all integers from 1 to n. Noora asks the hacker to find value of the expression . Here F(a) is calculated as the maximum among the distances between all pairs of computers from the set a. Formally, . Since the required sum can be quite large Noora asks to find it modulo 109 + 7.Though, Leha is too tired. Consequently he is not able to solve this task. Help the hacker to attend a date.
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.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.Set; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; public class CF415A { static StringTokenizer st; static BufferedReader br; static PrintWriter pw; static class Sort implements Comparable<Sort> { int ind, a; @Override public int compareTo(Sort o) { return a - o.a; } public Sort(int i, int an) { ind = i; a = an; } } public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); solve(); pw.close(); } static final long MOD = 1000000007; private static void solve() throws IOException { int n = nextInt(); Integer[] a = new Integer [n]; for (int i = 0; i < n; ++i) a[i] = nextInt(); Arrays.sort(a); if (n == 1) pw.println(0); else if (n == 2) { pw.println(a[1] - a[0]); } else { long mult = 1; long sum = 0; for (int i = 1; i < n; ++i) { sum = (sum + mult * a[i]) % MOD; mult = (mult + mult + 1) % MOD; } mult = 1; for (int i = n - 2; i >= 0; --i) { sum = (MOD + sum - (mult * a[i]) % MOD) % MOD; mult = (mult + mult + 1) % MOD; } pw.println(sum); } } private static int sumf(int[] fen, int id) { int summ = 0; for (; id >= 0; id = (id & (id + 1)) - 1) summ += fen[id]; return summ; } private static void addf(int[] fen, int id) { for (; id < fen.length; id |= id + 1) fen[id]++; } 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
["2\n4 7", "3\n4 3 1"]
2 seconds
["3", "9"]
NoteThere are three non-empty subsets in the first sample test:, and . The first and the second subset increase the sum by 0 and the third subset increases the sum by 7 - 4 = 3. In total the answer is 0 + 0 + 3 = 3.There are seven non-empty subsets in the second sample test. Among them only the following subsets increase the answer: , , , . In total the sum is (4 - 3) + (4 - 1) + (3 - 1) + (4 - 1) = 9.
Java 8
standard input
[ "implementation", "sortings", "math" ]
acff03fe274e819a74b5e9350a859471
The first line contains one integer n (1 ≤ n ≤ 3·105) denoting the number of hacked computers. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) denoting the coordinates of hacked computers. It is guaranteed that all xi are distinct.
1,500
Print a single integer — the required sum modulo 109 + 7.
standard output
PASSED
13ebdbee69e29778f629f412cd7dcbdb
train_001.jsonl
1495303500
Leha decided to move to a quiet town Vičkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to n computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on the same straight line, due to the reason that there is the only one straight street in Vičkopolis.Let's denote the coordinate system on this street. Besides let's number all the hacked computers with integers from 1 to n. So the i-th hacked computer is located at the point xi. Moreover the coordinates of all computers are distinct. Leha is determined to have a little rest after a hard week. Therefore he is going to invite his friend Noora to a restaurant. However the girl agrees to go on a date with the only one condition: Leha have to solve a simple task.Leha should calculate a sum of F(a) for all a, where a is a non-empty subset of the set, that consists of all hacked computers. Formally, let's denote A the set of all integers from 1 to n. Noora asks the hacker to find value of the expression . Here F(a) is calculated as the maximum among the distances between all pairs of computers from the set a. Formally, . Since the required sum can be quite large Noora asks to find it modulo 109 + 7.Though, Leha is too tired. Consequently he is not able to solve this task. Help the hacker to attend a date.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.util.Random; import java.io.IOException; 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 { private final static int mod = (int) 1e9 + 7; public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = in.nextInt(); Random random = new Random(); for (int i = 0; i < n; i++) { int j = random.nextInt(n - i) + i; int t = a[i]; a[i] = a[j]; a[j] = t; } Arrays.sort(a); long[] two = new long[n]; two[0] = 1; for (int i = 1; i < n; i++) two[i] = two[i - 1] * 2 % mod; long ans = 0, sum = a[0]; for (int i = 1; i < n; i++) { ans = (ans + (two[i] - 1) * a[i] % mod - sum) % mod; if (ans < 0) ans += mod; sum = (2 * sum + a[i]) % mod; } out.println(ans); } } static class InputReader { private final BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(nextLine()); } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["2\n4 7", "3\n4 3 1"]
2 seconds
["3", "9"]
NoteThere are three non-empty subsets in the first sample test:, and . The first and the second subset increase the sum by 0 and the third subset increases the sum by 7 - 4 = 3. In total the answer is 0 + 0 + 3 = 3.There are seven non-empty subsets in the second sample test. Among them only the following subsets increase the answer: , , , . In total the sum is (4 - 3) + (4 - 1) + (3 - 1) + (4 - 1) = 9.
Java 8
standard input
[ "implementation", "sortings", "math" ]
acff03fe274e819a74b5e9350a859471
The first line contains one integer n (1 ≤ n ≤ 3·105) denoting the number of hacked computers. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) denoting the coordinates of hacked computers. It is guaranteed that all xi are distinct.
1,500
Print a single integer — the required sum modulo 109 + 7.
standard output
PASSED
f7b3a5d185883cac52d614f018d5b276
train_001.jsonl
1495303500
Leha decided to move to a quiet town Vičkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to n computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on the same straight line, due to the reason that there is the only one straight street in Vičkopolis.Let's denote the coordinate system on this street. Besides let's number all the hacked computers with integers from 1 to n. So the i-th hacked computer is located at the point xi. Moreover the coordinates of all computers are distinct. Leha is determined to have a little rest after a hard week. Therefore he is going to invite his friend Noora to a restaurant. However the girl agrees to go on a date with the only one condition: Leha have to solve a simple task.Leha should calculate a sum of F(a) for all a, where a is a non-empty subset of the set, that consists of all hacked computers. Formally, let's denote A the set of all integers from 1 to n. Noora asks the hacker to find value of the expression . Here F(a) is calculated as the maximum among the distances between all pairs of computers from the set a. Formally, . Since the required sum can be quite large Noora asks to find it modulo 109 + 7.Though, Leha is too tired. Consequently he is not able to solve this task. Help the hacker to attend a date.
256 megabytes
import java.util.*; import java.math.*; import java.io.*; public class MainA { public static void main(String[] args) { try(BufferedReader in = new BufferedReader(new InputStreamReader(System.in))){ int n = Integer.parseInt(in.readLine()); BigInteger[] x = new BigInteger[n]; String[] sArr = in.readLine().split(" "); for(int i=0;i<n;i++){ x[i] = new BigInteger(sArr[i]); } Arrays.sort(x); BigInteger res = BigInteger.ZERO; BigInteger mod = BigInteger.valueOf(1000000000L+7L); BigInteger two = BigInteger.valueOf(2L); BigInteger[] twoPow = new BigInteger[n]; twoPow[0] = BigInteger.ONE; for(int i=1;i<n;i++){ twoPow[i] = twoPow[i-1].multiply(two).mod(mod); } for(int i=0;i<n;i++){ res = res.add(x[i].multiply(twoPow[i].subtract(twoPow[n-i-1]).add(mod))).mod(mod); } System.out.println(res.mod(mod)); }catch(IOException e){ e.printStackTrace(); } } }
Java
["2\n4 7", "3\n4 3 1"]
2 seconds
["3", "9"]
NoteThere are three non-empty subsets in the first sample test:, and . The first and the second subset increase the sum by 0 and the third subset increases the sum by 7 - 4 = 3. In total the answer is 0 + 0 + 3 = 3.There are seven non-empty subsets in the second sample test. Among them only the following subsets increase the answer: , , , . In total the sum is (4 - 3) + (4 - 1) + (3 - 1) + (4 - 1) = 9.
Java 8
standard input
[ "implementation", "sortings", "math" ]
acff03fe274e819a74b5e9350a859471
The first line contains one integer n (1 ≤ n ≤ 3·105) denoting the number of hacked computers. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) denoting the coordinates of hacked computers. It is guaranteed that all xi are distinct.
1,500
Print a single integer — the required sum modulo 109 + 7.
standard output
PASSED
0915703bb5d5133b39ed652bbe3dd179
train_001.jsonl
1495303500
Leha decided to move to a quiet town Vičkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to n computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on the same straight line, due to the reason that there is the only one straight street in Vičkopolis.Let's denote the coordinate system on this street. Besides let's number all the hacked computers with integers from 1 to n. So the i-th hacked computer is located at the point xi. Moreover the coordinates of all computers are distinct. Leha is determined to have a little rest after a hard week. Therefore he is going to invite his friend Noora to a restaurant. However the girl agrees to go on a date with the only one condition: Leha have to solve a simple task.Leha should calculate a sum of F(a) for all a, where a is a non-empty subset of the set, that consists of all hacked computers. Formally, let's denote A the set of all integers from 1 to n. Noora asks the hacker to find value of the expression . Here F(a) is calculated as the maximum among the distances between all pairs of computers from the set a. Formally, . Since the required sum can be quite large Noora asks to find it modulo 109 + 7.Though, Leha is too tired. Consequently he is not able to solve this task. Help the hacker to attend a date.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.io.IOException; 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; FastScanner in = new FastScanner(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, FastScanner in, PrintWriter out) { final int MOD = (int) (1e9 + 7); int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } radixSort(a); long ans = 0; long sum = 0; long p2 = 1; // Such idea. Much interesting. Very TL. for (int x : a) { ans = (ans + (p2 - 1) * x) % MOD; if (ans < 0) { ans += MOD; } ans -= sum; if (ans < 0) { ans += MOD; } sum += sum; if (sum >= MOD) { sum -= MOD; } sum += x; if (sum >= MOD) { sum -= MOD; } p2 += p2; if (p2 >= MOD) { p2 -= MOD; } } out.println(ans); } private void radixSort(int[] a) { int[] b = new int[a.length]; int[] c = new int[1 << 16]; int[] s = new int[c.length]; int mask = (1 << 16) - 1; for (int step = 0; step < 2; step++) { Arrays.fill(c, 0); for (int i = 0; i < a.length; i++) { int x = (a[i] >>> (16 * step)) & mask; ++c[x]; } int p = 0; for (int i = 0; i < c.length; i++) { s[i] = p; p += c[i]; } for (int i = 0; i < a.length; i++) { int x = (a[i] >>> (16 * step)) & mask; b[s[x]++] = a[i]; } System.arraycopy(b, 0, a, 0, a.length); } } } static class FastScanner { private BufferedReader in; private StringTokenizer st; public FastScanner(InputStream stream) { in = new BufferedReader(new InputStreamReader(stream)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { String rl = in.readLine(); if (rl == null) { return null; } st = new StringTokenizer(rl); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["2\n4 7", "3\n4 3 1"]
2 seconds
["3", "9"]
NoteThere are three non-empty subsets in the first sample test:, and . The first and the second subset increase the sum by 0 and the third subset increases the sum by 7 - 4 = 3. In total the answer is 0 + 0 + 3 = 3.There are seven non-empty subsets in the second sample test. Among them only the following subsets increase the answer: , , , . In total the sum is (4 - 3) + (4 - 1) + (3 - 1) + (4 - 1) = 9.
Java 8
standard input
[ "implementation", "sortings", "math" ]
acff03fe274e819a74b5e9350a859471
The first line contains one integer n (1 ≤ n ≤ 3·105) denoting the number of hacked computers. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) denoting the coordinates of hacked computers. It is guaranteed that all xi are distinct.
1,500
Print a single integer — the required sum modulo 109 + 7.
standard output
PASSED
e6a508897d26f6030a61c1fe425ad70e
train_001.jsonl
1495303500
Leha decided to move to a quiet town Vičkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to n computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on the same straight line, due to the reason that there is the only one straight street in Vičkopolis.Let's denote the coordinate system on this street. Besides let's number all the hacked computers with integers from 1 to n. So the i-th hacked computer is located at the point xi. Moreover the coordinates of all computers are distinct. Leha is determined to have a little rest after a hard week. Therefore he is going to invite his friend Noora to a restaurant. However the girl agrees to go on a date with the only one condition: Leha have to solve a simple task.Leha should calculate a sum of F(a) for all a, where a is a non-empty subset of the set, that consists of all hacked computers. Formally, let's denote A the set of all integers from 1 to n. Noora asks the hacker to find value of the expression . Here F(a) is calculated as the maximum among the distances between all pairs of computers from the set a. Formally, . Since the required sum can be quite large Noora asks to find it modulo 109 + 7.Though, Leha is too tired. Consequently he is not able to solve this task. Help the hacker to attend a date.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.io.IOException; 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; FastScanner in = new FastScanner(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, FastScanner in, PrintWriter out) { final int MOD = (int) (1e9 + 7); int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } radixSort(a); long ans = 0; long sum = 0; long p2 = 1; // Such idea. Much interesting. Very TL. for (int x : a) { ans = (ans + (p2 - 1) * x) % MOD; if (ans < 0) { ans += MOD; } ans -= sum; if (ans < 0) { ans += MOD; } sum += sum; if (sum >= MOD) { sum -= MOD; } sum += x; if (sum >= MOD) { sum -= MOD; } p2 += p2; if (p2 >= MOD) { p2 -= MOD; } } out.println(ans); } private void radixSort(int[] a) { int[] b = new int[a.length]; int[] c = new int[1 << 16]; int mask = (1 << 16) - 1; for (int step = 0; step < 2; step++) { Arrays.fill(c, 0); for (int i = 0; i < a.length; i++) { int x = (a[i] >>> (16 * step)) & mask; ++c[x]; } int s = 0; for (int i = 0; i < c.length; i++) { int ns = s + c[i]; c[i] = s; s = ns; } for (int i = 0; i < a.length; i++) { int x = (a[i] >>> (16 * step)) & mask; b[c[x]++] = a[i]; } int[] t = a; a = b; b = t; } } } static class FastScanner { private BufferedReader in; private StringTokenizer st; public FastScanner(InputStream stream) { in = new BufferedReader(new InputStreamReader(stream)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { String rl = in.readLine(); if (rl == null) { return null; } st = new StringTokenizer(rl); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["2\n4 7", "3\n4 3 1"]
2 seconds
["3", "9"]
NoteThere are three non-empty subsets in the first sample test:, and . The first and the second subset increase the sum by 0 and the third subset increases the sum by 7 - 4 = 3. In total the answer is 0 + 0 + 3 = 3.There are seven non-empty subsets in the second sample test. Among them only the following subsets increase the answer: , , , . In total the sum is (4 - 3) + (4 - 1) + (3 - 1) + (4 - 1) = 9.
Java 8
standard input
[ "implementation", "sortings", "math" ]
acff03fe274e819a74b5e9350a859471
The first line contains one integer n (1 ≤ n ≤ 3·105) denoting the number of hacked computers. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) denoting the coordinates of hacked computers. It is guaranteed that all xi are distinct.
1,500
Print a single integer — the required sum modulo 109 + 7.
standard output
PASSED
ffcdbe7ec340cdeac51db851049f5934
train_001.jsonl
1495303500
Leha decided to move to a quiet town Vičkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to n computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on the same straight line, due to the reason that there is the only one straight street in Vičkopolis.Let's denote the coordinate system on this street. Besides let's number all the hacked computers with integers from 1 to n. So the i-th hacked computer is located at the point xi. Moreover the coordinates of all computers are distinct. Leha is determined to have a little rest after a hard week. Therefore he is going to invite his friend Noora to a restaurant. However the girl agrees to go on a date with the only one condition: Leha have to solve a simple task.Leha should calculate a sum of F(a) for all a, where a is a non-empty subset of the set, that consists of all hacked computers. Formally, let's denote A the set of all integers from 1 to n. Noora asks the hacker to find value of the expression . Here F(a) is calculated as the maximum among the distances between all pairs of computers from the set a. Formally, . Since the required sum can be quite large Noora asks to find it modulo 109 + 7.Though, Leha is too tired. Consequently he is not able to solve this task. Help the hacker to attend a date.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.StringTokenizer; public class A415 { static long mod = 1_000_000_007; static long twoInv = 500000004; public static void main(String[] args) { FS scan = new FS(System.in); int N = scan.nextInt(); ArrayList<Integer> list = new ArrayList<>(); for(int i=0;i<N;i++)list.add(scan.nextInt()); Collections.sort(list); long[] d = new long[N]; long sum = 0; long two = 1; for(int i=1;i<N;i++){ d[i] = (list.get(i)*two)%mod; two*=2; two%=mod; sum+=d[i]; sum%=mod; } long sol = 0; for(int i=0;i<N-1;i++){ sol+=sum; sol-=(list.get(i)*((exp(2,N-(i+1),mod)-1+mod)%mod)); sol%=mod; sol+=mod; sol%=mod; sum-=list.get(i+1); sum+=mod; sum%=mod; sum*=twoInv; sum%=mod; } System.out.println(sol); } private static long exp(long a, long b, long c) { if(b==0)return 1L; long temp = exp(a,b/2,c); return b%2==0?(temp*temp)%c:(a*((temp*temp)%c))%c; } private static class FS { BufferedReader br; StringTokenizer st; public FS(InputStream in) { br = new BufferedReader(new InputStreamReader(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());} } }
Java
["2\n4 7", "3\n4 3 1"]
2 seconds
["3", "9"]
NoteThere are three non-empty subsets in the first sample test:, and . The first and the second subset increase the sum by 0 and the third subset increases the sum by 7 - 4 = 3. In total the answer is 0 + 0 + 3 = 3.There are seven non-empty subsets in the second sample test. Among them only the following subsets increase the answer: , , , . In total the sum is (4 - 3) + (4 - 1) + (3 - 1) + (4 - 1) = 9.
Java 8
standard input
[ "implementation", "sortings", "math" ]
acff03fe274e819a74b5e9350a859471
The first line contains one integer n (1 ≤ n ≤ 3·105) denoting the number of hacked computers. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) denoting the coordinates of hacked computers. It is guaranteed that all xi are distinct.
1,500
Print a single integer — the required sum modulo 109 + 7.
standard output
PASSED
8f89d3c4ab904b5cbc76c6945eaaa450
train_001.jsonl
1495303500
Leha decided to move to a quiet town Vičkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to n computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on the same straight line, due to the reason that there is the only one straight street in Vičkopolis.Let's denote the coordinate system on this street. Besides let's number all the hacked computers with integers from 1 to n. So the i-th hacked computer is located at the point xi. Moreover the coordinates of all computers are distinct. Leha is determined to have a little rest after a hard week. Therefore he is going to invite his friend Noora to a restaurant. However the girl agrees to go on a date with the only one condition: Leha have to solve a simple task.Leha should calculate a sum of F(a) for all a, where a is a non-empty subset of the set, that consists of all hacked computers. Formally, let's denote A the set of all integers from 1 to n. Noora asks the hacker to find value of the expression . Here F(a) is calculated as the maximum among the distances between all pairs of computers from the set a. Formally, . Since the required sum can be quite large Noora asks to find it modulo 109 + 7.Though, Leha is too tired. Consequently he is not able to solve this task. Help the hacker to attend a date.
256 megabytes
//package round415; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; import java.util.Random; public class A { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(); int[] a = na(n); a = shuffle(a, new Random()); Arrays.sort(a); int mod = 1000000007; long[] cum = new long[n+1]; for(int i = 0;i < n;i++){ cum[i+1] = cum[i] + a[i]; if(cum[i+1] >= mod)cum[i+1] -= mod; } long ret = 0; long po = 1; for(int i = 1;i <= n;i++){ ret += ((cum[n] - cum[i]) - (cum[n-i] - cum[0])) * po; ret %= mod; po = po * 2; if(po >= mod)po -= mod; } ret %= mod; if(ret < 0)ret += mod; out.println(ret%mod); // int[] u = new int[n]; // for(int i = 0;i < 1<<n;i++){ // if(Integer.bitCount(i) >= 2){ // int l = Integer.numberOfTrailingZeros(i); // int r = Integer.numberOfTrailingZeros(Integer.highestOneBit(i)); // u[r]++; // u[l]--; // } // } // tr(u); } public static int[] shuffle(int[] a, Random gen){ for(int i = 0, n = a.length;i < n;i++){ int ind = gen.nextInt(n-i)+i; int d = a[i]; a[i] = a[ind]; a[ind] = d; } return a; } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new A().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["2\n4 7", "3\n4 3 1"]
2 seconds
["3", "9"]
NoteThere are three non-empty subsets in the first sample test:, and . The first and the second subset increase the sum by 0 and the third subset increases the sum by 7 - 4 = 3. In total the answer is 0 + 0 + 3 = 3.There are seven non-empty subsets in the second sample test. Among them only the following subsets increase the answer: , , , . In total the sum is (4 - 3) + (4 - 1) + (3 - 1) + (4 - 1) = 9.
Java 8
standard input
[ "implementation", "sortings", "math" ]
acff03fe274e819a74b5e9350a859471
The first line contains one integer n (1 ≤ n ≤ 3·105) denoting the number of hacked computers. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) denoting the coordinates of hacked computers. It is guaranteed that all xi are distinct.
1,500
Print a single integer — the required sum modulo 109 + 7.
standard output
PASSED
1422351abae229d4a4b3af8eae24ff86
train_001.jsonl
1495303500
Leha decided to move to a quiet town Vičkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to n computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on the same straight line, due to the reason that there is the only one straight street in Vičkopolis.Let's denote the coordinate system on this street. Besides let's number all the hacked computers with integers from 1 to n. So the i-th hacked computer is located at the point xi. Moreover the coordinates of all computers are distinct. Leha is determined to have a little rest after a hard week. Therefore he is going to invite his friend Noora to a restaurant. However the girl agrees to go on a date with the only one condition: Leha have to solve a simple task.Leha should calculate a sum of F(a) for all a, where a is a non-empty subset of the set, that consists of all hacked computers. Formally, let's denote A the set of all integers from 1 to n. Noora asks the hacker to find value of the expression . Here F(a) is calculated as the maximum among the distances between all pairs of computers from the set a. Formally, . Since the required sum can be quite large Noora asks to find it modulo 109 + 7.Though, Leha is too tired. Consequently he is not able to solve this task. Help the hacker to attend a date.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class Solution { static long M=1000000007; public static long exponent(long x,long n) { long y=0; if(n==0) return 1; else if(n==1) return x%M; else { if(n%2==0) {y=exponent(x,n/2); return (((y%M)*(y%M))%M);} else return (((x%M)*(exponent(((x%M)*(x%M))%M,(n-1)/2)%M))%M); } } public static void main (String[] args) throws java.lang.Exception { Scan sn=new Scan(); Print p=new Print(); int n=sn.scanInt(); ArrayList<Long> arr=new ArrayList<Long>(n); for(int i=0;i<n;i++) arr.add((long)sn.scanInt()); Collections.sort(arr); long ans=0; for(int i=0;i<n;i++) { ans=((ans%M)+((arr.get(i)%M)*((exponent(2,(i))-1)%M))%M-((arr.get(i)%M)*((exponent(2,(n-i-1))-1)%M)%M)+M)%M; } p.printLine(Long.toString(ans)); p.close(); } } class Scan { private byte[] buf=new byte[1024]; private int index; private InputStream in; private int total; public Scan() { in=System.in; } public int scan()throws IOException { if(total<0) throw new InputMismatchException(); if(index>=total) { index=0; total=in.read(buf); if(total<=0) return -1; } return buf[index++]; } public int scanInt()throws IOException { int integer=0; int n=scan(); while(isWhiteSpace(n)) n=scan(); int neg=1; if(n=='-') { neg=-1; n=scan(); } while(!isWhiteSpace(n)) { if(n>='0'&&n<='9') { integer*=10; integer+=n-'0'; n=scan(); } else throw new InputMismatchException(); } return neg*integer; } public double scanDouble()throws IOException { double doub=0; int n=scan(); while(isWhiteSpace(n)) n=scan(); int neg=1; if(n=='-') { neg=-1; n=scan(); } while(!isWhiteSpace(n)&&n!='.') { if(n>='0'&&n<='9') { doub*=10; doub+=n-'0'; n=scan(); } else throw new InputMismatchException(); } if(n=='.') { n=scan(); double temp=1; while(!isWhiteSpace(n)) { if(n>='0'&&n<='9') { temp/=10; doub+=(n-'0')*temp; n=scan(); } else throw new InputMismatchException(); } } return doub*neg; } public String scanString()throws IOException { StringBuilder sb=new StringBuilder(); int n=scan(); while(isWhiteSpace(n)) n=scan(); while(!isWhiteSpace(n)) { sb.append((char)n); n=scan(); } return sb.toString(); } private boolean isWhiteSpace(int n) { if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1) return true; return false; } } class Print { private final BufferedWriter bw; public Print() { bw=new BufferedWriter(new OutputStreamWriter(System.out)); } public void print(String str)throws IOException { bw.append(str); } public void printLine(String str)throws IOException { print(str); bw.append("\n"); } public void close()throws IOException { bw.close(); }}
Java
["2\n4 7", "3\n4 3 1"]
2 seconds
["3", "9"]
NoteThere are three non-empty subsets in the first sample test:, and . The first and the second subset increase the sum by 0 and the third subset increases the sum by 7 - 4 = 3. In total the answer is 0 + 0 + 3 = 3.There are seven non-empty subsets in the second sample test. Among them only the following subsets increase the answer: , , , . In total the sum is (4 - 3) + (4 - 1) + (3 - 1) + (4 - 1) = 9.
Java 8
standard input
[ "implementation", "sortings", "math" ]
acff03fe274e819a74b5e9350a859471
The first line contains one integer n (1 ≤ n ≤ 3·105) denoting the number of hacked computers. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) denoting the coordinates of hacked computers. It is guaranteed that all xi are distinct.
1,500
Print a single integer — the required sum modulo 109 + 7.
standard output
PASSED
b34f7299393600e396b66f0ee1e2b8b6
train_001.jsonl
1495303500
Leha decided to move to a quiet town Vičkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to n computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on the same straight line, due to the reason that there is the only one straight street in Vičkopolis.Let's denote the coordinate system on this street. Besides let's number all the hacked computers with integers from 1 to n. So the i-th hacked computer is located at the point xi. Moreover the coordinates of all computers are distinct. Leha is determined to have a little rest after a hard week. Therefore he is going to invite his friend Noora to a restaurant. However the girl agrees to go on a date with the only one condition: Leha have to solve a simple task.Leha should calculate a sum of F(a) for all a, where a is a non-empty subset of the set, that consists of all hacked computers. Formally, let's denote A the set of all integers from 1 to n. Noora asks the hacker to find value of the expression . Here F(a) is calculated as the maximum among the distances between all pairs of computers from the set a. Formally, . Since the required sum can be quite large Noora asks to find it modulo 109 + 7.Though, Leha is too tired. Consequently he is not able to solve this task. Help the hacker to attend a date.
256 megabytes
import java.io.*; import java.util.Arrays; import java.util.Random; import java.util.StringTokenizer; public class Solution { private static String inputFilename = "input.txt"; private static String outputFilename = "output.txt"; private BufferedReader in; private StringTokenizer line; private PrintWriter out; private boolean isDebug; public Solution(boolean isDebug) { this.isDebug = isDebug; } public void solve() throws IOException { int mm = 1000000007; int n = nextInt(); int[] a = nextIntArray(n); Random r = new Random(); for (int i = 1; i < n; i++) { int j = r.nextInt(i); int t = a[i]; a[i] = a[j]; a[j] = t; } Arrays.sort(a); long res = 0; long t = 1; for (int i = 0; i < n; i++) { res = (res + a[i] * t) % mm; t = (t * 2) % mm; } t = 1; for (int i = n - 1; i >= 0; i--) { res = (res - a[i] * t) % mm; t = (t * 2) % mm; } res = (res + mm) % mm; out.println(res); } public static void main(String[] args) throws IOException { new Solution(Arrays.asList(args).contains("DEBUG_MODE")).run(args); } public void run(String[] args) throws IOException { if (isDebug) { in = new BufferedReader(new InputStreamReader(new FileInputStream(inputFilename))); // in = new BufferedReader(new InputStreamReader(System.in)); } else { in = new BufferedReader(new InputStreamReader(System.in)); } out = new PrintWriter(System.out); // out = new PrintWriter(outputFilename); // 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] = nextLong(); } 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(); } }
Java
["2\n4 7", "3\n4 3 1"]
2 seconds
["3", "9"]
NoteThere are three non-empty subsets in the first sample test:, and . The first and the second subset increase the sum by 0 and the third subset increases the sum by 7 - 4 = 3. In total the answer is 0 + 0 + 3 = 3.There are seven non-empty subsets in the second sample test. Among them only the following subsets increase the answer: , , , . In total the sum is (4 - 3) + (4 - 1) + (3 - 1) + (4 - 1) = 9.
Java 8
standard input
[ "implementation", "sortings", "math" ]
acff03fe274e819a74b5e9350a859471
The first line contains one integer n (1 ≤ n ≤ 3·105) denoting the number of hacked computers. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) denoting the coordinates of hacked computers. It is guaranteed that all xi are distinct.
1,500
Print a single integer — the required sum modulo 109 + 7.
standard output
PASSED
af40c328d89e78f7bd3453e07c2eb480
train_001.jsonl
1495303500
Leha decided to move to a quiet town Vičkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to n computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on the same straight line, due to the reason that there is the only one straight street in Vičkopolis.Let's denote the coordinate system on this street. Besides let's number all the hacked computers with integers from 1 to n. So the i-th hacked computer is located at the point xi. Moreover the coordinates of all computers are distinct. Leha is determined to have a little rest after a hard week. Therefore he is going to invite his friend Noora to a restaurant. However the girl agrees to go on a date with the only one condition: Leha have to solve a simple task.Leha should calculate a sum of F(a) for all a, where a is a non-empty subset of the set, that consists of all hacked computers. Formally, let's denote A the set of all integers from 1 to n. Noora asks the hacker to find value of the expression . Here F(a) is calculated as the maximum among the distances between all pairs of computers from the set a. Formally, . Since the required sum can be quite large Noora asks to find it modulo 109 + 7.Though, Leha is too tired. Consequently he is not able to solve this task. Help the hacker to attend a date.
256 megabytes
import java.io.*; import java.math.*; import java.security.KeyStore.Entry; import java.util.*; public class Main { private InputStream is; private PrintWriter out; int MOD = (int)(1e9+7); void solve() { int n = ni(); int arr[] = na(n); long ans = 0; shuffle(arr, new Random()); Arrays.sort(arr); long sum[] = new long[n+1]; sum[0] = 0; for(int i = 1;i<=n;i++){ sum[i] = (power(2,i)-1+MOD)%MOD; } for(int i = 0; i< n; i++){ ans += (arr[i]*(sum[i]))%MOD; ans %=MOD; ans = (ans - (sum[n-1-i]*arr[i])%MOD + MOD)%MOD; } System.out.println(ans%MOD); } public static int[] shuffle(int[] a, Random gen){ for(int i = 0, n = a.length;i < n;i++) { int ind = gen.nextInt(n-i)+i; int d = a[i]; a[i] = a[ind]; a[ind] = d; } return a; } long power(long x, long y){ long ans = 1; while(y>0){ if(y%2==0){ x = (x*x)%MOD; y/=2; } else{ ans = (x*ans)%MOD; y--; } } return ans; } void soln() { is = System.in; out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); //out.close(); out.flush(); //tr(System.currentTimeMillis() - s + "ms"); } public static void main(String[] args) throws Exception { new Main().soln(); } // To Get Input // Some Buffer Methods private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char) skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' // ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n && !(isSpaceChar(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if (!oj) System.out.println(Arrays.deepToString(o)); } }
Java
["2\n4 7", "3\n4 3 1"]
2 seconds
["3", "9"]
NoteThere are three non-empty subsets in the first sample test:, and . The first and the second subset increase the sum by 0 and the third subset increases the sum by 7 - 4 = 3. In total the answer is 0 + 0 + 3 = 3.There are seven non-empty subsets in the second sample test. Among them only the following subsets increase the answer: , , , . In total the sum is (4 - 3) + (4 - 1) + (3 - 1) + (4 - 1) = 9.
Java 8
standard input
[ "implementation", "sortings", "math" ]
acff03fe274e819a74b5e9350a859471
The first line contains one integer n (1 ≤ n ≤ 3·105) denoting the number of hacked computers. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) denoting the coordinates of hacked computers. It is guaranteed that all xi are distinct.
1,500
Print a single integer — the required sum modulo 109 + 7.
standard output
PASSED
1c233fff7ecba4ad34e61dbd1d9b7477
train_001.jsonl
1495303500
Leha decided to move to a quiet town Vičkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to n computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on the same straight line, due to the reason that there is the only one straight street in Vičkopolis.Let's denote the coordinate system on this street. Besides let's number all the hacked computers with integers from 1 to n. So the i-th hacked computer is located at the point xi. Moreover the coordinates of all computers are distinct. Leha is determined to have a little rest after a hard week. Therefore he is going to invite his friend Noora to a restaurant. However the girl agrees to go on a date with the only one condition: Leha have to solve a simple task.Leha should calculate a sum of F(a) for all a, where a is a non-empty subset of the set, that consists of all hacked computers. Formally, let's denote A the set of all integers from 1 to n. Noora asks the hacker to find value of the expression . Here F(a) is calculated as the maximum among the distances between all pairs of computers from the set a. Formally, . Since the required sum can be quite large Noora asks to find it modulo 109 + 7.Though, Leha is too tired. Consequently he is not able to solve this task. Help the hacker to attend a date.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { public int mod = 1000000007; public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); int[] arr = in.readIntArray(n); AUtils.sort(arr); int[] pow2 = new int[n + 1]; pow2[0] = 1; for (int i = 1; i <= n; i++) { pow2[i] = (pow2[i - 1] << 1) % mod; } long ret = 0; for (int i = 0; i + 1 < n; i++) { ret -= 1L * (pow2[n - i - 1] - 1) * arr[i] % mod; if (ret < 0) ret += mod; } for (int i = 1; i < n; i++) { ret += 1L * (pow2[i] - 1) * arr[i] % mod; if (ret >= mod) ret -= mod; } out.println(ret); } } static class AUtils { public static void sort(int[] arr) { for (int i = 1; i < arr.length; i++) { int j = (int) (Math.random() * (i + 1)); if (i != j) { int t = arr[i]; arr[i] = arr[j]; arr[j] = t; } } Arrays.sort(arr); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int[] readIntArray(int tokens) { int[] ret = new int[tokens]; for (int i = 0; i < tokens; i++) { ret[i] = nextInt(); } return ret; } public int read() { if (this.numChars == -1) { throw new InputMismatchException(); } else { if (this.curChar >= this.numChars) { this.curChar = 0; try { this.numChars = this.stream.read(this.buf); } catch (IOException var2) { throw new InputMismatchException(); } if (this.numChars <= 0) { return -1; } } return this.buf[this.curChar++]; } } public int nextInt() { int c; for (c = this.read(); isSpaceChar(c); c = this.read()) { ; } byte sgn = 1; if (c == 45) { sgn = -1; c = this.read(); } int res = 0; while (c >= 48 && c <= 57) { res *= 10; res += c - 48; c = this.read(); if (isSpaceChar(c)) { return res * sgn; } } throw new InputMismatchException(); } public static boolean isSpaceChar(int c) { return c == 32 || c == 10 || c == 13 || c == 9 || c == -1; } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void println(long i) { writer.println(i); } } }
Java
["2\n4 7", "3\n4 3 1"]
2 seconds
["3", "9"]
NoteThere are three non-empty subsets in the first sample test:, and . The first and the second subset increase the sum by 0 and the third subset increases the sum by 7 - 4 = 3. In total the answer is 0 + 0 + 3 = 3.There are seven non-empty subsets in the second sample test. Among them only the following subsets increase the answer: , , , . In total the sum is (4 - 3) + (4 - 1) + (3 - 1) + (4 - 1) = 9.
Java 8
standard input
[ "implementation", "sortings", "math" ]
acff03fe274e819a74b5e9350a859471
The first line contains one integer n (1 ≤ n ≤ 3·105) denoting the number of hacked computers. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) denoting the coordinates of hacked computers. It is guaranteed that all xi are distinct.
1,500
Print a single integer — the required sum modulo 109 + 7.
standard output
PASSED
f0b34c294a4b6ee5658c1b5624ac19fa
train_001.jsonl
1495303500
Leha decided to move to a quiet town Vičkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to n computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on the same straight line, due to the reason that there is the only one straight street in Vičkopolis.Let's denote the coordinate system on this street. Besides let's number all the hacked computers with integers from 1 to n. So the i-th hacked computer is located at the point xi. Moreover the coordinates of all computers are distinct. Leha is determined to have a little rest after a hard week. Therefore he is going to invite his friend Noora to a restaurant. However the girl agrees to go on a date with the only one condition: Leha have to solve a simple task.Leha should calculate a sum of F(a) for all a, where a is a non-empty subset of the set, that consists of all hacked computers. Formally, let's denote A the set of all integers from 1 to n. Noora asks the hacker to find value of the expression . Here F(a) is calculated as the maximum among the distances between all pairs of computers from the set a. Formally, . Since the required sum can be quite large Noora asks to find it modulo 109 + 7.Though, Leha is too tired. Consequently he is not able to solve this task. Help the hacker to attend a date.
256 megabytes
import java.util.*; import java.math.*; import java.io.*; public class Main { public static void main(String[] args) { try(BufferedReader in = new BufferedReader(new InputStreamReader(System.in))){ int n = Integer.parseInt(in.readLine()); BigInteger[] x = new BigInteger[n]; String[] sArr = in.readLine().split(" "); for(int i=0;i<n;i++){ x[i] = new BigInteger(sArr[i]); } Arrays.sort(x); BigInteger res = BigInteger.ZERO; BigInteger mod = BigInteger.valueOf(1000000000L+7L); BigInteger two = BigInteger.valueOf(2L); BigInteger[] twoPow = new BigInteger[n]; twoPow[0] = BigInteger.ONE; for(int i=1;i<n;i++){ twoPow[i] = twoPow[i-1].multiply(two).mod(mod); } for(int i=0;i<n;i++){ res = res.add(x[i].multiply(twoPow[i].subtract(twoPow[n-i-1]).add(mod))).mod(mod); } System.out.println(res.mod(mod)); }catch(IOException e){ e.printStackTrace(); } } }
Java
["2\n4 7", "3\n4 3 1"]
2 seconds
["3", "9"]
NoteThere are three non-empty subsets in the first sample test:, and . The first and the second subset increase the sum by 0 and the third subset increases the sum by 7 - 4 = 3. In total the answer is 0 + 0 + 3 = 3.There are seven non-empty subsets in the second sample test. Among them only the following subsets increase the answer: , , , . In total the sum is (4 - 3) + (4 - 1) + (3 - 1) + (4 - 1) = 9.
Java 8
standard input
[ "implementation", "sortings", "math" ]
acff03fe274e819a74b5e9350a859471
The first line contains one integer n (1 ≤ n ≤ 3·105) denoting the number of hacked computers. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) denoting the coordinates of hacked computers. It is guaranteed that all xi are distinct.
1,500
Print a single integer — the required sum modulo 109 + 7.
standard output
PASSED
1f96bf0b5aac2abf2ea347885593ae3b
train_001.jsonl
1495303500
Leha decided to move to a quiet town Vičkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to n computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on the same straight line, due to the reason that there is the only one straight street in Vičkopolis.Let's denote the coordinate system on this street. Besides let's number all the hacked computers with integers from 1 to n. So the i-th hacked computer is located at the point xi. Moreover the coordinates of all computers are distinct. Leha is determined to have a little rest after a hard week. Therefore he is going to invite his friend Noora to a restaurant. However the girl agrees to go on a date with the only one condition: Leha have to solve a simple task.Leha should calculate a sum of F(a) for all a, where a is a non-empty subset of the set, that consists of all hacked computers. Formally, let's denote A the set of all integers from 1 to n. Noora asks the hacker to find value of the expression . Here F(a) is calculated as the maximum among the distances between all pairs of computers from the set a. Formally, . Since the required sum can be quite large Noora asks to find it modulo 109 + 7.Though, Leha is too tired. Consequently he is not able to solve this task. Help the hacker to attend a date.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.security.SecureRandom; import java.util.*; /** * Created by noureldin on 4/05/17. */ public class Main { private static final int mod = 1000000007; private static int add(int x,int y){ x += y; if(x >= mod) x -= mod; if(x < 0) x += mod; return x; } private static int mul(int a,int b){ return (int)((a*1L*b)%mod); } public static void main(String[] args) throws Exception{ IO io = new IO(null,null); int n = io.getNextInt(); ArrayList<Integer> X = new ArrayList<>(); X.ensureCapacity(n); for (int i = 0;i < n;i++) X.add(io.getNextInt()); Collections.sort(X); int ans = 0,p2 = 1,com = 0; for(int x : X){ ans = add(ans, add(mul(p2-1,x) ,-com)); p2 = add(p2,p2); com = add(add(com,com),x); //System.err.println("ans = " + ans + " p2 = " + p2 + " com = " + com); } io.println(ans); io.close(); } } class IO{ private BufferedReader br; private StringTokenizer st; private PrintWriter writer; private String inputFile,outputFile; public String getNext() throws FileNotFoundException, IOException{ while(st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String getNextLine() throws FileNotFoundException, IOException{ return br.readLine().trim(); } public int getNextInt() throws FileNotFoundException, IOException{ return Integer.parseInt(getNext()); } public long getNextLong() throws FileNotFoundException, IOException{ return Long.parseLong(getNext()); } public void print(double x,int num_digits) throws IOException{ writer.printf("%." + num_digits + "f" ,x); } public void println(double x,int num_digits) throws IOException{ writer.printf("%." + num_digits + "f\n" ,x); } public void print(Object o) throws IOException{ writer.print(o.toString()); } public void println(Object o) throws IOException{ writer.println(o.toString()); } public IO(String x,String y) throws FileNotFoundException, IOException{ inputFile = x; outputFile = y; if(x != null) br = new BufferedReader(new FileReader(inputFile)); else br = new BufferedReader(new InputStreamReader(System.in)); if(y != null) writer = new PrintWriter(new BufferedWriter(new FileWriter(outputFile))); else writer = new PrintWriter(new OutputStreamWriter(System.out)); } protected void close() throws IOException{ br.close(); writer.close(); } }
Java
["2\n4 7", "3\n4 3 1"]
2 seconds
["3", "9"]
NoteThere are three non-empty subsets in the first sample test:, and . The first and the second subset increase the sum by 0 and the third subset increases the sum by 7 - 4 = 3. In total the answer is 0 + 0 + 3 = 3.There are seven non-empty subsets in the second sample test. Among them only the following subsets increase the answer: , , , . In total the sum is (4 - 3) + (4 - 1) + (3 - 1) + (4 - 1) = 9.
Java 8
standard input
[ "implementation", "sortings", "math" ]
acff03fe274e819a74b5e9350a859471
The first line contains one integer n (1 ≤ n ≤ 3·105) denoting the number of hacked computers. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) denoting the coordinates of hacked computers. It is guaranteed that all xi are distinct.
1,500
Print a single integer — the required sum modulo 109 + 7.
standard output
PASSED
f1ccc06ed92b576c363f2acc83c628b1
train_001.jsonl
1429029300
Tavas is a cheerleader in the new sports competition named "Pashmaks". This competition consists of two part: swimming and then running. People will immediately start running R meters after they finished swimming exactly S meters. A winner is a such person that nobody else finishes running before him/her (there may be more than one winner).Before the match starts, Tavas knows that there are n competitors registered for the match. Also, he knows that i-th person's swimming speed is si meters per second and his/her running speed is ri meters per second. Unfortunately, he doesn't know the values of R and S, but he knows that they are real numbers greater than 0.As a cheerleader, Tavas wants to know who to cheer up. So, he wants to know all people that might win. We consider a competitor might win if and only if there are some values of R and S such that with these values, (s)he will be a winner.Tavas isn't really familiar with programming, so he asked you to help him.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class C { private static Comparator<int[]> cmp = new Comparator<int[]>() { @Override public int compare(int[] a, int[] b) { if(a[0] != b[0]) return Integer.compare(a[0], b[0]); else return Integer.compare(a[1], b[1]); } }; public static void main(String [] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter(System.out); int n = Integer.parseInt(reader.readLine()); int [][] competitors = new int[n][]; int [] maxXY = new int[10000+13]; for(int i = 0 ; i < n ; i++) { StringTokenizer tokenizer = new StringTokenizer(reader.readLine()); int s = Integer.parseInt(tokenizer.nextToken()); int r = Integer.parseInt(tokenizer.nextToken()); maxXY[s] = Math.max(maxXY[s], r); competitors[i] = new int[]{s, r}; } int best = 0; int [][] convex = new int[n][]; int sz = 0; for(int i = 10000 ; i >= 1 ; i--) if(maxXY[i] > best) { best = maxXY[i]; while(sz > 1 && ccw(convex[sz-2], convex[sz-1], new int[] {i, maxXY[i]}) < 0) sz--; convex[sz++] = new int[] {i, maxXY[i]}; } Arrays.sort(convex, 0, sz, cmp); boolean [] good = new boolean[n]; for(int i = 0 ; i < n ; i++) if(Arrays.binarySearch(convex, 0, sz, competitors[i], cmp) >= 0) good[i] = true; for(int i = 0 ; i < n ; i++) if(good[i]) writer.print((i+1)+" "); writer.println(); writer.flush(); writer.close(); } private static long ccw(int[] a, int[] b,int[] c) { long u1 = (a[0]-b[0])*1L*(a[1]-c[1]); long u2 = (a[1]-b[1])*1L*(a[0]-c[0]); return Long.compare(u1*b[1]*1L*c[0], u2*b[0]*1L*c[1]); } }
Java
["3\n1 3\n2 2\n3 1", "3\n1 2\n1 1\n2 1"]
1 second
["1 2 3", "1 3"]
null
Java 8
standard input
[ "geometry", "math" ]
e54f8aff8ede309bd591cb9fbd565d1f
The first line of input contains a single integer n (1 ≤ n ≤ 2 × 105). The next n lines contain the details of competitors. i-th line contains two integers si and ri (1 ≤ si, ri ≤ 104).
2,600
In the first and the only line of output, print a sequence of numbers of possible winners in increasing order.
standard output
PASSED
7e0517e87411f0d699db1c5db49ef659
train_001.jsonl
1429029300
Tavas is a cheerleader in the new sports competition named "Pashmaks". This competition consists of two part: swimming and then running. People will immediately start running R meters after they finished swimming exactly S meters. A winner is a such person that nobody else finishes running before him/her (there may be more than one winner).Before the match starts, Tavas knows that there are n competitors registered for the match. Also, he knows that i-th person's swimming speed is si meters per second and his/her running speed is ri meters per second. Unfortunately, he doesn't know the values of R and S, but he knows that they are real numbers greater than 0.As a cheerleader, Tavas wants to know who to cheer up. So, he wants to know all people that might win. We consider a competitor might win if and only if there are some values of R and S such that with these values, (s)he will be a winner.Tavas isn't really familiar with programming, so he asked you to help him.
256 megabytes
import java.util.*; import java.io.*; public class TavasPashmaks { public static void main(String[] args) { FastScanner scanner = new FastScanner(); PrintWriter out = new PrintWriter(System.out,false); int n =scanner.nextInt(); P[] pts = new P[n]; P[] keep = new P[n]; for(int i = 0; i < n; i++) { int a = scanner.nextInt(), b = scanner.nextInt(); pts[i] = new P(a,b); keep[i] = new P(a,b); } P[] uhull = upper(pts); ArrayList<Integer> list= new ArrayList<>(); TreeSet<P> set = new TreeSet<>(); for(int i = 0; i < p; i++) { set.add(uhull[i]); } for(int i = 0; i < n; i++) { if (set.contains(keep[i])) list.add(1+i); } Collections.sort(list); for(int i = 0; i < list.size(); i++) { if (i > 0) out.print(" "); out.print(list.get(i)); } out.println(); out.flush(); } static class P implements Comparable<P>{ long x, y; public P (long xx, long yy) { x = xx; y = yy; } public int compareTo(P o) { if (x == o.x) return Long.compare(y,o.y); return Long.compare(x, o.x); } long det(P other) {return x *other.y - y * other.x;} static long comp(P a, P b, P c) { long mx = a.x * b.x * c.x; long my = a.y * b.y * c.y; P pa = new P(mx / a.x, my / a.y); P pb = new P(mx / b.x, my / b.y); P pc = new P(mx / c.x, my / c.y); return temp(pc, pb, pa); } static long temp(P a, P b, P c) { return new P(b.x-a.x, b.y-a.y).det(new P(c.x-a.x,c.y-a.y)); } } static int p = 0; static P[] upper (P[] pts) { Arrays.sort(pts); int N = pts.length; P[] up = new P[N]; for(int i = 0; i < N; i++) { while(p > 0 && up[p-1].y <= pts[i].y) p--; while(p > 1 && P.comp(up[p-2], up[p-1], pts[i]) < 0) { p--; } up[p++] = pts[i]; } return up; } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(Reader in) { br = new BufferedReader(in); } public FastScanner() { this(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String readNextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n1 3\n2 2\n3 1", "3\n1 2\n1 1\n2 1"]
1 second
["1 2 3", "1 3"]
null
Java 8
standard input
[ "geometry", "math" ]
e54f8aff8ede309bd591cb9fbd565d1f
The first line of input contains a single integer n (1 ≤ n ≤ 2 × 105). The next n lines contain the details of competitors. i-th line contains two integers si and ri (1 ≤ si, ri ≤ 104).
2,600
In the first and the only line of output, print a sequence of numbers of possible winners in increasing order.
standard output
PASSED
6d84586f798381f88a7c54915267002a
train_001.jsonl
1429029300
Tavas is a cheerleader in the new sports competition named "Pashmaks". This competition consists of two part: swimming and then running. People will immediately start running R meters after they finished swimming exactly S meters. A winner is a such person that nobody else finishes running before him/her (there may be more than one winner).Before the match starts, Tavas knows that there are n competitors registered for the match. Also, he knows that i-th person's swimming speed is si meters per second and his/her running speed is ri meters per second. Unfortunately, he doesn't know the values of R and S, but he knows that they are real numbers greater than 0.As a cheerleader, Tavas wants to know who to cheer up. So, he wants to know all people that might win. We consider a competitor might win if and only if there are some values of R and S such that with these values, (s)he will be a winner.Tavas isn't really familiar with programming, so he asked you to help him.
256 megabytes
import java.util.*; import java.io.*; public class runswim { private static final int INF = (int)1e9; private static class Pt implements Comparable <Pt> { double x; double y; public Pt(double a, double b){ x = a; y = b; } public int compareTo(Pt arg0) { int t = Double.compare(x, arg0.x); if(t!=0)return t; return Double.compare(y, arg0.y); } public static boolean ccw(Pt o, Pt a, Pt b){ return (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x) >= 0; } public String toString(){ return "(" + x + ", " + y + ")"; } private static final double EPS = 1e-6; public static boolean equals(double a, double b){ return Math.abs(a-b) <= EPS * Math.max(1.0, Math.max(a,b)); } public static Pt[] lowerHull(Pt[] points, boolean keepVertical){ /** * MODIFIES input array quite nontrivially */ //be careful about vertical ones. Arrays.sort(points); int start = 0; int end = points.length; if(keepVertical){ //we can't miss out on all vertical ones at the end } else{ // //we have all vertical ones at the beginning and need to delete them //actually, no. // double x0 = points[0].x; // while(equals(points[start+1].x, x0)){ // start++; // } } ArrayList<Pt> Q = new ArrayList<Pt>(); for(int i=start;i<end;i++){ Pt p = points[i]; while(Q.size() >= 2 && ccw(Q.get(Q.size() - 1), Q.get(Q.size() - 2), p)){ Q.remove(Q.size() - 1); } Q.add(p); } Pt[] ans = new Pt[Q.size()]; for(int i=0;i<Q.size();i++){ ans[i] = Q.get(i); } return ans; } } public static void main(String[] args) throws IOException { BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); int N = Integer.parseInt(f.readLine()); TreeMap<Pt, ArrayList<Integer>> M = new TreeMap<Pt, ArrayList<Integer>>(); Pt[] points = new Pt[N]; for(int i=0;i<N;i++){ StringTokenizer st = new StringTokenizer(f.readLine()); double swim = Integer.parseInt(st.nextToken()); double run = Integer.parseInt(st.nextToken()); swim = 100/swim; run = 100/run; double x = swim; double y = run; Pt p = new Pt(x,y); points[i] = p; if(!M.containsKey(p)){ M.put(p, new ArrayList<Integer>()); } M.get(p).add(i+1); } Pt[] hull = Pt.lowerHull(points, false); ArrayList<Integer> answers = new ArrayList<Integer>(); // for(Pt p : hull){ // System.out.println(p); // } for(int i=0;i<hull.length;i++){ answers.addAll(M.get(hull[i])); if(i != hull.length - 1 && (hull[i+1].y > hull[i].y || Pt.equals(hull[i+1].y, hull[i].y))){ // System.out.println(hull[i+1].y + " " + hull[i].y); break; } } Collections.sort(answers); for(int t : answers){ System.out.print(t + " "); } } }
Java
["3\n1 3\n2 2\n3 1", "3\n1 2\n1 1\n2 1"]
1 second
["1 2 3", "1 3"]
null
Java 8
standard input
[ "geometry", "math" ]
e54f8aff8ede309bd591cb9fbd565d1f
The first line of input contains a single integer n (1 ≤ n ≤ 2 × 105). The next n lines contain the details of competitors. i-th line contains two integers si and ri (1 ≤ si, ri ≤ 104).
2,600
In the first and the only line of output, print a sequence of numbers of possible winners in increasing order.
standard output
PASSED
e919e8b2843d0adc0c98213347ce09ab
train_001.jsonl
1429029300
Tavas is a cheerleader in the new sports competition named "Pashmaks". This competition consists of two part: swimming and then running. People will immediately start running R meters after they finished swimming exactly S meters. A winner is a such person that nobody else finishes running before him/her (there may be more than one winner).Before the match starts, Tavas knows that there are n competitors registered for the match. Also, he knows that i-th person's swimming speed is si meters per second and his/her running speed is ri meters per second. Unfortunately, he doesn't know the values of R and S, but he knows that they are real numbers greater than 0.As a cheerleader, Tavas wants to know who to cheer up. So, he wants to know all people that might win. We consider a competitor might win if and only if there are some values of R and S such that with these values, (s)he will be a winner.Tavas isn't really familiar with programming, so he asked you to help him.
256 megabytes
import java.util.*; import static java.lang.Math.*; import java.io.*; public class C { public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer stok = new StringTokenizer(in.readLine()); int N = Integer.valueOf(stok.nextToken()); Person[] P = new Person[N]; for (int i = 0; i < N; i++) { stok = new StringTokenizer(in.readLine()); int s = Integer.valueOf(stok.nextToken()); int r = Integer.valueOf(stok.nextToken()); P[i] = new Person(s, r, i + 1); } Arrays.sort(P); ArrayList<Person> S = new ArrayList<Person>(); Person prev = null; for (Person p : P) { //System.out.println(p); if (prev != null && p.compareTo(prev) == 0) { //System.out.println("pre"); prev.idxs.addAll(p.idxs); continue; } prev = p; if (S.size() > 0) { Person last = S.get(S.size() - 1); if (last.s >= p.s && last.r >= p.r) { //System.out.println("dominated"); continue; } } S.add(p); while (S.size() >= 3 && ccw(S.get(S.size() - 3), S.get(S.size() - 2), S.get(S.size() -1))) { S.remove(S.size() - 2); } } //System.out.println(S); StringBuffer anss = new StringBuffer(""); ArrayList<Integer> ans = new ArrayList<Integer>(); for (Person p : S) for (int idx : p.idxs) ans.add(idx); Collections.sort(ans); for (int a : ans) anss.append(a+" "); System.out.println(anss); } static boolean ccw(Person a, Person b, Person c) { return a.s * c.r * (a.r - b.r) * (b.s - c.s) < (a.s - b.s) * (b.r - c.r) * a.r * c.s; } static class Person implements Comparable<Person> { long s, r; ArrayList<Integer> idxs; public Person(int s, int r, int idx) { this.s = s; this.r = r; this.idxs = new ArrayList<Integer>(); this.idxs.add(idx); } public int compareTo(Person p) { if (r > p.r) return -1; if (r < p.r) return 1; if (s > p.s) return -1; if (s < p.s) return 1; return 0; } public String toString() { return String.format("(%d, %d, %s)", s, r, idxs); } } }
Java
["3\n1 3\n2 2\n3 1", "3\n1 2\n1 1\n2 1"]
1 second
["1 2 3", "1 3"]
null
Java 8
standard input
[ "geometry", "math" ]
e54f8aff8ede309bd591cb9fbd565d1f
The first line of input contains a single integer n (1 ≤ n ≤ 2 × 105). The next n lines contain the details of competitors. i-th line contains two integers si and ri (1 ≤ si, ri ≤ 104).
2,600
In the first and the only line of output, print a sequence of numbers of possible winners in increasing order.
standard output
PASSED
e79ad20fd66deca22f1d9104758e475a
train_001.jsonl
1429029300
Tavas is a cheerleader in the new sports competition named "Pashmaks". This competition consists of two part: swimming and then running. People will immediately start running R meters after they finished swimming exactly S meters. A winner is a such person that nobody else finishes running before him/her (there may be more than one winner).Before the match starts, Tavas knows that there are n competitors registered for the match. Also, he knows that i-th person's swimming speed is si meters per second and his/her running speed is ri meters per second. Unfortunately, he doesn't know the values of R and S, but he knows that they are real numbers greater than 0.As a cheerleader, Tavas wants to know who to cheer up. So, he wants to know all people that might win. We consider a competitor might win if and only if there are some values of R and S such that with these values, (s)he will be a winner.Tavas isn't really familiar with programming, so he asked you to help him.
256 megabytes
import java.io.*; import java.util.*; public class C { class Competitor implements Comparable<Competitor> { int id; int s, r; Competitor next; Competitor(int id, int s, int r) { this.id = id; this.s = s; this.r = r; } public int compareTo(Competitor c) { int d = c.s - s; if (d == 0) d = c.r - r; return d; } } class Fraction implements Comparable<Fraction> { long p, q; Fraction(long p, long q) { this.p = p; this.q = q; } public int compareTo(Fraction f) { long d = p * f.q - f.p * q; if (d < 0) return -1; if (d > 0) return 1; return 0; } } Fraction intersect(Competitor a, Competitor b) { long p = (long) a.s * b.s * (b.r - a.r); long q = a.s * b.r - b.s * a.r; if (q < 0) { p = -p; q = -q; } return new Fraction(p, q); } void solve() throws IOException { in = new InputReader("__std"); out = new OutputWriter("__std"); int n = in.readInt(); Competitor[] c = new Competitor[n]; for (int i = 0; i < n; ++i) { c[i] = new Competitor(i, in.readInt(), in.readInt()); } Arrays.sort(c); int m = 1; for (int i = 1; i < n; ++i) { if (c[i].s == c[m - 1].s && c[i].r == c[m - 1].r) { c[i].next = c[m - 1].next; c[m - 1].next = c[i]; } else { c[m++] = c[i]; } } int k = 1; for (int i = 1; i < m; ++i) { if (c[i].r > c[k - 1].r) { while (k > 1) { Fraction x1 = intersect(c[i], c[k - 2]); Fraction x2 = intersect(c[k - 1], c[k - 2]); if (x2.compareTo(x1) >= 0) break; --k; } c[k++] = c[i]; } } boolean[] mask = new boolean[n]; for (int i = 0; i < k; ++i) { Competitor cur = c[i]; while (cur != null) { mask[cur.id] = true; cur = cur.next; } } for (int i = 0; i < n; ++i) { if (mask[i]) out.print((i + 1) + " "); } exit(); } void exit() { //System.err.println((System.currentTimeMillis() - startTime) + " ms"); out.close(); System.exit(0); } InputReader in; OutputWriter out; //long startTime = System.currentTimeMillis(); public static void main(String[] args) throws IOException { new C().solve(); } class InputReader { private InputStream stream; private byte[] buffer = new byte[1024]; private int pos, len; private int cur; private StringBuilder sb = new StringBuilder(32); InputReader(String name) throws IOException { if (name.equals("__std")) { stream = System.in; } else { stream = new FileInputStream(name); } cur = read(); } private int read() throws IOException { if (len == -1) { throw new EOFException(); } if (pos >= len) { pos = 0; len = stream.read(buffer); if (len == -1) return -1; } return buffer[pos++]; } private boolean whitespace() { return cur == ' ' || cur == '\t' || cur == '\r' || cur == '\n' || cur == -1; } char readChar() throws IOException { if (cur == -1) { throw new EOFException(); } char res = (char) cur; cur = read(); return res; } int readInt() throws IOException { if (cur == -1) { throw new EOFException(); } while (whitespace()) { cur = read(); } if (cur == -1) { throw new EOFException(); } int sign = 1; if (cur == '-') { sign = -1; cur = read(); } int res = 0; while (!whitespace()) { if (cur < '0' || cur > '9') { throw new NumberFormatException(); } res *= 10; res += cur - '0'; cur = read(); } return res * sign; } long readLong() throws IOException { if (cur == -1) { throw new EOFException(); } return Long.parseLong(readToken()); } double readDouble() throws IOException { if (cur == -1) { throw new EOFException(); } return Double.parseDouble(readToken()); } String readLine() throws IOException { if (cur == -1) { throw new EOFException(); } sb.setLength(0); while (cur != -1 && cur != '\r' && cur != '\n') { sb.append((char) cur); cur = read(); } if (cur == '\r') { cur = read(); } if (cur == '\n') { cur = read(); } return sb.toString(); } String readToken() throws IOException { if (cur == -1) { throw new EOFException(); } while (whitespace()) { cur = read(); } if (cur == -1) { throw new EOFException(); } sb.setLength(0); while (!whitespace()) { sb.append((char) cur); cur = read(); } return sb.toString(); } boolean eof() { return cur == -1; } } class OutputWriter { private PrintWriter writer; OutputWriter(String name) throws IOException { if (name.equals("__std")) { writer = new PrintWriter(System.out); } else { writer = new PrintWriter(name); } } void print(String format, Object ... args) { writer.print(new Formatter(Locale.US).format(format, args)); } void println(String format, Object ... args) { writer.println(new Formatter(Locale.US).format(format, args)); } void print(Object value) { writer.print(value); } void println(Object value) { writer.println(value); } void println() { writer.println(); } void close() { writer.close(); } } }
Java
["3\n1 3\n2 2\n3 1", "3\n1 2\n1 1\n2 1"]
1 second
["1 2 3", "1 3"]
null
Java 8
standard input
[ "geometry", "math" ]
e54f8aff8ede309bd591cb9fbd565d1f
The first line of input contains a single integer n (1 ≤ n ≤ 2 × 105). The next n lines contain the details of competitors. i-th line contains two integers si and ri (1 ≤ si, ri ≤ 104).
2,600
In the first and the only line of output, print a sequence of numbers of possible winners in increasing order.
standard output
PASSED
2ed0d1e09eb1258641a7de2a0d4097f4
train_001.jsonl
1429029300
Tavas is a cheerleader in the new sports competition named "Pashmaks". This competition consists of two part: swimming and then running. People will immediately start running R meters after they finished swimming exactly S meters. A winner is a such person that nobody else finishes running before him/her (there may be more than one winner).Before the match starts, Tavas knows that there are n competitors registered for the match. Also, he knows that i-th person's swimming speed is si meters per second and his/her running speed is ri meters per second. Unfortunately, he doesn't know the values of R and S, but he knows that they are real numbers greater than 0.As a cheerleader, Tavas wants to know who to cheer up. So, he wants to know all people that might win. We consider a competitor might win if and only if there are some values of R and S such that with these values, (s)he will be a winner.Tavas isn't really familiar with programming, so he asked you to help him.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; 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); Task solver = new Task(); solver.solve(1, in, out); out.close(); } } class Task { public void solve(int testNumber, InputReader in, OutputWriter out) { int n=in.readInt(); Map<Point, List<Integer>> map=new HashMap<>(); double min=Double.MAX_VALUE; for (int i=0; i<n; i++) { Point p=new Point(1.0/in.readInt(), 1.0/in.readInt()); min=Math.min(min, p.y); if (!map.containsKey(p)) map.put(p, new ArrayList<Integer>()); map.get(p).add(i+1); } List<Integer> list=new ArrayList<>(); List<Point> points=new ArrayList<>(); GeometryUtils.epsilon=1e-16; for (Point i:Polygon.convexHull(map.keySet().toArray(new Point[0])).vertices) points.add(i); Point aux=points.get(0); points.remove(0); Collections.reverse(points); points.add(0, aux); for (Point i: points) { list.addAll(map.get(i)); if (Math.abs(min-i.y)<GeometryUtils.epsilon) break; } Collections.sort(list); // out.printLine(map); out.printLine(list); } } class InputReader { private boolean finished = false; private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int peek() { if (numChars == -1) return -1; if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { return -1; } if (numChars <= 0) return -1; } return buf[curChar]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long readLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private String readLine0() { StringBuilder buf = new StringBuilder(); int c = read(); while (c != '\n' && c != -1) { if (c != '\r') buf.appendCodePoint(c); c = read(); } return buf.toString(); } public String readLine() { String s = readLine0(); while (s.trim().length() == 0) s = readLine0(); return s; } public String readLine(boolean ignoreEmptyLines) { if (ignoreEmptyLines) return readLine(); else return readLine0(); } public BigInteger readBigInteger() { try { return new BigInteger(readString()); } catch (NumberFormatException e) { throw new InputMismatchException(); } } public char readCharacter() { int c = read(); while (isSpaceChar(c)) c = read(); return (char) c; } public double readDouble() { 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, readInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, readInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public boolean isExhausted() { int value; while (isSpaceChar(value = peek()) && value != -1) read(); return value == -1; } public String next() { return readString(); } public SpaceCharFilter getFilter() { return filter; } public void setFilter(SpaceCharFilter filter) { this.filter = filter; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter( outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(char[] array) { writer.print(array); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void print(int[] array) { for (int i = 0; i < array.length; i++) { if (i != 0) writer.print(' '); writer.print(array[i]); } } public void print(long[] array) { for (int i = 0; i < array.length; i++) { if (i != 0) writer.print(' '); writer.print(array[i]); } } public void print(Collection<Integer> collection) { boolean first = true; for (int i : collection) { if (first) first = false; else writer.print(' '); writer.print(i); } } public void printLine(int[] array) { print(array); writer.println(); } public void printLine(long[] array) { print(array); writer.println(); } public void printLine(Collection<Integer> collection) { print(collection); writer.println(); } public void printLine() { writer.println(); } public void printLine(Object... objects) { print(objects); writer.println(); } public void print(char i) { writer.print(i); } public void printLine(char i) { writer.println(i); } public void printLine(char[] array) { writer.println(array); } public void printFormat(String format, Object... objects) { writer.printf(format, objects); } public void close() { writer.close(); } public void flush() { writer.flush(); } public void print(long i) { writer.print(i); } public void printLine(long i) { writer.println(i); } public void print(int i) { writer.print(i); } public void printLine(int i) { writer.println(i); } } class Polygon { public final Point[] vertices; private Segment[] sides; public Polygon(Point...vertices) { this.vertices = vertices.clone(); } public double square() { double sum = 0; for (int i = 1; i < vertices.length; i++) sum += (vertices[i].x - vertices[i - 1].x) * (vertices[i].y + vertices[i - 1].y); sum += (vertices[0].x - vertices[vertices.length - 1].x) * (vertices[0].y + vertices[vertices.length - 1].y); return Math.abs(sum) / 2; } public Point center() { double sx = 0; double sy = 0; for (Point point : vertices) { sx += point.x; sy += point.y; } return new Point(sx / vertices.length, sy / vertices.length); } public static boolean over(Point a, Point b, Point c) { return a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y) < -GeometryUtils.epsilon; } private static boolean under(Point a, Point b, Point c) { return a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y) > GeometryUtils.epsilon; } public static Polygon convexHull(Point[] points) { if (points.length == 1) return new Polygon(points); Arrays.sort(points, new Comparator<Point>() { public int compare(Point o1, Point o2) { int value = Double.compare(o1.x, o2.x); if (value != 0) return value; return Double.compare(o1.y, o2.y); } }); Point left = points[0]; Point right = points[points.length - 1]; List<Point> up = new ArrayList<Point>(); List<Point> down = new ArrayList<Point>(); for (Point point : points) { if (point == left || point == right || !under(left, point, right)) { while (up.size() >= 2 && under(up.get(up.size() - 2), up.get(up.size() - 1), point)) up.remove(up.size() - 1); up.add(point); } if (point == left || point == right || !over(left, point, right)) { while (down.size() >= 2 && over(down.get(down.size() - 2), down.get(down.size() - 1), point)) down.remove(down.size() - 1); down.add(point); } } Point[] result = new Point[up.size() + down.size() - 2]; int index = 0; for (Point point : up) result[index++] = point; for (int i = down.size() - 2; i > 0; i--) result[index++] = down.get(i); return new Polygon(result); } public boolean contains(Point point) { return contains(point, false); } public boolean contains(Point point, boolean strict) { for (Segment segment : sides()) { if (segment.contains(point, true)) return !strict; } double totalAngle = GeometryUtils.canonicalAngle(Math.atan2(vertices[0].y - point.y, vertices[0].x - point.x) - Math.atan2(vertices[vertices.length - 1].y - point.y, vertices[vertices.length - 1].x - point.x)); for (int i = 1; i < vertices.length; i++) { totalAngle += GeometryUtils.canonicalAngle(Math.atan2(vertices[i].y - point.y, vertices[i].x - point.x) - Math.atan2(vertices[i - 1].y - point.y, vertices[i - 1].x - point.x)); } return Math.abs(totalAngle) > Math.PI; } public Segment[] sides() { if (sides == null) { sides = new Segment[vertices.length]; for (int i = 0; i < vertices.length - 1; i++) sides[i] = new Segment(vertices[i], vertices[i + 1]); sides[sides.length - 1] = new Segment(vertices[vertices.length - 1], vertices[0]); } return sides; } public static double triangleSquare(Point a, Point b, Point c) { return Math.abs((a.x - b.x) * (a.y + b.y) + (b.x - c.x) * (b.y + c.y) + (c.x - a.x) * (c.y + a.y)) / 2; } public double perimeter() { double result = vertices[0].distance(vertices[vertices.length - 1]); for (int i = 1; i < vertices.length; i++) result += vertices[i].distance(vertices[i - 1]); return result; } } class Point { public static final Point ORIGIN = new Point(0, 0); public final double x; public final double y; @Override public String toString() { return "(" + x + ", " + y + ")"; } public Point(double x, double y) { this.x = x; this.y = y; } public Line line(Point other) { if (equals(other)) return null; double a = other.y - y; double b = x - other.x; double c = -a * x - b * y; return new Line(a, b, c); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Point point = (Point) o; return Math.abs(x - point.x) <= GeometryUtils.epsilon && Math.abs(y - point.y) <= GeometryUtils.epsilon; } @Override public int hashCode() { int result; long temp; temp = x != +0.0d ? Double.doubleToLongBits(x) : 0L; result = (int) (temp ^ (temp >>> 32)); temp = y != +0.0d ? Double.doubleToLongBits(y) : 0L; result = 31 * result + (int) (temp ^ (temp >>> 32)); return result; } public double distance(Point other) { return GeometryUtils.fastHypot(x - other.x, y - other.y); } public double distance(Line line) { return Math.abs(line.a * x + line.b * y + line.c); } public double value() { return GeometryUtils.fastHypot(x, y); } public double angle() { return Math.atan2(y, x); } public static Point readPoint(InputReader in) { double x = in.readDouble(); double y = in.readDouble(); return new Point(x, y); } public Point rotate(double angle) { double nx = x * Math.cos(angle) - y * Math.sin(angle); double ny = y * Math.cos(angle) + x * Math.sin(angle); return new Point(nx, ny); } } class Segment { public final Point a; public final Point b; private double distance = Double.NaN; private Line line = null; public Segment(Point a, Point b) { this.a = a; this.b = b; } public double length() { if (Double.isNaN(distance)) distance = a.distance(b); return distance; } public double distance(Point point) { double length = length(); double left = point.distance(a); if (length < GeometryUtils.epsilon) return left; double right = point.distance(b); if (left * left > right * right + length * length) return right; if (right * right > left * left + length * length) return left; return point.distance(line()); } public Point intersect(Segment other, boolean includeEnds) { Line line = line(); Line otherLine = other.a.line(other.b); if (line.parallel(otherLine)) return null; Point intersection = line.intersect(otherLine); if (contains(intersection, includeEnds) && other.contains(intersection, includeEnds)) return intersection; else return null; } public boolean contains(Point point, boolean includeEnds) { if (a.equals(point) || b.equals(point)) return includeEnds; if (a.equals(b)) return false; Line line = line(); if (!line.contains(point)) return false; Line perpendicular = line.perpendicular(a); double aValue = perpendicular.value(a); double bValue = perpendicular.value(b); double pointValue = perpendicular.value(point); return aValue < pointValue && pointValue < bValue || bValue < pointValue && pointValue < aValue; } public Line line() { if (line == null) line = a.line(b); return line; } public Point middle() { return new Point((a.x + b.x) / 2, (a.y + b.y) / 2); } public Point[] intersect(Circle circle) { Point[] result = line().intersect(circle); if (result.length == 0) return result; if (result.length == 1) { if (contains(result[0], true)) return result; return new Point[0]; } if (contains(result[0], true)) { if (contains(result[1], true)) return result; return new Point[]{result[0]}; } if (contains(result[1], true)) return new Point[]{result[1]}; return new Point[0]; } public Point intersect(Line line) { Line selfLine = line(); Point intersect = selfLine.intersect(line); if (intersect == null) return null; if (contains(intersect, true)) return intersect; return null; } public double distance(Segment other) { Line line = line(); Line otherLine = other.line(); Point p = line == null || otherLine == null ? null : line.intersect(otherLine); if (p != null && contains(p, true) && other.contains(p, true)) return 0; return Math.min(Math.min(other.distance(a), other.distance(b)), Math.min(distance(other.a), distance(other.b))); } } class GeometryUtils { public static double epsilon = 1e-8; public static double fastHypot(double...x) { if (x.length == 0) return 0; else if (x.length == 1) return Math.abs(x[0]); else { double sumSquares = 0; for (double value : x) sumSquares += value * value; return Math.sqrt(sumSquares); } } public static double fastHypot(double x, double y) { return Math.sqrt(x * x + y * y); } public static double fastHypot(double[] x, double[] y) { if (x.length == 0) return 0; else if (x.length == 1) return Math.abs(x[0]- y[0]); else { double sumSquares = 0; for (int i = 0; i < x.length; i++) { double diff = x[i] - y[i]; sumSquares += diff * diff; } return Math.sqrt(sumSquares); } } public static double fastHypot(int[] x, int[] y) { if (x.length == 0) return 0; else if (x.length == 1) return Math.abs(x[0]- y[0]); else { double sumSquares = 0; for (int i = 0; i < x.length; i++) { double diff = x[i] - y[i]; sumSquares += diff * diff; } return Math.sqrt(sumSquares); } } public static double missileTrajectoryLength(double v, double angle, double g) { return (v * v * Math.sin(2 * angle)) / g; } public static double sphereVolume(double radius) { return 4 * Math.PI * radius * radius * radius / 3; } public static double triangleSquare(double first, double second, double third) { double p = (first + second + third) / 2; return Math.sqrt(p * (p - first) * (p - second) * (p - third)); } public static double canonicalAngle(double angle) { while (angle > Math.PI) angle -= 2 * Math.PI; while (angle < -Math.PI) angle += 2 * Math.PI; return angle; } public static double positiveAngle(double angle) { while (angle > 2 * Math.PI - GeometryUtils.epsilon) angle -= 2 * Math.PI; while (angle < -GeometryUtils.epsilon) angle += 2 * Math.PI; return angle; } } class Line { public final double a; public final double b; public final double c; public Line(Point p, double angle) { a = Math.sin(angle); b = -Math.cos(angle); c = -p.x * a - p.y * b; } public Line(double a, double b, double c) { double h = GeometryUtils.fastHypot(a, b); this.a = a / h; this.b = b / h; this.c = c / h; } public Point intersect(Line other) { if (parallel(other)) return null; double determinant = b * other.a - a * other.b; double x = (c * other.b - b * other.c) / determinant; double y = (a * other.c - c * other.a) / determinant; return new Point(x, y); } public boolean parallel(Line other) { return Math.abs(a * other.b - b * other.a) < GeometryUtils.epsilon; } public boolean contains(Point point) { return Math.abs(value(point)) < GeometryUtils.epsilon; } public Line perpendicular(Point point) { return new Line(-b, a, b * point.x - a * point.y); } public double value(Point point) { return a * point.x + b * point.y + c; } public Point[] intersect(Circle circle) { double distance = distance(circle.center); if (distance > circle.radius + GeometryUtils.epsilon) return new Point[0]; Point intersection = intersect(perpendicular(circle.center)); if (Math.abs(distance - circle.radius) < GeometryUtils.epsilon) return new Point[]{intersection}; double shift = Math.sqrt(circle.radius * circle.radius - distance * distance); return new Point[]{new Point(intersection.x + shift * b, intersection.y - shift * a), new Point(intersection.x - shift * b, intersection.y + shift * a)}; } public double distance(Point center) { return Math.abs(value(center)); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Line line = (Line) o; if (!parallel(line)) return false; if (Math.abs(a * line.c - c * line.a) > GeometryUtils.epsilon || Math.abs(b * line.c - c * line.b) > GeometryUtils.epsilon) return false; return true; } } class Circle { public final Point center; public final double radius; public Circle(Point center, double radius) { this.center = center; this.radius = radius; } public boolean contains(Point point) { return center.distance(point) < radius + GeometryUtils.epsilon; } public boolean strictContains(Point point) { return center.distance(point) < radius - GeometryUtils.epsilon; } public Point[] findTouchingPoints(Point point) { double distance = center.distance(point); if (distance < radius - GeometryUtils.epsilon) return new Point[0]; if (distance < radius + GeometryUtils.epsilon) return new Point[]{point}; Circle power = new Circle(point, Math.sqrt((distance - radius) * (distance + radius))); return intersect(power); } public Point[] intersect(Circle other) { double distance = center.distance(other.center); if (distance > radius + other.radius + GeometryUtils.epsilon || Math.abs(radius - other.radius) > distance + GeometryUtils.epsilon) return new Point[0]; double p = (radius + other.radius + distance) / 2; double height = 2 * Math.sqrt(p * (p - radius) * (p - other.radius) * (p - distance)) / distance; double l1 = Math.sqrt(radius * radius - height * height); double l2 = Math.sqrt(other.radius * other.radius - height * height); if (radius * radius + distance * distance < other.radius * other.radius) l1 = -l1; if (radius * radius > distance * distance + other.radius * other.radius) l2 = -l2; Point middle = new Point((center.x * l2 + other.center.x * l1) / (l1 + l2), (center.y * l2 + other.center.y * l1) / (l1 + l2)); Line line = center.line(other.center).perpendicular(middle); return line.intersect(this); } }
Java
["3\n1 3\n2 2\n3 1", "3\n1 2\n1 1\n2 1"]
1 second
["1 2 3", "1 3"]
null
Java 8
standard input
[ "geometry", "math" ]
e54f8aff8ede309bd591cb9fbd565d1f
The first line of input contains a single integer n (1 ≤ n ≤ 2 × 105). The next n lines contain the details of competitors. i-th line contains two integers si and ri (1 ≤ si, ri ≤ 104).
2,600
In the first and the only line of output, print a sequence of numbers of possible winners in increasing order.
standard output
PASSED
bcc941d20ae8bb33859ea9554b3b0250
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; public class MishaChangingHandles { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); HashMap<String, String> dataBase = new HashMap<>(); for(int i = 0; i < n; i++){ String[] handles = br.readLine().split(" "); if(dataBase.get(handles[0]) == null) dataBase.put(handles[1], handles[0]); else{ String old = dataBase.remove(handles[0]); dataBase.put(handles[1], old); } } System.out.println(dataBase.size()); for(String newHandle: dataBase.keySet()) System.out.println(dataBase.get(newHandle)+" "+newHandle); } }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
af729e48a7ca7125d14ede50aca56c3f
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
import java.util.Scanner; import java.util.Arrays; import java.util.LinkedList; public class main { public static void main(String args[]) { Scanner input = new Scanner(System.in); int n = input.nextInt(); input.nextLine(); String arr[][] = new String[n][2]; String result[][] = new String[n][2]; int i = 0; int k = n; while(k > 0) { String s = input.nextLine(); String ar[] = s.split(" "); arr[i][0] = ar[0]; arr[i][1] = ar[1]; i++; k--; } k = 0; LinkedList<String> list = new LinkedList<String>(); for(i=0;i<n;i++) { String temp = arr[i][1]; if(list.contains(temp)) { continue; } list.add(arr[i][0]); list.add(temp); for(int j = i+1;j<n;j++) { if(temp.equals(arr[j][0])) { temp = arr[j][1]; list.add(temp); list.add(arr[j][0]); } } result[k][0] = arr[i][0]; result[k][1] = temp; k++; } System.out.println(k); for(i=0;i<k;i++) { System.out.println(result[i][0]+" "+result[i][1]); } } }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
6c12dfacca75fc60783c372c0b181586
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.Queue; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; public class DisjointSets { int representative[]; int rank[]; public DisjointSets(int n) { representative = new int[n]; rank = new int[n]; for (int i = 0; i < representative.length; i++) representative[i] = i; Arrays.fill(rank, 1); } int findSet(int x) { if (x == representative[x]) return x; return representative[x] = findSet(representative[x]); } void union(int x, int y) { int x1 = findSet(x); int y1 = findSet(y); if (x1 != y1) if (rank[x1] < rank[y1]) { representative[y1] = x1; } else if (rank[x1] > rank[y1]) { representative[x1] = y1; } else { representative[x1] = y1; rank[y1]++; } } /* Name of the class has to be "Main" only if the class is public. */ public static void main (String[] args) throws java.lang.Exception { TreeMap<String,Integer> tmap = new TreeMap<String,Integer>(); TreeMap<Integer,String> tmap1 = new TreeMap<Integer,String>(); BufferedReader br =new BufferedReader(new InputStreamReader(System.in)); int n=Integer.parseInt(br.readLine()); String input ; int j=0; int q=0; DisjointSets set1 = new DisjointSets(2*n); String [] s = new String [n]; String one[]=new String[n]; for (int i = 0; i < n; i++) { input=br.readLine(); StringTokenizer str = new StringTokenizer(input); String x=str.nextToken(); String y=str.nextToken(); s[i]=input; if(!tmap.containsKey(x)){ tmap.put(x,j); tmap1.put(j,x); j++; one[i]=x; } tmap.put(y,j); tmap1.put(j,y); j++; }for (int i = 0; i < one.length; i++) { if(one[i]!=null) q++; } //set1.union(tmap.get(x),tmap.get(y)); for (int k = 0; k < tmap.size(); k++) { set1.representative[k]=k; } for (int k = 0; k <n; k++) { StringTokenizer st = new StringTokenizer(s[k]); String m=st.nextToken(); String p=st.nextToken(); set1.union(tmap.get(m),tmap.get(p)); } System.out.println(q); for (int i = 0; i < one.length; i++) { if(one[i]!=null){ int x=set1.findSet(tmap.get(one[i])); String y=tmap1.get(x); System.out.println(one[i]+" "+y ); } } } }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
6a29ddbacbdce25fbdc9d8f02970ee2a
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
import java.util.*; import java.lang.*; public class Contest { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); Hashtable<String, String> h = new Hashtable<String, String>(); while (n > 0) { String a = in.next(), b = in.next(); if (!h.contains(a)) { h.put(a, b); } else { for (String key : h.keySet()) { if (h.get(key).equals(a)) { h.put(key, b); break; } } } n--; } System.out.println(h.size()); for (String key : h.keySet()) System.out.println(key + " " + h.get(key)); } }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
49c7c2284846200bdb679ec4898b62b1
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; public class Div2_285 { public static void main(String args[])throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int q=Integer.parseInt(br.readLine()); String[][] names = new String[q][2]; boolean[] check = new boolean[q]; for(int i=0;i<q;i++){ names[i] = br.readLine().split(" "); } String[][] output = new String[q][2]; int count=0; for(int i=0;i<q;i++){ if(check[i])continue; output[count][0]=names[i][0]; String last = names[i][1]; check[i]=true; for(int j=i+1;j<q;j++){ if(names[j][0].equals(last)){ last=names[j][1]; check[j]=true; } } output[count++][1]=last; } System.out.println(count); for(int i=0;i<count;i++){ System.out.println(output[i][0] +" "+output[i][1]); } } }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
f3fa9b1f72acc08fbfd01b1ebfea5fc3
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Scanner; public class B { public static void main(String[] args) { HashMap<String, String> users = new HashMap<String, String>(); Scanner console = new Scanner(System.in); int count = console.nextInt(); console.nextLine(); for (int i = 0; i < count; ++i){ String[] names = console.nextLine().split(" "); check(users, names[0], names[1]); } System.out.println(users.size()); Iterator it = users.entrySet().iterator(); while (it.hasNext()) { Map.Entry pairs = (Map.Entry)it.next(); System.out.println(pairs.getKey() + " " + pairs.getValue()); } } private static void check(HashMap<String, String> map, String old, String newN){ if (map.containsValue(old)){ map.put(getKeyByValue(map, old), newN); }else map.put(old, newN); } public static <T, E> T getKeyByValue(Map<T, E> map, E value) { for (Map.Entry<T, E> entry : map.entrySet()) { if (value.equals(entry.getValue())) { T key = entry.getKey(); map.remove(key); return key; } } return null; } }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
a2a24b97656770c19260ef96e3df63f8
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
/* package whatever; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Ideone { public static void main (String[] args) throws java.lang.Exception { // your code goes here Scanner s=new Scanner(System.in); int n=s.nextInt(); String a[]=new String [n]; String b[]=new String[n]; for(int i=0;i<n;i++){ a[i]=s.next(); b[i]=s.next(); }int z=0; //search(int []a,int[] b); for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ if(b[i].equals(a[j])) { b[i]=b[j]; a[j]="oop";z++; // System.out.println(i); } } } System.out.println(n-z); for(int i=0;i<n;i++){ if(a[i]!="oop") System.out.println(a[i]+" "+b[i]); } //for(int i=0;i<n;i++){ //a[i]=s.nextInt(); //b[i]=s.nextInt(); //System.out.println(a[i]); // System.out.println(b[i]); // } /* for(int i=0;i<n;i++){ if() }*/ } /* private static String (int []a,int[] b){ for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ if(b[i]==a[j]) {b[i]=b[j]; a[i]=oop; } } }*/ }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
966e587ef5799a5ce4096ae017bfe887
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
import java.util.Scanner; public class B { public static void main(String args[]){ Scanner in = new Scanner(System.in); String s[][] = new String[1000][2]; int n = in.nextInt(); int ind = 0 , c = 0; String temp1 = "", temp2 = ""; for(int i = 0 ; i < n ; i++){ temp1 = in.next(); temp2 = in.next(); c = 0; if(i==0){ s[ind][0] = temp1; s[ind][1] = temp2; ind++; }else{ for(int j = 0 ; j < n ; j++){ if(temp1.equals(s[j][1])){ c = 1; s[j][1] = temp2; break; } } if(c==0){ s[ind][0] = temp1; s[ind][1] = temp2; ind++; } } } System.out.println(ind); for(int i = 0 ; i < ind ; i++) System.out.println(s[i][0]+" "+s[i][1]); } }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
8939fe96cce4fb78d04aa818cffca68c
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
import java.io.PrintWriter; import java.util.HashMap; import java.util.Scanner; public class ChangingHandles { public static void main(String args[]) { Scanner input = new Scanner(System.in); //PrintWriter out = new PrintWriter(System.out); int q = input.nextInt(); HashMap<String, String> map = new HashMap<String, String>(); for (int i = 0; i < q; i++) { String a = input.next(), b = input.next(); if(map.containsKey(a)) { String temp=map.get(a); map.remove(a); a=temp; } map.put(b, a); } System.out.println(map.size()); for(String s:map.keySet()) { System.out.println(map.get(s)+" "+s); } } }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
9af954e15b388d38b2e91f16cf5517f7
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.util.HashMap; public class Mishahandles { public static void main(String[] args) throws IOException{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String brr[]=br.readLine().trim().split(" "); int n=Integer.parseInt(brr[0]); int i; String temp,head; String crr[]; crr = new String[1000]; HashMap first; first=new HashMap<String,String>(); HashMap second; second=new HashMap<String,String>(); for(i=0;i<n;i++) { // System.out.println(i); String arr[]=br.readLine().trim().split(" "); String oldname=arr[0]; crr[i]=oldname; String newname=arr[1]; first.put(oldname,newname); second.put(newname,oldname); } int p=n; i=0; while(i<n) { //System.out.println(crr[i]); if(first.containsKey(crr[i])) { // System.out.println("kkkkkk"); temp=(String)first.get(crr[i]); if(first.containsKey(temp)) { //System.out.println("ddd"); head=(String)first.get(temp); first.put(crr[i],head); // System.out.println(temp); first.remove(temp); } else i++; } else i++; } System.out.println(first.size()); for(Object x:first.keySet()){ System.out.println(x+" "+(String)first.get(x)); } } }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
cdb5104cabf7419d8029723f0e810c5a
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
// package Div2; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Scanner; import java.util.Stack; public class Sketch { public static void main(String[] args){ Scanner input = new Scanner(System.in); int q = input.nextInt(); String[] olds = new String[q]; String[] news = new String[q]; int end = 0; for(int i=0; i<q; i++){ String first = input.next(); String second = input.next(); boolean found = false; for(int j=0; j<end; j++){ if(first.equals(news[j])){ news[j] = second; found = true; break; } } if(!found){ olds[end] = first; news[end++] = second; } } input.close(); System.out.println(end); for(int i=0; i<end; i++){ System.out.println(olds[i] + " " + news[i]); } } }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
104be5545347f3afc1ef32cbc9597ce0
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; public class Ques1 { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); String[] olds = new String[n]; String[] news = new String[n]; int cnt = 0; for (int i = 0; i < n; ++i) { String st[] = br.readLine().split("\\s+"); String a = st[0], b = st[1]; boolean flag = true; for (int j = 0; j < cnt; ++j) { if (news[j].equals(a)) { news[j] = b; flag = false; break; } } if (flag) { olds[cnt] = a; news[cnt] = b; cnt++; } } System.out.println(cnt); for (int i = 0; i < cnt; ++i) { System.out.println(olds[i] + " " + news[i]); } } }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
70fb280ea6a8caf4a27b4fd874460aad
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
import java.util.*; public class B { String old; String current; public B(String a, String b) { old = a; current =b; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int cases = in.nextInt(); B[]arr = new B[cases]; int count = 0; for(int i = 0; i<cases; i++) { boolean checked = false; B x = new B(in.next(), in.next()); for(int j = 0; j<arr.length; j++) { if((arr[j]!=null)&&(arr[j].current.equals(x.old))) { arr[j].current=x.current; checked = true; } } if(checked==false) { arr[count++]=x; } } System.out.println(count); for(int i = 0; i<count; i++) System.out.println(arr[i].old + " " + arr[i].current); } }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
70961c95f7166ff01292b432721829d1
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
import java.util.HashMap; import java.util.Scanner; /** * Date: 18-01-2015 * Time: 06:41 */ public class MishaAndChangingHandles { public static void main(String[] args) { Scanner in = new Scanner(System.in); HashMap<String, String> currentPrev = new HashMap<>(); int q = in.nextInt(); int n = 0; for (int i = 0; i < q; i++) { String oldName = in.next(); String newName = in.next(); if (currentPrev.containsKey(oldName)) { String firstName = currentPrev.get(oldName); currentPrev.remove(oldName); currentPrev.put(newName, firstName); } else { n++; currentPrev.put(newName, oldName); } } System.out.println(n); for (String s : currentPrev.keySet()) { System.out.println(currentPrev.get(s) + " " + s); } } }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
aadfce16ab9bcf81d7603f9b27e93a59
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.StringTokenizer; public class ASC { public static void main(String[] args) throws IOException { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader scn = new InputReader(inputStream); PrintWriter prn = new PrintWriter(outputStream); II__ASC__II Mechanism = new II__ASC__II(); Mechanism.Process(1, scn, prn); prn.close(); } } class II__ASC__II { private Scanner scnn = new Scanner(System.in); public void Process(int ASC, InputReader scn, PrintWriter prn) throws IOException { //double START = System.currentTimeMillis(); { int q = scn.nextInt(); HashMap<String, String> handles = new HashMap<String, String>(); String a, b; while (q-- > 0) { a = scn.next(); b = scn.next(); if (handles.containsKey(a)) { String original = handles.get(a); handles.remove(a); handles.put(b, original); } else { handles.put(b, a); } } prn.println(handles.size()); for (Map.Entry<String, String> find : handles.entrySet()) { prn.println(find.getValue() + " " + find.getKey()); } } //double END = System.currentTimeMillis(); //double RES = END - START; //prn.println(" |------------------------------------------------|"); //prn.printf(" | This Code Executed In :: [[%-10.5f]] Ms |\n",RES); //prn.println(" |------------------------------------------------|"); } } class InputReader { private BufferedReader reader; private 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 String nextLine() throws IOException { return reader.readLine(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public Integer toInt(String s) { return Integer.parseInt(s.trim()); } public Long toLong(String s) { return Long.parseLong(s.trim()); } public Double toDouble(String s) { return Double.parseDouble(s.trim()); } public int[] getIntArray(String line) { String s[] = line.split(" "); int a[] = new int[s.length]; for (int i = 0; i < s.length; ++i) { a[i] = Integer.parseInt(s[i]); } return a; } public Integer[] getIntegerArray(String line) { String s[] = line.split(" "); Integer a[] = new Integer[s.length]; for (int i = 0; i < s.length; ++i) { a[i] = Integer.parseInt(s[i]); } return a; } public Double[] getDoubleArray(String line) { String s[] = line.split(" "); Double a[] = new Double[s.length]; for (int i = 0; i < s.length; ++i) { a[i] = Double.parseDouble(s[i]); } return a; } public Long[] getLongArray(String line) { String s[] = line.split(" "); Long a[] = new Long[s.length]; for (int i = 0; i < s.length; ++i) { a[i] = Long.parseLong(s[i]); } return a; } public Long getMaxFromLongArray(Long a[]) { Long max = Long.MIN_VALUE; for (int i = 0; i < a.length; ++i) { if (max < a[i]) { max = a[i]; } } return max; } public Long getMinFromLongArray(Long a[]) { Long min = Long.MAX_VALUE; for (int i = 0; i < a.length; ++i) { if (min > a[i]) { min = a[i]; } } return min; } public Integer getMaxFromIntegerArray(Integer a[]) { Integer max = Integer.MIN_VALUE; for (int i = 0; i < a.length; ++i) { if (max < a[i]) { max = a[i]; } } return max; } public Integer getMinFromIntegerArray(Integer a[]) { Integer min = Integer.MAX_VALUE; for (int i = 0; i < a.length; ++i) { if (min > a[i]) { min = a[i]; } } return min; } public long modPow(long a, long x, long p) { long res = 1; while (x > 0) { if (x % 2 != 0) { res = (res % p * a % p) % p; } a = (a % p * a % p) % p; x /= 2; } return res; } public long modInverse(long a, long p) { return modPow(a, p - 2, p); } public long modBinomial(long n, long k, long p) { long numerator = 1; // n * (n-1) * ... * (n-k+1) for (long i = 0; i < k; i++) { numerator = (numerator % p * (n - i) % p) % p; } long denominator = 1; // k! for (long i = 1; i <= k; i++) { denominator = (denominator % p * i % p) % p; } return (numerator % p * modInverse(denominator, p) % p) % p; } public long calculate(long k, long n) { return (modBinomial(n, k, 1000000007)); } }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
e3483ee621ec4aff531ab403441c3fd7
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
import java.util.*; import java.io.*; import static java.lang.System.*; public class CF501B{ public static void main(String[] args) throws Exception{ BufferedReader sc = new BufferedReader(new InputStreamReader(in)); HashMap<String, String> mappings = new HashMap<String, String>(); ArrayList<String> starts = new ArrayList<String>(); int q = Integer.parseInt(sc.readLine()); while(q-->0){ String[] s = sc.readLine().split(" "); if(!mappings.containsValue(s[0])){ starts.add(s[0]); } mappings.put(s[0], s[1]); } out.println(starts.size()); for(int i=0; i<starts.size(); i++){ String s = starts.get(i); String cur = s; while(mappings.containsKey(cur)){ cur = mappings.get(cur); } out.println(s + " " + cur); } } }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
26c16f4301019458a9cd5d10a9bbdef9
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.TreeMap; import java.util.TreeSet; public class MishaAndChangingHandles_501B { public static void main(String[] args)throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); String[] s; TreeMap<String, String> map = new TreeMap<String, String>(); TreeSet<String> used = new TreeSet<String>(); TreeSet<String> start = new TreeSet<String>(); for(int i =0; i<n; i++){ s = br.readLine().split(" "); if( !used.contains(s[0]) ) start.add(s[0]); used.add(s[0]); used.add(s[1]); map.put(s[0], s[1]); } System.out.println(start.size()); for(String str : start){ System.out.print(str+" "); while( map.containsKey(str) ) str = map.get(str); System.out.println(str); } } }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
d8b8aa8d878c370a1f0a5bec4e77da22
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
import java.util.*; public class Main { public static HashMap<String,Integer> map=new HashMap<>(); public static int par[]=new int[1001*2]; public static String store[]=new String[1001*2]; public static String out[]; public static void main(String[] args) { // TODO Auto-generated method stub Scanner k=new Scanner(System.in); for(int i=1;i<par.length;i++){ // make set par[i]=i; } int cnt=0; int cs=k.nextInt(); k.nextLine(); for(int i=0;i<cs;i++){ String s=k.nextLine(); String tmp[]=s.split(" "); String a=tmp[0],b=tmp[1]; int u,v; if((map.containsKey(a))){ u = map.get(a); }else{ u = ++cnt; map.put(a, u); store[u]=a; } if((map.containsKey(b))){ v = map.get(b); }else{ v = ++cnt; map.put(b, v); store[v]=b; } union(u,v); } out=new String[cnt]; int key=0; int visit[]=new int[cnt+1]; int parLength=cnt+1; for(int i=1;i<parLength;i++){ int tmp=getParent(i); if(visit[tmp]==0){ out[key]=store[i]+" "+store[tmp]; key++; } visit[tmp]=1; // to remember that parent was just printed } System.out.println(key); for(int i=0;i<key;i++){ System.out.println(out[i]); } } public static void union(int a,int b){ int u=getParent(a); int v=getParent(b); if(u!=v) par[u]=v; } public static int getParent(int n){ if(par[n]==n)return n; else return par[n]=getParent(par[n]); } }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
da8a495c48367b9800447cd36de71e6c
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Scanner; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeSet; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Hasan0504 { // public static Scanner input = new Scanner(System.in); public static void main(String[] args) throws IOException { Scanner input = new Scanner(System.in); // BufferedReader buffer=new BufferedReader(new InputStreamReader(System.in)); int n=input.nextInt(); Stack<String>stack1=new Stack<String>(); Stack<String>stack2=new Stack<String>(); for(int i=0;i<n;i++){ stack1.add(input.next()); stack2.add(input.next()); } int c=0; String N=""; for(int i=0;i<stack1.size();i++){ String one=stack1.get(i); String two=stack2.get(i); for(int ii=0;ii<stack1.size();ii++){ if(ii==i) continue; if(stack1.get(ii).equals(two)){ two=stack2.get(ii); stack1.removeElementAt(ii); stack2.removeElementAt(ii); ii=0; } } N+=one+" "+two+"\n"; c++; }// main System.out.println(c); System.out.println(N); } }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
24ae8c8ca2fc39c8d84d91e4c87dbe44
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ import java.util.*; import java.math.*; import java.io.*; /** * * @author magzhankairanbay */ public class Code { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here try { Scanner in = new Scanner(System.in); int n = in.nextInt(); String[][] s = new String[n][2]; int c = 0; for (int i = 0; i < n; i++) { s[i][0] = in.next(); s[i][1] = in.next(); for (int j = 0; j < i; j++) { if (s[i][0].equals(s[j][1])) { // System.out.println("Start = " + s[i][0] + " " + s[i][1]); s[j][1] = s[i][1]; s[i][0] = "-"; c++; } } } System.out.println(n - c); for (int i = 0; i < n; i++) { if (!s[i][0].equals("-")) { System.out.println(s[i][0] + " " + s[i][1]); } } } catch(Exception ex) { System.out.println(ex.toString()); } } }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
97fef12ff767009e3bd5df532d537a6e
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
//package codeforces; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; public class B { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter(System.out); StringTokenizer stringTokenizer; B() throws IOException { // reader = new BufferedReader(new FileReader("cycle2.in")); // writer = new PrintWriter(new FileWriter("cycle2.out")); } String next() throws IOException { while (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) { stringTokenizer = new StringTokenizer(reader.readLine()); } return stringTokenizer.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } int[][] mul(int[][] a, int[][] b) { int[][] result = new int[2][2]; for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { for (int k = 0; k < 2; k++) { result[i][j] = sum(result[i][j], product(a[i][k], b[k][j])); } } } return result; } int[][] pow(int[][] a, int k) { int[][] result = {{1, 0}, {0, 1}}; while (k > 0) { if (k % 2 == 1) { result = mul(result, a); } a = mul(a, a); k /= 2; } return result; } final int MOD = 1000 * 1000 * 1000 + 7; int sum(int a, int b) { a += b; return a >= MOD ? a - MOD : a; } int product(int a, int b) { return (int) (1l * a * b % MOD); } @SuppressWarnings("unchecked") void solve() throws IOException { int n = nextInt(); Set<String> users = new HashSet<>(); Set<String> allHandles = new HashSet<>(); Map<String, String> changes = new HashMap<>(); for(int i = 0; i < n; i++) { String from = next(); String to = next(); if(!allHandles.contains(from)) { users.add(from); } allHandles.add(to); changes.put(from, to); } writer.println(users.size()); for (String user : users) { String handle = changes.get(user); while(changes.containsKey(handle)) { handle = changes.get(handle); } writer.println(user + " " + handle); } writer.close(); } public static void main(String[] args) throws IOException { new B().solve(); } }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
22b27753a24f8e59ad58e2fec0ef9d5d
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
import java.util.Scanner; public class Main { static Scanner in = new Scanner(System.in); public static void main(String[] args) { int TestCases = in.nextInt(); dsu ds = new dsu(TestCases); String st[][] = new String[TestCases][2]; boolean Changes[] = new boolean[TestCases]; for (int i = 0; i < TestCases; i++) { st[i][0] = in.next(); st[i][1] = in.next(); } for (int i = 0; i < TestCases; i++) { ds.makeset(i); } for (int i = 0; i < TestCases; i++) { for (int j = i + 1; j < TestCases; j++) { if (st[i][1].equals(st[j][0])) { ds.union(i, j); Changes[i] = true; } } } int ans = TestCases; for (int i = 0; i < TestCases; i++) { if ((ds.Fu_Set[i] == i && !Changes[i])) { continue; } //System.out.println(st[i][0] + " " + st[ds.find(i)][1]); ans--; } System.out.println(ans); for (int i = 0; i < TestCases; i++) { boolean flag = true ; for (int j = 0; j < TestCases; j++) { if (st[i][0].equals(st[j][1])) { flag = false ; } } if(flag) System.out.println(st[i][0] + " " + st[ds.find(i)][1]); } } public static class dsu { int Fu_Set[]; public dsu(int Size) { Fu_Set = new int[Size]; } void makeset(int index) { Fu_Set[index] = index; } int find(int index) { while (Fu_Set[index] != index) { index = Fu_Set[index]; } return index; } boolean union(int index1, int index2) { int Root1 = find(index1); int Root2 = find(index2); if (Root1 != Root2) { Fu_Set[Root1] = Root2; return true; } return false; } } }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
bbfdd748ecdce7e18a6f41479b3bf060
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Map; public final class Misha { static public void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); // para // leer // la // entrada StringBuilder out = new StringBuilder(); // para escribir la salida, // todo junto y no imprimir // linea por linea String line; // leer el input hasta EOF (line == null), esto se logra con Ctrl + D en una terminal while ((line = in.readLine()) != null) { String[] tokens = line.split(" "); // "partir" cada linea por espacios int cantidad = Integer.parseInt(tokens[0]); ArrayList<String[]> pares = new ArrayList<>(); for (int i = 0; i < cantidad; i++) { line = in.readLine(); tokens = line.split(" "); String[] par = {tokens[0], tokens[1]}; pares.add(par); } Map<String, Boolean> macheado = new HashMap<>(); Map<String, String> matching = new HashMap<>(); for (int i = 0; i < cantidad; i++) { matching.put(pares.get(i)[0], pares.get(i)[1]); macheado.put(pares.get(i)[1], true); } StringBuilder sb = new StringBuilder(); int count = 0; for (int i = 0; i < cantidad; i++) { if(!macheado.containsKey(pares.get(i)[0])){ String fin = pares.get(i)[1]; while(matching.containsKey(fin)){ fin = matching.get(fin); } sb.append(pares.get(i)[0] + " " + fin + "\n"); count++; } } System.out.println(count + "\n" + sb.toString()); } } }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
2039a3e4f773ac1003961eea2f4b47b1
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class B501 { public static void main(String[] args) { Scanner input = new Scanner(System.in); Map<String,String> map = new HashMap<String,String>(); int N = input.nextInt(); for (int n=0; n<N; n++) { String oldName = input.next(); String newName = input.next(); String originalName = map.remove(oldName); if (originalName == null) { originalName = oldName; } map.put(newName, originalName); } System.out.println(map.size()); for (Map.Entry<String,String> entry : map.entrySet()) { System.out.println(entry.getValue()+" "+entry.getKey()); } } }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
0c3884a34bb42b78c8cd8f803c2ec010
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedReader; import java.io.IOException; import java.util.StringTokenizer; import java.util.HashMap; import java.util.Map; import java.lang.String; import java.lang.Math; import java.util.Arrays; //import java.lang.Double; public class template { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(in, out); out.close(); } } class Task { public void solve(InputReader in, PrintWriter out) { int n = in.nextInt(); String[] olds = new String[n]; String[] news = new String[n]; int cnt = 0; for (int i = 0; i < n; ++i) { String a = in.next(), b = in.next(); boolean flag = true; for (int j = 0; j < cnt; ++j) { if (news[j].equals(a)) { news[j] = b; flag = false; break; } } if (flag) { olds[cnt] = a; news[cnt] = b; cnt++; } } out.println(cnt); for (int i = 0; i < cnt; ++i) { out.println(olds[i] + " " + news[i]); } } } class InputReader { BufferedReader reader; StringTokenizer tokenize; InputReader(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); tokenize = null; } public String next() { while (tokenize == null || !tokenize.hasMoreTokens()) { try{ tokenize = new StringTokenizer(reader.readLine()); }catch(IOException e) { throw new RuntimeException(e); } } return tokenize.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
b8bbbef500139f93a324e74af913055b
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; public class B501 { public static void main(String[] args) throws IOException { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); String[] input = bf.readLine().split(" "); int n = Integer.parseInt(input[0]); String[] olds = new String[n]; String[] news = new String[n]; int count_handles = 0; for (int i = 0; i < n; i++) { input = bf.readLine().split(" "); int index = -1; for (int j = 0; j < count_handles; j++) { if (input[0].compareTo(news[j]) == 0) { index = j; break; } } if (index == -1) { //doesn't exist olds[count_handles] = input[0]; news[count_handles] = input[1]; count_handles++; } else { // already exist news[index] = input[1]; } } System.out.println(count_handles); for (int i = 0; i < count_handles; i++) { System.out.println(olds[i]+" "+news[i]); } } }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
54e9c290eaecb22df16b8b459770608b
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
import java.util.*; public class cf501B { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); HashSet<String> hash = new HashSet<String>(); ArrayList<String> root = new ArrayList<String>(); ArrayList<String> newH = new ArrayList<String>(); for(int i = 0; i < n; i++) { String oldN = sc.next(); String newN = sc.next(); if(!hash.contains(oldN)) { hash.add(oldN); hash.add(newN); root.add(oldN); newH.add(newN); } else { int j = 0; while(true) { //System.out.println(oldN + " " + newH.get(j)); if(newH.get(j).equals(oldN)) { newH.set(j, newN); hash.add(newN); break; } j++; } } } System.out.println(root.size()); for(int i = 0; i < root.size(); i++) { System.out.println(root.get(i) + " " + newH.get(i)); } } }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
711f054ff66051d79eaade3609a6b5e7
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
import java.util.*; import java.lang.*; public class handles { public static void main(String args[]) { Scanner e=new Scanner(System.in); int n=e.nextInt(),i,x=0; String a[]=new String[n]; String b[]=new String[n]; String c[]=new String[n]; for(i=0;i<n;i++) { a[i]=e.next(); b[i]=e.next(); } for(i=0;i<n;i++) { //String s=b[i]; if(a[i]=="") continue; int t=-1; int l=i; if(l!=n-1) { for(int j=l+1;j<n;j++) { if(b[l].equals(a[j])==true) { t=j; a[j]=""; l=j; } } } if(t==-1) { c[x]=a[i]+" "+b[i]; x++; } else { c[x]=a[i]+" "+b[t]; x++; } } System.out.println(x); for(i=0;i<x;i++) System.out.println(c[i]); } }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
ac7dd4e4f542d5f9b7fd27bc1d7cf1f4
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
import java.util.*; import java.util.LinkedList; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; public class tmp { public static void main(String [] args) throws Exception{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(in.readLine()); int n = Integer.parseInt(st.nextToken()); HashMap<String, String> map = new HashMap(); String key, val; int num=0; for(int i=0; i<n; i++){ st = new StringTokenizer(in.readLine()); key = st.nextToken(); val = st.nextToken(); if(map.containsKey(key)){ map.put(val, map.get(key)); map.remove(key); }else{ num++; map.put(val, key); } } System.out.println(num); for(String k : map.keySet()){ System.out.println(map.get(k)+ " " + k ); } } } class Pair implements Comparable<Pair>{ int x,h; public Pair(int fi, int ti){ x = fi; h = ti; } public int compareTo(Pair p){ return x < p.x ? -1 : (x == p.x ? (h < p.h ? -1 : 1) : 1); } }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
7fd4f87129d4fe8eed0fc6a96d0c7ad2
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String[]args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); HashMap<String, Node> conv = new HashMap<String, Node>(); ArrayList<Node> graph = new ArrayList<Node>(); int n = Integer.parseInt(br.readLine()); for(int i=0; i<n; i++) { String input = br.readLine(); StringTokenizer tk = new StringTokenizer(input); String oldName = tk.nextToken(); String newName = tk.nextToken(); Node oldUser; if(!conv.containsKey(oldName)) { oldUser = new Node(oldName); conv.put(oldName,oldUser); graph.add(oldUser); }else oldUser = conv.get(oldName); Node newUser; if(!conv.containsKey(newName)) { newUser = new Node(newName); conv.put(newName,newUser); graph.add(newUser); }else newUser = conv.get(newName); //System.out.println(oldName + " " + newName); union(oldUser,newUser); oldUser.parent.lastName = newUser.name; } StringBuilder sb = new StringBuilder(); HashSet<String> pars = new HashSet<String>(); for(int i=0; i<graph.size(); i++) { Node temp = graph.get(i); //System.out.println(temp.name); if(!pars.contains(temp.parent.name)) { sb.append(temp.parent.name + " " + temp.parent.lastName +"\n"); pars.add(temp.parent.name); } } System.out.println(pars.size()); System.out.print(sb); } public static void union(Node a, Node b) { if(find(a)!=find(b)) b.parent = a.parent; } public static Node find(Node a) { if(a.parent!=a) a.parent = find(a.parent); return a.parent; } } class Node { Node parent; String name; String lastName; public Node(String name) { this.name=name; lastName = name; parent = this; } }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
af82a49f834ff314a73d5e12a8ec15df
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; public class B { public static void main(String args[]) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(in.readLine()); String x[] = new String[n]; String y[] = new String[n]; int count = 0; for (int i=0;i<n;i++) { String s = in.readLine(); String s1 = s.substring(0,s.indexOf(" ")); String s2 = s.substring(s.indexOf(" ")+1); //System.out.println(s1+ ":"+s2); boolean found = false; for (int j=0;j<count;j++) { if (y[j].equals(s1)) { y[j] = s2; found = true; break; } } if (!found) { x[count] = s1; y[count++] = s2; } } System.out.println(count); for (int i=0;i<count;i++) { System.out.println(x[i] + " " + y[i]); } in.close(); } }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
021109af91821b484df5657cc12e93ba
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
import java.util.*; public class Change { public static void main(String args[]) { Scanner input = new Scanner(System.in); ArrayList <User> a = new ArrayList <User>(); int n; n = input.nextInt(); for (int i = 0; i < n; i++) { String handle, newhandle; handle = input.next(); newhandle = input.next(); int ind = find(a, handle); if (ind == -1) { a.add(new User(handle, newhandle)); } else { a.get(ind).handle = newhandle; } } System.out.println(a.size()); for (int i = 0; i < a.size(); i++) System.out.println(a.get(i).firsthandle + " " + a.get(i).handle); } public static int find(ArrayList <User> a, String s) { int ind = -1; for (int i = 0; i < a.size(); i++) if (s.equals(a.get(i).handle)) { ind = i; break; } return ind; } } class User { String handle, firsthandle; User(String s1, String s2) { firsthandle = s1; handle = s2; } }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
2b5e94d01754079ea136ca9451062024
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
import java.io.PrintStream; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Scanner; import java.util.Set; public class B { public static void main(String[] args) { Scanner in = new Scanner(System.in); PrintStream out = System.out; int q = in.nextInt(); Set<String> users = new HashSet<>(); Map<String, String> handlesChanges = new HashMap<>(); for (int i = 0; i < q; i++){ String oldHandle = in.next(); String newHandle = in.next(); if (!handlesChanges.containsKey(oldHandle)){ //totally new user users.add(oldHandle); } handlesChanges.put(oldHandle, newHandle); handlesChanges.put(newHandle, null); } out.println(users.size()); for (String user: users){ out.print(user + " "); String handle = user; while (handlesChanges.get(handle) != null){ handle = handlesChanges.get(handle); } out.println(handle); } } }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
eef3e6a2926d69aa03c5dbb48249dc04
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
import java.util.*; import java.math.*; import java.io.*; import java.text.*; import java.awt.Point; import static java.util.Arrays.*; import static java.lang.Integer.*; import static java.lang.Double.*; import static java.lang.Long.*; import static java.lang.Short.*; import static java.lang.Math.*; import static java.math.BigInteger.*; import static java.util.Collections.*; public class B { // IO Imports private BufferedReader in; private StringTokenizer st; private PrintWriter out; // Pretty Stuff private DecimalFormat fmt = new DecimalFormat("0.0000000000"); public void solve() throws Exception { // map new to old HashMap<String, String> map = new HashMap<String, String>(); int n = Integer.parseInt(in.readLine()); for (int i=0; i<n; i++) { st = new StringTokenizer(in.readLine()); String a = st.nextToken(); String b = st.nextToken(); if (!map.containsKey(a)) { map.put(b, a); } else { String c = map.remove(a); map.put(b, c); } } out.println(map.size()); for (String s : map.keySet()) { out.println(map.get(s) + " " +s); } } public B() { this.in = new BufferedReader(new InputStreamReader(System.in)); this.out = new PrintWriter(System.out); } public void end() { try { this.out.flush(); this.out.close(); this.in.close(); } catch (Exception e) { //do nothing then :) } } public static void main(String[] args) throws Exception { B solver = new B(); solver.solve(); solver.end(); } }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
2de6dc353d4dd147ab9dc16406479e5a
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
import java.util.*; import java.math.*; import java.io.*; import java.text.*; import java.awt.Point; import static java.util.Arrays.*; import static java.lang.Integer.*; import static java.lang.Double.*; import static java.lang.Long.*; import static java.lang.Short.*; import static java.lang.Math.*; import static java.math.BigInteger.*; import static java.util.Collections.*; public class B { // IO Imports private BufferedReader in; private StringTokenizer st; private PrintWriter out; // Pretty Stuff private DecimalFormat fmt = new DecimalFormat("0.0000000000"); public void solve() throws Exception { // map new to old HashMap<String, String> map = new HashMap<String, String>(); int n = Integer.parseInt(in.readLine()); for (int i=0; i<n; i++) { st = new StringTokenizer(in.readLine()); String a = st.nextToken(); String b = st.nextToken(); if (!map.containsKey(a)) { map.put(b, a); } else { String c = map.remove(a); map.put(b, c); } } out.println(map.size()); for (String s : map.keySet()) { out.println(map.get(s) + " " +s); } } public B() { this.in = new BufferedReader(new InputStreamReader(System.in)); this.out = new PrintWriter(System.out); } public void end() { try { this.out.flush(); this.out.close(); this.in.close(); } catch (Exception e) { //do nothing then :) } } public static void main(String[] args) throws Exception { B solver = new B(); solver.solve(); solver.end(); } }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
4d20ec51d17eda5f22248d489dc13387
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
import java.io.*; import java.util.*; public final class changing_handles { static FastScanner sc=new FastScanner(new BufferedReader(new InputStreamReader(System.in))); static PrintWriter out=new PrintWriter(System.out); public static void main(String args[]) throws Exception { int n=sc.nextInt(); List<Pair> list=new ArrayList<Pair>(); for(int i=0;i<n;i++) { String s1=sc.next(),s2=sc.next(); boolean b1=false; for(int j=0;j<list.size();j++) { if(list.get(j).s2.equals(s1)) { b1=true; list.set(j,new Pair(list.get(j).s1,s2)); break; } } if(!b1) { list.add(new Pair(s1,s2)); } } out.println(list.size()); for(Pair p1:list) { out.println(p1.s1+" "+p1.s2); } out.close(); } } class Pair { String s1,s2; public Pair(String s1,String s2) { this.s1=s1; this.s2=s2; } } 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
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
614f720bb1125d1e158dd857054364eb
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
//package codeforces; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.StringTokenizer; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int N = Integer.parseInt(in.nextLine()); HashMap<String, String> map = new HashMap<String, String>(); for (int i = 0; i < N; i++) { StringTokenizer st = new StringTokenizer(in.nextLine()); String first = st.nextToken(); String second = st.nextToken(); if (map.containsKey(first)) { map.put(second, map.get(first)); map.remove(first); } else { map.put(second, first); } } System.out.println(map.size()); for (Map.Entry<String, String> entry : map.entrySet()) { System.out.println(entry.getValue() + " " + entry.getKey()); } } }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
be9bde30b2200835dafd6180fecad982
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
import java.util.LinkedList; import java.util.Scanner; public class ChangingHandles { public static void main(String[] args) { Scanner sc=new Scanner(System.in); LinkedList<LinkedList<String>> nombres=new LinkedList<LinkedList<String>>(); int n=Integer.parseInt(sc.nextLine()); int cambios=0; for(int k=0;k<n;k++){ String s[]=sc.nextLine().split(" "); boolean esta=false; int i=0; int p=0; while(i<nombres.size() && esta==false){ if(s[0].equals(nombres.get(i).getLast())){ esta=true; p=i; } i++; } if(esta==true){ nombres.get(p).add(s[1]); }else{ LinkedList<String> l=new LinkedList<String>(); l.add(s[0]); l.add(s[1]); nombres.add(l); cambios++; } } System.out.println(cambios); for(int j=0;j<nombres.size();j++){ System.out.println(nombres.get(j).getFirst()+" "+nombres.get(j).getLast()); } } }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
13455beec55971a3a1b9eae92dc22734
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
/* Rajarshee Mitra (rajarshee) */ import java.io.*; import java.util.*; public class Solution { static int n; static int h[]; public static void main(String[] args) { Scanner s = new Scanner(System.in); n = s.nextInt(); ArrayList<Name> al = new ArrayList<>(); Iterator it ; for(int i=0;i<n;i++) { String m = s.next(); it = al.iterator(); String t = s.next(); boolean f = false;; Name temp; while(it.hasNext()) { temp = (Name)it.next(); if(temp.child.equals(m)) { temp.child = t; f = true; } } if(!f) { temp = new Name(); temp.child = t; temp.value = m; al.add(temp); } } it = al.iterator(); System.out.println(al.size()); while(it.hasNext()) { Name temp = (Name)it.next(); System.out.println(temp.value+ " " + temp.child); } } } class Name { String value,child; }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
fe60a554e0bd12d6194db3fcbba1fb7b
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
import java.util.*; import java.lang.*; public class B285 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); Hashtable <String, String> hash = new Hashtable <String, String>(); int times = scan.nextInt(); int count = 0; String old; String neu; for (int i = 0; i < times; i++) { old = scan.next(); neu = scan.next(); if (hash.containsKey(old)) { hash.put(neu, hash.get(old)); hash.remove(old); } else { count++; hash.put(neu, old); } } System.out.println(count); for (String x: hash.keySet()) { System.out.println(hash.get(x) + " " + x); } } }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
3a613856b5f35b179cc3a1f410e2752f
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.StringTokenizer; import java.util.Arrays; import java.util.TreeMap; import java.util.Map.Entry; public class Change{ static class FastScanner{ BufferedReader s; StringTokenizer st; public FastScanner(){ st = new StringTokenizer(""); s = new BufferedReader(new InputStreamReader(System.in)); } public FastScanner(File f) throws FileNotFoundException{ st = new StringTokenizer(""); s = new BufferedReader (new FileReader(f)); } public int nextInt() throws IOException{ if(st.hasMoreTokens()) return Integer.parseInt(st.nextToken()); else{ st = new StringTokenizer(s.readLine()); return nextInt(); } } public double nextDouble() throws IOException{ if(st.hasMoreTokens()) return Double.parseDouble(st.nextToken()); else{ st = new StringTokenizer(s.readLine()); return nextDouble(); } } public long nextLong() throws IOException{ if(st.hasMoreTokens()) return Long.parseLong(st.nextToken()); else{ st = new StringTokenizer(s.readLine()); return nextLong(); } } public String nextString() throws IOException{ if(st.hasMoreTokens()) return st.nextToken(); else{ st = new StringTokenizer(s.readLine()); return nextString(); } } public String readLine() throws IOException{ return s.readLine(); } public void close() throws IOException{ s.close(); } } //Fastscanner class end static FastScanner in=new FastScanner(); static PrintWriter ww=new PrintWriter(new OutputStreamWriter(System.out)); public static void main(String args[])throws IOException { //Main ob=new Main(); Change ob=new Change(); ob.solve(); ww.close(); } public void solve()throws IOException { int n=in.nextInt(); int i; TreeMap <String,String> ts=new TreeMap<String,String>(); for(i=0;i<n;i++) { String old=in.nextString(); String nnew=in.nextString(); String lastold=null; for(Entry<String,String> s:ts.entrySet()) { if(s.getValue().equals(old)) { lastold=s.getKey(); break; } } if(lastold!=null) { ts.put(lastold,nnew); } else{ ts.put(old,nnew); } } System.out.println(ts.size()); for(Entry<String ,String> s: ts.entrySet()) { System.out.println(s.getKey()+" "+s.getValue()); } } }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
e7d0589ba21acbd6107e64f0321b8ff5
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
import java.io.PrintStream; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Scanner; import java.util.Set; public class B { public static void main(String[] args) { Scanner in = new Scanner(System.in); PrintStream out = System.out; int q = in.nextInt(); Set<String> users = new HashSet<>(); Map<String, String> handlesChanges = new HashMap<>(); for (int i = 0; i < q; i++){ String oldHandle = in.next(); String newHandle = in.next(); if (!handlesChanges.containsKey(oldHandle)){ //totally new user users.add(oldHandle); } handlesChanges.put(oldHandle, newHandle); handlesChanges.put(newHandle, null); } out.println(users.size()); for (String user: users){ out.print(user + " "); String handle = user; while (handlesChanges.get(handle) != null){ handle = handlesChanges.get(handle); } out.println(handle); } } }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
e70362ac98dd8aadd315e3302bb17c09
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.LinkedList; import java.util.List; import java.util.Scanner; public class Problem501b { /** * @param args */ public static void main(String[] args) { Scanner sc = new Scanner(new InputStreamReader(System.in)); int k = sc.nextInt(); int j; List<String> oldName = new LinkedList<>(); List<String> newName = new LinkedList<>(); String o; String n; boolean flag; for(int i = 0; i < k; i++){ o = sc.next(); n = sc.next(); j = 0; flag = false; for(String x : newName){ if(x.equals(o)){ newName.set(j, n); flag = true; break; } j++; } if(!flag){ oldName.add(o); newName.add(n); } } System.out.println(oldName.size()); for(int i = 0; i < oldName.size(); i++){ System.out.println(oldName.get(i) + " " + newName.get(i)); } sc.close(); } }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
2651c1c52de4d3d5a8535ea7e950ba03
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.math.BigDecimal; import java.math.BigInteger; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.StringTokenizer; public class Problem501b { /** * @param args */ public static void main(String[] args) { FastScanner sc = new FastScanner(System.in); int k = sc.nextInt(); Map<String, String> map = new HashMap<>(); String o; String n; String tmp; for (int i = 0; i < k; i++) { o = sc.next(); n = sc.next(); if (map.containsKey(o)) { tmp = o; o = map.get(o); map.remove(tmp); } map.put(n, o); } System.out.println(map.size()); for (Entry<String, String> e : map.entrySet()) { System.out.println(e.getValue() + " " + e.getKey()); } } static class FastScanner { BufferedReader bf; StringTokenizer st; public FastScanner(InputStream is) { bf = new BufferedReader(new InputStreamReader(is)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(bf.readLine()); } catch (Exception ex) { ex.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } float nextFloat() { return Float.parseFloat(next()); } BigInteger nextBigInteger() { return new BigInteger(next()); } BigDecimal nextBigDecimal() { return new BigDecimal(next()); } int[] nextArray(int n) { int x[] = new int[n]; for (int i = 0; i < n; i++) { x[i] = Integer.parseInt(next()); } return x; } } }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
80096bc5ef47211a71df7715c4a85d84
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Scanner; public class Problem501b { /** * @param args */ public static void main(String[] args) { Scanner sc = new Scanner(new InputStreamReader(System.in)); int k = sc.nextInt(); Map<String, String> map = new HashMap<>(); String o; String n; String tmp; for(int i = 0; i < k; i++){ o = sc.next(); n = sc.next(); if(map.containsKey(o)){ tmp = o; o = map.get(o); map.remove(tmp); } map.put(n, o); } System.out.println(map.size()); for(Entry<String, String> e : map.entrySet()){ System.out.println(e.getValue() + " " + e.getKey()); } sc.close(); } }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
be9602519320a2dce1c81e5fc8662055
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.Arrays; public class Main { //String [] Orig; String []Old; String []New; int counter = 0; static int j; public Main (int n){ Old = new String[n]; New = new String [n]; } public void Union (String O,String N){ if(Old[0]!=null){ boolean flag = true; for(int i = 0;i < Old.length; i++){ if(O.equals(New[i])){ New[i]=N; flag = false; //j++; break; } } if(flag){ Old[j]=O; New[j]=N; counter++; j++; } } else { Old[0]=O; New[0]=N; j++; counter++; } } public static void main(String [] args)throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); Main dsu = new Main(n); while (n-->0){ StringTokenizer st = new StringTokenizer(br.readLine()); String x = st.nextToken(); String y = st.nextToken(); dsu.Union(x,y); } System.out.println(dsu.counter); //System.out.println(Arrays.toString(dsu.New)+Arrays.toString(dsu.Old)); for(int i = 0;i < dsu.counter;i++) System.out.println(dsu.Old[i]+" "+dsu.New[i]); /*for (int i = 0;i < dsu.New.length;i++){ if(dsu.New[i]!=null &&dsu.Old[i]!=null) System.out.println(dsu.Old[i]+" "+dsu.New[i]); }*/ } }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
95c4c835f45d3b060ce521a6e168a993
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.LinkedList; import java.util.StringTokenizer; import java.util.TreeMap; public class Main { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); int q = Integer.parseInt(bf.readLine()); String s1; String s2; int count=0; LinkedList<String> newo=new LinkedList<>(); LinkedList<String> old=new LinkedList<>(); for (int i = 0; i < q; i++) { StringTokenizer st = new StringTokenizer(bf.readLine()); if (st.hasMoreTokens()) { s1=st.nextToken(); s2=st.nextToken(); if(!old.contains(s1)) {newo.add(count, s1); old.add(count,s2); count++;} else {int f=old.indexOf(s1); old.remove(f); old.add(f,s2);} } } System.out.println(count); for(int i=0;i<count;i++) { System.out.println(newo.get(i)+" "+old.get(i)); } } }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
125e503c7937facc0dc99dd37e6e3c8b
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
import java.util.ArrayList; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner s = new Scanner (System.in); int n = s.nextInt(); s.nextLine(); String L[] = new String [n]; String old[] = new String [n]; String nw[] = new String [n]; int i=0; for(i=0;i<n;i++) { L[i] = s.nextLine(); } for(i=0;i<n;i++) { old[i] = L[i].split(" ")[0]; nw[i] = L[i].split(" ")[1]; } int j=0; int count=0; String old1[] = new String [n]; String nw1[] = new String [n]; int k=0,p=0; for(i=0;i<n;i++) { if(old[i]!=null) { String b = nw[i]; for(j=i+1;j<n;j++) { if(old[j]!=null && b.equals(old[j])) { b = nw[j]; old[j]=null; } } old1[count] = old[i]; nw1[count] = b; count++; }} System.out.println(count); for(i=0;i<count;i++) { System.out.println(old1[i]+" "+nw1[i]); } } }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
f7be49d8b95eee430e51b16fbcaf51be
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
import java.util.HashMap; import java.util.Scanner; public class ProblemB { public static void main(String[] args){ Scanner scanner = new Scanner(System.in); int q = scanner.nextInt(); HashMap<String, String> rest = new HashMap<String, String>(); HashMap<String, String> curr = new HashMap<String, String>(); for(int i = 0; i < q; i++){ String old = scanner.next(), neew = scanner.next(); if(curr.containsKey(old)){ String last = curr.get(old); rest.put(last, neew); curr.put(neew, last); } else{ rest.put(old, neew); curr.put(neew, old); } } System.out.println(rest.size()); for(String name : rest.keySet()) System.out.println(name + " " +rest.get(name)); } }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
4ea04f5bed0001ee87587ac3ea941513
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
import java.util.*; import java.util.Map.Entry; import java.io.*; public class Main { public static void main (String[]args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); HashMap<String,Integer> unique = new HashMap<String, Integer>(); TreeMap<String, String> mapping = new TreeMap<String, String>(); int n = Integer.parseInt(br.readLine()); int countUnique = 0; for(int i=0; i<n; i++){ StringTokenizer st = new StringTokenizer(br.readLine()); String a = st.nextToken(); String b = st.nextToken(); if(!unique.containsKey(a)){ unique.put(a, 1); countUnique++; } else unique.put(a, 0); unique.put(b, 0); mapping.put(a,b); } System.out.println(countUnique); for(Entry<String, String> entry: mapping.entrySet()){ String a = entry.getKey(); String b = a; int un = unique.get(a); if(un==0) continue; String res = ""; while(mapping.containsKey(a)){ res = mapping.get(a); a = res; } System.out.println(b + " " + res); } } }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
18474dedfa869ab5d633df8f8dce88cb
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
import java.io.*; import java.util.*; public class MishaHandles{ public static int ips(String s){ return Integer.parseInt(s); } public static void main(String[] args) throws IOException{ BufferedReader r=new BufferedReader(new InputStreamReader(System.in)); int n=ips(r.readLine()); HashMap<String,String> hm=new HashMap<String,String>(); int x=n; while(x-- >0){ StringTokenizer str=new StringTokenizer(r.readLine()); String s1=str.nextToken(); String s2=str.nextToken(); if(hm.containsValue(s1)){ for(String o:hm.keySet()){ //String ss=(String)o; if(hm.get(o).compareTo(s1)==0) hm.put(o,s2); } } else hm.put(s1,s2); } System.out.println(hm.size()); for(Map.Entry<String,String> l:hm.entrySet()){ System.out.println(l.getKey()+" "+l.getValue()); } } }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
d924d0f6da4657b5400a0146cb2aab38
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 megabytes
import java.awt.Point; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.lang.reflect.Array; import java.math.BigInteger; import java.sql.PreparedStatement; import java.text.Collator; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; import java.util.Stack; import java.util.StringTokenizer; public class TestClass { static int[] dist ; static int[][][] vis; static ArrayList<Integer>[] resu; static char[][] graph; static int max; static int min; static int[][][] dp; static int zz; static int zzz; static boolean fin; public static void main(String args[] ) throws IOException { // BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); //BufferedReader in = new BufferedReader(new FileReader("C:\\Users\\Sompathak\\Desktop\\yes.txt")); //Scanner in = new Scanner(new FileReader("C:\\Users\\Sompathak\\Desktop\\yes.txt")); // PrintWriter pw = new PrintWriter(new FileWriter("C:\\Users\\Sompathak\\Desktop\\output.txt")); //InputStream inputStream = System.in; //InputReader in = new InputReader(inputStream); Scanner in = new Scanner(new InputStreamReader(System.in)); //Scanner in = new Scanner(new FileReader("C:\\Users\\Sompathak\\Desktop\\yes.txt")); int n = in.nextInt(); String[] a = new String[n]; HashMap<String, String> maps = new HashMap<String, String>(); int ans =0; int k=0; for(int i=0;i<n;i++){ String S = in.next(); String SS = in.next(); if(!maps.containsKey(S)){ maps.put(S, SS); a[k++]= S; ans++; maps.put(SS, "SOMP"); }else{ maps.put(S, SS); maps.put(SS, "SOMP"); } } System.out.println(ans); for(int i=0;i<k;i++){ String So = a[i]; System.out.print(So+" "); String f =""; while(maps.containsKey(So) && maps.get(So)!="SOMP"){ So = maps.get(So); } System.out.println(So); } } } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
910249d1d6a2dd34eb2014f2eef5afa1
train_001.jsonl
1421053200
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
256 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.PriorityQueue; 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; import javax.net.ssl.SSLContext; public class Main { /********************************************** a list of common variables **********************************************/ private MyScanner scan = new MyScanner(); private PrintWriter out = new PrintWriter(System.out); private final double PI = Math.acos(-1.0); private final int SIZEN = (int)(1e5); private final int MOD = (int)(1e9 + 7); private final long MODH = 10000000007L, BASE = 10007; private final int[] DX = {0, 1, 0, -1}, DY = {-1, 0, 1, 0}; private ArrayList<Integer>[] edge; public void foo() { int n = scan.nextInt(); HashMap<String, String> hm = new HashMap<String, String>(); for(int i = 0;i < n;++i) { String s1 = scan.next(); String s2 = scan.next(); if(!hm.containsKey(s1)) hm.put(s2, s1); else { String old = hm.get(s1); hm.remove(s1); hm.put(s2, old); } } out.println(hm.size()); for(Entry<String, String> en : hm.entrySet()) { out.println(en.getValue() + " " + en.getKey()); } } 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; } /** * 5---Get the hash code of a String * @param s: input string * @return hash code */ public long hash(String s) { long key = 0, t = 1; for(int i = 0;i < s.length();++i) { key = (key + s.charAt(i) * t) % MODH; t = t * BASE % MODH; } return key; } /** * 6---Get x ^ n % MOD quickly. * @param x: base * @param n: times * @return x ^ n % MOD */ public long quickMod(long x, long n) { long ans = 1; while(n > 0) { if(1 == n % 2) { ans = ans * x % MOD; } x = x * x % MOD; n >>= 1; } return ans; } /** * 7---judge if a point is located inside a polygon * @param x0 the x coordinate of the point * @param y0 the y coordinate of the point * @return true if it is inside the polygon, otherwise false */ /*public boolean contains(double x0, double y0) { int cross = 0; for(int i = 0;i < n;++i) { double s = x[i + 1] == x[i] ? 100000000 : (double)(y[i + 1] - y[i]) / (x[i + 1] - x[i]); boolean b1 = x[i] <= x0 && x0 < x[i + 1]; boolean b2 = x[i + 1] <= x0 && x0 < x[i]; boolean b3 = y0 < s * (x0 - x[i]) + y[i]; if((b1 || b2) && b3) ++cross; } return cross % 2 != 0; }*/ 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
["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"]
1 second
["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"]
null
Java 7
standard input
[ "data structures", "dsu", "strings" ]
bdd98d17ff0d804d88d662cba6a61e8f
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
1,100
In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.
standard output
PASSED
12c416840690efc8a00c81cf43f772f4
train_001.jsonl
1469205300
On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k people at the same time) and the speed equal to v2. In order to avoid seasick, each of the pupils want to get into the bus no more than once.Determine the minimum time required for all n pupils to reach the place of excursion. Consider that the embarkation and disembarkation of passengers, as well as the reversal of the bus, take place immediately and this time can be neglected.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Main { static int n, l, v1, v2, k, q; public static void main(String[] args) throws Exception { Reader.init(System.in); n = Reader.nextInt(); l = Reader.nextInt(); v1 = Reader.nextInt(); v2 = Reader.nextInt(); k = Reader.nextInt(); q = (int)Math.ceil(n/(double)k); double busDist = binarySearch(); double time = busDist/(double)v2 + (l-busDist)/v1; System.out.printf("%.10f\n", time); } public static double binarySearch() { double lo = 0, hi = l, mid = 0, last = 0; while (hi - lo > 10e-9) { mid = (lo+hi)/2.0; if (mid == last) { break; } last = mid; if (check(mid)) { lo = mid; } else { hi = mid; } } return lo; } public static boolean check(double b) { double d = (2.0*b*v1)/(v1+v2); double m = d*(q-1)+b; return m <= l; } static class Reader { 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 long nextLong() throws IOException { return Long.parseLong(next()); } static double nextDouble() throws IOException { return Double.parseDouble(next()); } static String nextLine() { String str = ""; try { str = reader.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5 10 1 2 5", "3 6 1 2 1"]
1 second
["5.0000000000", "4.7142857143"]
NoteIn the first sample we should immediately put all five pupils to the bus. The speed of the bus equals 2 and the distance is equal to 10, so the pupils will reach the place of excursion in time 10 / 2 = 5.
Java 11
standard input
[ "binary search", "math" ]
620a9baa531f0c614cc103e70cfca6fd
The first line of the input contains five positive integers n, l, v1, v2 and k (1 ≤ n ≤ 10 000, 1 ≤ l ≤ 109, 1 ≤ v1 &lt; v2 ≤ 109, 1 ≤ k ≤ n) — the number of pupils, the distance from meeting to the place of excursion, the speed of each pupil, the speed of bus and the number of seats in the bus.
1,900
Print the real number — the minimum time in which all pupils can reach the place of excursion. Your answer will be considered correct if its absolute or relative error won't exceed 10 - 6.
standard output
PASSED
e076b3c21e70333e5bc27594b2bcde54
train_001.jsonl
1583246100
To become the king of Codeforces, Kuroni has to solve the following problem.He is given $$$n$$$ numbers $$$a_1, a_2, \dots, a_n$$$. Help Kuroni to calculate $$$\prod_{1\le i&lt;j\le n} |a_i - a_j|$$$. As result can be very big, output it modulo $$$m$$$.If you are not familiar with short notation, $$$\prod_{1\le i&lt;j\le n} |a_i - a_j|$$$ is equal to $$$|a_1 - a_2|\cdot|a_1 - a_3|\cdot$$$ $$$\dots$$$ $$$\cdot|a_1 - a_n|\cdot|a_2 - a_3|\cdot|a_2 - a_4|\cdot$$$ $$$\dots$$$ $$$\cdot|a_2 - a_n| \cdot$$$ $$$\dots$$$ $$$\cdot |a_{n-1} - a_n|$$$. In other words, this is the product of $$$|a_i - a_j|$$$ for all $$$1\le i &lt; j \le n$$$.
256 megabytes
//package cf; import java.util.*; import java.util.Scanner; import java.io.*; public class Cf{ static class Node{ int sum,occur; Node(int sum){ this.sum=sum; } } public static void main(String[]args){ Scanner in=new Scanner(System.in); PrintWriter out=new PrintWriter(System.out); long t=1;//in.nextLong(); out: while(t-->0){ int n=in.nextInt(); int m=in.nextInt(); int []a=new int [n]; for(int i=0;i<n;i++){ a[i]=in.nextInt(); } if(n<=1000){ long mul=1; for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ int aa=Math.abs(a[i]-a[j]); mul=mul*(aa%m); mul=mul%m; } } mul=mul%m; out.print(mul); }else{ out.print(0); } } in.close(); out.close(); } }
Java
["2 10\n8 5", "3 12\n1 4 5", "3 7\n1 4 9"]
1 second
["3", "0", "1"]
NoteIn the first sample, $$$|8 - 5| = 3 \equiv 3 \bmod 10$$$.In the second sample, $$$|1 - 4|\cdot|1 - 5|\cdot|4 - 5| = 3\cdot 4 \cdot 1 = 12 \equiv 0 \bmod 12$$$.In the third sample, $$$|1 - 4|\cdot|1 - 9|\cdot|4 - 9| = 3 \cdot 8 \cdot 5 = 120 \equiv 1 \bmod 7$$$.
Java 8
standard input
[ "combinatorics", "number theory", "brute force", "math" ]
bf115b24d85a0581e709c012793b248b
The first line contains two integers $$$n$$$, $$$m$$$ ($$$2\le n \le 2\cdot 10^5$$$, $$$1\le m \le 1000$$$) — number of numbers and modulo. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^9$$$).
1,600
Output the single number — $$$\prod_{1\le i&lt;j\le n} |a_i - a_j| \bmod m$$$.
standard output
PASSED
8f972f14a6635e8fa5e0ad0ae505fc94
train_001.jsonl
1583246100
To become the king of Codeforces, Kuroni has to solve the following problem.He is given $$$n$$$ numbers $$$a_1, a_2, \dots, a_n$$$. Help Kuroni to calculate $$$\prod_{1\le i&lt;j\le n} |a_i - a_j|$$$. As result can be very big, output it modulo $$$m$$$.If you are not familiar with short notation, $$$\prod_{1\le i&lt;j\le n} |a_i - a_j|$$$ is equal to $$$|a_1 - a_2|\cdot|a_1 - a_3|\cdot$$$ $$$\dots$$$ $$$\cdot|a_1 - a_n|\cdot|a_2 - a_3|\cdot|a_2 - a_4|\cdot$$$ $$$\dots$$$ $$$\cdot|a_2 - a_n| \cdot$$$ $$$\dots$$$ $$$\cdot |a_{n-1} - a_n|$$$. In other words, this is the product of $$$|a_i - a_j|$$$ for all $$$1\le i &lt; j \le n$$$.
256 megabytes
import java.util.Scanner; public class C { public static void main(String[] args) { new C(); } public C() { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); long prod = 1; if (n <= m) { long[] array = new long[n]; for (int i = 0; i < n; i++) { array[i] = sc.nextLong(); } for (int i = 0; i < n; i++) { for (int j = i+1; j < n; j++) { prod *= (array[i]-array[j]); prod %= m; } } } else { prod = 0; for (int i = 0; i < n; i++) { sc.nextInt(); } } prod = Math.abs(prod); System.out.println(prod); sc.close(); } }
Java
["2 10\n8 5", "3 12\n1 4 5", "3 7\n1 4 9"]
1 second
["3", "0", "1"]
NoteIn the first sample, $$$|8 - 5| = 3 \equiv 3 \bmod 10$$$.In the second sample, $$$|1 - 4|\cdot|1 - 5|\cdot|4 - 5| = 3\cdot 4 \cdot 1 = 12 \equiv 0 \bmod 12$$$.In the third sample, $$$|1 - 4|\cdot|1 - 9|\cdot|4 - 9| = 3 \cdot 8 \cdot 5 = 120 \equiv 1 \bmod 7$$$.
Java 8
standard input
[ "combinatorics", "number theory", "brute force", "math" ]
bf115b24d85a0581e709c012793b248b
The first line contains two integers $$$n$$$, $$$m$$$ ($$$2\le n \le 2\cdot 10^5$$$, $$$1\le m \le 1000$$$) — number of numbers and modulo. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^9$$$).
1,600
Output the single number — $$$\prod_{1\le i&lt;j\le n} |a_i - a_j| \bmod m$$$.
standard output