src
stringlengths 95
64.6k
| complexity
stringclasses 7
values | problem
stringlengths 6
50
| from
stringclasses 1
value |
---|---|---|---|
import java.io.*;
import java.util.*;
public class Main {
static BufferedReader f;
static StringTokenizer st;
public static void main (String [] args) throws Exception {
// Use BufferedReader rather than RandomAccessFile; it's much faster
f = new BufferedReader(new java.io.InputStreamReader(System.in));
long unixTime = System.currentTimeMillis();
long l=nextLong();
long r=nextLong();
String ll=Long.toBinaryString(l);
String rr=Long.toBinaryString(r);
System.err.println(ll);
System.err.println(rr);
System.err.println(Long.parseLong(rr,2));
int len=0;
if(ll.length()!=rr.length()){
len=Math.max(ll.length(),rr.length());
}else{
//same
for(int i=0;i<ll.length();i++){
if(ll.charAt(i)!=rr.charAt(i)){
len=ll.length()-i;
break;
}
}
}
System.err.println(len);
//long out=0;
StringBuffer s=new StringBuffer();
for(int i=0;i<len;i++){
//out+=Math.pow(2, i);
s.append(1);
}
if(len==0){
System.out.println(0);
}else{
System.out.println(Long.parseLong(s.toString(),2));
}
// System.out.println("Time elapsed (ms): "+(System.currentTimeMillis()-unixTime));
System.exit(0); // don't omit this!
}
//Library
static long nextLong() throws Exception{
return Long.parseLong(next());
}
static int nextInt() throws Exception {
return Integer.parseInt(next());
}
static String next() throws Exception {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(f.readLine());
}
return st.nextToken();
}
}
class ii{
int a;
int b;
public ii(int a, int b){
this.a=a;
this.b=b;
}
} | logn | 276_D. Little Girl and Maximum XOR | CODEFORCES |
import java.io.*;
import java.lang.reflect.*;
public class D {
final int MOD = (int)1e9 + 7;
final double eps = 1e-12;
final int INF = (int)1e9;
public D () {
long L = sc.nextLong();
long R = sc.nextLong();
int Z = 64 - Long.numberOfLeadingZeros(L ^ R);
long res = (1L << Z) - 1;
exit(res);
}
////////////////////////////////////////////////////////////////////////////////////
/* Dear hacker, don't bother reading below this line, unless you want to help me debug my I/O routines :-) */
static MyScanner sc = new MyScanner();
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;
}
public String [] next (int N) {
String [] res = new String [N];
for (int i = 0; i < N; ++i)
res[i] = sc.next();
return res;
}
public Integer [] nextInt (int N) {
Integer [] res = new Integer [N];
for (int i = 0; i < N; ++i)
res[i] = sc.nextInt();
return res;
}
public Long [] nextLong (int N) {
Long [] res = new Long [N];
for (int i = 0; i < N; ++i)
res[i] = sc.nextLong();
return res;
}
public Double [] nextDouble (int N) {
Double [] res = new Double [N];
for (int i = 0; i < N; ++i)
res[i] = sc.nextDouble();
return res;
}
public String [][] nextStrings (int N) {
String [][] res = new String [N][];
for (int i = 0; i < N; ++i)
res[i] = sc.nextStrings();
return res;
}
public Integer [][] nextInts (int N) {
Integer [][] res = new Integer [N][];
for (int i = 0; i < N; ++i)
res[i] = sc.nextInts();
return res;
}
public Long [][] nextLongs (int N) {
Long [][] res = new Long [N][];
for (int i = 0; i < N; ++i)
res[i] = sc.nextLongs();
return res;
}
public Double [][] nextDoubles (int N) {
Double [][] res = new Double [N][];
for (int i = 0; i < N; ++i)
res[i] = sc.nextDoubles();
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) {
printDelim(" ", o, a);
}
static void cprint(Object o, Object... a) {
printDelim("", o, a);
}
static void printDelim (String delim, Object o, Object... a) {
pw.println(build(delim, 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(String delim, Object o, Object... a) {
StringBuilder b = new StringBuilder();
append(b, o, delim);
for (Object p : a)
append(b, p, delim);
return b.toString().trim();
}
static void append(StringBuilder b, Object o, String delim) {
if (o.getClass().isArray()) {
int L = Array.getLength(o);
for (int i = 0; i < L; ++i)
append(b, Array.get(o, i), delim);
} else if (o instanceof Iterable<?>) {
for (Object p : (Iterable<?>)o)
append(b, p, delim);
} else
b.append(delim).append(o);
}
////////////////////////////////////////////////////////////////////////////////////
public static void main(String[] args) {
new D();
exit();
}
static void start() {
t = millis();
}
static PrintWriter pw = new PrintWriter(System.out);
static long t;
static long millis() {
return System.currentTimeMillis();
}
}
| logn | 276_D. Little Girl and Maximum XOR | CODEFORCES |
import java.util.*;
public class D {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long L = sc.nextLong();
long R = sc.nextLong();
long res = Math.max(2 * Long.highestOneBit(L ^ R) - 1, 0);
System.out.println(res);
}
}
| logn | 276_D. Little Girl and Maximum XOR | CODEFORCES |
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Comparator;
import java.util.Random;
import java.util.StringTokenizer;
/**
* @author Polyarniy Nickolay
*/
public class ProblemD {
private BufferedReader in;
private PrintWriter out;
private StringTokenizer tok;
private final String DELIMETER = " ";
private final boolean ENABLE_MULTITEST = false;
private final boolean DEBUG = true;
private final String FILENAME = null;//if FILENAME = null, then works with console
public void run() throws Exception {
initInputOutput();
do {
init();
solve();
} while (hasMoreTokens() && ENABLE_MULTITEST);
finish();
}
private void init() throws Exception {
}
private void solve() throws Exception {
String a = Long.toBinaryString(nextLong());
String b = Long.toBinaryString(nextLong());
while (a.length() < 64) {
a = "0" + a;
}
while (b.length() < 64) {
b = "0" + b;
}
// out.println(a);
// out.println(b);
char[] res = new char[a.length()];
int cur = 0;
while (cur < a.length() && a.charAt(cur) == b.charAt(cur)) {
res[cur] = '0';
cur++;
}
while (cur < res.length) {
res[cur] = '1';
cur++;
}
out.println(Long.valueOf(new String(res), 2));
}
public static void main(String[] args) throws Exception {
ProblemD solution = new ProblemD();
solution.run();
}
private void initInputOutput() throws Exception {
if (FILENAME == null) {
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");
}
}
private void shuffleArray(Object[] arr) {
Random r = new Random();
for (int i = 0; i < arr.length; ++i) {
Object tmp = arr[i];
int j = r.nextInt(arr.length);
arr[i] = arr[j];
arr[j] = tmp;
}
}
private void shuffleArray(int[] arr) {
Random r = new Random();
for (int i = 0; i < arr.length; ++i) {
int tmp = arr[i];
int j = r.nextInt(arr.length);
arr[i] = arr[j];
arr[j] = tmp;
}
}
private int[] nextArrayInt(int n) throws Exception {
int[] res = new int[n];
for (int i = 0; i < n; i++) {
res[i] = nextInt();
}
return res;
}
private String nextWord() throws Exception {
if (updateTokenizer()) {
return null;
} else {
return tok.nextToken();
}
}
private boolean hasMoreTokens() throws Exception {
return !updateTokenizer();
}
private boolean updateTokenizer() throws Exception {
while (tok == null || !tok.hasMoreTokens()) {
String nextLine = in.readLine();
if (nextLine == null || nextLine.isEmpty()) {
return true;
}
tok = new StringTokenizer(nextLine, DELIMETER);
}
return false;
}
private int nextInt() throws Exception {
return Integer.parseInt(nextWord());
}
private long nextLong() throws Exception {
return Long.parseLong(nextWord());
}
private void finish() throws Exception {
in.close();
out.close();
}
private void print(String s) {
if (DEBUG) {
System.out.print(s);
}
}
private void println(String s) {
if (DEBUG) {
System.out.println(s);
}
}
private void println() {
if (DEBUG) {
System.out.println();
}
}
private long[] getFirstSimpleNums(int n) {
boolean[] notPr = new boolean[n];
int res = n;
notPr[0] = true;
res--;
notPr[1] = true;
res--;
for (int i = 2; i < n; ++i) {
if (!notPr[i]) {
for (int j = i + i; j < n; j += i) {
if (!notPr[j]) {
notPr[j] = true;
res--;
}
}
}
}
long[] resA = new long[res];
int next = 0;
for (int i = 0; i < n; i++) {
if (!notPr[i]) {
resA[next] = i;
next++;
}
}
return resA;
}
private static class Pair {
int a;
int b;
public Pair(int a, int b) {
this.a = a;
this.b = b;
}
public static final Comparator<Pair> comparator = new Comparator<Pair>() {
@Override
public int compare(Pair pair1, Pair pair2) {
return (pair1.a - pair2.a) != 0 ? (pair1.a - pair2.a) : (pair1.b - pair2.b);
}
};
@Override
public String toString() {
return "{" + a + "|" + b + '}';
}
}
} | logn | 276_D. Little Girl and Maximum XOR | 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.StringTokenizer;
public class D {
static StringTokenizer st;
static BufferedReader in;
public static void main(String[] args) throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
long L = nextLong();
long R = nextLong();
if (L==R) {
System.out.println(0);
return;
}
String s1 = Long.toBinaryString(L), s2 = Long.toBinaryString(R);
while (s1.length() != s2.length())
s1 = "0"+s1;
for (int i = 0; i < s1.length(); i++) {
if (s1.charAt(i) != s2.charAt(i)) {
int pow = s1.length()-i;
System.out.println((long)Math.pow(2, pow)-1);
return;
}
}
pw.close();
}
private static int nextInt() throws IOException{
return Integer.parseInt(next());
}
private static long nextLong() throws IOException{
return Long.parseLong(next());
}
private static double nextDouble() throws IOException{
return Double.parseDouble(next());
}
private static String next() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
}
| logn | 276_D. Little Girl and Maximum XOR | CODEFORCES |
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class con169_D {
private static final boolean DEBUG = false;
public static void main( final String[] args ) throws Exception {
final BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) );
final String line = br.readLine();
final StringTokenizer tok = new StringTokenizer( line );
final long L = Long.parseLong( tok.nextToken() );
final long R = Long.parseLong( tok.nextToken() );
System.out.println( solve( L, R ) );
}
public static long solve( final long L, final long R ) {
if ( L == R ) return L ^ R;
if ( DEBUG ) System.out.printf( "L=%d (%s), R=%d (%s)\n", L, Long.toBinaryString( L ), R,
Long.toBinaryString( R ) );
final int ld = length( L );
final int ldm1 = ld - 1;
final int rd = length( R );
if ( ld < rd ) {
long max = 1;
while ( length( max ) < rd ) {
max <<= 1;
}
long min = 1;
while ( length( min ) < rd - 1 ) {
min <<= 1;
++min;
}
if ( DEBUG ) System.out.printf( "min=%d (%s), max=%d (%s)\n", min, Long.toBinaryString( min ), max,
Long.toBinaryString( max ) );
return min ^ max;
} else {
final char[] minStr = Long.toBinaryString( L ).toCharArray();
final char[] maxStr = Long.toBinaryString( R ).toCharArray();
final char[] res = new char[minStr.length];
Arrays.fill( res, '0' );
{
int i = 0;
while ( i < res.length ) {
if ( minStr[ i ] == maxStr[ i ] ) {
res[ i ] = '0';
} else {
break;
}
++i;
}
if ( DEBUG ) System.out.println( "diff at pos: " + i );
if ( minStr[ i ] == '0' ) {
res[ i++ ] = '1';
for ( int j = i; j < res.length; ++j ) {
res[ j ] = '1';
}
} else {
throw new IllegalArgumentException();
}
}
return Long.parseLong( new String( res ), 2 );
}
}
private static int length( long l ) {
int res = 0;
while ( l > 0 ) {
++res;
l >>= 1;
}
return res;
}
}
| logn | 276_D. Little Girl and Maximum XOR | CODEFORCES |
import java.io.*;
import java.util.*;
import java.math.*;
public class Codeforces
{
public StreamTokenizer st;
public PrintWriter pw;
public static final int modulo = 1000000009;
static class Point
{
public int x, y;
Point(int _x, int _y)
{
x = _x;
y = _y;
}
}
void init(String in, String out)
{
if (in.isEmpty())
st = new StreamTokenizer(System.in);
else
{
try
{
st = new StreamTokenizer(new BufferedReader(new FileReader(in)));
}
catch(FileNotFoundException e)
{
}
}
if (out.isEmpty())
pw = new PrintWriter(System.out);
else
{
try
{
pw = new PrintWriter(new FileWriter(out));
}
catch(IOException e)
{
}
}
}
private void close()
{
pw.close();
}
private int nI()
{
try{
st.nextToken();
}
catch(IOException e)
{
}
return (int)st.nval;
}
private double nD()
{
try{
st.nextToken();
}
catch(IOException e)
{
}
return st.nval;
}
private String nS()
{
try{
st.nextToken();
}
catch(IOException e)
{
}
return st.sval;
}
private long nL()
{
try{
st.nextToken();
}
catch(IOException e)
{
}
return (long)st.nval;
}
public static void qSort(int[] A, int low, int high) {
int i = low;
int j = high;
int x = A[(low+high)/2];
do {
while(A[i] < x) ++i;
while(A[j] > x) --j;
if(i <= j){
int temp = A[i];
A[i] = A[j];
A[j] = temp;
i++; j--;
}
} while(i < j);
if(low < j)
qSort(A, low, j);
if(i < high)
qSort(A, i, high);
}
public static void main(String[] aslkdjlkgja) throws IOException
{
Codeforces z = new Codeforces();
z.init("", "");
long l = z.nL();
long r = z.nL();
if ( l == r)
{
System.out.println(0);
z.close();
return;
}
List<Boolean> R = new ArrayList<Boolean>();
List<Boolean> L = new ArrayList<Boolean>();
long temp = r;
while (temp != 0)
{
if (temp % 2 == 1)
R.add(true);
else
R.add(false);
temp /= 2;
}
Collections.reverse(R);
temp = l;
while (temp != 0)
{
if (temp % 2 == 1)
L.add(true);
else
L.add(false);
temp /= 2;
}
int n = R.size() - L.size();
while (n!=0)
{
L.add(false);
--n;
}
Collections.reverse(L);
List<Boolean> res = new ArrayList<Boolean>();
// for (int i = 0 ; i < R.size(); ++i)
// res.add(false);
int it = 0;
while (R.get(0) == L.get(0))
{
res.add(false);
R.remove(0);
L.remove(0);
}
for (int i = 0; i< R.size(); ++i)
res.add(true);
long out = 0;
it = 0;
long add = 1;
Collections.reverse(res);
while (it < res.size())
{
if (res.get(it))
out += add;
add *= 2;
++it;
}
System.out.println(out);
}
} | logn | 276_D. Little Girl and Maximum XOR | CODEFORCES |
import java.io.*;
import java.util.*;
public class pr169D implements Runnable {
BufferedReader in;
PrintWriter out;
StringTokenizer str;
public void solve() throws IOException {
long l = nextLong();
long r = nextLong();
long x = l ^ r;
long i = 1;
while (x >= i)
i *= 2;
out.println(x > i ? x : i - 1);
}
public String nextToken() throws IOException {
while (str == null || !str.hasMoreTokens()) {
str = new StringTokenizer(in.readLine());
}
return str.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
public long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
in.close();
out.close();
} catch (IOException e) {
}
}
public static void main(String[] args) {
new Thread(new pr169D()).start();
}
}
| logn | 276_D. Little Girl and Maximum XOR | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
public class A {
public static BufferedReader in;
public static PrintWriter out;
public static void main(String[] args) throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
boolean showLineError = true;
if (showLineError) {
solve();
out.close();
} else {
try {
solve();
} catch (Exception e) {
} finally {
out.close();
}
}
}
static void debug(Object... os) {
out.println(Arrays.deepToString(os));
}
private static void solve() throws IOException {
String[] line = in.readLine().split(" ");
String l = Long.toBinaryString(Long.parseLong(line[0]));
String r = Long.toBinaryString(Long.parseLong(line[1]));
if(l.equals(r)){
out.println(0);
return;
}
int dif = r.length()-l.length();
for(int i =0;i<dif;i++)
l= "0"+l;
int index=0;
for(;index<r.length();index++){
if(l.charAt(index)!=r.charAt(index))
break;
}
long ret=1;
for(int i=0;i<l.length()-index;i++)
ret+=ret;
ret--;
out.println(ret);
}
} | logn | 276_D. Little Girl and Maximum XOR | CODEFORCES |
import java.io.*;
import java.util.*;
import java.util.StringTokenizer;
public class SolutionD {
BufferedReader in;
StringTokenizer str;
PrintWriter out;
String SK;
String next() throws IOException {
while ((str == null) || (!str.hasMoreTokens())) {
SK = in.readLine();
if (SK == null)
return null;
str = new StringTokenizer(SK);
}
return str.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
void run() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
//in = new BufferedReader(new FileReader("input.txt"));
//out = new PrintWriter("output.txt");
solve();
out.close();
}
public static void main(String[] args) throws IOException {
new SolutionD().run();
}
void solve() throws IOException {
long l=Long.parseLong(next());
long r=Long.parseLong(next());
String low=Long.toBinaryString(l);
String up=Long.toBinaryString(r);
int n=low.length();
int m=up.length();
for(int i=0;i<m-n;i++){
low="0"+low;
}
String ret="";
boolean fu=false;
boolean fd=false;
boolean su=false;
boolean sd=false;
if(m>n){
su=true;
fd=true;
}
for(int i=0;i<m;i++){
if(low.charAt(i)==up.charAt(i)){
if(low.charAt(i)=='1'){
if(fd){
ret+="1";
fu=true;
}
else if(sd){
ret+="1";
su=true;
}
else ret+="0";
}
else{
if(fu){
ret+="1";
fd=true;
}
else if(su){
ret+="1";
sd=true;
}
else ret+="0";
}
}else{
if(up.charAt(i)=='1'){
su=true;
fd=true;
}
ret+="1";
}
}
out.println(Long.parseLong(ret, 2));
}
}
| logn | 276_D. Little Girl and Maximum XOR | CODEFORCES |
import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
long a,b;
a = scn.nextLong();
b = scn.nextLong();
long diff = b -a , tot = 0;
int ind = 0;
while(true) {
long res = (long)Math.pow(2.0, ind);
if (res > b) break;
if (((a>>ind) != (b>>ind)) || diff >= res)
tot += res;
ind++;
}
System.out.println(tot);
}
}
| logn | 276_D. Little Girl and Maximum XOR | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
import java.util.TreeMap;
public class D {
static long l, r;
static long[][][][][] dp;
public static void main(String[] args) throws IOException {
InputReader in = new InputReader();
l = in.nextLong();
r = in.nextLong();
dp = new long[65][2][2][2][2];
for(int i = 0 ; i < 65;i++)
for(int j = 0 ; j < 2;j++)
for(int k = 0 ; k < 2;k++)
for(int a = 0 ; a<2;a++)
dp[i][j][k][a][0]=dp[i][j][k][a][1]=-1;
System.out.println(go(63, 0, 0, 0, 0));
}
public static long go(int i, int a1, int a2, int b1, int b2) {
if(i==-1)return 0;
if(dp[i][a1][a2][b1][b2]!=-1)
return dp[i][a1][a2][b1][b2];
int f1 = 3, f2 = 3;
int bl = (int) ((l >> i)) & 1, br = (int) ((r >> i) & 1);
if (a2 == 0 && br==0)
f1 &= 1;
if(a1 == 0 && bl==1)
f1 &= 2;
if (b2 == 0 && br==0)
f2 &= 1;
if(b1 == 0 && bl==1)
f2 &= 2;
long res = 0;
for(int x = 0 ; x<2;x++){
for(int y = 0 ; y<2;y++){
if(((f1>>x)&1) == 1 &&((f2>>y)&1) == 1){
res = Math.max(res, (((long)(x^y))<<i)+go(i-1,x>bl||a1==1?1:0,x<br||a2==1?1:0,y>bl||b1==1?1:0,y<br||b2==1?1:0));
}
}
}
return dp[i][a1][a2][b1][b2]=res;
}
static class InputReader {
BufferedReader in;
StringTokenizer st;
public InputReader() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(in.readLine());
}
public String next() throws IOException {
while (!st.hasMoreElements())
st = new StringTokenizer(in.readLine());
return st.nextToken();
}
public int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(next());
}
public long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(next());
}
}
} | logn | 276_D. Little Girl and Maximum XOR | CODEFORCES |
import java.io.PrintWriter;
import java.util.Scanner;
public class D {
public static void main(String [] args){
Scanner cin = new Scanner(System.in);
PrintWriter cout = new PrintWriter(System.out);
long l = cin.nextLong(), r = cin.nextLong(), k = 1;
if (l == r)cout.println(0);
else {
while (((r>>k)<<k)>l)k++;k--;
cout.println(((r>>k)<<k)^(((r>>k)<<k)-1));
}
cout.flush();
}
} | logn | 276_D. Little Girl and Maximum XOR | CODEFORCES |
import java.io.InputStreamReader;
import java.io.IOException;
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
* @author vadimmm
*/
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();
}
}
class TaskD {
public void solve(int testNumber, InputReader in, PrintWriter out) {
long l = in.nextLong();
long r = in.nextLong();
/*
long max = 1;
boolean good = false;
for (int i = 0; i < 62; ++i) {
max <<= 1;
if (max > r) {
max >>= 1;
if (max >= l) {
good = true;
}
break;
}
}
if (good) {
if (max - 1 >= l)
out.println(max ^ (max - 1));
else
out.println(max ^ r);
return;
}
*/
boolean[][] answer = new boolean[2][100];
int cur = 0;
while (r > 0) {
answer[0][cur] = (r % 2 != 0);
++cur;
r >>= 1;
}
cur = 0;
while (l > 0) {
answer[1][cur] = (l % 2 != 0);
++cur;
l >>= 1;
}
int old = -1;
for (int i = 63; i >= 0; --i) {
if (answer[0][i] && !answer[1][i]) {
old = i;
break;
}
}
if (old == -1) {
out.println(0);
return;
}
long a = 1;
for (int i = 0; i < old; ++i) {
a <<= 1;
a += 1;
}
out.println(a);
}
}
class InputReader {
private static BufferedReader bufferedReader;
private static StringTokenizer stringTokenizer;
public InputReader(InputStream inputStream) {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
stringTokenizer = null;
}
public String next() {
while(stringTokenizer == null || !stringTokenizer.hasMoreTokens()) {
try {
stringTokenizer = new StringTokenizer(bufferedReader.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return stringTokenizer.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
}
| logn | 276_D. Little Girl and Maximum XOR | CODEFORCES |
import java.util.Scanner;
public class Main2 {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
long s = input.nextLong();
long e = input.nextLong();
System.out.println(count(s,e));
}
public static long count(long s,long e){
int ncount = 0;
long es = e;
while(es != 0){
es /= 2;
ncount++;
}
while(ncount >= 0){
if(((s>>ncount-1)&1) == 1 && ((e>>ncount-1)&1) == 0 || ((s>>ncount-1)&1) == 0 && ((e>>ncount-1)&1) == 1){
break;
}
ncount--;
}
if(ncount >= 0){
return (long)Math.pow(2, ncount)-1;
}else{
return 0;
}
}
} | logn | 276_D. Little Girl and Maximum XOR | CODEFORCES |
import java.util.*;
public class Code {
public Code(){}
public static void main(String args[]){
Scanner QQQ=new Scanner(System.in);
long l=QQQ.nextLong();
long r=QQQ.nextLong();
long ans=l^r;
int a[]=new int [70];
int b[]=new int [70];
int n=0,m=0;
while (l!=0){
a[m]=(int)(l%2);
l/=2;
m++;
}
while (r!=0){
b[n]=(int)(r%2);
r/=2;
n++;
}
m--;n--;
long deg[]=new long [70];
deg[0]=1;
for (int i=1;i<=62;i++) deg[i]=deg[i-1]*2;
for (int i=n;i>=0;i--)
if (b[i]==1&&a[i]==0){
System.out.println(deg[i+1]-1);
return;
}
System.out.println(ans);
}
} | logn | 276_D. Little Girl and Maximum XOR | CODEFORCES |
import java.io.*;
import java.util.*;
public class ProblemD {
InputReader in; PrintWriter out;
void solve() {
long l = in.nextLong();
long r = in.nextLong();
long ans = 0;
boolean add = false;
for (int k = 62; k >= 0; k--) {
long cb = (1L << k);
if ((l & cb) != (r & cb))
add = true;
if (add)
ans += (1L << k);
}
out.println(ans);
}
ProblemD(){
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 ProblemD();
}
}
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());
}
} | logn | 276_D. Little Girl and Maximum XOR | CODEFORCES |
//Author: Patel Rag
//Java version "1.8.0_211"
import java.util.*;
import java.io.*;
public class Main
{
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader(){ br = new BufferedReader(new InputStreamReader(System.in)); }
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong(){ return Long.parseLong(next()); }
double nextDouble(){ return Double.parseDouble(next()); }
float nextFloat() { return Float.parseFloat(next()); }
boolean nextBoolean() { return Boolean.parseBoolean(next()); }
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
static long modExp(long x, long n, long mod) //binary Modular exponentiation
{
long result = 1;
while(n > 0)
{
if(n % 2 == 1)
result = (result%mod * x%mod)%mod;
x = (x%mod * x%mod)%mod;
n=n/2;
}
return result;
}
static long gcd(long a, long b)
{
if(a==0) return b;
return gcd(b%a,a);
}
public static void main(String[] args)
throws IOException
{
FastReader fr = new FastReader();
int n = fr.nextInt();
int q = fr.nextInt();
long[] a = new long[n];
long[] k = new long[q];
for(int i = 0; i < n; i++) a[i] = fr.nextLong();
for(int i = 0; i < q; i++) k[i] = fr.nextLong();
long[] pre = new long[n];
pre[0] = a[0];
for(int i = 1; i < n; i++) pre[i] = pre[i-1] + a[i];
long pd = 0;
for(int i = 0; i < q; i++)
{
int l = 0;
int r = n - 1;
while(r > l)
{
int mid = (l + r) >> 1;
if(pre[mid] - pd < k[i])
{
l = mid + 1;
}
else if(pre[mid] - pd > k[i])
{
r = mid - 1;
}
else
{
l = r = mid;
}
}
int ans = 0;
if(pre[l] - pd <= k[i])
{
ans = n - l - 1;
}
else
{
ans = n - l;
}
if(ans == 0) ans = n;
pd = pd + k[i];
if(pd >= pre[n-1]) pd = 0;
System.out.println(ans);
}
}
}
class pair
{
public int first;
public int second;
public pair(int first,int second)
{
this.first = first;
this.second = second;
}
public pair(pair p)
{
this.first = p.first;
this.second = p.second;
}
public int first() { return first; }
public int second() { return second; }
public void setFirst(int first) { this.first = first; }
public void setSecond(int second) { this.second = second; }
}
class myComp implements Comparator<pair>
{
public int compare(pair a,pair b)
{
if(a.first != b.first) return (a.first - b.first);
return (b.second - a.second);
}
}
class BIT //Binary Indexed Tree aka Fenwick Tree
{
public long[] m_array;
public BIT(long[] dat)
{
m_array = new long[dat.length + 1];
Arrays.fill(m_array,0);
for(int i = 0; i < dat.length; i++)
{
m_array[i + 1] = dat[i];
}
for(int i = 1; i < m_array.length; i++)
{
int j = i + (i & -i);
if(j < m_array.length)
{
m_array[j] = m_array[j] + m_array[i];
}
}
}
public final long prefix_query(int i)
{
long result = 0;
for(++i; i > 0; i = i - (i & -i))
{
result = result + m_array[i];
}
return result;
}
public final long range_query(int fro, int to)
{
if(fro == 0)
{
return prefix_query(to);
}
else
{
return (prefix_query(to) - prefix_query(fro - 1));
}
}
public void update(int i, long add)
{
for(++i; i < m_array.length; i = i + (i & -i))
{
m_array[i] = m_array[i] + add;
}
}
}
| nlogn | 975_C. Valhalla Siege | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.FileNotFoundException;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author \/
*/
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);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
TaskC.pair[] songs = new TaskC.pair[n];
long sum = 0;
for (int i = 0; i < n; i++) {
songs[i] = new TaskC.pair(in.nextInt(), in.nextInt());
sum += songs[i].a;
}
Arrays.sort(songs);
int res = 0;
int idx = n - 1;
while (sum > m) {
if (idx < 0) {
break;
}
sum -= (songs[idx].a - songs[idx].b);
res++;
idx--;
}
if (sum > m) {
out.println(-1);
} else {
out.println(res);
}
}
static class pair implements Comparable<TaskC.pair> {
int a;
int b;
pair(int a, int b) {
this.a = a;
this.b = b;
}
public int compareTo(TaskC.pair p) {
return (this.a - this.b) - (p.a - p.b);
}
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(String s) {
try {
br = new BufferedReader(new FileReader(s));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| nlogn | 1015_C. Songs Compression | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class CoveredPointsCount {
//UPSOLVE
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
long[] myArray = new long[2 * n];
for (int i = 0; i < n; i++) {
StringTokenizer st1 = new StringTokenizer(br.readLine());
myArray[2 * i] = Long.parseLong(st1.nextToken()) * 2;
myArray[2 * i + 1] = Long.parseLong(st1.nextToken()) * 2 + 1;
}
Arrays.sort(myArray);
long[] ans = new long[n + 1];
int cnt = 0;
for (int i = 0; i < 2 * n - 1; i++) {
if (myArray[i] % 2 == 0) cnt++; else cnt--;
ans[cnt] += (myArray[i + 1] + 1) / 2 - (myArray[i] + 1) / 2;
}
StringBuilder answer = new StringBuilder();
for (int i = 1; i < n + 1; i++) {
answer.append(ans[i]);
answer.append(" ");
}
System.out.println(answer);
}
}
| nlogn | 1000_C. Covered Points Count | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class CoveredPointsCount {
//UPSOLVE
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
long[] myArray = new long[2 * n];
for (int i = 0; i < n; i++) {
StringTokenizer st1 = new StringTokenizer(br.readLine());
myArray[2 * i] = Long.parseLong(st1.nextToken()) * 2;
myArray[2 * i + 1] = Long.parseLong(st1.nextToken()) * 2 + 1;
}
Arrays.sort(myArray);
long[] ans = new long[n + 1];
int cnt = 0;
for (int i = 0; i < 2 * n - 1; i++) {
if (myArray[i] % 2 == 0) cnt++; else cnt--;
ans[cnt] += (myArray[i + 1] + 1) / 2 - (myArray[i] + 1) / 2;
}
StringBuilder answer = new StringBuilder();
for (int i = 1; i < n + 1; i++) {
answer.append(ans[i]);
answer.append(" ");
}
System.out.println(answer);
}
}
| nlogn | 1000_C. Covered Points Count | CODEFORCES |
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.StringTokenizer;
public class A {
static int[] parent;
public static int find(int x) {
if (x == parent[x])
return x;
return parent[x] = find(parent[x]);
}
public static void union(int x, int y) {
int px = find(x);
int py = find(y);
if (px != py) {
parent[py] = px;
}
}
public static void main(String[] args) throws Exception {
int numCnt = (int) nextLong();
long k = nextLong();
parent = new int[numCnt];
for (int i = 0; i < parent.length; i++) {
parent[i] = i;
}
HashMap<Long, Integer> map = new HashMap<Long, Integer>();
long[] ar = new long[numCnt];
for (int i = 0; i < numCnt; i++) {
ar[i] = nextLong();
map.put(ar[i] * 10007 + ar[i] / 13, i);
}
for (int i = 0; i < ar.length; i++) {
long req = ar[i] * k;
Integer idx=map.get(req * 10007 + req / 13);
if (idx!=null) {
union(i, idx);
}
}
int[] count = new int[numCnt];
for (int i = 0; i < parent.length; i++) {
count[find(i)]++;
}
int res = 0;
for (int i = 0; i < numCnt; i++) {
res += (int) ((count[i] + 1) / 2.0);
}
System.out.println(res);
}
static BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
static StringTokenizer tokenizer = new StringTokenizer("");
static long nextLong() throws Exception {
return Long.parseLong(next());
}
static double nextDouble() throws Exception {
return Double.parseDouble(next());
}
static String next() throws Exception {
while (true) {
if (tokenizer.hasMoreTokens()) {
return tokenizer.nextToken();
}
String s = br.readLine();
if (s == null) {
return null;
}
tokenizer = new StringTokenizer(s);
}
}
} | nlogn | 274_A. k-Multiple Free Set | CODEFORCES |
// @author Sanzhar
import java.io.*;
import java.util.*;
import java.awt.Point;
public class Template {
BufferedReader in;
PrintWriter out;
StringTokenizer st;
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(in.readLine());
} catch (Exception e) {
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
public void run() throws Exception {
//in = new BufferedReader(new FileReader("input.txt"));
//out = new PrintWriter(new FileWriter("output.txt"));
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.flush();
out.close();
in.close();
}
public void solve() throws Exception {
int n = nextInt();
int k = nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
boolean[] ok = new boolean[n];
Arrays.fill(ok, true);
Arrays.sort(a);
if (k != 1) {
for (int i = 0; i < n; i++) {
if (a[i] % k == 0) {
int x = a[i] / k;
int ind = Arrays.binarySearch(a, x);
if (ind >= 0 && ok[ind]) {
ok[i] = false;
}
}
}
}
int ans = 0;
for (int i = 0; i < n; i++) {
if (ok[i]) {
ans++;
}
}
out.println(ans);
}
public static void main(String[] args) throws Exception {
new Template().run();
}
}
| nlogn | 274_A. k-Multiple Free Set | CODEFORCES |
import java.util.*;
import java.math.*;
import java.io.*;
public class Main
{
public static void main(String args[]) throws IOException
{
BufferedReader c=new BufferedReader(new InputStreamReader(System.in));
String S[]=c.readLine().split(" ");
int N=Integer.parseInt(S[0]);
int K=Integer.parseInt(S[1]);
int A[]=parseArray(c.readLine(),N);
shuffle(A);
Arrays.sort(A);
TreeMap<Long,Long> T=new TreeMap<Long, Long>();
int ans=0;
for(int i=0;i<N;i++)
T.put((long)A[i],1L);
//System.out.println(Arrays.toString(A));
if(K==1)
{
System.out.println(N);
return;
}
else
{
for(int i=0;i<N;i++)
{
if(A[i]%K==0&&T.containsKey((long)A[i]/K)) //A[i] is not start of a chain
continue;
//System.out.println("considering "+A[i]);
int chainSize=0;
long init=A[i];
while(T.containsKey(init))
{
chainSize++;
init=init*K;
}
//System.out.println("\t"+chainSize);
ans+=(chainSize+1)/2;
}
}
System.out.println(ans);
}
/**
* Knuth's shuffle. Generate a random permutation of an array
*/
public static int[] shuffle(int A[])
{
int N=A.length;
for(int i=1;i<N;i++)
{
int j=(int) (Math.random()*100000)%(i+1); // 0<=j<=i;
int temp=A[i];
A[i]=A[j];
A[j]=temp;
}
return A;
}
// Parse an integer array of size N from a string s
public static int[] parseArray(String s,int N)
{
int A[]=new int[N];
StringTokenizer st=new StringTokenizer(s);
for(int i=0;i<N;i++)
A[i]=Integer.parseInt(st.nextToken());
return A;
}
} | nlogn | 274_A. k-Multiple Free Set | CODEFORCES |
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeSet;
//basically tried to understand ping's greedy alg
public class kMultRedo {
static int n;
static int k;
public static void main(String[] args){
//lol what?? If use HashSet timeout, but if use tree set, not?
//even with super high initialize capacty = 100,000,where max 100000
Set<Integer> set = new HashSet<Integer>(1000000);
FastScanner s = new FastScanner();
n = s.nextInt();
k = s.nextInt();
int[] a = new int[n];
for(int i=0; i<n; i++){
a[i] = s.nextInt();
}
Arrays.sort(a);
for(int i=0; i<n; i++){
if(a[i]%k !=0){
set.add(a[i]);
}else{
if(!set.contains(a[i]/k)){
set.add(a[i]);
}
}
}
System.out.println(set.size());
}
public static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(String s) {
try {
br = new BufferedReader(new FileReader(s));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String nextToken() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
}
}
| nlogn | 274_A. k-Multiple Free Set | CODEFORCES |
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Set;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.TreeSet;
import java.util.StringTokenizer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Zakhar Voit
*/
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 k = in.nextInt();
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
Set <Integer> vis = new TreeSet<Integer>();
Arrays.sort(a);
int ans = 0;
for (int i = 0; i < n; i++) {
if (!(a[i] % k == 0 && vis.contains(a[i] / k))) {
++ans;
vis.add(a[i]);
}
}
out.println(ans);
}
}
class Scanner {
BufferedReader in;
StringTokenizer tok;
public Scanner(InputStream in) {
this.in = new BufferedReader(new InputStreamReader(in));
tok = new StringTokenizer("");
}
public String nextToken() {
if (!tok.hasMoreTokens()) {
try {
String newLine = in.readLine();
if (newLine == null)
throw new InputMismatchException();
tok = new StringTokenizer(newLine);
} catch (IOException e) {
throw new InputMismatchException();
}
return nextToken();
}
return tok.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
}
| nlogn | 274_A. k-Multiple Free Set | 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.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
public class A {
static StringTokenizer st;
static BufferedReader in;
public static void main(String[] args) throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int n = nextInt();
int k = nextInt();
Integer[]a = new Integer[n+1];
for (int i = 1; i <= n; i++) {
a[i] = nextInt();
}
if (k==1) {
System.out.println(n);
return;
}
Arrays.sort(a, 1, n+1);
Set<Integer> set = new HashSet<Integer>();
int ans = 0;
int INF = (int) 1e9;
for (int i = 1; i <= n; i++) {
if (set.contains(a[i]))
continue;
int t = a[i];
int s = 1;
while ((long)t*k <= INF) {
t *= k;
if (Arrays.binarySearch(a, 1, n+1, t) >= 0) {
set.add(t);
s++;
}
else
break;
}
if (s % 2==0)
ans += s/2;
else
ans += s/2+1;
}
System.out.println(ans);
pw.close();
}
private static int nextInt() throws IOException{
return Integer.parseInt(next());
}
private static long nextLong() throws IOException{
return Long.parseLong(next());
}
private static double nextDouble() throws IOException{
return Double.parseDouble(next());
}
private static String next() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
}
| nlogn | 274_A. k-Multiple Free Set | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class CFJava {
private static void println(Integer n) {
System.out.println(n);
}
private static void println(String s) {
System.out.println(s);
}
private static void print(Integer n) {
System.out.print(n);
}
private static void print(String s) {
System.out.print(s);
}
public static void main(String[] args) throws IOException {
MyScanner scanner = new MyScanner();
int n = scanner.nextInt();
int k = scanner.nextInt();
Integer[] a = scanner.getIntArray(n);
Arrays.sort(a);
TreeSet<Integer> res = new TreeSet<Integer>();
for (Integer i: a){
if (!res.contains(i/k)||(i%k!=0))
res.add(i);
}
println(res.size());
}
}
class Pair {
public int x;
public int y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
class MyScanner {
private BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
private String[] buffer;
private int pos = 0;
public Integer nextInt() throws IOException {
if (buffer == null) {
buffer = in.readLine().split(" ");
pos = 0;
}
if (buffer.length <= pos) {
buffer = in.readLine().split(" ");
pos = 0;
}
pos++;
return Integer.parseInt(buffer[pos - 1]);
}
public String nextString() throws IOException {
if (buffer == null) {
buffer = in.readLine().split(" ");
pos = 0;
}
if (buffer.length <= pos) {
buffer = in.readLine().split(" ");
pos = 0;
}
pos++;
return buffer[pos - 1];
}
public ArrayList<Integer> getIntList(Integer n) throws IOException {
ArrayList<Integer> result = new ArrayList<Integer>(n);
for (int i = 0; i < n; i++)
result.add(nextInt());
return result;
}
public Integer[] getIntArray(Integer n) throws IOException {
Integer[] result = new Integer[n];
for (int i = 0; i < n; i++)
result[i]= (nextInt());
return result;
}
}
| nlogn | 274_A. k-Multiple Free Set | CODEFORCES |
import static java.math.BigInteger.*;
import static java.util.Arrays.*;
import java.io.*;
import java.lang.reflect.*;
import java.util.*;
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 K = sc.nextInt();
Long [] A = sc.nextLongs();
sort(A);
Set<Long> S = new HashSet<Long>();
for (long a : A) {
if (a % K == 0 && S.contains(H(a/K)))
continue;
S.add(H(a));
}
int res = S.size();
exit(res);
}
long P = probablePrime(60, new Random()).longValue();
long Q = probablePrime(60, new Random()).longValue();
long H(long x) {
return P*x + Q;
}
////////////////////////////////////////////////////////////////////////////////////
/* Dear hacker, don't bother reading below this line, unless you want to help me debug my I/O routines :-) */
static MyScanner sc = new MyScanner();
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;
}
public String [] next (int N) {
String [] res = new String [N];
for (int i = 0; i < N; ++i)
res[i] = sc.next();
return res;
}
public Integer [] nextInt (int N) {
Integer [] res = new Integer [N];
for (int i = 0; i < N; ++i)
res[i] = sc.nextInt();
return res;
}
public Long [] nextLong (int N) {
Long [] res = new Long [N];
for (int i = 0; i < N; ++i)
res[i] = sc.nextLong();
return res;
}
public Double [] nextDouble (int N) {
Double [] res = new Double [N];
for (int i = 0; i < N; ++i)
res[i] = sc.nextDouble();
return res;
}
public String [][] nextStrings (int N) {
String [][] res = new String [N][];
for (int i = 0; i < N; ++i)
res[i] = sc.nextStrings();
return res;
}
public Integer [][] nextInts (int N) {
Integer [][] res = new Integer [N][];
for (int i = 0; i < N; ++i)
res[i] = sc.nextInts();
return res;
}
public Long [][] nextLongs (int N) {
Long [][] res = new Long [N][];
for (int i = 0; i < N; ++i)
res[i] = sc.nextLongs();
return res;
}
public Double [][] nextDoubles (int N) {
Double [][] res = new Double [N][];
for (int i = 0; i < N; ++i)
res[i] = sc.nextDoubles();
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) {
printDelim(" ", o, a);
}
static void cprint(Object o, Object... a) {
printDelim("", o, a);
}
static void printDelim (String delim, Object o, Object... a) {
pw.println(build(delim, 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(String delim, Object o, Object... a) {
StringBuilder b = new StringBuilder();
append(b, o, delim);
for (Object p : a)
append(b, p, delim);
return b.toString().trim();
}
static void append(StringBuilder b, Object o, String delim) {
if (o.getClass().isArray()) {
int L = Array.getLength(o);
for (int i = 0; i < L; ++i)
append(b, Array.get(o, i), delim);
} else if (o instanceof Iterable<?>) {
for (Object p : (Iterable<?>)o)
append(b, p, delim);
} else
b.append(delim).append(o);
}
////////////////////////////////////////////////////////////////////////////////////
public static void main(String[] args) {
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 | 274_A. k-Multiple Free Set | CODEFORCES |
import java.io.*;
import java.util.*;
import java.math.*;
public class Main {
public static void main(String[] args) {
new Main().run();
}
void run() {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = 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 ret = 0, it = 0;
for (int i = 0; i < n; ++i) {
int val = a[i] % k == 0 ? a[i] / k : -1;
while (it < i && a[it] < val) ++it;
if (it == i || a[it] != val) {
++ret;
}
else {
a[i] = 0;
}
}
out.println(ret);
out.close();
}
}
class InputReader {
BufferedReader buff;
StringTokenizer tokenizer;
InputReader(InputStream stream) {
buff = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
boolean hasNext() {
while (tokenizer == null || !tokenizer.hasMoreTokens())
try {
tokenizer = new StringTokenizer(buff.readLine());
}
catch (Exception e) {
return false;
}
return true;
}
String next() {
if (!hasNext())
throw new RuntimeException();
return tokenizer.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
}
| nlogn | 274_A. k-Multiple Free Set | CODEFORCES |
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.util.HashSet;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author sheep
*/
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 k = in.nextInt();
HashSet<Integer> set = new HashSet<Integer>();
int a[] = new int[n];
for (int i = 0; i < n; ++i) {
a[i] = in.nextInt();
}
Arrays.sort(a);
int ans = 0;
int ptr = -1;
boolean chosen[] = new boolean[n];
for (int i = 0; i < n; ++i) {
while (ptr + 1 < i && a[ptr + 1] * (long)k <= a[i]) {
++ptr;
}
if (a[i] % k != 0 || ptr == -1 || !chosen[ptr] || a[ptr] * (long)k != a[i]) {
++ans;
chosen[i] = true;
}
}
out.println(ans);
}
}
class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (Exception e) {
throw new UnknownError();
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
| nlogn | 274_A. k-Multiple Free Set | CODEFORCES |
import java.io.*;
import java.util.*;
public class A {
public static void main(String[] args) throws Exception {
new A().solve();
// new FileInputStream(new File("input.txt")),
// new PrintStream(new FileOutputStream(new File("output.txt"))));
}
void solve() throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
// Scanner sc = new Scanner(System.in);
String[] sp;
sp = in.readLine().split(" ");
int n = Integer.parseInt(sp[0]);
long k = Integer.parseInt(sp[1]);
Long[] a = new Long[n];
sp = in.readLine().split(" ");
for (int i = 0; i < n; i++) {
a[i] = (long) Integer.parseInt(sp[i]);
}
Arrays.sort(a);
TreeSet<Long> set = new TreeSet<Long>();
for (int i = 0; i < n; i++) {
long x = a[i];
if (!set.contains(x)) {
set.add(x * k);
}
}
System.out.println(set.size());
}
}
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
| nlogn | 274_A. k-Multiple Free Set | CODEFORCES |
import java.util.*;
import java.math.*;
import java.io.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
public class test{
// ArrayList<Integer> lis = new ArrayList<Integer>();
// ArrayList<String> lis = new ArrayList<String>();
// PriorityQueue<P> que = new PriorityQueue<P>();
// PriorityQueue<Integer> que = new PriorityQueue<Integer>();
// Stack<Integer> que = new Stack<Integer>();
// static long sum=0;
// 1000000007 (10^9+7)
static int mod = 1000000007;
//static int mod = 1000000009,r=0;
// static int dx[]={1,-1,0,0};
// static int dy[]={0,0,1,-1};
// static int dx[]={1,-1,0,0,1,1,-1,-1};
// static int dy[]={0,0,1,-1,1,-1,1,-1};
//static long H,L;
//static Set<Integer> set = new HashSet<Integer>();
public static void main(String[] args) throws Exception, IOException{
//String line=""; throws Exception, IOException
//(line=br.readLine())!=null
//Scanner sc =new Scanner(System.in);
// !!caution!! int long //
Reader sc = new Reader(System.in);
// while( ){
// int n=sc.nextInt(),m=sc.nextInt();//a[]=new int[n],b[]=new int[n];
int n=sc.nextInt(),r=0;long k=sc.nextInt();
Integer x[]=new Integer[n];
boolean b[]=new boolean[n];
for(int i=0;i<n;i++){
x[i]=sc.nextInt();
}
if( k==1 ){System.out.println(n); return;}
sort(x);
for(int i=0;i<n;i++){
if( b[i] )continue;
r++;
long p=x[i],pr=x[i];
while( p*k<=x[n-1] ) {p*=k;
int up=n,dw=0,mid=(up+dw)/2;
boolean f=false;
while( up-dw!=1 ){
//db(p,x[mid]);
if( x[mid]==p ){f=true;break;}
if( p<x[mid] ){ up=mid; mid=(up+dw)/2; }
else { dw=mid; mid=(up+dw)/2; }
}
if( f ){ if(pr*k!=p){r++; pr=p;} b[mid]=true; }
}
}
System.out.println(r);
}
static void db(Object... os){
System.err.println(Arrays.deepToString(os));
}
}
class Reader
{
private BufferedReader x;
private StringTokenizer st;
public Reader(InputStream in)
{
x = new BufferedReader(new InputStreamReader(in));
st = null;
}
public String nextString() throws IOException
{
while( st==null || !st.hasMoreTokens() )
st = new StringTokenizer(x.readLine());
return st.nextToken();
}
public int nextInt() throws IOException
{
return Integer.parseInt(nextString());
}
public long nextLong() throws IOException
{
return Long.parseLong(nextString());
}
public double nextDouble() throws IOException
{
return Double.parseDouble(nextString());
}
}
/*
class P implements Comparable<P>{
int x,y;
P(int x,int y){ this.x=x; this.y=y; }
public int compareTo(P z) {
if( x-z.x!=0) return x-z.x ; //ascend
else return y-z.y ;
}
}
//*/
| nlogn | 274_A. k-Multiple Free Set | CODEFORCES |
import java.util.*;
import java.io.*;
public class a {
public static void main(String[] args) throws IOException
{
input.init(System.in);
int n = input.nextInt(), k = input.nextInt();
TreeSet<Integer> ts = new TreeSet<Integer>();
int[] data = new int[n];
for(int i = 0; i<n; i++)
{
data[i] = input.nextInt();
}
Arrays.sort(data);
if(n>1 && k==1.*data[n-1]/data[0])
System.out.println(n-1);
else
{
for(int i = 0; i<n; i++)
{
if(data[i]%k != 0)
ts.add(data[i]);
else
{
if(!ts.contains(data[i]/k))
ts.add(data[i]);
}
}
System.out.println(ts.size());
}
}
public static class input {
static BufferedReader reader;
static StringTokenizer tokenizer;
/** call this method to initialize reader for InputStream */
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input) );
tokenizer = new StringTokenizer("");
}
/** get next word */
static String next() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer(
reader.readLine() );
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt( next() );
}
static double nextDouble() throws IOException {
return Double.parseDouble( next() );
}
static long nextLong() throws IOException {
return Long.parseLong( next() );
}
}
}
| nlogn | 274_A. k-Multiple Free Set | CODEFORCES |
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.TreeSet;
public class Main {
public static void main(String [] args ) {
try{
String str;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedOutputStream bos = new BufferedOutputStream(System.out);
String eol = System.getProperty("line.separator");
byte [] eolb = eol.getBytes();
byte[] spaceb= " ".getBytes();
str = br.readLine();
int blank = str.indexOf( " ");
int n = Integer.parseInt(str.substring(0,blank));
int m = Integer.parseInt(str.substring(blank+1));
long [] num = new long[n];
int j=0;
int s=0;
int k =0;
str = br.readLine();
int length = str.length();
while(j<length) {
while(j<length) {
if(str.charAt(j) == ' ') {
break;
}else {
j++;
}
}
num[k] = Long.parseLong(str.substring(s,j)) ;
k++;
j++;
s=j;
}
Arrays.sort(num);
int count = 0;
if(m==1) {
count = 1;
for(int i = 1 ; i < n ; i++) {
if(num[i]!=num[i-1]) {
count++;
}
}
} else {
TreeSet<Long> take = new TreeSet<Long>();
TreeSet<Long> notTake = new TreeSet<Long>();
for(int i = 0 ; i < n ; i++) {
long temp = num[i];
if(!notTake.contains(temp)){
take.add(temp);
temp *= ((long)m);
notTake.add(temp);
}
}
count = take.size();
}
bos.write(new Integer(count).toString().getBytes());
bos.write(eolb);
bos.flush();
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
}
| nlogn | 274_A. k-Multiple Free Set | CODEFORCES |
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.util.Locale;
import java.io.OutputStream;
import java.util.RandomAccess;
import java.io.PrintWriter;
import java.util.AbstractList;
import java.io.Writer;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.TreeMap;
import java.math.BigInteger;
import java.util.Collections;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Jacob Jiang
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
long k = in.nextInt();
if (k == 1) {
out.println(n);
return;
}
long[] a = in.nextLongArray(n);
ArrayUtils.safeSort(a);
Map<Long, Integer> map = new TreeMap<Long, Integer>();
for (int i = 0; i < n; i++) {
map.put(a[i], i);
}
int answer = 0;
boolean[] visited = new boolean[n];
for (int i = 0; i < n; i++) {
if (!visited[i]) {
visited[i] = true;
int count = 1;
long cur = a[i];
while (true) {
cur *= k;
Integer index = map.get(cur);
if (index == null)
break;
visited[index] = true;
count++;
}
answer += NumberUtils.upDiv(count, 2);
}
}
out.println(answer);
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1 << 16];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c & 15;
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public static boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public 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 & 15;
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long[] nextLongArray(int count) {
long[] result = new long[count];
for (int i = 0; i < count; i++) {
result[i] = nextLong();
}
return result;
}
}
class OutputWriter {
private PrintWriter writer;
public OutputWriter(OutputStream stream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void println(int i) {
writer.println(i);
}
public void close() {
writer.close();
}
}
class ArrayUtils {
public static List<Long> asList(long[] array) {
return new LongList(array);
}
private static class LongList extends AbstractList<Long> implements RandomAccess {
long[] array;
private LongList(long[] array) {
this.array = array;
}
public Long set(int index, Long element) {
long result = array[index];
array[index] = element;
return result;
}
public Long get(int index) {
return array[index];
}
public int size() {
return array.length;
}
}
public static void safeSort(long[] array) {
Collections.shuffle(asList(array));
Arrays.sort(array);
}
}
class NumberUtils {
public static int upDiv(int a, int b) {
return a % b == 0 ? (a / b) : (a / b + 1);
}
}
| nlogn | 274_A. k-Multiple Free Set | CODEFORCES |
import static java.lang.Math.*;
import static java.util.Arrays.*;
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws Exception {
Class<?> here = new Object(){}.getClass().getEnclosingClass();
try {
String packageName = here.getPackage().getName();
packageName = "src/" + packageName.replaceAll("\\.", "/") + "/";
System.setIn(new FileInputStream(packageName + "input.txt"));
// System.setOut(new PrintStream(new FileOutputStream(packageName + "output.txt")));
} catch (FileNotFoundException e) {
} catch (NullPointerException e) {
}
Object o = Class.forName(here.getName()).newInstance();
o.getClass().getMethod("run").invoke(o);
}
static void tr(Object... os) {
System.err.println(deepToString(os));
}
MyScanner sc = null;
PrintWriter out = null;
public void run() throws Exception {
sc = new MyScanner(System.in);
out = new PrintWriter(System.out);
for (;sc.hasNext();) {
solve();
out.flush();
}
out.close();
}
void solve() {
int n = sc.nextInt();
int k = sc.nextInt();
TreeSet<Integer> at = new TreeSet<Integer>();
for (int i = 0; i < n; i++) at.add(sc.nextInt());
Integer[] ai = at.toArray(new Integer[0]);
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = ai[i];
if (k == 1) {
out.println(n);
return;
}
boolean[] invalid = new boolean[n];
tr(a);
int ans = 0;
for (int i = 0, j = 0; i < n; i++) if (!invalid[i]) {
++ans;
long kx = (long)k * a[i];
while (j < n && a[j] < kx) {
j++;
}
if (j < n && kx == a[j]) {
invalid[j] = true;
}
}
out.println(ans);
}
void print(int[] a) {
out.print(a[0]);
for (int i = 1; i < a.length; i++) out.print(" " + a[i]);
out.println();
}
class MyScanner {
String line;
BufferedReader reader;
StringTokenizer tokenizer;
public MyScanner(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public void eat() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
line = reader.readLine();
if (line == null) {
tokenizer = null;
return;
}
tokenizer = new StringTokenizer(line);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
public String next() {
eat();
return tokenizer.nextToken();
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public boolean hasNext() {
eat();
return (tokenizer != null && tokenizer.hasMoreElements());
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
}
}
| nlogn | 274_A. k-Multiple Free Set | CODEFORCES |
import java.io.*;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.TreeSet;
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();
long k = readInt();
Long[] a = new Long[n];
for(int i = 0; i < n; i++){
a[i] = readLong();
}
Arrays.sort(a);
TreeSet<Long> set = new TreeSet<Long>();
for(int i = 0; i < n; i++){
set.add(a[i]);
}
if(k == 1) {
out.println(n);
return;
}
int res = 0;
TreeSet<Long> used = new TreeSet<Long>();
for(Long cur: set){
if(!used.contains(cur)){
int num = 1;
used.add(cur);
Long temp = cur * 1;
while(true){
if(set.contains(k*temp)){
num++;
used.add(k*temp);
temp *= k;
}
else{
res += (num+1)/2;
break;
}
}
}
}
out.println(res);
}
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 | 274_A. k-Multiple Free Set | CODEFORCES |
import java.util.*;
import java.io.*;
public class solve {
Scanner in;
PrintWriter out;
public void solve() throws IOException {
int n = in.nextInt();
long k = in.nextLong();
int[] a = new int[n];
Set<Long> b = new TreeSet<Long>();
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
Arrays.sort(a);
int ans = 0;
for (int i = n - 1; i >= 0; i--) {
if (!b.contains((long) k * a[i])) {
ans++;
b.add((long) a[i]);
}
}
out.print(ans);
}
public void run() {
try {
in = new Scanner(System.in);
out = new PrintWriter(System.out);
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
}
public static void main(String[] arg) {
new solve().run();
}
}
| nlogn | 274_A. k-Multiple Free Set | CODEFORCES |
import java.io.DataInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
public class div168C {
public static void main(String[] args) throws Exception{
div168C a=new div168C();
Parserdoubt pd=a.new Parserdoubt(System.in);
StringBuffer sb = new StringBuffer();
ArrayList<Integer> arr=new ArrayList<Integer>();
int max=0;
int n=pd.nextInt();
int k=pd.nextInt();
for(int i=0;i<n;i++){
arr.add(pd.nextInt());
max=Math.max(max, arr.get(i));
}
Collections.sort(arr);
int count=0;
int[] mat=new int[n+1];
for(int i=n-1;i>=0;i--){
if(mat[i]!=1){
int x=arr.get(i);
if(x%k==0){
int ans=Collections.binarySearch(arr, x/k);
// System.out.println("index "+ans);
if(ans>=0&&arr.get(ans)==(x/k)){
count++;
mat[ans]=1;
}
else{
count++;
}
}
else{
count++;
}
}
}
/*for(int i=0;i<arr.size();i++){
System.out.print(arr.get(i)+" ");
}
System.out.println();
*/
if(n==1)
count=1;
System.out.println(count);
}
class Parserdoubt
{
final private int BUFFER_SIZE = 1 << 17;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Parserdoubt(InputStream in)
{
din = new DataInputStream(in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String nextString() throws Exception
{
StringBuffer sb=new StringBuffer("");
byte c = read();
while (c <= ' ') c = read();
do
{
sb.append((char)c);
c=read();
}while(c>' ');
return sb.toString();
}
public char nextChar() throws Exception
{
byte c=read();
while(c<=' ') c= read();
return (char)c;
}
public int nextInt() throws Exception
{
int ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = c == '-';
if (neg) c = read();
do
{
ret = ret * 10 + c - '0';
c = read();
} while (c > ' ');
if (neg) return -ret;
return ret;
}
public long nextLong() throws Exception
{
long ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = c == '-';
if (neg) c = read();
do
{
ret = ret * 10 + c - '0';
c = read();
} while (c > ' ');
if (neg) return -ret;
return ret;
}
private void fillBuffer() throws Exception
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) buffer[0] = -1;
}
private byte read() throws Exception
{
if (bufferPointer == bytesRead) fillBuffer();
return buffer[bufferPointer++];
}
}
}
| nlogn | 274_A. k-Multiple Free Set | CODEFORCES |
import static java.math.BigInteger.*;
import static java.util.Arrays.*;
import java.io.*;
import java.lang.reflect.*;
import java.util.*;
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 K = sc.nextInt();
Long [] A = sc.nextLongs();
sort(A);
Set<Long> S = new HashSet<Long>();
for (long a : A) {
if (a % K == 0 && S.contains(H(a/K)))
continue;
S.add(H(a));
}
int res = S.size();
exit(res);
}
long P = probablePrime(60, new Random()).longValue();
long Q = probablePrime(60, new Random()).longValue();
long H(long x) {
return (P*x) % Q;
}
////////////////////////////////////////////////////////////////////////////////////
/* Dear hacker, don't bother reading below this line, unless you want to help me debug my I/O routines :-) */
static MyScanner sc = new MyScanner();
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;
}
public String [] next (int N) {
String [] res = new String [N];
for (int i = 0; i < N; ++i)
res[i] = sc.next();
return res;
}
public Integer [] nextInt (int N) {
Integer [] res = new Integer [N];
for (int i = 0; i < N; ++i)
res[i] = sc.nextInt();
return res;
}
public Long [] nextLong (int N) {
Long [] res = new Long [N];
for (int i = 0; i < N; ++i)
res[i] = sc.nextLong();
return res;
}
public Double [] nextDouble (int N) {
Double [] res = new Double [N];
for (int i = 0; i < N; ++i)
res[i] = sc.nextDouble();
return res;
}
public String [][] nextStrings (int N) {
String [][] res = new String [N][];
for (int i = 0; i < N; ++i)
res[i] = sc.nextStrings();
return res;
}
public Integer [][] nextInts (int N) {
Integer [][] res = new Integer [N][];
for (int i = 0; i < N; ++i)
res[i] = sc.nextInts();
return res;
}
public Long [][] nextLongs (int N) {
Long [][] res = new Long [N][];
for (int i = 0; i < N; ++i)
res[i] = sc.nextLongs();
return res;
}
public Double [][] nextDoubles (int N) {
Double [][] res = new Double [N][];
for (int i = 0; i < N; ++i)
res[i] = sc.nextDoubles();
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) {
printDelim(" ", o, a);
}
static void cprint(Object o, Object... a) {
printDelim("", o, a);
}
static void printDelim (String delim, Object o, Object... a) {
pw.println(build(delim, 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(String delim, Object o, Object... a) {
StringBuilder b = new StringBuilder();
append(b, o, delim);
for (Object p : a)
append(b, p, delim);
return b.toString().trim();
}
static void append(StringBuilder b, Object o, String delim) {
if (o.getClass().isArray()) {
int L = Array.getLength(o);
for (int i = 0; i < L; ++i)
append(b, Array.get(o, i), delim);
} else if (o instanceof Iterable<?>) {
for (Object p : (Iterable<?>)o)
append(b, p, delim);
} else
b.append(delim).append(o);
}
////////////////////////////////////////////////////////////////////////////////////
public static void main(String[] args) {
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 | 274_A. k-Multiple Free Set | CODEFORCES |
import java.util.*;
import java.io.*;
import java.awt.Point;
import java.math.BigInteger;
import static java.lang.Math.*;
// Solution is at the bottom of code
public class _AAAA implements Runnable{
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
BufferedReader in;
OutputWriter out;
StringTokenizer tok = new StringTokenizer("");
public static void main(String[] args){
new Thread(null, new _AAAA(), "", 128 * (1L << 20)).start();
}
/////////////////////////////////////////////////////////////////////
void init() throws FileNotFoundException{
Locale.setDefault(Locale.US);
if (ONLINE_JUDGE){
in = new BufferedReader(new InputStreamReader(System.in));
out = new OutputWriter(System.out);
}else{
in = new BufferedReader(new FileReader("input.txt"));
out = new OutputWriter("output.txt");
}
}
////////////////////////////////////////////////////////////////
long timeBegin, timeEnd;
void time(){
timeEnd = System.currentTimeMillis();
System.err.println("Time = " + (timeEnd - timeBegin));
}
void debug(Object... objects){
if (ONLINE_JUDGE){
for (Object o: objects){
System.err.println(o.toString());
}
}
}
/////////////////////////////////////////////////////////////////////
public void run(){
try{
timeBegin = System.currentTimeMillis();
Locale.setDefault(Locale.US);
init();
solve();
out.close();
time();
}catch (Exception e){
e.printStackTrace(System.err);
System.exit(-1);
}
}
/////////////////////////////////////////////////////////////////////
String delim = " ";
String readString() throws IOException{
while(!tok.hasMoreTokens()){
try{
tok = new StringTokenizer(in.readLine());
}catch (Exception e){
return null;
}
}
return tok.nextToken(delim);
}
String readLine() throws IOException{
return in.readLine();
}
/////////////////////////////////////////////////////////////////
final char NOT_A_SYMBOL = '\0';
char readChar() throws IOException{
int intValue = in.read();
if (intValue == -1){
return NOT_A_SYMBOL;
}
return (char) intValue;
}
char[] readCharArray() throws IOException{
return readLine().toCharArray();
}
/////////////////////////////////////////////////////////////////
int readInt() throws IOException{
return Integer.parseInt(readString());
}
int[] readIntArray(int size) throws IOException{
int[] array = new int[size];
for (int index = 0; index < size; ++index){
array[index] = readInt();
}
return array;
}
///////////////////////////////////////////////////////////////////
long readLong() throws IOException{
return Long.parseLong(readString());
}
long[] readLongArray(int size) throws IOException{
long[] array = new long[size];
for (int index = 0; index < size; ++index){
array[index] = readLong();
}
return array;
}
////////////////////////////////////////////////////////////////////
double readDouble() throws IOException{
return Double.parseDouble(readString());
}
double[] readDoubleArray(int size) throws IOException{
double[] array = new double[size];
for (int index = 0; index < size; ++index){
array[index] = readDouble();
}
return array;
}
/////////////////////////////////////////////////////////////////////
Point readPoint() throws IOException{
return new Point(readInt(), readInt());
}
Point[] readPointArray(int size) throws IOException{
Point[] array = new Point[size];
for (int index = 0; index < size; ++index){
array[index] = readPoint();
}
return array;
}
/////////////////////////////////////////////////////////////////////
class OutputWriter extends PrintWriter{
final int DEFAULT_PRECISION = 12;
int precision;
String format, formatWithSpace;
{
precision = DEFAULT_PRECISION;
format = createFormat(precision);
formatWithSpace = format + " ";
}
public OutputWriter(OutputStream out) {
super(out);
}
public OutputWriter(String fileName) throws FileNotFoundException {
super(fileName);
}
public int getPrecision() {
return precision;
}
public void setPrecision(int precision) {
this.precision = precision;
format = createFormat(precision);
formatWithSpace = format + " ";
}
private String createFormat(int precision){
return "%." + precision + "f";
}
@Override
public void print(double d){
printf(format, d);
}
public void printWithSpace(double d){
printf(formatWithSpace, d);
}
public void printAll(double...d){
for (int i = 0; i < d.length - 1; ++i){
printWithSpace(d[i]);
}
print(d[d.length - 1]);
}
@Override
public void println(double d){
printlnAll(d);
}
public void printlnAll(double... d){
printAll(d);
println();
}
}
/////////////////////////////////////////////////////////////////////
int[][] steps = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
boolean check(int index, int lim){
return (0 <= index && index < lim);
}
/////////////////////////////////////////////////////////////////////
void solve() throws IOException{
int n = readInt();
int k = readInt();
Map<Long, Integer> map = new TreeMap<Long, Integer>();
for (int i = 0; i < n; ++i){
map.put(readLong(), i);
}
int ans = 0;
boolean[] used = new boolean[n];
for (Map.Entry<Long, Integer> e: map.entrySet()){
if (used[e.getValue()]) continue;
long value = e.getKey() * k;
Integer index = map.get(value);
if (index != null){
used[index] = true;
}
++ans;
}
out.println(ans);
}
}
| nlogn | 274_A. k-Multiple Free Set | CODEFORCES |
import java.io.DataInputStream;
import java.io.InputStream;
import java.util.Arrays;
import java.util.TreeSet;
public class Main{
public static void main(String[] args) throws Exception {
Parserdoubt3 s = new Parserdoubt3(System.in);
int n = s.nextInt();
long k = s.nextInt();
Long a[] = new Long[n];
TreeSet<Long> tree = new TreeSet<Long>();
for (int i = 0; i < a.length; i++) {
a[i] = s.nextLong();
tree.add(a[i]);
}
Arrays.sort(a);
int ans = 0;
for (int i = 0; i < a.length; i++) {
if(tree.contains(a[i])){
ans++;
long next = a[i] * k;
if(tree.contains(next)) tree.remove(next);
}
}
System.out.println(ans);
}
}
class Parserdoubt3 {
final private int BUFFER_SIZE = 1 << 17;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Parserdoubt3(InputStream in) {
din = new DataInputStream(in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String nextString() throws Exception {
StringBuffer sb = new StringBuffer("");
byte c = read();
while (c <= ' ')
c = read();
do {
sb.append((char) c);
c = read();
} while (c > ' ');
return sb.toString();
}
public char nextChar() throws Exception {
byte c = read();
while (c <= ' ')
c = read();
return (char) c;
}
public int nextInt() throws Exception {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = c == '-';
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
c = read();
} while (c > ' ');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws Exception {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = c == '-';
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
c = read();
} while (c > ' ');
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws Exception {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws Exception {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
} | nlogn | 274_A. k-Multiple Free Set | CODEFORCES |
import java.io.*;
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 k = sc.nextInt();
TreeSet<Integer> bad = new TreeSet<>();
int a [] = new int [n];
for (int i = 0; i < n; i++)
a[i] = sc.nextInt();
Arrays.sort(a);
int result = 0;
for (int i = 0; i < n; i++) {
if (!bad.contains(a[i])) {
result++;
long next = (long) a[i] * k;
if (next <= 1000000000)
bad.add((int) next);
}
}
out.println(result);
}
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 | 274_A. k-Multiple Free Set | CODEFORCES |
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.Scanner;
public class f {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
Hashtable<Long, Boolean> d = new Hashtable<Long, Boolean>();
int n = in.nextInt(), k = in.nextInt(), size = 0, a[] = new int[n];
for (int i = 0; i < n; i++) a[i] = in.nextInt();
Arrays.sort(a);
for (int i = 0; i < n; i++) {
long x = a[i];
if (!d.containsKey(x)) {
d.put(x * k, true);
size++;
}
}
System.out.println(size);
}
}
| nlogn | 274_A. k-Multiple Free Set | CODEFORCES |
import java.io.*;
import java.util.*;
import java.math.*;
public class Main {
public static void main(String[] args) {
new Main().run();
}
void run() {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = 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 ret = 0, it = 0;
for (int i = 0; i < n; ++i) {
int val = a[i] % k == 0 ? a[i] / k : -1;
while (it < i && a[it] < val) ++it;
if (it == i || a[it] != val) {
++ret;
}
else {
a[i] = 0;
}
}
out.println(ret);
out.close();
}
}
class InputReader {
BufferedReader buff;
StringTokenizer tokenizer;
InputReader(InputStream stream) {
buff = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
boolean hasNext() {
while (tokenizer == null || !tokenizer.hasMoreTokens())
try {
tokenizer = new StringTokenizer(buff.readLine());
}
catch (Exception e) {
return false;
}
return true;
}
String next() {
if (!hasNext())
throw new RuntimeException();
return tokenizer.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
}
| nlogn | 274_A. k-Multiple Free Set | CODEFORCES |
import java.io.*;
import java.util.*;
import java.util.Map.Entry;
public class Main {
Scanner in;
static PrintWriter out;
static class Scanner {
StreamTokenizer in;
Scanner(InputStream is) {
in = new StreamTokenizer(new BufferedReader(new InputStreamReader(is)));
in.resetSyntax();
in.whitespaceChars(0, 32);
in.wordChars(33, 255);
}
String readLine() {
try {
in.nextToken();
asserT(in.ttype == StreamTokenizer.TT_WORD);
return in.sval;
} catch (IOException e) {
throw new Error();
}
}
int nextInt() {
return Integer.parseInt(readLine());
}
}
void solve() {
int n = in.nextInt();
long k = in.nextInt();
int ar[] = new int[n];
TreeMap <Integer, Integer> nums = new TreeMap<Integer, Integer>();
for (int i = 0; i < n; i++) {
ar[i] = in.nextInt();
nums.put(ar[i], i);
}
if (k == 1) {
out.println(n);
return;
}
int next[] = new int[n];
Arrays.fill(next, -1);
int count = 0;
for (int i = 0; i < n; i++) {
long val = ar[i] * k;
int intVal = (int)val;
if (intVal == val) {
if (nums.containsKey(intVal)) {
int idx = nums.get(intVal);
next[i] = idx;
continue;
}
}
if (ar[i] % k == 0) {
intVal = ar[i] / (int)k;
if (nums.containsKey(intVal)) {
continue;
}
}
count++;
}
for (int i = 0; i < n; i++) {
int curr = nums.pollFirstEntry().getValue();
boolean odd = false;
while (next[curr] != -1) {
if (!odd) {
count++;
}
int to = next[curr];
next[curr] = -1;
curr = to;
odd = !odd;
if (next[curr] == -1) {
if (!odd) {
count++;
}
}
}
}
out.println(count);
}
static void asserT(boolean e) {
if (!e) {
throw new Error();
}
}
public void run() {
in = new Scanner(System.in);
out = new PrintWriter(System.out);
try {
solve();
} finally {
out.close();
}
}
public static void main(String[] args) {
new Main().run();
}
} | nlogn | 274_A. k-Multiple Free Set | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class ProblemA {
public static void main(String[] args) throws IOException {
BufferedReader s = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
String[] data = s.readLine().split(" ");
int n = Integer.valueOf(data[0]);
int k = Integer.valueOf(data[1]);
long[] a = new long[n];
String[] ai = s.readLine().split(" ");
for (int i = 0 ; i < n ; i++) {
a[i] = Integer.valueOf(ai[i]);
}
for (int i = 0 ; i < n ; i++) {
int tm = (int)(Math.random() * n);
long tmp = a[tm];
a[tm] = a[i];
a[i] = tmp;
}
Arrays.sort(a);
Set<Long> invalid = new HashSet<Long>();
int cnt = 0;
for (int i = 0 ; i < n ; i++) {
if (!invalid.contains(a[i])) {
cnt++;
invalid.add(a[i] * k);
}
}
out.println(cnt);
out.flush();
}
public static void debug(Object... os){
System.err.println(Arrays.deepToString(os));
}
} | nlogn | 274_A. k-Multiple Free Set | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class A {
public static void main(String[] args) throws IOException {
InputReader in = new InputReader();
int n = in.nextInt();
long k = in.nextInt();
Long[] a = new Long[n];
for(int i = 0 ; i < n;i++)a[i]=in.nextLong();
if(k==1)System.out.println(n);
else{
int res = 0;
Arrays.sort(a);
boolean[] v = new boolean[n];
for(int i = 0 ; i < n;i++){
if(!v[i]){
long cur = a[i];
int cnt = 1;
while(true){
int idx = Arrays.binarySearch(a, cur*k);
if(idx<0){
res+= cnt/2 + cnt%2;
break;
}
v[idx]=true;
cur = a[idx];
cnt++;
}
}
}
System.out.println(res);
}
}
static class InputReader {
BufferedReader in;
StringTokenizer st;
public InputReader() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(in.readLine());
}
public String next() throws IOException {
while (!st.hasMoreElements())
st = new StringTokenizer(in.readLine());
return st.nextToken();
}
public int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(next());
}
public long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(next());
}
}
} | nlogn | 274_A. k-Multiple Free Set | CODEFORCES |
import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author NAO93
*/
public class a {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
long k = in.nextLong();
Long []a = new Long[n];
for (int i = 0; i<n; i++)
a[i] = in.nextLong();
HashSet<Long> hash = new HashSet<Long>();
Arrays.sort(a);
for (int i = 0; i<n; i++)
if (!hash.contains(a[i])){
hash.add(a[i] * k);
}
System.out.println(hash.size());
}
}
| nlogn | 274_A. k-Multiple Free Set | CODEFORCES |
import java.util.*;
import java.io.*;
import java.awt.Point;
import static java.lang.Math.*;
public class P274A {
public static int i(String s) { return Integer.parseInt(s); }
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String[] arr = in.readLine().split(" ");
int n = i(arr[0]);
long k = i(arr[1]);
long[] A = new long[n];
arr = in.readLine().split(" ");
for(int i=0; i<n; i++)
A[i] = i(arr[i]);
shuffle(A);
Arrays.sort(A);
Set<Long> BAN = new HashSet<Long>();
int ans = 0;
for(int i=0; i<n; i++) {
if(!BAN.contains(A[i])) {
ans++;
BAN.add(A[i]*k);
}
}
System.out.println(ans);
}
public static void shuffle(long[] array) {
for (int i = array.length; i > 1; i--) {
long temp = array[i - 1];
int randIx = (int) (Math.random() * i);
array[i - 1] = array[randIx];
array[randIx] = temp;
}
}
}
| nlogn | 274_A. k-Multiple Free Set | CODEFORCES |
import static java.util.Arrays.*;
import java.io.*;
import java.lang.reflect.*;
import java.util.*;
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 K = sc.nextInt();
Long [] A = sc.nextLongs();
sort(A);
TreeSet<Long> S = new TreeSet<Long>();
for (long a : A) {
if (a % K == 0 && S.contains(a/K))
continue;
S.add(a);
}
int res = S.size();
exit(res);
}
////////////////////////////////////////////////////////////////////////////////////
/* Dear hacker, don't bother reading below this line, unless you want to help me debug my I/O routines :-) */
static MyScanner sc = new MyScanner();
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;
}
public String [] next (int N) {
String [] res = new String [N];
for (int i = 0; i < N; ++i)
res[i] = sc.next();
return res;
}
public Integer [] nextInt (int N) {
Integer [] res = new Integer [N];
for (int i = 0; i < N; ++i)
res[i] = sc.nextInt();
return res;
}
public Long [] nextLong (int N) {
Long [] res = new Long [N];
for (int i = 0; i < N; ++i)
res[i] = sc.nextLong();
return res;
}
public Double [] nextDouble (int N) {
Double [] res = new Double [N];
for (int i = 0; i < N; ++i)
res[i] = sc.nextDouble();
return res;
}
public String [][] nextStrings (int N) {
String [][] res = new String [N][];
for (int i = 0; i < N; ++i)
res[i] = sc.nextStrings();
return res;
}
public Integer [][] nextInts (int N) {
Integer [][] res = new Integer [N][];
for (int i = 0; i < N; ++i)
res[i] = sc.nextInts();
return res;
}
public Long [][] nextLongs (int N) {
Long [][] res = new Long [N][];
for (int i = 0; i < N; ++i)
res[i] = sc.nextLongs();
return res;
}
public Double [][] nextDoubles (int N) {
Double [][] res = new Double [N][];
for (int i = 0; i < N; ++i)
res[i] = sc.nextDoubles();
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) {
printDelim(" ", o, a);
}
static void cprint(Object o, Object... a) {
printDelim("", o, a);
}
static void printDelim (String delim, Object o, Object... a) {
pw.println(build(delim, 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(String delim, Object o, Object... a) {
StringBuilder b = new StringBuilder();
append(b, o, delim);
for (Object p : a)
append(b, p, delim);
return b.toString().trim();
}
static void append(StringBuilder b, Object o, String delim) {
if (o.getClass().isArray()) {
int L = Array.getLength(o);
for (int i = 0; i < L; ++i)
append(b, Array.get(o, i), delim);
} else if (o instanceof Iterable<?>) {
for (Object p : (Iterable<?>)o)
append(b, p, delim);
} else
b.append(delim).append(o);
}
////////////////////////////////////////////////////////////////////////////////////
public static void main(String[] args) {
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 | 274_A. k-Multiple Free Set | CODEFORCES |
/* Codeforces Template */
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.fill;
import static java.util.Arrays.binarySearch;
import static java.util.Arrays.sort;
public class Main {
static long initTime;
static final Random rnd = new Random(7777L);
static boolean writeLog = false;
public static void main(String[] args) throws IOException {
initTime = System.currentTimeMillis();
try {
writeLog = "true".equals(System.getProperty("LOCAL_RUN_7777"));
} catch (SecurityException e) {}
new Thread(null, new Runnable() {
public void run() {
try {
try {
if (new File("input.txt").exists())
System.setIn(new FileInputStream("input.txt"));
} catch (SecurityException e) {}
long prevTime = System.currentTimeMillis();
new Main().run();
log("Total time: " + (System.currentTimeMillis() - prevTime) + " ms");
log("Memory status: " + memoryStatus());
} catch (IOException e) {
e.printStackTrace();
}
}
}, "1", 1L << 24).start();
}
void run() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
in.close();
}
/***************************************************************
* Solution
**************************************************************/
void solve() throws IOException {
int n = nextInt();
long k = nextLong();
int[] a = nextIntArray(n);
Set<Long> bad = new TreeSet<Long>();
sort(a);
int ans = 0;
for (int x : a) {
if (!bad.contains((long) x)) {
bad.add(x * k);
ans++;
}
}
out.println(ans);
}
/***************************************************************
* Input
**************************************************************/
BufferedReader in;
PrintWriter out;
StringTokenizer st = new StringTokenizer("");
String nextToken() throws IOException {
while (!st.hasMoreTokens())
st = new StringTokenizer(in.readLine());
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
int[] nextIntArray(int size) throws IOException {
int[] ret = new int [size];
for (int i = 0; i < size; i++)
ret[i] = nextInt();
return ret;
}
long[] nextLongArray(int size) throws IOException {
long[] ret = new long [size];
for (int i = 0; i < size; i++)
ret[i] = nextLong();
return ret;
}
double[] nextDoubleArray(int size) throws IOException {
double[] ret = new double [size];
for (int i = 0; i < size; i++)
ret[i] = nextDouble();
return ret;
}
String nextLine() throws IOException {
st = new StringTokenizer("");
return in.readLine();
}
boolean EOF() throws IOException {
while (!st.hasMoreTokens()) {
String s = in.readLine();
if (s == null)
return true;
st = new StringTokenizer(s);
}
return false;
}
/***************************************************************
* Output
**************************************************************/
void printRepeat(String s, int count) {
for (int i = 0; i < count; i++)
out.print(s);
}
void printArray(int[] array) {
if (array == null || array.length == 0)
return;
for (int i = 0; i < array.length; i++) {
if (i > 0) out.print(' ');
out.print(array[i]);
}
out.println();
}
void printArray(long[] array) {
if (array == null || array.length == 0)
return;
for (int i = 0; i < array.length; i++) {
if (i > 0) out.print(' ');
out.print(array[i]);
}
out.println();
}
void printArray(double[] array) {
if (array == null || array.length == 0)
return;
for (int i = 0; i < array.length; i++) {
if (i > 0) out.print(' ');
out.print(array[i]);
}
out.println();
}
void printArray(double[] array, String spec) {
if (array == null || array.length == 0)
return;
for (int i = 0; i < array.length; i++) {
if (i > 0) out.print(' ');
out.printf(Locale.US, spec, array[i]);
}
out.println();
}
void printArray(Object[] array) {
if (array == null || array.length == 0)
return;
boolean blank = false;
for (Object x : array) {
if (blank) out.print(' '); else blank = true;
out.print(x);
}
out.println();
}
@SuppressWarnings("rawtypes")
void printCollection(Collection collection) {
if (collection == null || collection.isEmpty())
return;
boolean blank = false;
for (Object x : collection) {
if (blank) out.print(' '); else blank = true;
out.print(x);
}
out.println();
}
/***************************************************************
* Utility
**************************************************************/
static String memoryStatus() {
return (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory() >> 20) + "/" + (Runtime.getRuntime().totalMemory() >> 20) + " MB";
}
static void checkMemory() {
System.err.println(memoryStatus());
}
static long prevTimeStamp = Long.MIN_VALUE;
static void updateTimer() {
prevTimeStamp = System.currentTimeMillis();
}
static long elapsedTime() {
return (System.currentTimeMillis() - prevTimeStamp);
}
static void checkTimer() {
System.err.println(elapsedTime() + " ms");
}
static void chk(boolean f) {
if (!f) throw new RuntimeException("Assert failed");
}
static void chk(boolean f, String format, Object ... args) {
if (!f) throw new RuntimeException(String.format(format, args));
}
static void log(String format, Object ... args) {
if (writeLog) System.err.println(String.format(Locale.US, format, args));
}
}
| nlogn | 274_A. k-Multiple Free Set | CODEFORCES |
//package round168;
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(), K = ni();
int[] a = na(n);
if(K == 1){
out.println(n);
return;
}
a = radixSort(a);
boolean[] dead = new boolean[n];
int ct = 0;
for(int i = 0;i < n;i++){
if(!dead[i]){
ct++;
if((long)a[i]*K<=1000000000){
int ind = Arrays.binarySearch(a, a[i]*K);
if(ind >= 0){
dead[ind] = true;
}
}
}
}
out.println(ct);
}
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 | 274_A. k-Multiple Free Set | CODEFORCES |
import java.io.*;
import java.math.*;
import java.util.*;
import java.lang.*;
public class Main
{
static Input in;
static Output out;
public static void main(String[] args) throws IOException
{
in = new Input(System.in);
out = new Output(System.out);
run();
out.close();
System.exit(0);
}
private static void run() throws IOException
{
int n = 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 count = n;
boolean[] hash = new boolean[n];
for (int i = n-1; i > 0; i--)
{
if(!hash[i])
{
int a = A[i];
if(a % k == 0)
{
int p = a / k;
int j = Arrays.binarySearch(A, p);
if(j >= 0 && j < i)
{
hash[j] = true;
count--;
}
}
}
}
out.print(count);
}
}
class Input
{
final int SIZE = 8192;
private InputStream in;
private byte[] buf = new byte[SIZE];
private int last, current, total;
public Input(InputStream stream) throws IOException
{
in = stream;
last = read();
}
private int read() throws IOException
{
if (total == -1) return -1;
if (current >= total)
{
current = 0;
total = in.read(buf);
if (total <= 0) return -1;
}
return buf[current++];
}
private void advance() throws IOException
{
while (true)
{
if (last == -1) return;
if (!isValidChar(last)) last = read();
else break;
}
}
private boolean isValidChar(int c)
{
return c > 32 && c < 127;
}
public boolean isEOF() throws IOException
{
advance();
return last == -1;
}
public String nextString() throws IOException
{
advance();
if (last == -1) throw new EOFException();
StringBuilder s = new StringBuilder();
while (true)
{
s.appendCodePoint(last);
last = read();
if (!isValidChar(last)) break;
}
return s.toString();
}
public String nextLine() throws IOException
{
if (last == -1) throw new EOFException();
StringBuilder s = new StringBuilder();
while (true)
{
s.appendCodePoint(last);
last = read();
if (last == '\n' || last == -1) break;
}
return s.toString();
}
public String nextLine(boolean ignoreIfEmpty) throws IOException
{
if (!ignoreIfEmpty) return nextLine();
String s = nextLine();
while (s.trim().length() == 0) s = nextLine();
return s;
}
public int nextInt() throws IOException
{
advance();
if (last == -1) throw new EOFException();
int n = 0, s = 1;
if (last == '-')
{
s = -1;
last = read();
if (last == -1) throw new EOFException();
}
while (true)
{
n = n * 10 + last - '0';
last = read();
if (!isValidChar(last)) break;
}
return n * s;
}
public long nextLong() throws IOException
{
advance();
if (last == -1) throw new EOFException();
int s = 1;
if (last == '-')
{
s = -1;
last = read();
if (last == -1) throw new EOFException();
}
long n = 0;
while (true)
{
n = n * 10 + last - '0';
last = read();
if (!isValidChar(last)) break;
}
return n * s;
}
public BigInteger nextBigInt() throws IOException
{
return new BigInteger(nextString());
}
public char nextChar() throws IOException
{
advance();
return (char) last;
}
public double nextDouble() throws IOException
{
advance();
if (last == -1) throw new EOFException();
int s = 1;
if (last == '-')
{
s = -1;
last = read();
if (last == -1) throw new EOFException();
}
double n = 0;
while (true)
{
n = n * 10 + last - '0';
last = read();
if (!isValidChar(last) || last == '.') break;
}
if (last == '.')
{
last = read();
if (last == -1) throw new EOFException();
double m = 1;
while (true)
{
m = m / 10;
n = n + (last - '0') * m;
last = read();
if (!isValidChar(last)) break;
}
}
return n * s;
}
public BigDecimal nextBigDecimal() throws IOException
{
return new BigDecimal(nextString());
}
public void close() throws IOException
{
in.close();
in = null;
}
}
class Output
{
final int SIZE = 8192;
private Writer out;
private char cb[] = new char[SIZE];
private int nChars = SIZE, nextChar = 0;
private char lineSeparator = '\n';
public Output(OutputStream stream)
{
out = new OutputStreamWriter(stream);
}
void flushBuffer() throws IOException
{
if (nextChar == 0) return;
out.write(cb, 0, nextChar);
nextChar = 0;
}
void write(int c) throws IOException
{
if (nextChar >= nChars) flushBuffer();
cb[nextChar++] = (char) c;
}
void write(String s, int off, int len) throws IOException
{
int b = off, t = off + len;
while (b < t)
{
int a = nChars - nextChar, a1 = t - b;
int d = a < a1 ? a : a1;
s.getChars(b, b + d, cb, nextChar);
b += d;
nextChar += d;
if (nextChar >= nChars) flushBuffer();
}
}
void write(String s) throws IOException
{
write(s, 0, s.length());
}
public void print(Object obj) throws IOException
{
write(String.valueOf(obj));
}
public void println(Object obj) throws IOException
{
write(String.valueOf(obj));
write(lineSeparator);
}
public void printf(String format, Object... obj) throws IOException
{
write(String.format(format, obj));
}
public void close() throws IOException
{
flushBuffer();
out.close();
out = null;
}
} | nlogn | 274_A. k-Multiple Free Set | CODEFORCES |
import java.io.*;
import java.util.*;
import java.math.*;
public class A implements Runnable {
static BufferedReader in;
static PrintWriter out;
static StringTokenizer st;
static Random rnd;
void solve() throws IOException {
int n = nextInt();
long k = nextLong();
if (k == 1) {
out.println(n);
} else {
TreeMap<Long, ArrayList<Integer>> numbers = new TreeMap<Long, ArrayList<Integer>>();
for (int i = 0; i < n; i++) {
long m = nextLong();
int howMuch = 0;
while (m % k == 0) {
m /= k;
++howMuch;
}
if (!numbers.containsKey(m)) {
numbers.put(m, new ArrayList<Integer>());
}
numbers.get(m).add(howMuch);
}
int res = 0;
for (ArrayList<Integer> oneGroup : numbers.values()) {
res += parseOneGroup(oneGroup);
}
out.println(res);
}
}
private int parseOneGroup(ArrayList<Integer> oneGroup) {
Collections.sort(oneGroup);
int res = 0, prevValue = Integer.MIN_VALUE;
for (int i = 0; i < oneGroup.size(); i++) {
int curValue = oneGroup.get(i);
if (prevValue + 1 != curValue) {
++res;
prevValue = curValue;
}
}
return res;
}
public static void main(String[] args) {
new A().run();
}
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
rnd = new Random();
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(42);
}
}
String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String line = in.readLine();
if (line == null)
return null;
st = new StringTokenizer(line);
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
} | nlogn | 274_A. k-Multiple Free Set | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Random;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class Main {
//http://www.codeforces.com/contest/275/problem/C
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
int num = Integer.parseInt(st.nextToken());
int k = Integer.parseInt(st.nextToken());
st = new StringTokenizer(br.readLine(), " ");
if (k == 1) System.out.println(num);
else {
Set<Integer> set = new TreeSet<Integer>();
Set<Integer> bad = new TreeSet<Integer>();
int sel;
int[] arr = new int[num];
for (int i = 0; i < num; i++) {
arr[i] = Integer.parseInt((st.nextToken()));
}
shuffle(arr);
Arrays.sort(arr);
for (int i = 0; i < num; i++) {
sel = arr[i];
if (sel % k != 0) {
set.add(sel);
bad.add(sel * k);
}
if (!bad.contains(sel) && !set.contains(sel / k)) {
bad.add(sel * k);
set.add(sel);
}
}
System.out.println(set.size());
}
}
public static void shuffle(int[] arr) {
Random rand = new Random();
for (int i = arr.length - 1; i >= 0; --i) {
int pos = rand.nextInt(i + 1);
int aux = arr[i];
arr[i] = arr[pos];
arr[pos] = aux;
}
}
} | nlogn | 274_A. k-Multiple Free Set | CODEFORCES |
import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
public class CF274A {
public static void main(String[] args) throws Exception {
new CF274A().solve();
}
private void solve() throws Exception {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
long k = sc.nextInt();
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
Arrays.sort(a);
HashSet<Integer> used = new HashSet<>(n);
int count = 0;
for (int i = 0; i < n; i++) {
Integer v = a[i];
if (!used.contains(v)) {
count++;
long next = v * k;
if (next <= 1000000000) used.add((int) next);
}
}
System.out.println(count);
}
}
| nlogn | 274_A. k-Multiple Free Set | 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();
long k = in.nextLong();
long[] a = new long[n];
for (int i = 0; i < n; ++i) a[i] = in.nextLong();
Arrays.sort(a);
boolean[] take = new boolean[n];
Arrays.fill(take, true);
int j = 0;
int res = n;
for (int i = 0; i < n; ++i) {
while (j < i && a[j] * k < a[i]) ++j;
if (j < i && take[j] && a[j] * k == a[i]) {
take[i] = false;
--res;
}
}
out.println(res);
}
}
class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
| nlogn | 274_A. k-Multiple Free Set | CODEFORCES |
import static java.lang.Math.*;
import java.io.*;
import java.util.*;
public class Template {
BufferedReader in;
PrintWriter out;
StringTokenizer st;
String next() {
while (st==null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(in.readLine());
} catch (Exception e) {}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
class Point implements Comparable<Point> {
int x, y;
public Point(int x, int y) {
this.x=x;
this.y=y;
}
public int compareTo(Point o) {
return x-o.x;
}
public String toString() {
return x + " " + y;
}
}
public void run() throws Exception {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
Long start = System.currentTimeMillis();
int n = nextInt();
long k = nextLong();
long[] a = new long[n];
TreeMap<Long, Integer> st = new TreeMap<Long, Integer>();
for (int i=0; i<n; i++) {
a[i] = nextLong();
st.put(a[i], 1);
}
Arrays.sort(a);
for (int i=0; i<n; i++) {
if (a[i] % k == 0) {
long x = a[i] / k;
if (st.containsKey(x)) {
int y = st.get(x);
st.remove(a[i]);
st.put(a[i], y + 1);
}
}
}
int ans = 0;
for (int i=0; i<n; i++) {
//System.err.println(a[n-i-1] + " " + st.get(a[n-i-1]));
ans+=(st.get(a[n-i-1]) + 1) / 2;
if (a[n-i-1] % k == 0) {
long x = a[n-i-1] / k;
if (st.containsKey(x)) {
//System.err.println(x);
st.remove(x);
st.put(x, 0);
}
}
}
out.println(ans);
Long end = System.currentTimeMillis();
out.close();
}
public static void main(String[] args) throws Exception {
new Template().run();
}
} | nlogn | 274_A. k-Multiple Free Set | CODEFORCES |
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.StringTokenizer;
public class A {
static int[] parent;
public static int find(int x) {
if (x == parent[x])
return x;
return parent[x] = find(parent[x]);
}
public static void union(int x, int y) {
int px = find(x);
int py = find(y);
if (px != py) {
parent[py] = px;
}
}
public static void main(String[] args) throws Exception {
int numCnt = (int) nextLong();
long k = nextLong();
parent = new int[numCnt];
for (int i = 0; i < parent.length; i++) {
parent[i] = i;
}
Long[] ar=new Long[numCnt];
for (int i = 0; i < numCnt; i++) {
ar[i] = nextLong();
}
Arrays.sort(ar);
for (int i = 0; i < ar.length; i++) {
long req = ar[i] * k;
int l=0,h=ar.length,mid;
while(l<h){
mid=l+(h-l)/2;
if(ar[mid]<req){
l=mid+1;
}else{
h=mid;
}
}
if(l<ar.length&&ar[l]==req){
union(i,l);
}
}
int[] count = new int[numCnt];
for (int i = 0; i < parent.length; i++) {
count[find(i)]++;
}
int res = 0;
for (int i = 0; i < numCnt; i++) {
res += (int) ((count[i] + 1) / 2.0);
}
System.out.println(res);
}
static BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
static StringTokenizer tokenizer = new StringTokenizer("");
static long nextLong() throws Exception {
return Long.parseLong(next());
}
static double nextDouble() throws Exception {
return Double.parseDouble(next());
}
static String next() throws Exception {
while (true) {
if (tokenizer.hasMoreTokens()) {
return tokenizer.nextToken();
}
String s = br.readLine();
if (s == null) {
return null;
}
tokenizer = new StringTokenizer(s);
}
}
}
| nlogn | 274_A. k-Multiple Free Set | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Random;
import java.util.InputMismatchException;
import java.io.Writer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author emotionalBlind
*/
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();
long K = in.readLong();
long[] a = new long[N];
for (int i = 0; i < N; ++i) {
a[i] = in.readLong();
}
ArrayShuffler s = new ArrayShuffler();
s.shuffle(a);
Arrays.sort(a);
boolean[] taken = new boolean[N];
Arrays.fill(taken, true);
int i = 0;
int j = i + 1;
int res = N;
while (i < a.length) {
if (taken[i] == false) {
i++;
if (j <= i) j = i + 1;
continue;
}
while (j < a.length && a[j] < a[i] * K) {
j++;
}
if (j < a.length) {
if (a[j] == a[i] * K) {
taken[j] = false;
res--;
}
}
i++;
if (j <= i) j = i + 1;
}
out.printLine(res);
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
// InputMismatchException -> UnknownError
if (numChars == -1)
throw new UnknownError();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new UnknownError();
}
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();
} else if (c == '+') {
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long readLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public static boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(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();
}
}
class ArrayShuffler {
static Random random = new Random(7428429L);
public void shuffle(long[] p) {
for (int i = 0; i < p.length; ++i) {
int j = i + random.nextInt(p.length - i);
long temp = p[i];
p[i] = p[j];
p[j] = temp;
}
}
}
| nlogn | 274_A. k-Multiple Free Set | CODEFORCES |
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.List;
import java.util.Random;
import java.util.TreeSet;
/**
* Actual solution is at the top, in class Solver
*/
final public class Main implements Runnable {
private static String[] args;
public static void main(String[] args) {
Main.args = args;
new Thread(null, new Main(), "MyRunThread", 1 << 27).start();
}
//@Override
public void run() {
long time_beg = -1;
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
if (args.length > 0 && args[0].equals("outside")) {
time_beg = System.currentTimeMillis();
try {
inputStream = new FileInputStream("IO/in.txt");
// outputStream = new FileOutputStream("IO/out.txt");
} catch (Exception e) {
System.err.println(e);
System.exit(1);
}
} else {
try {
// inputStream = new FileInputStream("IO/in.txt");
// outputStream = new FileOutputStream("IO/out.txt");
} catch (Exception e) {
System.err.println(e);
System.exit(1);
}
}
Solver s = new Solver();
s.in = new InputReader(inputStream);
s.out = new OutputWriter(outputStream);
if (args.length > 0 && args[0].equals("outside")) {
s.dout = new DebugWriter(s.out);
}
s.solve();
if (args.length > 0 && args[0].equals("outside")) {
s.dout.printFormat("*** Total time: %.3f ***\n", (System.currentTimeMillis() - time_beg) / 1000.0);
}
s.out.close();
}
}
final class Solver {
InputReader in;
OutputWriter out;
DebugWriter dout;
public void solve() {
int n = in.readInt();
int k = in.readInt();
TreeSet<Integer> q = new TreeSet<Integer>();
int[] mas = new int[n];
for (int i = 0; i < n; ++i) {
mas[i] = in.readInt();
if (mas[i] % k != 0)
q.add(mas[i]);
}
// SequenceUtils.quickSort(mas);
Arrays.sort(mas);
for (int i = 0; i < n; ++i)
if (mas[i] % k == 0 && !q.contains(mas[i] / k))
q.add(mas[i]);
out.printLine(q.size());
}
}
final class InputReader {
private boolean finished = false;
private InputStream stream;
private byte[] buf = new byte[1 << 10];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
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++];
}
public int peek() {
if (numChars == -1)
return -1;
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
if (numChars <= 0)
return -1;
}
return buf[curChar];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long readLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public static boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuilder buf = new StringBuilder();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r')
buf.appendCodePoint(c);
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0)
s = readLine0();
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines)
return readLine();
else
return readLine0();
}
public BigInteger readBigInteger() {
try {
return new BigInteger(readString());
} catch (NumberFormatException e) {
throw new InputMismatchException();
}
}
public char readCharacter() {
int c = read();
while (isSpaceChar(c))
c = read();
return (char) c;
}
public double readDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public boolean isExhausted() {
int value;
while (isSpaceChar(value = peek()) && value != -1)
read();
return value == -1;
}
}
final class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream), 1 << 10));
}
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 printFormat(String format, Object... objects) {
writer.printf(format, objects);
}
public void print(char[] objects) {
writer.print(objects);
}
public void printLine(char[] objects) {
writer.println(objects);
}
public void printLine(char[][] objects) {
for (int i = 0; i < objects.length; ++i)
printLine(objects[i]);
}
public void print(int[] objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(int[] objects) {
print(objects);
writer.println();
}
public void printLine(int[][] objects) {
for (int i = 0; i < objects.length; ++i)
printLine(objects[i]);
}
public void print(short[] objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(short[] objects) {
print(objects);
writer.println();
}
public void printLine(short[][] objects) {
for (int i = 0; i < objects.length; ++i)
printLine(objects[i]);
}
public void print(long[] objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(long[] objects) {
print(objects);
writer.println();
}
public void printLine(long[][] objects) {
for (int i = 0; i < objects.length; ++i)
printLine(objects[i]);
}
public void print(double[] objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(double[] objects) {
print(objects);
writer.println();
}
public void printLine(double[][] objects) {
for (int i = 0; i < objects.length; ++i)
printLine(objects[i]);
}
public void print(byte[] objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(byte[] objects) {
print(objects);
writer.println();
}
public void printLine(byte[][] objects) {
for (int i = 0; i < objects.length; ++i)
printLine(objects[i]);
}
public void print(boolean[] objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(boolean[] objects) {
print(objects);
writer.println();
}
public void printLine(boolean[][] objects) {
for (int i = 0; i < objects.length; ++i)
printLine(objects[i]);
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
}
final class DebugWriter {
private final OutputWriter writer;
public DebugWriter(OutputWriter writer) {
this.writer = writer;
}
private void printDebugMessage() {
writer.print("DEBUG:\t");
}
public void printLine(Object... objects) {
flush();
printDebugMessage();
writer.printLine(objects);
flush();
}
public void printFormat(String format, Object... objects) {
flush();
printDebugMessage();
writer.printFormat(format, objects);
flush();
}
public void printLine(char[] objects) {
flush();
printDebugMessage();
writer.printLine(objects);
flush();
}
public void printLine(char[][] objects) {
flush();
for (int i = 0; i < objects.length; ++i)
printLine(objects[i]);
flush();
}
public void printLine(double[] objects) {
flush();
printDebugMessage();
writer.printLine(objects);
flush();
}
public void printLine(double[][] objects) {
flush();
for (int i = 0; i < objects.length; ++i)
printLine(objects[i]);
flush();
}
public void printLine(int[] objects) {
flush();
printDebugMessage();
writer.printLine(objects);
flush();
}
public void printLine(int[][] objects) {
flush();
for (int i = 0; i < objects.length; ++i)
printLine(objects[i]);
flush();
}
public void printLine(short[] objects) {
flush();
printDebugMessage();
writer.printLine(objects);
flush();
}
public void printLine(short[][] objects) {
flush();
for (int i = 0; i < objects.length; ++i)
printLine(objects[i]);
flush();
}
public void printLine(long[] objects) {
flush();
printDebugMessage();
writer.printLine(objects);
flush();
}
public void printLine(long[][] objects) {
flush();
for (int i = 0; i < objects.length; ++i)
printLine(objects[i]);
flush();
}
public void printLine(byte[] objects) {
flush();
printDebugMessage();
writer.printLine(objects);
flush();
}
public void printLine(byte[][] objects) {
flush();
for (int i = 0; i < objects.length; ++i)
printLine(objects[i]);
flush();
}
public void printLine(boolean[] objects) {
flush();
printDebugMessage();
writer.printLine(objects);
flush();
}
public void printLine(boolean[][] objects) {
flush();
for (int i = 0; i < objects.length; ++i)
printLine(objects[i]);
flush();
}
public void flush() {
writer.flush();
}
}
interface Graph {
// add vertexes
public void addVertexes(int amount);
// add edge
public void addEdge(int source, int destination, boolean directed);
public void addEdge(int source, int destination, boolean directed, long weight);
public void addEdge(int source, int destination, long capacity);
public void addEdge(int source, int destination, long weight, long capacity);
// iterate through incident edges
public int getFirstEdge(int source);
public boolean hasNextEdge(int id);
public int getNextEdge(int id);
// graph info
public int getVertexCount();
public int getEdgeCount();
public void show(DebugWriter writer);
// simple edge info
public int getSource(int id);
public int getDestination(int id);
public int getColor(int id);
public void setColor(int id, int color);
public boolean hasReverseEdge(int id);
public int getReverseEdge(int id);
public String edgeToString(int id);
// weighted edge info
public long getWeight(int id);
public void setWeight(int id, long weight);
// flow edge info
public long getCapacity(int id);
public void addCapacity(int id, long capacity);
public long getFlow(int id);
public void pushFlow(int id, long flow);
}
class GraphSimple implements Graph {
protected int[] firstEdge;
protected int[] nextEdge;
protected int vertexCount = 0;
protected int edgeCount = 0;
protected int[] reverseEdge;
protected int[] source;
protected int[] destination;
protected int[] color;
public GraphSimple() {
this(16, 16);
}
public GraphSimple(int vertexCapacity, int edgeCapacity) {
firstEdge = new int[vertexCapacity];
nextEdge = new int[edgeCapacity];
reverseEdge = new int[edgeCapacity];
source = new int[edgeCapacity];
destination = new int[edgeCapacity];
color = new int[edgeCapacity];
}
protected void ensureVertexCapacity(int size) {
}
protected void ensureEdgeCapacity(int size) {
}
// add vertexes
@Override
public void addVertexes(int amount) {
ensureVertexCapacity(vertexCount + amount);
for (int i = 0; i < amount; ++i)
firstEdge[i + vertexCount] = -1;
vertexCount += amount;
}
// add edge
@Override
public void addEdge(int source, int destination, boolean directed) {
if (source >= vertexCount || destination >= vertexCount)
throw new ArrayIndexOutOfBoundsException("wrong vertex's number");
ensureEdgeCapacity(edgeCount + 2);
nextEdge[edgeCount] = firstEdge[source];
firstEdge[source] = edgeCount;
this.source[edgeCount] = source;
this.destination[edgeCount] = destination;
this.color[edgeCount] = -1;
if (directed) reverseEdge[edgeCount++] = -1;
else {
reverseEdge[edgeCount] = edgeCount + 1;
++edgeCount;
nextEdge[edgeCount] = firstEdge[destination];
firstEdge[destination] = edgeCount;
this.source[edgeCount] = destination;
this.destination[edgeCount] = source;
this.color[edgeCount] = -1;
reverseEdge[edgeCount] = edgeCount - 1;
++edgeCount;
}
}
@Override
public void addEdge(int source, int destination, boolean directed, long weight) {
throw new UnsupportedOperationException();
}
@Override
public void addEdge(int source, int destination, long capacity) {
throw new UnsupportedOperationException();
}
@Override
public void addEdge(int source, int destination, long weight, long capacity) {
throw new UnsupportedOperationException();
}
// iterate through incident edges
@Override
public int getFirstEdge(int source) {
if (source >= vertexCount)
throw new ArrayIndexOutOfBoundsException("wrong vertex's number");
return firstEdge[source];
}
@Override
public boolean hasNextEdge(int id) {
return id != -1;
}
@Override
public int getNextEdge(int id) {
return nextEdge[id];
}
// graph info
@Override
public int getVertexCount() {
return vertexCount;
}
@Override
public int getEdgeCount() {
return edgeCount;
}
@Override
public void show(DebugWriter writer) {
writer.printLine("Graph:");
for (int i = 0; i < getVertexCount(); ++i) {
writer.printLine("\tincident to vertex [" + i + "]: ");
for (int id = getFirstEdge(i); hasNextEdge(id); id = getNextEdge(id))
writer.printLine("\t\t" + edgeToString(id));
}
}
// simple edge info
@Override
public int getSource(int id) {
return source[id];
}
@Override
public int getDestination(int id) {
return destination[id];
}
@Override
public int getColor(int id) {
return color[id];
}
@Override
public void setColor(int id, int color) {
this.color[id] = color;
}
@Override
public boolean hasReverseEdge(int id) {
return reverseEdge[id] != -1;
}
@Override
public int getReverseEdge(int id) {
if (reverseEdge[id] == -1)
throw new NoSuchFieldError();
return reverseEdge[id];
}
@Override
public String edgeToString(int id) {
return "<(" + getSource(id) + " -> " + getDestination(id) + ") color : " + getColor(id) + ">";
}
// weighted edge info
@Override
public long getWeight(int id) {
throw new UnsupportedOperationException();
}
@Override
public void setWeight(int id, long weight) {
throw new UnsupportedOperationException();
}
// flow edge info
@Override
public long getCapacity(int id) {
throw new UnsupportedOperationException();
}
@Override
public void addCapacity(int id, long capacity) {
throw new UnsupportedOperationException();
}
@Override
public long getFlow(int id) {
throw new UnsupportedOperationException();
}
@Override
public void pushFlow(int id, long flow) {
throw new UnsupportedOperationException();
}
}
abstract class SequenceUtils {
// swap
public final static <T> void swap(List<T> sequence, int j, int i) {
T tmp = sequence.get(j);
sequence.set(j, sequence.get(i));
sequence.set(i, tmp);
}
public final static <T> void swap(T[] sequence, int j, int i) {
T tmp = sequence[j];
sequence[j] = sequence[i];
sequence[i] = tmp;
}
public final static void swap(int[] sequence, int j, int i) {
int tmp = sequence[j];
sequence[j] = sequence[i];
sequence[i] = tmp;
}
public final static void swap(long[] sequence, int j, int i) {
long tmp = sequence[j];
sequence[j] = sequence[i];
sequence[i] = tmp;
}
public final static void swap(char[] sequence, int j, int i) {
char tmp = sequence[j];
sequence[j] = sequence[i];
sequence[i] = tmp;
}
public final static void swap(double[] sequence, int j, int i) {
double tmp = sequence[j];
sequence[j] = sequence[i];
sequence[i] = tmp;
}
public final static void swap(boolean[] sequence, int j, int i) {
boolean tmp = sequence[j];
sequence[j] = sequence[i];
sequence[i] = tmp;
}
public final static void swap(short[] sequence, int j, int i) {
short tmp = sequence[j];
sequence[j] = sequence[i];
sequence[i] = tmp;
}
public final static void swap(byte[] sequence, int j, int i) {
byte tmp = sequence[j];
sequence[j] = sequence[i];
sequence[i] = tmp;
}
// reverse
public final static <T> void reverse(List<T> sequence) {
for (int left = 0, right = sequence.size() - 1; left < right; ++left, --right)
swap(sequence, left, right);
}
public final static <T> void reverse(T[] sequence) {
for (int left = 0, right = sequence.length - 1; left < right; ++left, --right)
swap(sequence, left, right);
}
public final static void reverse(int[] sequence) {
for (int left = 0, right = sequence.length - 1; left < right; ++left, --right)
swap(sequence, left, right);
}
public final static void reverse(long[] sequence) {
for (int left = 0, right = sequence.length - 1; left < right; ++left, --right)
swap(sequence, left, right);
}
public final static void reverse(char[] sequence) {
for (int left = 0, right = sequence.length - 1; left < right; ++left, --right)
swap(sequence, left, right);
}
public final static void reverse(double[] sequence) {
for (int left = 0, right = sequence.length - 1; left < right; ++left, --right)
swap(sequence, left, right);
}
public final static void reverse(boolean[] sequence) {
for (int left = 0, right = sequence.length - 1; left < right; ++left, --right)
swap(sequence, left, right);
}
public final static void reverse(short[] sequence) {
for (int left = 0, right = sequence.length - 1; left < right; ++left, --right)
swap(sequence, left, right);
}
public final static void reverse(byte[] sequence) {
for (int left = 0, right = sequence.length - 1; left < right; ++left, --right)
swap(sequence, left, right);
}
// next permutation
public final static <T extends Comparable<T>> boolean nextPermutation(List<T> sequence) {
for (int j = sequence.size() - 2; j >= 0; --j) {
if (sequence.get(j).compareTo(sequence.get(j + 1)) < 0) {
reverse(sequence.subList(j + 1, sequence.size()));
for (int i = j + 1; i < sequence.size(); ++i)
if (sequence.get(j).compareTo(sequence.get(i)) < 0) {
swap(sequence, j, i);
return true;
}
}
}
return false;
}
public final static <T> boolean nextPermutation(List<T> sequence, Comparator<T> comparator) {
for (int j = sequence.size() - 2; j >= 0; --j) {
if (comparator.compare(sequence.get(j), sequence.get(j + 1)) < 0) {
reverse(sequence.subList(j + 1, sequence.size()));
for (int i = j + 1; i < sequence.size(); ++i)
if (comparator.compare(sequence.get(j), sequence.get(i)) < 0) {
swap(sequence, j, i);
return true;
}
}
}
return false;
}
// random shuffle
public final static <T> void shuffle(List<T> sequence) {
Random random = new Random(System.nanoTime());
for (int i = 1; i < sequence.size(); ++i)
swap(sequence, random.nextInt(i + 1), i);
}
public final static <T> void shuffle(T[] sequence) {
Random random = new Random(System.nanoTime());
for (int i = 1; i < sequence.length; ++i)
swap(sequence, random.nextInt(i + 1), i);
}
public final static void shuffle(int[] sequence) {
Random random = new Random(System.nanoTime());
for (int i = 1; i < sequence.length; ++i)
swap(sequence, random.nextInt(i + 1), i);
}
public final static void shuffle(long[] sequence) {
Random random = new Random(System.nanoTime());
for (int i = 1; i < sequence.length; ++i)
swap(sequence, random.nextInt(i + 1), i);
}
public final static void shuffle(char[] sequence) {
Random random = new Random(System.nanoTime());
for (int i = 1; i < sequence.length; ++i)
swap(sequence, random.nextInt(i + 1), i);
}
public final static void shuffle(double[] sequence) {
Random random = new Random(System.nanoTime());
for (int i = 1; i < sequence.length; ++i)
swap(sequence, random.nextInt(i + 1), i);
}
public final static void shuffle(boolean[] sequence) {
Random random = new Random(System.nanoTime());
for (int i = 1; i < sequence.length; ++i)
swap(sequence, random.nextInt(i + 1), i);
}
public final static void shuffle(short[] sequence) {
Random random = new Random(System.nanoTime());
for (int i = 1; i < sequence.length; ++i)
swap(sequence, random.nextInt(i + 1), i);
}
public final static void shuffle(byte[] sequence) {
Random random = new Random(System.nanoTime());
for (int i = 1; i < sequence.length; ++i)
swap(sequence, random.nextInt(i + 1), i);
}
// merge sort
public final static <T extends Comparable<T>> void mergeSort(List<T> sequence) {
int n = sequence.size();
T[] tmp = (T[]) new Object[n];
for (int step = 1; step < n; step *= 2) {
for (int i = 0; i < n; ++i)
tmp[i] = sequence.get(i);
for (int i = 0; i + step < n; i += 2 * step)
merge(sequence, tmp, i, i + step - 1, Math.min(i + step * 2 - 1, n - 1));
}
}
private final static <T extends Comparable<T>> void merge(List<T> sequence, T[] tmp, int left, int mid, int right) {
int pLeft = left;
int pRight = mid + 1;
for (int i = left; i <= right; ++i)
if (pLeft > mid) sequence.set(i, tmp[pRight++]);
else if (pRight > right) sequence.set(i, tmp[pLeft++]);
else if (tmp[pLeft].compareTo(tmp[pRight]) <= 0) sequence.set(i, tmp[pLeft++]);
else sequence.set(i, tmp[pRight++]);
}
public final static <T> void mergeSort(List<T> sequence, Comparator<T> comparator) {
int n = sequence.size();
T[] tmp = (T[]) new Object[n];
for (int step = 1; step < n; step *= 2) {
for (int i = 0; i < n; ++i)
tmp[i] = sequence.get(i);
for (int i = 0; i + step < n; i += 2 * step)
merge(sequence, tmp, i, i + step - 1, Math.min(i + step * 2 - 1, n - 1), comparator);
}
}
private final static <T> void merge(List<T> sequence, T[] tmp, int left, int mid, int right, Comparator<T> comparator) {
int pLeft = left;
int pRight = mid + 1;
for (int i = left; i <= right; ++i)
if (pLeft > mid) sequence.set(i, tmp[pRight++]);
else if (pRight > right) sequence.set(i, tmp[pLeft++]);
else if (comparator.compare(tmp[pLeft], tmp[pRight]) <= 0) sequence.set(i, tmp[pLeft++]);
else sequence.set(i, tmp[pRight++]);
}
public final static void mergeSort(int[] sequence) {
int n = sequence.length;
int[] tmp = new int[n];
for (int step = 1; step < n; step *= 2) {
for (int i = 0; i < n; ++i)
tmp[i] = sequence[i];
for (int i = 0; i + step < n; i += 2 * step)
merge(sequence, tmp, i, i + step - 1, Math.min(i + step * 2 - 1, n - 1));
}
}
private final static void merge(int[] sequence, int[] tmp, int left, int mid, int right) {
int pLeft = left;
int pRight = mid + 1;
for (int i = left; i <= right; ++i)
if (pLeft > mid) sequence[i] = tmp[pRight++];
else if (pRight > right) sequence[i] = tmp[pLeft++];
else if (tmp[pLeft] <= tmp[pRight]) sequence[i] = tmp[pLeft++];
else sequence[i] = tmp[pRight++];
}
public final static void mergeSort(long[] sequence) {
int n = sequence.length;
long[] tmp = new long[n];
for (int step = 1; step < n; step *= 2) {
for (int i = 0; i < n; ++i)
tmp[i] = sequence[i];
for (int i = 0; i + step < n; i += 2 * step)
merge(sequence, tmp, i, i + step - 1, Math.min(i + step * 2 - 1, n - 1));
}
}
private final static void merge(long[] sequence, long[] tmp, int left, int mid, int right) {
int pLeft = left;
int pRight = mid + 1;
for (int i = left; i <= right; ++i)
if (pLeft > mid) sequence[i] = tmp[pRight++];
else if (pRight > right) sequence[i] = tmp[pLeft++];
else if (tmp[pLeft] <= tmp[pRight]) sequence[i] = tmp[pLeft++];
else sequence[i] = tmp[pRight++];
}
public final static void mergeSort(char[] sequence) {
int n = sequence.length;
char[] tmp = new char[n];
for (int step = 1; step < n; step *= 2) {
for (int i = 0; i < n; ++i)
tmp[i] = sequence[i];
for (int i = 0; i + step < n; i += 2 * step)
merge(sequence, tmp, i, i + step - 1, Math.min(i + step * 2 - 1, n - 1));
}
}
private final static void merge(char[] sequence, char[] tmp, int left, int mid, int right) {
int pLeft = left;
int pRight = mid + 1;
for (int i = left; i <= right; ++i)
if (pLeft > mid) sequence[i] = tmp[pRight++];
else if (pRight > right) sequence[i] = tmp[pLeft++];
else if (tmp[pLeft] <= tmp[pRight]) sequence[i] = tmp[pLeft++];
else sequence[i] = tmp[pRight++];
}
public final static void mergeSort(double[] sequence) {
int n = sequence.length;
double[] tmp = new double[n];
for (int step = 1; step < n; step *= 2) {
for (int i = 0; i < n; ++i)
tmp[i] = sequence[i];
for (int i = 0; i + step < n; i += 2 * step)
merge(sequence, tmp, i, i + step - 1, Math.min(i + step * 2 - 1, n - 1));
}
}
private final static void merge(double[] sequence, double[] tmp, int left, int mid, int right) {
int pLeft = left;
int pRight = mid + 1;
for (int i = left; i <= right; ++i)
if (pLeft > mid) sequence[i] = tmp[pRight++];
else if (pRight > right) sequence[i] = tmp[pLeft++];
else if (tmp[pLeft] <= tmp[pRight]) sequence[i] = tmp[pLeft++];
else sequence[i] = tmp[pRight++];
}
public final static void mergeSort(boolean[] sequence) {
int n = sequence.length;
boolean[] tmp = new boolean[n];
for (int step = 1; step < n; step *= 2) {
for (int i = 0; i < n; ++i)
tmp[i] = sequence[i];
for (int i = 0; i + step < n; i += 2 * step)
merge(sequence, tmp, i, i + step - 1, Math.min(i + step * 2 - 1, n - 1));
}
}
private final static void merge(boolean[] sequence, boolean[] tmp, int left, int mid, int right) {
int pLeft = left;
int pRight = mid + 1;
for (int i = left; i <= right; ++i)
if (pLeft > mid) sequence[i] = tmp[pRight++];
else if (pRight > right) sequence[i] = tmp[pLeft++];
else if (!tmp[pLeft] || tmp[pRight]) sequence[i] = tmp[pLeft++];
else sequence[i] = tmp[pRight++];
}
public final static void mergeSort(short[] sequence) {
int n = sequence.length;
short[] tmp = new short[n];
for (int step = 1; step < n; step *= 2) {
for (int i = 0; i < n; ++i)
tmp[i] = sequence[i];
for (int i = 0; i + step < n; i += 2 * step)
merge(sequence, tmp, i, i + step - 1, Math.min(i + step * 2 - 1, n - 1));
}
}
private final static void merge(short[] sequence, short[] tmp, int left, int mid, int right) {
int pLeft = left;
int pRight = mid + 1;
for (int i = left; i <= right; ++i)
if (pLeft > mid) sequence[i] = tmp[pRight++];
else if (pRight > right) sequence[i] = tmp[pLeft++];
else if (tmp[pLeft] <= tmp[pRight]) sequence[i] = tmp[pLeft++];
else sequence[i] = tmp[pRight++];
}
public final static void mergeSort(byte[] sequence) {
int n = sequence.length;
byte[] tmp = new byte[n];
for (int step = 1; step < n; step *= 2) {
for (int i = 0; i < n; ++i)
tmp[i] = sequence[i];
for (int i = 0; i + step < n; i += 2 * step)
merge(sequence, tmp, i, i + step - 1, Math.min(i + step * 2 - 1, n - 1));
}
}
private final static void merge(byte[] sequence, byte[] tmp, int left, int mid, int right) {
int pLeft = left;
int pRight = mid + 1;
for (int i = left; i <= right; ++i)
if (pLeft > mid) sequence[i] = tmp[pRight++];
else if (pRight > right) sequence[i] = tmp[pLeft++];
else if (tmp[pLeft] <= tmp[pRight]) sequence[i] = tmp[pLeft++];
else sequence[i] = tmp[pRight++];
}
// quick sort
public final static <T> void quickSort(List<T> sequence, Comparator<T> comparator) {
shuffle(sequence);
quickSortImplementation(sequence, 0, sequence.size() - 1, comparator);
}
private final static <T> void quickSortImplementation(List<T> sequence, int left, int right, Comparator<T> comparator) {
if (left >= right) return;
int lessThen = left;
int greaterThen = right;
int i = left;
T value = sequence.get(left);
while (i <= greaterThen) {
int cmp = comparator.compare(sequence.get(i), value);
if (cmp < 0) swap(sequence, i++, lessThen++);
else if (cmp > 0) swap(sequence, i, greaterThen--);
else ++i;
}
quickSortImplementation(sequence, left, lessThen - 1, comparator);
quickSortImplementation(sequence, greaterThen + 1, right, comparator);
}
public final static <T extends Comparable<T>> void quickSort(List<T> sequence) {
shuffle(sequence);
quickSortImplementation(sequence, 0, sequence.size() - 1);
}
private final static <T extends Comparable<T>> void quickSortImplementation(List<T> sequence, int left, int right) {
if (left >= right) return;
int lessThen = left;
int greaterThen = right;
int i = left;
T value = sequence.get(left);
while (i <= greaterThen) {
int cmp = sequence.get(i).compareTo(value);
if (cmp < 0) swap(sequence, i++, lessThen++);
else if (cmp > 0) swap(sequence, i, greaterThen--);
else ++i;
}
quickSortImplementation(sequence, left, lessThen - 1);
quickSortImplementation(sequence, greaterThen + 1, right);
}
public final static void quickSort(int[] sequence) {
shuffle(sequence);
quickSortImplementation(sequence, 0, sequence.length - 1);
}
private final static void quickSortImplementation(int[] sequence, int left, int right) {
if (left >= right) return;
int lessThen = left;
int greaterThen = right;
int i = left;
int value = sequence[left];
while (i <= greaterThen) {
if (sequence[i] < value) swap(sequence, i++, lessThen++);
else if (sequence[i] > value) swap(sequence, i, greaterThen--);
else ++i;
}
quickSortImplementation(sequence, left, lessThen - 1);
quickSortImplementation(sequence, greaterThen + 1, right);
}
public final static void quickSort(long[] sequence) {
shuffle(sequence);
quickSortImplementation(sequence, 0, sequence.length - 1);
}
private final static void quickSortImplementation(long[] sequence, int left, int right) {
if (left >= right) return;
int lessThen = left;
int greaterThen = right;
int i = left;
long value = sequence[left];
while (i <= greaterThen) {
if (sequence[i] < value) swap(sequence, i++, lessThen++);
else if (sequence[i] > value) swap(sequence, i, greaterThen--);
else ++i;
}
quickSortImplementation(sequence, left, lessThen - 1);
quickSortImplementation(sequence, greaterThen + 1, right);
}
public final static void quickSort(char[] sequence) {
shuffle(sequence);
quickSortImplementation(sequence, 0, sequence.length - 1);
}
private final static void quickSortImplementation(char[] sequence, int left, int right) {
if (left >= right) return;
int lessThen = left;
int greaterThen = right;
int i = left;
char value = sequence[left];
while (i <= greaterThen) {
if (sequence[i] < value) swap(sequence, i++, lessThen++);
else if (sequence[i] > value) swap(sequence, i, greaterThen--);
else ++i;
}
quickSortImplementation(sequence, left, lessThen - 1);
quickSortImplementation(sequence, greaterThen + 1, right);
}
public final static void quickSort(double[] sequence) {
shuffle(sequence);
quickSortImplementation(sequence, 0, sequence.length - 1);
}
private final static void quickSortImplementation(double[] sequence, int left, int right) {
if (left >= right) return;
int lessThen = left;
int greaterThen = right;
int i = left;
double value = sequence[left];
while (i <= greaterThen) {
if (sequence[i] < value) swap(sequence, i++, lessThen++);
else if (sequence[i] > value) swap(sequence, i, greaterThen--);
else ++i;
}
quickSortImplementation(sequence, left, lessThen - 1);
quickSortImplementation(sequence, greaterThen + 1, right);
}
public final static void quickSort(boolean[] sequence) {
shuffle(sequence);
quickSortImplementation(sequence, 0, sequence.length - 1);
}
private final static void quickSortImplementation(boolean[] sequence, int left, int right) {
if (left >= right) return;
int lessThen = left;
int greaterThen = right;
int i = left;
boolean value = sequence[left];
while (i <= greaterThen) {
if (!sequence[i] && value) swap(sequence, i++, lessThen++);
else if (sequence[i] && !value) swap(sequence, i, greaterThen--);
else ++i;
}
quickSortImplementation(sequence, left, lessThen - 1);
quickSortImplementation(sequence, greaterThen + 1, right);
}
public final static void quickSort(short[] sequence) {
shuffle(sequence);
quickSortImplementation(sequence, 0, sequence.length - 1);
}
private final static void quickSortImplementation(short[] sequence, int left, int right) {
if (left >= right) return;
int lessThen = left;
int greaterThen = right;
int i = left;
short value = sequence[left];
while (i <= greaterThen) {
if (sequence[i] < value) swap(sequence, i++, lessThen++);
else if (sequence[i] > value) swap(sequence, i, greaterThen--);
else ++i;
}
quickSortImplementation(sequence, left, lessThen - 1);
quickSortImplementation(sequence, greaterThen + 1, right);
}
public final static void quickSort(byte[] sequence) {
shuffle(sequence);
quickSortImplementation(sequence, 0, sequence.length - 1);
}
private final static void quickSortImplementation(byte[] sequence, int left, int right) {
if (left >= right) return;
int lessThen = left;
int greaterThen = right;
int i = left;
byte value = sequence[left];
while (i <= greaterThen) {
if (sequence[i] < value) swap(sequence, i++, lessThen++);
else if (sequence[i] > value) swap(sequence, i, greaterThen--);
else ++i;
}
quickSortImplementation(sequence, left, lessThen - 1);
quickSortImplementation(sequence, greaterThen + 1, right);
}
// unique
public static <T> ArrayList<T> unique(ArrayList<T> sequence) {
int size = 1;
for (int i = 1; i < sequence.size(); ++i)
if (!sequence.get(i).equals(sequence.get(i - 1)))
++size;
ArrayList<T> newSequence = new ArrayList<T>(size);
newSequence.add(sequence.get(0));
for (int i = 1; i < sequence.size(); ++i)
if (!sequence.get(i).equals(sequence.get(i - 1)))
newSequence.add(sequence.get(i));
return newSequence;
}
public static <T> T[] unique(T[] sequence) {
int size = 1;
for (int i = 1; i < sequence.length; ++i)
if (!sequence[i].equals(sequence[i - 1]))
++size;
T[] newSequence = (T[]) new Object[size];
newSequence[0] = sequence[0];
size = 0;
for (int i = 1; i < sequence.length; ++i)
if (!sequence[i].equals(sequence[i - 1]))
newSequence[++size] = sequence[i];
return newSequence;
}
public static int[] unique(int[] sequence) {
int size = 1;
for (int i = 1; i < sequence.length; ++i)
if (sequence[i] != sequence[i - 1])
++size;
int[] newSequence = new int[size];
newSequence[0] = sequence[0];
size = 0;
for (int i = 1; i < sequence.length; ++i)
if (sequence[i] != sequence[i - 1])
newSequence[++size] = sequence[i];
return newSequence;
}
public static long[] unique(long[] sequence) {
int size = 1;
for (int i = 1; i < sequence.length; ++i)
if (sequence[i] != sequence[i - 1])
++size;
long[] newSequence = new long[size];
newSequence[0] = sequence[0];
size = 0;
for (int i = 1; i < sequence.length; ++i)
if (sequence[i] != sequence[i - 1])
newSequence[++size] = sequence[i];
return newSequence;
}
public static char[] unique(char[] sequence) {
int size = 1;
for (int i = 1; i < sequence.length; ++i)
if (sequence[i] != sequence[i - 1])
++size;
char[] newSequence = new char[size];
newSequence[0] = sequence[0];
size = 0;
for (int i = 1; i < sequence.length; ++i)
if (sequence[i] != sequence[i - 1])
newSequence[++size] = sequence[i];
return newSequence;
}
public static double[] unique(double[] sequence) {
int size = 1;
for (int i = 1; i < sequence.length; ++i)
if (sequence[i] != sequence[i - 1])
++size;
double[] newSequence = new double[size];
newSequence[0] = sequence[0];
size = 0;
for (int i = 1; i < sequence.length; ++i)
if (sequence[i] != sequence[i - 1])
newSequence[++size] = sequence[i];
return newSequence;
}
public static boolean[] unique(boolean[] sequence) {
int size = 1;
for (int i = 1; i < sequence.length; ++i)
if (sequence[i] != sequence[i - 1])
++size;
boolean[] newSequence = new boolean[size];
newSequence[0] = sequence[0];
size = 0;
for (int i = 1; i < sequence.length; ++i)
if (sequence[i] != sequence[i - 1])
newSequence[++size] = sequence[i];
return newSequence;
}
public static short[] unique(short[] sequence) {
int size = 1;
for (int i = 1; i < sequence.length; ++i)
if (sequence[i] != sequence[i - 1])
++size;
short[] newSequence = new short[size];
newSequence[0] = sequence[0];
size = 0;
for (int i = 1; i < sequence.length; ++i)
if (sequence[i] != sequence[i - 1])
newSequence[++size] = sequence[i];
return newSequence;
}
public static byte[] unique(byte[] sequence) {
int size = 1;
for (int i = 1; i < sequence.length; ++i)
if (sequence[i] != sequence[i - 1])
++size;
byte[] newSequence = new byte[size];
newSequence[0] = sequence[0];
size = 0;
for (int i = 1; i < sequence.length; ++i)
if (sequence[i] != sequence[i - 1])
newSequence[++size] = sequence[i];
return newSequence;
}
}
| nlogn | 274_A. k-Multiple Free Set | 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 C {
public static final long MAX = 1000000000L;
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tok1 = new StringTokenizer(br.readLine());
final int n = Integer.parseInt(tok1.nextToken());
final long k = Integer.parseInt(tok1.nextToken());
StringTokenizer tok2 = new StringTokenizer(br.readLine());
int[] array = new int[n];
for(int i = 0; i < n; i++){
array[i] = Integer.parseInt(tok2.nextToken());
}
int size = n;
Arrays.sort(array);
boolean[] skip = new boolean[n];
for(int i = 0; i < n; i++){
if(skip[i]){
size--;
continue;
}
long input = array[i];
input *= k;
if(input > MAX){
continue;
}
final int pos = Arrays.binarySearch(array, (int)(input));
if(pos >= 0 && !skip[pos]){
skip[pos] = true;
}
}
System.out.println(size);
}
}
| nlogn | 274_A. k-Multiple Free Set | CODEFORCES |
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
import java.util.Arrays;
public class Main {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
long k = input.nextInt();
long[] nums = new long[n];
for (int i = 0; i < n; i++) {
nums[i] = input.nextInt();
}
Arrays.sort(nums);
Set<Long> wrong = new TreeSet<Long>();
long ans = 0;
for (int i = 0; i < n; i++) {
if (!wrong.contains(nums[i])) {
try {
wrong.add(nums[i] * k);
} catch (Exception e) {
}
ans++;
}
}
System.out.println(ans);
}
} | nlogn | 274_A. k-Multiple Free Set | CODEFORCES |
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class A implements Runnable {
BufferedReader in;
PrintWriter out;
StringTokenizer tok;
public static void main(String[] args) {
new Thread(null, new A(), "", 64*1024*1024).start();
}
public void run() {
try {
long t1 = 0, t2 = 0, m1 = 0, m2 = 0;
if (LOCAL) {
t1 = System.currentTimeMillis();
m1 = Runtime.getRuntime().freeMemory();
}
Locale.setDefault(Locale.US);
if (LOCAL) {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
} else {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
tok = new StringTokenizer("");
solve();
in.close();
out.close();
if (LOCAL) {
t2 = System.currentTimeMillis();
m2 = Runtime.getRuntime().freeMemory();
System.err.println("Time = " + (t2 - t1) + " ms.");
System.err.println("Memory = " + ((m1 - m2) / 1024) + " KB.");
}
} catch (Throwable e) {
e.printStackTrace(System.err);
throw new RuntimeException();
}
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
String line = in.readLine();
if (line == null) return null;
tok = new StringTokenizer(line);
}
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());
}
static class Mergesort {
private Mergesort() {}
public static void sort(int[] a) {
mergesort(a, 0, a.length - 1);
}
public static void sort(long[] a) {
mergesort(a, 0, a.length - 1);
}
public static void sort(double[] a) {
mergesort(a, 0, a.length - 1);
}
private static final int MAGIC_VALUE = 42;
private static void mergesort(int[] a, int leftIndex, int rightIndex) {
if (leftIndex < rightIndex) {
if (rightIndex - leftIndex <= MAGIC_VALUE) {
insertionSort(a, leftIndex, rightIndex);
} else {
int middleIndex = (leftIndex + rightIndex) / 2;
mergesort(a, leftIndex, middleIndex);
mergesort(a, middleIndex + 1, rightIndex);
merge(a, leftIndex, middleIndex, rightIndex);
}
}
}
private static void mergesort(long[] a, int leftIndex, int rightIndex) {
if (leftIndex < rightIndex) {
if (rightIndex - leftIndex <= MAGIC_VALUE) {
insertionSort(a, leftIndex, rightIndex);
} else {
int middleIndex = (leftIndex + rightIndex) / 2;
mergesort(a, leftIndex, middleIndex);
mergesort(a, middleIndex + 1, rightIndex);
merge(a, leftIndex, middleIndex, rightIndex);
}
}
}
private static void mergesort(double[] a, int leftIndex, int rightIndex) {
if (leftIndex < rightIndex) {
if (rightIndex - leftIndex <= MAGIC_VALUE) {
insertionSort(a, leftIndex, rightIndex);
} else {
int middleIndex = (leftIndex + rightIndex) / 2;
mergesort(a, leftIndex, middleIndex);
mergesort(a, middleIndex + 1, rightIndex);
merge(a, leftIndex, middleIndex, rightIndex);
}
}
}
private static void merge(int[] a, int leftIndex, int middleIndex, int rightIndex) {
int length1 = middleIndex - leftIndex + 1;
int length2 = rightIndex - middleIndex;
int[] leftArray = new int[length1];
int[] rightArray = new int[length2];
System.arraycopy(a, leftIndex, leftArray, 0, length1);
System.arraycopy(a, middleIndex + 1, rightArray, 0, length2);
for (int k = leftIndex, i = 0, j = 0; k <= rightIndex; k++) {
if (i == length1) {
a[k] = rightArray[j++];
} else if (j == length2) {
a[k] = leftArray[i++];
} else {
a[k] = leftArray[i] <= rightArray[j] ? leftArray[i++] : rightArray[j++];
}
}
}
private static void merge(long[] a, int leftIndex, int middleIndex, int rightIndex) {
int length1 = middleIndex - leftIndex + 1;
int length2 = rightIndex - middleIndex;
long[] leftArray = new long[length1];
long[] rightArray = new long[length2];
System.arraycopy(a, leftIndex, leftArray, 0, length1);
System.arraycopy(a, middleIndex + 1, rightArray, 0, length2);
for (int k = leftIndex, i = 0, j = 0; k <= rightIndex; k++) {
if (i == length1) {
a[k] = rightArray[j++];
} else if (j == length2) {
a[k] = leftArray[i++];
} else {
a[k] = leftArray[i] <= rightArray[j] ? leftArray[i++] : rightArray[j++];
}
}
}
private static void merge(double[] a, int leftIndex, int middleIndex, int rightIndex) {
int length1 = middleIndex - leftIndex + 1;
int length2 = rightIndex - middleIndex;
double[] leftArray = new double[length1];
double[] rightArray = new double[length2];
System.arraycopy(a, leftIndex, leftArray, 0, length1);
System.arraycopy(a, middleIndex + 1, rightArray, 0, length2);
for (int k = leftIndex, i = 0, j = 0; k <= rightIndex; k++) {
if (i == length1) {
a[k] = rightArray[j++];
} else if (j == length2) {
a[k] = leftArray[i++];
} else {
a[k] = leftArray[i] <= rightArray[j] ? leftArray[i++] : rightArray[j++];
}
}
}
private static void insertionSort(int[] a, int leftIndex, int rightIndex) {
for (int i = leftIndex + 1; i <= rightIndex; i++) {
int current = a[i];
int j = i - 1;
while (j >= leftIndex && a[j] > current) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = current;
}
}
private static void insertionSort(long[] a, int leftIndex, int rightIndex) {
for (int i = leftIndex + 1; i <= rightIndex; i++) {
long current = a[i];
int j = i - 1;
while (j >= leftIndex && a[j] > current) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = current;
}
}
private static void insertionSort(double[] a, int leftIndex, int rightIndex) {
for (int i = leftIndex + 1; i <= rightIndex; i++) {
double current = a[i];
int j = i - 1;
while (j >= leftIndex && a[j] > current) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = current;
}
}
}
void debug(Object... o) {
if (LOCAL) {
System.err.println(Arrays.deepToString(o));
}
}
final static boolean LOCAL = System.getProperty("ONLINE_JUDGE") == null;
//------------------------------------------------------------------------------
void solve() throws IOException {
int n = readInt();
long k = readLong();
if (k == 1) {
out.println(n);
return;
}
long[] a = new long[n];
for (int i = 0; i < n; i++) {
a[i] = readLong();
}
Mergesort.sort(a);
int ans = 0;
boolean[] processed = new boolean[n];
debug(a);
for (int i = 0; i < n; i++) {
if (processed[i]) {
continue;
}
processed[i] = true;
long cur = a[i];
ans++;
int index = Arrays.binarySearch(a, cur * k);
if (index >= 0) {
processed[index] = true;
}
}
out.println(ans);
}
}
| nlogn | 274_A. k-Multiple Free Set | CODEFORCES |
import java.io.*;
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 k = sc.nextInt();
TreeSet<Integer> bad = new TreeSet<>();
int a [] = new int [n];
for (int i = 0; i < n; i++)
a[i] = sc.nextInt();
Random rnd = new Random();
for (int i = 1; i < n; i++) {
int j = rnd.nextInt(i + 1);
int t = a[i];
a[i] = a[j];
a[j] = t;
}
Arrays.sort(a);
int result = 0;
for (int i = 0; i < n; i++) {
if (!bad.contains(a[i])) {
result++;
long next = (long) a[i] * k;
if (next <= 1000000000)
bad.add((int) next);
}
}
out.println(result);
}
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 | 274_A. k-Multiple Free Set | CODEFORCES |
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeSet;
//basically tried to understand ping's greedy alg
public class kMultRedo {
static int n;
static int k;
public static void main(String[] args){
Set<Integer> set = new TreeSet<Integer>();
FastScanner s = new FastScanner();
n = s.nextInt();
k = s.nextInt();
int[] a = new int[n];
for(int i=0; i<n; i++){
a[i] = s.nextInt();
}
Arrays.sort(a);
for(int i=0; i<n; i++){
if(a[i]%k !=0){
set.add(a[i]);
}else{
if(!set.contains(a[i]/k)){
set.add(a[i]);
}
}
}
System.out.println(set.size());
}
public static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(String s) {
try {
br = new BufferedReader(new FileReader(s));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String nextToken() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
}
}
| nlogn | 274_A. k-Multiple Free Set | 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
* @author ocelopilli
*/
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();
long k = in.nextLong();
long[] a = new long[n];
for (int i=0; i<n; i++) a[i] = in.nextInt();
Arrays.sort( a );
boolean[] ok = new boolean[ n ];
Arrays.fill( ok, true );
if (k > 1) for (int i=0; i<n; i++)
{
if ( ok[i] == false ) continue;
int pos = Arrays.binarySearch( a, a[i]*k );
if ( pos >= 0 )
{
//out.println( a[i]+" "+a[pos] );
ok[ pos ] = false;
}
}
int ans = 0;
for (boolean x : ok) if ( x ) ans++;
out.println( ans );
}
}
class InputReader {
BufferedReader br;
StringTokenizer st;
public InputReader(InputStream in)
{
br = new BufferedReader(new InputStreamReader(in));
st = null;
}
public String next()
{
while (st==null || !st.hasMoreTokens())
{
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt()
{
return Integer.parseInt(next());
}
public long nextLong()
{
return Long.parseLong(next());
}
}
| nlogn | 274_A. k-Multiple Free Set | CODEFORCES |
import java.io.*;
import java.util.*;
public class A274 {
/**
* @param args
*/
public static void main(String[] args) {
Scanner in= new Scanner(System.in);
int n=in.nextInt();
int k=in.nextInt();
Long a[] =new Long[n];
Hashtable<Long, Boolean> hash= new Hashtable<Long, Boolean>();
for (int i=0;i< n;i++){
a[i]=in.nextLong();
}
Arrays.sort(a);
for (int i=0;i<n;i++){
if (!hash.containsKey(a[i]) ){
hash.put(a[i]*k, true);
}
}
System.out.println(hash.size());
}
}
| nlogn | 274_A. k-Multiple Free Set | CODEFORCES |
import static java.math.BigInteger.*;
import static java.util.Arrays.*;
import java.io.*;
import java.lang.reflect.*;
import java.util.*;
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 K = sc.nextInt();
Long [] A = sc.nextLongs();
sort(A);
Set<Long> S = new HashSet<Long>();
for (long a : A) {
if (a % K == 0 && S.contains(P * (a/K)))
continue;
S.add(P*a);
}
int res = S.size();
exit(res);
}
long P = probablePrime(50, new Random()).longValue();
////////////////////////////////////////////////////////////////////////////////////
/* Dear hacker, don't bother reading below this line, unless you want to help me debug my I/O routines :-) */
static MyScanner sc = new MyScanner();
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;
}
public String [] next (int N) {
String [] res = new String [N];
for (int i = 0; i < N; ++i)
res[i] = sc.next();
return res;
}
public Integer [] nextInt (int N) {
Integer [] res = new Integer [N];
for (int i = 0; i < N; ++i)
res[i] = sc.nextInt();
return res;
}
public Long [] nextLong (int N) {
Long [] res = new Long [N];
for (int i = 0; i < N; ++i)
res[i] = sc.nextLong();
return res;
}
public Double [] nextDouble (int N) {
Double [] res = new Double [N];
for (int i = 0; i < N; ++i)
res[i] = sc.nextDouble();
return res;
}
public String [][] nextStrings (int N) {
String [][] res = new String [N][];
for (int i = 0; i < N; ++i)
res[i] = sc.nextStrings();
return res;
}
public Integer [][] nextInts (int N) {
Integer [][] res = new Integer [N][];
for (int i = 0; i < N; ++i)
res[i] = sc.nextInts();
return res;
}
public Long [][] nextLongs (int N) {
Long [][] res = new Long [N][];
for (int i = 0; i < N; ++i)
res[i] = sc.nextLongs();
return res;
}
public Double [][] nextDoubles (int N) {
Double [][] res = new Double [N][];
for (int i = 0; i < N; ++i)
res[i] = sc.nextDoubles();
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) {
printDelim(" ", o, a);
}
static void cprint(Object o, Object... a) {
printDelim("", o, a);
}
static void printDelim (String delim, Object o, Object... a) {
pw.println(build(delim, 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(String delim, Object o, Object... a) {
StringBuilder b = new StringBuilder();
append(b, o, delim);
for (Object p : a)
append(b, p, delim);
return b.toString().trim();
}
static void append(StringBuilder b, Object o, String delim) {
if (o.getClass().isArray()) {
int L = Array.getLength(o);
for (int i = 0; i < L; ++i)
append(b, Array.get(o, i), delim);
} else if (o instanceof Iterable<?>) {
for (Object p : (Iterable<?>)o)
append(b, p, delim);
} else
b.append(delim).append(o);
}
////////////////////////////////////////////////////////////////////////////////////
public static void main(String[] args) {
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 | 274_A. k-Multiple Free Set | CODEFORCES |
import java.util.*;
import java.io.*;
public class P220A
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] a = new int[n];
List<Integer> b = new ArrayList<Integer>(n);
for (int i = 0; i < n; i++)
{
a[i] = sc.nextInt();
b.add(a[i]);
}
Collections.sort(b);
int c = 0;
for (int i = 0; i < n; i++)
{
if (a[i] != b.get(i)) c++;
}
if (c == 0 || c == 2)
{
System.out.println("YES");
}
else
{
System.out.println("NO");
}
}
}
| nlogn | 220_A. Little Elephant and Problem | CODEFORCES |
import java.io.*;
import java.util.*;
import java.math.*;
import static java.lang.Math.*;
public class Main implements Runnable {
void randomShuffle(int[] arr) {
Random rnd = new Random();
for (int i = arr.length - 1; i >= 0; i--) {
int pos = rnd.nextInt(i + 1);
int temp = arr[pos];
arr[pos] = arr[i];
arr[i] = temp;
}
}
void solve() throws Exception {
int n = sc.nextInt();
int[] a = new int[n];
int[] ac = new int[n];
for (int i = 0; i < n; i++) {
a[i] = ac[i] = sc.nextInt();
}
randomShuffle(ac);
Arrays.sort(ac);
int diff = 0;
for (int i = 0; i < n; i++) {
if (a[i] != ac[i]) {
diff++;
}
}
if (diff <= 2) {
out.println("YES");
} else {
out.println("NO");
}
}
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) {
Main.uncaught = t;
} finally {
out.close();
}
}
public static void main(String[] args) throws Throwable {
Thread t = new Thread(null, new Main(), "", 128 * 1024 * 1024);
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 | 220_A. Little Elephant and Problem | CODEFORCES |
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.util.Locale;
import java.io.OutputStream;
import java.util.RandomAccess;
import java.io.PrintWriter;
import java.util.AbstractList;
import java.io.Writer;
import java.util.Collection;
import java.util.List;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.math.BigInteger;
import java.util.Collections;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Jacob Jiang
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int[] a = in.nextIntArray(n);
int[] b = a.clone();
Collections.sort(ArrayUtils.asList(b));
int diff = 0;
for (int i = 0; i < n; i++) {
if (a[i] != b[i])
diff++;
}
out.println(diff <= 2 ? "YES" : "NO");
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1 << 16];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c & 15;
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public static boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int[] nextIntArray(int count) {
int[] result = new int[count];
for (int i = 0; i < count; i++) {
result[i] = nextInt();
}
return result;
}
}
class OutputWriter {
private PrintWriter writer;
public OutputWriter(OutputStream stream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void println(String x) {
writer.println(x);
}
public void close() {
writer.close();
}
}
class ArrayUtils {
public static List<Integer> asList(int[] array) {
return new IntList(array);
}
private static class IntList extends AbstractList<Integer> implements RandomAccess {
int[] array;
private IntList(int[] array) {
this.array = array;
}
public Integer get(int index) {
return array[index];
}
public Integer set(int index, Integer element) {
int result = array[index];
array[index] = element;
return result;
}
public int size() {
return array.length;
}
}
}
| nlogn | 220_A. Little Elephant and Problem | CODEFORCES |
import java.io.*;
import java.util.*;
public class Solution {
private StringTokenizer st;
private BufferedReader in;
private PrintWriter out;
public void solve() throws IOException {
int n = nextInt();
int[] a = new int[n];
for (int i = 0; i < n; ++i) {
a[i] = nextInt();
}
int[] b = a.clone();
Arrays.sort(b);
int diff = 0;
for (int i = 0; i < n; ++i) {
if (a[i] != b[i]) {
diff++;
}
}
out.println(diff <= 2 ? "YES" : "NO");
}
public void run() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
eat("");
solve();
out.close();
}
void eat(String s) {
st = new StringTokenizer(s);
}
String next() throws IOException {
while (!st.hasMoreTokens()) {
String line = in.readLine();
if (line == null) {
return null;
}
eat(line);
}
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());
}
public static void main(String[] args) throws IOException {
Locale.setDefault(Locale.US);
new Solution().run();
}
} | nlogn | 220_A. Little Elephant and Problem | CODEFORCES |
import java.awt.Point;
import java.io.*;
import java.math.BigInteger;
import java.util.*;
import static java.lang.Math.*;
public class A implements Runnable{
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
void init() throws FileNotFoundException{
if (ONLINE_JUDGE){
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}else{
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
}
}
String readString() throws IOException{
while(!tok.hasMoreTokens()){
try{
tok = new StringTokenizer(in.readLine());
}catch (Exception e){
return null;
}
}
return tok.nextToken();
}
int readInt() throws IOException{
return Integer.parseInt(readString());
}
long readLong() throws IOException{
return Long.parseLong(readString());
}
double readDouble() throws IOException{
return Double.parseDouble(readString());
}
public static void main(String[] args){
new Thread(null, new A(), "", 128 * (1L << 20)).start();
}
long timeBegin, timeEnd;
void time(){
timeEnd = System.currentTimeMillis();
System.err.println("Time = " + (timeEnd - timeBegin));
}
long memoryTotal, memoryFree;
void memory(){
memoryFree = Runtime.getRuntime().freeMemory();
System.err.println("Memory = " + ((memoryTotal - memoryFree) >> 10) + " KB");
}
void debug(Object... objects){
if (DEBUG){
for (Object o: objects){
System.err.println(o.toString());
}
}
}
public void run(){
try{
timeBegin = System.currentTimeMillis();
memoryTotal = Runtime.getRuntime().freeMemory();
init();
solve();
out.close();
time();
memory();
}catch (Exception e){
e.printStackTrace(System.err);
System.exit(-1);
}
}
boolean DEBUG = false;
void solve() throws IOException{
int n = readInt();
int[] a = new int[n];
Integer[] b = new Integer[n];
for (int i = 0; i < n; ++i){
a[i] = readInt();
b[i] = a[i];
}
Arrays.sort(b);
int count = 0;
for (int i = 0; i < n; ++i){
if (a[i] != b[i]){
count++;
}
}
if (count == 2 || count == 0){
out.println("YES");
}else{
out.println("NO");
}
}
}
| nlogn | 220_A. Little Elephant and Problem | CODEFORCES |
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Task solver = new Task();
int testCount = 1;
for (int i = 1; i <= testCount; i++)
solver.solve(i, in, out);
out.close();
}
}
class Task {
int n;
int[] a;
int[] b;
public void solve(int testNumber, InputReader in, PrintWriter out) {
n = in.readInt();
a = new int[n];
b = new int[n];
for (int i = 0; i < n; ++i)
a[i] = b[i] = in.readInt();
sort(0, n - 1);
int different = 0;
for (int i = 0; i < n; ++i)
if (a[i] != b[i])
++different;
out.println(different <= 2 ? "YES" : "NO");
}
public void sort(int lo, int hi) {
if (lo < hi) {
int mid = (lo + hi) / 2;
sort(lo, mid);
sort(mid + 1, hi);
merge(lo, mid, hi);
}
}
public void merge(int lo, int mid, int hi) {
int n1 = mid - lo + 1;
int n2 = hi - (mid + 1) + 1;
int[] x = new int[n1 + 1];
int[] y = new int[n2 + 1];
for (int i = 0; i < n1; ++i)
x[i] = b[lo + i];
for (int j = 0; j < n2; ++j)
y[j] = b[mid + 1 + j];
x[n1] = y[n2] = Integer.MAX_VALUE;
for (int k = lo, i = 0, j = 0; k <= hi; ++k)
b[k] = x[i] < y[j] ? x[i++] : y[j++];
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuffer res = new StringBuffer();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public Long readLong() {
return Long.parseLong(readString());
}
public Double readDouble() {
return Double.parseDouble(readString());
}
public static boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
} | nlogn | 220_A. Little Elephant and Problem | CODEFORCES |
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.Scanner;
import java.util.Vector;
public class Main {
public static void main(String[] args) {
Scanner in=new Scanner(new InputStreamReader(System.in));
PrintWriter out=new PrintWriter(System.out);
int n=in.nextInt();
Vector<Integer> mas=new Vector<Integer>();
Vector<Integer> mas2=new Vector<Integer>();
int index=-1;
boolean res=false;
for(int i=0; i<n; i++){
mas.add(in.nextInt());
if(i!=0 && mas.get(i)<mas.get(i-1)){
index=i-1;
break;
}
}
if(index==-1) res=true;
else{
int min=mas.get(index+1);
int minIndex=index+1;
for(int i=index+2; i<n; i++){
mas.add(in.nextInt());
if(mas.get(i)<=min){
min=mas.get(i);
minIndex=i;
}
}
mas2.addAll(mas);
mas.set(minIndex, mas.get(index));
mas.set(index, min);
int o=mas.hashCode();
Collections.sort(mas);
int nw=mas.hashCode();
res=nw==o;
}
if(!res){
mas=mas2;
for(int i=n-1; i>=0; i--){
if(i!=n-1 && mas.get(i)>mas.get(i+1)){
index=i+1;
break;
}
}
if(index==-1) res=true;
else{
int max=mas.get(index-1);
int maxIndex=index-1;
for(int i=index-1; i>=0; i--){
if(mas.get(i)>=max){
max=mas.get(i);
maxIndex=i;
}
}
mas.set(maxIndex, mas.get(index));
mas.set(index, max);
int o=mas.hashCode();
Collections.sort(mas);
int nw=mas.hashCode();
res=res||nw==o;
}
}
if(res) out.println("YES");
else out.println("NO");
out.close();
}
} | nlogn | 220_A. Little Elephant and Problem | CODEFORCES |
import java.io.BufferedReader;
import java.io.DataInputStream;
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.util.Arrays;
public class Main{
public static void main(String[] args) throws Exception {
Parserdoubt12 s = new Parserdoubt12(System.in);
int n = s.nextInt();
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
}
int copy[] = a.clone();
Arrays.sort(a);
int count = 0;
for (int i = 0; i < copy.length; i++) {
if(a[i] != copy[i]) count++;
}
if(count <= 2) System.out.println("YES");
else System.out.println("NO");
}
}
class Parserdoubt12
{
final private int BUFFER_SIZE = 1 << 17;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Parserdoubt12(InputStream in)
{
din = new DataInputStream(in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String nextString() throws Exception
{
StringBuffer sb=new StringBuffer("");
byte c = read();
while (c <= ' ') c = read();
do
{
sb.append((char)c);
c=read();
}while(c>' ');
return sb.toString();
}
public char nextChar() throws Exception
{
byte c=read();
while(c<=' ') c= read();
return (char)c;
}
public int nextInt() throws Exception
{
int ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = c == '-';
if (neg) c = read();
do
{
ret = ret * 10 + c - '0';
c = read();
} while (c > ' ');
if (neg) return -ret;
return ret;
}
public long nextLong() throws Exception
{
long ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = c == '-';
if (neg) c = read();
do
{
ret = ret * 10 + c - '0';
c = read();
} while (c > ' ');
if (neg) return -ret;
return ret;
}
private void fillBuffer() throws Exception
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) buffer[0] = -1;
}
private byte read() throws Exception
{
if (bufferPointer == bytesRead) fillBuffer();
return buffer[bufferPointer++];
}
} | nlogn | 220_A. Little Elephant and Problem | CODEFORCES |
import java.util.*;
public class Main {
public static void main(String[] args) {
// long start = System.currentTimeMillis();
// long end = System.currentTimeMillis();
// System.out.println(" Execution time was "+(end-start)+" ms.");
Scanner kb = new Scanner(System.in);
int n = kb.nextInt();
int a[] = new int[n];
int b[] = new int[n];
for(int i = 0;i<n;i++){
a[i]=kb.nextInt();
b[i]=a[i];
}
Arrays.sort(a);
int count = 0;
for(int i=0;i<n;i++){
if(a[i]!=b[i])count++;
}
if(count<=2)
System.out.println("YES");
else
System.out.println("NO");
}
}
| nlogn | 220_A. Little Elephant and Problem | CODEFORCES |
import java.io.*;
import java.util.*;
import java.math.*;
public class A {
static BufferedReader in;
static PrintWriter out;
static StringTokenizer st;
static Random rnd;
void solve() throws IOException {
int n = nextInt();
int[] arr = new int[n];
Integer[] arrCopy = new Integer[n];
for (int i = 0; i < n; i++)
arr[i] = arrCopy[i] = nextInt();
Arrays.sort(arrCopy);
int bad = 0;
for (int i = 0; i < n; i++)
if (arr[i] != arrCopy[i])
++bad;
boolean fail = bad > 2;
out.println(!fail ? "YES" : "NO");
}
public static void main(String[] args) {
new A().run();
}
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
rnd = new Random();
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(42);
}
}
String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String line = in.readLine();
if (line == null)
return null;
st = new StringTokenizer(line);
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
} | nlogn | 220_A. Little Elephant and Problem | CODEFORCES |
import java.awt.geom.*;
import java.io.*;
import java.math.*;
import java.util.*;
import java.util.regex.*;
import static java.lang.Math.*;
public class A {
public A() throws Exception {
int n = in.nextInt();
int[] arr = new int[n];
for (int i=0; i<n; i++) arr[i] = in.nextInt();
int[] arr2 = arr.clone();
Arrays.sort(arr2);
int diff = 0;
for (int i=0; i<n; i++) {
if (arr2[i]!=arr[i]) diff++;
}
if (diff<=2) System.out.println("YES");
else System.out.println("NO");
}
Scanner in = new Scanner(System.in);
StringBuilder buf = new StringBuilder();
public static void main(String[] args) throws Exception { // {{{
new A();
} // }}}
public static void debug(Object... arr) { // {{{
System.err.println(Arrays.deepToString(arr));
} // }}}
public static class Scanner { // {{{
BufferedReader br;
String line;
StringTokenizer st;
public Scanner(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
}
public boolean hasNext() throws IOException {
while ((st==null||!st.hasMoreTokens())&&(line=br.readLine())!=null)
st = new StringTokenizer(line);
return st.hasMoreTokens();
}
public String next() throws IOException {
if (hasNext()) return st.nextToken();
throw new NoSuchElementException();
}
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());
}
} // }}}
}
| nlogn | 220_A. Little Elephant and Problem | CODEFORCES |
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Locale;
import java.util.Queue;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
public class Solution implements Runnable {
BufferedReader in;
PrintWriter out;
StringTokenizer st;
String nextToken() throws Exception {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
int nextInt() throws Exception {
return Integer.parseInt(nextToken());
}
long nextLong() throws Exception {
return Long.parseLong(nextToken());
}
double nextDouble() throws Exception {
return Double.parseDouble(nextToken());
}
int fu(int[] a, int l) {
for (int i = l; i < a.length - 1; i++) {
if (a[i] > a[i + 1]) return i;
}
return a.length;
}
void swap(int[] a, int q, int w) {
int t = a[q]; a[q] = a[w]; a[w] = t;
}
void solve() throws Exception {
int n = nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
int q = fu(a, 0);
if (q == n) out.println("YES"); else {
int w = fu(a, q + 1);
if (w < n) {
boolean ans = false;
swap(a, q, w);
ans |= fu(a, 0) == n;
swap(a, q, w);
if (q < n - 1) {
swap(a, q + 1, w);
ans |= fu(a, 0) == n;
swap(a, q + 1, w);
}
if (w < n - 1) {
swap(a, q, w + 1);
ans |= fu(a, 0) == n;
swap(a, q, w + 1);
}
if (q < n - 1 && w < n - 1) {
swap(a, q + 1, w + 1);
ans |= fu(a, 0) == n;
swap(a, q + 1, w + 1);
}
if (ans) out.println("YES"); else out.println("NO");
} else {
int j = q + 1;
while (j < n && a[j] == a[q + 1]) j++;
j--;
swap(a, q, j);
if (fu(a, 0) == n) out.println("YES"); else {
swap(a, q, j);
q++;
j = q - 1;
while (j >= 0 && a[j] == a[q - 1]) j--;
j++;
swap(a, q, j);
if (fu(a, 0) == n) out.println("YES"); else out.println("NO");
}
}
}
}
public void run() {
try {
Locale.setDefault(Locale.UK);
in = new BufferedReader(new InputStreamReader(System.in));
// in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter(System.out);
// out = new PrintWriter("output.txt");
solve();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
} finally {
out.close();
}
}
public static void main(String[] args) {
// new Thread(null, new Solution(), "1", 1 << 28).start();
(new Solution()).run();
}
} | nlogn | 220_A. Little Elephant and Problem | CODEFORCES |
import java.util.List;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Random;
import java.io.Reader;
import java.io.Writer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author niyaznigmatul
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
FastPrinter out = new FastPrinter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public void solve(int testNumber, FastScanner in, FastPrinter out) {
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
int[] b = a.clone();
ArrayUtils.sort(b);
int count = 0;
for (int i = 0; i < n; i++) {
if (a[i] != b[i]) {
++count;
}
}
out.println(count <= 2 ? "YES" : "NO");
}
}
class FastScanner extends BufferedReader {
boolean isEOF;
public FastScanner(InputStream is) {
super(new InputStreamReader(is));
}
public int read() {
try {
int ret = super.read();
if (isEOF && ret < 0) {
throw new InputMismatchException();
}
isEOF = ret == -1;
return ret;
} catch (IOException e) {
throw new InputMismatchException();
}
}
static boolean isWhiteSpace(int c) {
return c >= -1 && c <= 32;
}
public int nextInt() {
int c = read();
while (isWhiteSpace(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int ret = 0;
while (!isWhiteSpace(c)) {
if (c < '0' || c > '9') {
throw new NumberFormatException("digit expected " + (char) c
+ " found");
}
ret = ret * 10 + c - '0';
c = read();
}
return ret * sgn;
}
}
class FastPrinter extends PrintWriter {
public FastPrinter(OutputStream out) {
super(out);
}
public FastPrinter(Writer out) {
super(out);
}
}
class ArrayUtils {
public static void sort(int[] a) {
Random rand = new Random(System.nanoTime());
for (int i = 0; i < a.length; i++) {
int j = rand.nextInt(i + 1);
int t = a[i];
a[i] = a[j];
a[j] = t;
}
Arrays.sort(a);
}
}
| nlogn | 220_A. Little Elephant and Problem | CODEFORCES |
import static java.lang.Math.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
import java.util.*;
import java.io.*;
import java.math.*;
import java.awt.geom.Line2D;
import java.awt.Point;
import static java.lang.reflect.Array.*;
public class LittleElephantAndProblem {
boolean DEBUG = true;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringBuilder out = new StringBuilder();
StringTokenizer st = null;
String s() throws IOException {
if (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
int i() throws IOException {
return Integer.parseInt(s());
}
int i(String s) throws IOException {
return Integer.parseInt(s);
}
long l() throws IOException {
return Long.parseLong(s());
}
long l(String s) throws IOException {
return Long.parseLong(s);
}
double d() throws IOException {
return Double.parseDouble(s());
}
double d(String s) throws IOException {
return Double.parseDouble(s);
}
void D(Object a) {
if (DEBUG) {
int len = getLength(a);
for (int i = 0; i < len; ++i) {
System.out.print(get(a, i) + " ");
}
System.out.println();
}
}
void D(Object[] a) {
if (DEBUG) {
int R = getLength(a), C = getLength(get(a, 0));
for (int i = 0; i < R; ++i) {
for (int j = 0; j < C; ++j) {
System.out.print(get(get(a, i), j) + " ");
}
System.out.println();
}
}
}
void D(String args) {
if (DEBUG) {
System.out.print(args);
}
}
void D(String format, Object... args) {
if (DEBUG) {
System.out.printf(format, args);
}
}
void fl() {
System.out.print(out);
}
int n = i();
public LittleElephantAndProblem() throws IOException {
List<Integer> a = new ArrayList<Integer>();
List<Integer> b = new ArrayList<Integer>();
for (int i = 0; i < n; ++i) {
int x = i();
a.add(x);
b.add(x);
}
sort(b);
int d = 0;
for (int i = 0; i < n; ++i) {
if ((int)a.get(i) != (int)b.get(i)) {
++d;
}
}
if (d > 2) {
out.append("NO\n");
} else {
out.append("YES\n");
}
fl();
}
public static void main(String[] args) throws IOException {
new LittleElephantAndProblem();
}
} | nlogn | 220_A. Little Elephant and Problem | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Locale;
import java.util.StringTokenizer;
public class A {
private void solve() throws IOException {
int n = nextInt();
Integer[] a = new Integer[n];
Integer[] b = new Integer[n];
for (int i = 0; i < n; i++) {
a[i] = b[i] = nextInt();
}
Arrays.sort(a);
int k = 0;
for (int i = 0; i < n; i++) {
if (!a[i].equals(b[i])) {
k++;
}
}
if (k <= 2) {
println("YES");
} else {
println("NO");
}
}
private String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
private int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(nextToken());
}
private double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(nextToken());
}
private long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
private void print(Object o) {
writer.print(o);
}
private void println(Object o) {
writer.println(o);
}
private void printf(String format, Object... o) {
writer.printf(format, o);
}
public static void main(String[] args) {
long time = System.currentTimeMillis();
Locale.setDefault(Locale.US);
new A().run();
System.err.printf("%.3f\n", 1e-3 * (System.currentTimeMillis() - time));
}
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter writer;
private void run() {
try {
reader = new BufferedReader(new InputStreamReader(System.in));
writer = new PrintWriter(System.out);
solve();
reader.close();
writer.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(13);
}
}
} | nlogn | 220_A. Little Elephant and Problem | CODEFORCES |
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Locale;
import java.util.Queue;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
public class Solution implements Runnable {
BufferedReader in;
PrintWriter out;
StringTokenizer st;
String nextToken() throws Exception {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
int nextInt() throws Exception {
return Integer.parseInt(nextToken());
}
long nextLong() throws Exception {
return Long.parseLong(nextToken());
}
double nextDouble() throws Exception {
return Double.parseDouble(nextToken());
}
void solve() throws Exception {
int n = nextInt();
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
Integer[] b = a.clone();
Arrays.sort(b);
int d = 0;
for (int i = 0; i < n; i++) {
if (!a[i].equals(b[i])) d++;
}
out.println(d > 2? "NO" : "YES");
}
public void run() {
try {
Locale.setDefault(Locale.UK);
in = new BufferedReader(new InputStreamReader(System.in));
// in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter(System.out);
// out = new PrintWriter("output.txt");
solve();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
} finally {
out.close();
}
}
public static void main(String[] args) {
// new Thread(null, new Solution(), "1", 1 << 28).start();
(new Solution()).run();
}
} | nlogn | 220_A. Little Elephant and Problem | CODEFORCES |
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.util.Comparator;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.io.IOException;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Egor Kulikov ([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 count = in.readInt();
int[] array = IOUtils.readIntArray(in, count);
int[] sorted = array.clone();
ArrayUtils.sort(sorted, IntComparator.DEFAULT);
int differs = 0;
for (int i = 0; i < count; i++) {
if (array[i] != sorted[i])
differs++;
}
if (differs <= 2)
out.printLine("YES");
else
out.printLine("NO");
}
}
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();
}
}
class IOUtils {
public static int[] readIntArray(InputReader in, int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = in.readInt();
return array;
}
}
class ArrayUtils {
private static int[] tempInt = new int[0];
public static int[] sort(int[] array, IntComparator comparator) {
return sort(array, 0, array.length, comparator);
}
public static int[] sort(int[] array, int from, int to, IntComparator comparator) {
ensureCapacityInt(to - from);
System.arraycopy(array, from, tempInt, 0, to - from);
sortImpl(array, from, to, tempInt, 0, to - from, comparator);
return array;
}
private static void ensureCapacityInt(int size) {
if (tempInt.length >= size)
return;
size = Math.max(size, tempInt.length << 1);
tempInt = new int[size];
}
private static void sortImpl(int[] array, int from, int to, int[] temp, int fromTemp, int toTemp, IntComparator comparator) {
if (to - from <= 1)
return;
int middle = (to - from) >> 1;
int tempMiddle = fromTemp + middle;
sortImpl(temp, fromTemp, tempMiddle, array, from, from + middle, comparator);
sortImpl(temp, tempMiddle, toTemp, array, from + middle, to, comparator);
int index = from;
int index1 = fromTemp;
int index2 = tempMiddle;
while (index1 < tempMiddle && index2 < toTemp) {
if (comparator.compare(temp[index1], temp[index2]) <= 0)
array[index++] = temp[index1++];
else
array[index++] = temp[index2++];
}
if (index1 != tempMiddle)
System.arraycopy(temp, index1, array, index, tempMiddle - index1);
if (index2 != toTemp)
System.arraycopy(temp, index2, array, index, toTemp - index2);
}
}
interface IntComparator {
public static final IntComparator DEFAULT = new IntComparator() {
public int compare(int first, int second) {
if (first < second)
return -1;
if (first > second)
return 1;
return 0;
}
};
public int compare(int first, int second);
} | nlogn | 220_A. Little Elephant and Problem | 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 A implements Runnable
{
String file = "input";
boolean TEST = System.getProperty("ONLINE_JUDGE") == null;
void solve() throws IOException
{
int n = nextInt();
int[] a = new int[n];
for(int i = 0; i < n; i++) a[i] = nextInt();
int[] b = a.clone();
sortInt(b);
int count = 0;
for(int i = 0; i < a.length; i++)
if(a[i] != b[i]) count++;
if(count == 0 || count == 2) out.println("YES");
else out.println("NO");
}
Random rnd = new Random();
void sortInt(int[] a)
{
sortInt(a, 0, a.length - 1);
}
void sortInt(int[] a, int from, int to)
{
if(from >= to) return;
int i = from - 1;
int p = rnd.nextInt(to - from + 1) + from;
int t = a[p]; a[p] = a[to]; a[to] = t;
for(int j = from; j < to; j++)
if(a[j] <= a[to])
{
i++;
t = a[i]; a[i] = a[j]; a[j] = t;
}
t = a[i + 1]; a[i + 1] = a[to]; a[to] = t;
sortInt(a, i + 2, to);
while(i >= 0 && a[i] == a[i + 1]) i--;
sortInt(a, from, i);
}
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 print(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(file + ".in"));
else input = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new BufferedOutputStream(System.out));
}
public static void main(String[] args) throws IOException
{
new Thread(null, new A(), "", 1 << 22).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 | 220_A. Little Elephant and Problem | CODEFORCES |
import java.io.*;
import java.util.*;
import java.math.*;
public class A {
static BufferedReader in;
static PrintWriter out;
static StringTokenizer st;
static Random rnd;
void solve() throws IOException {
int n = nextInt();
int[] arr = new int[n];
Integer[] arrCopy = new Integer[n];
for (int i = 0; i < n; i++)
arr[i] = arrCopy[i] = nextInt();
Arrays.sort(arrCopy);
int bad = 0;
for (int i = 0; i < n; i++)
if (arr[i] != arrCopy[i])
++bad;
boolean fail = bad > 2;
out.println(!fail ? "YES" : "NO");
}
public static void main(String[] args) {
new A().run();
}
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
rnd = new Random();
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(42);
}
}
String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String line = in.readLine();
if (line == null)
return null;
st = new StringTokenizer(line);
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
} | nlogn | 220_A. Little Elephant and Problem | 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 A implements Runnable
{
String file = "input";
boolean TEST = System.getProperty("ONLINE_JUDGE") == null;
void solve() throws IOException
{
int n = nextInt();
int[] a = new int[n];
for(int i = 0; i < n; i++) a[i] = nextInt();
int[] b = a.clone();
qsort(b);
//sortInt(b);
int count = 0;
for(int i = 0; i < a.length; i++)
if(a[i] != b[i]) count++;
if(count == 0 || count == 2) out.println("YES");
else out.println("NO");
}
void qsort(int[] a)
{
List<Integer> as = new ArrayList<Integer>();
for(int x : a) as.add(x);
Collections.shuffle(as);
for(int i = 0; i < a.length; i++) a[i] = as.get(i);
sort(a);
}
Random rnd = new Random();
void sortInt(int[] a)
{
sortInt(a, 0, a.length - 1);
}
void sortInt(int[] a, int from, int to)
{
if(from >= to) return;
int i = from - 1;
int p = rnd.nextInt(to - from + 1) + from;
int t = a[p]; a[p] = a[to]; a[to] = t;
for(int j = from; j < to; j++)
if(a[j] <= a[to])
{
i++;
t = a[i]; a[i] = a[j]; a[j] = t;
}
t = a[i + 1]; a[i + 1] = a[to]; a[to] = t;
sortInt(a, i + 2, to);
while(i >= 0 && a[i] == a[i + 1]) i--;
sortInt(a, from, i);
}
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 print(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(file + ".in"));
else input = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new BufferedOutputStream(System.out));
}
public static void main(String[] args) throws IOException
{
new Thread(null, new A(), "", 1 << 22).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 | 220_A. Little Elephant and Problem | 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.io.StreamTokenizer;
import java.util.Arrays;
public class A {
static StreamTokenizer st;
static class Sort implements Comparable<Sort> {
int val;
public int compareTo(Sort o) {
return this.val-o.val;
}
}
public static void main(String[] args) throws IOException{
st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int n = nextInt();
Sort[]a = new Sort[n+1];
int[]b = new int[n+1];
for (int i = 1; i <= n; i++) {
a[i] = new Sort();
a[i].val = nextInt();
b[i] = a[i].val;
}
Arrays.sort(a, 1, n+1);
int k1 = 0, k2 = 0;
for (int i = 1; i <= n; i++) {
if (b[i] != a[i].val) {
if (k1==0)
k1 = i;
else if (k2==0)
k2 = i;
else {
System.out.println("NO");
return;
}
}
}
if (k1==0)
System.out.println("YES");
else if (k2==0)
System.out.println("NO");
else {
if (b[k1]==a[k2].val && b[k2]==a[k1].val)
System.out.println("YES");
else
System.out.println("NO");
}
pw.close();
}
private static int nextInt() throws IOException{
st.nextToken();
return (int) st.nval;
}
}
| nlogn | 220_A. Little Elephant and Problem | CODEFORCES |
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class A {
public void run() throws IOException {
final int n = IOFast.nextInt();
int[] xs = new int[n];
for(int i = 0; i < n; i++) {
xs[i] = IOFast.nextInt();
}
int[] ys = xs.clone();
Random random = new Random();
for(int i = 0; i < n; i++) {
final int j = random.nextInt(i + 1);
final int t = ys[j]; ys[j] = ys[i]; ys[i] = t;
}
Arrays.sort(ys);
int diff = 0;
for(int i = 0; i < ys.length; i++) {
if(xs[i] != ys[i]) {
diff++;
}
}
IOFast.out.println(diff > 2 ? "NO" : "YES");
}
public static void main(String[] args) throws IOException {
new A().run();
IOFast.out.flush();
}
static public class IOFast {
private static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
private static PrintWriter out = new PrintWriter(System.out);
// private static final int BUFFER_SIZE = 50 * 200000;
private static int pos, readLen;
private static final char[] buffer = new char[1024 * 8];
private static final StringBuilder buf = new StringBuilder();
private static boolean[] isDigit = new boolean[256];
private static boolean[] isSpace = new boolean[256];
static {
for(int i = 0; i < 10; i++) {
isDigit['0' + i] = true;
}
isDigit['-'] = true;
isSpace[' '] = isSpace['\r'] = isSpace['\n'] = isSpace['\t'] = true;
}
static boolean endInput;
private static int read() throws IOException {
if(readLen == -1) {
return -1;
}
if(pos >= readLen) {
readLen = in.read(buffer);
pos = 0;
if(readLen <= 0) {
return -1;
}
}
return buffer[pos++];
}
private static int nextInt() throws IOException {
boolean plus = false;
int ret = 0;
while(true) {
final int c = read();
if(c == -1) {
endInput = true;
return Integer.MIN_VALUE;
}
if(isDigit[c]) {
if(c != '-') {
plus = true;
ret = c - '0';
}
break;
}
}
while(true) {
final int c = read();
if(c == -1 || !isDigit[c]) {
break;
}
ret = ret * 10 + c - '0';
}
return plus ? ret : -ret;
}
private static long nextLong() throws IOException {
boolean plus = false;
long ret = 0;
while(true) {
final int c = read();
if(c == -1) {
endInput = true;
return Integer.MIN_VALUE;
}
if(isDigit[c]) {
if(c != '-') {
plus = true;
ret = c - '0';
}
break;
}
}
while(true) {
final int c = read();
if(c == -1 || !isDigit[c]) {
break;
}
ret = ret * 10 + c - '0';
}
return plus ? ret : -ret;
}
private static char nextChar() throws IOException {
while(true) {
final int c = read();
if(c == -1) {
endInput = true;
return '\0';
}
if(!isSpace[c]) {
return (char)c;
}
}
}
private static int next(char[] cs) throws IOException {
int n = 0;
while(true) {
final int c = read();
if(c == -1) {
endInput = true;
return n;
}
if(!isSpace[c]) {
cs[n++] = (char)c;
break;
}
}
while(true) {
final int c = read();
if(c == -1 || isSpace[c]) {
break;
}
cs[n++] = (char)c;
}
return n;
}
private static String next() throws IOException {
buf.setLength(0);
while(true) {
final int c = read();
if(c == -1) {
endInput = true;
return "-1";
}
if(!isSpace[c]) {
buf.append((char)c);
break;
}
}
while(true) {
final int c = read();
if(c == -1 || isSpace[c]) {
break;
}
buf.append((char)c);
}
return buf.toString();
}
private static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
}
| nlogn | 220_A. Little Elephant and Problem | CODEFORCES |
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.util.Comparator;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.io.IOException;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Egor Kulikov ([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 count = in.readInt();
int[] array = IOUtils.readIntArray(in, count);
int[] sorted = array.clone();
ArrayUtils.sort(sorted, IntComparator.DEFAULT);
int differs = 0;
for (int i = 0; i < count; i++) {
if (array[i] != sorted[i])
differs++;
}
if (differs <= 2)
out.printLine("YES");
else
out.printLine("NO");
}
}
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();
}
}
class IOUtils {
public static int[] readIntArray(InputReader in, int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = in.readInt();
return array;
}
}
class ArrayUtils {
private static int[] tempInt = new int[0];
public static int[] sort(int[] array, IntComparator comparator) {
return sort(array, 0, array.length, comparator);
}
public static int[] sort(int[] array, int from, int to, IntComparator comparator) {
ensureCapacityInt(to - from);
System.arraycopy(array, from, tempInt, 0, to - from);
sortImpl(array, from, to, tempInt, 0, to - from, comparator);
return array;
}
private static void ensureCapacityInt(int size) {
if (tempInt.length >= size)
return;
size = Math.max(size, tempInt.length << 1);
tempInt = new int[size];
}
private static void sortImpl(int[] array, int from, int to, int[] temp, int fromTemp, int toTemp, IntComparator comparator) {
if (to - from <= 1)
return;
int middle = (to - from) >> 1;
int tempMiddle = fromTemp + middle;
sortImpl(temp, fromTemp, tempMiddle, array, from, from + middle, comparator);
sortImpl(temp, tempMiddle, toTemp, array, from + middle, to, comparator);
int index = from;
int index1 = fromTemp;
int index2 = tempMiddle;
while (index1 < tempMiddle && index2 < toTemp) {
if (comparator.compare(temp[index1], temp[index2]) <= 0)
array[index++] = temp[index1++];
else
array[index++] = temp[index2++];
}
if (index1 != tempMiddle)
System.arraycopy(temp, index1, array, index, tempMiddle - index1);
if (index2 != toTemp)
System.arraycopy(temp, index2, array, index, toTemp - index2);
}
}
interface IntComparator {
public static final IntComparator DEFAULT = new IntComparator() {
public int compare(int first, int second) {
if (first < second)
return -1;
if (first > second)
return 1;
return 0;
}
};
public int compare(int first, int second);
}
| nlogn | 220_A. Little Elephant and Problem | 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 A implements Runnable
{
String file = "input";
boolean TEST = System.getProperty("ONLINE_JUDGE") == null;
void solve() throws IOException
{
int n = nextInt();
int[] a = new int[n];
for(int i = 0; i < n; i++) a[i] = nextInt();
int[] b = a.clone();
qsort(b);
//sortInt(b);
int count = 0;
for(int i = 0; i < a.length; i++)
if(a[i] != b[i]) count++;
if(count == 0 || count == 2) out.println("YES");
else out.println("NO");
}
void qsort(int[] a)
{
List<Integer> as = new ArrayList<Integer>();
for(int x : a) as.add(x);
Collections.shuffle(as);
int j = 0;
for(int x : as) a[j++] = x;
sort(a);
}
Random rnd = new Random();
void sortInt(int[] a)
{
sortInt(a, 0, a.length - 1);
}
void sortInt(int[] a, int from, int to)
{
if(from >= to) return;
int i = from - 1;
int p = rnd.nextInt(to - from + 1) + from;
int t = a[p]; a[p] = a[to]; a[to] = t;
for(int j = from; j < to; j++)
if(a[j] <= a[to])
{
i++;
t = a[i]; a[i] = a[j]; a[j] = t;
}
t = a[i + 1]; a[i + 1] = a[to]; a[to] = t;
sortInt(a, i + 2, to);
while(i >= 0 && a[i] == a[i + 1]) i--;
sortInt(a, from, i);
}
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 print(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(file + ".in"));
else input = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new BufferedOutputStream(System.out));
}
public static void main(String[] args) throws IOException
{
new Thread(null, new A(), "", 1 << 22).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 | 220_A. Little Elephant and Problem | CODEFORCES |
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
import java.util.StringTokenizer;
public class C {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = null;
PrintWriter out;
public void solution() throws IOException {
int n = nextInt();
int a[] = new int[n];
int b[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
b[i] = a[i];
}
Arrays.sort(a);
int ans = 0;
for (int i = 0; i < n; i++) {
if (a[i] != b[i]) {
ans++;
}
}
if (ans == 2 || ans == 0) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
public String nextToken() throws IOException {
if (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(bf.readLine());
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
public void print(int a[]) {
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
}
public static void main(String args[]) throws IOException {
new C().solution();
}
} | nlogn | 220_A. Little Elephant and Problem | CODEFORCES |
import java.io.*;
import java.util.*;
public class A {
final String filename = new String("C").toLowerCase();
void solve() throws Exception {
int n = nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
if (isSorted(a)) {
out.println("YES");
return;
}
int pos1 = -1;
for (int i = 0; i < n - 1; i++) {
if (a[i] > a[i + 1]) {
int j = i;
while (j >= 0 && a[j] == a[i]) {
j--;
}
pos1 = j + 1;
break;
}
}
int pos2 = -1;
for (int i = n - 2; i >= 0; i--) {
if (a[i] > a[i + 1]) {
int j = i + 1;
while (j < n && a[j] == a[i + 1]) {
j++;
}
pos2 = j - 1;
break;
}
}
int tmp = a[pos1];
a[pos1] = a[pos2];
a[pos2] = tmp;
if (isSorted(a)) {
out.println("YES");
} else {
out.println("NO");
}
}
boolean isSorted(int[] a) {
for (int i = 0; i < a.length - 1; i++) {
if (a[i] > a[i + 1]) {
return false;
}
}
return true;
}
void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
// in = new BufferedReader(new FileReader("input.txt"));
// out = new PrintWriter("output.txt");
solve();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
BufferedReader in;
StringTokenizer st;
PrintWriter out;
String nextToken() throws Exception {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(in.readLine());
return st.nextToken();
}
int nextInt() throws Exception {
return Integer.parseInt(nextToken());
}
long nextLong() throws Exception {
return Long.parseLong(nextToken());
}
double nextDouble() throws Exception {
return Double.parseDouble(nextToken());
}
public static void main(String[] args) {
new A().run();
}
}
| nlogn | 220_A. Little Elephant and Problem | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Random;
import java.util.StringTokenizer;
public class c {
class IO {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
StringTokenizer st;
Random rnd = new Random();;
String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String line = in.readLine();
if (line == null)
return null;
st = new StringTokenizer(line);
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
}
void run() throws IOException{
IO read=new IO();
int n=read.nextInt();
int a[]=new int[n],b[]=new int[n];
for(int i=0;i<n;i++)
a[i]=b[i]=read.nextInt();
Arrays.sort(b);
int cnt=0;
for(int i=0;i<n;i++)
if(a[i]!=b[i])
cnt++;
if(cnt==0||cnt==2)
read.out.println("YES");
else
read.out.println("NO");
read.out.close();
}
public static void main(String[] args) throws IOException {
new c().run();
}
}
| nlogn | 220_A. Little Elephant and Problem | CODEFORCES |
//package round136;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
public class A {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni();
int[] a = new int[n];
int[] b = new int[n];
for(int i = 0;i < n;i++)b[i] = a[i] = ni();
Arrays.sort(b);
int ct = 0;
for(int i = 0;i < n;i++){
if(a[i] != b[i])ct++;
}
if(ct <= 2){
out.println("YES");
}else{
out.println("NO");
}
}
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();
}
public int ni()
{
try {
int num = 0;
boolean minus = false;
while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-'));
if(num == '-'){
num = 0;
minus = true;
}else{
num -= '0';
}
while(true){
int b = is.read();
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
}
} catch (IOException e) {
}
return -1;
}
public long nl()
{
try {
long num = 0;
boolean minus = false;
while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-'));
if(num == '-'){
num = 0;
minus = true;
}else{
num -= '0';
}
while(true){
int b = is.read();
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
}
} catch (IOException e) {
}
return -1;
}
public String ns()
{
try{
int b = 0;
StringBuilder sb = new StringBuilder();
while((b = is.read()) != -1 && (b == '\r' || b == '\n' || b == ' '));
if(b == -1)return "";
sb.append((char)b);
while(true){
b = is.read();
if(b == -1)return sb.toString();
if(b == '\r' || b == '\n' || b == ' ')return sb.toString();
sb.append((char)b);
}
} catch (IOException e) {
}
return "";
}
public char[] ns(int n)
{
char[] buf = new char[n];
try{
int b = 0, p = 0;
while((b = is.read()) != -1 && (b == ' ' || b == '\r' || b == '\n'));
if(b == -1)return null;
buf[p++] = (char)b;
while(p < n){
b = is.read();
if(b == -1 || b == ' ' || b == '\r' || b == '\n')break;
buf[p++] = (char)b;
}
return Arrays.copyOf(buf, p);
} catch (IOException e) {
}
return null;
}
double nd() { return Double.parseDouble(ns()); }
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
| nlogn | 220_A. Little Elephant and Problem | CODEFORCES |
import java.io.IOException;
import java.io.InputStreamReader;
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.util.Random;
import java.io.Writer;
import java.util.StringTokenizer;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int a[] = in.nextIntArray(n);
int i,j,k;
int b[] = a.clone();
ArrayUtils.randomShuffle(a);
Arrays.sort(a);
int c[] = new int[n];
k=0;
for(i=0;i<n;++i) if(a[i]!=b[i]) c[k++] = i;
String res = "NO";
if(k==0){
res = "YES";
}else
if(k==1){
}else
if(k==2){
i = c[0]; j = c[1];
if(a[i]==b[j] && a[j]==b[i]) res = "YES";
}
out.writeln(res);
}
}
class InputReader{
private BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream stream){
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String next(){
while(tokenizer==null || !tokenizer.hasMoreTokens()){
try{
tokenizer = new StringTokenizer(reader.readLine());
}catch(Exception e){
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt(){
return Integer.parseInt(next());
}
public int[] nextIntArray(int size){
int array[] = new int[size];
for(int i=0; i<size; ++i) array[i] = nextInt();
return array;
}
}
class OutputWriter{
private PrintWriter out;
public OutputWriter(Writer out){
this.out = new PrintWriter(out);
}
public OutputWriter(OutputStream out){
this.out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(out)));
}
public void close(){
out.flush();
out.close();
}
public void writeln(Object ... o){
for(Object x : o) out.print(x);
out.println();
}
}
class ArrayUtils{
private final static Random random = new Random(System.nanoTime());
public static void randomShuffle(int a[]){
int n = a.length;
for(int i=0;i<n;++i){
int j = random.nextInt(n-i);
int t = a[i]; a[i] = a[j]; a[j] = t;
}
}
}
| nlogn | 220_A. Little Elephant and Problem | 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.