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 | 1564041efee057a0c2c1ddd5b1940e20 | train_001.jsonl | 1495877700 | In his spare time Vladik estimates beauty of the flags.Every flag could be represented as the matrix nβΓβm which consists of positive integers.Let's define the beauty of the flag as number of components in its matrix. We call component a set of cells with same numbers and between any pair of cells from that set there exists a path through adjacent cells from same component. Here is the example of the partitioning some flag matrix into components: But this time he decided to change something in the process. Now he wants to estimate not the entire flag, but some segment. Segment of flag can be described as a submatrix of the flag matrix with opposite corners at (1,βl) and (n,βr), where conditions 1ββ€βlββ€βrββ€βm are satisfied.Help Vladik to calculate the beauty for some segments of the given flag. | 256 megabytes | //package round416;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class E {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni(), m = ni(), Q = ni();
int[][] a = new int[n][];
for(int i = 0;i < n;i++){
a[i] = na(m);
}
int[][] qs = new int[Q][];
for(int i = 0;i < Q;i++){
qs[i] = new int[]{ni()-1, ni()-1, i};
}
int[] anss = new int[Q];
go(0, m, a, qs, anss);
for(int v : anss){
out.println(v);
}
}
void go(int l, int r, int[][] a, int[][] qs, int[] anss)
{
int n = a.length;
if(r-l == 1){
int con = n;
for(int i = 0;i < n-1;i++){
if(a[i][l] == a[i+1][l])con--;
}
for(int[] q : qs){
anss[q[2]] = con;
}
return;
}
int h = l+r>>1;
// [l,h),[h,r)
int[] consl = new int[h-l];
int[][] samel = new int[h-l][n];
{
DJSet ds = new DJSet((h-l)*n);
int con = 0;
for(int j = h-1;j >= l;j--){
con += n;
for(int i = 0;i < n-1;i++){
if(a[i][j] == a[i+1][j]){
if(!ds.union(i*(h-l)+j-l, (i+1)*(h-l)+j-l)){
con--;
}
}
}
if(j < h-1){
for(int i = 0;i < n;i++){
if(a[i][j] == a[i][j+1]){
if(!ds.union(i*(h-l)+j-l, i*(h-l)+j-l+1)){
con--;
}
}
}
}
consl[j-l] = con;
inner:
for(int i = 0;i < n;i++){
for(int k = 0;k < i;k++){
if(ds.equiv(k*(h-l)+h-1-l, i*(h-l)+h-1-l)){
samel[j-l][i] = k;
continue inner;
}
}
samel[j-l][i] = -1;
}
}
}
int[] consr = new int[r-h];
int[][] samer = new int[r-h][n];
{
DJSet ds = new DJSet((r-h)*n);
int con = 0;
for(int j = h;j < r;j++){
con += n;
for(int i = 0;i < n-1;i++){
if(a[i][j] == a[i+1][j]){
if(!ds.union(i*(r-h)+j-h, (i+1)*(r-h)+j-h)){
con--;
}
}
}
if(j > h){
for(int i = 0;i < n;i++){
if(a[i][j] == a[i][j-1]){
if(!ds.union(i*(r-h)+j-h, i*(r-h)+j-h-1)){
con--;
}
}
}
}
consr[j-h] = con;
inner:
for(int i = 0;i < n;i++){
for(int k = 0;k < i;k++){
if(ds.equiv(k*(r-h)+0, i*(r-h)+0)){
samer[j-h][i] = k;
continue inner;
}
}
samer[j-h][i] = -1;
}
}
}
// tr(l, h, r);
// tr(samel, samer);
// tr(consl, consr);
int[][] lqs = new int[qs.length][];
int[][] rqs = new int[qs.length][];
int lp = 0, rp = 0;
for(int[] q : qs){
if(q[0] < h && q[1] >= h){
int basecon = consl[q[0]-l] + consr[q[1]-h];
int[] cl = samel[q[0]-l];
int[] cr = samer[q[1]-h];
DJSet ds = new DJSet(2*n);
for(int u = 0;u < n;u++){
if(cl[u] != -1){
ds.union(u, cl[u]);
}
if(cr[u] != -1){
ds.union(u+n, cr[u]+n);
}
}
for(int u = 0;u < n;u++){
if(a[u][h-1] == a[u][h]){
if(!ds.union(u, u+n)){
basecon--;
}
}
}
anss[q[2]] = basecon;
}else if(q[1] < h){
lqs[lp++] = q;
}else{
rqs[rp++] = q;
}
}
if(lp > 0){
go(l, h, a, Arrays.copyOf(lqs, lp), anss);
}
if(rp > 0){
go(h, r, a, Arrays.copyOf(rqs, rp), anss);
}
}
public static class DJSet {
public int[] upper;
public DJSet(int n) {
upper = new int[n];
Arrays.fill(upper, -1);
}
public int root(int x) {
return upper[x] < 0 ? x : (upper[x] = root(upper[x]));
}
public boolean equiv(int x, int y) {
return root(x) == root(y);
}
public boolean union(int x, int y) {
x = root(x);
y = root(y);
if (x != y) {
if (upper[y] < upper[x]) {
int d = x;
x = y;
y = d;
}
upper[x] += upper[y];
upper[y] = x;
}
return x == y;
}
public int count() {
int ct = 0;
for (int u : upper)
if (u < 0)
ct++;
return ct;
}
}
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 E().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 | ["4 5 4\n1 1 1 1 1\n1 2 2 3 3\n1 1 1 2 5\n4 4 5 5 5\n1 5\n2 5\n1 2\n4 5"] | 2 seconds | ["6\n7\n3\n4"] | NotePartitioning on components for every segment from first test case: | Java 8 | standard input | [
"data structures",
"dsu",
"graphs"
] | 167594e0be56b9d93e62258eb052fdc3 | First line contains three space-separated integers n, m, q (1ββ€βnββ€β10, 1ββ€βm,βqββ€β105)Β β dimensions of flag matrix and number of segments respectively. Each of next n lines contains m space-separated integersΒ β description of flag matrix. All elements of flag matrix is positive integers not exceeding 106. Each of next q lines contains two space-separated integers l, r (1ββ€βlββ€βrββ€βm)Β β borders of segment which beauty Vladik wants to know. | 2,600 | For each segment print the result on the corresponding line. | standard output | |
PASSED | bc29c986563d39c44660ae548353fed0 | train_001.jsonl | 1509113100 | The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself.There are n stations in the subway. It was built according to the Bertown Transport Law: For each station i there exists exactly one train that goes from this station. Its destination station is pi, possibly piβ=βi; For each station i there exists exactly one station j such that pjβ=βi. The President will consider the convenience of subway after visiting it. The convenience is the number of ordered pairs (x,βy) such that person can start at station x and, after taking some subway trains (possibly zero), arrive at station y (1ββ€βx,βyββ€βn).The mayor of Bertown thinks that if the subway is not convenient enough, then the President might consider installing a new mayor (and, of course, the current mayor doesn't want it to happen). Before President visits the city mayor has enough time to rebuild some paths of subway, thus changing the values of pi for not more than two subway stations. Of course, breaking the Bertown Transport Law is really bad, so the subway must be built according to the Law even after changes.The mayor wants to do these changes in such a way that the convenience of the subway is maximized. Help him to calculate the maximum possible convenience he can get! | 256 megabytes | import java.io.*;
import java.util.*;
public class CODEFORCES
{
private InputStream is;
private PrintWriter out;
int time = 0, DP[], start[], end[], dist[], black[], MOD = (int) (1e9 + 7),
arr[], weight[][], x[], y[], parent[];
int MAX = 10000010, N, K;
long red[];
ArrayList<Integer>[] amp;
ArrayList<Pair>[][] pmp;
boolean b[], boo[][];
Pair prr[];
HashMap<Pair, Integer> hm = new HashMap();
long Dp[][][][] = new long[110][110][12][12];
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 Thread(null, new Runnable()
{
public void run()
{
try
{
// new CODEFORCES().soln();
} catch (Exception e)
{
System.out.println(e);
}
}
}, "1", 1 << 26).start();
new CODEFORCES().soln();
}
int ans = 0, cost = 0, D[][];
char ch[], ch1[];
int hash = 29;
TreeSet<Cell> ts;
int prime[] = new int[100000];
int dp[] = new int[50000];
TreeSet<String> tset = new TreeSet<>();
void solve()
{
int n = ni();
amp = (ArrayList<Integer>[]) new ArrayList[n];
for(int i = 0; i< n; i ++) amp[i] = new ArrayList<>();
int arr[] = na(n);
for(int i = 0; i< n ;i++) amp[i].add(arr[i]-1);
b= new boolean[n];
PriorityQueue<Integer> ts = new PriorityQueue<>(Collections.reverseOrder());
for(int i = 0; i< n; i++) {
if(!b[i]) {
ts.add(dfs(i));
}
}
if(ts.size()==1) {
System.out.println(ts.peek()*1l*ts.peek());
}
else{
int temp = ts.poll()+ts.poll();
long ans = temp*1l*temp;
for(int i : ts) {
ans += i*1l*i;
}
System.out.println(ans);
}
}
int dfs(int x) {
b[x] = true;
int ans = 1;
for(int i : amp[x]) {
if(!b[i]) {
ans += dfs(i);
}
}
return ans;
}
int calc(int x) {
String s = Integer.toString(x);
int ans = 0;
for(char ch : s.toCharArray()) ans += (ch-'0');
return ans;
}
boolean isCons(char ch){
if(ch!='a' && ch!='e' && ch!='i' && ch!='o' && ch!='u' && ch!=' ') return true;
return false;
}
void seive(int x){
b = new boolean[x+1];
for(int i = 2;i*i<=x;i++){
if(!b[i]){
for(int j = 2*i;j<=x;j+=i) b[j] = true;
}
}
}
long[][] matMul(long a[][] , long b[][], int n)
{
long res[][] = new long[n][n];
for(int i = 0;i<n;i++){
for(int j = 0;j<n;j++){
long sum = 0;
for(int k = 0;k<n;k++){
sum += (a[i][k]*1l*b[k][j]);
sum %= MOD;
}
res[i][j] = sum;
}
}
return res;
}
int min(int a, int b)
{
return (a<b)?a:b;
}
private class Cell implements Comparable<Cell>
{
int u, v, s;
public Cell(int u, int v, int s)
{
this.u = u;
this.v = v;
this.s = s;
}
public int hashCode()
{
return Objects.hash();
}
public int compareTo(Cell other)
{
return (Long.compare(s, other.s) != 0 ? (Long.compare(s, other.s)):(Long.compare(v, other.v)!=0?Long.compare(v, other.v):Long.compare(u, other.u)))
&((Long.compare(s, other.s) != 0 ? (Long.compare(s, other.s)):(Long.compare(u, other.v)!=0?Long.compare(u, other.v):Long.compare(v, other.u))));
}
public String toString()
{
return this.u + " " + this.v;
}
}
class Pair implements Comparable<Pair>
{
int u, v, i;
Pair(int u, int v)
{
this.u = u;
this.v = v;
}
Pair()
{
}
Pair(int u, int v, int i)
{
this.u = u;
this.v = v;
this.i = i;
}
public int hashCode()
{
return Objects.hash();
}
public boolean equals(Object o)
{
Pair other = (Pair) o;
return (((u == other.v && v == other.u)));
}
public int compareTo(Pair other)
{
//return (((u == other.v && v == other.u)))?0:1;
// return Integer.compare(val, other.val);
return Long.compare(u, other.u);// != 0 ? (Long.compare(u, other.u)): (Long.compare(v, other.v));
//&(Long.compare(u, other.v) != 0 ? (Long.compare(u, other.v)): (Long.compare(v, other.u))));
}
public String toString()
{
return this.u + " " + this.v;
}
}
int max(int a, int b)
{
if (a > b)
return a;
return b;
}
static class FenwickTree
{
int[] array; // 1-indexed array, In this array We save cumulative
// information to perform efficient range queries and
// updates
public FenwickTree(int size)
{
array = new int[size + 1];
}
public int rsq(int ind)
{
assert ind > 0;
int sum = 0;
while (ind > 0)
{
sum += array[ind];
// Extracting the portion up to the first significant one of the
// binary representation of 'ind' and decrementing ind by that
// number
ind -= ind & (-ind);
}
return sum;
}
public int rsq(int a, int b)
{
assert b >= a && a > 0 && b > 0;
return rsq(b) - rsq(a - 1);
}
public void update(int ind, int value)
{
assert ind > 0;
while (ind < array.length)
{
array[ind] += value;
// Extracting the portion up to the first significant one of the
// binary representation of 'ind' and incrementing ind by that
// number
ind += ind & (-ind);
}
}
public int size()
{
return array.length - 1;
}
}
void buildGraph(int n)
{
for (int i = 0; i < n; i++)
{
int x1 = ni() - 1, y1 = ni() - 1;
amp[x1].add(y1);
amp[y1].add(x1);
}
}
long modInverse(long a, long mOD2)
{
return power(a, mOD2 - 2, mOD2);
}
long power(long x, long y, long m)
{
if (y == 0)
return 1;
long p = power(x, y / 2, m) % m;
p = (p * p) % m;
return (y % 2 == 0) ? p : (x * p) % m;
}
public long gcd(long a, long b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static class ST1
{
int arr[], st[], size;
ST1(int a[])
{
arr = a.clone();
size = 10 * arr.length;
st = new int[size];
build(0, arr.length - 1, 1);
}
void build(int ss, int se, int si)
{
if (ss == se)
{
st[si] = arr[ss];
return;
}
int mid = (ss + se) / 2;
int val = 2 * si;
build(ss, mid, val);
build(mid + 1, se, val + 1);
st[si] = Math.min(st[val], st[val + 1]);
}
int get(int ss, int se, int l, int r, int si)
{
if (l > se || r < ss || l > r)
return Integer.MAX_VALUE;
if (l <= ss && r >= se)
return st[si];
int mid = (ss + se) / 2;
int val = 2 * si;
return Math.min(get(ss, mid, l, r, val),
get(mid + 1, se, l, r, val + 1));
}
}
static class ST
{
int arr[], lazy[], n;
ST(int a)
{
n = a;
arr = new int[10 * n];
lazy = new int[10 * n];
}
void up(int l, int r, int val)
{
update(0, n - 1, 0, l, r, val);
}
void update(int l, int r, int c, int x, int y, int val)
{
if (lazy[c] != 0) {
lazy[2 * c + 1] += lazy[c];
lazy[2 * c + 2] += lazy[c];
if (l == r)
arr[c] += lazy[c];
lazy[c] = 0;
}
if (l > r || x > y || l > y || x > r)
return;
if (x <= l && y >= r)
{
lazy[c] += val;
return;
}
int mid = l + r >> 1;
update(l, mid, 2 * c + 1, x, y, val);
update(mid + 1, r, 2 * c + 2, x, y, val);
arr[c] = Math.max(arr[2 * c + 1], arr[2 * c + 2]);
}
int an(int ind)
{
return ans(0, n - 1, 0, ind);
}
int ans(int l, int r, int c, int ind)
{
if (lazy[c] != 0)
{
lazy[2 * c + 1] += lazy[c];
lazy[2 * c + 2] += lazy[c];
if (l == r)
arr[c] += lazy[c];
lazy[c] = 0;
}
if (l == r)
return arr[c];
int mid = l + r >> 1;
if (mid >= ind)
return ans(l, mid, 2 * c + 1, ind);
return ans(mid + 1, r, 2 * c + 2, ind);
}
}
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, int mod)
{
long ans = 1;
while (y > 0)
{
if (y % 2 == 0)
{
x = (x * x) % mod;
y /= 2;
} else
{
ans = (x * ans) % mod;
y--;
}
}
return ans;
}
// 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 | ["3\n2 1 3", "5\n1 5 4 3 2"] | 1 second | ["9", "17"] | NoteIn the first example the mayor can change p2 to 3 and p3 to 1, so there will be 9 pairs: (1,β1), (1,β2), (1,β3), (2,β1), (2,β2), (2,β3), (3,β1), (3,β2), (3,β3).In the second example the mayor can change p2 to 4 and p3 to 5. | Java 8 | standard input | [
"dfs and similar",
"greedy",
"math"
] | ad9fd71025c5f91cece740ea95b0eb6f | The first line contains one integer number n (1ββ€βnββ€β100000) β the number of stations. The second line contains n integer numbers p1, p2, ..., pn (1ββ€βpiββ€βn) β the current structure of the subway. All these numbers are distinct. | 1,500 | Print one number β the maximum possible value of convenience. | standard output | |
PASSED | 44abfc7d0fc0c200e1df07956caa8a57 | train_001.jsonl | 1509113100 | The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself.There are n stations in the subway. It was built according to the Bertown Transport Law: For each station i there exists exactly one train that goes from this station. Its destination station is pi, possibly piβ=βi; For each station i there exists exactly one station j such that pjβ=βi. The President will consider the convenience of subway after visiting it. The convenience is the number of ordered pairs (x,βy) such that person can start at station x and, after taking some subway trains (possibly zero), arrive at station y (1ββ€βx,βyββ€βn).The mayor of Bertown thinks that if the subway is not convenient enough, then the President might consider installing a new mayor (and, of course, the current mayor doesn't want it to happen). Before President visits the city mayor has enough time to rebuild some paths of subway, thus changing the values of pi for not more than two subway stations. Of course, breaking the Bertown Transport Law is really bad, so the subway must be built according to the Law even after changes.The mayor wants to do these changes in such a way that the convenience of the subway is maximized. Help him to calculate the maximum possible convenience he can get! | 256 megabytes | import java.io.*;
import java.util.*;
public class First {
private static final Scanner sc = new Scanner(System.in);
private static final PrintWriter pw = new PrintWriter(System.out);
private static StringBuffer ans = new StringBuffer();
private static final long mod = 1000000007L;
private static HashMap<Integer, HashSet<Integer>> g = new HashMap<>();
private static boolean[] marked;
private static ArrayList<Integer> temp;
public static void main(String[] args) throws Exception {
int n = sc.nextInt();
marked = new boolean[n];
ArrayList<Integer> cc = new ArrayList<>();
for (int i = 0; i < n; i++) {
g.put(i, new HashSet<>());
marked[i] = false;
}
for (int i = 0; i < n; i++) g.get(i).add(sc.nextInt() - 1);
for (int i = 0; i < n; i++) {
if (!marked[i]) {
temp = new ArrayList<>();
dfs(i);
cc.add(temp.size());
}
}
if (cc.size() == 1) ans.append((long) Math.pow(n, 2));
else {
Collections.sort(cc, new Comparator<Integer>() {
@Override
public int compare(Integer a, Integer b) {
if (a < b) return 1;
else return -1;
}
});
long tot = (long) Math.pow(cc.get(0) + cc.get(1), 2);
for (int i = 2; i < cc.size(); i++) tot += (cc.get(i) * cc.get(i));
ans.append(tot);
}
pw.print(ans);
sc.close();
pw.close();
}
private static void dfs(int u) {
marked[u] = true;
temp.add(u);
for (int x : g.get(u)) if (!marked[x]) dfs(x);
}
}
class Scanner {
private final BufferedReader br;
private StringTokenizer st;
public Scanner(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
st = new StringTokenizer("");
}
public String next() throws IOException {
if (!st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public void close() throws IOException {
br.close();
}
}
class PrintWriter {
private final BufferedOutputStream pw;
public PrintWriter(OutputStream out) {
pw = new BufferedOutputStream(out);
}
public void print(Object o) throws IOException {
pw.write(o.toString().trim().getBytes());
pw.flush();
}
public void println(Object o) throws IOException {
print(o);
pw.write('\n');
}
public void close() throws IOException {
pw.close();
}
} | Java | ["3\n2 1 3", "5\n1 5 4 3 2"] | 1 second | ["9", "17"] | NoteIn the first example the mayor can change p2 to 3 and p3 to 1, so there will be 9 pairs: (1,β1), (1,β2), (1,β3), (2,β1), (2,β2), (2,β3), (3,β1), (3,β2), (3,β3).In the second example the mayor can change p2 to 4 and p3 to 5. | Java 8 | standard input | [
"dfs and similar",
"greedy",
"math"
] | ad9fd71025c5f91cece740ea95b0eb6f | The first line contains one integer number n (1ββ€βnββ€β100000) β the number of stations. The second line contains n integer numbers p1, p2, ..., pn (1ββ€βpiββ€βn) β the current structure of the subway. All these numbers are distinct. | 1,500 | Print one number β the maximum possible value of convenience. | standard output | |
PASSED | 29086252364919032b3881df6abb03ab | train_001.jsonl | 1509113100 | The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself.There are n stations in the subway. It was built according to the Bertown Transport Law: For each station i there exists exactly one train that goes from this station. Its destination station is pi, possibly piβ=βi; For each station i there exists exactly one station j such that pjβ=βi. The President will consider the convenience of subway after visiting it. The convenience is the number of ordered pairs (x,βy) such that person can start at station x and, after taking some subway trains (possibly zero), arrive at station y (1ββ€βx,βyββ€βn).The mayor of Bertown thinks that if the subway is not convenient enough, then the President might consider installing a new mayor (and, of course, the current mayor doesn't want it to happen). Before President visits the city mayor has enough time to rebuild some paths of subway, thus changing the values of pi for not more than two subway stations. Of course, breaking the Bertown Transport Law is really bad, so the subway must be built according to the Law even after changes.The mayor wants to do these changes in such a way that the convenience of the subway is maximized. Help him to calculate the maximum possible convenience he can get! | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.FilterInputStream;
import java.io.BufferedInputStream;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author khokharnikunj8
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
ScanReader in = new ScanReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
NOVEASY4 solver = new NOVEASY4();
solver.solve(1, in, out);
out.close();
}
static class NOVEASY4 {
int[] disjoint;
int[] size;
int n;
public void solve(int testNumber, ScanReader in, PrintWriter out) {
n = in.scanInt();
initialise();
for (int i = 1; i <= n; i++) {
union(i, in.scanInt());
}
int max1 = -1, max2 = -1;
for (int i = 1; i <= n; i++) {
if (disjoint[i] == i) {
if (max1 == -1) {
max1 = i;
} else {
if (size[i] >= size[max1]) {
max2 = max1;
max1 = i;
} else {
if (max2 == -1) max2 = i;
else if (size[i] >= size[max2]) {
max2 = i;
}
}
}
}
}
if (max2 == -1) {
out.println(((long) n * (n)));
return;
}
long ans = 0;
ans += ((long) (size[max1] + size[max2])) * (size[max1] + size[max2]);
for (int i = 1; i <= n; i++) {
if (size[i] != -2) {
if (i != max1 && i != max2) ans += ((long) size[i] * (size[i]));
}
}
out.println(ans);
}
private void initialise() {
disjoint = new int[n + 1];
size = new int[n + 1];
for (int i = 1; i <= n; i++) {
disjoint[i] = i;
}
Arrays.fill(size, 1);
}
private int findRoot(int node) {
while (disjoint[node] != node) {
disjoint[node] = disjoint[disjoint[node]];
node = disjoint[node];
}
return node;
}
private void union(int a, int b) {
int rootA = findRoot(a);
int rootB = findRoot(b);
if (rootA != rootB) {
if (size[rootA] < size[rootB]) {
disjoint[rootA] = disjoint[rootB];
size[rootB] += size[rootA];
size[rootA] = -2;
} else {
disjoint[rootB] = disjoint[rootA];
size[rootA] += size[rootB];
size[rootB] = -2;
}
}
}
}
static class ScanReader {
private byte[] buf = new byte[4 * 1024];
private int index;
private BufferedInputStream in;
private int total;
public ScanReader(InputStream inputStream) {
in = new BufferedInputStream(inputStream);
}
private int scan() {
if (index >= total) {
index = 0;
try {
total = in.read(buf);
} catch (Exception e) {
e.printStackTrace();
}
if (total <= 0) return -1;
}
return buf[index++];
}
public int scanInt() {
int 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();
}
}
return neg * integer;
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true;
else return false;
}
}
}
| Java | ["3\n2 1 3", "5\n1 5 4 3 2"] | 1 second | ["9", "17"] | NoteIn the first example the mayor can change p2 to 3 and p3 to 1, so there will be 9 pairs: (1,β1), (1,β2), (1,β3), (2,β1), (2,β2), (2,β3), (3,β1), (3,β2), (3,β3).In the second example the mayor can change p2 to 4 and p3 to 5. | Java 8 | standard input | [
"dfs and similar",
"greedy",
"math"
] | ad9fd71025c5f91cece740ea95b0eb6f | The first line contains one integer number n (1ββ€βnββ€β100000) β the number of stations. The second line contains n integer numbers p1, p2, ..., pn (1ββ€βpiββ€βn) β the current structure of the subway. All these numbers are distinct. | 1,500 | Print one number β the maximum possible value of convenience. | standard output | |
PASSED | 2e7b5f16afec9aa02aa81a2d4bcd30fb | train_001.jsonl | 1509113100 | The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself.There are n stations in the subway. It was built according to the Bertown Transport Law: For each station i there exists exactly one train that goes from this station. Its destination station is pi, possibly piβ=βi; For each station i there exists exactly one station j such that pjβ=βi. The President will consider the convenience of subway after visiting it. The convenience is the number of ordered pairs (x,βy) such that person can start at station x and, after taking some subway trains (possibly zero), arrive at station y (1ββ€βx,βyββ€βn).The mayor of Bertown thinks that if the subway is not convenient enough, then the President might consider installing a new mayor (and, of course, the current mayor doesn't want it to happen). Before President visits the city mayor has enough time to rebuild some paths of subway, thus changing the values of pi for not more than two subway stations. Of course, breaking the Bertown Transport Law is really bad, so the subway must be built according to the Law even after changes.The mayor wants to do these changes in such a way that the convenience of the subway is maximized. Help him to calculate the maximum possible convenience he can get! | 256 megabytes | /*
Keep solving problems.
*/
import java.util.*;
import java.io.*;
public class CFA {
BufferedReader br;
PrintWriter out;
StringTokenizer st;
boolean eof;
final long MOD = 1000L * 1000L * 1000L + 7;
int n;
List<List<Integer>> graph;
int cnt;
boolean[] vis;
void solve() throws IOException {
n = nextInt();
graph = new ArrayList<>();
for (int i = 0; i < n; i++) {
graph.add(new ArrayList<>());
}
for (int i = 0; i < n; i++) {
int v = nextInt() - 1;
graph.get(i).add(v);
graph.get(v).add(i);
}
List<Integer> comp = new ArrayList<>();
vis = new boolean[n];
for (int i = 0; i < n; i++) {
if (!vis[i]) {
cnt = 0;
dfs(i);
comp.add(cnt);
}
}
Collections.sort(comp);
int sz = comp.size();
long res = 0;
if (sz == 1) {
int v = comp.get(0);
out(1L * v * v);
}
else {
int v1 = comp.get(sz - 1);
int v2 = comp.get(sz - 2);
for (int i = 0; i < sz - 2; i++) {
int v = comp.get(i);
res += 1L * v * v;
}
res += 1L * (v1 + v2) * (v1 + v2);
out(res);
}
}
void dfs(int cur) {
if (vis[cur]) {
return;
}
vis[cur] = true;
cnt++;
for (int nxt : graph.get(cur)) {
dfs(nxt);
}
}
void dfs(int cur, boolean[] vis, boolean[][] graph) {
if (vis[cur]) {
return;
}
vis[cur] = true;
for (int i = 0; i < vis.length; i++) {
if (graph[cur][i]) {
dfs(i, vis, graph);
}
}
}
void shuffle(int[] a) {
int n = a.length;
for(int i = 0; i < n; i++) {
int r = i + (int) (Math.random() * (n - i));
int tmp = a[i];
a[i] = a[r];
a[r] = tmp;
}
}
private void outln(Object o) {
out.println(o);
}
private void out(Object o) {
out.print(o);
}
public CFA() throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
}
public static void main(String[] args) throws IOException {
new CFA();
}
public long[] nextLongArr(int n) throws IOException{
long[] res = new long[n];
for(int i = 0; i < n; i++)
res[i] = nextLong();
return res;
}
public int[] nextIntArr(int n) throws IOException {
int[] res = new int[n];
for(int i = 0; i < n; i++)
res[i] = nextInt();
return res;
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
eof = true;
return null;
}
}
return st.nextToken();
}
public String nextString() {
try {
return br.readLine();
} catch (IOException e) {
eof = true;
return null;
}
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
}
| Java | ["3\n2 1 3", "5\n1 5 4 3 2"] | 1 second | ["9", "17"] | NoteIn the first example the mayor can change p2 to 3 and p3 to 1, so there will be 9 pairs: (1,β1), (1,β2), (1,β3), (2,β1), (2,β2), (2,β3), (3,β1), (3,β2), (3,β3).In the second example the mayor can change p2 to 4 and p3 to 5. | Java 8 | standard input | [
"dfs and similar",
"greedy",
"math"
] | ad9fd71025c5f91cece740ea95b0eb6f | The first line contains one integer number n (1ββ€βnββ€β100000) β the number of stations. The second line contains n integer numbers p1, p2, ..., pn (1ββ€βpiββ€βn) β the current structure of the subway. All these numbers are distinct. | 1,500 | Print one number β the maximum possible value of convenience. | standard output | |
PASSED | a8f602d90ba312ae54376849bd106f92 | train_001.jsonl | 1509113100 | The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself.There are n stations in the subway. It was built according to the Bertown Transport Law: For each station i there exists exactly one train that goes from this station. Its destination station is pi, possibly piβ=βi; For each station i there exists exactly one station j such that pjβ=βi. The President will consider the convenience of subway after visiting it. The convenience is the number of ordered pairs (x,βy) such that person can start at station x and, after taking some subway trains (possibly zero), arrive at station y (1ββ€βx,βyββ€βn).The mayor of Bertown thinks that if the subway is not convenient enough, then the President might consider installing a new mayor (and, of course, the current mayor doesn't want it to happen). Before President visits the city mayor has enough time to rebuild some paths of subway, thus changing the values of pi for not more than two subway stations. Of course, breaking the Bertown Transport Law is really bad, so the subway must be built according to the Law even after changes.The mayor wants to do these changes in such a way that the convenience of the subway is maximized. Help him to calculate the maximum possible convenience he can get! | 256 megabytes | import java.math.*;
import java.util.*;
public class Main {
static class Max {
long val;
long key;
public Max(long value,long Key){
val=value;
key=Key;
}
public long getKey() {
return key;
}
public long getVal() {
return val;
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
long [] conect=new long[n+1];
long [] cCon=new long[n+1];
Max max1=new Max(0,0);
Max max2=new Max(-1,0);
boolean [] vis=new boolean[n+1];
for (int i = 1; i <=n ; i++) {
long a =in.nextLong();
conect[i]=a;
}
for (int i = 1; i <=n ; i++) {
if(vis[i])continue;
long pass=0;
long j=i;
long count=0;
while(pass!=i)
{
vis[(int)j]=true;
pass=conect[(int)j];
count++;
j=pass;
}
//System.out.println("estacion "+i+" Esta conectada a "+ count+" Estaciones");
if(count>=max1.val) {
max2 = max1;
max1 = new Max(count,i);
} else if (count > max2.val) {
max2 =new Max(count,i);
}
//System.out.println("max1 "+max1.key+" : "+max1.val+" max2 "+max2.key+" : "+max2.val);
cCon[i]=count;
}
cCon[(int)max2.key]=0;
cCon[(int)max1.key]=(max1.val +max2.val);
long oh=0;
for (long i:cCon ) {
if(oh>=Long.MAX_VALUE)System.out.println("overflow Carajo");
else oh+=i*i;
}
System.out.println(oh);
}
} | Java | ["3\n2 1 3", "5\n1 5 4 3 2"] | 1 second | ["9", "17"] | NoteIn the first example the mayor can change p2 to 3 and p3 to 1, so there will be 9 pairs: (1,β1), (1,β2), (1,β3), (2,β1), (2,β2), (2,β3), (3,β1), (3,β2), (3,β3).In the second example the mayor can change p2 to 4 and p3 to 5. | Java 8 | standard input | [
"dfs and similar",
"greedy",
"math"
] | ad9fd71025c5f91cece740ea95b0eb6f | The first line contains one integer number n (1ββ€βnββ€β100000) β the number of stations. The second line contains n integer numbers p1, p2, ..., pn (1ββ€βpiββ€βn) β the current structure of the subway. All these numbers are distinct. | 1,500 | Print one number β the maximum possible value of convenience. | standard output | |
PASSED | 6a96b227012ef81e3d720e87416e444e | train_001.jsonl | 1509113100 | The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself.There are n stations in the subway. It was built according to the Bertown Transport Law: For each station i there exists exactly one train that goes from this station. Its destination station is pi, possibly piβ=βi; For each station i there exists exactly one station j such that pjβ=βi. The President will consider the convenience of subway after visiting it. The convenience is the number of ordered pairs (x,βy) such that person can start at station x and, after taking some subway trains (possibly zero), arrive at station y (1ββ€βx,βyββ€βn).The mayor of Bertown thinks that if the subway is not convenient enough, then the President might consider installing a new mayor (and, of course, the current mayor doesn't want it to happen). Before President visits the city mayor has enough time to rebuild some paths of subway, thus changing the values of pi for not more than two subway stations. Of course, breaking the Bertown Transport Law is really bad, so the subway must be built according to the Law even after changes.The mayor wants to do these changes in such a way that the convenience of the subway is maximized. Help him to calculate the maximum possible convenience he can get! | 256 megabytes | import javax.xml.stream.util.EventReaderDelegate;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.security.KeyPair;
import java.util.*;
public class Main {
static long[][] c ;
static int[] arr;
static long n , m , k;
static int dp[];
static int[] parent; /// DSU
public static void main(String[] args) throws IOException {
Reader.init(System.in);
int n = Reader.nextInt();
parent = new int[n+1];
for (int i = 0 ; i <= n; i++){
parent[i] = i;
}
for (int i = 1 ; i <= n ; i++){
int n1 = Reader.nextInt();
parent[find(i)] = find(n1);
}
int size[] = new int[n+1];
for (int i = 1 ; i <= n ; i++){
size[find(i)]++;
}
Arrays.sort(size);
//System.out.println(Arrays.toString(size));
long ans = size[n-1] + size[n];
ans*=ans;
for (int i = 1 ; i < n-1 ; i++){
ans+=size[i]*size[i];
}
System.out.println(ans);
}
static class Node implements Comparable<Node>{
int a;
int b;
Node(int a , int b){
this.a = a;
this.b = b;
}
@Override
public int compareTo(Node o) {
if (this.a != o.a ){
return this.a - o.a;
}
else{
return this.b - this.b;
}
}
}
static int find(int a){
if (parent[a]!=a){
parent[a] = find(parent[a]);
}
return parent[a];
}
public static int coinChange(int[] coins, int amount) {
if(amount==0){
return 0;
}
dp = new int[amount];
n= coins.length;
Arrays.fill(dp,-1);
arr= coins;
return rec(amount);
}
public static int rec(int left){
System.out.println(left);
if (left < 0){
return -1;
}
if (left==0){
return 0;
}
if (dp[left-1]!=-1){
return dp[left-1];
}
int min = Integer.MAX_VALUE;
for (int i = 0 ; i < n ; i++){
int tmp = rec(left- arr[i]);
if (tmp > 0 && tmp < min){
min = 1 + tmp;
}
}
if (min== Integer.MAX_VALUE){
return -1;
}
dp[left] = min;
//System.out.println(left + " " + dp[left]);
return dp[left];
}
public static void sortbyColumn_asc(int arr[][], int col)
{
// Using built-in sort function Arrays.sort
Arrays.sort(arr, new Comparator<int[]>() {
@Override
// Compare values according to columns
public int compare(final int[] entry1,
final int[] entry2) {
// To sort in descending order revert
// the '>' Operator
if (entry1[col] > entry2[col])
return 1;
else
return -1;
}
}); // End of function call sort().
}
public static void sortbyColumn_dsc(int arr[][], int col)
{
// Using built-in sort function Arrays.sort
Arrays.sort(arr, new Comparator<int[]>() {
@Override
// Compare values according to columns
public int compare(final int[] entry1,
final int[] entry2) {
// To sort in descending order revert
// the '>' Operator
if (entry1[col] > entry2[col])
return -1;
else
return 1;
}
}); // End of function call sort().
}
static void swap(char[] arr , int i , int j){
char tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
static void swap(int[] arr , int i , int j){
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
class Node implements Comparable<Node>{
int a ;
int b;
Node(int a , int b){
this.a = a;
this.b = b;
}
public int compareTo(Node o) {
if (this.a < o.a && this.b < o.b){
return -1;
}
else{
return 1;
}
}
}
class Edge implements Comparable<Edge>{
int x , y , w;
public Edge(int x, int y, int w) {
this.x = x;
this.y = y;
this.w = w;
}
@Override
public int compareTo(Edge o) {
return this.w - o.w;
}
}
class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
/** call this method to initialize reader for InputStream */
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input) );
tokenizer = new StringTokenizer("");
}
/** get next word */
static String next() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
//TODO add check for eof if necessary
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() );
}
}
class MergeSort
{
// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l, int m, int r)
{
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;
/* Create temp arrays */
int L[] = new int [n1];
int R[] = new int [n2];
/*Copy data to temp arrays*/
for (int i=0; i<n1; ++i)
L[i] = arr[l + i];
for (int j=0; j<n2; ++j)
R[j] = arr[m + 1+ j];
/* Merge the temp arrays */
// Initial indexes of first and second subarrays
int i = 0, j = 0;
// Initial index of merged subarry array
int k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
/* Copy remaining elements of L[] if any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
/* Copy remaining elements of R[] if any */
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
// Main function that sorts arr[l..r] using
// merge()
void sort(int arr[], int l, int r)
{
if (l < r)
{
// Find the middle point
int m = (l+r)/2;
// Sort first and second halves
sort(arr, l, m);
sort(arr , m+1, r);
// Merge the sorted halves
merge(arr, l, m, r);
}
}
/* A utility function to print array of size n */
static void printArray(int arr[])
{
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
// Driver method
} | Java | ["3\n2 1 3", "5\n1 5 4 3 2"] | 1 second | ["9", "17"] | NoteIn the first example the mayor can change p2 to 3 and p3 to 1, so there will be 9 pairs: (1,β1), (1,β2), (1,β3), (2,β1), (2,β2), (2,β3), (3,β1), (3,β2), (3,β3).In the second example the mayor can change p2 to 4 and p3 to 5. | Java 8 | standard input | [
"dfs and similar",
"greedy",
"math"
] | ad9fd71025c5f91cece740ea95b0eb6f | The first line contains one integer number n (1ββ€βnββ€β100000) β the number of stations. The second line contains n integer numbers p1, p2, ..., pn (1ββ€βpiββ€βn) β the current structure of the subway. All these numbers are distinct. | 1,500 | Print one number β the maximum possible value of convenience. | standard output | |
PASSED | 06a769a3915abcb6ceacc07d56e57522 | train_001.jsonl | 1509113100 | The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself.There are n stations in the subway. It was built according to the Bertown Transport Law: For each station i there exists exactly one train that goes from this station. Its destination station is pi, possibly piβ=βi; For each station i there exists exactly one station j such that pjβ=βi. The President will consider the convenience of subway after visiting it. The convenience is the number of ordered pairs (x,βy) such that person can start at station x and, after taking some subway trains (possibly zero), arrive at station y (1ββ€βx,βyββ€βn).The mayor of Bertown thinks that if the subway is not convenient enough, then the President might consider installing a new mayor (and, of course, the current mayor doesn't want it to happen). Before President visits the city mayor has enough time to rebuild some paths of subway, thus changing the values of pi for not more than two subway stations. Of course, breaking the Bertown Transport Law is really bad, so the subway must be built according to the Law even after changes.The mayor wants to do these changes in such a way that the convenience of the subway is maximized. Help him to calculate the maximum possible convenience he can get! | 256 megabytes | import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.*;
import java.io.*;
import java.math.*;
public class Main5{
static class Pair
{
long x;
int y;
public Pair(long x, int y)
{
this.x = x;
this.y = y;
}
}
static class Compare
{
static void compare(Pair arr[], int n)
{
// Comparator to sort the pair according to second element
Arrays.sort(arr, new Comparator<Pair>() {
@Override public int compare(Pair p1, Pair p2)
{
if(p1.x>p2.x)
{
return 1;
}
else if(p2.x>p1.x)
{
return -1;
}
else
{
if(p1.y>p2.y)
{
return 1;
}
else if(p1.y<p2.y)
{
return -1;
}
else
return 0;
}
}
});
}
}
public static long pow(long a, long b)
{
long result=1;
while(b>0)
{
if (b % 2 != 0)
{
result=(result*a);
b--;
}
a=(a*a);
b /= 2;
}
return result;
}
public static long fact(long num)
{
long value=1;
int i=0;
for(i=2;i<num;i++)
{
value=((value%mod)*i%mod)%mod;
}
return value;
}
public static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
public static long lcm(int a,int b)
{
return a * (b / gcd(a, b));
}
public static long sum(int h)
{
return (h*(h+1)/2);
}
public static void dfs(int parent,boolean[] visited)
{
ArrayList<Integer> arr=new ArrayList<Integer>();
arr=graph.get(parent);
visited[parent]=true;
for(int i=0;i<arr.size();i++)
{
int num=arr.get(i);
if(visited[num]==false)
{
dfs(num,visited);
}
}
count++;
}
static int edges=0,count=0;
static TreeSet<Integer> ts;
static int f=0;
static long mod=1000000007L;
static ArrayList<ArrayList<Integer>> graph;
static int[] color;
public static void bfs(int num,boolean[] visited)
{
Queue<Integer> q=new LinkedList<>();
q.add(num);
visited[num]=true;
while(!q.isEmpty())
{
int x=q.poll();
ArrayList<Integer> al=graph.get(x);
for(int i=0;i<al.size();i++)
{
int y=al.get(i);
if(visited[y]==false)
{
q.add(y);
visited[y]=true;
}
}
}
}
public static void main(String args[])throws IOException
{
// InputReader in=new InputReader(System.in);
// OutputWriter out=new OutputWriter(System.out);
// long a=pow(26,1000000005);
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
ArrayList<Integer> ar=new ArrayList<>();
ArrayList<Integer> ar1=new ArrayList<>();
ArrayList<Integer> ar2=new ArrayList<>();
ArrayList<Integer> ar3=new ArrayList<>();
ArrayList<Integer> ar4=new ArrayList<>();
TreeSet<Integer> ts1=new TreeSet<>();
TreeSet<String> pre=new TreeSet<>();
HashMap<Long,Long> hash=new HashMap<>();
//HashMap<Long,Integer> hash1=new HashMap<Long,Integer>();
HashMap<Long,Integer> hash2=new HashMap<Long,Integer>();
/* boolean[] prime=new boolean[10001];
for(int i=2;i*i<=10000;i++)
{
if(prime[i]==false)
{
for(int j=2*i;j<=10000;j+=i)
{
prime[j]=true;
}
}
}*/
int n=i();
int[] a=new int[n];
int[] b=new int[n];
graph=new ArrayList<>();
for(int i=0;i<n;i++)
{
graph.add(new ArrayList<>());
}
for(int i=0;i<n;i++)
{
a[i]=i()-1;
graph.get(i).add(a[i]);
graph.get(a[i]).add(i);
}
// pln(graph+"");
boolean[] visited=new boolean[n];
int flag=0;
PriorityQueue<Integer> pq=new PriorityQueue<>(Collections.reverseOrder());
for(int i=0;i<n;i++)
{
if(visited[i]==false)
{
dfs(i,visited);
pq.add(count);
count=0;
}
}
long ans=0;
// pln(pq+"");
if(pq.size()>1)
{
int num=pq.poll();
int num1=pq.poll();
ans+=(long)(num+num1)*(long)(num+num1);
while(pq.size()>0)
{
int num3=pq.poll();
ans+=num3*(long)num3;
}
}
else
{
ans=pq.poll();
ans=ans*ans;
}
pln(ans+"");
}
/**/
static InputReader in=new InputReader(System.in);
static OutputWriter out=new OutputWriter(System.out);
public static long l()
{
String s=in.String();
return Long.parseLong(s);
}
public static void pln(String value)
{
System.out.println(value);
}
public static int i()
{
return in.Int();
}
public static String s()
{
return in.String();
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars== -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int Int() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String String() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return String();
}
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(Object...objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object...objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
}
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.Int();
return array;
}
} | Java | ["3\n2 1 3", "5\n1 5 4 3 2"] | 1 second | ["9", "17"] | NoteIn the first example the mayor can change p2 to 3 and p3 to 1, so there will be 9 pairs: (1,β1), (1,β2), (1,β3), (2,β1), (2,β2), (2,β3), (3,β1), (3,β2), (3,β3).In the second example the mayor can change p2 to 4 and p3 to 5. | Java 8 | standard input | [
"dfs and similar",
"greedy",
"math"
] | ad9fd71025c5f91cece740ea95b0eb6f | The first line contains one integer number n (1ββ€βnββ€β100000) β the number of stations. The second line contains n integer numbers p1, p2, ..., pn (1ββ€βpiββ€βn) β the current structure of the subway. All these numbers are distinct. | 1,500 | Print one number β the maximum possible value of convenience. | standard output | |
PASSED | d7349b1f2ede2d8ca5bc70da24e8910d | train_001.jsonl | 1509113100 | The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself.There are n stations in the subway. It was built according to the Bertown Transport Law: For each station i there exists exactly one train that goes from this station. Its destination station is pi, possibly piβ=βi; For each station i there exists exactly one station j such that pjβ=βi. The President will consider the convenience of subway after visiting it. The convenience is the number of ordered pairs (x,βy) such that person can start at station x and, after taking some subway trains (possibly zero), arrive at station y (1ββ€βx,βyββ€βn).The mayor of Bertown thinks that if the subway is not convenient enough, then the President might consider installing a new mayor (and, of course, the current mayor doesn't want it to happen). Before President visits the city mayor has enough time to rebuild some paths of subway, thus changing the values of pi for not more than two subway stations. Of course, breaking the Bertown Transport Law is really bad, so the subway must be built according to the Law even after changes.The mayor wants to do these changes in such a way that the convenience of the subway is maximized. Help him to calculate the maximum possible convenience he can get! | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class Main
{
static class Reader
{
private InputStream mIs;private byte[] buf = new byte[1024];private int curChar,numChars;public Reader() { this(System.in); }public Reader(InputStream is) { mIs = is;}
public int read() {if (numChars == -1) throw new InputMismatchException();if (curChar >= numChars) {curChar = 0;try { numChars = mIs.read(buf);} catch (IOException e) { throw new InputMismatchException();}if (numChars <= 0) return -1; }return buf[curChar++];}
public String nextLine(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isEndOfLine(c));return res.toString() ;}
public String s(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isSpaceChar(c));return res.toString();}
public long l(){int c = read();while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }long res = 0; do{ if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read();}while(!isSpaceChar(c));return res * sgn;}
public int i(){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 double d() throws IOException {return Double.parseDouble(s()) ;}
public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; }
public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; }
public int[] arr(int n){int[] ret = new int[n];for (int i = 0; i < n; i++) {ret[i] = i();}return ret;}
}
///////////////////////////////////////////////////////////////////////////////////////////
// RRRRRRRRR AAA HHH HHH IIIIIIIIIIIII LLL //
// RR RRR AAAAA HHH HHH IIIIIIIIIII LLL //
// RR RRR AAAAAAA HHH HHH III LLL //
// RR RRR AAA AAA HHHHHHHHHHH III LLL //
// RRRRRR AAA AAA HHHHHHHHHHH III LLL //
// RR RRR AAAAAAAAAAAAA HHH HHH III LLL //
// RR RRR AAA AAA HHH HHH IIIIIIIIIII LLLLLLLLLLLL //
// RR RRR AAA AAA HHH HHH IIIIIIIIIIIII LLLLLLLLLLLL //
///////////////////////////////////////////////////////////////////////////////////////////
static int n,arr[],vis[];
static int counter=0;
static class B implements Comparable<B>
{
int x;int y;
public B(int a,int b)
{
x=a;
y=b;
}
public int compareTo(B num)
{
return num.y-y;
}
}
public static void dfs(int i,int marker)
{
if(vis[i]!=0)
return;
vis[i]=marker;
counter++;
dfs(arr[i]-1,marker);
}
public static void main(String[] args)throws IOException
{
PrintWriter out= new PrintWriter(System.out);
Reader sc=new Reader();
n=sc.i();
arr=sc.arr(n);
vis=new int[n];
B store[]=new B[n];
int ct=0;
for(int i=0;i<n;i++)
{
if(vis[i]==0)
{
dfs(i,counter+1);
store[ct++]=new B(i,counter);
counter=0;
}
}
Arrays.sort(store,0,ct);
if(ct==1)
out.println((long)n*n);
else
{
long ans=(store[0].y+store[1].y)*(long)(store[0].y+store[1].y);
for(int i=2;i<ct;i++)
ans+=(long)store[i].y*store[i].y;
out.println(ans);
}
out.flush();
}
} | Java | ["3\n2 1 3", "5\n1 5 4 3 2"] | 1 second | ["9", "17"] | NoteIn the first example the mayor can change p2 to 3 and p3 to 1, so there will be 9 pairs: (1,β1), (1,β2), (1,β3), (2,β1), (2,β2), (2,β3), (3,β1), (3,β2), (3,β3).In the second example the mayor can change p2 to 4 and p3 to 5. | Java 8 | standard input | [
"dfs and similar",
"greedy",
"math"
] | ad9fd71025c5f91cece740ea95b0eb6f | The first line contains one integer number n (1ββ€βnββ€β100000) β the number of stations. The second line contains n integer numbers p1, p2, ..., pn (1ββ€βpiββ€βn) β the current structure of the subway. All these numbers are distinct. | 1,500 | Print one number β the maximum possible value of convenience. | standard output | |
PASSED | cb3efd075f463176aa54e98b5c6da255 | train_001.jsonl | 1509113100 | The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself.There are n stations in the subway. It was built according to the Bertown Transport Law: For each station i there exists exactly one train that goes from this station. Its destination station is pi, possibly piβ=βi; For each station i there exists exactly one station j such that pjβ=βi. The President will consider the convenience of subway after visiting it. The convenience is the number of ordered pairs (x,βy) such that person can start at station x and, after taking some subway trains (possibly zero), arrive at station y (1ββ€βx,βyββ€βn).The mayor of Bertown thinks that if the subway is not convenient enough, then the President might consider installing a new mayor (and, of course, the current mayor doesn't want it to happen). Before President visits the city mayor has enough time to rebuild some paths of subway, thus changing the values of pi for not more than two subway stations. Of course, breaking the Bertown Transport Law is really bad, so the subway must be built according to the Law even after changes.The mayor wants to do these changes in such a way that the convenience of the subway is maximized. Help him to calculate the maximum possible convenience he can get! | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.Collections;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
BertownSubway solver = new BertownSubway();
solver.solve(1, in, out);
out.close();
}
static class BertownSubway {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt(), c = 0;
int arr[] = new int[n + 1];
ArrayList<Integer> al = new ArrayList<>();
for (int i = 1; i <= n; i++) arr[i] = in.nextInt();
boolean v[] = new boolean[n + 1];
for (int i = 1; i <= n; i++) {
if (v[i]) continue;
else {
int t = i;
c = 0;
while (!v[t]) {
v[t] = true;
t = arr[t];
c++;
}
}
al.add(c);
}
Collections.sort(al);
if (al.size() >= 2) {
int a = al.remove(al.size() - 1);
int b = al.remove(al.size() - 1);
al.add(a + b);
}
long res = 0;
for (Integer el : al) {
res += (long) el * (long) el;
}
out.println(res);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void println(long i) {
writer.println(i);
}
}
}
| Java | ["3\n2 1 3", "5\n1 5 4 3 2"] | 1 second | ["9", "17"] | NoteIn the first example the mayor can change p2 to 3 and p3 to 1, so there will be 9 pairs: (1,β1), (1,β2), (1,β3), (2,β1), (2,β2), (2,β3), (3,β1), (3,β2), (3,β3).In the second example the mayor can change p2 to 4 and p3 to 5. | Java 8 | standard input | [
"dfs and similar",
"greedy",
"math"
] | ad9fd71025c5f91cece740ea95b0eb6f | The first line contains one integer number n (1ββ€βnββ€β100000) β the number of stations. The second line contains n integer numbers p1, p2, ..., pn (1ββ€βpiββ€βn) β the current structure of the subway. All these numbers are distinct. | 1,500 | Print one number β the maximum possible value of convenience. | standard output | |
PASSED | 179e6b8bdcda1f207c502957cecfa6b3 | train_001.jsonl | 1509113100 | The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself.There are n stations in the subway. It was built according to the Bertown Transport Law: For each station i there exists exactly one train that goes from this station. Its destination station is pi, possibly piβ=βi; For each station i there exists exactly one station j such that pjβ=βi. The President will consider the convenience of subway after visiting it. The convenience is the number of ordered pairs (x,βy) such that person can start at station x and, after taking some subway trains (possibly zero), arrive at station y (1ββ€βx,βyββ€βn).The mayor of Bertown thinks that if the subway is not convenient enough, then the President might consider installing a new mayor (and, of course, the current mayor doesn't want it to happen). Before President visits the city mayor has enough time to rebuild some paths of subway, thus changing the values of pi for not more than two subway stations. Of course, breaking the Bertown Transport Law is really bad, so the subway must be built according to the Law even after changes.The mayor wants to do these changes in such a way that the convenience of the subway is maximized. Help him to calculate the maximum possible convenience he can get! | 256 megabytes | import java.util.*;
import java.io.*;
public class CF884C {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] child = new int[n+1];
for(int i = 1; i < child.length; i++){
child[i] = sc.nextInt();
}
long[] sizes = new long[n+1];
boolean[] visited = new boolean[n+1];
for(int i = 1; i < sizes.length; i++){
sizes[i] = dfs(i, child, visited);
}
long max = -1;
long secondMax = -1;
long sum = 0;
for(int i = 1; i < child.length; i++){
sum += sizes[i]*sizes[i];
if(sizes[i] > max) {
secondMax = max;
max = sizes[i];
}
else if(sizes[i] > secondMax){
secondMax = sizes[i];
}
}
sum = sum - (max*max + secondMax*secondMax);
sum += Math.pow((max+secondMax),2);
if(n==1)
System.out.println(1);
else
System.out.println(sum);
}
public static int dfs(int i, int[] child, boolean[] visited){
if(visited[i])
return 0;
visited[i] = true;
return dfs(child[i], child, visited) + 1;
}
} | Java | ["3\n2 1 3", "5\n1 5 4 3 2"] | 1 second | ["9", "17"] | NoteIn the first example the mayor can change p2 to 3 and p3 to 1, so there will be 9 pairs: (1,β1), (1,β2), (1,β3), (2,β1), (2,β2), (2,β3), (3,β1), (3,β2), (3,β3).In the second example the mayor can change p2 to 4 and p3 to 5. | Java 8 | standard input | [
"dfs and similar",
"greedy",
"math"
] | ad9fd71025c5f91cece740ea95b0eb6f | The first line contains one integer number n (1ββ€βnββ€β100000) β the number of stations. The second line contains n integer numbers p1, p2, ..., pn (1ββ€βpiββ€βn) β the current structure of the subway. All these numbers are distinct. | 1,500 | Print one number β the maximum possible value of convenience. | standard output | |
PASSED | 131e7cc6c669f55c497bcb9ef9459fe8 | train_001.jsonl | 1509113100 | The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself.There are n stations in the subway. It was built according to the Bertown Transport Law: For each station i there exists exactly one train that goes from this station. Its destination station is pi, possibly piβ=βi; For each station i there exists exactly one station j such that pjβ=βi. The President will consider the convenience of subway after visiting it. The convenience is the number of ordered pairs (x,βy) such that person can start at station x and, after taking some subway trains (possibly zero), arrive at station y (1ββ€βx,βyββ€βn).The mayor of Bertown thinks that if the subway is not convenient enough, then the President might consider installing a new mayor (and, of course, the current mayor doesn't want it to happen). Before President visits the city mayor has enough time to rebuild some paths of subway, thus changing the values of pi for not more than two subway stations. Of course, breaking the Bertown Transport Law is really bad, so the subway must be built according to the Law even after changes.The mayor wants to do these changes in such a way that the convenience of the subway is maximized. Help him to calculate the maximum possible convenience he can get! | 256 megabytes | import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
/**
* Created by Giorgi on 9/12/2015.
*/
public class Main {
private static boolean[] marked;
private static int[] path;
private static long count;
private static int n;
private static List<Long> conv = new ArrayList<>();
public static void main(String[] args) {
// BufferedReader br = new BufferedReader(new
// InputStreamReader(System.in));
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
marked = new boolean[n];
path = new int[n];
for (int i = 0; i < n; i++) {
path[i] = sc.nextInt();
}
for (int i = 0; i < n; i++) {
if (!marked[i]) {
marked[i] = true;
conv.add(findLength(path[i]-1, i, 1L));
}
}
Collections.sort(conv);
if (conv.size() == 1) {
System.out.println(conv.get(0) * conv.get(0));
} else {
long sum = 0;
for (int i = 0; i < conv.size()-2; i++) {
long tmp = conv.get(i) * conv.get(i);
sum += tmp;
}
long last = conv.get(conv.size()-1) + conv.get(conv.size()-2);
sum += last * last;
System.out.println(sum);
}
}
private static long findLength(int current, int start, long length) {
marked[current] = true;
if (current == start) {
return length;
}
return findLength(path[current]-1, start, length + 1);
}
}
| Java | ["3\n2 1 3", "5\n1 5 4 3 2"] | 1 second | ["9", "17"] | NoteIn the first example the mayor can change p2 to 3 and p3 to 1, so there will be 9 pairs: (1,β1), (1,β2), (1,β3), (2,β1), (2,β2), (2,β3), (3,β1), (3,β2), (3,β3).In the second example the mayor can change p2 to 4 and p3 to 5. | Java 8 | standard input | [
"dfs and similar",
"greedy",
"math"
] | ad9fd71025c5f91cece740ea95b0eb6f | The first line contains one integer number n (1ββ€βnββ€β100000) β the number of stations. The second line contains n integer numbers p1, p2, ..., pn (1ββ€βpiββ€βn) β the current structure of the subway. All these numbers are distinct. | 1,500 | Print one number β the maximum possible value of convenience. | standard output | |
PASSED | fd098c5d50120a10e9fff9ddc3e3014f | train_001.jsonl | 1509113100 | The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself.There are n stations in the subway. It was built according to the Bertown Transport Law: For each station i there exists exactly one train that goes from this station. Its destination station is pi, possibly piβ=βi; For each station i there exists exactly one station j such that pjβ=βi. The President will consider the convenience of subway after visiting it. The convenience is the number of ordered pairs (x,βy) such that person can start at station x and, after taking some subway trains (possibly zero), arrive at station y (1ββ€βx,βyββ€βn).The mayor of Bertown thinks that if the subway is not convenient enough, then the President might consider installing a new mayor (and, of course, the current mayor doesn't want it to happen). Before President visits the city mayor has enough time to rebuild some paths of subway, thus changing the values of pi for not more than two subway stations. Of course, breaking the Bertown Transport Law is really bad, so the subway must be built according to the Law even after changes.The mayor wants to do these changes in such a way that the convenience of the subway is maximized. Help him to calculate the maximum possible convenience he can get! | 256 megabytes | import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.InputMismatchException;
import java.util.List;
public class Main {
private static final int MAXN = 5000;
private static final String NO = "NO";
private static final String YES = "YES";
InputStream is;
PrintWriter out;
String INPUT = "";
private static final long MOD = 1000000007L;
void solve() {
int N = ni();
int[] a = na(N);
boolean vis[] = new boolean[N];
List<Integer> l = new ArrayList<Integer>();
for (int i = 0; i < N; i++) {
if (vis[i])
continue;
vis[i] = true;
int sz = 1;
for (int j = a[i]; !vis[j - 1]; j = a[j - 1]) {
vis[j - 1] = true;
sz++;
}
l.add(sz);
}
long ans = 0;
Collections.sort(l);
if (l.size() > 1) {
Integer n = l.remove(l.size() - 1);
l.set(l.size() - 1, l.get(l.size() - 1) + n);
}
for (int i : l)
ans += ((long) i) * i;
out.println(ans);
}
long power(long a, long b) {
long x = 1, y = a;
while (b > 0) {
if (b % 2 != 0) {
x = (x * y) % MOD;
}
y = (y * y) % MOD;
b /= 2;
}
return x % MOD;
}
private long gcd(long a, long b) {
while (a != 0) {
long tmp = b % a;
b = a;
a = tmp;
}
return b;
}
void run() throws Exception {
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
if (!INPUT.isEmpty())
tr(System.currentTimeMillis() - s + "ms");
}
public static void main(String[] args) throws Exception {
new Main().run();
}
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private boolean vis[];
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) {
if (!(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 List<Integer> na2(int n) {
List<Integer> a = new ArrayList<Integer>();
for (int i = 0; i < n; i++)
a.add(ni());
return a;
}
private int[][] na(int n, int m) {
int[][] a = new int[n][];
for (int i = 0; i < n; i++)
a[i] = na(m);
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(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nl();
return a;
}
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 static void tr(Object... o) {
System.out.println(Arrays.deepToString(o));
}
} | Java | ["3\n2 1 3", "5\n1 5 4 3 2"] | 1 second | ["9", "17"] | NoteIn the first example the mayor can change p2 to 3 and p3 to 1, so there will be 9 pairs: (1,β1), (1,β2), (1,β3), (2,β1), (2,β2), (2,β3), (3,β1), (3,β2), (3,β3).In the second example the mayor can change p2 to 4 and p3 to 5. | Java 8 | standard input | [
"dfs and similar",
"greedy",
"math"
] | ad9fd71025c5f91cece740ea95b0eb6f | The first line contains one integer number n (1ββ€βnββ€β100000) β the number of stations. The second line contains n integer numbers p1, p2, ..., pn (1ββ€βpiββ€βn) β the current structure of the subway. All these numbers are distinct. | 1,500 | Print one number β the maximum possible value of convenience. | standard output | |
PASSED | 9e87f8738db938ac1fb18295de7e6287 | train_001.jsonl | 1509113100 | The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself.There are n stations in the subway. It was built according to the Bertown Transport Law: For each station i there exists exactly one train that goes from this station. Its destination station is pi, possibly piβ=βi; For each station i there exists exactly one station j such that pjβ=βi. The President will consider the convenience of subway after visiting it. The convenience is the number of ordered pairs (x,βy) such that person can start at station x and, after taking some subway trains (possibly zero), arrive at station y (1ββ€βx,βyββ€βn).The mayor of Bertown thinks that if the subway is not convenient enough, then the President might consider installing a new mayor (and, of course, the current mayor doesn't want it to happen). Before President visits the city mayor has enough time to rebuild some paths of subway, thus changing the values of pi for not more than two subway stations. Of course, breaking the Bertown Transport Law is really bad, so the subway must be built according to the Law even after changes.The mayor wants to do these changes in such a way that the convenience of the subway is maximized. Help him to calculate the maximum possible convenience he can get! | 256 megabytes | import java.awt.image.IndexColorModel;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;
public class A {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni();
int p[] = new int[n+1];
for(int i=0;i<n;i++) p[i+1] = ni();
int visited[] = new int[n+1];
long len[] = new long[n+1];
ArrayList<Long> cycles = new ArrayList<Long>();
for(int i=1;i<=n;i++){
if(visited[i]==0){
visited[i] = 1;
len[i] = 1 + dfs(i, visited, p);
cycles.add(len[i]);
}
}
// out.println(Arrays.toString(cycles.toArray()));
Collections.sort(cycles, Collections.reverseOrder());
long ans = 0;
if(cycles.size()<=1){
ans += cycles.get(0) * cycles.get(0);
}else{
long x = (cycles.get(0) + cycles.get(1));
ans += (x*x);
for(int i=2;i<cycles.size();i++){
ans += (cycles.get(i) * cycles.get(i));
}
}
out.println(ans);
}
static int dfs(int i, int visited[], int p[]){
int v = p[i];
if(visited[v]==0){
visited[v] = 1;
return 1 + dfs(v, visited, p);
}else{
return 0;
}
}
static void printArr(int ar[][], int n){
for(int i=0;i<n;i++) System.out.println(Arrays.toString(ar[i]));
System.out.println();
}
static void printArr(char ar[][], int n){
for(int i=0;i<n;i++) System.out.println(Arrays.toString(ar[i]));
System.out.println();
}
void run() throws Exception
{
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
if(!INPUT.isEmpty())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 static void tr(Object... o) { System.out.println(Arrays.deepToString(o)); }
} | Java | ["3\n2 1 3", "5\n1 5 4 3 2"] | 1 second | ["9", "17"] | NoteIn the first example the mayor can change p2 to 3 and p3 to 1, so there will be 9 pairs: (1,β1), (1,β2), (1,β3), (2,β1), (2,β2), (2,β3), (3,β1), (3,β2), (3,β3).In the second example the mayor can change p2 to 4 and p3 to 5. | Java 8 | standard input | [
"dfs and similar",
"greedy",
"math"
] | ad9fd71025c5f91cece740ea95b0eb6f | The first line contains one integer number n (1ββ€βnββ€β100000) β the number of stations. The second line contains n integer numbers p1, p2, ..., pn (1ββ€βpiββ€βn) β the current structure of the subway. All these numbers are distinct. | 1,500 | Print one number β the maximum possible value of convenience. | standard output | |
PASSED | ffd8c26715e4356465c40e69db3b2ffc | train_001.jsonl | 1509113100 | The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself.There are n stations in the subway. It was built according to the Bertown Transport Law: For each station i there exists exactly one train that goes from this station. Its destination station is pi, possibly piβ=βi; For each station i there exists exactly one station j such that pjβ=βi. The President will consider the convenience of subway after visiting it. The convenience is the number of ordered pairs (x,βy) such that person can start at station x and, after taking some subway trains (possibly zero), arrive at station y (1ββ€βx,βyββ€βn).The mayor of Bertown thinks that if the subway is not convenient enough, then the President might consider installing a new mayor (and, of course, the current mayor doesn't want it to happen). Before President visits the city mayor has enough time to rebuild some paths of subway, thus changing the values of pi for not more than two subway stations. Of course, breaking the Bertown Transport Law is really bad, so the subway must be built according to the Law even after changes.The mayor wants to do these changes in such a way that the convenience of the subway is maximized. Help him to calculate the maximum possible convenience he can get! | 256 megabytes | import java.io.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public class P884C {
private static class HpReader {
private BufferedReader in;
private String containingDirPath;
public HpReader(String dir, String inFile, String outFile) {
initAndRedirectInOut(dir, inFile, outFile);
}
private static int ivl(String val) {
return Integer.parseInt(val);
}
private void initAndRedirectInOut(String dir, String inFile, String outFile) {
if (dir != null) {
try {
containingDirPath = dir.endsWith(File.separator) ? dir : dir + File.separator;
if (isDebug && inFile != null) System.setIn(new FileInputStream(new File(containingDirPath + inFile)));
if (isDebug && outFile != null) System.setOut(new PrintStream(new File(containingDirPath + outFile)));
} catch (FileNotFoundException e) {
// Do nothing, stdin & stdout are not redirected
}
}
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
private String nextSingleStr() throws IOException {
return in.readLine();
}
private String[] nextLineStr() throws IOException {
return nextLineStr(0);
}
private String[] nextLineStr(int offset) throws IOException {
String[] inp = nextSingleStr().split(" ");
String[] rs = new String[offset + inp.length];
System.arraycopy(inp, 0, rs, offset, inp.length);
return rs;
}
private int nextSingleInt() throws IOException {
return ivl(in.readLine());
}
private int[] nextLineInt() throws IOException {
return nextLineInt(0);
}
private int[] nextLineInt(int offset) throws IOException {
String[] inp = nextLineStr();
int[] rs = new int[offset + inp.length];
for (int i = 0; i < inp.length; i++) rs[offset + i] = ivl(inp[i]);
return rs;
}
private int[][] nextMatInt(int lineCount) throws IOException {
return nextMatInt(lineCount, 0, 0);
}
private int[][] nextMatInt(int lineCount, int rowOffset, int colOffset) throws IOException {
int[][] rs = new int[rowOffset + lineCount][];
for (int i = rowOffset; i < rs.length; i++) rs[i] = nextLineInt(colOffset);
return rs;
}
}
private static class HpHelper {
private static final String LOCAL_DEBUG_FLAG = "COM_PROG_DEBUG";
private static boolean isDebug() {
try {
return Boolean.parseBoolean(System.getenv(HpHelper.LOCAL_DEBUG_FLAG));
} catch (Exception e) {
return false;
}
}
private static String createDelimiter(String delimiter) {
return delimiter == null ? " " : delimiter;
}
private static void println(int[] data, String delimiter) {
delimiter = createDelimiter(delimiter);
for (int t : data) out.print(t + delimiter);
out.println();
}
private static void println(long[] data, String delimiter) {
delimiter = createDelimiter(delimiter);
for (long t : data) out.print(t + delimiter);
out.println();
}
private static <T> void println(T[] data, String delimiter) {
delimiter = createDelimiter(delimiter);
for (T t : data) {
if (t instanceof int[]) {
println((int[]) t, delimiter);
} else if (t instanceof long[]) {
println((long[]) t, delimiter);
} else if (t instanceof Object[]) {
println((Object[]) t, delimiter);
} else {
out.print(t + delimiter);
}
}
out.println();
}
}
private static boolean isDebug = HpHelper.isDebug();
private static HpReader in = new HpReader("/Users/apple/Work/WorkSpaces/CompetitiveProg/", "in.txt", null);
private static PrintWriter out;
public static void main(String[] args) throws IOException {
int n = in.nextSingleInt();
int[] des = in.nextLineInt(1);
boolean[] visited = new boolean[n + 1];
List<Integer> cSize = new ArrayList<>();
for (int i = 1; i <= n; i++) {
int cur = i, count = 0;
while (!visited[cur]) {
visited[cur] = true;
count += 1;
cur = des[cur];
}
if (count > 0) cSize.add(count);
}
Collections.sort(cSize);
long rs = 0, n0 = 0, n1 = 0, n2 = 0, taken = 0;
n0 = cSize.get(cSize.size() - 1); taken += 1;
if (cSize.size() >= 2) {
n1 = cSize.get(cSize.size() - 2);
taken += 1;
}
if (cSize.size() >= 3) {
n2 = cSize.get(cSize.size() - 3);
taken += 1;
}
rs = (n0 + n1) * (n0 + n1) + n2 * n2;
for (int i = 0; i < cSize.size() - taken; i++) rs += cSize.get(i) * cSize.get(i);
out.println(rs);
out.flush();
}
}
| Java | ["3\n2 1 3", "5\n1 5 4 3 2"] | 1 second | ["9", "17"] | NoteIn the first example the mayor can change p2 to 3 and p3 to 1, so there will be 9 pairs: (1,β1), (1,β2), (1,β3), (2,β1), (2,β2), (2,β3), (3,β1), (3,β2), (3,β3).In the second example the mayor can change p2 to 4 and p3 to 5. | Java 8 | standard input | [
"dfs and similar",
"greedy",
"math"
] | ad9fd71025c5f91cece740ea95b0eb6f | The first line contains one integer number n (1ββ€βnββ€β100000) β the number of stations. The second line contains n integer numbers p1, p2, ..., pn (1ββ€βpiββ€βn) β the current structure of the subway. All these numbers are distinct. | 1,500 | Print one number β the maximum possible value of convenience. | standard output | |
PASSED | b010a847d687992a4f752aa598f976e0 | train_001.jsonl | 1509113100 | The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself.There are n stations in the subway. It was built according to the Bertown Transport Law: For each station i there exists exactly one train that goes from this station. Its destination station is pi, possibly piβ=βi; For each station i there exists exactly one station j such that pjβ=βi. The President will consider the convenience of subway after visiting it. The convenience is the number of ordered pairs (x,βy) such that person can start at station x and, after taking some subway trains (possibly zero), arrive at station y (1ββ€βx,βyββ€βn).The mayor of Bertown thinks that if the subway is not convenient enough, then the President might consider installing a new mayor (and, of course, the current mayor doesn't want it to happen). Before President visits the city mayor has enough time to rebuild some paths of subway, thus changing the values of pi for not more than two subway stations. Of course, breaking the Bertown Transport Law is really bad, so the subway must be built according to the Law even after changes.The mayor wants to do these changes in such a way that the convenience of the subway is maximized. Help him to calculate the maximum possible convenience he can get! | 256 megabytes | import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.StringTokenizer;
public class C {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt();
UnionFind uf = new UnionFind(n);
for (int i = 0; i < n; i++) {
uf.unionSet(i, sc.nextInt() - 1);
}
int[] c = new int[n];
for (int i = 0; i < n; i++) {
c[uf.findSet(i)]++;
}
ArrayList<Integer> lis = new ArrayList<>();
for (int i = 0; i < n; i++) {
if(c[i] > 0)
lis.add(c[i]);
}
long ans = 0;
if(lis.size() == 1) {
ans = 1l * n * n;
}
else {
Collections.sort(lis, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
});
ans = 1l * (lis.get(0) + lis.get(1)) * (lis.get(0) + lis.get(1));
for (int i = 2; i < lis.size(); i++) {
ans += 1l * lis.get(i) * lis.get(i);
}
}
out.println(ans);
out.flush();
out.close();
}
static class UnionFind {
int[] p, rank, setSize;
int numSets;
public UnionFind(int N)
{
p = new int[numSets = N];
rank = new int[N];
setSize = new int[N];
for (int i = 0; i < N; i++) { p[i] = i; setSize[i] = 1; }
}
public int findSet(int i) { return p[i] == i ? i : (p[i] = findSet(p[i])); }
public boolean isSameSet(int i, int j) { return findSet(i) == findSet(j); }
public void unionSet(int i, int j)
{
if (isSameSet(i, j))
return;
numSets--;
int x = findSet(i), y = findSet(j);
if(rank[x] > rank[y]) { p[y] = x; setSize[x] += setSize[y]; }
else
{ p[x] = y; setSize[y] += setSize[x];
if(rank[x] == rank[y]) rank[y]++;
}
}
public int numDisjointSets() { return numSets; }
public int sizeOfSet(int i) { return setSize[findSet(i)]; }
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public Scanner(String file) throws FileNotFoundException{ br = new BufferedReader(new FileReader(file));}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public double nextDouble() throws IOException
{
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if(x.charAt(0) == '-')
{
neg = true;
start++;
}
for(int i = start; i < x.length(); i++)
if(x.charAt(i) == '.')
{
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
}
else
{
sb.append(x.charAt(i));
if(dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg?-1:1);
}
public boolean ready() throws IOException {return br.ready();}
}
}
| Java | ["3\n2 1 3", "5\n1 5 4 3 2"] | 1 second | ["9", "17"] | NoteIn the first example the mayor can change p2 to 3 and p3 to 1, so there will be 9 pairs: (1,β1), (1,β2), (1,β3), (2,β1), (2,β2), (2,β3), (3,β1), (3,β2), (3,β3).In the second example the mayor can change p2 to 4 and p3 to 5. | Java 8 | standard input | [
"dfs and similar",
"greedy",
"math"
] | ad9fd71025c5f91cece740ea95b0eb6f | The first line contains one integer number n (1ββ€βnββ€β100000) β the number of stations. The second line contains n integer numbers p1, p2, ..., pn (1ββ€βpiββ€βn) β the current structure of the subway. All these numbers are distinct. | 1,500 | Print one number β the maximum possible value of convenience. | standard output | |
PASSED | 1c74b850deb83e051b74000942d644ee | train_001.jsonl | 1509113100 | The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself.There are n stations in the subway. It was built according to the Bertown Transport Law: For each station i there exists exactly one train that goes from this station. Its destination station is pi, possibly piβ=βi; For each station i there exists exactly one station j such that pjβ=βi. The President will consider the convenience of subway after visiting it. The convenience is the number of ordered pairs (x,βy) such that person can start at station x and, after taking some subway trains (possibly zero), arrive at station y (1ββ€βx,βyββ€βn).The mayor of Bertown thinks that if the subway is not convenient enough, then the President might consider installing a new mayor (and, of course, the current mayor doesn't want it to happen). Before President visits the city mayor has enough time to rebuild some paths of subway, thus changing the values of pi for not more than two subway stations. Of course, breaking the Bertown Transport Law is really bad, so the subway must be built according to the Law even after changes.The mayor wants to do these changes in such a way that the convenience of the subway is maximized. Help him to calculate the maximum possible convenience he can get! | 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
{
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
HashMap<Integer, Integer> hm = new HashMap<>();
long top1 = 0; long top2 = 0; long sum = 0L;
for(int i =1; i <= n; i++) {
hm.put(i, scan.nextInt());
}
while (!hm.isEmpty()) {
Integer first = hm.keySet().iterator().next();
Integer next = first; long c = 0;
do {
c++;
next = hm.remove(next);
} while (!first.equals(next));
if (c > top1) {
top2 = top1; top1 = c;
} else if (c > top2) {
top2 = c;
}
sum += c * c;
}
if (top2 == 0) {
System.out.println(sum);
} else {
long q = sum - top1 * top1 - top2 * top2 + (top1 + top2) * (top1 + top2);
System.out.println(q);
}
}
} | Java | ["3\n2 1 3", "5\n1 5 4 3 2"] | 1 second | ["9", "17"] | NoteIn the first example the mayor can change p2 to 3 and p3 to 1, so there will be 9 pairs: (1,β1), (1,β2), (1,β3), (2,β1), (2,β2), (2,β3), (3,β1), (3,β2), (3,β3).In the second example the mayor can change p2 to 4 and p3 to 5. | Java 8 | standard input | [
"dfs and similar",
"greedy",
"math"
] | ad9fd71025c5f91cece740ea95b0eb6f | The first line contains one integer number n (1ββ€βnββ€β100000) β the number of stations. The second line contains n integer numbers p1, p2, ..., pn (1ββ€βpiββ€βn) β the current structure of the subway. All these numbers are distinct. | 1,500 | Print one number β the maximum possible value of convenience. | standard output | |
PASSED | e36ee9f09b6158517b77bd7f422aa7dc | train_001.jsonl | 1509113100 | The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself.There are n stations in the subway. It was built according to the Bertown Transport Law: For each station i there exists exactly one train that goes from this station. Its destination station is pi, possibly piβ=βi; For each station i there exists exactly one station j such that pjβ=βi. The President will consider the convenience of subway after visiting it. The convenience is the number of ordered pairs (x,βy) such that person can start at station x and, after taking some subway trains (possibly zero), arrive at station y (1ββ€βx,βyββ€βn).The mayor of Bertown thinks that if the subway is not convenient enough, then the President might consider installing a new mayor (and, of course, the current mayor doesn't want it to happen). Before President visits the city mayor has enough time to rebuild some paths of subway, thus changing the values of pi for not more than two subway stations. Of course, breaking the Bertown Transport Law is really bad, so the subway must be built according to the Law even after changes.The mayor wants to do these changes in such a way that the convenience of the subway is maximized. Help him to calculate the maximum possible convenience he can get! | 256 megabytes | import java.io.*;
import java.util.*;
/*
TASK: CFC
LANG: JAVA
*/
public class CFC {
static int n , cnt;
static int[] p;
static long[] sz;
static boolean[] seen;
public static void main(String[] args) throws IOException {
FastScanner in = new FastScanner(System.in);
n = in.nextInt();
p = new int[n];
sz = new long[n];
seen = new boolean[n];
for(int i = 0;i < n; i++){
p[i] = in.nextInt() - 1;
}
for(int i = 0;i < n; i++){
if(!seen[i]){
sz[cnt++] = dfs(i);
}
}
Arrays.sort(sz);
if(cnt == 1){
System.out.println((long)n*n);
return;
}
long sum = 0;
for(int i = n-3; i >= n-cnt; i--){
sum += sz[i]*sz[i];
}
sz[0] = sz[n-1] + sz[n-2];
sum += sz[0]*sz[0];
System.out.println(sum);
}
private static int dfs(int i){
if(seen[i])return 0;
seen[i] = true;
return 1 + dfs(p[i]);
}
private static 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;
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String next() {
int c = read();
while (isSpaceChar(c)) c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = read();
while (isEndline(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndline(c));
return res.toString();
}
}
}
| Java | ["3\n2 1 3", "5\n1 5 4 3 2"] | 1 second | ["9", "17"] | NoteIn the first example the mayor can change p2 to 3 and p3 to 1, so there will be 9 pairs: (1,β1), (1,β2), (1,β3), (2,β1), (2,β2), (2,β3), (3,β1), (3,β2), (3,β3).In the second example the mayor can change p2 to 4 and p3 to 5. | Java 8 | standard input | [
"dfs and similar",
"greedy",
"math"
] | ad9fd71025c5f91cece740ea95b0eb6f | The first line contains one integer number n (1ββ€βnββ€β100000) β the number of stations. The second line contains n integer numbers p1, p2, ..., pn (1ββ€βpiββ€βn) β the current structure of the subway. All these numbers are distinct. | 1,500 | Print one number β the maximum possible value of convenience. | standard output | |
PASSED | 1b93ec016d781334ee6574807fa3d727 | train_001.jsonl | 1509113100 | The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself.There are n stations in the subway. It was built according to the Bertown Transport Law: For each station i there exists exactly one train that goes from this station. Its destination station is pi, possibly piβ=βi; For each station i there exists exactly one station j such that pjβ=βi. The President will consider the convenience of subway after visiting it. The convenience is the number of ordered pairs (x,βy) such that person can start at station x and, after taking some subway trains (possibly zero), arrive at station y (1ββ€βx,βyββ€βn).The mayor of Bertown thinks that if the subway is not convenient enough, then the President might consider installing a new mayor (and, of course, the current mayor doesn't want it to happen). Before President visits the city mayor has enough time to rebuild some paths of subway, thus changing the values of pi for not more than two subway stations. Of course, breaking the Bertown Transport Law is really bad, so the subway must be built according to the Law even after changes.The mayor wants to do these changes in such a way that the convenience of the subway is maximized. Help him to calculate the maximum possible convenience he can get! | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.stream.Stream;
import java.util.Collection;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.Collections;
import java.util.stream.Collectors;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author svilen.marchev@gmail.com
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.readInt();
int[] next = new int[n];
for (int i = 0; i < n; ++i) {
next[i] = in.readInt() - 1;
}
ArrayList<Long> sizes = new ArrayList<>();
boolean[] u = new boolean[n];
for (int i = 0; i < n; ++i) {
if (!u[i]) {
long sz = 0;
for (int j = i; !u[j]; j = next[j]) {
u[j] = true;
sz++;
}
sizes.add(sz);
}
}
Collections.sort(sizes);
if (sizes.size() > 1) {
long newSz = sizes.get(sizes.size() - 1) + sizes.get(sizes.size() - 2);
sizes.remove(sizes.size() - 1);
sizes.set(sizes.size() - 1, newSz);
}
long ans = sizes.stream().collect(Collectors.summingLong(value -> value * value));
out.println(ans);
}
}
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);
}
}
}
| Java | ["3\n2 1 3", "5\n1 5 4 3 2"] | 1 second | ["9", "17"] | NoteIn the first example the mayor can change p2 to 3 and p3 to 1, so there will be 9 pairs: (1,β1), (1,β2), (1,β3), (2,β1), (2,β2), (2,β3), (3,β1), (3,β2), (3,β3).In the second example the mayor can change p2 to 4 and p3 to 5. | Java 8 | standard input | [
"dfs and similar",
"greedy",
"math"
] | ad9fd71025c5f91cece740ea95b0eb6f | The first line contains one integer number n (1ββ€βnββ€β100000) β the number of stations. The second line contains n integer numbers p1, p2, ..., pn (1ββ€βpiββ€βn) β the current structure of the subway. All these numbers are distinct. | 1,500 | Print one number β the maximum possible value of convenience. | standard output | |
PASSED | fcc6963fe21f950fbf1570cb9efc2d67 | train_001.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes |
import java.util.Arrays;
import java.util.Scanner;
/*
* 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.
*/
/**
*
* @author KHALED
*/
public class XeniaandDivisors {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();
int[]arr=new int[n];
for (int i = 0; i < n; i++) {
arr[i]=scan.nextInt();
}
Arrays.sort(arr);
for (int i = 0; i < n-n/3; i++)
{
if(arr[i+n/3]%arr[i]!=0||arr[i+n/3]<=arr[i])
{
System.out.println(-1);
return;
}
}
for (int i = 0; i < n/3; i++)
{
for (int j = i; j < n; j+=n/3) {
System.out.print(arr[j]+" ");
}
System.out.println("");
}
}
}
| Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 7 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | 52f4239aa9f6afde59ab6aa1d80405b8 | train_001.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes | import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.util.Comparator;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.NoSuchElementException;
import java.io.Writer;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Nguyen Trung Hieu - vuondenthanhcong11@yahoo.com
*/
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();
}
}
class TaskA {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int count = in.readInt();
int[] A = IOUtils.readIntArray(in, count);
int[][] answer = new int[count / 3][3];
Arrays.sort(A);
for (int i = 0; i < count / 3; i++) {
answer[i][0] = A[i];
answer[i][1] = A[i + count / 3];
answer[i][2] = A[i + 2 * (count / 3)];
}
for (int i = 0; i < count / 3; i++) {
if (answer[i][0] == 1) {
if (answer[i][1] == 2) {
if (answer[i][2] != 4 && answer[i][2] != 6) {
out.printLine(-1);
return;
}
}
else if (answer[i][1] == 3) {
if (answer[i][2] != 6) {
out.printLine(-1);
return;
}
}
else {
out.printLine(-1);
return;
}
}
else {
out.printLine(-1);
return;
}
}
for (int i = 0; i < count / 3; i++)
out.printLine(answer[i]);
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
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(int[] array) {
for (int i = 0; i < array.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(array[i]);
}
}
public void printLine(int[] array) {
print(array);
writer.println();
}
public void print(Object...objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object...objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
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;
}
}
| Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 7 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | 7b9b79056f0ca39864542427f446b6ee | train_001.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
static BufferedReader br;
static FileInputStream fis;
static InputStreamReader isr;
static FileWriter fw;
public static void main(String[] args) throws IOException{
//fis = new FileInputStream("input.txt");
//isr = new InputStreamReader(fis);
isr = new InputStreamReader(System.in);
br = new BufferedReader(isr);
//File file = new File("output.txt");
//fw = new FileWriter(file);
solve();
//fis.close();
isr.close();
br.close();
//fw.close();
return;
}
// the followings are methods to take care of inputs.
static int nextInt(){
return Integer.parseInt(nextLine());
}
static long nextLong(){
return Long.parseLong(nextLine());
}
static int[] nextIntArray(){
String[] inp = nextLine().split("\\s+");
int[] ary = new int[inp.length];
for (int i = 0; i < ary.length; i++){
ary[i] = Integer.parseInt(inp[i]);
}
return ary;
}
static int[] nextIntArrayFrom1(){
String[] inp = nextLine().split("\\s+");
int[] ary = new int[inp.length + 1];
for (int i = 0; i < inp.length; i++){
ary[i+1] = Integer.parseInt(inp[i]);
}
return ary;
}
static long[] nextLongArray(){
String[] inp = nextLine().split("\\s+");
long[] ary = new long[inp.length];
for (int i = 0; i < inp.length; i++){
ary[i] = Long.parseLong(inp[i]);
}
return ary;
}
static long[] nextLongArrayFrom1(){
String[] inp = nextLine().split("\\s+");
long[] ary = new long[inp.length + 1];
for (int i = 0; i < inp.length; i++){
ary[i+1] = Long.parseLong(inp[i]);
}
return ary;
}
static String nextLine(){
try {
return br.readLine().trim();
} catch (Exception e){}
return null;
}
static void write(String str){
try{
fw.write(str);
}catch (Exception e){
System.out.println(e);
}
return;
}
static void solve(){
FastScanner scn = new FastScanner(System.in);
int n = scn.nextInt();
if(n%3!=0){
System.out.println(-1);
return;
}
int[] num = new int[8];
StringBuilder ret = new StringBuilder();
for(int i=0;i<n;i++){
int x = scn.nextInt();
if(x==5 || x==7){
System.out.println(-1);
return;
}
num[x]++;
}
if(num[3]>num[1] || num[3]>num[6]){
System.out.println(-1);
return;
}else{
for(int i=0;i<num[3];i++){
ret.append("1 3 6\n");
}
num[1]-=num[3];
num[6]-=num[3];
num[3]=0;
}
if(num[6]>num[1] || num[6] > num[2]){
System.out.println(-1);
return;
}else{
for(int i=0;i<num[6];i++){
ret.append("1 2 6\n");
}
num[1]-=num[6];
num[2]-=num[6];
num[6]=0;
}
if(num[4]!=num[1] || num[4]!=num[2]){
System.out.println(-1);
return;
}else{
for(int i=0;i<num[4];i++){
ret.append("1 2 4\n");
}
num[1]=0;
num[2]=0;
num[4]=0;
}
System.out.println(ret);
return;
}
}
class FastScanner
{
BufferedReader reader;
StringTokenizer tokenizer;
FastScanner (InputStream inputStream)
{
reader = new BufferedReader(new InputStreamReader(inputStream));
}
String nextToken()
{
while (tokenizer == null || ! tokenizer.hasMoreTokens())
{
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (Exception e){}
}
return tokenizer.nextToken();
}
int nextInt()
{
return Integer.parseInt(nextToken());
}
}
| Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 7 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | f0ca71106798d7003545ce925231c68b | train_001.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes | import java.util.HashMap;
import java.util.Scanner;
/**
* Author: Trofimov Artem
* Date: 07.09.13
*/
public class Index {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int array[] = new int[n];
for (int i = 0; i < n; i++) {
array[i] = scanner.nextInt();
}
scanner.close();
HashMap<Integer, Integer> hashMap = new HashMap<Integer, Integer>();
int[] possibleNumbers = {1,2,3,4,5,6,7};
for (Integer character : possibleNumbers) {
hashMap.put(character, 0);
}
for (Integer character : array) {
Integer charCount = hashMap.get(character);
/*if (charCount == null)
charCount = 0;*/
hashMap.put(character, charCount + 1);
}
boolean exists = false;
if ((hashMap.get(1) + hashMap.get(2) + hashMap.get(3) + hashMap.get(4) + hashMap.get(6)) == n) {
if (hashMap.get(1) == (hashMap.get(2) + hashMap.get(3))) {
if (hashMap.get(1) == (hashMap.get(4) + hashMap.get(6))) {
if (hashMap.get(2) >= hashMap.get(4)) {
exists = true;
}
}
}
}
if (exists) {
int[][] results = new int[n/3][3];
//1
for (int i = 0; i < n/3; i++) {
results[i][0] = 1;
}
//2
int j = 0;
for (; j < hashMap.get(2); j++) {
results[j][1] = 2;
}
for (; j < n/3; j++) {
results[j][1] = 3;
}
//3
int k = 0;
for (; k < hashMap.get(4); k++) {
results[k][2] = 4;
}
for (; k < n/3; k++) {
results[k][2] = 6;
}
//out
for (int i = 0; i < n/3; i++) {
System.out.println(String.valueOf(results[i][0]) + " " + String.valueOf(results[i][1]) + " " + String.valueOf(results[i][2]));
}
} else {
System.out.println(-1);
}
}
}
| Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 7 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | a3d3536446bf3a72bc0774ba5c9c48c0 | train_001.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes |
import java.awt.Point;
import java.io.*;
import java.math.BigInteger;
import java.util.*;
import static java.lang.Math.*;
public class _Solution implements Runnable{
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
void init() throws FileNotFoundException{
if (ONLINE_JUDGE){
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}else{
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
}
}
String readString() throws IOException{
while(!tok.hasMoreTokens()){
try{
tok = new StringTokenizer(in.readLine());
}catch (Exception e){
return null;
}
}
return tok.nextToken();
}
int readInt() throws IOException{
return Integer.parseInt(readString());
}
long readLong() throws IOException{
return Long.parseLong(readString());
}
double readDouble() throws IOException{
return Double.parseDouble(readString());
}
public static void main(String[] args){
new Thread(null, new _Solution(), "", 256 * (1L << 20)).start();
}
long timeBegin, timeEnd;
void time(){
timeEnd = System.currentTimeMillis();
System.err.println("Time = " + (timeEnd - timeBegin));
}
public void run(){
try{
timeBegin = System.currentTimeMillis();
init();
solve();
out.close();
time();
}catch (Exception e){
e.printStackTrace(System.err);
System.exit(-1);
}
}
void solve() throws IOException{
StringBuilder s = new StringBuilder();
int n = readInt();
int[] arr = new int[n];
int one = 0;
int two = 0;
int three = 0;
int six = 0;
int fore = 0;
for (int i = 0; i < n; i++)
{
arr[i] = readInt();
int x = arr[i];
if (arr[i] == 1){
one++;
}
if (arr[i] == 2)
{
two++;
}
if (arr[i] == 3) {
three++;
}
if (arr[i] == 4) {
fore++;
}
if (arr[i] == 6) {
six++;
}
if (arr[i] == 5 || arr[i] == 7) {
out.println("-1");
return;
}
}
Arrays.sort(arr);
while (fore > 0 && two > 0 && one > 0)
{
s.append("1 2 4\n");
one--;
two--;
fore--;
}
while (six > 0 && two > 0 && one > 0)
{
s.append("1 2 6\n");
one--;
two--;
six--;
}
while (six > 0 && three > 0 && one > 0)
{
s.append("1 3 6\n");
one--;
three--;
six--;
}
if (one > 0 || two > 0 || three > 0 || fore > 0 || six > 0) {
out.println("-1");
return;
}
out.print(s);
}
} | Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 7 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | 51bb727c5f8d40582074305e88cd857c | train_001.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes | import java.io.*;
import java.util.*;
import java.*;
import java.math.BigInteger;
public class zad {
private static BufferedReader in;
private static StringTokenizer tok;
private static PrintWriter out;
private static String readToken() throws IOException {
while (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
private static int readInt() throws IOException {
return Integer.parseInt(readToken());
}
private static double readDouble() throws IOException {
return Double.parseDouble(readToken());
}
private static long readLong() throws IOException {
return Long.parseLong(readToken());
}
static int partition (int[] array, int start, int end) {
int marker = start;
for ( int i = start; i <= end; i++ ) {
if ( array[i] <= array[end] ) {
int temp = array[marker];
array[marker] = array[i];
array[i] = temp;
marker += 1;
}
}
return marker - 1;
}
static void quicksort (int[] array, int start, int end) {
int pivot;
if ( start >= end ) {
return;
}
pivot = partition (array, start, end);
quicksort (array, start, pivot-1);
quicksort (array, pivot+1, end);
}
public static void Solve() throws IOException{
int n=readInt();
int[] a=new int[n];
int[] b=new int[8];
for(int i=0;i<n;i++){
a[i]=readInt();
b[a[i]]++;
}
Arrays.sort(a);
if (b[5]>0 || b[7]>0 || b[1]*3!=n){
out.println("-1");
return;
}
if (b[2]+b[3]!=b[4]+b[6]){
out.println("-1");
return;
}
ArrayList<String> list=new ArrayList<>();
for (int i=0;i<b[3];i++){
list.add("1 3 6");
}
b[6]-=b[3];
boolean p=true;
if (b[6]<0) p=false;
b[3]=0;
for (int i=0;i<b[6];i++){
list.add("1 2 6");
}
b[2]-=b[6];
if (b[2]<0) p=false;
b[6]=0;
if (b[2]!=b[4]) p=false;
if (!p){
out.println("-1");
return;
}
for (String s:list){
out.println(s);
}
for (int i=0;i<b[2];i++){
out.println("1 2 4");
}
}
public static void main(String[] args) throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
Solve();
in.close();
out.close();
}
}
| Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 7 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | 06da3f72ebcbe74de9258fa631c4e76a | train_001.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes |
import java.util.Scanner;
public class XeniaAndDivisors {
public static void main(String asd[])throws Exception
{
Scanner in=new Scanner(System.in);
int n=in.nextInt();
int a[]=new int[8];
for(int i=0;i<n;i++)
a[in.nextInt()]++;
int k=n/3;
if(a[1]==k)
{
if(a[2]==k && a[4]==k)
{
for(int i=0;i<k;i++)
System.out.println("1 2 4");
}
else if(a[2]==k && a[6]==k)
for(int i=0;i<k;i++)
System.out.println("1 2 6");
else if(a[3]==k && a[6]==k)
for(int i=0;i<k;i++)
System.out.println("1 3 6");
else if(a[2]==k && a[4]+a[6]==k)
{
for(int i=0;i<a[4];i++)
System.out.println("1 2 4");
for(int i=0;i<a[6];i++)
System.out.println("1 2 6");
}else if(a[2]+a[3]==k && a[6]==k)
{
for(int i=0;i<a[2];i++)
System.out.println("1 2 6");
for(int i=0;i<a[3];i++)
System.out.println("1 3 6");
}
else if(a[2]!=0 && a[4]!=0)
{if(a[2]+a[3]==k && a[4]+a[6]==k && (a[4]==a[2] && a[3]==a[6]))
{
for(int i=0;i<a[2];i++)
System.out.println("1 2 4");
for(int i=0;i<a[3];i++)
System.out.println("1 3 6");
}
else if(a[2]+a[3]==k && a[4]+a[6]==k && a[6]==a[3]+a[2]-a[4] && a[4]<a[2]){
for(int i=0;i<a[4];i++)
System.out.println("1 2 4");
for(int j=0;j<a[2]-a[4];j++)
System.out.println("1 2 6");
for(int i=0;i<a[3];i++)
System.out.println("1 3 6");
}
else
System.out.println(-1);}
else
System.out.println(-1);
}
else
System.out.println(-1);
}
}
| Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 7 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | 38842b041932633ddec133156299bf9a | train_001.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes | import java.util.*;
public class xad
{
public static void main(String ar[])
{
Scanner obj=new Scanner(System.in);
int n=Integer.parseInt(obj.nextLine());
int arr[]=new int[n];
int a,b,c;
for(int i=0;i<n;i++)
arr[i]=obj.nextInt();
Arrays.sort(arr);
int count=0;
for(int j=0;j<n/3;j++)
{
a=arr[j];
b=arr[j+(n/3)];
c=arr[j+((2*n)/3)];
if(a<b&&b<c&&b%a==0&&c%b==0)
{
//System.out.println(a+" "+b+" "+c);
count++;
}
}
if(count!=n/3)
System.out.println(-1);
if(count==n/3)
{
for(int j=0;j<n/3;j++)
{
a=arr[j];
b=arr[j+(n/3)];
c=arr[j+((2*n)/3)];
System.out.println(a+" "+b+" "+c);
}
}
}
}
| Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 7 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | d84f6188c0691d01f7cc4c35e1a7091e | train_001.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes | import java.io.*;
import java.util.*;
public class mierda{
public static void main(String args[]) throws IOException{
BufferedReader lector = new BufferedReader(new InputStreamReader(System.in));
int a = Integer.parseInt(lector.readLine());
String t[] = lector.readLine().split(" ");
int tal[] = new int[8];
boolean paila = false;
for(int n = 0;n<t.length;n++)
tal[Integer.parseInt(t[n])]++;
if(tal[2]>tal[1] || tal[5]>0 || tal[7]>0 ||tal[4]>tal[2])paila = true;
StringBuilder res = new StringBuilder("");
for(int n = 0;n<tal[4];n++){
res.append("1 2 4\n");
tal[2]--;
tal[1]--;
}
tal[4]=0;
for(int n = 0;n<tal[2];n++){
res.append("1 2 6\n");
tal[1]--;
tal[6]--;
}
tal[2]=0;
for(int n =0;n<tal[3];n++){
res.append("1 3 6\n");
tal[1]--;
tal[6]--;
}
tal[3]=0;
if(tal[1]>0){
paila = true;
tal[1]=0;
}
for(int n = 0;n<8;n++)paila = paila | tal[n]!=0;
System.out.println(paila?-1:res.substring(0,res.length()-1));
}
} | Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 7 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | 4e56de08980e14321971e9a170010e7a | train_001.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes | import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
StringBuilder out = new StringBuilder();
int n = in.nextInt();
int[] a = new int[7+1];
for (int i = 0; i < n; i++) {
a[in.nextInt()]++;
}
if(a[5] != 0 || a[7] != 0)
System.out.println("-1");
else if(a[1] == 0 || (a[3] != 0 && a[6] < a[3]) || (a[4] != 0 && a[2] < a[4]) || a[2]+a[3] != a[1] || a[4]+a[6] != a[1] || a[2]-(a[6]-a[3])!=a[4] || a[2]-a[4]!=a[6]-a[3] || a[6]-(a[2]-a[4])!=a[3])
System.out.println("-1");
else{
for (int i = a[4]; i >0; i--) {
out.append("1 2 4\n");
}
for (int i = a[6]-a[3]; i > 0; i--) {
out.append("1 2 6\n");
}
for (int i = a[3]; i > 0; i--) {
out.append("1 3 6\n");
}
System.out.print(out);
}
}
} | Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 7 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | e8c28afcd6085cb228cbec13f4cde789 | train_001.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes | import java.io.PrintWriter;
import java.util.Scanner;
public class A342 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int count[] = new int[8];
for (int i = 0; i < n; ++i) {
count[in.nextInt()]++;
}
PrintWriter writer = new PrintWriter(System.out);
int min = Math.min(count[1], count[2]);
min = Math.min(min, count[4]);
for (int i = 0; i < min; ++i) {
writer.println("1 2 4");
}
count[1] -= min;
count[2] -= min;
count[4] -= min;
min = Math.min(count[1], count[2]);
min = Math.min(min, count[6]);
for (int i = 0; i < min; ++i) {
writer.println("1 2 6");
}
count[1] -= min;
count[2] -= min;
count[6] -= min;
min = Math.min(count[1], count[3]);
min = Math.min(min, count[6]);
for (int i = 0; i < min; ++i) {
writer.println("1 3 6");
}
count[1] -= min;
count[3] -= min;
count[6] -= min;
for (int i = 1; i <= 7; ++i) {
if (count[i] != 0) {
System.out.println(-1);
return;
}
}
writer.close();
}
}
| Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 7 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | 3a6926219e8734ba94072708bf9652fb | train_001.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes | import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class solver {
BufferedReader in;
PrintWriter out;
StringTokenizer tok;
final boolean OJ=System.getProperty("ONLINE_JUDGE")!=null;
String readString() throws IOException{
while (tok==null || !tok.hasMoreTokens()){
tok=new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
int readInt() throws NumberFormatException, IOException{
return Integer.parseInt(readString());
}
long readLong() throws NumberFormatException, IOException{
return Long.parseLong(readString());
}
double readDouble() throws NumberFormatException, IOException{
return Double.parseDouble(readString());
}
int gcd(int a,int b){
return (b==0)?a:gcd(b,a%b);
}
void Solve() throws NumberFormatException, IOException{
int n=readInt();
int[] a=new int[8];
for (int i=0;i<n;i++){
a[readInt()]++;
}
if (a[7]>0 || a[5]>0) {
out.println(-1);
return;
}
if (a[1]==a[2]+a[3] && a[1]==a[4]+a[6]){
if (a[2]<a[4]){
out.println(-1);
return;
}
if (a[3]>a[6]){
out.println(-1);
return;
}
for (int i=0;i<a[4];i++){
out.println("1 2 4");
}
a[2]-=a[4];
a[1]-=a[4];
a[4]=0;
for (int i=0;i<a[3];i++){
out.println("1 3 6");
}
a[6]-=a[3];
a[1]-=a[3];
a[3]=0;
for (int i=0;i<a[2];i++){
out.println("1 2 6");
}
return;
}
out.println(-1);
}
void Run() throws NumberFormatException, IOException{
if (OJ){
in =new BufferedReader(new InputStreamReader(System.in));
out=new PrintWriter(System.out);
}else{
in=new BufferedReader(new FileReader("input.txt"));
out=new PrintWriter("output.txt");
}
long h=System.currentTimeMillis();
Solve();
System.err.println(System.currentTimeMillis()-h);
in.close();
out.close();
}
public static void main(String[] args) throws NumberFormatException, IOException{
new solver().Run();
}
} | Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 7 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | 2ef94160885ca152a7babb1c98936ac5 | train_001.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes | import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.math.BigDecimal;
import java.io.BufferedWriter;
import java.util.Locale;
import java.util.InputMismatchException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Jacob Jiang
*/
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();
}
}
class TaskA {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int[] a = new int[8];
int n = in.nextInt();
for (int i : in.nextIntArray(n)) {
a[i]++;
}
int[] b = new int[8];
int c1 = a[4];
b[1] += c1;
b[2] += c1;
b[4] += c1;
int c2 = a[3];
b[1] += c2;
b[3] += c2;
b[6] += c2;
int c3 = n / 3 - c1 - c2;
b[1] += c3;
b[2] += c3;
b[6] += c3;
if (Arrays.equals(a, b) && c1 >= 0 && c2 >= 0 && c3 >= 0) {
for (int i = 0; i < c1; i++) {
out.println("1 2 4");
}
for (int i = 0; i < c2; i++) {
out.println("1 3 6");
}
for (int i = 0; i < c3; i++) {
out.println("1 2 6");
}
} else {
out.println(-1);
}
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1 << 16];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
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 & 15;
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public static boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int[] nextIntArray(int count) {
int[] result = new int[count];
for (int i = 0; i < count; i++) {
result[i] = nextInt();
}
return result;
}
}
class OutputWriter {
private PrintWriter writer;
public OutputWriter(OutputStream stream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void println(int i) {
writer.println(i);
}
public void println(String x) {
writer.println(x);
}
public void close() {
writer.close();
}
}
| Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 7 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | 43861b3a05bcad73d2c142b09935c8b7 | train_001.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class con199_A {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
StringTokenizer tok = new StringTokenizer(line);
int n = ti(tok.nextToken());
line = br.readLine();
tok = new StringTokenizer(line);
int[] cnts = new int[8];
Arrays.fill(cnts, 0);
for (int i = 0; i < n; i++) {
int a = ti(tok.nextToken());
++cnts[a];
}
int a = cnts[4];
int c = cnts[3];
int b = cnts[6] - c;
if (b < 0) { System.out.println(-1); return; }
int[] nc = new int[8];
Arrays.fill(nc, 0);
nc[1] = a + b + c;
if (cnts[1] != nc[1] ) { System.out.println(-1); return; }
nc[2] = a + b;
if (cnts[2] != nc[2] ) { System.out.println(-1); return; }
nc[3] = c;
if (cnts[3] != nc[3] ) { System.out.println(-1); return; }
nc[4] = a;
if (cnts[4] != nc[4] ) { System.out.println(-1); return; }
nc[5] = 0;
if (cnts[5] != nc[5] ) { System.out.println(-1); return; }
nc[6] = b + c;
if (cnts[6] != nc[6] ) { System.out.println(-1); return; }
nc[7] = 0;
if (cnts[7] != nc[7] ) { System.out.println(-1); return; }
for (int i = 0; i < a; i++) {
System.out.println("1 2 4");
}
for (int i = 0; i < b; i++) {
System.out.println("1 2 6");
}
for (int i = 0; i < c; i++) {
System.out.println("1 3 6");
}
}
private static int ti(String s) {
return Integer.parseInt(s);
}
private static long tl(String s) {
return Long.parseLong(s);
}
}
| Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 7 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | 2d633850171b9df52f43201d078a4537 | train_001.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes | import java.util.*; //Scanner;
import java.io.PrintWriter; //PrintWriter
public class R199_Div2_A //Name: Xenia and Divisors
{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
solve(in, out);
out.close();
in.close();
}
public static void solve(Scanner in, PrintWriter out)
{
int n = in.nextInt();
int a;
int[] b = new int[10];
for (int i = 0; i < n; i++)
{
a = in.nextInt();
b[a]++;
}
StringBuilder sb = new StringBuilder();
boolean good = true;
if (b[1] != n / 3 || b[5] > 0 || b[7] > 0)
out.println(-1);
else
{
int i = 0;
while (good && i < n / 3)
{
if (b[3] > 0 && b[6] > 0)
{
b[1]--; b[3]--; b[6]--;
sb.append("1 3 6\r\n");
}
else if (b[6] > 0 && b[2] > 0)
{
b[1]--; b[2]--; b[6]--;
sb.append("1 2 6\r\n");
}
else if (b[4] > 0 && b[2] > 0)
{
b[1]--; b[2]--; b[4]--;
sb.append("1 2 4\r\n");
}
else good = false;
i++;
}
if (good)
out.println(sb);
else
out.println(-1);
}
}
}
| Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 7 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | cd84379d05a669452d991f5310e2d45b | train_001.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes | import java.util.Scanner;
public class XeniaAndDivisors {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int[] deg = new int[8];
for (int i = 0; i < n; i++)
deg[scan.nextInt()]++;
int[][] ret = solve(n, deg);
if (ret == null) {
System.out.println(-1);
} else {
for (int[] x : ret) {
System.out.println(x[0] + " " + x[1] + " " + x[2]);
}
}
scan.close();
}
static int[][] solve(int n, int[] deg) {
if (deg[5] >= 1 || deg[7] >= 1) {
return null;
}
if (deg[1] != n / 3) {
return null;
}
int[][] g = new int[n / 3][3];
int gi = 0;
int[][] grp = new int[][] { { 1, 2, 4 }, { 1, 2, 6 }, { 1, 3, 6 } };
for (int[] gr : grp) {
while (deg[gr[0]] >= 1 && deg[gr[1]] >= 1 && deg[gr[2]] >= 1) {
g[gi++] = gr.clone();
deg[gr[0]]--;
deg[gr[1]]--;
deg[gr[2]]--;
}
}
if (gi != n / 3) {
return null;
}
return g;
}
} | Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 7 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | d63e807a4402b0add15abcaf5e151c28 | train_001.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes | import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int inputs = scan.nextInt(), firstcheck = 0, secondcheck = 0, thirdcheck = 0, fourthcheck = 0;
int[] values = new int[inputs];
for (int i = 0; i < inputs; i++) {
values[i] = scan.nextInt();
}
Arrays.sort(values);
if((values[0]!=(values[(values.length-1)/2]))){
firstcheck = 1;
}
if((values[values.length-1])!=(((values[((values.length-1)/2)+1])))){
fourthcheck = 1;
}
for (int i = 0; i < (inputs/3); i++) {
if( ((((values[i + (inputs/3)]) % (values[i])) == 0) &&
(((values[i + ((inputs/3)*2)]) % (values[i + (inputs/3)])) == 0)) && (firstcheck == 1) && (fourthcheck ==1)
){
thirdcheck ++;
}else{
secondcheck ++;
}
}
for (int i = 0; i < (inputs/3); i++) {
if(secondcheck > 0){
System.out.println(-1);
break;
}else if(thirdcheck > 0){
System.out.print(values[i] + " " + values[i + (inputs/3)] + " " + values[i + ((inputs/3)*2)]);
System.out.println();
}
}
}
}
/* System.out.print(values[i] + " " + values[i + (inputs/3)] + " " + values[i + ((inputs/3)*2)]);
//System.out.println();
System.out.println("value i :" + values[i]);
System.out.println("value i + (inputs/3) :" + values[i + (inputs/3)]);
System.out.println("value i + inputs/3)*2 :" + values[i + ((inputs/3)*2)]);
System.out.println("A checker :" + (values[i + (inputs/3)]) / (values[i]));
System.out.println("B checker :" + ((values[i + ((inputs/3)*2)]) / (values[i + (inputs/3)])));
if( !( ((values[i + (inputs/3)]) / (values[i])) % 1 == 0) &&
!( ((values[i + ((inputs/3)*2)]) / (values[i + (inputs/3)])) % 1 == 0)
){
System.out.println("there is no decimal");
}else{
System.out.println("there is decimal");
}*/ | Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 7 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | 63775cdbff8f9205523e3bcc8dd7851c | train_001.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes | import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int inputs = scan.nextInt(), firstcheck = 0, secondcheck = 0, thirdcheck = 0, fourthcheck = 0;
int[] values = new int[inputs];
for (int i = 0; i < inputs; i++) {
values[i] = scan.nextInt();
}
Arrays.sort(values);
if ((values[0] != (values[(values.length - 1) / 2]))) {
firstcheck = 1;
}
if ((values[values.length - 1]) != (((values[((values.length - 1) / 2) + 1])))) {
fourthcheck = 1;
}
for (int i = 0; i < (inputs / 3); i++) {
if (((((values[i + (inputs / 3)]) % (values[i])) == 0) && (((values[i
+ ((inputs / 3) * 2)]) % (values[i + (inputs / 3)])) == 0))
&& (firstcheck == 1) && (fourthcheck == 1)) {
thirdcheck++;
} else {
secondcheck++;
}
}
for (int i = 0; i < (inputs / 3); i++) {
if (secondcheck > 0) {
System.out.println(-1);
break;
} else if (thirdcheck > 0) {
System.out.print(values[i] + " " + values[i + (inputs / 3)]
+ " " + values[i + ((inputs / 3) * 2)]);
System.out.println();
}
}
}
} | Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 7 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | c1c6f7b1fc86f1096af6a5687e344bbc | train_001.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes | import java.util.Scanner;
/**
*
* @author afrooz
*/
public class XeniaAndDivisors {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner input=new Scanner(System.in);
int te=Integer.parseInt(input.nextLine());
int[] info={0,0,0,0,0,0,0,0};
for(int i=0;i<te;i++)
{
int in=input.nextInt();
info[in]++;
}
if(info[0]!=0||info[5]!=0||info[7]!=0)
System.out.println("-1");
else
{
if(info[1]!=info[4]+info[6])
System.out.println("-1");
else
{
info[2]=info[2]-info[4];
if(info[2]<0)
System.out.println("-1");
else if(info[2]+info[3]!=info[6])
System.out.println("-1");
else
{
for(int i=0;i<info[4];i++)
System.out.println("1 2 4");
for(int i=0;i<info[2];i++)
System.out.println("1 2 6");
for(int i=0;i<info[3];i++)
System.out.println("1 3 6");
}
}
}
}
} | Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 7 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | c5cdc367985be224866da371c8b02d3b | train_001.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes | import java.util.Scanner;
public class XeniaAndDivisors {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
int n, s, a=0, b=0, c=0, d=0, e=0, m1=0, m2=0, m3=0;
String g="", g1="1 2 4", g2="1 2 6", g3= "1 3 6";
n=input.nextInt();
for(int i=0; i<n; i++)
{
s=input.nextInt();
if(s==1)
a++;
else
if(s==2)
b++;
else
if(s==3)
c++;
else
if(s==4)
d++;
else
if(s==6)
e++;
else
{
a=0; b=0; c=0; d=0; e=0;
g="-1";
break;
}
}
while(a>=1 & c>=1 & e>=1)
{
m3++;
a--;
c--;
e--;
}
while(a>=1 & b>=1 & d>=1)
{
m1++;
a--;
b--;
d--;
}
while(a>=1 & b>=1 & e>=1)
{
m2++;
a--;
b--;
e--;
}
if(a>=1 || b>=1 || c>=1 || d>=1 || e>=1 || g=="-1")
{
m1=0; m2=0; m3=0;
g="-1";
System.out.println(g);
}
while(m1>0)
{
System.out.println(g1);
m1--;
}
while(m2>0){
System.out.println(g2);
m2--;}
while(m3>0){
System.out.println(g3);
m3--;}
}
} | Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 7 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | 8751d120510c2cbc8e070ef5d684a911 | train_001.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes | import java.util.*;
public class XeniaAndDivisors {
public static void main(String ar[]) {
Scanner cin = new Scanner(System.in);
int n = Integer.parseInt(cin.nextLine());
int arr[] = new int[n];
int a, b, c;
for (int i = 0; i < n; i++) {
arr[i] = cin.nextInt();
}
cin.close();
Arrays.sort(arr);
int count = 0;
for (int j = 0; j < n / 3; j++) {
a = arr[j];
b = arr[j + (n / 3)];
c = arr[j + ((2 * n) / 3)];
if (a < b && b < c && b % a == 0 && c % b == 0) {
count++;
}
}
if (count != n / 3) {
System.out.println(-1);
}
if (count == n / 3) {
for (int j = 0; j < n / 3; j++) {
a = arr[j];
b = arr[j + (n / 3)];
c = arr[j + ((2 * n) / 3)];
System.out.println(a + " " + b + " " + c);
}
}
}
} | Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 7 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | 3a7891f06272409f972eef9f6c368c56 | train_001.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes | import java.io.*;
import java.util.ArrayList;
import java.util.StringTokenizer;
/**
* @author kperikov
*/
public class A implements Runnable {
PrintWriter out;
BufferedReader br;
StringTokenizer st;
public static void main(String[] args) throws IOException {
new Thread(new A()).start();
}
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 void run() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new BufferedOutputStream(System.out));
solve();
out.close();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
public void solve() throws IOException {
int n = nextInt();
int[] a = new int[n];
int[] d = new int[10];
for (int i = 0; i < n; ++i) {
a[i] = nextInt();
d[a[i]]++;
}
ArrayList<String> ans = new ArrayList<>();
for (int i = 0; i < n / 3; ++i) {
String tmp = "";
if (d[1] > 0) {
tmp += 1 + " ";
d[1]--;
} else {
out.println("-1");
return;
}
boolean is2 = false;
if (d[2] > 0) {
tmp += "2 ";
d[2]--;
is2 = true;
} else if (d[3] > 0) {
tmp += "3 ";
d[3]--;
} else {
out.println("-1");
return;
}
if (is2) {
if (d[4] > 0) {
tmp += "4 ";
d[4]--;
} else if (d[6] > 0) {
tmp += "6 ";
d[6]--;
} else {
out.println("-1");
return;
}
} else {
if (d[6] > 0) {
d[6]--;
tmp += "6 ";
} else {
out.println("-1");
return;
}
}
ans.add(tmp);
}
if (ans.size() != n / 3) {
out.println("-1");
return;
}
for (int i = 0; i < ans.size(); ++i) {
out.println(ans.get(i));
}
}
}
| Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 7 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | 3a3ce85976649a5e804ea8b0d84221fb | train_001.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Scanner;
public class A199 {
void run() {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int[] integers = new int[n];
for (int i = 0; i < n; i++) {
integers[i] = input.nextInt();
}
Arrays.sort(integers);
int numOfGroups = n / 3;
int[][] output = new int[numOfGroups][3];
int indexOfGroup = 0;
int x = 0;
int i;
for (i = 0; i < n; i++) {
if (i >= numOfGroups
&& (integers[i] == output[indexOfGroup][x-1] || integers[i]
% output[indexOfGroup][x-1] != 0)) {
System.out.println("-1");
break;
}
output[indexOfGroup][x] = integers[i];
if (indexOfGroup == numOfGroups - 1) {
indexOfGroup = 0;
if (x == 2) {
x = 0;
} else {
x++;
}
} else {
indexOfGroup++;
}
}
if (i == n) {
for (int j = 0; j < numOfGroups; j++) {
for (int j2 = 0; j2 < 3; j2++) {
System.out.print(output[j][j2]);
if (j2 != 2) {
System.out.print(" ");
}
}
System.out.println();
}
}
}
public static void main(String[] args) {
new A199().run();
}
}
| Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 7 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | d5dd8b2e9c46d09176b6ddfb383882a5 | train_001.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes | import java.util.Scanner;
public class Divisors {
public static int[] prepare(){
int[] count = new int[8];
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
sc.nextLine();
String[] line = sc.nextLine().split(" ");
for (String str : line) {
int tmp = Integer.parseInt(str);
if(tmp == 5 || tmp == 7 || tmp == 0)
return null;
else
count[tmp]++;
}
return count;
}
public static void main(String[] args) {
int [] count = prepare();
if(count == null || !((count[1]==count[2]+count[3])&&(count[3]<=count[6])
&& ((count[2]==count[4]&&count[3]==count[6])||((count[2]-count[4]+count[3])==count[6])))){
System.out.println("-1");
return;
}
for (int i = 0; i < count[4]; i++) {
System.out.println("1 2 4");
}
if(count[2]>count[4]){
for (int i = 0; i < count[2]-count[4]; i++)
System.out.println("1 2 6");
}
for (int i = 0; i < count[6]- (count[2]-count[4]); i++) {
System.out.println("1 3 6");
}
}
}
| Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 7 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | cb6989d9de18e68142a10d3edc6c44f0 | train_001.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes | import java.util.Scanner;
public class xenia_and_div {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[] arr=new int[10];
for(int i=0;i<n;i++)
arr[sc.nextInt()]++;
if(arr[7]>0||arr[5]>0||arr[1]!=n/3){
System.out.println(-1);
System.exit(0);
}
if((arr[2]+arr[3]!=arr[4]+arr[6]) || (arr[2]+arr[6]==0) || arr[4]>arr[2]){
System.out.println(-1);
System.exit(0);
}
for(int i=0;i<arr[4];i++){
System.out.println("1 2 4");
arr[1]--;
arr[2]--;
}
for(int i=0;i<arr[2];i++){
System.out.println("1 2 6");
arr[1]--;
}
for(int i=0;i<arr[1];i++)
System.out.println("1 3 6");
}
}
| Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 7 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | fb5af6dd991b63ad6d25439153a93c0f | train_001.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] m = new int[n];
int[] a = new int[6];
boolean flag = false;
for(int i = 0; i < n; i++) {
m[i] = in.nextInt();
if(m[i] == 5 || m[i] == 7)
flag = true;
switch (m[i]) {
case 1: a[0]++; break;
case 2: a[1]++; break;
case 3: a[2]++; break;
case 4: a[3]++; break;
case 6: a[4]++; break;
default : break;
}
}
if(flag == true)
System.out.println(-1);
else if(a[0] == 1 && a[2] == 1 && a[3] == 1)
System.out.println(-1);
else {
if(a[1] >= a[3] && a[3] + a[4] == a[0] && a[1] + a[2] == a[0]) {
for(int i = 0; i < a[3]; i++)
System.out.println("1 2 4");
for(int i = 0; i < a[2]; i++)
System.out.println("1 3 6");
for(int i = 0; i < a[0] - a[2] - a[3]; i++)
System.out.println("1 2 6");
}
else
System.out.println(-1);
}
in.close();
}
} | Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 7 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | 668bfbc6e5f39862c4de79b1a3081736 | train_001.jsonl | 1378540800 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,βb,βc the following conditions held: aβ<βbβ<βc; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist. | 256 megabytes | import java.util.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.IOException;
public class Code{
BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
PrintWriter writer=new PrintWriter(System.out);
int [] readInts() throws IOException{
String s[]=reader.readLine().split(" ");
int [] ints=new int[s.length];
for (int i=0;i<ints.length;i++)
ints[i]=Integer.parseInt(s[i]);
return ints;
}
int tmp[];
int tmpn=0;
int readInt() throws IOException{
if (tmp==null||tmpn>tmp.length){
tmp=readInts();
tmpn=0;
}
return tmp[tmpn++];
}
void solve() throws IOException{
int n=readInt();
int [] a=new int[1000006];
int [] cnt=new int [10];
a=readInts();
boolean ind=false;
for (int i=0;i<n;i++){
if (a[i]==5||a[i]==7){
ind=true;
break;
}
cnt[a[i]]++;
}
if ((cnt[1]==cnt[4]+cnt[6])&&(cnt[1]==cnt[2]+cnt[3])&&(cnt[4]<=cnt[2])&&!ind){
for (int i=1;i<=cnt[4];i++) writer.println("1 2 4");
for (int i=1;i<=cnt[3];i++) writer.println("1 3 6");
for (int i=1;i<=cnt[6]-cnt[3];i++) writer.println("1 2 6");
writer.flush();
return;
}
writer.println("-1");
writer.flush();
}
public static void main(String args[]) throws IOException{
new Code().solve();
}
} | Java | ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"] | 1 second | ["-1", "1 2 4\n1 2 6"] | null | Java 7 | standard input | [
"implementation",
"greedy"
] | 513234db1bab98c2c2ed6c7030c1ac72 | The first line contains integer n (3ββ€βnββ€β99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. | 1,200 | If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. | standard output | |
PASSED | 8ee383a80370d3d8f7df93d9e5fac27d | train_001.jsonl | 1588343700 | Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of lengthΒ $$$k$$$ have the same sum. A subarray of an array is any sequence of consecutive elements.Phoenix currently has an array $$$a$$$ of length $$$n$$$. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautiful. The inserted integers must be between $$$1$$$ and $$$n$$$ inclusive. Integers may be inserted anywhere (even before the first or after the last element), and he is not trying to minimize the number of inserted integers. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.BigInteger;
import java.lang.*;
public class Main {
public static void main(String[] args) throws java.lang.Exception {
try{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int t=Integer.parseInt(br.readLine());
while(t>0){
String str[]=br.readLine().split(" ");
int n=Integer.parseInt(str[0]);
int k=Integer.parseInt(str[1]);
int arr[]=new int[n];
ArrayList<Integer> al=new ArrayList<Integer>();
long sum=0;
int flag=0;
String s=br.readLine();
String str1[]=s.split(" ");
if(k==n){
System.out.println(2*n);
System.out.print(s+" "+s);
}
else{
for(int i=0;i<n;i++){
arr[i]=Integer.parseInt(str1[i]);
if(!al.contains(arr[i])){
al.add(arr[i]);
}
// System.out.println(al);
}
if(al.size()>k){
System.out.print("-1");
}
else{
if(al.size()!=k){
for(int v=1;v<=k;v++){
if(!al.contains(v)){
al.add(v);
}
if(al.size()==k)
break;
}
}
System.out.println(n*k);
for(int m=0;m<n;m++){
for(int u=0;u<k;u++){
System.out.print(al.get(u)+" ");
}
}
}
//12
//2 3 4 2 3 4 2 3 4 2 3 4
}
System.out.println("");
t--;
}
}
catch(Exception e){
System.out.println("d");
System.exit(0);
}
}
} | Java | ["4\n4 2\n1 2 2 1\n4 3\n1 2 2 1\n3 2\n1 2 3\n4 4\n4 3 4 2"] | 2 seconds | ["5\n1 2 1 2 1\n4\n1 2 2 1\n-1\n7\n4 3 2 1 4 3 2"] | NoteIn the first test case, we can make array $$$a$$$ beautiful by inserting the integer $$$1$$$ at index $$$3$$$ (in between the two existing $$$2$$$s). Now, all subarrays of length $$$k=2$$$ have the same sum $$$3$$$. There exists many other possible solutions, for example: $$$2, 1, 2, 1, 2, 1$$$ $$$1, 2, 1, 2, 1, 2$$$ In the second test case, the array is already beautiful: all subarrays of length $$$k=3$$$ have the same sum $$$5$$$.In the third test case, it can be shown that we cannot insert numbers to make array $$$a$$$ beautiful.In the fourth test case, the array $$$b$$$ shown is beautiful and all subarrays of length $$$k=4$$$ have the same sum $$$10$$$. There exist other solutions also. | Java 8 | standard input | [
"data structures",
"constructive algorithms",
"sortings",
"greedy"
] | 80d4b2d01215b12ebd89b8ee2d1ac6ed | The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 50$$$)Β β the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 100$$$). The second line of each test case contains $$$n$$$ space-separated integers ($$$1 \le a_i \le n$$$)Β β the array that Phoenix currently has. This array may or may not be already beautiful. | 1,400 | For each test case, if it is impossible to create a beautiful array, print -1. Otherwise, print two lines. The first line should contain the length of the beautiful array $$$m$$$ ($$$n \le m \le 10^4$$$). You don't need to minimize $$$m$$$. The second line should contain $$$m$$$ space-separated integers ($$$1 \le b_i \le n$$$)Β β a beautiful array that Phoenix can obtain after inserting some, possibly zero, integers into his array $$$a$$$. You may print integers that weren't originally in array $$$a$$$. If there are multiple solutions, print any. It's guaranteed that if we can make array $$$a$$$ beautiful, we can always make it with resulting length no more than $$$10^4$$$. | standard output | |
PASSED | 2aa71de849529b5aab14d8a8c85f86dc | train_001.jsonl | 1588343700 | Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of lengthΒ $$$k$$$ have the same sum. A subarray of an array is any sequence of consecutive elements.Phoenix currently has an array $$$a$$$ of length $$$n$$$. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautiful. The inserted integers must be between $$$1$$$ and $$$n$$$ inclusive. Integers may be inserted anywhere (even before the first or after the last element), and he is not trying to minimize the number of inserted integers. | 256 megabytes | import java.io.*;
import java.util.*;
public class Solution {
private static final String NO = "NO";
private static final String YES = "YES";
public static BufferedWriter bw;
public static FastReader sc;
private static final int LIMIT = (int) Math.pow(10, 6);
public static void main(String[] args) throws Exception {
FastReader sc = new FastReader();
bw = new BufferedWriter(new OutputStreamWriter(System.out));
int t = sc.nextInt();
// int t = 1;
while (t > 0) {
t--;
int n = sc.nextInt();
int k = sc.nextInt();
int[] a = sc.nextIntArr(n);
int ans = solve(n, a, k);
if (ans == -1)
bw.write(ans + "\n");
}
bw.close();
}
private static int solve(int n, int[] a, int k) {
int[] b;
try {
b = getDistinctElements(a, n, k);
} catch (RuntimeException e) {
return -1;
}
final int size = 10000;
int[] ans = new int[size];
for (int i = 0; i < size; i++) {
ans[i] = b[i % k];
}
try {
bw.write(size + "\n");
} catch (IOException e) {
e.printStackTrace();
}
pA(ans);
return 0;
}
private static void pA(int[] ans) {
try {
for (int x : ans)
bw.write(x + " ");
bw.write("\n");
} catch (IOException e) {
}
}
private static int[] getDistinctElements(int[] a, int n, int k) throws RuntimeException {
Set<Integer> ans = new HashSet<>();
for (int x : a)
ans.add(x);
if (ans.size() > k)
throw new RuntimeException();
for (int i = 1; i <= n && ans.size() < k; i++)
ans.add(i);
return ans.stream().mapToInt(Number::intValue).toArray();
}
}
class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public String next() {
if (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public int[] nextIntArr(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public long nextLong() {
return Long.parseLong(next());
}
} | Java | ["4\n4 2\n1 2 2 1\n4 3\n1 2 2 1\n3 2\n1 2 3\n4 4\n4 3 4 2"] | 2 seconds | ["5\n1 2 1 2 1\n4\n1 2 2 1\n-1\n7\n4 3 2 1 4 3 2"] | NoteIn the first test case, we can make array $$$a$$$ beautiful by inserting the integer $$$1$$$ at index $$$3$$$ (in between the two existing $$$2$$$s). Now, all subarrays of length $$$k=2$$$ have the same sum $$$3$$$. There exists many other possible solutions, for example: $$$2, 1, 2, 1, 2, 1$$$ $$$1, 2, 1, 2, 1, 2$$$ In the second test case, the array is already beautiful: all subarrays of length $$$k=3$$$ have the same sum $$$5$$$.In the third test case, it can be shown that we cannot insert numbers to make array $$$a$$$ beautiful.In the fourth test case, the array $$$b$$$ shown is beautiful and all subarrays of length $$$k=4$$$ have the same sum $$$10$$$. There exist other solutions also. | Java 8 | standard input | [
"data structures",
"constructive algorithms",
"sortings",
"greedy"
] | 80d4b2d01215b12ebd89b8ee2d1ac6ed | The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 50$$$)Β β the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 100$$$). The second line of each test case contains $$$n$$$ space-separated integers ($$$1 \le a_i \le n$$$)Β β the array that Phoenix currently has. This array may or may not be already beautiful. | 1,400 | For each test case, if it is impossible to create a beautiful array, print -1. Otherwise, print two lines. The first line should contain the length of the beautiful array $$$m$$$ ($$$n \le m \le 10^4$$$). You don't need to minimize $$$m$$$. The second line should contain $$$m$$$ space-separated integers ($$$1 \le b_i \le n$$$)Β β a beautiful array that Phoenix can obtain after inserting some, possibly zero, integers into his array $$$a$$$. You may print integers that weren't originally in array $$$a$$$. If there are multiple solutions, print any. It's guaranteed that if we can make array $$$a$$$ beautiful, we can always make it with resulting length no more than $$$10^4$$$. | standard output | |
PASSED | 7de9abb515bf07bc38d13f5f25ec9132 | train_001.jsonl | 1588343700 | Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of lengthΒ $$$k$$$ have the same sum. A subarray of an array is any sequence of consecutive elements.Phoenix currently has an array $$$a$$$ of length $$$n$$$. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautiful. The inserted integers must be between $$$1$$$ and $$$n$$$ inclusive. Integers may be inserted anywhere (even before the first or after the last element), and he is not trying to minimize the number of inserted integers. | 256 megabytes | import java.util.*;
/**
* Created by rkarumuru on 5/3/20
**/
public class Arrays {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int t = parseInt();
for (int i = 0; i < t; i++) {
printBeatyArray(nextInt(), parseInt());
}
}
private static void printBeatyArray(int n, int k) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
skipLine();
if (n == 1) {
println(2);
println(arr[0] + " " + arr[0]);
}
else if (n == k) {
println(2 * n - 1);
for (int i = 0; i < n; i++) {
print(arr[i] + " ");
}
for (int i = 0; i < n - 2; i++) {
print(arr[i] + " ");
}
print(arr[n - 2] + "\n");
return;
} else {
Set<Integer> set = new HashSet<>();
for (int i = 0; i < n; i++) {
set.add(arr[i]);
}
if (set.size() > k) {
println(-1);
return;
} else {
String [] soln = new String[n*k];
int iter = 0;
for (int i = 0; i < n; i++) {
for (Integer s : set) {
soln[iter++] = String.valueOf(s);
}
for (int j = 0; j < k - set.size(); j++) {
soln[iter++] = "1";
}
}
println(soln.length);
println(String.join(" ", java.util.Arrays.asList(soln)));
}
}
}
private static void print(int i) {
print(String.valueOf(i));
}
private static void println(int i) {
println(String.valueOf(i));
}
private static int nextInt() {
return scanner.nextInt();
}
private static void skipLine() {
scanner.nextLine();
}
private static int parseInt() {
return Integer.parseInt(scanner.nextLine().trim());
}
private static String getString() {
return scanner.nextLine().trim();
}
private static double getDouble() {
return Double.parseDouble(scanner.nextLine().trim());
}
private static long getlong() {
return Long.parseLong(scanner.nextLine().trim());
}
private static void print(String s) {
System.out.print(s);
}
private static void println(String s) {
System.out.println(s);
}
}
| Java | ["4\n4 2\n1 2 2 1\n4 3\n1 2 2 1\n3 2\n1 2 3\n4 4\n4 3 4 2"] | 2 seconds | ["5\n1 2 1 2 1\n4\n1 2 2 1\n-1\n7\n4 3 2 1 4 3 2"] | NoteIn the first test case, we can make array $$$a$$$ beautiful by inserting the integer $$$1$$$ at index $$$3$$$ (in between the two existing $$$2$$$s). Now, all subarrays of length $$$k=2$$$ have the same sum $$$3$$$. There exists many other possible solutions, for example: $$$2, 1, 2, 1, 2, 1$$$ $$$1, 2, 1, 2, 1, 2$$$ In the second test case, the array is already beautiful: all subarrays of length $$$k=3$$$ have the same sum $$$5$$$.In the third test case, it can be shown that we cannot insert numbers to make array $$$a$$$ beautiful.In the fourth test case, the array $$$b$$$ shown is beautiful and all subarrays of length $$$k=4$$$ have the same sum $$$10$$$. There exist other solutions also. | Java 8 | standard input | [
"data structures",
"constructive algorithms",
"sortings",
"greedy"
] | 80d4b2d01215b12ebd89b8ee2d1ac6ed | The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 50$$$)Β β the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 100$$$). The second line of each test case contains $$$n$$$ space-separated integers ($$$1 \le a_i \le n$$$)Β β the array that Phoenix currently has. This array may or may not be already beautiful. | 1,400 | For each test case, if it is impossible to create a beautiful array, print -1. Otherwise, print two lines. The first line should contain the length of the beautiful array $$$m$$$ ($$$n \le m \le 10^4$$$). You don't need to minimize $$$m$$$. The second line should contain $$$m$$$ space-separated integers ($$$1 \le b_i \le n$$$)Β β a beautiful array that Phoenix can obtain after inserting some, possibly zero, integers into his array $$$a$$$. You may print integers that weren't originally in array $$$a$$$. If there are multiple solutions, print any. It's guaranteed that if we can make array $$$a$$$ beautiful, we can always make it with resulting length no more than $$$10^4$$$. | standard output | |
PASSED | 597d7e77f90d854f4fa33c11545942ed | train_001.jsonl | 1588343700 | Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of lengthΒ $$$k$$$ have the same sum. A subarray of an array is any sequence of consecutive elements.Phoenix currently has an array $$$a$$$ of length $$$n$$$. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautiful. The inserted integers must be between $$$1$$$ and $$$n$$$ inclusive. Integers may be inserted anywhere (even before the first or after the last element), and he is not trying to minimize the number of inserted integers. | 256 megabytes | import java.io.*;
import java.util.*;
public class cf638B {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
while(t-- > 0)
{
String[] str = br.readLine().split(" ");
int n = Integer.parseInt(str[0]);
int k = Integer.parseInt(str[1]);
str = br.readLine().split(" ");
List<Integer> l = new ArrayList<>();
for(int i=0;i<n;i++)
{
int temp = Integer.parseInt(str[i]);
if(!l.contains(temp))
l.add(temp);
}
if(l.size()>k)
{
System.out.println(-1);
}
else
{
if(l.size()!=k)
{
for(int i=1;i<=k;i++)
{
if(!l.contains(i))
l.add(i);
if(l.size() == k)
break;
}
}
System.out.println(n*k);
for(int i=0;i<n;i++)
{
for(int j=0;j<k;j++)
{
System.out.print(l.get(j)+" ");
}
}
System.out.println("");
}
}
}
} | Java | ["4\n4 2\n1 2 2 1\n4 3\n1 2 2 1\n3 2\n1 2 3\n4 4\n4 3 4 2"] | 2 seconds | ["5\n1 2 1 2 1\n4\n1 2 2 1\n-1\n7\n4 3 2 1 4 3 2"] | NoteIn the first test case, we can make array $$$a$$$ beautiful by inserting the integer $$$1$$$ at index $$$3$$$ (in between the two existing $$$2$$$s). Now, all subarrays of length $$$k=2$$$ have the same sum $$$3$$$. There exists many other possible solutions, for example: $$$2, 1, 2, 1, 2, 1$$$ $$$1, 2, 1, 2, 1, 2$$$ In the second test case, the array is already beautiful: all subarrays of length $$$k=3$$$ have the same sum $$$5$$$.In the third test case, it can be shown that we cannot insert numbers to make array $$$a$$$ beautiful.In the fourth test case, the array $$$b$$$ shown is beautiful and all subarrays of length $$$k=4$$$ have the same sum $$$10$$$. There exist other solutions also. | Java 8 | standard input | [
"data structures",
"constructive algorithms",
"sortings",
"greedy"
] | 80d4b2d01215b12ebd89b8ee2d1ac6ed | The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 50$$$)Β β the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 100$$$). The second line of each test case contains $$$n$$$ space-separated integers ($$$1 \le a_i \le n$$$)Β β the array that Phoenix currently has. This array may or may not be already beautiful. | 1,400 | For each test case, if it is impossible to create a beautiful array, print -1. Otherwise, print two lines. The first line should contain the length of the beautiful array $$$m$$$ ($$$n \le m \le 10^4$$$). You don't need to minimize $$$m$$$. The second line should contain $$$m$$$ space-separated integers ($$$1 \le b_i \le n$$$)Β β a beautiful array that Phoenix can obtain after inserting some, possibly zero, integers into his array $$$a$$$. You may print integers that weren't originally in array $$$a$$$. If there are multiple solutions, print any. It's guaranteed that if we can make array $$$a$$$ beautiful, we can always make it with resulting length no more than $$$10^4$$$. | standard output | |
PASSED | cf630c69aedbb22878bebaefd1d350f0 | train_001.jsonl | 1588343700 | Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of lengthΒ $$$k$$$ have the same sum. A subarray of an array is any sequence of consecutive elements.Phoenix currently has an array $$$a$$$ of length $$$n$$$. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautiful. The inserted integers must be between $$$1$$$ and $$$n$$$ inclusive. Integers may be inserted anywhere (even before the first or after the last element), and he is not trying to minimize the number of inserted integers. | 256 megabytes | import java.util.*;
public class newFile {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
while (T-- > 0) {
int n = sc.nextInt(); int k = sc.nextInt();
HashSet<Integer> set = new HashSet<Integer>();
int[] arr = new int[n];
for (int i=0; i<n; i++) {
arr[i] = sc.nextInt();
set.add(arr[i]);
}
if (k < set.size()) {
System.out.println(-1);
}
else if (k == set.size()) {
ArrayList<Integer> res = new ArrayList<Integer>();
for (int i=0; i<n; i++) {
res.addAll(set);
}
System.out.println(res.size());
for (int i=0; i<res.size(); i++) {
System.out.print(res.get(i) + " ");
}
System.out.println();
}
else {
ArrayList<Integer> res = new ArrayList<Integer>();
for (int i=0; i<n; i++) {
res.addAll(set);
int j = 0;
while (j < k-set.size()) {
res.add(1);
j += 1;
}
}
System.out.println(res.size());
for (int i=0; i<res.size(); i++) {
System.out.print(res.get(i) + " ");
}
System.out.println();
}
}
}
} | Java | ["4\n4 2\n1 2 2 1\n4 3\n1 2 2 1\n3 2\n1 2 3\n4 4\n4 3 4 2"] | 2 seconds | ["5\n1 2 1 2 1\n4\n1 2 2 1\n-1\n7\n4 3 2 1 4 3 2"] | NoteIn the first test case, we can make array $$$a$$$ beautiful by inserting the integer $$$1$$$ at index $$$3$$$ (in between the two existing $$$2$$$s). Now, all subarrays of length $$$k=2$$$ have the same sum $$$3$$$. There exists many other possible solutions, for example: $$$2, 1, 2, 1, 2, 1$$$ $$$1, 2, 1, 2, 1, 2$$$ In the second test case, the array is already beautiful: all subarrays of length $$$k=3$$$ have the same sum $$$5$$$.In the third test case, it can be shown that we cannot insert numbers to make array $$$a$$$ beautiful.In the fourth test case, the array $$$b$$$ shown is beautiful and all subarrays of length $$$k=4$$$ have the same sum $$$10$$$. There exist other solutions also. | Java 8 | standard input | [
"data structures",
"constructive algorithms",
"sortings",
"greedy"
] | 80d4b2d01215b12ebd89b8ee2d1ac6ed | The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 50$$$)Β β the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 100$$$). The second line of each test case contains $$$n$$$ space-separated integers ($$$1 \le a_i \le n$$$)Β β the array that Phoenix currently has. This array may or may not be already beautiful. | 1,400 | For each test case, if it is impossible to create a beautiful array, print -1. Otherwise, print two lines. The first line should contain the length of the beautiful array $$$m$$$ ($$$n \le m \le 10^4$$$). You don't need to minimize $$$m$$$. The second line should contain $$$m$$$ space-separated integers ($$$1 \le b_i \le n$$$)Β β a beautiful array that Phoenix can obtain after inserting some, possibly zero, integers into his array $$$a$$$. You may print integers that weren't originally in array $$$a$$$. If there are multiple solutions, print any. It's guaranteed that if we can make array $$$a$$$ beautiful, we can always make it with resulting length no more than $$$10^4$$$. | standard output | |
PASSED | b2dd1ee27fd80ddcaf018db4a24e2169 | train_001.jsonl | 1588343700 | Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of lengthΒ $$$k$$$ have the same sum. A subarray of an array is any sequence of consecutive elements.Phoenix currently has an array $$$a$$$ of length $$$n$$$. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautiful. The inserted integers must be between $$$1$$$ and $$$n$$$ inclusive. Integers may be inserted anywhere (even before the first or after the last element), and he is not trying to minimize the number of inserted integers. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
try{
int testCases = GetInput.getInt();
while (testCases-->0) {
int []ins = GetInput.getArrayInt();
int n = ins[0]; int k = ins[1];
int [] arrau = GetInput.getArrayInt();
// if (beuat(arrau, k)){
// System.out.println(arrau.length);
// for (int i = 0; i < n; i++){
// System.out.print(arrau[i]+" ");
// }
// System.out.println();
// continue;
// }
Set<Integer> distinc = isBeut(arrau, k);
if (distinc.size() <=k){
System.out.println(k*n);
StringBuilder string = new StringBuilder();
Iterator<Integer> itr = distinc.iterator();
while(itr.hasNext()){
string.append(itr.next());
string.append(" ");
}
for (int i = 0 ; i < k-distinc.size();i++ ){
string.append(1); string.append(" ");
}
for (int i = 0; i <n ;i++){
System.out.print(string);
}
}
else {
System.out.print(-1);
}
System.out.println();
}
}catch(Exception e){
return;
}
}
private static boolean beuat(int[] arrau, int k) {
for (int i = 0; i < arrau.length-k; i++){
if (arrau[i] == arrau[i+k]){
continue;
}
return false;
}
return true;
}
private static Set<Integer> isBeut(int[] arrau, int k) {
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
int distinct = 0;
Set<Integer> set = new HashSet<>();
for (int i = 0; i < arrau.length; i++) {
if (arrau[i] > max) {
max = arrau[i];
}
if (arrau[i] < min) {
min = arrau[i];
}
if (!set.contains(arrau[i])) {
distinct++;
set.add(arrau[i]);
}
}
return set;
}
private static long sumUpto(int n){
return (long) (Math.pow(2,n+1)-2);
}
private static long mod(long position, long position1) {
if (position-position1>0){
return position-position1;
}
return position1-position;
}
}
class GetInput {
static BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
static char[] getCharArray() {
char[] charArray;
try {
StringBuilder string = getInputString();
charArray = new char[string.length()];
for (int i = 0; i < string.length(); i++) {
charArray[i] = string.charAt(i);
}
return charArray;
} catch (Exception e) {
e.printStackTrace();
}
charArray = new char[0];
return charArray;
}
static int[] getArrayInt() {
String[] string;
int[] array;
try {
string = bufferedReader.readLine().split("\\s+");
array = new int[string.length];
for (int i = 0; i < string.length; i++) {
array[i] = Integer.parseInt(string[i]);
}
return array;
} catch (IOException e) {
e.printStackTrace();
}
int[] arra = new int[2];
return arra;
}
static int getInt() {
try {
String string = bufferedReader.readLine();
return Integer.parseInt(string);
} catch (IOException e) {
e.printStackTrace();
}
return 0;
}
static StringBuilder getInputString() {
try {
StringBuilder string = new StringBuilder();
string.append(bufferedReader.readLine());
return string;
} catch (IOException e) {
e.printStackTrace();
}
return new StringBuilder();
}
static long getLongInput() {
try {
String string = bufferedReader.readLine();
return Long.parseLong(string);
} catch (IOException e) {
e.printStackTrace();
}
return 0;
}
static long[] getLongArrayInput() {
String[] string;
long[] array;
try {
string = bufferedReader.readLine().split("\\s+");
array = new long[string.length];
for (int i = 0; i < string.length; i++) {
array[i] = Long.parseLong(string[i]);
}
return array;
} catch (IOException e) {
e.printStackTrace();
}
long[] arra = new long[2];
return arra;
}
}
| Java | ["4\n4 2\n1 2 2 1\n4 3\n1 2 2 1\n3 2\n1 2 3\n4 4\n4 3 4 2"] | 2 seconds | ["5\n1 2 1 2 1\n4\n1 2 2 1\n-1\n7\n4 3 2 1 4 3 2"] | NoteIn the first test case, we can make array $$$a$$$ beautiful by inserting the integer $$$1$$$ at index $$$3$$$ (in between the two existing $$$2$$$s). Now, all subarrays of length $$$k=2$$$ have the same sum $$$3$$$. There exists many other possible solutions, for example: $$$2, 1, 2, 1, 2, 1$$$ $$$1, 2, 1, 2, 1, 2$$$ In the second test case, the array is already beautiful: all subarrays of length $$$k=3$$$ have the same sum $$$5$$$.In the third test case, it can be shown that we cannot insert numbers to make array $$$a$$$ beautiful.In the fourth test case, the array $$$b$$$ shown is beautiful and all subarrays of length $$$k=4$$$ have the same sum $$$10$$$. There exist other solutions also. | Java 8 | standard input | [
"data structures",
"constructive algorithms",
"sortings",
"greedy"
] | 80d4b2d01215b12ebd89b8ee2d1ac6ed | The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 50$$$)Β β the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 100$$$). The second line of each test case contains $$$n$$$ space-separated integers ($$$1 \le a_i \le n$$$)Β β the array that Phoenix currently has. This array may or may not be already beautiful. | 1,400 | For each test case, if it is impossible to create a beautiful array, print -1. Otherwise, print two lines. The first line should contain the length of the beautiful array $$$m$$$ ($$$n \le m \le 10^4$$$). You don't need to minimize $$$m$$$. The second line should contain $$$m$$$ space-separated integers ($$$1 \le b_i \le n$$$)Β β a beautiful array that Phoenix can obtain after inserting some, possibly zero, integers into his array $$$a$$$. You may print integers that weren't originally in array $$$a$$$. If there are multiple solutions, print any. It's guaranteed that if we can make array $$$a$$$ beautiful, we can always make it with resulting length no more than $$$10^4$$$. | standard output | |
PASSED | ada2604d34f84b3a3055f5fee3ae911d | train_001.jsonl | 1588343700 | Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of lengthΒ $$$k$$$ have the same sum. A subarray of an array is any sequence of consecutive elements.Phoenix currently has an array $$$a$$$ of length $$$n$$$. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautiful. The inserted integers must be between $$$1$$$ and $$$n$$$ inclusive. Integers may be inserted anywhere (even before the first or after the last element), and he is not trying to minimize the number of inserted integers. | 256 megabytes |
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Main {
public static void main(String[] args) throws IOException {
Reader sc = new Reader();
int t = sc.nextInt();
while (t-- > 0){
int n = sc.nextInt();
int k = sc.nextInt();
int[] arr = new int[n];
int[] counts = new int[101];
Set<Integer> set = new HashSet<>();
for(int i = 0; i < n; i++){
arr[i] = sc.nextInt();
set.add(arr[i]);
counts[arr[i]]++;
}
int distincts = 0;
int max = 0;
for(int i = 0; i < 101; i++){
if(counts[i] > 0) distincts++;
max = Math.max(max, counts[i]);
}
StringBuilder sb = new StringBuilder();
List<Integer> list = new ArrayList<>(set);
if(distincts > k){
sb.append(-1);
}else{
StringBuilder temp = new StringBuilder();
for(int i = 0; i < list.size(); i++){
temp.append(list.get(i)).append(" ");
}
int xx = list.size();
for(int i = 1; i <= n; i++){
if(counts[i] == 0 && xx < k){
temp.append(i).append(" ");
xx++;
}
}
StringBuilder t2 = new StringBuilder();
for(int i = 0; i < n; i++){
t2.append(temp);
}
sb.append(k*n).append("\n").append(t2.toString());
}
System.out.println(sb.toString());
}
}
/** Faster input **/
static class Reader {
final private int BUFFER_SIZE = 1 << 32;private DataInputStream din;private byte[] buffer;private int bufferPointer, bytesRead;
public Reader(){din=new DataInputStream(System.in);buffer=new byte[BUFFER_SIZE];bufferPointer=bytesRead=0;}
public Reader(String file_name)throws IOException {din=new DataInputStream(new FileInputStream(file_name));buffer=new byte[BUFFER_SIZE];bufferPointer=bytesRead=0;}
public String readLine()throws IOException{byte[] buf=new byte[1024*16];int cnt=0,c;
while((c=read())!=-1){if(c=='\n')break;buf[cnt++]=(byte)c;}return new String(buf,0,cnt);}
public int nextInt()throws IOException{int ret=0;byte c=read();while(c<=' ')c=read();boolean neg=(c=='-');
if(neg)c=read();do{ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');if(neg)return -ret;return ret;}
public long nextLong()throws IOException{long ret=0;byte c=read();while(c<=' ')c=read();boolean neg=(c=='-');
if(neg)c=read();do{ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');if(neg)return -ret;return ret;}
public double nextDouble()throws IOException{double ret=0,div=1;byte c=read();while(c<=' ')c=read();boolean neg=(c=='-');if(neg)c = read();do {ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');
if(c=='.')while((c=read())>='0'&&c<='9')ret+=(c-'0')/(div*=10);if(neg)return -ret;return ret;}
private void fillBuffer()throws IOException{bytesRead=din.read(buffer,bufferPointer=0,BUFFER_SIZE);if(bytesRead==-1)buffer[0]=-1;}
private byte read()throws IOException{if(bufferPointer==bytesRead)fillBuffer();return buffer[bufferPointer++];}
public void close()throws IOException{if(din==null) return;din.close();}
}
}
| Java | ["4\n4 2\n1 2 2 1\n4 3\n1 2 2 1\n3 2\n1 2 3\n4 4\n4 3 4 2"] | 2 seconds | ["5\n1 2 1 2 1\n4\n1 2 2 1\n-1\n7\n4 3 2 1 4 3 2"] | NoteIn the first test case, we can make array $$$a$$$ beautiful by inserting the integer $$$1$$$ at index $$$3$$$ (in between the two existing $$$2$$$s). Now, all subarrays of length $$$k=2$$$ have the same sum $$$3$$$. There exists many other possible solutions, for example: $$$2, 1, 2, 1, 2, 1$$$ $$$1, 2, 1, 2, 1, 2$$$ In the second test case, the array is already beautiful: all subarrays of length $$$k=3$$$ have the same sum $$$5$$$.In the third test case, it can be shown that we cannot insert numbers to make array $$$a$$$ beautiful.In the fourth test case, the array $$$b$$$ shown is beautiful and all subarrays of length $$$k=4$$$ have the same sum $$$10$$$. There exist other solutions also. | Java 8 | standard input | [
"data structures",
"constructive algorithms",
"sortings",
"greedy"
] | 80d4b2d01215b12ebd89b8ee2d1ac6ed | The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 50$$$)Β β the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 100$$$). The second line of each test case contains $$$n$$$ space-separated integers ($$$1 \le a_i \le n$$$)Β β the array that Phoenix currently has. This array may or may not be already beautiful. | 1,400 | For each test case, if it is impossible to create a beautiful array, print -1. Otherwise, print two lines. The first line should contain the length of the beautiful array $$$m$$$ ($$$n \le m \le 10^4$$$). You don't need to minimize $$$m$$$. The second line should contain $$$m$$$ space-separated integers ($$$1 \le b_i \le n$$$)Β β a beautiful array that Phoenix can obtain after inserting some, possibly zero, integers into his array $$$a$$$. You may print integers that weren't originally in array $$$a$$$. If there are multiple solutions, print any. It's guaranteed that if we can make array $$$a$$$ beautiful, we can always make it with resulting length no more than $$$10^4$$$. | standard output | |
PASSED | 32423f6f4543c9c8c12339c491e71db8 | train_001.jsonl | 1588343700 | Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of lengthΒ $$$k$$$ have the same sum. A subarray of an array is any sequence of consecutive elements.Phoenix currently has an array $$$a$$$ of length $$$n$$$. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautiful. The inserted integers must be between $$$1$$$ and $$$n$$$ inclusive. Integers may be inserted anywhere (even before the first or after the last element), and he is not trying to minimize the number of inserted integers. | 256 megabytes | import java.util.*;
import java.io.*;
public class Solution{
static PrintWriter out=new PrintWriter(System.out);
public static void main (String[] args) throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String[] temp=br.readLine().trim().split(" ");
int numTestCases=Integer.parseInt(temp[0]);
while(numTestCases-->0) {
temp=br.readLine().trim().split(" ");
int n=Integer.parseInt(temp[0]);
int k=Integer.parseInt(temp[1]);
temp=br.readLine().trim().split(" ");
int[] arr=new int[n];
for(int i=0;i<n;i++) {
arr[i]=Integer.parseInt(temp[i]);
}
printArray(k,arr);
}
out.flush();
out.close();
}
public static void printArray(int k,int[] arr) {
int n=arr.length;
int[] freqArray=new int[100+1];
for(int i=0;i<n;i++) {
freqArray[arr[i]]++;
}
int numDistinct=0;
for(int i=0;i<freqArray.length;i++) {
if(freqArray[i]>0) {
numDistinct++;
}
}
if(numDistinct>k) {
out.println(-1);
return;
}
ArrayList<Integer> distinct=new ArrayList<Integer>();
for(int i=0;i<freqArray.length;i++) {
if(freqArray[i]>0)
{
distinct.add(i);
}
}
out.println(n*k);
for(int i=0;i<n;i++) {
for(int j=0;j<distinct.size();j++) {
out.print(distinct.get(j)+" ");
}
if(numDistinct<k) {
int count=numDistinct;
while(count<k) {
out.print("1 ");
count++;
}
}
}
out.println();
}
} | Java | ["4\n4 2\n1 2 2 1\n4 3\n1 2 2 1\n3 2\n1 2 3\n4 4\n4 3 4 2"] | 2 seconds | ["5\n1 2 1 2 1\n4\n1 2 2 1\n-1\n7\n4 3 2 1 4 3 2"] | NoteIn the first test case, we can make array $$$a$$$ beautiful by inserting the integer $$$1$$$ at index $$$3$$$ (in between the two existing $$$2$$$s). Now, all subarrays of length $$$k=2$$$ have the same sum $$$3$$$. There exists many other possible solutions, for example: $$$2, 1, 2, 1, 2, 1$$$ $$$1, 2, 1, 2, 1, 2$$$ In the second test case, the array is already beautiful: all subarrays of length $$$k=3$$$ have the same sum $$$5$$$.In the third test case, it can be shown that we cannot insert numbers to make array $$$a$$$ beautiful.In the fourth test case, the array $$$b$$$ shown is beautiful and all subarrays of length $$$k=4$$$ have the same sum $$$10$$$. There exist other solutions also. | Java 8 | standard input | [
"data structures",
"constructive algorithms",
"sortings",
"greedy"
] | 80d4b2d01215b12ebd89b8ee2d1ac6ed | The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 50$$$)Β β the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 100$$$). The second line of each test case contains $$$n$$$ space-separated integers ($$$1 \le a_i \le n$$$)Β β the array that Phoenix currently has. This array may or may not be already beautiful. | 1,400 | For each test case, if it is impossible to create a beautiful array, print -1. Otherwise, print two lines. The first line should contain the length of the beautiful array $$$m$$$ ($$$n \le m \le 10^4$$$). You don't need to minimize $$$m$$$. The second line should contain $$$m$$$ space-separated integers ($$$1 \le b_i \le n$$$)Β β a beautiful array that Phoenix can obtain after inserting some, possibly zero, integers into his array $$$a$$$. You may print integers that weren't originally in array $$$a$$$. If there are multiple solutions, print any. It's guaranteed that if we can make array $$$a$$$ beautiful, we can always make it with resulting length no more than $$$10^4$$$. | standard output | |
PASSED | acdbc01a0c71b3d5c7d492d5047722a1 | train_001.jsonl | 1588343700 | Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of lengthΒ $$$k$$$ have the same sum. A subarray of an array is any sequence of consecutive elements.Phoenix currently has an array $$$a$$$ of length $$$n$$$. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautiful. The inserted integers must be between $$$1$$$ and $$$n$$$ inclusive. Integers may be inserted anywhere (even before the first or after the last element), and he is not trying to minimize the number of inserted integers. | 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.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws Exception {
long startTime = System.nanoTime();
int t = in.nextInt();
while (t-- > 0) {
solve();
}
long endTime = System.nanoTime();
err.println("Execution Time : +" + (endTime - startTime) / 1000000 + " ms");
exit(0);
}
static void solve() {
int n = in.nextInt();
int k = in.nextInt();
int[] data = in.readAllInts(n);
ArrayList<Integer> uu = Arrays.stream(data)
.distinct()
.collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
if (uu.size() > k) {
out.println("-1");
return;
}
out.println(n * k);
for (int i = 0; i < n; i++) {
for (int a : uu) {
out.print(a);
out.print(' ');
}
for (int j = 0; j < k - uu.size(); j++) {
out.print(1);
out.print(' ');
}
}
out.println("");
}
static ArrayList<Integer> missing(int a, int b, ArrayList<Integer> req, ArrayList<Integer> sol) {
// out.println(sol);
//out.println(a + " " + b);
ArrayList<Integer> sols = new ArrayList<>();
ArrayList<Integer> temp = new ArrayList<>(req);
for (int i = a; i <= b; i++) {
assert (i < sol.size());
if (temp.contains(sol.get(i))) {
temp.remove(sol.get(i));
}
}
sols.addAll(temp);
//out.println(sols);
return sols;
}
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 long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public int[] readAllInts(int n) {
int[] p = new int[n];
for (int i = 0; i < n; i++) {
p[i] = in.nextInt();
}
return p;
}
public int[] readAllInts(int n, int s) {
int[] p = new int[n + s];
for (int i = s; i < n + s; i++) {
p[i] = in.nextInt();
}
return p;
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
static void exit(int a) {
out.close();
err.close();
System.exit(a);
}
static InputStream inputStream = System.in;
static OutputStream outputStream = System.out;
static OutputStream errStream = System.err;
static InputReader in = new InputReader(inputStream);
static PrintWriter out = new PrintWriter(outputStream);
static PrintWriter err = new PrintWriter(errStream);
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
}
| Java | ["4\n4 2\n1 2 2 1\n4 3\n1 2 2 1\n3 2\n1 2 3\n4 4\n4 3 4 2"] | 2 seconds | ["5\n1 2 1 2 1\n4\n1 2 2 1\n-1\n7\n4 3 2 1 4 3 2"] | NoteIn the first test case, we can make array $$$a$$$ beautiful by inserting the integer $$$1$$$ at index $$$3$$$ (in between the two existing $$$2$$$s). Now, all subarrays of length $$$k=2$$$ have the same sum $$$3$$$. There exists many other possible solutions, for example: $$$2, 1, 2, 1, 2, 1$$$ $$$1, 2, 1, 2, 1, 2$$$ In the second test case, the array is already beautiful: all subarrays of length $$$k=3$$$ have the same sum $$$5$$$.In the third test case, it can be shown that we cannot insert numbers to make array $$$a$$$ beautiful.In the fourth test case, the array $$$b$$$ shown is beautiful and all subarrays of length $$$k=4$$$ have the same sum $$$10$$$. There exist other solutions also. | Java 8 | standard input | [
"data structures",
"constructive algorithms",
"sortings",
"greedy"
] | 80d4b2d01215b12ebd89b8ee2d1ac6ed | The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 50$$$)Β β the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 100$$$). The second line of each test case contains $$$n$$$ space-separated integers ($$$1 \le a_i \le n$$$)Β β the array that Phoenix currently has. This array may or may not be already beautiful. | 1,400 | For each test case, if it is impossible to create a beautiful array, print -1. Otherwise, print two lines. The first line should contain the length of the beautiful array $$$m$$$ ($$$n \le m \le 10^4$$$). You don't need to minimize $$$m$$$. The second line should contain $$$m$$$ space-separated integers ($$$1 \le b_i \le n$$$)Β β a beautiful array that Phoenix can obtain after inserting some, possibly zero, integers into his array $$$a$$$. You may print integers that weren't originally in array $$$a$$$. If there are multiple solutions, print any. It's guaranteed that if we can make array $$$a$$$ beautiful, we can always make it with resulting length no more than $$$10^4$$$. | standard output | |
PASSED | 0ac3142a17a91adbe704624db56c7150 | train_001.jsonl | 1588343700 | Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of lengthΒ $$$k$$$ have the same sum. A subarray of an array is any sequence of consecutive elements.Phoenix currently has an array $$$a$$$ of length $$$n$$$. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautiful. The inserted integers must be between $$$1$$$ and $$$n$$$ inclusive. Integers may be inserted anywhere (even before the first or after the last element), and he is not trying to minimize the number of inserted integers. | 256 megabytes | // Working program with FastReader
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
import java.util.TreeSet;
import java.util.StringTokenizer;
public class Main
{
public static void main(String[] args)
{
FastReader sc=new FastReader();
int test=sc.nextInt();
while(test-->0){
int n=sc.nextInt();
int k=sc.nextInt();
int inp[]=new int[n];
int freq[]=new int[n+1];
int count=0;
TreeSet<Integer> set=new TreeSet<>();
for(int i=0;i<n;i++){
inp[i]=sc.nextInt();
if(freq[inp[i]] == 0) set.add(inp[i]);
freq[inp[i]]++;
}
int sz=set.size();
if(sz>k){
System.out.println(-1);
continue;
}
// System.out.println(sz+" "+k);
StringBuffer str=new StringBuffer();
System.out.println(k*n);
for(int i:set)str=str.append(Integer.toString(i)+" ");
for(int i=sz;i<k;i++)str=str.append("1 ");
for(int i=1;i<=n;i++)System.out.print(str);
System.out.println();
}
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
}
| Java | ["4\n4 2\n1 2 2 1\n4 3\n1 2 2 1\n3 2\n1 2 3\n4 4\n4 3 4 2"] | 2 seconds | ["5\n1 2 1 2 1\n4\n1 2 2 1\n-1\n7\n4 3 2 1 4 3 2"] | NoteIn the first test case, we can make array $$$a$$$ beautiful by inserting the integer $$$1$$$ at index $$$3$$$ (in between the two existing $$$2$$$s). Now, all subarrays of length $$$k=2$$$ have the same sum $$$3$$$. There exists many other possible solutions, for example: $$$2, 1, 2, 1, 2, 1$$$ $$$1, 2, 1, 2, 1, 2$$$ In the second test case, the array is already beautiful: all subarrays of length $$$k=3$$$ have the same sum $$$5$$$.In the third test case, it can be shown that we cannot insert numbers to make array $$$a$$$ beautiful.In the fourth test case, the array $$$b$$$ shown is beautiful and all subarrays of length $$$k=4$$$ have the same sum $$$10$$$. There exist other solutions also. | Java 8 | standard input | [
"data structures",
"constructive algorithms",
"sortings",
"greedy"
] | 80d4b2d01215b12ebd89b8ee2d1ac6ed | The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 50$$$)Β β the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 100$$$). The second line of each test case contains $$$n$$$ space-separated integers ($$$1 \le a_i \le n$$$)Β β the array that Phoenix currently has. This array may or may not be already beautiful. | 1,400 | For each test case, if it is impossible to create a beautiful array, print -1. Otherwise, print two lines. The first line should contain the length of the beautiful array $$$m$$$ ($$$n \le m \le 10^4$$$). You don't need to minimize $$$m$$$. The second line should contain $$$m$$$ space-separated integers ($$$1 \le b_i \le n$$$)Β β a beautiful array that Phoenix can obtain after inserting some, possibly zero, integers into his array $$$a$$$. You may print integers that weren't originally in array $$$a$$$. If there are multiple solutions, print any. It's guaranteed that if we can make array $$$a$$$ beautiful, we can always make it with resulting length no more than $$$10^4$$$. | standard output | |
PASSED | a3ba26d97be5707d376d4e4f16735d32 | train_001.jsonl | 1588343700 | Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of lengthΒ $$$k$$$ have the same sum. A subarray of an array is any sequence of consecutive elements.Phoenix currently has an array $$$a$$$ of length $$$n$$$. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautiful. The inserted integers must be between $$$1$$$ and $$$n$$$ inclusive. Integers may be inserted anywhere (even before the first or after the last element), and he is not trying to minimize the number of inserted integers. | 256 megabytes | import java.io.*;
import java.util.*;
public class A implements Runnable {
boolean judge = false;
FastReader scn;
PrintWriter out;
String INPUT = "4\r\n" + "4 2\r\n" + "1 2 2 1\r\n" + "4 3\r\n" + "1 2 2 1\r\n" + "3 2\r\n" + "1 2 3\r\n" + "4 4\r\n"
+ "4 3 4 2\r\n" + "";
void solve() {
int t = scn.nextInt();
while (t-- > 0) {
int n = scn.nextInt(), k = scn.nextInt();
int[] arr = new int[n];
HashSet<Integer> set = new HashSet<>();
for (int i = 0; i < n; i++) {
arr[i] = scn.nextInt();
set.add(arr[i]);
}
if (set.size() > k) {
out.println(-1);
continue;
}
for (int i = 1; i <= n; i++) {
if (set.size() == k)
break;
set.add(i);
}
out.println(n * k);
for (int i = 1; i <= n; i++) {
for (Integer it : set)
out.print(it + " ");
}
out.println();
}
out.close();
}
int dfs(ArrayList<Integer>[] graph, int[] arr, int x, int sv, int p) {
int res = 0;
for (Integer adj : graph[sv]) {
if (adj != p)
res += dfs(graph, arr, x, adj, sv);
}
return Math.max(arr[sv] + res, -x);
}
public void run() {
long time = System.currentTimeMillis();
boolean oj = System.getProperty("ONLINE_JUDGE") != null || judge;
out = new PrintWriter(System.out);
scn = new FastReader(oj);
solve();
out.flush();
if (!oj) {
System.out.println(Arrays.deepToString(new Object[] { System.currentTimeMillis() - time + " ms" }));
}
}
public static void main(String[] args) {
new Thread(null, new A(), "Main", 1 << 28).start();
}
class FastReader {
InputStream is;
public FastReader(boolean onlineJudge) {
is = onlineJudge ? System.in : new ByteArrayInputStream(INPUT.getBytes());
}
byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
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++];
}
boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b))
;
return b;
}
double nextDouble() {
return Double.parseDouble(next());
}
char nextChar() {
return (char) skip();
}
String next() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
String nextLine() {
int b = skip();
StringBuilder sb = new StringBuilder();
while ((!isSpaceChar(b) || b == ' ')) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
char[] next(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);
}
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();
}
}
long nextLong() {
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();
}
}
char[][] nextMatrix(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++)
map[i] = next(m);
return map;
}
int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
int[][] next2DInt(int n, int m) {
int[][] arr = new int[n][];
for (int i = 0; i < n; i++) {
arr[i] = nextIntArray(m);
}
return arr;
}
long[][] next2DLong(int n, int m) {
long[][] arr = new long[n][];
for (int i = 0; i < n; i++) {
arr[i] = nextLongArray(m);
}
return arr;
}
int[] shuffle(int[] arr) {
Random r = new Random();
for (int i = 1, j; i < arr.length; i++) {
j = r.nextInt(i);
int c = arr[i];
arr[i] = arr[j];
arr[j] = c;
}
return arr;
}
long[] shuffle(long[] arr) {
Random r = new Random();
for (int i = 1, j; i < arr.length; i++) {
j = r.nextInt(i);
long c = arr[i];
arr[i] = arr[j];
arr[j] = c;
}
return arr;
}
int[] uniq(int[] arr) {
arr = scn.shuffle(arr);
Arrays.sort(arr);
int[] rv = new int[arr.length];
int pos = 0;
rv[pos++] = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] != arr[i - 1]) {
rv[pos++] = arr[i];
}
}
return Arrays.copyOf(rv, pos);
}
long[] uniq(long[] arr) {
arr = scn.shuffle(arr);
Arrays.sort(arr);
long[] rv = new long[arr.length];
int pos = 0;
rv[pos++] = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] != arr[i - 1]) {
rv[pos++] = arr[i];
}
}
return Arrays.copyOf(rv, pos);
}
int[] reverse(int[] arr) {
int l = 0, r = arr.length - 1;
while (l < r) {
arr[l] = arr[l] ^ arr[r];
arr[r] = arr[l] ^ arr[r];
arr[l] = arr[l] ^ arr[r];
l++;
r--;
}
return arr;
}
long[] reverse(long[] arr) {
int l = 0, r = arr.length - 1;
while (l < r) {
arr[l] = arr[l] ^ arr[r];
arr[r] = arr[l] ^ arr[r];
arr[l] = arr[l] ^ arr[r];
l++;
r--;
}
return arr;
}
int[] compress(int[] arr) {
int n = arr.length;
int[] rv = Arrays.copyOf(arr, n);
rv = uniq(rv);
for (int i = 0; i < n; i++) {
arr[i] = Arrays.binarySearch(rv, arr[i]);
}
return arr;
}
long[] compress(long[] arr) {
int n = arr.length;
long[] rv = Arrays.copyOf(arr, n);
rv = uniq(rv);
for (int i = 0; i < n; i++) {
arr[i] = Arrays.binarySearch(rv, arr[i]);
}
return arr;
}
}
} | Java | ["4\n4 2\n1 2 2 1\n4 3\n1 2 2 1\n3 2\n1 2 3\n4 4\n4 3 4 2"] | 2 seconds | ["5\n1 2 1 2 1\n4\n1 2 2 1\n-1\n7\n4 3 2 1 4 3 2"] | NoteIn the first test case, we can make array $$$a$$$ beautiful by inserting the integer $$$1$$$ at index $$$3$$$ (in between the two existing $$$2$$$s). Now, all subarrays of length $$$k=2$$$ have the same sum $$$3$$$. There exists many other possible solutions, for example: $$$2, 1, 2, 1, 2, 1$$$ $$$1, 2, 1, 2, 1, 2$$$ In the second test case, the array is already beautiful: all subarrays of length $$$k=3$$$ have the same sum $$$5$$$.In the third test case, it can be shown that we cannot insert numbers to make array $$$a$$$ beautiful.In the fourth test case, the array $$$b$$$ shown is beautiful and all subarrays of length $$$k=4$$$ have the same sum $$$10$$$. There exist other solutions also. | Java 8 | standard input | [
"data structures",
"constructive algorithms",
"sortings",
"greedy"
] | 80d4b2d01215b12ebd89b8ee2d1ac6ed | The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 50$$$)Β β the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 100$$$). The second line of each test case contains $$$n$$$ space-separated integers ($$$1 \le a_i \le n$$$)Β β the array that Phoenix currently has. This array may or may not be already beautiful. | 1,400 | For each test case, if it is impossible to create a beautiful array, print -1. Otherwise, print two lines. The first line should contain the length of the beautiful array $$$m$$$ ($$$n \le m \le 10^4$$$). You don't need to minimize $$$m$$$. The second line should contain $$$m$$$ space-separated integers ($$$1 \le b_i \le n$$$)Β β a beautiful array that Phoenix can obtain after inserting some, possibly zero, integers into his array $$$a$$$. You may print integers that weren't originally in array $$$a$$$. If there are multiple solutions, print any. It's guaranteed that if we can make array $$$a$$$ beautiful, we can always make it with resulting length no more than $$$10^4$$$. | standard output | |
PASSED | a632d59d1d327f180c2de21b073529a9 | train_001.jsonl | 1588343700 | Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of lengthΒ $$$k$$$ have the same sum. A subarray of an array is any sequence of consecutive elements.Phoenix currently has an array $$$a$$$ of length $$$n$$$. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautiful. The inserted integers must be between $$$1$$$ and $$$n$$$ inclusive. Integers may be inserted anywhere (even before the first or after the last element), and he is not trying to minimize the number of inserted integers. | 256 megabytes | import java.lang.*;
import java.io.*;
import java.util.*;
public class PhoneixArray
{
static Scanner sc = new Scanner(System.in);
static int getInt() throws Exception {
int n = 0;
if(sc.hasNext())
n = sc.nextInt();
return n;
}
static boolean check(int T) throws Exception {
if(T<=0 && T>50)
return false;
else
return true;
}
static boolean checker(int T) throws Exception {
if(T<=0 && T>100)
return false;
else
return true;
}
static boolean Arraycheck(int[] T,int k) throws Exception {
Boolean flag = true;
for(int i = 0;i<T.length;i++) {
if(T[i]<=0 && T[i]>k) {
return (flag^flag);
}
}
return flag;
}
static int[] getIntarr(int n) throws Exception {
int t[] = new int[n];
for (int i = 0; i < t.length; i++) {
if(sc.hasNext())
t[i] = sc.nextInt();
}
return t;
}
static boolean slide(int[] a,int k) throws Exception {
int start = 0,end = 0,presum=0,sum=0;
boolean flag = true;
while(start<k) {
presum+=a[start];
start++;
}
loop :
for(int i=k;i<a.length;i++) {
sum=(presum+a[i])-(a[end]);
end++;
if(sum!=presum) {
flag = false;
break loop;
}
}
return flag;
}
public static void main (String[] args) throws java.lang.Exception
{
int T = 0;
T = getInt();
if(check(T)) {
for(int tt=1;tt<=T;tt++) {
int k = 0,n = 0;
n = getInt();
k = getInt();
if(checker(k) && checker(n)) {
int[] a = getIntarr(n);
if(Arraycheck(a,n)) {
ArrayList<Integer> list = new ArrayList<>();
for(int y : a) {
if(!list.contains(y))
list.add(y);
}
if(list.size()>k) {
System.out.println(-1);
}
else {
int[] r = new int[k];
int j = 0;
if(slide(a,k)) {
System.out.println(n);
for(int l=0;l<n;l++)
System.out.print(a[l] + " ");
System.out.println();
}
else {
while(j<k) {
if(j<list.size())
r[j]=list.get(j);
else
r[j]=1;
j++;
}
int i = 0;
System.out.println(n*k);
while(i<n) {
for(int f=0;f<r.length;f++)
System.out.print(r[f] + " ");
i++;
}
System.out.println();
}
}
}
}
}
}
}
} | Java | ["4\n4 2\n1 2 2 1\n4 3\n1 2 2 1\n3 2\n1 2 3\n4 4\n4 3 4 2"] | 2 seconds | ["5\n1 2 1 2 1\n4\n1 2 2 1\n-1\n7\n4 3 2 1 4 3 2"] | NoteIn the first test case, we can make array $$$a$$$ beautiful by inserting the integer $$$1$$$ at index $$$3$$$ (in between the two existing $$$2$$$s). Now, all subarrays of length $$$k=2$$$ have the same sum $$$3$$$. There exists many other possible solutions, for example: $$$2, 1, 2, 1, 2, 1$$$ $$$1, 2, 1, 2, 1, 2$$$ In the second test case, the array is already beautiful: all subarrays of length $$$k=3$$$ have the same sum $$$5$$$.In the third test case, it can be shown that we cannot insert numbers to make array $$$a$$$ beautiful.In the fourth test case, the array $$$b$$$ shown is beautiful and all subarrays of length $$$k=4$$$ have the same sum $$$10$$$. There exist other solutions also. | Java 8 | standard input | [
"data structures",
"constructive algorithms",
"sortings",
"greedy"
] | 80d4b2d01215b12ebd89b8ee2d1ac6ed | The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 50$$$)Β β the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 100$$$). The second line of each test case contains $$$n$$$ space-separated integers ($$$1 \le a_i \le n$$$)Β β the array that Phoenix currently has. This array may or may not be already beautiful. | 1,400 | For each test case, if it is impossible to create a beautiful array, print -1. Otherwise, print two lines. The first line should contain the length of the beautiful array $$$m$$$ ($$$n \le m \le 10^4$$$). You don't need to minimize $$$m$$$. The second line should contain $$$m$$$ space-separated integers ($$$1 \le b_i \le n$$$)Β β a beautiful array that Phoenix can obtain after inserting some, possibly zero, integers into his array $$$a$$$. You may print integers that weren't originally in array $$$a$$$. If there are multiple solutions, print any. It's guaranteed that if we can make array $$$a$$$ beautiful, we can always make it with resulting length no more than $$$10^4$$$. | standard output | |
PASSED | f7bae8e0d53ea10e0cb1b351f8ceee87 | train_001.jsonl | 1588343700 | Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of lengthΒ $$$k$$$ have the same sum. A subarray of an array is any sequence of consecutive elements.Phoenix currently has an array $$$a$$$ of length $$$n$$$. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautiful. The inserted integers must be between $$$1$$$ and $$$n$$$ inclusive. Integers may be inserted anywhere (even before the first or after the last element), and he is not trying to minimize the number of inserted integers. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class Main{
public static void main(String[] args) throws Exception {
IO io = new IO();
PrintWriter out = new PrintWriter(System.out);
Solver sr = new Solver();
sr.solve(io,out);
out.flush();
out.close();
}
static class Solver
{
void solve(IO io, PrintWriter out)
{
int t = io.nextInt();
while(t-->0)
{
int n = io.nextInt();
int k = io.nextInt();
int[] ar = new int[n];
HashSet<Integer> hs= new HashSet<>();
for(int i=0 ; i<n ; i++){
ar[i] = io.nextInt();
hs.add(ar[i]);
}
if(hs.size()>k)
{
out.println("-1");
continue;
}
out.println(n*k);
for(int i=0 ; i<n ; i++)
{
for(int num: hs)
out.print(num+" ");
for(int j=0 ; j<k-hs.size() ; j++)
out.print("1 ");
}
out.println();
}
}
}
//Special thanks to Petr (on codeforces) who inspired me to implement IO class!
static class IO
{
BufferedReader reader;
StringTokenizer tokenizer;
public IO() {
reader = new BufferedReader(new InputStreamReader(System.in));
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() {
String s="";
try {
s=reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return s;
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
}
} | Java | ["4\n4 2\n1 2 2 1\n4 3\n1 2 2 1\n3 2\n1 2 3\n4 4\n4 3 4 2"] | 2 seconds | ["5\n1 2 1 2 1\n4\n1 2 2 1\n-1\n7\n4 3 2 1 4 3 2"] | NoteIn the first test case, we can make array $$$a$$$ beautiful by inserting the integer $$$1$$$ at index $$$3$$$ (in between the two existing $$$2$$$s). Now, all subarrays of length $$$k=2$$$ have the same sum $$$3$$$. There exists many other possible solutions, for example: $$$2, 1, 2, 1, 2, 1$$$ $$$1, 2, 1, 2, 1, 2$$$ In the second test case, the array is already beautiful: all subarrays of length $$$k=3$$$ have the same sum $$$5$$$.In the third test case, it can be shown that we cannot insert numbers to make array $$$a$$$ beautiful.In the fourth test case, the array $$$b$$$ shown is beautiful and all subarrays of length $$$k=4$$$ have the same sum $$$10$$$. There exist other solutions also. | Java 8 | standard input | [
"data structures",
"constructive algorithms",
"sortings",
"greedy"
] | 80d4b2d01215b12ebd89b8ee2d1ac6ed | The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 50$$$)Β β the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 100$$$). The second line of each test case contains $$$n$$$ space-separated integers ($$$1 \le a_i \le n$$$)Β β the array that Phoenix currently has. This array may or may not be already beautiful. | 1,400 | For each test case, if it is impossible to create a beautiful array, print -1. Otherwise, print two lines. The first line should contain the length of the beautiful array $$$m$$$ ($$$n \le m \le 10^4$$$). You don't need to minimize $$$m$$$. The second line should contain $$$m$$$ space-separated integers ($$$1 \le b_i \le n$$$)Β β a beautiful array that Phoenix can obtain after inserting some, possibly zero, integers into his array $$$a$$$. You may print integers that weren't originally in array $$$a$$$. If there are multiple solutions, print any. It's guaranteed that if we can make array $$$a$$$ beautiful, we can always make it with resulting length no more than $$$10^4$$$. | standard output | |
PASSED | e0446c60622a7038d3aab2cfa8c4e419 | train_001.jsonl | 1588343700 | Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of lengthΒ $$$k$$$ have the same sum. A subarray of an array is any sequence of consecutive elements.Phoenix currently has an array $$$a$$$ of length $$$n$$$. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautiful. The inserted integers must be between $$$1$$$ and $$$n$$$ inclusive. Integers may be inserted anywhere (even before the first or after the last element), and he is not trying to minimize the number of inserted integers. | 256 megabytes | import java.io.*;
import java.util.*;
public class Sol4{
public static void main(String[] args) throws IOException{
FastIO sc = new FastIO(System.in);
PrintWriter out = new PrintWriter(System.out);
int t = sc.nextInt();
wh: while(t-->0) {
int n = sc.nextInt();
int k = sc.nextInt();
int arr[] = new int[n];
int all[] = new int[101];
for(int i=0; i<n; i++) {
arr[i] = sc.nextInt();
all[arr[i]]++;
}
int ans[] = new int[k];
int idx = 0;
for(int i=1; i<101; i++) {
if(all[i]>0) {
ans[idx] = i;
idx++;
all[i] = Math.max(0, all[i]-10000/(k));
i--;
if(idx>=k)break;
}
}
for(int i=1; i<101; i++) {
if(all[i]>0) {
out.println(-1);
continue wh;
}
}
out.println(10000);
for(int i=0; i<10000; i++) {
out.print(Math.max(ans[i%k],1) + " ");
}
out.println("\n");
}
out.close();
}
static void shuffle(int[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
public static void ColumnSort(int arr[][], int col) {
Arrays.sort(arr, new Comparator<int[]>() {
@Override
public int compare(int[] entry1,
int[] entry2) {
Integer a = entry1[col];
Integer b = entry2[col];
return a.compareTo(b);
}
});
}
static class FastIO {
// Is your Fast I/O being bad?
InputStream dis;
byte[] buffer = new byte[1 << 17];
int pointer = 0;
public FastIO(String fileName) throws IOException {
dis = new FileInputStream(fileName);
}
public FastIO(InputStream is) throws IOException {
dis = is;
}
int nextInt() throws IOException {
int ret = 0;
byte b;
do {
b = nextByte();
} while (b <= ' ');
boolean negative = false;
if (b == '-') {
negative = true;
b = nextByte();
}
while (b >= '0' && b <= '9') {
ret = 10 * ret + b - '0';
b = nextByte();
}
return (negative) ? -ret : ret;
}
long nextLong() throws IOException {
long ret = 0;
byte b;
do {
b = nextByte();
} while (b <= ' ');
boolean negative = false;
if (b == '-') {
negative = true;
b = nextByte();
}
while (b >= '0' && b <= '9') {
ret = 10 * ret + b - '0';
b = nextByte();
}
return (negative) ? -ret : ret;
}
byte nextByte() throws IOException {
if (pointer == buffer.length) {
dis.read(buffer, 0, buffer.length);
pointer = 0;
}
return buffer[pointer++];
}
String next() throws IOException {
StringBuffer ret = new StringBuffer();
byte b;
do {
b = nextByte();
} while (b <= ' ');
while (b > ' ') {
ret.appendCodePoint(b);
b = nextByte();
}
return ret.toString();
}
}
} | Java | ["4\n4 2\n1 2 2 1\n4 3\n1 2 2 1\n3 2\n1 2 3\n4 4\n4 3 4 2"] | 2 seconds | ["5\n1 2 1 2 1\n4\n1 2 2 1\n-1\n7\n4 3 2 1 4 3 2"] | NoteIn the first test case, we can make array $$$a$$$ beautiful by inserting the integer $$$1$$$ at index $$$3$$$ (in between the two existing $$$2$$$s). Now, all subarrays of length $$$k=2$$$ have the same sum $$$3$$$. There exists many other possible solutions, for example: $$$2, 1, 2, 1, 2, 1$$$ $$$1, 2, 1, 2, 1, 2$$$ In the second test case, the array is already beautiful: all subarrays of length $$$k=3$$$ have the same sum $$$5$$$.In the third test case, it can be shown that we cannot insert numbers to make array $$$a$$$ beautiful.In the fourth test case, the array $$$b$$$ shown is beautiful and all subarrays of length $$$k=4$$$ have the same sum $$$10$$$. There exist other solutions also. | Java 8 | standard input | [
"data structures",
"constructive algorithms",
"sortings",
"greedy"
] | 80d4b2d01215b12ebd89b8ee2d1ac6ed | The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 50$$$)Β β the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 100$$$). The second line of each test case contains $$$n$$$ space-separated integers ($$$1 \le a_i \le n$$$)Β β the array that Phoenix currently has. This array may or may not be already beautiful. | 1,400 | For each test case, if it is impossible to create a beautiful array, print -1. Otherwise, print two lines. The first line should contain the length of the beautiful array $$$m$$$ ($$$n \le m \le 10^4$$$). You don't need to minimize $$$m$$$. The second line should contain $$$m$$$ space-separated integers ($$$1 \le b_i \le n$$$)Β β a beautiful array that Phoenix can obtain after inserting some, possibly zero, integers into his array $$$a$$$. You may print integers that weren't originally in array $$$a$$$. If there are multiple solutions, print any. It's guaranteed that if we can make array $$$a$$$ beautiful, we can always make it with resulting length no more than $$$10^4$$$. | standard output | |
PASSED | 3d67c54f69f468599278e0559e237b73 | train_001.jsonl | 1588343700 | Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of lengthΒ $$$k$$$ have the same sum. A subarray of an array is any sequence of consecutive elements.Phoenix currently has an array $$$a$$$ of length $$$n$$$. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautiful. The inserted integers must be between $$$1$$$ and $$$n$$$ inclusive. Integers may be inserted anywhere (even before the first or after the last element), and he is not trying to minimize the number of inserted integers. | 256 megabytes | // Main Code at the Bottom
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.BigInteger;
public class Main {
//Fast IO class
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
boolean env=System.getProperty("ONLINE_JUDGE") != null;
if(!env) {
try {
br=new BufferedReader(new FileReader("src\\input.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
else br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static long MOD=1000000000+7;
//Euclidean Algorithm
static long gcd(long A,long B){
return (B==0)?A:gcd(B,A%B);
}
//Modular Exponentiation
static long fastExpo(long x,long n){
if(n==0) return 1;
if((n&1)==0) return fastExpo((x*x)%MOD,n/2)%MOD;
return ((x%MOD)*fastExpo((x*x)%MOD,(n-1)/2))%MOD;
}
//Modular Inverse
static long inverse(long x) {
return fastExpo(x,MOD-2);
}
//Prime Number Algorithm
static boolean isPrime(long n){
if(n<=1) return false;
if(n<=3) return true;
if(n%2==0 || n%3==0) return false;
for(int i=5;i*i<=n;i+=6) if(n%i==0 || n%(i+2)==0) return false;
return true;
}
//Reverse an array
static void reverse(char arr[],int l,int r){
while(l<r) {
char tmp=arr[l];
arr[l++]=arr[r];
arr[r--]=tmp;
}
}
//Print array
static void print1d(int arr[]) {
out.println(Arrays.toString(arr));
}
static void print2d(int arr[][]) {
for(int a[]: arr) out.println(Arrays.toString(a));
}
// Pair
static class pair{
int x,y;
pair(int a,int b){
this.x=a;
this.y=b;
}
public boolean equals(Object obj) {
if(obj == null || obj.getClass()!= this.getClass()) return false;
pair p = (pair) obj;
return (this.x==p.x && this.y==p.y);
}
public int hashCode() {
return Objects.hash(x,y);
}
}
static FastReader sc=new FastReader();
static PrintWriter out=new PrintWriter(System.out);
//Main function(The main code starts from here
public static void main (String[] args) throws java.lang.Exception {
int test=1;
test=sc.nextInt();
while(test-->0){
int n=sc.nextInt(),k=sc.nextInt(),a[]=new int[n];
HashMap<Integer,Integer> map=new LinkedHashMap<>();
for(int i=0;i<n;i++) {
a[i]=sc.nextInt();
map.put(a[i],1);
}
if(map.size()>k) {
out.println(-1);
continue;
}
ArrayList<Integer> ans=new ArrayList<>();
for(Integer x: map.keySet()) ans.add(x);
while(ans.size()!=k) ans.add(ans.get(0));
out.println(10000);
int cur=ans.size();
for(int i=0;i<10000;i++) out.print(ans.get(i%cur)+" ");
out.println();
}
out.flush();
out.close();
}
} | Java | ["4\n4 2\n1 2 2 1\n4 3\n1 2 2 1\n3 2\n1 2 3\n4 4\n4 3 4 2"] | 2 seconds | ["5\n1 2 1 2 1\n4\n1 2 2 1\n-1\n7\n4 3 2 1 4 3 2"] | NoteIn the first test case, we can make array $$$a$$$ beautiful by inserting the integer $$$1$$$ at index $$$3$$$ (in between the two existing $$$2$$$s). Now, all subarrays of length $$$k=2$$$ have the same sum $$$3$$$. There exists many other possible solutions, for example: $$$2, 1, 2, 1, 2, 1$$$ $$$1, 2, 1, 2, 1, 2$$$ In the second test case, the array is already beautiful: all subarrays of length $$$k=3$$$ have the same sum $$$5$$$.In the third test case, it can be shown that we cannot insert numbers to make array $$$a$$$ beautiful.In the fourth test case, the array $$$b$$$ shown is beautiful and all subarrays of length $$$k=4$$$ have the same sum $$$10$$$. There exist other solutions also. | Java 8 | standard input | [
"data structures",
"constructive algorithms",
"sortings",
"greedy"
] | 80d4b2d01215b12ebd89b8ee2d1ac6ed | The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 50$$$)Β β the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 100$$$). The second line of each test case contains $$$n$$$ space-separated integers ($$$1 \le a_i \le n$$$)Β β the array that Phoenix currently has. This array may or may not be already beautiful. | 1,400 | For each test case, if it is impossible to create a beautiful array, print -1. Otherwise, print two lines. The first line should contain the length of the beautiful array $$$m$$$ ($$$n \le m \le 10^4$$$). You don't need to minimize $$$m$$$. The second line should contain $$$m$$$ space-separated integers ($$$1 \le b_i \le n$$$)Β β a beautiful array that Phoenix can obtain after inserting some, possibly zero, integers into his array $$$a$$$. You may print integers that weren't originally in array $$$a$$$. If there are multiple solutions, print any. It's guaranteed that if we can make array $$$a$$$ beautiful, we can always make it with resulting length no more than $$$10^4$$$. | standard output | |
PASSED | a67d58fe4abb31eaab603311665a612f | train_001.jsonl | 1602407100 | You have $$$n$$$ barrels lined up in a row, numbered from left to right from one. Initially, the $$$i$$$-th barrel contains $$$a_i$$$ liters of water.You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels $$$x$$$ and $$$y$$$ (the $$$x$$$-th barrel shouldn't be empty) and pour any possible amount of water from barrel $$$x$$$ to barrel $$$y$$$ (possibly, all water). You may assume that barrels have infinite capacity, so you can pour any amount of water in each of them. Calculate the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most $$$k$$$ times.Some examples: if you have four barrels, each containing $$$5$$$ liters of water, and $$$k = 1$$$, you may pour $$$5$$$ liters from the second barrel into the fourth, so the amounts of water in the barrels are $$$[5, 0, 5, 10]$$$, and the difference between the maximum and the minimum is $$$10$$$; if all barrels are empty, you can't make any operation, so the difference between the maximum and the minimum amount is still $$$0$$$. | 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.util.InputMismatchException;
import java.io.IOException;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author PersonOfInterest
*/
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);
BBarrels solver = new BBarrels();
int testCount = Integer.parseInt(in.next());
for (int i = 1; i <= testCount; i++)
solver.solve(i, in, out);
out.close();
}
static class BBarrels {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt(), k = in.nextInt();
Long a[] = new Long[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextLong();
}
Arrays.sort(a);
int i = n - 2;
long sum = a[n - 1];
while (k-- > 0) {
sum += a[i--];
}
out.println(sum);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String nextString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return nextString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void println(long i) {
writer.println(i);
}
}
}
| Java | ["2\n4 1\n5 5 5 5\n3 2\n0 0 0"] | 2 seconds | ["10\n0"] | null | Java 8 | standard input | [
"implementation",
"sortings",
"greedy"
] | 08c797a7972fae99f8b64b47c53d8aeb | The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$)Β β the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k < n \le 2 \cdot 10^5$$$)Β β the number of barrels and the number of pourings you can make. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^{9}$$$), where $$$a_i$$$ is the initial amount of water the $$$i$$$-th barrel has. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$. | 800 | For each test case, print the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most $$$k$$$ times. | standard output | |
PASSED | 0e59c805b9dd5a42db7f436a0a8a50e5 | train_001.jsonl | 1602407100 | You have $$$n$$$ barrels lined up in a row, numbered from left to right from one. Initially, the $$$i$$$-th barrel contains $$$a_i$$$ liters of water.You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels $$$x$$$ and $$$y$$$ (the $$$x$$$-th barrel shouldn't be empty) and pour any possible amount of water from barrel $$$x$$$ to barrel $$$y$$$ (possibly, all water). You may assume that barrels have infinite capacity, so you can pour any amount of water in each of them. Calculate the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most $$$k$$$ times.Some examples: if you have four barrels, each containing $$$5$$$ liters of water, and $$$k = 1$$$, you may pour $$$5$$$ liters from the second barrel into the fourth, so the amounts of water in the barrels are $$$[5, 0, 5, 10]$$$, and the difference between the maximum and the minimum is $$$10$$$; if all barrels are empty, you can't make any operation, so the difference between the maximum and the minimum amount is still $$$0$$$. | 256 megabytes | import java.util.*;
public class asd
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
int t=s.nextInt();
while(t-->0)
{
int n=s.nextInt();
int k=s.nextInt();
Long arr[]=new Long[n];
long sum=0;
for(int i=0;i<n;i++)
{
arr[i]=s.nextLong();
}
Arrays.sort(arr);
long min=arr[0];
for(int i=n-1;i>=0&&k>=0;i--,k--)
{
sum+=arr[i];
}
System.out.println(sum);
}
}
} | Java | ["2\n4 1\n5 5 5 5\n3 2\n0 0 0"] | 2 seconds | ["10\n0"] | null | Java 8 | standard input | [
"implementation",
"sortings",
"greedy"
] | 08c797a7972fae99f8b64b47c53d8aeb | The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$)Β β the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k < n \le 2 \cdot 10^5$$$)Β β the number of barrels and the number of pourings you can make. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^{9}$$$), where $$$a_i$$$ is the initial amount of water the $$$i$$$-th barrel has. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$. | 800 | For each test case, print the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most $$$k$$$ times. | standard output | |
PASSED | 7dd8dcea0184451da5a1c6c1fa2eeb60 | train_001.jsonl | 1602407100 | You have $$$n$$$ barrels lined up in a row, numbered from left to right from one. Initially, the $$$i$$$-th barrel contains $$$a_i$$$ liters of water.You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels $$$x$$$ and $$$y$$$ (the $$$x$$$-th barrel shouldn't be empty) and pour any possible amount of water from barrel $$$x$$$ to barrel $$$y$$$ (possibly, all water). You may assume that barrels have infinite capacity, so you can pour any amount of water in each of them. Calculate the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most $$$k$$$ times.Some examples: if you have four barrels, each containing $$$5$$$ liters of water, and $$$k = 1$$$, you may pour $$$5$$$ liters from the second barrel into the fourth, so the amounts of water in the barrels are $$$[5, 0, 5, 10]$$$, and the difference between the maximum and the minimum is $$$10$$$; if all barrels are empty, you can't make any operation, so the difference between the maximum and the minimum amount is still $$$0$$$. | 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.LinkedList;
import java.util.Random;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
public class First {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
int t;
t = in.nextInt();
while (t > 0) {
solver.call(in,out);
t--;
}
out.close();
}
static class TaskA {
public void call(InputReader in, PrintWriter out) {
int n , k ,a= 0;
n = in.nextInt();
k = in.nextInt();
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = in.nextLong();
}
shuffleSort(arr);
for (int i = n-2; i >=0; i--) {
arr[n-1] += arr[i];
a++;
if(a==k)
break;
}
out.println(arr[n-1]);
}
}
static int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static final Random random=new Random();
static void shuffleSort(long[] arr) {
int n=arr.length;
for (int i=0; i<n; i++) {
int a=random.nextInt(n), temp= (int) arr[a];
arr[a]=arr[i];
arr[i]=temp;
}
Arrays.sort(arr);
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong(){
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
} | Java | ["2\n4 1\n5 5 5 5\n3 2\n0 0 0"] | 2 seconds | ["10\n0"] | null | Java 8 | standard input | [
"implementation",
"sortings",
"greedy"
] | 08c797a7972fae99f8b64b47c53d8aeb | The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$)Β β the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k < n \le 2 \cdot 10^5$$$)Β β the number of barrels and the number of pourings you can make. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^{9}$$$), where $$$a_i$$$ is the initial amount of water the $$$i$$$-th barrel has. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$. | 800 | For each test case, print the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most $$$k$$$ times. | standard output | |
PASSED | 45963a75a5fbdfbddcb73e88b3b971b2 | train_001.jsonl | 1602407100 | You have $$$n$$$ barrels lined up in a row, numbered from left to right from one. Initially, the $$$i$$$-th barrel contains $$$a_i$$$ liters of water.You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels $$$x$$$ and $$$y$$$ (the $$$x$$$-th barrel shouldn't be empty) and pour any possible amount of water from barrel $$$x$$$ to barrel $$$y$$$ (possibly, all water). You may assume that barrels have infinite capacity, so you can pour any amount of water in each of them. Calculate the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most $$$k$$$ times.Some examples: if you have four barrels, each containing $$$5$$$ liters of water, and $$$k = 1$$$, you may pour $$$5$$$ liters from the second barrel into the fourth, so the amounts of water in the barrels are $$$[5, 0, 5, 10]$$$, and the difference between the maximum and the minimum is $$$10$$$; if all barrels are empty, you can't make any operation, so the difference between the maximum and the minimum amount is still $$$0$$$. | 256 megabytes | import java.util.*;
public class Barrels {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
int k = sc.nextInt();
Long[] arr = new Long[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextLong();
}
long sum = 0;
Arrays.sort(arr);
for (int i = n - k - 1; i <= n - 2; i++) {
sum += arr[i];
}
System.out.println(sum + arr[n - 1]);
}
}
} | Java | ["2\n4 1\n5 5 5 5\n3 2\n0 0 0"] | 2 seconds | ["10\n0"] | null | Java 8 | standard input | [
"implementation",
"sortings",
"greedy"
] | 08c797a7972fae99f8b64b47c53d8aeb | The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$)Β β the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k < n \le 2 \cdot 10^5$$$)Β β the number of barrels and the number of pourings you can make. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^{9}$$$), where $$$a_i$$$ is the initial amount of water the $$$i$$$-th barrel has. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$. | 800 | For each test case, print the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most $$$k$$$ times. | standard output | |
PASSED | e78d56b09145b70b5368e76150d5116d | train_001.jsonl | 1602407100 | You have $$$n$$$ barrels lined up in a row, numbered from left to right from one. Initially, the $$$i$$$-th barrel contains $$$a_i$$$ liters of water.You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels $$$x$$$ and $$$y$$$ (the $$$x$$$-th barrel shouldn't be empty) and pour any possible amount of water from barrel $$$x$$$ to barrel $$$y$$$ (possibly, all water). You may assume that barrels have infinite capacity, so you can pour any amount of water in each of them. Calculate the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most $$$k$$$ times.Some examples: if you have four barrels, each containing $$$5$$$ liters of water, and $$$k = 1$$$, you may pour $$$5$$$ liters from the second barrel into the fourth, so the amounts of water in the barrels are $$$[5, 0, 5, 10]$$$, and the difference between the maximum and the minimum is $$$10$$$; if all barrels are empty, you can't make any operation, so the difference between the maximum and the minimum amount is still $$$0$$$. | 256 megabytes | import java.util.Arrays;
import java.util.Scanner;
public class Barrels {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int t = scanner.nextInt();
for (int i = 0; i < t; i++) {
int n = scanner.nextInt();
int k = scanner.nextInt();
Integer[] b = new Integer[n];
for (int j = 0; j < n; j++) {
b[j] = scanner.nextInt();
}
Arrays.sort(b);
int ctr = b.length - 2;
long sum = b[b.length - 1];
for (int j = 0; j < k; j++) {
sum += b[ctr];
ctr--;
}
System.out.println(sum);
}
}
}
| Java | ["2\n4 1\n5 5 5 5\n3 2\n0 0 0"] | 2 seconds | ["10\n0"] | null | Java 8 | standard input | [
"implementation",
"sortings",
"greedy"
] | 08c797a7972fae99f8b64b47c53d8aeb | The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$)Β β the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k < n \le 2 \cdot 10^5$$$)Β β the number of barrels and the number of pourings you can make. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^{9}$$$), where $$$a_i$$$ is the initial amount of water the $$$i$$$-th barrel has. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$. | 800 | For each test case, print the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most $$$k$$$ times. | standard output | |
PASSED | df335307cac6ed61f67419efd43b1edb | train_001.jsonl | 1602407100 | You have $$$n$$$ barrels lined up in a row, numbered from left to right from one. Initially, the $$$i$$$-th barrel contains $$$a_i$$$ liters of water.You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels $$$x$$$ and $$$y$$$ (the $$$x$$$-th barrel shouldn't be empty) and pour any possible amount of water from barrel $$$x$$$ to barrel $$$y$$$ (possibly, all water). You may assume that barrels have infinite capacity, so you can pour any amount of water in each of them. Calculate the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most $$$k$$$ times.Some examples: if you have four barrels, each containing $$$5$$$ liters of water, and $$$k = 1$$$, you may pour $$$5$$$ liters from the second barrel into the fourth, so the amounts of water in the barrels are $$$[5, 0, 5, 10]$$$, and the difference between the maximum and the minimum is $$$10$$$; if all barrels are empty, you can't make any operation, so the difference between the maximum and the minimum amount is still $$$0$$$. | 256 megabytes | //package com.company;
import java.util.*;
import java.util.Arrays;
//import java.lang.Math.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
int t = scan.nextInt();
for(int j=0;j<t;j++)
{
int n= scan.nextInt();
int k = scan.nextInt();
Integer [] a = new Integer[n];
for(int i=0;i<n;i++)
{
a[i] = scan.nextInt();
}
Arrays.sort(a);
long res = a[n-1] ;
for(int i =0;i<k;i++)
{
res+=a[n-i-2];
}
System.out.println(res);
}
}
}
| Java | ["2\n4 1\n5 5 5 5\n3 2\n0 0 0"] | 2 seconds | ["10\n0"] | null | Java 8 | standard input | [
"implementation",
"sortings",
"greedy"
] | 08c797a7972fae99f8b64b47c53d8aeb | The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$)Β β the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k < n \le 2 \cdot 10^5$$$)Β β the number of barrels and the number of pourings you can make. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^{9}$$$), where $$$a_i$$$ is the initial amount of water the $$$i$$$-th barrel has. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$. | 800 | For each test case, print the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most $$$k$$$ times. | standard output | |
PASSED | c2912ec8eb94db1c46eaf33662873c91 | train_001.jsonl | 1602407100 | You have $$$n$$$ barrels lined up in a row, numbered from left to right from one. Initially, the $$$i$$$-th barrel contains $$$a_i$$$ liters of water.You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels $$$x$$$ and $$$y$$$ (the $$$x$$$-th barrel shouldn't be empty) and pour any possible amount of water from barrel $$$x$$$ to barrel $$$y$$$ (possibly, all water). You may assume that barrels have infinite capacity, so you can pour any amount of water in each of them. Calculate the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most $$$k$$$ times.Some examples: if you have four barrels, each containing $$$5$$$ liters of water, and $$$k = 1$$$, you may pour $$$5$$$ liters from the second barrel into the fourth, so the amounts of water in the barrels are $$$[5, 0, 5, 10]$$$, and the difference between the maximum and the minimum is $$$10$$$; if all barrels are empty, you can't make any operation, so the difference between the maximum and the minimum amount is still $$$0$$$. | 256 megabytes | import java.util.*;
public class dd{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0){
int n=sc.nextInt();
int k=sc.nextInt();
Long[] arr=new Long[n];
for (int i=0;i<n ;i++ ) {
arr[i]=sc.nextLong();
}
long sum=0;
Arrays.sort(arr);
for (int i=n-k-1;i<=n-2 ;i++ ) {
sum+=arr[i];
}
System.out.println(sum+arr[n-1]);
}
}
} | Java | ["2\n4 1\n5 5 5 5\n3 2\n0 0 0"] | 2 seconds | ["10\n0"] | null | Java 8 | standard input | [
"implementation",
"sortings",
"greedy"
] | 08c797a7972fae99f8b64b47c53d8aeb | The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$)Β β the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k < n \le 2 \cdot 10^5$$$)Β β the number of barrels and the number of pourings you can make. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^{9}$$$), where $$$a_i$$$ is the initial amount of water the $$$i$$$-th barrel has. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$. | 800 | For each test case, print the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most $$$k$$$ times. | standard output | |
PASSED | 9b1dc31337fcc3c162619a9a30b9ccf8 | train_001.jsonl | 1602407100 | You have $$$n$$$ barrels lined up in a row, numbered from left to right from one. Initially, the $$$i$$$-th barrel contains $$$a_i$$$ liters of water.You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels $$$x$$$ and $$$y$$$ (the $$$x$$$-th barrel shouldn't be empty) and pour any possible amount of water from barrel $$$x$$$ to barrel $$$y$$$ (possibly, all water). You may assume that barrels have infinite capacity, so you can pour any amount of water in each of them. Calculate the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most $$$k$$$ times.Some examples: if you have four barrels, each containing $$$5$$$ liters of water, and $$$k = 1$$$, you may pour $$$5$$$ liters from the second barrel into the fourth, so the amounts of water in the barrels are $$$[5, 0, 5, 10]$$$, and the difference between the maximum and the minimum is $$$10$$$; if all barrels are empty, you can't make any operation, so the difference between the maximum and the minimum amount is still $$$0$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class B {
public static void main(String[] args) {
Scanner fs=new Scanner(System.in);
int T=fs.nextInt();
for (int tt=0; tt<T; tt++) {
int n=fs.nextInt(), k=fs.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++) a[i]=fs.nextInt();
long sum=0;
//Arrays.sort(a);
sort(a);
for (int i=0; i<=k; i++)
sum+=a[n-1-i];
System.out.println(sum);
}
}
static void sort(int[] a) {
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
} | Java | ["2\n4 1\n5 5 5 5\n3 2\n0 0 0"] | 2 seconds | ["10\n0"] | null | Java 8 | standard input | [
"implementation",
"sortings",
"greedy"
] | 08c797a7972fae99f8b64b47c53d8aeb | The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$)Β β the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k < n \le 2 \cdot 10^5$$$)Β β the number of barrels and the number of pourings you can make. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^{9}$$$), where $$$a_i$$$ is the initial amount of water the $$$i$$$-th barrel has. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$. | 800 | For each test case, print the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most $$$k$$$ times. | standard output | |
PASSED | ccdfeb5b9349a9808f828d34f2f70aea | train_001.jsonl | 1602407100 | You have $$$n$$$ barrels lined up in a row, numbered from left to right from one. Initially, the $$$i$$$-th barrel contains $$$a_i$$$ liters of water.You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels $$$x$$$ and $$$y$$$ (the $$$x$$$-th barrel shouldn't be empty) and pour any possible amount of water from barrel $$$x$$$ to barrel $$$y$$$ (possibly, all water). You may assume that barrels have infinite capacity, so you can pour any amount of water in each of them. Calculate the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most $$$k$$$ times.Some examples: if you have four barrels, each containing $$$5$$$ liters of water, and $$$k = 1$$$, you may pour $$$5$$$ liters from the second barrel into the fourth, so the amounts of water in the barrels are $$$[5, 0, 5, 10]$$$, and the difference between the maximum and the minimum is $$$10$$$; if all barrels are empty, you can't make any operation, so the difference between the maximum and the minimum amount is still $$$0$$$. | 256 megabytes | import java.util.*;
public class Solution{
public static void main(String args[])
{
Scanner take=new Scanner(System.in);
int t=take.nextInt();
int i,j;
for(int li=1;li<=t;li++)
{
int n=take.nextInt();
int k=take.nextInt();
int a[]=new int[(int)n];
for(i=0;i<n;i++) a[i]=take.nextInt();
sort(a);
long ans=0;
for(i=0;i<=k;i++)
{
ans+=a[n-1-i];
}
System.out.println(ans);
}
}
public static void sort(int a[])
{ ArrayList<Integer> al=new ArrayList<>();
al.clear();
for(int i=0;i<a.length;i++) al.add(a[i]);
Collections.sort(al);
for(int i=0;i<a.length;i++) a[i]=al.get(i);
}
} | Java | ["2\n4 1\n5 5 5 5\n3 2\n0 0 0"] | 2 seconds | ["10\n0"] | null | Java 8 | standard input | [
"implementation",
"sortings",
"greedy"
] | 08c797a7972fae99f8b64b47c53d8aeb | The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$)Β β the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k < n \le 2 \cdot 10^5$$$)Β β the number of barrels and the number of pourings you can make. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^{9}$$$), where $$$a_i$$$ is the initial amount of water the $$$i$$$-th barrel has. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$. | 800 | For each test case, print the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most $$$k$$$ times. | standard output | |
PASSED | fc08352679615a7a7fe023893a034b1e | train_001.jsonl | 1602407100 | You have $$$n$$$ barrels lined up in a row, numbered from left to right from one. Initially, the $$$i$$$-th barrel contains $$$a_i$$$ liters of water.You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels $$$x$$$ and $$$y$$$ (the $$$x$$$-th barrel shouldn't be empty) and pour any possible amount of water from barrel $$$x$$$ to barrel $$$y$$$ (possibly, all water). You may assume that barrels have infinite capacity, so you can pour any amount of water in each of them. Calculate the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most $$$k$$$ times.Some examples: if you have four barrels, each containing $$$5$$$ liters of water, and $$$k = 1$$$, you may pour $$$5$$$ liters from the second barrel into the fourth, so the amounts of water in the barrels are $$$[5, 0, 5, 10]$$$, and the difference between the maximum and the minimum is $$$10$$$; if all barrels are empty, you can't make any operation, so the difference between the maximum and the minimum amount is still $$$0$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class B {
public static void main(String[] args) {
Scanner fs=new Scanner(System.in);
int T=fs.nextInt();
for (int tt=0; tt<T; tt++) {
int n=fs.nextInt(), k=fs.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++) a[i]=fs.nextInt();
long sum=0;
sort(a);
for (int i=0; i<=k; i++)
sum+=a[n-1-i];
System.out.println(sum);
}
}
static void sort(int[] a) {
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
} | Java | ["2\n4 1\n5 5 5 5\n3 2\n0 0 0"] | 2 seconds | ["10\n0"] | null | Java 8 | standard input | [
"implementation",
"sortings",
"greedy"
] | 08c797a7972fae99f8b64b47c53d8aeb | The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$)Β β the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k < n \le 2 \cdot 10^5$$$)Β β the number of barrels and the number of pourings you can make. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^{9}$$$), where $$$a_i$$$ is the initial amount of water the $$$i$$$-th barrel has. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$. | 800 | For each test case, print the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most $$$k$$$ times. | standard output | |
PASSED | f296674cc0180b435891016dc2c7ca0e | train_001.jsonl | 1602407100 | You have $$$n$$$ barrels lined up in a row, numbered from left to right from one. Initially, the $$$i$$$-th barrel contains $$$a_i$$$ liters of water.You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels $$$x$$$ and $$$y$$$ (the $$$x$$$-th barrel shouldn't be empty) and pour any possible amount of water from barrel $$$x$$$ to barrel $$$y$$$ (possibly, all water). You may assume that barrels have infinite capacity, so you can pour any amount of water in each of them. Calculate the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most $$$k$$$ times.Some examples: if you have four barrels, each containing $$$5$$$ liters of water, and $$$k = 1$$$, you may pour $$$5$$$ liters from the second barrel into the fourth, so the amounts of water in the barrels are $$$[5, 0, 5, 10]$$$, and the difference between the maximum and the minimum is $$$10$$$; if all barrels are empty, you can't make any operation, so the difference between the maximum and the minimum amount is still $$$0$$$. | 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.StringTokenizer;
public class B {
public static void main(String[] args) {
FastScanner fs=new FastScanner();
int T=fs.nextInt();
for (int tt=0; tt<T; tt++) {
int n=fs.nextInt(), k=fs.nextInt();
int[] a=fs.readArray(n);
long sum=0;
sort(a);
for (int i=0; i<=k; i++)
sum+=a[n-1-i];
System.out.println(sum);
}
}
static void sort(int[] a) {
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
} | Java | ["2\n4 1\n5 5 5 5\n3 2\n0 0 0"] | 2 seconds | ["10\n0"] | null | Java 8 | standard input | [
"implementation",
"sortings",
"greedy"
] | 08c797a7972fae99f8b64b47c53d8aeb | The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$)Β β the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k < n \le 2 \cdot 10^5$$$)Β β the number of barrels and the number of pourings you can make. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^{9}$$$), where $$$a_i$$$ is the initial amount of water the $$$i$$$-th barrel has. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$. | 800 | For each test case, print the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most $$$k$$$ times. | standard output | |
PASSED | 2662e1d9d6f35fedaa8bd0a566c30063 | train_001.jsonl | 1602407100 | You have $$$n$$$ barrels lined up in a row, numbered from left to right from one. Initially, the $$$i$$$-th barrel contains $$$a_i$$$ liters of water.You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels $$$x$$$ and $$$y$$$ (the $$$x$$$-th barrel shouldn't be empty) and pour any possible amount of water from barrel $$$x$$$ to barrel $$$y$$$ (possibly, all water). You may assume that barrels have infinite capacity, so you can pour any amount of water in each of them. Calculate the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most $$$k$$$ times.Some examples: if you have four barrels, each containing $$$5$$$ liters of water, and $$$k = 1$$$, you may pour $$$5$$$ liters from the second barrel into the fourth, so the amounts of water in the barrels are $$$[5, 0, 5, 10]$$$, and the difference between the maximum and the minimum is $$$10$$$; if all barrels are empty, you can't make any operation, so the difference between the maximum and the minimum amount is still $$$0$$$. | 256 megabytes | import java.util.Collections;
import java.util.PriorityQueue;
import java.util.Scanner;
public class heapBarrels {
// https://codeforces.com/problemset/problem/1430/B
public static void main(String[] args) {
/*
* PriorityQueue<Integer> barrels = new
* PriorityQueue<Integer>(Collections.reverseOrder()); barrels.add(3);
* barrels.add(1); barrels.add(4);
*
* System.out.println(barrels.poll()); System.out.println(barrels.poll());
* System.out.println(barrels.poll());
*/
Scanner scanner = new Scanner(System.in);
int tc = scanner.nextInt();
for (int i = 0; i < tc; i++) {
int barrel = scanner.nextInt();
int count = scanner.nextInt();
PriorityQueue<Long> barrelsQueue = new PriorityQueue<Long>(Collections.reverseOrder());
for (int j = 0; j < barrel; j++)
barrelsQueue.add(scanner.nextLong());
//System.out.println(barrelsQueue);
Long diff = getMaxDiff(count, barrelsQueue);
System.out.println(diff);
}
}
private static Long getMaxDiff(int count, PriorityQueue<Long> barrelsQueue) {
if (barrelsQueue.size() > 1) {
for (int i = 0; i < count; i++) {
Long last = barrelsQueue.poll();
Long secLast = barrelsQueue.poll();
if (last == 0 || secLast == 0) {
return Math.abs(last - secLast);
} else {
barrelsQueue.add(last + secLast);
barrelsQueue.add((long) 0);
}
}
PriorityQueue<Long> ascOrder = new PriorityQueue<Long>();
ascOrder.addAll(barrelsQueue);
return barrelsQueue.poll() - ascOrder.poll();
} else {
return (long) -1;
}
}
}
| Java | ["2\n4 1\n5 5 5 5\n3 2\n0 0 0"] | 2 seconds | ["10\n0"] | null | Java 8 | standard input | [
"implementation",
"sortings",
"greedy"
] | 08c797a7972fae99f8b64b47c53d8aeb | The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$)Β β the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k < n \le 2 \cdot 10^5$$$)Β β the number of barrels and the number of pourings you can make. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^{9}$$$), where $$$a_i$$$ is the initial amount of water the $$$i$$$-th barrel has. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$. | 800 | For each test case, print the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most $$$k$$$ times. | standard output | |
PASSED | 033774eb44f5a9a345bc458d006071d1 | train_001.jsonl | 1602407100 | You have $$$n$$$ barrels lined up in a row, numbered from left to right from one. Initially, the $$$i$$$-th barrel contains $$$a_i$$$ liters of water.You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels $$$x$$$ and $$$y$$$ (the $$$x$$$-th barrel shouldn't be empty) and pour any possible amount of water from barrel $$$x$$$ to barrel $$$y$$$ (possibly, all water). You may assume that barrels have infinite capacity, so you can pour any amount of water in each of them. Calculate the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most $$$k$$$ times.Some examples: if you have four barrels, each containing $$$5$$$ liters of water, and $$$k = 1$$$, you may pour $$$5$$$ liters from the second barrel into the fourth, so the amounts of water in the barrels are $$$[5, 0, 5, 10]$$$, and the difference between the maximum and the minimum is $$$10$$$; if all barrels are empty, you can't make any operation, so the difference between the maximum and the minimum amount is still $$$0$$$. | 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;
import java.io.PrintWriter;
public class bEdu96 {
static int [] dx = {1,0,-1,0}, dy = {0,1,0,-1};
public static void main(String[] args) {
FastScanner fs = new FastScanner ();
int T = fs.nextInt();
for (int tt=0; tt<T; tt++) {
int n = fs.nextInt(), k =fs.nextInt();
int [] ar = fs.readArray(n);
sort(ar);
long sum = 0;
for (int i=0;i<=k;i++) {
sum += ar[n-i-1];
}
System.out.println(sum);
}
}
static void sort(int[] a) {
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreElements())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
boolean hasNext() {
String next=null;
try {
next = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (next==null) {
return false;
}
st=new StringTokenizer(next);
return true;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
}
}
| Java | ["2\n4 1\n5 5 5 5\n3 2\n0 0 0"] | 2 seconds | ["10\n0"] | null | Java 8 | standard input | [
"implementation",
"sortings",
"greedy"
] | 08c797a7972fae99f8b64b47c53d8aeb | The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$)Β β the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k < n \le 2 \cdot 10^5$$$)Β β the number of barrels and the number of pourings you can make. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^{9}$$$), where $$$a_i$$$ is the initial amount of water the $$$i$$$-th barrel has. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$. | 800 | For each test case, print the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most $$$k$$$ times. | standard output | |
PASSED | 731275a30136d7ce3d86047c46bc9153 | train_001.jsonl | 1602407100 | You have $$$n$$$ barrels lined up in a row, numbered from left to right from one. Initially, the $$$i$$$-th barrel contains $$$a_i$$$ liters of water.You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels $$$x$$$ and $$$y$$$ (the $$$x$$$-th barrel shouldn't be empty) and pour any possible amount of water from barrel $$$x$$$ to barrel $$$y$$$ (possibly, all water). You may assume that barrels have infinite capacity, so you can pour any amount of water in each of them. Calculate the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most $$$k$$$ times.Some examples: if you have four barrels, each containing $$$5$$$ liters of water, and $$$k = 1$$$, you may pour $$$5$$$ liters from the second barrel into the fourth, so the amounts of water in the barrels are $$$[5, 0, 5, 10]$$$, and the difference between the maximum and the minimum is $$$10$$$; if all barrels are empty, you can't make any operation, so the difference between the maximum and the minimum amount is still $$$0$$$. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
public static void solve(InputReader in, OutputWriter out) {
int n = in.readInt();
int k = in.readInt();
Integer a[] = new Integer[n];
for(int i = 0; i<n; i++)
a[i] = in.readInt();
Arrays.sort(a);
long sum = a[n-1];
for(int i = n-2; k-- > 0; i--) {
sum += a[i];
}
if(n == 1) out.println(0);
else out.println(sum);
}
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
OutputWriter out = new OutputWriter(System.out);
int t = in.readInt();
while (t-- > 0)
solve(in , out);
out.flush();
out.close();
}
}
class InputReader{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public 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 boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
}
| Java | ["2\n4 1\n5 5 5 5\n3 2\n0 0 0"] | 2 seconds | ["10\n0"] | null | Java 8 | standard input | [
"implementation",
"sortings",
"greedy"
] | 08c797a7972fae99f8b64b47c53d8aeb | The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$)Β β the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k < n \le 2 \cdot 10^5$$$)Β β the number of barrels and the number of pourings you can make. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^{9}$$$), where $$$a_i$$$ is the initial amount of water the $$$i$$$-th barrel has. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$. | 800 | For each test case, print the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most $$$k$$$ times. | standard output | |
PASSED | cb99e4c9ffa981202557d66044fa3915 | train_001.jsonl | 1602407100 | You have $$$n$$$ barrels lined up in a row, numbered from left to right from one. Initially, the $$$i$$$-th barrel contains $$$a_i$$$ liters of water.You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels $$$x$$$ and $$$y$$$ (the $$$x$$$-th barrel shouldn't be empty) and pour any possible amount of water from barrel $$$x$$$ to barrel $$$y$$$ (possibly, all water). You may assume that barrels have infinite capacity, so you can pour any amount of water in each of them. Calculate the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most $$$k$$$ times.Some examples: if you have four barrels, each containing $$$5$$$ liters of water, and $$$k = 1$$$, you may pour $$$5$$$ liters from the second barrel into the fourth, so the amounts of water in the barrels are $$$[5, 0, 5, 10]$$$, and the difference between the maximum and the minimum is $$$10$$$; if all barrels are empty, you can't make any operation, so the difference between the maximum and the minimum amount is still $$$0$$$. | 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.Scanner;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Tanzim Ibn Patowary
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
public void solve(int testNumber, Scanner in, PrintWriter out) {
while (testNumber-- != 0) {
int t = in.nextInt();
while (t-- != 0) {
int n = in.nextInt();
int k = in.nextInt();
Long[] array = new Long[n];
for (int i = 0; i < n; i++)
array[i] = in.nextLong();
Arrays.sort(array);
int steps = 0;
long max = array[n - 1];
while (steps < k) {
max += array[n - 2 - steps];
steps += 1;
}
out.println(max);
}
}
}
}
}
| Java | ["2\n4 1\n5 5 5 5\n3 2\n0 0 0"] | 2 seconds | ["10\n0"] | null | Java 8 | standard input | [
"implementation",
"sortings",
"greedy"
] | 08c797a7972fae99f8b64b47c53d8aeb | The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$)Β β the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k < n \le 2 \cdot 10^5$$$)Β β the number of barrels and the number of pourings you can make. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^{9}$$$), where $$$a_i$$$ is the initial amount of water the $$$i$$$-th barrel has. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$. | 800 | For each test case, print the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most $$$k$$$ times. | standard output | |
PASSED | 47d4eda64ad177204e6ef97814126ea6 | train_001.jsonl | 1602407100 | You have $$$n$$$ barrels lined up in a row, numbered from left to right from one. Initially, the $$$i$$$-th barrel contains $$$a_i$$$ liters of water.You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels $$$x$$$ and $$$y$$$ (the $$$x$$$-th barrel shouldn't be empty) and pour any possible amount of water from barrel $$$x$$$ to barrel $$$y$$$ (possibly, all water). You may assume that barrels have infinite capacity, so you can pour any amount of water in each of them. Calculate the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most $$$k$$$ times.Some examples: if you have four barrels, each containing $$$5$$$ liters of water, and $$$k = 1$$$, you may pour $$$5$$$ liters from the second barrel into the fourth, so the amounts of water in the barrels are $$$[5, 0, 5, 10]$$$, and the difference between the maximum and the minimum is $$$10$$$; if all barrels are empty, you can't make any operation, so the difference between the maximum and the minimum amount is still $$$0$$$. | 256 megabytes | import java.util.*;
public class p1430B {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
for (int t = sc.nextInt(); t-- > 0;) {
Integer n = sc.nextInt(), k = sc.nextInt(), a[] = new Integer[n];
for (int i = 0; i < n; i++) a[i] = sc.nextInt();
Arrays.sort(a);
long sum = a[n-1];
for (int i = 2; k-- > 0; i++) sum+=a[n-i];
System.out.println(sum);
} } } | Java | ["2\n4 1\n5 5 5 5\n3 2\n0 0 0"] | 2 seconds | ["10\n0"] | null | Java 8 | standard input | [
"implementation",
"sortings",
"greedy"
] | 08c797a7972fae99f8b64b47c53d8aeb | The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$)Β β the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k < n \le 2 \cdot 10^5$$$)Β β the number of barrels and the number of pourings you can make. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^{9}$$$), where $$$a_i$$$ is the initial amount of water the $$$i$$$-th barrel has. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$. | 800 | For each test case, print the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most $$$k$$$ times. | standard output | |
PASSED | 6a8c5687d6c70bd92154843cf312bd94 | train_001.jsonl | 1602407100 | You have $$$n$$$ barrels lined up in a row, numbered from left to right from one. Initially, the $$$i$$$-th barrel contains $$$a_i$$$ liters of water.You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels $$$x$$$ and $$$y$$$ (the $$$x$$$-th barrel shouldn't be empty) and pour any possible amount of water from barrel $$$x$$$ to barrel $$$y$$$ (possibly, all water). You may assume that barrels have infinite capacity, so you can pour any amount of water in each of them. Calculate the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most $$$k$$$ times.Some examples: if you have four barrels, each containing $$$5$$$ liters of water, and $$$k = 1$$$, you may pour $$$5$$$ liters from the second barrel into the fourth, so the amounts of water in the barrels are $$$[5, 0, 5, 10]$$$, and the difference between the maximum and the minimum is $$$10$$$; if all barrels are empty, you can't make any operation, so the difference between the maximum and the minimum amount is still $$$0$$$. | 256 megabytes | // package Education96;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.util.*;
public class typeB {
public static void main(String[] args) {
FastReader s = new FastReader();
PrintWriter out = new PrintWriter(System.out);
int T = s.nextInt();
for(int t=0;t<T;t++) {
int n = s.nextInt();
int k = s.nextInt();
List<Long> arr = new ArrayList<>();;
for(int i=0;i<n;i++)
arr.add(s.nextLong());
Collections.sort(arr);
int j = n-1;
long sum = arr.get(j);
j--;
while(k>0){
sum+=arr.get(j);
j--;
k--;
}
out.println(sum);
}
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 | ["2\n4 1\n5 5 5 5\n3 2\n0 0 0"] | 2 seconds | ["10\n0"] | null | Java 8 | standard input | [
"implementation",
"sortings",
"greedy"
] | 08c797a7972fae99f8b64b47c53d8aeb | The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$)Β β the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k < n \le 2 \cdot 10^5$$$)Β β the number of barrels and the number of pourings you can make. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^{9}$$$), where $$$a_i$$$ is the initial amount of water the $$$i$$$-th barrel has. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$. | 800 | For each test case, print the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most $$$k$$$ times. | standard output | |
PASSED | 65d26f3af2f3e5e3c4cdec1b7328849a | train_001.jsonl | 1602407100 | You have $$$n$$$ barrels lined up in a row, numbered from left to right from one. Initially, the $$$i$$$-th barrel contains $$$a_i$$$ liters of water.You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels $$$x$$$ and $$$y$$$ (the $$$x$$$-th barrel shouldn't be empty) and pour any possible amount of water from barrel $$$x$$$ to barrel $$$y$$$ (possibly, all water). You may assume that barrels have infinite capacity, so you can pour any amount of water in each of them. Calculate the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most $$$k$$$ times.Some examples: if you have four barrels, each containing $$$5$$$ liters of water, and $$$k = 1$$$, you may pour $$$5$$$ liters from the second barrel into the fourth, so the amounts of water in the barrels are $$$[5, 0, 5, 10]$$$, and the difference between the maximum and the minimum is $$$10$$$; if all barrels are empty, you can't make any operation, so the difference between the maximum and the minimum amount is still $$$0$$$. | 256 megabytes | import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.time.LocalTime;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class B {
public static void main(String[] args) {
FastScanner scan = new FastScanner();
int t = scan.nextInt();
for(int tt=0; tt<t; tt++) {
int n = scan.nextInt(), k = scan.nextInt();
int [] arr = scan.readArray(n);
sort(arr);
long sum = 0;
for(int i=0; i<=k; i++) {
sum += arr[n-i-1];
}
System.out.println(sum);
}
}
public static void sort(int [] a) {
ArrayList<Integer> b = new ArrayList<>();
for(int i: a) b.add(i);
Collections.sort(b);
for(int i=0; i<a.length; i++) a[i]= b.get(i);
}
static class FastScanner{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while(!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e){
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int [] readArray(int n) {
int [] a = new int[n];
for(int i=0; i<n ; i++) a[i] = nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["2\n4 1\n5 5 5 5\n3 2\n0 0 0"] | 2 seconds | ["10\n0"] | null | Java 8 | standard input | [
"implementation",
"sortings",
"greedy"
] | 08c797a7972fae99f8b64b47c53d8aeb | The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$)Β β the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k < n \le 2 \cdot 10^5$$$)Β β the number of barrels and the number of pourings you can make. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^{9}$$$), where $$$a_i$$$ is the initial amount of water the $$$i$$$-th barrel has. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$. | 800 | For each test case, print the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most $$$k$$$ times. | standard output | |
PASSED | b5b49367ce33fc3e8dfc55bf387a4d8b | train_001.jsonl | 1380295800 | One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other nβ-β1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want? | 256 megabytes | import java.util.*;
import java.io.*;
import static java.lang.Math.*;
public class GenericProblem
{
/*
* This FastReader code is taken from GeeksForGeeks.com
* https://www.geeksforgeeks.org/fast-io-in-java-in-competitive-programming/
*
* The article was written by Rishabh Mahrsee
*/
public static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
public static FastReader file = new FastReader();
public static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args)
{
int n = file.nextInt();
double sum = 0;
int max = Integer.MIN_VALUE;
for (int i = 0; i < n; i++)
{
int next = file.nextInt();
sum += next;
max = max(max, next);
}
int ans = (int)Math.ceil(sum / (n - 1));
out.println(max(ans, max));
out.close();
}
} | Java | ["3\n3 2 2", "4\n2 2 2 2"] | 2 seconds | ["4", "3"] | NoteYou don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game). | Java 8 | standard input | [
"binary search",
"sortings",
"math"
] | 09f5623c3717c9d360334500b198d8e0 | The first line contains integer n (3ββ€βnββ€β105). The second line contains n space-separated integers a1,βa2,β...,βan (1ββ€βaiββ€β109) β the i-th number in the list is the number of rounds the i-th person wants to play. | 1,600 | In a single line print a single integer β the minimum number of game rounds the friends need to let the i-th person play at least ai rounds. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | 6ff2970bfca01dbce7aeaea212d3f9c0 | train_001.jsonl | 1380295800 | One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other nβ-β1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want? | 256 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class Main {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = sc.nextInt();
long[] a = new long[n];
long ans = 0;
long sum = 0;
for (int i = 0; i < n; i++) {
a[i] = sc.nextLong();
ans = max(ans, a[i]);
sum += a[i];
}
ans = max(ans, (sum + n - 2) / (n - 1));
pw.print(ans);
pw.close();
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st = new StringTokenizer("");
public FastScanner(InputStream inputStream) throws FileNotFoundException {
br = new BufferedReader(new InputStreamReader(inputStream));
}
public FastScanner(String file) throws FileNotFoundException {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (!st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
} | Java | ["3\n3 2 2", "4\n2 2 2 2"] | 2 seconds | ["4", "3"] | NoteYou don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game). | Java 8 | standard input | [
"binary search",
"sortings",
"math"
] | 09f5623c3717c9d360334500b198d8e0 | The first line contains integer n (3ββ€βnββ€β105). The second line contains n space-separated integers a1,βa2,β...,βan (1ββ€βaiββ€β109) β the i-th number in the list is the number of rounds the i-th person wants to play. | 1,600 | In a single line print a single integer β the minimum number of game rounds the friends need to let the i-th person play at least ai rounds. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | 6626d68512bc646226c0f1534a6450c8 | train_001.jsonl | 1380295800 | One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other nβ-β1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want? | 256 megabytes | import java.util.Scanner;
public class Mafia {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[] arr=new int[n];
long m=0,sum=0, res=0;
for(int i=0;i<n;i++){
arr[i]=sc.nextInt();
sum+=arr[i];
m=Math.max(arr[i], m);
}
res=sum/(n-1);
while(res*(n-1)<sum)
res++;
System.out.println(Math.max(res, m));
}
}
| Java | ["3\n3 2 2", "4\n2 2 2 2"] | 2 seconds | ["4", "3"] | NoteYou don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game). | Java 6 | standard input | [
"binary search",
"sortings",
"math"
] | 09f5623c3717c9d360334500b198d8e0 | The first line contains integer n (3ββ€βnββ€β105). The second line contains n space-separated integers a1,βa2,β...,βan (1ββ€βaiββ€β109) β the i-th number in the list is the number of rounds the i-th person wants to play. | 1,600 | In a single line print a single integer β the minimum number of game rounds the friends need to let the i-th person play at least ai rounds. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | db7d2a9606555822f89cc24f8cd0eba6 | train_001.jsonl | 1380295800 | One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other nβ-β1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want? | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
int n = Integer.parseInt(br.readLine());
String str[] = br.readLine().split(" ");
// int a[]=new int [n];
double sum = 0;
int max = -1;
for (int i = 0; i < n; i++) {
sum += Integer.parseInt(str[i]);
if (max < Integer.parseInt(str[i]))
max = Integer.parseInt(str[i]);
}
if ((int) Math.ceil(sum / (n - 1)) < max)
System.out.println(max);
else
System.out.println((int) Math.ceil(sum / (n - 1)));
br.close();
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| Java | ["3\n3 2 2", "4\n2 2 2 2"] | 2 seconds | ["4", "3"] | NoteYou don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game). | Java 6 | standard input | [
"binary search",
"sortings",
"math"
] | 09f5623c3717c9d360334500b198d8e0 | The first line contains integer n (3ββ€βnββ€β105). The second line contains n space-separated integers a1,βa2,β...,βan (1ββ€βaiββ€β109) β the i-th number in the list is the number of rounds the i-th person wants to play. | 1,600 | In a single line print a single integer β the minimum number of game rounds the friends need to let the i-th person play at least ai rounds. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | fdaa337dc3d3bf7da286cce2106d4959 | train_001.jsonl | 1380295800 | One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other nβ-β1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want? | 256 megabytes | import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
/*
br = new BufferedReader(new FileReader("input.txt"));
pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
*/
public class Main {
private static BufferedReader br;
private static StringTokenizer st;
private static PrintWriter pw;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
//int qq = 1;
int qq = Integer.MAX_VALUE;
//int qq = readInt();
for(int casenum = 1; casenum <= qq; casenum++) {
int n = readInt();
int[] list = new int[n];
int max = 0;
for(int i = 0; i < n; i++) {
list[i] = readInt();
max = Math.max(max, list[i]);
}
long over = 0;
for(int out: list) {
over += max - out;
}
if(over >= max) {
pw.println(max);
}
else {
pw.println(max + (max-over+n-2)/(n-1));
}
}
pw.close();
}
private static void exitImmediately() {
pw.close();
System.exit(0);
}
private static long readLong() throws IOException {
return Long.parseLong(nextToken());
}
private static double readDouble() throws IOException {
return Double.parseDouble(nextToken());
}
private static int readInt() throws IOException {
return Integer.parseInt(nextToken());
}
private static String nextToken() throws IOException {
while(st == null || !st.hasMoreTokens()) {
if(!br.ready()) {
exitImmediately();
}
st = new StringTokenizer(br.readLine().trim());
}
return st.nextToken();
}
}
| Java | ["3\n3 2 2", "4\n2 2 2 2"] | 2 seconds | ["4", "3"] | NoteYou don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game). | Java 6 | standard input | [
"binary search",
"sortings",
"math"
] | 09f5623c3717c9d360334500b198d8e0 | The first line contains integer n (3ββ€βnββ€β105). The second line contains n space-separated integers a1,βa2,β...,βan (1ββ€βaiββ€β109) β the i-th number in the list is the number of rounds the i-th person wants to play. | 1,600 | In a single line print a single integer β the minimum number of game rounds the friends need to let the i-th person play at least ai rounds. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | 360be9052fc4a58447ccb62a611d6fe5 | train_001.jsonl | 1380295800 | One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other nβ-β1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want? | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class A {
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter out;
public void solve() throws IOException {
int N = nextInt();
long[] A = new long[N];
long max = 0;
for(int i = 0; i < N; i++){
A[i] = nextLong();
max = Math.max(max, A[i]);
}
long l = max;
long r = max*N;
while(l < r){
long mid = (l+r)/2;
if(OK(mid, A))
r = mid;
else
l = mid+1;
}
out.println(l);
}
public boolean OK(long r, long[] A){
long total = 0;
for(int i = 0; i < A.length; i++){
if(A[i] < r)
total += (r-A[i]);
}
return total >= r;
}
/**
* @param args
*/
public static void main(String[] args) {
new A().run();
}
public void run() {
try {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
out = new PrintWriter(System.out);
solve();
reader.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
}
| Java | ["3\n3 2 2", "4\n2 2 2 2"] | 2 seconds | ["4", "3"] | NoteYou don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game). | Java 6 | standard input | [
"binary search",
"sortings",
"math"
] | 09f5623c3717c9d360334500b198d8e0 | The first line contains integer n (3ββ€βnββ€β105). The second line contains n space-separated integers a1,βa2,β...,βan (1ββ€βaiββ€β109) β the i-th number in the list is the number of rounds the i-th person wants to play. | 1,600 | In a single line print a single integer β the minimum number of game rounds the friends need to let the i-th person play at least ai rounds. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | b06921b08fbaa245cade8a9b84a3396c | train_001.jsonl | 1380295800 | One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other nβ-β1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want? | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
reader.readLine();
String[] nums = reader.readLine().split(" ");
long sum = 0, max = -99;
for (int i = 0; i < nums.length; i++) {
int temp = Integer.parseInt(nums[i]);
if (temp > max) {
max = temp;
}
sum += temp;
}
if (max > (long) Math.ceil(sum * 1.0 / (nums.length - 1))) {
System.out.println(max);
} else {
System.out.println((long) Math.ceil(sum * 1.0 / (nums.length - 1)));
}
reader.close();
}
} | Java | ["3\n3 2 2", "4\n2 2 2 2"] | 2 seconds | ["4", "3"] | NoteYou don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game). | Java 6 | standard input | [
"binary search",
"sortings",
"math"
] | 09f5623c3717c9d360334500b198d8e0 | The first line contains integer n (3ββ€βnββ€β105). The second line contains n space-separated integers a1,βa2,β...,βan (1ββ€βaiββ€β109) β the i-th number in the list is the number of rounds the i-th person wants to play. | 1,600 | In a single line print a single integer β the minimum number of game rounds the friends need to let the i-th person play at least ai rounds. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | e5c2423f62a646cef606dd0ed99a0702 | train_001.jsonl | 1380295800 | One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other nβ-β1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want? | 256 megabytes | import java.io.*;
import java.util.*;
public class A implements Runnable {
private void solve() throws IOException {
int n = nextInt();
long[] a = new long[n];
long sum = 0, max = 0;
for (int i = 0; i < n; i++) {
a[i] = nextLong();
max = Math.max(max, a[i]);
sum += a[i];
}
print(Math.max((sum + n - 2) / (n - 1), max));
}
public static void main(String[] args) {
new A().run();
}
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter writer;
public void run() {
try {
reader = new BufferedReader(new InputStreamReader(System.in));
writer = new PrintWriter(System.out);
solve();
writer.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(261);
}
}
void halt() {
writer.close();
System.exit(0);
}
void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
void println(Object... objects) {
print(objects);
writer.println();
}
String nextLine() throws IOException {
return reader.readLine();
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens())
tokenizer = new StringTokenizer(nextLine());
return tokenizer.nextToken();
}
int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(nextToken());
}
}
| Java | ["3\n3 2 2", "4\n2 2 2 2"] | 2 seconds | ["4", "3"] | NoteYou don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game). | Java 6 | standard input | [
"binary search",
"sortings",
"math"
] | 09f5623c3717c9d360334500b198d8e0 | The first line contains integer n (3ββ€βnββ€β105). The second line contains n space-separated integers a1,βa2,β...,βan (1ββ€βaiββ€β109) β the i-th number in the list is the number of rounds the i-th person wants to play. | 1,600 | In a single line print a single integer β the minimum number of game rounds the friends need to let the i-th person play at least ai rounds. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | e1ae38d24b1298d6b890e1c39067b10d | train_001.jsonl | 1380295800 | One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other nβ-β1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want? | 256 megabytes | import java.util.*;
import java.io.*;
public class a {
static long mod = 1000000007;
public static void main(String[] args) throws IOException {
// Scanner input = new Scanner(new File("input.txt"));
// PrintWriter out = new PrintWriter(new File("output.txt"));
input.init(System.in);
PrintWriter out = new PrintWriter((System.out));
int n = input.nextInt();
int[] data = new int[n];
for(int i = 0; i<n; i++) data[i] = input.nextInt();
long max = 0, sum = 0;
for(int i = 0; i<n; i++)
{
sum += data[i];
max = Math.max(max, data[i]);
}
out.println(Math.max((sum+n-2)/(n-1), max));
out.close();
}
static long pow(long x, long p) {
if (p == 0)
return 1;
if ((p & 1) > 0) {
return (x * pow(x, p - 1)) % mod;
}
long sqrt = pow(x, p / 2);
return (sqrt * sqrt) % mod;
}
static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static class input {
static BufferedReader reader;
static StringTokenizer tokenizer;
/** call this method to initialize reader for InputStream */
static void init(InputStream input) {
reader = new BufferedReader(new InputStreamReader(input));
tokenizer = new StringTokenizer("");
}
/** get next word */
static String next() throws IOException {
while (!tokenizer.hasMoreTokens()) {
// TODO add check for eof if necessary
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
static String nextLine() throws IOException {
return reader.readLine();
}
}
}
| Java | ["3\n3 2 2", "4\n2 2 2 2"] | 2 seconds | ["4", "3"] | NoteYou don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game). | Java 6 | standard input | [
"binary search",
"sortings",
"math"
] | 09f5623c3717c9d360334500b198d8e0 | The first line contains integer n (3ββ€βnββ€β105). The second line contains n space-separated integers a1,βa2,β...,βan (1ββ€βaiββ€β109) β the i-th number in the list is the number of rounds the i-th person wants to play. | 1,600 | In a single line print a single integer β the minimum number of game rounds the friends need to let the i-th person play at least ai rounds. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | c5a79bc2f0ddc1e12877f754603fe472 | train_001.jsonl | 1380295800 | One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other nβ-β1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want? | 256 megabytes | import java.util.Arrays;
import java.util.Scanner;
public class MafiaCF {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
solve();
}
public static void solve(){
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int[] mas = new int[n];
if(n==1){
System.out.println(0);
return;
}
for(int i = 0;i<n;i++){
mas[i] = scan.nextInt();
}
Arrays.sort(mas);
int max = mas[mas.length-1];
long t=0;
for(int i:mas){
t+=i;
}
long result = t/(mas.length-1);
if(t%(mas.length-1)>0){
result++;
}
if(result<max){
result = max;
}
System.out.println(result);
}
public static int findX(int[] mas,int left,int right){
if(right == left){
return right;
}
int middle = (right+left)/2;
int slots = (mas.length)*middle;
for(int m:mas){
slots-=m;
}
if(slots == 0){
return middle;
}else if(slots<0){
return findX(mas,middle,right);
}else{
return findX(mas, left,middle);
}
}
}
| Java | ["3\n3 2 2", "4\n2 2 2 2"] | 2 seconds | ["4", "3"] | NoteYou don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game). | Java 6 | standard input | [
"binary search",
"sortings",
"math"
] | 09f5623c3717c9d360334500b198d8e0 | The first line contains integer n (3ββ€βnββ€β105). The second line contains n space-separated integers a1,βa2,β...,βan (1ββ€βaiββ€β109) β the i-th number in the list is the number of rounds the i-th person wants to play. | 1,600 | In a single line print a single integer β the minimum number of game rounds the friends need to let the i-th person play at least ai rounds. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | 8fd995d219a14be13c2d04900c651ec8 | train_001.jsonl | 1380295800 | One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other nβ-β1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want? | 256 megabytes | import java.util.*;
import java.io.*;
public class A {
public static void main(String[] args) throws IOException {
BufferedReader rd = new BufferedReader(new InputStreamReader(System.in));
long n = Integer.parseInt(rd.readLine());
StringTokenizer st = new StringTokenizer(rd.readLine());
long s = 0, max = 0;
for(int i=0; i<n; i++){
int cur = Integer.parseInt(st.nextToken());
s+= cur;
max = Math.max(max, cur);
}
long x = s / (n-1);
while(x*(n-1)<s) x++;
System.out.println(Math.max(x, max));
}
}
| Java | ["3\n3 2 2", "4\n2 2 2 2"] | 2 seconds | ["4", "3"] | NoteYou don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game). | Java 6 | standard input | [
"binary search",
"sortings",
"math"
] | 09f5623c3717c9d360334500b198d8e0 | The first line contains integer n (3ββ€βnββ€β105). The second line contains n space-separated integers a1,βa2,β...,βan (1ββ€βaiββ€β109) β the i-th number in the list is the number of rounds the i-th person wants to play. | 1,600 | In a single line print a single integer β the minimum number of game rounds the friends need to let the i-th person play at least ai rounds. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | fa5d3509aaf25534e95ef952b63af448 | train_001.jsonl | 1380295800 | One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other nβ-β1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want? | 256 megabytes |
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import static java.lang.Math.*;
import java.util.ArrayList;
import java.util.StringTokenizer;
/**
*
* @author pttrung
*/
public class C {
public static long Mod = 1000000007;
public static double Epsilon = 1e-5;
public static void main(String[] args) {
Scanner in = new Scanner();
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
long [] data = new long[n];
long total = 0;
long max = 0;
for(int i = 0; i < n; i++){
data[i] = in.nextLong();
max = max > data[i] ? max : data[i];
total += data[i];
}
long val = (long) Math.ceil((double) total / (n - 1));
out.println(val > max ? val : max);
out.close();
}
public static double squareDistance(Point a, Point b) {
return (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y);
}
public static long pow(int a, int b) {
if (b == 0) {
return 1;
}
long val = pow(a, b / 2);
if (b % 2 == 0) {
return val * val % Mod;
} else {
return a * val * val % Mod;
}
}
public static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
static class Line {
double a, b, c;
Line(double x1, double y1, double x2, double y2) {
if (Math.abs(x1 - x2) < Epsilon && Math.abs(y1 - y2) < Epsilon) {
throw new RuntimeException("Two point are the same");
}
a = y1 - y2;
b = x2 - x1;
c = -a * x1 - b * y1;
}
Line(Point x, Point y) {
this(x.x, x.y, y.x, y.y);
}
public Line perpendicular(Point p) {
return new Line(p, new Point(p.x + a, p.y + b));
}
public Point intersect(Line l) {
double d = a * l.b - b * l.a;
if (d == 0) {
throw new RuntimeException("Two lines are parallel");
}
return new Point((l.c * b - c * l.b) / d, (l.a * c - l.c * a) / d);
}
}
static void check(Point a, Point b, ArrayList<Point> p, Point[] rec, int index) {
for (int i = 0; i < 4; i++) {
int m = (i + index) % 4;
int j = (i + 1 + index) % 4;
Point k = intersect(minus(b, a), minus(rec[m], rec[j]), minus(rec[m], a));
if (k.x >= 0 && k.x <= 1 && k.y >= 0 && k.y <= 1) {
Point val = new Point(k.x * minus(b, a).x, k.x * minus(b, a).y);
p.add(add(val, a));
// System.out.println(a + " " + b + " " + rec[i] + " " + rec[j]);
// System.out.println(add(val, a));
}
}
}
static Point intersect(Point a, Point b, Point c) {
double D = cross(a, b);
if (D != 0) {
return new Point(cross(c, b) / D, cross(a, c) / D);
}
return null;
}
static Point convert(Point a, double angle) {
double x = a.x * cos(angle) - a.y * sin(angle);
double y = a.x * sin(angle) + a.y * cos(angle);
return new Point(x, y);
}
static Point minus(Point a, Point b) {
return new Point(a.x - b.x, a.y - b.y);
}
static Point add(Point a, Point b) {
return new Point(a.x + b.x, a.y + b.y);
}
static double cross(Point a, Point b) {
return a.x * b.y - a.y * b.x;
}
static class Point {
double x, y;
Point(double x, double y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return "Point: " + x + " " + y;
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() {
// System.setOut(new PrintStream(new BufferedOutputStream(System.out), true));
br = new BufferedReader(new InputStreamReader(System.in));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
throw new RuntimeException();
}
}
return st.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
st = null;
try {
return br.readLine();
} catch (Exception e) {
throw new RuntimeException();
}
}
public boolean endLine() {
try {
String next = br.readLine();
while (next != null && next.trim().isEmpty()) {
next = br.readLine();
}
if (next == null) {
return true;
}
st = new StringTokenizer(next);
return st.hasMoreTokens();
} catch (Exception e) {
throw new RuntimeException();
}
}
}
}
| Java | ["3\n3 2 2", "4\n2 2 2 2"] | 2 seconds | ["4", "3"] | NoteYou don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game). | Java 6 | standard input | [
"binary search",
"sortings",
"math"
] | 09f5623c3717c9d360334500b198d8e0 | The first line contains integer n (3ββ€βnββ€β105). The second line contains n space-separated integers a1,βa2,β...,βan (1ββ€βaiββ€β109) β the i-th number in the list is the number of rounds the i-th person wants to play. | 1,600 | In a single line print a single integer β the minimum number of game rounds the friends need to let the i-th person play at least ai rounds. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | 62f695e1041133ae3d0612537f3118f1 | train_001.jsonl | 1380295800 | One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other nβ-β1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want? | 256 megabytes | //package round202;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class A {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni();
int[] a = na(n);
long low = 0, high = 2000000000L+100;
outer:
while(high - low > 1){
long x = (high + low) / 2;
long sum = 0;
for(int i = 0;i < n;i++){
sum += x - a[i];
if(a[i] > x){
low = x;
continue outer;
}
}
if(sum < x){
low = x;
}else{
high = x;
}
}
out.println(high);
}
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];
private int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
| Java | ["3\n3 2 2", "4\n2 2 2 2"] | 2 seconds | ["4", "3"] | NoteYou don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game). | Java 6 | standard input | [
"binary search",
"sortings",
"math"
] | 09f5623c3717c9d360334500b198d8e0 | The first line contains integer n (3ββ€βnββ€β105). The second line contains n space-separated integers a1,βa2,β...,βan (1ββ€βaiββ€β109) β the i-th number in the list is the number of rounds the i-th person wants to play. | 1,600 | In a single line print a single integer β the minimum number of game rounds the friends need to let the i-th person play at least ai rounds. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | 95ea1217bc9cb46b3eacc4aa6ce7ba19 | train_001.jsonl | 1380295800 | One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other nβ-β1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want? | 256 megabytes | import java.util.*;
import java.io.*;
public class first
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
long sum=0;
long max=0;
for(int i=0;i<n;i++)
{
long k = sc.nextLong();
if(k>max)max=k;
sum+=k;
}
long result=sum/(n-1);
if(sum%(n-1)!=0)
{
result+=1;
}
System.out.println(Math.max(result,max));
}
}
| Java | ["3\n3 2 2", "4\n2 2 2 2"] | 2 seconds | ["4", "3"] | NoteYou don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game). | Java 6 | standard input | [
"binary search",
"sortings",
"math"
] | 09f5623c3717c9d360334500b198d8e0 | The first line contains integer n (3ββ€βnββ€β105). The second line contains n space-separated integers a1,βa2,β...,βan (1ββ€βaiββ€β109) β the i-th number in the list is the number of rounds the i-th person wants to play. | 1,600 | In a single line print a single integer β the minimum number of game rounds the friends need to let the i-th person play at least ai rounds. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | 2f345f93016d88b61788e2ace1c07014 | train_001.jsonl | 1380295800 | One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other nβ-β1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want? | 256 megabytes | import java.util.*;
import java.util.Map.Entry;
import java.io.*;
import java.awt.Point;
import java.math.BigInteger;
import static java.lang.Math.*;
public class Codeforces_Solution_A implements Runnable{
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
void init() throws FileNotFoundException{
if (ONLINE_JUDGE){
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}else{
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
}
}
String readString() throws IOException{
while(!tok.hasMoreTokens()){
try{
tok = new StringTokenizer(in.readLine());
}catch (Exception e){
return null;
}
}
return tok.nextToken();
}
int readInt() throws IOException{
return Integer.parseInt(readString());
}
long readLong() throws IOException{
return Long.parseLong(readString());
}
double readDouble() throws IOException{
return Double.parseDouble(readString());
}
public static void main(String[] args){
new Thread(null, new Codeforces_Solution_A(), "", 128 * (1L << 20)).start();
}
long timeBegin, timeEnd;
void time(){
timeEnd = System.currentTimeMillis();
System.err.println("Time = " + (timeEnd - timeBegin));
}
long memoryTotal, memoryFree;
void memory(){
memoryFree = Runtime.getRuntime().freeMemory();
System.err.println("Memory = " + ((memoryTotal - memoryFree) >> 10) + " KB");
}
void debug(Object... objects){
if (DEBUG){
for (Object o: objects){
System.err.println(o.toString());
}
}
}
public void run(){
try{
timeBegin = System.currentTimeMillis();
memoryTotal = Runtime.getRuntime().freeMemory();
init();
solve();
out.close();
time();
memory();
}catch (Exception e){
e.printStackTrace(System.err);
System.exit(-1);
}
}
boolean DEBUG = false;
void solve() throws IOException{
int n = readInt();
int[] a = new int[n];
for (int i=0; i<n; i++) a[i]=readInt();
long sum= 0;
int max=-1000;
for (int i=0; i<n; i++) {
sum+=a[i];
max = Math.max(max, a[i]);
}
out.println(Math.max(sum%(n-1)==0? sum/(n-1) : sum/(n-1)+1,max));
}
}
| Java | ["3\n3 2 2", "4\n2 2 2 2"] | 2 seconds | ["4", "3"] | NoteYou don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game). | Java 6 | standard input | [
"binary search",
"sortings",
"math"
] | 09f5623c3717c9d360334500b198d8e0 | The first line contains integer n (3ββ€βnββ€β105). The second line contains n space-separated integers a1,βa2,β...,βan (1ββ€βaiββ€β109) β the i-th number in the list is the number of rounds the i-th person wants to play. | 1,600 | In a single line print a single integer β the minimum number of game rounds the friends need to let the i-th person play at least ai rounds. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | 7cd5e89f3c7c1781d11215f042319422 | train_001.jsonl | 1380295800 | One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other nβ-β1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want? | 256 megabytes | import java.util.*;
public class Mafia348A
{
public static void main(String[] args)
{
// Set up scanner
Scanner sc = new Scanner(System.in);
// System.out.println("Enter n");
long n = sc.nextLong();
long maximum = 0;
long sum = 0;
for (int i=0; i<n; i++)
{
// System.out.println("Enter next a");
long next = sc.nextLong();
sum += next;
if (next > maximum)
{
maximum = next;
}
}
// BUT MUST HAVE AS MANY AS THE BIGGEST GUY WANTS!!
if (sum % (n-1) == 0)
{
System.out.println(Math.max(sum/(n-1), maximum));
}
else
{
System.out.println(Math.max((sum/(n-1) + 1), maximum));
}
}
} | Java | ["3\n3 2 2", "4\n2 2 2 2"] | 2 seconds | ["4", "3"] | NoteYou don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game). | Java 6 | standard input | [
"binary search",
"sortings",
"math"
] | 09f5623c3717c9d360334500b198d8e0 | The first line contains integer n (3ββ€βnββ€β105). The second line contains n space-separated integers a1,βa2,β...,βan (1ββ€βaiββ€β109) β the i-th number in the list is the number of rounds the i-th person wants to play. | 1,600 | In a single line print a single integer β the minimum number of game rounds the friends need to let the i-th person play at least ai rounds. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | 0604efe25cbad1f4e9b11ca6ee9b6528 | train_001.jsonl | 1380295800 | One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other nβ-β1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want? | 256 megabytes | import java.io.*;
import java.util.*;
public class Mafia {
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String numberSpace = br.readLine();
String integers = br.readLine();
int numInts = Integer.parseInt(numberSpace);
int arrNum[] = new int[numInts];
int MAX =0;
long SumDiff =0;
int arrDiff[]=new int[numInts];
StringTokenizer st = new StringTokenizer(integers);
for (int i = 0; i < numInts; i++)
{
arrNum[i] = Integer.parseInt(st.nextToken());
if(arrNum[i]>MAX) MAX=arrNum[i];
}
for (int i = 0; i < numInts; i++)
{
arrDiff[i]=MAX-arrNum[i];
SumDiff+=arrDiff[i];
}
if(SumDiff>MAX) System.out.print(MAX);
else
System.out.print(MAX+(MAX-SumDiff+numInts-2)/(numInts-1));
}
} | Java | ["3\n3 2 2", "4\n2 2 2 2"] | 2 seconds | ["4", "3"] | NoteYou don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game). | Java 6 | standard input | [
"binary search",
"sortings",
"math"
] | 09f5623c3717c9d360334500b198d8e0 | The first line contains integer n (3ββ€βnββ€β105). The second line contains n space-separated integers a1,βa2,β...,βan (1ββ€βaiββ€β109) β the i-th number in the list is the number of rounds the i-th person wants to play. | 1,600 | In a single line print a single integer β the minimum number of game rounds the friends need to let the i-th person play at least ai rounds. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | 7d9ff31ff12ad24e88385f42aea2fbfe | train_001.jsonl | 1380295800 | One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other nβ-β1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want? | 256 megabytes | import java.util.Scanner;
public class Mafia {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
long num = 0;
long num2 = 0;
long max = 0;
for(int i=0;i<n; i++) {
num2 = sc.nextInt();
if(num2 > max) max = num2;
num += num2;
}
if((num / (n-1) + 1) < max) {
System.out.println(max);
}
else if(num % (n-1) == 0){
System.out.println(num / (n-1));
}
else {
System.out.println(num / (n-1) + 1);
}
}
}
| Java | ["3\n3 2 2", "4\n2 2 2 2"] | 2 seconds | ["4", "3"] | NoteYou don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game). | Java 6 | standard input | [
"binary search",
"sortings",
"math"
] | 09f5623c3717c9d360334500b198d8e0 | The first line contains integer n (3ββ€βnββ€β105). The second line contains n space-separated integers a1,βa2,β...,βan (1ββ€βaiββ€β109) β the i-th number in the list is the number of rounds the i-th person wants to play. | 1,600 | In a single line print a single integer β the minimum number of game rounds the friends need to let the i-th person play at least ai rounds. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | d297f4f697b3179ab372d7003e8df420 | train_001.jsonl | 1380295800 | One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other nβ-β1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want? | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class round202A {
public static boolean can(long rounds, int [] wants){
long spect = 0;
for(int i = 0 ; i < wants.length ; ++i){
if(wants[i] > rounds)
return false;
else
spect += rounds - wants[i];
}
if(spect >= rounds)
return true;
else
return false;
}
public static void main(String[] args)throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
String [] use = br.readLine().split(" ");
int [] want = new int [n];
for(int i = 0 ; i < n ; ++i)
want[i] = Integer.parseInt(use[i]);
Arrays.sort(want);
long lo = 0, hi = (long) 1e14 + 1;
long ans = Long.MAX_VALUE;
while(lo < hi){
long mid = lo + ((hi - lo) / 2);
if(can(mid, want)){
hi = mid;
ans = Math.min(ans, mid);
}else
lo = mid + 1;
}
System.out.println(ans);
}
}
| Java | ["3\n3 2 2", "4\n2 2 2 2"] | 2 seconds | ["4", "3"] | NoteYou don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game). | Java 6 | standard input | [
"binary search",
"sortings",
"math"
] | 09f5623c3717c9d360334500b198d8e0 | The first line contains integer n (3ββ€βnββ€β105). The second line contains n space-separated integers a1,βa2,β...,βan (1ββ€βaiββ€β109) β the i-th number in the list is the number of rounds the i-th person wants to play. | 1,600 | In a single line print a single integer β the minimum number of game rounds the friends need to let the i-th person play at least ai rounds. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | c583ffa99427a2538a28016ab1a51c2d | train_001.jsonl | 1576401300 | There are $$$n$$$ blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white. You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa). You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed $$$3 \cdot n$$$. If it is impossible to find such a sequence of operations, you need to report it. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
static class Scan {
private byte[] buf=new byte[1024];
private int index;
private InputStream in;
private int total;
public Scan()
{
in=System.in;
}
public int scan()throws IOException
{
if(total<0)
throw new InputMismatchException();
if(index>=total)
{
index=0;
total=in.read(buf);
if(total<=0)
return -1;
}
return buf[index++];
}
public int scanInt()throws IOException
{
int integer=0;
int n=scan();
while(isWhiteSpace(n))
n=scan();
int neg=1;
if(n=='-')
{
neg=-1;
n=scan();
}
while(!isWhiteSpace(n))
{
if(n>='0'&&n<='9')
{
integer*=10;
integer+=n-'0';
n=scan();
}
else throw new InputMismatchException();
}
return neg*integer;
}
public double scanDouble()throws IOException
{
double doub=0;
int n=scan();
while(isWhiteSpace(n))
n=scan();
int neg=1;
if(n=='-')
{
neg=-1;
n=scan();
}
while(!isWhiteSpace(n)&&n!='.')
{
if(n>='0'&&n<='9')
{
doub*=10;
doub+=n-'0';
n=scan();
}
else throw new InputMismatchException();
}
if(n=='.')
{
n=scan();
double temp=1;
while(!isWhiteSpace(n))
{
if(n>='0'&&n<='9')
{
temp/=10;
doub+=(n-'0')*temp;
n=scan();
}
else throw new InputMismatchException();
}
}
return doub*neg;
}
public String scanString()throws IOException
{
StringBuilder sb=new StringBuilder();
int n=scan();
while(isWhiteSpace(n))
n=scan();
while(!isWhiteSpace(n))
{
sb.append((char)n);
n=scan();
}
return sb.toString();
}
private boolean isWhiteSpace(int n)
{
if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1)
return true;
return false;
}
}
public static void main(String args[]) throws IOException {
Scan input=new Scan();
int n=input.scanInt();
StringBuilder str=new StringBuilder(input.scanString());
StringBuilder str1=new StringBuilder(""+str);
StringBuilder ans=new StringBuilder("");
int indx=n-1;
int cnt=0;
for(int i=0;i<n-1;i++) {
if(str.charAt(i)=='B') {
continue;
}
if(str.charAt(i)=='W' && str.charAt(i+1)=='B') {
str.setCharAt(i,'B');
str.setCharAt(i+1,'W');
cnt++;
ans.append((i+1)+" ");
}
else {
str.setCharAt(i,'B');
str.setCharAt(i+1,'B');
cnt++;
ans.append((i+1)+" ");
}
}
boolean is_pos=true;
for(int i=0;i<n;i++) {
if(str.charAt(i)!='B') {
is_pos=false;
break;
}
}
if(is_pos) {
System.out.println(cnt+"\n"+ans);
return;
}
ans=new StringBuilder("");
indx=n-1;
cnt=0;
for(int i=0;i<n-1;i++) {
if(str1.charAt(i)=='W') {
continue;
}
if(str1.charAt(i)=='B' && str1.charAt(i+1)=='W') {
str1.setCharAt(i,'W');
str1.setCharAt(i+1,'B');
cnt++;
ans.append((i+1)+" ");
}
else {
str1.setCharAt(i,'W');
str1.setCharAt(i+1,'W');
cnt++;
ans.append((i+1)+" ");
}
}
is_pos=true;
for(int i=0;i<n;i++) {
if(str1.charAt(i)!='W') {
is_pos=false;
break;
}
}
if(is_pos) {
System.out.println(cnt+"\n"+ans);
return;
}
System.out.println(-1);
}
}
| Java | ["8\nBWWWWWWB", "4\nBWBB", "5\nWWWWW", "3\nBWB"] | 2 seconds | ["3\n6 2 4", "-1", "0", "2\n2 1"] | NoteIn the first example, it is possible to make all blocks black in $$$3$$$ operations. Start with changing blocks $$$6$$$ and $$$7$$$, so the sequence is "BWWWWBBB". Then change blocks $$$2$$$ and $$$3$$$, so the sequence is "BBBWWBB". And finally, change blocks $$$4$$$ and $$$5$$$, so all blocks are black.It is impossible to make all colors equal in the second example.All blocks are already white in the third example.In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks $$$2$$$ and $$$3$$$ (so the sequence is "BBW"), and then change blocks $$$1$$$ and $$$2$$$ (so all blocks are white). | Java 11 | standard input | [
"greedy",
"math"
] | 3336662e6362693b8ac9455d4c2fe158 | The first line contains one integer $$$n$$$ ($$$2 \le n \le 200$$$) β the number of blocks. The second line contains one string $$$s$$$ consisting of $$$n$$$ characters, each character is either "W" or "B". If the $$$i$$$-th character is "W", then the $$$i$$$-th block is white. If the $$$i$$$-th character is "B", then the $$$i$$$-th block is black. | 1,300 | If it is impossible to make all the blocks having the same color, print $$$-1$$$. Otherwise, print an integer $$$k$$$ ($$$0 \le k \le 3 \cdot n$$$) β the number of operations. Then print $$$k$$$ integers $$$p_1, p_2, \dots, p_k$$$ $$$(1 \le p_j \le n - 1)$$$, where $$$p_j$$$ is the position of the left block in the pair of blocks that should be affected by the $$$j$$$-th operation. If there are multiple answers, print any of them. | standard output | |
PASSED | 5e3145234937712c2f4379e47294ade8 | train_001.jsonl | 1576401300 | There are $$$n$$$ blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white. You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa). You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed $$$3 \cdot n$$$. If it is impossible to find such a sequence of operations, you need to report it. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main{
static int mod = (int)(Math.pow(10, 9) + 7);
public static void main(String[] args) {
MyScanner sc = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out));
int n =sc.nextInt();
String s= sc.next();
List<Integer> blackMoves = new ArrayList<Integer>();
List<Integer> whiteMoves = new ArrayList<Integer>();
char[] c = s.toCharArray();
boolean validB = solve(blackMoves, c, 'B');
boolean validW = solve(whiteMoves, c, 'W');
if (validB) {
print(blackMoves);
}
else if (validW) print(whiteMoves);
else out.println(-1);
out.close();
}
static void print(List<Integer> a) {
out.println(a.size());
for (int x: a) out.print(x + " ");
out.println();
}
static boolean solve(List<Integer> m, char[] c, char t) {
int n = c.length;
char[] ch = new char[c.length];
for (int i = 0; i < n; i++) ch[i] = c[i];
for (int i = 0; i < n-1; i++) {
if (ch[i] != t && ch[i+1] != t) {
swap(ch, i);
swap(ch, i+1);
m.add(i+1);
}
}
for (int i = 0; i < n-2; i++) {
if (ch[i] != t && ch[i+1] == t && ch[i] != t) {
swap(ch, i);
swap(ch, i+2);
m.add(i+1);
m.add(i+2);
}
}
for (int i = 0; i < n-1; i++) {
if (ch[i] != t) {
swap(ch, i);
swap(ch, i+1);
m.add(i+1);
}
}
for (int i = 0; i <n ; i++) {
if (ch[i] != t) return false;
}
return true;
}
static void swap(char[] c, int i) {
if (c[i]== 'B') c[i] = 'W';
else c[i] = 'B';
}
static long pow(long a, long N) {
if (N == 0) return 1;
else if (N == 1) return a;
else {
long R = pow(a,N/2);
if (N % 2 == 0) {
return R*R;
}
else {
return R*R*a;
}
}
}
static long powMod(long a, long N) {
if (N == 0) return 1;
else if (N == 1) return a % mod;
else {
long R = powMod(a,N/2) % mod;
R *= R % mod;
if (N % 2 == 1) {
R *= a % mod;
}
return R % mod;
}
}
static void mergeSort(int[] A){ // low to hi sort, single array only
int n = A.length;
if (n < 2) return;
int[] l = new int[n/2];
int[] r = new int[n - n/2];
for (int i = 0; i < n/2; i++){
l[i] = A[i];
}
for (int j = n/2; j < n; j++){
r[j-n/2] = A[j];
}
mergeSort(l);
mergeSort(r);
merge(l, r, A);
}
static void merge(int[] l, int[] r, int[] a){
int i = 0, j = 0, k = 0;
while (i < l.length && j < r.length && k < a.length){
if (l[i] < r[j]){
a[k] = l[i];
i++;
}
else{
a[k] = r[j];
j++;
}
k++;
}
while (i < l.length){
a[k] = l[i];
i++;
k++;
}
while (j < r.length){
a[k] = r[j];
j++;
k++;
}
}
//-----------PrintWriter for faster output---------------------------------
public static PrintWriter out;
//-----------MyScanner class for faster input----------
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
//--------------------------------------------------------
}
| Java | ["8\nBWWWWWWB", "4\nBWBB", "5\nWWWWW", "3\nBWB"] | 2 seconds | ["3\n6 2 4", "-1", "0", "2\n2 1"] | NoteIn the first example, it is possible to make all blocks black in $$$3$$$ operations. Start with changing blocks $$$6$$$ and $$$7$$$, so the sequence is "BWWWWBBB". Then change blocks $$$2$$$ and $$$3$$$, so the sequence is "BBBWWBB". And finally, change blocks $$$4$$$ and $$$5$$$, so all blocks are black.It is impossible to make all colors equal in the second example.All blocks are already white in the third example.In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks $$$2$$$ and $$$3$$$ (so the sequence is "BBW"), and then change blocks $$$1$$$ and $$$2$$$ (so all blocks are white). | Java 11 | standard input | [
"greedy",
"math"
] | 3336662e6362693b8ac9455d4c2fe158 | The first line contains one integer $$$n$$$ ($$$2 \le n \le 200$$$) β the number of blocks. The second line contains one string $$$s$$$ consisting of $$$n$$$ characters, each character is either "W" or "B". If the $$$i$$$-th character is "W", then the $$$i$$$-th block is white. If the $$$i$$$-th character is "B", then the $$$i$$$-th block is black. | 1,300 | If it is impossible to make all the blocks having the same color, print $$$-1$$$. Otherwise, print an integer $$$k$$$ ($$$0 \le k \le 3 \cdot n$$$) β the number of operations. Then print $$$k$$$ integers $$$p_1, p_2, \dots, p_k$$$ $$$(1 \le p_j \le n - 1)$$$, where $$$p_j$$$ is the position of the left block in the pair of blocks that should be affected by the $$$j$$$-th operation. If there are multiple answers, print any of them. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.