src
stringlengths 95
64.6k
| complexity
stringclasses 7
values | problem
stringlengths 6
50
| from
stringclasses 1
value |
---|---|---|---|
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int m = s.nextInt();
int k = s.nextInt();
int a[] = new int [n];
for (int i = 0; i < a.length; i++) {
a[i] = s.nextInt();
}
int ans = 0;
while(k < m){
k--;
int max = -1;
int ix = -1;
for (int i = 0; i < a.length; i++) {
if(a[i] > max){
max = a[i];
ix = i;
}
}
if(ix == -1){
System.out.println("-1");
return ;
}
k += a[ix];
a[ix] = -1;
ans++;
}
System.out.println(ans);
}
}
| nlogn | 257_A. Sockets | CODEFORCES |
//package round159;
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(), m = ni(), K = ni();
int[] a = na(n);
a = radixSort(a);
if(K >= m){
out.println(0);
return;
}
int p = 1;
for(int i = n-1;i >= 0;i--){
K += a[i]-1;
if(K >= m){
out.println(p);
return;
}
p++;
}
out.println(-1);
}
public static int[] radixSort(int[] f)
{
int[] to = new int[f.length];
{
int[] b = new int[65537];
for(int i = 0;i < f.length;i++)b[1+(f[i]&0xffff)]++;
for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
for(int i = 0;i < f.length;i++)to[b[f[i]&0xffff]++] = f[i];
int[] d = f; f = to;to = d;
}
{
int[] b = new int[65537];
for(int i = 0;i < f.length;i++)b[1+(f[i]>>>16)]++;
for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
for(int i = 0;i < f.length;i++)to[b[f[i]>>>16]++] = f[i];
int[] d = f; f = to;to = d;
}
return f;
}
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)); }
}
| nlogn | 257_A. Sockets | CODEFORCES |
//package A;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
public class Solution {
public static void main(String args[]) throws IOException {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; ++i)
a[i] = in.nextInt();
Arrays.sort(a);
int res = 0, p = n - 1;
while (k < m && p >= 0) {
++res;
k += a[p] - 1;
--p;
}
if (k >= m)
System.out.println(res);
else
System.out.println("-1");
}
}
| nlogn | 257_A. Sockets | CODEFORCES |
import java.util.Arrays;
import java.util.Scanner;
public class Main2 {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int m = input.nextInt();
int k = input.nextInt();
int[] num = new int[n];
for(int i = 0 ; i < n ; i++){
num[i] = input.nextInt();
}
System.out.println(str(n,m,k,num));
}
static int str(int n,int m,int k,int[] num){
Arrays.sort(num);
int total = k;
int count = 0;
while(k < m){
if(count == num.length)return -1;
k += num[num.length-count-1]-1;
count++;
}
return count;
}
} | nlogn | 257_A. Sockets | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] in = br.readLine().split(" ");
int n=Integer.parseInt(in[0]),m=Integer.parseInt(in[1]),k=Integer.parseInt(in[2]);
StringTokenizer st = new StringTokenizer(br.readLine());
int[] caps = new int[n];
for (int i = 0; i < caps.length; i++) {
caps[i] = Integer.parseInt(st.nextToken());
}
Arrays.sort(caps);
int curSockets=k, neededLines=0;
int i = n-1;
while(curSockets<m && i>=0){
curSockets+=caps[i]-1;
neededLines++;
i--;
}
if(curSockets>=m)
System.out.println(neededLines);
else
System.out.println(-1);
}
}
| nlogn | 257_A. Sockets | CODEFORCES |
import java.io.*;
import java.util.*;
import java.lang.*;
public class Main {
public static void main(String[] args) {
Scanner cin=new Scanner(new BufferedInputStream(System.in));
int n=cin.nextInt(),
m=cin.nextInt(),
k=cin.nextInt();
int[] a=new int[51];
for (int i=0;i<n;i++) {
a[i]=-cin.nextInt();
}
Arrays.sort(a);
if (m<=k) {
System.out.println(0);
return;
}
for (int i=0;i<Math.min(k,n);i++) {
m+=a[i];
if (m-(k-1-i)<=0) {
System.out.println(i+1);
return;
}
}
for (int i=k;i<n;i++) {
m+=a[i]+1;
if (m<=0) {
System.out.println(i+1);
return;
}
}
System.out.println(-1);
cin.close();
}
} | nlogn | 257_A. Sockets | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class CFTest6 {
static BufferedReader br;
public static void main(String[] args) {
br = new BufferedReader(new InputStreamReader(System.in));
try {
int[] a1 = readIntArr();
int[] a2 = readIntArr();
br.close();
int f = a1[0];
int d = a1[1];
int s = a1[2];
Arrays.sort(a2);
if (d <= s)
System.out.println(0);
else {
int cur = d - s + 1;
int num=0;
for(int i=0;i<f;i++){
num++;
cur-=a2[f-i-1];
if(cur<=0)break;
cur++;
}
if (cur > 0)
System.out.println(-1);
else{
System.out.println(num);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
static public String readLine() throws IOException {
return br.readLine();
}
static public String readString() throws IOException {
return br.readLine();
}
static public long readlong() throws IOException {
return Long.parseLong(br.readLine());
}
static public int readInt() throws IOException {
return Integer.parseInt(br.readLine());
}
static public int[] readIntArr() throws IOException {
String[] str = br.readLine().split(" ");
int arr[] = new int[str.length];
for (int i = 0; i < arr.length; i++)
arr[i] = Integer.parseInt(str[i]);
return arr;
}
static public double[] readDoubleArr() throws IOException {
String[] str = br.readLine().split(" ");
double arr[] = new double[str.length];
for (int i = 0; i < arr.length; i++)
arr[i] = Double.parseDouble(str[i]);
return arr;
}
static public long[] readLongArr() throws IOException {
String[] str = br.readLine().split(" ");
long arr[] = new long[str.length];
for (int i = 0; i < arr.length; i++)
arr[i] = Long.parseLong(str[i]);
return arr;
}
static public double readDouble() throws IOException {
return Double.parseDouble(br.readLine());
}
}
| nlogn | 257_A. Sockets | CODEFORCES |
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Comparator;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.util.Collections;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n=in.nextInt();
int m=in.nextInt();
int k=in.nextInt();
Integer []cap=new Integer[n];
for(int i=0;i<n;i++) {
cap[i]=in.nextInt();
}
Arrays.sort(cap, Collections.reverseOrder());
int count=0;
while(k<m && count<cap.length) {
k+=(cap[count]-1);
++count;
}
if(k>=m) {
out.println(count);
} else {
out.println(-1);
}
}
}
class InputReader {
StringTokenizer st;
BufferedReader in;
public InputReader(InputStream ins)
{
in = new BufferedReader(new InputStreamReader(ins));
}
public String nextToken()
{
while(st==null || !st.hasMoreTokens())
{
try {
st=new StringTokenizer(in.readLine());
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
return st.nextToken();
}
public int nextInt()
{
return Integer.parseInt(nextToken());
}
}
| nlogn | 257_A. Sockets | CODEFORCES |
import java.util.*;
import java.io.*;
import java.math.*;
import java.util.regex.*;
public class Main {
static InputReader in;
public static void main(String[] args) throws IOException{
File file = new File("input.txt");
if(file.exists())in = new InputReader( new FileInputStream(file) );
else in = new InputReader( System.in );
int n=in.nextInt(), m=in.nextInt(), k=in.nextInt();
int a[]=new int[n];
for( int i=0; i<n; i++ ) a[i]=in.nextInt();
Arrays.sort( a );
int i=n-1, ans=0;
while( k<m && i>=0 ) {
k+=a[i]-1;
i--;
ans++;
}
if( m<=k ) System.out.println( ans );
else System.out.println("-1");
}
// IO utilities:
static void out(Object ...o){
System.out.println(Arrays.deepToString(o));
}
static class InputReader {
private BufferedInputStream inp;
private int offset;
private final int size=5120000;
private byte buff[];
InputReader( InputStream in ) throws IOException {
inp = new BufferedInputStream( in );
buff=new byte[size];
offset=0;
inp.read( buff, 0, size );
}
int nextInt() throws IOException {
int parsedInt=0;
int i=offset;
if( buff[i]==0 ) throw new IOException(); //EOF
// skip any non digits
while ( i<size && ( buff[i]<'0' || buff[i]>'9' ) ) i++;
// read digits and parse number
while( i<size && buff[i]>='0' && buff[i]<='9') {
parsedInt*=10;
parsedInt+=buff[i]-'0';
i++;
}
// check if we reached end of buffer
if ( i==size ) {
// copy leftovers to buffer start
int j = 0;
for ( ; offset<buff.length; j++, offset++ )
buff[j] = buff[offset];
// and now fill the buffer
inp.read( buff, j, size - j );
// and attempt to parse int again
offset = 0;
parsedInt = nextInt();
} else offset=i;
return parsedInt;
}
long nextLong() throws IOException{
long parsedLong=0;
int i=offset;
if( buff[i]==0 ) throw new IOException(); //EOF
// skip any non digits
while( i<size && ( buff[i]<'0' || buff[i]>'9' ) ) i++;
// read digits and parse number
while( i<size && buff[i]>='0' && buff[i]<='9') {
parsedLong*=10L;
parsedLong+=buff[i]-'0';
i++;
}
// check if we reached end of buffer
if ( i==size ) {
// copy leftovers to buffer start
int j = 0;
for ( ; offset<buff.length; j++, offset++ )
buff[j] = buff[offset];
// and now fill the buffer
inp.read( buff, j, size - j );
// and attempt to parse int again
offset = 0;
parsedLong = nextLong();
} else offset=i;
return parsedLong;
}
String next() throws IOException {
StringBuilder token=new StringBuilder();
int i=offset;
if( buff[i]==0 ) throw new IOException(); //EOF
// skip any non chars
while( i<size && ( buff[i]=='\n' || buff[i]==' ' || buff[i]=='\r' ||
buff[i]=='\t' ) ) i++;
// read chars
while( i<size && buff[i]!='\n' && buff[i]!=' ' && buff[i]!='\r' &&
buff[i]!='\t' && buff[i]!=0 ) {
token.append( (char)buff[i] );
i++;
}
// check if we reached end of buffer
if ( i==size ) {
// copy leftovers to buffer start
int j = 0;
for ( ; offset<buff.length; j++, offset++ )
buff[j] = buff[offset];
// and now fill the buffer
inp.read( buff, j, size - j );
// and attempt to parse int again
offset = 0;
return next();
} else offset=i;
return token.toString();
}
String nextLine() throws IOException {
StringBuilder line=new StringBuilder();
int i=offset;
if( buff[i]==0 ) throw new IOException(); //EOF
// read chars
while( i<size && buff[i]!='\n' && buff[i]!=0 ) {
line.append( (char)buff[i] );
i++;
}
if( i<size && buff[i]=='\n' ) i++;
// check if we reached end of buffer
if ( i==size ) {
// copy leftovers to buffer start
int j = 0;
for ( ; offset<buff.length; j++, offset++ )
buff[j] = buff[offset];
// and now fill the buffer
inp.read( buff, j, size - j );
// and attempt to parse int again
offset = 0;
return nextLine();
} else offset=i;
line.deleteCharAt( line.length()-1 );
return line.toString();
}
}
} | nlogn | 257_A. Sockets | CODEFORCES |
import java.util.Arrays;
import java.util.Scanner;
/**
*
* @author oleksiys
*/
public class A {
public static void main(String [] args){
try(Scanner s = new Scanner(System.in)){
final int n = s.nextInt();
final int m = s.nextInt();
final int k = s.nextInt();
final int [] a = new int [n];
for (int i = 0; i < a.length; ++i){
a[i] = s.nextInt();
}
Arrays.sort(a);
int i = a.length - 1;
int available = k;
int filters = 0;
while (available < m && i >= 0){
available -= 1;
available += a[i];
filters++;
i--;
}
if (available < m){
System.out.println(-1);
}else{
System.out.println(filters);
}
}
}
}
| nlogn | 257_A. Sockets | CODEFORCES |
import java.awt.Point;
import java.io.*;
import java.math.BigInteger;
import java.util.*;
import static java.lang.Math.*;
public class A {
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
void solve() throws IOException {
int n = readInt();
int m = readInt();
int k = readInt();
int[] a = readArr(n);
Arrays.sort(a);
for(int i = 0; i <= n; i++){
int curR = k;
for(int j = n-1; j >= n-i; j--){
curR += a[j];
}
curR -= i;
if(curR >= m){
out.println(i);
return;
}
}
out.println(-1);
}
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()) {
tok = new StringTokenizer(in.readLine());
}
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());
}
int[] readArr(int n) throws IOException {
int[] res = new int[n];
for (int i = 0; i < n; i++) {
res[i] = readInt();
}
return res;
}
long[] readArrL(int n) throws IOException {
long[] res = new long[n];
for (int i = 0; i < n; i++) {
res[i] = readLong();
}
return res;
}
public static void main(String[] args) {
new A().run();
}
public void run() {
try {
long t1 = System.currentTimeMillis();
init();
solve();
out.close();
long t2 = System.currentTimeMillis();
System.err.println("Time = " + (t2 - t1));
} catch (Exception e) {
e.printStackTrace(System.err);
System.exit(-1);
}
}
} | nlogn | 257_A. Sockets | CODEFORCES |
//package codeforces.contests.cf159;
import java.io.*;
import java.util.Arrays;
public class ProblemA {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
PrintWriter writer = new PrintWriter(new OutputStreamWriter(System.out));
int[] readInts() throws IOException {
String[] strings = reader.readLine().split(" ");
int[] ints = new int[strings.length];
for(int i = 0; i < ints.length; i++) {
ints[i] = Integer.parseInt(strings[i]);
}
return ints;
}
void solve() throws IOException {
int[] tt = readInts();
int n = tt[0];
int m = tt[1];
int k = tt[2];
int[] a = readInts();
Arrays.sort(a);
for(int i = 0, j = a.length - 1; i < j; i++, j--) {
int t = a[i];
a[i] = a[j];
a[j] = t;
}
int ix = 0;
while(k < m && ix < n) {
k += a[ix++] - 1;
}
if(k < m) {
writer.println(-1);
}
else {
writer.println(ix);
}
writer.flush();
}
public static void main(String[] args) throws IOException {
new ProblemA().solve();
}
}
| nlogn | 257_A. Sockets | CODEFORCES |
import static java.util.Arrays.*;
import static java.util.Collections.*;
import java.io.*;
import java.lang.reflect.*;
public class A {
final int MOD = (int)1e9 + 7;
final double eps = 1e-12;
final int INF = (int)1e9;
public A () {
int N = sc.nextInt();
int M = sc.nextInt();
int K = sc.nextInt();
Integer [] S = sc.nextInts();
sort(S, reverseOrder());
int cnt = K, res;
for (res = 0; res < N && cnt < M; ++res)
cnt += S[res] - 1;
exit(cnt < M ? -1 : res);
}
////////////////////////////////////////////////////////////////////////////////////
static MyScanner sc;
static class MyScanner {
public String next() {
newLine();
return line[index++];
}
public char nextChar() {
return next().charAt(0);
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
line = null;
return readLine();
}
public String [] nextStrings() {
line = null;
return readLine().split(" ");
}
public char [] nextChars() {
return next().toCharArray();
}
public Integer [] nextInts() {
String [] L = nextStrings();
Integer [] res = new Integer [L.length];
for (int i = 0; i < L.length; ++i)
res[i] = Integer.parseInt(L[i]);
return res;
}
public Long [] nextLongs() {
String [] L = nextStrings();
Long [] res = new Long [L.length];
for (int i = 0; i < L.length; ++i)
res[i] = Long.parseLong(L[i]);
return res;
}
public Double [] nextDoubles() {
String [] L = nextStrings();
Double [] res = new Double [L.length];
for (int i = 0; i < L.length; ++i)
res[i] = Double.parseDouble(L[i]);
return res;
}
//////////////////////////////////////////////
private boolean eol() {
return index == line.length;
}
private String readLine() {
try {
return r.readLine();
} catch (Exception e) {
throw new Error(e);
}
}
private final BufferedReader r;
MyScanner () {
this(new BufferedReader(new InputStreamReader(System.in)));
}
MyScanner(BufferedReader r) {
try {
this.r = r;
while (!r.ready())
Thread.sleep(1);
start();
} catch (Exception e) {
throw new Error(e);
}
}
private String [] line;
private int index;
private void newLine() {
if (line == null || eol()) {
line = readLine().split(" ");
index = 0;
}
}
}
static void print (Object o, Object... a) {
pw.println(build(o, a));
}
static void exit (Object o, Object... a) {
print(o, a);
exit();
}
static void exit () {
pw.close();
System.out.flush();
System.err.println("------------------");
System.err.println("Time: " + ((millis() - t) / 1000.0));
System.exit(0);
}
void NO() {
throw new Error("NO!");
}
////////////////////////////////////////////////////////////////////////////////////
static String build(Object... a) {
StringBuilder b = new StringBuilder();
for (Object o : a)
append(b, o);
return b.toString().trim();
}
static void append(StringBuilder b, Object o) {
if (o.getClass().isArray()) {
int L = Array.getLength(o);
for (int i = 0; i < L; ++i)
append(b, Array.get(o, i));
} else if (o instanceof Iterable<?>) {
for (Object p : (Iterable<?>)o)
append(b, p);
} else
b.append(" ").append(o);
}
////////////////////////////////////////////////////////////////////////////////////
public static void main(String[] args) {
sc = new MyScanner ();
new A();
exit();
}
static void start() {
t = millis();
}
static PrintWriter pw = new PrintWriter(System.out);
static long t;
static long millis() {
return System.currentTimeMillis();
}
}
| nlogn | 257_A. Sockets | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public class Round159ProblemA {
public static void main(String[] args) {
Reader r = new Reader();
int filters = r.nextInt();
int devices = r.nextInt();
int sockets = r.nextInt();
List<Integer> filtery = new ArrayList<>();
for (int i = 0; i < filters; i++) {
filtery.add(r.nextInt()-1);
}
//System.out.println(filtery);
if(devices <= sockets){
System.out.println(0);
return;
}else{
Collections.shuffle(filtery);
Collections.sort(filtery);
devices -= sockets;
int act = filtery.size()-1;
int result = 0;
while(devices > 0){
//System.out.println(devices + " " + act);
if(act < 0){
System.out.println(-1);
return;
}
devices -= filtery.get(act);
act--;
result++;
}
System.out.println(result);
}
}
static class Reader {
StreamTokenizer in;
public Reader() {
in = new StreamTokenizer(new BufferedReader(new InputStreamReader(
System.in)));
}
public int nextInt() {
try {
in.nextToken();
} catch (IOException e) {
e.printStackTrace();
}
return (int) in.nval;
}
public long nextLong() {
try {
in.nextToken();
} catch (IOException e) {
e.printStackTrace();
}
return (long) in.nval;
}
public String next() {
try {
in.nextToken();
} catch (IOException e) {
e.printStackTrace();
}
return in.sval;
}
}
}
| nlogn | 257_A. Sockets | CODEFORCES |
import java.util.*;
import java.lang.*;
public class Main
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc = new Scanner(System.in);
int numSupply = sc.nextInt();
int dev = sc.nextInt();
int socket = sc.nextInt();
int[] sockInSu = new int[numSupply];
for (int i = 0; i< sockInSu.length; i++) {
sockInSu[i] = sc.nextInt();
}
Arrays.sort(sockInSu);
if (socket >= dev) {
System.out.println(0);
}else {
int count = 0;
for (int i = sockInSu.length-1; i >= 0; i--) {
socket+= sockInSu[i]-1;
count++;
if (socket >= dev) {
System.out.println(count);
break;
}
}
if (socket < dev)
System.out.println(-1);
}
}
} | nlogn | 257_A. Sockets | CODEFORCES |
import java.io.*;
import java.util.*;
public class Main
{
public static void main(String[] args) throws IOException
{
new Main().run();
}
StreamTokenizer in;
PrintWriter out;
int nextInt() throws IOException
{
in.nextToken();
return (int)in.nval;
}
long nextLong() throws IOException
{
in.nextToken();
return (long)in.nval;
}
void run() throws IOException
{
// in = new StreamTokenizer(new BufferedReader(new FileReader("input.txt")));
// out = new PrintWriter(new FileWriter("output.txt"));
in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(new OutputStreamWriter(System.out));
solve();
out.flush();
}
void solve() throws IOException
{
int N=nextInt();
int m=nextInt();
int k=nextInt();
// System.out.println("k "+k);
ArrayList<Integer> ts= new ArrayList<Integer>();
for (int i = 0; i < N; i++) {
ts.add(nextInt());
}
int count=0,pos=0;
Collections.sort(ts);
int jj=ts.size()-1;
while(m>k){
if((jj<0)||(k==0))
{pos=1;break;}
else{
// System.out.println(k);
k+=ts.get(jj) -1;
jj--;
count++;
}
}
if(pos==0)
out.println(count);
else
out.println("-1");
}
} | nlogn | 257_A. Sockets | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class A {
static class Scanner{
BufferedReader br=null;
StringTokenizer tk=null;
public Scanner(){
br=new BufferedReader(new InputStreamReader(System.in));
}
public String next() throws IOException{
while(tk==null || !tk.hasMoreTokens())
tk=new StringTokenizer(br.readLine());
return tk.nextToken();
}
public int nextInt() throws NumberFormatException, IOException{
return Integer.valueOf(next());
}
public double nextDouble() throws NumberFormatException, IOException{
return Double.valueOf(next());
}
}
public static void main(String args[]) throws NumberFormatException, IOException{
Scanner sc=new Scanner();
int N=sc.nextInt();
int M=sc.nextInt();
int K=sc.nextInt();
int[] array=new int[N];
for(int i=0;i<N;i++)
array[i]=sc.nextInt();
Arrays.sort(array);
int val=K;
int index=N - 1;
while(index>=0 && val<M){
val--;
val+=array[index];
index--;
}
if (val<M)
System.out.println("-1");
else
System.out.println((N - 1) - index);
}
}
| nlogn | 257_A. Sockets | CODEFORCES |
import java.util.Scanner;
import java.io.OutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.io.PrintWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
int[] fs = IOUtils.readIntArray(in, n);
Arrays.sort(fs);
int ptr = fs.length - 1;
int res = 0;
while (ptr >= 0 && k < m) {
k += fs[ptr--] - 1;
res++;
}
if (k < m) out.println(-1);
else out.println(res);
}
}
class IOUtils {
public static int[] readIntArray(Scanner in, int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = in.nextInt();
return array;
}
}
| nlogn | 257_A. Sockets | CODEFORCES |
import java.util.Arrays;
import java.util.Scanner;
/**
*
* @author Natasha
*/
public class Main{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int produzeni = in.nextInt();
int devices = in.nextInt();
int stekovi = in.nextInt();
int [] filter = new int[produzeni];
for(int i = 0; i<produzeni; i++){
filter[i] = in.nextInt();
}
Arrays.sort(filter);
int filt_no = filter.length-1;
if(devices<=stekovi) {
System.out.println("0");
return;
}
int used = 0;
while(devices>stekovi){
try{
stekovi+=filter[filt_no--]-1;
}
catch(Exception e){
System.out.println("-1");
return;
}
}
System.out.println(filter.length - filt_no-1);
}
}
| nlogn | 257_A. Sockets | CODEFORCES |
import java.util.*;
public class a {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int n = input.nextInt(), m = input.nextInt(), k = input.nextInt();
int[] data = new int[n];
for(int i = 0; i<n; i++)
data[i] = input.nextInt();
Arrays.sort(data);
m -= k;
int at = n-1;
int count = 0;
while(at>=0 && m>0)
{
count++;
m++;
m -= data[at];
at--;
}
if(m>0)
System.out.println(-1);
else
System.out.println(count);
}
}
| nlogn | 257_A. Sockets | CODEFORCES |
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
public class TaskA {
/**
* @param args
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
new TaskA().solve(in, out);
in.close();
out.close();
}
private void solve(Scanner in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
int answer = 0;
int counter = k;
int[] a = new int[n];
for (int i = 0; i < n; ++i)
a[i] = in.nextInt();
Arrays.sort(a);
int[] b = Arrays.copyOf(a, a.length);
for (int i = 0; i < n; ++i)
a[i] = b[n - i - 1];
for (int i = 0; i < n; ++i) {
if (counter < m) {
counter += a[i] - 1;
++answer;
} else
break;
}
if (counter < m)
out.println("-1");
else
out.println(answer);
}
}
| nlogn | 257_A. Sockets | CODEFORCES |
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class round159A {
static BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
static StringTokenizer st = new StringTokenizer("");
static int nextInt() throws Exception {
return Integer.parseInt(next());
}
static String next() throws Exception {
while (true) {
if (st.hasMoreTokens()) {
return st.nextToken();
}
String s = br.readLine();
if (s == null) {
return null;
}
st = new StringTokenizer(s);
}
}
public static void main(String[] args) throws Exception {
int n = nextInt();
int m = nextInt();
int k = nextInt();
int[] supply = new int[n];
for (int i = 0; i < n; ++i)
supply[i] = nextInt();
if (m <= k) {
System.out.println(0);
} else {
int have = k;
Arrays.sort(supply);
for(int i = n - 1 ; i >= 0 ; --i){
have--;
have += supply[i];
if(have >= m){
System.out.println(n - i);
return;
}
}
System.out.println(-1);
}
}
}
| nlogn | 257_A. Sockets | CODEFORCES |
import java.io.*;
import java.util.*;
public class ProblemA {
InputReader in; PrintWriter out;
void solve() {
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = in.nextInt();
Arrays.sort(a);
int d = k;
int cur = n - 1;
int ans = 0;
while (d < m && cur >= 0) {
d += a[cur] - 1;
cur--;
ans++;
}
if (d >= m)
out.println(ans);
else
out.println("-1");
}
ProblemA(){
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
try {
if (oj) {
in = new InputReader(System.in);
out = new PrintWriter(System.out);
}
else {
Writer w = new FileWriter("output.txt");
in = new InputReader(new FileReader("input.txt"));
out = new PrintWriter(w);
}
} catch(Exception e) {
throw new RuntimeException(e);
}
solve();
out.close();
}
public static void main(String[] args){
new ProblemA();
}
}
class InputReader {
private BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public InputReader(FileReader fr) {
reader = new BufferedReader(fr);
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());
}
} | nlogn | 257_A. Sockets | CODEFORCES |
import java.io.*;
import java.util.*;
import java.math.*;
import java.awt.geom.*;
import static java.lang.Math.*;
public class Solution implements Runnable {
void solve() throws Exception {
int n = sc.nextInt();
int m = sc.nextInt();
int k = sc.nextInt();
int a [] = new int [n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
Arrays.sort(a);
if (k >= m) {
out.println(0);
return;
}
int sum = k;
for (int j = n - 1; j >= 0; j--) {
sum--;
sum += a[j];
if (sum >= m) {
out.println((n - j));
return;
}
}
out.println(-1);
}
BufferedReader in;
PrintWriter out;
FastScanner sc;
static Throwable uncaught;
@Override
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
sc = new FastScanner(in);
solve();
} catch (Throwable t) {
Solution.uncaught = t;
} finally {
out.close();
}
}
public static void main(String[] args) throws Throwable {
Thread t = new Thread(null, new Solution(), "", (1 << 26));
t.start();
t.join();
if (uncaught != null) {
throw uncaught;
}
}
}
class FastScanner {
BufferedReader reader;
StringTokenizer strTok;
public FastScanner(BufferedReader reader) {
this.reader = reader;
}
public String nextToken() throws IOException {
while (strTok == null || !strTok.hasMoreTokens()) {
strTok = new StringTokenizer(reader.readLine());
}
return strTok.nextToken();
}
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());
}
} | nlogn | 257_A. Sockets | CODEFORCES |
import java.io.*;
import java.util.*;
public class A {
public static void main(String[] args) throws Exception {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
int so[]= new int[n];
for(int i=0;i<n;i++) so[i]=in.nextInt();
Arrays.sort(so);
if(m<=k) {
System.out.println("0");
return;
}
int sum=0;
int socUsed=0;
int cont=0;
for(int i=n-1;i>=0;i--){
cont++;
sum+=so[i];
if(sum>=m || sum+(k-1)>=m){
System.out.println(cont);
return;
}
sum--;
}
System.out.println("-1");
}
}
| nlogn | 257_A. Sockets | CODEFORCES |
import java.io.*;
import java.util.*;
public class A {
void run() throws IOException {
int n = ni();
int m = ni();
int k = ni();
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = ni() - 1;
Arrays.sort(a);
int ans = 0;
if (m > k) {
m -= k - 1;
for (int i = n - 1; i >= 0; i--) {
ans++;
m -= a[i];
if (m < 2)
break;
}
if (m > 1)
ans = -1;
}
pw.print(ans);
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
int ni() throws IOException {
return Integer.parseInt(next());
}
String nl() throws IOException {
return br.readLine();
}
PrintWriter pw;
BufferedReader br;
StringTokenizer st;
public static void main(String[] args) throws IOException {
long timeout = System.currentTimeMillis();
boolean CF = System.getProperty("ONLINE_JUDGE") != null;
PrintWriter _pw = new PrintWriter(System.out);
BufferedReader _br = new BufferedReader(CF ? new InputStreamReader(System.in) : new FileReader(new File("in.txt")));
new A(_br, _pw).run();
if (!CF) {
_pw.println();
_pw.println(System.currentTimeMillis() - timeout);
}
_br.close();
_pw.close();
}
public A(BufferedReader _br, PrintWriter _pw) {
br = _br;
pw = _pw;
}
}
| nlogn | 257_A. Sockets | CODEFORCES |
import java.io.*;
import java.util.*;
public class A {
int n, m, k;
int[] a;
void run()throws IOException{
// BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
Scanner sc = new Scanner(new InputStreamReader(System.in));
n = sc.nextInt();
m = sc.nextInt();
k = sc.nextInt();
a = new int[n];
for(int i=0;i<n; i++) a[i] = sc.nextInt();
Arrays.sort(a);
if(m<=k){
System.out.println(0);
return;
}
int cnt = k;
int ind = a.length-1;
int ret = 0;
while(cnt<m && ind>=0){
cnt += a[ind]-1;
--ind;
ret++;
}
if(cnt>=m) System.out.println(ret);
else System.out.println(-1);
}
public static void main(String[] args)throws IOException {
new A().run();
}
}
| nlogn | 257_A. Sockets | CODEFORCES |
import java.io.*;
import java.util.*;
public class CF159DIV2 {
FastScanner in;
PrintWriter out;
void solve() {
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = in.nextInt();
Arrays.sort(a);
for (int i = 0; i < a.length / 2; i++) {
int tmp = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = tmp;
}
int need = m;
int have = k;
int ans = 0;
int it = 0;
while (have < need) {
have += a[it++] - 1;
ans++;
if (it >= n) break;
}
if (have >= need) {
out.println(ans);
} else {
out.println(-1);
}
}
void run() {
try {
in = new FastScanner(new File("object.in"));
out = new PrintWriter(new File("object.out"));
solve();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
void runIO() {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
solve();
out.close();
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f));
}
String next() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
boolean hasMoreTokens() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return false;
st = new StringTokenizer(s);
}
return true;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
public static void main(String[] args) {
new CF159DIV2().runIO();
}
} | nlogn | 257_A. Sockets | CODEFORCES |
import java.io.*;
import java.util.*;
public class Main {
public static void main (String[] args) throws IOException {
BufferedReader reader = new BufferedReader (new InputStreamReader (System.in));
String[] splitted = reader.readLine().split(" ");
int n = Integer.parseInt(splitted[0]);
int m = Integer.parseInt(splitted[1]);
int k = Integer.parseInt(splitted[2]);
PriorityQueue<Integer> queue = new PriorityQueue<Integer> (1000, Collections.reverseOrder());
splitted = reader.readLine().split(" ");
for (int ii = 0; ii < splitted.length; ii++) {
queue.add(Integer.parseInt(splitted[ii]));
}
int counter = 0;
int spot = k;
while (spot < m && !queue.isEmpty()) {
spot = spot + queue.poll() - 1;
counter++;
}
if (spot < m) {
System.out.println("-1");
} else {
System.out.println(counter);
}
}
} | nlogn | 257_A. Sockets | CODEFORCES |
import java.util.Arrays;
import java.util.StringTokenizer;
public class Solution {
//<editor-fold desc="input parse" defaultstate="collapsed">
private static StringTokenizer st;
private static java.io.BufferedReader reader;
private static java.io.BufferedWriter writer;
private static long nextLong() {
return Long.parseLong(st.nextToken());
}
private static int nextInt() {
return Integer.parseInt(st.nextToken());
}
private static double nextDouble() {
return Double.parseDouble(st.nextToken());
}
private static short nextShort() {
return Short.parseShort(st.nextToken());
}
private static byte nextByte() {
return Byte.parseByte(st.nextToken());
}
private static void initTokenizer() throws Exception {
st = new StringTokenizer(reader.readLine());
}
//</editor-fold>
public static void main(String[] args) throws Exception {
reader = new java.io.BufferedReader(new java.io.InputStreamReader(System.in), 1 << 20);
writer = new java.io.BufferedWriter(new java.io.OutputStreamWriter(System.out));
//reader = new java.io.BufferedReader(new java.io.FileReader("input.txt"), 1 << 20);
//writer = new java.io.BufferedWriter(new java.io.FileWriter("output.txt"));
initTokenizer();
int n = nextInt();
int m = nextInt();
int k = nextInt();
initTokenizer();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
Arrays.sort(a);
int total = k;
int cnt = 0;
while (total < m && cnt < a.length) {
total += a[a.length - 1 - cnt] - 1;
cnt++;
}
if (total >= m) System.out.println(cnt);
else System.out.println(-1);
}
} | nlogn | 257_A. Sockets | CODEFORCES |
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.StringTokenizer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Lokesh Khandelwal
*/
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 n=in.nextInt(),m=in.nextInt(),k=in.nextInt();
int ans=-1;
int i;
int a[]=new int[n];
for(i=0;i<n;i++)
a[i]=in.nextInt();
Arrays.sort(a);
int p=k,c=0;
for(i=n-1;i>=0;i--)
{
if(p>=m)
break;
p+=a[i]-1;
c++;
}
if(p>=m)
out.printLine(c);
else out.printLine(-1);
}
}
class InputReader
{
BufferedReader in;
StringTokenizer tokenizer=null;
public InputReader(InputStream inputStream)
{
in=new BufferedReader(new InputStreamReader(inputStream));
}
public String next()
{
try{
while (tokenizer==null||!tokenizer.hasMoreTokens())
{
tokenizer=new StringTokenizer(in.readLine());
}
return tokenizer.nextToken();
}
catch (IOException e)
{
return null;
}
}
public int nextInt()
{
return Integer.parseInt(next());
}
}
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();
}
}
| nlogn | 257_A. Sockets | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Scanner;
import java.util.StringTokenizer;
public class A {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
// BufferedReader rd = new BufferedReader(new
// InputStreamReader(System.in));
// StringTokenizer t = new StringTokenizer(rd.readLine(), " ");
int n = sc.nextInt(), m = sc.nextInt(), k = sc.nextInt();
int pl[] = new int[n];
if (k >= m) {
System.out.println(0);
System.exit(0);
}
m -= k;
for (int i = 0; i < n; i++) {
pl[i] = sc.nextInt() - 1;
}
Arrays.sort(pl);
int out = 0;
for (int i = n - 1; i >= 0; i--) {
m -= pl[i];
out++;
if (m <= 0)
break;
}
if (m <= 0)
System.out.println(out);
else
System.out.println(-1);
}
}
| nlogn | 257_A. Sockets | CODEFORCES |
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Arrays;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = in.nextInt();
Arrays.sort(a);
if (k >= m) {
out.println(0);
return;
}
for (int i = 1; i <= n; i++) {
int sockets = k - 1;
for (int j = 0; j < i; j++)
sockets += a[n - j - 1];
sockets -= i - 1;
if (sockets >= m) {
out.println(i);
return;
}
}
out.println(-1);
}
}
class InputReader {
private BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public int nextInt() {
return Integer.parseInt(next());
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
}
| nlogn | 257_A. Sockets | CODEFORCES |
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class CodeforcesRound159 {
/**
* @param args
*/
public static void main(String[] args)
{
Scanner kde = new Scanner(System.in);
int n =kde.nextInt(); //���������� ������� ��������
int m =kde.nextInt(); //���������� ���������
int k =kde.nextInt(); //���������� �������
ArrayList<Integer> count = new ArrayList<Integer>();
for (int i=0; i<n; i++ )
{
count.add(kde.nextInt()) ;
}
Collections.sort(count);
Collections.reverse(count);
if(m<=k)
{
System.out.println("0");
return;
}
m=m-k+1;
int res=0;
for(int i=0; i<n; i++ )
{
if(i!=0)
{
res+=count.get(i)-1;
}
else
{
res+=count.get(i);
}
if(res>=m)
{
System.out.println(i+1);
return;
}
}
System.out.println("-1");
}
}
| nlogn | 257_A. Sockets | CODEFORCES |
import java.util.Arrays;
import java.util.Scanner;
public class A {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
int[] A = new int[n];
for (int i = 0; i < n; i++)
A[i] = in.nextInt();
Arrays.sort(A);
int cnt = 0;
for (int i = n - 1; i >= 0; i--) {
if (k >= m) {
System.out.println(cnt);
return;
}
cnt++;
k += A[i] - 1;
}
if (k >= m)
System.out.println(cnt);
else
System.out.println(-1);
}
}
| nlogn | 257_A. Sockets | CODEFORCES |
import java.io.*;
import java.util.*;
public class a{
static int a;
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) throws IOException{
int n = sc.nextInt();
int p = n;
int m = sc.nextInt();
int k = sc.nextInt();
int a[] = new int[n];
for (int i = 0; i < n; i++)
{
a[i] = sc.nextInt() - 1;
}
Arrays.sort(a);
int j =0;
for(int i=0; i<n; i++){
if(m > k){
k = k + a[n-i-1];
j++;
}
}
if(m > k)
System.out.println(-1);
else
System.out.println(j);
}
} | nlogn | 257_A. Sockets | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Scanner;
import java.util.StringTokenizer;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author AndresFelipe
*/
public class A {
public static void main(String Args[]) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
st = new StringTokenizer(br.readLine());
int n=Integer.valueOf(st.nextToken());
int m=Integer.valueOf(st.nextToken());
int k=Integer.valueOf(st.nextToken());
st = new StringTokenizer(br.readLine());
int sock[] = new int[n];
for (int i=0;i<n;i++){
sock[i]= Integer.valueOf(st.nextToken());
}
Arrays.sort(sock);
m-=k;
int count=0;
int index=sock.length-1;
while(m>0){
if(index<0){
System.out.println("-1");
return;
}
m++;
m-=sock[index];
index--;
count++;
}
System.out.println(count);
}
}
| nlogn | 257_A. Sockets | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.Writer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author BSRK Aditya ([email protected])
*/
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 n = in.readInt();
int m = in.readInt();
int k = in.readInt();
int [] filters = new int[n];
for(int i = 0; i < n; ++i) filters[i] = in.readInt();
Arrays.sort(filters);
int nS = 0, tN = k;
while(tN < m && nS < n) {
tN += filters[n-1-nS] - 1;
nS++;
}
if(tN >= m) out.printLine(nS);
else out.printLine(-1);
}
}
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(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();
}
}
| nlogn | 257_A. Sockets | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author kessido
*/
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);
TaskG solver = new TaskG();
solver.solve(1, in, out);
out.close();
}
static class TaskG {
static int[][] g;
static int n;
static int[] a;
static int[][] edges;
static long[] dp;
static long[] dpPathToRootWithDetours;
static int time = 0;
static int[] appearance;
static int[] firstAppearance;
static int[] depth;
public static void dfs(int i, int parE) {
firstAppearance[i] = time;
appearance[time++] = i;
dp[i] = a[i];
for (int eIndex : g[i]) {
if (eIndex == parE) continue;
int child = i ^ edges[eIndex][0] ^ edges[eIndex][1];
dfs(child, eIndex);
appearance[time++] = i;
dp[i] += Math.max(dp[child] - edges[eIndex][2] * 2, 0);
}
}
public static void dfs2(int i, int parE) {
if (i == 0) {
dpPathToRootWithDetours[i] = dp[i];
} else {
int par = i ^ edges[parE][0] ^ edges[parE][1];
depth[i] = depth[par] + 1;
dpPathToRootWithDetours[i] = dpPathToRootWithDetours[par] - Math.max(0, dp[i] - edges[parE][2] * 2);
dpPathToRootWithDetours[i] -= edges[parE][2];
dpPathToRootWithDetours[i] += dp[i];
long myPathWeight = Math.max(dp[i] - edges[parE][2] * 2, 0);
long change = dp[par] - myPathWeight - edges[parE][2] * 2;
change = Math.max(change, 0);
dp[i] += change;
}
for (int eIndex : g[i]) {
if (eIndex == parE) continue;
dfs2(i ^ edges[eIndex][0] ^ edges[eIndex][1], eIndex);
}
}
public void solve(int testNumber, InputReader in, PrintWriter out) {
n = in.NextInt();
int q = in.NextInt();
a = in.NextIntArray(n);
edges = new int[n - 1][3];
{
long[] count = new long[n];
for (int i = 0; i < n - 1; i++) {
int u = in.NextInt() - 1;
int v = in.NextInt() - 1;
int w = in.NextInt();
edges[i][0] = u;
edges[i][1] = v;
edges[i][2] = w;
count[u]++;
count[v]++;
}
g = new int[n][];
for (int i = 0; i < n; i++) {
g[i] = new int[(int) count[i]];
}
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < 2; j++) {
g[edges[i][j]][(int) --count[edges[i][j]]] = i;
}
}
}
dp = new long[n];
dpPathToRootWithDetours = new long[n];
depth = new int[n];
firstAppearance = new int[n];
appearance = new int[(n - 1) * 2 + 1];
dfs(0, -1);
dfs2(0, -1);
GraphLowestCommonAncestor.LCA lca = GraphLowestCommonAncestor.createLCA(appearance, firstAppearance, depth);
firstAppearance = null;
depth = null;
appearance = null;
edges = null;
g = null;
for (int i = 0; i < q; i++) {
int u = in.NextInt() - 1;
int v = in.NextInt() - 1;
int lcaI = lca.getLCA(u, v);
long res = dpPathToRootWithDetours[u] + dpPathToRootWithDetours[v] - 2 * dpPathToRootWithDetours[lcaI] + dp[lcaI];
out.println(res);
}
}
}
static class MinRangeSparseTable implements ISearchInRange {
private final int[][] sparseTables;
private final long[] array;
private final boolean reverseOrdered;
public MinRangeSparseTable(long[] array, boolean reverseOrdered) {
this.reverseOrdered = reverseOrdered;
this.array = array;
int LCALength = IntegerExtension.getNumberOfBits(array.length);
sparseTables = new int[LCALength][];
sparseTables[0] = new int[array.length];
for (int i = 0; i < array.length; i++) {
sparseTables[0][i] = i;
}
for (int i = 1; i < LCALength; i++) {
int size = 1 << i;
int jumpSize = 1 << (i - 1);
sparseTables[i] = new int[sparseTables[0].length - size + 1];
for (int j = 0; j < sparseTables[i].length; j++) {
sparseTables[i][j] = min(sparseTables[i - 1][j], sparseTables[i - 1][j + jumpSize]);
}
}
}
private int min(int a, int b) {
return ((array[a] < array[b]) ^ reverseOrdered) ? a : b;
}
public Pair<Long, Long> queryIndexValueInRange(long l, long r) {
int size = (int) (r - l + 1);
int LCAIndex = IntegerExtension.getNumberOfBits(size) - 1;
int sizeNeeded = 1 << LCAIndex;
int res = min(sparseTables[LCAIndex][(int) l], sparseTables[LCAIndex][(int) (r - sizeNeeded + 1)]);
return new Pair<>((long) res, array[res]);
}
public MinRangeSparseTable(long[] array) {
this(array, false);
}
}
static class GraphLowestCommonAncestor {
public static GraphLowestCommonAncestor.LCA createLCA(int[] appearances, final int[] firstAppearance, final int[] depth) {
return new GraphLowestCommonAncestor.LCA_MinRangeSparseTable(appearances, firstAppearance, depth);
}
public interface LCA {
int getLCA(int a, int b);
}
private static class LCA_MinRangeSparseTable implements GraphLowestCommonAncestor.LCA {
private final MinRangeSparseTable minRangeSparseTable;
private final int[] firstAppearance;
private final int[] indexToNode;
public LCA_MinRangeSparseTable(int[] appearances, final int[] firstAppearance, final int[] depth) {
this.firstAppearance = firstAppearance;
this.indexToNode = appearances;
long[] depthOrder = new long[appearances.length];
for (int i = 0; i < depthOrder.length; i++) {
depthOrder[i] = depth[appearances[i]];
}
minRangeSparseTable = new MinRangeSparseTable(depthOrder);
}
public int getLCA(int a, int b) {
a = firstAppearance[a];
b = firstAppearance[b];
int l = Math.min(a, b), r = Math.max(a, b);
return indexToNode[(int) (long) minRangeSparseTable.queryIndexValueInRange(l, r).first];
}
}
}
static class InputReader {
BufferedReader reader;
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(), " \t\n\r\f,");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int NextInt() {
return Integer.parseInt(next());
}
public int[] NextIntArray(int n) {
return NextIntArray(n, 0);
}
public int[] NextIntArray(int n, int offset) {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = NextInt() + offset;
}
return a;
}
}
static interface ISearchInRange {
}
static class Pair<T1, T2> {
public T1 first;
public T2 second;
public Pair(T1 f, T2 s) {
first = f;
second = s;
}
}
static class IntegerExtension {
public static int getNumberOfBits(long i) {
return 64 - Long.numberOfLeadingZeros(i);
}
}
}
| nlogn | 1000_G. Two-Paths | CODEFORCES |
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
long totalBlocks = 0;
long a[] = new long[n];
for(int i = 0; i < n; ++i) {
a[i] = sc.nextLong();
totalBlocks += a[i];
}
Arrays.sort(a);
long selected = 0;
for(int i = 0; i < n; ++i) {
if(a[i] > selected)
selected++;
}
long leftCols = a[n - 1] - selected;
long remBlocks = totalBlocks - leftCols - n;
System.out.print(remBlocks);
}
} | nlogn | 1061_B. Views Matter | CODEFORCES |
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
long totalBlocks = 0;
long a[] = new long[n];
for(int i = 0; i < n; ++i) {
a[i] = sc.nextLong();
totalBlocks += a[i];
}
Arrays.sort(a);
long selected = 0;
for(int i = 0; i < n; ++i) {
if(a[i] > selected)
selected++;
}
long leftCols = a[n - 1] - selected;
long remBlocks = totalBlocks - leftCols - n;
System.out.print(remBlocks);
}
} | nlogn | 1061_B. Views Matter | CODEFORCES |
import java.util.*;
import java.io.*;
public class A
{
public static void main(String ar[]) throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s1[]=br.readLine().split(" ");
int n=Integer.parseInt(s1[0]);
int m=Integer.parseInt(s1[1]);
int a[]=new int[n];
String s2[]=br.readLine().split(" ");
long S=0;
for(int i=0;i<n;i++)
{ a[i]=Integer.parseInt(s2[i]); S+=(long)a[i]; }
Arrays.sort(a);
m=a[n-1];
int last=1;
int t=1;
for(int i=1;i<n-1;i++)
{
if(a[i]==last)
t++;
else
{
t++;
last=last+1;
}
}
if(last<m)
{ t+=m-last; }
else
t++;
System.out.println(S-t);
}
} | nlogn | 1061_B. Views Matter | CODEFORCES |
import java.util.*;
public class test{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
int n=s.nextInt();
int m=s.nextInt();
int arr[]=new int[n];
int max = Integer.MIN_VALUE;
long sum = 0;
for(int i=0;i<n;i++)
{
arr[i] = s.nextInt();
sum = sum + arr[i];
max = Math.max(max,arr[i]);
}
Arrays.sort(arr);
int i = 0;
int count = 0;
int d = 0;
for(i=0; i<n; i++)
{
if(arr[i] > d)
{
count++;
d++;
}
else if(arr[i] == d && arr[i] > 0)
{
count++;
}
}
//System.out.println(count + " " + max);
if(max - d > 0)
{
count = count + max - d;
}
System.out.println(sum - count);}} | nlogn | 1061_B. Views Matter | CODEFORCES |
import java.util.*;
import java.io.*;
import java.awt.Point;
import java.math.BigInteger;
public class stacks {
public static void main(String[] args) throws Exception {
FastIO sc = new FastIO(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = sc.nextInt();
int m = sc.nextInt();
long remove = 0;
int[] heights = new int[n+1];
for(int i = 0; i < n; i++) {
heights[i] = sc.nextInt();
remove += heights[i];
}
Arrays.sort(heights);
//System.out.println(Arrays.toString(heights));
long keep = 0;
for(int i = n; i> 0; i--) {
if(heights[i-1] >= heights[i]) {
heights[i-1] = heights[i]-1;
}
keep += heights[i] - heights[i-1];
}
//System.out.println(Arrays.toString(heights));
pw.println(remove - keep);
pw.close();
}
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 Exception {
dis = new FileInputStream(fileName);
}
public FastIO(InputStream is) throws Exception {
dis = is;
}
int nextInt() throws Exception {
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 Exception {
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 Exception {
if (pointer == buffer.length) {
dis.read(buffer, 0, buffer.length);
pointer = 0;
}
return buffer[pointer++];
}
String next() throws Exception {
StringBuffer ret = new StringBuffer();
byte b;
do {
b = nextByte();
} while (b <= ' ');
while (b > ' ') {
ret.appendCodePoint(b);
b = nextByte();
}
return ret.toString();
}
}
}
| nlogn | 1061_B. Views Matter | CODEFORCES |
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] wide = new int[n], sta = new int[n];
HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
for (int i = 0; i < n; i++) {
wide[i] = sc.nextInt();
hm.put(wide[i], i + 1);
}
Util.sort(wide);
sc.nextLine();
String s = sc.nextLine();
int tp = 0, pos = 0;
StringBuilder out = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
int t;
if (s.charAt(i) == '0') {
t = wide[pos++];
sta[tp++] = t;
} else t = sta[--tp];
out.append(hm.get(t) + " ");
}
System.out.println(out.toString());
sc.close();
}
public static class Util {
public static <T extends Comparable<T> > void merge_sort(T[] a) {
Object[] aux = new Object[a.length];
merge_sort0(a, aux, 0, a.length);
}
public static <T extends Comparable<T> > void merge_sort(T[] a, int l, int r) {
Object[] aux = new Object[a.length];
merge_sort0(a, aux, l, r);
}
@SuppressWarnings("unchecked")
private static <T extends Comparable<T> > void merge_sort0(T[] a, Object[] temp, int l, int r) {
if (l + 1 == r) return;
int mid = (l + r) >> 1;
merge_sort0(a, temp, l, mid);
merge_sort0(a, temp, mid, r);
int x = l, y = mid, c = l;
while (x < mid || y < r) {
if (y == r || (x < mid && a[x].compareTo(a[y]) <= 0)) temp[c++] = a[x++];
else temp[c++] = a[y++];
}
for (int i = l; i < r; i++) a[i] = (T)temp[i];
}
static final Random RAN = new Random();
public static <T extends Comparable<T> > void quick_sort(T[] a) {
quick_sort0(a, 0, a.length);
}
public static <T extends Comparable<T> > void quick_sort(T[] a, int l, int r) {
quick_sort0(a, l, r);
}
private static <T extends Comparable<T> > void quick_sort0(T[] a, int l, int r) {
if (l + 1 >= r) return;
int p = l + RAN.nextInt(r - l);
T t = a[p]; a[p] = a[l]; a[l] = t;
int x = l, y = r - 1;
while (x < y) {
while (x < y && a[y].compareTo(t) > 0) --y;
while (x < y && a[x].compareTo(t) < 0) ++x;
if (x < y) {
T b = a[x]; a[x] = a[y]; a[y] = b;
++x; --y;
}
}
quick_sort0(a, l, y + 1);
quick_sort0(a, x, r);
}
static final int BOUND = 8;
public static void bucket_sort(int[] a) {
bucket_sort(a, 0, a.length);
}
public static void bucket_sort(int[] a, int l, int r) {
int[] cnt = new int[1 << BOUND], b = new int[r - l + 1];
int y = 0;
for (int i = l; i < r; i++) ++cnt[a[i] & (1 << BOUND) - 1];
while (y < Integer.SIZE) {
for (int i = 1; i < 1 << BOUND; i++) cnt[i] += cnt[i - 1];
for (int i = r - 1; i >= l; i--) b[--cnt[a[i] >> y & (1 << BOUND) - 1]] = a[i];
y += BOUND;
Arrays.fill(cnt, 0);
for (int i = l; i < r; i++) {
a[i] = b[i - l];
++cnt[a[i] >> y & (1 << BOUND) - 1];
}
}
}
public static void bucket_sort(long[] a) {
bucket_sort(a, 0, a.length);
}
public static void bucket_sort(long[] a, int l, int r) {
int[] cnt = new int[1 << BOUND];
long[] b = new long[r - l + 1];
int y = 0;
while (y < Long.SIZE) {
Arrays.fill(cnt, 0);
for (int i = l; i < r; i++) ++cnt[(int) (a[i] >> y & (1 << BOUND) - 1)];
for (int i = 1; i < 1 << BOUND; i++) cnt[i] += cnt[i - 1];
for (int i = r - 1; i >= l; i--) b[--cnt[(int) (a[i] >> y & (1 << BOUND) - 1)]] = a[i];
for (int i = l; i < r; i++) a[i] = b[i - l];
y += BOUND;
}
}
public static void sort(int[] a) {
if (a.length <= 1 << BOUND) {
Integer[] b = new Integer[a.length];
for (int i = 0; i < a.length; i++) b[i] = a[i];
quick_sort(b);
for (int i = 0; i < a.length; i++) a[i] = b[i];
} else bucket_sort(a);
}
public static void sort(long[] a) {
if (a.length <= 1 << BOUND) {
Long[] b = new Long[a.length];
for (int i = 0; i < a.length; i++) b[i] = a[i];
quick_sort(b);
for (int i = 0; i < a.length; i++) a[i] = b[i];
} else bucket_sort(a);
}
public static <T extends Comparable<T> > void sort(T[] a) {
quick_sort(a);
}
public static void shuffle(int[] a) {
Random ran = new Random();
for (int i = 0; i < a.length; i++) {
int p = ran.nextInt(i + 1);
int q = a[p]; a[p] = a[i]; a[i] = q;
}
}
public static void shuffle(long[] a) {
Random ran = new Random();
for (int i = 0; i < a.length; i++) {
int p = ran.nextInt(i + 1);
long q = a[p]; a[p] = a[i]; a[i] = q;
}
}
public static <T> void shuffle(T[] a) {
Random ran = new Random();
for (int i = 0; i < a.length; i++) {
int p = ran.nextInt(i + 1);
T q = a[p]; a[p] = a[i]; a[i] = q;
}
}
}
} | nlogn | 982_B. Bus of Characters | CODEFORCES |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashSet;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;
import java.util.StringJoiner;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Test {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String[] line = reader.readLine().split(" ");
int w = Integer.valueOf(line[0]);
int h = Integer.valueOf(line[1]);
int n = Integer.valueOf(line[2]);
Request[] requests = new Request[n];
for (int i = 0; i < n; i++) {
line = reader.readLine().split(" ");
requests[i] = new Request(line[0], Integer.valueOf(line[1]));
}
for (long e : solve(h, w, requests))
System.out.println(e);
// int w = 200000, h = 200000, n = 400000;
// Request[] requests = generate(w, h, n);
//
// long start = System.currentTimeMillis();
// solve(h, w, requests);
// long end = System.currentTimeMillis();
//
// System.out.println("Time: " + (end - start) + " ms");
}
private static Request[] generate(int w, int h, int n) {
Request[] requests = new Request[n];
Random rnd = new Random();
for (int i = 0; i < n; i++) {
requests[i] = rnd.nextBoolean() ? new Request("V", rnd.nextInt(w)) : new Request("H", rnd.nextInt(h));
}
return requests;
}
private static long[] solve(int h, int w, Request[] requests) {
TreeSet<Integer> hTree = new TreeSet<>();
TreeSet<Integer> wTree = new TreeSet<>();
Queue<CoordinateWithSize> hHeap = new PriorityQueue<>();
Queue<CoordinateWithSize> wHeap = new PriorityQueue<>();
hTree.add(0);
hTree.add(h);
wTree.add(0);
wTree.add(w);
hHeap.add(new CoordinateWithSize(0, h));
wHeap.add(new CoordinateWithSize(0, w));
long[] res = new long[requests.length];
for (int i = 0; i < requests.length; i++) {
Request request = requests[i];
switch (request.type) {
case "H": {
if (!hTree.contains(request.coordinate)) {
int higher = hTree.higher(request.coordinate);
int lower = hTree.lower(request.coordinate);
hHeap.add(new CoordinateWithSize(lower, request.coordinate - lower));
hHeap.add(new CoordinateWithSize(request.coordinate, higher - request.coordinate));
hTree.add(request.coordinate);
}
break;
}
case "V": {
if (!wTree.contains(request.coordinate)) {
int higher = wTree.higher(request.coordinate);
int lower = wTree.lower(request.coordinate);
wHeap.add(new CoordinateWithSize(lower, request.coordinate - lower));
wHeap.add(new CoordinateWithSize(request.coordinate, higher - request.coordinate));
wTree.add(request.coordinate);
}
break;
}
default:
throw new IllegalStateException("Unknown type [type=" + request.type + "]");
}
while (true) {
CoordinateWithSize c = hHeap.peek();
if (hTree.higher(c.coordinate) - c.coordinate == c.size)
break;
hHeap.remove();
}
while (true) {
CoordinateWithSize c = wHeap.peek();
if (wTree.higher(c.coordinate) - c.coordinate == c.size)
break;
wHeap.remove();
}
res[i] = 1L * hHeap.peek().size * wHeap.peek().size;
}
return res;
}
private static class CoordinateWithSize implements Comparable<CoordinateWithSize> {
private final int coordinate;
private final int size;
public CoordinateWithSize(int coordinate, int size) {
this.coordinate = coordinate;
this.size = size;
}
@Override public int compareTo(CoordinateWithSize o) {
return Integer.compare(o.size, size);
}
}
private static class Request {
private final String type;
private final int coordinate;
public Request(String type, int coordinate) {
this.type = type;
this.coordinate = coordinate;
}
}
}
| nlogn | 527_C. Glass Carving | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.TreeMap;
import java.util.Map;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Ribhav
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
CGlassCarving solver = new CGlassCarving();
solver.solve(1, in, out);
out.close();
}
static class CGlassCarving {
public void solve(int testNumber, FastReader s, PrintWriter out) {
TreeMap<Long, Integer> mapH = new TreeMap<>();
TreeMap<Long, Integer> mapV = new TreeMap<>();
TreeMap<Long, Integer> hDiff = new TreeMap<>();
TreeMap<Long, Integer> vDiff = new TreeMap<>();
long width = s.nextInt();
long height = s.nextInt();
mapH.put(0L, 1);
mapV.put(0L, 1);
mapV.put(width, 1);
mapH.put(height, 1);
vDiff.put(width, 1);
hDiff.put(height, 1);
long maxV = height;
long maxH = width;
int n = s.nextInt();
for (int i = 0; i < n; i++) {
char ch = s.nextCharacter();
long cut = s.nextInt();
if (ch == 'H') {
Long next = mapH.higherKey(cut);
Long prev = mapH.lowerKey(cut);
Long diff = next - prev;
int freq = hDiff.get(diff);
if (freq == 1) {
hDiff.remove(diff);
} else {
hDiff.put(diff, freq - 1);
}
hDiff.put(next - cut, hDiff.getOrDefault(next - cut, 0) + 1);
hDiff.put(cut - prev, hDiff.getOrDefault(cut - prev, 0) + 1);
mapH.put(cut, mapH.getOrDefault(cut, 0) + 1);
} else {
Long next = mapV.higherKey(cut);
Long prev = mapV.lowerKey(cut);
Long diff = next - prev;
int freq = vDiff.get(diff);
if (freq == 1) {
vDiff.remove(diff);
} else {
vDiff.put(diff, freq - 1);
}
vDiff.put(next - cut, vDiff.getOrDefault(next - cut, 0) + 1);
vDiff.put(cut - prev, vDiff.getOrDefault(cut - prev, 0) + 1);
mapV.put(cut, mapV.getOrDefault(cut, 0) + 1);
}
out.println(hDiff.lastKey() * vDiff.lastKey());
}
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private FastReader.SpaceCharFilter filter;
public FastReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public char nextCharacter() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
return (char) c;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| nlogn | 527_C. Glass Carving | CODEFORCES |
import sun.reflect.generics.tree.Tree;
import java.io.*;
import java.math.BigInteger;
import java.net.Inet4Address;
import java.util.*;
public class l {
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////// /////////
//////// /////////
//////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOOOOO SSSSSSS EEEEEEEEEEEEE /////////
//////// HHHH HHHH EEEEEEEEEEEEE MMMMMM MMMMMM OOO OOO SSSS SSS EEEEEEEEEEEEE /////////
//////// HHHH HHHH EEEEE MMMM MMM MMM MMMM OOO OOO SSSS SSS EEEEE /////////
//////// HHHH HHHH EEEEE MMMM MMMMMM MMMM OOO OOO SSSS EEEEE /////////
//////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSSSSSS EEEEE /////////
//////// HHHHHHHHHHHHHHHH EEEEEEEEEEE MMMM MMMM OOO OOO SSSSSS EEEEEEEEEEE /////////
//////// HHHHHHHHHHHHHHHH EEEEEEEEEEE MMMM MMMM OOO OOO SSSSSSS EEEEEEEEEEE /////////
//////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSSS EEEEE /////////
//////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSS SSSS EEEEE /////////
//////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOO OOO SSS SSSS EEEEEEEEEEEEE /////////
//////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOOOOO SSSSSSS EEEEEEEEEEEEE /////////
//////// /////////
//////// /////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static long mod = (int) (1e9 + 7);
static int n;
static StringBuilder sol;
static class pair implements Comparable<pair> {
int L,R;
public pair( int x,int y) {
L=x;R=y;
}
public int compareTo(pair o) {
if (L!=o.L)return L-o.L;
return o.R-R;
}
public String toString(){
return L+" "+R;
}
}
static boolean is;
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
//FileWriter f = new FileWriter("C:\\Users\\Ibrahim\\out.txt");
PrintWriter pw = new PrintWriter(System.out);
int m = sc.nextInt();
int n = sc.nextInt();
int q = sc.nextInt();
TreeSet<Integer>length= new TreeSet<>();
length.add(0);
length.add(n);
TreeSet<Integer>width= new TreeSet<>();
width.add(0);
width.add(m);
TreeMap<Integer,Integer>len= new TreeMap<>();
len.put(n,1);
TreeMap<Integer,Integer>wid= new TreeMap<>();
wid.put(m,1);
while (q-->0){
String t= sc.next();
if (t.equals("H")) {
int x = sc.nextInt();
int k1 = length.ceiling(x);
int k2 = length.floor(x);
if (x != k1) {
int s = k1 - k2;
int con = len.get(s);
if (con == 1) len.remove(s);
else len.put(s, con - 1);
len.put((k1 - x), len.getOrDefault((k1 - x), 0) + 1);
len.put((x - k2), len.getOrDefault((x - k2), 0) + 1);
length.add(x);
}
}
else {
int x = sc.nextInt();
int k1 = width.ceiling(x);
int k2 = width.floor(x);
if (x != k1) {
int s = k1 - k2;
//System.out.println(s+" "+k1+" "+k2);
int con = wid.get(s);
if (con == 1) wid.remove(s);
else wid.put(s, con - 1);
wid.put((k1 - x), wid.getOrDefault((k1 - x), 0) + 1);
wid.put((x - k2), wid.getOrDefault((x - k2), 0) + 1);
width.add(x);
}
}
pw.println(1l*len.lastKey()*wid.lastKey());
}
pw.flush();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() 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();
}
}
} | nlogn | 527_C. Glass Carving | CODEFORCES |
import java.util.*;
import java.util.Map.Entry;
import java.io.*;
import java.lang.reflect.Array;
import java.math.*;
import java.security.SecureRandom;
public class WCS {
public static class Vector implements Comparable <Vector> {
long x, y;
int position;
Vector first, second;
boolean toReverse;
public Vector(long xx, long yy, int p) {
x = xx;
y = yy;
position = p;
first = null;
second = null;
toReverse = false;
}
public Vector negate() {
Vector vv = new Vector(-x, -y, position);
vv.first = first;
vv.second = second;
vv.toReverse = !toReverse;
return vv;
}
public Vector add(Vector v) {
Vector sum = new Vector(this.x + v.x, this.y + v.y, position);
sum.first = this;
sum.second = v;
return sum;
}
public Vector subtract(Vector v) {
return this.add(v.negate());
}
public double euclideanNorm() {
return Math.sqrt(x * x + y * y);
}
@Override
public int compareTo(Vector v) {
double thisa = Math.atan2(this.y, this.x);
double va = Math.atan2(v.y, v.x);
if(thisa < 0)
thisa += 2 * Math.PI;
if(va < 0)
va += 2 * Math.PI;
if(thisa < va)
return -1;
if(thisa > va)
return 1;
return Integer.compare(this.position, v.position);
}
@Override
public String toString() {
return x + " " + y;
}
}
public static void dfs(Vector curr, int[] ans) {
if(curr.first == null) {
ans[curr.position] = curr.toReverse ? -1 : 1;
return;
}
curr.first.toReverse ^= curr.toReverse;
curr.second.toReverse ^= curr.toReverse;
dfs(curr.first, ans);
dfs(curr.second, ans);
}
public static boolean ok(Vector v1, Vector v2) {
return v1.add(v2).euclideanNorm() <= Math.max(v1.euclideanNorm(), v2.euclideanNorm());
}
public static void stop(long k) {
long time = System.currentTimeMillis();
while(System.currentTimeMillis() - time < k);
}
public static void main(String[] args) throws IOException {
int n = in.nextInt();
TreeSet <Vector> vectors = new TreeSet <> ();
for(int i = 0; i < n; i ++) {
Vector v = new Vector(in.nextLong(), in.nextLong(), i);
vectors.add(v);
}
while(vectors.size() > 2) {
//System.out.println(vectors);
//stop(500);
TreeSet <Vector> support = new TreeSet <> ();
while(vectors.size() > 0) {
Vector curr = vectors.pollFirst();
Vector next1 = vectors.higher(curr);
Vector next2 = vectors.lower(curr.negate());
Vector next3 = vectors.higher(curr.negate());
Vector next4 = vectors.lower(curr);
//System.out.println("CURR: " + curr + "\n" + next1 + "\n" + next2);
if(next1 != null) {
if(ok(curr, next1)) {
support.add(curr.add(next1));
vectors.remove(next1);
continue;
}
}
if(next1 != null) {
if(ok(curr, next1.negate())) {
support.add(curr.subtract(next1));
vectors.remove(next1);
continue;
}
}
if(next2 != null) {
if(ok(curr, next2)) {
support.add(curr.add(next2));
vectors.remove(next2);
continue;
}
}
if(next2 != null) {
if(ok(curr, next2.negate())) {
support.add(curr.subtract(next2));
vectors.remove(next2);
continue;
}
}
if(next3 != null) {
if(ok(curr, next3)) {
support.add(curr.add(next3));
vectors.remove(next3);
continue;
}
}
if(next3 != null) {
if(ok(curr, next3.negate())) {
support.add(curr.subtract(next3));
vectors.remove(next3);
continue;
}
}
if(next4 != null) {
if(ok(curr, next4)) {
support.add(curr.add(next4));
vectors.remove(next4);
continue;
}
}
if(next4 != null) {
if(ok(curr, next4.negate())) {
support.add(curr.subtract(next4));
vectors.remove(next4);
continue;
}
}
support.add(curr);
}
vectors = support;
}
if(vectors.size() == 2) {
Vector curr = vectors.pollFirst();
Vector next = vectors.pollFirst();
Vector add = curr.add(next);
Vector sub = curr.subtract(next);
if(sub.euclideanNorm() <= add.euclideanNorm())
vectors.add(sub);
else
vectors.add(add);
}
//System.out.println(vectors.first().euclideanNorm());
StringBuilder buffer = new StringBuilder();
int[] ans = new int[n];
dfs(vectors.pollFirst(), ans);
for(int i = 0; i < n; i ++)
buffer.append(ans[i] + " ");
System.out.println(buffer);
}
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();
}
BigInteger nextBigInteger() {
return new BigInteger(in.next());
}
int nextInt() {
return Integer.parseInt(next());
}
char nextChar() {
return in.next().charAt(0);
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static FastReader in = new FastReader();
static OutputStream out = new BufferedOutputStream(System.out);
public static byte[] toByte(Object o) {
return String.valueOf(o).getBytes();
}
public static void sop(Object o) {
System.out.print(o);
}
} | nlogn | 995_C. Leaving the Bar | CODEFORCES |
import java.util.*;
import java.io.*;
import java.math.*;
public class Main {
public static void main(String[] args) throws IOException {
PrintWriter out = new PrintWriter(System.out);
//Scanner sc = new Scanner();
Reader in = new Reader();
Main solver = new Main();
solver.solve(out, in);
out.flush();
out.close();
}
static int INF = (int)1e5*4*4+5;
static int maxn = (int)1e5*2+1;
static int mod=(int)1e9+7 ;
static int n,m,k,t,q,x,a,b,y;
static ArrayList<Integer> adj[];
static int[] dist,parent,back;
static boolean[] vis,vist;
static int root=0,ans=1;
void solve(PrintWriter out, Reader in) throws IOException{
n = in.nextInt();
if(n==1) {out.println(1);return;}
adj = new ArrayList[n+1];
for(int i=1;i<=n;i++)
adj[i] = new ArrayList<Integer>();
int u,v;
for(int i=0;i<n-1;i++){
u = in.nextInt();
v = in.nextInt();
adj[u].add(v);
adj[v].add(u);
}
vist = new boolean[n+1];
vis = new boolean[n+1];
vist[1] =true;
makeroot(1);
parent = new int[n+1];
dist = new int[n+1];
back = new int[n+1];
dfs(root,0);
calcdist(root);
vist = new boolean[n+1];
vis = new boolean[n+1];
vist[root] =true;
PriorityQueue<Node> pq = new PriorityQueue<Node>();
for(int i=1;i<=n;i++){
if(i!=root) pq.add(new Node(i,dist[i]));
}
Node elm;
int rt = root;
out.print(1);
makeroot(root);
removeNodes(root,rt);
ans+=dist[rt];
out.print(" "+ans);
int itr=2;
for(int i=2;i<=n;i++){
elm = pq.remove();
if(vis[elm.idx]) continue;
removeNodes(back[elm.idx],elm.idx);
ans += elm.dist+1;
out.print(" "+ans);
itr++;
}
for(int i=itr;i<n;i++)
out.print(" "+ans);
out.println();
}
//<>
static class Node implements Comparable<Node>{
int dist,idx;
Node(int idx,int dist){
this.idx = idx;
this.dist = dist;
}
public int compareTo(Node o) {
return o.dist-this.dist;
}
}
static void removeNodes(int s,int e){
vis[s]=true;
while(s!=e){
vis[s] = true;
s = parent[s];
}
vis[s]=true;
return;
}
static int calcdist(int s){
int res=0;
int tmp=0;
for(int e:adj[s]){
if(e!=parent[s]){
tmp= calcdist(e);
if(1+tmp>res){
res = 1+tmp;
back[s] = back[e];
}
}
}
if(res==0) back[s]=s;
return dist[s] = res;
}
static void dfs(int s,int p){
for(int e:adj[s]){
if(e!=p){
parent[e]=s;
dfs(e,s);
}
}
return;
}
static void makeroot(int s){
Queue<Integer> q = new LinkedList<>();
q.add(s);
int elm=0;
while(q.size()!=0){
elm = q.remove();
for(int e:adj[elm]){
if(!vist[e]){
vist[e]=true;
q.add(e);
root = e;
}
}
}
return;
}
static class Reader {
private InputStream mIs;
private byte[] buf = new byte[1024];
private int curChar;
private int 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 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();
}
double nextDouble()
{
return Double.parseDouble(next());
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public 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;
}
}
} | nlogn | 958_B2. Maximum Control (medium) | CODEFORCES |
// discussed with rainboy
import java.io.*;
import java.util.*;
public class CF915E {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
int n = Integer.parseInt(br.readLine());
int q = Integer.parseInt(br.readLine());
TreeMap<Integer, Integer> mp = new TreeMap<>();
int ans = 0;
while (q-- > 0) {
StringTokenizer st = new StringTokenizer(br.readLine());
int l = Integer.parseInt(st.nextToken()) - 1;
int r = Integer.parseInt(st.nextToken());
int t = Integer.parseInt(st.nextToken());
Map.Entry<Integer, Integer> e;
int l_, r_;
if (t == 1) {
if ((e = mp.floorEntry(l)) != null && (r_ = e.getValue()) >= l) {
l_ = e.getKey();
ans -= r_ - l_;
l = l_;
r = Math.max(r, r_);
}
while ((e = mp.higherEntry(l)) != null && (l_ = e.getKey()) <= r) {
r_ = e.getValue();
ans -= r_ - l_;
r = Math.max(r, r_);
mp.remove(l_);
}
ans += r - l;
mp.put(l, r);
} else {
r_ = l;
if ((e = mp.floorEntry(l)) != null && (r_ = e.getValue()) > l) {
l_ = e.getKey();
if (l_ < l)
mp.put(l_, l);
else
mp.remove(l_);
ans -= r_ - l;
}
while ((e = mp.higherEntry(l)) != null && (l_ = e.getKey()) < r) {
r_ = e.getValue();
mp.remove(l_);
ans -= r_ - l_;
}
if (r_ > r) {
mp.put(r, r_);
ans += r_ - r;
}
}
pw.println(n - ans);
}
pw.close();
}
}
| nlogn | 915_E. Physical Education Lessons | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Collection;
import java.util.AbstractList;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.Deque;
import java.util.ArrayDeque;
import java.util.NoSuchElementException;
import java.util.ConcurrentModificationException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author cunbidun
*/
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);
DPairOfLines solver = new DPairOfLines();
solver.solve(1, in, out);
out.close();
}
static class DPairOfLines {
private static final int INF = (int) 2e9 + 7;
private InputReader in;
private PrintWriter out;
public void solve(int testNumber, InputReader in, PrintWriter out) {
this.in = in;
this.out = out;
int n = in.nextInt();
if (n <= 4) {
out.println("YES");
return;
}
TreeList<PairII> list = new TreeList<>();
PairII[] a = new PairII[n + 1];
for (int i = 1; i <= n; i++) {
a[i] = (new PairII(in.nextInt(), in.nextInt()));
list.add(a[i]);
}
PairII pos1 = new PairII(INF, INF);
PairII pos2 = new PairII(INF, INF);
for (int i = 1; i <= 5; i++) {
for (int j = i + 1; j <= 5; j++) {
for (int k = j + 1; k <= 5; k++) {
int x1 = a[i].first;
int y1 = a[i].second;
int x2 = a[j].first;
int y2 = a[j].second;
int x = a[k].first;
int y = a[k].second;
long s = (long) (y2 - y1) * x + (long) (x1 - x2) * y + ((long) x2 * y1 - (long) x1 * y2);
if (s == 0) {
pos1 = a[i];
pos2 = a[j];
}
}
}
}
if (pos1.equals(new PairII(INF, INF))) {
out.println("NO");
return;
}
int x1 = pos1.first;
int y1 = pos1.second;
int x2 = pos2.first;
int y2 = pos2.second;
for (int i = 0; i < list.size(); i++) {
int x = list.get(i).first;
int y = list.get(i).second;
long s = (long) (y2 - y1) * x + (long) (x1 - x2) * y + ((long) x2 * y1 - (long) x1 * y2);
if (s == 0) {
list.remove(i);
i--;
}
}
if (list.size() <= 2) {
out.println("YES");
return;
}
x1 = list.get(0).first;
y1 = list.get(0).second;
x2 = list.get(1).first;
y2 = list.get(1).second;
for (int i = 0; i < list.size(); i++) {
int x = list.get(i).first;
int y = list.get(i).second;
long s = (long) (y2 - y1) * x + (long) (x1 - x2) * y + ((long) x2 * y1 - (long) x1 * y2);
if (s == 0) {
list.remove(i);
i--;
}
}
if (list.size() == 0) {
out.println("YES");
} else out.println("NO");
}
}
static interface OrderedIterator<E> extends Iterator<E> {
}
static class PairII implements Comparable<PairII> {
public int first;
public int second;
public PairII(int first, int second) {
this.first = first;
this.second = second;
}
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PairII pair = (PairII) o;
return first == pair.first && second == pair.second;
}
public String toString() {
return "(" + first + "," + second + ")";
}
public int compareTo(PairII o) {
int value = Integer.compare(first, o.first);
if (value != 0) {
return value;
}
return Integer.compare(second, o.second);
}
}
static class TreeList<E> extends AbstractList<E> {
private TreeList.AVLNode<E> root;
private int size;
public TreeList() {
super();
}
public TreeList(final Collection<? extends E> coll) {
super();
if (!coll.isEmpty()) {
root = new TreeList.AVLNode<>(coll);
size = coll.size();
}
}
public E get(final int index) {
return root.get(index).getValue();
}
public int size() {
return size;
}
public Iterator<E> iterator() {
// override to go 75% faster
return listIterator(0);
}
public ListIterator<E> listIterator() {
// override to go 75% faster
return listIterator(0);
}
public ListIterator<E> listIterator(final int fromIndex) {
return new TreeList.TreeListIterator<>(this, fromIndex);
}
public int indexOf(final Object object) {
// override to go 75% faster
if (root == null) {
return -1;
}
return root.indexOf(object, root.relativePosition);
}
public boolean contains(final Object object) {
return indexOf(object) >= 0;
}
public Object[] toArray() {
final Object[] array = new Object[size()];
if (root != null) {
root.toArray(array, root.relativePosition);
}
return array;
}
public void add(final int index, final E obj) {
modCount++;
if (root == null) {
root = new TreeList.AVLNode<>(index, obj, null, null);
} else {
root = root.insert(index, obj);
}
size++;
}
public boolean addAll(final Collection<? extends E> c) {
if (c.isEmpty()) {
return false;
}
modCount += c.size();
final TreeList.AVLNode<E> cTree = new TreeList.AVLNode<>(c);
root = root == null ? cTree : root.addAll(cTree, size);
size += c.size();
return true;
}
public E set(final int index, final E obj) {
final TreeList.AVLNode<E> node = root.get(index);
final E result = node.value;
node.setValue(obj);
return result;
}
public E remove(final int index) {
modCount++;
final E result = get(index);
root = root.remove(index);
size--;
return result;
}
public void clear() {
modCount++;
root = null;
size = 0;
}
static class AVLNode<E> {
private TreeList.AVLNode<E> left;
private boolean leftIsPrevious;
private TreeList.AVLNode<E> right;
private boolean rightIsNext;
private int height;
private int relativePosition;
private E value;
private AVLNode(final int relativePosition, final E obj,
final TreeList.AVLNode<E> rightFollower, final TreeList.AVLNode<E> leftFollower) {
this.relativePosition = relativePosition;
value = obj;
rightIsNext = true;
leftIsPrevious = true;
right = rightFollower;
left = leftFollower;
}
private AVLNode(final Collection<? extends E> coll) {
this(coll.iterator(), 0, coll.size() - 1, 0, null, null);
}
private AVLNode(final Iterator<? extends E> iterator, final int start, final int end,
final int absolutePositionOfParent, final TreeList.AVLNode<E> prev, final TreeList.AVLNode<E> next) {
final int mid = start + (end - start) / 2;
if (start < mid) {
left = new TreeList.AVLNode<>(iterator, start, mid - 1, mid, prev, this);
} else {
leftIsPrevious = true;
left = prev;
}
value = iterator.next();
relativePosition = mid - absolutePositionOfParent;
if (mid < end) {
right = new TreeList.AVLNode<>(iterator, mid + 1, end, mid, this, next);
} else {
rightIsNext = true;
right = next;
}
recalcHeight();
}
E getValue() {
return value;
}
void setValue(final E obj) {
this.value = obj;
}
TreeList.AVLNode<E> get(final int index) {
final int indexRelativeToMe = index - relativePosition;
if (indexRelativeToMe == 0) {
return this;
}
final TreeList.AVLNode<E> nextNode = indexRelativeToMe < 0 ? getLeftSubTree() : getRightSubTree();
if (nextNode == null) {
return null;
}
return nextNode.get(indexRelativeToMe);
}
int indexOf(final Object object, final int index) {
if (getLeftSubTree() != null) {
final int result = left.indexOf(object, index + left.relativePosition);
if (result != -1) {
return result;
}
}
if (value == null ? value == object : value.equals(object)) {
return index;
}
if (getRightSubTree() != null) {
return right.indexOf(object, index + right.relativePosition);
}
return -1;
}
void toArray(final Object[] array, final int index) {
array[index] = value;
if (getLeftSubTree() != null) {
left.toArray(array, index + left.relativePosition);
}
if (getRightSubTree() != null) {
right.toArray(array, index + right.relativePosition);
}
}
TreeList.AVLNode<E> next() {
if (rightIsNext || right == null) {
return right;
}
return right.min();
}
TreeList.AVLNode<E> previous() {
if (leftIsPrevious || left == null) {
return left;
}
return left.max();
}
TreeList.AVLNode<E> insert(final int index, final E obj) {
final int indexRelativeToMe = index - relativePosition;
if (indexRelativeToMe <= 0) {
return insertOnLeft(indexRelativeToMe, obj);
}
return insertOnRight(indexRelativeToMe, obj);
}
private TreeList.AVLNode<E> insertOnLeft(final int indexRelativeToMe, final E obj) {
if (getLeftSubTree() == null) {
setLeft(new TreeList.AVLNode<>(-1, obj, this, left), null);
} else {
setLeft(left.insert(indexRelativeToMe, obj), null);
}
if (relativePosition >= 0) {
relativePosition++;
}
final TreeList.AVLNode<E> ret = balance();
recalcHeight();
return ret;
}
private TreeList.AVLNode<E> insertOnRight(final int indexRelativeToMe, final E obj) {
if (getRightSubTree() == null) {
setRight(new TreeList.AVLNode<>(+1, obj, right, this), null);
} else {
setRight(right.insert(indexRelativeToMe, obj), null);
}
if (relativePosition < 0) {
relativePosition--;
}
final TreeList.AVLNode<E> ret = balance();
recalcHeight();
return ret;
}
private TreeList.AVLNode<E> getLeftSubTree() {
return leftIsPrevious ? null : left;
}
private TreeList.AVLNode<E> getRightSubTree() {
return rightIsNext ? null : right;
}
private TreeList.AVLNode<E> max() {
return getRightSubTree() == null ? this : right.max();
}
private TreeList.AVLNode<E> min() {
return getLeftSubTree() == null ? this : left.min();
}
TreeList.AVLNode<E> remove(final int index) {
final int indexRelativeToMe = index - relativePosition;
if (indexRelativeToMe == 0) {
return removeSelf();
}
if (indexRelativeToMe > 0) {
setRight(right.remove(indexRelativeToMe), right.right);
if (relativePosition < 0) {
relativePosition++;
}
} else {
setLeft(left.remove(indexRelativeToMe), left.left);
if (relativePosition > 0) {
relativePosition--;
}
}
recalcHeight();
return balance();
}
private TreeList.AVLNode<E> removeMax() {
if (getRightSubTree() == null) {
return removeSelf();
}
setRight(right.removeMax(), right.right);
if (relativePosition < 0) {
relativePosition++;
}
recalcHeight();
return balance();
}
private TreeList.AVLNode<E> removeMin() {
if (getLeftSubTree() == null) {
return removeSelf();
}
setLeft(left.removeMin(), left.left);
if (relativePosition > 0) {
relativePosition--;
}
recalcHeight();
return balance();
}
private TreeList.AVLNode<E> removeSelf() {
if (getRightSubTree() == null && getLeftSubTree() == null) {
return null;
}
if (getRightSubTree() == null) {
if (relativePosition > 0) {
left.relativePosition += relativePosition;
}
left.max().setRight(null, right);
return left;
}
if (getLeftSubTree() == null) {
right.relativePosition += relativePosition - (relativePosition < 0 ? 0 : 1);
right.min().setLeft(null, left);
return right;
}
if (heightRightMinusLeft() > 0) {
// more on the right, so delete from the right
final TreeList.AVLNode<E> rightMin = right.min();
value = rightMin.value;
if (leftIsPrevious) {
left = rightMin.left;
}
right = right.removeMin();
if (relativePosition < 0) {
relativePosition++;
}
} else {
// more on the left or equal, so delete from the left
final TreeList.AVLNode<E> leftMax = left.max();
value = leftMax.value;
if (rightIsNext) {
right = leftMax.right;
}
final TreeList.AVLNode<E> leftPrevious = left.left;
left = left.removeMax();
if (left == null) {
// special case where left that was deleted was a double link
// only occurs when height difference is equal
left = leftPrevious;
leftIsPrevious = true;
}
if (relativePosition > 0) {
relativePosition--;
}
}
recalcHeight();
return this;
}
private TreeList.AVLNode<E> balance() {
switch (heightRightMinusLeft()) {
case 1:
case 0:
case -1:
return this;
case -2:
if (left.heightRightMinusLeft() > 0) {
setLeft(left.rotateLeft(), null);
}
return rotateRight();
case 2:
if (right.heightRightMinusLeft() < 0) {
setRight(right.rotateRight(), null);
}
return rotateLeft();
default:
throw new RuntimeException("tree inconsistent!");
}
}
private int getOffset(final TreeList.AVLNode<E> node) {
if (node == null) {
return 0;
}
return node.relativePosition;
}
private int setOffset(final TreeList.AVLNode<E> node, final int newOffest) {
if (node == null) {
return 0;
}
final int oldOffset = getOffset(node);
node.relativePosition = newOffest;
return oldOffset;
}
private void recalcHeight() {
height = Math.max(
getLeftSubTree() == null ? -1 : getLeftSubTree().height,
getRightSubTree() == null ? -1 : getRightSubTree().height) + 1;
}
private int getHeight(final TreeList.AVLNode<E> node) {
return node == null ? -1 : node.height;
}
private int heightRightMinusLeft() {
return getHeight(getRightSubTree()) - getHeight(getLeftSubTree());
}
private TreeList.AVLNode<E> rotateLeft() {
final TreeList.AVLNode<E> newTop = right; // can't be faedelung!
final TreeList.AVLNode<E> movedNode = getRightSubTree().getLeftSubTree();
final int newTopPosition = relativePosition + getOffset(newTop);
final int myNewPosition = -newTop.relativePosition;
final int movedPosition = getOffset(newTop) + getOffset(movedNode);
setRight(movedNode, newTop);
newTop.setLeft(this, null);
setOffset(newTop, newTopPosition);
setOffset(this, myNewPosition);
setOffset(movedNode, movedPosition);
return newTop;
}
private TreeList.AVLNode<E> rotateRight() {
final TreeList.AVLNode<E> newTop = left;
final TreeList.AVLNode<E> movedNode = getLeftSubTree().getRightSubTree();
final int newTopPosition = relativePosition + getOffset(newTop);
final int myNewPosition = -newTop.relativePosition;
final int movedPosition = getOffset(newTop) + getOffset(movedNode);
setLeft(movedNode, newTop);
newTop.setRight(this, null);
setOffset(newTop, newTopPosition);
setOffset(this, myNewPosition);
setOffset(movedNode, movedPosition);
return newTop;
}
private void setLeft(final TreeList.AVLNode<E> node, final TreeList.AVLNode<E> previous) {
leftIsPrevious = node == null;
left = leftIsPrevious ? previous : node;
recalcHeight();
}
private void setRight(final TreeList.AVLNode<E> node, final TreeList.AVLNode<E> next) {
rightIsNext = node == null;
right = rightIsNext ? next : node;
recalcHeight();
}
private TreeList.AVLNode<E> addAll(TreeList.AVLNode<E> otherTree, final int currentSize) {
final TreeList.AVLNode<E> maxNode = max();
final TreeList.AVLNode<E> otherTreeMin = otherTree.min();
// We need to efficiently merge the two AVL trees while keeping them
// balanced (or nearly balanced). To do this, we take the shorter
// tree and combine it with a similar-height subtree of the taller
// tree. There are two symmetric cases:
// * this tree is taller, or
// * otherTree is taller.
if (otherTree.height > height) {
// CASE 1: The other tree is taller than this one. We will thus
// merge this tree into otherTree.
// STEP 1: Remove the maximum element from this tree.
final TreeList.AVLNode<E> leftSubTree = removeMax();
// STEP 2: Navigate left from the root of otherTree until we
// contains a subtree, s, that is no taller than me. (While we are
// navigating left, we store the nodes we encounter in a stack
// so that we can re-balance them in step 4.)
final Deque<TreeList.AVLNode<E>> sAncestors = new ArrayDeque<>();
TreeList.AVLNode<E> s = otherTree;
int sAbsolutePosition = s.relativePosition + currentSize;
int sParentAbsolutePosition = 0;
while (s != null && s.height > getHeight(leftSubTree)) {
sParentAbsolutePosition = sAbsolutePosition;
sAncestors.push(s);
s = s.left;
if (s != null) {
sAbsolutePosition += s.relativePosition;
}
}
// STEP 3: Replace s with a newly constructed subtree whose root
// is maxNode, whose left subtree is leftSubTree, and whose right
// subtree is s.
maxNode.setLeft(leftSubTree, null);
maxNode.setRight(s, otherTreeMin);
if (leftSubTree != null) {
leftSubTree.max().setRight(null, maxNode);
leftSubTree.relativePosition -= currentSize - 1;
}
if (s != null) {
s.min().setLeft(null, maxNode);
s.relativePosition = sAbsolutePosition - currentSize + 1;
}
maxNode.relativePosition = currentSize - 1 - sParentAbsolutePosition;
otherTree.relativePosition += currentSize;
// STEP 4: Re-balance the tree and recalculate the heights of s's ancestors.
s = maxNode;
while (!sAncestors.isEmpty()) {
final TreeList.AVLNode<E> sAncestor = sAncestors.pop();
sAncestor.setLeft(s, null);
s = sAncestor.balance();
}
return s;
}
otherTree = otherTree.removeMin();
final Deque<TreeList.AVLNode<E>> sAncestors = new ArrayDeque<>();
TreeList.AVLNode<E> s = this;
int sAbsolutePosition = s.relativePosition;
int sParentAbsolutePosition = 0;
while (s != null && s.height > getHeight(otherTree)) {
sParentAbsolutePosition = sAbsolutePosition;
sAncestors.push(s);
s = s.right;
if (s != null) {
sAbsolutePosition += s.relativePosition;
}
}
otherTreeMin.setRight(otherTree, null);
otherTreeMin.setLeft(s, maxNode);
if (otherTree != null) {
otherTree.min().setLeft(null, otherTreeMin);
otherTree.relativePosition++;
}
if (s != null) {
s.max().setRight(null, otherTreeMin);
s.relativePosition = sAbsolutePosition - currentSize;
}
otherTreeMin.relativePosition = currentSize - sParentAbsolutePosition;
s = otherTreeMin;
while (!sAncestors.isEmpty()) {
final TreeList.AVLNode<E> sAncestor = sAncestors.pop();
sAncestor.setRight(s, null);
s = sAncestor.balance();
}
return s;
}
}
static class TreeListIterator<E> implements ListIterator<E>, OrderedIterator<E> {
private final TreeList<E> parent;
private TreeList.AVLNode<E> next;
private int nextIndex;
private TreeList.AVLNode<E> current;
private int currentIndex;
private int expectedModCount;
private TreeListIterator(final TreeList<E> parent, final int fromIndex) throws IndexOutOfBoundsException {
super();
this.parent = parent;
this.expectedModCount = parent.modCount;
this.next = parent.root == null ? null : parent.root.get(fromIndex);
this.nextIndex = fromIndex;
this.currentIndex = -1;
}
private void checkModCount() {
if (parent.modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
public boolean hasNext() {
return nextIndex < parent.size();
}
public E next() {
checkModCount();
if (!hasNext()) {
throw new NoSuchElementException("No element at index " + nextIndex + ".");
}
if (next == null) {
next = parent.root.get(nextIndex);
}
final E value = next.getValue();
current = next;
currentIndex = nextIndex++;
next = next.next();
return value;
}
public boolean hasPrevious() {
return nextIndex > 0;
}
public E previous() {
checkModCount();
if (!hasPrevious()) {
throw new NoSuchElementException("Already at start of list.");
}
if (next == null) {
next = parent.root.get(nextIndex - 1);
} else {
next = next.previous();
}
final E value = next.getValue();
current = next;
currentIndex = --nextIndex;
return value;
}
public int nextIndex() {
return nextIndex;
}
public int previousIndex() {
return nextIndex() - 1;
}
public void remove() {
checkModCount();
if (currentIndex == -1) {
throw new IllegalStateException();
}
parent.remove(currentIndex);
if (nextIndex != currentIndex) {
// remove() following next()
nextIndex--;
}
// the AVL node referenced by next may have become stale after a remove
// reset it now: will be retrieved by next call to next()/previous() via nextIndex
next = null;
current = null;
currentIndex = -1;
expectedModCount++;
}
public void set(final E obj) {
checkModCount();
if (current == null) {
throw new IllegalStateException();
}
current.setValue(obj);
}
public void add(final E obj) {
checkModCount();
parent.add(nextIndex, obj);
current = null;
currentIndex = -1;
nextIndex++;
expectedModCount++;
}
}
}
static class InputReader extends InputStream {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
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;
}
private static boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
| nlogn | 961_D. Pair Of Lines | CODEFORCES |
import java.util.*;
import java.io.*;
public class A
{
public static void main(String ar[]) throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s1[]=br.readLine().split(" ");
int n=Integer.parseInt(s1[0]);
long x=Long.parseLong(s1[1]);
long y=Long.parseLong(s1[2]);
long S=0;
long mod=1000000007;
B a[]=new B[n];
TreeMap<Long,Long> tm=new TreeMap<Long,Long>();
long ans[]=new long[n];
for(int i=0;i<n;i++)
{
String s2[]=br.readLine().split(" ");
long l=Long.parseLong(s2[0]);
long r=Long.parseLong(s2[1]);
B b1=new B(l,r);
a[i]=b1;
}
Arrays.sort(a,new The_Comp());
for(int i=0;i<n;i++)
{
long l=a[i].x;
long r=a[i].y;
if(tm.floorKey(l-1)!=null)
{
long u=tm.floorKey(l-1);
long v=l;
if((v-u)*y<x)
{ ans[i]=((r-u)*y)%mod;
if(tm.get(u)>1)
tm.put(u,tm.get(u)-1);
else
tm.remove(u);
}
else
{ ans[i]=(x+(r-l)*y)%mod; }
}
else
ans[i]=(x+(r-l)*y)%mod;
S=(S+ans[i])%mod;
if(tm.containsKey(r))
tm.put(r,1+tm.get(r));
else
tm.put(r,(long)1);
}
System.out.println(S);
}
}
class The_Comp implements Comparator<B>
{
public int compare(B b1,B b2)
{
if(b1.x>b2.x)
return 1;
else if(b1.x==b2.x)
{
if(b1.y>b2.y)
return 1;
else if(b1.y==b2.y)
return 0;
else
return -1;
}
else
return -1;
}
}
class B
{
long x=(long)1;
long y=(long)1;
public B(long l1,long l2)
{ x=l1; y=l2; }
} | nlogn | 1061_D. TV Shows | CODEFORCES |
import org.omg.PortableServer.AdapterActivator;
import java.io.*;
import java.lang.reflect.Array;
import java.net.CookieHandler;
import java.util.*;
import java.math.*;
import java.lang.*;
import java.util.concurrent.LinkedBlockingDeque;
import static java.lang.Math.*;
public class TaskA implements Runnable {
long m = (int)1e9+7;
PrintWriter w;
InputReader c;
public void run() {
c = new InputReader(System.in);
w = new PrintWriter(System.out);
int n = c.nextInt();
int a[] = scanArrayI(n);
int maxtime = Integer.MAX_VALUE,ind = -1;
for(int i=0;i<n;i++){
int time = Integer.MAX_VALUE;
if(a[i]<i+1)
time = i;
else{
time = (int)ceil((a[i] - i)/(double)n) * n + i;
}
if(time<maxtime){
maxtime = time;
ind = i;
}
}
w.println(ind+1);
w.close();
}
static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
public static void sortbyColumn(int arr[][], int col){
Arrays.sort(arr, new Comparator<int[]>()
{
public int compare(int[] o1, int[] o2){
return(Integer.valueOf(o1[col]).compareTo(o2[col]));
}
});
}
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 static int[] radixSort(int[] f) {
int[] to = new int[f.length];
{
int[] b = new int[65537];
for(int i = 0;i < f.length;i++)b[1+(f[i]&0xffff)]++;
for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
for(int i = 0;i < f.length;i++)to[b[f[i]&0xffff]++] = f[i];
int[] d = f; f = to;to = d;
}
{
int[] b = new int[65537];
for(int i = 0;i < f.length;i++)b[1+(f[i]>>>16)]++;
for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
for(int i = 0;i < f.length;i++)to[b[f[i]>>>16]++] = f[i];
int[] d = f; f = to;to = d;
}
return f;
}
public void printArray(int[] a){
for(int i=0;i<a.length;i++)
w.print(a[i]+" ");
w.println();
}
public int[] scanArrayI(int n){
int a[] = new int[n];
for(int i=0;i<n;i++)
a[i] = c.nextInt();
return a;
}
public long[] scanArrayL(int n){
long a[] = new long[n];
for(int i=0;i<n;i++)
a[i] = c.nextLong();
return a;
}
public void printArray(long[] a){
for(int i=0;i<a.length;i++)
w.print(a[i]+" ");
w.println();
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars==-1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
}
catch (IOException e) {
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
public int nextInt() {
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if(c<'0'||c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
public static void main(String args[]) throws Exception {
new Thread(null, new TaskA(),"TaskA",1<<26).start();
}
} | nlogn | 996_B. World Cup | CODEFORCES |
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Comp c1 = getComp(scanner);
Comp c2 = getComp(scanner);
c1.sortByPrice();
c2.sortByPrice();
int i = 0;
int j = 0;
while(i < c1.num || j < c2.num) {
Elem xi = (i < c1.num) ? c1.elems.get(i) : null;
Elem yj = (j < c2.num) ? c2.elems.get(j) : null;
if(xi != null && yj != null) {
if(xi.price >= yj.price) {
if(!c2.resultSet.contains(xi)) {
c1.resultSet.add(xi);
}
i++;
} else {
if(!c1.resultSet.contains(yj)) {
c2.resultSet.add(yj);
}
j++;
}
} else
if(xi != null) {
if(!c2.resultSet.contains(xi)) {
c1.resultSet.add(xi);
}
i++;
} else {
if(!c1.resultSet.contains(yj)) {
c2.resultSet.add(yj);
}
j++;
}
}
long result = c1.getResultPrice() + c2.getResultPrice();
System.out.println(result);
}
private static Comp getComp(Scanner scanner) {
Comp c = new Comp();
c.num = scanner.nextInt();
for(int i = 0; i < c.num; i++) {
c.addElem(scanner.nextLong(), scanner.nextLong());
}
return c;
}
}
class Comp {
int num;
List<Elem> elems = new ArrayList<>();
Set<Elem> resultSet = new HashSet<>();
void addElem(long el, long pr) {
Elem elem = new Elem(el, pr);
elems.add(elem);
}
void sortByPrice() {
Collections.sort(elems);
}
long getResultPrice() {
long sumPrice = 0;
for(Elem elem : resultSet) {
sumPrice += elem.price;
}
return sumPrice;
}
}
class Elem implements Comparable<Elem> {
long elem;
long price;
public Elem(long el, long pr) {
this.elem = el;
this.price = pr;
}
public int compareTo(Elem other) {
return (int) (other.price - price);
}
public boolean equals(Object o) {
if(!(o instanceof Elem)) {
return false;
}
Elem other = (Elem) o;
return (other.elem == elem);
}
public int hashCode() {
return (int) elem;
}
public String toString() {
return "(" + elem + ", " + price + ")";
}
}
| nlogn | 981_B. Businessmen Problems | CODEFORCES |
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.StringTokenizer;
public class Div1_526C {
static int nV;
static ArrayList<Integer>[] chldn;
static int root;
static int[][] anc;
static int[] depth;
static int[] num;
static int[] nLoc;
static int[][] tree;
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
PrintWriter printer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
nV = Integer.parseInt(reader.readLine());
chldn = new ArrayList[nV];
for (int i = 0; i < nV; i++) {
chldn[i] = new ArrayList<>();
}
anc = new int[nV][21];
depth = new int[nV];
num = new int[nV];
nLoc = new int[nV];
tree = new int[nV * 4][2];
for (int[] a : tree) {
a[0] = a[1] = -1;
}
root = 0;
StringTokenizer inputData = new StringTokenizer(reader.readLine());
for (int i = 0; i < nV; i++) {
num[i] = Integer.parseInt(inputData.nextToken());
nLoc[num[i]] = i;
}
inputData = new StringTokenizer(reader.readLine());
for (int i = 1; i < nV; i++) {
anc[i][0] = Integer.parseInt(inputData.nextToken()) - 1;
chldn[anc[i][0]].add(i);
}
preprocess();
build(1, 0, nV - 1);
int nQ = Integer.parseInt(reader.readLine());
while (nQ-- > 0) {
inputData = new StringTokenizer(reader.readLine());
if (inputData.nextToken().equals("1")) {
int a = Integer.parseInt(inputData.nextToken()) - 1;
int b = Integer.parseInt(inputData.nextToken()) - 1;
int temp = num[a];
num[a] = num[b];
num[b] = temp;
nLoc[num[a]] = a;
nLoc[num[b]] = b;
update(1, 0, nV - 1, num[a]);
update(1, 0, nV - 1, num[b]);
} else {
printer.println(query(1, 0, nV - 1, nLoc[0], nLoc[0]) + 1);
}
}
printer.close();
}
static void build(int nI, int cL, int cR) {
if (cL == cR) {
tree[nI][0] = nLoc[cL];
tree[nI][1] = nLoc[cL];
} else {
int mid = (cL + cR) >> 1;
build(nI * 2, cL, mid);
build(nI * 2 + 1, mid + 1, cR);
if (tree[nI * 2][0] != -1 && tree[nI * 2 + 1][0] != -1) {
merge(tree[nI * 2][0], tree[nI * 2][1], tree[nI * 2 + 1][0], tree[nI * 2 + 1][1]);
tree[nI][0] = mResp[0];
tree[nI][1] = mResp[1];
}
}
}
static int query(int nI, int cL, int cR, int e1, int e2) {
if (cL == cR) {
merge(e1, e2, nLoc[cL], nLoc[cL]);
if (mResp[0] != -1) {
return cL;
} else {
return cL - 1;
}
}
int mid = (cL + cR) >> 1;
merge(tree[nI * 2][0], tree[nI * 2][1], e1, e2);
if (mResp[0] != -1) {
return query(nI * 2 + 1, mid + 1, cR, mResp[0], mResp[1]);
}
return query(nI * 2, cL, mid, e1, e2);
}
static void update(int nI, int cL, int cR, int uI) {
if (cL == cR) {
tree[nI][0] = nLoc[cL];
tree[nI][1] = nLoc[cL];
} else {
int mid = (cL + cR) >> 1;
if (uI <= mid) {
update(nI * 2, cL, mid, uI);
} else {
update(nI * 2 + 1, mid + 1, cR, uI);
}
merge(tree[nI * 2][0], tree[nI * 2][1], tree[nI * 2 + 1][0], tree[nI * 2 + 1][1]);
tree[nI][0] = mResp[0];
tree[nI][1] = mResp[1];
}
}
static int[] mResp = new int[2];
static void merge1(int... a) {
for (int i = 0; i < 3; i++) {
if (a[i] == -1) {
mResp[0] = mResp[1] = -1;
return;
}
}
if (onPath(a[0], a[1], a[2])) {
mResp[0] = a[0];
mResp[1] = a[1];
return;
}
if (onPath(a[0], a[2], a[1])) {
mResp[0] = a[0];
mResp[1] = a[2];
return;
}
if (onPath(a[1], a[2], a[0])) {
mResp[0] = a[1];
mResp[1] = a[2];
return;
}
mResp[0] = mResp[1] = -1;
}
static void merge(int... a) {
merge1(a[0], a[1], a[2]);
merge1(mResp[0], mResp[1], a[3]);
}
static boolean onPath(int a, int b, int c) {
if (a == c || b == c) {
return true;
}
if (depth[a] > depth[c]) {
a = jump(a, depth[a] - depth[c] - 1);
}
if (depth[b] > depth[c]) {
b = jump(b, depth[b] - depth[c] - 1);
}
if (a == b) {
return false;
}
if (anc[a][0] == c || anc[b][0] == c) {
return true;
}
return false;
}
// good for depth of up to 1_048_576 = 2^20
static void preprocess() {
anc[root][0] = root;
fParent(root);
for (int k = 1; k <= 20; k++) {
for (int i = 0; i < nV; i++) {
anc[i][k] = anc[anc[i][k - 1]][k - 1];
}
}
}
static void fParent(int cV) {
for (int aV : chldn[cV]) {
anc[aV][0] = cV;
depth[aV] = depth[cV] + 1;
fParent(aV);
}
}
static int fLCA(int a, int b) {
if (depth[a] > depth[b]) {
int temp = b;
b = a;
a = temp;
}
b = jump(b, depth[b] - depth[a]);
if (a == b) {
return a;
}
for (int i = 20; i >= 0; i--) {
if (anc[a][i] != anc[b][i]) {
a = anc[a][i];
b = anc[b][i];
}
}
return anc[a][0];
}
static int jump(int cV, int d) {
for (int i = 0; i <= 20; i++) {
if ((d & (1 << i)) != 0) {
cV = anc[cV][i];
}
}
return cV;
}
static Comparator<Integer> BY_DEPTH = new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
return -Integer.compare(depth[o1], depth[o2]); // greatest depth first
}
};
} | nlogn | 1084_F. Max Mex | CODEFORCES |
import java.util.Scanner;
import java.util.Vector;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int a[] = new int[n];
int b[] = new int[n];
for (int i = 0; i < n; i++) a[i] = sc.nextInt();
for (int i = 0; i < n; i++) b[i] = sc.nextInt();
int c[] = new int[2 * n];
c[0] = a[0];
for (int i = 1; i < n; i++) {
c[i * 2] = a[i];
c[i * 2 - 1] = b[i];
if (a[i] == 1 || b[i] == 1) {
System.out.print(-1);
System.exit(0);
}
}
c[2 * n - 1] = b[0];
if (a[0] == 1 || b[0] == 1) {
System.out.print(-1);
System.exit(0);
}
System.out.println(bin_search(c, m));
}
private static double bin_search(int[] c, int m) {
double start = 0;
double end = Integer.MAX_VALUE;
double mid;
while (start + 0.0000001 < end) {
mid = (start + end) / 2;
if (test(mid, m, c)) end = mid;
else start = mid;
}
return end;
}
private static boolean test(double fuel, int m, int[] c) {
for (int i = 0; i < c.length; i++) {
fuel -= (m + fuel) / c[i];
if (fuel < 0) {
return false;
}
}
return true;
}
}
| nlogn | 1010_A. Fly | CODEFORCES |
import java.util.Scanner;
import java.util.Vector;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int a[] = new int[n];
int b[] = new int[n];
for (int i = 0; i < n; i++) a[i] = sc.nextInt();
for (int i = 0; i < n; i++) b[i] = sc.nextInt();
int c[] = new int[2 * n];
c[0] = a[0];
for (int i = 1; i < n; i++) {
c[i * 2] = a[i];
c[i * 2 - 1] = b[i];
if (a[i] == 1 || b[i] == 1) {
System.out.print(-1);
System.exit(0);
}
}
c[2 * n - 1] = b[0];
if (a[0] == 1 || b[0] == 1) {
System.out.print(-1);
System.exit(0);
}
System.out.println(bin_search(c, m));
}
private static double bin_search(int[] c, int m) {
double start = 0;
double end = Integer.MAX_VALUE;
double mid;
while (start + 0.0000001 < end) {
mid = (start + end) / 2;
if (test(mid, m, c)) end = mid;
else start = mid;
}
return end;
}
private static boolean test(double fuel, int m, int[] c) {
for (int i = 0; i < c.length; i++) {
fuel -= (m + fuel) / c[i];
if (fuel < 0) {
return false;
}
}
return true;
}
}
| nlogn | 1010_A. Fly | CODEFORCES |
import com.sun.org.apache.xpath.internal.operations.Bool;
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
MyScanner scan = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out));
int n = scan.nextInt();
int[] vals = new int[n];
for (int i = 0; i < n; i++) {
vals[i] = scan.nextInt();
}
for (int i = 0; i < n; i++) {
if (solve(i, vals)) {
out.print('A');
} else {
out.print('B');
}
}
out.close();
}
static HashMap<Integer, Boolean> dpResult = new HashMap<>();
private static boolean solve(int pos, int[] vals) {
if (dpResult.containsKey(pos)) return dpResult.get(pos);
int val = vals[pos];
boolean hasLose = false;
for (int i = pos; i < vals.length; i += val) {
if (i == pos) continue;
if (vals[i] <= vals[pos]) continue;
if (hasLose) break;
if (!solve(i, vals)) {
hasLose = true;
}
}
for (int i = pos; i >= 0; i -= val) {
if (i == pos) continue;
if (vals[i] <= vals[pos]) continue;
if (hasLose) break;
if (!solve(i, vals)) {
hasLose = true;
}
}
dpResult.put(pos, hasLose);
return hasLose;
}
//-----------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;
}
}
//--------------------------------------------------------
} | nlogn | 1033_C. Permutation Game | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.StringTokenizer;
public class D {
public static void main(String[] args){
FastScanner scan = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int n = scan.nextInt();
long[] a = scan.nextLongArray(n);
BigInteger res = BigInteger.ZERO;
for (int i = n-1; i >= 0; i--) res = res.add(BigInteger.valueOf(i*a[i] - (n-1-i)*a[i]));
HashMap<Long, Long> map = new HashMap<>();
for(int i = 0; i < n; i++) {
res = res.subtract(BigInteger.valueOf(map.getOrDefault(a[i]-1, 0L)));
res = res.add(BigInteger.valueOf(map.getOrDefault(a[i]+1, 0L)));
map.put(a[i], map.getOrDefault(a[i], 0L)+1);
}
out.println(res);
out.close();
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(br.readLine());
} catch (Exception e){e.printStackTrace();}
}
public String next() {
if (st.hasMoreTokens()) return st.nextToken();
try {st = new StringTokenizer(br.readLine());}
catch (Exception e) {e.printStackTrace();}
return st.nextToken();
}
public int nextInt() {return Integer.parseInt(next());}
public long nextLong() {return Long.parseLong(next());}
public double nextDouble() {return Double.parseDouble(next());}
public String nextLine() {
String line = "";
if(st.hasMoreTokens()) line = st.nextToken();
else try {return br.readLine();}catch(IOException e){e.printStackTrace();}
while(st.hasMoreTokens()) line += " "+st.nextToken();
return line;
}
public int[] nextIntArray(int n) {
int[] a = new int[n];
for(int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
public long[] nextLongArray(int n){
long[] a = new long[n];
for(int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
public double[] nextDoubleArray(int n){
double[] a = new double[n];
for(int i = 0; i < n; i++) a[i] = nextDouble();
return a;
}
public char[][] nextGrid(int n, int m){
char[][] grid = new char[n][m];
for(int i = 0; i < n; i++) grid[i] = next().toCharArray();
return grid;
}
}
}
| nlogn | 903_D. Almost Difference | CODEFORCES |
import java.util.*;
import java.io.*;
import java.math.BigInteger;
public class ProblemE
{
static int mod = (int) (1e9+7);
static InputReader in;
static PrintWriter out;
static class SegmentTree {
long st[];
SegmentTree(int n) {
st = new long[4*n];
build(0, n - 1, 1);
}
int getMid(int s, int e) {
return (s+e)>>1;
}
long merge(long a,long b){
return a+b;
}
void update(int s, int e, int x, int y, long c, int si){
if(s == x && e == y){
st[si] += c;
}
else{
int mid = getMid(s, e);
if(y <= mid)
update(s, mid, x, y, c, 2*si);
else if(x > mid)
update(mid + 1, e, x ,y ,c ,2*si + 1);
else{
update(s, mid, x, mid, c, 2*si);
update(mid + 1, e, mid + 1, y, c, 2*si + 1);
}
st[si] = merge(st[2*si],st[2*si+1]);
}
}
long get(int s, int e, int x, int y, int si){
if(s == x && e == y){
return st[si];
}
int mid = getMid(s, e);
if(y <= mid)
return get(s, mid, x, y, 2*si);
else if(x > mid)
return get(mid + 1, e, x, y, 2*si + 1);
return merge(get(s, mid, x, mid, 2*si), get(mid + 1, e, mid + 1, y, 2*si + 1));
}
void build(int ss, int se, int si){
if (ss == se) {
st[si] = 0;
return;
}
int mid = getMid(ss, se);
build(ss, mid, si * 2 );
build(mid + 1, se, si * 2 + 1);
st[si] = merge(st[2*si],st[2*si+1]);
}
}
public static void main(String[] args) throws FileNotFoundException
{
in = new InputReader(System.in);
out = new PrintWriter(System.out);
int n = in.nextInt();
int[] arr = in.nextIntArray(n);
ArrayList<Integer>list = new ArrayList<>();
HashMap<Integer,Integer> map = new HashMap<>();
for(int i = 0; i < n; i++){
list.add(arr[i]);
list.add(arr[i] + 1);
list.add(arr[i] - 1);
}
Collections.sort(list);
int j = 1;
for(int k : list){
if(map.containsKey(k)) continue;
map.put(k, j++);
}
SegmentTree seg = new SegmentTree(j + 1);
SegmentTree seg1 = new SegmentTree(j + 1);
BigInteger ans = BigInteger.ZERO;
BigInteger sum = BigInteger.ZERO;
// long ans = 0;
// long sum = 0;
for(int i = 0; i < n; i++){
long x = seg.get(0, j - 1, map.get(arr[i] - 1), map.get(arr[i] + 1), 1);
long y = seg1.get(0, j - 1, map.get(arr[i] - 1), map.get(arr[i] + 1), 1);
ans = ans.add(new BigInteger(""+x));
ans = ans.subtract(sum);
ans = ans.add(new BigInteger(""+((arr[i] * 1l *(i - y)))));
// ans += arr[i] * 1l * (i - y) - sum + x;
seg.update(0, j - 1, map.get(arr[i]), map.get(arr[i]), arr[i], 1);
seg1.update(0, j - 1, map.get(arr[i]), map.get(arr[i]), 1, 1);
sum = sum.add(new BigInteger(arr[i] + ""));
}
out.println(ans);
out.close();
}
static class Pair implements Comparable<Pair>
{
int x,y;
int i;
Pair (int x,int y)
{
this.x = x;
this.y = y;
}
Pair (int x,int y, int i)
{
this.x = x;
this.y = y;
this.i = i;
}
public int compareTo(Pair o)
{
return Long.compare(this.i,o.i);
//return 0;
}
public boolean equals(Object o)
{
if (o instanceof Pair)
{
Pair p = (Pair)o;
return p.x == x && p.y==y;
}
return false;
}
@Override
public String toString()
{
return x + " "+ y + " "+i;
}
/*public int hashCode()
{
return new Long(x).hashCode() * 31 + new Long(y).hashCode();
}*/
}
static long gcd(long x,long y)
{
if(y==0)
return x;
else
return gcd(y,x%y);
}
static int gcd(int x,int y)
{
if(y==0)
return x;
else
return gcd(y,x%y);
}
static long pow(long n,long p,long m)
{
long result = 1;
if(p==0){
return n;
}
while(p!=0)
{
if(p%2==1)
result *= n;
if(result >= m)
result %= m;
p >>=1;
n*=n;
if(n >= m)
n%=m;
}
return result;
}
static long pow(long n,long p)
{
long result = 1;
if(p==0)
return 1;
while(p!=0)
{
if(p%2==1)
result *= n;
p >>=1;
n*=n;
}
return result;
}
static void debug(Object... o)
{
System.out.println(Arrays.deepToString(o));
}
static class InputReader
{
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int snext()
{
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars)
{
curChar = 0;
try
{
snumChars = stream.read(buf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n)
{
int a[] = new int[n];
for (int i = 0; i < n; i++)
{
a[i] = nextInt();
}
return a;
}
public long[] nextLongArray(int n)
{
long a[] = new long[n];
for (int i = 0; i < n; i++)
{
a[i] = nextLong();
}
return a;
}
public String readString()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine()
{
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c)
{
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
}
| nlogn | 903_D. Almost Difference | CODEFORCES |
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Map.Entry;
import java.util.Collections;
import java.util.PriorityQueue;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
public class D {
public static class BIT {
long[] dat;
public BIT(int n){
dat = new long[n + 1];
}
public void add(int k, long a){ // k : 0-indexed
for(int i = k + 1; i < dat.length; i += i & -i){
dat[i] += a;
}
}
public long sum(int s, int t){ // [s, t)
if(s > 0) return sum(0, t) - sum(0, s);
long ret = 0;
for(int i = t; i > 0; i -= i & -i) {
ret += dat[i];
}
return ret;
}
}
public static void main(String[] args) {
try (final Scanner sc = new Scanner(System.in)) {
final int n = sc.nextInt();
long[] array = new long[n];
for(int i = 0; i < n; i++){ array[i] = sc.nextLong(); }
TreeSet<Long> value_set = new TreeSet<Long>();
for(int i = 0; i < n; i++){ value_set.add(array[i]); }
ArrayList<Long> value_list = new ArrayList<Long>(value_set);
BigInteger answer = BigInteger.ZERO;
final int bit_n = value_list.size();
BIT cnt_bit = new BIT(bit_n);
BIT val_bit = new BIT(bit_n);
for(int i = n - 1; i >= 0; i--){
final long value = array[i];
final int value_index = Collections.binarySearch(value_list, value);
int upper_pos = Collections.binarySearch(value_list, value + 2);
if(upper_pos < 0){ upper_pos = (-upper_pos) - 1; }
if(0 <= upper_pos && upper_pos < bit_n){
final long upper_sum = val_bit.sum(upper_pos, bit_n) - cnt_bit.sum(upper_pos, bit_n) * value;
answer = answer.add(BigInteger.valueOf(upper_sum));
}
int lower_pos = Collections.binarySearch(value_list, value - 2);
if(lower_pos < 0){ lower_pos = (-lower_pos) - 2; }
if(0 <= lower_pos && lower_pos < bit_n){
final long lower_sum = val_bit.sum(0, lower_pos + 1) - cnt_bit.sum(0, lower_pos + 1) * value;
answer = answer.add(BigInteger.valueOf(lower_sum));
}
cnt_bit.add(value_index, 1);
val_bit.add(value_index, value);
//System.out.println(answer);
}
System.out.println(answer);
}
}
public static class Scanner implements Closeable {
private BufferedReader br;
private StringTokenizer tok;
public Scanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
private void getLine() {
try {
while (!hasNext()) {
tok = new StringTokenizer(br.readLine());
}
} catch (IOException e) { /* ignore */
}
}
private boolean hasNext() {
return tok != null && tok.hasMoreTokens();
}
public String next() {
getLine();
return tok.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public void close() {
try {
br.close();
} catch (IOException e) { /* ignore */
}
}
}
}
| nlogn | 903_D. Almost Difference | CODEFORCES |
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class Main {
protected static final double EPS = 1e-11;
private static StreamTokenizer in;
private static Scanner ins;
private static PrintWriter out;
protected static final Double[] BAD = new Double[]{null, null};
private boolean[][] layouts;
private int c;
private int b;
private int a;
private String word;
public static void main(String[] args) {
try {
in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
ins = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(System.out);
try {
if (System.getProperty("xDx") != null) {
in = new StreamTokenizer(new BufferedReader(new FileReader("input.txt")));
ins = new Scanner(new FileReader("input.txt"));
out = new PrintWriter(new FileWriter("output.txt"));
}
} catch (Exception e) {
in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
ins = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(System.out);
}
new Main().run();
} catch (Throwable e) {
// e.printStackTrace();
throw new RuntimeException(e);
} finally {
out.close();
}
}
private int nextInt() throws IOException {
in.nextToken();
return (int) in.nval;
}
private long nextLong() throws IOException {
in.nextToken();
return (long) in.nval;
}
private double nextDouble() throws IOException {
in.nextToken();
return in.nval;
}
private String nextString() throws IOException {
in.nextToken();
return in.sval;
}
private char nextChar() throws IOException {
in.nextToken();
return (char) in.ttype;
}
private void run() throws Exception {
/*int t = nextInt();
for (int i = 0; i < t; i++) {
out.printf(Locale.US, "Case #%d: %d\n", i + 1, solve());
}*/
solve();
}
private void solve() throws IOException {
int n = nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
Map<Long, Integer> map = new HashMap<>();
BigInteger res = BigInteger.ZERO;
long sum = 0;
long amount = 0;
for (int i = n - 1; i >= 0; i--) {
long cur = a[i];
Pair same = getZeroAmount(cur, map);
res = res.add(BigInteger.valueOf((sum - same.sum) - cur * (amount - same.amount)));
amount++;
sum += cur;
map.put(cur, map.getOrDefault(cur, 0) + 1);
}
out.println(res);
}
class Pair {
long amount;
long sum;
public Pair(long amount, long sum) {
this.amount = amount;
this.sum = sum;
}
}
private Pair getZeroAmount(long cur, Map<Long, Integer> map) {
long amount = 0;
long sum = 0;
for (long i = cur - 1; i <= cur + 1; i++) {
long amountI = map.getOrDefault(i, 0);
amount += amountI;
sum += amountI * i;
}
return new Pair(amount, sum);
}
private List<Integer> iterate(List<Integer> a) {
ArrayList<Integer> b = new ArrayList<>();
int prev = -1;
for (int x : a) {
if (x == prev) {
b.add(x);
} else {
prev = x;
}
}
return b;
}
private long gcd(long a, long b) {
while (a > 0 && b > 0) {
long k = a % b;
a = b;
b = k;
}
return a | b;
}
} | nlogn | 903_D. Almost Difference | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.util.HashMap;
import java.math.BigInteger;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Liavontsi Brechka
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static
@SuppressWarnings("Duplicates")
class TaskD {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
long[] a = in.nextLongArray(n);
HashMap<Integer, Integer> count = new HashMap<>();
BigInteger res = BigInteger.ZERO;
long prev = 0;
count.put((int) a[0], 1);
long temp;
long nextRes;
for (int i = 1; i < n; i++) {
temp = ((a[i] - a[i - 1]) * i + prev);
nextRes = temp - count.getOrDefault((int) a[i] - 1, 0) + count.getOrDefault((int) a[i] + 1, 0);
res = res.add(new BigInteger(String.valueOf(nextRes)));
count.put((int) a[i], count.getOrDefault((int) a[i], 0) + 1);
prev = temp;
}
out.print(res);
}
}
static class InputReader {
private final BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream in) {
reader = new BufferedReader(new InputStreamReader(in));
}
public long[] nextLongArray(int size) {
long[] array = new long[size];
for (int i = 0; i < size; ++i) {
array[i] = nextLong();
}
return array;
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(readLine());
}
return tokenizer.nextToken();
}
public String readLine() {
String line;
try {
line = reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return line;
}
}
}
| nlogn | 903_D. Almost Difference | CODEFORCES |
//Educational Codeforces Round 34
import java.io.*;
import java.util.*;
import java.math.*;
public class TaskD {
public static void main (String[] args) throws IOException {
FastScanner fs = new FastScanner(System.in);
PrintWriter pw = new PrintWriter(new BufferedOutputStream(System.out));
int n = fs.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = fs.nextInt();
}
HashMap<Integer,Integer> h = new HashMap<Integer,Integer>(n);
BigInteger s = new BigInteger(""+a[0]);
BigInteger x = new BigInteger("0");
h.put(a[0], 1);
for (int i = 1; i < n; i++) {
x = x.add(new BigInteger(""+(((long)i)*((long)a[i]))));
x = x.subtract(s);
s = s.add(new BigInteger(""+a[i]));
Integer q = null;
q = h.get(a[i]-1);
if (q != null) {
x = x.subtract(new BigInteger(""+q));
}
q = h.get(a[i]+1);
if (q != null) {
x = x.add(new BigInteger(""+q));
}
q = h.get(a[i]);
if (q != null) {
h.put(a[i], q + 1);
} else {
h.put(a[i], 1);
}
}
pw.println(x);
pw.close();
}
static class FastScanner {
BufferedReader reader;
StringTokenizer tokenizer;
FastScanner(InputStream i) {
reader = new BufferedReader(new InputStreamReader(i));
tokenizer = new StringTokenizer("");
}
String next() throws IOException {
while(!tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(reader.readLine());
return tokenizer.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
}
} | nlogn | 903_D. Almost Difference | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.*;
public class CFD {
BufferedReader br;
PrintWriter out;
StringTokenizer st;
boolean eof;
final long MOD = 1000L * 1000L * 1000L + 7;
int[] dx = {0, -1, 0, 1};
int[] dy = {1, 0, -1, 0};
void solve() throws IOException {
int n = nextInt();
long[] arr = nextLongArr(n);
long[] diff = new long[n];
long presum = 0;
for (int i = n - 1; i >= 0; i--) {
diff[i] = presum - (n - i - 1) * arr[i];
presum += arr[i];
}
BigInteger pairs = new BigInteger("0");
for (long s : diff) {
pairs = pairs.add(new BigInteger(Long.toString(s)));
}
BigInteger need = new BigInteger("0");
Map<Long, Long> hm = new HashMap<>();
for (int i = n - 1; i >= 0; i--) {
long v1 = hm.getOrDefault(arr[i] - 1, 0L) * (-1);
need = need.add(new BigInteger(Long.toString(v1)));
long v2 = hm.getOrDefault(arr[i] + 1, 0L);
need = need.add(new BigInteger(Long.toString(v2)));
hm.put(arr[i], hm.getOrDefault(arr[i], 0L) + 1);
}
BigInteger res = pairs.subtract(need);
out(res.toString());
}
void shuffle(long[] a) {
int n = a.length;
for(int i = 0; i < n; i++) {
int r = i + (int) (Math.random() * (n - i));
long 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 CFD() 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 CFD();
}
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());
}
}
| nlogn | 903_D. Almost Difference | CODEFORCES |
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class DD {
public static void main(String[] args)throws Throwable {
MyScanner sc=new MyScanner();
PrintWriter pw=new PrintWriter(System.out);
int n=sc.nextInt();
int [] a=new int [n];
for(int i=0;i<n;i++)
a[i]=sc.nextInt();
TreeMap<Integer, Integer> map=new TreeMap<Integer, Integer>();
BigInteger ans=new BigInteger("0");
long sum=0;
for(int i=0;i<n;i++){
sum+=a[i];
map.put(a[i], map.getOrDefault(a[i], 0)+1);
int cntSame=map.get(a[i]);
int cntLess=map.getOrDefault(a[i]-1, 0);
int cntMore=map.getOrDefault(a[i]+1, 0);
long sum2=sum;
sum2-=1L*cntSame*a[i];
sum2-=1L*cntLess*(a[i]-1);
sum2-=1L*cntMore*(a[i]+1);
int cnt=i+1-(cntSame+cntLess+cntMore);
ans = ans.subtract(BigInteger.valueOf(sum2));
ans= ans.add(BigInteger.valueOf(1L*cnt*a[i]));
}
pw.println(ans);
pw.flush();
pw.close();
}
static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {while (st == null || !st.hasMoreElements()) {
try {st = new StringTokenizer(br.readLine());}
catch (IOException e) {e.printStackTrace();}}
return st.nextToken();}
int nextInt() {return Integer.parseInt(next());}
long nextLong() {return Long.parseLong(next());}
double nextDouble() {return Double.parseDouble(next());}
String nextLine(){String str = "";
try {str = br.readLine();}
catch (IOException e) {e.printStackTrace();}
return str;}
}
} | nlogn | 903_D. Almost Difference | CODEFORCES |
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.*;
public class D {
static HashMap<Long, Integer> comp = new HashMap<Long, Integer>();
static HashMap<Integer, Long> rev = new HashMap<Integer, Long>();
static long freq[];
public static void main(String[] args) {
FastScanner in = new FastScanner();
int n = in.nextInt();
long a[] = new long[n];
long copy[] = new long[n];
long sum = 0;
for(int i = 0; i < n; i++){
a[i] = in.nextLong();
copy[i] = a[i];
sum+=a[i];
}
Arrays.sort(copy);
for(int i = 0; i < n; i++) //Compress values to be 1-indexed
if(!comp.containsKey(copy[i])){
comp.put(copy[i], (comp.size()+1));
//rev.put(comp.get(copy[i]), copy[i]);
}
// BIT bit = new BIT(n);
freq = new long[n+1];
Arrays.fill(freq, 0);
for(int i = 0; i < n; i++){
int v = comp.get(a[i]);
freq[v]++;
}
long res = 0;
BigInteger res2 = new BigInteger("0");
for(int i = 0; i < n; i++){ //Go through each element in the array
long x = a[i];
//freq[comp.get(x)]--;
//Find the amount of values equal to (x-1), x, and (x+1);
long below = getFreq(x-1);
long eq = getFreq(x);
long above = getFreq(x+1);
long other = (n-i)-below-eq-above;
// System.out.println("x= "+x+" b:"+below+" e:"+eq+" a:"+above);
long leaveOut = below*(x-1) + eq*(x) + above*(x+1);
long cur = (sum-leaveOut)-(x*other);
// System.out.println("sum:"+sum+" leave:"+leaveOut+" oth:"+other+" cur:"+cur+"\n");
res2 = res2.add(new BigInteger(""+cur));
res += cur;
sum -= x;
freq[comp.get(x)]--;
}
System.out.println(res2);
}
static long getFreq(long n){
if(!comp.containsKey(n)) return 0;
else return freq[comp.get(n)];
}
static class FastScanner{
BufferedReader br;
StringTokenizer st;
public FastScanner(String s) {
try{
br = new BufferedReader(new FileReader(s));
}
catch(FileNotFoundException e) {
e.printStackTrace();
}
}
public FastScanner(){
br = new BufferedReader(new InputStreamReader(System.in));
}
String nextToken() {
while(st == null ||!st.hasMoreElements()){
try {
st = new StringTokenizer(br.readLine());}
catch(IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
String next() {
return nextToken();
}
}
}
| nlogn | 903_D. Almost Difference | CODEFORCES |
import java.util.*;
import java.io.*;
import java.math.BigInteger;
public class D {
FastScanner in;
PrintWriter out;
boolean systemIO = true;
public void solve() {
int n = in.nextInt();
HashMap<Long, Integer> map = new HashMap();
BigInteger sum = BigInteger.ZERO;
BigInteger ans = BigInteger.valueOf(0);
for (int i = 0; i < n; i++) {
long x = in.nextLong();
ans = ans.add(BigInteger.valueOf(i * x));
if (map.containsKey(x + 1)) {
ans = ans.add(BigInteger.valueOf(map.get(x + 1)));
}
if (map.containsKey(x - 1)) {
ans = ans.subtract(BigInteger.valueOf(map.get(x - 1)));
}
if (map.containsKey(x)) {
map.put(x, map.get(x) + 1);
} else {
map.put(x, 1);
}
ans = ans.subtract(sum);
sum = sum.add(BigInteger.valueOf(x));
}
out.print(ans.toString());
}
public void run() {
try {
if (systemIO) {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
} else {
in = new FastScanner(new File("segments.in"));
out = new PrintWriter(new File("segments.out"));
}
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f));
}
String nextLine() {
try {
return br.readLine();
} catch (IOException e) {
return null;
}
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
// AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
public static void main(String[] arg) {
new D().run();
}
} | nlogn | 903_D. Almost Difference | CODEFORCES |
import static java.util.Arrays.*;
import static java.lang.Math.*;
import static java.math.BigInteger.*;
import java.util.*;
import java.math.*;
import java.io.*;
public class Main implements Runnable {
boolean TEST = System.getProperty("ONLINE_JUDGE") == null;
void solve() throws IOException {
int n = nextInt();
Pair[] ps = new Pair[n];
for (int i = 0; i < n; i++) {
ps[i] = new Pair(nextInt(), i + 1);
}
sort(ps, new Comparator<Pair>() {
public int compare(Pair a, Pair b) {
return a.x - b.x;
}
});
BigInteger res = find(ps, n);
for (int i = 0; i * 2 < n; i++) {
Pair t = ps[i];
ps[i] = ps[n - i - 1];
ps[n - i - 1] = t;
}
res = res.add(find(ps, n));
out.println(res);
}
BigInteger find(Pair[] ps, int n) {
BigInteger res = ZERO;
int i = 0;
FenwickTree ft = new FenwickTree(n + 1);
boolean[] added = new boolean[n + 1];
for (int j = 0; j < n; j++) {
if (abs(ps[j].x - ps[i].x) <= 1) continue;
while (abs(ps[j].x - ps[i].x) > 1) {
if (!added[ps[i].i]) ft.add(ps[i].i, 1);
added[ps[i].i] = true;
i++;
}
i--;
long total = ft.sum(n);
long left = ft.sum(ps[j].i - 1);
long right = total - left;
res = res.add(valueOf(ps[j].x).multiply(valueOf(left)));
res = res.add(valueOf(-ps[j].x).multiply(valueOf(right)));
}
return res;
}
class Pair implements Comparable<Pair> {
int x, i;
Pair(int x, int i) {
this.x = x;
this.i = i;
}
public int compareTo(Pair p) {
return x - p.x;
}
public String toString() {
return "(" + x + ", " + i + ")";
}
}
class FenwickTree {
int n;
int[] tree;
public FenwickTree(int n) {
this.n = n;
tree = new int[n];
}
public int sum(int id) {
int res = 0;
while (id > 0) {
res += tree[id];
id -= id & -id;
}
return res;
}
public void add(int id, int v) {
while (id < n) {
tree[id] += v;
id += id & -id;
}
}
int findkth(int k) {
int low = 1, high = n;
while (low < high) {
int mid = (low + high) / 2;
int val = sum(mid);
if(val < k) low = mid + 1;
else high = mid;
}
return low;
}
}
String next() throws IOException {
while(st == null || !st.hasMoreTokens()) st = new StringTokenizer(input.readLine());
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
void debug(Object... o) {
System.out.println(deepToString(o));
}
void gcj(Object o) {
String s = String.valueOf(o);
out.println("Case #" + test + ": " + s);
System.out.println("Case #" + test + ": " + s);
}
BufferedReader input;
PrintWriter out;
StringTokenizer st;
int test;
void init() throws IOException {
if (TEST) input = new BufferedReader(new FileReader("input.in"));
else input = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new BufferedOutputStream(System.out));
//out = new PrintWriter(new BufferedWriter(new FileWriter("output.out")));
}
public static void main(String[] args) throws IOException {
new Thread(null, new Main(), "", 1 << 20).start();
}
public void run() {
try {
init();
if (TEST) {
int runs = nextInt();
for(int i = 0; i < runs; i++) solve();
} else solve();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
} | nlogn | 903_D. Almost Difference | CODEFORCES |
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class main
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
private PrintWriter pw;
private long mod = 1000000000 + 7;
private StringBuilder ans_sb;
private ArrayList<Integer> primes;
private long ans;
private void soln()
{
int n = nextInt();
long[] arr = new long[n];
for (int i = 0; i < n; i++)
arr[i] = nextLong();
Segment tree = new Segment(n, arr);
long[] ans = new long[n];
BigInteger fa = BigInteger.ZERO;
HashMap<Long, Integer> map = new HashMap<>();
for (int i = 0; i < n; i++)
{
ans[i] = ((long) i + 1) * arr[i] - tree.query(0, i);
if (map.containsKey(arr[i] - 1))
{
long tmp = map.get(arr[i] - 1);
ans[i] -= tmp;
}
if (map.containsKey(arr[i] + 1))
{
long tmp = map.get(arr[i] + 1);
ans[i] += tmp;
}
if (!map.containsKey(arr[i]))
map.put(arr[i], 0);
map.put(arr[i], map.get(arr[i]) + 1);
fa = fa.add(new BigInteger(Long.toString(ans[i])));
}
// debug(ans);
/*
* Node[] nn = new Node[n]; for(int i=0;i<n;i++) { nn[i] = new Node();
* nn[i].node = i; nn[i].dist = arr[i]; } //debug(fa); Arrays.sort(nn);
* //debug(nn); for(int i=0;i<n-1;i++) { if(nn[i].dist + 1 == nn[i+1].dist) {
* System.out.println(nn[i].node +" "+nn[i+1].node); if(nn[i].node >
* nn[i+1].node) { fa++; }else fa--; } }
*/
pw.println(fa.toString());
// int k = nextInt();
// int n = nextInt();
// String[] arr = new String[k];
// for(int i=0;i<k;i++)
// arr[i] = nextLine();
// HashSet<String> set1 = new HashSet<>();
// for(int i=0;i<k;i++)
// set1.add(arr[i]);
// if(set1.size() == 1) {
// String s = arr[0];
// pw.print(s.charAt(1));
// pw.print(s.charAt(0));
// for(int i=2;i<n;i++)
// pw.print(s.charAt(i));
// }else {
// String s1 = arr[0];
// set1.remove(arr[0]);
// HashSet<Integer>[] aa = new HashSet[set1.size()];
// ArrayList<String> set = new ArrayList<>();
// for(String s:set1)
// set.add(s);
// int k1 = 0;
// boolean f1 = false;
// for(String s:set) {
// aa[k1] = new HashSet<>();
// for(int i=0;i<n;i++)
// if(s1.charAt(i) != s.charAt(i))
// aa[k1].add(i);
// if(aa[k1].size() > 4) {
// pw.println(-1);
// f1 = true;
// }
// k1++;
// }
// //debug(set);
// char[] ch = s1.toCharArray();
//
// boolean[] f11 = new boolean[set.size()];
// int k2 = 0;
// for(String s:set) {
// int[] freq = new int[26];
// for(int i=0;i<n;i++)
// freq[s.charAt(i)-'a']++;
// boolean kuu = false;
// for(int i=0;i<26;i++)
// if(freq[i] >= 2) {
// kuu = true;
// break;
// }
// f11[k2] = true;
// k2++;
// }
// // debug(f11);
//
// for(int i=0;i<n;i++) {
// if(f1)
// break;
// for(int j=i+1;j<n;j++) {
// if(f1)
// break;
// //System.out.println(i+" "+j);
// char tmp = ch[i];
// ch[i] = ch[j];
// ch[j] = tmp;
// k1 = 0;
// HashSet<Integer> haha = new HashSet<>();
// boolean f = true;
// for(String s:set) {
// HashSet<Integer> indi = aa[k1];
// boolean h1 = false;
// boolean h2 = false;
// if(!indi.contains(i)) {
// indi.add(i);
// h1 = true;
// }
// if(!indi.contains(j)) {
// indi.add(j);
// h2 = true;
// }
// int cnt = 0;
// for(int ii:indi) {
// if(s.charAt(ii) != ch[ii])
// cnt++;
// }
// /*if(i==1 && j==3) {
// System.out.println(cnt+" "+i+" "+j+" "+s);
// debug(indi);
// }*/
// if(cnt > 2 ) {
// f = false;
// break;
// }
// if(cnt ==1 && !f11[k1]) {
// f = false;
// break;
// }
// if(h1)
// indi.remove(i);
// if(h2)
// indi.remove(j);
// k1++;
//
// }
// if(f) {
// for(int i1=0;i1<n;i1++) {
// pw.print(ch[i1]);
// }
// f1 = true;
// break;
// }
// tmp = ch[i];
// ch[i] = ch[j];
// ch[j] = tmp;
// }
// }
// if(!f1)
// pw.println(-1);
// }
}
public class Segment
{
private Node[] tree;
private boolean[] lazy;
private int size;
private int n;
private long[] base;
private class Node
{
private int l;
private int r;
private long ans;
private long ans2;
}
public Segment(int n, long[] arr)
{
this.base = arr;
int x = (int) (Math.ceil(Math.log(n) / Math.log(2)));
size = 2 * (int) Math.pow(2, x) - 1;
tree = new Node[size];
lazy = new boolean[size];
this.n = n;
// this.set = set1;
build(0, 0, n - 1);
}
public void build(int id, int l, int r)
{
if (l == r)
{
tree[id] = new Node();
tree[id].l = l;
tree[id].r = r;
tree[id].ans = base[l];
return;
}
int mid = (l + r) / 2;
build(2 * id + 1, l, mid);
build(2 * id + 2, mid + 1, r);
tree[id] = merge(tree[2 * id + 1], tree[2 * id + 2], l, r);
// System.out.println(l+" "+r+" "+tree[id].l+" "+tree[id].r+" "+tree[id].ans);
}
public Node merge(Node n1, Node n2, int l, int r)
{
Node ret = new Node();
if (n1 == null && n2 == null)
return null;
else if (n1 == null)
{
ret.ans = n2.ans;
}
else if (n2 == null)
{
ret.ans = n1.ans;
} else
{
ret.ans = n1.ans + n2.ans;
}
return ret;
}
public long query(int l, int r)
{
Node ret = queryUtil(l, r, 0, 0, n - 1);
if (ret == null)
{
return 0;
} else
return ret.ans;
}
private Node queryUtil(int x, int y, int id, int l, int r)
{
if (l > y || x > r)
return null;
if (x <= l && r <= y)
{
return tree[id];
}
int mid = l + (r - l) / 2;
// shift(id);
Node q1 = queryUtil(x, y, 2 * id + 1, l, mid);
Node q2 = queryUtil(x, y, 2 * id + 2, mid + 1, r);
return merge(q1, q2, Math.max(l, x), Math.min(r, y));
}
public void update(int x, int y, int c)
{
update1(x, y, c, 0, 0, n - 1);
}
private void update1(int x, int y, int colour, int id, int l, int r)
{
// System.out.println(l+" "+r+" "+x);
if (x > r || y < l)
return;
if (x <= l && r <= y)
{
if (colour != -1)
{
tree[id] = new Node();
tree[id].ans = 1;
} else
tree[id] = null;
return;
}
int mid = l + (r - l) / 2;
// shift(id);
if (y <= mid)
update1(x, y, colour, 2 * id + 1, l, mid);
else if (x > mid)
update1(x, y, colour, 2 * id + 2, mid + 1, r);
else
{
update1(x, y, colour, 2 * id + 1, l, mid);
update1(x, y, colour, 2 * id + 2, mid + 1, r);
}
tree[id] = merge(tree[2 * id + 1], tree[2 * id + 2], l, r);
}
public void print(int l, int r, int id)
{
if (l == r)
{
if (tree[id] != null)
System.out.println(l + " " + r + " " + tree[id].l + " " + tree[id].r + " " + tree[id].ans + " "
+ tree[id].ans2);
return;
}
int mid = l + (r - l) / 2;
print(l, mid, 2 * id + 1);
print(mid + 1, r, 2 * id + 2);
if (tree[id] != null)
System.out.println(
l + " " + r + " " + tree[id].l + " " + tree[id].r + " " + tree[id].ans + " " + tree[id].ans2);
}
public void shift(int id)
{
}
}
private class Node implements Comparable<Node>
{
int node;
long dist;
@Override
public int compareTo(Node arg0)
{
if (this.dist != arg0.dist)
return (int) (this.dist - arg0.dist);
return this.node - arg0.node;
}
public boolean equals(Object o)
{
if (o instanceof Node)
{
Node c = (Node) o;
return this.node == c.node && this.dist == c.dist;
}
return false;
}
public String toString()
{
return this.node + ", " + this.dist;
}
}
private void debug(Object... o)
{
System.out.println(Arrays.deepToString(o));
}
private long pow(long a, long b, long c)
{
if (b == 0)
return 1;
long p = pow(a, b / 2, c);
p = (p * p) % c;
return (b % 2 == 0) ? p : (a * p) % c;
}
private long gcd(long n, long l)
{
if (l == 0)
return n;
return gcd(l, n % l);
}
public static void main(String[] args) throws Exception
{
new Thread(null, new Runnable()
{
@Override
public void run()
{
new main().solve();
}
}, "1", 1 << 26).start();
}
public StringBuilder solve()
{
InputReader(System.in);
/*
* try { InputReader(new FileInputStream("C:\\Users\\hardik\\Desktop\\in.txt"));
* } catch(FileNotFoundException e) {}
*/
pw = new PrintWriter(System.out);
ans_sb = new StringBuilder();
soln();
pw.close();
// System.out.println(ans_sb);
return ans_sb;
}
public void InputReader(InputStream stream1)
{
stream = stream1;
}
private boolean isWhitespace(int c)
{
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c)
{
return c == '\n' || c == '\r' || c == -1;
}
private 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++];
}
private 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;
}
private 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;
}
private String nextToken()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private 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();
}
private int[] nextIntArray(int n)
{
int[] arr = new int[n];
for (int i = 0; i < n; i++)
{
arr[i] = nextInt();
}
return arr;
}
private long[] nextLongArray(int n)
{
long[] arr = new long[n];
for (int i = 0; i < n; i++)
{
arr[i] = nextLong();
}
return arr;
}
private void pArray(int[] arr)
{
for (int i = 0; i < arr.length; i++)
{
System.out.print(arr[i] + " ");
}
System.out.println();
return;
}
private void pArray(long[] arr)
{
for (int i = 0; i < arr.length; i++)
{
System.out.print(arr[i] + " ");
}
System.out.println();
return;
}
private boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
private char nextChar()
{
int c = read();
while (isSpaceChar(c))
c = read();
char c1 = (char) c;
while (!isSpaceChar(c))
c = read();
return c1;
}
private interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
} | nlogn | 903_D. Almost Difference | CODEFORCES |
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class D implements Runnable{
public static void main (String[] args) {new Thread(null, new D(), "_cf", 1 << 28).start();}
public void run() {
FastScanner fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
System.err.println("Go!");
int n = fs.nextInt();
Pair[] a = new Pair[n], b = new Pair[n];
for(int i = 0; i < n; i++) {
a[i] = new Pair(fs.nextInt(), i+1);
b[i] = new Pair(a[i].val, a[i].id);
}
Arrays.sort(a);
Fenwick_Tree ft = new Fenwick_Tree(n), ftFreq = new Fenwick_Tree(n);
BigInteger res = BigInteger.ZERO;
int[] update = new int[n];
int sum = 0;
for(int i = 0; i < n; i++) {
// System.out.println(sum + " " + a[i].val);
if(i + 1 == n || (i + 1 < n && a[i+1].val != a[i].val)) {
update[i] = sum+1;
sum = 0;
}
else {
sum++;
}
}
// System.out.println(Arrays.toString(update));
for(int i = 0; i < n; i++) {
int pos = a[i].id;
long val = a[i].val;
long right = ft.sum(n) - ft.sum(pos);
long freq = ftFreq.sum(n) - ftFreq.sum(pos);
// System.out.println(a[i].val + " " + a[i].id + " " + right + " " + freq);
res = add(res, right - (val * freq));
// res += right - (val * freq);
long left = ft.sum(pos);
freq = ftFreq.sum(pos);
res = add(res, (val * freq) - left);
// res += (val * freq) - left;
// System.out.println(a[i].val + " " + a[i].id + " " + left + " " + freq);
// System.out.println();
if(update[i] > 0) {
ft.update(pos, val);
ftFreq.update(pos, 1);
int ptr = i-1;
while(ptr >= 0 && update[ptr] == 0) {
ft.update(a[ptr].id, val);
ftFreq.update(a[ptr].id, 1);
ptr--;
}
}
}
HashMap<Integer, Integer> freq = new HashMap<>();
for(int i = n-1; i >= 0; i--) {
if(!freq.containsKey(b[i].val+1)) {
if(!freq.containsKey(b[i].val)) freq.put(b[i].val, 0);
freq.put(b[i].val, freq.get(b[i].val)+1);
continue;
}
long fr = freq.get(b[i].val+1);
// System.out.println(i + " " + b[i].val + " " + fr);
res = sub(res, fr * (b[i].val+1) - (fr * (b[i].val)));
// res -= (fr*(b[i].val+1)) - (fr*b[i].val);
if(!freq.containsKey(b[i].val)) freq.put(b[i].val, 0);
freq.put(b[i].val, freq.get(b[i].val)+1);
}
// System.out.println(res);
freq.clear();
for(int i = 0; i < n; i++) {
if(!freq.containsKey(b[i].val+1)) {
if(!freq.containsKey(b[i].val)) freq.put(b[i].val, 0);
freq.put(b[i].val, freq.get(b[i].val)+1);
continue;
}
long fr = freq.get(b[i].val+1);
// System.out.println(i + " " + b[i].val + " " + fr);
res = add(res, (fr*(b[i].val+1)) - (fr*b[i].val));
// res += (fr*(b[i].val+1)) - (fr*b[i].val);
if(!freq.containsKey(b[i].val)) freq.put(b[i].val, 0);
freq.put(b[i].val, freq.get(b[i].val)+1);
}
out.println(res);
out.close();
}
BigInteger add (BigInteger a, long b) {
BigInteger res = a.add(BigInteger.valueOf(b));
return res;
}
BigInteger sub (BigInteger a, long b) {
BigInteger res = a.subtract(BigInteger.valueOf(b));
return res;
}
class Pair implements Comparable<Pair> {
int val, id;
Pair (int a, int b) {
val = a;
id = b;
}
public int compareTo (Pair o) {
if(val == o.val) return Integer.compare(id, o.id);
return Integer.compare(o.val, val);
}
}
class Fenwick_Tree {
long[] bit;
int n;
public Fenwick_Tree(int a) {
n = a + 1;
bit = new long[n];
}
//Remember that when querying a sum to query the 1-based index of the value.
void update (int index, long val) {
while(index < n) {
bit[index] += val;
index += (index & (-index));
}
}
long sum (int index) {
long sum = 0;
while(index > 0) {
sum += bit[index];
index -= (index & (-index));
}
return sum;
}
}
void sort (int[] a) {
int n = a.length;
for(int i = 0; i < 1000; i++) {
Random r = new Random();
int x = r.nextInt(n), y = r.nextInt(n);
int temp = a[x];
a[x] = a[y];
a[y] = temp;
}
Arrays.sort(a);
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
// br = new BufferedReader(new FileReader("cases.in"));
st = new StringTokenizer("");
} catch (Exception e){e.printStackTrace();}
}
public String next() {
if (st.hasMoreTokens()) return st.nextToken();
try {st = new StringTokenizer(br.readLine());}
catch (Exception e) {e.printStackTrace();}
return st.nextToken();
}
public int nextInt() {return Integer.parseInt(next());}
public long nextLong() {return Long.parseLong(next());}
public double nextDouble() {return Double.parseDouble(next());}
public String nextLine() {
String line = "";
try {line = br.readLine();}
catch (Exception e) {e.printStackTrace();}
return line;
}
public Integer[] nextIntegerArray(int n) {
Integer[] a = new Integer[n];
for(int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
public int[] nextIntArray(int n) {
int[] a = new int[n];
for(int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
public char[] nextCharArray() {return nextLine().toCharArray();}
}
} | nlogn | 903_D. Almost Difference | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.FilterInputStream;
import java.io.BufferedInputStream;
import java.math.BigInteger;
import java.util.HashMap;
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);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
public void solve(int testNumber, ScanReader in, PrintWriter out) {
int n = in.scanInt();
BigInteger ans = new BigInteger("0");
long val, index, index1, index2;
long sum[] = new long[n];
val = in.scanInt();
HashMap<Long, Integer> hs = new HashMap<>();
hs.put(val, 1);
sum[0] = val;
for (int i = 1; i < n; i++) {
val = in.scanInt();
sum[i] += sum[i - 1];
sum[i] += val;
if (!hs.containsKey(val)) hs.put(val, 0);
hs.put(val, hs.get(val) + 1);
ans = ans.add(BigInteger.valueOf(((i + 1) * val) - sum[i]));
index = (hs.containsKey(val + 1)) ? hs.get(val + 1) : 0;
index1 = (hs.containsKey(val - 1)) ? hs.get(val - 1) : 0;
index2 = (hs.containsKey(val)) ? hs.get(val) : 0;
ans = ans.subtract(BigInteger.valueOf(((index + index1 + index2) * val) - ((index * (val + 1)) + (index1 * (val - 1)) + (index2 * (val)))));
}
out.println(ans);
}
}
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;
}
}
}
| nlogn | 903_D. Almost Difference | CODEFORCES |
import java.math.BigInteger;
import java.util.Scanner;
public class d {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int N = in.nextInt();
int[] arr = new int[N];
for(int n=0;n<N;n++){
arr[n] = in.nextInt();
}
Wavelet waveyMcWaveFace = new Wavelet(arr);
BigInteger bigSum = BigInteger.ZERO;
for(int n=0;n<N;n++){
// calculate the amount added for all j = n all at once
// it's a[j] - a[i]
// step one
// positive part
long amtPlus = arr[n] * (long)(waveyMcWaveFace.numValsBtwn(1, arr[n] - 2, 0, n)
+ waveyMcWaveFace.numValsBtwn(arr[n] + 2, 2147483647, 0, n));
// step two
// negative part
long amtMinus = waveyMcWaveFace.sumOfValsBtwn(1, arr[n] - 2, 0, n)
+ waveyMcWaveFace.sumOfValsBtwn(arr[n] + 2, 2147483647, 0, n);
// System.out.println(amtPlus+" "+amtMinus);
bigSum = bigSum.add(new BigInteger(""+(amtPlus - amtMinus)));
}
System.out.println(bigSum);
}
static class Wavelet{
int l = 2147483647, h = -2147483648;
int[] arr, ldex, hdex;
long[] sum;
Wavelet low = null, high = null;
Wavelet(int[] arr){
this.arr = arr;
for(int i : arr){
l = Math.min(l, i);
h = Math.max(h, i);
}
ldex = new int[arr.length + 1];
hdex = new int[arr.length + 1];
sum = new long[arr.length + 1];
int mid = l + (h - l) / 2;
for(int n = 0; n < arr.length; n++){
sum[n+1] = sum[n] + arr[n];
if(arr[n] > mid){
ldex[n+1] = ldex[n];
hdex[n+1] = hdex[n] + 1;
}
else{
ldex[n+1] = ldex[n] + 1;
hdex[n+1] = hdex[n];
}
}
if(l == h) return;
int[] larr = new int[ldex[arr.length]];
int[] harr = new int[hdex[arr.length]];
for(int n=0;n<arr.length;n++){
if(hdex[n] == hdex[n+1]){
larr[ldex[n]] = arr[n];
}
else{
harr[hdex[n]] = arr[n];
}
}
low = new Wavelet(larr);
high = new Wavelet(harr);
}
// range [ll, rr)
int kthLowest(int k, int ll, int rr){
if(l == h){
return arr[ll + k-1];
}
if(ldex[rr] - ldex[ll] >= k){
return low.kthLowest(k, ldex[ll], ldex[rr]);
}
return high.kthLowest(k - ldex[rr] + ldex[ll], hdex[ll], hdex[rr]);
}
// number of values in between [lo, hi] in range [ll, rr)
int numValsBtwn(int lo, int hi, int ll, int rr){
if(hi < lo) return 0;
if(lo <= l && h <= hi){
return rr - ll;
}
if(l == h) return 0;
if(hi < high.l){
return low.numValsBtwn(lo, hi, ldex[ll], ldex[rr]);
}
if(low.h < lo){
return high.numValsBtwn(lo, hi, hdex[ll], hdex[rr]);
}
return low.numValsBtwn(lo, hi, ldex[ll], ldex[rr])
+ high.numValsBtwn(lo, hi, hdex[ll], hdex[rr]);
}
// sum of values between [lo, hi] in range [ll, rr)
long sumOfValsBtwn(int lo, int hi, int ll, int rr){
if(lo <= l && h <= hi){
return sum[rr] - sum[ll];
}
if(l == h) return 0;
if(hi < high.l){
return low.sumOfValsBtwn(lo, hi, ldex[ll], ldex[rr]);
}
if(low.h < lo){
return high.sumOfValsBtwn(lo, hi, hdex[ll], hdex[rr]);
}
return low.sumOfValsBtwn(lo, hi, ldex[ll], ldex[rr])
+ high.sumOfValsBtwn(lo, hi, hdex[ll], hdex[rr]);
}
}
}
| nlogn | 903_D. Almost Difference | CODEFORCES |
/*
* PDPM IIITDM Jabalpur
* Asutosh Rana
*/
import java.util.*;
import java.io.*;
import java.math.*;
public class Main
{
long MOD = 1000000007;
InputReader in;BufferedReader br;PrintWriter out;
public static void main (String[] args) throws java.lang.Exception
{
Main solver = new Main();
solver.in = new InputReader(System.in);
solver.br = new BufferedReader(new InputStreamReader(System.in));
solver.out = new PrintWriter(System.out);
solver.solve();
solver.out.flush();
solver.out.close();
}
public void solve(){
int tc = 1;//in.readInt();
for(int cas=1;cas<=tc;cas++){
int N = in.readInt();
int[] A = new int[N];
in.readInt(A);
HashMap<Integer, Integer> H = new HashMap<>();
long sum = A[0], count = 1;
BigInteger B = BigInteger.ZERO;
H.put(A[0], 1);
for(int i=1;i<N;i++){
// res = res + (count*A[i] - sum);
B = B.add(BigInteger.valueOf(count*A[i]-sum));
if(!H.containsKey(A[i]))
H.put(A[i], 0);
H.put(A[i], H.get(A[i])+1);
if(H.containsKey(A[i]-1)){
int k = H.get(A[i]-1);
// res = res + (k*(A[i]-1) - k*A[i]);
B = B.add(BigInteger.valueOf((k*(A[i]-1) - k*A[i])));
}
if(H.containsKey(A[i]+1)){
int k = H.get(A[i]+1);
B = B.add(BigInteger.valueOf((k*(A[i]+1) - k*A[i])));
// res = res + (k*(A[i]+1) - k*A[i]);
}
// out.println(res);
sum+=A[i];count++;
}
// out.println("-1");
out.println(B);
}
}
}
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 void readInt(int[] A){
for(int i=0;i<A.length;i++)
A[i] = readInt();
}
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 void readLong(long[] A){
for(int i=0;i<A.length;i++)
A[i] = readLong();
}
public double readDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public char[] readCharA(){
return readString().toCharArray();
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
} | nlogn | 903_D. Almost Difference | CODEFORCES |
import java.io.*;
import java.math.*;
import java.util.*;
public class Main {
static Map<BigInteger, BigInteger> mp = new HashMap<BigInteger, BigInteger>();
public static void main(String[] args) {
mp.clear();
Scanner cin = new Scanner(new BufferedInputStream(System.in));
BigInteger n = cin.nextBigInteger();
BigInteger x = cin.nextBigInteger();
mp.put(x, BigInteger.ONE);
BigInteger sum = x;
BigInteger ans = BigInteger.ZERO;
for (int i = 2;i <= n.intValue(); i++) {
x=cin.nextBigInteger();
BigInteger tmp = x.multiply(BigInteger.valueOf(i-1)).subtract(sum);
if (mp.containsKey(x.subtract(BigInteger.ONE))) tmp = tmp.subtract(mp.get(x.subtract(BigInteger.ONE)));
if (mp.containsKey(x.add(BigInteger.ONE))) tmp = tmp.add(mp.get(x.add(BigInteger.ONE)));
ans = ans.add(tmp);
sum = sum.add(x);
BigInteger xx;
if (mp.containsKey(x)) xx = mp.get(x);
else xx = BigInteger.ZERO;
mp.put(x, xx.add(BigInteger.ONE));
}
System.out.println(ans);
}
}
| nlogn | 903_D. Almost Difference | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Map;
import java.math.BigInteger;
import java.io.BufferedReader;
import java.util.Collections;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author darkhan imangaliyev
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
MyReader in = new MyReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
public void solve(int testNumber, MyReader in, PrintWriter out) {
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; ++i) {
a[i] = in.nextInt();
}
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < n; ++i) {
if (map.containsKey(a[i])) {
map.put(a[i], map.get(a[i]) + 1);
} else {
map.put(a[i], 1);
}
}
List<Integer> compressed = new ArrayList<>();
compressed.add(-1);
compressed.add(Integer.MAX_VALUE);
compressed.addAll(map.keySet());
Collections.sort(compressed);
// System.out.println(compressed);
int N = compressed.size() + 10;
BIT count = new BIT(N);
BIT sum = new BIT(N);
BigInteger ret = BigInteger.ZERO;
for (int i = n - 1; i >= 0; --i) {
int l = findLeft(compressed, a[i] - 2);
int r = findRight(compressed, a[i] + 2);
long left = sum.sum(0, l);
long countLeft = count.sum(0, l);
long right = sum.sum(r, N);
long countRight = count.sum(r, N);
// System.out.println("b[i] = " + b[i]);
// System.out.println("l = " + l + ", r = " + r);
// System.out.println("left = " + left + ", right = " + right);
// System.out.println("countLeft = " + countLeft + ", countRight = " + countRight);
// System.out.println();
long t = (left - countLeft * a[i]) + (right - a[i] * countRight);
ret = ret.add(BigInteger.valueOf(t));
int x = Collections.binarySearch(compressed, a[i]);
sum.update(x, a[i]);
count.update(x, 1);
}
out.println(ret);
}
private int findLeft(List<Integer> a, int t) {
int lo = -1, hi = a.size();
while (hi - lo > 1) {
int m = lo + (hi - lo) / 2;
if (a.get(m) <= t) {
lo = m;
} else {
hi = m;
}
}
return lo;
}
private int findRight(List<Integer> a, int t) {
int lo = -1, hi = a.size();
while (hi - lo > 1) {
int m = lo + (hi - lo) / 2;
if (a.get(m) < t) {
lo = m;
} else {
hi = m;
}
}
return hi;
}
class BIT {
long[] tree;
public BIT(int n) {
tree = new long[n + 1];
}
public void update(int x, long d) {
while (x < tree.length) {
tree[x] += d;
x += x & -x;
}
}
public long sum(int l, int r) {
return sum(r) - sum(l - 1);
}
public long sum(int x) {
long sum = 0;
while (x > 0) {
sum += tree[x];
x -= x & -x;
}
return sum;
}
}
}
static class MyReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public MyReader(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());
}
}
}
| nlogn | 903_D. Almost Difference | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Map;
import java.util.Scanner;
import java.math.BigInteger;
import java.util.HashMap;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author ZYCSwing
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int n = in.nextInt();
int[] a = new int[n];
BigInteger sum = new BigInteger("0");
for (int i = 0; i < n; ++i) {
a[i] = in.nextInt();
long tmp = ((long) (2 * i + 1 - n)) * a[i];
sum = sum.add(BigInteger.valueOf(tmp));
}
Map<Integer, Integer> cnt = new HashMap<>();
for (int i = n - 1; i >= 0; --i) {
if (cnt.containsKey(a[i] + 1)) {
sum = sum.subtract(BigInteger.valueOf(cnt.get(a[i] + 1)));
}
if (cnt.containsKey(a[i] - 1)) {
sum = sum.add(BigInteger.valueOf(cnt.get(a[i] - 1)));
}
if (cnt.containsKey(a[i])) {
cnt.put(a[i], cnt.get(a[i]) + 1);
} else {
cnt.put(a[i], 1);
}
}
out.println(sum);
}
}
}
| nlogn | 903_D. Almost Difference | CODEFORCES |
import java.io.*;
import java.math.*;
import java.util.*;
public class Main1
{
private InputStream is;
private PrintWriter out;
static int MOD = (int)(1e9+7);
ArrayList<Integer>[] amp;
public static void main(String[] args) throws Exception
{
new Thread(null, new Runnable()
{
public void run()
{
try {
} catch (Exception e)
{
System.out.println(e);
}
}
}, "1", 1 << 26).start();
new Main1().soln();
}
char ch[][];
static ArrayList<Integer>[] g;
static ArrayList<Integer> ar[];
static long ok[];
static int phi[]=new int[500005];
void solve()
{
int n=ni();
int a[]=na(n);
long sum=0;
HashMap<Integer,Integer> hm=new HashMap();
BigInteger ans=(BigInteger.ZERO);
int count=0;
for(int i=n-1;i>=0;i--)
{
int tmp1=0;
int tmp2=0;
int tmp3=0;
if(hm.containsKey(a[i]))
tmp1=hm.get(a[i]);
if(hm.containsKey(a[i]+1))
tmp2=hm.get(a[i]+1);
if(hm.containsKey(a[i]-1))
tmp3=hm.get(a[i]-1);
long lol=sum;
lol-=((long)tmp1*(long)a[i]);
lol-=((long)tmp2*(long)(a[i]+1));
lol-=((long)tmp3*(long)(a[i]-1));
int fr=(count)-tmp1-tmp2-tmp3;
long fuck=(lol)-((long)fr*(long)a[i]);
ans=ans.add(BigInteger.valueOf(fuck));
if(!hm.containsKey(a[i]))
hm.put(a[i],1);
else
hm.put(a[i],hm.get(a[i])+1);
sum+=(long)a[i];
count++;
// System.out.println(ans+" "+tmp1+" "+tmp2+" "+tmp3+" "+lol);
}
out.println(ans);
}
public static long multiply(long a)
{
return a*10;
}
public static long query1(int v,int start,int end,int l,int r,int x)
{
if(r < start || end < l)
{
return Long.MAX_VALUE;
}
if(l <= start && end <= r)
{
return (tre[v]);
}
int mid = (start + end) / 2;
long p1 = query1(2*v, start, mid, l, r,x);
long p2 = query1(2*v+1, mid+1, end, l, r,x);
return Math.min(p1, p2);
}
public static void update1(int v,int tl,int tr,int index,long a2)
{
if(tl==tr)
{
tre[v]=a2;
}
else
{
int mid=(tl+tr)/2;
if(tl <= index &&index <= mid)
{
update1(2*v,tl, mid, index, a2);
}
else
{
update1(2*v+1,mid+1,tr, index, a2);
}
tre[v]=(Math.min(tre[2*v],tre[2*v+1]));
}
}
static boolean visited[][];
static int a[][];
public static long query(int v,int start,int end,int l,int r,int x)
{
if(r < start || end < l)
{
return 0;
}
if(l <= start && end <= r)
{
return (tre[v]);
}
int mid = (start + end) / 2;
long p1 = query(2*v, start, mid, l, r,x);
long p2 = query(2*v+1, mid+1, end, l, r,x);
return Math.max(p1, p2);
}
public static void update(int v,int tl,int tr,int index,long a2)
{
if(tl==tr)
{
tre[v]=a2;
}
else
{
int mid=(tl+tr)/2;
if(tl <= index &&index <= mid)
{
update(2*v,tl, mid, index, a2);
}
else
{
update(2*v+1,mid+1,tr, index, a2);
}
tre[v]=(Math.max(tre[2*v],tre[2*v+1]));
}
}
static long tre[]=new long[400005];
/* public static int find(int v,int start,int end,int l,int r)
{
if(r < start || end < l)
{
return Integer.MIN_VALUE;
}
if(l <= start && end <= r)
{
return (tre[v]);
}
int mid = (start + end) / 2;
int p1 = find(2*v, start, mid, l, r);
int p2 = find(2*v+1, mid+1, end, l, r);
return Math.max(p1, p2);
}
static int tre[]=new int[4000005];
public static void Update(int v,int tl,int tr,int index,int val)
{
if(tl==tr)
{
tre[v]=val;
}
else
{
int mid=(tl+tr)/2;
if(tl <= index &&index <= mid)
{
Update(2*v,tl, mid, index, val);
}
else
{
Update(2*v+1,mid+1,tr, index, val);
}
tre[v]=(Math.max(tre[2*v],tre[2*v+1]));
}
}
*/
boolean isPrime(int x)
{
if(x==0||x==1)
return false;
for(int i = 2;i*1L*i<=x;i++) if(x%i==0) return false;
return true;
}
int p ;
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 static long gcd(long a, long b){
if(b==0) return a;
return gcd(b,a%b);
}
class Pair1 implements Comparable<Pair1>{
long a;
long b;
long c;
Pair1(long x,long y,long z){
this.a=x;
this.b=y;
this.c=z;
}
public int hashCode() {
return Objects.hash();
}
@Override
public int compareTo(Pair1 arg0) {
return (int)(arg0.c-c);
}
}
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;
}
void soln() {
is = System.in;
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
}
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte() {
if (lenbuf == -1)
throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0)
return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b))
;
return b;
}
private double nd() {
return Double.parseDouble(ns());
}
private char nc() {
return (char) skip();
}
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(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 int[][] nm(int n, int m) {
int[][] map = new int[n][m];
for (int i = 0; i < n; i++)
{
for(int j=0;j<m;j++)
map[i][j]=ni();
}
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));
}
} | nlogn | 903_D. Almost Difference | CODEFORCES |
//package educational.round34;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Random;
public class D {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni();
int[] a = na(n);
int[] xs = new int[3*n];
for(int i = 0;i < n;i++){
xs[3*i] = a[i];
xs[3*i+1] = a[i]-1;
xs[3*i+2] = a[i]+1;
}
xs = shuffle(xs, new Random());
int[] imap = shrinkX(xs);
BigInteger ans = BigInteger.valueOf(0L);
{
int[] ft = new int[3*n+3];
for(int i = 0;i < n;i++){
int y = Arrays.binarySearch(imap, a[i]);
int num =
i - sumFenwick(ft, y + 1) + sumFenwick(ft, y - 2);
ans = ans.add(BigInteger.valueOf((long)a[i] * num));
addFenwick(ft, y, 1);
}
}
{
int[] ft = new int[3*n+3];
for(int i = n-1;i >= 0;i--){
int y = Arrays.binarySearch(imap, a[i]);
int num =
n-1-i - sumFenwick(ft, y + 1) + sumFenwick(ft, y - 2);
ans = ans.subtract(BigInteger.valueOf((long)a[i] * num));
addFenwick(ft, y, 1);
}
}
out.println(ans);
}
public static int sumFenwick(int[] ft, int i)
{
int sum = 0;
for(i++;i > 0;i -= i&-i)sum += ft[i];
return sum;
}
public static void addFenwick(int[] ft, int i, int v)
{
if(v == 0 || i < 0)return;
int n = ft.length;
for(i++;i < n;i += i&-i)ft[i] += v;
}
public static int[] 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; }
public static int[] shrinkX(int[] a) {
int n = a.length;
long[] b = new long[n];
for (int i = 0; i < n; i++)
b[i] = (long) a[i] << 32 | i;
Arrays.sort(b);
int[] ret = new int[n];
int p = 0;
ret[0] = (int) (b[0] >> 32);
for (int i = 0; i < n; i++) {
if (i > 0 && (b[i] ^ b[i - 1]) >> 32 != 0) {
p++;
ret[p] = (int) (b[i] >> 32);
}
a[(int) b[i]] = p;
}
return Arrays.copyOf(ret, p + 1);
}
void run() throws Exception
{
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new D().run(); }
private byte[] inbuf = new byte[1024];
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)); }
}
| nlogn | 903_D. Almost Difference | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.SplittableRandom;
import java.math.BigInteger;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Pradyumn
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
public void solve(int testNumber, FastReader in, PrintWriter out) {
int n = in.nextInt();
int[] a = in.nextIntArray(n);
int[] b = a.clone();
b = Arrays.copyOf(b, a.length + 2);
b[a.length] = 0;
b[a.length + 1] = (int) 2e9;
ArrayUtils.sort(b);
b = ArrayUtils.uniqueArray(b);
SegmentTreeSumL segmentTreeSumL = new SegmentTreeSumL(b.length + 1);
SegmentTreeSumL size = new SegmentTreeSumL(b.length + 1);
for (int i = 0; i < n; ++i) {
segmentTreeSumL.update(Arrays.binarySearch(b, a[i]), a[i]);
size.update(Arrays.binarySearch(b, a[i]), 1);
}
Debug debug = new Debug(out);
BigInteger sum = new BigInteger("0");
for (int i = 0; i < n; ++i) {
segmentTreeSumL.update(Arrays.binarySearch(b, a[i]), -a[i]);
size.update(Arrays.binarySearch(b, a[i]), -1);
int indG = ArrayUtils.LowerBound(b, a[i] + 2);
indG = Math.min(indG, b.length);
long s1 = size.getRangeSum(indG, b.length);
long sum1 = segmentTreeSumL.getRangeSum(indG, b.length);
//debug.tr("1", s1, sum1);
sum = sum.add(BigInteger.valueOf(sum1 - s1 * a[i]));
int indL = ArrayUtils.LowerBound(b, a[i] - 1) - 1;
indL = Math.max(0, indL);
long s2 = size.getRangeSum(0, indL);
long sum2 = segmentTreeSumL.getRangeSum(0, indL);
//debug.tr("2", s2, sum2);
sum = sum.add(BigInteger.valueOf(sum2 - s2 * a[i]));
}
out.println(sum.toString());
}
}
static class ArrayUtils {
public static int LowerBound(int[] a, int v) {
int high = a.length;
int low = -1;
while (high - low > 1) {
int mid = (high + low) >>> 1;
if (a[mid] >= v) {
high = mid;
} else {
low = mid;
}
}
return high;
}
public static int[] sort(int[] a) {
a = shuffle(a, new SplittableRandom());
Arrays.sort(a);
return a;
}
public static int[] shuffle(int[] a, SplittableRandom 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;
}
public static int[] uniqueArray(int[] a) {
int n = a.length;
int p = 0;
for (int i = 0; i < n; i++) {
if (i == 0 || a[i] != a[i - 1]) a[p++] = a[i];
}
return Arrays.copyOf(a, p);
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar;
private int pnumChars;
private FastReader.SpaceCharFilter filter;
public FastReader(InputStream stream) {
this.stream = stream;
}
private int pread() {
if (pnumChars == -1) {
throw new InputMismatchException();
}
if (curChar >= pnumChars) {
curChar = 0;
try {
pnumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (pnumChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = pread();
while (isSpaceChar(c))
c = pread();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = pread();
}
int res = 0;
do {
if (c == ',') {
c = pread();
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = pread();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = nextInt();
}
return array;
}
private boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
private static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class SegmentTreeSumL {
long[] lazy;
long[] seg;
long[] a;
int size;
int N;
public SegmentTreeSumL(long[] a) {
this.N = a.length;
size = 4 * N;
seg = new long[size];
lazy = new long[size];
this.a = a;
build(0, N - 1, 0);
}
public SegmentTreeSumL(int n) {
this.N = n;
size = 4 * N;
seg = new long[size];
lazy = new long[size];
}
private void build(int s, int e, int c) {
if (s == e) {
seg[c] = a[s];
return;
}
int m = (s + e) >>> 1;
build(s, m, 2 * c + 1);
build(m + 1, e, 2 * c + 2);
seg[c] = seg[2 * c + 1] + seg[2 * c + 2];
}
public void update(int index, int value) {
update(0, N - 1, 0, index, value);
}
private void update(int s, int e, int c, int index, int value) {
if (s == e) {
seg[c] += value;
return;
}
int m = (s + e) >>> 1;
if (index <= m) {
update(s, m, 2 * c + 1, index, value);
} else {
update(m + 1, e, 2 * c + 2, index, value);
}
seg[c] = seg[2 * c + 1] + seg[2 * c + 2];
}
public long getRangeSum(int l, int r) {
return getRangeSum(0, N - 1, 0, l, r);
}
private long getRangeSum(int s, int e, int c, int l, int r) {
if (s > e || l > r || l > e || r < s) return 0;
if (lazy[c] != 0) {
if (s != e) {
lazy[2 * c + 1] += lazy[c];
lazy[2 * c + 2] += lazy[c];
}
seg[c] += (e - s + 1) * (1L) * lazy[c];
lazy[c] = 0;
}
if (s == e) {
return seg[c];
}
if (s >= l && e <= r) {
return seg[c];
}
int m = (s + e) >>> 1;
return getRangeSum(s, m, 2 * c + 1, l, r)
+ getRangeSum(m + 1, e, 2 * c + 2, l, r);
}
}
static class Debug {
PrintWriter out;
boolean oj;
public Debug(PrintWriter out) {
oj = System.getProperty("ONLINE_JUDGE") != null;
this.out = out;
}
}
}
| nlogn | 903_D. Almost Difference | CODEFORCES |
import java.math.BigInteger;
import java.util.*;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class D {
public static void main(String[] args) {
init();
int n = in.nextInt();
long total = 0L;
int arr[] = new int[n+5];
Map<Integer, Integer> freq = new HashMap<>();
Map<Integer, Integer> kiri = new HashMap<>();
for (int i = 1; i <= n; ++i){
arr[i] = in.nextInt();
if (freq.containsKey(arr[i])) {
freq.put(arr[i], freq.get(arr[i])+1);
} else {
freq.put(arr[i], 1);
kiri.put(arr[i], 0);
}
total += (long)arr[i];
}
BigInteger ans = BigInteger.valueOf(0L);
for (int i = 1; i <= n - 1; ++i) {
kiri.put(arr[i], kiri.get(arr[i])+1);
total -= arr[i];
int cnt_kanan = n - i;
long temp = total;
int cnt_sama = freq.get(arr[i]) - kiri.get(arr[i]);
temp -= (cnt_sama)*(long)arr[i];
cnt_kanan -= (cnt_sama);
if (freq.containsKey(arr[i]-1)) {
int cnt_kurang = freq.get(arr[i]-1) - kiri.get(arr[i]-1);
cnt_kanan -= cnt_kurang;
temp -= (long) cnt_kurang * (long)(arr[i]-1);
}
if (freq.containsKey(arr[i]+1)) {
int cnt_lebih = freq.get(arr[i]+1) - kiri.get(arr[i]+1);
cnt_kanan -= cnt_lebih;
temp -= (long)(cnt_lebih) * (long)(arr[i]+1);
}
temp -= (long)cnt_kanan * (long)arr[i];
ans = ans.add(BigInteger.valueOf(temp));
}
out.println(ans.toString());
out.close();
}
/* PrintWriter and BufferedReader Template from Codeforces */
public static MyScanner in;
public static PrintWriter out;
public static void init() {
in = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out));
}
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
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;
}
}
} | nlogn | 903_D. Almost Difference | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
D903 solver = new D903();
solver.solve(1, in, out);
out.close();
}
static class D903 {
int N;
long ripple;
BigInteger tot;
long[] nums;
BigInteger[] cs;
public void solve(int testNumber, FastScanner s, PrintWriter out) {
N = s.nextInt();
nums = s.nextLongArray(N);
tot = new BigInteger("0");
cs = new BigInteger[N + 1];
cs[0] = new BigInteger("0");
ripple = 0;
for (int i = 1; i <= N; i++)
cs[i] = cs[i - 1].add(new BigInteger("" + nums[i - 1]));
for (int i = 1; i <= N; i++) {
long cur = nums[i - 1];
// out.printf("%d: cs %d, minus %d%n", i, (cs[N] - cs[i]), cur * (N - i));
tot = tot.add(cs[N].subtract(cs[i])).subtract(new BigInteger("" + (cur * (N - i))));
}
HashMap<Long, Integer> seen = new HashMap<>();
for (long i : nums) {
Integer lo = seen.get(i - 1);
Integer hi = seen.get(i + 1);
if (lo != null)
tot = tot.subtract(new BigInteger("" + lo));
if (hi != null)
tot = tot.add(new BigInteger("" + hi));
if (!seen.containsKey(i))
seen.put(i, 0);
seen.put(i, seen.get(i) + 1);
}
out.println(tot);
}
}
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;
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public String next() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long[] nextLongArray(int N) {
long[] ret = new long[N];
for (int i = 0; i < N; i++)
ret[i] = this.nextLong();
return ret;
}
}
}
| nlogn | 903_D. Almost Difference | CODEFORCES |
import java.util.*;
import java.io.*;
import java.math.*;
public class d {
public static void main(String[] args) throws IOException {
FastScanner in = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
long[] arr = new long[n];//in.nextLongArray(n);
for (int i = 0; i < n; i++) {
//if (i < n / 2) arr[i] = 1;
//else arr[i] = 1000000000;
arr[i] = in.nextLong();
}
long sum = 0;
long count = 0;
TreeSet<Long> ts = new TreeSet<>();
ts.add(1L);
long oo = 1000000000 + 100;
ts.add(oo);
for (long a : arr) {
a += 10;
ts.add(a);
ts.add(a - 2);
ts.add(a + 2);
}
long[] inds = new long[ts.size()];
int idx = 0;
for (long a : ts) {
inds[idx++] = a;
}
SuperBIT bit1 = new SuperBIT(inds);
SuperBIT bit2 = new SuperBIT(inds);
BigInteger ans = BigInteger.valueOf(0);
for (long a : arr) {
a += 10;
long countLess = bit1.queryCompr(1, a - 2);
long sumLess = bit2.queryCompr(1, a - 2);
long countMore = bit1.queryCompr(a + 2, oo);
long sumMore = bit2.queryCompr(a + 2, oo);
//System.out.println(a + " " + countLess + " " + sumLess + " " + countMore + " " + sumMore);
bit1.updateCompr(a, 1);
bit2.updateCompr(a, a);
long tmp = 0;
tmp += countLess * a - sumLess;
tmp -= sumMore - countMore * a;
ans = ans.add(BigInteger.valueOf(tmp));
}
out.println(ans);
out.close();
}
static class SuperBIT {
long[] dataMul, dataAdd;
SuperBIT(int n) {
dataMul = new long[n];
dataAdd = new long[n];
}
void update(int left, int right, long val) {
internalUpdate(left, val, -val * (left-1));
internalUpdate(right, -val, val * right);
}
void internalUpdate(int at, long mul, long add) {
while (at < dataMul.length) {
dataMul[at] += mul;
dataAdd[at] += add;
at |= (at + 1);
}
}
long query(int at) {
long mul = 0;
long add = 0;
int start = at;
while(at >= 0) {
mul += dataMul[at];
add += dataAdd[at];
at = (at & (at + 1)) -1;
}
return mul * start + add;
}
long query(int left, int right) {
if (left > right) {
int temp = left;
left = right;
right = temp;
}
return query(right) - (left > 0 ? query(left-1) : 0);
}
long[] indices; // Used for compressed BIT
// Compressed BIT constructor
// A BIT that only stores the values that will be updated.
// indices is a sorted array of all the unique indices
// that would be used for this BIT.
public SuperBIT(long[] indices) {
this.indices = indices;
dataMul = new long[indices.length];
dataAdd = new long[indices.length];
}
// Search for the index in the array. If the index was not found,
// return the first index lower than the search index.
int binSearch(long ind) {
int low = 0;
int high = dataMul.length-1;
while(low < high) {
int mid = (low + high+1)/2;
if(indices[mid] == ind)
return mid;
else if(indices[mid] < ind)
low = mid;
else if(indices[mid] > ind)
high = mid-1;
}
if(indices[low] > ind)
--low;
return low;
}
// Read the largest index less than or equal to the given index.
long queryCompr(long index) {
return query(binSearch(index));
}
long queryCompr(long left, long right) {
return query(binSearch(left), binSearch(right));
}
// Update a specific index by a value. If the index is not in this
// compressed BIT, the index below will be updated.
void updateCompr(long index, long val) {
int ind = binSearch(index);
update(ind, ind, val);
}
void updateCompr(long left, long right, long val) {
update(binSearch(left), binSearch(right), val);
}
}
static Random rand = new Random();
static void sort(int[] a) {
int n = a.length;
for (int i = a.length - 1; i > 0; i--) {
int j = rand.nextInt(i + 1);
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
Arrays.sort(a);
}
static void sort(long[] a) {
int n = a.length;
for (int i = a.length - 1; i > 0; i--) {
int j = rand.nextInt(i + 1);
long tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
Arrays.sort(a);
}
static void sort(double[] a) {
int n = a.length;
for (int i = a.length - 1; i > 0; i--) {
int j = rand.nextInt(i + 1);
double tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
Arrays.sort(a);
}
static long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); }
static long lcm(long a, long b) { return a / gcd(a, b) * b; }
static long[] eEuclid(long a, long b) {
if (b == 0) return new long[] { a, 1, 0 };
long[] ans = eEuclid(b, a % b);
long temp = ans[1] - ans[2] * (a / b);
ans[1] = ans[2]; ans[2] = temp;
return ans;
}
static long modInverse(long a, long m) {
return ((eEuclid(a, m)[1] % m) + m) % m;
}
static class IntList {
static int[] EMPTY = {};
int[] a = EMPTY;
int n = 0;
void add(int v) {
if (n >= a.length)
a = Arrays.copyOf(a, (n << 2) + 8);
a[n++] = v;
}
int get(int idx) {
return a[idx];
}
int size() {
return n;
}
}
static class DisjointSet {
int[] s, r;
public DisjointSet(int n) {
s = new int[n]; r = new int[n];
for (int i = 0; i < n; i++) s[i] = i;
}
public int find(int i) { return s[i] == i ? i : (s[i] = find(s[i])); }
public void union(int a, int b) {
if(r[a = find(a)] == r[b = find(b)]) r[a]++;
if(r[a] >= r[b]) s[b] = a; else s[a] = b;
}
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream i) {
br = new BufferedReader(new InputStreamReader(i));
st = new StringTokenizer("");
}
public String next() throws IOException {
if(st.hasMoreTokens())
return st.nextToken();
else
st = new StringTokenizer(br.readLine());
return next();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public int[] nextOffsetIntArray(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = nextInt() - 1;
return arr;
}
public int[] nextIntArray(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = nextInt();
return arr;
}
public int[][] nextIntArray(int n, int m) throws IOException {
int[][] arr = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
arr[i][j] = nextInt();
return arr;
}
public long[] nextLongArray(int n) throws IOException {
long[] arr = new long[n];
for (int i = 0; i < n; i++)
arr[i] = nextLong();
return arr;
}
public long[][] nextLongArray(int n, int m) throws IOException {
long[][] arr = new long[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
arr[i][j] = nextLong();
return arr;
}
public double[] nextDoubleArray(int n) throws IOException {
double[] arr = new double[n];
for (int i = 0; i < n; i++)
arr[i] = nextDouble();
return arr;
}
public double[][] nextDoubleArray(int n, int m) throws IOException {
double[][] arr = new double[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
arr[i][j] = nextDouble();
return arr;
}
public char[][] nextCharArray(int n, int m) throws IOException {
char[][] arr = new char[n][];
for (int i = 0; i < n; i++)
arr[i] = next().toCharArray();
return arr;
}
}
}
| nlogn | 903_D. Almost Difference | CODEFORCES |
/**
* Created by Aminul on 12/12/2017.
*/
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class CF903D {
public static void main(String[] args) throws Exception {
FastReader in = new FastReader(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = in.nextInt();
int a[] = new int[n+1];
int b[] = new int[n+1];
TreeSet<Integer> set = new TreeSet<>();
for(int i = 1; i <= n; i++){
a[i] = in.nextInt();
set.add(a[i]);
}
int k = 0;
HashMap<Integer, Integer> map = new HashMap<>();
int last = set.first();
for(int i : set){
if(i - last > 1) k += 2;
else k += 1;
map.put(i, k);
last = i;
}
for(int i = 1; i <= n; i++){
b[i] = map.get(a[i]);
}
BinaryIndexTree bit = new BinaryIndexTree(k);
BinaryIndexTree freq = new BinaryIndexTree(k);
BigInteger res = BigInteger.ZERO;
for(int i = n; i >= 1; i--){
long l = bit.query(1, b[i]-2), r = bit.query(b[i]+2, k);
long lf = freq.query(1, b[i]-2), rf = freq.query(b[i]+2, k);
res = res.add(BigInteger.valueOf(r));
res = res.add(BigInteger.valueOf(l));
res = res.subtract(BigInteger.valueOf(rf*a[i]));
res = res.subtract(BigInteger.valueOf(lf*a[i]));
bit.add(b[i], a[i]);
freq.add(b[i], 1);
}
pw.println(res);
pw.close();
}
static class BinaryIndexTree{
public long bit[];
int n, len;
public BinaryIndexTree(int nn){
n = nn;
bit = new long[n+1];
len = bit.length;
}
public void add(int index, long value){
for(; index < len;index = index + ( index & -index)){
bit[index] += value;
}
}
public long sum(int index){
if(index <= 0) return 0;
long sum = 0;
for(; index > 0;index = index - (index & -index)){
sum += bit[index];
}
return sum;
}
public long query(int i, int j){
if(j < i) return 0;
return sum(j) - sum(i-1);
}
}
static void debug(Object... obj) {
System.err.println(Arrays.deepToString(obj));
}
static class FastReader {
InputStream is;
private byte[] inbuf = new byte[1024];
private int lenbuf = 0, ptrbuf = 0;
static final int ints[] = new int[128];
public FastReader(InputStream is) {
for (int i = '0'; i <= '9'; i++) ints[i] = i - '0';
this.is = is;
}
public 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++];
}
public boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
public int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b)) ;
return b;
}
public 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();
}
public int nextInt() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = (num << 3) + (num << 1) + ints[b];
} else {
return minus ? -num : num;
}
b = readByte();
}
}
public 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 << 3) + (num << 1) + ints[b];
} else {
return minus ? -num : num;
}
b = readByte();
}
}
public double nextDouble() {
return Double.parseDouble(next());
}
/* public char nextChar() {
return (char)skip();
}*/
public 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);
}
/*private char buff[] = new char[1005];
public char[] nextCharArray(){
int b = skip(), p = 0;
while(!(isSpaceChar(b))){
buff[p++] = (char)b;
b = readByte();
}
return Arrays.copyOf(buff, p);
}*/
}
} | nlogn | 903_D. Almost Difference | CODEFORCES |
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.StringTokenizer;
public class D
{
public static void main(String[] args) throws IOException
{
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
BigInteger ans = BigInteger.ZERO;
int n = sc.nextInt();
int arr[] = new int[n];
long cum[] = new long[n];
for (int i = 0; i < n; i++)
arr[i] = sc.nextInt();
// int n=(int)2e5;
// for(int i=0;i<n;i++){
// arr[i]=1;
// if(i>n/2)
// arr[i]=(int)1e9;
// }
for (int i = 0; i < cum.length; i++)
{
cum[i] = arr[i];
if(i > 0)
cum[i] += cum[i-1];
}
for (int i = 0; i < n; i++)
ans = ans.add(BigInteger.valueOf((1l*(i+1)*arr[i] - cum[i])));
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < n; i++)
{
ans = ans.subtract(BigInteger.valueOf(map.getOrDefault(arr[i]-1, 0)));
ans = ans.add(BigInteger.valueOf(map.getOrDefault(arr[i]+1, 0)));
map.put(arr[i], map.getOrDefault(arr[i], 0)+1);
}
pw.println(ans);
pw.flush();
pw.close();
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s)
{
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(String s) throws FileNotFoundException
{
br = new BufferedReader(new FileReader(new File((s))));
}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException
{
return Integer.parseInt(next());
}
public long nextLong() throws IOException
{
return Long.parseLong(next());
}
public String nextLine() throws IOException
{
return br.readLine();
}
public double nextDouble() throws IOException
{
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-')
{
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.')
{
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else
{
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public boolean ready() throws IOException
{
return br.ready();
}
}
}
| nlogn | 903_D. Almost Difference | CODEFORCES |
import java.math.BigDecimal;
import java.util.*;
import java.math.BigInteger;
public class Main {
static Long[] a = new Long[205000];
static Long[] postfix=new Long[205000];
static HashMap<Long,Long> check=new HashMap<Long,Long>();
public static void main(String args[]) {
Scanner cin = new Scanner(System.in);
long k, j, p,sum,equal,bigone,lessone,cnt;
BigInteger ans;
int i,n;
while (cin.hasNext()) {
n=cin.nextInt();
check.clear();
for(i=1;i<=n;i++)
{
a[i]=cin.nextLong();
}
postfix[n+1]=0L;
for(i=n;i>=1;i--) {
postfix[i] = postfix[i + 1] + a[i];
if (check.containsKey(a[i]) == true) {
Long v = check.get(a[i]);
v += 1;
check.put(a[i], v);
}
else
check.put(a[i],1L);
}
ans=BigInteger.ZERO;
for(i=1;i<n;i++){
Long v=check.get(a[i]);
v--;
check.put(a[i],v);
equal=check.get(a[i]);
bigone=0L;
lessone=0L;
if(check.containsKey(a[i]+1L)==true)
bigone=check.get(a[i]+1L);
if(check.containsKey(a[i]-1L)==true)
lessone=check.get(a[i]-1L);
sum=postfix[i]-bigone*(a[i]+1L)-lessone*(a[i]-1L)-equal*a[i]-a[i];
cnt=n-i-bigone-lessone-equal;
ans=ans.add(BigInteger.valueOf(a[i]*cnt).subtract(BigInteger.valueOf(sum)));
}
System.out.println(ans.multiply(BigInteger.valueOf(-1)));
}
}
} | nlogn | 903_D. Almost Difference | CODEFORCES |
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class Main {
protected static final double EPS = 1e-11;
private static StreamTokenizer in;
private static Scanner ins;
private static PrintWriter out;
protected static final Double[] BAD = new Double[]{null, null};
private boolean[][] layouts;
private int c;
private int b;
private int a;
private String word;
public static void main(String[] args) {
try {
in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
ins = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(System.out);
try {
if (System.getProperty("xDx") != null) {
in = new StreamTokenizer(new BufferedReader(new FileReader("input.txt")));
ins = new Scanner(new FileReader("input.txt"));
out = new PrintWriter(new FileWriter("output.txt"));
}
} catch (Exception e) {
in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
ins = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(System.out);
}
new Main().run();
} catch (Throwable e) {
// e.printStackTrace();
throw new RuntimeException(e);
} finally {
out.close();
}
}
private int nextInt() throws IOException {
in.nextToken();
return (int) in.nval;
}
private long nextLong() throws IOException {
in.nextToken();
return (long) in.nval;
}
private double nextDouble() throws IOException {
in.nextToken();
return in.nval;
}
private String nextString() throws IOException {
in.nextToken();
return in.sval;
}
private char nextChar() throws IOException {
in.nextToken();
return (char) in.ttype;
}
private void run() throws Exception {
/*int t = nextInt();
for (int i = 0; i < t; i++) {
out.printf(Locale.US, "Case #%d: %d\n", i + 1, solve());
}*/
solve();
}
private void solve() throws IOException {
int n = ins.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = ins.nextInt();
}
Map<Long, Integer> map = new HashMap<>();
BigInteger res = BigInteger.ZERO;
long sum = 0;
long amount = 0;
for (int i = n - 1; i >= 0; i--) {
long cur = a[i];
Pair same = getZeroAmount(cur, map);
res = res.add(BigInteger.valueOf((sum - same.sum) - cur * (amount - same.amount)));
amount++;
sum += cur;
map.put(cur, map.getOrDefault(cur, 0) + 1);
}
out.println(res);
}
class Pair {
long amount;
long sum;
public Pair(long amount, long sum) {
this.amount = amount;
this.sum = sum;
}
}
private Pair getZeroAmount(long cur, Map<Long, Integer> map) {
long amount = 0;
long sum = 0;
for (long i = cur - 1; i <= cur + 1; i++) {
long amountI = map.getOrDefault(i, 0);
amount += amountI;
sum += amountI * i;
}
return new Pair(amount, sum);
}
private List<Integer> iterate(List<Integer> a) {
ArrayList<Integer> b = new ArrayList<>();
int prev = -1;
for (int x : a) {
if (x == prev) {
b.add(x);
} else {
prev = x;
}
}
return b;
}
private long gcd(long a, long b) {
while (a > 0 && b > 0) {
long k = a % b;
a = b;
b = k;
}
return a | b;
}
} | nlogn | 903_D. Almost Difference | CODEFORCES |
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.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
public class Main {
static void insert(TreeMap<Integer, Integer>map,int v,int d)
{
if(!map.containsKey(v))map.put(v, 0);
map.put(v, d+map.get(v));
if(map.get(v)==0)map.remove(v);
}
static void cut(TreeSet<Integer> cuts, TreeMap<Integer, Integer>segments,int v)
{
int upper = cuts.higher(v) , lower = cuts.lower(v);
insert(segments, upper-lower, -1);
insert(segments, upper-v, 1);
insert(segments, v-lower, 1);
cuts.add(v);
}
public static void main(String[] args) throws Throwable {
Scanner sc = new Scanner(System.in);
int w = sc.nextInt(), h = sc.nextInt() , n = sc.nextInt();
TreeSet<Integer> vCuts = new TreeSet<>() , hCuts = new TreeSet<>();
TreeMap<Integer, Integer> vSegments = new TreeMap<>() , hSegments = new TreeMap<>();
vCuts.add(0);vCuts.add(w);
hCuts.add(0);hCuts.add(h);
insert(vSegments, w, 1);
insert(hSegments, h, 1);
StringBuilder sb = new StringBuilder();
while(n-->0)
{
if(sc.next().equals("H"))
cut(hCuts, hSegments, sc.nextInt());
else
cut(vCuts, vSegments, sc.nextInt());
sb.append(1l*hSegments.lastKey() * vSegments.lastKey() + "\n");
}
System.out.println(sb);
}
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 int[] nexIntArray() throws Throwable {
st = new StringTokenizer(br.readLine());
int[] a = new int[st.countTokens()];
for (int i = 0; i < a.length; i++)a[i] = nextInt();
return a;
}
public boolean ready() throws IOException {return br.ready();}
}
} | nlogn | 528_A. Glass Carving | CODEFORCES |
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
public class A {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = sc.nextInt();
int[] a = new int[n];
int sum = 0;
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
sum += a[i];
}
for (int i = 0; i < n; i++)
a[i] *= -1;
Arrays.sort(a);
for (int i = 0; i < n; i++)
a[i] *= -1;
int ans = 0;
int sum1 = 0;
for (int i = 0; i < n; i++) {
sum1 += a[i];
sum -= a[i];
ans++;
if (sum1 > sum)
break;
}
pw.print(ans);
pw.close();
}
}
| nlogn | 160_A. Twins | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.*;
public class A {
private void solve() throws IOException {
int n = nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
Arrays.sort(a);
int sum = 0;
for (int i = a.length - 1; i >= 0; i--) {
sum += a[i];
int k = 0;
for (int j = 0; j < i; j++)
k += a[j];
if (sum > k) {
pl(a.length - i);
return;
}
}
}
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));
tokenizer = null;
writer = new PrintWriter(System.out);
solve();
reader.close();
writer.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());
}
BigInteger nextBigInteger() throws IOException {
return new BigInteger(nextToken());
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
void p(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.flush();
writer.print(objects[i]);
writer.flush();
}
}
void pl(Object... objects) {
p(objects);
writer.flush();
writer.println();
writer.flush();
}
int cc;
void pf() {
writer.printf("Case #%d: ", ++cc);
writer.flush();
}
}
| nlogn | 160_A. Twins | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Test {
static BufferedReader reader;
static StringTokenizer tokenizer;
static PrintWriter writer;
static int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
static long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
static double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
static String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
public static void main(String[] args) throws IOException {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
writer = new PrintWriter(System.out);
solve();
reader.close();
writer.close();
}
private static void solve() throws IOException {
int n = nextInt();
int[] mas = new int[n];
int sum=0;
for(int i=0;i<n;i++)
{
mas[i]=nextInt();
sum+=mas[i];
}
Arrays.sort(mas);
int cs=0;
int res=0;
for(int i=n-1;i>=0;i--)
{
cs+=mas[i];
sum-=mas[i];
res++;
if(cs>sum)
break;
}
writer.println(res);
}
} | nlogn | 160_A. Twins | CODEFORCES |
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(), sum = 0;
Integer[] A = new Integer[n];
for (int i = 0 ; i < n ; i++) {
A[i] = sc.nextInt();
sum += A[i];
}
Arrays.sort(A, Collections.reverseOrder());
int c = 0, ans = 0;
while (ans <= sum) {
ans += A[c];
sum -= A[c];
c++;
}
System.out.println(c);
}
}
| nlogn | 160_A. Twins | CODEFORCES |
import java.util.Arrays;
import java.util.Scanner;
import static java.lang.Math.*;
public class a111 {
public static void debug(Object... obs) {
System.out.println(Arrays.deepToString(obs));
}
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
int[]a=new int[n];
int su=0;
for(int i=0;i<n;i++)
{
a[i]=-sc.nextInt();
su+=-1*a[i];
}
Arrays.sort(a);
int ss=0;
for(int i=0;i<n;i++)
{
ss+=-1*a[i];
su-=-1*a[i];
if(ss > su)
{
System.out.println(i+1);
return;
}
}
}
}
| nlogn | 160_A. Twins | CODEFORCES |
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Arrays;
/**
* Works good for CF
*
* @author cykeltillsalu
*/
public class A111_div2 {
// some local config
static boolean test = false;
static String testDataFile = "testdata.txt";
static String feedFile = "feed.txt";
CompetitionType type = CompetitionType.CF;
private static String ENDL = "\n";
// solution
private void solve() throws Throwable {
int n = iread();
int[] vals = new int[n];
double tot = 0;
for (int i = 0; i < n; i++) {
int value = iread();
vals[i] = value;
tot += value;
}
Arrays.sort(vals);
int pick = 0;
int worth = 0;
for (int i = vals.length - 1; i >= 0; i--) {
worth += vals[i];
pick ++;
if(worth > tot/2.0d){
break;
}
}
out.write(pick + ENDL);
out.flush();
}
public int iread() throws Exception {
return Integer.parseInt(wread());
}
public double dread() throws Exception {
return Double.parseDouble(wread());
}
public long lread() throws Exception {
return Long.parseLong(wread());
}
public String wread() throws IOException {
StringBuilder b = new StringBuilder();
int c;
c = in.read();
while (c >= 0 && c <= ' ')
c = in.read();
if (c < 0)
return "";
while (c > ' ') {
b.append((char) c);
c = in.read();
}
return b.toString();
}
public static void main(String[] args) throws Throwable {
if (test) { // run all cases from testfile:
BufferedReader testdataReader = new BufferedReader(new FileReader(testDataFile));
String readLine = testdataReader.readLine();
int casenr = 0;
out: while (true) {
BufferedWriter w = new BufferedWriter(new FileWriter(feedFile));
if (!readLine.equals("input")) {
break;
}
while (true) {
readLine = testdataReader.readLine();
if (readLine.equals("output")) {
break;
}
w.write(readLine + "\n");
}
w.close();
System.out.println("Answer on case " + (++casenr) + ": ");
new A111_div2().solve();
System.out.println("Expected answer: ");
while (true) {
readLine = testdataReader.readLine();
if (readLine == null) {
break out;
}
if (readLine.equals("input")) {
break;
}
System.out.println(readLine);
}
System.out.println("----------------");
}
testdataReader.close();
} else { // run on server
new A111_div2().solve();
}
out.close();
}
public A111_div2() throws Throwable {
if (test) {
in = new BufferedReader(new FileReader(new File(feedFile)));
}
}
InputStreamReader inp = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(inp);
static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
enum CompetitionType {
CF, OTHER
};
} | nlogn | 160_A. Twins | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Scanner;
public class AAA {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] array = new int[n];
int sum = 0;
for (int i = 0; i < n; i++) {
array[i] = sc.nextInt();
sum += array[i];
}
int counter = 0;
Arrays.sort(array);
int first = 0;
for (int j = n - 1; j >= 0; j--) {
first += array[j];
sum -= array[j];
counter++;
if (first > sum) {
break;
}
}
System.out.println(counter);
}
} | nlogn | 160_A. Twins | CODEFORCES |
import java.io.*;
import java.security.SecureRandom;
import java.util.*;
import java.math.*;
import java.awt.geom.*;
import static java.lang.Math.*;
public class Solution implements Runnable {
public void solve() throws Exception {
int n = sc.nextInt();
int a[] = new int[n];
int s = 0;
for (int i = 0;i < n; ++ i) {
a[i] = sc.nextInt();
s += a[i];
}
Arrays.sort(a);
int s2 = 0;
for (int i = n - 1;i >= 0; -- i) {
s2 += a[i];
if (s2 > s - s2) {
out.println(n - i);
break;
}
}
}
class Pair implements Comparable<Pair> {
int x;
int y;
public Pair() {
}
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Pair arg0) {
if (x == arg0.x)
return y - arg0.y;
return x - arg0.x;
}
}
/*--------------------------------------------------------------*/
static String filename = "";
static boolean fromFile = false;
BufferedReader in;
PrintWriter out;
FastScanner sc;
public static void main(String[] args) {
new Thread(null, new Solution(), "", 1 << 25).start();
}
public void run() {
try {
init();
solve();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
out.close();
}
}
void init() throws Exception {
if (fromFile) {
in = new BufferedReader(new FileReader(filename+".in"));
out = new PrintWriter(new FileWriter(filename+".out"));
} else {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
sc = new FastScanner(in);
}
}
class FastScanner {
BufferedReader reader;
StringTokenizer strTok;
public FastScanner(BufferedReader reader) {
this.reader = reader;
}
public String nextToken() throws IOException {
while (strTok == null || !strTok.hasMoreTokens()) {
strTok = new StringTokenizer(reader.readLine());
}
return strTok.nextToken();
}
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());
}
public BigInteger nextBigInteger() throws IOException {
return new BigInteger(nextToken());
}
public BigDecimal nextBigDecimal() throws IOException {
return new BigDecimal(nextToken());
}
} | nlogn | 160_A. Twins | CODEFORCES |
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author @listen
*/
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);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int n = in.nextInt();
int [] input = new int[n];
int total = 0;
for (int i = 0; i < n; ++i){
input[i] = in.nextInt();
total +=input[i];
}
Arrays.sort(input);
int res = 0;
int now = 0;
for (int i = n - 1; i >= 0; --i){
now += input[i];
int left = total - now;
++res;
if (now > left){
break;
}
}
out.println(res);
return;
}
}
| nlogn | 160_A. Twins | CODEFORCES |
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Scanner;
import java.util.StringTokenizer;
public class a implements Comparable<a>{
int x, y, id;
//static BufferedReader in;
//static StringTokenizer st;
public a(int x1, int y1, int id1){
this.x = x1; this.y = y1; this.id = id1;
}
public int compareTo(a o) {
return x - o.x;
}
static int n;
static int arr[];
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
//in = new BufferedReader(new InputStreamReader(System.in));
//st = new StringTokenizer(""," ");
int n = in.nextInt();
arr = new int[n];
int sum = 0;
for (int i=0; i<n; i++){
arr[i] = in.nextInt();
sum +=arr[i];
}
Arrays.sort(arr);
int sum2= 0;
int ans = 0;
for (int i=n-1; i>=0; i--){
sum2+=arr[i];
//System.out.println(sum2 + " " + sum);
if (sum2>sum-sum2){
ans = n - i;
break;
}
}
System.out.println(ans);
}
}
| nlogn | 160_A. Twins | CODEFORCES |
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
public class SolA {
static Scanner in;
static PrintWriter out;
public static void main(String[] args) {
in = new Scanner(System.in);
out = new PrintWriter(System.out);
new SolA().run();
in.close();
out.close();
}
private void run() {
int n = in.nextInt();
int[] a = new int[n];
int sum = 0;
for(int i = 0; i < n; i++) {
a[i] = in.nextInt();
sum+=a[i];
}
Arrays.sort(a);
int cs = 0;
int kol = 0;
for(int i = n - 1; i>=0; i--) {
cs+=a[i];
kol++;
if (cs > sum - cs) {
break;
}
}
out.print(kol);
}
}
| nlogn | 160_A. Twins | CODEFORCES |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.